1 /*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <binder/Binder.h>
18
19 #include <atomic>
20 #include <set>
21
22 #include <binder/BpBinder.h>
23 #include <binder/IInterface.h>
24 #include <binder/IPCThreadState.h>
25 #include <binder/IResultReceiver.h>
26 #include <binder/IShellCallback.h>
27 #include <binder/Parcel.h>
28 #include <binder/RecordedTransaction.h>
29 #include <binder/RpcServer.h>
30 #include <binder/unique_fd.h>
31 #include <pthread.h>
32
33 #include <inttypes.h>
34 #include <stdio.h>
35
36 #ifdef __linux__
37 #include <linux/sched.h>
38 #endif
39
40 #include "BuildFlags.h"
41 #include "Constants.h"
42 #include "OS.h"
43 #include "RpcState.h"
44
45 namespace android {
46
47 using android::binder::unique_fd;
48
49 constexpr uid_t kUidRoot = 0;
50
51 // Service implementations inherit from BBinder and IBinder, and this is frozen
52 // in prebuilts.
53 #ifdef __LP64__
54 static_assert(sizeof(IBinder) == 24);
55 static_assert(sizeof(BBinder) == 40);
56 #else
57 static_assert(sizeof(IBinder) == 12);
58 static_assert(sizeof(BBinder) == 20);
59 #endif
60
61 // global b/c b/230079120 - consistent symbol table
62 #ifdef BINDER_RPC_DEV_SERVERS
63 constexpr bool kEnableRpcDevServers = true;
64 #else
65 constexpr bool kEnableRpcDevServers = false;
66 #endif
67
68 #ifdef BINDER_ENABLE_RECORDING
69 constexpr bool kEnableRecording = true;
70 #else
71 constexpr bool kEnableRecording = false;
72 #endif
73
74 // ---------------------------------------------------------------------------
75
IBinder()76 IBinder::IBinder()
77 : RefBase()
78 {
79 }
80
~IBinder()81 IBinder::~IBinder()
82 {
83 }
84
85 // ---------------------------------------------------------------------------
86
queryLocalInterface(const String16 &)87 sp<IInterface> IBinder::queryLocalInterface(const String16& /*descriptor*/)
88 {
89 return nullptr;
90 }
91
localBinder()92 BBinder* IBinder::localBinder()
93 {
94 return nullptr;
95 }
96
remoteBinder()97 BpBinder* IBinder::remoteBinder()
98 {
99 return nullptr;
100 }
101
checkSubclass(const void *) const102 bool IBinder::checkSubclass(const void* /*subclassID*/) const
103 {
104 return false;
105 }
106
107
shellCommand(const sp<IBinder> & target,int in,int out,int err,Vector<String16> & args,const sp<IShellCallback> & callback,const sp<IResultReceiver> & resultReceiver)108 status_t IBinder::shellCommand(const sp<IBinder>& target, int in, int out, int err,
109 Vector<String16>& args, const sp<IShellCallback>& callback,
110 const sp<IResultReceiver>& resultReceiver)
111 {
112 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]);
121 }
122 send.writeStrongBinder(callback != nullptr ? IInterface::asBinder(callback) : nullptr);
123 send.writeStrongBinder(resultReceiver != nullptr ? IInterface::asBinder(resultReceiver) : nullptr);
124 return target->transact(SHELL_COMMAND_TRANSACTION, send, &reply);
125 }
126
getExtension(sp<IBinder> * out)127 status_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
addFrozenStateChangeCallback(const wp<FrozenStateChangeCallback> & callback)145 status_t IBinder::addFrozenStateChangeCallback(const wp<FrozenStateChangeCallback>& callback) {
146 BpBinder* proxy = this->remoteBinder();
147 if (proxy != nullptr) {
148 return proxy->addFrozenStateChangeCallback(callback);
149 }
150 return INVALID_OPERATION;
151 }
152
removeFrozenStateChangeCallback(const wp<FrozenStateChangeCallback> & callback)153 status_t IBinder::removeFrozenStateChangeCallback(const wp<FrozenStateChangeCallback>& callback) {
154 BpBinder* proxy = this->remoteBinder();
155 if (proxy != nullptr) {
156 return proxy->removeFrozenStateChangeCallback(callback);
157 }
158 return INVALID_OPERATION;
159 }
160
getDebugPid(pid_t * out)161 status_t IBinder::getDebugPid(pid_t* out) {
162 BBinder* local = this->localBinder();
163 if (local != nullptr) {
164 *out = local->getDebugPid();
165 return OK;
166 }
167
168 BpBinder* proxy = this->remoteBinder();
169 LOG_ALWAYS_FATAL_IF(proxy == nullptr);
170
171 Parcel data;
172 Parcel reply;
173 status_t status = transact(DEBUG_PID_TRANSACTION, data, &reply);
174 if (status != OK) return status;
175
176 int32_t pid;
177 status = reply.readInt32(&pid);
178 if (status != OK) return status;
179
180 if (pid < 0 || pid > std::numeric_limits<pid_t>::max()) {
181 return BAD_VALUE;
182 }
183 *out = pid;
184 return OK;
185 }
186
setRpcClientDebug(unique_fd socketFd,const sp<IBinder> & keepAliveBinder)187 status_t IBinder::setRpcClientDebug(unique_fd socketFd, const sp<IBinder>& keepAliveBinder) {
188 if (!kEnableRpcDevServers) {
189 ALOGW("setRpcClientDebug disallowed because RPC is not enabled");
190 return INVALID_OPERATION;
191 }
192 if (!kEnableKernelIpc) {
193 ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
194 return INVALID_OPERATION;
195 }
196
197 BBinder* local = this->localBinder();
198 if (local != nullptr) {
199 return local->BBinder::setRpcClientDebug(std::move(socketFd), keepAliveBinder);
200 }
201
202 BpBinder* proxy = this->remoteBinder();
203 LOG_ALWAYS_FATAL_IF(proxy == nullptr, "binder object must be either local or remote");
204
205 Parcel data;
206 Parcel reply;
207 status_t status;
208 if (status = data.writeBool(socketFd.ok()); status != OK) return status;
209 if (socketFd.ok()) {
210 // writeUniqueFileDescriptor currently makes an unnecessary dup().
211 status = data.writeFileDescriptor(socketFd.release(), true /* own */);
212 if (status != OK) return status;
213 }
214 if (status = data.writeStrongBinder(keepAliveBinder); status != OK) return status;
215 return transact(SET_RPC_CLIENT_TRANSACTION, data, &reply);
216 }
217
withLock(const std::function<void ()> & doWithLock)218 void IBinder::withLock(const std::function<void()>& doWithLock) {
219 BBinder* local = localBinder();
220 if (local) {
221 local->withLock(doWithLock);
222 return;
223 }
224 BpBinder* proxy = this->remoteBinder();
225 LOG_ALWAYS_FATAL_IF(proxy == nullptr, "binder object must be either local or remote");
226 proxy->withLock(doWithLock);
227 }
228
lookupOrCreateWeak(const void * objectID,object_make_func make,const void * makeArgs)229 sp<IBinder> IBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
230 const void* makeArgs) {
231 BBinder* local = localBinder();
232 if (local) {
233 return local->lookupOrCreateWeak(objectID, make, makeArgs);
234 }
235 BpBinder* proxy = this->remoteBinder();
236 LOG_ALWAYS_FATAL_IF(proxy == nullptr, "binder object must be either local or remote");
237 return proxy->lookupOrCreateWeak(objectID, make, makeArgs);
238 }
239
240 // ---------------------------------------------------------------------------
241
242 class BBinder::RpcServerLink : public IBinder::DeathRecipient {
243 public:
244 // On binder died, calls RpcServer::shutdown on @a rpcServer, and removes itself from @a binder.
RpcServerLink(const sp<RpcServer> & rpcServer,const sp<IBinder> & keepAliveBinder,const wp<BBinder> & binder)245 RpcServerLink(const sp<RpcServer>& rpcServer, const sp<IBinder>& keepAliveBinder,
246 const wp<BBinder>& binder)
247 : mRpcServer(rpcServer), mKeepAliveBinder(keepAliveBinder), mBinder(binder) {}
248 virtual ~RpcServerLink();
binderDied(const wp<IBinder> &)249 void binderDied(const wp<IBinder>&) override {
250 auto promoted = mBinder.promote();
251 ALOGI("RpcBinder: binder died, shutting down RpcServer for %s",
252 promoted ? String8(promoted->getInterfaceDescriptor()).c_str() : "<NULL>");
253
254 if (mRpcServer == nullptr) {
255 ALOGW("RpcServerLink: Unable to shut down RpcServer because it does not exist.");
256 } else {
257 ALOGW_IF(!mRpcServer->shutdown(),
258 "RpcServerLink: RpcServer did not shut down properly. Not started?");
259 }
260 mRpcServer.clear();
261
262 if (promoted) {
263 promoted->removeRpcServerLink(sp<RpcServerLink>::fromExisting(this));
264 }
265 mBinder.clear();
266 }
267
268 private:
269 sp<RpcServer> mRpcServer;
270 sp<IBinder> mKeepAliveBinder; // hold to avoid automatically unlinking
271 wp<BBinder> mBinder;
272 };
~RpcServerLink()273 BBinder::RpcServerLink::~RpcServerLink() {}
274
275 class BBinder::Extras
276 {
277 public:
278 // unlocked objects
279 sp<IBinder> mExtension;
280 #ifdef __linux__
281 int mPolicy = SCHED_NORMAL;
282 int mPriority = 0;
283 #endif
284 bool mRequestingSid = false;
285 bool mInheritRt = false;
286
287 // for below objects
288 RpcMutex mLock;
289 std::set<sp<RpcServerLink>> mRpcServerLinks;
290 BpBinder::ObjectManager mObjectMgr;
291
292 unique_fd mRecordingFd;
293 };
294
295 // ---------------------------------------------------------------------------
296
BBinder()297 BBinder::BBinder() : mExtras(nullptr), mStability(0), mParceled(false), mRecordingOn(false) {}
298
isBinderAlive() const299 bool BBinder::isBinderAlive() const
300 {
301 return true;
302 }
303
pingBinder()304 status_t BBinder::pingBinder()
305 {
306 return NO_ERROR;
307 }
308
startRecordingTransactions(const Parcel & data)309 status_t BBinder::startRecordingTransactions(const Parcel& data) {
310 if (!kEnableRecording) {
311 ALOGW("Binder recording disallowed because recording is not enabled");
312 return INVALID_OPERATION;
313 }
314 if (!kEnableKernelIpc) {
315 ALOGW("Binder recording disallowed because kernel binder is not enabled");
316 return INVALID_OPERATION;
317 }
318 uid_t uid = IPCThreadState::self()->getCallingUid();
319 if (uid != kUidRoot) {
320 ALOGE("Binder recording not allowed because client %" PRIu32 " is not root", uid);
321 return PERMISSION_DENIED;
322 }
323 Extras* e = getOrCreateExtras();
324 RpcMutexUniqueLock lock(e->mLock);
325 if (mRecordingOn) {
326 ALOGI("Could not start Binder recording. Another is already in progress.");
327 return INVALID_OPERATION;
328 } else {
329 status_t readStatus = data.readUniqueFileDescriptor(&(e->mRecordingFd));
330 if (readStatus != OK) {
331 return readStatus;
332 }
333 mRecordingOn = true;
334 ALOGI("Started Binder recording.");
335 return NO_ERROR;
336 }
337 }
338
stopRecordingTransactions()339 status_t BBinder::stopRecordingTransactions() {
340 if (!kEnableRecording) {
341 ALOGW("Binder recording disallowed because recording is not enabled");
342 return INVALID_OPERATION;
343 }
344 if (!kEnableKernelIpc) {
345 ALOGW("Binder recording disallowed because kernel binder is not enabled");
346 return INVALID_OPERATION;
347 }
348 uid_t uid = IPCThreadState::self()->getCallingUid();
349 if (uid != kUidRoot) {
350 ALOGE("Binder recording not allowed because client %" PRIu32 " is not root", uid);
351 return PERMISSION_DENIED;
352 }
353 Extras* e = getOrCreateExtras();
354 RpcMutexUniqueLock lock(e->mLock);
355 if (mRecordingOn) {
356 e->mRecordingFd.reset();
357 mRecordingOn = false;
358 ALOGI("Stopped Binder recording.");
359 return NO_ERROR;
360 } else {
361 ALOGI("Could not stop Binder recording. One is not in progress.");
362 return INVALID_OPERATION;
363 }
364 }
365
getInterfaceDescriptor() const366 const String16& BBinder::getInterfaceDescriptor() const
367 {
368 static StaticString16 sBBinder(u"BBinder");
369 ALOGW("Reached BBinder::getInterfaceDescriptor (this=%p). Override?", this);
370 return sBBinder;
371 }
372
373 // NOLINTNEXTLINE(google-default-arguments)
transact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)374 status_t BBinder::transact(
375 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
376 {
377 data.setDataPosition(0);
378
379 if (reply != nullptr && (flags & FLAG_CLEAR_BUF)) {
380 reply->markSensitive();
381 }
382
383 status_t err = NO_ERROR;
384 switch (code) {
385 case PING_TRANSACTION:
386 err = pingBinder();
387 break;
388 case START_RECORDING_TRANSACTION:
389 err = startRecordingTransactions(data);
390 break;
391 case STOP_RECORDING_TRANSACTION:
392 err = stopRecordingTransactions();
393 break;
394 case EXTENSION_TRANSACTION:
395 LOG_ALWAYS_FATAL_IF(reply == nullptr, "reply == nullptr");
396 err = reply->writeStrongBinder(getExtension());
397 break;
398 case DEBUG_PID_TRANSACTION:
399 LOG_ALWAYS_FATAL_IF(reply == nullptr, "reply == nullptr");
400 err = reply->writeInt32(getDebugPid());
401 break;
402 case SET_RPC_CLIENT_TRANSACTION: {
403 err = setRpcClientDebug(data);
404 break;
405 }
406 default:
407 err = onTransact(code, data, reply, flags);
408 break;
409 }
410
411 // In case this is being transacted on in the same process.
412 if (reply != nullptr) {
413 reply->setDataPosition(0);
414 if (reply->dataSize() > binder::kLogTransactionsOverBytes) {
415 ALOGW("Large reply transaction of %zu bytes, interface descriptor %s, code %d",
416 reply->dataSize(), String8(getInterfaceDescriptor()).c_str(), code);
417 }
418 }
419
420 if (kEnableKernelIpc && mRecordingOn && code != START_RECORDING_TRANSACTION) [[unlikely]] {
421 Extras* e = mExtras.load(std::memory_order_acquire);
422 RpcMutexUniqueLock lock(e->mLock);
423 if (mRecordingOn) {
424 Parcel emptyReply;
425 timespec ts;
426 timespec_get(&ts, TIME_UTC);
427 auto transaction = android::binder::debug::RecordedTransaction::
428 fromDetails(getInterfaceDescriptor(), code, flags, ts, data,
429 reply ? *reply : emptyReply, err);
430 if (transaction) {
431 if (status_t err = transaction->dumpToFile(e->mRecordingFd); err != NO_ERROR) {
432 ALOGI("Failed to dump RecordedTransaction to file with error %d", err);
433 }
434 } else {
435 ALOGI("Failed to create RecordedTransaction object.");
436 }
437 }
438 }
439
440 return err;
441 }
442
443 // NOLINTNEXTLINE(google-default-arguments)
linkToDeath(const sp<DeathRecipient> &,void *,uint32_t)444 status_t BBinder::linkToDeath(
445 const sp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
446 uint32_t /*flags*/)
447 {
448 // BBinder::linkToDeath is invalid because this process owns this binder.
449 // The DeathRecipient is called on BpBinders when the process owning the
450 // binder node dies.
451 return INVALID_OPERATION;
452 }
453
454 // NOLINTNEXTLINE(google-default-arguments)
unlinkToDeath(const wp<DeathRecipient> &,void *,uint32_t,wp<DeathRecipient> *)455 status_t BBinder::unlinkToDeath(
456 const wp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
457 uint32_t /*flags*/, wp<DeathRecipient>* /*outRecipient*/)
458 {
459 return INVALID_OPERATION;
460 }
461
dump(int,const Vector<String16> &)462 status_t BBinder::dump(int /*fd*/, const Vector<String16>& /*args*/)
463 {
464 return NO_ERROR;
465 }
466
attachObject(const void * objectID,void * object,void * cleanupCookie,object_cleanup_func func)467 void* BBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
468 object_cleanup_func func) {
469 Extras* e = getOrCreateExtras();
470 LOG_ALWAYS_FATAL_IF(!e, "no memory");
471
472 RpcMutexUniqueLock _l(e->mLock);
473 return e->mObjectMgr.attach(objectID, object, cleanupCookie, func);
474 }
475
findObject(const void * objectID) const476 void* BBinder::findObject(const void* objectID) const
477 {
478 Extras* e = mExtras.load(std::memory_order_acquire);
479 if (!e) return nullptr;
480
481 RpcMutexUniqueLock _l(e->mLock);
482 return e->mObjectMgr.find(objectID);
483 }
484
detachObject(const void * objectID)485 void* BBinder::detachObject(const void* objectID) {
486 Extras* e = mExtras.load(std::memory_order_acquire);
487 if (!e) return nullptr;
488
489 RpcMutexUniqueLock _l(e->mLock);
490 return e->mObjectMgr.detach(objectID);
491 }
492
withLock(const std::function<void ()> & doWithLock)493 void BBinder::withLock(const std::function<void()>& doWithLock) {
494 Extras* e = getOrCreateExtras();
495 LOG_ALWAYS_FATAL_IF(!e, "no memory");
496
497 RpcMutexUniqueLock _l(e->mLock);
498 doWithLock();
499 }
500
lookupOrCreateWeak(const void * objectID,object_make_func make,const void * makeArgs)501 sp<IBinder> BBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
502 const void* makeArgs) {
503 Extras* e = getOrCreateExtras();
504 LOG_ALWAYS_FATAL_IF(!e, "no memory");
505 RpcMutexUniqueLock _l(e->mLock);
506 return e->mObjectMgr.lookupOrCreateWeak(objectID, make, makeArgs);
507 }
508
localBinder()509 BBinder* BBinder::localBinder()
510 {
511 return this;
512 }
513
isRequestingSid()514 bool BBinder::isRequestingSid()
515 {
516 Extras* e = mExtras.load(std::memory_order_acquire);
517
518 return e && e->mRequestingSid;
519 }
520
setRequestingSid(bool requestingSid)521 void BBinder::setRequestingSid(bool requestingSid)
522 {
523 LOG_ALWAYS_FATAL_IF(mParceled,
524 "setRequestingSid() should not be called after a binder object "
525 "is parceled/sent to another process");
526
527 Extras* e = mExtras.load(std::memory_order_acquire);
528
529 if (!e) {
530 // default is false. Most things don't need sids, so avoiding allocations when possible.
531 if (!requestingSid) {
532 return;
533 }
534
535 e = getOrCreateExtras();
536 if (!e) return; // out of memory
537 }
538
539 e->mRequestingSid = requestingSid;
540 }
541
getExtension()542 sp<IBinder> BBinder::getExtension() {
543 Extras* e = mExtras.load(std::memory_order_acquire);
544 if (e == nullptr) return nullptr;
545 return e->mExtension;
546 }
547
548 #ifdef __linux__
setMinSchedulerPolicy(int policy,int priority)549 void BBinder::setMinSchedulerPolicy(int policy, int priority) {
550 LOG_ALWAYS_FATAL_IF(mParceled,
551 "setMinSchedulerPolicy() should not be called after a binder object "
552 "is parceled/sent to another process");
553
554 switch (policy) {
555 case SCHED_NORMAL:
556 LOG_ALWAYS_FATAL_IF(priority < -20 || priority > 19, "Invalid priority for SCHED_NORMAL: %d", priority);
557 break;
558 case SCHED_RR:
559 case SCHED_FIFO:
560 LOG_ALWAYS_FATAL_IF(priority < 1 || priority > 99, "Invalid priority for sched %d: %d", policy, priority);
561 break;
562 default:
563 LOG_ALWAYS_FATAL("Unrecognized scheduling policy: %d", policy);
564 }
565
566 Extras* e = mExtras.load(std::memory_order_acquire);
567
568 if (e == nullptr) {
569 // Avoid allocations if called with default.
570 if (policy == SCHED_NORMAL && priority == 0) {
571 return;
572 }
573
574 e = getOrCreateExtras();
575 if (!e) return; // out of memory
576 }
577
578 e->mPolicy = policy;
579 e->mPriority = priority;
580 }
581
getMinSchedulerPolicy()582 int BBinder::getMinSchedulerPolicy() {
583 Extras* e = mExtras.load(std::memory_order_acquire);
584 if (e == nullptr) return SCHED_NORMAL;
585 return e->mPolicy;
586 }
587
getMinSchedulerPriority()588 int BBinder::getMinSchedulerPriority() {
589 Extras* e = mExtras.load(std::memory_order_acquire);
590 if (e == nullptr) return 0;
591 return e->mPriority;
592 }
593 #endif // __linux__
594
isInheritRt()595 bool BBinder::isInheritRt() {
596 Extras* e = mExtras.load(std::memory_order_acquire);
597
598 return e && e->mInheritRt;
599 }
600
setInheritRt(bool inheritRt)601 void BBinder::setInheritRt(bool inheritRt) {
602 LOG_ALWAYS_FATAL_IF(mParceled,
603 "setInheritRt() should not be called after a binder object "
604 "is parceled/sent to another process");
605
606 Extras* e = mExtras.load(std::memory_order_acquire);
607
608 if (!e) {
609 if (!inheritRt) {
610 return;
611 }
612
613 e = getOrCreateExtras();
614 if (!e) return; // out of memory
615 }
616
617 e->mInheritRt = inheritRt;
618 }
619
getDebugPid()620 pid_t BBinder::getDebugPid() {
621 #ifdef __linux__
622 return getpid();
623 #else
624 // TODO: handle other OSes
625 return 0;
626 #endif // __linux__
627 }
628
setExtension(const sp<IBinder> & extension)629 void BBinder::setExtension(const sp<IBinder>& extension) {
630 LOG_ALWAYS_FATAL_IF(mParceled,
631 "setExtension() should not be called after a binder object "
632 "is parceled/sent to another process");
633
634 Extras* e = getOrCreateExtras();
635 e->mExtension = extension;
636 }
637
wasParceled()638 bool BBinder::wasParceled() {
639 return mParceled;
640 }
641
setParceled()642 void BBinder::setParceled() {
643 mParceled = true;
644 }
645
setRpcClientDebug(const Parcel & data)646 status_t BBinder::setRpcClientDebug(const Parcel& data) {
647 if (!kEnableRpcDevServers) {
648 ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
649 return INVALID_OPERATION;
650 }
651 if (!kEnableKernelIpc) {
652 ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
653 return INVALID_OPERATION;
654 }
655 uid_t uid = IPCThreadState::self()->getCallingUid();
656 if (uid != kUidRoot) {
657 ALOGE("%s: not allowed because client %" PRIu32 " is not root", __PRETTY_FUNCTION__, uid);
658 return PERMISSION_DENIED;
659 }
660 status_t status;
661 bool hasSocketFd;
662 unique_fd clientFd;
663
664 if (status = data.readBool(&hasSocketFd); status != OK) return status;
665 if (hasSocketFd) {
666 if (status = data.readUniqueFileDescriptor(&clientFd); status != OK) return status;
667 }
668 sp<IBinder> keepAliveBinder;
669 if (status = data.readNullableStrongBinder(&keepAliveBinder); status != OK) return status;
670
671 return setRpcClientDebug(std::move(clientFd), keepAliveBinder);
672 }
673
setRpcClientDebug(unique_fd socketFd,const sp<IBinder> & keepAliveBinder)674 status_t BBinder::setRpcClientDebug(unique_fd socketFd, const sp<IBinder>& keepAliveBinder) {
675 if (!kEnableRpcDevServers) {
676 ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
677 return INVALID_OPERATION;
678 }
679 if (!kEnableKernelIpc) {
680 ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
681 return INVALID_OPERATION;
682 }
683
684 const int socketFdForPrint = socketFd.get();
685 LOG_RPC_DETAIL("%s(fd=%d)", __PRETTY_FUNCTION__, socketFdForPrint);
686
687 if (!socketFd.ok()) {
688 ALOGE("%s: No socket FD provided.", __PRETTY_FUNCTION__);
689 return BAD_VALUE;
690 }
691
692 if (keepAliveBinder == nullptr) {
693 ALOGE("%s: No keepAliveBinder provided.", __PRETTY_FUNCTION__);
694 return UNEXPECTED_NULL;
695 }
696
697 size_t binderThreadPoolMaxCount = ProcessState::self()->getThreadPoolMaxTotalThreadCount();
698 if (binderThreadPoolMaxCount <= 1) {
699 ALOGE("%s: ProcessState thread pool max count is %zu. RPC is disabled for this service "
700 "because RPC requires the service to support multithreading.",
701 __PRETTY_FUNCTION__, binderThreadPoolMaxCount);
702 return INVALID_OPERATION;
703 }
704
705 // Weak ref to avoid circular dependency:
706 // BBinder -> RpcServerLink ----> RpcServer -X-> BBinder
707 // `-X-> BBinder
708 auto weakThis = wp<BBinder>::fromExisting(this);
709
710 Extras* e = getOrCreateExtras();
711 RpcMutexUniqueLock _l(e->mLock);
712 auto rpcServer = RpcServer::make();
713 LOG_ALWAYS_FATAL_IF(rpcServer == nullptr, "RpcServer::make returns null");
714 auto link = sp<RpcServerLink>::make(rpcServer, keepAliveBinder, weakThis);
715 if (auto status = keepAliveBinder->linkToDeath(link, nullptr, 0); status != OK) {
716 ALOGE("%s: keepAliveBinder->linkToDeath returns %s", __PRETTY_FUNCTION__,
717 statusToString(status).c_str());
718 return status;
719 }
720 rpcServer->setRootObjectWeak(weakThis);
721 if (auto status = rpcServer->setupExternalServer(std::move(socketFd)); status != OK) {
722 return status;
723 }
724 rpcServer->setMaxThreads(binderThreadPoolMaxCount);
725 ALOGI("RpcBinder: Started Binder debug on %s", String8(getInterfaceDescriptor()).c_str());
726 rpcServer->start();
727 e->mRpcServerLinks.emplace(link);
728 LOG_RPC_DETAIL("%s(fd=%d) successful", __PRETTY_FUNCTION__, socketFdForPrint);
729 return OK;
730 }
731
removeRpcServerLink(const sp<RpcServerLink> & link)732 void BBinder::removeRpcServerLink(const sp<RpcServerLink>& link) {
733 Extras* e = mExtras.load(std::memory_order_acquire);
734 if (!e) return;
735 RpcMutexUniqueLock _l(e->mLock);
736 (void)e->mRpcServerLinks.erase(link);
737 }
738
~BBinder()739 BBinder::~BBinder()
740 {
741 if (!wasParceled()) {
742 if (getExtension()) {
743 ALOGW("Binder %p destroyed with extension attached before being parceled.", this);
744 }
745 if (isRequestingSid()) {
746 ALOGW("Binder %p destroyed when requesting SID before being parceled.", this);
747 }
748 if (isInheritRt()) {
749 ALOGW("Binder %p destroyed after setInheritRt before being parceled.", this);
750 }
751 #ifdef __linux__
752 if (getMinSchedulerPolicy() != SCHED_NORMAL) {
753 ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
754 }
755 if (getMinSchedulerPriority() != 0) {
756 ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
757 }
758 #endif // __linux__
759 }
760
761 Extras* e = mExtras.load(std::memory_order_relaxed);
762 if (e) delete e;
763 }
764
765
766 // NOLINTNEXTLINE(google-default-arguments)
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t)767 status_t BBinder::onTransact(
768 uint32_t code, const Parcel& data, Parcel* reply, uint32_t /*flags*/)
769 {
770 switch (code) {
771 case INTERFACE_TRANSACTION:
772 LOG_ALWAYS_FATAL_IF(reply == nullptr, "reply == nullptr");
773 reply->writeString16(getInterfaceDescriptor());
774 return NO_ERROR;
775
776 case DUMP_TRANSACTION: {
777 int fd = data.readFileDescriptor();
778 int argc = data.readInt32();
779 Vector<String16> args;
780 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
781 args.add(data.readString16());
782 }
783 return dump(fd, args);
784 }
785
786 case SHELL_COMMAND_TRANSACTION: {
787 int in = data.readFileDescriptor();
788 int out = data.readFileDescriptor();
789 int err = data.readFileDescriptor();
790 int argc = data.readInt32();
791 Vector<String16> args;
792 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
793 args.add(data.readString16());
794 }
795 sp<IBinder> shellCallbackBinder = data.readStrongBinder();
796 sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(
797 data.readStrongBinder());
798
799 // XXX can't add virtuals until binaries are updated.
800 // sp<IShellCallback> shellCallback = IShellCallback::asInterface(
801 // shellCallbackBinder);
802 // return shellCommand(in, out, err, args, resultReceiver);
803 (void)in;
804 (void)out;
805 (void)err;
806
807 if (resultReceiver != nullptr) {
808 resultReceiver->send(INVALID_OPERATION);
809 }
810
811 return NO_ERROR;
812 }
813
814 case SYSPROPS_TRANSACTION: {
815 if (!binder::os::report_sysprop_change()) return INVALID_OPERATION;
816 return NO_ERROR;
817 }
818
819 default:
820 return UNKNOWN_TRANSACTION;
821 }
822 }
823
getOrCreateExtras()824 BBinder::Extras* BBinder::getOrCreateExtras()
825 {
826 Extras* e = mExtras.load(std::memory_order_acquire);
827
828 if (!e) {
829 e = new Extras;
830 Extras* expected = nullptr;
831 if (!mExtras.compare_exchange_strong(expected, e,
832 std::memory_order_release,
833 std::memory_order_acquire)) {
834 delete e;
835 e = expected; // Filled in by CAS
836 }
837 if (e == nullptr) return nullptr; // out of memory
838 }
839
840 return e;
841 }
842
843 // ---------------------------------------------------------------------------
844
845 enum {
846 // This is used to transfer ownership of the remote binder from
847 // the BpRefBase object holding it (when it is constructed), to the
848 // owner of the BpRefBase object when it first acquires that BpRefBase.
849 kRemoteAcquired = 0x00000001
850 };
851
BpRefBase(const sp<IBinder> & o)852 BpRefBase::BpRefBase(const sp<IBinder>& o)
853 : mRemote(o.get()), mRefs(nullptr), mState(0)
854 {
855 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
856
857 if (mRemote) {
858 mRemote->incStrong(this); // Removed on first IncStrong().
859 mRefs = mRemote->createWeak(this); // Held for our entire lifetime.
860 }
861 }
862
~BpRefBase()863 BpRefBase::~BpRefBase()
864 {
865 if (mRemote) {
866 if (!(mState.load(std::memory_order_relaxed)&kRemoteAcquired)) {
867 mRemote->decStrong(this);
868 }
869 mRefs->decWeak(this);
870 }
871 }
872
onFirstRef()873 void BpRefBase::onFirstRef()
874 {
875 mState.fetch_or(kRemoteAcquired, std::memory_order_relaxed);
876 }
877
onLastStrongRef(const void *)878 void BpRefBase::onLastStrongRef(const void* /*id*/)
879 {
880 if (mRemote) {
881 mRemote->decStrong(this);
882 }
883 }
884
onIncStrongAttempted(uint32_t,const void *)885 bool BpRefBase::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
886 {
887 return mRemote ? mRefs->attemptIncStrong(this) : false;
888 }
889
890 // ---------------------------------------------------------------------------
891
892 } // namespace android
893