blob: 0e23ea7515e3d30e83b01da54646bdf57dd11c66 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
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>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000021#include <binder/RpcSession.h>
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000022#include <binder/RpcThreads.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000023
24#include <map>
Steven Morelande8393342021-05-05 23:27:53 +000025#include <optional>
Steven Moreland5553ac42020-11-11 02:14:45 +000026#include <queue>
27
Andrei Homescua39e4ed2021-12-10 08:41:54 +000028#include <sys/uio.h>
29
Steven Moreland5553ac42020-11-11 02:14:45 +000030namespace android {
31
32struct 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
Steven Morelandb8176792021-06-22 20:29:21 +000048#define RPC_FLAKE_PRONE false
49
Devin Moore08256432021-07-02 13:03:49 -070050#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000051void rpcMaybeWaitToFlake();
52#define MAYBE_WAIT_IN_FLAKE_MODE rpcMaybeWaitToFlake()
53#else
54#define MAYBE_WAIT_IN_FLAKE_MODE do {} while (false)
55#endif
56
Steven Moreland5553ac42020-11-11 02:14:45 +000057/**
58 * Abstracts away management of ref counts and the wire format from
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059 * RpcSession
Steven Moreland5553ac42020-11-11 02:14:45 +000060 */
61class RpcState {
62public:
63 RpcState();
64 ~RpcState();
65
Steven Morelandfc027e02021-10-25 15:31:31 -070066 [[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);
Steven Morelandc88b7fc2021-06-10 00:40:39 +000072
Steven Moreland7c5e6c22021-05-01 02:55:20 +000073 // TODO(b/182940634): combine some special transactions into one "getServerInfo" call?
Steven Moreland5ae62562021-06-10 03:21:42 +000074 sp<IBinder> getRootObject(const sp<RpcSession::RpcConnection>& connection,
75 const sp<RpcSession>& session);
Steven Morelandfc027e02021-10-25 15:31:31 -070076 [[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);
Steven Moreland5553ac42020-11-11 02:14:45 +000081
Steven Moreland5ae62562021-06-10 03:21:42 +000082 [[nodiscard]] status_t transact(const sp<RpcSession::RpcConnection>& connection,
83 const sp<IBinder>& address, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000084 const sp<RpcSession>& session, Parcel* reply, uint32_t flags);
Steven Moreland5ae62562021-06-10 03:21:42 +000085 [[nodiscard]] status_t transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -070086 uint64_t address, uint32_t code, const Parcel& data,
87 const sp<RpcSession>& session, Parcel* reply,
88 uint32_t flags);
Steven Morelandfd1e8a02021-07-21 23:30:29 +000089
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);
Steven Moreland52eee942021-06-03 00:59:28 +0000112
113 enum class CommandType {
114 ANY,
115 CONTROL_ONLY,
116 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000117 [[nodiscard]] status_t getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland52eee942021-06-03 00:59:28 +0000118 const sp<RpcSession>& session, CommandType type);
Steven Moreland5ae62562021-06-10 03:21:42 +0000119 [[nodiscard]] status_t drainCommands(const sp<RpcSession::RpcConnection>& connection,
120 const sp<RpcSession>& session, CommandType type);
Steven Moreland5553ac42020-11-11 02:14:45 +0000121
122 /**
123 * Called by Parcel for outgoing binders. This implies one refcount of
124 * ownership to the outgoing binder.
125 */
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000126 [[nodiscard]] status_t onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700127 uint64_t* outAddress);
Steven Moreland5553ac42020-11-11 02:14:45 +0000128
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 */
Steven Moreland5623d1a2021-09-10 15:45:34 -0700134 [[nodiscard]] status_t onBinderEntering(const sp<RpcSession>& session, uint64_t address,
135 sp<IBinder>* out);
Steven Morelandd8083312021-09-22 13:37:10 -0700136 /**
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);
Devin Moore66d5b7a2022-07-07 21:42:10 +0000143 /**
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);
Steven Moreland5553ac42020-11-11 02:14:45 +0000148
149 size_t countBinders();
150 void dump();
151
Steven Moreland5553ac42020-11-11 02:14:45 +0000152 /**
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000153 * Called when reading or writing data to a session fails to clean up
154 * data associated with the session in order to cleanup binders.
Steven Moreland5553ac42020-11-11 02:14:45 +0000155 * Specifically, we have a strong dependency cycle, since BpBinder is
156 * OBJECT_LIFETIME_WEAK (so that onAttemptIncStrong may return true).
157 *
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000158 * BpBinder -> RpcSession -> RpcState
Steven Moreland5553ac42020-11-11 02:14:45 +0000159 * ^-----------------------------/
160 *
161 * In the success case, eventually all refcounts should be propagated over
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162 * the session, though this could also be called to eagerly cleanup
163 * the session.
Steven Moreland5553ac42020-11-11 02:14:45 +0000164 *
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000165 * WARNING: RpcState is responsible for calling this when the session is
Steven Moreland5553ac42020-11-11 02:14:45 +0000166 * no longer recoverable.
167 */
Steven Morelandc9d7b532021-06-04 20:57:41 +0000168 void clear();
Steven Moreland5553ac42020-11-11 02:14:45 +0000169
Steven Moreland659416d2021-05-11 00:47:50 +0000170private:
Steven Moreland67f85902023-03-15 01:13:49 +0000171 void clear(RpcMutexUniqueLock nodeLock);
Steven Moreland583a14a2021-06-04 02:04:58 +0000172 void dumpLocked();
Steven Moreland583a14a2021-06-04 02:04:58 +0000173
Steven Morelanddbe71832021-05-12 23:31:00 +0000174 // 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);
Steven Morelande8393342021-05-05 23:27:53 +0000178 bool valid() { return mSize == 0 || mData != nullptr; }
179 size_t size() { return mSize; }
180 uint8_t* data() { return mData.get(); }
181 uint8_t* release() { return mData.release(); }
182
183 private:
184 std::unique_ptr<uint8_t[]> mData;
185 size_t mSize;
186 };
187
Devin Moore695368f2022-06-03 22:29:14 +0000188 [[nodiscard]] status_t rpcSend(
189 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
190 const char* what, iovec* iovs, int niovs,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000191 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);
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000194 [[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);
Steven Moreland5553ac42020-11-11 02:14:45 +0000198
Steven Moreland5ae62562021-06-10 03:21:42 +0000199 [[nodiscard]] status_t waitForReply(const sp<RpcSession::RpcConnection>& connection,
200 const sp<RpcSession>& session, Parcel* reply);
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000201 [[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);
Steven Moreland5ae62562021-06-10 03:21:42 +0000213 [[nodiscard]] status_t processDecStrong(const sp<RpcSession::RpcConnection>& connection,
Steven Morelandee3f4662021-05-22 01:07:33 +0000214 const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000215 const RpcWireHeader& command);
216
Frederick Mayle69a0c992022-05-26 20:38:39 +0000217 // Whether `parcel` is compatible with `session`.
218 [[nodiscard]] static status_t validateParcel(const sp<RpcSession>& session,
219 const Parcel& parcel, std::string* errorMsg);
220
Steven Moreland5553ac42020-11-11 02:14:45 +0000221 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 {
Steven Morelandf5174272021-05-25 00:39:28 +0000252 sp<IBinder> ref;
Steven Morelanddbe71832021-05-12 23:31:00 +0000253 CommandData data;
Frederick Mayleb0221d12022-10-03 23:10:53 +0000254 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000255 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)
Steven Moreland3fa32922022-07-14 18:45:51 +0000268
269 std::string toString() const;
Steven Moreland5553ac42020-11-11 02:14:45 +0000270 };
271
Steven Moreland67f85902023-03-15 01:13:49 +0000272 // 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
Steven Moreland583a14a2021-06-04 02:04:58 +0000286 // true - success
Steven Morelandc9d7b532021-06-04 20:57:41 +0000287 // false - session shutdown, halt
288 [[nodiscard]] bool nodeProgressAsyncNumber(BinderNode* node);
Steven Moreland31bde7a2021-06-04 00:57:36 +0000289
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000290 RpcMutex mNodeMutex;
Steven Moreland5553ac42020-11-11 02:14:45 +0000291 bool mTerminated = false;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700292 uint32_t mNextId = 0;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000293 // binders known by both sides of a session
Steven Moreland5623d1a2021-09-10 15:45:34 -0700294 std::map<uint64_t, BinderNode> mNodeForAddress;
Steven Moreland5553ac42020-11-11 02:14:45 +0000295};
296
297} // namespace android