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 <cutils/compiler.h>
27 #include <utils/Log.h>
28
29 #include <stdio.h>
30
31 //#undef ALOGV
32 //#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
33
34 namespace android {
35
36 // ---------------------------------------------------------------------------
37
38 Mutex BpBinder::sTrackingLock;
39 std::unordered_map<int32_t, uint32_t> BpBinder::sTrackingMap;
40 std::unordered_map<int32_t, uint32_t> BpBinder::sLastLimitCallbackMap;
41 int BpBinder::sNumTrackedUids = 0;
42 std::atomic_bool BpBinder::sCountByUidEnabled(false);
43 binder_proxy_limit_callback BpBinder::sLimitCallback;
44 bool BpBinder::sBinderProxyThrottleCreate = false;
45
46 // Arbitrarily high value that probably distinguishes a bad behaving app
47 uint32_t BpBinder::sBinderProxyCountHighWatermark = 2500;
48 // Another arbitrary value a binder count needs to drop below before another callback will be called
49 uint32_t BpBinder::sBinderProxyCountLowWatermark = 2000;
50
51 // Log any transactions for which the data exceeds this size
52 #define LOG_TRANSACTIONS_OVER_SIZE (300 * 1024)
53
54 enum {
55 LIMIT_REACHED_MASK = 0x80000000, // A flag denoting that the limit has been reached
56 COUNTING_VALUE_MASK = 0x7FFFFFFF, // A mask of the remaining bits for the count value
57 };
58
ObjectManager()59 BpBinder::ObjectManager::ObjectManager()
60 {
61 }
62
~ObjectManager()63 BpBinder::ObjectManager::~ObjectManager()
64 {
65 kill();
66 }
67
attach(const void * objectID,void * object,void * cleanupCookie,IBinder::object_cleanup_func func)68 void* BpBinder::ObjectManager::attach(const void* objectID, void* object, void* cleanupCookie,
69 IBinder::object_cleanup_func func) {
70 entry_t e;
71 e.object = object;
72 e.cleanupCookie = cleanupCookie;
73 e.func = func;
74
75 if (mObjects.find(objectID) != mObjects.end()) {
76 ALOGI("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object "
77 "ID already in use",
78 objectID, this, object);
79 return mObjects[objectID].object;
80 }
81
82 mObjects.insert({objectID, e});
83 return nullptr;
84 }
85
find(const void * objectID) const86 void* BpBinder::ObjectManager::find(const void* objectID) const
87 {
88 auto i = mObjects.find(objectID);
89 if (i == mObjects.end()) return nullptr;
90 return i->second.object;
91 }
92
detach(const void * objectID)93 void* BpBinder::ObjectManager::detach(const void* objectID) {
94 auto i = mObjects.find(objectID);
95 if (i == mObjects.end()) return nullptr;
96 void* value = i->second.object;
97 mObjects.erase(i);
98 return value;
99 }
100
kill()101 void BpBinder::ObjectManager::kill()
102 {
103 const size_t N = mObjects.size();
104 ALOGV("Killing %zu objects in manager %p", N, this);
105 for (auto i : mObjects) {
106 const entry_t& e = i.second;
107 if (e.func != nullptr) {
108 e.func(i.first, e.object, e.cleanupCookie);
109 }
110 }
111
112 mObjects.clear();
113 }
114
115 // ---------------------------------------------------------------------------
116
create(int32_t handle)117 sp<BpBinder> BpBinder::create(int32_t handle) {
118 int32_t trackedUid = -1;
119 if (sCountByUidEnabled) {
120 trackedUid = IPCThreadState::self()->getCallingUid();
121 AutoMutex _l(sTrackingLock);
122 uint32_t trackedValue = sTrackingMap[trackedUid];
123 if (CC_UNLIKELY(trackedValue & LIMIT_REACHED_MASK)) {
124 if (sBinderProxyThrottleCreate) {
125 return nullptr;
126 }
127 trackedValue = trackedValue & COUNTING_VALUE_MASK;
128 uint32_t lastLimitCallbackAt = sLastLimitCallbackMap[trackedUid];
129
130 if (trackedValue > lastLimitCallbackAt &&
131 (trackedValue - lastLimitCallbackAt > sBinderProxyCountHighWatermark)) {
132 ALOGE("Still too many binder proxy objects sent to uid %d from uid %d (%d proxies "
133 "held)",
134 getuid(), trackedUid, trackedValue);
135 if (sLimitCallback) sLimitCallback(trackedUid);
136 sLastLimitCallbackMap[trackedUid] = trackedValue;
137 }
138 } else {
139 if ((trackedValue & COUNTING_VALUE_MASK) >= sBinderProxyCountHighWatermark) {
140 ALOGE("Too many binder proxy objects sent to uid %d from uid %d (%d proxies held)",
141 getuid(), trackedUid, trackedValue);
142 sTrackingMap[trackedUid] |= LIMIT_REACHED_MASK;
143 if (sLimitCallback) sLimitCallback(trackedUid);
144 sLastLimitCallbackMap[trackedUid] = trackedValue & COUNTING_VALUE_MASK;
145 if (sBinderProxyThrottleCreate) {
146 ALOGI("Throttling binder proxy creates from uid %d in uid %d until binder proxy"
147 " count drops below %d",
148 trackedUid, getuid(), sBinderProxyCountLowWatermark);
149 return nullptr;
150 }
151 }
152 }
153 sTrackingMap[trackedUid]++;
154 }
155 return sp<BpBinder>::make(BinderHandle{handle}, trackedUid);
156 }
157
create(const sp<RpcSession> & session,uint64_t address)158 sp<BpBinder> BpBinder::create(const sp<RpcSession>& session, uint64_t address) {
159 LOG_ALWAYS_FATAL_IF(session == nullptr, "BpBinder::create null session");
160
161 // These are not currently tracked, since there is no UID or other
162 // identifier to track them with. However, if similar functionality is
163 // needed, session objects keep track of all BpBinder objects on a
164 // per-session basis.
165
166 return sp<BpBinder>::make(RpcHandle{session, address});
167 }
168
BpBinder(Handle && handle)169 BpBinder::BpBinder(Handle&& handle)
170 : mStability(0),
171 mHandle(handle),
172 mAlive(true),
173 mObitsSent(false),
174 mObituaries(nullptr),
175 mTrackedUid(-1) {
176 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
177 }
178
BpBinder(BinderHandle && handle,int32_t trackedUid)179 BpBinder::BpBinder(BinderHandle&& handle, int32_t trackedUid) : BpBinder(Handle(handle)) {
180 mTrackedUid = trackedUid;
181
182 ALOGV("Creating BpBinder %p handle %d\n", this, this->binderHandle());
183
184 IPCThreadState::self()->incWeakHandle(this->binderHandle(), this);
185 }
186
BpBinder(RpcHandle && handle)187 BpBinder::BpBinder(RpcHandle&& handle) : BpBinder(Handle(handle)) {
188 LOG_ALWAYS_FATAL_IF(rpcSession() == nullptr, "BpBinder created w/o session object");
189 }
190
isRpcBinder() const191 bool BpBinder::isRpcBinder() const {
192 return std::holds_alternative<RpcHandle>(mHandle);
193 }
194
rpcAddress() const195 uint64_t BpBinder::rpcAddress() const {
196 return std::get<RpcHandle>(mHandle).address;
197 }
198
rpcSession() const199 const sp<RpcSession>& BpBinder::rpcSession() const {
200 return std::get<RpcHandle>(mHandle).session;
201 }
202
binderHandle() const203 int32_t BpBinder::binderHandle() const {
204 return std::get<BinderHandle>(mHandle).handle;
205 }
206
getDebugBinderHandle() const207 std::optional<int32_t> BpBinder::getDebugBinderHandle() const {
208 if (!isRpcBinder()) {
209 return binderHandle();
210 } else {
211 return std::nullopt;
212 }
213 }
214
isDescriptorCached() const215 bool BpBinder::isDescriptorCached() const {
216 Mutex::Autolock _l(mLock);
217 return mDescriptorCache.size() ? true : false;
218 }
219
getInterfaceDescriptor() const220 const String16& BpBinder::getInterfaceDescriptor() const
221 {
222 if (isDescriptorCached() == false) {
223 sp<BpBinder> thiz = sp<BpBinder>::fromExisting(const_cast<BpBinder*>(this));
224
225 Parcel data;
226 data.markForBinder(thiz);
227 Parcel reply;
228 // do the IPC without a lock held.
229 status_t err = thiz->transact(INTERFACE_TRANSACTION, data, &reply);
230 if (err == NO_ERROR) {
231 String16 res(reply.readString16());
232 Mutex::Autolock _l(mLock);
233 // mDescriptorCache could have been assigned while the lock was
234 // released.
235 if (mDescriptorCache.size() == 0)
236 mDescriptorCache = res;
237 }
238 }
239
240 // we're returning a reference to a non-static object here. Usually this
241 // is not something smart to do, however, with binder objects it is
242 // (usually) safe because they are reference-counted.
243
244 return mDescriptorCache;
245 }
246
isBinderAlive() const247 bool BpBinder::isBinderAlive() const
248 {
249 return mAlive != 0;
250 }
251
pingBinder()252 status_t BpBinder::pingBinder()
253 {
254 Parcel data;
255 data.markForBinder(sp<BpBinder>::fromExisting(this));
256 Parcel reply;
257 return transact(PING_TRANSACTION, data, &reply);
258 }
259
dump(int fd,const Vector<String16> & args)260 status_t BpBinder::dump(int fd, const Vector<String16>& args)
261 {
262 Parcel send;
263 Parcel reply;
264 send.writeFileDescriptor(fd);
265 const size_t numArgs = args.size();
266 send.writeInt32(numArgs);
267 for (size_t i = 0; i < numArgs; i++) {
268 send.writeString16(args[i]);
269 }
270 status_t err = transact(DUMP_TRANSACTION, send, &reply);
271 return err;
272 }
273
274 // NOLINTNEXTLINE(google-default-arguments)
transact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)275 status_t BpBinder::transact(
276 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
277 {
278 // Once a binder has died, it will never come back to life.
279 if (mAlive) {
280 bool privateVendor = flags & FLAG_PRIVATE_VENDOR;
281 // don't send userspace flags to the kernel
282 flags = flags & ~FLAG_PRIVATE_VENDOR;
283
284 // user transactions require a given stability level
285 if (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {
286 using android::internal::Stability;
287
288 int16_t stability = Stability::getRepr(this);
289 Stability::Level required = privateVendor ? Stability::VENDOR
290 : Stability::getLocalLevel();
291
292 if (CC_UNLIKELY(!Stability::check(stability, required))) {
293 ALOGE("Cannot do a user transaction on a %s binder (%s) in a %s context.",
294 Stability::levelString(stability).c_str(),
295 String8(getInterfaceDescriptor()).c_str(),
296 Stability::levelString(required).c_str());
297 return BAD_TYPE;
298 }
299 }
300
301 status_t status;
302 if (CC_UNLIKELY(isRpcBinder())) {
303 status = rpcSession()->transact(sp<IBinder>::fromExisting(this), code, data, reply,
304 flags);
305 } else {
306 status = IPCThreadState::self()->transact(binderHandle(), code, data, reply, flags);
307 }
308 if (data.dataSize() > LOG_TRANSACTIONS_OVER_SIZE) {
309 Mutex::Autolock _l(mLock);
310 ALOGW("Large outgoing transaction of %zu bytes, interface descriptor %s, code %d",
311 data.dataSize(),
312 mDescriptorCache.size() ? String8(mDescriptorCache).c_str()
313 : "<uncached descriptor>",
314 code);
315 }
316
317 if (status == DEAD_OBJECT) mAlive = 0;
318
319 return status;
320 }
321
322 return DEAD_OBJECT;
323 }
324
325 // NOLINTNEXTLINE(google-default-arguments)
linkToDeath(const sp<DeathRecipient> & recipient,void * cookie,uint32_t flags)326 status_t BpBinder::linkToDeath(
327 const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
328 {
329 if (isRpcBinder()) return UNKNOWN_TRANSACTION;
330
331 Obituary ob;
332 ob.recipient = recipient;
333 ob.cookie = cookie;
334 ob.flags = flags;
335
336 LOG_ALWAYS_FATAL_IF(recipient == nullptr,
337 "linkToDeath(): recipient must be non-NULL");
338
339 {
340 AutoMutex _l(mLock);
341
342 if (!mObitsSent) {
343 if (!mObituaries) {
344 mObituaries = new Vector<Obituary>;
345 if (!mObituaries) {
346 return NO_MEMORY;
347 }
348 ALOGV("Requesting death notification: %p handle %d\n", this, binderHandle());
349 getWeakRefs()->incWeak(this);
350 IPCThreadState* self = IPCThreadState::self();
351 self->requestDeathNotification(binderHandle(), this);
352 self->flushCommands();
353 }
354 ssize_t res = mObituaries->add(ob);
355 return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
356 }
357 }
358
359 return DEAD_OBJECT;
360 }
361
362 // NOLINTNEXTLINE(google-default-arguments)
unlinkToDeath(const wp<DeathRecipient> & recipient,void * cookie,uint32_t flags,wp<DeathRecipient> * outRecipient)363 status_t BpBinder::unlinkToDeath(
364 const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
365 wp<DeathRecipient>* outRecipient)
366 {
367 if (isRpcBinder()) return UNKNOWN_TRANSACTION;
368
369 AutoMutex _l(mLock);
370
371 if (mObitsSent) {
372 return DEAD_OBJECT;
373 }
374
375 const size_t N = mObituaries ? mObituaries->size() : 0;
376 for (size_t i=0; i<N; i++) {
377 const Obituary& obit = mObituaries->itemAt(i);
378 if ((obit.recipient == recipient
379 || (recipient == nullptr && obit.cookie == cookie))
380 && obit.flags == flags) {
381 if (outRecipient != nullptr) {
382 *outRecipient = mObituaries->itemAt(i).recipient;
383 }
384 mObituaries->removeAt(i);
385 if (mObituaries->size() == 0) {
386 ALOGV("Clearing death notification: %p handle %d\n", this, binderHandle());
387 IPCThreadState* self = IPCThreadState::self();
388 self->clearDeathNotification(binderHandle(), this);
389 self->flushCommands();
390 delete mObituaries;
391 mObituaries = nullptr;
392 }
393 return NO_ERROR;
394 }
395 }
396
397 return NAME_NOT_FOUND;
398 }
399
sendObituary()400 void BpBinder::sendObituary()
401 {
402 LOG_ALWAYS_FATAL_IF(isRpcBinder(), "Cannot send obituary for remote binder.");
403
404 ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n", this, binderHandle(),
405 mObitsSent ? "true" : "false");
406
407 mAlive = 0;
408 if (mObitsSent) return;
409
410 mLock.lock();
411 Vector<Obituary>* obits = mObituaries;
412 if(obits != nullptr) {
413 ALOGV("Clearing sent death notification: %p handle %d\n", this, binderHandle());
414 IPCThreadState* self = IPCThreadState::self();
415 self->clearDeathNotification(binderHandle(), this);
416 self->flushCommands();
417 mObituaries = nullptr;
418 }
419 mObitsSent = 1;
420 mLock.unlock();
421
422 ALOGV("Reporting death of proxy %p for %zu recipients\n",
423 this, obits ? obits->size() : 0U);
424
425 if (obits != nullptr) {
426 const size_t N = obits->size();
427 for (size_t i=0; i<N; i++) {
428 reportOneDeath(obits->itemAt(i));
429 }
430
431 delete obits;
432 }
433 }
434
reportOneDeath(const Obituary & obit)435 void BpBinder::reportOneDeath(const Obituary& obit)
436 {
437 sp<DeathRecipient> recipient = obit.recipient.promote();
438 ALOGV("Reporting death to recipient: %p\n", recipient.get());
439 if (recipient == nullptr) return;
440
441 recipient->binderDied(wp<BpBinder>::fromExisting(this));
442 }
443
attachObject(const void * objectID,void * object,void * cleanupCookie,object_cleanup_func func)444 void* BpBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
445 object_cleanup_func func) {
446 AutoMutex _l(mLock);
447 ALOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);
448 return mObjects.attach(objectID, object, cleanupCookie, func);
449 }
450
findObject(const void * objectID) const451 void* BpBinder::findObject(const void* objectID) const
452 {
453 AutoMutex _l(mLock);
454 return mObjects.find(objectID);
455 }
456
detachObject(const void * objectID)457 void* BpBinder::detachObject(const void* objectID) {
458 AutoMutex _l(mLock);
459 return mObjects.detach(objectID);
460 }
461
withLock(const std::function<void ()> & doWithLock)462 void BpBinder::withLock(const std::function<void()>& doWithLock) {
463 AutoMutex _l(mLock);
464 doWithLock();
465 }
466
remoteBinder()467 BpBinder* BpBinder::remoteBinder()
468 {
469 return this;
470 }
471
~BpBinder()472 BpBinder::~BpBinder()
473 {
474 ALOGV("Destroying BpBinder %p handle %d\n", this, binderHandle());
475
476 if (CC_UNLIKELY(isRpcBinder())) return;
477
478 IPCThreadState* ipc = IPCThreadState::self();
479
480 if (mTrackedUid >= 0) {
481 AutoMutex _l(sTrackingLock);
482 uint32_t trackedValue = sTrackingMap[mTrackedUid];
483 if (CC_UNLIKELY((trackedValue & COUNTING_VALUE_MASK) == 0)) {
484 ALOGE("Unexpected Binder Proxy tracking decrement in %p handle %d\n", this,
485 binderHandle());
486 } else {
487 if (CC_UNLIKELY(
488 (trackedValue & LIMIT_REACHED_MASK) &&
489 ((trackedValue & COUNTING_VALUE_MASK) <= sBinderProxyCountLowWatermark)
490 )) {
491 ALOGI("Limit reached bit reset for uid %d (fewer than %d proxies from uid %d held)",
492 getuid(), sBinderProxyCountLowWatermark, mTrackedUid);
493 sTrackingMap[mTrackedUid] &= ~LIMIT_REACHED_MASK;
494 sLastLimitCallbackMap.erase(mTrackedUid);
495 }
496 if (--sTrackingMap[mTrackedUid] == 0) {
497 sTrackingMap.erase(mTrackedUid);
498 }
499 }
500 }
501
502 if (ipc) {
503 ipc->expungeHandle(binderHandle(), this);
504 ipc->decWeakHandle(binderHandle());
505 }
506 }
507
onFirstRef()508 void BpBinder::onFirstRef()
509 {
510 ALOGV("onFirstRef BpBinder %p handle %d\n", this, binderHandle());
511 if (CC_UNLIKELY(isRpcBinder())) return;
512 IPCThreadState* ipc = IPCThreadState::self();
513 if (ipc) ipc->incStrongHandle(binderHandle(), this);
514 }
515
onLastStrongRef(const void *)516 void BpBinder::onLastStrongRef(const void* /*id*/)
517 {
518 ALOGV("onLastStrongRef BpBinder %p handle %d\n", this, binderHandle());
519 if (CC_UNLIKELY(isRpcBinder())) {
520 (void)rpcSession()->sendDecStrong(this);
521 return;
522 }
523 IF_ALOGV() {
524 printRefs();
525 }
526 IPCThreadState* ipc = IPCThreadState::self();
527 if (ipc) ipc->decStrongHandle(binderHandle());
528
529 mLock.lock();
530 Vector<Obituary>* obits = mObituaries;
531 if(obits != nullptr) {
532 if (!obits->isEmpty()) {
533 ALOGI("onLastStrongRef automatically unlinking death recipients: %s",
534 mDescriptorCache.size() ? String8(mDescriptorCache).c_str() : "<uncached descriptor>");
535 }
536
537 if (ipc) ipc->clearDeathNotification(binderHandle(), this);
538 mObituaries = nullptr;
539 }
540 mLock.unlock();
541
542 if (obits != nullptr) {
543 // XXX Should we tell any remaining DeathRecipient
544 // objects that the last strong ref has gone away, so they
545 // are no longer linked?
546 delete obits;
547 }
548 }
549
onIncStrongAttempted(uint32_t,const void *)550 bool BpBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
551 {
552 // RPC binder doesn't currently support inc from weak binders
553 if (CC_UNLIKELY(isRpcBinder())) return false;
554
555 ALOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, binderHandle());
556 IPCThreadState* ipc = IPCThreadState::self();
557 return ipc ? ipc->attemptIncStrongHandle(binderHandle()) == NO_ERROR : false;
558 }
559
getBinderProxyCount(uint32_t uid)560 uint32_t BpBinder::getBinderProxyCount(uint32_t uid)
561 {
562 AutoMutex _l(sTrackingLock);
563 auto it = sTrackingMap.find(uid);
564 if (it != sTrackingMap.end()) {
565 return it->second & COUNTING_VALUE_MASK;
566 }
567 return 0;
568 }
569
getCountByUid(Vector<uint32_t> & uids,Vector<uint32_t> & counts)570 void BpBinder::getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts)
571 {
572 AutoMutex _l(sTrackingLock);
573 uids.setCapacity(sTrackingMap.size());
574 counts.setCapacity(sTrackingMap.size());
575 for (const auto& it : sTrackingMap) {
576 uids.push_back(it.first);
577 counts.push_back(it.second & COUNTING_VALUE_MASK);
578 }
579 }
580
enableCountByUid()581 void BpBinder::enableCountByUid() { sCountByUidEnabled.store(true); }
disableCountByUid()582 void BpBinder::disableCountByUid() { sCountByUidEnabled.store(false); }
setCountByUidEnabled(bool enable)583 void BpBinder::setCountByUidEnabled(bool enable) { sCountByUidEnabled.store(enable); }
584
setLimitCallback(binder_proxy_limit_callback cb)585 void BpBinder::setLimitCallback(binder_proxy_limit_callback cb) {
586 AutoMutex _l(sTrackingLock);
587 sLimitCallback = cb;
588 }
589
setBinderProxyCountWatermarks(int high,int low)590 void BpBinder::setBinderProxyCountWatermarks(int high, int low) {
591 AutoMutex _l(sTrackingLock);
592 sBinderProxyCountHighWatermark = high;
593 sBinderProxyCountLowWatermark = low;
594 }
595
596 // ---------------------------------------------------------------------------
597
598 } // namespace android
599