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 #define LOG_TAG "BpBinder"
18 //#define LOG_NDEBUG 0
19
20 #include <binder/BpBinder.h>
21
22 #include <binder/IPCThreadState.h>
23 #include <binder/IResultReceiver.h>
24 #include <binder/RpcSession.h>
25 #include <binder/Stability.h>
26 #include <binder/Trace.h>
27
28 #include <stdio.h>
29
30 #include "BuildFlags.h"
31 #include "file.h"
32
33 //#undef ALOGV
34 //#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
35
36 namespace android {
37
38 using android::binder::unique_fd;
39
40 // ---------------------------------------------------------------------------
41
42 RpcMutex BpBinder::sTrackingLock;
43 std::unordered_map<int32_t, uint32_t> BpBinder::sTrackingMap;
44 std::unordered_map<int32_t, uint32_t> BpBinder::sLastLimitCallbackMap;
45 int BpBinder::sNumTrackedUids = 0;
46 std::atomic_bool BpBinder::sCountByUidEnabled(false);
47 binder_proxy_limit_callback BpBinder::sLimitCallback;
48 binder_proxy_warning_callback BpBinder::sWarningCallback;
49 bool BpBinder::sBinderProxyThrottleCreate = false;
50
51 static StaticString16 kDescriptorUninit(u"");
52
53 // Arbitrarily high value that probably distinguishes a bad behaving app
54 uint32_t BpBinder::sBinderProxyCountHighWatermark = 2500;
55 // Another arbitrary value a binder count needs to drop below before another callback will be called
56 uint32_t BpBinder::sBinderProxyCountLowWatermark = 2000;
57 // Arbitrary value between low and high watermark on a bad behaving app to
58 // trigger a warning callback.
59 uint32_t BpBinder::sBinderProxyCountWarningWatermark = 2250;
60
61 std::atomic<uint32_t> BpBinder::sBinderProxyCount(0);
62 std::atomic<uint32_t> BpBinder::sBinderProxyCountWarned(0);
63
64 static constexpr uint32_t kBinderProxyCountWarnInterval = 5000;
65
66 // Log any transactions for which the data exceeds this size
67 #define LOG_TRANSACTIONS_OVER_SIZE (300 * 1024)
68
69 enum {
70 LIMIT_REACHED_MASK = 0x80000000, // A flag denoting that the limit has been reached
71 WARNING_REACHED_MASK = 0x40000000, // A flag denoting that the warning has been reached
72 COUNTING_VALUE_MASK = 0x3FFFFFFF, // A mask of the remaining bits for the count value
73 };
74
ObjectManager()75 BpBinder::ObjectManager::ObjectManager()
76 {
77 }
78
~ObjectManager()79 BpBinder::ObjectManager::~ObjectManager()
80 {
81 kill();
82 }
83
attach(const void * objectID,void * object,void * cleanupCookie,IBinder::object_cleanup_func func)84 void* BpBinder::ObjectManager::attach(const void* objectID, void* object, void* cleanupCookie,
85 IBinder::object_cleanup_func func) {
86 entry_t e;
87 e.object = object;
88 e.cleanupCookie = cleanupCookie;
89 e.func = func;
90
91 if (mObjects.find(objectID) != mObjects.end()) {
92 ALOGI("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object "
93 "ID already in use",
94 objectID, this, object);
95 return mObjects[objectID].object;
96 }
97
98 mObjects.insert({objectID, e});
99 return nullptr;
100 }
101
find(const void * objectID) const102 void* BpBinder::ObjectManager::find(const void* objectID) const
103 {
104 auto i = mObjects.find(objectID);
105 if (i == mObjects.end()) return nullptr;
106 return i->second.object;
107 }
108
detach(const void * objectID)109 void* BpBinder::ObjectManager::detach(const void* objectID) {
110 auto i = mObjects.find(objectID);
111 if (i == mObjects.end()) return nullptr;
112 void* value = i->second.object;
113 mObjects.erase(i);
114 return value;
115 }
116
117 namespace {
118 struct Tag {
119 wp<IBinder> binder;
120 };
121 } // namespace
122
cleanWeak(const void *,void * obj,void *)123 static void cleanWeak(const void* /* id */, void* obj, void* /* cookie */) {
124 delete static_cast<Tag*>(obj);
125 }
126
lookupOrCreateWeak(const void * objectID,object_make_func make,const void * makeArgs)127 sp<IBinder> BpBinder::ObjectManager::lookupOrCreateWeak(const void* objectID, object_make_func make,
128 const void* makeArgs) {
129 entry_t& e = mObjects[objectID];
130 if (e.object != nullptr) {
131 if (auto attached = static_cast<Tag*>(e.object)->binder.promote()) {
132 return attached;
133 }
134 } else {
135 e.object = new Tag;
136 LOG_ALWAYS_FATAL_IF(!e.object, "no more memory");
137 }
138 sp<IBinder> newObj = make(makeArgs);
139
140 static_cast<Tag*>(e.object)->binder = newObj;
141 e.cleanupCookie = nullptr;
142 e.func = cleanWeak;
143
144 return newObj;
145 }
146
kill()147 void BpBinder::ObjectManager::kill()
148 {
149 const size_t N = mObjects.size();
150 ALOGV("Killing %zu objects in manager %p", N, this);
151 for (auto i : mObjects) {
152 const entry_t& e = i.second;
153 if (e.func != nullptr) {
154 e.func(i.first, e.object, e.cleanupCookie);
155 }
156 }
157
158 mObjects.clear();
159 }
160
161 // ---------------------------------------------------------------------------
162
create(int32_t handle)163 sp<BpBinder> BpBinder::create(int32_t handle) {
164 if constexpr (!kEnableKernelIpc) {
165 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
166 return nullptr;
167 }
168
169 int32_t trackedUid = -1;
170 if (sCountByUidEnabled) {
171 trackedUid = IPCThreadState::self()->getCallingUid();
172 RpcMutexUniqueLock _l(sTrackingLock);
173 uint32_t trackedValue = sTrackingMap[trackedUid];
174 if (trackedValue & LIMIT_REACHED_MASK) [[unlikely]] {
175 if (sBinderProxyThrottleCreate) {
176 return nullptr;
177 }
178 trackedValue = trackedValue & COUNTING_VALUE_MASK;
179 uint32_t lastLimitCallbackAt = sLastLimitCallbackMap[trackedUid];
180
181 if (trackedValue > lastLimitCallbackAt &&
182 (trackedValue - lastLimitCallbackAt > sBinderProxyCountHighWatermark)) {
183 ALOGE("Still too many binder proxy objects sent to uid %d from uid %d (%d proxies "
184 "held)",
185 getuid(), trackedUid, trackedValue);
186 if (sLimitCallback) sLimitCallback(trackedUid);
187 sLastLimitCallbackMap[trackedUid] = trackedValue;
188 }
189 } else {
190 uint32_t currentValue = trackedValue & COUNTING_VALUE_MASK;
191 if (currentValue >= sBinderProxyCountWarningWatermark
192 && currentValue < sBinderProxyCountHighWatermark
193 && ((trackedValue & WARNING_REACHED_MASK) == 0)) [[unlikely]] {
194 sTrackingMap[trackedUid] |= WARNING_REACHED_MASK;
195 if (sWarningCallback) sWarningCallback(trackedUid);
196 } else if (currentValue >= sBinderProxyCountHighWatermark) {
197 ALOGE("Too many binder proxy objects sent to uid %d from uid %d (%d proxies held)",
198 getuid(), trackedUid, trackedValue);
199 sTrackingMap[trackedUid] |= LIMIT_REACHED_MASK;
200 if (sLimitCallback) sLimitCallback(trackedUid);
201 sLastLimitCallbackMap[trackedUid] = trackedValue & COUNTING_VALUE_MASK;
202 if (sBinderProxyThrottleCreate) {
203 ALOGI("Throttling binder proxy creates from uid %d in uid %d until binder proxy"
204 " count drops below %d",
205 trackedUid, getuid(), sBinderProxyCountLowWatermark);
206 return nullptr;
207 }
208 }
209 }
210 sTrackingMap[trackedUid]++;
211 }
212 uint32_t numProxies = sBinderProxyCount.fetch_add(1, std::memory_order_relaxed);
213 binder::os::trace_int(ATRACE_TAG_AIDL, "binder_proxies", numProxies);
214 uint32_t numLastWarned = sBinderProxyCountWarned.load(std::memory_order_relaxed);
215 uint32_t numNextWarn = numLastWarned + kBinderProxyCountWarnInterval;
216 if (numProxies >= numNextWarn) {
217 // Multiple threads can get here, make sure only one of them gets to
218 // update the warn counter.
219 if (sBinderProxyCountWarned.compare_exchange_strong(numLastWarned,
220 numNextWarn,
221 std::memory_order_relaxed)) {
222 ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
223 }
224 }
225 return sp<BpBinder>::make(BinderHandle{handle}, trackedUid);
226 }
227
create(const sp<RpcSession> & session,uint64_t address)228 sp<BpBinder> BpBinder::create(const sp<RpcSession>& session, uint64_t address) {
229 LOG_ALWAYS_FATAL_IF(session == nullptr, "BpBinder::create null session");
230
231 // These are not currently tracked, since there is no UID or other
232 // identifier to track them with. However, if similar functionality is
233 // needed, session objects keep track of all BpBinder objects on a
234 // per-session basis.
235
236 return sp<BpBinder>::make(RpcHandle{session, address});
237 }
238
BpBinder(Handle && handle)239 BpBinder::BpBinder(Handle&& handle)
240 : mStability(0),
241 mHandle(handle),
242 mAlive(true),
243 mObitsSent(false),
244 mObituaries(nullptr),
245 mDescriptorCache(kDescriptorUninit),
246 mTrackedUid(-1) {
247 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
248 }
249
BpBinder(BinderHandle && handle,int32_t trackedUid)250 BpBinder::BpBinder(BinderHandle&& handle, int32_t trackedUid) : BpBinder(Handle(handle)) {
251 if constexpr (!kEnableKernelIpc) {
252 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
253 return;
254 }
255
256 mTrackedUid = trackedUid;
257
258 ALOGV("Creating BpBinder %p handle %d\n", this, this->binderHandle());
259
260 IPCThreadState::self()->incWeakHandle(this->binderHandle(), this);
261 }
262
BpBinder(RpcHandle && handle)263 BpBinder::BpBinder(RpcHandle&& handle) : BpBinder(Handle(handle)) {
264 LOG_ALWAYS_FATAL_IF(rpcSession() == nullptr, "BpBinder created w/o session object");
265 }
266
isRpcBinder() const267 bool BpBinder::isRpcBinder() const {
268 return std::holds_alternative<RpcHandle>(mHandle);
269 }
270
rpcAddress() const271 uint64_t BpBinder::rpcAddress() const {
272 return std::get<RpcHandle>(mHandle).address;
273 }
274
rpcSession() const275 const sp<RpcSession>& BpBinder::rpcSession() const {
276 return std::get<RpcHandle>(mHandle).session;
277 }
278
binderHandle() const279 int32_t BpBinder::binderHandle() const {
280 return std::get<BinderHandle>(mHandle).handle;
281 }
282
getDebugBinderHandle() const283 std::optional<int32_t> BpBinder::getDebugBinderHandle() const {
284 if (!isRpcBinder()) {
285 return binderHandle();
286 } else {
287 return std::nullopt;
288 }
289 }
290
isDescriptorCached() const291 bool BpBinder::isDescriptorCached() const {
292 RpcMutexUniqueLock _l(mLock);
293 return mDescriptorCache.c_str() != kDescriptorUninit.c_str();
294 }
295
getInterfaceDescriptor() const296 const String16& BpBinder::getInterfaceDescriptor() const
297 {
298 if (!isDescriptorCached()) {
299 sp<BpBinder> thiz = sp<BpBinder>::fromExisting(const_cast<BpBinder*>(this));
300
301 Parcel data;
302 data.markForBinder(thiz);
303 Parcel reply;
304 // do the IPC without a lock held.
305 status_t err = thiz->transact(INTERFACE_TRANSACTION, data, &reply);
306 if (err == NO_ERROR) {
307 String16 res(reply.readString16());
308 RpcMutexUniqueLock _l(mLock);
309 // mDescriptorCache could have been assigned while the lock was
310 // released.
311 if (mDescriptorCache.c_str() == kDescriptorUninit.c_str()) mDescriptorCache = res;
312 }
313 }
314
315 // we're returning a reference to a non-static object here. Usually this
316 // is not something smart to do, however, with binder objects it is
317 // (usually) safe because they are reference-counted.
318
319 return mDescriptorCache;
320 }
321
isBinderAlive() const322 bool BpBinder::isBinderAlive() const
323 {
324 return mAlive != 0;
325 }
326
pingBinder()327 status_t BpBinder::pingBinder()
328 {
329 Parcel data;
330 data.markForBinder(sp<BpBinder>::fromExisting(this));
331 Parcel reply;
332 return transact(PING_TRANSACTION, data, &reply);
333 }
334
startRecordingBinder(const unique_fd & fd)335 status_t BpBinder::startRecordingBinder(const unique_fd& fd) {
336 Parcel send, reply;
337 send.writeUniqueFileDescriptor(fd);
338 return transact(START_RECORDING_TRANSACTION, send, &reply);
339 }
340
stopRecordingBinder()341 status_t BpBinder::stopRecordingBinder() {
342 Parcel data, reply;
343 data.markForBinder(sp<BpBinder>::fromExisting(this));
344 return transact(STOP_RECORDING_TRANSACTION, data, &reply);
345 }
346
dump(int fd,const Vector<String16> & args)347 status_t BpBinder::dump(int fd, const Vector<String16>& args)
348 {
349 Parcel send;
350 Parcel reply;
351 send.writeFileDescriptor(fd);
352 const size_t numArgs = args.size();
353 send.writeInt32(numArgs);
354 for (size_t i = 0; i < numArgs; i++) {
355 send.writeString16(args[i]);
356 }
357 status_t err = transact(DUMP_TRANSACTION, send, &reply);
358 return err;
359 }
360
361 // NOLINTNEXTLINE(google-default-arguments)
transact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)362 status_t BpBinder::transact(
363 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
364 {
365 // Once a binder has died, it will never come back to life.
366 if (mAlive) {
367 bool privateVendor = flags & FLAG_PRIVATE_VENDOR;
368 // don't send userspace flags to the kernel
369 flags = flags & ~static_cast<uint32_t>(FLAG_PRIVATE_VENDOR);
370
371 // user transactions require a given stability level
372 if (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {
373 using android::internal::Stability;
374
375 int16_t stability = Stability::getRepr(this);
376 Stability::Level required = privateVendor ? Stability::VENDOR
377 : Stability::getLocalLevel();
378
379 if (!Stability::check(stability, required)) [[unlikely]] {
380 ALOGE("Cannot do a user transaction on a %s binder (%s) in a %s context.",
381 Stability::levelString(stability).c_str(),
382 String8(getInterfaceDescriptor()).c_str(),
383 Stability::levelString(required).c_str());
384 return BAD_TYPE;
385 }
386 }
387
388 status_t status;
389 if (isRpcBinder()) [[unlikely]] {
390 status = rpcSession()->transact(sp<IBinder>::fromExisting(this), code, data, reply,
391 flags);
392 } else {
393 if constexpr (!kEnableKernelIpc) {
394 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
395 return INVALID_OPERATION;
396 }
397
398 status = IPCThreadState::self()->transact(binderHandle(), code, data, reply, flags);
399 }
400 if (data.dataSize() > LOG_TRANSACTIONS_OVER_SIZE) {
401 RpcMutexUniqueLock _l(mLock);
402 ALOGW("Large outgoing transaction of %zu bytes, interface descriptor %s, code %d",
403 data.dataSize(), String8(mDescriptorCache).c_str(), code);
404 }
405
406 if (status == DEAD_OBJECT) mAlive = 0;
407
408 return status;
409 }
410
411 return DEAD_OBJECT;
412 }
413
414 // NOLINTNEXTLINE(google-default-arguments)
linkToDeath(const sp<DeathRecipient> & recipient,void * cookie,uint32_t flags)415 status_t BpBinder::linkToDeath(
416 const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
417 {
418 if (isRpcBinder()) {
419 if (rpcSession()->getMaxIncomingThreads() < 1) {
420 ALOGE("Cannot register a DeathRecipient without any incoming threads. Need to set max "
421 "incoming threads to a value greater than 0 before calling linkToDeath.");
422 return INVALID_OPERATION;
423 }
424 } else if constexpr (!kEnableKernelIpc) {
425 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
426 return INVALID_OPERATION;
427 } else {
428 if (ProcessState::self()->getThreadPoolMaxTotalThreadCount() == 0) {
429 ALOGW("Linking to death on %s but there are no threads (yet?) listening to incoming "
430 "transactions. See ProcessState::startThreadPool and "
431 "ProcessState::setThreadPoolMaxThreadCount. Generally you should setup the "
432 "binder "
433 "threadpool before other initialization steps.",
434 String8(getInterfaceDescriptor()).c_str());
435 }
436 }
437
438 Obituary ob;
439 ob.recipient = recipient;
440 ob.cookie = cookie;
441 ob.flags = flags;
442
443 LOG_ALWAYS_FATAL_IF(recipient == nullptr,
444 "linkToDeath(): recipient must be non-NULL");
445
446 {
447 RpcMutexUniqueLock _l(mLock);
448
449 if (!mObitsSent) {
450 if (!mObituaries) {
451 mObituaries = new Vector<Obituary>;
452 if (!mObituaries) {
453 return NO_MEMORY;
454 }
455 ALOGV("Requesting death notification: %p handle %d\n", this, binderHandle());
456 if (!isRpcBinder()) {
457 if constexpr (kEnableKernelIpc) {
458 getWeakRefs()->incWeak(this);
459 IPCThreadState* self = IPCThreadState::self();
460 self->requestDeathNotification(binderHandle(), this);
461 self->flushCommands();
462 }
463 }
464 }
465 ssize_t res = mObituaries->add(ob);
466 return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
467 }
468 }
469
470 return DEAD_OBJECT;
471 }
472
473 // NOLINTNEXTLINE(google-default-arguments)
unlinkToDeath(const wp<DeathRecipient> & recipient,void * cookie,uint32_t flags,wp<DeathRecipient> * outRecipient)474 status_t BpBinder::unlinkToDeath(
475 const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
476 wp<DeathRecipient>* outRecipient)
477 {
478 if (!kEnableKernelIpc && !isRpcBinder()) {
479 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
480 return INVALID_OPERATION;
481 }
482
483 RpcMutexUniqueLock _l(mLock);
484
485 if (mObitsSent) {
486 return DEAD_OBJECT;
487 }
488
489 const size_t N = mObituaries ? mObituaries->size() : 0;
490 for (size_t i=0; i<N; i++) {
491 const Obituary& obit = mObituaries->itemAt(i);
492 if ((obit.recipient == recipient
493 || (recipient == nullptr && obit.cookie == cookie))
494 && obit.flags == flags) {
495 if (outRecipient != nullptr) {
496 *outRecipient = mObituaries->itemAt(i).recipient;
497 }
498 mObituaries->removeAt(i);
499 if (mObituaries->size() == 0) {
500 ALOGV("Clearing death notification: %p handle %d\n", this, binderHandle());
501 if (!isRpcBinder()) {
502 if constexpr (kEnableKernelIpc) {
503 IPCThreadState* self = IPCThreadState::self();
504 self->clearDeathNotification(binderHandle(), this);
505 self->flushCommands();
506 }
507 }
508 delete mObituaries;
509 mObituaries = nullptr;
510 }
511 return NO_ERROR;
512 }
513 }
514
515 return NAME_NOT_FOUND;
516 }
517
sendObituary()518 void BpBinder::sendObituary()
519 {
520 if (!kEnableKernelIpc && !isRpcBinder()) {
521 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
522 return;
523 }
524
525 ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n", this, binderHandle(),
526 mObitsSent ? "true" : "false");
527
528 mAlive = 0;
529 if (mObitsSent) return;
530
531 mLock.lock();
532 Vector<Obituary>* obits = mObituaries;
533 if(obits != nullptr) {
534 ALOGV("Clearing sent death notification: %p handle %d\n", this, binderHandle());
535 if (!isRpcBinder()) {
536 if constexpr (kEnableKernelIpc) {
537 IPCThreadState* self = IPCThreadState::self();
538 self->clearDeathNotification(binderHandle(), this);
539 self->flushCommands();
540 }
541 }
542 mObituaries = nullptr;
543 }
544 mObitsSent = 1;
545 mLock.unlock();
546
547 ALOGV("Reporting death of proxy %p for %zu recipients\n",
548 this, obits ? obits->size() : 0U);
549
550 if (obits != nullptr) {
551 const size_t N = obits->size();
552 for (size_t i=0; i<N; i++) {
553 reportOneDeath(obits->itemAt(i));
554 }
555
556 delete obits;
557 }
558 }
559
reportOneDeath(const Obituary & obit)560 void BpBinder::reportOneDeath(const Obituary& obit)
561 {
562 sp<DeathRecipient> recipient = obit.recipient.promote();
563 ALOGV("Reporting death to recipient: %p\n", recipient.get());
564 if (recipient == nullptr) return;
565
566 recipient->binderDied(wp<BpBinder>::fromExisting(this));
567 }
568
attachObject(const void * objectID,void * object,void * cleanupCookie,object_cleanup_func func)569 void* BpBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
570 object_cleanup_func func) {
571 RpcMutexUniqueLock _l(mLock);
572 ALOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);
573 return mObjects.attach(objectID, object, cleanupCookie, func);
574 }
575
findObject(const void * objectID) const576 void* BpBinder::findObject(const void* objectID) const
577 {
578 RpcMutexUniqueLock _l(mLock);
579 return mObjects.find(objectID);
580 }
581
detachObject(const void * objectID)582 void* BpBinder::detachObject(const void* objectID) {
583 RpcMutexUniqueLock _l(mLock);
584 return mObjects.detach(objectID);
585 }
586
withLock(const std::function<void ()> & doWithLock)587 void BpBinder::withLock(const std::function<void()>& doWithLock) {
588 RpcMutexUniqueLock _l(mLock);
589 doWithLock();
590 }
591
lookupOrCreateWeak(const void * objectID,object_make_func make,const void * makeArgs)592 sp<IBinder> BpBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
593 const void* makeArgs) {
594 RpcMutexUniqueLock _l(mLock);
595 return mObjects.lookupOrCreateWeak(objectID, make, makeArgs);
596 }
597
remoteBinder()598 BpBinder* BpBinder::remoteBinder()
599 {
600 return this;
601 }
602
~BpBinder()603 BpBinder::~BpBinder() {
604 if (isRpcBinder()) [[unlikely]] {
605 return;
606 }
607
608 if constexpr (!kEnableKernelIpc) {
609 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
610 return;
611 }
612
613 ALOGV("Destroying BpBinder %p handle %d\n", this, binderHandle());
614
615 IPCThreadState* ipc = IPCThreadState::self();
616
617 if (mTrackedUid >= 0) {
618 RpcMutexUniqueLock _l(sTrackingLock);
619 uint32_t trackedValue = sTrackingMap[mTrackedUid];
620 if ((trackedValue & COUNTING_VALUE_MASK) == 0) [[unlikely]] {
621 ALOGE("Unexpected Binder Proxy tracking decrement in %p handle %d\n", this,
622 binderHandle());
623 } else {
624 auto countingValue = trackedValue & COUNTING_VALUE_MASK;
625 if ((trackedValue & (LIMIT_REACHED_MASK | WARNING_REACHED_MASK)) &&
626 (countingValue <= sBinderProxyCountLowWatermark)) [[unlikely]] {
627 ALOGI("Limit reached bit reset for uid %d (fewer than %d proxies from uid %d held)",
628 getuid(), sBinderProxyCountLowWatermark, mTrackedUid);
629 sTrackingMap[mTrackedUid] &= ~(LIMIT_REACHED_MASK | WARNING_REACHED_MASK);
630 sLastLimitCallbackMap.erase(mTrackedUid);
631 }
632 if (--sTrackingMap[mTrackedUid] == 0) {
633 sTrackingMap.erase(mTrackedUid);
634 }
635 }
636 }
637 uint32_t numProxies = --sBinderProxyCount;
638 binder::os::trace_int(ATRACE_TAG_AIDL, "binder_proxies", numProxies);
639 if (ipc) {
640 ipc->expungeHandle(binderHandle(), this);
641 ipc->decWeakHandle(binderHandle());
642 }
643 }
644
onFirstRef()645 void BpBinder::onFirstRef() {
646 if (isRpcBinder()) [[unlikely]] {
647 return;
648 }
649
650 if constexpr (!kEnableKernelIpc) {
651 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
652 return;
653 }
654
655 ALOGV("onFirstRef BpBinder %p handle %d\n", this, binderHandle());
656 IPCThreadState* ipc = IPCThreadState::self();
657 if (ipc) ipc->incStrongHandle(binderHandle(), this);
658 }
659
onLastStrongRef(const void *)660 void BpBinder::onLastStrongRef(const void* /*id*/) {
661 if (isRpcBinder()) [[unlikely]] {
662 (void)rpcSession()->sendDecStrong(this);
663 return;
664 }
665
666 if constexpr (!kEnableKernelIpc) {
667 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
668 return;
669 }
670
671 ALOGV("onLastStrongRef BpBinder %p handle %d\n", this, binderHandle());
672 IF_ALOGV() {
673 printRefs();
674 }
675 IPCThreadState* ipc = IPCThreadState::self();
676 if (ipc) ipc->decStrongHandle(binderHandle());
677
678 mLock.lock();
679 Vector<Obituary>* obits = mObituaries;
680 if(obits != nullptr) {
681 if (!obits->isEmpty()) {
682 ALOGI("onLastStrongRef automatically unlinking death recipients: %s",
683 String8(mDescriptorCache).c_str());
684 }
685
686 if (ipc) ipc->clearDeathNotification(binderHandle(), this);
687 mObituaries = nullptr;
688 }
689 mLock.unlock();
690
691 if (obits != nullptr) {
692 // XXX Should we tell any remaining DeathRecipient
693 // objects that the last strong ref has gone away, so they
694 // are no longer linked?
695 delete obits;
696 }
697 }
698
onIncStrongAttempted(uint32_t,const void *)699 bool BpBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
700 {
701 // RPC binder doesn't currently support inc from weak binders
702 if (isRpcBinder()) [[unlikely]] {
703 return false;
704 }
705
706 if constexpr (!kEnableKernelIpc) {
707 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
708 return false;
709 }
710
711 ALOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, binderHandle());
712 IPCThreadState* ipc = IPCThreadState::self();
713 return ipc ? ipc->attemptIncStrongHandle(binderHandle()) == NO_ERROR : false;
714 }
715
getBinderProxyCount(uint32_t uid)716 uint32_t BpBinder::getBinderProxyCount(uint32_t uid)
717 {
718 RpcMutexUniqueLock _l(sTrackingLock);
719 auto it = sTrackingMap.find(uid);
720 if (it != sTrackingMap.end()) {
721 return it->second & COUNTING_VALUE_MASK;
722 }
723 return 0;
724 }
725
getBinderProxyCount()726 uint32_t BpBinder::getBinderProxyCount()
727 {
728 return sBinderProxyCount.load();
729 }
730
getCountByUid(Vector<uint32_t> & uids,Vector<uint32_t> & counts)731 void BpBinder::getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts)
732 {
733 RpcMutexUniqueLock _l(sTrackingLock);
734 uids.setCapacity(sTrackingMap.size());
735 counts.setCapacity(sTrackingMap.size());
736 for (const auto& it : sTrackingMap) {
737 uids.push_back(it.first);
738 counts.push_back(it.second & COUNTING_VALUE_MASK);
739 }
740 }
741
enableCountByUid()742 void BpBinder::enableCountByUid() { sCountByUidEnabled.store(true); }
disableCountByUid()743 void BpBinder::disableCountByUid() { sCountByUidEnabled.store(false); }
setCountByUidEnabled(bool enable)744 void BpBinder::setCountByUidEnabled(bool enable) { sCountByUidEnabled.store(enable); }
745
setBinderProxyCountEventCallback(binder_proxy_limit_callback cbl,binder_proxy_warning_callback cbw)746 void BpBinder::setBinderProxyCountEventCallback(binder_proxy_limit_callback cbl,
747 binder_proxy_warning_callback cbw) {
748 RpcMutexUniqueLock _l(sTrackingLock);
749 sLimitCallback = std::move(cbl);
750 sWarningCallback = std::move(cbw);
751 }
752
setBinderProxyCountWatermarks(int high,int low,int warning)753 void BpBinder::setBinderProxyCountWatermarks(int high, int low, int warning) {
754 RpcMutexUniqueLock _l(sTrackingLock);
755 sBinderProxyCountHighWatermark = high;
756 sBinderProxyCountLowWatermark = low;
757 sBinderProxyCountWarningWatermark = warning;
758 }
759
760 // ---------------------------------------------------------------------------
761
762 } // namespace android
763