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