1 /*
2  * Copyright (C) 2016 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 "hwservicemanager"
18 
19 #include "ServiceManager.h"
20 #include "Vintf.h"
21 
22 #include <android-base/logging.h>
23 #include <android-base/properties.h>
24 #include <hwbinder/IPCThreadState.h>
25 #include <hidl/HidlSupport.h>
26 #include <hidl/HidlTransportSupport.h>
27 #include <regex>
28 #include <sstream>
29 #include <thread>
30 
31 using android::hardware::IPCThreadState;
32 using ::android::hardware::interfacesEqual;
33 
34 namespace android {
35 namespace hidl {
36 namespace manager {
37 namespace implementation {
38 
getBinderCallingContext()39 AccessControl::CallingContext getBinderCallingContext() {
40     const auto& self = IPCThreadState::self();
41 
42     pid_t pid = self->getCallingPid();
43     const char* sid = self->getCallingSid();
44 
45     if (sid == nullptr) {
46         if (pid != getpid()) {
47             android_errorWriteLog(0x534e4554, "121035042");
48         }
49 
50         return AccessControl::getCallingContext(pid);
51     } else {
52         return { true, sid, pid };
53     }
54 }
55 
56 static constexpr uint64_t kServiceDiedCookie = 0;
57 static constexpr uint64_t kPackageListenerDiedCookie = 1;
58 static constexpr uint64_t kServiceListenerDiedCookie = 2;
59 static constexpr uint64_t kClientCallbackDiedCookie = 3;
60 
countExistingService() const61 size_t ServiceManager::countExistingService() const {
62     size_t total = 0;
63     forEachExistingService([&] (const HidlService *) {
64         ++total;
65         return true;  // continue
66     });
67     return total;
68 }
69 
forEachExistingService(std::function<bool (const HidlService *)> f) const70 void ServiceManager::forEachExistingService(std::function<bool(const HidlService *)> f) const {
71     forEachServiceEntry([&] (const HidlService *service) {
72         if (service->getService() == nullptr) {
73             return true;  // continue
74         }
75         return f(service);
76     });
77 }
78 
forEachExistingService(std::function<bool (HidlService *)> f)79 void ServiceManager::forEachExistingService(std::function<bool(HidlService *)> f) {
80     forEachServiceEntry([&] (HidlService *service) {
81         if (service->getService() == nullptr) {
82             return true;  // continue
83         }
84         return f(service);
85     });
86 }
87 
forEachServiceEntry(std::function<bool (const HidlService *)> f) const88 void ServiceManager::forEachServiceEntry(std::function<bool(const HidlService *)> f) const {
89     for (const auto& interfaceMapping : mServiceMap) {
90         const auto& instanceMap = interfaceMapping.second.getInstanceMap();
91 
92         for (const auto& instanceMapping : instanceMap) {
93             if (!f(instanceMapping.second.get())) {
94                 return;
95             }
96         }
97     }
98 }
99 
forEachServiceEntry(std::function<bool (HidlService *)> f)100 void ServiceManager::forEachServiceEntry(std::function<bool(HidlService *)> f) {
101     for (auto& interfaceMapping : mServiceMap) {
102         auto& instanceMap = interfaceMapping.second.getInstanceMap();
103 
104         for (auto& instanceMapping : instanceMap) {
105             if (!f(instanceMapping.second.get())) {
106                 return;
107             }
108         }
109     }
110 }
111 
lookup(const std::string & fqName,const std::string & name)112 HidlService* ServiceManager::lookup(const std::string& fqName, const std::string& name) {
113     auto ifaceIt = mServiceMap.find(fqName);
114     if (ifaceIt == mServiceMap.end()) {
115         return nullptr;
116     }
117 
118     PackageInterfaceMap &ifaceMap = ifaceIt->second;
119 
120     HidlService *hidlService = ifaceMap.lookup(name);
121 
122     return hidlService;
123 }
124 
serviceDied(uint64_t cookie,const wp<IBase> & who)125 void ServiceManager::serviceDied(uint64_t cookie, const wp<IBase>& who) {
126     bool serviceRemoved = false;
127     switch (cookie) {
128         case kServiceDiedCookie:
129             serviceRemoved = removeService(who, nullptr /* restrictToInstanceName */);
130             break;
131         case kPackageListenerDiedCookie:
132             serviceRemoved = removePackageListener(who);
133             break;
134         case kServiceListenerDiedCookie:
135             serviceRemoved = removeServiceListener(who);
136             break;
137         case kClientCallbackDiedCookie: {
138             sp<IBase> base = who.promote();
139             IClientCallback* callback = static_cast<IClientCallback*>(base.get());
140             serviceRemoved = unregisterClientCallback(nullptr /*service*/,
141                                                       sp<IClientCallback>(callback));
142         } break;
143     }
144 
145     if (!serviceRemoved) {
146         LOG(ERROR) << "Received death notification but interface instance not removed. Cookie: "
147                    << cookie << " Service pointer: " << who.promote().get();
148     }
149 }
150 
getInstanceMap()151 ServiceManager::InstanceMap &ServiceManager::PackageInterfaceMap::getInstanceMap() {
152     return mInstanceMap;
153 }
154 
getInstanceMap() const155 const ServiceManager::InstanceMap &ServiceManager::PackageInterfaceMap::getInstanceMap() const {
156     return mInstanceMap;
157 }
158 
lookup(const std::string & name) const159 const HidlService *ServiceManager::PackageInterfaceMap::lookup(
160         const std::string &name) const {
161     auto it = mInstanceMap.find(name);
162 
163     if (it == mInstanceMap.end()) {
164         return nullptr;
165     }
166 
167     return it->second.get();
168 }
169 
lookup(const std::string & name)170 HidlService *ServiceManager::PackageInterfaceMap::lookup(
171         const std::string &name) {
172 
173     return const_cast<HidlService*>(
174         const_cast<const PackageInterfaceMap*>(this)->lookup(name));
175 }
176 
insertService(std::unique_ptr<HidlService> && service)177 void ServiceManager::PackageInterfaceMap::insertService(
178         std::unique_ptr<HidlService> &&service) {
179     mInstanceMap.insert({service->getInstanceName(), std::move(service)});
180 }
181 
sendPackageRegistrationNotification(const hidl_string & fqName,const hidl_string & instanceName)182 void ServiceManager::PackageInterfaceMap::sendPackageRegistrationNotification(
183         const hidl_string &fqName,
184         const hidl_string &instanceName) {
185 
186     for (auto it = mPackageListeners.begin(); it != mPackageListeners.end();) {
187         auto ret = (*it)->onRegistration(fqName, instanceName, false /* preexisting */);
188         if (ret.isOk()) {
189             ++it;
190         } else {
191             LOG(ERROR) << "Dropping registration callback for " << fqName << "/" << instanceName
192                        << ": transport error.";
193             it = mPackageListeners.erase(it);
194         }
195     }
196 }
197 
addPackageListener(sp<IServiceNotification> listener)198 void ServiceManager::PackageInterfaceMap::addPackageListener(sp<IServiceNotification> listener) {
199     for (const auto &instanceMapping : mInstanceMap) {
200         const std::unique_ptr<HidlService> &service = instanceMapping.second;
201 
202         if (service->getService() == nullptr) {
203             continue;
204         }
205 
206         auto ret = listener->onRegistration(
207             service->getInterfaceName(),
208             service->getInstanceName(),
209             true /* preexisting */);
210         if (!ret.isOk()) {
211             LOG(ERROR) << "Not adding package listener for " << service->getInterfaceName()
212                        << "/" << service->getInstanceName() << ": transport error "
213                        << "when sending notification for already registered instance.";
214             return;
215         }
216     }
217     mPackageListeners.push_back(listener);
218 }
219 
removePackageListener(const wp<IBase> & who)220 bool ServiceManager::PackageInterfaceMap::removePackageListener(const wp<IBase>& who) {
221     bool found = false;
222 
223     for (auto it = mPackageListeners.begin(); it != mPackageListeners.end();) {
224         if (interfacesEqual(*it, who.promote())) {
225             it = mPackageListeners.erase(it);
226             found = true;
227         } else {
228             ++it;
229         }
230     }
231 
232     return found;
233 }
234 
removeServiceListener(const wp<IBase> & who)235 bool ServiceManager::PackageInterfaceMap::removeServiceListener(const wp<IBase>& who) {
236     bool found = false;
237 
238     for (auto &servicePair : getInstanceMap()) {
239         const std::unique_ptr<HidlService> &service = servicePair.second;
240         found |= service->removeListener(who);
241     }
242 
243     return found;
244 }
245 
tryStartService(const std::string & fqName,const std::string & name)246 static void tryStartService(const std::string& fqName, const std::string& name) {
247     using ::android::base::SetProperty;
248 
249     // The "happy path" here is starting up a service that is configured as a
250     // lazy HAL, but we aren't sure that is the case. If the service doesn't
251     // have an 'interface' entry in its .rc file OR if the service is already
252     // running, then this will be a no-op. So, for instance, if a service is
253     // deadlocked during startup, you will see this message repeatedly.
254     LOG(INFO) << "Since " << fqName << "/" << name
255               << " is not registered, trying to start it as a lazy HAL.";
256 
257     std::thread([=] {
258         (void)SetProperty("ctl.interface_start", fqName + "/" + name);
259     }).detach();
260 }
261 
262 // Methods from ::android::hidl::manager::V1_0::IServiceManager follow.
get(const hidl_string & hidlFqName,const hidl_string & hidlName)263 Return<sp<IBase>> ServiceManager::get(const hidl_string& hidlFqName,
264                                       const hidl_string& hidlName) {
265     const std::string fqName = hidlFqName;
266     const std::string name = hidlName;
267 
268     if (!mAcl.canGet(fqName, getBinderCallingContext())) {
269         return nullptr;
270     }
271 
272     HidlService* hidlService = lookup(fqName, name);
273     if (hidlService == nullptr) {
274         tryStartService(fqName, name);
275         return nullptr;
276     }
277 
278     sp<IBase> service = hidlService->getService();
279     if (service == nullptr) {
280         tryStartService(fqName, name);
281         return nullptr;
282     }
283 
284     // Let HidlService know that we handed out a client. If the client drops the service before the
285     // next time handleClientCallbacks is called, it will still know that the service had been handed out.
286     hidlService->guaranteeClient();
287     forEachExistingService([&] (HidlService *otherService) {
288         if (otherService != hidlService && interfacesEqual(service, otherService->getService())) {
289             otherService->guaranteeClient();
290         }
291         return true;
292     });
293 
294     // This is executed immediately after the binder driver confirms the transaction. The driver
295     // will update the appropriate data structures to reflect the fact that the client now has the
296     // service this function is returning. Nothing else can update the HidlService at the same
297     // time. This will run before anything else can modify the HidlService which is owned by this
298     // object, so it will be in the same state that it was when this function returns.
299     hardware::addPostCommandTask([hidlService] {
300         hidlService->handleClientCallbacks(false /* isCalledOnInterval */, 1 /*knownClientCount*/);
301     });
302 
303     return service;
304 }
305 
add(const hidl_string & name,const sp<IBase> & service)306 Return<bool> ServiceManager::add(const hidl_string& name, const sp<IBase>& service) {
307     bool addSuccess = false;
308 
309     if (service == nullptr) {
310         return false;
311     }
312 
313     auto pidcon = getBinderCallingContext();
314 
315     auto ret = service->interfaceChain([&](const auto &interfaceChain) {
316         addSuccess = addImpl(name, service, interfaceChain, pidcon);
317     });
318 
319     if (!ret.isOk()) {
320         LOG(ERROR) << "Failed to retrieve interface chain: " << ret.description();
321         return false;
322     }
323 
324     return addSuccess;
325 }
326 
addImpl(const std::string & name,const sp<IBase> & service,const hidl_vec<hidl_string> & interfaceChain,const AccessControl::CallingContext & callingContext)327 bool ServiceManager::addImpl(const std::string& name,
328                              const sp<IBase>& service,
329                              const hidl_vec<hidl_string>& interfaceChain,
330                              const AccessControl::CallingContext& callingContext) {
331     if (interfaceChain.size() == 0) {
332         LOG(WARNING) << "Empty interface chain for " << name;
333         return false;
334     }
335 
336     // First, verify you're allowed to add() the whole interface hierarchy
337     for(size_t i = 0; i < interfaceChain.size(); i++) {
338         const std::string fqName = interfaceChain[i];
339 
340         if (!mAcl.canAdd(fqName, callingContext)) {
341             return false;
342         }
343     }
344 
345     // Detect duplicate registration
346     if (interfaceChain.size() > 1) {
347         // second to last entry should be the highest base class other than IBase.
348         const std::string baseFqName = interfaceChain[interfaceChain.size() - 2];
349         const HidlService *hidlService = lookup(baseFqName, name);
350         if (hidlService != nullptr && hidlService->getService() != nullptr) {
351             // This shouldn't occur during normal operation. Here are some cases where
352             // it might get hit:
353             // - bad configuration (service installed on device multiple times)
354             // - race between death notification and a new service being registered
355             //     (previous logs should indicate a separate problem)
356             const std::string childFqName = interfaceChain[0];
357             pid_t newServicePid = IPCThreadState::self()->getCallingPid();
358             pid_t oldServicePid = hidlService->getDebugPid();
359             LOG(WARNING) << "Detected instance of " << childFqName << " (pid: " << newServicePid
360                     << ") registering over instance of or with base of " << baseFqName << " (pid: "
361                     << oldServicePid << ").";
362         }
363     }
364 
365     // Unregister superclass if subclass is registered over it
366     {
367         // For IBar extends IFoo if IFoo/default is being registered, remove
368         // IBar/default. This makes sure the following two things are equivalent
369         // 1). IBar::castFrom(IFoo::getService(X))
370         // 2). IBar::getService(X)
371         // assuming that IBar is declared in the device manifest and there
372         // is also not an IBaz extends IFoo and there is no race.
373         const std::string childFqName = interfaceChain[0];
374         const HidlService *hidlService = lookup(childFqName, name);
375         if (hidlService != nullptr) {
376             const sp<IBase> remove = hidlService->getService();
377 
378             if (remove != nullptr) {
379                 const std::string instanceName = name;
380                 removeService(remove, &instanceName /* restrictToInstanceName */);
381             }
382         }
383     }
384 
385     for(size_t i = 0; i < interfaceChain.size(); i++) {
386         const std::string fqName = interfaceChain[i];
387 
388         PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
389         HidlService *hidlService = ifaceMap.lookup(name);
390 
391         if (hidlService == nullptr) {
392             ifaceMap.insertService(
393                 std::make_unique<HidlService>(fqName, name, service, callingContext.pid));
394         } else {
395             hidlService->setService(service, callingContext.pid);
396         }
397 
398         ifaceMap.sendPackageRegistrationNotification(fqName, name);
399     }
400 
401     bool linkRet = service->linkToDeath(this, kServiceDiedCookie).withDefault(false);
402     if (!linkRet) {
403         LOG(ERROR) << "Could not link to death for " << interfaceChain[0] << "/" << name;
404     }
405 
406     return true;
407 }
408 
getTransport(const hidl_string & fqName,const hidl_string & name)409 Return<ServiceManager::Transport> ServiceManager::getTransport(const hidl_string& fqName,
410                                                                const hidl_string& name) {
411     using ::android::hardware::getTransport;
412 
413     if (!mAcl.canGet(fqName, getBinderCallingContext())) {
414         return Transport::EMPTY;
415     }
416 
417     switch (getTransport(fqName, name)) {
418         case vintf::Transport::HWBINDER:
419              return Transport::HWBINDER;
420         case vintf::Transport::PASSTHROUGH:
421              return Transport::PASSTHROUGH;
422         case vintf::Transport::EMPTY:
423         default:
424              return Transport::EMPTY;
425     }
426 }
427 
list(list_cb _hidl_cb)428 Return<void> ServiceManager::list(list_cb _hidl_cb) {
429     if (!mAcl.canList(getBinderCallingContext())) {
430         _hidl_cb({});
431         return Void();
432     }
433 
434     hidl_vec<hidl_string> list;
435 
436     list.resize(countExistingService());
437 
438     size_t idx = 0;
439     forEachExistingService([&] (const HidlService *service) {
440         list[idx++] = service->string();
441         return true;  // continue
442     });
443 
444     _hidl_cb(list);
445     return Void();
446 }
447 
listByInterface(const hidl_string & fqName,listByInterface_cb _hidl_cb)448 Return<void> ServiceManager::listByInterface(const hidl_string& fqName,
449                                              listByInterface_cb _hidl_cb) {
450     if (!mAcl.canGet(fqName, getBinderCallingContext())) {
451         _hidl_cb({});
452         return Void();
453     }
454 
455     auto ifaceIt = mServiceMap.find(fqName);
456     if (ifaceIt == mServiceMap.end()) {
457         _hidl_cb(hidl_vec<hidl_string>());
458         return Void();
459     }
460 
461     const auto &instanceMap = ifaceIt->second.getInstanceMap();
462 
463     hidl_vec<hidl_string> list;
464 
465     size_t total = 0;
466     for (const auto &serviceMapping : instanceMap) {
467         const std::unique_ptr<HidlService> &service = serviceMapping.second;
468         if (service->getService() == nullptr) continue;
469 
470         ++total;
471     }
472     list.resize(total);
473 
474     size_t idx = 0;
475     for (const auto &serviceMapping : instanceMap) {
476         const std::unique_ptr<HidlService> &service = serviceMapping.second;
477         if (service->getService() == nullptr) continue;
478 
479         list[idx++] = service->getInstanceName();
480     }
481 
482     _hidl_cb(list);
483     return Void();
484 }
485 
registerForNotifications(const hidl_string & fqName,const hidl_string & name,const sp<IServiceNotification> & callback)486 Return<bool> ServiceManager::registerForNotifications(const hidl_string& fqName,
487                                                       const hidl_string& name,
488                                                       const sp<IServiceNotification>& callback) {
489     if (callback == nullptr) {
490         return false;
491     }
492 
493     if (!mAcl.canGet(fqName, getBinderCallingContext())) {
494         return false;
495     }
496 
497     PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
498 
499     if (name.empty()) {
500         bool ret = callback->linkToDeath(this, kPackageListenerDiedCookie).withDefault(false);
501         if (!ret) {
502             LOG(ERROR) << "Failed to register death recipient for " << fqName << "/" << name;
503             return false;
504         }
505         ifaceMap.addPackageListener(callback);
506         return true;
507     }
508 
509     HidlService *service = ifaceMap.lookup(name);
510 
511     bool ret = callback->linkToDeath(this, kServiceListenerDiedCookie).withDefault(false);
512     if (!ret) {
513         LOG(ERROR) << "Failed to register death recipient for " << fqName << "/" << name;
514         return false;
515     }
516 
517     if (service == nullptr) {
518         auto adding = std::make_unique<HidlService>(fqName, name);
519         adding->addListener(callback);
520         ifaceMap.insertService(std::move(adding));
521     } else {
522         service->addListener(callback);
523     }
524 
525     return true;
526 }
527 
unregisterForNotifications(const hidl_string & fqName,const hidl_string & name,const sp<IServiceNotification> & callback)528 Return<bool> ServiceManager::unregisterForNotifications(const hidl_string& fqName,
529                                                         const hidl_string& name,
530                                                         const sp<IServiceNotification>& callback) {
531     if (callback == nullptr) {
532         LOG(ERROR) << "Cannot unregister null callback for " << fqName << "/" << name;
533         return false;
534     }
535 
536     // NOTE: don't need ACL since callback is binder token, and if someone has gotten it,
537     // then they already have access to it.
538 
539     if (fqName.empty()) {
540         bool success = false;
541         success |= removePackageListener(callback);
542         success |= removeServiceListener(callback);
543         return success;
544     }
545 
546     PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
547 
548     if (name.empty()) {
549         bool success = false;
550         success |= ifaceMap.removePackageListener(callback);
551         success |= ifaceMap.removeServiceListener(callback);
552         return success;
553     }
554 
555     HidlService *service = ifaceMap.lookup(name);
556 
557     if (service == nullptr) {
558         return false;
559     }
560 
561     return service->removeListener(callback);
562 }
563 
registerClientCallback(const hidl_string & hidlFqName,const hidl_string & hidlName,const sp<IBase> & server,const sp<IClientCallback> & cb)564 Return<bool> ServiceManager::registerClientCallback(const hidl_string& hidlFqName,
565                                                     const hidl_string& hidlName,
566                                                     const sp<IBase>& server,
567                                                     const sp<IClientCallback>& cb) {
568     if (server == nullptr || cb == nullptr) return false;
569 
570     const std::string fqName = hidlFqName;
571     const std::string name = hidlName;
572 
573     // only the server of the interface can register a client callback
574     pid_t pid = IPCThreadState::self()->getCallingPid();
575     if (!mAcl.canAdd(fqName, getBinderCallingContext())) {
576         return false;
577     }
578 
579     HidlService* registered = lookup(fqName, name);
580 
581     if (registered == nullptr) {
582         return false;
583     }
584 
585     // sanity
586     if (registered->getDebugPid() != pid) {
587         LOG(WARNING) << "Only a server can register for client callbacks (for " << fqName
588             << "/" << name << ")";
589         return false;
590     }
591 
592     sp<IBase> service = registered->getService();
593 
594     if (!interfacesEqual(service, server)) {
595         LOG(WARNING) << "Tried to register client callback for " << fqName << "/" << name
596             << " but a different service is registered under this name.";
597         return false;
598     }
599 
600     bool linkRet = cb->linkToDeath(this, kClientCallbackDiedCookie).withDefault(false);
601     if (!linkRet) {
602         LOG(ERROR) << "Could not link to death for registerClientCallback";
603         return false;
604     }
605 
606     // knownClientCount
607     // - one from binder transaction (base here)
608     // - one from hwservicemanager
609     registered->addClientCallback(cb, 2 /*knownClientCount*/);
610 
611     return true;
612 }
613 
unregisterClientCallback(const sp<IBase> & server,const sp<IClientCallback> & cb)614 Return<bool> ServiceManager::unregisterClientCallback(const sp<IBase>& server,
615                                                       const sp<IClientCallback>& cb) {
616     if (cb == nullptr) return false;
617 
618     bool removed = false;
619 
620     forEachExistingService([&] (HidlService *service) {
621         if (server == nullptr || interfacesEqual(service->getService(), server)) {
622             removed |= service->removeClientCallback(cb);
623         }
624         return true;  // continue
625     });
626 
627     return removed;
628 }
629 
handleClientCallbacks()630 void ServiceManager::handleClientCallbacks() {
631     forEachServiceEntry([&] (HidlService *service) {
632         // hwservicemanager will hold one reference, so knownClientCount is 1.
633         service->handleClientCallbacks(true /* isCalledOnInterval */, 1 /*knownClientCount*/);
634         return true;  // continue
635     });
636 }
637 
addWithChain(const hidl_string & name,const sp<IBase> & service,const hidl_vec<hidl_string> & chain)638 Return<bool> ServiceManager::addWithChain(const hidl_string& name,
639                                           const sp<IBase>& service,
640                                           const hidl_vec<hidl_string>& chain) {
641     if (service == nullptr) {
642         return false;
643     }
644 
645     auto callingContext = getBinderCallingContext();
646 
647     return addImpl(name, service, chain, callingContext);
648 }
649 
listManifestByInterface(const hidl_string & fqName,listManifestByInterface_cb _hidl_cb)650 Return<void> ServiceManager::listManifestByInterface(const hidl_string& fqName,
651                                                      listManifestByInterface_cb _hidl_cb) {
652     if (!mAcl.canGet(fqName, getBinderCallingContext())) {
653         _hidl_cb({});
654         return Void();
655     }
656 
657     std::set<std::string> instances = getInstances(fqName);
658     hidl_vec<hidl_string> ret(instances.begin(), instances.end());
659 
660     _hidl_cb(ret);
661     return Void();
662 }
663 
tryUnregister(const hidl_string & hidlFqName,const hidl_string & hidlName,const sp<IBase> & service)664 Return<bool> ServiceManager::tryUnregister(const hidl_string& hidlFqName,
665                                            const hidl_string& hidlName,
666                                            const sp<IBase>& service) {
667     const std::string fqName = hidlFqName;
668     const std::string name = hidlName;
669 
670     if (service == nullptr) {
671         return false;
672     }
673 
674     if (!mAcl.canAdd(fqName, getBinderCallingContext())) {
675         return false;
676     }
677 
678     HidlService* registered = lookup(fqName, name);
679 
680     // sanity
681     pid_t pid = IPCThreadState::self()->getCallingPid();
682     if (registered->getDebugPid() != pid) {
683         LOG(WARNING) << "Only a server can unregister itself (for " << fqName
684             << "/" << name << ")";
685         return false;
686     }
687 
688     sp<IBase> server = registered->getService();
689 
690     if (!interfacesEqual(service, server)) {
691         LOG(WARNING) << "Tried to unregister for " << fqName << "/" << name
692             << " but a different service is registered under this name.";
693         return false;
694     }
695 
696     // knownClientCount
697     // - one from binder transaction (base here)
698     // - one from hwservicemanager
699     bool clients = registered->forceHandleClientCallbacks(false /*isCalledOnInterval*/, 2 /*knownClientCount*/);
700 
701     if (clients) {
702         // client callbacks are either disabled or there are other clients
703         LOG(INFO) << "Tried to unregister for " << fqName << "/" << name
704             << " but there are clients: " << clients;
705         return false;
706     }
707 
708     // will remove entire parent hierarchy
709     bool success = removeService(service, &name /*restrictToInstanceName*/);
710 
711     if (registered->getService() != nullptr) {
712         LOG(ERROR) << "Bad state. Unregistration failed for " << fqName << "/" << name << ".";
713         return false;
714     }
715 
716     return success;
717 }
718 
debugDump(debugDump_cb _cb)719 Return<void> ServiceManager::debugDump(debugDump_cb _cb) {
720     if (!mAcl.canList(getBinderCallingContext())) {
721         _cb({});
722         return Void();
723     }
724 
725     std::vector<IServiceManager::InstanceDebugInfo> list;
726     forEachServiceEntry([&] (const HidlService *service) {
727         hidl_vec<int32_t> clientPids;
728         clientPids.resize(service->getPassthroughClients().size());
729 
730         size_t i = 0;
731         for (pid_t p : service->getPassthroughClients()) {
732             clientPids[i++] = p;
733         }
734 
735         list.push_back({
736             .interfaceName = service->getInterfaceName(),
737             .instanceName = service->getInstanceName(),
738             .pid = service->getDebugPid(),
739             .clientPids = clientPids,
740             .arch = ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN
741         });
742 
743         return true;  // continue
744     });
745 
746     _cb(list);
747     return Void();
748 }
749 
750 
registerPassthroughClient(const hidl_string & fqName,const hidl_string & name)751 Return<void> ServiceManager::registerPassthroughClient(const hidl_string &fqName,
752         const hidl_string &name) {
753     auto callingContext = getBinderCallingContext();
754 
755     if (!mAcl.canGet(fqName, callingContext)) {
756         /* We guard this function with "get", because it's typically used in
757          * the getService() path, albeit for a passthrough service in this
758          * case
759          */
760         return Void();
761     }
762 
763     PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
764 
765     if (name.empty()) {
766         LOG(WARNING) << "registerPassthroughClient encounters empty instance name for "
767                      << fqName.c_str();
768         return Void();
769     }
770 
771     HidlService *service = ifaceMap.lookup(name);
772 
773     if (service == nullptr) {
774         auto adding = std::make_unique<HidlService>(fqName, name);
775         adding->registerPassthroughClient(callingContext.pid);
776         ifaceMap.insertService(std::move(adding));
777     } else {
778         service->registerPassthroughClient(callingContext.pid);
779     }
780     return Void();
781 }
782 
removeService(const wp<IBase> & who,const std::string * restrictToInstanceName)783 bool ServiceManager::removeService(const wp<IBase>& who, const std::string* restrictToInstanceName) {
784     bool keepInstance = false;
785     bool removed = false;
786     for (auto &interfaceMapping : mServiceMap) {
787         auto &instanceMap = interfaceMapping.second.getInstanceMap();
788 
789         for (auto &servicePair : instanceMap) {
790             const std::string &instanceName = servicePair.first;
791             const std::unique_ptr<HidlService> &service = servicePair.second;
792 
793             if (interfacesEqual(service->getService(), who.promote())) {
794                 if (restrictToInstanceName != nullptr && *restrictToInstanceName != instanceName) {
795                     // We cannot remove all instances of this service, so we don't return that it
796                     // has been entirely removed.
797                     keepInstance = true;
798                     continue;
799                 }
800 
801                 service->setService(nullptr, static_cast<pid_t>(IServiceManager::PidConstant::NO_PID));
802                 removed = true;
803             }
804         }
805     }
806 
807     return !keepInstance && removed;
808 }
809 
removePackageListener(const wp<IBase> & who)810 bool ServiceManager::removePackageListener(const wp<IBase>& who) {
811     bool found = false;
812 
813     for (auto &interfaceMapping : mServiceMap) {
814         found |= interfaceMapping.second.removePackageListener(who);
815     }
816 
817     return found;
818 }
819 
removeServiceListener(const wp<IBase> & who)820 bool ServiceManager::removeServiceListener(const wp<IBase>& who) {
821     bool found = false;
822     for (auto &interfaceMapping : mServiceMap) {
823         auto &packageInterfaceMap = interfaceMapping.second;
824 
825         found |= packageInterfaceMap.removeServiceListener(who);
826     }
827     return found;
828 }
829 }  // namespace implementation
830 }  // namespace manager
831 }  // namespace hidl
832 }  // namespace android
833