xref: /aosp_15_r20/frameworks/native/libs/binder/ndk/ibinder.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
2  * Copyright (C) 2018 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 <android/binder_ibinder.h>
18 #include <android/binder_ibinder_platform.h>
19 #include <android/binder_stability.h>
20 #include <android/binder_status.h>
21 #include <binder/Functional.h>
22 #include <binder/IPCThreadState.h>
23 #include <binder/IResultReceiver.h>
24 #include <binder/Trace.h>
25 #if __has_include(<private/android_filesystem_config.h>)
26 #include <private/android_filesystem_config.h>
27 #endif
28 
29 #include "../BuildFlags.h"
30 #include "ibinder_internal.h"
31 #include "parcel_internal.h"
32 #include "status_internal.h"
33 
34 using DeathRecipient = ::android::IBinder::DeathRecipient;
35 
36 using ::android::IBinder;
37 using ::android::IResultReceiver;
38 using ::android::Parcel;
39 using ::android::sp;
40 using ::android::status_t;
41 using ::android::statusToString;
42 using ::android::String16;
43 using ::android::String8;
44 using ::android::wp;
45 using ::android::binder::impl::make_scope_guard;
46 using ::android::binder::impl::scope_guard;
47 using ::android::binder::os::get_trace_enabled_tags;
48 using ::android::binder::os::trace_begin;
49 using ::android::binder::os::trace_end;
50 
51 // transaction codes for getInterfaceHash and getInterfaceVersion are defined
52 // in file : system/tools/aidl/aidl.cpp
53 static constexpr int kGetInterfaceVersionId = 0x00fffffe;
54 static const char* kInterfaceVersion = "getInterfaceVersion";
55 static constexpr int kGetInterfaceHashId = 0x00fffffd;
56 static const char* kInterfaceHash = "getInterfaceHash";
57 static const char* kNdkTrace = "AIDL::ndk::";
58 static const char* kServerTrace = "::server";
59 static const char* kClientTrace = "::client";
60 static const char* kSeparator = "::";
61 static const char* kUnknownCode = "Unknown_Transaction_Code:";
62 
63 namespace ABBinderTag {
64 
65 static const void* kId = "ABBinder";
66 static void* kValue = static_cast<void*>(new bool{true});
clean(const void *,void *,void *)67 void clean(const void* /*id*/, void* /*obj*/, void* /*cookie*/) {
68     /* do nothing */
69 }
70 
attach(const sp<IBinder> & binder)71 static void attach(const sp<IBinder>& binder) {
72     auto alreadyAttached = binder->attachObject(kId, kValue, nullptr /*cookie*/, clean);
73     LOG_ALWAYS_FATAL_IF(alreadyAttached != nullptr, "can only attach once");
74 }
has(const sp<IBinder> & binder)75 static bool has(const sp<IBinder>& binder) {
76     return binder != nullptr && binder->findObject(kId) == kValue;
77 }
78 
79 }  // namespace ABBinderTag
80 
81 namespace ABpBinderTag {
82 
83 static const void* kId = "ABpBinder";
84 struct Value {
85     wp<ABpBinder> binder;
86 };
clean(const void * id,void * obj,void * cookie)87 void clean(const void* id, void* obj, void* cookie) {
88     // be weary of leaks!
89     // ALOGI("Deleting an ABpBinder");
90 
91     LOG_ALWAYS_FATAL_IF(id != kId, "%p %p %p", id, obj, cookie);
92 
93     delete static_cast<Value*>(obj);
94 }
95 
96 }  // namespace ABpBinderTag
97 
AIBinder(const AIBinder_Class * clazz)98 AIBinder::AIBinder(const AIBinder_Class* clazz) : mClazz(clazz) {}
~AIBinder()99 AIBinder::~AIBinder() {}
100 
101 // b/175635923 libcxx causes "implicit-conversion" with a string with invalid char
SanitizeString(const String16 & str)102 static std::string SanitizeString(const String16& str) {
103     std::string sanitized{String8(str)};
104     for (auto& c : sanitized) {
105         if (!isprint(c)) {
106             c = '?';
107         }
108     }
109     return sanitized;
110 }
111 
getMethodName(const AIBinder_Class * clazz,transaction_code_t code)112 const std::string getMethodName(const AIBinder_Class* clazz, transaction_code_t code) {
113     // TODO(b/150155678) - Move getInterfaceHash and getInterfaceVersion to libbinder and remove
114     // hardcoded cases.
115     if (code <= clazz->getTransactionCodeToFunctionLength() && code >= FIRST_CALL_TRANSACTION) {
116         // Codes have FIRST_CALL_TRANSACTION as added offset. Subtract to access function name
117         return clazz->getFunctionName(code);
118     } else if (code == kGetInterfaceVersionId) {
119         return kInterfaceVersion;
120     } else if (code == kGetInterfaceHashId) {
121         return kInterfaceHash;
122     }
123     return kUnknownCode + std::to_string(code);
124 }
125 
getTraceSectionName(const AIBinder_Class * clazz,transaction_code_t code,bool isServer)126 const std::string getTraceSectionName(const AIBinder_Class* clazz, transaction_code_t code,
127                                       bool isServer) {
128     if (clazz == nullptr) {
129         ALOGE("class associated with binder is null. Class is needed to add trace with interface "
130               "name and function name");
131         return kNdkTrace;
132     }
133 
134     const std::string descriptor = clazz->getInterfaceDescriptorUtf8();
135     const std::string methodName = getMethodName(clazz, code);
136 
137     size_t traceSize =
138             strlen(kNdkTrace) + descriptor.size() + strlen(kSeparator) + methodName.size();
139     traceSize += isServer ? strlen(kServerTrace) : strlen(kClientTrace);
140 
141     std::string trace;
142     // reserve to avoid repeated allocations
143     trace.reserve(traceSize);
144 
145     trace += kNdkTrace;
146     trace += clazz->getInterfaceDescriptorUtf8();
147     trace += kSeparator;
148     trace += methodName;
149     trace += isServer ? kServerTrace : kClientTrace;
150 
151     LOG_ALWAYS_FATAL_IF(trace.size() != traceSize, "Trace size mismatch. Expected %zu, got %zu",
152                         traceSize, trace.size());
153 
154     return trace;
155 }
156 
associateClass(const AIBinder_Class * clazz)157 bool AIBinder::associateClass(const AIBinder_Class* clazz) {
158     if (clazz == nullptr) return false;
159 
160     // If mClazz is non-null, this must have been called and cached
161     // already. So, we can safely call this first. Due to the implementation
162     // of getInterfaceDescriptor (at time of writing), two simultaneous calls
163     // may lead to extra binder transactions, but this is expected to be
164     // exceedingly rare. Once we have a binder, when we get it again later,
165     // we won't make another binder transaction here.
166     const String16& descriptor = getBinder()->getInterfaceDescriptor();
167     const String16& newDescriptor = clazz->getInterfaceDescriptor();
168 
169     std::lock_guard<std::mutex> lock(mClazzMutex);
170     if (mClazz == clazz) return true;
171 
172     // If this is an ABpBinder, the first class object becomes the canonical one. The implication
173     // of this is that no API can require a proxy information to get information on how to behave.
174     // from the class itself - which should only store the interface descriptor. The functionality
175     // should be implemented by adding AIBinder_* APIs to set values on binders themselves, by
176     // setting things on AIBinder_Class which get transferred along with the binder, so that they
177     // can be read along with the BpBinder, or by modifying APIs directly (e.g. an option in
178     // onTransact).
179     //
180     // While this check is required to support linkernamespaces, one downside of it is that
181     // you may parcel code to communicate between things in the same process. However, comms
182     // between linkernamespaces like this already happen for cross-language calls like Java<->C++
183     // or Rust<->Java, and there are good stability guarantees here. This interacts with
184     // binder Stability checks exactly like any other in-process call. The stability is known
185     // to the IBinder object, so that it doesn't matter if a class object comes from
186     // a different stability level.
187     if (mClazz != nullptr && !asABpBinder()) {
188         const String16& currentDescriptor = mClazz->getInterfaceDescriptor();
189         if (newDescriptor == currentDescriptor) {
190             ALOGE("Class descriptors '%s' match during associateClass, but they are different class"
191                   " objects (%p vs %p). Class descriptor collision?",
192                   String8(currentDescriptor).c_str(), clazz, mClazz);
193         } else {
194             ALOGE("%s: Class cannot be associated on object which already has a class. "
195                   "Trying to associate to '%s' but already set to '%s'.",
196                   __func__, String8(newDescriptor).c_str(), String8(currentDescriptor).c_str());
197         }
198 
199         // always a failure because we know mClazz != clazz
200         return false;
201     }
202 
203     // This will always be an O(n) comparison, but it's expected to be extremely rare.
204     // since it's an error condition. Do the comparison after we take the lock and
205     // check the pointer equality fast path. By always taking the lock, it's also
206     // more flake-proof. However, the check is not dependent on the lock.
207     if (descriptor != newDescriptor && !(asABpBinder() && asABpBinder()->isServiceFuzzing())) {
208         if (getBinder()->isBinderAlive()) {
209             ALOGE("%s: Expecting binder to have class '%s' but descriptor is actually '%s'.",
210                   __func__, String8(newDescriptor).c_str(), SanitizeString(descriptor).c_str());
211         } else {
212             // b/155793159
213             ALOGE("%s: Cannot associate class '%s' to dead binder with cached descriptor '%s'.",
214                   __func__, String8(newDescriptor).c_str(), SanitizeString(descriptor).c_str());
215         }
216         return false;
217     }
218 
219     // A local binder being set for the first time OR
220     // ignoring a proxy binder which is set multiple time, by considering the first
221     // associated class as the canonical one.
222     if (mClazz == nullptr) {
223         mClazz = clazz;
224     }
225 
226     return true;
227 }
228 
ABBinder(const AIBinder_Class * clazz,void * userData)229 ABBinder::ABBinder(const AIBinder_Class* clazz, void* userData)
230     : AIBinder(clazz), BBinder(), mUserData(userData) {
231     LOG_ALWAYS_FATAL_IF(clazz == nullptr, "clazz == nullptr");
232 }
~ABBinder()233 ABBinder::~ABBinder() {
234     getClass()->onDestroy(mUserData);
235 }
236 
getInterfaceDescriptor() const237 const String16& ABBinder::getInterfaceDescriptor() const {
238     return getClass()->getInterfaceDescriptor();
239 }
240 
dump(int fd,const::android::Vector<String16> & args)241 status_t ABBinder::dump(int fd, const ::android::Vector<String16>& args) {
242     AIBinder_onDump onDump = getClass()->onDump;
243 
244     if (onDump == nullptr) {
245         return STATUS_OK;
246     }
247 
248     // technically UINT32_MAX would be okay here, but INT32_MAX is expected since this may be
249     // null in Java
250     if (args.size() > INT32_MAX) {
251         ALOGE("ABBinder::dump received too many arguments: %zu", args.size());
252         return STATUS_BAD_VALUE;
253     }
254 
255     std::vector<String8> utf8Args;  // owns memory of utf8s
256     utf8Args.reserve(args.size());
257     std::vector<const char*> utf8Pointers;  // what can be passed over NDK API
258     utf8Pointers.reserve(args.size());
259 
260     for (size_t i = 0; i < args.size(); i++) {
261         utf8Args.push_back(String8(args[i]));
262         utf8Pointers.push_back(utf8Args[i].c_str());
263     }
264 
265     return onDump(this, fd, utf8Pointers.data(), utf8Pointers.size());
266 }
267 
onTransact(transaction_code_t code,const Parcel & data,Parcel * reply,binder_flags_t flags)268 status_t ABBinder::onTransact(transaction_code_t code, const Parcel& data, Parcel* reply,
269                               binder_flags_t flags) {
270     std::string sectionName;
271     bool tracingEnabled = get_trace_enabled_tags() & ATRACE_TAG_AIDL;
272     if (tracingEnabled) {
273         sectionName = getTraceSectionName(getClass(), code, true /*isServer*/);
274         trace_begin(ATRACE_TAG_AIDL, sectionName.c_str());
275     }
276 
277     scope_guard guard = make_scope_guard([&]() {
278         if (tracingEnabled) trace_end(ATRACE_TAG_AIDL);
279     });
280 
281     if (isUserCommand(code)) {
282         if (getClass()->writeHeader && !data.checkInterface(this)) {
283             return STATUS_BAD_TYPE;
284         }
285 
286         const AParcel in = AParcel::readOnly(this, &data);
287         AParcel out = AParcel(this, reply, false /*owns*/);
288 
289         binder_status_t status = getClass()->onTransact(this, code, &in, &out);
290         return PruneStatusT(status);
291     } else if (code == SHELL_COMMAND_TRANSACTION && getClass()->handleShellCommand != nullptr) {
292         if constexpr (!android::kEnableKernelIpc) {
293             // Non-IPC builds do not have getCallingUid(),
294             // so we have no way of authenticating the caller
295             return STATUS_PERMISSION_DENIED;
296         }
297 
298         int in = data.readFileDescriptor();
299         int out = data.readFileDescriptor();
300         int err = data.readFileDescriptor();
301 
302         int argc = data.readInt32();
303         std::vector<String8> utf8Args;          // owns memory of utf8s
304         std::vector<const char*> utf8Pointers;  // what can be passed over NDK API
305         for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
306             utf8Args.push_back(String8(data.readString16()));
307             utf8Pointers.push_back(utf8Args[i].c_str());
308         }
309 
310         data.readStrongBinder();  // skip over the IShellCallback
311         sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(data.readStrongBinder());
312 
313         // Shell commands should only be callable by ADB.
314         uid_t uid = AIBinder_getCallingUid();
315         if (uid != 0 /* root */
316 #ifdef AID_SHELL
317             && uid != AID_SHELL
318 #endif
319         ) {
320             if (resultReceiver != nullptr) {
321                 resultReceiver->send(-1);
322             }
323             return STATUS_PERMISSION_DENIED;
324         }
325 
326         // Check that the file descriptors are valid.
327         if (in == STATUS_BAD_TYPE || out == STATUS_BAD_TYPE || err == STATUS_BAD_TYPE) {
328             if (resultReceiver != nullptr) {
329                 resultReceiver->send(-1);
330             }
331             return STATUS_BAD_VALUE;
332         }
333 
334         binder_status_t status = getClass()->handleShellCommand(
335                 this, in, out, err, utf8Pointers.data(), utf8Pointers.size());
336         if (resultReceiver != nullptr) {
337             resultReceiver->send(status);
338         }
339         return status;
340     } else {
341         return BBinder::onTransact(code, data, reply, flags);
342     }
343 }
344 
addDeathRecipient(const::android::sp<AIBinder_DeathRecipient> &,void *)345 void ABBinder::addDeathRecipient(const ::android::sp<AIBinder_DeathRecipient>& /* recipient */,
346                                  void* /* cookie */) {
347     LOG_ALWAYS_FATAL("Should not reach this. Can't linkToDeath local binders.");
348 }
349 
ABpBinder(const::android::sp<::android::IBinder> & binder)350 ABpBinder::ABpBinder(const ::android::sp<::android::IBinder>& binder)
351     : AIBinder(nullptr /*clazz*/), mRemote(binder) {
352     LOG_ALWAYS_FATAL_IF(binder == nullptr, "binder == nullptr");
353 }
354 
~ABpBinder()355 ABpBinder::~ABpBinder() {
356     for (auto& recip : mDeathRecipients) {
357         sp<AIBinder_DeathRecipient> strongRecip = recip.recipient.promote();
358         if (strongRecip) {
359             strongRecip->pruneThisTransferEntry(getBinder(), recip.cookie);
360         }
361     }
362 }
363 
lookupOrCreateFromBinder(const::android::sp<::android::IBinder> & binder)364 sp<AIBinder> ABpBinder::lookupOrCreateFromBinder(const ::android::sp<::android::IBinder>& binder) {
365     if (binder == nullptr) {
366         return nullptr;
367     }
368     if (ABBinderTag::has(binder)) {
369         return static_cast<ABBinder*>(binder.get());
370     }
371 
372     // The following code ensures that for a given binder object (remote or local), if it is not an
373     // ABBinder then at most one ABpBinder object exists in a given process representing it.
374 
375     auto* value = static_cast<ABpBinderTag::Value*>(binder->findObject(ABpBinderTag::kId));
376     if (value == nullptr) {
377         value = new ABpBinderTag::Value;
378         auto oldValue = static_cast<ABpBinderTag::Value*>(
379                 binder->attachObject(ABpBinderTag::kId, static_cast<void*>(value),
380                                      nullptr /*cookie*/, ABpBinderTag::clean));
381 
382         // allocated by another thread
383         if (oldValue) {
384             delete value;
385             value = oldValue;
386         }
387     }
388 
389     sp<ABpBinder> ret;
390     binder->withLock([&]() {
391         ret = value->binder.promote();
392         if (ret == nullptr) {
393             ret = sp<ABpBinder>::make(binder);
394             value->binder = ret;
395         }
396     });
397 
398     return ret;
399 }
400 
addDeathRecipient(const::android::sp<AIBinder_DeathRecipient> & recipient,void * cookie)401 void ABpBinder::addDeathRecipient(const ::android::sp<AIBinder_DeathRecipient>& recipient,
402                                   void* cookie) {
403     std::lock_guard<std::mutex> l(mDeathRecipientsMutex);
404     mDeathRecipients.emplace_back(recipient, cookie);
405 }
406 
407 struct AIBinder_Weak {
408     wp<AIBinder> binder;
409 };
AIBinder_Weak_new(AIBinder * binder)410 AIBinder_Weak* AIBinder_Weak_new(AIBinder* binder) {
411     if (binder == nullptr) {
412         return nullptr;
413     }
414 
415     return new AIBinder_Weak{wp<AIBinder>(binder)};
416 }
AIBinder_Weak_delete(AIBinder_Weak * weakBinder)417 void AIBinder_Weak_delete(AIBinder_Weak* weakBinder) {
418     delete weakBinder;
419 }
AIBinder_Weak_promote(AIBinder_Weak * weakBinder)420 AIBinder* AIBinder_Weak_promote(AIBinder_Weak* weakBinder) {
421     if (weakBinder == nullptr) {
422         return nullptr;
423     }
424 
425     sp<AIBinder> binder = weakBinder->binder.promote();
426     AIBinder_incStrong(binder.get());
427     return binder.get();
428 }
429 
AIBinder_Weak_clone(const AIBinder_Weak * weak)430 AIBinder_Weak* AIBinder_Weak_clone(const AIBinder_Weak* weak) {
431     if (weak == nullptr) {
432         return nullptr;
433     }
434 
435     return new AIBinder_Weak{weak->binder};
436 }
437 
AIBinder_lt(const AIBinder * lhs,const AIBinder * rhs)438 bool AIBinder_lt(const AIBinder* lhs, const AIBinder* rhs) {
439     if (lhs == nullptr || rhs == nullptr) return lhs < rhs;
440 
441     return const_cast<AIBinder*>(lhs)->getBinder() < const_cast<AIBinder*>(rhs)->getBinder();
442 }
443 
AIBinder_Weak_lt(const AIBinder_Weak * lhs,const AIBinder_Weak * rhs)444 bool AIBinder_Weak_lt(const AIBinder_Weak* lhs, const AIBinder_Weak* rhs) {
445     if (lhs == nullptr || rhs == nullptr) return lhs < rhs;
446 
447     return lhs->binder < rhs->binder;
448 }
449 
450 // WARNING: When multiple classes exist with the same interface descriptor in different
451 // linkernamespaces, the first one to be associated with mClazz becomes the canonical one
452 // and the only requirement on this is that the interface descriptors match. If this
453 // is an ABpBinder, no other state can be referenced from mClazz.
AIBinder_Class(const char * interfaceDescriptor,AIBinder_Class_onCreate onCreate,AIBinder_Class_onDestroy onDestroy,AIBinder_Class_onTransact onTransact)454 AIBinder_Class::AIBinder_Class(const char* interfaceDescriptor, AIBinder_Class_onCreate onCreate,
455                                AIBinder_Class_onDestroy onDestroy,
456                                AIBinder_Class_onTransact onTransact)
457     : onCreate(onCreate),
458       onDestroy(onDestroy),
459       onTransact(onTransact),
460       mInterfaceDescriptor(interfaceDescriptor),
461       mWideInterfaceDescriptor(interfaceDescriptor) {}
462 
setTransactionCodeMap(const char ** transactionCodeMap,size_t length)463 bool AIBinder_Class::setTransactionCodeMap(const char** transactionCodeMap, size_t length) {
464     if (mTransactionCodeToFunction != nullptr) {
465         ALOGE("mTransactionCodeToFunction is already set!");
466         return false;
467     }
468     mTransactionCodeToFunction = transactionCodeMap;
469     mTransactionCodeToFunctionLength = length;
470     return true;
471 }
472 
getFunctionName(transaction_code_t code) const473 const char* AIBinder_Class::getFunctionName(transaction_code_t code) const {
474     if (mTransactionCodeToFunction == nullptr) {
475         ALOGE("mTransactionCodeToFunction is not set!");
476         return nullptr;
477     }
478 
479     if (code < FIRST_CALL_TRANSACTION ||
480         code - FIRST_CALL_TRANSACTION >= mTransactionCodeToFunctionLength) {
481         ALOGE("Function name for requested code not found!");
482         return nullptr;
483     }
484 
485     return mTransactionCodeToFunction[code - FIRST_CALL_TRANSACTION];
486 }
487 
AIBinder_Class_define(const char * interfaceDescriptor,AIBinder_Class_onCreate onCreate,AIBinder_Class_onDestroy onDestroy,AIBinder_Class_onTransact onTransact)488 AIBinder_Class* AIBinder_Class_define(const char* interfaceDescriptor,
489                                       AIBinder_Class_onCreate onCreate,
490                                       AIBinder_Class_onDestroy onDestroy,
491                                       AIBinder_Class_onTransact onTransact) {
492     if (interfaceDescriptor == nullptr || onCreate == nullptr || onDestroy == nullptr ||
493         onTransact == nullptr) {
494         return nullptr;
495     }
496 
497     return new AIBinder_Class(interfaceDescriptor, onCreate, onDestroy, onTransact);
498 }
499 
AIBinder_Class_setOnDump(AIBinder_Class * clazz,AIBinder_onDump onDump)500 void AIBinder_Class_setOnDump(AIBinder_Class* clazz, AIBinder_onDump onDump) {
501     LOG_ALWAYS_FATAL_IF(clazz == nullptr, "setOnDump requires non-null clazz");
502 
503     // this is required to be called before instances are instantiated
504     clazz->onDump = onDump;
505 }
506 
AIBinder_Class_setTransactionCodeToFunctionNameMap(AIBinder_Class * clazz,const char ** transactionCodeToFunction,size_t length)507 void AIBinder_Class_setTransactionCodeToFunctionNameMap(AIBinder_Class* clazz,
508                                                         const char** transactionCodeToFunction,
509                                                         size_t length) {
510     LOG_ALWAYS_FATAL_IF(clazz == nullptr || transactionCodeToFunction == nullptr,
511                         "Valid clazz and transactionCodeToFunction are needed to set code to "
512                         "function mapping.");
513     LOG_ALWAYS_FATAL_IF(!clazz->setTransactionCodeMap(transactionCodeToFunction, length),
514                         "Failed to set transactionCodeToFunction to clazz! Is "
515                         "transactionCodeToFunction already set?");
516 }
517 
AIBinder_Class_getFunctionName(AIBinder_Class * clazz,transaction_code_t code)518 const char* AIBinder_Class_getFunctionName(AIBinder_Class* clazz, transaction_code_t code) {
519     LOG_ALWAYS_FATAL_IF(
520             clazz == nullptr,
521             "Valid clazz is needed to get function name for requested transaction code");
522     return clazz->getFunctionName(code);
523 }
524 
AIBinder_Class_disableInterfaceTokenHeader(AIBinder_Class * clazz)525 void AIBinder_Class_disableInterfaceTokenHeader(AIBinder_Class* clazz) {
526     LOG_ALWAYS_FATAL_IF(clazz == nullptr, "disableInterfaceTokenHeader requires non-null clazz");
527 
528     clazz->writeHeader = false;
529 }
530 
AIBinder_Class_setHandleShellCommand(AIBinder_Class * clazz,AIBinder_handleShellCommand handleShellCommand)531 void AIBinder_Class_setHandleShellCommand(AIBinder_Class* clazz,
532                                           AIBinder_handleShellCommand handleShellCommand) {
533     LOG_ALWAYS_FATAL_IF(clazz == nullptr, "setHandleShellCommand requires non-null clazz");
534 
535     clazz->handleShellCommand = handleShellCommand;
536 }
537 
AIBinder_Class_getDescriptor(const AIBinder_Class * clazz)538 const char* AIBinder_Class_getDescriptor(const AIBinder_Class* clazz) {
539     LOG_ALWAYS_FATAL_IF(clazz == nullptr, "getDescriptor requires non-null clazz");
540 
541     return clazz->getInterfaceDescriptorUtf8();
542 }
543 
~TransferDeathRecipient()544 AIBinder_DeathRecipient::TransferDeathRecipient::~TransferDeathRecipient() {
545     if (mOnUnlinked != nullptr) {
546         mOnUnlinked(mCookie);
547     }
548 }
549 
binderDied(const wp<IBinder> & who)550 void AIBinder_DeathRecipient::TransferDeathRecipient::binderDied(const wp<IBinder>& who) {
551     LOG_ALWAYS_FATAL_IF(who != mWho, "%p (%p) vs %p (%p)", who.unsafe_get(), who.get_refs(),
552                         mWho.unsafe_get(), mWho.get_refs());
553 
554     mOnDied(mCookie);
555 
556     sp<AIBinder_DeathRecipient> recipient = mParentRecipient.promote();
557     sp<IBinder> strongWho = who.promote();
558 
559     // otherwise this will be cleaned up later with pruneDeadTransferEntriesLocked
560     if (recipient != nullptr && strongWho != nullptr) {
561         status_t result = recipient->unlinkToDeath(strongWho, mCookie);
562         if (result != ::android::DEAD_OBJECT) {
563             ALOGW("Unlinking to dead binder resulted in: %d", result);
564         }
565     }
566 
567     mWho = nullptr;
568 }
569 
AIBinder_DeathRecipient(AIBinder_DeathRecipient_onBinderDied onDied)570 AIBinder_DeathRecipient::AIBinder_DeathRecipient(AIBinder_DeathRecipient_onBinderDied onDied)
571     : mOnDied(onDied), mOnUnlinked(nullptr) {
572     LOG_ALWAYS_FATAL_IF(onDied == nullptr, "onDied == nullptr");
573 }
574 
pruneThisTransferEntry(const sp<IBinder> & who,void * cookie)575 void AIBinder_DeathRecipient::pruneThisTransferEntry(const sp<IBinder>& who, void* cookie) {
576     std::lock_guard<std::mutex> l(mDeathRecipientsMutex);
577     mDeathRecipients.erase(std::remove_if(mDeathRecipients.begin(), mDeathRecipients.end(),
578                                           [&](const sp<TransferDeathRecipient>& tdr) {
579                                               auto tdrWho = tdr->getWho();
580                                               return tdrWho != nullptr && tdrWho.promote() == who &&
581                                                      cookie == tdr->getCookie();
582                                           }),
583                            mDeathRecipients.end());
584 }
585 
pruneDeadTransferEntriesLocked()586 void AIBinder_DeathRecipient::pruneDeadTransferEntriesLocked() {
587     mDeathRecipients.erase(std::remove_if(mDeathRecipients.begin(), mDeathRecipients.end(),
588                                           [](const sp<TransferDeathRecipient>& tdr) {
589                                               return tdr->getWho() == nullptr;
590                                           }),
591                            mDeathRecipients.end());
592 }
593 
linkToDeath(const sp<IBinder> & binder,void * cookie)594 binder_status_t AIBinder_DeathRecipient::linkToDeath(const sp<IBinder>& binder, void* cookie) {
595     LOG_ALWAYS_FATAL_IF(binder == nullptr, "binder == nullptr");
596 
597     std::lock_guard<std::mutex> l(mDeathRecipientsMutex);
598 
599     if (mOnUnlinked && cookie &&
600         std::find_if(mDeathRecipients.begin(), mDeathRecipients.end(),
601                      [&cookie](android::sp<TransferDeathRecipient> recipient) {
602                          return recipient->getCookie() == cookie;
603                      }) != mDeathRecipients.end()) {
604         ALOGE("Attempting to AIBinder_linkToDeath with the same cookie with an onUnlink callback. "
605               "This will cause the onUnlinked callback to be called multiple times with the same "
606               "cookie, which is usually not intended.");
607     }
608     if (!mOnUnlinked && cookie) {
609         ALOGW("AIBinder_linkToDeath is being called with a non-null cookie and no onUnlink "
610               "callback set. This might not be intended. AIBinder_DeathRecipient_setOnUnlinked "
611               "should be called first.");
612     }
613 
614     sp<TransferDeathRecipient> recipient =
615             new TransferDeathRecipient(binder, cookie, this, mOnDied, mOnUnlinked);
616 
617     status_t status = binder->linkToDeath(recipient, cookie, 0 /*flags*/);
618     if (status != STATUS_OK) {
619         // When we failed to link, the destructor of TransferDeathRecipient runs here, which
620         // ensures that mOnUnlinked is called before we return with an error from this method.
621         return PruneStatusT(status);
622     }
623 
624     mDeathRecipients.push_back(recipient);
625 
626     pruneDeadTransferEntriesLocked();
627     return STATUS_OK;
628 }
629 
unlinkToDeath(const sp<IBinder> & binder,void * cookie)630 binder_status_t AIBinder_DeathRecipient::unlinkToDeath(const sp<IBinder>& binder, void* cookie) {
631     LOG_ALWAYS_FATAL_IF(binder == nullptr, "binder == nullptr");
632 
633     std::lock_guard<std::mutex> l(mDeathRecipientsMutex);
634 
635     for (auto it = mDeathRecipients.rbegin(); it != mDeathRecipients.rend(); ++it) {
636         sp<TransferDeathRecipient> recipient = *it;
637 
638         if (recipient->getCookie() == cookie && recipient->getWho() == binder) {
639             mDeathRecipients.erase(it.base() - 1);
640 
641             status_t status = binder->unlinkToDeath(recipient, cookie, 0 /*flags*/);
642             if (status != ::android::OK) {
643                 ALOGE("%s: removed reference to death recipient but unlink failed: %s", __func__,
644                       statusToString(status).c_str());
645             }
646             return PruneStatusT(status);
647         }
648     }
649 
650     return STATUS_NAME_NOT_FOUND;
651 }
652 
setOnUnlinked(AIBinder_DeathRecipient_onBinderUnlinked onUnlinked)653 void AIBinder_DeathRecipient::setOnUnlinked(AIBinder_DeathRecipient_onBinderUnlinked onUnlinked) {
654     mOnUnlinked = onUnlinked;
655 }
656 
657 // start of C-API methods
658 
AIBinder_new(const AIBinder_Class * clazz,void * args)659 AIBinder* AIBinder_new(const AIBinder_Class* clazz, void* args) {
660     if (clazz == nullptr) {
661         ALOGE("%s: Must provide class to construct local binder.", __func__);
662         return nullptr;
663     }
664 
665     void* userData = clazz->onCreate(args);
666 
667     sp<AIBinder> ret = new ABBinder(clazz, userData);
668     ABBinderTag::attach(ret->getBinder());
669 
670     AIBinder_incStrong(ret.get());
671     return ret.get();
672 }
673 
AIBinder_isRemote(const AIBinder * binder)674 bool AIBinder_isRemote(const AIBinder* binder) {
675     if (binder == nullptr) {
676         return false;
677     }
678 
679     return binder->isRemote();
680 }
681 
AIBinder_isAlive(const AIBinder * binder)682 bool AIBinder_isAlive(const AIBinder* binder) {
683     if (binder == nullptr) {
684         return false;
685     }
686 
687     return const_cast<AIBinder*>(binder)->getBinder()->isBinderAlive();
688 }
689 
AIBinder_ping(AIBinder * binder)690 binder_status_t AIBinder_ping(AIBinder* binder) {
691     if (binder == nullptr) {
692         return STATUS_UNEXPECTED_NULL;
693     }
694 
695     return PruneStatusT(binder->getBinder()->pingBinder());
696 }
697 
AIBinder_dump(AIBinder * binder,int fd,const char ** args,uint32_t numArgs)698 binder_status_t AIBinder_dump(AIBinder* binder, int fd, const char** args, uint32_t numArgs) {
699     if (binder == nullptr) {
700         return STATUS_UNEXPECTED_NULL;
701     }
702 
703     ABBinder* bBinder = binder->asABBinder();
704     if (bBinder != nullptr) {
705         AIBinder_onDump onDump = binder->getClass()->onDump;
706         if (onDump == nullptr) {
707             return STATUS_OK;
708         }
709         return PruneStatusT(onDump(bBinder, fd, args, numArgs));
710     }
711 
712     ::android::Vector<String16> utf16Args;
713     utf16Args.setCapacity(numArgs);
714     for (uint32_t i = 0; i < numArgs; i++) {
715         utf16Args.push(String16(String8(args[i])));
716     }
717 
718     status_t status = binder->getBinder()->dump(fd, utf16Args);
719     return PruneStatusT(status);
720 }
721 
AIBinder_linkToDeath(AIBinder * binder,AIBinder_DeathRecipient * recipient,void * cookie)722 binder_status_t AIBinder_linkToDeath(AIBinder* binder, AIBinder_DeathRecipient* recipient,
723                                      void* cookie) {
724     if (binder == nullptr || recipient == nullptr) {
725         ALOGE("%s: Must provide binder (%p) and recipient (%p)", __func__, binder, recipient);
726         return STATUS_UNEXPECTED_NULL;
727     }
728 
729     binder_status_t ret = recipient->linkToDeath(binder->getBinder(), cookie);
730     if (ret == STATUS_OK) {
731         binder->addDeathRecipient(recipient, cookie);
732     }
733     return ret;
734 }
735 
AIBinder_unlinkToDeath(AIBinder * binder,AIBinder_DeathRecipient * recipient,void * cookie)736 binder_status_t AIBinder_unlinkToDeath(AIBinder* binder, AIBinder_DeathRecipient* recipient,
737                                        void* cookie) {
738     if (binder == nullptr || recipient == nullptr) {
739         ALOGE("%s: Must provide binder (%p) and recipient (%p)", __func__, binder, recipient);
740         return STATUS_UNEXPECTED_NULL;
741     }
742 
743     // returns binder_status_t
744     return recipient->unlinkToDeath(binder->getBinder(), cookie);
745 }
746 
747 #ifdef BINDER_WITH_KERNEL_IPC
AIBinder_getCallingUid()748 uid_t AIBinder_getCallingUid() {
749     return ::android::IPCThreadState::self()->getCallingUid();
750 }
751 
AIBinder_getCallingPid()752 pid_t AIBinder_getCallingPid() {
753     return ::android::IPCThreadState::self()->getCallingPid();
754 }
755 
AIBinder_isHandlingTransaction()756 bool AIBinder_isHandlingTransaction() {
757     return ::android::IPCThreadState::self()->getServingStackPointer() != nullptr;
758 }
759 #endif
760 
AIBinder_incStrong(AIBinder * binder)761 void AIBinder_incStrong(AIBinder* binder) {
762     if (binder == nullptr) {
763         return;
764     }
765 
766     binder->incStrong(nullptr);
767 }
AIBinder_decStrong(AIBinder * binder)768 void AIBinder_decStrong(AIBinder* binder) {
769     if (binder == nullptr) {
770         ALOGE("%s: on null binder", __func__);
771         return;
772     }
773 
774     binder->decStrong(nullptr);
775 }
AIBinder_debugGetRefCount(AIBinder * binder)776 int32_t AIBinder_debugGetRefCount(AIBinder* binder) {
777     if (binder == nullptr) {
778         ALOGE("%s: on null binder", __func__);
779         return -1;
780     }
781 
782     return binder->getStrongCount();
783 }
784 
AIBinder_associateClass(AIBinder * binder,const AIBinder_Class * clazz)785 bool AIBinder_associateClass(AIBinder* binder, const AIBinder_Class* clazz) {
786     if (binder == nullptr) {
787         return false;
788     }
789 
790     return binder->associateClass(clazz);
791 }
792 
AIBinder_getClass(AIBinder * binder)793 const AIBinder_Class* AIBinder_getClass(AIBinder* binder) {
794     if (binder == nullptr) {
795         return nullptr;
796     }
797 
798     return binder->getClass();
799 }
800 
AIBinder_getUserData(AIBinder * binder)801 void* AIBinder_getUserData(AIBinder* binder) {
802     if (binder == nullptr) {
803         return nullptr;
804     }
805 
806     ABBinder* bBinder = binder->asABBinder();
807     if (bBinder == nullptr) {
808         return nullptr;
809     }
810 
811     return bBinder->getUserData();
812 }
813 
AIBinder_prepareTransaction(AIBinder * binder,AParcel ** in)814 binder_status_t AIBinder_prepareTransaction(AIBinder* binder, AParcel** in) {
815     if (binder == nullptr || in == nullptr) {
816         ALOGE("%s: requires non-null parameters binder (%p) and in (%p).", __func__, binder, in);
817         return STATUS_UNEXPECTED_NULL;
818     }
819     const AIBinder_Class* clazz = binder->getClass();
820     if (clazz == nullptr) {
821         ALOGE("%s: Class must be defined for a remote binder transaction. See "
822               "AIBinder_associateClass.",
823               __func__);
824         return STATUS_INVALID_OPERATION;
825     }
826 
827     *in = new AParcel(binder);
828     (*in)->get()->markForBinder(binder->getBinder());
829 
830     status_t status = android::OK;
831 
832     // note - this is the only read of a value in clazz, and it comes with a warning
833     // on the API itself. Do not copy this design. Instead, attach data in a new
834     // version of the prepareTransaction function.
835     if (clazz->writeHeader) {
836         status = (*in)->get()->writeInterfaceToken(clazz->getInterfaceDescriptor());
837     }
838     binder_status_t ret = PruneStatusT(status);
839 
840     if (ret != STATUS_OK) {
841         delete *in;
842         *in = nullptr;
843     }
844 
845     return ret;
846 }
847 
DestroyParcel(AParcel ** parcel)848 static void DestroyParcel(AParcel** parcel) {
849     delete *parcel;
850     *parcel = nullptr;
851 }
852 
AIBinder_transact(AIBinder * binder,transaction_code_t code,AParcel ** in,AParcel ** out,binder_flags_t flags)853 binder_status_t AIBinder_transact(AIBinder* binder, transaction_code_t code, AParcel** in,
854                                   AParcel** out, binder_flags_t flags) {
855     const AIBinder_Class* clazz = binder ? binder->getClass() : nullptr;
856 
857     std::string sectionName;
858     bool tracingEnabled = get_trace_enabled_tags() & ATRACE_TAG_AIDL;
859     if (tracingEnabled) {
860         sectionName = getTraceSectionName(clazz, code, false /*isServer*/);
861         trace_begin(ATRACE_TAG_AIDL, sectionName.c_str());
862     }
863 
864     scope_guard guard = make_scope_guard([&]() {
865         if (tracingEnabled) trace_end(ATRACE_TAG_AIDL);
866     });
867 
868     if (in == nullptr) {
869         ALOGE("%s: requires non-null in parameter", __func__);
870         return STATUS_UNEXPECTED_NULL;
871     }
872 
873     using AutoParcelDestroyer = std::unique_ptr<AParcel*, void (*)(AParcel**)>;
874     // This object is the input to the transaction. This function takes ownership of it and deletes
875     // it.
876     AutoParcelDestroyer forIn(in, DestroyParcel);
877 
878     if (!isUserCommand(code)) {
879         ALOGE("%s: Only user-defined transactions can be made from the NDK, but requested: %d",
880               __func__, code);
881         return STATUS_UNKNOWN_TRANSACTION;
882     }
883 
884     constexpr binder_flags_t kAllFlags = FLAG_PRIVATE_VENDOR | FLAG_ONEWAY | FLAG_CLEAR_BUF;
885     if ((flags & ~kAllFlags) != 0) {
886         ALOGE("%s: Unrecognized flags sent: %d", __func__, flags);
887         return STATUS_BAD_VALUE;
888     }
889 
890     if (binder == nullptr || *in == nullptr || out == nullptr) {
891         ALOGE("%s: requires non-null parameters binder (%p), in (%p), and out (%p).", __func__,
892               binder, in, out);
893         return STATUS_UNEXPECTED_NULL;
894     }
895 
896     if ((*in)->getBinder() != binder) {
897         ALOGE("%s: parcel is associated with binder object %p but called with %p", __func__, binder,
898               (*in)->getBinder());
899         return STATUS_BAD_VALUE;
900     }
901 
902     *out = new AParcel(binder);
903 
904     status_t status = binder->getBinder()->transact(code, *(*in)->get(), (*out)->get(), flags);
905     binder_status_t ret = PruneStatusT(status);
906 
907     if (ret != STATUS_OK) {
908         delete *out;
909         *out = nullptr;
910     }
911 
912     return ret;
913 }
914 
AIBinder_DeathRecipient_new(AIBinder_DeathRecipient_onBinderDied onBinderDied)915 AIBinder_DeathRecipient* AIBinder_DeathRecipient_new(
916         AIBinder_DeathRecipient_onBinderDied onBinderDied) {
917     if (onBinderDied == nullptr) {
918         ALOGE("%s: requires non-null onBinderDied parameter.", __func__);
919         return nullptr;
920     }
921     auto ret = new AIBinder_DeathRecipient(onBinderDied);
922     ret->incStrong(nullptr);
923     return ret;
924 }
925 
AIBinder_DeathRecipient_setOnUnlinked(AIBinder_DeathRecipient * recipient,AIBinder_DeathRecipient_onBinderUnlinked onUnlinked)926 void AIBinder_DeathRecipient_setOnUnlinked(AIBinder_DeathRecipient* recipient,
927                                            AIBinder_DeathRecipient_onBinderUnlinked onUnlinked) {
928     if (recipient == nullptr) {
929         return;
930     }
931 
932     recipient->setOnUnlinked(onUnlinked);
933 }
934 
AIBinder_DeathRecipient_delete(AIBinder_DeathRecipient * recipient)935 void AIBinder_DeathRecipient_delete(AIBinder_DeathRecipient* recipient) {
936     if (recipient == nullptr) {
937         return;
938     }
939 
940     recipient->decStrong(nullptr);
941 }
942 
AIBinder_getExtension(AIBinder * binder,AIBinder ** outExt)943 binder_status_t AIBinder_getExtension(AIBinder* binder, AIBinder** outExt) {
944     if (binder == nullptr || outExt == nullptr) {
945         if (outExt != nullptr) {
946             *outExt = nullptr;
947         }
948         return STATUS_UNEXPECTED_NULL;
949     }
950 
951     sp<IBinder> ext;
952     status_t res = binder->getBinder()->getExtension(&ext);
953 
954     if (res != android::OK) {
955         *outExt = nullptr;
956         return PruneStatusT(res);
957     }
958 
959     sp<AIBinder> ret = ABpBinder::lookupOrCreateFromBinder(ext);
960     if (ret != nullptr) ret->incStrong(binder);
961 
962     *outExt = ret.get();
963     return STATUS_OK;
964 }
965 
AIBinder_setExtension(AIBinder * binder,AIBinder * ext)966 binder_status_t AIBinder_setExtension(AIBinder* binder, AIBinder* ext) {
967     if (binder == nullptr || ext == nullptr) {
968         return STATUS_UNEXPECTED_NULL;
969     }
970 
971     ABBinder* rawBinder = binder->asABBinder();
972     if (rawBinder == nullptr) {
973         return STATUS_INVALID_OPERATION;
974     }
975 
976     rawBinder->setExtension(ext->getBinder());
977     return STATUS_OK;
978 }
979 
980 // platform methods follow
981 
AIBinder_setRequestingSid(AIBinder * binder,bool requestingSid)982 void AIBinder_setRequestingSid(AIBinder* binder, bool requestingSid) {
983     ABBinder* localBinder = binder->asABBinder();
984     LOG_ALWAYS_FATAL_IF(localBinder == nullptr,
985                         "AIBinder_setRequestingSid must be called on a local binder");
986 
987     localBinder->setRequestingSid(requestingSid);
988 }
989 
990 #ifdef BINDER_WITH_KERNEL_IPC
AIBinder_getCallingSid()991 const char* AIBinder_getCallingSid() {
992     return ::android::IPCThreadState::self()->getCallingSid();
993 }
994 #endif
995 
AIBinder_setMinSchedulerPolicy(AIBinder * binder,int policy,int priority)996 void AIBinder_setMinSchedulerPolicy(AIBinder* binder, int policy, int priority) {
997     binder->asABBinder()->setMinSchedulerPolicy(policy, priority);
998 }
999 
AIBinder_setInheritRt(AIBinder * binder,bool inheritRt)1000 void AIBinder_setInheritRt(AIBinder* binder, bool inheritRt) {
1001     ABBinder* localBinder = binder->asABBinder();
1002     LOG_ALWAYS_FATAL_IF(localBinder == nullptr,
1003                         "AIBinder_setInheritRt must be called on a local binder");
1004 
1005     localBinder->setInheritRt(inheritRt);
1006 }