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