blob: b0c1af21a96df6e57e20333b966d9fac15cee653 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070020#include <binder/BpBinder.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070022#include <binder/IPCThreadState.h>
Dianne Hackborn23eb1e22015-10-07 17:35:27 -070023#include <binder/IResultReceiver.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000024#include <binder/RpcSession.h>
Steven Moreland6e5a7752019-08-05 20:30:14 -070025#include <binder/Stability.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026#include <utils/Log.h>
27
28#include <stdio.h>
29
Steven Moreland32150282021-11-12 22:54:53 +000030#include "BuildFlags.h"
31
Sahil Somani2522b072022-08-08 14:07:47 -070032#include <android-base/file.h>
33
Steve Block6807e592011-10-20 11:56:00 +010034//#undef ALOGV
35//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
37namespace android {
38
39// ---------------------------------------------------------------------------
40
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070041Mutex BpBinder::sTrackingLock;
Martijn Coenena8d509d2021-09-03 18:06:24 +020042std::unordered_map<int32_t, uint32_t> BpBinder::sTrackingMap;
43std::unordered_map<int32_t, uint32_t> BpBinder::sLastLimitCallbackMap;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070044int BpBinder::sNumTrackedUids = 0;
45std::atomic_bool BpBinder::sCountByUidEnabled(false);
46binder_proxy_limit_callback BpBinder::sLimitCallback;
47bool BpBinder::sBinderProxyThrottleCreate = false;
48
Steven Moreland847d8c52023-05-02 23:56:58 +000049static StaticString16 kDescriptorUninit(u"");
Steven Morelandf2830fe2022-12-21 00:45:34 +000050
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070051// Arbitrarily high value that probably distinguishes a bad behaving app
52uint32_t BpBinder::sBinderProxyCountHighWatermark = 2500;
53// Another arbitrary value a binder count needs to drop below before another callback will be called
54uint32_t BpBinder::sBinderProxyCountLowWatermark = 2000;
55
Martijn Coenen1cad19c2021-10-04 09:19:01 +020056// Log any transactions for which the data exceeds this size
57#define LOG_TRANSACTIONS_OVER_SIZE (300 * 1024)
58
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070059enum {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -070060 LIMIT_REACHED_MASK = 0x80000000, // A flag denoting that the limit has been reached
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070061 COUNTING_VALUE_MASK = 0x7FFFFFFF, // A mask of the remaining bits for the count value
62};
63
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064BpBinder::ObjectManager::ObjectManager()
65{
66}
67
68BpBinder::ObjectManager::~ObjectManager()
69{
70 kill();
71}
72
Steven Moreland63a2d512021-06-25 01:10:15 +000073void* BpBinder::ObjectManager::attach(const void* objectID, void* object, void* cleanupCookie,
74 IBinder::object_cleanup_func func) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075 entry_t e;
76 e.object = object;
77 e.cleanupCookie = cleanupCookie;
78 e.func = func;
79
Jiyong Park5970d0a2022-03-08 16:56:13 +090080 if (mObjects.find(objectID) != mObjects.end()) {
Steven Moreland63a2d512021-06-25 01:10:15 +000081 ALOGI("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object "
82 "ID already in use",
83 objectID, this, object);
Jiyong Park5970d0a2022-03-08 16:56:13 +090084 return mObjects[objectID].object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085 }
86
Jiyong Park5970d0a2022-03-08 16:56:13 +090087 mObjects.insert({objectID, e});
Steven Moreland63a2d512021-06-25 01:10:15 +000088 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089}
90
91void* BpBinder::ObjectManager::find(const void* objectID) const
92{
Jiyong Park5970d0a2022-03-08 16:56:13 +090093 auto i = mObjects.find(objectID);
94 if (i == mObjects.end()) return nullptr;
95 return i->second.object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096}
97
Steven Moreland63a2d512021-06-25 01:10:15 +000098void* BpBinder::ObjectManager::detach(const void* objectID) {
Jiyong Park5970d0a2022-03-08 16:56:13 +090099 auto i = mObjects.find(objectID);
100 if (i == mObjects.end()) return nullptr;
101 void* value = i->second.object;
102 mObjects.erase(i);
Steven Moreland63a2d512021-06-25 01:10:15 +0000103 return value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104}
105
Devin Moore3faaa002022-07-27 15:54:06 +0000106namespace {
107struct Tag {
108 wp<IBinder> binder;
109};
110} // namespace
111
112static void cleanWeak(const void* /* id */, void* obj, void* /* cookie */) {
113 delete static_cast<Tag*>(obj);
114}
115
116sp<IBinder> BpBinder::ObjectManager::lookupOrCreateWeak(const void* objectID, object_make_func make,
117 const void* makeArgs) {
118 entry_t& e = mObjects[objectID];
119 if (e.object != nullptr) {
120 if (auto attached = static_cast<Tag*>(e.object)->binder.promote()) {
121 return attached;
122 }
123 } else {
124 e.object = new Tag;
125 LOG_ALWAYS_FATAL_IF(!e.object, "no more memory");
126 }
127 sp<IBinder> newObj = make(makeArgs);
128
129 static_cast<Tag*>(e.object)->binder = newObj;
130 e.cleanupCookie = nullptr;
131 e.func = cleanWeak;
132
133 return newObj;
134}
135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136void BpBinder::ObjectManager::kill()
137{
138 const size_t N = mObjects.size();
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700139 ALOGV("Killing %zu objects in manager %p", N, this);
Jiyong Park5970d0a2022-03-08 16:56:13 +0900140 for (auto i : mObjects) {
141 const entry_t& e = i.second;
Yi Kongfdd8da92018-06-07 17:52:27 -0700142 if (e.func != nullptr) {
Jiyong Park5970d0a2022-03-08 16:56:13 +0900143 e.func(i.first, e.object, e.cleanupCookie);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144 }
145 }
146
147 mObjects.clear();
148}
149
150// ---------------------------------------------------------------------------
151
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000152sp<BpBinder> BpBinder::create(int32_t handle) {
Steven Moreland32150282021-11-12 22:54:53 +0000153 if constexpr (!kEnableKernelIpc) {
154 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
155 return nullptr;
156 }
157
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700158 int32_t trackedUid = -1;
159 if (sCountByUidEnabled) {
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700160 trackedUid = IPCThreadState::self()->getCallingUid();
161 AutoMutex _l(sTrackingLock);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700162 uint32_t trackedValue = sTrackingMap[trackedUid];
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000163 if (trackedValue & LIMIT_REACHED_MASK) [[unlikely]] {
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700164 if (sBinderProxyThrottleCreate) {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700165 return nullptr;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700166 }
Martijn Coenena8d509d2021-09-03 18:06:24 +0200167 trackedValue = trackedValue & COUNTING_VALUE_MASK;
168 uint32_t lastLimitCallbackAt = sLastLimitCallbackMap[trackedUid];
169
170 if (trackedValue > lastLimitCallbackAt &&
Martijn Coenen6711b6d2021-09-23 09:44:29 +0200171 (trackedValue - lastLimitCallbackAt > sBinderProxyCountHighWatermark)) {
Martijn Coenena8d509d2021-09-03 18:06:24 +0200172 ALOGE("Still too many binder proxy objects sent to uid %d from uid %d (%d proxies "
173 "held)",
174 getuid(), trackedUid, trackedValue);
175 if (sLimitCallback) sLimitCallback(trackedUid);
176 sLastLimitCallbackMap[trackedUid] = trackedValue;
177 }
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700178 } else {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700179 if ((trackedValue & COUNTING_VALUE_MASK) >= sBinderProxyCountHighWatermark) {
180 ALOGE("Too many binder proxy objects sent to uid %d from uid %d (%d proxies held)",
181 getuid(), trackedUid, trackedValue);
182 sTrackingMap[trackedUid] |= LIMIT_REACHED_MASK;
183 if (sLimitCallback) sLimitCallback(trackedUid);
Martijn Coenena8d509d2021-09-03 18:06:24 +0200184 sLastLimitCallbackMap[trackedUid] = trackedValue & COUNTING_VALUE_MASK;
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700185 if (sBinderProxyThrottleCreate) {
186 ALOGI("Throttling binder proxy creates from uid %d in uid %d until binder proxy"
187 " count drops below %d",
188 trackedUid, getuid(), sBinderProxyCountLowWatermark);
189 return nullptr;
190 }
191 }
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700192 }
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700193 sTrackingMap[trackedUid]++;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700194 }
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000195 return sp<BpBinder>::make(BinderHandle{handle}, trackedUid);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700196}
197
Steven Moreland5623d1a2021-09-10 15:45:34 -0700198sp<BpBinder> BpBinder::create(const sp<RpcSession>& session, uint64_t address) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000199 LOG_ALWAYS_FATAL_IF(session == nullptr, "BpBinder::create null session");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200
Steven Moreland5553ac42020-11-11 02:14:45 +0000201 // These are not currently tracked, since there is no UID or other
202 // identifier to track them with. However, if similar functionality is
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000203 // needed, session objects keep track of all BpBinder objects on a
204 // per-session basis.
Steven Moreland5553ac42020-11-11 02:14:45 +0000205
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000206 return sp<BpBinder>::make(RpcHandle{session, address});
Steven Moreland5553ac42020-11-11 02:14:45 +0000207}
208
209BpBinder::BpBinder(Handle&& handle)
210 : mStability(0),
211 mHandle(handle),
212 mAlive(true),
213 mObitsSent(false),
214 mObituaries(nullptr),
Steven Morelandf2830fe2022-12-21 00:45:34 +0000215 mDescriptorCache(kDescriptorUninit),
Steven Moreland5553ac42020-11-11 02:14:45 +0000216 mTrackedUid(-1) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218}
219
Steven Moreland5553ac42020-11-11 02:14:45 +0000220BpBinder::BpBinder(BinderHandle&& handle, int32_t trackedUid) : BpBinder(Handle(handle)) {
Steven Moreland32150282021-11-12 22:54:53 +0000221 if constexpr (!kEnableKernelIpc) {
222 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
223 return;
224 }
225
Steven Moreland5553ac42020-11-11 02:14:45 +0000226 mTrackedUid = trackedUid;
227
228 ALOGV("Creating BpBinder %p handle %d\n", this, this->binderHandle());
229
230 IPCThreadState::self()->incWeakHandle(this->binderHandle(), this);
231}
232
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000233BpBinder::BpBinder(RpcHandle&& handle) : BpBinder(Handle(handle)) {
234 LOG_ALWAYS_FATAL_IF(rpcSession() == nullptr, "BpBinder created w/o session object");
Steven Moreland5553ac42020-11-11 02:14:45 +0000235}
236
237bool BpBinder::isRpcBinder() const {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000238 return std::holds_alternative<RpcHandle>(mHandle);
Steven Moreland5553ac42020-11-11 02:14:45 +0000239}
240
Steven Moreland5623d1a2021-09-10 15:45:34 -0700241uint64_t BpBinder::rpcAddress() const {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000242 return std::get<RpcHandle>(mHandle).address;
Steven Moreland5553ac42020-11-11 02:14:45 +0000243}
244
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000245const sp<RpcSession>& BpBinder::rpcSession() const {
246 return std::get<RpcHandle>(mHandle).session;
Steven Moreland5553ac42020-11-11 02:14:45 +0000247}
248
249int32_t BpBinder::binderHandle() const {
250 return std::get<BinderHandle>(mHandle).handle;
Steven Moreland85180c02019-07-16 14:24:20 -0700251}
252
Devin Mooref6f2e642021-08-05 19:03:47 +0000253std::optional<int32_t> BpBinder::getDebugBinderHandle() const {
254 if (!isRpcBinder()) {
255 return binderHandle();
256 } else {
257 return std::nullopt;
258 }
259}
260
Mathias Agopian83c04462009-05-22 19:00:22 -0700261bool BpBinder::isDescriptorCached() const {
262 Mutex::Autolock _l(mLock);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000263 return mDescriptorCache.c_str() != kDescriptorUninit.c_str();
Mathias Agopian83c04462009-05-22 19:00:22 -0700264}
265
266const String16& BpBinder::getInterfaceDescriptor() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267{
Steven Morelandf2830fe2022-12-21 00:45:34 +0000268 if (!isDescriptorCached()) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000269 sp<BpBinder> thiz = sp<BpBinder>::fromExisting(const_cast<BpBinder*>(this));
Steven Moreland4cf688f2021-03-31 01:48:58 +0000270
271 Parcel data;
272 data.markForBinder(thiz);
273 Parcel reply;
Mathias Agopian83c04462009-05-22 19:00:22 -0700274 // do the IPC without a lock held.
Steven Moreland4cf688f2021-03-31 01:48:58 +0000275 status_t err = thiz->transact(INTERFACE_TRANSACTION, data, &reply);
Mathias Agopian83c04462009-05-22 19:00:22 -0700276 if (err == NO_ERROR) {
277 String16 res(reply.readString16());
278 Mutex::Autolock _l(mLock);
279 // mDescriptorCache could have been assigned while the lock was
280 // released.
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000281 if (mDescriptorCache.c_str() == kDescriptorUninit.c_str()) mDescriptorCache = res;
Mathias Agopian83c04462009-05-22 19:00:22 -0700282 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700284
Mathias Agopian83c04462009-05-22 19:00:22 -0700285 // we're returning a reference to a non-static object here. Usually this
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700286 // is not something smart to do, however, with binder objects it is
Mathias Agopian83c04462009-05-22 19:00:22 -0700287 // (usually) safe because they are reference-counted.
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700288
Mathias Agopian83c04462009-05-22 19:00:22 -0700289 return mDescriptorCache;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290}
291
292bool BpBinder::isBinderAlive() const
293{
Steven Moreland06074d82020-03-05 23:16:51 +0000294 return mAlive != 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800295}
296
297status_t BpBinder::pingBinder()
298{
Steven Moreland5553ac42020-11-11 02:14:45 +0000299 Parcel data;
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000300 data.markForBinder(sp<BpBinder>::fromExisting(this));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 Parcel reply;
Steven Moreland5553ac42020-11-11 02:14:45 +0000302 return transact(PING_TRANSACTION, data, &reply);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303}
304
Sahil Somani2522b072022-08-08 14:07:47 -0700305status_t BpBinder::startRecordingBinder(const android::base::unique_fd& fd) {
306 Parcel send, reply;
307 send.writeUniqueFileDescriptor(fd);
308 return transact(START_RECORDING_TRANSACTION, send, &reply);
309}
310
311status_t BpBinder::stopRecordingBinder() {
312 Parcel data, reply;
313 data.markForBinder(sp<BpBinder>::fromExisting(this));
314 return transact(STOP_RECORDING_TRANSACTION, data, &reply);
315}
316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317status_t BpBinder::dump(int fd, const Vector<String16>& args)
318{
319 Parcel send;
320 Parcel reply;
321 send.writeFileDescriptor(fd);
322 const size_t numArgs = args.size();
323 send.writeInt32(numArgs);
324 for (size_t i = 0; i < numArgs; i++) {
325 send.writeString16(args[i]);
326 }
327 status_t err = transact(DUMP_TRANSACTION, send, &reply);
328 return err;
329}
330
Jiyong Parkb86c8662018-10-29 23:01:57 +0900331// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800332status_t BpBinder::transact(
333 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
334{
335 // Once a binder has died, it will never come back to life.
336 if (mAlive) {
Steven Moreland46b5fea2019-10-15 11:22:18 -0700337 bool privateVendor = flags & FLAG_PRIVATE_VENDOR;
338 // don't send userspace flags to the kernel
Andrei Homescu7cdf5c22022-04-30 03:41:16 +0000339 flags = flags & ~static_cast<uint32_t>(FLAG_PRIVATE_VENDOR);
Steven Moreland46b5fea2019-10-15 11:22:18 -0700340
Steven Moreland6e5a7752019-08-05 20:30:14 -0700341 // user transactions require a given stability level
342 if (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {
343 using android::internal::Stability;
344
Steven Moreland16a41062021-07-23 13:35:25 -0700345 int16_t stability = Stability::getRepr(this);
Steven Moreland89ddfc52020-11-13 02:39:26 +0000346 Stability::Level required = privateVendor ? Stability::VENDOR
347 : Stability::getLocalLevel();
Steven Moreland6e5a7752019-08-05 20:30:14 -0700348
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000349 if (!Stability::check(stability, required)) [[unlikely]] {
Steven Morelandb269b582021-02-10 17:09:11 +0000350 ALOGE("Cannot do a user transaction on a %s binder (%s) in a %s context.",
Steven Moreland16a41062021-07-23 13:35:25 -0700351 Stability::levelString(stability).c_str(),
352 String8(getInterfaceDescriptor()).c_str(),
353 Stability::levelString(required).c_str());
Steven Moreland6e5a7752019-08-05 20:30:14 -0700354 return BAD_TYPE;
355 }
356 }
357
Steven Moreland5553ac42020-11-11 02:14:45 +0000358 status_t status;
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000359 if (isRpcBinder()) [[unlikely]] {
Steven Morelandf5174272021-05-25 00:39:28 +0000360 status = rpcSession()->transact(sp<IBinder>::fromExisting(this), code, data, reply,
361 flags);
Steven Moreland5553ac42020-11-11 02:14:45 +0000362 } else {
Steven Moreland32150282021-11-12 22:54:53 +0000363 if constexpr (!kEnableKernelIpc) {
364 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
365 return INVALID_OPERATION;
366 }
367
Steven Moreland5553ac42020-11-11 02:14:45 +0000368 status = IPCThreadState::self()->transact(binderHandle(), code, data, reply, flags);
369 }
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200370 if (data.dataSize() > LOG_TRANSACTIONS_OVER_SIZE) {
371 Mutex::Autolock _l(mLock);
372 ALOGW("Large outgoing transaction of %zu bytes, interface descriptor %s, code %d",
Steven Morelandf2830fe2022-12-21 00:45:34 +0000373 data.dataSize(), String8(mDescriptorCache).c_str(), code);
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200374 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000375
Steven Moreland06074d82020-03-05 23:16:51 +0000376 if (status == DEAD_OBJECT) mAlive = 0;
Steven Morelanda86a3562019-08-01 23:28:34 +0000377
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378 return status;
379 }
380
381 return DEAD_OBJECT;
382}
383
Jiyong Parkb86c8662018-10-29 23:01:57 +0900384// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385status_t BpBinder::linkToDeath(
386 const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
387{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000388 if (isRpcBinder()) {
389 if (rpcSession()->getMaxIncomingThreads() < 1) {
Devin Moorebd41dc12023-02-08 17:06:22 +0000390 ALOGE("Cannot register a DeathRecipient without any incoming threads. Need to set max "
391 "incoming threads to a value greater than 0 before calling linkToDeath.");
Devin Moore66d5b7a2022-07-07 21:42:10 +0000392 return INVALID_OPERATION;
393 }
394 } else if constexpr (!kEnableKernelIpc) {
Steven Moreland32150282021-11-12 22:54:53 +0000395 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
396 return INVALID_OPERATION;
Devin Moore66d5b7a2022-07-07 21:42:10 +0000397 } else {
398 if (ProcessState::self()->getThreadPoolMaxTotalThreadCount() == 0) {
399 ALOGW("Linking to death on %s but there are no threads (yet?) listening to incoming "
400 "transactions. See ProcessState::startThreadPool and "
401 "ProcessState::setThreadPoolMaxThreadCount. Generally you should setup the "
402 "binder "
403 "threadpool before other initialization steps.",
404 String8(getInterfaceDescriptor()).c_str());
405 }
Steven Moreland32150282021-11-12 22:54:53 +0000406 }
407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408 Obituary ob;
409 ob.recipient = recipient;
410 ob.cookie = cookie;
411 ob.flags = flags;
412
Yi Kongfdd8da92018-06-07 17:52:27 -0700413 LOG_ALWAYS_FATAL_IF(recipient == nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414 "linkToDeath(): recipient must be non-NULL");
415
416 {
417 AutoMutex _l(mLock);
418
419 if (!mObitsSent) {
420 if (!mObituaries) {
421 mObituaries = new Vector<Obituary>;
422 if (!mObituaries) {
423 return NO_MEMORY;
424 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000425 ALOGV("Requesting death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000426 if (!isRpcBinder()) {
427 if constexpr (kEnableKernelIpc) {
428 getWeakRefs()->incWeak(this);
429 IPCThreadState* self = IPCThreadState::self();
430 self->requestDeathNotification(binderHandle(), this);
431 self->flushCommands();
432 }
433 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434 }
435 ssize_t res = mObituaries->add(ob);
436 return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
437 }
438 }
439
440 return DEAD_OBJECT;
441}
442
Jiyong Parkb86c8662018-10-29 23:01:57 +0900443// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444status_t BpBinder::unlinkToDeath(
445 const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
446 wp<DeathRecipient>* outRecipient)
447{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000448 if (!kEnableKernelIpc && !isRpcBinder()) {
Steven Moreland32150282021-11-12 22:54:53 +0000449 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
450 return INVALID_OPERATION;
451 }
452
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453 AutoMutex _l(mLock);
454
455 if (mObitsSent) {
456 return DEAD_OBJECT;
457 }
458
459 const size_t N = mObituaries ? mObituaries->size() : 0;
460 for (size_t i=0; i<N; i++) {
461 const Obituary& obit = mObituaries->itemAt(i);
462 if ((obit.recipient == recipient
Yi Kongfdd8da92018-06-07 17:52:27 -0700463 || (recipient == nullptr && obit.cookie == cookie))
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800464 && obit.flags == flags) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700465 if (outRecipient != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800466 *outRecipient = mObituaries->itemAt(i).recipient;
467 }
468 mObituaries->removeAt(i);
469 if (mObituaries->size() == 0) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000470 ALOGV("Clearing death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000471 if (!isRpcBinder()) {
472 if constexpr (kEnableKernelIpc) {
473 IPCThreadState* self = IPCThreadState::self();
474 self->clearDeathNotification(binderHandle(), this);
475 self->flushCommands();
476 }
477 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800478 delete mObituaries;
Yi Kongfdd8da92018-06-07 17:52:27 -0700479 mObituaries = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800480 }
481 return NO_ERROR;
482 }
483 }
484
485 return NAME_NOT_FOUND;
486}
487
488void BpBinder::sendObituary()
489{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000490 if (!kEnableKernelIpc && !isRpcBinder()) {
Steven Moreland32150282021-11-12 22:54:53 +0000491 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
492 return;
493 }
494
Steven Moreland5553ac42020-11-11 02:14:45 +0000495 ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n", this, binderHandle(),
496 mObitsSent ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800497
Steven Moreland06074d82020-03-05 23:16:51 +0000498 mAlive = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800499 if (mObitsSent) return;
500
501 mLock.lock();
502 Vector<Obituary>* obits = mObituaries;
Yi Kongfdd8da92018-06-07 17:52:27 -0700503 if(obits != nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000504 ALOGV("Clearing sent death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000505 if (!isRpcBinder()) {
506 if constexpr (kEnableKernelIpc) {
507 IPCThreadState* self = IPCThreadState::self();
508 self->clearDeathNotification(binderHandle(), this);
509 self->flushCommands();
510 }
511 }
Yi Kongfdd8da92018-06-07 17:52:27 -0700512 mObituaries = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800513 }
Steven Moreland06074d82020-03-05 23:16:51 +0000514 mObitsSent = 1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515 mLock.unlock();
516
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700517 ALOGV("Reporting death of proxy %p for %zu recipients\n",
518 this, obits ? obits->size() : 0U);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519
Yi Kongfdd8da92018-06-07 17:52:27 -0700520 if (obits != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 const size_t N = obits->size();
522 for (size_t i=0; i<N; i++) {
523 reportOneDeath(obits->itemAt(i));
524 }
525
526 delete obits;
527 }
528}
529
530void BpBinder::reportOneDeath(const Obituary& obit)
531{
532 sp<DeathRecipient> recipient = obit.recipient.promote();
Steve Block6807e592011-10-20 11:56:00 +0100533 ALOGV("Reporting death to recipient: %p\n", recipient.get());
Yi Kongfdd8da92018-06-07 17:52:27 -0700534 if (recipient == nullptr) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000536 recipient->binderDied(wp<BpBinder>::fromExisting(this));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537}
538
Steven Moreland63a2d512021-06-25 01:10:15 +0000539void* BpBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
540 object_cleanup_func func) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541 AutoMutex _l(mLock);
Steve Block6807e592011-10-20 11:56:00 +0100542 ALOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);
Steven Moreland63a2d512021-06-25 01:10:15 +0000543 return mObjects.attach(objectID, object, cleanupCookie, func);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544}
545
546void* BpBinder::findObject(const void* objectID) const
547{
548 AutoMutex _l(mLock);
549 return mObjects.find(objectID);
550}
551
Steven Moreland63a2d512021-06-25 01:10:15 +0000552void* BpBinder::detachObject(const void* objectID) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553 AutoMutex _l(mLock);
Steven Moreland63a2d512021-06-25 01:10:15 +0000554 return mObjects.detach(objectID);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555}
556
Steven Moreland9e759e82021-06-25 21:30:23 +0000557void BpBinder::withLock(const std::function<void()>& doWithLock) {
558 AutoMutex _l(mLock);
559 doWithLock();
560}
561
Devin Moore3faaa002022-07-27 15:54:06 +0000562sp<IBinder> BpBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
563 const void* makeArgs) {
564 AutoMutex _l(mLock);
565 return mObjects.lookupOrCreateWeak(objectID, make, makeArgs);
566}
567
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800568BpBinder* BpBinder::remoteBinder()
569{
570 return this;
571}
572
Steven Moreland32150282021-11-12 22:54:53 +0000573BpBinder::~BpBinder() {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000574 if (isRpcBinder()) [[unlikely]] {
575 return;
576 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800577
Steven Moreland32150282021-11-12 22:54:53 +0000578 if constexpr (!kEnableKernelIpc) {
579 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
580 return;
581 }
582
583 ALOGV("Destroying BpBinder %p handle %d\n", this, binderHandle());
584
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585 IPCThreadState* ipc = IPCThreadState::self();
586
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700587 if (mTrackedUid >= 0) {
588 AutoMutex _l(sTrackingLock);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700589 uint32_t trackedValue = sTrackingMap[mTrackedUid];
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000590 if ((trackedValue & COUNTING_VALUE_MASK) == 0) [[unlikely]] {
Steven Moreland5553ac42020-11-11 02:14:45 +0000591 ALOGE("Unexpected Binder Proxy tracking decrement in %p handle %d\n", this,
592 binderHandle());
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700593 } else {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000594 auto countingValue = trackedValue & COUNTING_VALUE_MASK;
595 if ((trackedValue & LIMIT_REACHED_MASK) &&
596 (countingValue <= sBinderProxyCountLowWatermark)) [[unlikely]] {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700597 ALOGI("Limit reached bit reset for uid %d (fewer than %d proxies from uid %d held)",
Martijn Coenena8d509d2021-09-03 18:06:24 +0200598 getuid(), sBinderProxyCountLowWatermark, mTrackedUid);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700599 sTrackingMap[mTrackedUid] &= ~LIMIT_REACHED_MASK;
Martijn Coenena8d509d2021-09-03 18:06:24 +0200600 sLastLimitCallbackMap.erase(mTrackedUid);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700601 }
602 if (--sTrackingMap[mTrackedUid] == 0) {
603 sTrackingMap.erase(mTrackedUid);
604 }
605 }
606 }
607
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800608 if (ipc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000609 ipc->expungeHandle(binderHandle(), this);
610 ipc->decWeakHandle(binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800611 }
612}
613
Steven Moreland32150282021-11-12 22:54:53 +0000614void BpBinder::onFirstRef() {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000615 if (isRpcBinder()) [[unlikely]] {
616 return;
617 }
Steven Moreland32150282021-11-12 22:54:53 +0000618
619 if constexpr (!kEnableKernelIpc) {
620 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
621 return;
622 }
623
624 ALOGV("onFirstRef BpBinder %p handle %d\n", this, binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800625 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000626 if (ipc) ipc->incStrongHandle(binderHandle(), this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800627}
628
Steven Moreland32150282021-11-12 22:54:53 +0000629void BpBinder::onLastStrongRef(const void* /*id*/) {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000630 if (isRpcBinder()) [[unlikely]] {
Steven Moreland4f622fe2021-09-13 17:38:09 -0700631 (void)rpcSession()->sendDecStrong(this);
Steven Moreland5553ac42020-11-11 02:14:45 +0000632 return;
633 }
Steven Moreland32150282021-11-12 22:54:53 +0000634
635 if constexpr (!kEnableKernelIpc) {
636 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
637 return;
638 }
639
640 ALOGV("onLastStrongRef BpBinder %p handle %d\n", this, binderHandle());
Steve Block6807e592011-10-20 11:56:00 +0100641 IF_ALOGV() {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800642 printRefs();
643 }
644 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000645 if (ipc) ipc->decStrongHandle(binderHandle());
Steven Moreland80d23932019-06-07 12:43:27 -0700646
647 mLock.lock();
648 Vector<Obituary>* obits = mObituaries;
649 if(obits != nullptr) {
650 if (!obits->isEmpty()) {
Steven Moreland70fcb4e2019-12-13 17:28:58 -0800651 ALOGI("onLastStrongRef automatically unlinking death recipients: %s",
Steven Morelandf2830fe2022-12-21 00:45:34 +0000652 String8(mDescriptorCache).c_str());
Steven Moreland80d23932019-06-07 12:43:27 -0700653 }
654
Steven Moreland5553ac42020-11-11 02:14:45 +0000655 if (ipc) ipc->clearDeathNotification(binderHandle(), this);
Steven Moreland80d23932019-06-07 12:43:27 -0700656 mObituaries = nullptr;
657 }
658 mLock.unlock();
659
660 if (obits != nullptr) {
661 // XXX Should we tell any remaining DeathRecipient
662 // objects that the last strong ref has gone away, so they
663 // are no longer linked?
664 delete obits;
665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666}
667
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800668bool BpBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800669{
Steven Moreland5553ac42020-11-11 02:14:45 +0000670 // RPC binder doesn't currently support inc from weak binders
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000671 if (isRpcBinder()) [[unlikely]] {
672 return false;
673 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000674
Steven Moreland32150282021-11-12 22:54:53 +0000675 if constexpr (!kEnableKernelIpc) {
676 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
677 return false;
678 }
679
Steven Moreland5553ac42020-11-11 02:14:45 +0000680 ALOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800681 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000682 return ipc ? ipc->attemptIncStrongHandle(binderHandle()) == NO_ERROR : false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800683}
684
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700685uint32_t BpBinder::getBinderProxyCount(uint32_t uid)
686{
687 AutoMutex _l(sTrackingLock);
688 auto it = sTrackingMap.find(uid);
689 if (it != sTrackingMap.end()) {
690 return it->second & COUNTING_VALUE_MASK;
691 }
692 return 0;
693}
694
695void BpBinder::getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts)
696{
697 AutoMutex _l(sTrackingLock);
698 uids.setCapacity(sTrackingMap.size());
699 counts.setCapacity(sTrackingMap.size());
700 for (const auto& it : sTrackingMap) {
701 uids.push_back(it.first);
702 counts.push_back(it.second & COUNTING_VALUE_MASK);
703 }
704}
705
706void BpBinder::enableCountByUid() { sCountByUidEnabled.store(true); }
707void BpBinder::disableCountByUid() { sCountByUidEnabled.store(false); }
708void BpBinder::setCountByUidEnabled(bool enable) { sCountByUidEnabled.store(enable); }
709
710void BpBinder::setLimitCallback(binder_proxy_limit_callback cb) {
711 AutoMutex _l(sTrackingLock);
712 sLimitCallback = cb;
713}
714
715void BpBinder::setBinderProxyCountWatermarks(int high, int low) {
716 AutoMutex _l(sTrackingLock);
717 sBinderProxyCountHighWatermark = high;
718 sBinderProxyCountLowWatermark = low;
719}
720
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721// ---------------------------------------------------------------------------
722
Steven Moreland61ff8492019-09-26 16:05:45 -0700723} // namespace android