• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 "ProtectCallback.h"
18 
19 #include <android-base/logging.h>
20 #include <android-base/scopeguard.h>
21 #include <android-base/thread_annotations.h>
22 #include <android/binder_auto_utils.h>
23 #include <android/binder_interface_utils.h>
24 #include <nnapi/Result.h>
25 
26 #include <algorithm>
27 #include <functional>
28 #include <map>
29 #include <memory>
30 #include <mutex>
31 #include <vector>
32 
33 #include "Utils.h"
34 
35 namespace aidl::android::hardware::neuralnetworks::utils {
36 
37 namespace {
38 
39 // Only dereference the cookie if it's valid (if it's in this set)
40 // Only used with ndk
41 std::mutex sCookiesMutex;
42 uintptr_t sCookieKeyCounter GUARDED_BY(sCookiesMutex) = 0;
43 std::map<uintptr_t, std::weak_ptr<DeathMonitor>> sCookies GUARDED_BY(sCookiesMutex);
44 
45 }  // namespace
46 
serviceDied()47 void DeathMonitor::serviceDied() {
48     std::lock_guard guard(mMutex);
49     std::for_each(mObjects.begin(), mObjects.end(),
50                   [](IProtectedCallback* killable) { killable->notifyAsDeadObject(); });
51 }
52 
serviceDied(void * cookie)53 void DeathMonitor::serviceDied(void* cookie) {
54     std::shared_ptr<DeathMonitor> monitor;
55     {
56         std::lock_guard<std::mutex> guard(sCookiesMutex);
57         if (auto it = sCookies.find(reinterpret_cast<uintptr_t>(cookie)); it != sCookies.end()) {
58             monitor = it->second.lock();
59             sCookies.erase(it);
60         } else {
61             LOG(INFO)
62                     << "Service died, but cookie is no longer valid so there is nothing to notify.";
63             return;
64         }
65     }
66     if (monitor) {
67         LOG(INFO) << "Notifying DeathMonitor from serviceDied.";
68         monitor->serviceDied();
69     } else {
70         LOG(INFO) << "Tried to notify DeathMonitor from serviceDied but could not promote.";
71     }
72 }
73 
add(IProtectedCallback * killable) const74 void DeathMonitor::add(IProtectedCallback* killable) const {
75     CHECK(killable != nullptr);
76     std::lock_guard guard(mMutex);
77     mObjects.push_back(killable);
78 }
79 
remove(IProtectedCallback * killable) const80 void DeathMonitor::remove(IProtectedCallback* killable) const {
81     CHECK(killable != nullptr);
82     std::lock_guard guard(mMutex);
83     const auto removedIter = std::remove(mObjects.begin(), mObjects.end(), killable);
84     mObjects.erase(removedIter);
85 }
86 
~DeathMonitor()87 DeathMonitor::~DeathMonitor() {
88     // lock must be taken so object is not used in OnBinderDied"
89     std::lock_guard<std::mutex> guard(sCookiesMutex);
90     sCookies.erase(kCookieKey);
91 }
92 
create(std::shared_ptr<ndk::ICInterface> object)93 nn::GeneralResult<DeathHandler> DeathHandler::create(std::shared_ptr<ndk::ICInterface> object) {
94     if (object == nullptr) {
95         return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
96                << "utils::DeathHandler::create must have non-null object";
97     }
98 
99     std::shared_ptr<DeathMonitor> deathMonitor;
100     {
101         std::lock_guard<std::mutex> guard(sCookiesMutex);
102         deathMonitor = std::make_shared<DeathMonitor>(sCookieKeyCounter++);
103         sCookies[deathMonitor->getCookieKey()] = deathMonitor;
104     }
105 
106     auto deathRecipient = ndk::ScopedAIBinder_DeathRecipient(
107             AIBinder_DeathRecipient_new(DeathMonitor::serviceDied));
108 
109     // If passed a local binder, AIBinder_linkToDeath will do nothing and return
110     // STATUS_INVALID_OPERATION. We ignore this case because we only use local binders in tests
111     // where this is not an error.
112     if (object->isRemote()) {
113         const auto ret = ndk::ScopedAStatus::fromStatus(
114                 AIBinder_linkToDeath(object->asBinder().get(), deathRecipient.get(),
115                                      reinterpret_cast<void*>(deathMonitor->getCookieKey())));
116         HANDLE_ASTATUS(ret) << "AIBinder_linkToDeath failed";
117     }
118 
119     return DeathHandler(std::move(object), std::move(deathRecipient), std::move(deathMonitor));
120 }
121 
DeathHandler(std::shared_ptr<ndk::ICInterface> object,ndk::ScopedAIBinder_DeathRecipient deathRecipient,std::shared_ptr<DeathMonitor> deathMonitor)122 DeathHandler::DeathHandler(std::shared_ptr<ndk::ICInterface> object,
123                            ndk::ScopedAIBinder_DeathRecipient deathRecipient,
124                            std::shared_ptr<DeathMonitor> deathMonitor)
125     : kObject(std::move(object)),
126       kDeathRecipient(std::move(deathRecipient)),
127       kDeathMonitor(std::move(deathMonitor)) {
128     CHECK(kObject != nullptr);
129     CHECK(kDeathRecipient.get() != nullptr);
130     CHECK(kDeathMonitor != nullptr);
131 }
132 
~DeathHandler()133 DeathHandler::~DeathHandler() {
134     if (kObject != nullptr && kDeathRecipient.get() != nullptr && kDeathMonitor != nullptr) {
135         const auto ret = ndk::ScopedAStatus::fromStatus(
136                 AIBinder_unlinkToDeath(kObject->asBinder().get(), kDeathRecipient.get(),
137                                        reinterpret_cast<void*>(kDeathMonitor->getCookieKey())));
138         const auto maybeSuccess = handleTransportError(ret);
139         if (!maybeSuccess.ok()) {
140             LOG(ERROR) << maybeSuccess.error().message;
141         }
142     }
143 }
144 
protectCallback(IProtectedCallback * killable) const145 [[nodiscard]] ::android::base::ScopeGuard<DeathHandler::Cleanup> DeathHandler::protectCallback(
146         IProtectedCallback* killable) const {
147     CHECK(killable != nullptr);
148     kDeathMonitor->add(killable);
149     return ::android::base::make_scope_guard(
150             [deathMonitor = kDeathMonitor, killable] { deathMonitor->remove(killable); });
151 }
152 
153 }  // namespace aidl::android::hardware::neuralnetworks::utils
154