blob: 49038b1974c626b94b0b60fb7869280c410101b4 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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#define LOG_TAG "BpBinder"
18//#define LOG_NDEBUG 0
19
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070020#include <binder/BpBinder.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070022#include <binder/IPCThreadState.h>
Dianne Hackborn23eb1e22015-10-07 17:35:27 -070023#include <binder/IResultReceiver.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000024#include <binder/RpcSession.h>
Steven Moreland6e5a7752019-08-05 20:30:14 -070025#include <binder/Stability.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
27#include <stdio.h>
28
Steven Moreland32150282021-11-12 22:54:53 +000029#include "BuildFlags.h"
30
Sahil Somani2522b072022-08-08 14:07:47 -070031#include <android-base/file.h>
32
Steve Block6807e592011-10-20 11:56:00 +010033//#undef ALOGV
34//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
36namespace android {
37
38// ---------------------------------------------------------------------------
39
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -070040RpcMutex BpBinder::sTrackingLock;
Martijn Coenena8d509d2021-09-03 18:06:24 +020041std::unordered_map<int32_t, uint32_t> BpBinder::sTrackingMap;
42std::unordered_map<int32_t, uint32_t> BpBinder::sLastLimitCallbackMap;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070043int BpBinder::sNumTrackedUids = 0;
44std::atomic_bool BpBinder::sCountByUidEnabled(false);
45binder_proxy_limit_callback BpBinder::sLimitCallback;
46bool BpBinder::sBinderProxyThrottleCreate = false;
47
Steven Moreland847d8c52023-05-02 23:56:58 +000048static StaticString16 kDescriptorUninit(u"");
Steven Morelandf2830fe2022-12-21 00:45:34 +000049
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070050// Arbitrarily high value that probably distinguishes a bad behaving app
51uint32_t BpBinder::sBinderProxyCountHighWatermark = 2500;
52// Another arbitrary value a binder count needs to drop below before another callback will be called
53uint32_t BpBinder::sBinderProxyCountLowWatermark = 2000;
54
Jing Ji4c4ac062023-10-07 15:20:23 -070055std::atomic<uint32_t> BpBinder::sBinderProxyCount(0);
56std::atomic<uint32_t> BpBinder::sBinderProxyCountWarned(0);
57
58static constexpr uint32_t kBinderProxyCountWarnInterval = 5000;
59
Martijn Coenen1cad19c2021-10-04 09:19:01 +020060// Log any transactions for which the data exceeds this size
61#define LOG_TRANSACTIONS_OVER_SIZE (300 * 1024)
62
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070063enum {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -070064 LIMIT_REACHED_MASK = 0x80000000, // A flag denoting that the limit has been reached
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070065 COUNTING_VALUE_MASK = 0x7FFFFFFF, // A mask of the remaining bits for the count value
66};
67
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068BpBinder::ObjectManager::ObjectManager()
69{
70}
71
72BpBinder::ObjectManager::~ObjectManager()
73{
74 kill();
75}
76
Steven Moreland63a2d512021-06-25 01:10:15 +000077void* BpBinder::ObjectManager::attach(const void* objectID, void* object, void* cleanupCookie,
78 IBinder::object_cleanup_func func) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079 entry_t e;
80 e.object = object;
81 e.cleanupCookie = cleanupCookie;
82 e.func = func;
83
Jiyong Park5970d0a2022-03-08 16:56:13 +090084 if (mObjects.find(objectID) != mObjects.end()) {
Steven Moreland63a2d512021-06-25 01:10:15 +000085 ALOGI("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object "
86 "ID already in use",
87 objectID, this, object);
Jiyong Park5970d0a2022-03-08 16:56:13 +090088 return mObjects[objectID].object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089 }
90
Jiyong Park5970d0a2022-03-08 16:56:13 +090091 mObjects.insert({objectID, e});
Steven Moreland63a2d512021-06-25 01:10:15 +000092 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093}
94
95void* BpBinder::ObjectManager::find(const void* objectID) const
96{
Jiyong Park5970d0a2022-03-08 16:56:13 +090097 auto i = mObjects.find(objectID);
98 if (i == mObjects.end()) return nullptr;
99 return i->second.object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100}
101
Steven Moreland63a2d512021-06-25 01:10:15 +0000102void* BpBinder::ObjectManager::detach(const void* objectID) {
Jiyong Park5970d0a2022-03-08 16:56:13 +0900103 auto i = mObjects.find(objectID);
104 if (i == mObjects.end()) return nullptr;
105 void* value = i->second.object;
106 mObjects.erase(i);
Steven Moreland63a2d512021-06-25 01:10:15 +0000107 return value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108}
109
Devin Moore3faaa002022-07-27 15:54:06 +0000110namespace {
111struct Tag {
112 wp<IBinder> binder;
113};
114} // namespace
115
116static void cleanWeak(const void* /* id */, void* obj, void* /* cookie */) {
117 delete static_cast<Tag*>(obj);
118}
119
120sp<IBinder> BpBinder::ObjectManager::lookupOrCreateWeak(const void* objectID, object_make_func make,
121 const void* makeArgs) {
122 entry_t& e = mObjects[objectID];
123 if (e.object != nullptr) {
124 if (auto attached = static_cast<Tag*>(e.object)->binder.promote()) {
125 return attached;
126 }
127 } else {
128 e.object = new Tag;
129 LOG_ALWAYS_FATAL_IF(!e.object, "no more memory");
130 }
131 sp<IBinder> newObj = make(makeArgs);
132
133 static_cast<Tag*>(e.object)->binder = newObj;
134 e.cleanupCookie = nullptr;
135 e.func = cleanWeak;
136
137 return newObj;
138}
139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140void BpBinder::ObjectManager::kill()
141{
142 const size_t N = mObjects.size();
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700143 ALOGV("Killing %zu objects in manager %p", N, this);
Jiyong Park5970d0a2022-03-08 16:56:13 +0900144 for (auto i : mObjects) {
145 const entry_t& e = i.second;
Yi Kongfdd8da92018-06-07 17:52:27 -0700146 if (e.func != nullptr) {
Jiyong Park5970d0a2022-03-08 16:56:13 +0900147 e.func(i.first, e.object, e.cleanupCookie);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800148 }
149 }
150
151 mObjects.clear();
152}
153
154// ---------------------------------------------------------------------------
155
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000156sp<BpBinder> BpBinder::create(int32_t handle) {
Steven Moreland32150282021-11-12 22:54:53 +0000157 if constexpr (!kEnableKernelIpc) {
158 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
159 return nullptr;
160 }
161
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700162 int32_t trackedUid = -1;
163 if (sCountByUidEnabled) {
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700164 trackedUid = IPCThreadState::self()->getCallingUid();
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700165 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700166 uint32_t trackedValue = sTrackingMap[trackedUid];
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000167 if (trackedValue & LIMIT_REACHED_MASK) [[unlikely]] {
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700168 if (sBinderProxyThrottleCreate) {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700169 return nullptr;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700170 }
Martijn Coenena8d509d2021-09-03 18:06:24 +0200171 trackedValue = trackedValue & COUNTING_VALUE_MASK;
172 uint32_t lastLimitCallbackAt = sLastLimitCallbackMap[trackedUid];
173
174 if (trackedValue > lastLimitCallbackAt &&
Martijn Coenen6711b6d2021-09-23 09:44:29 +0200175 (trackedValue - lastLimitCallbackAt > sBinderProxyCountHighWatermark)) {
Martijn Coenena8d509d2021-09-03 18:06:24 +0200176 ALOGE("Still too many binder proxy objects sent to uid %d from uid %d (%d proxies "
177 "held)",
178 getuid(), trackedUid, trackedValue);
179 if (sLimitCallback) sLimitCallback(trackedUid);
180 sLastLimitCallbackMap[trackedUid] = trackedValue;
181 }
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700182 } else {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700183 if ((trackedValue & COUNTING_VALUE_MASK) >= sBinderProxyCountHighWatermark) {
184 ALOGE("Too many binder proxy objects sent to uid %d from uid %d (%d proxies held)",
185 getuid(), trackedUid, trackedValue);
186 sTrackingMap[trackedUid] |= LIMIT_REACHED_MASK;
187 if (sLimitCallback) sLimitCallback(trackedUid);
Martijn Coenena8d509d2021-09-03 18:06:24 +0200188 sLastLimitCallbackMap[trackedUid] = trackedValue & COUNTING_VALUE_MASK;
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700189 if (sBinderProxyThrottleCreate) {
190 ALOGI("Throttling binder proxy creates from uid %d in uid %d until binder proxy"
191 " count drops below %d",
192 trackedUid, getuid(), sBinderProxyCountLowWatermark);
193 return nullptr;
194 }
195 }
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700196 }
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700197 sTrackingMap[trackedUid]++;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700198 }
Jing Ji4c4ac062023-10-07 15:20:23 -0700199 uint32_t numProxies = sBinderProxyCount.fetch_add(1, std::memory_order_relaxed);
200 uint32_t numLastWarned = sBinderProxyCountWarned.load(std::memory_order_relaxed);
201 uint32_t numNextWarn = numLastWarned + kBinderProxyCountWarnInterval;
202 if (numProxies >= numNextWarn) {
203 // Multiple threads can get here, make sure only one of them gets to
204 // update the warn counter.
205 if (sBinderProxyCountWarned.compare_exchange_strong(numLastWarned,
206 numNextWarn,
207 std::memory_order_relaxed)) {
208 ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
209 }
210 }
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000211 return sp<BpBinder>::make(BinderHandle{handle}, trackedUid);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700212}
213
Steven Moreland5623d1a2021-09-10 15:45:34 -0700214sp<BpBinder> BpBinder::create(const sp<RpcSession>& session, uint64_t address) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000215 LOG_ALWAYS_FATAL_IF(session == nullptr, "BpBinder::create null session");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216
Steven Moreland5553ac42020-11-11 02:14:45 +0000217 // These are not currently tracked, since there is no UID or other
218 // identifier to track them with. However, if similar functionality is
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000219 // needed, session objects keep track of all BpBinder objects on a
220 // per-session basis.
Steven Moreland5553ac42020-11-11 02:14:45 +0000221
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000222 return sp<BpBinder>::make(RpcHandle{session, address});
Steven Moreland5553ac42020-11-11 02:14:45 +0000223}
224
225BpBinder::BpBinder(Handle&& handle)
226 : mStability(0),
227 mHandle(handle),
228 mAlive(true),
229 mObitsSent(false),
230 mObituaries(nullptr),
Steven Morelandf2830fe2022-12-21 00:45:34 +0000231 mDescriptorCache(kDescriptorUninit),
Steven Moreland5553ac42020-11-11 02:14:45 +0000232 mTrackedUid(-1) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234}
235
Steven Moreland5553ac42020-11-11 02:14:45 +0000236BpBinder::BpBinder(BinderHandle&& handle, int32_t trackedUid) : BpBinder(Handle(handle)) {
Steven Moreland32150282021-11-12 22:54:53 +0000237 if constexpr (!kEnableKernelIpc) {
238 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
239 return;
240 }
241
Steven Moreland5553ac42020-11-11 02:14:45 +0000242 mTrackedUid = trackedUid;
243
244 ALOGV("Creating BpBinder %p handle %d\n", this, this->binderHandle());
245
246 IPCThreadState::self()->incWeakHandle(this->binderHandle(), this);
247}
248
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000249BpBinder::BpBinder(RpcHandle&& handle) : BpBinder(Handle(handle)) {
250 LOG_ALWAYS_FATAL_IF(rpcSession() == nullptr, "BpBinder created w/o session object");
Steven Moreland5553ac42020-11-11 02:14:45 +0000251}
252
253bool BpBinder::isRpcBinder() const {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000254 return std::holds_alternative<RpcHandle>(mHandle);
Steven Moreland5553ac42020-11-11 02:14:45 +0000255}
256
Steven Moreland5623d1a2021-09-10 15:45:34 -0700257uint64_t BpBinder::rpcAddress() const {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000258 return std::get<RpcHandle>(mHandle).address;
Steven Moreland5553ac42020-11-11 02:14:45 +0000259}
260
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000261const sp<RpcSession>& BpBinder::rpcSession() const {
262 return std::get<RpcHandle>(mHandle).session;
Steven Moreland5553ac42020-11-11 02:14:45 +0000263}
264
265int32_t BpBinder::binderHandle() const {
266 return std::get<BinderHandle>(mHandle).handle;
Steven Moreland85180c02019-07-16 14:24:20 -0700267}
268
Devin Mooref6f2e642021-08-05 19:03:47 +0000269std::optional<int32_t> BpBinder::getDebugBinderHandle() const {
270 if (!isRpcBinder()) {
271 return binderHandle();
272 } else {
273 return std::nullopt;
274 }
275}
276
Mathias Agopian83c04462009-05-22 19:00:22 -0700277bool BpBinder::isDescriptorCached() const {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700278 RpcMutexUniqueLock _l(mLock);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000279 return mDescriptorCache.c_str() != kDescriptorUninit.c_str();
Mathias Agopian83c04462009-05-22 19:00:22 -0700280}
281
282const String16& BpBinder::getInterfaceDescriptor() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283{
Steven Morelandf2830fe2022-12-21 00:45:34 +0000284 if (!isDescriptorCached()) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000285 sp<BpBinder> thiz = sp<BpBinder>::fromExisting(const_cast<BpBinder*>(this));
Steven Moreland4cf688f2021-03-31 01:48:58 +0000286
287 Parcel data;
288 data.markForBinder(thiz);
289 Parcel reply;
Mathias Agopian83c04462009-05-22 19:00:22 -0700290 // do the IPC without a lock held.
Steven Moreland4cf688f2021-03-31 01:48:58 +0000291 status_t err = thiz->transact(INTERFACE_TRANSACTION, data, &reply);
Mathias Agopian83c04462009-05-22 19:00:22 -0700292 if (err == NO_ERROR) {
293 String16 res(reply.readString16());
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700294 RpcMutexUniqueLock _l(mLock);
Mathias Agopian83c04462009-05-22 19:00:22 -0700295 // mDescriptorCache could have been assigned while the lock was
296 // released.
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000297 if (mDescriptorCache.c_str() == kDescriptorUninit.c_str()) mDescriptorCache = res;
Mathias Agopian83c04462009-05-22 19:00:22 -0700298 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700300
Mathias Agopian83c04462009-05-22 19:00:22 -0700301 // we're returning a reference to a non-static object here. Usually this
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700302 // is not something smart to do, however, with binder objects it is
Mathias Agopian83c04462009-05-22 19:00:22 -0700303 // (usually) safe because they are reference-counted.
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700304
Mathias Agopian83c04462009-05-22 19:00:22 -0700305 return mDescriptorCache;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306}
307
308bool BpBinder::isBinderAlive() const
309{
Steven Moreland06074d82020-03-05 23:16:51 +0000310 return mAlive != 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800311}
312
313status_t BpBinder::pingBinder()
314{
Steven Moreland5553ac42020-11-11 02:14:45 +0000315 Parcel data;
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000316 data.markForBinder(sp<BpBinder>::fromExisting(this));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317 Parcel reply;
Steven Moreland5553ac42020-11-11 02:14:45 +0000318 return transact(PING_TRANSACTION, data, &reply);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319}
320
Sahil Somani2522b072022-08-08 14:07:47 -0700321status_t BpBinder::startRecordingBinder(const android::base::unique_fd& fd) {
322 Parcel send, reply;
323 send.writeUniqueFileDescriptor(fd);
324 return transact(START_RECORDING_TRANSACTION, send, &reply);
325}
326
327status_t BpBinder::stopRecordingBinder() {
328 Parcel data, reply;
329 data.markForBinder(sp<BpBinder>::fromExisting(this));
330 return transact(STOP_RECORDING_TRANSACTION, data, &reply);
331}
332
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333status_t BpBinder::dump(int fd, const Vector<String16>& args)
334{
335 Parcel send;
336 Parcel reply;
337 send.writeFileDescriptor(fd);
338 const size_t numArgs = args.size();
339 send.writeInt32(numArgs);
340 for (size_t i = 0; i < numArgs; i++) {
341 send.writeString16(args[i]);
342 }
343 status_t err = transact(DUMP_TRANSACTION, send, &reply);
344 return err;
345}
346
Jiyong Parkb86c8662018-10-29 23:01:57 +0900347// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348status_t BpBinder::transact(
349 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
350{
351 // Once a binder has died, it will never come back to life.
352 if (mAlive) {
Steven Moreland46b5fea2019-10-15 11:22:18 -0700353 bool privateVendor = flags & FLAG_PRIVATE_VENDOR;
354 // don't send userspace flags to the kernel
Andrei Homescu7cdf5c22022-04-30 03:41:16 +0000355 flags = flags & ~static_cast<uint32_t>(FLAG_PRIVATE_VENDOR);
Steven Moreland46b5fea2019-10-15 11:22:18 -0700356
Steven Moreland6e5a7752019-08-05 20:30:14 -0700357 // user transactions require a given stability level
358 if (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {
359 using android::internal::Stability;
360
Steven Moreland16a41062021-07-23 13:35:25 -0700361 int16_t stability = Stability::getRepr(this);
Steven Moreland89ddfc52020-11-13 02:39:26 +0000362 Stability::Level required = privateVendor ? Stability::VENDOR
363 : Stability::getLocalLevel();
Steven Moreland6e5a7752019-08-05 20:30:14 -0700364
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000365 if (!Stability::check(stability, required)) [[unlikely]] {
Steven Morelandb269b582021-02-10 17:09:11 +0000366 ALOGE("Cannot do a user transaction on a %s binder (%s) in a %s context.",
Steven Moreland16a41062021-07-23 13:35:25 -0700367 Stability::levelString(stability).c_str(),
368 String8(getInterfaceDescriptor()).c_str(),
369 Stability::levelString(required).c_str());
Steven Moreland6e5a7752019-08-05 20:30:14 -0700370 return BAD_TYPE;
371 }
372 }
373
Steven Moreland5553ac42020-11-11 02:14:45 +0000374 status_t status;
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000375 if (isRpcBinder()) [[unlikely]] {
Steven Morelandf5174272021-05-25 00:39:28 +0000376 status = rpcSession()->transact(sp<IBinder>::fromExisting(this), code, data, reply,
377 flags);
Steven Moreland5553ac42020-11-11 02:14:45 +0000378 } else {
Steven Moreland32150282021-11-12 22:54:53 +0000379 if constexpr (!kEnableKernelIpc) {
380 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
381 return INVALID_OPERATION;
382 }
383
Steven Moreland5553ac42020-11-11 02:14:45 +0000384 status = IPCThreadState::self()->transact(binderHandle(), code, data, reply, flags);
385 }
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200386 if (data.dataSize() > LOG_TRANSACTIONS_OVER_SIZE) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700387 RpcMutexUniqueLock _l(mLock);
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200388 ALOGW("Large outgoing transaction of %zu bytes, interface descriptor %s, code %d",
Steven Morelandf2830fe2022-12-21 00:45:34 +0000389 data.dataSize(), String8(mDescriptorCache).c_str(), code);
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200390 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000391
Steven Moreland06074d82020-03-05 23:16:51 +0000392 if (status == DEAD_OBJECT) mAlive = 0;
Steven Morelanda86a3562019-08-01 23:28:34 +0000393
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394 return status;
395 }
396
397 return DEAD_OBJECT;
398}
399
Jiyong Parkb86c8662018-10-29 23:01:57 +0900400// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401status_t BpBinder::linkToDeath(
402 const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
403{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000404 if (isRpcBinder()) {
405 if (rpcSession()->getMaxIncomingThreads() < 1) {
Devin Moorebd41dc12023-02-08 17:06:22 +0000406 ALOGE("Cannot register a DeathRecipient without any incoming threads. Need to set max "
407 "incoming threads to a value greater than 0 before calling linkToDeath.");
Devin Moore66d5b7a2022-07-07 21:42:10 +0000408 return INVALID_OPERATION;
409 }
410 } else if constexpr (!kEnableKernelIpc) {
Steven Moreland32150282021-11-12 22:54:53 +0000411 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
412 return INVALID_OPERATION;
Devin Moore66d5b7a2022-07-07 21:42:10 +0000413 } else {
414 if (ProcessState::self()->getThreadPoolMaxTotalThreadCount() == 0) {
415 ALOGW("Linking to death on %s but there are no threads (yet?) listening to incoming "
416 "transactions. See ProcessState::startThreadPool and "
417 "ProcessState::setThreadPoolMaxThreadCount. Generally you should setup the "
418 "binder "
419 "threadpool before other initialization steps.",
420 String8(getInterfaceDescriptor()).c_str());
421 }
Steven Moreland32150282021-11-12 22:54:53 +0000422 }
423
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 Obituary ob;
425 ob.recipient = recipient;
426 ob.cookie = cookie;
427 ob.flags = flags;
428
Yi Kongfdd8da92018-06-07 17:52:27 -0700429 LOG_ALWAYS_FATAL_IF(recipient == nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430 "linkToDeath(): recipient must be non-NULL");
431
432 {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700433 RpcMutexUniqueLock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434
435 if (!mObitsSent) {
436 if (!mObituaries) {
437 mObituaries = new Vector<Obituary>;
438 if (!mObituaries) {
439 return NO_MEMORY;
440 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 ALOGV("Requesting death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000442 if (!isRpcBinder()) {
443 if constexpr (kEnableKernelIpc) {
444 getWeakRefs()->incWeak(this);
445 IPCThreadState* self = IPCThreadState::self();
446 self->requestDeathNotification(binderHandle(), this);
447 self->flushCommands();
448 }
449 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 }
451 ssize_t res = mObituaries->add(ob);
452 return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
453 }
454 }
455
456 return DEAD_OBJECT;
457}
458
Jiyong Parkb86c8662018-10-29 23:01:57 +0900459// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800460status_t BpBinder::unlinkToDeath(
461 const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
462 wp<DeathRecipient>* outRecipient)
463{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000464 if (!kEnableKernelIpc && !isRpcBinder()) {
Steven Moreland32150282021-11-12 22:54:53 +0000465 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
466 return INVALID_OPERATION;
467 }
468
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700469 RpcMutexUniqueLock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470
471 if (mObitsSent) {
472 return DEAD_OBJECT;
473 }
474
475 const size_t N = mObituaries ? mObituaries->size() : 0;
476 for (size_t i=0; i<N; i++) {
477 const Obituary& obit = mObituaries->itemAt(i);
478 if ((obit.recipient == recipient
Yi Kongfdd8da92018-06-07 17:52:27 -0700479 || (recipient == nullptr && obit.cookie == cookie))
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800480 && obit.flags == flags) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700481 if (outRecipient != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800482 *outRecipient = mObituaries->itemAt(i).recipient;
483 }
484 mObituaries->removeAt(i);
485 if (mObituaries->size() == 0) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000486 ALOGV("Clearing death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000487 if (!isRpcBinder()) {
488 if constexpr (kEnableKernelIpc) {
489 IPCThreadState* self = IPCThreadState::self();
490 self->clearDeathNotification(binderHandle(), this);
491 self->flushCommands();
492 }
493 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800494 delete mObituaries;
Yi Kongfdd8da92018-06-07 17:52:27 -0700495 mObituaries = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800496 }
497 return NO_ERROR;
498 }
499 }
500
501 return NAME_NOT_FOUND;
502}
503
504void BpBinder::sendObituary()
505{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000506 if (!kEnableKernelIpc && !isRpcBinder()) {
Steven Moreland32150282021-11-12 22:54:53 +0000507 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
508 return;
509 }
510
Steven Moreland5553ac42020-11-11 02:14:45 +0000511 ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n", this, binderHandle(),
512 mObitsSent ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800513
Steven Moreland06074d82020-03-05 23:16:51 +0000514 mAlive = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515 if (mObitsSent) return;
516
517 mLock.lock();
518 Vector<Obituary>* obits = mObituaries;
Yi Kongfdd8da92018-06-07 17:52:27 -0700519 if(obits != nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000520 ALOGV("Clearing sent death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000521 if (!isRpcBinder()) {
522 if constexpr (kEnableKernelIpc) {
523 IPCThreadState* self = IPCThreadState::self();
524 self->clearDeathNotification(binderHandle(), this);
525 self->flushCommands();
526 }
527 }
Yi Kongfdd8da92018-06-07 17:52:27 -0700528 mObituaries = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529 }
Steven Moreland06074d82020-03-05 23:16:51 +0000530 mObitsSent = 1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531 mLock.unlock();
532
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700533 ALOGV("Reporting death of proxy %p for %zu recipients\n",
534 this, obits ? obits->size() : 0U);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535
Yi Kongfdd8da92018-06-07 17:52:27 -0700536 if (obits != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537 const size_t N = obits->size();
538 for (size_t i=0; i<N; i++) {
539 reportOneDeath(obits->itemAt(i));
540 }
541
542 delete obits;
543 }
544}
545
546void BpBinder::reportOneDeath(const Obituary& obit)
547{
548 sp<DeathRecipient> recipient = obit.recipient.promote();
Steve Block6807e592011-10-20 11:56:00 +0100549 ALOGV("Reporting death to recipient: %p\n", recipient.get());
Yi Kongfdd8da92018-06-07 17:52:27 -0700550 if (recipient == nullptr) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000552 recipient->binderDied(wp<BpBinder>::fromExisting(this));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553}
554
Steven Moreland63a2d512021-06-25 01:10:15 +0000555void* BpBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
556 object_cleanup_func func) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700557 RpcMutexUniqueLock _l(mLock);
Steve Block6807e592011-10-20 11:56:00 +0100558 ALOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);
Steven Moreland63a2d512021-06-25 01:10:15 +0000559 return mObjects.attach(objectID, object, cleanupCookie, func);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560}
561
562void* BpBinder::findObject(const void* objectID) const
563{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700564 RpcMutexUniqueLock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800565 return mObjects.find(objectID);
566}
567
Steven Moreland63a2d512021-06-25 01:10:15 +0000568void* BpBinder::detachObject(const void* objectID) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700569 RpcMutexUniqueLock _l(mLock);
Steven Moreland63a2d512021-06-25 01:10:15 +0000570 return mObjects.detach(objectID);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800571}
572
Steven Moreland9e759e82021-06-25 21:30:23 +0000573void BpBinder::withLock(const std::function<void()>& doWithLock) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700574 RpcMutexUniqueLock _l(mLock);
Steven Moreland9e759e82021-06-25 21:30:23 +0000575 doWithLock();
576}
577
Devin Moore3faaa002022-07-27 15:54:06 +0000578sp<IBinder> BpBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
579 const void* makeArgs) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700580 RpcMutexUniqueLock _l(mLock);
Devin Moore3faaa002022-07-27 15:54:06 +0000581 return mObjects.lookupOrCreateWeak(objectID, make, makeArgs);
582}
583
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584BpBinder* BpBinder::remoteBinder()
585{
586 return this;
587}
588
Steven Moreland32150282021-11-12 22:54:53 +0000589BpBinder::~BpBinder() {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000590 if (isRpcBinder()) [[unlikely]] {
591 return;
592 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800593
Steven Moreland32150282021-11-12 22:54:53 +0000594 if constexpr (!kEnableKernelIpc) {
595 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
596 return;
597 }
598
599 ALOGV("Destroying BpBinder %p handle %d\n", this, binderHandle());
600
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800601 IPCThreadState* ipc = IPCThreadState::self();
602
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700603 if (mTrackedUid >= 0) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700604 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700605 uint32_t trackedValue = sTrackingMap[mTrackedUid];
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000606 if ((trackedValue & COUNTING_VALUE_MASK) == 0) [[unlikely]] {
Steven Moreland5553ac42020-11-11 02:14:45 +0000607 ALOGE("Unexpected Binder Proxy tracking decrement in %p handle %d\n", this,
608 binderHandle());
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700609 } else {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000610 auto countingValue = trackedValue & COUNTING_VALUE_MASK;
611 if ((trackedValue & LIMIT_REACHED_MASK) &&
612 (countingValue <= sBinderProxyCountLowWatermark)) [[unlikely]] {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700613 ALOGI("Limit reached bit reset for uid %d (fewer than %d proxies from uid %d held)",
Martijn Coenena8d509d2021-09-03 18:06:24 +0200614 getuid(), sBinderProxyCountLowWatermark, mTrackedUid);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700615 sTrackingMap[mTrackedUid] &= ~LIMIT_REACHED_MASK;
Martijn Coenena8d509d2021-09-03 18:06:24 +0200616 sLastLimitCallbackMap.erase(mTrackedUid);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700617 }
618 if (--sTrackingMap[mTrackedUid] == 0) {
619 sTrackingMap.erase(mTrackedUid);
620 }
621 }
622 }
Jing Ji4c4ac062023-10-07 15:20:23 -0700623 --sBinderProxyCount;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700624
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800625 if (ipc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000626 ipc->expungeHandle(binderHandle(), this);
627 ipc->decWeakHandle(binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800628 }
629}
630
Steven Moreland32150282021-11-12 22:54:53 +0000631void BpBinder::onFirstRef() {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000632 if (isRpcBinder()) [[unlikely]] {
633 return;
634 }
Steven Moreland32150282021-11-12 22:54:53 +0000635
636 if constexpr (!kEnableKernelIpc) {
637 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
638 return;
639 }
640
641 ALOGV("onFirstRef BpBinder %p handle %d\n", this, binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800642 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000643 if (ipc) ipc->incStrongHandle(binderHandle(), this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800644}
645
Steven Moreland32150282021-11-12 22:54:53 +0000646void BpBinder::onLastStrongRef(const void* /*id*/) {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000647 if (isRpcBinder()) [[unlikely]] {
Steven Moreland4f622fe2021-09-13 17:38:09 -0700648 (void)rpcSession()->sendDecStrong(this);
Steven Moreland5553ac42020-11-11 02:14:45 +0000649 return;
650 }
Steven Moreland32150282021-11-12 22:54:53 +0000651
652 if constexpr (!kEnableKernelIpc) {
653 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
654 return;
655 }
656
657 ALOGV("onLastStrongRef BpBinder %p handle %d\n", this, binderHandle());
Steve Block6807e592011-10-20 11:56:00 +0100658 IF_ALOGV() {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800659 printRefs();
660 }
661 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000662 if (ipc) ipc->decStrongHandle(binderHandle());
Steven Moreland80d23932019-06-07 12:43:27 -0700663
664 mLock.lock();
665 Vector<Obituary>* obits = mObituaries;
666 if(obits != nullptr) {
667 if (!obits->isEmpty()) {
Steven Moreland70fcb4e2019-12-13 17:28:58 -0800668 ALOGI("onLastStrongRef automatically unlinking death recipients: %s",
Steven Morelandf2830fe2022-12-21 00:45:34 +0000669 String8(mDescriptorCache).c_str());
Steven Moreland80d23932019-06-07 12:43:27 -0700670 }
671
Steven Moreland5553ac42020-11-11 02:14:45 +0000672 if (ipc) ipc->clearDeathNotification(binderHandle(), this);
Steven Moreland80d23932019-06-07 12:43:27 -0700673 mObituaries = nullptr;
674 }
675 mLock.unlock();
676
677 if (obits != nullptr) {
678 // XXX Should we tell any remaining DeathRecipient
679 // objects that the last strong ref has gone away, so they
680 // are no longer linked?
681 delete obits;
682 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800683}
684
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800685bool BpBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800686{
Steven Moreland5553ac42020-11-11 02:14:45 +0000687 // RPC binder doesn't currently support inc from weak binders
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000688 if (isRpcBinder()) [[unlikely]] {
689 return false;
690 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000691
Steven Moreland32150282021-11-12 22:54:53 +0000692 if constexpr (!kEnableKernelIpc) {
693 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
694 return false;
695 }
696
Steven Moreland5553ac42020-11-11 02:14:45 +0000697 ALOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800698 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000699 return ipc ? ipc->attemptIncStrongHandle(binderHandle()) == NO_ERROR : false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700}
701
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700702uint32_t BpBinder::getBinderProxyCount(uint32_t uid)
703{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700704 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700705 auto it = sTrackingMap.find(uid);
706 if (it != sTrackingMap.end()) {
707 return it->second & COUNTING_VALUE_MASK;
708 }
709 return 0;
710}
711
Jing Ji4c4ac062023-10-07 15:20:23 -0700712uint32_t BpBinder::getBinderProxyCount()
713{
714 return sBinderProxyCount.load();
715}
716
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700717void BpBinder::getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts)
718{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700719 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700720 uids.setCapacity(sTrackingMap.size());
721 counts.setCapacity(sTrackingMap.size());
722 for (const auto& it : sTrackingMap) {
723 uids.push_back(it.first);
724 counts.push_back(it.second & COUNTING_VALUE_MASK);
725 }
726}
727
728void BpBinder::enableCountByUid() { sCountByUidEnabled.store(true); }
729void BpBinder::disableCountByUid() { sCountByUidEnabled.store(false); }
730void BpBinder::setCountByUidEnabled(bool enable) { sCountByUidEnabled.store(enable); }
731
732void BpBinder::setLimitCallback(binder_proxy_limit_callback cb) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700733 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700734 sLimitCallback = cb;
735}
736
737void BpBinder::setBinderProxyCountWatermarks(int high, int low) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700738 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700739 sBinderProxyCountHighWatermark = high;
740 sBinderProxyCountLowWatermark = low;
741}
742
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800743// ---------------------------------------------------------------------------
744
Steven Moreland61ff8492019-09-26 16:05:45 -0700745} // namespace android