blob: da5affb274d6f0f61508a19efc909dbd04fea15b [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
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070017#include <binder/Binder.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080018
Bailey Forrest6913c462015-08-18 17:15:10 -070019#include <atomic>
Yifan Hong8b890852021-06-10 13:44:09 -070020#include <set>
Yifan Hong84bedeb2021-04-21 21:37:17 -070021
Jiyong Park5970d0a2022-03-08 16:56:13 +090022#include <android-base/logging.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070023#include <android-base/unique_fd.h>
Sahil Somani2522b072022-08-08 14:07:47 -070024#include <binder/BinderRecordReplay.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070025#include <binder/BpBinder.h>
26#include <binder/IInterface.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070027#include <binder/IPCThreadState.h>
Dianne Hackborn23eb1e22015-10-07 17:35:27 -070028#include <binder/IResultReceiver.h>
Dianne Hackborn1941a402016-08-29 12:30:43 -070029#include <binder/IShellCallback.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070030#include <binder/Parcel.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070031#include <binder/RpcServer.h>
Sahil Somani2522b072022-08-08 14:07:47 -070032#include <cutils/compiler.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070033#include <private/android_filesystem_config.h>
Sahil Somani2522b072022-08-08 14:07:47 -070034#include <pthread.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070035#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Yifan Hong84bedeb2021-04-21 21:37:17 -070037#include <inttypes.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <stdio.h>
39
Andrei Homescuf55d6882022-04-30 00:50:20 +000040#ifdef __linux__
41#include <linux/sched.h>
42#endif
43
Steven Moreland32150282021-11-12 22:54:53 +000044#include "BuildFlags.h"
Yifan Hong84bedeb2021-04-21 21:37:17 -070045#include "RpcState.h"
46
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080047namespace android {
48
Steven Moreland90c1f9a2021-05-03 18:27:24 +000049// Service implementations inherit from BBinder and IBinder, and this is frozen
50// in prebuilts.
51#ifdef __LP64__
52static_assert(sizeof(IBinder) == 24);
53static_assert(sizeof(BBinder) == 40);
54#else
55static_assert(sizeof(IBinder) == 12);
56static_assert(sizeof(BBinder) == 20);
57#endif
58
Steven Morelandd9a74002022-06-02 00:03:18 +000059// global b/c b/230079120 - consistent symbol table
Yifan Hong84bedeb2021-04-21 21:37:17 -070060#ifdef BINDER_RPC_DEV_SERVERS
Steven Morelandd9a74002022-06-02 00:03:18 +000061bool kEnableRpcDevServers = true;
Yifan Hong84bedeb2021-04-21 21:37:17 -070062#else
Steven Morelandd9a74002022-06-02 00:03:18 +000063bool kEnableRpcDevServers = false;
Yifan Hong84bedeb2021-04-21 21:37:17 -070064#endif
65
Sahil Somani2522b072022-08-08 14:07:47 -070066#ifdef BINDER_ENABLE_RECORDING
67bool kEnableRecording = true;
68#else
69bool kEnableRecording = false;
70#endif
71
Martijn Coenen1cad19c2021-10-04 09:19:01 +020072// Log any reply transactions for which the data exceeds this size
73#define LOG_REPLIES_OVER_SIZE (300 * 1024)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074// ---------------------------------------------------------------------------
75
Mathias Agopian83c04462009-05-22 19:00:22 -070076IBinder::IBinder()
77 : RefBase()
78{
79}
80
81IBinder::~IBinder()
82{
83}
84
85// ---------------------------------------------------------------------------
86
Colin Cross6f4f3ab2014-02-05 17:42:44 -080087sp<IInterface> IBinder::queryLocalInterface(const String16& /*descriptor*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088{
Yi Kongfdd8da92018-06-07 17:52:27 -070089 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090}
91
92BBinder* IBinder::localBinder()
93{
Yi Kongfdd8da92018-06-07 17:52:27 -070094 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095}
96
97BpBinder* IBinder::remoteBinder()
98{
Yi Kongfdd8da92018-06-07 17:52:27 -070099 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100}
101
102bool IBinder::checkSubclass(const void* /*subclassID*/) const
103{
104 return false;
105}
106
Dianne Hackborn23eb1e22015-10-07 17:35:27 -0700107
Dianne Hackbornf2bf93b2015-10-14 15:13:02 -0700108status_t IBinder::shellCommand(const sp<IBinder>& target, int in, int out, int err,
Dianne Hackborn1941a402016-08-29 12:30:43 -0700109 Vector<String16>& args, const sp<IShellCallback>& callback,
110 const sp<IResultReceiver>& resultReceiver)
Dianne Hackborn23eb1e22015-10-07 17:35:27 -0700111{
Dianne Hackbornf2bf93b2015-10-14 15:13:02 -0700112 Parcel send;
113 Parcel reply;
114 send.writeFileDescriptor(in);
115 send.writeFileDescriptor(out);
116 send.writeFileDescriptor(err);
117 const size_t numArgs = args.size();
118 send.writeInt32(numArgs);
119 for (size_t i = 0; i < numArgs; i++) {
120 send.writeString16(args[i]);
Dianne Hackborn23eb1e22015-10-07 17:35:27 -0700121 }
Yi Kongfdd8da92018-06-07 17:52:27 -0700122 send.writeStrongBinder(callback != nullptr ? IInterface::asBinder(callback) : nullptr);
123 send.writeStrongBinder(resultReceiver != nullptr ? IInterface::asBinder(resultReceiver) : nullptr);
Dianne Hackbornf2bf93b2015-10-14 15:13:02 -0700124 return target->transact(SHELL_COMMAND_TRANSACTION, send, &reply);
Dianne Hackborn23eb1e22015-10-07 17:35:27 -0700125}
126
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700127status_t IBinder::getExtension(sp<IBinder>* out) {
128 BBinder* local = this->localBinder();
129 if (local != nullptr) {
130 *out = local->getExtension();
131 return OK;
132 }
133
134 BpBinder* proxy = this->remoteBinder();
135 LOG_ALWAYS_FATAL_IF(proxy == nullptr);
136
137 Parcel data;
138 Parcel reply;
139 status_t status = transact(EXTENSION_TRANSACTION, data, &reply);
140 if (status != OK) return status;
141
142 return reply.readNullableStrongBinder(out);
143}
144
Steven Moreland86080b82019-09-23 15:41:18 -0700145status_t IBinder::getDebugPid(pid_t* out) {
146 BBinder* local = this->localBinder();
147 if (local != nullptr) {
148 *out = local->getDebugPid();
149 return OK;
150 }
151
152 BpBinder* proxy = this->remoteBinder();
153 LOG_ALWAYS_FATAL_IF(proxy == nullptr);
154
155 Parcel data;
156 Parcel reply;
157 status_t status = transact(DEBUG_PID_TRANSACTION, data, &reply);
158 if (status != OK) return status;
159
160 int32_t pid;
161 status = reply.readInt32(&pid);
162 if (status != OK) return status;
163
164 if (pid < 0 || pid > std::numeric_limits<pid_t>::max()) {
165 return BAD_VALUE;
166 }
167 *out = pid;
168 return OK;
169}
170
Yifan Hong02530ec2021-06-10 13:38:38 -0700171status_t IBinder::setRpcClientDebug(android::base::unique_fd socketFd,
172 const sp<IBinder>& keepAliveBinder) {
Steven Morelandd9a74002022-06-02 00:03:18 +0000173 if (!kEnableRpcDevServers) {
Yifan Hong84bedeb2021-04-21 21:37:17 -0700174 ALOGW("setRpcClientDebug disallowed because RPC is not enabled");
175 return INVALID_OPERATION;
176 }
Steven Moreland32150282021-11-12 22:54:53 +0000177 if (!kEnableKernelIpc) {
178 ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
179 return INVALID_OPERATION;
180 }
Yifan Hong84bedeb2021-04-21 21:37:17 -0700181
182 BBinder* local = this->localBinder();
183 if (local != nullptr) {
Yifan Hong02530ec2021-06-10 13:38:38 -0700184 return local->BBinder::setRpcClientDebug(std::move(socketFd), keepAliveBinder);
Yifan Hong84bedeb2021-04-21 21:37:17 -0700185 }
186
187 BpBinder* proxy = this->remoteBinder();
188 LOG_ALWAYS_FATAL_IF(proxy == nullptr, "binder object must be either local or remote");
189
190 Parcel data;
191 Parcel reply;
192 status_t status;
193 if (status = data.writeBool(socketFd.ok()); status != OK) return status;
194 if (socketFd.ok()) {
195 // writeUniqueFileDescriptor currently makes an unnecessary dup().
196 status = data.writeFileDescriptor(socketFd.release(), true /* own */);
197 if (status != OK) return status;
198 }
Yifan Hong02530ec2021-06-10 13:38:38 -0700199 if (status = data.writeStrongBinder(keepAliveBinder); status != OK) return status;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700200 return transact(SET_RPC_CLIENT_TRANSACTION, data, &reply);
201}
202
Steven Moreland9e759e82021-06-25 21:30:23 +0000203void IBinder::withLock(const std::function<void()>& doWithLock) {
204 BBinder* local = localBinder();
205 if (local) {
206 local->withLock(doWithLock);
207 return;
208 }
209 BpBinder* proxy = this->remoteBinder();
210 LOG_ALWAYS_FATAL_IF(proxy == nullptr, "binder object must be either local or remote");
211 proxy->withLock(doWithLock);
212}
213
Devin Moore3faaa002022-07-27 15:54:06 +0000214sp<IBinder> IBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
215 const void* makeArgs) {
216 BBinder* local = localBinder();
217 if (local) {
218 return local->lookupOrCreateWeak(objectID, make, makeArgs);
219 }
220 BpBinder* proxy = this->remoteBinder();
221 LOG_ALWAYS_FATAL_IF(proxy == nullptr, "binder object must be either local or remote");
222 return proxy->lookupOrCreateWeak(objectID, make, makeArgs);
223}
224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225// ---------------------------------------------------------------------------
226
Yifan Hong8b890852021-06-10 13:44:09 -0700227class BBinder::RpcServerLink : public IBinder::DeathRecipient {
228public:
229 // On binder died, calls RpcServer::shutdown on @a rpcServer, and removes itself from @a binder.
230 RpcServerLink(const sp<RpcServer>& rpcServer, const sp<IBinder>& keepAliveBinder,
231 const wp<BBinder>& binder)
232 : mRpcServer(rpcServer), mKeepAliveBinder(keepAliveBinder), mBinder(binder) {}
Steven Morelandd9a74002022-06-02 00:03:18 +0000233 virtual ~RpcServerLink();
Yifan Hong8b890852021-06-10 13:44:09 -0700234 void binderDied(const wp<IBinder>&) override {
Steven Morelandf6957b72022-09-24 03:12:16 +0000235 auto promoted = mBinder.promote();
236 ALOGI("RpcBinder: binder died, shutting down RpcServer for %s",
237 promoted ? String8(promoted->getInterfaceDescriptor()).c_str() : "<NULL>");
238
Yifan Hong8b890852021-06-10 13:44:09 -0700239 if (mRpcServer == nullptr) {
240 ALOGW("RpcServerLink: Unable to shut down RpcServer because it does not exist.");
241 } else {
242 ALOGW_IF(!mRpcServer->shutdown(),
243 "RpcServerLink: RpcServer did not shut down properly. Not started?");
244 }
245 mRpcServer.clear();
246
Steven Morelandf6957b72022-09-24 03:12:16 +0000247 if (promoted) {
Yifan Hong8b890852021-06-10 13:44:09 -0700248 promoted->removeRpcServerLink(sp<RpcServerLink>::fromExisting(this));
249 }
250 mBinder.clear();
251 }
252
253private:
254 sp<RpcServer> mRpcServer;
255 sp<IBinder> mKeepAliveBinder; // hold to avoid automatically unlinking
256 wp<BBinder> mBinder;
257};
Steven Morelandd9a74002022-06-02 00:03:18 +0000258BBinder::RpcServerLink::~RpcServerLink() {}
Yifan Hong8b890852021-06-10 13:44:09 -0700259
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260class BBinder::Extras
261{
262public:
Steven Morelandf0212002018-12-26 13:59:23 -0800263 // unlocked objects
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700264 sp<IBinder> mExtension;
Andrei Homescuf55d6882022-04-30 00:50:20 +0000265#ifdef __linux__
Steven Morelandbf1915b2020-07-16 22:43:02 +0000266 int mPolicy = SCHED_NORMAL;
267 int mPriority = 0;
Andrei Homescuf55d6882022-04-30 00:50:20 +0000268#endif
269 bool mRequestingSid = false;
270 bool mInheritRt = false;
Steven Morelandf0212002018-12-26 13:59:23 -0800271
272 // for below objects
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800273 Mutex mLock;
Yifan Hong8b890852021-06-10 13:44:09 -0700274 std::set<sp<RpcServerLink>> mRpcServerLinks;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275 BpBinder::ObjectManager mObjects;
Sahil Somani2522b072022-08-08 14:07:47 -0700276
277 android::base::unique_fd mRecordingFd;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278};
279
280// ---------------------------------------------------------------------------
281
Sahil Somani2522b072022-08-08 14:07:47 -0700282BBinder::BBinder() : mExtras(nullptr), mStability(0), mParceled(false), mRecordingOn(false) {}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283
284bool BBinder::isBinderAlive() const
285{
286 return true;
287}
288
289status_t BBinder::pingBinder()
290{
291 return NO_ERROR;
292}
293
Sahil Somani2522b072022-08-08 14:07:47 -0700294status_t BBinder::startRecordingTransactions(const Parcel& data) {
295 if (!kEnableRecording) {
296 ALOGW("Binder recording disallowed because recording is not enabled");
297 return INVALID_OPERATION;
298 }
299 if (!kEnableKernelIpc) {
300 ALOGW("Binder recording disallowed because kernel binder is not enabled");
301 return INVALID_OPERATION;
302 }
303 uid_t uid = IPCThreadState::self()->getCallingUid();
304 if (uid != AID_ROOT) {
305 ALOGE("Binder recording not allowed because client %" PRIu32 " is not root", uid);
306 return PERMISSION_DENIED;
307 }
308 Extras* e = getOrCreateExtras();
309 AutoMutex lock(e->mLock);
310 if (mRecordingOn) {
311 LOG(INFO) << "Could not start Binder recording. Another is already in progress.";
312 return INVALID_OPERATION;
313 } else {
314 status_t readStatus = data.readUniqueFileDescriptor(&(e->mRecordingFd));
315 if (readStatus != OK) {
316 return readStatus;
317 }
318 mRecordingOn = true;
319 LOG(INFO) << "Started Binder recording.";
320 return NO_ERROR;
321 }
322}
323
324status_t BBinder::stopRecordingTransactions() {
325 if (!kEnableRecording) {
326 ALOGW("Binder recording disallowed because recording is not enabled");
327 return INVALID_OPERATION;
328 }
329 if (!kEnableKernelIpc) {
330 ALOGW("Binder recording disallowed because kernel binder is not enabled");
331 return INVALID_OPERATION;
332 }
333 uid_t uid = IPCThreadState::self()->getCallingUid();
334 if (uid != AID_ROOT) {
335 ALOGE("Binder recording not allowed because client %" PRIu32 " is not root", uid);
336 return PERMISSION_DENIED;
337 }
338 Extras* e = getOrCreateExtras();
339 AutoMutex lock(e->mLock);
340 if (mRecordingOn) {
341 e->mRecordingFd.reset();
342 mRecordingOn = false;
343 LOG(INFO) << "Stopped Binder recording.";
344 return NO_ERROR;
345 } else {
346 LOG(INFO) << "Could not stop Binder recording. One is not in progress.";
347 return INVALID_OPERATION;
348 }
349}
350
Mathias Agopian83c04462009-05-22 19:00:22 -0700351const String16& BBinder::getInterfaceDescriptor() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352{
Steven Moreland1ef0eb62022-08-18 20:09:30 +0000353 static StaticString16 sBBinder(u"BBinder");
354 ALOGW("Reached BBinder::getInterfaceDescriptor (this=%p). Override?", this);
355 return sBBinder;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356}
357
Jiyong Parkb86c8662018-10-29 23:01:57 +0900358// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800359status_t BBinder::transact(
360 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
361{
362 data.setDataPosition(0);
363
Steven Morelandf183fdd2020-10-27 00:12:12 +0000364 if (reply != nullptr && (flags & FLAG_CLEAR_BUF)) {
365 reply->markSensitive();
366 }
367
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368 status_t err = NO_ERROR;
369 switch (code) {
370 case PING_TRANSACTION:
Steven Moreland6e69d652019-07-10 14:17:55 -0700371 err = pingBinder();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 break;
Sahil Somani2522b072022-08-08 14:07:47 -0700373 case START_RECORDING_TRANSACTION:
374 err = startRecordingTransactions(data);
375 break;
376 case STOP_RECORDING_TRANSACTION:
377 err = stopRecordingTransactions();
378 break;
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700379 case EXTENSION_TRANSACTION:
Jiyong Park5970d0a2022-03-08 16:56:13 +0900380 CHECK(reply != nullptr);
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700381 err = reply->writeStrongBinder(getExtension());
382 break;
Steven Moreland86080b82019-09-23 15:41:18 -0700383 case DEBUG_PID_TRANSACTION:
Jiyong Park5970d0a2022-03-08 16:56:13 +0900384 CHECK(reply != nullptr);
Steven Moreland86080b82019-09-23 15:41:18 -0700385 err = reply->writeInt32(getDebugPid());
386 break;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700387 case SET_RPC_CLIENT_TRANSACTION: {
388 err = setRpcClientDebug(data);
389 break;
390 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391 default:
392 err = onTransact(code, data, reply, flags);
393 break;
394 }
395
Steven Morelanda86a3562019-08-01 23:28:34 +0000396 // In case this is being transacted on in the same process.
Yi Kongfdd8da92018-06-07 17:52:27 -0700397 if (reply != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398 reply->setDataPosition(0);
Martijn Coenen1cad19c2021-10-04 09:19:01 +0200399 if (reply->dataSize() > LOG_REPLIES_OVER_SIZE) {
400 ALOGW("Large reply transaction of %zu bytes, interface descriptor %s, code %d",
401 reply->dataSize(), String8(getInterfaceDescriptor()).c_str(), code);
402 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800403 }
404
Sahil Somani2522b072022-08-08 14:07:47 -0700405 if (CC_UNLIKELY(kEnableKernelIpc && mRecordingOn && code != START_RECORDING_TRANSACTION)) {
406 Extras* e = mExtras.load(std::memory_order_acquire);
407 AutoMutex lock(e->mLock);
408 if (mRecordingOn) {
409 Parcel emptyReply;
Fabián Cañas68dbcfe2023-01-06 15:37:39 -0500410 timespec ts;
411 timespec_get(&ts, TIME_UTC);
Sahil Somani2522b072022-08-08 14:07:47 -0700412 auto transaction =
Fabián Cañas68dbcfe2023-01-06 15:37:39 -0500413 android::binder::debug::RecordedTransaction::fromDetails(code, flags, ts, data,
Sahil Somani2522b072022-08-08 14:07:47 -0700414 reply ? *reply
415 : emptyReply,
416 err);
417 if (transaction) {
418 if (status_t err = transaction->dumpToFile(e->mRecordingFd); err != NO_ERROR) {
419 LOG(INFO) << "Failed to dump RecordedTransaction to file with error " << err;
420 }
421 } else {
422 LOG(INFO) << "Failed to create RecordedTransaction object.";
423 }
424 }
425 }
426
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427 return err;
428}
429
Jiyong Parkb86c8662018-10-29 23:01:57 +0900430// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431status_t BBinder::linkToDeath(
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800432 const sp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
433 uint32_t /*flags*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434{
435 return INVALID_OPERATION;
436}
437
Jiyong Parkb86c8662018-10-29 23:01:57 +0900438// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439status_t BBinder::unlinkToDeath(
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800440 const wp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
441 uint32_t /*flags*/, wp<DeathRecipient>* /*outRecipient*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800442{
443 return INVALID_OPERATION;
444}
445
Dianne Hackborn23eb1e22015-10-07 17:35:27 -0700446status_t BBinder::dump(int /*fd*/, const Vector<String16>& /*args*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447{
448 return NO_ERROR;
449}
450
Steven Moreland63a2d512021-06-25 01:10:15 +0000451void* BBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
452 object_cleanup_func func) {
Steven Morelandf0212002018-12-26 13:59:23 -0800453 Extras* e = getOrCreateExtras();
Steven Moreland5ce7ca52021-06-25 21:59:50 +0000454 LOG_ALWAYS_FATAL_IF(!e, "no memory");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800455
456 AutoMutex _l(e->mLock);
Steven Moreland63a2d512021-06-25 01:10:15 +0000457 return e->mObjects.attach(objectID, object, cleanupCookie, func);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800458}
459
460void* BBinder::findObject(const void* objectID) const
461{
Bailey Forrest6913c462015-08-18 17:15:10 -0700462 Extras* e = mExtras.load(std::memory_order_acquire);
Yi Kongfdd8da92018-06-07 17:52:27 -0700463 if (!e) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800464
465 AutoMutex _l(e->mLock);
466 return e->mObjects.find(objectID);
467}
468
Steven Moreland63a2d512021-06-25 01:10:15 +0000469void* BBinder::detachObject(const void* objectID) {
Bailey Forrest6913c462015-08-18 17:15:10 -0700470 Extras* e = mExtras.load(std::memory_order_acquire);
Steven Moreland63a2d512021-06-25 01:10:15 +0000471 if (!e) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472
473 AutoMutex _l(e->mLock);
Steven Moreland63a2d512021-06-25 01:10:15 +0000474 return e->mObjects.detach(objectID);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800475}
476
Steven Moreland9e759e82021-06-25 21:30:23 +0000477void BBinder::withLock(const std::function<void()>& doWithLock) {
478 Extras* e = getOrCreateExtras();
479 LOG_ALWAYS_FATAL_IF(!e, "no memory");
480
481 AutoMutex _l(e->mLock);
482 doWithLock();
483}
484
Devin Moore3faaa002022-07-27 15:54:06 +0000485sp<IBinder> BBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
486 const void* makeArgs) {
487 Extras* e = getOrCreateExtras();
488 LOG_ALWAYS_FATAL_IF(!e, "no memory");
489 AutoMutex _l(e->mLock);
490 return e->mObjects.lookupOrCreateWeak(objectID, make, makeArgs);
491}
492
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800493BBinder* BBinder::localBinder()
494{
495 return this;
496}
497
Steven Morelandf0212002018-12-26 13:59:23 -0800498bool BBinder::isRequestingSid()
499{
500 Extras* e = mExtras.load(std::memory_order_acquire);
501
502 return e && e->mRequestingSid;
503}
504
505void BBinder::setRequestingSid(bool requestingSid)
506{
Steven Morelandd37e6dd2021-06-16 22:07:51 +0000507 LOG_ALWAYS_FATAL_IF(mParceled,
508 "setRequestingSid() should not be called after a binder object "
509 "is parceled/sent to another process");
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500510
Steven Morelandf0212002018-12-26 13:59:23 -0800511 Extras* e = mExtras.load(std::memory_order_acquire);
512
513 if (!e) {
514 // default is false. Most things don't need sids, so avoiding allocations when possible.
515 if (!requestingSid) {
516 return;
517 }
518
519 e = getOrCreateExtras();
520 if (!e) return; // out of memory
521 }
522
Steven Moreland3668be62019-02-08 17:56:55 -0800523 e->mRequestingSid = requestingSid;
Steven Morelandf0212002018-12-26 13:59:23 -0800524}
525
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700526sp<IBinder> BBinder::getExtension() {
527 Extras* e = mExtras.load(std::memory_order_acquire);
528 if (e == nullptr) return nullptr;
529 return e->mExtension;
530}
531
Andrei Homescuf55d6882022-04-30 00:50:20 +0000532#ifdef __linux__
Steven Morelandbf1915b2020-07-16 22:43:02 +0000533void BBinder::setMinSchedulerPolicy(int policy, int priority) {
Steven Morelandd37e6dd2021-06-16 22:07:51 +0000534 LOG_ALWAYS_FATAL_IF(mParceled,
535 "setMinSchedulerPolicy() should not be called after a binder object "
536 "is parceled/sent to another process");
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500537
Steven Morelandbf1915b2020-07-16 22:43:02 +0000538 switch (policy) {
539 case SCHED_NORMAL:
540 LOG_ALWAYS_FATAL_IF(priority < -20 || priority > 19, "Invalid priority for SCHED_NORMAL: %d", priority);
541 break;
542 case SCHED_RR:
543 case SCHED_FIFO:
544 LOG_ALWAYS_FATAL_IF(priority < 1 || priority > 99, "Invalid priority for sched %d: %d", policy, priority);
545 break;
546 default:
547 LOG_ALWAYS_FATAL("Unrecognized scheduling policy: %d", policy);
548 }
549
550 Extras* e = mExtras.load(std::memory_order_acquire);
551
552 if (e == nullptr) {
553 // Avoid allocations if called with default.
554 if (policy == SCHED_NORMAL && priority == 0) {
555 return;
556 }
557
558 e = getOrCreateExtras();
559 if (!e) return; // out of memory
560 }
561
562 e->mPolicy = policy;
563 e->mPriority = priority;
564}
565
566int BBinder::getMinSchedulerPolicy() {
567 Extras* e = mExtras.load(std::memory_order_acquire);
568 if (e == nullptr) return SCHED_NORMAL;
569 return e->mPolicy;
570}
571
572int BBinder::getMinSchedulerPriority() {
573 Extras* e = mExtras.load(std::memory_order_acquire);
574 if (e == nullptr) return 0;
575 return e->mPriority;
576}
Andrei Homescuf55d6882022-04-30 00:50:20 +0000577#endif // __linux__
Steven Morelandbf1915b2020-07-16 22:43:02 +0000578
Steven Morelandcf03cf12020-12-04 02:58:40 +0000579bool BBinder::isInheritRt() {
580 Extras* e = mExtras.load(std::memory_order_acquire);
581
582 return e && e->mInheritRt;
583}
584
585void BBinder::setInheritRt(bool inheritRt) {
Steven Morelandd37e6dd2021-06-16 22:07:51 +0000586 LOG_ALWAYS_FATAL_IF(mParceled,
587 "setInheritRt() should not be called after a binder object "
588 "is parceled/sent to another process");
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500589
Steven Morelandcf03cf12020-12-04 02:58:40 +0000590 Extras* e = mExtras.load(std::memory_order_acquire);
591
592 if (!e) {
593 if (!inheritRt) {
594 return;
595 }
596
597 e = getOrCreateExtras();
598 if (!e) return; // out of memory
599 }
600
601 e->mInheritRt = inheritRt;
602}
603
Steven Moreland86080b82019-09-23 15:41:18 -0700604pid_t BBinder::getDebugPid() {
Andrei Homescuf55d6882022-04-30 00:50:20 +0000605#ifdef __linux__
Steven Moreland86080b82019-09-23 15:41:18 -0700606 return getpid();
Andrei Homescuf55d6882022-04-30 00:50:20 +0000607#else
608 // TODO: handle other OSes
609 return 0;
610#endif // __linux__
Steven Moreland86080b82019-09-23 15:41:18 -0700611}
612
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700613void BBinder::setExtension(const sp<IBinder>& extension) {
Steven Morelandd37e6dd2021-06-16 22:07:51 +0000614 LOG_ALWAYS_FATAL_IF(mParceled,
615 "setExtension() should not be called after a binder object "
616 "is parceled/sent to another process");
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500617
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700618 Extras* e = getOrCreateExtras();
619 e->mExtension = extension;
620}
621
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500622bool BBinder::wasParceled() {
623 return mParceled;
624}
625
626void BBinder::setParceled() {
627 mParceled = true;
628}
629
Yifan Hong84bedeb2021-04-21 21:37:17 -0700630status_t BBinder::setRpcClientDebug(const Parcel& data) {
Steven Morelandd9a74002022-06-02 00:03:18 +0000631 if (!kEnableRpcDevServers) {
Yifan Hong84bedeb2021-04-21 21:37:17 -0700632 ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
633 return INVALID_OPERATION;
634 }
Steven Moreland32150282021-11-12 22:54:53 +0000635 if (!kEnableKernelIpc) {
636 ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
637 return INVALID_OPERATION;
638 }
Yifan Hong84bedeb2021-04-21 21:37:17 -0700639 uid_t uid = IPCThreadState::self()->getCallingUid();
640 if (uid != AID_ROOT) {
641 ALOGE("%s: not allowed because client %" PRIu32 " is not root", __PRETTY_FUNCTION__, uid);
642 return PERMISSION_DENIED;
643 }
644 status_t status;
645 bool hasSocketFd;
646 android::base::unique_fd clientFd;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700647
648 if (status = data.readBool(&hasSocketFd); status != OK) return status;
649 if (hasSocketFd) {
650 if (status = data.readUniqueFileDescriptor(&clientFd); status != OK) return status;
651 }
Yifan Hong02530ec2021-06-10 13:38:38 -0700652 sp<IBinder> keepAliveBinder;
653 if (status = data.readNullableStrongBinder(&keepAliveBinder); status != OK) return status;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700654
Yifan Hong02530ec2021-06-10 13:38:38 -0700655 return setRpcClientDebug(std::move(clientFd), keepAliveBinder);
Yifan Hong84bedeb2021-04-21 21:37:17 -0700656}
657
Yifan Hong02530ec2021-06-10 13:38:38 -0700658status_t BBinder::setRpcClientDebug(android::base::unique_fd socketFd,
659 const sp<IBinder>& keepAliveBinder) {
Steven Morelandd9a74002022-06-02 00:03:18 +0000660 if (!kEnableRpcDevServers) {
Yifan Hong84bedeb2021-04-21 21:37:17 -0700661 ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
662 return INVALID_OPERATION;
663 }
Steven Moreland32150282021-11-12 22:54:53 +0000664 if (!kEnableKernelIpc) {
665 ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
666 return INVALID_OPERATION;
667 }
Yifan Hong84bedeb2021-04-21 21:37:17 -0700668
669 const int socketFdForPrint = socketFd.get();
Yifan Hong34823232021-06-07 17:23:00 -0700670 LOG_RPC_DETAIL("%s(fd=%d)", __PRETTY_FUNCTION__, socketFdForPrint);
Yifan Hong84bedeb2021-04-21 21:37:17 -0700671
672 if (!socketFd.ok()) {
673 ALOGE("%s: No socket FD provided.", __PRETTY_FUNCTION__);
674 return BAD_VALUE;
675 }
Yifan Hong84bedeb2021-04-21 21:37:17 -0700676
Yifan Hong02530ec2021-06-10 13:38:38 -0700677 if (keepAliveBinder == nullptr) {
678 ALOGE("%s: No keepAliveBinder provided.", __PRETTY_FUNCTION__);
679 return UNEXPECTED_NULL;
680 }
681
Elie Kheirallah47431c12022-04-21 23:46:17 +0000682 size_t binderThreadPoolMaxCount = ProcessState::self()->getThreadPoolMaxTotalThreadCount();
Yifan Hong84bedeb2021-04-21 21:37:17 -0700683 if (binderThreadPoolMaxCount <= 1) {
684 ALOGE("%s: ProcessState thread pool max count is %zu. RPC is disabled for this service "
685 "because RPC requires the service to support multithreading.",
686 __PRETTY_FUNCTION__, binderThreadPoolMaxCount);
687 return INVALID_OPERATION;
688 }
689
Yifan Hong8b890852021-06-10 13:44:09 -0700690 // Weak ref to avoid circular dependency:
691 // BBinder -> RpcServerLink ----> RpcServer -X-> BBinder
692 // `-X-> BBinder
693 auto weakThis = wp<BBinder>::fromExisting(this);
694
Yifan Hong84bedeb2021-04-21 21:37:17 -0700695 Extras* e = getOrCreateExtras();
696 AutoMutex _l(e->mLock);
Yifan Hong8b890852021-06-10 13:44:09 -0700697 auto rpcServer = RpcServer::make();
698 LOG_ALWAYS_FATAL_IF(rpcServer == nullptr, "RpcServer::make returns null");
Yifan Hong8b890852021-06-10 13:44:09 -0700699 auto link = sp<RpcServerLink>::make(rpcServer, keepAliveBinder, weakThis);
700 if (auto status = keepAliveBinder->linkToDeath(link, nullptr, 0); status != OK) {
701 ALOGE("%s: keepAliveBinder->linkToDeath returns %s", __PRETTY_FUNCTION__,
702 statusToString(status).c_str());
703 return status;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700704 }
Yifan Hong8b890852021-06-10 13:44:09 -0700705 rpcServer->setRootObjectWeak(weakThis);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700706 if (auto status = rpcServer->setupExternalServer(std::move(socketFd)); status != OK) {
707 return status;
708 }
Yifan Hong8b890852021-06-10 13:44:09 -0700709 rpcServer->setMaxThreads(binderThreadPoolMaxCount);
Steven Morelandf6957b72022-09-24 03:12:16 +0000710 LOG(INFO) << "RpcBinder: Started Binder debug on " << getInterfaceDescriptor();
Yifan Hong8b890852021-06-10 13:44:09 -0700711 rpcServer->start();
712 e->mRpcServerLinks.emplace(link);
Yifan Hong34823232021-06-07 17:23:00 -0700713 LOG_RPC_DETAIL("%s(fd=%d) successful", __PRETTY_FUNCTION__, socketFdForPrint);
Yifan Hong84bedeb2021-04-21 21:37:17 -0700714 return OK;
715}
716
Yifan Hong8b890852021-06-10 13:44:09 -0700717void BBinder::removeRpcServerLink(const sp<RpcServerLink>& link) {
718 Extras* e = mExtras.load(std::memory_order_acquire);
719 if (!e) return;
720 AutoMutex _l(e->mLock);
721 (void)e->mRpcServerLinks.erase(link);
722}
723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724BBinder::~BBinder()
725{
Steven Moreland1bd2bc72022-07-29 20:29:40 +0000726 if (!wasParceled()) {
727 if (getExtension()) {
728 ALOGW("Binder %p destroyed with extension attached before being parceled.", this);
729 }
730 if (isRequestingSid()) {
731 ALOGW("Binder %p destroyed when requesting SID before being parceled.", this);
732 }
733 if (isInheritRt()) {
734 ALOGW("Binder %p destroyed after setInheritRt before being parceled.", this);
735 }
Andrei Homescu40525502022-08-02 01:23:22 +0000736#ifdef __linux__
Steven Moreland1bd2bc72022-07-29 20:29:40 +0000737 if (getMinSchedulerPolicy() != SCHED_NORMAL) {
738 ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
739 }
740 if (getMinSchedulerPriority() != 0) {
741 ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
742 }
Andrei Homescu40525502022-08-02 01:23:22 +0000743#endif // __linux__
Steven Moreland55a12542022-03-31 21:53:11 +0000744 }
745
Bailey Forrest6913c462015-08-18 17:15:10 -0700746 Extras* e = mExtras.load(std::memory_order_relaxed);
Hans Boehm3effaba2014-08-12 22:56:00 +0000747 if (e) delete e;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800748}
749
750
Jiyong Parkb86c8662018-10-29 23:01:57 +0900751// NOLINTNEXTLINE(google-default-arguments)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800752status_t BBinder::onTransact(
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800753 uint32_t code, const Parcel& data, Parcel* reply, uint32_t /*flags*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800754{
755 switch (code) {
756 case INTERFACE_TRANSACTION:
Jiyong Park5970d0a2022-03-08 16:56:13 +0900757 CHECK(reply != nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758 reply->writeString16(getInterfaceDescriptor());
759 return NO_ERROR;
760
761 case DUMP_TRANSACTION: {
762 int fd = data.readFileDescriptor();
763 int argc = data.readInt32();
764 Vector<String16> args;
765 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
766 args.add(data.readString16());
767 }
768 return dump(fd, args);
769 }
Dianne Hackborn555f89d2012-05-08 18:54:22 -0700770
Dianne Hackborn23eb1e22015-10-07 17:35:27 -0700771 case SHELL_COMMAND_TRANSACTION: {
772 int in = data.readFileDescriptor();
773 int out = data.readFileDescriptor();
774 int err = data.readFileDescriptor();
775 int argc = data.readInt32();
776 Vector<String16> args;
777 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
778 args.add(data.readString16());
779 }
Andrei Homescua543a842022-07-07 22:17:55 +0000780 sp<IBinder> shellCallbackBinder = data.readStrongBinder();
Dianne Hackborn23eb1e22015-10-07 17:35:27 -0700781 sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(
782 data.readStrongBinder());
783
Dianne Hackbornf2bf93b2015-10-14 15:13:02 -0700784 // XXX can't add virtuals until binaries are updated.
Andrei Homescua543a842022-07-07 22:17:55 +0000785 // sp<IShellCallback> shellCallback = IShellCallback::asInterface(
786 // shellCallbackBinder);
787 // return shellCommand(in, out, err, args, resultReceiver);
Christopher Wiley0a9a1c12016-07-20 08:28:14 -0700788 (void)in;
789 (void)out;
790 (void)err;
791
Yi Kongfdd8da92018-06-07 17:52:27 -0700792 if (resultReceiver != nullptr) {
Dianne Hackbornf2bf93b2015-10-14 15:13:02 -0700793 resultReceiver->send(INVALID_OPERATION);
794 }
Martijn Coenenaa6ee992017-08-17 15:38:08 +0200795
796 return NO_ERROR;
Dianne Hackborn23eb1e22015-10-07 17:35:27 -0700797 }
798
Dianne Hackborn555f89d2012-05-08 18:54:22 -0700799 case SYSPROPS_TRANSACTION: {
800 report_sysprop_change();
801 return NO_ERROR;
802 }
803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800804 default:
805 return UNKNOWN_TRANSACTION;
806 }
807}
808
Steven Morelandf0212002018-12-26 13:59:23 -0800809BBinder::Extras* BBinder::getOrCreateExtras()
810{
811 Extras* e = mExtras.load(std::memory_order_acquire);
812
813 if (!e) {
814 e = new Extras;
815 Extras* expected = nullptr;
816 if (!mExtras.compare_exchange_strong(expected, e,
817 std::memory_order_release,
818 std::memory_order_acquire)) {
819 delete e;
820 e = expected; // Filled in by CAS
821 }
822 if (e == nullptr) return nullptr; // out of memory
823 }
824
825 return e;
826}
827
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800828// ---------------------------------------------------------------------------
829
830enum {
831 // This is used to transfer ownership of the remote binder from
832 // the BpRefBase object holding it (when it is constructed), to the
833 // owner of the BpRefBase object when it first acquires that BpRefBase.
834 kRemoteAcquired = 0x00000001
835};
836
837BpRefBase::BpRefBase(const sp<IBinder>& o)
Yi Kongfdd8da92018-06-07 17:52:27 -0700838 : mRemote(o.get()), mRefs(nullptr), mState(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800839{
840 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
841
842 if (mRemote) {
843 mRemote->incStrong(this); // Removed on first IncStrong().
844 mRefs = mRemote->createWeak(this); // Held for our entire lifetime.
845 }
846}
847
848BpRefBase::~BpRefBase()
849{
850 if (mRemote) {
Bailey Forrest6913c462015-08-18 17:15:10 -0700851 if (!(mState.load(std::memory_order_relaxed)&kRemoteAcquired)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800852 mRemote->decStrong(this);
853 }
854 mRefs->decWeak(this);
855 }
856}
857
858void BpRefBase::onFirstRef()
859{
Bailey Forrest6913c462015-08-18 17:15:10 -0700860 mState.fetch_or(kRemoteAcquired, std::memory_order_relaxed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800861}
862
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800863void BpRefBase::onLastStrongRef(const void* /*id*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800864{
865 if (mRemote) {
866 mRemote->decStrong(this);
867 }
868}
869
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800870bool BpRefBase::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800871{
872 return mRemote ? mRefs->attemptIncStrong(this) : false;
873}
874
875// ---------------------------------------------------------------------------
876
Steven Moreland61ff8492019-09-26 16:05:45 -0700877} // namespace android