1 /*
2  * Copyright (C) 2019 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 "AidlLazyServiceRegistrar"
18 
19 #include <binder/LazyServiceRegistrar.h>
20 #include <binder/IPCThreadState.h>
21 #include <binder/IServiceManager.h>
22 #include <android/os/BnClientCallback.h>
23 #include <android/os/IServiceManager.h>
24 #include <utils/Log.h>
25 
26 namespace android {
27 namespace binder {
28 namespace internal {
29 
30 using AidlServiceManager = android::os::IServiceManager;
31 
32 class ClientCounterCallback : public ::android::os::BnClientCallback {
33 public:
ClientCounterCallback()34     ClientCounterCallback() : mNumConnectedServices(0), mForcePersist(false) {}
35 
36     bool registerService(const sp<IBinder>& service, const std::string& name,
37                          bool allowIsolated, int dumpFlags);
38 
39     /**
40      * Set a flag to prevent services from automatically shutting down
41      */
42     void forcePersist(bool persist);
43 
44 protected:
45     Status onClients(const sp<IBinder>& service, bool clients) override;
46 
47 private:
48     /**
49      * Unregisters all services that we can. If we can't unregister all, re-register other
50      * services.
51      */
52     void tryShutdown();
53 
54     /**
55      * Counter of the number of services that currently have at least one client.
56      */
57     size_t mNumConnectedServices;
58 
59     struct Service {
60         sp<IBinder> service;
61         bool allowIsolated;
62         int dumpFlags;
63     };
64     /**
65      * Map of registered names and services
66      */
67     std::map<std::string, Service> mRegisteredServices;
68 
69     bool mForcePersist;
70 };
71 
registerService(const sp<IBinder> & service,const std::string & name,bool allowIsolated,int dumpFlags)72 bool ClientCounterCallback::registerService(const sp<IBinder>& service, const std::string& name,
73                                             bool allowIsolated, int dumpFlags) {
74     auto manager = interface_cast<AidlServiceManager>(asBinder(defaultServiceManager()));
75 
76     bool reRegister = mRegisteredServices.count(name) > 0;
77     std::string regStr = (reRegister) ? "Re-registering" : "Registering";
78     ALOGI("%s service %s", regStr.c_str(), name.c_str());
79 
80     if (!manager->addService(name.c_str(), service, allowIsolated, dumpFlags).isOk()) {
81         ALOGE("Failed to register service %s", name.c_str());
82         return false;
83     }
84 
85     if (!reRegister) {
86         if (!manager->registerClientCallback(name, service, this).isOk()) {
87             ALOGE("Failed to add client callback for service %s", name.c_str());
88             return false;
89         }
90 
91         // Only add this when a service is added for the first time, as it is not removed
92         mRegisteredServices[name] = {service, allowIsolated, dumpFlags};
93     }
94 
95     return true;
96 }
97 
forcePersist(bool persist)98 void ClientCounterCallback::forcePersist(bool persist) {
99     mForcePersist = persist;
100     if(!mForcePersist) {
101         // Attempt a shutdown in case the number of clients hit 0 while the flag was on
102         tryShutdown();
103     }
104 }
105 
106 /**
107  * onClients is oneway, so no need to worry about multi-threading. Note that this means multiple
108  * invocations could occur on different threads however.
109  */
onClients(const sp<IBinder> & service,bool clients)110 Status ClientCounterCallback::onClients(const sp<IBinder>& service, bool clients) {
111     if (clients) {
112         mNumConnectedServices++;
113     } else {
114         mNumConnectedServices--;
115     }
116 
117     ALOGI("Process has %zu (of %zu available) client(s) in use after notification %s has clients: %d",
118           mNumConnectedServices, mRegisteredServices.size(),
119           String8(service->getInterfaceDescriptor()).string(), clients);
120 
121     tryShutdown();
122     return Status::ok();
123 }
124 
tryShutdown()125 void ClientCounterCallback::tryShutdown() {
126     if(mNumConnectedServices > 0) {
127         // Should only shut down if there are no clients
128         return;
129     }
130 
131     if(mForcePersist) {
132         ALOGI("Shutdown prevented by forcePersist override flag.");
133         return;
134     }
135 
136     ALOGI("Trying to shut down the service. No clients in use for any service in process.");
137 
138     auto manager = interface_cast<AidlServiceManager>(asBinder(defaultServiceManager()));
139 
140     auto unRegisterIt = mRegisteredServices.begin();
141     for (; unRegisterIt != mRegisteredServices.end(); ++unRegisterIt) {
142         auto& entry = (*unRegisterIt);
143 
144         bool success = manager->tryUnregisterService(entry.first, entry.second.service).isOk();
145 
146 
147         if (!success) {
148             ALOGI("Failed to unregister service %s", entry.first.c_str());
149             break;
150         }
151     }
152 
153     if (unRegisterIt == mRegisteredServices.end()) {
154         ALOGI("Unregistered all clients and exiting");
155         exit(EXIT_SUCCESS);
156     }
157 
158     for (auto reRegisterIt = mRegisteredServices.begin(); reRegisterIt != unRegisterIt;
159          reRegisterIt++) {
160         auto& entry = (*reRegisterIt);
161 
162         // re-register entry
163         if (!registerService(entry.second.service, entry.first, entry.second.allowIsolated,
164                              entry.second.dumpFlags)) {
165             // Must restart. Otherwise, clients will never be able to get a hold of this service.
166             ALOGE("Bad state: could not re-register services");
167         }
168     }
169 }
170 
171 }  // namespace internal
172 
LazyServiceRegistrar()173 LazyServiceRegistrar::LazyServiceRegistrar() {
174     mClientCC = std::make_shared<internal::ClientCounterCallback>();
175 }
176 
getInstance()177 LazyServiceRegistrar& LazyServiceRegistrar::getInstance() {
178     static auto registrarInstance = new LazyServiceRegistrar();
179     return *registrarInstance;
180 }
181 
registerService(const sp<IBinder> & service,const std::string & name,bool allowIsolated,int dumpFlags)182 status_t LazyServiceRegistrar::registerService(const sp<IBinder>& service, const std::string& name,
183                                                bool allowIsolated, int dumpFlags) {
184     if (!mClientCC->registerService(service, name, allowIsolated, dumpFlags)) {
185         return UNKNOWN_ERROR;
186     }
187     return OK;
188 }
189 
forcePersist(bool persist)190 void LazyServiceRegistrar::forcePersist(bool persist) {
191     mClientCC->forcePersist(persist);
192 }
193 
194 }  // namespace hardware
195 }  // namespace android