blob: 810285920a0c46ed8289cd419efcc52f8e16d45a [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
27#include <stdio.h>
28
Steven Moreland32150282021-11-12 22:54:53 +000029#include "BuildFlags.h"
30
Sahil Somani2522b072022-08-08 14:07:47 -070031#include <android-base/file.h>
32
Steve Block6807e592011-10-20 11:56:00 +010033//#undef ALOGV
34//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
36namespace android {
37
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070038using android::binder::unique_fd;
39
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080040// ---------------------------------------------------------------------------
41
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -070042RpcMutex BpBinder::sTrackingLock;
Martijn Coenena8d509d2021-09-03 18:06:24 +020043std::unordered_map<int32_t, uint32_t> BpBinder::sTrackingMap;
44std::unordered_map<int32_t, uint32_t> BpBinder::sLastLimitCallbackMap;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070045int BpBinder::sNumTrackedUids = 0;
46std::atomic_bool BpBinder::sCountByUidEnabled(false);
47binder_proxy_limit_callback BpBinder::sLimitCallback;
48bool BpBinder::sBinderProxyThrottleCreate = false;
49
Steven Moreland847d8c52023-05-02 23:56:58 +000050static StaticString16 kDescriptorUninit(u"");
Steven Morelandf2830fe2022-12-21 00:45:34 +000051
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070052// Arbitrarily high value that probably distinguishes a bad behaving app
53uint32_t BpBinder::sBinderProxyCountHighWatermark = 2500;
54// Another arbitrary value a binder count needs to drop below before another callback will be called
55uint32_t BpBinder::sBinderProxyCountLowWatermark = 2000;
56
Jing Ji4c4ac062023-10-07 15:20:23 -070057std::atomic<uint32_t> BpBinder::sBinderProxyCount(0);
58std::atomic<uint32_t> BpBinder::sBinderProxyCountWarned(0);
59
60static constexpr uint32_t kBinderProxyCountWarnInterval = 5000;
61
Martijn Coenen1cad19c2021-10-04 09:19:01 +020062// Log any transactions for which the data exceeds this size
63#define LOG_TRANSACTIONS_OVER_SIZE (300 * 1024)
64
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070065enum {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -070066 LIMIT_REACHED_MASK = 0x80000000, // A flag denoting that the limit has been reached
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -070067 COUNTING_VALUE_MASK = 0x7FFFFFFF, // A mask of the remaining bits for the count value
68};
69
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070BpBinder::ObjectManager::ObjectManager()
71{
72}
73
74BpBinder::ObjectManager::~ObjectManager()
75{
76 kill();
77}
78
Steven Moreland63a2d512021-06-25 01:10:15 +000079void* BpBinder::ObjectManager::attach(const void* objectID, void* object, void* cleanupCookie,
80 IBinder::object_cleanup_func func) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081 entry_t e;
82 e.object = object;
83 e.cleanupCookie = cleanupCookie;
84 e.func = func;
85
Jiyong Park5970d0a2022-03-08 16:56:13 +090086 if (mObjects.find(objectID) != mObjects.end()) {
Steven Moreland63a2d512021-06-25 01:10:15 +000087 ALOGI("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object "
88 "ID already in use",
89 objectID, this, object);
Jiyong Park5970d0a2022-03-08 16:56:13 +090090 return mObjects[objectID].object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091 }
92
Jiyong Park5970d0a2022-03-08 16:56:13 +090093 mObjects.insert({objectID, e});
Steven Moreland63a2d512021-06-25 01:10:15 +000094 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095}
96
97void* BpBinder::ObjectManager::find(const void* objectID) const
98{
Jiyong Park5970d0a2022-03-08 16:56:13 +090099 auto i = mObjects.find(objectID);
100 if (i == mObjects.end()) return nullptr;
101 return i->second.object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102}
103
Steven Moreland63a2d512021-06-25 01:10:15 +0000104void* BpBinder::ObjectManager::detach(const void* objectID) {
Jiyong Park5970d0a2022-03-08 16:56:13 +0900105 auto i = mObjects.find(objectID);
106 if (i == mObjects.end()) return nullptr;
107 void* value = i->second.object;
108 mObjects.erase(i);
Steven Moreland63a2d512021-06-25 01:10:15 +0000109 return value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110}
111
Devin Moore3faaa002022-07-27 15:54:06 +0000112namespace {
113struct Tag {
114 wp<IBinder> binder;
115};
116} // namespace
117
118static void cleanWeak(const void* /* id */, void* obj, void* /* cookie */) {
119 delete static_cast<Tag*>(obj);
120}
121
122sp<IBinder> BpBinder::ObjectManager::lookupOrCreateWeak(const void* objectID, object_make_func make,
123 const void* makeArgs) {
124 entry_t& e = mObjects[objectID];
125 if (e.object != nullptr) {
126 if (auto attached = static_cast<Tag*>(e.object)->binder.promote()) {
127 return attached;
128 }
129 } else {
130 e.object = new Tag;
131 LOG_ALWAYS_FATAL_IF(!e.object, "no more memory");
132 }
133 sp<IBinder> newObj = make(makeArgs);
134
135 static_cast<Tag*>(e.object)->binder = newObj;
136 e.cleanupCookie = nullptr;
137 e.func = cleanWeak;
138
139 return newObj;
140}
141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142void BpBinder::ObjectManager::kill()
143{
144 const size_t N = mObjects.size();
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700145 ALOGV("Killing %zu objects in manager %p", N, this);
Jiyong Park5970d0a2022-03-08 16:56:13 +0900146 for (auto i : mObjects) {
147 const entry_t& e = i.second;
Yi Kongfdd8da92018-06-07 17:52:27 -0700148 if (e.func != nullptr) {
Jiyong Park5970d0a2022-03-08 16:56:13 +0900149 e.func(i.first, e.object, e.cleanupCookie);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 }
151 }
152
153 mObjects.clear();
154}
155
156// ---------------------------------------------------------------------------
157
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000158sp<BpBinder> BpBinder::create(int32_t handle) {
Steven Moreland32150282021-11-12 22:54:53 +0000159 if constexpr (!kEnableKernelIpc) {
160 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
161 return nullptr;
162 }
163
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700164 int32_t trackedUid = -1;
165 if (sCountByUidEnabled) {
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700166 trackedUid = IPCThreadState::self()->getCallingUid();
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700167 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700168 uint32_t trackedValue = sTrackingMap[trackedUid];
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000169 if (trackedValue & LIMIT_REACHED_MASK) [[unlikely]] {
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700170 if (sBinderProxyThrottleCreate) {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700171 return nullptr;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700172 }
Martijn Coenena8d509d2021-09-03 18:06:24 +0200173 trackedValue = trackedValue & COUNTING_VALUE_MASK;
174 uint32_t lastLimitCallbackAt = sLastLimitCallbackMap[trackedUid];
175
176 if (trackedValue > lastLimitCallbackAt &&
Martijn Coenen6711b6d2021-09-23 09:44:29 +0200177 (trackedValue - lastLimitCallbackAt > sBinderProxyCountHighWatermark)) {
Martijn Coenena8d509d2021-09-03 18:06:24 +0200178 ALOGE("Still too many binder proxy objects sent to uid %d from uid %d (%d proxies "
179 "held)",
180 getuid(), trackedUid, trackedValue);
181 if (sLimitCallback) sLimitCallback(trackedUid);
182 sLastLimitCallbackMap[trackedUid] = trackedValue;
183 }
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700184 } else {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700185 if ((trackedValue & COUNTING_VALUE_MASK) >= sBinderProxyCountHighWatermark) {
186 ALOGE("Too many binder proxy objects sent to uid %d from uid %d (%d proxies held)",
187 getuid(), trackedUid, trackedValue);
188 sTrackingMap[trackedUid] |= LIMIT_REACHED_MASK;
189 if (sLimitCallback) sLimitCallback(trackedUid);
Martijn Coenena8d509d2021-09-03 18:06:24 +0200190 sLastLimitCallbackMap[trackedUid] = trackedValue & COUNTING_VALUE_MASK;
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700191 if (sBinderProxyThrottleCreate) {
192 ALOGI("Throttling binder proxy creates from uid %d in uid %d until binder proxy"
193 " count drops below %d",
194 trackedUid, getuid(), sBinderProxyCountLowWatermark);
195 return nullptr;
196 }
197 }
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700198 }
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700199 sTrackingMap[trackedUid]++;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700200 }
Jing Ji4c4ac062023-10-07 15:20:23 -0700201 uint32_t numProxies = sBinderProxyCount.fetch_add(1, std::memory_order_relaxed);
202 uint32_t numLastWarned = sBinderProxyCountWarned.load(std::memory_order_relaxed);
203 uint32_t numNextWarn = numLastWarned + kBinderProxyCountWarnInterval;
204 if (numProxies >= numNextWarn) {
205 // Multiple threads can get here, make sure only one of them gets to
206 // update the warn counter.
207 if (sBinderProxyCountWarned.compare_exchange_strong(numLastWarned,
208 numNextWarn,
209 std::memory_order_relaxed)) {
210 ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
211 }
212 }
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000213 return sp<BpBinder>::make(BinderHandle{handle}, trackedUid);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700214}
215
Steven Moreland5623d1a2021-09-10 15:45:34 -0700216sp<BpBinder> BpBinder::create(const sp<RpcSession>& session, uint64_t address) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000217 LOG_ALWAYS_FATAL_IF(session == nullptr, "BpBinder::create null session");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218
Steven Moreland5553ac42020-11-11 02:14:45 +0000219 // These are not currently tracked, since there is no UID or other
220 // identifier to track them with. However, if similar functionality is
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000221 // needed, session objects keep track of all BpBinder objects on a
222 // per-session basis.
Steven Moreland5553ac42020-11-11 02:14:45 +0000223
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000224 return sp<BpBinder>::make(RpcHandle{session, address});
Steven Moreland5553ac42020-11-11 02:14:45 +0000225}
226
227BpBinder::BpBinder(Handle&& handle)
228 : mStability(0),
229 mHandle(handle),
230 mAlive(true),
231 mObitsSent(false),
232 mObituaries(nullptr),
Steven Morelandf2830fe2022-12-21 00:45:34 +0000233 mDescriptorCache(kDescriptorUninit),
Steven Moreland5553ac42020-11-11 02:14:45 +0000234 mTrackedUid(-1) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236}
237
Steven Moreland5553ac42020-11-11 02:14:45 +0000238BpBinder::BpBinder(BinderHandle&& handle, int32_t trackedUid) : BpBinder(Handle(handle)) {
Steven Moreland32150282021-11-12 22:54:53 +0000239 if constexpr (!kEnableKernelIpc) {
240 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
241 return;
242 }
243
Steven Moreland5553ac42020-11-11 02:14:45 +0000244 mTrackedUid = trackedUid;
245
246 ALOGV("Creating BpBinder %p handle %d\n", this, this->binderHandle());
247
248 IPCThreadState::self()->incWeakHandle(this->binderHandle(), this);
249}
250
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000251BpBinder::BpBinder(RpcHandle&& handle) : BpBinder(Handle(handle)) {
252 LOG_ALWAYS_FATAL_IF(rpcSession() == nullptr, "BpBinder created w/o session object");
Steven Moreland5553ac42020-11-11 02:14:45 +0000253}
254
255bool BpBinder::isRpcBinder() const {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000256 return std::holds_alternative<RpcHandle>(mHandle);
Steven Moreland5553ac42020-11-11 02:14:45 +0000257}
258
Steven Moreland5623d1a2021-09-10 15:45:34 -0700259uint64_t BpBinder::rpcAddress() const {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000260 return std::get<RpcHandle>(mHandle).address;
Steven Moreland5553ac42020-11-11 02:14:45 +0000261}
262
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000263const sp<RpcSession>& BpBinder::rpcSession() const {
264 return std::get<RpcHandle>(mHandle).session;
Steven Moreland5553ac42020-11-11 02:14:45 +0000265}
266
267int32_t BpBinder::binderHandle() const {
268 return std::get<BinderHandle>(mHandle).handle;
Steven Moreland85180c02019-07-16 14:24:20 -0700269}
270
Devin Mooref6f2e642021-08-05 19:03:47 +0000271std::optional<int32_t> BpBinder::getDebugBinderHandle() const {
272 if (!isRpcBinder()) {
273 return binderHandle();
274 } else {
275 return std::nullopt;
276 }
277}
278
Mathias Agopian83c04462009-05-22 19:00:22 -0700279bool BpBinder::isDescriptorCached() const {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700280 RpcMutexUniqueLock _l(mLock);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000281 return mDescriptorCache.c_str() != kDescriptorUninit.c_str();
Mathias Agopian83c04462009-05-22 19:00:22 -0700282}
283
284const String16& BpBinder::getInterfaceDescriptor() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285{
Steven Morelandf2830fe2022-12-21 00:45:34 +0000286 if (!isDescriptorCached()) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000287 sp<BpBinder> thiz = sp<BpBinder>::fromExisting(const_cast<BpBinder*>(this));
Steven Moreland4cf688f2021-03-31 01:48:58 +0000288
289 Parcel data;
290 data.markForBinder(thiz);
291 Parcel reply;
Mathias Agopian83c04462009-05-22 19:00:22 -0700292 // do the IPC without a lock held.
Steven Moreland4cf688f2021-03-31 01:48:58 +0000293 status_t err = thiz->transact(INTERFACE_TRANSACTION, data, &reply);
Mathias Agopian83c04462009-05-22 19:00:22 -0700294 if (err == NO_ERROR) {
295 String16 res(reply.readString16());
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700296 RpcMutexUniqueLock _l(mLock);
Mathias Agopian83c04462009-05-22 19:00:22 -0700297 // mDescriptorCache could have been assigned while the lock was
298 // released.
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000299 if (mDescriptorCache.c_str() == kDescriptorUninit.c_str()) mDescriptorCache = res;
Mathias Agopian83c04462009-05-22 19:00:22 -0700300 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700302
Mathias Agopian83c04462009-05-22 19:00:22 -0700303 // we're returning a reference to a non-static object here. Usually this
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700304 // is not something smart to do, however, with binder objects it is
Mathias Agopian83c04462009-05-22 19:00:22 -0700305 // (usually) safe because they are reference-counted.
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700306
Mathias Agopian83c04462009-05-22 19:00:22 -0700307 return mDescriptorCache;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308}
309
310bool BpBinder::isBinderAlive() const
311{
Steven Moreland06074d82020-03-05 23:16:51 +0000312 return mAlive != 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800313}
314
315status_t BpBinder::pingBinder()
316{
Steven Moreland5553ac42020-11-11 02:14:45 +0000317 Parcel data;
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000318 data.markForBinder(sp<BpBinder>::fromExisting(this));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319 Parcel reply;
Steven Moreland5553ac42020-11-11 02:14:45 +0000320 return transact(PING_TRANSACTION, data, &reply);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321}
322
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700323status_t BpBinder::startRecordingBinder(const unique_fd& fd) {
Sahil Somani2522b072022-08-08 14:07:47 -0700324 Parcel send, reply;
325 send.writeUniqueFileDescriptor(fd);
326 return transact(START_RECORDING_TRANSACTION, send, &reply);
327}
328
329status_t BpBinder::stopRecordingBinder() {
330 Parcel data, reply;
331 data.markForBinder(sp<BpBinder>::fromExisting(this));
332 return transact(STOP_RECORDING_TRANSACTION, data, &reply);
333}
334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335status_t BpBinder::dump(int fd, const Vector<String16>& args)
336{
337 Parcel send;
338 Parcel reply;
339 send.writeFileDescriptor(fd);
340 const size_t numArgs = args.size();
341 send.writeInt32(numArgs);
342 for (size_t i = 0; i < numArgs; i++) {
343 send.writeString16(args[i]);
344 }
345 status_t err = transact(DUMP_TRANSACTION, send, &reply);
346 return err;
347}
348
Jiyong Parkb86c8662018-10-29 23:01:57 +0900349// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350status_t BpBinder::transact(
351 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
352{
353 // Once a binder has died, it will never come back to life.
354 if (mAlive) {
Steven Moreland46b5fea2019-10-15 11:22:18 -0700355 bool privateVendor = flags & FLAG_PRIVATE_VENDOR;
356 // don't send userspace flags to the kernel
Andrei Homescu7cdf5c22022-04-30 03:41:16 +0000357 flags = flags & ~static_cast<uint32_t>(FLAG_PRIVATE_VENDOR);
Steven Moreland46b5fea2019-10-15 11:22:18 -0700358
Steven Moreland6e5a7752019-08-05 20:30:14 -0700359 // user transactions require a given stability level
360 if (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {
361 using android::internal::Stability;
362
Steven Moreland16a41062021-07-23 13:35:25 -0700363 int16_t stability = Stability::getRepr(this);
Steven Moreland89ddfc52020-11-13 02:39:26 +0000364 Stability::Level required = privateVendor ? Stability::VENDOR
365 : Stability::getLocalLevel();
Steven Moreland6e5a7752019-08-05 20:30:14 -0700366
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000367 if (!Stability::check(stability, required)) [[unlikely]] {
Steven Morelandb269b582021-02-10 17:09:11 +0000368 ALOGE("Cannot do a user transaction on a %s binder (%s) in a %s context.",
Steven Moreland16a41062021-07-23 13:35:25 -0700369 Stability::levelString(stability).c_str(),
370 String8(getInterfaceDescriptor()).c_str(),
371 Stability::levelString(required).c_str());
Steven Moreland6e5a7752019-08-05 20:30:14 -0700372 return BAD_TYPE;
373 }
374 }
375
Steven Moreland5553ac42020-11-11 02:14:45 +0000376 status_t status;
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000377 if (isRpcBinder()) [[unlikely]] {
Steven Morelandf5174272021-05-25 00:39:28 +0000378 status = rpcSession()->transact(sp<IBinder>::fromExisting(this), code, data, reply,
379 flags);
Steven Moreland5553ac42020-11-11 02:14:45 +0000380 } else {
Steven Moreland32150282021-11-12 22:54:53 +0000381 if constexpr (!kEnableKernelIpc) {
382 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
383 return INVALID_OPERATION;
384 }
385
Steven Moreland5553ac42020-11-11 02:14:45 +0000386 status = IPCThreadState::self()->transact(binderHandle(), code, data, reply, flags);
387 }
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200388 if (data.dataSize() > LOG_TRANSACTIONS_OVER_SIZE) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700389 RpcMutexUniqueLock _l(mLock);
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200390 ALOGW("Large outgoing transaction of %zu bytes, interface descriptor %s, code %d",
Steven Morelandf2830fe2022-12-21 00:45:34 +0000391 data.dataSize(), String8(mDescriptorCache).c_str(), code);
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200392 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000393
Steven Moreland06074d82020-03-05 23:16:51 +0000394 if (status == DEAD_OBJECT) mAlive = 0;
Steven Morelanda86a3562019-08-01 23:28:34 +0000395
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 return status;
397 }
398
399 return DEAD_OBJECT;
400}
401
Jiyong Parkb86c8662018-10-29 23:01:57 +0900402// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800403status_t BpBinder::linkToDeath(
404 const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
405{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000406 if (isRpcBinder()) {
407 if (rpcSession()->getMaxIncomingThreads() < 1) {
Devin Moorebd41dc12023-02-08 17:06:22 +0000408 ALOGE("Cannot register a DeathRecipient without any incoming threads. Need to set max "
409 "incoming threads to a value greater than 0 before calling linkToDeath.");
Devin Moore66d5b7a2022-07-07 21:42:10 +0000410 return INVALID_OPERATION;
411 }
412 } else if constexpr (!kEnableKernelIpc) {
Steven Moreland32150282021-11-12 22:54:53 +0000413 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
414 return INVALID_OPERATION;
Devin Moore66d5b7a2022-07-07 21:42:10 +0000415 } else {
416 if (ProcessState::self()->getThreadPoolMaxTotalThreadCount() == 0) {
417 ALOGW("Linking to death on %s but there are no threads (yet?) listening to incoming "
418 "transactions. See ProcessState::startThreadPool and "
419 "ProcessState::setThreadPoolMaxThreadCount. Generally you should setup the "
420 "binder "
421 "threadpool before other initialization steps.",
422 String8(getInterfaceDescriptor()).c_str());
423 }
Steven Moreland32150282021-11-12 22:54:53 +0000424 }
425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426 Obituary ob;
427 ob.recipient = recipient;
428 ob.cookie = cookie;
429 ob.flags = flags;
430
Yi Kongfdd8da92018-06-07 17:52:27 -0700431 LOG_ALWAYS_FATAL_IF(recipient == nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432 "linkToDeath(): recipient must be non-NULL");
433
434 {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700435 RpcMutexUniqueLock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436
437 if (!mObitsSent) {
438 if (!mObituaries) {
439 mObituaries = new Vector<Obituary>;
440 if (!mObituaries) {
441 return NO_MEMORY;
442 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 ALOGV("Requesting death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000444 if (!isRpcBinder()) {
445 if constexpr (kEnableKernelIpc) {
446 getWeakRefs()->incWeak(this);
447 IPCThreadState* self = IPCThreadState::self();
448 self->requestDeathNotification(binderHandle(), this);
449 self->flushCommands();
450 }
451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452 }
453 ssize_t res = mObituaries->add(ob);
454 return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
455 }
456 }
457
458 return DEAD_OBJECT;
459}
460
Jiyong Parkb86c8662018-10-29 23:01:57 +0900461// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800462status_t BpBinder::unlinkToDeath(
463 const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
464 wp<DeathRecipient>* outRecipient)
465{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000466 if (!kEnableKernelIpc && !isRpcBinder()) {
Steven Moreland32150282021-11-12 22:54:53 +0000467 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
468 return INVALID_OPERATION;
469 }
470
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700471 RpcMutexUniqueLock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472
473 if (mObitsSent) {
474 return DEAD_OBJECT;
475 }
476
477 const size_t N = mObituaries ? mObituaries->size() : 0;
478 for (size_t i=0; i<N; i++) {
479 const Obituary& obit = mObituaries->itemAt(i);
480 if ((obit.recipient == recipient
Yi Kongfdd8da92018-06-07 17:52:27 -0700481 || (recipient == nullptr && obit.cookie == cookie))
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800482 && obit.flags == flags) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700483 if (outRecipient != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800484 *outRecipient = mObituaries->itemAt(i).recipient;
485 }
486 mObituaries->removeAt(i);
487 if (mObituaries->size() == 0) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000488 ALOGV("Clearing death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000489 if (!isRpcBinder()) {
490 if constexpr (kEnableKernelIpc) {
491 IPCThreadState* self = IPCThreadState::self();
492 self->clearDeathNotification(binderHandle(), this);
493 self->flushCommands();
494 }
495 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800496 delete mObituaries;
Yi Kongfdd8da92018-06-07 17:52:27 -0700497 mObituaries = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498 }
499 return NO_ERROR;
500 }
501 }
502
503 return NAME_NOT_FOUND;
504}
505
506void BpBinder::sendObituary()
507{
Devin Moore66d5b7a2022-07-07 21:42:10 +0000508 if (!kEnableKernelIpc && !isRpcBinder()) {
Steven Moreland32150282021-11-12 22:54:53 +0000509 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
510 return;
511 }
512
Steven Moreland5553ac42020-11-11 02:14:45 +0000513 ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n", this, binderHandle(),
514 mObitsSent ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515
Steven Moreland06074d82020-03-05 23:16:51 +0000516 mAlive = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800517 if (mObitsSent) return;
518
519 mLock.lock();
520 Vector<Obituary>* obits = mObituaries;
Yi Kongfdd8da92018-06-07 17:52:27 -0700521 if(obits != nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000522 ALOGV("Clearing sent death notification: %p handle %d\n", this, binderHandle());
Devin Moore66d5b7a2022-07-07 21:42:10 +0000523 if (!isRpcBinder()) {
524 if constexpr (kEnableKernelIpc) {
525 IPCThreadState* self = IPCThreadState::self();
526 self->clearDeathNotification(binderHandle(), this);
527 self->flushCommands();
528 }
529 }
Yi Kongfdd8da92018-06-07 17:52:27 -0700530 mObituaries = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531 }
Steven Moreland06074d82020-03-05 23:16:51 +0000532 mObitsSent = 1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800533 mLock.unlock();
534
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700535 ALOGV("Reporting death of proxy %p for %zu recipients\n",
536 this, obits ? obits->size() : 0U);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537
Yi Kongfdd8da92018-06-07 17:52:27 -0700538 if (obits != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800539 const size_t N = obits->size();
540 for (size_t i=0; i<N; i++) {
541 reportOneDeath(obits->itemAt(i));
542 }
543
544 delete obits;
545 }
546}
547
548void BpBinder::reportOneDeath(const Obituary& obit)
549{
550 sp<DeathRecipient> recipient = obit.recipient.promote();
Steve Block6807e592011-10-20 11:56:00 +0100551 ALOGV("Reporting death to recipient: %p\n", recipient.get());
Yi Kongfdd8da92018-06-07 17:52:27 -0700552 if (recipient == nullptr) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000554 recipient->binderDied(wp<BpBinder>::fromExisting(this));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555}
556
Steven Moreland63a2d512021-06-25 01:10:15 +0000557void* BpBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
558 object_cleanup_func func) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700559 RpcMutexUniqueLock _l(mLock);
Steve Block6807e592011-10-20 11:56:00 +0100560 ALOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);
Steven Moreland63a2d512021-06-25 01:10:15 +0000561 return mObjects.attach(objectID, object, cleanupCookie, func);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800562}
563
564void* BpBinder::findObject(const void* objectID) const
565{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700566 RpcMutexUniqueLock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800567 return mObjects.find(objectID);
568}
569
Steven Moreland63a2d512021-06-25 01:10:15 +0000570void* BpBinder::detachObject(const void* objectID) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700571 RpcMutexUniqueLock _l(mLock);
Steven Moreland63a2d512021-06-25 01:10:15 +0000572 return mObjects.detach(objectID);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800573}
574
Steven Moreland9e759e82021-06-25 21:30:23 +0000575void BpBinder::withLock(const std::function<void()>& doWithLock) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700576 RpcMutexUniqueLock _l(mLock);
Steven Moreland9e759e82021-06-25 21:30:23 +0000577 doWithLock();
578}
579
Devin Moore3faaa002022-07-27 15:54:06 +0000580sp<IBinder> BpBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
581 const void* makeArgs) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700582 RpcMutexUniqueLock _l(mLock);
Devin Moore3faaa002022-07-27 15:54:06 +0000583 return mObjects.lookupOrCreateWeak(objectID, make, makeArgs);
584}
585
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800586BpBinder* BpBinder::remoteBinder()
587{
588 return this;
589}
590
Steven Moreland32150282021-11-12 22:54:53 +0000591BpBinder::~BpBinder() {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000592 if (isRpcBinder()) [[unlikely]] {
593 return;
594 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800595
Steven Moreland32150282021-11-12 22:54:53 +0000596 if constexpr (!kEnableKernelIpc) {
597 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
598 return;
599 }
600
601 ALOGV("Destroying BpBinder %p handle %d\n", this, binderHandle());
602
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800603 IPCThreadState* ipc = IPCThreadState::self();
604
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700605 if (mTrackedUid >= 0) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700606 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700607 uint32_t trackedValue = sTrackingMap[mTrackedUid];
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000608 if ((trackedValue & COUNTING_VALUE_MASK) == 0) [[unlikely]] {
Steven Moreland5553ac42020-11-11 02:14:45 +0000609 ALOGE("Unexpected Binder Proxy tracking decrement in %p handle %d\n", this,
610 binderHandle());
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700611 } else {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000612 auto countingValue = trackedValue & COUNTING_VALUE_MASK;
613 if ((trackedValue & LIMIT_REACHED_MASK) &&
614 (countingValue <= sBinderProxyCountLowWatermark)) [[unlikely]] {
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700615 ALOGI("Limit reached bit reset for uid %d (fewer than %d proxies from uid %d held)",
Martijn Coenena8d509d2021-09-03 18:06:24 +0200616 getuid(), sBinderProxyCountLowWatermark, mTrackedUid);
Michael Wachenschwanz74d967a2018-05-15 15:03:57 -0700617 sTrackingMap[mTrackedUid] &= ~LIMIT_REACHED_MASK;
Martijn Coenena8d509d2021-09-03 18:06:24 +0200618 sLastLimitCallbackMap.erase(mTrackedUid);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700619 }
620 if (--sTrackingMap[mTrackedUid] == 0) {
621 sTrackingMap.erase(mTrackedUid);
622 }
623 }
624 }
Jing Ji4c4ac062023-10-07 15:20:23 -0700625 --sBinderProxyCount;
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700626
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800627 if (ipc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000628 ipc->expungeHandle(binderHandle(), this);
629 ipc->decWeakHandle(binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800630 }
631}
632
Steven Moreland32150282021-11-12 22:54:53 +0000633void BpBinder::onFirstRef() {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000634 if (isRpcBinder()) [[unlikely]] {
635 return;
636 }
Steven Moreland32150282021-11-12 22:54:53 +0000637
638 if constexpr (!kEnableKernelIpc) {
639 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
640 return;
641 }
642
643 ALOGV("onFirstRef BpBinder %p handle %d\n", this, binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800644 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000645 if (ipc) ipc->incStrongHandle(binderHandle(), this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800646}
647
Steven Moreland32150282021-11-12 22:54:53 +0000648void BpBinder::onLastStrongRef(const void* /*id*/) {
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000649 if (isRpcBinder()) [[unlikely]] {
Steven Moreland4f622fe2021-09-13 17:38:09 -0700650 (void)rpcSession()->sendDecStrong(this);
Steven Moreland5553ac42020-11-11 02:14:45 +0000651 return;
652 }
Steven Moreland32150282021-11-12 22:54:53 +0000653
654 if constexpr (!kEnableKernelIpc) {
655 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
656 return;
657 }
658
659 ALOGV("onLastStrongRef BpBinder %p handle %d\n", this, binderHandle());
Steve Block6807e592011-10-20 11:56:00 +0100660 IF_ALOGV() {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800661 printRefs();
662 }
663 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000664 if (ipc) ipc->decStrongHandle(binderHandle());
Steven Moreland80d23932019-06-07 12:43:27 -0700665
666 mLock.lock();
667 Vector<Obituary>* obits = mObituaries;
668 if(obits != nullptr) {
669 if (!obits->isEmpty()) {
Steven Moreland70fcb4e2019-12-13 17:28:58 -0800670 ALOGI("onLastStrongRef automatically unlinking death recipients: %s",
Steven Morelandf2830fe2022-12-21 00:45:34 +0000671 String8(mDescriptorCache).c_str());
Steven Moreland80d23932019-06-07 12:43:27 -0700672 }
673
Steven Moreland5553ac42020-11-11 02:14:45 +0000674 if (ipc) ipc->clearDeathNotification(binderHandle(), this);
Steven Moreland80d23932019-06-07 12:43:27 -0700675 mObituaries = nullptr;
676 }
677 mLock.unlock();
678
679 if (obits != nullptr) {
680 // XXX Should we tell any remaining DeathRecipient
681 // objects that the last strong ref has gone away, so they
682 // are no longer linked?
683 delete obits;
684 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800685}
686
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800687bool BpBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800688{
Steven Moreland5553ac42020-11-11 02:14:45 +0000689 // RPC binder doesn't currently support inc from weak binders
Tomasz Wasilczyk32746ae2023-10-09 19:57:58 +0000690 if (isRpcBinder()) [[unlikely]] {
691 return false;
692 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000693
Steven Moreland32150282021-11-12 22:54:53 +0000694 if constexpr (!kEnableKernelIpc) {
695 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
696 return false;
697 }
698
Steven Moreland5553ac42020-11-11 02:14:45 +0000699 ALOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, binderHandle());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700 IPCThreadState* ipc = IPCThreadState::self();
Steven Moreland5553ac42020-11-11 02:14:45 +0000701 return ipc ? ipc->attemptIncStrongHandle(binderHandle()) == NO_ERROR : false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800702}
703
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700704uint32_t BpBinder::getBinderProxyCount(uint32_t uid)
705{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700706 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700707 auto it = sTrackingMap.find(uid);
708 if (it != sTrackingMap.end()) {
709 return it->second & COUNTING_VALUE_MASK;
710 }
711 return 0;
712}
713
Jing Ji4c4ac062023-10-07 15:20:23 -0700714uint32_t BpBinder::getBinderProxyCount()
715{
716 return sBinderProxyCount.load();
717}
718
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700719void BpBinder::getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts)
720{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700721 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700722 uids.setCapacity(sTrackingMap.size());
723 counts.setCapacity(sTrackingMap.size());
724 for (const auto& it : sTrackingMap) {
725 uids.push_back(it.first);
726 counts.push_back(it.second & COUNTING_VALUE_MASK);
727 }
728}
729
730void BpBinder::enableCountByUid() { sCountByUidEnabled.store(true); }
731void BpBinder::disableCountByUid() { sCountByUidEnabled.store(false); }
732void BpBinder::setCountByUidEnabled(bool enable) { sCountByUidEnabled.store(enable); }
733
734void BpBinder::setLimitCallback(binder_proxy_limit_callback cb) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700735 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700736 sLimitCallback = cb;
737}
738
739void BpBinder::setBinderProxyCountWatermarks(int high, int low) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700740 RpcMutexUniqueLock _l(sTrackingLock);
Michael Wachenschwanzd296d0c2017-08-15 00:57:14 -0700741 sBinderProxyCountHighWatermark = high;
742 sBinderProxyCountLowWatermark = low;
743}
744
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800745// ---------------------------------------------------------------------------
746
Steven Moreland61ff8492019-09-26 16:05:45 -0700747} // namespace android