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