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