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 "ibinder_internal.h"
20 
21 #include <android/binder_stability.h>
22 #include <android/binder_status.h>
23 #include "parcel_internal.h"
24 #include "status_internal.h"
25 
26 #include <android-base/logging.h>
27 #include <binder/IPCThreadState.h>
28 #include <binder/IResultReceiver.h>
29 #include <private/android_filesystem_config.h>
30 
31 using DeathRecipient = ::android::IBinder::DeathRecipient;
32 
33 using ::android::IBinder;
34 using ::android::IResultReceiver;
35 using ::android::Parcel;
36 using ::android::sp;
37 using ::android::status_t;
38 using ::android::String16;
39 using ::android::String8;
40 using ::android::wp;
41 
42 namespace ABBinderTag {
43 
44 static const void* kId = "ABBinder";
45 static void* kValue = static_cast<void*>(new bool{true});
clean(const void *,void *,void *)46 void clean(const void* /*id*/, void* /*obj*/, void* /*cookie*/){/* do nothing */};
47 
attach(const sp<IBinder> & binder)48 static void attach(const sp<IBinder>& binder) {
49     binder->attachObject(kId, kValue, nullptr /*cookie*/, clean);
50 }
has(const sp<IBinder> & binder)51 static bool has(const sp<IBinder>& binder) {
52     return binder != nullptr && binder->findObject(kId) == kValue;
53 }
54 
55 }  // namespace ABBinderTag
56 
57 namespace ABpBinderTag {
58 
59 static std::mutex gLock;
60 static const void* kId = "ABpBinder";
61 struct Value {
62     wp<ABpBinder> binder;
63 };
clean(const void * id,void * obj,void * cookie)64 void clean(const void* id, void* obj, void* cookie) {
65     CHECK(id == kId) << id << " " << obj << " " << cookie;
66 
67     delete static_cast<Value*>(obj);
68 };
69 
70 }  // namespace ABpBinderTag
71 
AIBinder(const AIBinder_Class * clazz)72 AIBinder::AIBinder(const AIBinder_Class* clazz) : mClazz(clazz) {}
~AIBinder()73 AIBinder::~AIBinder() {}
74 
associateClass(const AIBinder_Class * clazz)75 bool AIBinder::associateClass(const AIBinder_Class* clazz) {
76     if (clazz == nullptr) return false;
77     if (mClazz == clazz) return true;
78 
79     String8 newDescriptor(clazz->getInterfaceDescriptor());
80 
81     if (mClazz != nullptr) {
82         String8 currentDescriptor(mClazz->getInterfaceDescriptor());
83         if (newDescriptor == currentDescriptor) {
84             LOG(ERROR) << __func__ << ": Class descriptors '" << currentDescriptor
85                        << "' match during associateClass, but they are different class objects. "
86                           "Class descriptor collision?";
87         } else {
88             LOG(ERROR) << __func__
89                        << ": Class cannot be associated on object which already has a class. "
90                           "Trying to associate to '"
91                        << newDescriptor.c_str() << "' but already set to '"
92                        << currentDescriptor.c_str() << "'.";
93         }
94 
95         // always a failure because we know mClazz != clazz
96         return false;
97     }
98 
99     CHECK(asABpBinder() != nullptr);  // ABBinder always has a descriptor
100 
101     String8 descriptor(getBinder()->getInterfaceDescriptor());
102     if (descriptor != newDescriptor) {
103         if (getBinder()->isBinderAlive()) {
104             LOG(ERROR) << __func__ << ": Expecting binder to have class '" << newDescriptor.c_str()
105                        << "' but descriptor is actually '" << descriptor.c_str() << "'.";
106         } else {
107             // b/155793159
108             LOG(ERROR) << __func__ << ": Cannot associate class '" << newDescriptor.c_str()
109                        << "' to dead binder.";
110         }
111         return false;
112     }
113 
114     // if this is a local object, it's not one known to libbinder_ndk
115     mClazz = clazz;
116 
117     return true;
118 }
119 
ABBinder(const AIBinder_Class * clazz,void * userData)120 ABBinder::ABBinder(const AIBinder_Class* clazz, void* userData)
121     : AIBinder(clazz), BBinder(), mUserData(userData) {
122     CHECK(clazz != nullptr);
123 }
~ABBinder()124 ABBinder::~ABBinder() {
125     getClass()->onDestroy(mUserData);
126 }
127 
getInterfaceDescriptor() const128 const String16& ABBinder::getInterfaceDescriptor() const {
129     return getClass()->getInterfaceDescriptor();
130 }
131 
dump(int fd,const::android::Vector<String16> & args)132 status_t ABBinder::dump(int fd, const ::android::Vector<String16>& args) {
133     AIBinder_onDump onDump = getClass()->onDump;
134 
135     if (onDump == nullptr) {
136         return STATUS_OK;
137     }
138 
139     // technically UINT32_MAX would be okay here, but INT32_MAX is expected since this may be
140     // null in Java
141     if (args.size() > INT32_MAX) {
142         LOG(ERROR) << "ABBinder::dump received too many arguments: " << args.size();
143         return STATUS_BAD_VALUE;
144     }
145 
146     std::vector<String8> utf8Args;  // owns memory of utf8s
147     utf8Args.reserve(args.size());
148     std::vector<const char*> utf8Pointers;  // what can be passed over NDK API
149     utf8Pointers.reserve(args.size());
150 
151     for (size_t i = 0; i < args.size(); i++) {
152         utf8Args.push_back(String8(args[i]));
153         utf8Pointers.push_back(utf8Args[i].c_str());
154     }
155 
156     return onDump(this, fd, utf8Pointers.data(), utf8Pointers.size());
157 }
158 
onTransact(transaction_code_t code,const Parcel & data,Parcel * reply,binder_flags_t flags)159 status_t ABBinder::onTransact(transaction_code_t code, const Parcel& data, Parcel* reply,
160                               binder_flags_t flags) {
161     if (isUserCommand(code)) {
162         if (!data.checkInterface(this)) {
163             return STATUS_BAD_TYPE;
164         }
165 
166         const AParcel in = AParcel::readOnly(this, &data);
167         AParcel out = AParcel(this, reply, false /*owns*/);
168 
169         binder_status_t status = getClass()->onTransact(this, code, &in, &out);
170         return PruneStatusT(status);
171     } else if (code == SHELL_COMMAND_TRANSACTION) {
172         int in = data.readFileDescriptor();
173         int out = data.readFileDescriptor();
174         int err = data.readFileDescriptor();
175 
176         int argc = data.readInt32();
177         std::vector<String8> utf8Args;          // owns memory of utf8s
178         std::vector<const char*> utf8Pointers;  // what can be passed over NDK API
179         for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
180             utf8Args.push_back(String8(data.readString16()));
181             utf8Pointers.push_back(utf8Args[i].c_str());
182         }
183 
184         data.readStrongBinder();  // skip over the IShellCallback
185         sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(data.readStrongBinder());
186 
187         // Shell commands should only be callable by ADB.
188         uid_t uid = AIBinder_getCallingUid();
189         if (uid != AID_ROOT && uid != AID_SHELL) {
190             if (resultReceiver != nullptr) {
191                 resultReceiver->send(-1);
192             }
193             return STATUS_PERMISSION_DENIED;
194         }
195 
196         // Check that the file descriptors are valid.
197         if (in == STATUS_BAD_TYPE || out == STATUS_BAD_TYPE || err == STATUS_BAD_TYPE) {
198             if (resultReceiver != nullptr) {
199                 resultReceiver->send(-1);
200             }
201             return STATUS_BAD_VALUE;
202         }
203 
204         binder_status_t status = getClass()->handleShellCommand(
205                 this, in, out, err, utf8Pointers.data(), utf8Pointers.size());
206         if (resultReceiver != nullptr) {
207             resultReceiver->send(status);
208         }
209         return status;
210     } else {
211         return BBinder::onTransact(code, data, reply, flags);
212     }
213 }
214 
ABpBinder(const::android::sp<::android::IBinder> & binder)215 ABpBinder::ABpBinder(const ::android::sp<::android::IBinder>& binder)
216     : AIBinder(nullptr /*clazz*/), BpRefBase(binder) {
217     CHECK(binder != nullptr);
218 }
~ABpBinder()219 ABpBinder::~ABpBinder() {}
220 
onLastStrongRef(const void * id)221 void ABpBinder::onLastStrongRef(const void* id) {
222     {
223         std::lock_guard<std::mutex> lock(ABpBinderTag::gLock);
224         // Since ABpBinder is OBJECT_LIFETIME_WEAK, we must remove this weak reference in order for
225         // the ABpBinder to be deleted. Since a strong reference to this ABpBinder object should no
226         // longer be able to exist at the time of this method call, there is no longer a need to
227         // recover it.
228 
229         ABpBinderTag::Value* value =
230                 static_cast<ABpBinderTag::Value*>(remote()->findObject(ABpBinderTag::kId));
231         if (value != nullptr) {
232             value->binder = nullptr;
233         }
234     }
235 
236     BpRefBase::onLastStrongRef(id);
237 }
238 
lookupOrCreateFromBinder(const::android::sp<::android::IBinder> & binder)239 sp<AIBinder> ABpBinder::lookupOrCreateFromBinder(const ::android::sp<::android::IBinder>& binder) {
240     if (binder == nullptr) {
241         return nullptr;
242     }
243     if (ABBinderTag::has(binder)) {
244         return static_cast<ABBinder*>(binder.get());
245     }
246 
247     // The following code ensures that for a given binder object (remote or local), if it is not an
248     // ABBinder then at most one ABpBinder object exists in a given process representing it.
249     std::lock_guard<std::mutex> lock(ABpBinderTag::gLock);
250 
251     ABpBinderTag::Value* value =
252             static_cast<ABpBinderTag::Value*>(binder->findObject(ABpBinderTag::kId));
253     if (value == nullptr) {
254         value = new ABpBinderTag::Value;
255         binder->attachObject(ABpBinderTag::kId, static_cast<void*>(value), nullptr /*cookie*/,
256                              ABpBinderTag::clean);
257     }
258 
259     sp<ABpBinder> ret = value->binder.promote();
260     if (ret == nullptr) {
261         ret = new ABpBinder(binder);
262         value->binder = ret;
263     }
264 
265     return ret;
266 }
267 
268 struct AIBinder_Weak {
269     wp<AIBinder> binder;
270 };
AIBinder_Weak_new(AIBinder * binder)271 AIBinder_Weak* AIBinder_Weak_new(AIBinder* binder) {
272     if (binder == nullptr) {
273         return nullptr;
274     }
275 
276     return new AIBinder_Weak{wp<AIBinder>(binder)};
277 }
AIBinder_Weak_delete(AIBinder_Weak * weakBinder)278 void AIBinder_Weak_delete(AIBinder_Weak* weakBinder) {
279     delete weakBinder;
280 }
AIBinder_Weak_promote(AIBinder_Weak * weakBinder)281 AIBinder* AIBinder_Weak_promote(AIBinder_Weak* weakBinder) {
282     if (weakBinder == nullptr) {
283         return nullptr;
284     }
285 
286     sp<AIBinder> binder = weakBinder->binder.promote();
287     AIBinder_incStrong(binder.get());
288     return binder.get();
289 }
290 
AIBinder_Class(const char * interfaceDescriptor,AIBinder_Class_onCreate onCreate,AIBinder_Class_onDestroy onDestroy,AIBinder_Class_onTransact onTransact)291 AIBinder_Class::AIBinder_Class(const char* interfaceDescriptor, AIBinder_Class_onCreate onCreate,
292                                AIBinder_Class_onDestroy onDestroy,
293                                AIBinder_Class_onTransact onTransact)
294     : onCreate(onCreate),
295       onDestroy(onDestroy),
296       onTransact(onTransact),
297       mInterfaceDescriptor(interfaceDescriptor) {}
298 
AIBinder_Class_define(const char * interfaceDescriptor,AIBinder_Class_onCreate onCreate,AIBinder_Class_onDestroy onDestroy,AIBinder_Class_onTransact onTransact)299 AIBinder_Class* AIBinder_Class_define(const char* interfaceDescriptor,
300                                       AIBinder_Class_onCreate onCreate,
301                                       AIBinder_Class_onDestroy onDestroy,
302                                       AIBinder_Class_onTransact onTransact) {
303     if (interfaceDescriptor == nullptr || onCreate == nullptr || onDestroy == nullptr ||
304         onTransact == nullptr) {
305         return nullptr;
306     }
307 
308     return new AIBinder_Class(interfaceDescriptor, onCreate, onDestroy, onTransact);
309 }
310 
AIBinder_Class_setOnDump(AIBinder_Class * clazz,AIBinder_onDump onDump)311 void AIBinder_Class_setOnDump(AIBinder_Class* clazz, AIBinder_onDump onDump) {
312     CHECK(clazz != nullptr) << "setOnDump requires non-null clazz";
313 
314     // this is required to be called before instances are instantiated
315     clazz->onDump = onDump;
316 }
317 
AIBinder_Class_setHandleShellCommand(AIBinder_Class * clazz,AIBinder_handleShellCommand handleShellCommand)318 void AIBinder_Class_setHandleShellCommand(AIBinder_Class* clazz,
319                                           AIBinder_handleShellCommand handleShellCommand) {
320     CHECK(clazz != nullptr) << "setHandleShellCommand requires non-null clazz";
321 
322     clazz->handleShellCommand = handleShellCommand;
323 }
324 
binderDied(const wp<IBinder> & who)325 void AIBinder_DeathRecipient::TransferDeathRecipient::binderDied(const wp<IBinder>& who) {
326     CHECK(who == mWho);
327 
328     mOnDied(mCookie);
329 
330     sp<AIBinder_DeathRecipient> recipient = mParentRecipient.promote();
331     sp<IBinder> strongWho = who.promote();
332 
333     // otherwise this will be cleaned up later with pruneDeadTransferEntriesLocked
334     if (recipient != nullptr && strongWho != nullptr) {
335         status_t result = recipient->unlinkToDeath(strongWho, mCookie);
336         if (result != ::android::DEAD_OBJECT) {
337             LOG(WARNING) << "Unlinking to dead binder resulted in: " << result;
338         }
339     }
340 
341     mWho = nullptr;
342 }
343 
AIBinder_DeathRecipient(AIBinder_DeathRecipient_onBinderDied onDied)344 AIBinder_DeathRecipient::AIBinder_DeathRecipient(AIBinder_DeathRecipient_onBinderDied onDied)
345     : mOnDied(onDied) {
346     CHECK(onDied != nullptr);
347 }
348 
pruneDeadTransferEntriesLocked()349 void AIBinder_DeathRecipient::pruneDeadTransferEntriesLocked() {
350     mDeathRecipients.erase(std::remove_if(mDeathRecipients.begin(), mDeathRecipients.end(),
351                                           [](const sp<TransferDeathRecipient>& tdr) {
352                                               return tdr->getWho() == nullptr;
353                                           }),
354                            mDeathRecipients.end());
355 }
356 
linkToDeath(sp<IBinder> binder,void * cookie)357 binder_status_t AIBinder_DeathRecipient::linkToDeath(sp<IBinder> binder, void* cookie) {
358     CHECK(binder != nullptr);
359 
360     std::lock_guard<std::mutex> l(mDeathRecipientsMutex);
361 
362     sp<TransferDeathRecipient> recipient =
363             new TransferDeathRecipient(binder, cookie, this, mOnDied);
364 
365     status_t status = binder->linkToDeath(recipient, cookie, 0 /*flags*/);
366     if (status != STATUS_OK) {
367         return PruneStatusT(status);
368     }
369 
370     mDeathRecipients.push_back(recipient);
371 
372     pruneDeadTransferEntriesLocked();
373     return STATUS_OK;
374 }
375 
unlinkToDeath(sp<IBinder> binder,void * cookie)376 binder_status_t AIBinder_DeathRecipient::unlinkToDeath(sp<IBinder> binder, void* cookie) {
377     CHECK(binder != nullptr);
378 
379     std::lock_guard<std::mutex> l(mDeathRecipientsMutex);
380 
381     for (auto it = mDeathRecipients.rbegin(); it != mDeathRecipients.rend(); ++it) {
382         sp<TransferDeathRecipient> recipient = *it;
383 
384         if (recipient->getCookie() == cookie && recipient->getWho() == binder) {
385             mDeathRecipients.erase(it.base() - 1);
386 
387             status_t status = binder->unlinkToDeath(recipient, cookie, 0 /*flags*/);
388             if (status != ::android::OK) {
389                 LOG(ERROR) << __func__
390                            << ": removed reference to death recipient but unlink failed.";
391             }
392             return PruneStatusT(status);
393         }
394     }
395 
396     return STATUS_NAME_NOT_FOUND;
397 }
398 
399 // start of C-API methods
400 
AIBinder_new(const AIBinder_Class * clazz,void * args)401 AIBinder* AIBinder_new(const AIBinder_Class* clazz, void* args) {
402     if (clazz == nullptr) {
403         LOG(ERROR) << __func__ << ": Must provide class to construct local binder.";
404         return nullptr;
405     }
406 
407     void* userData = clazz->onCreate(args);
408 
409     sp<AIBinder> ret = new ABBinder(clazz, userData);
410     ABBinderTag::attach(ret->getBinder());
411 
412     AIBinder_incStrong(ret.get());
413     return ret.get();
414 }
415 
AIBinder_isRemote(const AIBinder * binder)416 bool AIBinder_isRemote(const AIBinder* binder) {
417     if (binder == nullptr) {
418         return false;
419     }
420 
421     return binder->isRemote();
422 }
423 
AIBinder_isAlive(const AIBinder * binder)424 bool AIBinder_isAlive(const AIBinder* binder) {
425     if (binder == nullptr) {
426         return false;
427     }
428 
429     return const_cast<AIBinder*>(binder)->getBinder()->isBinderAlive();
430 }
431 
AIBinder_ping(AIBinder * binder)432 binder_status_t AIBinder_ping(AIBinder* binder) {
433     if (binder == nullptr) {
434         return STATUS_UNEXPECTED_NULL;
435     }
436 
437     return PruneStatusT(binder->getBinder()->pingBinder());
438 }
439 
AIBinder_dump(AIBinder * binder,int fd,const char ** args,uint32_t numArgs)440 binder_status_t AIBinder_dump(AIBinder* binder, int fd, const char** args, uint32_t numArgs) {
441     if (binder == nullptr) {
442         return STATUS_UNEXPECTED_NULL;
443     }
444 
445     ABBinder* bBinder = binder->asABBinder();
446     if (bBinder != nullptr) {
447         AIBinder_onDump onDump = binder->getClass()->onDump;
448         if (onDump == nullptr) {
449             return STATUS_OK;
450         }
451         return PruneStatusT(onDump(bBinder, fd, args, numArgs));
452     }
453 
454     ::android::Vector<String16> utf16Args;
455     utf16Args.setCapacity(numArgs);
456     for (uint32_t i = 0; i < numArgs; i++) {
457         utf16Args.push(String16(String8(args[i])));
458     }
459 
460     status_t status = binder->getBinder()->dump(fd, utf16Args);
461     return PruneStatusT(status);
462 }
463 
AIBinder_linkToDeath(AIBinder * binder,AIBinder_DeathRecipient * recipient,void * cookie)464 binder_status_t AIBinder_linkToDeath(AIBinder* binder, AIBinder_DeathRecipient* recipient,
465                                      void* cookie) {
466     if (binder == nullptr || recipient == nullptr) {
467         LOG(ERROR) << __func__ << ": Must provide binder and recipient.";
468         return STATUS_UNEXPECTED_NULL;
469     }
470 
471     // returns binder_status_t
472     return recipient->linkToDeath(binder->getBinder(), cookie);
473 }
474 
AIBinder_unlinkToDeath(AIBinder * binder,AIBinder_DeathRecipient * recipient,void * cookie)475 binder_status_t AIBinder_unlinkToDeath(AIBinder* binder, AIBinder_DeathRecipient* recipient,
476                                        void* cookie) {
477     if (binder == nullptr || recipient == nullptr) {
478         LOG(ERROR) << __func__ << ": Must provide binder and recipient.";
479         return STATUS_UNEXPECTED_NULL;
480     }
481 
482     // returns binder_status_t
483     return recipient->unlinkToDeath(binder->getBinder(), cookie);
484 }
485 
AIBinder_getCallingUid()486 uid_t AIBinder_getCallingUid() {
487     return ::android::IPCThreadState::self()->getCallingUid();
488 }
489 
AIBinder_getCallingPid()490 pid_t AIBinder_getCallingPid() {
491     return ::android::IPCThreadState::self()->getCallingPid();
492 }
493 
AIBinder_incStrong(AIBinder * binder)494 void AIBinder_incStrong(AIBinder* binder) {
495     if (binder == nullptr) {
496         return;
497     }
498 
499     binder->incStrong(nullptr);
500 }
AIBinder_decStrong(AIBinder * binder)501 void AIBinder_decStrong(AIBinder* binder) {
502     if (binder == nullptr) {
503         LOG(ERROR) << __func__ << ": on null binder";
504         return;
505     }
506 
507     binder->decStrong(nullptr);
508 }
AIBinder_debugGetRefCount(AIBinder * binder)509 int32_t AIBinder_debugGetRefCount(AIBinder* binder) {
510     if (binder == nullptr) {
511         LOG(ERROR) << __func__ << ": on null binder";
512         return -1;
513     }
514 
515     return binder->getStrongCount();
516 }
517 
AIBinder_associateClass(AIBinder * binder,const AIBinder_Class * clazz)518 bool AIBinder_associateClass(AIBinder* binder, const AIBinder_Class* clazz) {
519     if (binder == nullptr) {
520         return false;
521     }
522 
523     return binder->associateClass(clazz);
524 }
525 
AIBinder_getClass(AIBinder * binder)526 const AIBinder_Class* AIBinder_getClass(AIBinder* binder) {
527     if (binder == nullptr) {
528         return nullptr;
529     }
530 
531     return binder->getClass();
532 }
533 
AIBinder_getUserData(AIBinder * binder)534 void* AIBinder_getUserData(AIBinder* binder) {
535     if (binder == nullptr) {
536         return nullptr;
537     }
538 
539     ABBinder* bBinder = binder->asABBinder();
540     if (bBinder == nullptr) {
541         return nullptr;
542     }
543 
544     return bBinder->getUserData();
545 }
546 
AIBinder_prepareTransaction(AIBinder * binder,AParcel ** in)547 binder_status_t AIBinder_prepareTransaction(AIBinder* binder, AParcel** in) {
548     if (binder == nullptr || in == nullptr) {
549         LOG(ERROR) << __func__ << ": requires non-null parameters.";
550         return STATUS_UNEXPECTED_NULL;
551     }
552     const AIBinder_Class* clazz = binder->getClass();
553     if (clazz == nullptr) {
554         LOG(ERROR) << __func__
555                    << ": Class must be defined for a remote binder transaction. See "
556                       "AIBinder_associateClass.";
557         return STATUS_INVALID_OPERATION;
558     }
559 
560     if (!binder->isRemote()) {
561         LOG(WARNING) << "A binder object at " << binder
562                      << " is being transacted on, however, this object is in the same process as "
563                         "its proxy. Transacting with this binder is expensive compared to just "
564                         "calling the corresponding functionality in the same process.";
565     }
566 
567     *in = new AParcel(binder);
568     status_t status = (*in)->get()->writeInterfaceToken(clazz->getInterfaceDescriptor());
569     binder_status_t ret = PruneStatusT(status);
570 
571     if (ret != STATUS_OK) {
572         delete *in;
573         *in = nullptr;
574     }
575 
576     return ret;
577 }
578 
DestroyParcel(AParcel ** parcel)579 static void DestroyParcel(AParcel** parcel) {
580     delete *parcel;
581     *parcel = nullptr;
582 }
583 
AIBinder_transact(AIBinder * binder,transaction_code_t code,AParcel ** in,AParcel ** out,binder_flags_t flags)584 binder_status_t AIBinder_transact(AIBinder* binder, transaction_code_t code, AParcel** in,
585                                   AParcel** out, binder_flags_t flags) {
586     if (in == nullptr) {
587         LOG(ERROR) << __func__ << ": requires non-null in parameter";
588         return STATUS_UNEXPECTED_NULL;
589     }
590 
591     using AutoParcelDestroyer = std::unique_ptr<AParcel*, void (*)(AParcel**)>;
592     // This object is the input to the transaction. This function takes ownership of it and deletes
593     // it.
594     AutoParcelDestroyer forIn(in, DestroyParcel);
595 
596     if (!isUserCommand(code)) {
597         LOG(ERROR) << __func__ << ": Only user-defined transactions can be made from the NDK.";
598         return STATUS_UNKNOWN_TRANSACTION;
599     }
600 
601     constexpr binder_flags_t kAllFlags = FLAG_PRIVATE_VENDOR | FLAG_ONEWAY;
602     if ((flags & ~kAllFlags) != 0) {
603         LOG(ERROR) << __func__ << ": Unrecognized flags sent: " << flags;
604         return STATUS_BAD_VALUE;
605     }
606 
607     if (binder == nullptr || *in == nullptr || out == nullptr) {
608         LOG(ERROR) << __func__ << ": requires non-null parameters.";
609         return STATUS_UNEXPECTED_NULL;
610     }
611 
612     if ((*in)->getBinder() != binder) {
613         LOG(ERROR) << __func__ << ": parcel is associated with binder object " << binder
614                    << " but called with " << (*in)->getBinder();
615         return STATUS_BAD_VALUE;
616     }
617 
618     *out = new AParcel(binder);
619 
620     status_t status = binder->getBinder()->transact(code, *(*in)->get(), (*out)->get(), flags);
621     binder_status_t ret = PruneStatusT(status);
622 
623     if (ret != STATUS_OK) {
624         delete *out;
625         *out = nullptr;
626     }
627 
628     return ret;
629 }
630 
AIBinder_DeathRecipient_new(AIBinder_DeathRecipient_onBinderDied onBinderDied)631 AIBinder_DeathRecipient* AIBinder_DeathRecipient_new(
632         AIBinder_DeathRecipient_onBinderDied onBinderDied) {
633     if (onBinderDied == nullptr) {
634         LOG(ERROR) << __func__ << ": requires non-null onBinderDied parameter.";
635         return nullptr;
636     }
637     auto ret = new AIBinder_DeathRecipient(onBinderDied);
638     ret->incStrong(nullptr);
639     return ret;
640 }
641 
AIBinder_DeathRecipient_delete(AIBinder_DeathRecipient * recipient)642 void AIBinder_DeathRecipient_delete(AIBinder_DeathRecipient* recipient) {
643     if (recipient == nullptr) {
644         return;
645     }
646 
647     recipient->decStrong(nullptr);
648 }
649 
AIBinder_getExtension(AIBinder * binder,AIBinder ** outExt)650 binder_status_t AIBinder_getExtension(AIBinder* binder, AIBinder** outExt) {
651     if (binder == nullptr || outExt == nullptr) {
652         if (outExt != nullptr) {
653             *outExt = nullptr;
654         }
655         return STATUS_UNEXPECTED_NULL;
656     }
657 
658     sp<IBinder> ext;
659     status_t res = binder->getBinder()->getExtension(&ext);
660 
661     if (res != android::OK) {
662         *outExt = nullptr;
663         return PruneStatusT(res);
664     }
665 
666     sp<AIBinder> ret = ABpBinder::lookupOrCreateFromBinder(ext);
667     if (ret != nullptr) ret->incStrong(binder);
668 
669     *outExt = ret.get();
670     return STATUS_OK;
671 }
672 
AIBinder_setExtension(AIBinder * binder,AIBinder * ext)673 binder_status_t AIBinder_setExtension(AIBinder* binder, AIBinder* ext) {
674     if (binder == nullptr || ext == nullptr) {
675         return STATUS_UNEXPECTED_NULL;
676     }
677 
678     ABBinder* rawBinder = binder->asABBinder();
679     if (rawBinder == nullptr) {
680         return STATUS_INVALID_OPERATION;
681     }
682 
683     rawBinder->setExtension(ext->getBinder());
684     return STATUS_OK;
685 }
686 
687 // platform methods follow
688 
AIBinder_setRequestingSid(AIBinder * binder,bool requestingSid)689 void AIBinder_setRequestingSid(AIBinder* binder, bool requestingSid) {
690     ABBinder* localBinder = binder->asABBinder();
691     if (localBinder == nullptr) {
692         LOG(FATAL) << "AIBinder_setRequestingSid must be called on a local binder";
693     }
694 
695     localBinder->setRequestingSid(requestingSid);
696 }
697 
AIBinder_getCallingSid()698 const char* AIBinder_getCallingSid() {
699     return ::android::IPCThreadState::self()->getCallingSid();
700 }
701 
AIBinder_toPlatformBinder(AIBinder * binder)702 android::sp<android::IBinder> AIBinder_toPlatformBinder(AIBinder* binder) {
703     if (binder == nullptr) return nullptr;
704     return binder->getBinder();
705 }
706 
AIBinder_fromPlatformBinder(const android::sp<android::IBinder> & binder)707 AIBinder* AIBinder_fromPlatformBinder(const android::sp<android::IBinder>& binder) {
708     sp<AIBinder> ndkBinder = ABpBinder::lookupOrCreateFromBinder(binder);
709     AIBinder_incStrong(ndkBinder.get());
710     return ndkBinder.get();
711 }
712