• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <android-base/logging.h>
23 #include <android-base/unique_fd.h>
24 #include <binder/BpBinder.h>
25 #include <binder/IInterface.h>
26 #include <binder/IPCThreadState.h>
27 #include <binder/IResultReceiver.h>
28 #include <binder/IShellCallback.h>
29 #include <binder/Parcel.h>
30 #include <binder/RecordedTransaction.h>
31 #include <binder/RpcServer.h>
32 #include <cutils/compiler.h>
33 #include <private/android_filesystem_config.h>
34 #include <pthread.h>
35 #include <utils/misc.h>
36 
37 #include <inttypes.h>
38 #include <stdio.h>
39 
40 #ifdef __linux__
41 #include <linux/sched.h>
42 #endif
43 
44 #include "BuildFlags.h"
45 #include "RpcState.h"
46 
47 namespace android {
48 
49 // Service implementations inherit from BBinder and IBinder, and this is frozen
50 // in prebuilts.
51 #ifdef __LP64__
52 static_assert(sizeof(IBinder) == 24);
53 static_assert(sizeof(BBinder) == 40);
54 #else
55 static_assert(sizeof(IBinder) == 12);
56 static_assert(sizeof(BBinder) == 20);
57 #endif
58 
59 // global b/c b/230079120 - consistent symbol table
60 #ifdef BINDER_RPC_DEV_SERVERS
61 bool kEnableRpcDevServers = true;
62 #else
63 bool kEnableRpcDevServers = false;
64 #endif
65 
66 #ifdef BINDER_ENABLE_RECORDING
67 bool kEnableRecording = true;
68 #else
69 bool kEnableRecording = false;
70 #endif
71 
72 // Log any reply transactions for which the data exceeds this size
73 #define LOG_REPLIES_OVER_SIZE (300 * 1024)
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 
getDebugPid(pid_t * out)145 status_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 
setRpcClientDebug(android::base::unique_fd socketFd,const sp<IBinder> & keepAliveBinder)171 status_t IBinder::setRpcClientDebug(android::base::unique_fd socketFd,
172                                     const sp<IBinder>& keepAliveBinder) {
173     if (!kEnableRpcDevServers) {
174         ALOGW("setRpcClientDebug disallowed because RPC is not enabled");
175         return INVALID_OPERATION;
176     }
177     if (!kEnableKernelIpc) {
178         ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
179         return INVALID_OPERATION;
180     }
181 
182     BBinder* local = this->localBinder();
183     if (local != nullptr) {
184         return local->BBinder::setRpcClientDebug(std::move(socketFd), keepAliveBinder);
185     }
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     }
199     if (status = data.writeStrongBinder(keepAliveBinder); status != OK) return status;
200     return transact(SET_RPC_CLIENT_TRANSACTION, data, &reply);
201 }
202 
withLock(const std::function<void ()> & doWithLock)203 void 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 
lookupOrCreateWeak(const void * objectID,object_make_func make,const void * makeArgs)214 sp<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 
225 // ---------------------------------------------------------------------------
226 
227 class BBinder::RpcServerLink : public IBinder::DeathRecipient {
228 public:
229     // 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)230     RpcServerLink(const sp<RpcServer>& rpcServer, const sp<IBinder>& keepAliveBinder,
231                   const wp<BBinder>& binder)
232           : mRpcServer(rpcServer), mKeepAliveBinder(keepAliveBinder), mBinder(binder) {}
233     virtual ~RpcServerLink();
binderDied(const wp<IBinder> &)234     void binderDied(const wp<IBinder>&) override {
235         auto promoted = mBinder.promote();
236         ALOGI("RpcBinder: binder died, shutting down RpcServer for %s",
237               promoted ? String8(promoted->getInterfaceDescriptor()).c_str() : "<NULL>");
238 
239         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 
247         if (promoted) {
248             promoted->removeRpcServerLink(sp<RpcServerLink>::fromExisting(this));
249         }
250         mBinder.clear();
251     }
252 
253 private:
254     sp<RpcServer> mRpcServer;
255     sp<IBinder> mKeepAliveBinder; // hold to avoid automatically unlinking
256     wp<BBinder> mBinder;
257 };
~RpcServerLink()258 BBinder::RpcServerLink::~RpcServerLink() {}
259 
260 class BBinder::Extras
261 {
262 public:
263     // unlocked objects
264     sp<IBinder> mExtension;
265 #ifdef __linux__
266     int mPolicy = SCHED_NORMAL;
267     int mPriority = 0;
268 #endif
269     bool mRequestingSid = false;
270     bool mInheritRt = false;
271 
272     // for below objects
273     Mutex mLock;
274     std::set<sp<RpcServerLink>> mRpcServerLinks;
275     BpBinder::ObjectManager mObjects;
276 
277     android::base::unique_fd mRecordingFd;
278 };
279 
280 // ---------------------------------------------------------------------------
281 
BBinder()282 BBinder::BBinder() : mExtras(nullptr), mStability(0), mParceled(false), mRecordingOn(false) {}
283 
isBinderAlive() const284 bool BBinder::isBinderAlive() const
285 {
286     return true;
287 }
288 
pingBinder()289 status_t BBinder::pingBinder()
290 {
291     return NO_ERROR;
292 }
293 
startRecordingTransactions(const Parcel & data)294 status_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 
stopRecordingTransactions()324 status_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 
getInterfaceDescriptor() const351 const String16& BBinder::getInterfaceDescriptor() const
352 {
353     static StaticString16 sBBinder(u"BBinder");
354     ALOGW("Reached BBinder::getInterfaceDescriptor (this=%p). Override?", this);
355     return sBBinder;
356 }
357 
358 // NOLINTNEXTLINE(google-default-arguments)
transact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)359 status_t BBinder::transact(
360     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
361 {
362     data.setDataPosition(0);
363 
364     if (reply != nullptr && (flags & FLAG_CLEAR_BUF)) {
365         reply->markSensitive();
366     }
367 
368     status_t err = NO_ERROR;
369     switch (code) {
370         case PING_TRANSACTION:
371             err = pingBinder();
372             break;
373         case START_RECORDING_TRANSACTION:
374             err = startRecordingTransactions(data);
375             break;
376         case STOP_RECORDING_TRANSACTION:
377             err = stopRecordingTransactions();
378             break;
379         case EXTENSION_TRANSACTION:
380             CHECK(reply != nullptr);
381             err = reply->writeStrongBinder(getExtension());
382             break;
383         case DEBUG_PID_TRANSACTION:
384             CHECK(reply != nullptr);
385             err = reply->writeInt32(getDebugPid());
386             break;
387         case SET_RPC_CLIENT_TRANSACTION: {
388             err = setRpcClientDebug(data);
389             break;
390         }
391         default:
392             err = onTransact(code, data, reply, flags);
393             break;
394     }
395 
396     // In case this is being transacted on in the same process.
397     if (reply != nullptr) {
398         reply->setDataPosition(0);
399         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         }
403     }
404 
405     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;
410             timespec ts;
411             timespec_get(&ts, TIME_UTC);
412             auto transaction = android::binder::debug::RecordedTransaction::
413                     fromDetails(getInterfaceDescriptor(), code, flags, ts, data,
414                                 reply ? *reply : emptyReply, err);
415             if (transaction) {
416                 if (status_t err = transaction->dumpToFile(e->mRecordingFd); err != NO_ERROR) {
417                     LOG(INFO) << "Failed to dump RecordedTransaction to file with error " << err;
418                 }
419             } else {
420                 LOG(INFO) << "Failed to create RecordedTransaction object.";
421             }
422         }
423     }
424 
425     return err;
426 }
427 
428 // NOLINTNEXTLINE(google-default-arguments)
linkToDeath(const sp<DeathRecipient> &,void *,uint32_t)429 status_t BBinder::linkToDeath(
430     const sp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
431     uint32_t /*flags*/)
432 {
433     return INVALID_OPERATION;
434 }
435 
436 // NOLINTNEXTLINE(google-default-arguments)
unlinkToDeath(const wp<DeathRecipient> &,void *,uint32_t,wp<DeathRecipient> *)437 status_t BBinder::unlinkToDeath(
438     const wp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
439     uint32_t /*flags*/, wp<DeathRecipient>* /*outRecipient*/)
440 {
441     return INVALID_OPERATION;
442 }
443 
dump(int,const Vector<String16> &)444 status_t BBinder::dump(int /*fd*/, const Vector<String16>& /*args*/)
445 {
446     return NO_ERROR;
447 }
448 
attachObject(const void * objectID,void * object,void * cleanupCookie,object_cleanup_func func)449 void* BBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
450                             object_cleanup_func func) {
451     Extras* e = getOrCreateExtras();
452     LOG_ALWAYS_FATAL_IF(!e, "no memory");
453 
454     AutoMutex _l(e->mLock);
455     return e->mObjects.attach(objectID, object, cleanupCookie, func);
456 }
457 
findObject(const void * objectID) const458 void* BBinder::findObject(const void* objectID) const
459 {
460     Extras* e = mExtras.load(std::memory_order_acquire);
461     if (!e) return nullptr;
462 
463     AutoMutex _l(e->mLock);
464     return e->mObjects.find(objectID);
465 }
466 
detachObject(const void * objectID)467 void* BBinder::detachObject(const void* objectID) {
468     Extras* e = mExtras.load(std::memory_order_acquire);
469     if (!e) return nullptr;
470 
471     AutoMutex _l(e->mLock);
472     return e->mObjects.detach(objectID);
473 }
474 
withLock(const std::function<void ()> & doWithLock)475 void BBinder::withLock(const std::function<void()>& doWithLock) {
476     Extras* e = getOrCreateExtras();
477     LOG_ALWAYS_FATAL_IF(!e, "no memory");
478 
479     AutoMutex _l(e->mLock);
480     doWithLock();
481 }
482 
lookupOrCreateWeak(const void * objectID,object_make_func make,const void * makeArgs)483 sp<IBinder> BBinder::lookupOrCreateWeak(const void* objectID, object_make_func make,
484                                         const void* makeArgs) {
485     Extras* e = getOrCreateExtras();
486     LOG_ALWAYS_FATAL_IF(!e, "no memory");
487     AutoMutex _l(e->mLock);
488     return e->mObjects.lookupOrCreateWeak(objectID, make, makeArgs);
489 }
490 
localBinder()491 BBinder* BBinder::localBinder()
492 {
493     return this;
494 }
495 
isRequestingSid()496 bool BBinder::isRequestingSid()
497 {
498     Extras* e = mExtras.load(std::memory_order_acquire);
499 
500     return e && e->mRequestingSid;
501 }
502 
setRequestingSid(bool requestingSid)503 void BBinder::setRequestingSid(bool requestingSid)
504 {
505     LOG_ALWAYS_FATAL_IF(mParceled,
506                         "setRequestingSid() should not be called after a binder object "
507                         "is parceled/sent to another process");
508 
509     Extras* e = mExtras.load(std::memory_order_acquire);
510 
511     if (!e) {
512         // default is false. Most things don't need sids, so avoiding allocations when possible.
513         if (!requestingSid) {
514             return;
515         }
516 
517         e = getOrCreateExtras();
518         if (!e) return; // out of memory
519     }
520 
521     e->mRequestingSid = requestingSid;
522 }
523 
getExtension()524 sp<IBinder> BBinder::getExtension() {
525     Extras* e = mExtras.load(std::memory_order_acquire);
526     if (e == nullptr) return nullptr;
527     return e->mExtension;
528 }
529 
530 #ifdef __linux__
setMinSchedulerPolicy(int policy,int priority)531 void BBinder::setMinSchedulerPolicy(int policy, int priority) {
532     LOG_ALWAYS_FATAL_IF(mParceled,
533                         "setMinSchedulerPolicy() should not be called after a binder object "
534                         "is parceled/sent to another process");
535 
536     switch (policy) {
537     case SCHED_NORMAL:
538       LOG_ALWAYS_FATAL_IF(priority < -20 || priority > 19, "Invalid priority for SCHED_NORMAL: %d", priority);
539       break;
540     case SCHED_RR:
541     case SCHED_FIFO:
542       LOG_ALWAYS_FATAL_IF(priority < 1 || priority > 99, "Invalid priority for sched %d: %d", policy, priority);
543       break;
544     default:
545       LOG_ALWAYS_FATAL("Unrecognized scheduling policy: %d", policy);
546     }
547 
548     Extras* e = mExtras.load(std::memory_order_acquire);
549 
550     if (e == nullptr) {
551         // Avoid allocations if called with default.
552         if (policy == SCHED_NORMAL && priority == 0) {
553             return;
554         }
555 
556         e = getOrCreateExtras();
557         if (!e) return; // out of memory
558     }
559 
560     e->mPolicy = policy;
561     e->mPriority = priority;
562 }
563 
getMinSchedulerPolicy()564 int BBinder::getMinSchedulerPolicy() {
565     Extras* e = mExtras.load(std::memory_order_acquire);
566     if (e == nullptr) return SCHED_NORMAL;
567     return e->mPolicy;
568 }
569 
getMinSchedulerPriority()570 int BBinder::getMinSchedulerPriority() {
571     Extras* e = mExtras.load(std::memory_order_acquire);
572     if (e == nullptr) return 0;
573     return e->mPriority;
574 }
575 #endif // __linux__
576 
isInheritRt()577 bool BBinder::isInheritRt() {
578     Extras* e = mExtras.load(std::memory_order_acquire);
579 
580     return e && e->mInheritRt;
581 }
582 
setInheritRt(bool inheritRt)583 void BBinder::setInheritRt(bool inheritRt) {
584     LOG_ALWAYS_FATAL_IF(mParceled,
585                         "setInheritRt() should not be called after a binder object "
586                         "is parceled/sent to another process");
587 
588     Extras* e = mExtras.load(std::memory_order_acquire);
589 
590     if (!e) {
591         if (!inheritRt) {
592             return;
593         }
594 
595         e = getOrCreateExtras();
596         if (!e) return; // out of memory
597     }
598 
599     e->mInheritRt = inheritRt;
600 }
601 
getDebugPid()602 pid_t BBinder::getDebugPid() {
603 #ifdef __linux__
604     return getpid();
605 #else
606     // TODO: handle other OSes
607     return 0;
608 #endif // __linux__
609 }
610 
setExtension(const sp<IBinder> & extension)611 void BBinder::setExtension(const sp<IBinder>& extension) {
612     LOG_ALWAYS_FATAL_IF(mParceled,
613                         "setExtension() should not be called after a binder object "
614                         "is parceled/sent to another process");
615 
616     Extras* e = getOrCreateExtras();
617     e->mExtension = extension;
618 }
619 
wasParceled()620 bool BBinder::wasParceled() {
621     return mParceled;
622 }
623 
setParceled()624 void BBinder::setParceled() {
625     mParceled = true;
626 }
627 
setRpcClientDebug(const Parcel & data)628 status_t BBinder::setRpcClientDebug(const Parcel& data) {
629     if (!kEnableRpcDevServers) {
630         ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
631         return INVALID_OPERATION;
632     }
633     if (!kEnableKernelIpc) {
634         ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
635         return INVALID_OPERATION;
636     }
637     uid_t uid = IPCThreadState::self()->getCallingUid();
638     if (uid != AID_ROOT) {
639         ALOGE("%s: not allowed because client %" PRIu32 " is not root", __PRETTY_FUNCTION__, uid);
640         return PERMISSION_DENIED;
641     }
642     status_t status;
643     bool hasSocketFd;
644     android::base::unique_fd clientFd;
645 
646     if (status = data.readBool(&hasSocketFd); status != OK) return status;
647     if (hasSocketFd) {
648         if (status = data.readUniqueFileDescriptor(&clientFd); status != OK) return status;
649     }
650     sp<IBinder> keepAliveBinder;
651     if (status = data.readNullableStrongBinder(&keepAliveBinder); status != OK) return status;
652 
653     return setRpcClientDebug(std::move(clientFd), keepAliveBinder);
654 }
655 
setRpcClientDebug(android::base::unique_fd socketFd,const sp<IBinder> & keepAliveBinder)656 status_t BBinder::setRpcClientDebug(android::base::unique_fd socketFd,
657                                     const sp<IBinder>& keepAliveBinder) {
658     if (!kEnableRpcDevServers) {
659         ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
660         return INVALID_OPERATION;
661     }
662     if (!kEnableKernelIpc) {
663         ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
664         return INVALID_OPERATION;
665     }
666 
667     const int socketFdForPrint = socketFd.get();
668     LOG_RPC_DETAIL("%s(fd=%d)", __PRETTY_FUNCTION__, socketFdForPrint);
669 
670     if (!socketFd.ok()) {
671         ALOGE("%s: No socket FD provided.", __PRETTY_FUNCTION__);
672         return BAD_VALUE;
673     }
674 
675     if (keepAliveBinder == nullptr) {
676         ALOGE("%s: No keepAliveBinder provided.", __PRETTY_FUNCTION__);
677         return UNEXPECTED_NULL;
678     }
679 
680     size_t binderThreadPoolMaxCount = ProcessState::self()->getThreadPoolMaxTotalThreadCount();
681     if (binderThreadPoolMaxCount <= 1) {
682         ALOGE("%s: ProcessState thread pool max count is %zu. RPC is disabled for this service "
683               "because RPC requires the service to support multithreading.",
684               __PRETTY_FUNCTION__, binderThreadPoolMaxCount);
685         return INVALID_OPERATION;
686     }
687 
688     // Weak ref to avoid circular dependency:
689     // BBinder -> RpcServerLink ----> RpcServer -X-> BBinder
690     //                          `-X-> BBinder
691     auto weakThis = wp<BBinder>::fromExisting(this);
692 
693     Extras* e = getOrCreateExtras();
694     AutoMutex _l(e->mLock);
695     auto rpcServer = RpcServer::make();
696     LOG_ALWAYS_FATAL_IF(rpcServer == nullptr, "RpcServer::make returns null");
697     auto link = sp<RpcServerLink>::make(rpcServer, keepAliveBinder, weakThis);
698     if (auto status = keepAliveBinder->linkToDeath(link, nullptr, 0); status != OK) {
699         ALOGE("%s: keepAliveBinder->linkToDeath returns %s", __PRETTY_FUNCTION__,
700               statusToString(status).c_str());
701         return status;
702     }
703     rpcServer->setRootObjectWeak(weakThis);
704     if (auto status = rpcServer->setupExternalServer(std::move(socketFd)); status != OK) {
705         return status;
706     }
707     rpcServer->setMaxThreads(binderThreadPoolMaxCount);
708     LOG(INFO) << "RpcBinder: Started Binder debug on " << getInterfaceDescriptor();
709     rpcServer->start();
710     e->mRpcServerLinks.emplace(link);
711     LOG_RPC_DETAIL("%s(fd=%d) successful", __PRETTY_FUNCTION__, socketFdForPrint);
712     return OK;
713 }
714 
removeRpcServerLink(const sp<RpcServerLink> & link)715 void BBinder::removeRpcServerLink(const sp<RpcServerLink>& link) {
716     Extras* e = mExtras.load(std::memory_order_acquire);
717     if (!e) return;
718     AutoMutex _l(e->mLock);
719     (void)e->mRpcServerLinks.erase(link);
720 }
721 
~BBinder()722 BBinder::~BBinder()
723 {
724     if (!wasParceled()) {
725         if (getExtension()) {
726              ALOGW("Binder %p destroyed with extension attached before being parceled.", this);
727         }
728         if (isRequestingSid()) {
729              ALOGW("Binder %p destroyed when requesting SID before being parceled.", this);
730         }
731         if (isInheritRt()) {
732              ALOGW("Binder %p destroyed after setInheritRt before being parceled.", this);
733         }
734 #ifdef __linux__
735         if (getMinSchedulerPolicy() != SCHED_NORMAL) {
736              ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
737         }
738         if (getMinSchedulerPriority() != 0) {
739              ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
740         }
741 #endif // __linux__
742     }
743 
744     Extras* e = mExtras.load(std::memory_order_relaxed);
745     if (e) delete e;
746 }
747 
748 
749 // NOLINTNEXTLINE(google-default-arguments)
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t)750 status_t BBinder::onTransact(
751     uint32_t code, const Parcel& data, Parcel* reply, uint32_t /*flags*/)
752 {
753     switch (code) {
754         case INTERFACE_TRANSACTION:
755             CHECK(reply != nullptr);
756             reply->writeString16(getInterfaceDescriptor());
757             return NO_ERROR;
758 
759         case DUMP_TRANSACTION: {
760             int fd = data.readFileDescriptor();
761             int argc = data.readInt32();
762             Vector<String16> args;
763             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
764                args.add(data.readString16());
765             }
766             return dump(fd, args);
767         }
768 
769         case SHELL_COMMAND_TRANSACTION: {
770             int in = data.readFileDescriptor();
771             int out = data.readFileDescriptor();
772             int err = data.readFileDescriptor();
773             int argc = data.readInt32();
774             Vector<String16> args;
775             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
776                args.add(data.readString16());
777             }
778             sp<IBinder> shellCallbackBinder = data.readStrongBinder();
779             sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(
780                     data.readStrongBinder());
781 
782             // XXX can't add virtuals until binaries are updated.
783             // sp<IShellCallback> shellCallback = IShellCallback::asInterface(
784             //        shellCallbackBinder);
785             // return shellCommand(in, out, err, args, resultReceiver);
786             (void)in;
787             (void)out;
788             (void)err;
789 
790             if (resultReceiver != nullptr) {
791                 resultReceiver->send(INVALID_OPERATION);
792             }
793 
794             return NO_ERROR;
795         }
796 
797         case SYSPROPS_TRANSACTION: {
798             report_sysprop_change();
799             return NO_ERROR;
800         }
801 
802         default:
803             return UNKNOWN_TRANSACTION;
804     }
805 }
806 
getOrCreateExtras()807 BBinder::Extras* BBinder::getOrCreateExtras()
808 {
809     Extras* e = mExtras.load(std::memory_order_acquire);
810 
811     if (!e) {
812         e = new Extras;
813         Extras* expected = nullptr;
814         if (!mExtras.compare_exchange_strong(expected, e,
815                                              std::memory_order_release,
816                                              std::memory_order_acquire)) {
817             delete e;
818             e = expected;  // Filled in by CAS
819         }
820         if (e == nullptr) return nullptr; // out of memory
821     }
822 
823     return e;
824 }
825 
826 // ---------------------------------------------------------------------------
827 
828 enum {
829     // This is used to transfer ownership of the remote binder from
830     // the BpRefBase object holding it (when it is constructed), to the
831     // owner of the BpRefBase object when it first acquires that BpRefBase.
832     kRemoteAcquired = 0x00000001
833 };
834 
BpRefBase(const sp<IBinder> & o)835 BpRefBase::BpRefBase(const sp<IBinder>& o)
836     : mRemote(o.get()), mRefs(nullptr), mState(0)
837 {
838     extendObjectLifetime(OBJECT_LIFETIME_WEAK);
839 
840     if (mRemote) {
841         mRemote->incStrong(this);           // Removed on first IncStrong().
842         mRefs = mRemote->createWeak(this);  // Held for our entire lifetime.
843     }
844 }
845 
~BpRefBase()846 BpRefBase::~BpRefBase()
847 {
848     if (mRemote) {
849         if (!(mState.load(std::memory_order_relaxed)&kRemoteAcquired)) {
850             mRemote->decStrong(this);
851         }
852         mRefs->decWeak(this);
853     }
854 }
855 
onFirstRef()856 void BpRefBase::onFirstRef()
857 {
858     mState.fetch_or(kRemoteAcquired, std::memory_order_relaxed);
859 }
860 
onLastStrongRef(const void *)861 void BpRefBase::onLastStrongRef(const void* /*id*/)
862 {
863     if (mRemote) {
864         mRemote->decStrong(this);
865     }
866 }
867 
onIncStrongAttempted(uint32_t,const void *)868 bool BpRefBase::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
869 {
870     return mRemote ? mRefs->attemptIncStrong(this) : false;
871 }
872 
873 // ---------------------------------------------------------------------------
874 
875 } // namespace android
876