1 /* 2 * Copyright (C) 2020 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 #pragma once 17 18 #include <android-base/unique_fd.h> 19 #include <binder/IBinder.h> 20 #include <binder/Parcel.h> 21 #include <binder/RpcSession.h> 22 #include <binder/RpcThreads.h> 23 24 #include <map> 25 #include <optional> 26 #include <queue> 27 28 #include <sys/uio.h> 29 30 namespace android { 31 32 struct RpcWireHeader; 33 34 /** 35 * Log a lot more information about RPC calls, when debugging issues. Usually, 36 * you would want to enable this in only one process. If repeated issues require 37 * a specific subset of logs to debug, this could be broken up like 38 * IPCThreadState's. 39 */ 40 #define SHOULD_LOG_RPC_DETAIL false 41 42 #if SHOULD_LOG_RPC_DETAIL 43 #define LOG_RPC_DETAIL(...) ALOGI(__VA_ARGS__) 44 #else 45 #define LOG_RPC_DETAIL(...) ALOGV(__VA_ARGS__) // for type checking 46 #endif 47 48 #define RPC_FLAKE_PRONE false 49 50 #if RPC_FLAKE_PRONE 51 void rpcMaybeWaitToFlake(); 52 #define MAYBE_WAIT_IN_FLAKE_MODE rpcMaybeWaitToFlake() 53 #else 54 #define MAYBE_WAIT_IN_FLAKE_MODE do {} while (false) 55 #endif 56 57 /** 58 * Abstracts away management of ref counts and the wire format from 59 * RpcSession 60 */ 61 class RpcState { 62 public: 63 RpcState(); 64 ~RpcState(); 65 66 [[nodiscard]] status_t readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection, 67 const sp<RpcSession>& session, uint32_t* version); 68 [[nodiscard]] status_t sendConnectionInit(const sp<RpcSession::RpcConnection>& connection, 69 const sp<RpcSession>& session); 70 [[nodiscard]] status_t readConnectionInit(const sp<RpcSession::RpcConnection>& connection, 71 const sp<RpcSession>& session); 72 73 // TODO(b/182940634): combine some special transactions into one "getServerInfo" call? 74 sp<IBinder> getRootObject(const sp<RpcSession::RpcConnection>& connection, 75 const sp<RpcSession>& session); 76 [[nodiscard]] status_t getMaxThreads(const sp<RpcSession::RpcConnection>& connection, 77 const sp<RpcSession>& session, size_t* maxThreadsOut); 78 [[nodiscard]] status_t getSessionId(const sp<RpcSession::RpcConnection>& connection, 79 const sp<RpcSession>& session, 80 std::vector<uint8_t>* sessionIdOut); 81 82 [[nodiscard]] status_t transact(const sp<RpcSession::RpcConnection>& connection, 83 const sp<IBinder>& address, uint32_t code, const Parcel& data, 84 const sp<RpcSession>& session, Parcel* reply, uint32_t flags); 85 [[nodiscard]] status_t transactAddress(const sp<RpcSession::RpcConnection>& connection, 86 uint64_t address, uint32_t code, const Parcel& data, 87 const sp<RpcSession>& session, Parcel* reply, 88 uint32_t flags); 89 90 /** 91 * The ownership model here carries an implicit strong refcount whenever a 92 * binder is sent across processes. Since we have a local strong count in 93 * sp<> over these objects, we only ever need to keep one of these. So, 94 * typically we tell the remote process that we drop all the implicit dec 95 * strongs, and we hold onto the last one. 'target' here is the target 96 * timesRecd (the number of remaining reference counts) we wish to keep. 97 * Typically this should be '0' or '1'. The target is used instead of an 98 * explicit decrement count in order to allow multiple threads to lower the 99 * number of counts simultaneously. Since we only lower the count to 0 when 100 * a binder is deleted, targets of '1' should only be sent when the caller 101 * owns a local strong reference to the binder. Larger targets may be used 102 * for testing, and to make the function generic, but generally this should 103 * be avoided because it would be hard to guarantee another thread doesn't 104 * lower the number of held refcounts to '1'. Note also, these refcounts 105 * must be sent actively. If they are sent when binders are deleted, this 106 * can cause leaks, since even remote binders carry an implicit strong ref 107 * when they are sent to another process. 108 */ 109 [[nodiscard]] status_t sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection, 110 const sp<RpcSession>& session, uint64_t address, 111 size_t target); 112 113 enum class CommandType { 114 ANY, 115 CONTROL_ONLY, 116 }; 117 [[nodiscard]] status_t getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection, 118 const sp<RpcSession>& session, CommandType type); 119 [[nodiscard]] status_t drainCommands(const sp<RpcSession::RpcConnection>& connection, 120 const sp<RpcSession>& session, CommandType type); 121 122 /** 123 * Called by Parcel for outgoing binders. This implies one refcount of 124 * ownership to the outgoing binder. 125 */ 126 [[nodiscard]] status_t onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder, 127 uint64_t* outAddress); 128 129 /** 130 * Called by Parcel for incoming binders. This either returns the refcount 131 * to the process, if this process already has one, or it takes ownership of 132 * that refcount 133 */ 134 [[nodiscard]] status_t onBinderEntering(const sp<RpcSession>& session, uint64_t address, 135 sp<IBinder>* out); 136 /** 137 * Called on incoming binders to update refcounting information. This should 138 * only be called when it is done as part of making progress on a 139 * transaction. 140 */ 141 [[nodiscard]] status_t flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address, 142 const sp<IBinder>& binder); 143 /** 144 * Called when the RpcSession is shutdown. 145 * Send obituaries for each known remote binder with this session. 146 */ 147 [[nodiscard]] status_t sendObituaries(const sp<RpcSession>& session); 148 149 size_t countBinders(); 150 void dump(); 151 152 /** 153 * Called when reading or writing data to a session fails to clean up 154 * data associated with the session in order to cleanup binders. 155 * Specifically, we have a strong dependency cycle, since BpBinder is 156 * OBJECT_LIFETIME_WEAK (so that onAttemptIncStrong may return true). 157 * 158 * BpBinder -> RpcSession -> RpcState 159 * ^-----------------------------/ 160 * 161 * In the success case, eventually all refcounts should be propagated over 162 * the session, though this could also be called to eagerly cleanup 163 * the session. 164 * 165 * WARNING: RpcState is responsible for calling this when the session is 166 * no longer recoverable. 167 */ 168 void clear(); 169 170 private: 171 void clear(RpcMutexUniqueLock nodeLock); 172 void dumpLocked(); 173 174 // Alternative to std::vector<uint8_t> that doesn't abort on allocation failure and caps 175 // large allocations to avoid being requested from allocating too much data. 176 struct CommandData { 177 explicit CommandData(size_t size); validCommandData178 bool valid() { return mSize == 0 || mData != nullptr; } sizeCommandData179 size_t size() { return mSize; } dataCommandData180 uint8_t* data() { return mData.get(); } releaseCommandData181 uint8_t* release() { return mData.release(); } 182 183 private: 184 std::unique_ptr<uint8_t[]> mData; 185 size_t mSize; 186 }; 187 188 [[nodiscard]] status_t rpcSend( 189 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session, 190 const char* what, iovec* iovs, int niovs, 191 const std::optional<android::base::function_ref<status_t()>>& altPoll, 192 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds = 193 nullptr); 194 [[nodiscard]] status_t rpcRec( 195 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session, 196 const char* what, iovec* iovs, int niovs, 197 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds = nullptr); 198 199 [[nodiscard]] status_t waitForReply(const sp<RpcSession::RpcConnection>& connection, 200 const sp<RpcSession>& session, Parcel* reply); 201 [[nodiscard]] status_t processCommand( 202 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session, 203 const RpcWireHeader& command, CommandType type, 204 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds); 205 [[nodiscard]] status_t processTransact( 206 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session, 207 const RpcWireHeader& command, 208 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds); 209 [[nodiscard]] status_t processTransactInternal( 210 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session, 211 CommandData transactionData, 212 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds); 213 [[nodiscard]] status_t processDecStrong(const sp<RpcSession::RpcConnection>& connection, 214 const sp<RpcSession>& session, 215 const RpcWireHeader& command); 216 217 // Whether `parcel` is compatible with `session`. 218 [[nodiscard]] static status_t validateParcel(const sp<RpcSession>& session, 219 const Parcel& parcel, std::string* errorMsg); 220 221 struct BinderNode { 222 // Two cases: 223 // A - local binder we are serving 224 // B - remote binder, we are sending transactions to 225 wp<IBinder> binder; 226 227 // if timesSent > 0, this will be equal to binder.promote() 228 sp<IBinder> sentRef; 229 230 // Number of times we've sent this binder out of process, which 231 // translates to an implicit strong count. A client must send RPC binder 232 // socket's dec ref for each time it is sent out of process in order to 233 // deallocate it. Note, a proxy binder we are holding onto might be 234 // sent (this is important when the only remaining refcount of this 235 // binder is the one associated with a transaction sending it back to 236 // its server) 237 size_t timesSent = 0; 238 239 // Number of times we've received this binder, each time corresponds to 240 // a reference we hold over the wire (not a local incStrong/decStrong) 241 size_t timesRecd = 0; 242 243 // transaction ID, for async transactions 244 uint64_t asyncNumber = 0; 245 246 // 247 // CASE A - local binder we are serving 248 // 249 250 // async transaction queue, _only_ for local binder 251 struct AsyncTodo { 252 sp<IBinder> ref; 253 CommandData data; 254 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds; 255 uint64_t asyncNumber = 0; 256 257 bool operator<(const AsyncTodo& o) const { 258 return asyncNumber > /* !!! */ o.asyncNumber; 259 } 260 }; 261 std::priority_queue<AsyncTodo> asyncTodo; 262 263 // 264 // CASE B - remote binder, we are sending transactions to 265 // 266 267 // (no additional data specific to remote binders) 268 269 std::string toString() const; 270 }; 271 272 // Checks if there is any reference left to a node and erases it. If this 273 // is the last node, shuts down the session. 274 // 275 // Node lock is passed here for convenience, so that we can release it 276 // and terminate the session, but we could leave it up to the caller 277 // by returning a continuation if we needed to erase multiple specific 278 // nodes. It may be tempting to allow the client to keep on holding the 279 // lock and instead just return whether or not we should shutdown, but 280 // this introduces the posssibility that another thread calls 281 // getRootBinder and thinks it is valid, rather than immediately getting 282 // an error. 283 sp<IBinder> tryEraseNode(const sp<RpcSession>& session, RpcMutexUniqueLock nodeLock, 284 std::map<uint64_t, BinderNode>::iterator& it); 285 286 // true - success 287 // false - session shutdown, halt 288 [[nodiscard]] bool nodeProgressAsyncNumber(BinderNode* node); 289 290 RpcMutex mNodeMutex; 291 bool mTerminated = false; 292 uint32_t mNextId = 0; 293 // binders known by both sides of a session 294 std::map<uint64_t, BinderNode> mNodeForAddress; 295 }; 296 297 } // namespace android 298