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 #define LOG_TAG "HidlLazyUtils"
18 
19 #include <hidl/HidlLazyUtils.h>
20 #include <hidl/HidlTransportSupport.h>
21 
22 #include <android-base/logging.h>
23 
24 #include <android/hidl/manager/1.2/IClientCallback.h>
25 #include <android/hidl/manager/1.2/IServiceManager.h>
26 
27 namespace android {
28 namespace hardware {
29 namespace details {
30 
31 using ::android::hidl::base::V1_0::IBase;
32 
33 class ClientCounterCallback : public ::android::hidl::manager::V1_2::IClientCallback {
34   public:
ClientCounterCallback()35     ClientCounterCallback() {}
36 
37     bool addRegisteredService(const sp<IBase>& service, const std::string& name);
38 
39   protected:
40     Return<void> onClients(const sp<IBase>& service, bool clients) override;
41 
42   private:
43     struct Service {
44         sp<IBase> service;
45         std::string name;
46         bool clients = false;
47     };
48 
49     /**
50      * Looks up service that is guaranteed to be registered (service from
51      * onClients).
52      */
53     Service& assertRegisteredService(const sp<IBase>& service);
54 
55     /**
56      * Registers or re-registers services. Returns whether successful.
57      */
58     bool registerService(const sp<IBase>& service, const std::string& name);
59 
60     /**
61      * Unregisters all services that we can. If we can't unregister all, re-register other
62      * services.
63      */
64     void tryShutdown();
65 
66     /**
67      * Number of services that have been registered.
68      */
69     std::vector<Service> mRegisteredServices;
70 };
71 
72 class LazyServiceRegistrarImpl {
73   public:
LazyServiceRegistrarImpl()74     LazyServiceRegistrarImpl() : mClientCallback(new ClientCounterCallback) {}
75 
76     status_t registerService(const sp<::android::hidl::base::V1_0::IBase>& service,
77                              const std::string& name);
78 
79   private:
80     sp<ClientCounterCallback> mClientCallback;
81 };
82 
addRegisteredService(const sp<IBase> & service,const std::string & name)83 bool ClientCounterCallback::addRegisteredService(const sp<IBase>& service,
84                                                  const std::string& name) {
85     bool success = registerService(service, name);
86 
87     if (success) {
88         mRegisteredServices.push_back({service, name});
89     }
90 
91     return success;
92 }
93 
assertRegisteredService(const sp<IBase> & service)94 ClientCounterCallback::Service& ClientCounterCallback::assertRegisteredService(
95         const sp<IBase>& service) {
96     for (Service& registered : mRegisteredServices) {
97         if (registered.service != service) continue;
98         return registered;
99     }
100     LOG(FATAL) << "Got callback on service " << getDescriptor(service.get())
101                << " which we did not register.";
102     __builtin_unreachable();
103 }
104 
registerService(const sp<IBase> & service,const std::string & name)105 bool ClientCounterCallback::registerService(const sp<IBase>& service, const std::string& name) {
106     auto manager = hardware::defaultServiceManager1_2();
107 
108     const std::string descriptor = getDescriptor(service.get());
109 
110     LOG(INFO) << "Registering HAL: " << descriptor << " with name: " << name;
111 
112     status_t res = android::hardware::details::registerAsServiceInternal(service, name);
113     if (res != android::OK) {
114         LOG(ERROR) << "Failed to register as service.";
115         return false;
116     }
117 
118     bool ret = manager->registerClientCallback(getDescriptor(service.get()), name, service, this);
119     if (!ret) {
120         LOG(ERROR) << "Failed to add client callback.";
121         return false;
122     }
123 
124     return true;
125 }
126 
127 /**
128  * onClients is oneway, so no need to worry about multi-threading. Note that this means multiple
129  * invocations could occur on different threads however.
130  */
onClients(const sp<::android::hidl::base::V1_0::IBase> & service,bool clients)131 Return<void> ClientCounterCallback::onClients(const sp<::android::hidl::base::V1_0::IBase>& service,
132                                               bool clients) {
133     Service& registered = assertRegisteredService(service);
134     if (registered.clients == clients) {
135         LOG(FATAL) << "Process already thought " << getDescriptor(service.get()) << "/"
136                    << registered.name << " had clients: " << registered.clients
137                    << " but hwservicemanager has notified has clients: " << clients;
138     }
139     registered.clients = clients;
140 
141     size_t numWithClients = 0;
142     for (const Service& registered : mRegisteredServices) {
143         if (registered.clients) numWithClients++;
144     }
145 
146     LOG(INFO) << "Process has " << numWithClients << " (of " << mRegisteredServices.size()
147               << " available) client(s) in use after notification " << getDescriptor(service.get())
148               << "/" << registered.name << " has clients: " << clients;
149 
150     if (numWithClients == 0) {
151         tryShutdown();
152     }
153 
154     return Status::ok();
155 }
156 
tryShutdown()157 void ClientCounterCallback::tryShutdown() {
158     LOG(INFO) << "Trying to exit HAL. No clients in use for any service in process.";
159 
160     auto manager = hardware::defaultServiceManager1_2();
161 
162     auto unRegisterIt = mRegisteredServices.begin();
163     for (; unRegisterIt != mRegisteredServices.end(); ++unRegisterIt) {
164         auto& entry = (*unRegisterIt);
165 
166         const std::string descriptor = getDescriptor(entry.service.get());
167         bool success = manager->tryUnregister(descriptor, entry.name, entry.service);
168 
169         if (!success) {
170             LOG(INFO) << "Failed to unregister HAL " << descriptor << "/" << entry.name;
171             break;
172         }
173     }
174 
175     if (unRegisterIt == mRegisteredServices.end()) {
176         LOG(INFO) << "Unregistered all clients and exiting";
177         exit(EXIT_SUCCESS);
178     }
179 
180     for (auto reRegisterIt = mRegisteredServices.begin(); reRegisterIt != unRegisterIt;
181          reRegisterIt++) {
182         auto& entry = (*reRegisterIt);
183 
184         // re-register entry
185         if (!registerService(entry.service, entry.name)) {
186             // Must restart. Otherwise, clients will never be able to get ahold of this service.
187             LOG(FATAL) << "Bad state: could not re-register " << getDescriptor(entry.service.get());
188         }
189     }
190 }
191 
registerService(const sp<::android::hidl::base::V1_0::IBase> & service,const std::string & name)192 status_t LazyServiceRegistrarImpl::registerService(
193     const sp<::android::hidl::base::V1_0::IBase>& service, const std::string& name) {
194     if (!mClientCallback->addRegisteredService(service, name)) {
195         return ::android::UNKNOWN_ERROR;
196     }
197 
198     return ::android::OK;
199 }
200 
201 }  // namespace details
202 
LazyServiceRegistrar()203 LazyServiceRegistrar::LazyServiceRegistrar() {
204     mImpl = std::make_shared<details::LazyServiceRegistrarImpl>();
205 }
206 
getInstance()207 LazyServiceRegistrar& LazyServiceRegistrar::getInstance() {
208     static auto registrarInstance = new LazyServiceRegistrar();
209     return *registrarInstance;
210 }
211 
registerService(const sp<::android::hidl::base::V1_0::IBase> & service,const std::string & name)212 status_t LazyServiceRegistrar::registerService(
213     const sp<::android::hidl::base::V1_0::IBase>& service, const std::string& name) {
214     return mImpl->registerService(service, name);
215 }
216 
217 }  // namespace hardware
218 }  // namespace android
219