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