xref: /aosp_15_r20/frameworks/native/libs/binder/BpBinder.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
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,std::function<void ()> * postTask)163 sp<BpBinder> BpBinder::create(int32_t handle, std::function<void()>* postTask) {
164     if constexpr (!kEnableKernelIpc) {
165         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
166         return nullptr;
167     }
168     LOG_ALWAYS_FATAL_IF(postTask == nullptr, "BAD STATE");
169 
170     int32_t trackedUid = -1;
171     if (sCountByUidEnabled) {
172         trackedUid = IPCThreadState::self()->getCallingUid();
173         RpcMutexUniqueLock _l(sTrackingLock);
174         uint32_t trackedValue = sTrackingMap[trackedUid];
175         if (trackedValue & LIMIT_REACHED_MASK) [[unlikely]] {
176             if (sBinderProxyThrottleCreate) {
177                 return nullptr;
178             }
179             trackedValue = trackedValue & COUNTING_VALUE_MASK;
180             uint32_t lastLimitCallbackAt = sLastLimitCallbackMap[trackedUid];
181 
182             if (trackedValue > lastLimitCallbackAt &&
183                 (trackedValue - lastLimitCallbackAt > sBinderProxyCountHighWatermark)) {
184                 ALOGE("Still too many binder proxy objects sent to uid %d from uid %d (%d proxies "
185                       "held)",
186                       getuid(), trackedUid, trackedValue);
187 
188                 if (sLimitCallback) {
189                     *postTask = [=]() { sLimitCallback(trackedUid); };
190                 }
191 
192                 sLastLimitCallbackMap[trackedUid] = trackedValue;
193             }
194         } else {
195             uint32_t currentValue = trackedValue & COUNTING_VALUE_MASK;
196             if (currentValue >= sBinderProxyCountWarningWatermark
197                     && currentValue < sBinderProxyCountHighWatermark
198                     && ((trackedValue & WARNING_REACHED_MASK) == 0)) [[unlikely]] {
199                 sTrackingMap[trackedUid] |= WARNING_REACHED_MASK;
200                 if (sWarningCallback) {
201                     *postTask = [=]() { sWarningCallback(trackedUid); };
202                 }
203             } else if (currentValue >= sBinderProxyCountHighWatermark) {
204                 ALOGE("Too many binder proxy objects sent to uid %d from uid %d (%d proxies held)",
205                       getuid(), trackedUid, trackedValue);
206                 sTrackingMap[trackedUid] |= LIMIT_REACHED_MASK;
207 
208                 if (sLimitCallback) {
209                     *postTask = [=]() { sLimitCallback(trackedUid); };
210                 }
211 
212                 sLastLimitCallbackMap[trackedUid] = trackedValue & COUNTING_VALUE_MASK;
213                 if (sBinderProxyThrottleCreate) {
214                     ALOGI("Throttling binder proxy creates from uid %d in uid %d until binder proxy"
215                           " count drops below %d",
216                           trackedUid, getuid(), sBinderProxyCountLowWatermark);
217                     return nullptr;
218                 }
219             }
220         }
221         sTrackingMap[trackedUid]++;
222     }
223     uint32_t numProxies = sBinderProxyCount.fetch_add(1, std::memory_order_relaxed);
224     binder::os::trace_int(ATRACE_TAG_AIDL, "binder_proxies", numProxies);
225     uint32_t numLastWarned = sBinderProxyCountWarned.load(std::memory_order_relaxed);
226     uint32_t numNextWarn = numLastWarned + kBinderProxyCountWarnInterval;
227     if (numProxies >= numNextWarn) {
228         // Multiple threads can get here, make sure only one of them gets to
229         // update the warn counter.
230         if (sBinderProxyCountWarned.compare_exchange_strong(numLastWarned,
231                                                             numNextWarn,
232                                                             std::memory_order_relaxed)) {
233             ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
234         }
235     }
236     return sp<BpBinder>::make(BinderHandle{handle}, trackedUid);
237 }
238 
create(const sp<RpcSession> & session,uint64_t address)239 sp<BpBinder> BpBinder::create(const sp<RpcSession>& session, uint64_t address) {
240     LOG_ALWAYS_FATAL_IF(session == nullptr, "BpBinder::create null session");
241 
242     // These are not currently tracked, since there is no UID or other
243     // identifier to track them with. However, if similar functionality is
244     // needed, session objects keep track of all BpBinder objects on a
245     // per-session basis.
246 
247     return sp<BpBinder>::make(RpcHandle{session, address});
248 }
249 
BpBinder(Handle && handle)250 BpBinder::BpBinder(Handle&& handle)
251       : mStability(0),
252         mHandle(handle),
253         mAlive(true),
254         mObitsSent(false),
255         mObituaries(nullptr),
256         mDescriptorCache(kDescriptorUninit),
257         mTrackedUid(-1) {
258     extendObjectLifetime(OBJECT_LIFETIME_WEAK);
259 }
260 
BpBinder(BinderHandle && handle,int32_t trackedUid)261 BpBinder::BpBinder(BinderHandle&& handle, int32_t trackedUid) : BpBinder(Handle(handle)) {
262     if constexpr (!kEnableKernelIpc) {
263         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
264         return;
265     }
266 
267     mTrackedUid = trackedUid;
268 
269     ALOGV("Creating BpBinder %p handle %d\n", this, this->binderHandle());
270 
271     IPCThreadState::self()->incWeakHandle(this->binderHandle(), this);
272 }
273 
BpBinder(RpcHandle && handle)274 BpBinder::BpBinder(RpcHandle&& handle) : BpBinder(Handle(handle)) {
275     LOG_ALWAYS_FATAL_IF(rpcSession() == nullptr, "BpBinder created w/o session object");
276 }
277 
isRpcBinder() const278 bool BpBinder::isRpcBinder() const {
279     return std::holds_alternative<RpcHandle>(mHandle);
280 }
281 
rpcAddress() const282 uint64_t BpBinder::rpcAddress() const {
283     return std::get<RpcHandle>(mHandle).address;
284 }
285 
rpcSession() const286 const sp<RpcSession>& BpBinder::rpcSession() const {
287     return std::get<RpcHandle>(mHandle).session;
288 }
289 
binderHandle() const290 int32_t BpBinder::binderHandle() const {
291     return std::get<BinderHandle>(mHandle).handle;
292 }
293 
getDebugBinderHandle() const294 std::optional<int32_t> BpBinder::getDebugBinderHandle() const {
295     if (!isRpcBinder()) {
296         return binderHandle();
297     } else {
298         return std::nullopt;
299     }
300 }
301 
isDescriptorCached() const302 bool BpBinder::isDescriptorCached() const {
303     RpcMutexUniqueLock _l(mLock);
304     return mDescriptorCache.c_str() != kDescriptorUninit.c_str();
305 }
306 
getInterfaceDescriptor() const307 const String16& BpBinder::getInterfaceDescriptor() const
308 {
309     if (!isDescriptorCached()) {
310         sp<BpBinder> thiz = sp<BpBinder>::fromExisting(const_cast<BpBinder*>(this));
311 
312         Parcel data;
313         data.markForBinder(thiz);
314         Parcel reply;
315         // do the IPC without a lock held.
316         status_t err = thiz->transact(INTERFACE_TRANSACTION, data, &reply);
317         if (err == NO_ERROR) {
318             String16 res(reply.readString16());
319             RpcMutexUniqueLock _l(mLock);
320             // mDescriptorCache could have been assigned while the lock was
321             // released.
322             if (mDescriptorCache.c_str() == kDescriptorUninit.c_str()) mDescriptorCache = res;
323         }
324     }
325 
326     // we're returning a reference to a non-static object here. Usually this
327     // is not something smart to do, however, with binder objects it is
328     // (usually) safe because they are reference-counted.
329 
330     return mDescriptorCache;
331 }
332 
isBinderAlive() const333 bool BpBinder::isBinderAlive() const
334 {
335     return mAlive != 0;
336 }
337 
pingBinder()338 status_t BpBinder::pingBinder()
339 {
340     Parcel data;
341     data.markForBinder(sp<BpBinder>::fromExisting(this));
342     Parcel reply;
343     return transact(PING_TRANSACTION, data, &reply);
344 }
345 
startRecordingBinder(const unique_fd & fd)346 status_t BpBinder::startRecordingBinder(const unique_fd& fd) {
347     Parcel send, reply;
348     send.writeUniqueFileDescriptor(fd);
349     return transact(START_RECORDING_TRANSACTION, send, &reply);
350 }
351 
stopRecordingBinder()352 status_t BpBinder::stopRecordingBinder() {
353     Parcel data, reply;
354     data.markForBinder(sp<BpBinder>::fromExisting(this));
355     return transact(STOP_RECORDING_TRANSACTION, data, &reply);
356 }
357 
dump(int fd,const Vector<String16> & args)358 status_t BpBinder::dump(int fd, const Vector<String16>& args)
359 {
360     Parcel send;
361     Parcel reply;
362     send.writeFileDescriptor(fd);
363     const size_t numArgs = args.size();
364     send.writeInt32(numArgs);
365     for (size_t i = 0; i < numArgs; i++) {
366         send.writeString16(args[i]);
367     }
368     status_t err = transact(DUMP_TRANSACTION, send, &reply);
369     return err;
370 }
371 
372 // NOLINTNEXTLINE(google-default-arguments)
transact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)373 status_t BpBinder::transact(
374     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
375 {
376     // Once a binder has died, it will never come back to life.
377     if (mAlive) {
378         bool privateVendor = flags & FLAG_PRIVATE_VENDOR;
379         // don't send userspace flags to the kernel
380         flags = flags & ~static_cast<uint32_t>(FLAG_PRIVATE_VENDOR);
381 
382         // user transactions require a given stability level
383         if (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {
384             using android::internal::Stability;
385 
386             int16_t stability = Stability::getRepr(this);
387             Stability::Level required = privateVendor ? Stability::VENDOR
388                 : Stability::getLocalLevel();
389 
390             if (!Stability::check(stability, required)) [[unlikely]] {
391                 ALOGE("Cannot do a user transaction on a %s binder (%s) in a %s context.",
392                       Stability::levelString(stability).c_str(),
393                       String8(getInterfaceDescriptor()).c_str(),
394                       Stability::levelString(required).c_str());
395                 return BAD_TYPE;
396             }
397         }
398 
399         status_t status;
400         if (isRpcBinder()) [[unlikely]] {
401             status = rpcSession()->transact(sp<IBinder>::fromExisting(this), code, data, reply,
402                                             flags);
403         } else {
404             if constexpr (!kEnableKernelIpc) {
405                 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
406                 return INVALID_OPERATION;
407             }
408 
409             status = IPCThreadState::self()->transact(binderHandle(), code, data, reply, flags);
410         }
411         if (data.dataSize() > LOG_TRANSACTIONS_OVER_SIZE) {
412             RpcMutexUniqueLock _l(mLock);
413             ALOGW("Large outgoing transaction of %zu bytes, interface descriptor %s, code %d",
414                   data.dataSize(), String8(mDescriptorCache).c_str(), code);
415         }
416 
417         if (status == DEAD_OBJECT) mAlive = 0;
418 
419         return status;
420     }
421 
422     return DEAD_OBJECT;
423 }
424 
425 // NOLINTNEXTLINE(google-default-arguments)
linkToDeath(const sp<DeathRecipient> & recipient,void * cookie,uint32_t flags)426 status_t BpBinder::linkToDeath(
427     const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
428 {
429     if (isRpcBinder()) {
430         if (rpcSession()->getMaxIncomingThreads() < 1) {
431             ALOGE("Cannot register a DeathRecipient without any incoming threads. Need to set max "
432                   "incoming threads to a value greater than 0 before calling linkToDeath.");
433             return INVALID_OPERATION;
434         }
435     } else if constexpr (!kEnableKernelIpc) {
436         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
437         return INVALID_OPERATION;
438     } else {
439         if (ProcessState::self()->getThreadPoolMaxTotalThreadCount() == 0) {
440             ALOGW("Linking to death on %s but there are no threads (yet?) listening to incoming "
441                   "transactions. See ProcessState::startThreadPool and "
442                   "ProcessState::setThreadPoolMaxThreadCount. Generally you should setup the "
443                   "binder "
444                   "threadpool before other initialization steps.",
445                   String8(getInterfaceDescriptor()).c_str());
446         }
447     }
448 
449     Obituary ob;
450     ob.recipient = recipient;
451     ob.cookie = cookie;
452     ob.flags = flags;
453 
454     LOG_ALWAYS_FATAL_IF(recipient == nullptr,
455                         "linkToDeath(): recipient must be non-NULL");
456 
457     {
458         RpcMutexUniqueLock _l(mLock);
459 
460         if (!mObitsSent) {
461             if (!mObituaries) {
462                 mObituaries = new Vector<Obituary>;
463                 if (!mObituaries) {
464                     return NO_MEMORY;
465                 }
466                 ALOGV("Requesting death notification: %p handle %d\n", this, binderHandle());
467                 if (!isRpcBinder()) {
468                     if constexpr (kEnableKernelIpc) {
469                         getWeakRefs()->incWeak(this);
470                         IPCThreadState* self = IPCThreadState::self();
471                         self->requestDeathNotification(binderHandle(), this);
472                         self->flushCommands();
473                     }
474                 }
475             }
476             ssize_t res = mObituaries->add(ob);
477             return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
478         }
479     }
480 
481     return DEAD_OBJECT;
482 }
483 
484 // NOLINTNEXTLINE(google-default-arguments)
unlinkToDeath(const wp<DeathRecipient> & recipient,void * cookie,uint32_t flags,wp<DeathRecipient> * outRecipient)485 status_t BpBinder::unlinkToDeath(
486     const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
487     wp<DeathRecipient>* outRecipient)
488 {
489     if (!kEnableKernelIpc && !isRpcBinder()) {
490         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
491         return INVALID_OPERATION;
492     }
493 
494     RpcMutexUniqueLock _l(mLock);
495 
496     if (mObitsSent) {
497         return DEAD_OBJECT;
498     }
499 
500     const size_t N = mObituaries ? mObituaries->size() : 0;
501     for (size_t i=0; i<N; i++) {
502         const Obituary& obit = mObituaries->itemAt(i);
503         if ((obit.recipient == recipient
504                     || (recipient == nullptr && obit.cookie == cookie))
505                 && obit.flags == flags) {
506             if (outRecipient != nullptr) {
507                 *outRecipient = mObituaries->itemAt(i).recipient;
508             }
509             mObituaries->removeAt(i);
510             if (mObituaries->size() == 0) {
511                 ALOGV("Clearing death notification: %p handle %d\n", this, binderHandle());
512                 if (!isRpcBinder()) {
513                     if constexpr (kEnableKernelIpc) {
514                         IPCThreadState* self = IPCThreadState::self();
515                         self->clearDeathNotification(binderHandle(), this);
516                         self->flushCommands();
517                     }
518                 }
519                 delete mObituaries;
520                 mObituaries = nullptr;
521             }
522             return NO_ERROR;
523         }
524     }
525 
526     return NAME_NOT_FOUND;
527 }
528 
sendObituary()529 void BpBinder::sendObituary()
530 {
531     if (!kEnableKernelIpc && !isRpcBinder()) {
532         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
533         return;
534     }
535 
536     ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n", this, binderHandle(),
537           mObitsSent ? "true" : "false");
538 
539     mAlive = 0;
540     if (mObitsSent) return;
541 
542     mLock.lock();
543     Vector<Obituary>* obits = mObituaries;
544     if(obits != nullptr) {
545         ALOGV("Clearing sent death notification: %p handle %d\n", this, binderHandle());
546         if (!isRpcBinder()) {
547             if constexpr (kEnableKernelIpc) {
548                 IPCThreadState* self = IPCThreadState::self();
549                 self->clearDeathNotification(binderHandle(), this);
550                 self->flushCommands();
551             }
552         }
553         mObituaries = nullptr;
554     }
555     mObitsSent = 1;
556     mLock.unlock();
557 
558     ALOGV("Reporting death of proxy %p for %zu recipients\n",
559         this, obits ? obits->size() : 0U);
560 
561     if (obits != nullptr) {
562         const size_t N = obits->size();
563         for (size_t i=0; i<N; i++) {
564             reportOneDeath(obits->itemAt(i));
565         }
566 
567         delete obits;
568     }
569 }
570 
addFrozenStateChangeCallback(const wp<FrozenStateChangeCallback> & callback)571 status_t BpBinder::addFrozenStateChangeCallback(const wp<FrozenStateChangeCallback>& callback) {
572     LOG_ALWAYS_FATAL_IF(isRpcBinder(),
573                         "addFrozenStateChangeCallback() is not supported for RPC Binder.");
574     LOG_ALWAYS_FATAL_IF(!kEnableKernelIpc, "Binder kernel driver disabled at build time");
575     LOG_ALWAYS_FATAL_IF(ProcessState::self()->getThreadPoolMaxTotalThreadCount() == 0,
576                         "addFrozenStateChangeCallback on %s but there are no threads "
577                         "(yet?) listening to incoming transactions. See "
578                         "ProcessState::startThreadPool "
579                         "and ProcessState::setThreadPoolMaxThreadCount. Generally you should "
580                         "setup the binder threadpool before other initialization steps.",
581                         String8(getInterfaceDescriptor()).c_str());
582     LOG_ALWAYS_FATAL_IF(callback == nullptr,
583                         "addFrozenStateChangeCallback(): callback must be non-NULL");
584 
585     const sp<FrozenStateChangeCallback> strongCallback = callback.promote();
586     if (strongCallback == nullptr) {
587         return BAD_VALUE;
588     }
589 
590     {
591         RpcMutexUniqueLock _l(mLock);
592         if (!mFrozen) {
593             ALOGV("Requesting freeze notification: %p handle %d\n", this, binderHandle());
594             IPCThreadState* self = IPCThreadState::self();
595             status_t status = self->addFrozenStateChangeCallback(binderHandle(), this);
596             if (status != NO_ERROR) {
597                 // Avoids logspam if kernel does not support freeze
598                 // notification.
599                 if (status != INVALID_OPERATION) {
600                     ALOGE("IPCThreadState.addFrozenStateChangeCallback "
601                           "failed with %s. %p handle %d\n",
602                           statusToString(status).c_str(), this, binderHandle());
603                 }
604                 return status;
605             }
606             mFrozen = std::make_unique<FrozenStateChange>();
607             if (!mFrozen) {
608                 std::ignore =
609                         IPCThreadState::self()->removeFrozenStateChangeCallback(binderHandle(),
610                                                                                 this);
611                 return NO_MEMORY;
612             }
613         }
614         if (mFrozen->initialStateReceived) {
615             strongCallback->onStateChanged(wp<BpBinder>::fromExisting(this),
616                                            mFrozen->isFrozen
617                                                    ? FrozenStateChangeCallback::State::FROZEN
618                                                    : FrozenStateChangeCallback::State::UNFROZEN);
619         }
620         ssize_t res = mFrozen->callbacks.add(callback);
621         if (res < 0) {
622             return res;
623         }
624         return NO_ERROR;
625     }
626 }
627 
removeFrozenStateChangeCallback(const wp<FrozenStateChangeCallback> & callback)628 status_t BpBinder::removeFrozenStateChangeCallback(const wp<FrozenStateChangeCallback>& callback) {
629     LOG_ALWAYS_FATAL_IF(isRpcBinder(),
630                         "removeFrozenStateChangeCallback() is not supported for RPC Binder.");
631     LOG_ALWAYS_FATAL_IF(!kEnableKernelIpc, "Binder kernel driver disabled at build time");
632 
633     RpcMutexUniqueLock _l(mLock);
634 
635     const size_t N = mFrozen ? mFrozen->callbacks.size() : 0;
636     for (size_t i = 0; i < N; i++) {
637         if (mFrozen->callbacks.itemAt(i) == callback) {
638             mFrozen->callbacks.removeAt(i);
639             if (mFrozen->callbacks.size() == 0) {
640                 ALOGV("Clearing freeze notification: %p handle %d\n", this, binderHandle());
641                 status_t status =
642                         IPCThreadState::self()->removeFrozenStateChangeCallback(binderHandle(),
643                                                                                 this);
644                 if (status != NO_ERROR) {
645                     ALOGE("Unexpected error from "
646                           "IPCThreadState.removeFrozenStateChangeCallback: %s. "
647                           "%p handle %d\n",
648                           statusToString(status).c_str(), this, binderHandle());
649                 }
650                 mFrozen.reset();
651             }
652             return NO_ERROR;
653         }
654     }
655 
656     return NAME_NOT_FOUND;
657 }
658 
onFrozenStateChanged(bool isFrozen)659 void BpBinder::onFrozenStateChanged(bool isFrozen) {
660     LOG_ALWAYS_FATAL_IF(isRpcBinder(), "onFrozenStateChanged is not supported for RPC Binder.");
661     LOG_ALWAYS_FATAL_IF(!kEnableKernelIpc, "Binder kernel driver disabled at build time");
662 
663     ALOGV("Sending frozen state change notification for proxy %p handle %d, isFrozen=%s\n", this,
664           binderHandle(), isFrozen ? "true" : "false");
665 
666     RpcMutexUniqueLock _l(mLock);
667     if (!mFrozen) {
668         return;
669     }
670     bool stateChanged = !mFrozen->initialStateReceived || mFrozen->isFrozen != isFrozen;
671     if (stateChanged) {
672         mFrozen->isFrozen = isFrozen;
673         mFrozen->initialStateReceived = true;
674         for (size_t i = 0; i < mFrozen->callbacks.size();) {
675             sp<FrozenStateChangeCallback> callback = mFrozen->callbacks.itemAt(i).promote();
676             if (callback != nullptr) {
677                 callback->onStateChanged(wp<BpBinder>::fromExisting(this),
678                                          isFrozen ? FrozenStateChangeCallback::State::FROZEN
679                                                   : FrozenStateChangeCallback::State::UNFROZEN);
680                 i++;
681             } else {
682                 mFrozen->callbacks.removeItemsAt(i);
683             }
684         }
685     }
686 }
687 
reportOneDeath(const Obituary & obit)688 void BpBinder::reportOneDeath(const Obituary& obit)
689 {
690     sp<DeathRecipient> recipient = obit.recipient.promote();
691     ALOGV("Reporting death to recipient: %p\n", recipient.get());
692     if (recipient == nullptr) return;
693 
694     recipient->binderDied(wp<BpBinder>::fromExisting(this));
695 }
696 
attachObject(const void * objectID,void * object,void * cleanupCookie,object_cleanup_func func)697 void* BpBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
698                              object_cleanup_func func) {
699     RpcMutexUniqueLock _l(mLock);
700     ALOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);
701     return mObjects.attach(objectID, object, cleanupCookie, func);
702 }
703 
findObject(const void * objectID) const704 void* BpBinder::findObject(const void* objectID) const
705 {
706     RpcMutexUniqueLock _l(mLock);
707     return mObjects.find(objectID);
708 }
709 
detachObject(const void * objectID)710 void* BpBinder::detachObject(const void* objectID) {
711     RpcMutexUniqueLock _l(mLock);
712     return mObjects.detach(objectID);
713 }
714 
withLock(const std::function<void ()> & doWithLock)715 void BpBinder::withLock(const std::function<void()>& doWithLock) {
716     RpcMutexUniqueLock _l(mLock);
717     doWithLock();
718 }
719 
lookupOrCreateWeak(const void * objectID,object_make_func make,const void * makeArgs)720 sp<IBinder> BpBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
721                                          const void* makeArgs) {
722     RpcMutexUniqueLock _l(mLock);
723     return mObjects.lookupOrCreateWeak(objectID, make, makeArgs);
724 }
725 
remoteBinder()726 BpBinder* BpBinder::remoteBinder()
727 {
728     return this;
729 }
730 
~BpBinder()731 BpBinder::~BpBinder() {
732     if (isRpcBinder()) [[unlikely]] {
733         return;
734     }
735 
736     if constexpr (!kEnableKernelIpc) {
737         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
738         return;
739     }
740 
741     ALOGV("Destroying BpBinder %p handle %d\n", this, binderHandle());
742 
743     IPCThreadState* ipc = IPCThreadState::self();
744 
745     if (mTrackedUid >= 0) {
746         RpcMutexUniqueLock _l(sTrackingLock);
747         uint32_t trackedValue = sTrackingMap[mTrackedUid];
748         if ((trackedValue & COUNTING_VALUE_MASK) == 0) [[unlikely]] {
749             ALOGE("Unexpected Binder Proxy tracking decrement in %p handle %d\n", this,
750                   binderHandle());
751         } else {
752             auto countingValue = trackedValue & COUNTING_VALUE_MASK;
753             if ((trackedValue & (LIMIT_REACHED_MASK | WARNING_REACHED_MASK)) &&
754                 (countingValue <= sBinderProxyCountLowWatermark)) [[unlikely]] {
755                 ALOGI("Limit reached bit reset for uid %d (fewer than %d proxies from uid %d held)",
756                       getuid(), sBinderProxyCountLowWatermark, mTrackedUid);
757                 sTrackingMap[mTrackedUid] &= ~(LIMIT_REACHED_MASK | WARNING_REACHED_MASK);
758                 sLastLimitCallbackMap.erase(mTrackedUid);
759             }
760             if (--sTrackingMap[mTrackedUid] == 0) {
761                 sTrackingMap.erase(mTrackedUid);
762             }
763         }
764     }
765     uint32_t numProxies = --sBinderProxyCount;
766     binder::os::trace_int(ATRACE_TAG_AIDL, "binder_proxies", numProxies);
767     if (ipc) {
768         ipc->expungeHandle(binderHandle(), this);
769         ipc->decWeakHandle(binderHandle());
770     }
771 }
772 
onFirstRef()773 void BpBinder::onFirstRef() {
774     if (isRpcBinder()) [[unlikely]] {
775         return;
776     }
777 
778     if constexpr (!kEnableKernelIpc) {
779         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
780         return;
781     }
782 
783     ALOGV("onFirstRef BpBinder %p handle %d\n", this, binderHandle());
784     IPCThreadState* ipc = IPCThreadState::self();
785     if (ipc) ipc->incStrongHandle(binderHandle(), this);
786 }
787 
onLastStrongRef(const void *)788 void BpBinder::onLastStrongRef(const void* /*id*/) {
789     if (isRpcBinder()) [[unlikely]] {
790         (void)rpcSession()->sendDecStrong(this);
791         return;
792     }
793 
794     if constexpr (!kEnableKernelIpc) {
795         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
796         return;
797     }
798 
799     ALOGV("onLastStrongRef BpBinder %p handle %d\n", this, binderHandle());
800     IF_ALOGV() {
801         printRefs();
802     }
803     IPCThreadState* ipc = IPCThreadState::self();
804     if (ipc) ipc->decStrongHandle(binderHandle());
805 
806     mLock.lock();
807     Vector<Obituary>* obits = mObituaries;
808     if(obits != nullptr) {
809         if (!obits->isEmpty()) {
810             ALOGI("onLastStrongRef automatically unlinking death recipients: %s",
811                   String8(mDescriptorCache).c_str());
812         }
813 
814         if (ipc) ipc->clearDeathNotification(binderHandle(), this);
815         mObituaries = nullptr;
816     }
817     if (mFrozen != nullptr) {
818         std::ignore = IPCThreadState::self()->removeFrozenStateChangeCallback(binderHandle(), this);
819         mFrozen.reset();
820     }
821     mLock.unlock();
822 
823     if (obits != nullptr) {
824         // XXX Should we tell any remaining DeathRecipient
825         // objects that the last strong ref has gone away, so they
826         // are no longer linked?
827         delete obits;
828     }
829 }
830 
onIncStrongAttempted(uint32_t,const void *)831 bool BpBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
832 {
833     // RPC binder doesn't currently support inc from weak binders
834     if (isRpcBinder()) [[unlikely]] {
835         return false;
836     }
837 
838     if constexpr (!kEnableKernelIpc) {
839         LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
840         return false;
841     }
842 
843     ALOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, binderHandle());
844     IPCThreadState* ipc = IPCThreadState::self();
845     return ipc ? ipc->attemptIncStrongHandle(binderHandle()) == NO_ERROR : false;
846 }
847 
getBinderProxyCount(uint32_t uid)848 uint32_t BpBinder::getBinderProxyCount(uint32_t uid)
849 {
850     RpcMutexUniqueLock _l(sTrackingLock);
851     auto it = sTrackingMap.find(uid);
852     if (it != sTrackingMap.end()) {
853         return it->second & COUNTING_VALUE_MASK;
854     }
855     return 0;
856 }
857 
getBinderProxyCount()858 uint32_t BpBinder::getBinderProxyCount()
859 {
860     return sBinderProxyCount.load();
861 }
862 
getCountByUid(Vector<uint32_t> & uids,Vector<uint32_t> & counts)863 void BpBinder::getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts)
864 {
865     RpcMutexUniqueLock _l(sTrackingLock);
866     uids.setCapacity(sTrackingMap.size());
867     counts.setCapacity(sTrackingMap.size());
868     for (const auto& it : sTrackingMap) {
869         uids.push_back(it.first);
870         counts.push_back(it.second & COUNTING_VALUE_MASK);
871     }
872 }
873 
enableCountByUid()874 void BpBinder::enableCountByUid() { sCountByUidEnabled.store(true); }
disableCountByUid()875 void BpBinder::disableCountByUid() { sCountByUidEnabled.store(false); }
setCountByUidEnabled(bool enable)876 void BpBinder::setCountByUidEnabled(bool enable) { sCountByUidEnabled.store(enable); }
877 
setBinderProxyCountEventCallback(binder_proxy_limit_callback cbl,binder_proxy_warning_callback cbw)878 void BpBinder::setBinderProxyCountEventCallback(binder_proxy_limit_callback cbl,
879                                                 binder_proxy_warning_callback cbw) {
880     RpcMutexUniqueLock _l(sTrackingLock);
881     sLimitCallback = std::move(cbl);
882     sWarningCallback = std::move(cbw);
883 }
884 
setBinderProxyCountWatermarks(int high,int low,int warning)885 void BpBinder::setBinderProxyCountWatermarks(int high, int low, int warning) {
886     RpcMutexUniqueLock _l(sTrackingLock);
887     sBinderProxyCountHighWatermark = high;
888     sBinderProxyCountLowWatermark = low;
889     sBinderProxyCountWarningWatermark = warning;
890 }
891 
892 // ---------------------------------------------------------------------------
893 
894 } // namespace android
895