blob: 6fb2e4a011ad8545c0034b0cfd50ea9cadaaac28 [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);
Steven Moreland5553ac42020-11-11 02:14:45 +0000143
144 size_t countBinders();
145 void dump();
146
Steven Moreland5553ac42020-11-11 02:14:45 +0000147 /**
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000148 * Called when reading or writing data to a session fails to clean up
149 * data associated with the session in order to cleanup binders.
Steven Moreland5553ac42020-11-11 02:14:45 +0000150 * Specifically, we have a strong dependency cycle, since BpBinder is
151 * OBJECT_LIFETIME_WEAK (so that onAttemptIncStrong may return true).
152 *
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000153 * BpBinder -> RpcSession -> RpcState
Steven Moreland5553ac42020-11-11 02:14:45 +0000154 * ^-----------------------------/
155 *
156 * In the success case, eventually all refcounts should be propagated over
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000157 * the session, though this could also be called to eagerly cleanup
158 * the session.
Steven Moreland5553ac42020-11-11 02:14:45 +0000159 *
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000160 * WARNING: RpcState is responsible for calling this when the session is
Steven Moreland5553ac42020-11-11 02:14:45 +0000161 * no longer recoverable.
162 */
Steven Morelandc9d7b532021-06-04 20:57:41 +0000163 void clear();
Steven Moreland5553ac42020-11-11 02:14:45 +0000164
Steven Moreland659416d2021-05-11 00:47:50 +0000165private:
Steven Moreland583a14a2021-06-04 02:04:58 +0000166 void dumpLocked();
Steven Moreland583a14a2021-06-04 02:04:58 +0000167
Steven Morelanddbe71832021-05-12 23:31:00 +0000168 // Alternative to std::vector<uint8_t> that doesn't abort on allocation failure and caps
169 // large allocations to avoid being requested from allocating too much data.
170 struct CommandData {
171 explicit CommandData(size_t size);
Steven Morelande8393342021-05-05 23:27:53 +0000172 bool valid() { return mSize == 0 || mData != nullptr; }
173 size_t size() { return mSize; }
174 uint8_t* data() { return mData.get(); }
175 uint8_t* release() { return mData.release(); }
176
177 private:
178 std::unique_ptr<uint8_t[]> mData;
179 size_t mSize;
180 };
181
Devin Moore695368f2022-06-03 22:29:14 +0000182 [[nodiscard]] status_t rpcSend(
183 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
184 const char* what, iovec* iovs, int niovs,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000185 const std::optional<android::base::function_ref<status_t()>>& altPoll,
186 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds =
187 nullptr);
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000188 [[nodiscard]] status_t rpcRec(
189 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
190 const char* what, iovec* iovs, int niovs,
191 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds = nullptr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000192
Steven Moreland5ae62562021-06-10 03:21:42 +0000193 [[nodiscard]] status_t waitForReply(const sp<RpcSession::RpcConnection>& connection,
194 const sp<RpcSession>& session, Parcel* reply);
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000195 [[nodiscard]] status_t processCommand(
196 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
197 const RpcWireHeader& command, CommandType type,
198 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds);
199 [[nodiscard]] status_t processTransact(
200 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
201 const RpcWireHeader& command,
202 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds);
203 [[nodiscard]] status_t processTransactInternal(
204 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
205 CommandData transactionData,
206 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds);
Steven Moreland5ae62562021-06-10 03:21:42 +0000207 [[nodiscard]] status_t processDecStrong(const sp<RpcSession::RpcConnection>& connection,
Steven Morelandee3f4662021-05-22 01:07:33 +0000208 const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000209 const RpcWireHeader& command);
210
Frederick Mayle69a0c992022-05-26 20:38:39 +0000211 // Whether `parcel` is compatible with `session`.
212 [[nodiscard]] static status_t validateParcel(const sp<RpcSession>& session,
213 const Parcel& parcel, std::string* errorMsg);
214
Steven Moreland5553ac42020-11-11 02:14:45 +0000215 struct BinderNode {
216 // Two cases:
217 // A - local binder we are serving
218 // B - remote binder, we are sending transactions to
219 wp<IBinder> binder;
220
221 // if timesSent > 0, this will be equal to binder.promote()
222 sp<IBinder> sentRef;
223
224 // Number of times we've sent this binder out of process, which
225 // translates to an implicit strong count. A client must send RPC binder
226 // socket's dec ref for each time it is sent out of process in order to
227 // deallocate it. Note, a proxy binder we are holding onto might be
228 // sent (this is important when the only remaining refcount of this
229 // binder is the one associated with a transaction sending it back to
230 // its server)
231 size_t timesSent = 0;
232
233 // Number of times we've received this binder, each time corresponds to
234 // a reference we hold over the wire (not a local incStrong/decStrong)
235 size_t timesRecd = 0;
236
237 // transaction ID, for async transactions
238 uint64_t asyncNumber = 0;
239
240 //
241 // CASE A - local binder we are serving
242 //
243
244 // async transaction queue, _only_ for local binder
245 struct AsyncTodo {
Steven Morelandf5174272021-05-25 00:39:28 +0000246 sp<IBinder> ref;
Steven Morelanddbe71832021-05-12 23:31:00 +0000247 CommandData data;
Steven Moreland5553ac42020-11-11 02:14:45 +0000248 uint64_t asyncNumber = 0;
249
250 bool operator<(const AsyncTodo& o) const {
251 return asyncNumber > /* !!! */ o.asyncNumber;
252 }
253 };
254 std::priority_queue<AsyncTodo> asyncTodo;
255
256 //
257 // CASE B - remote binder, we are sending transactions to
258 //
259
260 // (no additional data specific to remote binders)
261 };
262
Steven Moreland31bde7a2021-06-04 00:57:36 +0000263 // checks if there is any reference left to a node and erases it. If erase
264 // happens, and there is a strong reference to the binder kept by
265 // binderNode, this returns that strong reference, so that it can be
266 // dropped after any locks are removed.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700267 sp<IBinder> tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it);
Steven Moreland583a14a2021-06-04 02:04:58 +0000268 // true - success
Steven Morelandc9d7b532021-06-04 20:57:41 +0000269 // false - session shutdown, halt
270 [[nodiscard]] bool nodeProgressAsyncNumber(BinderNode* node);
Steven Moreland31bde7a2021-06-04 00:57:36 +0000271
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000272 RpcMutex mNodeMutex;
Steven Moreland5553ac42020-11-11 02:14:45 +0000273 bool mTerminated = false;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700274 uint32_t mNextId = 0;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000275 // binders known by both sides of a session
Steven Moreland5623d1a2021-09-10 15:45:34 -0700276 std::map<uint64_t, BinderNode> mNodeForAddress;
Steven Moreland5553ac42020-11-11 02:14:45 +0000277};
278
279} // namespace android