xref: /aosp_15_r20/frameworks/native/cmds/servicemanager/ServiceManager.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
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 #include "ServiceManager.h"
18 
19 #include <android-base/logging.h>
20 #include <android-base/properties.h>
21 #include <android-base/scopeguard.h>
22 #include <android-base/strings.h>
23 #include <binder/BpBinder.h>
24 #include <binder/IPCThreadState.h>
25 #include <binder/ProcessState.h>
26 #include <binder/Stability.h>
27 #include <cutils/android_filesystem_config.h>
28 #include <cutils/multiuser.h>
29 #include <thread>
30 
31 #if !defined(VENDORSERVICEMANAGER) && !defined(__ANDROID_RECOVERY__)
32 #include "perfetto/public/protos/trace/android/android_track_event.pzc.h"
33 #include "perfetto/public/te_category_macros.h"
34 #include "perfetto/public/te_macros.h"
35 #endif // !defined(VENDORSERVICEMANAGER) && !defined(__ANDROID_RECOVERY__)
36 
37 #ifndef VENDORSERVICEMANAGER
38 #include <vintf/VintfObject.h>
39 #ifdef __ANDROID_RECOVERY__
40 #include <vintf/VintfObjectRecovery.h>
41 #endif // __ANDROID_RECOVERY__
42 #include <vintf/constants.h>
43 #endif  // !VENDORSERVICEMANAGER
44 
45 #include "NameUtil.h"
46 
47 using ::android::binder::Status;
48 using ::android::internal::Stability;
49 
50 namespace android {
51 
52 #if defined(VENDORSERVICEMANAGER) || defined(__ANDROID_RECOVERY__)
53 #define SM_PERFETTO_TRACE_FUNC(...)
54 #else
55 
56 PERFETTO_TE_CATEGORIES_DEFINE(PERFETTO_SM_CATEGORIES);
57 
58 #define SM_PERFETTO_TRACE_FUNC(...) \
59     PERFETTO_TE_SCOPED(servicemanager, PERFETTO_TE_SLICE_BEGIN(__func__) __VA_OPT__(, ) __VA_ARGS__)
60 
61 constexpr uint32_t kProtoServiceName =
62         perfetto_protos_AndroidTrackEvent_binder_service_name_field_number;
63 constexpr uint32_t kProtoInterfaceName =
64         perfetto_protos_AndroidTrackEvent_binder_interface_name_field_number;
65 constexpr uint32_t kProtoApexName = perfetto_protos_AndroidTrackEvent_apex_name_field_number;
66 
67 #endif // !(defined(VENDORSERVICEMANAGER) || defined(__ANDROID_RECOVERY__))
68 
is_multiuser_uid_isolated(uid_t uid)69 bool is_multiuser_uid_isolated(uid_t uid) {
70     uid_t appid = multiuser_get_app_id(uid);
71     return appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
72 }
73 
74 #ifndef VENDORSERVICEMANAGER
75 
76 struct ManifestWithDescription {
77     std::shared_ptr<const vintf::HalManifest> manifest;
78     const char* description;
79 };
GetManifestsWithDescription()80 static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
81 #ifdef __ANDROID_RECOVERY__
82     auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
83     if (vintfObject == nullptr) {
84         ALOGE("NULL VintfObjectRecovery!");
85         return {};
86     }
87     return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
88 #else
89     auto vintfObject = vintf::VintfObject::GetInstance();
90     if (vintfObject == nullptr) {
91         ALOGE("NULL VintfObject!");
92         return {};
93     }
94     return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
95             ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
96 #endif
97 }
98 
99 // func true -> stop search and forEachManifest will return true
forEachManifest(const std::function<bool (const ManifestWithDescription &)> & func)100 static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
101     for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
102         if (mwd.manifest == nullptr) {
103             ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
104             // note, we explicitly do not retry here, so that we can detect VINTF
105             // or other bugs (b/151696835)
106             continue;
107         }
108         if (func(mwd)) return true;
109     }
110     return false;
111 }
112 
getNativeInstanceName(const vintf::ManifestInstance & instance)113 static std::string getNativeInstanceName(const vintf::ManifestInstance& instance) {
114     return instance.package() + "/" + instance.instance();
115 }
116 
117 struct AidlName {
118     std::string package;
119     std::string iface;
120     std::string instance;
121 
fillandroid::AidlName122     static bool fill(const std::string& name, AidlName* aname, bool logError) {
123         size_t firstSlash = name.find('/');
124         size_t lastDot = name.rfind('.', firstSlash);
125         if (firstSlash == std::string::npos || lastDot == std::string::npos) {
126             if (logError) {
127                 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
128                       "some.package.foo.IFoo/default) but got: %s",
129                       name.c_str());
130             }
131             return false;
132         }
133         aname->package = name.substr(0, lastDot);
134         aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
135         aname->instance = name.substr(firstSlash + 1);
136         return true;
137     }
138 };
139 
getAidlInstanceName(const vintf::ManifestInstance & instance)140 static std::string getAidlInstanceName(const vintf::ManifestInstance& instance) {
141     return instance.package() + "." + instance.interface() + "/" + instance.instance();
142 }
143 
isVintfDeclared(const Access::CallingContext & ctx,const std::string & name)144 static bool isVintfDeclared(const Access::CallingContext& ctx, const std::string& name) {
145     NativeName nname;
146     if (NativeName::fill(name, &nname)) {
147         bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
148             if (mwd.manifest->hasNativeInstance(nname.package, nname.instance)) {
149                 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(),
150                       name.c_str(), mwd.description);
151                 return true; // break
152             }
153             return false; // continue
154         });
155         if (!found) {
156             ALOGI("%s Could not find %s in the VINTF manifest.", ctx.toDebugString().c_str(),
157                   name.c_str());
158         }
159         return found;
160     }
161 
162     AidlName aname;
163     if (!AidlName::fill(name, &aname, true)) return false;
164 
165     bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
166         if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
167             ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(), name.c_str(),
168                   mwd.description);
169             return true; // break
170         }
171         return false;  // continue
172     });
173 
174     if (!found) {
175         std::set<std::string> instances;
176         forEachManifest([&](const ManifestWithDescription& mwd) {
177             std::set<std::string> res = mwd.manifest->getAidlInstances(aname.package, aname.iface);
178             instances.insert(res.begin(), res.end());
179             return true;
180         });
181 
182         std::string available;
183         if (instances.empty()) {
184             available = "No alternative instances declared in VINTF";
185         } else {
186             // for logging only. We can't return this information to the client
187             // because they may not have permissions to find or list those
188             // instances
189             available = "VINTF declared instances: " + base::Join(instances, ", ");
190         }
191         // Although it is tested, explicitly rebuilding qualified name, in case it
192         // becomes something unexpected.
193         ALOGI("%s Could not find %s.%s/%s in the VINTF manifest. %s.", ctx.toDebugString().c_str(),
194               aname.package.c_str(), aname.iface.c_str(), aname.instance.c_str(),
195               available.c_str());
196     }
197 
198     return found;
199 }
200 
getVintfUpdatableApex(const std::string & name)201 static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
202     NativeName nname;
203     if (NativeName::fill(name, &nname)) {
204         std::optional<std::string> updatableViaApex;
205 
206         forEachManifest([&](const ManifestWithDescription& mwd) {
207             bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
208                 if (manifestInstance.format() != vintf::HalFormat::NATIVE) return true;
209                 if (manifestInstance.package() != nname.package) return true;
210                 if (manifestInstance.instance() != nname.instance) return true;
211                 updatableViaApex = manifestInstance.updatableViaApex();
212                 return false; // break (libvintf uses opposite convention)
213             });
214             return !cont;
215         });
216 
217         return updatableViaApex;
218     }
219 
220     AidlName aname;
221     if (!AidlName::fill(name, &aname, true)) return std::nullopt;
222 
223     std::optional<std::string> updatableViaApex;
224 
225     forEachManifest([&](const ManifestWithDescription& mwd) {
226         bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
227             if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
228             if (manifestInstance.package() != aname.package) return true;
229             if (manifestInstance.interface() != aname.iface) return true;
230             if (manifestInstance.instance() != aname.instance) return true;
231             updatableViaApex = manifestInstance.updatableViaApex();
232             return false; // break (libvintf uses opposite convention)
233         });
234         return !cont;
235     });
236 
237     return updatableViaApex;
238 }
239 
getVintfUpdatableNames(const std::string & apexName)240 static std::vector<std::string> getVintfUpdatableNames(const std::string& apexName) {
241     std::vector<std::string> names;
242 
243     forEachManifest([&](const ManifestWithDescription& mwd) {
244         mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
245             if (manifestInstance.updatableViaApex().has_value() &&
246                 manifestInstance.updatableViaApex().value() == apexName) {
247                 if (manifestInstance.format() == vintf::HalFormat::NATIVE) {
248                     names.push_back(getNativeInstanceName(manifestInstance));
249                 } else if (manifestInstance.format() == vintf::HalFormat::AIDL) {
250                     names.push_back(getAidlInstanceName(manifestInstance));
251                 }
252             }
253             return true; // continue (libvintf uses opposite convention)
254         });
255         return false; // continue
256     });
257 
258     return names;
259 }
260 
getVintfAccessorName(const std::string & name)261 static std::optional<std::string> getVintfAccessorName(const std::string& name) {
262     AidlName aname;
263     if (!AidlName::fill(name, &aname, false)) return std::nullopt;
264 
265     std::optional<std::string> accessor;
266     forEachManifest([&](const ManifestWithDescription& mwd) {
267         mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
268             if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
269             if (manifestInstance.package() != aname.package) return true;
270             if (manifestInstance.interface() != aname.iface) return true;
271             if (manifestInstance.instance() != aname.instance) return true;
272             accessor = manifestInstance.accessor();
273             return false; // break (libvintf uses opposite convention)
274         });
275         return false; // continue
276     });
277     return accessor;
278 }
279 
getVintfConnectionInfo(const std::string & name)280 static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
281     AidlName aname;
282     if (!AidlName::fill(name, &aname, true)) return std::nullopt;
283 
284     std::optional<std::string> ip;
285     std::optional<uint64_t> port;
286     forEachManifest([&](const ManifestWithDescription& mwd) {
287         mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
288             if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
289             if (manifestInstance.package() != aname.package) return true;
290             if (manifestInstance.interface() != aname.iface) return true;
291             if (manifestInstance.instance() != aname.instance) return true;
292             ip = manifestInstance.ip();
293             port = manifestInstance.port();
294             return false; // break (libvintf uses opposite convention)
295         });
296         return false; // continue
297     });
298 
299     if (ip.has_value() && port.has_value()) {
300         ConnectionInfo info;
301         info.ipAddress = *ip;
302         info.port = *port;
303         return std::make_optional<ConnectionInfo>(info);
304     } else {
305         return std::nullopt;
306     }
307 }
308 
getVintfInstances(const std::string & interface)309 static std::vector<std::string> getVintfInstances(const std::string& interface) {
310     size_t lastDot = interface.rfind('.');
311     if (lastDot == std::string::npos) {
312         // This might be a package for native instance.
313         std::vector<std::string> ret;
314         (void)forEachManifest([&](const ManifestWithDescription& mwd) {
315             auto instances = mwd.manifest->getNativeInstances(interface);
316             ret.insert(ret.end(), instances.begin(), instances.end());
317             return false; // continue
318         });
319         // If found, return it without error log.
320         if (!ret.empty()) {
321             return ret;
322         }
323 
324         ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
325               "but got: %s",
326               interface.c_str());
327         return {};
328     }
329     const std::string package = interface.substr(0, lastDot);
330     const std::string iface = interface.substr(lastDot+1);
331 
332     std::vector<std::string> ret;
333     (void)forEachManifest([&](const ManifestWithDescription& mwd) {
334         auto instances = mwd.manifest->getAidlInstances(package, iface);
335         ret.insert(ret.end(), instances.begin(), instances.end());
336         return false;  // continue
337     });
338 
339     return ret;
340 }
341 
meetsDeclarationRequirements(const Access::CallingContext & ctx,const sp<IBinder> & binder,const std::string & name)342 static bool meetsDeclarationRequirements(const Access::CallingContext& ctx,
343                                          const sp<IBinder>& binder, const std::string& name) {
344     if (!Stability::requiresVintfDeclaration(binder)) {
345         return true;
346     }
347 
348     return isVintfDeclared(ctx, name);
349 }
350 #endif  // !VENDORSERVICEMANAGER
351 
~Service()352 ServiceManager::Service::~Service() {
353     if (hasClients) {
354         // only expected to happen on process death, we don't store the service
355         // name this late (it's in the map that holds this service), but if it
356         // is happening, we might want to change 'unlinkToDeath' to explicitly
357         // clear this bit so that we can abort in other cases, where it would
358         // mean inconsistent logic in servicemanager (unexpected and tested, but
359         // the original lazy service impl here had that bug).
360         ALOGW("A service was removed when there are clients");
361     }
362 }
363 
ServiceManager(std::unique_ptr<Access> && access)364 ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
365 // TODO(b/151696835): reenable performance hack when we solve bug, since with
366 //     this hack and other fixes, it is unlikely we will see even an ephemeral
367 //     failure when the manifest parse fails. The goal is that the manifest will
368 //     be read incorrectly and cause the process trying to register a HAL to
369 //     fail. If this is in fact an early boot kernel contention issue, then we
370 //     will get no failure, and by its absence, be signalled to invest more
371 //     effort in re-adding this performance hack.
372 // #ifndef VENDORSERVICEMANAGER
373 //     // can process these at any times, don't want to delay first VINTF client
374 //     std::thread([] {
375 //         vintf::VintfObject::GetDeviceHalManifest();
376 //         vintf::VintfObject::GetFrameworkHalManifest();
377 //     }).detach();
378 // #endif  // !VENDORSERVICEMANAGER
379 }
~ServiceManager()380 ServiceManager::~ServiceManager() {
381     // this should only happen in tests
382 
383     for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
384         CHECK(!callbacks.empty()) << name;
385         for (const auto& callback : callbacks) {
386             CHECK(callback != nullptr) << name;
387         }
388     }
389 
390     for (const auto& [name, service] : mNameToService) {
391         CHECK(service.binder != nullptr) << name;
392     }
393 }
394 
getService(const std::string & name,sp<IBinder> * outBinder)395 Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
396     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
397             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
398 
399     *outBinder = tryGetBinder(name, true).service;
400     // returns ok regardless of result for legacy reasons
401     return Status::ok();
402 }
403 
getService2(const std::string & name,os::Service * outService)404 Status ServiceManager::getService2(const std::string& name, os::Service* outService) {
405     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
406             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
407 
408     *outService = tryGetService(name, true);
409     // returns ok regardless of result for legacy reasons
410     return Status::ok();
411 }
412 
checkService(const std::string & name,os::Service * outService)413 Status ServiceManager::checkService(const std::string& name, os::Service* outService) {
414     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
415             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
416 
417     *outService = tryGetService(name, false);
418     // returns ok regardless of result for legacy reasons
419     return Status::ok();
420 }
421 
tryGetService(const std::string & name,bool startIfNotFound)422 os::Service ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
423     std::optional<std::string> accessorName;
424 #ifndef VENDORSERVICEMANAGER
425     accessorName = getVintfAccessorName(name);
426 #endif
427     if (accessorName.has_value()) {
428         auto ctx = mAccess->getCallingContext();
429         if (!mAccess->canFind(ctx, name)) {
430             return os::Service::make<os::Service::Tag::accessor>(nullptr);
431         }
432         return os::Service::make<os::Service::Tag::accessor>(
433                 tryGetBinder(*accessorName, startIfNotFound).service);
434     } else {
435         return os::Service::make<os::Service::Tag::serviceWithMetadata>(
436                 tryGetBinder(name, startIfNotFound));
437     }
438 }
439 
tryGetBinder(const std::string & name,bool startIfNotFound)440 os::ServiceWithMetadata ServiceManager::tryGetBinder(const std::string& name,
441                                                      bool startIfNotFound) {
442     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
443             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
444 
445     auto ctx = mAccess->getCallingContext();
446 
447     sp<IBinder> out;
448     Service* service = nullptr;
449     if (auto it = mNameToService.find(name); it != mNameToService.end()) {
450         service = &(it->second);
451 
452         if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
453             LOG(WARNING) << "Isolated app with UID " << ctx.uid << " requested '" << name
454                          << "', but the service is not allowed for isolated apps.";
455             return os::ServiceWithMetadata();
456         }
457         out = service->binder;
458     }
459 
460     if (!mAccess->canFind(ctx, name)) {
461         return os::ServiceWithMetadata();
462     }
463 
464     if (!out && startIfNotFound) {
465         tryStartService(ctx, name);
466     }
467 
468     if (out) {
469         // Force onClients to get sent, and then make sure the timerfd won't clear it
470         // by setting guaranteeClient again. This logic could be simplified by using
471         // a time-based guarantee. However, forcing onClients(true) to get sent
472         // right here is always going to be important for processes serving multiple
473         // lazy interfaces.
474         service->guaranteeClient = true;
475         CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
476         service->guaranteeClient = true;
477     }
478     os::ServiceWithMetadata serviceWithMetadata = os::ServiceWithMetadata();
479     serviceWithMetadata.service = out;
480     serviceWithMetadata.isLazyService =
481             service ? service->dumpPriority & FLAG_IS_LAZY_SERVICE : false;
482     return serviceWithMetadata;
483 }
484 
isValidServiceName(const std::string & name)485 bool isValidServiceName(const std::string& name) {
486     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
487             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
488 
489     if (name.size() == 0) return false;
490     if (name.size() > 127) return false;
491 
492     for (char c : name) {
493         if (c == '_' || c == '-' || c == '.' || c == '/') continue;
494         if (c >= 'a' && c <= 'z') continue;
495         if (c >= 'A' && c <= 'Z') continue;
496         if (c >= '0' && c <= '9') continue;
497         return false;
498     }
499 
500     return true;
501 }
502 
addService(const std::string & name,const sp<IBinder> & binder,bool allowIsolated,int32_t dumpPriority)503 Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
504     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
505             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
506 
507     auto ctx = mAccess->getCallingContext();
508 
509     if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
510         return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
511     }
512 
513     std::optional<std::string> accessorName;
514     if (auto status = canAddService(ctx, name, &accessorName); !status.isOk()) {
515         return status;
516     }
517 
518     if (binder == nullptr) {
519         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
520     }
521 
522     if (!isValidServiceName(name)) {
523         ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
524         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
525     }
526 
527 #ifndef VENDORSERVICEMANAGER
528     if (!meetsDeclarationRequirements(ctx, binder, name)) {
529         // already logged
530         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
531     }
532 #endif  // !VENDORSERVICEMANAGER
533 
534     if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
535         ALOGW("%s Dump flag priority is not set when adding %s", ctx.toDebugString().c_str(),
536               name.c_str());
537     }
538 
539     // implicitly unlinked when the binder is removed
540     if (binder->remoteBinder() != nullptr &&
541         binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
542         ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
543         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
544     }
545 
546     auto it = mNameToService.find(name);
547     bool prevClients = false;
548     if (it != mNameToService.end()) {
549         const Service& existing = it->second;
550         prevClients = existing.hasClients;
551 
552         // We could do better than this because if the other service dies, it
553         // may not have an entry here. However, this case is unlikely. We are
554         // only trying to detect when two different services are accidentally installed.
555 
556         if (existing.ctx.uid != ctx.uid) {
557             ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
558                   "from UID %u. Multiple instances installed?",
559                   name.c_str(), existing.ctx.uid, ctx.uid);
560         }
561 
562         if (existing.ctx.sid != ctx.sid) {
563             ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
564                   "from SID %s. Multiple instances installed?",
565                   name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
566         }
567 
568         ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
569               "from PID %d. Bad state? Late death notification? Multiple instances installed?",
570               name.c_str(), existing.ctx.debugPid, ctx.debugPid);
571     }
572 
573     // Overwrite the old service if it exists
574     mNameToService[name] = Service{
575             .binder = binder,
576             .allowIsolated = allowIsolated,
577             .dumpPriority = dumpPriority,
578             .hasClients = prevClients, // see b/279898063, matters if existing callbacks
579             .guaranteeClient = false,
580             .ctx = ctx,
581     };
582 
583     if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
584         // If someone is currently waiting on the service, notify the service that
585         // we're waiting and flush it to the service.
586         mNameToService[name].guaranteeClient = true;
587         CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
588         mNameToService[name].guaranteeClient = true;
589 
590         for (const sp<IServiceCallback>& cb : it->second) {
591             // permission checked in registerForNotifications
592             cb->onRegistration(name, binder);
593         }
594     }
595 
596     return Status::ok();
597 }
598 
listServices(int32_t dumpPriority,std::vector<std::string> * outList)599 Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
600     SM_PERFETTO_TRACE_FUNC();
601 
602     if (!mAccess->canList(mAccess->getCallingContext())) {
603         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
604     }
605 
606     size_t toReserve = 0;
607     for (auto const& [name, service] : mNameToService) {
608         (void) name;
609 
610         if (service.dumpPriority & dumpPriority) ++toReserve;
611     }
612 
613     CHECK(outList->empty());
614 
615     outList->reserve(toReserve);
616     for (auto const& [name, service] : mNameToService) {
617         (void) service;
618 
619         if (service.dumpPriority & dumpPriority) {
620             outList->push_back(name);
621         }
622     }
623 
624     return Status::ok();
625 }
626 
registerForNotifications(const std::string & name,const sp<IServiceCallback> & callback)627 Status ServiceManager::registerForNotifications(
628         const std::string& name, const sp<IServiceCallback>& callback) {
629     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
630             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
631 
632     auto ctx = mAccess->getCallingContext();
633 
634     // TODO(b/338541373): Implement the notification mechanism for services accessed via
635     // IAccessor.
636     std::optional<std::string> accessorName;
637     if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
638         return status;
639     }
640 
641     // note - we could allow isolated apps to get notifications if we
642     // keep track of isolated callbacks and non-isolated callbacks, but
643     // this is done since isolated apps shouldn't access lazy services
644     // so we should be able to use different APIs to keep things simple.
645     // Here, we disallow everything, because the service might not be
646     // registered yet.
647     if (is_multiuser_uid_isolated(ctx.uid)) {
648         return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
649     }
650 
651     if (!isValidServiceName(name)) {
652         ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
653         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
654     }
655 
656     if (callback == nullptr) {
657         return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
658     }
659 
660     if (OK !=
661         IInterface::asBinder(callback)->linkToDeath(
662                 sp<ServiceManager>::fromExisting(this))) {
663         ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
664         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
665     }
666 
667     mNameToRegistrationCallback[name].push_back(callback);
668 
669     if (auto it = mNameToService.find(name); it != mNameToService.end()) {
670         const sp<IBinder>& binder = it->second.binder;
671 
672         // never null if an entry exists
673         CHECK(binder != nullptr) << name;
674         callback->onRegistration(name, binder);
675     }
676 
677     return Status::ok();
678 }
unregisterForNotifications(const std::string & name,const sp<IServiceCallback> & callback)679 Status ServiceManager::unregisterForNotifications(
680         const std::string& name, const sp<IServiceCallback>& callback) {
681     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
682             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
683 
684     auto ctx = mAccess->getCallingContext();
685 
686     std::optional<std::string> accessorName;
687     if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
688         return status;
689     }
690 
691     bool found = false;
692 
693     auto it = mNameToRegistrationCallback.find(name);
694     if (it != mNameToRegistrationCallback.end()) {
695         removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
696     }
697 
698     if (!found) {
699         ALOGE("%s Trying to unregister callback, but none exists %s", ctx.toDebugString().c_str(),
700               name.c_str());
701         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
702     }
703 
704     return Status::ok();
705 }
706 
isDeclared(const std::string & name,bool * outReturn)707 Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
708     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
709             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
710 
711     auto ctx = mAccess->getCallingContext();
712 
713     std::optional<std::string> accessorName;
714     if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
715         return status;
716     }
717 
718     *outReturn = false;
719 
720 #ifndef VENDORSERVICEMANAGER
721     *outReturn = isVintfDeclared(ctx, name);
722 #endif
723     return Status::ok();
724 }
725 
getDeclaredInstances(const std::string & interface,std::vector<std::string> * outReturn)726 binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
727     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
728             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoInterfaceName, interface.c_str())));
729 
730     auto ctx = mAccess->getCallingContext();
731 
732     std::vector<std::string> allInstances;
733 #ifndef VENDORSERVICEMANAGER
734     allInstances = getVintfInstances(interface);
735 #endif
736 
737     outReturn->clear();
738 
739     std::optional<std::string> _accessorName;
740     for (const std::string& instance : allInstances) {
741         if (auto status = canFindService(ctx, interface + "/" + instance, &_accessorName);
742             status.isOk()) {
743             outReturn->push_back(instance);
744         }
745     }
746 
747     if (outReturn->size() == 0 && allInstances.size() != 0) {
748         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
749     }
750 
751     return Status::ok();
752 }
753 
updatableViaApex(const std::string & name,std::optional<std::string> * outReturn)754 Status ServiceManager::updatableViaApex(const std::string& name,
755                                         std::optional<std::string>* outReturn) {
756     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
757             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
758 
759     auto ctx = mAccess->getCallingContext();
760 
761     std::optional<std::string> _accessorName;
762     if (auto status = canFindService(ctx, name, &_accessorName); !status.isOk()) {
763         return status;
764     }
765 
766     *outReturn = std::nullopt;
767 
768 #ifndef VENDORSERVICEMANAGER
769     *outReturn = getVintfUpdatableApex(name);
770 #endif
771     return Status::ok();
772 }
773 
getUpdatableNames(const std::string & apexName,std::vector<std::string> * outReturn)774 Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
775                                          std::vector<std::string>* outReturn) {
776     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
777             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoApexName, apexName.c_str())));
778 
779     auto ctx = mAccess->getCallingContext();
780 
781     std::vector<std::string> apexUpdatableNames;
782 #ifndef VENDORSERVICEMANAGER
783     apexUpdatableNames = getVintfUpdatableNames(apexName);
784 #endif
785 
786     outReturn->clear();
787 
788     std::optional<std::string> _accessorName;
789     for (const std::string& name : apexUpdatableNames) {
790         if (auto status = canFindService(ctx, name, &_accessorName); status.isOk()) {
791             outReturn->push_back(name);
792         }
793     }
794 
795     if (outReturn->size() == 0 && apexUpdatableNames.size() != 0) {
796         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
797     }
798     return Status::ok();
799 }
800 
getConnectionInfo(const std::string & name,std::optional<ConnectionInfo> * outReturn)801 Status ServiceManager::getConnectionInfo(const std::string& name,
802                                          std::optional<ConnectionInfo>* outReturn) {
803     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
804             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
805 
806     auto ctx = mAccess->getCallingContext();
807 
808     std::optional<std::string> _accessorName;
809     if (auto status = canFindService(ctx, name, &_accessorName); !status.isOk()) {
810         return status;
811     }
812 
813     *outReturn = std::nullopt;
814 
815 #ifndef VENDORSERVICEMANAGER
816     *outReturn = getVintfConnectionInfo(name);
817 #endif
818     return Status::ok();
819 }
820 
removeRegistrationCallback(const wp<IBinder> & who,ServiceCallbackMap::iterator * it,bool * found)821 void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
822                                     ServiceCallbackMap::iterator* it,
823                                     bool* found) {
824     SM_PERFETTO_TRACE_FUNC();
825 
826     std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
827 
828     for (auto lit = listeners.begin(); lit != listeners.end();) {
829         if (IInterface::asBinder(*lit) == who) {
830             if(found) *found = true;
831             lit = listeners.erase(lit);
832         } else {
833             ++lit;
834         }
835     }
836 
837     if (listeners.empty()) {
838         *it = mNameToRegistrationCallback.erase(*it);
839     } else {
840         (*it)++;
841     }
842 }
843 
binderDied(const wp<IBinder> & who)844 void ServiceManager::binderDied(const wp<IBinder>& who) {
845     SM_PERFETTO_TRACE_FUNC();
846 
847     for (auto it = mNameToService.begin(); it != mNameToService.end();) {
848         if (who == it->second.binder) {
849             // TODO: currently, this entry contains the state also
850             // associated with mNameToClientCallback. If we allowed
851             // other processes to register client callbacks, we
852             // would have to preserve hasClients (perhaps moving
853             // that state into mNameToClientCallback, which is complicated
854             // because those callbacks are associated w/ particular binder
855             // objects, though they are indexed by name now, they may
856             // need to be indexed by binder at that point).
857             it = mNameToService.erase(it);
858         } else {
859             ++it;
860         }
861     }
862 
863     for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
864         removeRegistrationCallback(who, &it, nullptr /*found*/);
865     }
866 
867     for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
868         removeClientCallback(who, &it);
869     }
870 }
871 
tryStartService(const Access::CallingContext & ctx,const std::string & name)872 void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
873     ALOGI("%s Since '%s' could not be found trying to start it as a lazy AIDL service. (if it's "
874           "not configured to be a lazy service, it may be stuck starting or still starting).",
875           ctx.toDebugString().c_str(), name.c_str());
876 
877     std::thread([=] {
878         if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
879             ALOGI("%s Tried to start aidl service %s as a lazy service, but was unable to. Usually "
880                   "this happens when a service is not installed, but if the service is intended to "
881                   "be used as a lazy service, then it may be configured incorrectly.",
882                   ctx.toDebugString().c_str(), name.c_str());
883         }
884     }).detach();
885 }
886 
registerClientCallback(const std::string & name,const sp<IBinder> & service,const sp<IClientCallback> & cb)887 Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
888                                               const sp<IClientCallback>& cb) {
889     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
890             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
891 
892     if (cb == nullptr) {
893         return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
894     }
895 
896     auto ctx = mAccess->getCallingContext();
897     std::optional<std::string> accessorName;
898     if (auto status = canAddService(ctx, name, &accessorName); !status.isOk()) {
899         return status;
900     }
901 
902     auto serviceIt = mNameToService.find(name);
903     if (serviceIt == mNameToService.end()) {
904         ALOGE("%s Could not add callback for nonexistent service: %s", ctx.toDebugString().c_str(),
905               name.c_str());
906         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
907     }
908 
909     if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
910         ALOGW("%s Only a server can register for client callbacks (for %s)",
911               ctx.toDebugString().c_str(), name.c_str());
912         return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
913                                          "Only service can register client callback for itself.");
914     }
915 
916     if (serviceIt->second.binder != service) {
917         ALOGW("%s Tried to register client callback for %s but a different service is registered "
918               "under this name.",
919               ctx.toDebugString().c_str(), name.c_str());
920         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
921     }
922 
923     if (OK !=
924         IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
925         ALOGE("%s Could not linkToDeath when adding client callback for %s",
926               ctx.toDebugString().c_str(), name.c_str());
927         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
928     }
929 
930     // WARNING: binderDied makes an assumption about this. If we open up client
931     // callbacks to other services, certain race conditions may lead to services
932     // getting extra client callback notifications.
933     // Make sure all callbacks have been told about a consistent state - b/278038751
934     if (serviceIt->second.hasClients) {
935         cb->onClients(service, true);
936     }
937 
938     mNameToClientCallback[name].push_back(cb);
939 
940     // Flush updated info to client callbacks (especially if guaranteeClient
941     // and !hasClient, see b/285202885). We may or may not have clients at
942     // this point, so ignore the return value.
943     (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
944 
945     return Status::ok();
946 }
947 
removeClientCallback(const wp<IBinder> & who,ClientCallbackMap::iterator * it)948 void ServiceManager::removeClientCallback(const wp<IBinder>& who,
949                                           ClientCallbackMap::iterator* it) {
950     std::vector<sp<IClientCallback>>& listeners = (*it)->second;
951 
952     for (auto lit = listeners.begin(); lit != listeners.end();) {
953         if (IInterface::asBinder(*lit) == who) {
954             lit = listeners.erase(lit);
955         } else {
956             ++lit;
957         }
958     }
959 
960     if (listeners.empty()) {
961         *it = mNameToClientCallback.erase(*it);
962     } else {
963         (*it)++;
964     }
965 }
966 
getNodeStrongRefCount()967 ssize_t ServiceManager::Service::getNodeStrongRefCount() {
968     sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
969     if (bpBinder == nullptr) return -1;
970 
971     return ProcessState::self()->getStrongRefCountForNode(bpBinder);
972 }
973 
handleClientCallbacks()974 void ServiceManager::handleClientCallbacks() {
975     for (const auto& [name, service] : mNameToService) {
976         handleServiceClientCallback(1 /* sm has one refcount */, name, true);
977     }
978 }
979 
handleServiceClientCallback(size_t knownClients,const std::string & serviceName,bool isCalledOnInterval)980 bool ServiceManager::handleServiceClientCallback(size_t knownClients,
981                                                  const std::string& serviceName,
982                                                  bool isCalledOnInterval) {
983     auto serviceIt = mNameToService.find(serviceName);
984     if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
985         return true; // return we do have clients a.k.a. DON'T DO ANYTHING
986     }
987 
988     Service& service = serviceIt->second;
989     ssize_t count = service.getNodeStrongRefCount();
990 
991     // binder driver doesn't support this feature, consider we have clients
992     if (count == -1) return true;
993 
994     bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
995 
996     if (service.guaranteeClient) {
997         if (!service.hasClients && !hasKernelReportedClients) {
998             sendClientCallbackNotifications(serviceName, true,
999                                             "service is guaranteed to be in use");
1000         }
1001 
1002         // guarantee is temporary
1003         service.guaranteeClient = false;
1004     }
1005 
1006     // Regardless of this situation, we want to give this notification as soon as possible.
1007     // This way, we have a chance of preventing further thrashing.
1008     if (hasKernelReportedClients && !service.hasClients) {
1009         sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
1010     }
1011 
1012     // But limit rate of shutting down service.
1013     if (isCalledOnInterval) {
1014         if (!hasKernelReportedClients && service.hasClients) {
1015             sendClientCallbackNotifications(serviceName, false,
1016                                             "we now have no record of a client");
1017         }
1018     }
1019 
1020     // May be different than 'hasKernelReportedClients'. We intentionally delay
1021     // information about clients going away to reduce thrashing.
1022     return service.hasClients;
1023 }
1024 
sendClientCallbackNotifications(const std::string & serviceName,bool hasClients,const char * context)1025 void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
1026                                                      bool hasClients, const char* context) {
1027     auto serviceIt = mNameToService.find(serviceName);
1028     if (serviceIt == mNameToService.end()) {
1029         ALOGW("sendClientCallbackNotifications could not find service %s when %s",
1030               serviceName.c_str(), context);
1031         return;
1032     }
1033     Service& service = serviceIt->second;
1034 
1035     CHECK_NE(hasClients, service.hasClients) << context;
1036 
1037     ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
1038           hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
1039 
1040     auto ccIt = mNameToClientCallback.find(serviceName);
1041     CHECK(ccIt != mNameToClientCallback.end())
1042             << "sendClientCallbackNotifications could not find callbacks for service when "
1043             << context;
1044 
1045     for (const auto& callback : ccIt->second) {
1046         callback->onClients(service.binder, hasClients);
1047     }
1048 
1049     service.hasClients = hasClients;
1050 }
1051 
tryUnregisterService(const std::string & name,const sp<IBinder> & binder)1052 Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
1053     SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_PROTO_FIELDS(
1054             PERFETTO_TE_PROTO_FIELD_CSTR(kProtoServiceName, name.c_str())));
1055 
1056     if (binder == nullptr) {
1057         return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
1058     }
1059 
1060     auto ctx = mAccess->getCallingContext();
1061     std::optional<std::string> accessorName;
1062     if (auto status = canAddService(ctx, name, &accessorName); !status.isOk()) {
1063         return status;
1064     }
1065 
1066     auto serviceIt = mNameToService.find(name);
1067     if (serviceIt == mNameToService.end()) {
1068         ALOGW("%s Tried to unregister %s, but that service wasn't registered to begin with.",
1069               ctx.toDebugString().c_str(), name.c_str());
1070         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
1071     }
1072 
1073     if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
1074         ALOGW("%s Only a server can unregister itself (for %s)", ctx.toDebugString().c_str(),
1075               name.c_str());
1076         return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
1077                                          "Service can only unregister itself.");
1078     }
1079 
1080     sp<IBinder> storedBinder = serviceIt->second.binder;
1081 
1082     if (binder != storedBinder) {
1083         ALOGW("%s Tried to unregister %s, but a different service is registered under this name.",
1084               ctx.toDebugString().c_str(), name.c_str());
1085         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1086                                          "Different service registered under this name.");
1087     }
1088 
1089     // important because we don't have timer-based guarantees, we don't want to clear
1090     // this
1091     if (serviceIt->second.guaranteeClient) {
1092         ALOGI("%s Tried to unregister %s, but there is about to be a client.",
1093               ctx.toDebugString().c_str(), name.c_str());
1094         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1095                                          "Can't unregister, pending client.");
1096     }
1097 
1098     // - kernel driver will hold onto one refcount (during this transaction)
1099     // - servicemanager has a refcount (guaranteed by this transaction)
1100     constexpr size_t kKnownClients = 2;
1101 
1102     if (handleServiceClientCallback(kKnownClients, name, false)) {
1103         ALOGI("%s Tried to unregister %s, but there are clients.", ctx.toDebugString().c_str(),
1104               name.c_str());
1105 
1106         // Since we had a failed registration attempt, and the HIDL implementation of
1107         // delaying service shutdown for multiple periods wasn't ported here... this may
1108         // help reduce thrashing, but we should be able to remove it.
1109         serviceIt->second.guaranteeClient = true;
1110 
1111         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1112                                          "Can't unregister, known client.");
1113     }
1114 
1115     ALOGI("%s Unregistering %s", ctx.toDebugString().c_str(), name.c_str());
1116     mNameToService.erase(name);
1117 
1118     return Status::ok();
1119 }
1120 
canAddService(const Access::CallingContext & ctx,const std::string & name,std::optional<std::string> * accessor)1121 Status ServiceManager::canAddService(const Access::CallingContext& ctx, const std::string& name,
1122                                      std::optional<std::string>* accessor) {
1123     if (!mAccess->canAdd(ctx, name)) {
1124         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied for service.");
1125     }
1126 #ifndef VENDORSERVICEMANAGER
1127     *accessor = getVintfAccessorName(name);
1128 #endif
1129     if (accessor->has_value()) {
1130         if (!mAccess->canAdd(ctx, accessor->value())) {
1131             return Status::fromExceptionCode(Status::EX_SECURITY,
1132                                              "SELinux denied for the accessor of the service.");
1133         }
1134     }
1135     return Status::ok();
1136 }
1137 
canFindService(const Access::CallingContext & ctx,const std::string & name,std::optional<std::string> * accessor)1138 Status ServiceManager::canFindService(const Access::CallingContext& ctx, const std::string& name,
1139                                       std::optional<std::string>* accessor) {
1140     if (!mAccess->canFind(ctx, name)) {
1141         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied for service.");
1142     }
1143 #ifndef VENDORSERVICEMANAGER
1144     *accessor = getVintfAccessorName(name);
1145 #endif
1146     if (accessor->has_value()) {
1147         if (!mAccess->canFind(ctx, accessor->value())) {
1148             return Status::fromExceptionCode(Status::EX_SECURITY,
1149                                              "SELinux denied for the accessor of the service.");
1150         }
1151     }
1152     return Status::ok();
1153 }
1154 
getServiceDebugInfo(std::vector<ServiceDebugInfo> * outReturn)1155 Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
1156     SM_PERFETTO_TRACE_FUNC();
1157     if (!mAccess->canList(mAccess->getCallingContext())) {
1158         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
1159     }
1160 
1161     outReturn->reserve(mNameToService.size());
1162     for (auto const& [name, service] : mNameToService) {
1163         ServiceDebugInfo info;
1164         info.name = name;
1165         info.debugPid = service.ctx.debugPid;
1166 
1167         outReturn->push_back(std::move(info));
1168     }
1169 
1170     return Status::ok();
1171 }
1172 
clear()1173 void ServiceManager::clear() {
1174     mNameToService.clear();
1175     mNameToRegistrationCallback.clear();
1176     mNameToClientCallback.clear();
1177 }
1178 
1179 }  // namespace android
1180