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 do not use this as a security identifier! PID is unreliable 68 * as it may be re-used. This should mostly be used for debugging. 69 * 70 * oneway transactions do not receive PID. Even if you expect 71 * a transaction to be synchronous, a misbehaving client could send it 72 * as an asynchronous call and result in a 0 PID here. Additionally, if 73 * there is a race and the calling process dies, the PID may still be 74 * 0 for a synchronous call. 75 */ 76 [[nodiscard]] LIBBINDER_EXPORTED pid_t getCallingPid() const; 77 78 /** 79 * Returns the SELinux security identifier of the process which has 80 * made the current binder call. If not in a binder call this will 81 * return nullptr. If this isn't requested with 82 * Binder::setRequestingSid, it will also return nullptr. 83 * 84 * This can't be restored once it's cleared, and it does not return the 85 * context of the current process when not in a binder call. 86 */ 87 [[nodiscard]] LIBBINDER_EXPORTED const char* getCallingSid() const; 88 89 /** 90 * Returns the UID of the process which has made the current binder 91 * call. If not in a binder call, this will return 0. 92 */ 93 [[nodiscard]] LIBBINDER_EXPORTED uid_t getCallingUid() const; 94 95 /** 96 * Make it an abort to rely on getCalling* for a section of 97 * execution. 98 * 99 * Usage: 100 * IPCThreadState::SpGuard guard { 101 * .address = __builtin_frame_address(0), 102 * .context = "...", 103 * }; 104 * const auto* orig = pushGetCallingSpGuard(&guard); 105 * { 106 * // will abort if you call getCalling*, unless you are 107 * // serving a nested binder transaction 108 * } 109 * restoreCallingSpGuard(orig); 110 */ 111 struct SpGuard { 112 const void* address; 113 const char* context; 114 }; 115 LIBBINDER_EXPORTED const SpGuard* pushGetCallingSpGuard(const SpGuard* guard); 116 LIBBINDER_EXPORTED void restoreGetCallingSpGuard(const SpGuard* guard); 117 /** 118 * Used internally by getCalling*. Can also be used to assert that 119 * you are in a binder context (getCalling* is valid). This is 120 * intentionally not exposed as a boolean API since code should be 121 * written to know its environment. 122 */ 123 LIBBINDER_EXPORTED void checkContextIsBinderForUse(const char* use) const; 124 125 LIBBINDER_EXPORTED void setStrictModePolicy(int32_t policy); 126 LIBBINDER_EXPORTED int32_t getStrictModePolicy() const; 127 128 // See Binder#setCallingWorkSourceUid in Binder.java. 129 LIBBINDER_EXPORTED int64_t setCallingWorkSourceUid(uid_t uid); 130 // Internal only. Use setCallingWorkSourceUid(uid) instead. 131 LIBBINDER_EXPORTED int64_t setCallingWorkSourceUidWithoutPropagation(uid_t uid); 132 // See Binder#getCallingWorkSourceUid in Binder.java. 133 LIBBINDER_EXPORTED uid_t getCallingWorkSourceUid() const; 134 // See Binder#clearCallingWorkSource in Binder.java. 135 LIBBINDER_EXPORTED int64_t clearCallingWorkSource(); 136 // See Binder#restoreCallingWorkSource in Binder.java. 137 LIBBINDER_EXPORTED void restoreCallingWorkSource(int64_t token); 138 LIBBINDER_EXPORTED void clearPropagateWorkSource(); 139 LIBBINDER_EXPORTED bool shouldPropagateWorkSource() const; 140 141 LIBBINDER_EXPORTED void setLastTransactionBinderFlags(int32_t flags); 142 LIBBINDER_EXPORTED int32_t getLastTransactionBinderFlags() const; 143 144 LIBBINDER_EXPORTED void setCallRestriction(CallRestriction restriction); 145 LIBBINDER_EXPORTED CallRestriction getCallRestriction() const; 146 147 LIBBINDER_EXPORTED int64_t clearCallingIdentity(); 148 // Restores PID/UID (not SID) 149 LIBBINDER_EXPORTED void restoreCallingIdentity(int64_t token); 150 LIBBINDER_EXPORTED bool hasExplicitIdentity(); 151 152 // For main functions - dangerous for libraries to use 153 LIBBINDER_EXPORTED status_t setupPolling(int* fd); 154 LIBBINDER_EXPORTED status_t handlePolledCommands(); 155 LIBBINDER_EXPORTED void flushCommands(); 156 LIBBINDER_EXPORTED bool flushIfNeeded(); 157 158 // Adds the current thread into the binder threadpool. 159 // 160 // This is in addition to any threads which are started 161 // with startThreadPool. Libraries should not call this 162 // function, as they may be loaded into processes which 163 // try to configure the threadpool differently. 164 LIBBINDER_EXPORTED void joinThreadPool(bool isMain = true); 165 166 // Stop the local process. 167 LIBBINDER_EXPORTED void stopProcess(bool immediate = true); 168 169 LIBBINDER_EXPORTED status_t transact(int32_t handle, uint32_t code, const Parcel& data, 170 Parcel* reply, uint32_t flags); 171 172 LIBBINDER_EXPORTED void incStrongHandle(int32_t handle, BpBinder* proxy); 173 LIBBINDER_EXPORTED void decStrongHandle(int32_t handle); 174 LIBBINDER_EXPORTED void incWeakHandle(int32_t handle, BpBinder* proxy); 175 LIBBINDER_EXPORTED void decWeakHandle(int32_t handle); 176 LIBBINDER_EXPORTED status_t attemptIncStrongHandle(int32_t handle); 177 LIBBINDER_EXPORTED static void expungeHandle(int32_t handle, IBinder* binder); 178 LIBBINDER_EXPORTED status_t requestDeathNotification(int32_t handle, BpBinder* proxy); 179 LIBBINDER_EXPORTED status_t clearDeathNotification(int32_t handle, BpBinder* proxy); 180 [[nodiscard]] status_t addFrozenStateChangeCallback(int32_t handle, BpBinder* proxy); 181 [[nodiscard]] status_t removeFrozenStateChangeCallback(int32_t handle, BpBinder* proxy); 182 183 LIBBINDER_EXPORTED static void shutdown(); 184 185 // Call this to disable switching threads to background scheduling when 186 // receiving incoming IPC calls. This is specifically here for the 187 // Android system process, since it expects to have background apps calling 188 // in to it but doesn't want to acquire locks in its services while in 189 // the background. 190 LIBBINDER_EXPORTED static void disableBackgroundScheduling(bool disable); 191 LIBBINDER_EXPORTED bool backgroundSchedulingDisabled(); 192 193 // Call blocks until the number of executing binder threads is less than 194 // the maximum number of binder threads threads allowed for this process. 195 LIBBINDER_EXPORTED void blockUntilThreadAvailable(); 196 197 // Service manager registration 198 LIBBINDER_EXPORTED void setTheContextObject(const sp<BBinder>& obj); 199 200 // WARNING: DO NOT USE THIS API 201 // 202 // Returns a pointer to the stack from the last time a transaction 203 // was initiated by the kernel. Used to compare when making nested 204 // calls between multiple different transports. 205 LIBBINDER_EXPORTED const void* getServingStackPointer() const; 206 207 // The work source represents the UID of the process we should attribute the transaction 208 // to. We use -1 to specify that the work source was not set using #setWorkSource. 209 // 210 // This constant needs to be kept in sync with Binder.UNSET_WORKSOURCE from the Java 211 // side. 212 LIBBINDER_EXPORTED static const int32_t kUnsetWorkSource = -1; 213 214 private: 215 IPCThreadState(); 216 ~IPCThreadState(); 217 218 [[nodiscard]] status_t sendReply(const Parcel& reply, uint32_t flags); 219 [[nodiscard]] status_t waitForResponse(Parcel* reply, status_t* acquireResult = nullptr); 220 [[nodiscard]] status_t talkWithDriver(bool doReceive = true); 221 [[nodiscard]] status_t writeTransactionData(int32_t cmd, uint32_t binderFlags, int32_t handle, 222 uint32_t code, const Parcel& data, 223 status_t* statusBuffer); 224 [[nodiscard]] status_t getAndExecuteCommand(); 225 [[nodiscard]] status_t executeCommand(int32_t command); 226 void processPendingDerefs(); 227 void processPostWriteDerefs(); 228 229 void clearCaller(); 230 231 static void threadDestructor(void *st); 232 static void freeBuffer(const uint8_t* data, size_t dataSize, const binder_size_t* objects, 233 size_t objectsSize); 234 static void logExtendedError(); 235 236 const sp<ProcessState> mProcess; 237 Vector<BBinder*> mPendingStrongDerefs; 238 Vector<RefBase::weakref_type*> mPendingWeakDerefs; 239 Vector<RefBase*> mPostWriteStrongDerefs; 240 Vector<RefBase::weakref_type*> mPostWriteWeakDerefs; 241 Parcel mIn; 242 Parcel mOut; 243 status_t mLastError; 244 const void* mServingStackPointer; 245 const SpGuard* mServingStackPointerGuard; 246 pid_t mCallingPid; 247 const char* mCallingSid; 248 uid_t mCallingUid; 249 // The UID of the process who is responsible for this transaction. 250 // This is used for resource attribution. 251 int32_t mWorkSource; 252 // Whether the work source should be propagated. 253 bool mPropagateWorkSource; 254 bool mIsLooper; 255 bool mIsFlushing; 256 bool mHasExplicitIdentity; 257 int32_t mStrictModePolicy; 258 int32_t mLastTransactionBinderFlags; 259 CallRestriction mCallRestriction; 260 }; 261 262 } // namespace android 263 264 // --------------------------------------------------------------------------- 265