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