1 /* 2 * Copyright (C) 2005 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <binder/Common.h> 20 #include <binder/Parcel.h> 21 #include <binder/ProcessState.h> 22 #include <utils/Errors.h> 23 #include <utils/Vector.h> 24 25 #if defined(_WIN32) 26 typedef int uid_t; 27 #endif 28 29 // --------------------------------------------------------------------------- 30 namespace android { 31 32 /** 33 * Kernel binder thread state. All operations here refer to kernel binder. This 34 * object is allocated per-thread. 35 */ 36 class IPCThreadState { 37 public: 38 using CallRestriction = ProcessState::CallRestriction; 39 40 LIBBINDER_EXPORTED static IPCThreadState* self(); 41 LIBBINDER_EXPORTED static IPCThreadState* selfOrNull(); // self(), but won't instantiate 42 43 // Freeze or unfreeze the binder interface to a specific process. When freezing, this method 44 // will block up to timeout_ms to process pending transactions directed to pid. Unfreeze 45 // is immediate. Transactions to processes frozen via this method won't be delivered and the 46 // driver will return BR_FROZEN_REPLY to the client sending them. After unfreeze, 47 // transactions will be delivered normally. 48 // 49 // pid: id for the process for which the binder interface is to be frozen 50 // enable: freeze (true) or unfreeze (false) 51 // timeout_ms: maximum time this function is allowed to block the caller waiting for pending 52 // binder transactions to be processed. 53 // 54 // returns: 0 in case of success, a value < 0 in case of error 55 LIBBINDER_EXPORTED static status_t freeze(pid_t pid, bool enabled, uint32_t timeout_ms); 56 57 // Provide information about the state of a frozen process 58 LIBBINDER_EXPORTED static status_t getProcessFreezeInfo(pid_t pid, uint32_t* sync_received, 59 uint32_t* async_received); 60 61 LIBBINDER_EXPORTED status_t clearLastError(); 62 63 /** 64 * Returns the PID of the process which has made the current binder 65 * call. If not in a binder call, this will return getpid. 66 * 67 * Warning: oneway transactions do not receive PID. Even if you expect 68 * a transaction to be synchronous, a misbehaving client could send it 69 * as an asynchronous call and result in a 0 PID here. Additionally, if 70 * there is a race and the calling process dies, the PID may still be 71 * 0 for a synchronous call. 72 */ 73 [[nodiscard]] LIBBINDER_EXPORTED pid_t getCallingPid() const; 74 75 /** 76 * Returns the SELinux security identifier of the process which has 77 * made the current binder call. If not in a binder call this will 78 * return nullptr. If this isn't requested with 79 * Binder::setRequestingSid, it will also return nullptr. 80 * 81 * This can't be restored once it's cleared, and it does not return the 82 * context of the current process when not in a binder call. 83 */ 84 [[nodiscard]] LIBBINDER_EXPORTED const char* getCallingSid() const; 85 86 /** 87 * Returns the UID of the process which has made the current binder 88 * call. If not in a binder call, this will return 0. 89 */ 90 [[nodiscard]] LIBBINDER_EXPORTED uid_t getCallingUid() const; 91 92 /** 93 * Make it an abort to rely on getCalling* for a section of 94 * execution. 95 * 96 * Usage: 97 * IPCThreadState::SpGuard guard { 98 * .address = __builtin_frame_address(0), 99 * .context = "...", 100 * }; 101 * const auto* orig = pushGetCallingSpGuard(&guard); 102 * { 103 * // will abort if you call getCalling*, unless you are 104 * // serving a nested binder transaction 105 * } 106 * restoreCallingSpGuard(orig); 107 */ 108 struct SpGuard { 109 const void* address; 110 const char* context; 111 }; 112 LIBBINDER_EXPORTED const SpGuard* pushGetCallingSpGuard(const SpGuard* guard); 113 LIBBINDER_EXPORTED void restoreGetCallingSpGuard(const SpGuard* guard); 114 /** 115 * Used internally by getCalling*. Can also be used to assert that 116 * you are in a binder context (getCalling* is valid). This is 117 * intentionally not exposed as a boolean API since code should be 118 * written to know its environment. 119 */ 120 LIBBINDER_EXPORTED void checkContextIsBinderForUse(const char* use) const; 121 122 LIBBINDER_EXPORTED void setStrictModePolicy(int32_t policy); 123 LIBBINDER_EXPORTED int32_t getStrictModePolicy() const; 124 125 // See Binder#setCallingWorkSourceUid in Binder.java. 126 LIBBINDER_EXPORTED int64_t setCallingWorkSourceUid(uid_t uid); 127 // Internal only. Use setCallingWorkSourceUid(uid) instead. 128 LIBBINDER_EXPORTED int64_t setCallingWorkSourceUidWithoutPropagation(uid_t uid); 129 // See Binder#getCallingWorkSourceUid in Binder.java. 130 LIBBINDER_EXPORTED uid_t getCallingWorkSourceUid() const; 131 // See Binder#clearCallingWorkSource in Binder.java. 132 LIBBINDER_EXPORTED int64_t clearCallingWorkSource(); 133 // See Binder#restoreCallingWorkSource in Binder.java. 134 LIBBINDER_EXPORTED void restoreCallingWorkSource(int64_t token); 135 LIBBINDER_EXPORTED void clearPropagateWorkSource(); 136 LIBBINDER_EXPORTED bool shouldPropagateWorkSource() const; 137 138 LIBBINDER_EXPORTED void setLastTransactionBinderFlags(int32_t flags); 139 LIBBINDER_EXPORTED int32_t getLastTransactionBinderFlags() const; 140 141 LIBBINDER_EXPORTED void setCallRestriction(CallRestriction restriction); 142 LIBBINDER_EXPORTED CallRestriction getCallRestriction() const; 143 144 LIBBINDER_EXPORTED int64_t clearCallingIdentity(); 145 // Restores PID/UID (not SID) 146 LIBBINDER_EXPORTED void restoreCallingIdentity(int64_t token); 147 LIBBINDER_EXPORTED bool hasExplicitIdentity(); 148 149 // For main functions - dangerous for libraries to use 150 LIBBINDER_EXPORTED status_t setupPolling(int* fd); 151 LIBBINDER_EXPORTED status_t handlePolledCommands(); 152 LIBBINDER_EXPORTED void flushCommands(); 153 LIBBINDER_EXPORTED bool flushIfNeeded(); 154 155 // Adds the current thread into the binder threadpool. 156 // 157 // This is in addition to any threads which are started 158 // with startThreadPool. Libraries should not call this 159 // function, as they may be loaded into processes which 160 // try to configure the threadpool differently. 161 LIBBINDER_EXPORTED void joinThreadPool(bool isMain = true); 162 163 // Stop the local process. 164 LIBBINDER_EXPORTED void stopProcess(bool immediate = true); 165 166 LIBBINDER_EXPORTED status_t transact(int32_t handle, uint32_t code, const Parcel& data, 167 Parcel* reply, uint32_t flags); 168 169 LIBBINDER_EXPORTED void incStrongHandle(int32_t handle, BpBinder* proxy); 170 LIBBINDER_EXPORTED void decStrongHandle(int32_t handle); 171 LIBBINDER_EXPORTED void incWeakHandle(int32_t handle, BpBinder* proxy); 172 LIBBINDER_EXPORTED void decWeakHandle(int32_t handle); 173 LIBBINDER_EXPORTED status_t attemptIncStrongHandle(int32_t handle); 174 LIBBINDER_EXPORTED static void expungeHandle(int32_t handle, IBinder* binder); 175 LIBBINDER_EXPORTED status_t requestDeathNotification(int32_t handle, BpBinder* proxy); 176 LIBBINDER_EXPORTED status_t clearDeathNotification(int32_t handle, BpBinder* proxy); 177 [[nodiscard]] status_t addFrozenStateChangeCallback(int32_t handle, BpBinder* proxy); 178 [[nodiscard]] status_t removeFrozenStateChangeCallback(int32_t handle, BpBinder* proxy); 179 180 LIBBINDER_EXPORTED static void shutdown(); 181 182 // Call this to disable switching threads to background scheduling when 183 // receiving incoming IPC calls. This is specifically here for the 184 // Android system process, since it expects to have background apps calling 185 // in to it but doesn't want to acquire locks in its services while in 186 // the background. 187 LIBBINDER_EXPORTED static void disableBackgroundScheduling(bool disable); 188 LIBBINDER_EXPORTED bool backgroundSchedulingDisabled(); 189 190 // Call blocks until the number of executing binder threads is less than 191 // the maximum number of binder threads threads allowed for this process. 192 LIBBINDER_EXPORTED void blockUntilThreadAvailable(); 193 194 // Service manager registration 195 LIBBINDER_EXPORTED void setTheContextObject(const sp<BBinder>& obj); 196 197 // WARNING: DO NOT USE THIS API 198 // 199 // Returns a pointer to the stack from the last time a transaction 200 // was initiated by the kernel. Used to compare when making nested 201 // calls between multiple different transports. 202 LIBBINDER_EXPORTED const void* getServingStackPointer() const; 203 204 // The work source represents the UID of the process we should attribute the transaction 205 // to. We use -1 to specify that the work source was not set using #setWorkSource. 206 // 207 // This constant needs to be kept in sync with Binder.UNSET_WORKSOURCE from the Java 208 // side. 209 LIBBINDER_EXPORTED static const int32_t kUnsetWorkSource = -1; 210 211 private: 212 IPCThreadState(); 213 ~IPCThreadState(); 214 215 [[nodiscard]] status_t sendReply(const Parcel& reply, uint32_t flags); 216 [[nodiscard]] status_t waitForResponse(Parcel* reply, status_t* acquireResult = nullptr); 217 [[nodiscard]] status_t talkWithDriver(bool doReceive = true); 218 [[nodiscard]] status_t writeTransactionData(int32_t cmd, uint32_t binderFlags, int32_t handle, 219 uint32_t code, const Parcel& data, 220 status_t* statusBuffer); 221 [[nodiscard]] status_t getAndExecuteCommand(); 222 [[nodiscard]] status_t executeCommand(int32_t command); 223 void processPendingDerefs(); 224 void processPostWriteDerefs(); 225 226 void clearCaller(); 227 228 static void threadDestructor(void *st); 229 static void freeBuffer(const uint8_t* data, size_t dataSize, const binder_size_t* objects, 230 size_t objectsSize); 231 static void logExtendedError(); 232 233 const sp<ProcessState> mProcess; 234 Vector<BBinder*> mPendingStrongDerefs; 235 Vector<RefBase::weakref_type*> mPendingWeakDerefs; 236 Vector<RefBase*> mPostWriteStrongDerefs; 237 Vector<RefBase::weakref_type*> mPostWriteWeakDerefs; 238 Parcel mIn; 239 Parcel mOut; 240 status_t mLastError; 241 const void* mServingStackPointer; 242 const SpGuard* mServingStackPointerGuard; 243 pid_t mCallingPid; 244 const char* mCallingSid; 245 uid_t mCallingUid; 246 // The UID of the process who is responsible for this transaction. 247 // This is used for resource attribution. 248 int32_t mWorkSource; 249 // Whether the work source should be propagated. 250 bool mPropagateWorkSource; 251 bool mIsLooper; 252 bool mIsFlushing; 253 bool mHasExplicitIdentity; 254 int32_t mStrictModePolicy; 255 int32_t mLastTransactionBinderFlags; 256 CallRestriction mCallRestriction; 257 }; 258 259 } // namespace android 260 261 // --------------------------------------------------------------------------- 262