1 /*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <binder/Binder.h>
18
19 #include <atomic>
20 #include <set>
21
22 #include <android-base/logging.h>
23 #include <android-base/unique_fd.h>
24 #include <binder/BpBinder.h>
25 #include <binder/IInterface.h>
26 #include <binder/IPCThreadState.h>
27 #include <binder/IResultReceiver.h>
28 #include <binder/IShellCallback.h>
29 #include <binder/Parcel.h>
30 #include <binder/RpcServer.h>
31 #include <private/android_filesystem_config.h>
32 #include <utils/misc.h>
33
34 #include <inttypes.h>
35 #include <linux/sched.h>
36 #include <stdio.h>
37
38 #include "RpcState.h"
39
40 namespace android {
41
42 // Service implementations inherit from BBinder and IBinder, and this is frozen
43 // in prebuilts.
44 #ifdef __LP64__
45 static_assert(sizeof(IBinder) == 24);
46 static_assert(sizeof(BBinder) == 40);
47 #else
48 static_assert(sizeof(IBinder) == 12);
49 static_assert(sizeof(BBinder) == 20);
50 #endif
51
52 #ifdef BINDER_RPC_DEV_SERVERS
53 constexpr const bool kEnableRpcDevServers = true;
54 #else
55 constexpr const bool kEnableRpcDevServers = false;
56 #endif
57
58 // Log any reply transactions for which the data exceeds this size
59 #define LOG_REPLIES_OVER_SIZE (300 * 1024)
60 // ---------------------------------------------------------------------------
61
IBinder()62 IBinder::IBinder()
63 : RefBase()
64 {
65 }
66
~IBinder()67 IBinder::~IBinder()
68 {
69 }
70
71 // ---------------------------------------------------------------------------
72
queryLocalInterface(const String16 &)73 sp<IInterface> IBinder::queryLocalInterface(const String16& /*descriptor*/)
74 {
75 return nullptr;
76 }
77
localBinder()78 BBinder* IBinder::localBinder()
79 {
80 return nullptr;
81 }
82
remoteBinder()83 BpBinder* IBinder::remoteBinder()
84 {
85 return nullptr;
86 }
87
checkSubclass(const void *) const88 bool IBinder::checkSubclass(const void* /*subclassID*/) const
89 {
90 return false;
91 }
92
93
shellCommand(const sp<IBinder> & target,int in,int out,int err,Vector<String16> & args,const sp<IShellCallback> & callback,const sp<IResultReceiver> & resultReceiver)94 status_t IBinder::shellCommand(const sp<IBinder>& target, int in, int out, int err,
95 Vector<String16>& args, const sp<IShellCallback>& callback,
96 const sp<IResultReceiver>& resultReceiver)
97 {
98 Parcel send;
99 Parcel reply;
100 send.writeFileDescriptor(in);
101 send.writeFileDescriptor(out);
102 send.writeFileDescriptor(err);
103 const size_t numArgs = args.size();
104 send.writeInt32(numArgs);
105 for (size_t i = 0; i < numArgs; i++) {
106 send.writeString16(args[i]);
107 }
108 send.writeStrongBinder(callback != nullptr ? IInterface::asBinder(callback) : nullptr);
109 send.writeStrongBinder(resultReceiver != nullptr ? IInterface::asBinder(resultReceiver) : nullptr);
110 return target->transact(SHELL_COMMAND_TRANSACTION, send, &reply);
111 }
112
getExtension(sp<IBinder> * out)113 status_t IBinder::getExtension(sp<IBinder>* out) {
114 BBinder* local = this->localBinder();
115 if (local != nullptr) {
116 *out = local->getExtension();
117 return OK;
118 }
119
120 BpBinder* proxy = this->remoteBinder();
121 LOG_ALWAYS_FATAL_IF(proxy == nullptr);
122
123 Parcel data;
124 Parcel reply;
125 status_t status = transact(EXTENSION_TRANSACTION, data, &reply);
126 if (status != OK) return status;
127
128 return reply.readNullableStrongBinder(out);
129 }
130
getDebugPid(pid_t * out)131 status_t IBinder::getDebugPid(pid_t* out) {
132 BBinder* local = this->localBinder();
133 if (local != nullptr) {
134 *out = local->getDebugPid();
135 return OK;
136 }
137
138 BpBinder* proxy = this->remoteBinder();
139 LOG_ALWAYS_FATAL_IF(proxy == nullptr);
140
141 Parcel data;
142 Parcel reply;
143 status_t status = transact(DEBUG_PID_TRANSACTION, data, &reply);
144 if (status != OK) return status;
145
146 int32_t pid;
147 status = reply.readInt32(&pid);
148 if (status != OK) return status;
149
150 if (pid < 0 || pid > std::numeric_limits<pid_t>::max()) {
151 return BAD_VALUE;
152 }
153 *out = pid;
154 return OK;
155 }
156
setRpcClientDebug(android::base::unique_fd socketFd,const sp<IBinder> & keepAliveBinder)157 status_t IBinder::setRpcClientDebug(android::base::unique_fd socketFd,
158 const sp<IBinder>& keepAliveBinder) {
159 if constexpr (!kEnableRpcDevServers) {
160 ALOGW("setRpcClientDebug disallowed because RPC is not enabled");
161 return INVALID_OPERATION;
162 }
163
164 BBinder* local = this->localBinder();
165 if (local != nullptr) {
166 return local->BBinder::setRpcClientDebug(std::move(socketFd), keepAliveBinder);
167 }
168
169 BpBinder* proxy = this->remoteBinder();
170 LOG_ALWAYS_FATAL_IF(proxy == nullptr, "binder object must be either local or remote");
171
172 Parcel data;
173 Parcel reply;
174 status_t status;
175 if (status = data.writeBool(socketFd.ok()); status != OK) return status;
176 if (socketFd.ok()) {
177 // writeUniqueFileDescriptor currently makes an unnecessary dup().
178 status = data.writeFileDescriptor(socketFd.release(), true /* own */);
179 if (status != OK) return status;
180 }
181 if (status = data.writeStrongBinder(keepAliveBinder); status != OK) return status;
182 return transact(SET_RPC_CLIENT_TRANSACTION, data, &reply);
183 }
184
withLock(const std::function<void ()> & doWithLock)185 void IBinder::withLock(const std::function<void()>& doWithLock) {
186 BBinder* local = localBinder();
187 if (local) {
188 local->withLock(doWithLock);
189 return;
190 }
191 BpBinder* proxy = this->remoteBinder();
192 LOG_ALWAYS_FATAL_IF(proxy == nullptr, "binder object must be either local or remote");
193 proxy->withLock(doWithLock);
194 }
195
196 // ---------------------------------------------------------------------------
197
198 class BBinder::RpcServerLink : public IBinder::DeathRecipient {
199 public:
200 // On binder died, calls RpcServer::shutdown on @a rpcServer, and removes itself from @a binder.
RpcServerLink(const sp<RpcServer> & rpcServer,const sp<IBinder> & keepAliveBinder,const wp<BBinder> & binder)201 RpcServerLink(const sp<RpcServer>& rpcServer, const sp<IBinder>& keepAliveBinder,
202 const wp<BBinder>& binder)
203 : mRpcServer(rpcServer), mKeepAliveBinder(keepAliveBinder), mBinder(binder) {}
binderDied(const wp<IBinder> &)204 void binderDied(const wp<IBinder>&) override {
205 LOG_RPC_DETAIL("RpcServerLink: binder died, shutting down RpcServer");
206 if (mRpcServer == nullptr) {
207 ALOGW("RpcServerLink: Unable to shut down RpcServer because it does not exist.");
208 } else {
209 ALOGW_IF(!mRpcServer->shutdown(),
210 "RpcServerLink: RpcServer did not shut down properly. Not started?");
211 }
212 mRpcServer.clear();
213
214 auto promoted = mBinder.promote();
215 if (promoted == nullptr) {
216 ALOGW("RpcServerLink: Unable to remove link from parent binder object because parent "
217 "binder object is gone.");
218 } else {
219 promoted->removeRpcServerLink(sp<RpcServerLink>::fromExisting(this));
220 }
221 mBinder.clear();
222 }
223
224 private:
225 sp<RpcServer> mRpcServer;
226 sp<IBinder> mKeepAliveBinder; // hold to avoid automatically unlinking
227 wp<BBinder> mBinder;
228 };
229
230 class BBinder::Extras
231 {
232 public:
233 // unlocked objects
234 bool mRequestingSid = false;
235 bool mInheritRt = false;
236 sp<IBinder> mExtension;
237 int mPolicy = SCHED_NORMAL;
238 int mPriority = 0;
239
240 // for below objects
241 Mutex mLock;
242 std::set<sp<RpcServerLink>> mRpcServerLinks;
243 BpBinder::ObjectManager mObjects;
244 };
245
246 // ---------------------------------------------------------------------------
247
BBinder()248 BBinder::BBinder() : mExtras(nullptr), mStability(0), mParceled(false) {}
249
isBinderAlive() const250 bool BBinder::isBinderAlive() const
251 {
252 return true;
253 }
254
pingBinder()255 status_t BBinder::pingBinder()
256 {
257 return NO_ERROR;
258 }
259
getInterfaceDescriptor() const260 const String16& BBinder::getInterfaceDescriptor() const
261 {
262 // This is a local static rather than a global static,
263 // to avoid static initializer ordering issues.
264 static String16 sEmptyDescriptor;
265 ALOGW("reached BBinder::getInterfaceDescriptor (this=%p)", this);
266 return sEmptyDescriptor;
267 }
268
269 // NOLINTNEXTLINE(google-default-arguments)
transact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)270 status_t BBinder::transact(
271 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
272 {
273 data.setDataPosition(0);
274
275 if (reply != nullptr && (flags & FLAG_CLEAR_BUF)) {
276 reply->markSensitive();
277 }
278
279 status_t err = NO_ERROR;
280 switch (code) {
281 case PING_TRANSACTION:
282 err = pingBinder();
283 break;
284 case EXTENSION_TRANSACTION:
285 CHECK(reply != nullptr);
286 err = reply->writeStrongBinder(getExtension());
287 break;
288 case DEBUG_PID_TRANSACTION:
289 CHECK(reply != nullptr);
290 err = reply->writeInt32(getDebugPid());
291 break;
292 case SET_RPC_CLIENT_TRANSACTION: {
293 err = setRpcClientDebug(data);
294 break;
295 }
296 default:
297 err = onTransact(code, data, reply, flags);
298 break;
299 }
300
301 // In case this is being transacted on in the same process.
302 if (reply != nullptr) {
303 reply->setDataPosition(0);
304 if (reply->dataSize() > LOG_REPLIES_OVER_SIZE) {
305 ALOGW("Large reply transaction of %zu bytes, interface descriptor %s, code %d",
306 reply->dataSize(), String8(getInterfaceDescriptor()).c_str(), code);
307 }
308 }
309
310 return err;
311 }
312
313 // NOLINTNEXTLINE(google-default-arguments)
linkToDeath(const sp<DeathRecipient> &,void *,uint32_t)314 status_t BBinder::linkToDeath(
315 const sp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
316 uint32_t /*flags*/)
317 {
318 return INVALID_OPERATION;
319 }
320
321 // NOLINTNEXTLINE(google-default-arguments)
unlinkToDeath(const wp<DeathRecipient> &,void *,uint32_t,wp<DeathRecipient> *)322 status_t BBinder::unlinkToDeath(
323 const wp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
324 uint32_t /*flags*/, wp<DeathRecipient>* /*outRecipient*/)
325 {
326 return INVALID_OPERATION;
327 }
328
dump(int,const Vector<String16> &)329 status_t BBinder::dump(int /*fd*/, const Vector<String16>& /*args*/)
330 {
331 return NO_ERROR;
332 }
333
attachObject(const void * objectID,void * object,void * cleanupCookie,object_cleanup_func func)334 void* BBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,
335 object_cleanup_func func) {
336 Extras* e = getOrCreateExtras();
337 LOG_ALWAYS_FATAL_IF(!e, "no memory");
338
339 AutoMutex _l(e->mLock);
340 return e->mObjects.attach(objectID, object, cleanupCookie, func);
341 }
342
findObject(const void * objectID) const343 void* BBinder::findObject(const void* objectID) const
344 {
345 Extras* e = mExtras.load(std::memory_order_acquire);
346 if (!e) return nullptr;
347
348 AutoMutex _l(e->mLock);
349 return e->mObjects.find(objectID);
350 }
351
detachObject(const void * objectID)352 void* BBinder::detachObject(const void* objectID) {
353 Extras* e = mExtras.load(std::memory_order_acquire);
354 if (!e) return nullptr;
355
356 AutoMutex _l(e->mLock);
357 return e->mObjects.detach(objectID);
358 }
359
withLock(const std::function<void ()> & doWithLock)360 void BBinder::withLock(const std::function<void()>& doWithLock) {
361 Extras* e = getOrCreateExtras();
362 LOG_ALWAYS_FATAL_IF(!e, "no memory");
363
364 AutoMutex _l(e->mLock);
365 doWithLock();
366 }
367
localBinder()368 BBinder* BBinder::localBinder()
369 {
370 return this;
371 }
372
isRequestingSid()373 bool BBinder::isRequestingSid()
374 {
375 Extras* e = mExtras.load(std::memory_order_acquire);
376
377 return e && e->mRequestingSid;
378 }
379
setRequestingSid(bool requestingSid)380 void BBinder::setRequestingSid(bool requestingSid)
381 {
382 LOG_ALWAYS_FATAL_IF(mParceled,
383 "setRequestingSid() should not be called after a binder object "
384 "is parceled/sent to another process");
385
386 Extras* e = mExtras.load(std::memory_order_acquire);
387
388 if (!e) {
389 // default is false. Most things don't need sids, so avoiding allocations when possible.
390 if (!requestingSid) {
391 return;
392 }
393
394 e = getOrCreateExtras();
395 if (!e) return; // out of memory
396 }
397
398 e->mRequestingSid = requestingSid;
399 }
400
getExtension()401 sp<IBinder> BBinder::getExtension() {
402 Extras* e = mExtras.load(std::memory_order_acquire);
403 if (e == nullptr) return nullptr;
404 return e->mExtension;
405 }
406
setMinSchedulerPolicy(int policy,int priority)407 void BBinder::setMinSchedulerPolicy(int policy, int priority) {
408 LOG_ALWAYS_FATAL_IF(mParceled,
409 "setMinSchedulerPolicy() should not be called after a binder object "
410 "is parceled/sent to another process");
411
412 switch (policy) {
413 case SCHED_NORMAL:
414 LOG_ALWAYS_FATAL_IF(priority < -20 || priority > 19, "Invalid priority for SCHED_NORMAL: %d", priority);
415 break;
416 case SCHED_RR:
417 case SCHED_FIFO:
418 LOG_ALWAYS_FATAL_IF(priority < 1 || priority > 99, "Invalid priority for sched %d: %d", policy, priority);
419 break;
420 default:
421 LOG_ALWAYS_FATAL("Unrecognized scheduling policy: %d", policy);
422 }
423
424 Extras* e = mExtras.load(std::memory_order_acquire);
425
426 if (e == nullptr) {
427 // Avoid allocations if called with default.
428 if (policy == SCHED_NORMAL && priority == 0) {
429 return;
430 }
431
432 e = getOrCreateExtras();
433 if (!e) return; // out of memory
434 }
435
436 e->mPolicy = policy;
437 e->mPriority = priority;
438 }
439
getMinSchedulerPolicy()440 int BBinder::getMinSchedulerPolicy() {
441 Extras* e = mExtras.load(std::memory_order_acquire);
442 if (e == nullptr) return SCHED_NORMAL;
443 return e->mPolicy;
444 }
445
getMinSchedulerPriority()446 int BBinder::getMinSchedulerPriority() {
447 Extras* e = mExtras.load(std::memory_order_acquire);
448 if (e == nullptr) return 0;
449 return e->mPriority;
450 }
451
isInheritRt()452 bool BBinder::isInheritRt() {
453 Extras* e = mExtras.load(std::memory_order_acquire);
454
455 return e && e->mInheritRt;
456 }
457
setInheritRt(bool inheritRt)458 void BBinder::setInheritRt(bool inheritRt) {
459 LOG_ALWAYS_FATAL_IF(mParceled,
460 "setInheritRt() should not be called after a binder object "
461 "is parceled/sent to another process");
462
463 Extras* e = mExtras.load(std::memory_order_acquire);
464
465 if (!e) {
466 if (!inheritRt) {
467 return;
468 }
469
470 e = getOrCreateExtras();
471 if (!e) return; // out of memory
472 }
473
474 e->mInheritRt = inheritRt;
475 }
476
getDebugPid()477 pid_t BBinder::getDebugPid() {
478 return getpid();
479 }
480
setExtension(const sp<IBinder> & extension)481 void BBinder::setExtension(const sp<IBinder>& extension) {
482 LOG_ALWAYS_FATAL_IF(mParceled,
483 "setExtension() should not be called after a binder object "
484 "is parceled/sent to another process");
485
486 Extras* e = getOrCreateExtras();
487 e->mExtension = extension;
488 }
489
wasParceled()490 bool BBinder::wasParceled() {
491 return mParceled;
492 }
493
setParceled()494 void BBinder::setParceled() {
495 mParceled = true;
496 }
497
setRpcClientDebug(const Parcel & data)498 status_t BBinder::setRpcClientDebug(const Parcel& data) {
499 if constexpr (!kEnableRpcDevServers) {
500 ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
501 return INVALID_OPERATION;
502 }
503 uid_t uid = IPCThreadState::self()->getCallingUid();
504 if (uid != AID_ROOT) {
505 ALOGE("%s: not allowed because client %" PRIu32 " is not root", __PRETTY_FUNCTION__, uid);
506 return PERMISSION_DENIED;
507 }
508 status_t status;
509 bool hasSocketFd;
510 android::base::unique_fd clientFd;
511
512 if (status = data.readBool(&hasSocketFd); status != OK) return status;
513 if (hasSocketFd) {
514 if (status = data.readUniqueFileDescriptor(&clientFd); status != OK) return status;
515 }
516 sp<IBinder> keepAliveBinder;
517 if (status = data.readNullableStrongBinder(&keepAliveBinder); status != OK) return status;
518
519 return setRpcClientDebug(std::move(clientFd), keepAliveBinder);
520 }
521
setRpcClientDebug(android::base::unique_fd socketFd,const sp<IBinder> & keepAliveBinder)522 status_t BBinder::setRpcClientDebug(android::base::unique_fd socketFd,
523 const sp<IBinder>& keepAliveBinder) {
524 if constexpr (!kEnableRpcDevServers) {
525 ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
526 return INVALID_OPERATION;
527 }
528
529 const int socketFdForPrint = socketFd.get();
530 LOG_RPC_DETAIL("%s(fd=%d)", __PRETTY_FUNCTION__, socketFdForPrint);
531
532 if (!socketFd.ok()) {
533 ALOGE("%s: No socket FD provided.", __PRETTY_FUNCTION__);
534 return BAD_VALUE;
535 }
536
537 if (keepAliveBinder == nullptr) {
538 ALOGE("%s: No keepAliveBinder provided.", __PRETTY_FUNCTION__);
539 return UNEXPECTED_NULL;
540 }
541
542 size_t binderThreadPoolMaxCount = ProcessState::self()->getThreadPoolMaxThreadCount();
543 if (binderThreadPoolMaxCount <= 1) {
544 ALOGE("%s: ProcessState thread pool max count is %zu. RPC is disabled for this service "
545 "because RPC requires the service to support multithreading.",
546 __PRETTY_FUNCTION__, binderThreadPoolMaxCount);
547 return INVALID_OPERATION;
548 }
549
550 // Weak ref to avoid circular dependency:
551 // BBinder -> RpcServerLink ----> RpcServer -X-> BBinder
552 // `-X-> BBinder
553 auto weakThis = wp<BBinder>::fromExisting(this);
554
555 Extras* e = getOrCreateExtras();
556 AutoMutex _l(e->mLock);
557 auto rpcServer = RpcServer::make();
558 LOG_ALWAYS_FATAL_IF(rpcServer == nullptr, "RpcServer::make returns null");
559 auto link = sp<RpcServerLink>::make(rpcServer, keepAliveBinder, weakThis);
560 if (auto status = keepAliveBinder->linkToDeath(link, nullptr, 0); status != OK) {
561 ALOGE("%s: keepAliveBinder->linkToDeath returns %s", __PRETTY_FUNCTION__,
562 statusToString(status).c_str());
563 return status;
564 }
565 rpcServer->setRootObjectWeak(weakThis);
566 if (auto status = rpcServer->setupExternalServer(std::move(socketFd)); status != OK) {
567 return status;
568 }
569 rpcServer->setMaxThreads(binderThreadPoolMaxCount);
570 rpcServer->start();
571 e->mRpcServerLinks.emplace(link);
572 LOG_RPC_DETAIL("%s(fd=%d) successful", __PRETTY_FUNCTION__, socketFdForPrint);
573 return OK;
574 }
575
removeRpcServerLink(const sp<RpcServerLink> & link)576 void BBinder::removeRpcServerLink(const sp<RpcServerLink>& link) {
577 Extras* e = mExtras.load(std::memory_order_acquire);
578 if (!e) return;
579 AutoMutex _l(e->mLock);
580 (void)e->mRpcServerLinks.erase(link);
581 }
582
~BBinder()583 BBinder::~BBinder()
584 {
585 if (!wasParceled() && getExtension()) {
586 ALOGW("Binder %p destroyed with extension attached before being parceled.", this);
587 }
588
589 Extras* e = mExtras.load(std::memory_order_relaxed);
590 if (e) delete e;
591 }
592
593
594 // NOLINTNEXTLINE(google-default-arguments)
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t)595 status_t BBinder::onTransact(
596 uint32_t code, const Parcel& data, Parcel* reply, uint32_t /*flags*/)
597 {
598 switch (code) {
599 case INTERFACE_TRANSACTION:
600 CHECK(reply != nullptr);
601 reply->writeString16(getInterfaceDescriptor());
602 return NO_ERROR;
603
604 case DUMP_TRANSACTION: {
605 int fd = data.readFileDescriptor();
606 int argc = data.readInt32();
607 Vector<String16> args;
608 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
609 args.add(data.readString16());
610 }
611 return dump(fd, args);
612 }
613
614 case SHELL_COMMAND_TRANSACTION: {
615 int in = data.readFileDescriptor();
616 int out = data.readFileDescriptor();
617 int err = data.readFileDescriptor();
618 int argc = data.readInt32();
619 Vector<String16> args;
620 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
621 args.add(data.readString16());
622 }
623 sp<IShellCallback> shellCallback = IShellCallback::asInterface(
624 data.readStrongBinder());
625 sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(
626 data.readStrongBinder());
627
628 // XXX can't add virtuals until binaries are updated.
629 //return shellCommand(in, out, err, args, resultReceiver);
630 (void)in;
631 (void)out;
632 (void)err;
633
634 if (resultReceiver != nullptr) {
635 resultReceiver->send(INVALID_OPERATION);
636 }
637
638 return NO_ERROR;
639 }
640
641 case SYSPROPS_TRANSACTION: {
642 report_sysprop_change();
643 return NO_ERROR;
644 }
645
646 default:
647 return UNKNOWN_TRANSACTION;
648 }
649 }
650
getOrCreateExtras()651 BBinder::Extras* BBinder::getOrCreateExtras()
652 {
653 Extras* e = mExtras.load(std::memory_order_acquire);
654
655 if (!e) {
656 e = new Extras;
657 Extras* expected = nullptr;
658 if (!mExtras.compare_exchange_strong(expected, e,
659 std::memory_order_release,
660 std::memory_order_acquire)) {
661 delete e;
662 e = expected; // Filled in by CAS
663 }
664 if (e == nullptr) return nullptr; // out of memory
665 }
666
667 return e;
668 }
669
670 // ---------------------------------------------------------------------------
671
672 enum {
673 // This is used to transfer ownership of the remote binder from
674 // the BpRefBase object holding it (when it is constructed), to the
675 // owner of the BpRefBase object when it first acquires that BpRefBase.
676 kRemoteAcquired = 0x00000001
677 };
678
BpRefBase(const sp<IBinder> & o)679 BpRefBase::BpRefBase(const sp<IBinder>& o)
680 : mRemote(o.get()), mRefs(nullptr), mState(0)
681 {
682 extendObjectLifetime(OBJECT_LIFETIME_WEAK);
683
684 if (mRemote) {
685 mRemote->incStrong(this); // Removed on first IncStrong().
686 mRefs = mRemote->createWeak(this); // Held for our entire lifetime.
687 }
688 }
689
~BpRefBase()690 BpRefBase::~BpRefBase()
691 {
692 if (mRemote) {
693 if (!(mState.load(std::memory_order_relaxed)&kRemoteAcquired)) {
694 mRemote->decStrong(this);
695 }
696 mRefs->decWeak(this);
697 }
698 }
699
onFirstRef()700 void BpRefBase::onFirstRef()
701 {
702 mState.fetch_or(kRemoteAcquired, std::memory_order_relaxed);
703 }
704
onLastStrongRef(const void *)705 void BpRefBase::onLastStrongRef(const void* /*id*/)
706 {
707 if (mRemote) {
708 mRemote->decStrong(this);
709 }
710 }
711
onIncStrongAttempted(uint32_t,const void *)712 bool BpRefBase::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
713 {
714 return mRemote ? mRefs->attemptIncStrong(this) : false;
715 }
716
717 // ---------------------------------------------------------------------------
718
719 } // namespace android
720