• 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 <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 "OS.h"
42 #include "RpcState.h"
43 
44 namespace android {
45 
46 using android::binder::unique_fd;
47 
48 constexpr uid_t kUidRoot = 0;
49 
50 // Service implementations inherit from BBinder and IBinder, and this is frozen
51 // in prebuilts.
52 #ifdef __LP64__
53 static_assert(sizeof(IBinder) == 24);
54 static_assert(sizeof(BBinder) == 40);
55 #else
56 static_assert(sizeof(IBinder) == 12);
57 static_assert(sizeof(BBinder) == 20);
58 #endif
59 
60 // global b/c b/230079120 - consistent symbol table
61 #ifdef BINDER_RPC_DEV_SERVERS
62 constexpr bool kEnableRpcDevServers = true;
63 #else
64 constexpr bool kEnableRpcDevServers = false;
65 #endif
66 
67 #ifdef BINDER_ENABLE_RECORDING
68 constexpr bool kEnableRecording = true;
69 #else
70 constexpr bool kEnableRecording = false;
71 #endif
72 
73 // Log any reply transactions for which the data exceeds this size
74 #define LOG_REPLIES_OVER_SIZE (300 * 1024)
75 // ---------------------------------------------------------------------------
76 
IBinder()77 IBinder::IBinder()
78     : RefBase()
79 {
80 }
81 
~IBinder()82 IBinder::~IBinder()
83 {
84 }
85 
86 // ---------------------------------------------------------------------------
87 
queryLocalInterface(const String16 &)88 sp<IInterface>  IBinder::queryLocalInterface(const String16& /*descriptor*/)
89 {
90     return nullptr;
91 }
92 
localBinder()93 BBinder* IBinder::localBinder()
94 {
95     return nullptr;
96 }
97 
remoteBinder()98 BpBinder* IBinder::remoteBinder()
99 {
100     return nullptr;
101 }
102 
checkSubclass(const void *) const103 bool IBinder::checkSubclass(const void* /*subclassID*/) const
104 {
105     return false;
106 }
107 
108 
shellCommand(const sp<IBinder> & target,int in,int out,int err,Vector<String16> & args,const sp<IShellCallback> & callback,const sp<IResultReceiver> & resultReceiver)109 status_t IBinder::shellCommand(const sp<IBinder>& target, int in, int out, int err,
110     Vector<String16>& args, const sp<IShellCallback>& callback,
111     const sp<IResultReceiver>& resultReceiver)
112 {
113     Parcel send;
114     Parcel reply;
115     send.writeFileDescriptor(in);
116     send.writeFileDescriptor(out);
117     send.writeFileDescriptor(err);
118     const size_t numArgs = args.size();
119     send.writeInt32(numArgs);
120     for (size_t i = 0; i < numArgs; i++) {
121         send.writeString16(args[i]);
122     }
123     send.writeStrongBinder(callback != nullptr ? IInterface::asBinder(callback) : nullptr);
124     send.writeStrongBinder(resultReceiver != nullptr ? IInterface::asBinder(resultReceiver) : nullptr);
125     return target->transact(SHELL_COMMAND_TRANSACTION, send, &reply);
126 }
127 
getExtension(sp<IBinder> * out)128 status_t IBinder::getExtension(sp<IBinder>* out) {
129     BBinder* local = this->localBinder();
130     if (local != nullptr) {
131         *out = local->getExtension();
132         return OK;
133     }
134 
135     BpBinder* proxy = this->remoteBinder();
136     LOG_ALWAYS_FATAL_IF(proxy == nullptr);
137 
138     Parcel data;
139     Parcel reply;
140     status_t status = transact(EXTENSION_TRANSACTION, data, &reply);
141     if (status != OK) return status;
142 
143     return reply.readNullableStrongBinder(out);
144 }
145 
getDebugPid(pid_t * out)146 status_t IBinder::getDebugPid(pid_t* out) {
147     BBinder* local = this->localBinder();
148     if (local != nullptr) {
149       *out = local->getDebugPid();
150       return OK;
151     }
152 
153     BpBinder* proxy = this->remoteBinder();
154     LOG_ALWAYS_FATAL_IF(proxy == nullptr);
155 
156     Parcel data;
157     Parcel reply;
158     status_t status = transact(DEBUG_PID_TRANSACTION, data, &reply);
159     if (status != OK) return status;
160 
161     int32_t pid;
162     status = reply.readInt32(&pid);
163     if (status != OK) return status;
164 
165     if (pid < 0 || pid > std::numeric_limits<pid_t>::max()) {
166         return BAD_VALUE;
167     }
168     *out = pid;
169     return OK;
170 }
171 
setRpcClientDebug(unique_fd socketFd,const sp<IBinder> & keepAliveBinder)172 status_t IBinder::setRpcClientDebug(unique_fd socketFd, 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     RpcMutex mLock;
274     std::set<sp<RpcServerLink>> mRpcServerLinks;
275     BpBinder::ObjectManager mObjects;
276 
277     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 != kUidRoot) {
305         ALOGE("Binder recording not allowed because client %" PRIu32 " is not root", uid);
306         return PERMISSION_DENIED;
307     }
308     Extras* e = getOrCreateExtras();
309     RpcMutexUniqueLock lock(e->mLock);
310     if (mRecordingOn) {
311         ALOGI("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         ALOGI("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 != kUidRoot) {
335         ALOGE("Binder recording not allowed because client %" PRIu32 " is not root", uid);
336         return PERMISSION_DENIED;
337     }
338     Extras* e = getOrCreateExtras();
339     RpcMutexUniqueLock lock(e->mLock);
340     if (mRecordingOn) {
341         e->mRecordingFd.reset();
342         mRecordingOn = false;
343         ALOGI("Stopped Binder recording.");
344         return NO_ERROR;
345     } else {
346         ALOGI("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             LOG_ALWAYS_FATAL_IF(reply == nullptr, "reply == nullptr");
381             err = reply->writeStrongBinder(getExtension());
382             break;
383         case DEBUG_PID_TRANSACTION:
384             LOG_ALWAYS_FATAL_IF(reply == nullptr, "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 (kEnableKernelIpc && mRecordingOn && code != START_RECORDING_TRANSACTION) [[unlikely]] {
406         Extras* e = mExtras.load(std::memory_order_acquire);
407         RpcMutexUniqueLock 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                     ALOGI("Failed to dump RecordedTransaction to file with error %d", err);
418                 }
419             } else {
420                 ALOGI("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     RpcMutexUniqueLock _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     RpcMutexUniqueLock _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     RpcMutexUniqueLock _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     RpcMutexUniqueLock _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     RpcMutexUniqueLock _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 != kUidRoot) {
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     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(unique_fd socketFd,const sp<IBinder> & keepAliveBinder)656 status_t BBinder::setRpcClientDebug(unique_fd socketFd, const sp<IBinder>& keepAliveBinder) {
657     if (!kEnableRpcDevServers) {
658         ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
659         return INVALID_OPERATION;
660     }
661     if (!kEnableKernelIpc) {
662         ALOGW("setRpcClientDebug disallowed because kernel binder is not enabled");
663         return INVALID_OPERATION;
664     }
665 
666     const int socketFdForPrint = socketFd.get();
667     LOG_RPC_DETAIL("%s(fd=%d)", __PRETTY_FUNCTION__, socketFdForPrint);
668 
669     if (!socketFd.ok()) {
670         ALOGE("%s: No socket FD provided.", __PRETTY_FUNCTION__);
671         return BAD_VALUE;
672     }
673 
674     if (keepAliveBinder == nullptr) {
675         ALOGE("%s: No keepAliveBinder provided.", __PRETTY_FUNCTION__);
676         return UNEXPECTED_NULL;
677     }
678 
679     size_t binderThreadPoolMaxCount = ProcessState::self()->getThreadPoolMaxTotalThreadCount();
680     if (binderThreadPoolMaxCount <= 1) {
681         ALOGE("%s: ProcessState thread pool max count is %zu. RPC is disabled for this service "
682               "because RPC requires the service to support multithreading.",
683               __PRETTY_FUNCTION__, binderThreadPoolMaxCount);
684         return INVALID_OPERATION;
685     }
686 
687     // Weak ref to avoid circular dependency:
688     // BBinder -> RpcServerLink ----> RpcServer -X-> BBinder
689     //                          `-X-> BBinder
690     auto weakThis = wp<BBinder>::fromExisting(this);
691 
692     Extras* e = getOrCreateExtras();
693     RpcMutexUniqueLock _l(e->mLock);
694     auto rpcServer = RpcServer::make();
695     LOG_ALWAYS_FATAL_IF(rpcServer == nullptr, "RpcServer::make returns null");
696     auto link = sp<RpcServerLink>::make(rpcServer, keepAliveBinder, weakThis);
697     if (auto status = keepAliveBinder->linkToDeath(link, nullptr, 0); status != OK) {
698         ALOGE("%s: keepAliveBinder->linkToDeath returns %s", __PRETTY_FUNCTION__,
699               statusToString(status).c_str());
700         return status;
701     }
702     rpcServer->setRootObjectWeak(weakThis);
703     if (auto status = rpcServer->setupExternalServer(std::move(socketFd)); status != OK) {
704         return status;
705     }
706     rpcServer->setMaxThreads(binderThreadPoolMaxCount);
707     ALOGI("RpcBinder: Started Binder debug on %s", String8(getInterfaceDescriptor()).c_str());
708     rpcServer->start();
709     e->mRpcServerLinks.emplace(link);
710     LOG_RPC_DETAIL("%s(fd=%d) successful", __PRETTY_FUNCTION__, socketFdForPrint);
711     return OK;
712 }
713 
removeRpcServerLink(const sp<RpcServerLink> & link)714 void BBinder::removeRpcServerLink(const sp<RpcServerLink>& link) {
715     Extras* e = mExtras.load(std::memory_order_acquire);
716     if (!e) return;
717     RpcMutexUniqueLock _l(e->mLock);
718     (void)e->mRpcServerLinks.erase(link);
719 }
720 
~BBinder()721 BBinder::~BBinder()
722 {
723     if (!wasParceled()) {
724         if (getExtension()) {
725             ALOGW("Binder %p destroyed with extension attached before being parceled.", this);
726         }
727         if (isRequestingSid()) {
728             ALOGW("Binder %p destroyed when requesting SID before being parceled.", this);
729         }
730         if (isInheritRt()) {
731             ALOGW("Binder %p destroyed after setInheritRt before being parceled.", this);
732         }
733 #ifdef __linux__
734         if (getMinSchedulerPolicy() != SCHED_NORMAL) {
735             ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
736         }
737         if (getMinSchedulerPriority() != 0) {
738             ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
739         }
740 #endif // __linux__
741     }
742 
743     Extras* e = mExtras.load(std::memory_order_relaxed);
744     if (e) delete e;
745 }
746 
747 
748 // NOLINTNEXTLINE(google-default-arguments)
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t)749 status_t BBinder::onTransact(
750     uint32_t code, const Parcel& data, Parcel* reply, uint32_t /*flags*/)
751 {
752     switch (code) {
753         case INTERFACE_TRANSACTION:
754             LOG_ALWAYS_FATAL_IF(reply == nullptr, "reply == nullptr");
755             reply->writeString16(getInterfaceDescriptor());
756             return NO_ERROR;
757 
758         case DUMP_TRANSACTION: {
759             int fd = data.readFileDescriptor();
760             int argc = data.readInt32();
761             Vector<String16> args;
762             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
763                args.add(data.readString16());
764             }
765             return dump(fd, args);
766         }
767 
768         case SHELL_COMMAND_TRANSACTION: {
769             int in = data.readFileDescriptor();
770             int out = data.readFileDescriptor();
771             int err = data.readFileDescriptor();
772             int argc = data.readInt32();
773             Vector<String16> args;
774             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
775                args.add(data.readString16());
776             }
777             sp<IBinder> shellCallbackBinder = data.readStrongBinder();
778             sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(
779                     data.readStrongBinder());
780 
781             // XXX can't add virtuals until binaries are updated.
782             // sp<IShellCallback> shellCallback = IShellCallback::asInterface(
783             //        shellCallbackBinder);
784             // return shellCommand(in, out, err, args, resultReceiver);
785             (void)in;
786             (void)out;
787             (void)err;
788 
789             if (resultReceiver != nullptr) {
790                 resultReceiver->send(INVALID_OPERATION);
791             }
792 
793             return NO_ERROR;
794         }
795 
796         case SYSPROPS_TRANSACTION: {
797             if (!binder::os::report_sysprop_change()) return INVALID_OPERATION;
798             return NO_ERROR;
799         }
800 
801         default:
802             return UNKNOWN_TRANSACTION;
803     }
804 }
805 
getOrCreateExtras()806 BBinder::Extras* BBinder::getOrCreateExtras()
807 {
808     Extras* e = mExtras.load(std::memory_order_acquire);
809 
810     if (!e) {
811         e = new Extras;
812         Extras* expected = nullptr;
813         if (!mExtras.compare_exchange_strong(expected, e,
814                                              std::memory_order_release,
815                                              std::memory_order_acquire)) {
816             delete e;
817             e = expected;  // Filled in by CAS
818         }
819         if (e == nullptr) return nullptr; // out of memory
820     }
821 
822     return e;
823 }
824 
825 // ---------------------------------------------------------------------------
826 
827 enum {
828     // This is used to transfer ownership of the remote binder from
829     // the BpRefBase object holding it (when it is constructed), to the
830     // owner of the BpRefBase object when it first acquires that BpRefBase.
831     kRemoteAcquired = 0x00000001
832 };
833 
BpRefBase(const sp<IBinder> & o)834 BpRefBase::BpRefBase(const sp<IBinder>& o)
835     : mRemote(o.get()), mRefs(nullptr), mState(0)
836 {
837     extendObjectLifetime(OBJECT_LIFETIME_WEAK);
838 
839     if (mRemote) {
840         mRemote->incStrong(this);           // Removed on first IncStrong().
841         mRefs = mRemote->createWeak(this);  // Held for our entire lifetime.
842     }
843 }
844 
~BpRefBase()845 BpRefBase::~BpRefBase()
846 {
847     if (mRemote) {
848         if (!(mState.load(std::memory_order_relaxed)&kRemoteAcquired)) {
849             mRemote->decStrong(this);
850         }
851         mRefs->decWeak(this);
852     }
853 }
854 
onFirstRef()855 void BpRefBase::onFirstRef()
856 {
857     mState.fetch_or(kRemoteAcquired, std::memory_order_relaxed);
858 }
859 
onLastStrongRef(const void *)860 void BpRefBase::onLastStrongRef(const void* /*id*/)
861 {
862     if (mRemote) {
863         mRemote->decStrong(this);
864     }
865 }
866 
onIncStrongAttempted(uint32_t,const void *)867 bool BpRefBase::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
868 {
869     return mRemote ? mRefs->attemptIncStrong(this) : false;
870 }
871 
872 // ---------------------------------------------------------------------------
873 
874 } // namespace android
875