blob: 3bc4f929e7d151a0fd4f3d3d1ff7aa87fe5e4d0b [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
Jing Ji4c4ac062023-10-07 15:20:23 -070056std::atomic<uint32_t> BpBinder::sBinderProxyCount(0);
57std::atomic<uint32_t> BpBinder::sBinderProxyCountWarned(0);
58
59static constexpr uint32_t kBinderProxyCountWarnInterval = 5000;
60
Martijn Coenen1cad19c2021-10-04 09:19:01 +020061// Log any transactions for which the data exceeds this size
62#define LOG_TRANSACTIONS_OVER_SIZE (300 * 1024)
63
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070064enum {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -070065 LIMIT_REACHED_MASK = 0x80000000, // A flag denoting that the limit has been reached
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070066 COUNTING_VALUE_MASK = 0x7FFFFFFF, // A mask of the remaining bits for the count value
67};
68
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069BpBinder::ObjectManager::ObjectManager()
70{
71}
72
73BpBinder::ObjectManager::~ObjectManager()
74{
75 kill();
76}
77
Steven Moreland63a2d512021-06-25 01:10:15 +000078void* BpBinder::ObjectManager::attach(const void* objectID, void* object, void* cleanupCookie,
79 IBinder::object_cleanup_func func) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080 entry_t e;
81 e.object = object;
82 e.cleanupCookie = cleanupCookie;
83 e.func = func;
84
Jiyong Park5970d0a2022-03-08 16:56:13 +090085 if (mObjects.find(objectID) != mObjects.end()) {
Steven Moreland63a2d512021-06-25 01:10:15 +000086 ALOGI("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object "
87 "ID already in use",
88 objectID, this, object);
Jiyong Park5970d0a2022-03-08 16:56:13 +090089 return mObjects[objectID].object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090 }
91
Jiyong Park5970d0a2022-03-08 16:56:13 +090092 mObjects.insert({objectID, e});
Steven Moreland63a2d512021-06-25 01:10:15 +000093 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094}
95
96void* BpBinder::ObjectManager::find(const void* objectID) const
97{
Jiyong Park5970d0a2022-03-08 16:56:13 +090098 auto i = mObjects.find(objectID);
99 if (i == mObjects.end()) return nullptr;
100 return i->second.object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101}
102
Steven Moreland63a2d512021-06-25 01:10:15 +0000103void* BpBinder::ObjectManager::detach(const void* objectID) {
Jiyong Park5970d0a2022-03-08 16:56:13 +0900104 auto i = mObjects.find(objectID);
105 if (i == mObjects.end()) return nullptr;
106 void* value = i->second.object;
107 mObjects.erase(i);
Steven Moreland63a2d512021-06-25 01:10:15 +0000108 return value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109}
110
Devin Moore3faaa002022-07-27 15:54:06 +0000111namespace {
112struct Tag {
113 wp<IBinder> binder;
114};
115} // namespace
116
117static void cleanWeak(const void* /* id */, void* obj, void* /* cookie */) {
118 delete static_cast<Tag*>(obj);
119}
120
121sp<IBinder> BpBinder::ObjectManager::lookupOrCreateWeak(const void* objectID, object_make_func make,
122 const void* makeArgs) {
123 entry_t& e = mObjects[objectID];
124 if (e.object != nullptr) {
125 if (auto attached = static_cast<Tag*>(e.object)->binder.promote()) {
126 return attached;
127 }
128 } else {
129 e.object = new Tag;
130 LOG_ALWAYS_FATAL_IF(!e.object, "no more memory");
131 }
132 sp<IBinder> newObj = make(makeArgs);
133
134 static_cast<Tag*>(e.object)->binder = newObj;
135 e.cleanupCookie = nullptr;
136 e.func = cleanWeak;
137
138 return newObj;
139}
140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141void BpBinder::ObjectManager::kill()
142{
143 const size_t N = mObjects.size();
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700144 ALOGV("Killing %zu objects in manager %p", N, this);
Jiyong Park5970d0a2022-03-08 16:56:13 +0900145 for (auto i : mObjects) {
146 const entry_t& e = i.second;
Yi Kongfdd8da92018-06-07 17:52:27 -0700147 if (e.func != nullptr) {
Jiyong Park5970d0a2022-03-08 16:56:13 +0900148 e.func(i.first, e.object, e.cleanupCookie);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800149 }
150 }
151
152 mObjects.clear();
153}
154
155// ---------------------------------------------------------------------------
156
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000157sp<BpBinder> BpBinder::create(int32_t handle) {
Steven Moreland32150282021-11-12 22:54:53 +0000158 if constexpr (!kEnableKernelIpc) {
159 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
160 return nullptr;
161 }
162
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700163 int32_t trackedUid = -1;
164 if (sCountByUidEnabled) {
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700165 trackedUid = IPCThreadState::self()->getCallingUid();
166 AutoMutex _l(sTrackingLock);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700167 uint32_t trackedValue = sTrackingMap[trackedUid];
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000168 if (trackedValue & LIMIT_REACHED_MASK) [[unlikely]] {
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700169 if (sBinderProxyThrottleCreate) {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700170 return nullptr;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700171 }
Martijn Coenena8d509d2021-09-03 18:06:24 +0200172 trackedValue = trackedValue & COUNTING_VALUE_MASK;
173 uint32_t lastLimitCallbackAt = sLastLimitCallbackMap[trackedUid];
174
175 if (trackedValue > lastLimitCallbackAt &&
Martijn Coenen6711b6d2021-09-23 09:44:29 +0200176 (trackedValue - lastLimitCallbackAt > sBinderProxyCountHighWatermark)) {
Martijn Coenena8d509d2021-09-03 18:06:24 +0200177 ALOGE("Still too many binder proxy objects sent to uid %d from uid %d (%d proxies "
178 "held)",
179 getuid(), trackedUid, trackedValue);
180 if (sLimitCallback) sLimitCallback(trackedUid);
181 sLastLimitCallbackMap[trackedUid] = trackedValue;
182 }
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700183 } else {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700184 if ((trackedValue & COUNTING_VALUE_MASK) >= sBinderProxyCountHighWatermark) {
185 ALOGE("Too many binder proxy objects sent to uid %d from uid %d (%d proxies held)",
186 getuid(), trackedUid, trackedValue);
187 sTrackingMap[trackedUid] |= LIMIT_REACHED_MASK;
188 if (sLimitCallback) sLimitCallback(trackedUid);
Martijn Coenena8d509d2021-09-03 18:06:24 +0200189 sLastLimitCallbackMap[trackedUid] = trackedValue & COUNTING_VALUE_MASK;
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700190 if (sBinderProxyThrottleCreate) {
191 ALOGI("Throttling binder proxy creates from uid %d in uid %d until binder proxy"
192 " count drops below %d",
193 trackedUid, getuid(), sBinderProxyCountLowWatermark);
194 return nullptr;
195 }
196 }
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700197 }
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700198 sTrackingMap[trackedUid]++;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700199 }
Jing Ji4c4ac062023-10-07 15:20:23 -0700200 uint32_t numProxies = sBinderProxyCount.fetch_add(1, std::memory_order_relaxed);
201 uint32_t numLastWarned = sBinderProxyCountWarned.load(std::memory_order_relaxed);
202 uint32_t numNextWarn = numLastWarned + kBinderProxyCountWarnInterval;
203 if (numProxies >= numNextWarn) {
204 // Multiple threads can get here, make sure only one of them gets to
205 // update the warn counter.
206 if (sBinderProxyCountWarned.compare_exchange_strong(numLastWarned,
207 numNextWarn,
208 std::memory_order_relaxed)) {
209 ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
210 }
211 }
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000212 return sp<BpBinder>::make(BinderHandle{handle}, trackedUid);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700213}
214
Steven Moreland5623d1a2021-09-10 15:45:34 -0700215sp<BpBinder> BpBinder::create(const sp<RpcSession>& session, uint64_t address) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000216 LOG_ALWAYS_FATAL_IF(session == nullptr, "BpBinder::create null session");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217
Steven Moreland5553ac42020-11-11 02:14:45 +0000218 // These are not currently tracked, since there is no UID or other
219 // identifier to track them with. However, if similar functionality is
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000220 // needed, session objects keep track of all BpBinder objects on a
221 // per-session basis.
Steven Moreland5553ac42020-11-11 02:14:45 +0000222
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223 return sp<BpBinder>::make(RpcHandle{session, address});
Steven Moreland5553ac42020-11-11 02:14:45 +0000224}
225
226BpBinder::BpBinder(Handle&& handle)
227 : mStability(0),
228 mHandle(handle),
229 mAlive(true),
230 mObitsSent(false),
231 mObituaries(nullptr),
Steven Morelandf2830fe2022-12-21 00:45:34 +0000232 mDescriptorCache(kDescriptorUninit),
Steven Moreland5553ac42020-11-11 02:14:45 +0000233 mTrackedUid(-1) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235}
236
Steven Moreland5553ac42020-11-11 02:14:45 +0000237BpBinder::BpBinder(BinderHandle&& handle, int32_t trackedUid) : BpBinder(Handle(handle)) {
Steven Moreland32150282021-11-12 22:54:53 +0000238 if constexpr (!kEnableKernelIpc) {
239 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
240 return;
241 }
242
Steven Moreland5553ac42020-11-11 02:14:45 +0000243 mTrackedUid = trackedUid;
244
245 ALOGV("Creating BpBinder %p handle %d\n", this, this->binderHandle());
246
247 IPCThreadState::self()->incWeakHandle(this->binderHandle(), this);
248}
249
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000250BpBinder::BpBinder(RpcHandle&& handle) : BpBinder(Handle(handle)) {
251 LOG_ALWAYS_FATAL_IF(rpcSession() == nullptr, "BpBinder created w/o session object");
Steven Moreland5553ac42020-11-11 02:14:45 +0000252}
253
254bool BpBinder::isRpcBinder() const {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000255 return std::holds_alternative<RpcHandle>(mHandle);
Steven Moreland5553ac42020-11-11 02:14:45 +0000256}
257
Steven Moreland5623d1a2021-09-10 15:45:34 -0700258uint64_t BpBinder::rpcAddress() const {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000259 return std::get<RpcHandle>(mHandle).address;
Steven Moreland5553ac42020-11-11 02:14:45 +0000260}
261
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262const sp<RpcSession>& BpBinder::rpcSession() const {
263 return std::get<RpcHandle>(mHandle).session;
Steven Moreland5553ac42020-11-11 02:14:45 +0000264}
265
266int32_t BpBinder::binderHandle() const {
267 return std::get<BinderHandle>(mHandle).handle;
Steven Moreland85180c02019-07-16 14:24:20 -0700268}
269
Devin Mooref6f2e642021-08-05 19:03:47 +0000270std::optional<int32_t> BpBinder::getDebugBinderHandle() const {
271 if (!isRpcBinder()) {
272 return binderHandle();
273 } else {
274 return std::nullopt;
275 }
276}
277
Mathias Agopian83c04462009-05-22 19:00:22 -0700278bool BpBinder::isDescriptorCached() const {
279 Mutex::Autolock _l(mLock);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000280 return mDescriptorCache.c_str() != kDescriptorUninit.c_str();
Mathias Agopian83c04462009-05-22 19:00:22 -0700281}
282
283const String16& BpBinder::getInterfaceDescriptor() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284{
Steven Morelandf2830fe2022-12-21 00:45:34 +0000285 if (!isDescriptorCached()) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000286 sp<BpBinder> thiz = sp<BpBinder>::fromExisting(const_cast<BpBinder*>(this));
Steven Moreland4cf688f2021-03-31 01:48:58 +0000287
288 Parcel data;
289 data.markForBinder(thiz);
290 Parcel reply;
Mathias Agopian83c04462009-05-22 19:00:22 -0700291 // do the IPC without a lock held.
Steven Moreland4cf688f2021-03-31 01:48:58 +0000292 status_t err = thiz->transact(INTERFACE_TRANSACTION, data, &reply);
Mathias Agopian83c04462009-05-22 19:00:22 -0700293 if (err == NO_ERROR) {
294 String16 res(reply.readString16());
295 Mutex::Autolock _l(mLock);
296 // mDescriptorCache could have been assigned while the lock was
297 // released.
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000298 if (mDescriptorCache.c_str() == kDescriptorUninit.c_str()) mDescriptorCache = res;
Mathias Agopian83c04462009-05-22 19:00:22 -0700299 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800300 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700301
Mathias Agopian83c04462009-05-22 19:00:22 -0700302 // we're returning a reference to a non-static object here. Usually this
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700303 // is not something smart to do, however, with binder objects it is
Mathias Agopian83c04462009-05-22 19:00:22 -0700304 // (usually) safe because they are reference-counted.
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700305
Mathias Agopian83c04462009-05-22 19:00:22 -0700306 return mDescriptorCache;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307}
308
309bool BpBinder::isBinderAlive() const
310{
Steven Moreland06074d82020-03-05 23:16:51 +0000311 return mAlive != 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312}
313
314status_t BpBinder::pingBinder()
315{
Steven Moreland5553ac42020-11-11 02:14:45 +0000316 Parcel data;
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000317 data.markForBinder(sp<BpBinder>::fromExisting(this));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318 Parcel reply;
Steven Moreland5553ac42020-11-11 02:14:45 +0000319 return transact(PING_TRANSACTION, data, &reply);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320}
321
Sahil Somani2522b072022-08-08 14:07:47 -0700322status_t BpBinder::startRecordingBinder(const android::base::unique_fd& fd) {
323 Parcel send, reply;
324 send.writeUniqueFileDescriptor(fd);
325 return transact(START_RECORDING_TRANSACTION, send, &reply);
326}
327
328status_t BpBinder::stopRecordingBinder() {
329 Parcel data, reply;
330 data.markForBinder(sp<BpBinder>::fromExisting(this));
331 return transact(STOP_RECORDING_TRANSACTION, data, &reply);
332}
333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334status_t BpBinder::dump(int fd, const Vector<String16>& args)
335{
336 Parcel send;
337 Parcel reply;
338 send.writeFileDescriptor(fd);
339 const size_t numArgs = args.size();
340 send.writeInt32(numArgs);
341 for (size_t i = 0; i < numArgs; i++) {
342 send.writeString16(args[i]);
343 }
344 status_t err = transact(DUMP_TRANSACTION, send, &reply);
345 return err;
346}
347
Jiyong Parkb86c8662018-10-29 23:01:57 +0900348// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349status_t BpBinder::transact(
350 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
351{
352 // Once a binder has died, it will never come back to life.
353 if (mAlive) {
Steven Moreland46b5fea2019-10-15 11:22:18 -0700354 bool privateVendor = flags & FLAG_PRIVATE_VENDOR;
355 // don't send userspace flags to the kernel
Andrei Homescu7cdf5c22022-04-30 03:41:16 +0000356 flags = flags & ~static_cast<uint32_t>(FLAG_PRIVATE_VENDOR);
Steven Moreland46b5fea2019-10-15 11:22:18 -0700357
Steven Moreland6e5a7752019-08-05 20:30:14 -0700358 // user transactions require a given stability level
359 if (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {
360 using android::internal::Stability;
361
Steven Moreland16a41062021-07-23 13:35:25 -0700362 int16_t stability = Stability::getRepr(this);
Steven Moreland89ddfc52020-11-13 02:39:26 +0000363 Stability::Level required = privateVendor ? Stability::VENDOR
364 : Stability::getLocalLevel();
Steven Moreland6e5a7752019-08-05 20:30:14 -0700365
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000366 if (!Stability::check(stability, required)) [[unlikely]] {
Steven Morelandb269b582021-02-10 17:09:11 +0000367 ALOGE("Cannot do a user transaction on a %s binder (%s) in a %s context.",
Steven Moreland16a41062021-07-23 13:35:25 -0700368 Stability::levelString(stability).c_str(),
369 String8(getInterfaceDescriptor()).c_str(),
370 Stability::levelString(required).c_str());
Steven Moreland6e5a7752019-08-05 20:30:14 -0700371 return BAD_TYPE;
372 }
373 }
374
Steven Moreland5553ac42020-11-11 02:14:45 +0000375 status_t status;
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000376 if (isRpcBinder()) [[unlikely]] {
Steven Morelandf5174272021-05-25 00:39:28 +0000377 status = rpcSession()->transact(sp<IBinder>::fromExisting(this), code, data, reply,
378 flags);
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 } else {
Steven Moreland32150282021-11-12 22:54:53 +0000380 if constexpr (!kEnableKernelIpc) {
381 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
382 return INVALID_OPERATION;
383 }
384
Steven Moreland5553ac42020-11-11 02:14:45 +0000385 status = IPCThreadState::self()->transact(binderHandle(), code, data, reply, flags);
386 }
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200387 if (data.dataSize() > LOG_TRANSACTIONS_OVER_SIZE) {
388 Mutex::Autolock _l(mLock);
389 ALOGW("Large outgoing transaction of %zu bytes, interface descriptor %s, code %d",
Steven Morelandf2830fe2022-12-21 00:45:34 +0000390 data.dataSize(), String8(mDescriptorCache).c_str(), code);
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200391 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000392
Steven Moreland06074d82020-03-05 23:16:51 +0000393 if (status == DEAD_OBJECT) mAlive = 0;
Steven Morelanda86a3562019-08-01 23:28:34 +0000394
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395 return status;
396 }
397
398 return DEAD_OBJECT;
399}
400
Jiyong Parkb86c8662018-10-29 23:01:57 +0900401// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800402status_t BpBinder::linkToDeath(
403 const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
404{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000405 if (isRpcBinder()) {
406 if (rpcSession()->getMaxIncomingThreads() < 1) {
Devin Moorebd41dc12023-02-08 17:06:22 +0000407 ALOGE("Cannot register a DeathRecipient without any incoming threads. Need to set max "
408 "incoming threads to a value greater than 0 before calling linkToDeath.");
Devin Moore66d5b7a2022-07-07 21:42:10 +0000409 return INVALID_OPERATION;
410 }
411 } else if constexpr (!kEnableKernelIpc) {
Steven Moreland32150282021-11-12 22:54:53 +0000412 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
413 return INVALID_OPERATION;
Devin Moore66d5b7a2022-07-07 21:42:10 +0000414 } else {
415 if (ProcessState::self()->getThreadPoolMaxTotalThreadCount() == 0) {
416 ALOGW("Linking to death on %s but there are no threads (yet?) listening to incoming "
417 "transactions. See ProcessState::startThreadPool and "
418 "ProcessState::setThreadPoolMaxThreadCount. Generally you should setup the "
419 "binder "
420 "threadpool before other initialization steps.",
421 String8(getInterfaceDescriptor()).c_str());
422 }
Steven Moreland32150282021-11-12 22:54:53 +0000423 }
424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425 Obituary ob;
426 ob.recipient = recipient;
427 ob.cookie = cookie;
428 ob.flags = flags;
429
Yi Kongfdd8da92018-06-07 17:52:27 -0700430 LOG_ALWAYS_FATAL_IF(recipient == nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431 "linkToDeath(): recipient must be non-NULL");
432
433 {
434 AutoMutex _l(mLock);
435
436 if (!mObitsSent) {
437 if (!mObituaries) {
438 mObituaries = new Vector<Obituary>;
439 if (!mObituaries) {
440 return NO_MEMORY;
441 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000442 ALOGV("Requesting death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000443 if (!isRpcBinder()) {
444 if constexpr (kEnableKernelIpc) {
445 getWeakRefs()->incWeak(this);
446 IPCThreadState* self = IPCThreadState::self();
447 self->requestDeathNotification(binderHandle(), this);
448 self->flushCommands();
449 }
450 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451 }
452 ssize_t res = mObituaries->add(ob);
453 return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
454 }
455 }
456
457 return DEAD_OBJECT;
458}
459
Jiyong Parkb86c8662018-10-29 23:01:57 +0900460// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800461status_t BpBinder::unlinkToDeath(
462 const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
463 wp<DeathRecipient>* outRecipient)
464{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000465 if (!kEnableKernelIpc && !isRpcBinder()) {
Steven Moreland32150282021-11-12 22:54:53 +0000466 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
467 return INVALID_OPERATION;
468 }
469
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470 AutoMutex _l(mLock);
471
472 if (mObitsSent) {
473 return DEAD_OBJECT;
474 }
475
476 const size_t N = mObituaries ? mObituaries->size() : 0;
477 for (size_t i=0; i<N; i++) {
478 const Obituary& obit = mObituaries->itemAt(i);
479 if ((obit.recipient == recipient
Yi Kongfdd8da92018-06-07 17:52:27 -0700480 || (recipient == nullptr && obit.cookie == cookie))
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800481 && obit.flags == flags) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700482 if (outRecipient != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800483 *outRecipient = mObituaries->itemAt(i).recipient;
484 }
485 mObituaries->removeAt(i);
486 if (mObituaries->size() == 0) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000487 ALOGV("Clearing death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000488 if (!isRpcBinder()) {
489 if constexpr (kEnableKernelIpc) {
490 IPCThreadState* self = IPCThreadState::self();
491 self->clearDeathNotification(binderHandle(), this);
492 self->flushCommands();
493 }
494 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800495 delete mObituaries;
Yi Kongfdd8da92018-06-07 17:52:27 -0700496 mObituaries = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800497 }
498 return NO_ERROR;
499 }
500 }
501
502 return NAME_NOT_FOUND;
503}
504
505void BpBinder::sendObituary()
506{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000507 if (!kEnableKernelIpc && !isRpcBinder()) {
Steven Moreland32150282021-11-12 22:54:53 +0000508 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
509 return;
510 }
511
Steven Moreland5553ac42020-11-11 02:14:45 +0000512 ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n", this, binderHandle(),
513 mObitsSent ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800514
Steven Moreland06074d82020-03-05 23:16:51 +0000515 mAlive = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516 if (mObitsSent) return;
517
518 mLock.lock();
519 Vector<Obituary>* obits = mObituaries;
Yi Kongfdd8da92018-06-07 17:52:27 -0700520 if(obits != nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 ALOGV("Clearing sent death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000522 if (!isRpcBinder()) {
523 if constexpr (kEnableKernelIpc) {
524 IPCThreadState* self = IPCThreadState::self();
525 self->clearDeathNotification(binderHandle(), this);
526 self->flushCommands();
527 }
528 }
Yi Kongfdd8da92018-06-07 17:52:27 -0700529 mObituaries = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530 }
Steven Moreland06074d82020-03-05 23:16:51 +0000531 mObitsSent = 1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532 mLock.unlock();
533
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700534 ALOGV("Reporting death of proxy %p for %zu recipients\n",
535 this, obits ? obits->size() : 0U);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800536
Yi Kongfdd8da92018-06-07 17:52:27 -0700537 if (obits != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538 const size_t N = obits->size();
539 for (size_t i=0; i<N; i++) {
540 reportOneDeath(obits->itemAt(i));
541 }
542
543 delete obits;
544 }
545}
546
547void BpBinder::reportOneDeath(const Obituary& obit)
548{
549 sp<DeathRecipient> recipient = obit.recipient.promote();
Steve Block6807e592011-10-20 11:56:00 +0100550 ALOGV("Reporting death to recipient: %p\n", recipient.get());
Yi Kongfdd8da92018-06-07 17:52:27 -0700551 if (recipient == nullptr) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000553 recipient->binderDied(wp<BpBinder>::fromExisting(this));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554}
555
Steven Moreland63a2d512021-06-25 01:10:15 +0000556void* BpBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
557 object_cleanup_func func) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800558 AutoMutex _l(mLock);
Steve Block6807e592011-10-20 11:56:00 +0100559 ALOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);
Steven Moreland63a2d512021-06-25 01:10:15 +0000560 return mObjects.attach(objectID, object, cleanupCookie, func);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800561}
562
563void* BpBinder::findObject(const void* objectID) const
564{
565 AutoMutex _l(mLock);
566 return mObjects.find(objectID);
567}
568
Steven Moreland63a2d512021-06-25 01:10:15 +0000569void* BpBinder::detachObject(const void* objectID) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800570 AutoMutex _l(mLock);
Steven Moreland63a2d512021-06-25 01:10:15 +0000571 return mObjects.detach(objectID);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800572}
573
Steven Moreland9e759e82021-06-25 21:30:23 +0000574void BpBinder::withLock(const std::function<void()>& doWithLock) {
575 AutoMutex _l(mLock);
576 doWithLock();
577}
578
Devin Moore3faaa002022-07-27 15:54:06 +0000579sp<IBinder> BpBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
580 const void* makeArgs) {
581 AutoMutex _l(mLock);
582 return mObjects.lookupOrCreateWeak(objectID, make, makeArgs);
583}
584
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585BpBinder* BpBinder::remoteBinder()
586{
587 return this;
588}
589
Steven Moreland32150282021-11-12 22:54:53 +0000590BpBinder::~BpBinder() {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000591 if (isRpcBinder()) [[unlikely]] {
592 return;
593 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800594
Steven Moreland32150282021-11-12 22:54:53 +0000595 if constexpr (!kEnableKernelIpc) {
596 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
597 return;
598 }
599
600 ALOGV("Destroying BpBinder %p handle %d\n", this, binderHandle());
601
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800602 IPCThreadState* ipc = IPCThreadState::self();
603
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700604 if (mTrackedUid >= 0) {
605 AutoMutex _l(sTrackingLock);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700606 uint32_t trackedValue = sTrackingMap[mTrackedUid];
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000607 if ((trackedValue & COUNTING_VALUE_MASK) == 0) [[unlikely]] {
Steven Moreland5553ac42020-11-11 02:14:45 +0000608 ALOGE("Unexpected Binder Proxy tracking decrement in %p handle %d\n", this,
609 binderHandle());
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700610 } else {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000611 auto countingValue = trackedValue & COUNTING_VALUE_MASK;
612 if ((trackedValue & LIMIT_REACHED_MASK) &&
613 (countingValue <= sBinderProxyCountLowWatermark)) [[unlikely]] {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700614 ALOGI("Limit reached bit reset for uid %d (fewer than %d proxies from uid %d held)",
Martijn Coenena8d509d2021-09-03 18:06:24 +0200615 getuid(), sBinderProxyCountLowWatermark, mTrackedUid);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700616 sTrackingMap[mTrackedUid] &= ~LIMIT_REACHED_MASK;
Martijn Coenena8d509d2021-09-03 18:06:24 +0200617 sLastLimitCallbackMap.erase(mTrackedUid);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700618 }
619 if (--sTrackingMap[mTrackedUid] == 0) {
620 sTrackingMap.erase(mTrackedUid);
621 }
622 }
623 }
Jing Ji4c4ac062023-10-07 15:20:23 -0700624 --sBinderProxyCount;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700625
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800626 if (ipc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000627 ipc->expungeHandle(binderHandle(), this);
628 ipc->decWeakHandle(binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800629 }
630}
631
Steven Moreland32150282021-11-12 22:54:53 +0000632void BpBinder::onFirstRef() {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000633 if (isRpcBinder()) [[unlikely]] {
634 return;
635 }
Steven Moreland32150282021-11-12 22:54:53 +0000636
637 if constexpr (!kEnableKernelIpc) {
638 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
639 return;
640 }
641
642 ALOGV("onFirstRef BpBinder %p handle %d\n", this, binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800643 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 if (ipc) ipc->incStrongHandle(binderHandle(), this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645}
646
Steven Moreland32150282021-11-12 22:54:53 +0000647void BpBinder::onLastStrongRef(const void* /*id*/) {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000648 if (isRpcBinder()) [[unlikely]] {
Steven Moreland4f622fe2021-09-13 17:38:09 -0700649 (void)rpcSession()->sendDecStrong(this);
Steven Moreland5553ac42020-11-11 02:14:45 +0000650 return;
651 }
Steven Moreland32150282021-11-12 22:54:53 +0000652
653 if constexpr (!kEnableKernelIpc) {
654 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
655 return;
656 }
657
658 ALOGV("onLastStrongRef BpBinder %p handle %d\n", this, binderHandle());
Steve Block6807e592011-10-20 11:56:00 +0100659 IF_ALOGV() {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800660 printRefs();
661 }
662 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000663 if (ipc) ipc->decStrongHandle(binderHandle());
Steven Moreland80d23932019-06-07 12:43:27 -0700664
665 mLock.lock();
666 Vector<Obituary>* obits = mObituaries;
667 if(obits != nullptr) {
668 if (!obits->isEmpty()) {
Steven Moreland70fcb4e2019-12-13 17:28:58 -0800669 ALOGI("onLastStrongRef automatically unlinking death recipients: %s",
Steven Morelandf2830fe2022-12-21 00:45:34 +0000670 String8(mDescriptorCache).c_str());
Steven Moreland80d23932019-06-07 12:43:27 -0700671 }
672
Steven Moreland5553ac42020-11-11 02:14:45 +0000673 if (ipc) ipc->clearDeathNotification(binderHandle(), this);
Steven Moreland80d23932019-06-07 12:43:27 -0700674 mObituaries = nullptr;
675 }
676 mLock.unlock();
677
678 if (obits != nullptr) {
679 // XXX Should we tell any remaining DeathRecipient
680 // objects that the last strong ref has gone away, so they
681 // are no longer linked?
682 delete obits;
683 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800684}
685
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800686bool BpBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800687{
Steven Moreland5553ac42020-11-11 02:14:45 +0000688 // RPC binder doesn't currently support inc from weak binders
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000689 if (isRpcBinder()) [[unlikely]] {
690 return false;
691 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000692
Steven Moreland32150282021-11-12 22:54:53 +0000693 if constexpr (!kEnableKernelIpc) {
694 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
695 return false;
696 }
697
Steven Moreland5553ac42020-11-11 02:14:45 +0000698 ALOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800699 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000700 return ipc ? ipc->attemptIncStrongHandle(binderHandle()) == NO_ERROR : false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701}
702
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700703uint32_t BpBinder::getBinderProxyCount(uint32_t uid)
704{
705 AutoMutex _l(sTrackingLock);
706 auto it = sTrackingMap.find(uid);
707 if (it != sTrackingMap.end()) {
708 return it->second & COUNTING_VALUE_MASK;
709 }
710 return 0;
711}
712
Jing Ji4c4ac062023-10-07 15:20:23 -0700713uint32_t BpBinder::getBinderProxyCount()
714{
715 return sBinderProxyCount.load();
716}
717
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700718void BpBinder::getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts)
719{
720 AutoMutex _l(sTrackingLock);
721 uids.setCapacity(sTrackingMap.size());
722 counts.setCapacity(sTrackingMap.size());
723 for (const auto& it : sTrackingMap) {
724 uids.push_back(it.first);
725 counts.push_back(it.second & COUNTING_VALUE_MASK);
726 }
727}
728
729void BpBinder::enableCountByUid() { sCountByUidEnabled.store(true); }
730void BpBinder::disableCountByUid() { sCountByUidEnabled.store(false); }
731void BpBinder::setCountByUidEnabled(bool enable) { sCountByUidEnabled.store(enable); }
732
733void BpBinder::setLimitCallback(binder_proxy_limit_callback cb) {
734 AutoMutex _l(sTrackingLock);
735 sLimitCallback = cb;
736}
737
738void BpBinder::setBinderProxyCountWatermarks(int high, int low) {
739 AutoMutex _l(sTrackingLock);
740 sBinderProxyCountHighWatermark = high;
741 sBinderProxyCountLowWatermark = low;
742}
743
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800744// ---------------------------------------------------------------------------
745
Steven Moreland61ff8492019-09-26 16:05:45 -0700746} // namespace android