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