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