xref: /aosp_15_r20/frameworks/native/libs/binder/IServiceManager.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
2  * Copyright (C) 2005 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 <sys/socket.h>
18 #define LOG_TAG "ServiceManagerCppClient"
19 
20 #include <binder/IServiceManager.h>
21 #include <binder/IServiceManagerUnitTestHelper.h>
22 #include "BackendUnifiedServiceManager.h"
23 
24 #include <inttypes.h>
25 #include <unistd.h>
26 #include <chrono>
27 #include <condition_variable>
28 
29 #include <FdTrigger.h>
30 #include <RpcSocketAddress.h>
31 #include <android-base/properties.h>
32 #include <android/os/BnAccessor.h>
33 #include <android/os/BnServiceCallback.h>
34 #include <android/os/BnServiceManager.h>
35 #include <android/os/IAccessor.h>
36 #include <android/os/IServiceManager.h>
37 #include <binder/IPCThreadState.h>
38 #include <binder/Parcel.h>
39 #include <binder/RpcSession.h>
40 #include <utils/String8.h>
41 #include <variant>
42 #ifndef __ANDROID_VNDK__
43 #include <binder/IPermissionController.h>
44 #endif
45 
46 #ifdef __ANDROID__
47 #include <cutils/properties.h>
48 #else
49 #include "ServiceManagerHost.h"
50 #endif
51 
52 #if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
53 #include <android/apexsupport.h>
54 #include <vndksupport/linker.h>
55 #endif
56 
57 #include "Static.h"
58 #include "Utils.h"
59 
60 namespace android {
61 
62 using namespace std::chrono_literals;
63 
64 using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
65 
66 using AidlServiceManager = android::os::IServiceManager;
67 using android::binder::Status;
68 using android::os::IAccessor;
69 using android::os::Service;
70 
71 // libbinder's IServiceManager.h can't rely on the values generated by AIDL
72 // because many places use its headers via include_dirs (meaning, without
73 // declaring the dependency in the build system). So, for now, we can just check
74 // the values here.
75 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
76 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
77 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
78 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
79 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
80 static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
81 
getInterfaceDescriptor() const82 const String16& IServiceManager::getInterfaceDescriptor() const {
83     return AidlServiceManager::descriptor;
84 }
IServiceManager()85 IServiceManager::IServiceManager() {}
~IServiceManager()86 IServiceManager::~IServiceManager() {}
87 
88 // From the old libbinder IServiceManager interface to IServiceManager.
89 class CppBackendShim : public IServiceManager {
90 public:
91     explicit CppBackendShim(const sp<BackendUnifiedServiceManager>& impl);
92 
93     sp<IBinder> getService(const String16& name) const override;
94     sp<IBinder> checkService(const String16& name) const override;
95     status_t addService(const String16& name, const sp<IBinder>& service,
96                         bool allowIsolated, int dumpsysPriority) override;
97     Vector<String16> listServices(int dumpsysPriority) override;
98     sp<IBinder> waitForService(const String16& name16) override;
99     bool isDeclared(const String16& name) override;
100     Vector<String16> getDeclaredInstances(const String16& interface) override;
101     std::optional<String16> updatableViaApex(const String16& name) override;
102     Vector<String16> getUpdatableNames(const String16& apexName) override;
103     std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
104     class RegistrationWaiter : public android::os::BnServiceCallback {
105     public:
RegistrationWaiter(const sp<AidlRegistrationCallback> & callback)106         explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
107               : mImpl(callback) {}
onRegistration(const std::string & name,const sp<IBinder> & binder)108         Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
109             mImpl->onServiceRegistration(String16(name.c_str()), binder);
110             return Status::ok();
111         }
112 
113     private:
114         sp<AidlRegistrationCallback> mImpl;
115     };
116 
117     status_t registerForNotifications(const String16& service,
118                                       const sp<AidlRegistrationCallback>& cb) override;
119 
120     status_t unregisterForNotifications(const String16& service,
121                                         const sp<AidlRegistrationCallback>& cb) override;
122 
123     std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
124     // for legacy ABI
getInterfaceDescriptor() const125     const String16& getInterfaceDescriptor() const override {
126         return mUnifiedServiceManager->getInterfaceDescriptor();
127     }
onAsBinder()128     IBinder* onAsBinder() override { return IInterface::asBinder(mUnifiedServiceManager).get(); }
129 
enableAddServiceCache(bool value)130     void enableAddServiceCache(bool value) { mUnifiedServiceManager->enableAddServiceCache(value); }
131 
132 protected:
133     sp<BackendUnifiedServiceManager> mUnifiedServiceManager;
134     // AidlRegistrationCallback -> services that its been registered for
135     // notifications.
136     using LocalRegistrationAndWaiter =
137             std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
138     using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
139     ServiceCallbackMap mNameToRegistrationCallback;
140     std::mutex mNameToRegistrationLock;
141 
142     void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
143                                           ServiceCallbackMap::iterator* it,
144                                           sp<RegistrationWaiter>* waiter);
145 
146     // Directly get the service in a way that, for lazy services, requests the service to be started
147     // if it is not currently started. This way, calls directly to CppBackendShim::getService
148     // will still have the 5s delay that is expected by a large amount of Android code.
149     //
150     // When implementing CppBackendShim, use realGetService instead of
151     // mUnifiedServiceManager->getService so that it can be overridden in CppServiceManagerHostShim.
realGetService(const std::string & name,sp<IBinder> * _aidl_return)152     virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
153         Service service;
154         Status status = mUnifiedServiceManager->getService2(name, &service);
155         auto serviceWithMetadata = service.get<Service::Tag::serviceWithMetadata>();
156         *_aidl_return = serviceWithMetadata.service;
157         return status;
158     }
159 };
160 
161 class AccessorProvider {
162 public:
AccessorProvider(std::set<std::string> && instances,RpcAccessorProvider && provider)163     AccessorProvider(std::set<std::string>&& instances, RpcAccessorProvider&& provider)
164           : mInstances(std::move(instances)), mProvider(std::move(provider)) {}
provide(const String16 & name)165     sp<IBinder> provide(const String16& name) {
166         if (mInstances.count(String8(name).c_str()) > 0) {
167             return mProvider(name);
168         } else {
169             return nullptr;
170         }
171     }
instances()172     const std::set<std::string>& instances() { return mInstances; }
173 
174 private:
175     AccessorProvider() = delete;
176 
177     std::set<std::string> mInstances;
178     RpcAccessorProvider mProvider;
179 };
180 
181 class AccessorProviderEntry {
182 public:
AccessorProviderEntry(std::shared_ptr<AccessorProvider> && provider)183     AccessorProviderEntry(std::shared_ptr<AccessorProvider>&& provider)
184           : mProvider(std::move(provider)) {}
185     std::shared_ptr<AccessorProvider> mProvider;
186 
187 private:
188     AccessorProviderEntry() = delete;
189 };
190 
191 [[clang::no_destroy]] static std::once_flag gSmOnce;
192 [[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
193 [[clang::no_destroy]] static std::mutex gAccessorProvidersMutex;
194 [[clang::no_destroy]] static std::vector<AccessorProviderEntry> gAccessorProviders;
195 
196 class LocalAccessor : public android::os::BnAccessor {
197 public:
LocalAccessor(const String16 & instance,RpcSocketAddressProvider && connectionInfoProvider)198     LocalAccessor(const String16& instance, RpcSocketAddressProvider&& connectionInfoProvider)
199           : mInstance(instance), mConnectionInfoProvider(std::move(connectionInfoProvider)) {
200         LOG_ALWAYS_FATAL_IF(!mConnectionInfoProvider,
201                             "LocalAccessor object needs a valid connection info provider");
202     }
203 
~LocalAccessor()204     ~LocalAccessor() {
205         if (mOnDelete) mOnDelete();
206     }
207 
addConnection(::android::os::ParcelFileDescriptor * outFd)208     ::android::binder::Status addConnection(::android::os::ParcelFileDescriptor* outFd) {
209         using android::os::IAccessor;
210         sockaddr_storage addrStorage;
211         std::unique_ptr<FdTrigger> trigger = FdTrigger::make();
212         RpcTransportFd fd;
213         status_t status =
214                 mConnectionInfoProvider(mInstance, reinterpret_cast<sockaddr*>(&addrStorage),
215                                         sizeof(addrStorage));
216         if (status != OK) {
217             const std::string error = "The connection info provider was unable to provide "
218                                       "connection info for instance " +
219                     std::string(String8(mInstance).c_str()) +
220                     " with status: " + statusToString(status);
221             ALOGE("%s", error.c_str());
222             return Status::fromServiceSpecificError(IAccessor::ERROR_CONNECTION_INFO_NOT_FOUND,
223                                                     error.c_str());
224         }
225         if (addrStorage.ss_family == AF_VSOCK) {
226             sockaddr_vm* addr = reinterpret_cast<sockaddr_vm*>(&addrStorage);
227             status = singleSocketConnection(VsockSocketAddress(addr->svm_cid, addr->svm_port),
228                                             trigger, &fd);
229         } else if (addrStorage.ss_family == AF_UNIX) {
230             sockaddr_un* addr = reinterpret_cast<sockaddr_un*>(&addrStorage);
231             status = singleSocketConnection(UnixSocketAddress(addr->sun_path), trigger, &fd);
232         } else if (addrStorage.ss_family == AF_INET) {
233             sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(&addrStorage);
234             status = singleSocketConnection(InetSocketAddress(reinterpret_cast<sockaddr*>(addr),
235                                                               sizeof(sockaddr_in),
236                                                               inet_ntoa(addr->sin_addr),
237                                                               ntohs(addr->sin_port)),
238                                             trigger, &fd);
239         } else {
240             const std::string error =
241                     "Unsupported socket family type or the ConnectionInfoProvider failed to find a "
242                     "valid address. Family type: " +
243                     std::to_string(addrStorage.ss_family);
244             ALOGE("%s", error.c_str());
245             return Status::fromServiceSpecificError(IAccessor::ERROR_UNSUPPORTED_SOCKET_FAMILY,
246                                                     error.c_str());
247         }
248         if (status != OK) {
249             const std::string error = "Failed to connect to socket for " +
250                     std::string(String8(mInstance).c_str()) +
251                     " with status: " + statusToString(status);
252             ALOGE("%s", error.c_str());
253             int err = 0;
254             if (status == -EACCES) {
255                 err = IAccessor::ERROR_FAILED_TO_CONNECT_EACCES;
256             } else {
257                 err = IAccessor::ERROR_FAILED_TO_CONNECT_TO_SOCKET;
258             }
259             return Status::fromServiceSpecificError(err, error.c_str());
260         }
261         *outFd = os::ParcelFileDescriptor(std::move(fd.fd));
262         return Status::ok();
263     }
264 
getInstanceName(String16 * instance)265     ::android::binder::Status getInstanceName(String16* instance) {
266         *instance = mInstance;
267         return Status::ok();
268     }
269 
270 private:
271     LocalAccessor() = delete;
272     String16 mInstance;
273     RpcSocketAddressProvider mConnectionInfoProvider;
274     std::function<void()> mOnDelete;
275 };
276 
getInjectedAccessor(const std::string & name,android::os::Service * service)277 android::binder::Status getInjectedAccessor(const std::string& name,
278                                             android::os::Service* service) {
279     std::vector<AccessorProviderEntry> copiedProviders;
280     {
281         std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
282         copiedProviders.insert(copiedProviders.begin(), gAccessorProviders.begin(),
283                                gAccessorProviders.end());
284     }
285 
286     // Unlocked to call the providers. This requires the providers to be
287     // threadsafe and not contain any references to objects that could be
288     // deleted.
289     for (const auto& provider : copiedProviders) {
290         sp<IBinder> binder = provider.mProvider->provide(String16(name.c_str()));
291         if (binder == nullptr) continue;
292         status_t status = validateAccessor(String16(name.c_str()), binder);
293         if (status != OK) {
294             ALOGE("A provider returned a binder that is not an IAccessor for instance %s. Status: "
295                   "%s",
296                   name.c_str(), statusToString(status).c_str());
297             return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
298         }
299         *service = os::Service::make<os::Service::Tag::accessor>(binder);
300         return android::binder::Status::ok();
301     }
302 
303     *service = os::Service::make<os::Service::Tag::accessor>(nullptr);
304     return android::binder::Status::ok();
305 }
306 
defaultServiceManager()307 sp<IServiceManager> defaultServiceManager()
308 {
309     std::call_once(gSmOnce, []() {
310         gDefaultServiceManager = sp<CppBackendShim>::make(getBackendUnifiedServiceManager());
311     });
312 
313     return gDefaultServiceManager;
314 }
315 
setDefaultServiceManager(const sp<IServiceManager> & sm)316 void setDefaultServiceManager(const sp<IServiceManager>& sm) {
317     bool called = false;
318     std::call_once(gSmOnce, [&]() {
319         gDefaultServiceManager = sm;
320         called = true;
321     });
322 
323     if (!called) {
324         LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
325     }
326 }
327 
getServiceManagerShimFromAidlServiceManagerForTests(const sp<AidlServiceManager> & sm)328 sp<IServiceManager> getServiceManagerShimFromAidlServiceManagerForTests(
329         const sp<AidlServiceManager>& sm) {
330     return sp<CppBackendShim>::make(sp<BackendUnifiedServiceManager>::make(sm));
331 }
332 
333 // gAccessorProvidersMutex must be locked already
isInstanceProvidedLocked(const std::string & instance)334 static bool isInstanceProvidedLocked(const std::string& instance) {
335     return gAccessorProviders.end() !=
336             std::find_if(gAccessorProviders.begin(), gAccessorProviders.end(),
337                          [&instance](const AccessorProviderEntry& entry) {
338                              return entry.mProvider->instances().count(instance) > 0;
339                          });
340 }
341 
addAccessorProvider(std::set<std::string> && instances,RpcAccessorProvider && providerCallback)342 std::weak_ptr<AccessorProvider> addAccessorProvider(std::set<std::string>&& instances,
343                                                     RpcAccessorProvider&& providerCallback) {
344     if (instances.empty()) {
345         ALOGE("Set of instances is empty! Need a non empty set of instances to provide for.");
346         return std::weak_ptr<AccessorProvider>();
347     }
348     std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
349     for (const auto& instance : instances) {
350         if (isInstanceProvidedLocked(instance)) {
351             ALOGE("The instance %s is already provided for by a previously added "
352                   "RpcAccessorProvider.",
353                   instance.c_str());
354             return std::weak_ptr<AccessorProvider>();
355         }
356     }
357     std::shared_ptr<AccessorProvider> provider =
358             std::make_shared<AccessorProvider>(std::move(instances), std::move(providerCallback));
359     std::weak_ptr<AccessorProvider> receipt = provider;
360     gAccessorProviders.push_back(AccessorProviderEntry(std::move(provider)));
361 
362     return receipt;
363 }
364 
removeAccessorProvider(std::weak_ptr<AccessorProvider> wProvider)365 status_t removeAccessorProvider(std::weak_ptr<AccessorProvider> wProvider) {
366     std::shared_ptr<AccessorProvider> provider = wProvider.lock();
367     if (provider == nullptr) {
368         ALOGE("The provider supplied to removeAccessorProvider has already been removed or the "
369               "argument to this function was nullptr.");
370         return BAD_VALUE;
371     }
372     std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
373     size_t sizeBefore = gAccessorProviders.size();
374     gAccessorProviders.erase(std::remove_if(gAccessorProviders.begin(), gAccessorProviders.end(),
375                                             [&](AccessorProviderEntry entry) {
376                                                 return entry.mProvider == provider;
377                                             }),
378                              gAccessorProviders.end());
379     if (sizeBefore == gAccessorProviders.size()) {
380         ALOGE("Failed to find an AccessorProvider for removeAccessorProvider");
381         return NAME_NOT_FOUND;
382     }
383 
384     return OK;
385 }
386 
validateAccessor(const String16 & instance,const sp<IBinder> & binder)387 status_t validateAccessor(const String16& instance, const sp<IBinder>& binder) {
388     if (binder == nullptr) {
389         ALOGE("Binder is null");
390         return BAD_VALUE;
391     }
392     sp<IAccessor> accessor = checked_interface_cast<IAccessor>(binder);
393     if (accessor == nullptr) {
394         ALOGE("This binder for %s is not an IAccessor binder", String8(instance).c_str());
395         return BAD_TYPE;
396     }
397     String16 reportedInstance;
398     Status status = accessor->getInstanceName(&reportedInstance);
399     if (!status.isOk()) {
400         ALOGE("Failed to validate the binder being used to create a new ARpc_Accessor for %s with "
401               "status: %s",
402               String8(instance).c_str(), status.toString8().c_str());
403         return NAME_NOT_FOUND;
404     }
405     if (reportedInstance != instance) {
406         ALOGE("Instance %s doesn't match the Accessor's instance of %s", String8(instance).c_str(),
407               String8(reportedInstance).c_str());
408         return NAME_NOT_FOUND;
409     }
410     return OK;
411 }
412 
createAccessor(const String16 & instance,RpcSocketAddressProvider && connectionInfoProvider)413 sp<IBinder> createAccessor(const String16& instance,
414                            RpcSocketAddressProvider&& connectionInfoProvider) {
415     // Try to create a new accessor
416     if (!connectionInfoProvider) {
417         ALOGE("Could not find an Accessor for %s and no ConnectionInfoProvider provided to "
418               "create a new one",
419               String8(instance).c_str());
420         return nullptr;
421     }
422     sp<IBinder> binder = sp<LocalAccessor>::make(instance, std::move(connectionInfoProvider));
423     return binder;
424 }
425 
delegateAccessor(const String16 & name,const sp<IBinder> & accessor,sp<IBinder> * delegator)426 status_t delegateAccessor(const String16& name, const sp<IBinder>& accessor,
427                           sp<IBinder>* delegator) {
428     LOG_ALWAYS_FATAL_IF(delegator == nullptr, "delegateAccessor called with a null out param");
429     if (accessor == nullptr) {
430         ALOGW("Accessor argument to delegateAccessor is null.");
431         *delegator = nullptr;
432         return OK;
433     }
434     status_t status = validateAccessor(name, accessor);
435     if (status != OK) {
436         ALOGE("The provided accessor binder is not an IAccessor for instance %s. Status: "
437               "%s",
438               String8(name).c_str(), statusToString(status).c_str());
439         return status;
440     }
441     // validateAccessor already called checked_interface_cast and made sure this
442     // is a valid accessor object.
443     *delegator = sp<android::os::IAccessorDelegator>::make(interface_cast<IAccessor>(accessor));
444 
445     return OK;
446 }
447 
448 #if !defined(__ANDROID_VNDK__)
449 // IPermissionController is not accessible to vendors
450 
checkCallingPermission(const String16 & permission)451 bool checkCallingPermission(const String16& permission)
452 {
453     return checkCallingPermission(permission, nullptr, nullptr);
454 }
455 
456 static StaticString16 _permission(u"permission");
457 
checkCallingPermission(const String16 & permission,int32_t * outPid,int32_t * outUid)458 bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
459 {
460     IPCThreadState* ipcState = IPCThreadState::self();
461     pid_t pid = ipcState->getCallingPid();
462     uid_t uid = ipcState->getCallingUid();
463     if (outPid) *outPid = pid;
464     if (outUid) *outUid = uid;
465     return checkPermission(permission, pid, uid);
466 }
467 
checkPermission(const String16 & permission,pid_t pid,uid_t uid,bool logPermissionFailure)468 bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
469     static std::mutex gPermissionControllerLock;
470     static sp<IPermissionController> gPermissionController;
471 
472     sp<IPermissionController> pc;
473     gPermissionControllerLock.lock();
474     pc = gPermissionController;
475     gPermissionControllerLock.unlock();
476 
477     auto startTime = std::chrono::steady_clock::now().min();
478 
479     while (true) {
480         if (pc != nullptr) {
481             bool res = pc->checkPermission(permission, pid, uid);
482             if (res) {
483                 if (startTime != startTime.min()) {
484                     const auto waitTime = std::chrono::steady_clock::now() - startTime;
485                     ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
486                           to_ms(waitTime), String8(permission).c_str(), uid, pid);
487                 }
488                 return res;
489             }
490 
491             // Is this a permission failure, or did the controller go away?
492             if (IInterface::asBinder(pc)->isBinderAlive()) {
493                 if (logPermissionFailure) {
494                     ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
495                           uid, pid);
496                 }
497                 return false;
498             }
499 
500             // Object is dead!
501             gPermissionControllerLock.lock();
502             if (gPermissionController == pc) {
503                 gPermissionController = nullptr;
504             }
505             gPermissionControllerLock.unlock();
506         }
507 
508         // Need to retrieve the permission controller.
509         sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
510         if (binder == nullptr) {
511             // Wait for the permission controller to come back...
512             if (startTime == startTime.min()) {
513                 startTime = std::chrono::steady_clock::now();
514                 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
515                       String8(permission).c_str(), uid, pid);
516             }
517             sleep(1);
518         } else {
519             pc = interface_cast<IPermissionController>(binder);
520             // Install the new permission controller, and try again.
521             gPermissionControllerLock.lock();
522             gPermissionController = pc;
523             gPermissionControllerLock.unlock();
524         }
525     }
526 }
527 
528 #endif //__ANDROID_VNDK__
529 
openDeclaredPassthroughHal(const String16 & interface,const String16 & instance,int flag)530 void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
531 #if defined(__ANDROID__) && !defined(__ANDROID_VENDOR__) && !defined(__ANDROID_RECOVERY__) && \
532         !defined(__ANDROID_NATIVE_BRIDGE__)
533     sp<IServiceManager> sm = defaultServiceManager();
534     String16 name = interface + String16("/") + instance;
535     if (!sm->isDeclared(name)) {
536         return nullptr;
537     }
538     String16 libraryName = interface + String16(".") + instance + String16(".so");
539     if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
540         return AApexSupport_loadLibrary(String8(libraryName).c_str(),
541                                         String8(*updatableViaApex).c_str(), flag);
542     }
543     return android_load_sphal_library(String8(libraryName).c_str(), flag);
544 #else
545     (void)interface;
546     (void)instance;
547     (void)flag;
548     return nullptr;
549 #endif
550 }
551 
552 // ----------------------------------------------------------------------
553 
CppBackendShim(const sp<BackendUnifiedServiceManager> & impl)554 CppBackendShim::CppBackendShim(const sp<BackendUnifiedServiceManager>& impl)
555       : mUnifiedServiceManager(impl) {}
556 
557 // This implementation could be simplified and made more efficient by delegating
558 // to waitForService. However, this changes the threading structure in some
559 // cases and could potentially break prebuilts. Once we have higher logistical
560 // complexity, this could be attempted.
getService(const String16 & name) const561 sp<IBinder> CppBackendShim::getService(const String16& name) const {
562     static bool gSystemBootCompleted = false;
563 
564     sp<IBinder> svc = checkService(name);
565     if (svc != nullptr) return svc;
566 
567     sp<ProcessState> self = ProcessState::selfOrNull();
568     const bool isVendorService =
569             self && strcmp(self->getDriverName().c_str(), "/dev/vndbinder") == 0;
570     constexpr auto timeout = 5s;
571     const auto startTime = std::chrono::steady_clock::now();
572     // Vendor code can't access system properties
573     if (!gSystemBootCompleted && !isVendorService) {
574 #ifdef __ANDROID__
575         char bootCompleted[PROPERTY_VALUE_MAX];
576         property_get("sys.boot_completed", bootCompleted, "0");
577         gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
578 #else
579         gSystemBootCompleted = true;
580 #endif
581     }
582     // retry interval in millisecond; note that vendor services stay at 100ms
583     const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
584 
585     ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
586           self ? self->getDriverName().c_str() : "RPC accessors only");
587 
588     int n = 0;
589     while (std::chrono::steady_clock::now() - startTime < timeout) {
590         n++;
591         usleep(1000*sleepTime);
592 
593         sp<IBinder> svc = checkService(name);
594         if (svc != nullptr) {
595             const auto waitTime = std::chrono::steady_clock::now() - startTime;
596             ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
597                   String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
598                   to_ms(waitTime));
599             return svc;
600         }
601     }
602     ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
603     return nullptr;
604 }
605 
checkService(const String16 & name) const606 sp<IBinder> CppBackendShim::checkService(const String16& name) const {
607     Service ret;
608     if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
609         return nullptr;
610     }
611     return ret.get<Service::Tag::serviceWithMetadata>().service;
612 }
613 
addService(const String16 & name,const sp<IBinder> & service,bool allowIsolated,int dumpsysPriority)614 status_t CppBackendShim::addService(const String16& name, const sp<IBinder>& service,
615                                     bool allowIsolated, int dumpsysPriority) {
616     Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
617                                                        allowIsolated, dumpsysPriority);
618     return status.exceptionCode();
619 }
620 
listServices(int dumpsysPriority)621 Vector<String16> CppBackendShim::listServices(int dumpsysPriority) {
622     std::vector<std::string> ret;
623     if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
624         return {};
625     }
626 
627     Vector<String16> res;
628     res.setCapacity(ret.size());
629     for (const std::string& name : ret) {
630         res.push(String16(name.c_str()));
631     }
632     return res;
633 }
634 
waitForService(const String16 & name16)635 sp<IBinder> CppBackendShim::waitForService(const String16& name16) {
636     class Waiter : public android::os::BnServiceCallback {
637         Status onRegistration(const std::string& /*name*/,
638                               const sp<IBinder>& binder) override {
639             std::unique_lock<std::mutex> lock(mMutex);
640             mBinder = binder;
641             lock.unlock();
642             // Flushing here helps ensure the service's ref count remains accurate
643             IPCThreadState::self()->flushCommands();
644             mCv.notify_one();
645             return Status::ok();
646         }
647     public:
648         sp<IBinder> mBinder;
649         std::mutex mMutex;
650         std::condition_variable mCv;
651     };
652 
653     // Simple RAII object to ensure a function call immediately before going out of scope
654     class Defer {
655     public:
656         explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
657         ~Defer() { mF(); }
658     private:
659         std::function<void()> mF;
660     };
661 
662     const std::string name = String8(name16).c_str();
663 
664     sp<IBinder> out;
665     if (Status status = realGetService(name, &out); !status.isOk()) {
666         ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
667               status.toString8().c_str());
668         sp<ProcessState> self = ProcessState::selfOrNull();
669         if (self && 0 == self->getThreadPoolMaxTotalThreadCount()) {
670             ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
671                   "Threadpool has 0 guaranteed threads. "
672                   "Is the threadpool configured properly? "
673                   "See ProcessState::startThreadPool and "
674                   "ProcessState::setThreadPoolMaxThreadCount.");
675         }
676         return nullptr;
677     }
678     if (out != nullptr) return out;
679 
680     sp<Waiter> waiter = sp<Waiter>::make();
681     if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
682         !status.isOk()) {
683         ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
684               status.toString8().c_str());
685         return nullptr;
686     }
687     Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
688 
689     while(true) {
690         {
691             // It would be really nice if we could read binder commands on this
692             // thread instead of needing a threadpool to be started, but for
693             // instance, if we call getAndExecuteCommand, it might be the case
694             // that another thread serves the callback, and we never get a
695             // command, so we hang indefinitely.
696             std::unique_lock<std::mutex> lock(waiter->mMutex);
697             waiter->mCv.wait_for(lock, 1s, [&] {
698                 return waiter->mBinder != nullptr;
699             });
700             if (waiter->mBinder != nullptr) return waiter->mBinder;
701         }
702 
703         sp<ProcessState> self = ProcessState::selfOrNull();
704         ALOGW("Waited one second for %s (is service started? Number of threads started in the "
705               "threadpool: %zu. Are binder threads started and available?)",
706               name.c_str(), self ? self->getThreadPoolMaxTotalThreadCount() : 0);
707 
708         // Handle race condition for lazy services. Here is what can happen:
709         // - the service dies (not processed by init yet).
710         // - sm processes death notification.
711         // - sm gets getService and calls init to start service.
712         // - init gets the start signal, but the service already appears
713         //   started, so it does nothing.
714         // - init gets death signal, but doesn't know it needs to restart
715         //   the service
716         // - we need to request service again to get it to start
717         if (Status status = realGetService(name, &out); !status.isOk()) {
718             ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
719                   status.toString8().c_str());
720             return nullptr;
721         }
722         if (out != nullptr) return out;
723     }
724 }
725 
isDeclared(const String16 & name)726 bool CppBackendShim::isDeclared(const String16& name) {
727     bool declared;
728     if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
729         !status.isOk()) {
730         ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
731               status.toString8().c_str());
732         return false;
733     }
734     return declared;
735 }
736 
getDeclaredInstances(const String16 & interface)737 Vector<String16> CppBackendShim::getDeclaredInstances(const String16& interface) {
738     std::vector<std::string> out;
739     if (Status status =
740                 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
741         !status.isOk()) {
742         ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
743               status.toString8().c_str());
744         return {};
745     }
746 
747     Vector<String16> res;
748     res.setCapacity(out.size());
749     for (const std::string& instance : out) {
750         res.push(String16(instance.c_str()));
751     }
752     return res;
753 }
754 
updatableViaApex(const String16 & name)755 std::optional<String16> CppBackendShim::updatableViaApex(const String16& name) {
756     std::optional<std::string> declared;
757     if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
758         !status.isOk()) {
759         ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
760               status.toString8().c_str());
761         return std::nullopt;
762     }
763     return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
764 }
765 
getUpdatableNames(const String16 & apexName)766 Vector<String16> CppBackendShim::getUpdatableNames(const String16& apexName) {
767     std::vector<std::string> out;
768     if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
769         !status.isOk()) {
770         ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
771               status.toString8().c_str());
772         return {};
773     }
774 
775     Vector<String16> res;
776     res.setCapacity(out.size());
777     for (const std::string& instance : out) {
778         res.push(String16(instance.c_str()));
779     }
780     return res;
781 }
782 
getConnectionInfo(const String16 & name)783 std::optional<IServiceManager::ConnectionInfo> CppBackendShim::getConnectionInfo(
784         const String16& name) {
785     std::optional<os::ConnectionInfo> connectionInfo;
786     if (Status status =
787                 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
788         !status.isOk()) {
789         ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
790               status.toString8().c_str());
791     }
792     return connectionInfo.has_value()
793             ? std::make_optional<IServiceManager::ConnectionInfo>(
794                       {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
795             : std::nullopt;
796 }
797 
registerForNotifications(const String16 & name,const sp<AidlRegistrationCallback> & cb)798 status_t CppBackendShim::registerForNotifications(const String16& name,
799                                                   const sp<AidlRegistrationCallback>& cb) {
800     if (cb == nullptr) {
801         ALOGE("%s: null cb passed", __FUNCTION__);
802         return BAD_VALUE;
803     }
804     std::string nameStr = String8(name).c_str();
805     sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
806     std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
807     if (Status status =
808                 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
809         !status.isOk()) {
810         ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
811               status.toString8().c_str());
812         return UNKNOWN_ERROR;
813     }
814     mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
815     return OK;
816 }
817 
removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback> & cb,ServiceCallbackMap::iterator * it,sp<RegistrationWaiter> * waiter)818 void CppBackendShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
819                                                       ServiceCallbackMap::iterator* it,
820                                                       sp<RegistrationWaiter>* waiter) {
821     std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
822     for (auto lit = localRegistrationAndWaiters.begin();
823          lit != localRegistrationAndWaiters.end();) {
824         if (lit->first == cb) {
825             if (waiter) {
826                 *waiter = lit->second;
827             }
828             lit = localRegistrationAndWaiters.erase(lit);
829         } else {
830             ++lit;
831         }
832     }
833 
834     if (localRegistrationAndWaiters.empty()) {
835         mNameToRegistrationCallback.erase(*it);
836     }
837 }
838 
unregisterForNotifications(const String16 & name,const sp<AidlRegistrationCallback> & cb)839 status_t CppBackendShim::unregisterForNotifications(const String16& name,
840                                                     const sp<AidlRegistrationCallback>& cb) {
841     if (cb == nullptr) {
842         ALOGE("%s: null cb passed", __FUNCTION__);
843         return BAD_VALUE;
844     }
845     std::string nameStr = String8(name).c_str();
846     std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
847     auto it = mNameToRegistrationCallback.find(nameStr);
848     sp<RegistrationWaiter> registrationWaiter;
849     if (it != mNameToRegistrationCallback.end()) {
850         removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
851     } else {
852         ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
853         return BAD_VALUE;
854     }
855     if (registrationWaiter == nullptr) {
856         ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
857         return BAD_VALUE;
858     }
859     if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
860                                                                            registrationWaiter);
861         !status.isOk()) {
862         ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
863               String8(name).c_str(), status.toString8().c_str());
864         return UNKNOWN_ERROR;
865     }
866     return OK;
867 }
868 
getServiceDebugInfo()869 std::vector<IServiceManager::ServiceDebugInfo> CppBackendShim::getServiceDebugInfo() {
870     std::vector<os::ServiceDebugInfo> serviceDebugInfos;
871     std::vector<IServiceManager::ServiceDebugInfo> ret;
872     if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
873         !status.isOk()) {
874         ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
875         return ret;
876     }
877     for (const auto& serviceDebugInfo : serviceDebugInfos) {
878         IServiceManager::ServiceDebugInfo retInfo;
879         retInfo.pid = serviceDebugInfo.debugPid;
880         retInfo.name = serviceDebugInfo.name;
881         ret.emplace_back(retInfo);
882     }
883     return ret;
884 }
885 
886 #ifndef __ANDROID__
887 // CppBackendShim for host. Implements the old libbinder android::IServiceManager API.
888 // The internal implementation of the AIDL interface android::os::IServiceManager calls into
889 // on-device service manager.
890 class CppServiceManagerHostShim : public CppBackendShim {
891 public:
CppServiceManagerHostShim(const sp<AidlServiceManager> & impl,const RpcDelegateServiceManagerOptions & options)892     CppServiceManagerHostShim(const sp<AidlServiceManager>& impl,
893                               const RpcDelegateServiceManagerOptions& options)
894           : CppBackendShim(sp<BackendUnifiedServiceManager>::make(impl)), mOptions(options) {}
895     // CppBackendShim::getService is based on checkService, so no need to override it.
checkService(const String16 & name) const896     sp<IBinder> checkService(const String16& name) const override {
897         return getDeviceService({String8(name).c_str()}, mOptions);
898     }
899 
900 protected:
901     // Override realGetService for CppBackendShim::waitForService.
realGetService(const std::string & name,sp<IBinder> * _aidl_return)902     Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
903         *_aidl_return = getDeviceService({"-g", name}, mOptions);
904         return Status::ok();
905     }
906 
907 private:
908     RpcDelegateServiceManagerOptions mOptions;
909 };
createRpcDelegateServiceManager(const RpcDelegateServiceManagerOptions & options)910 sp<IServiceManager> createRpcDelegateServiceManager(
911         const RpcDelegateServiceManagerOptions& options) {
912     auto binder = getDeviceService({"manager"}, options);
913     if (binder == nullptr) {
914         ALOGE("getDeviceService(\"manager\") returns null");
915         return nullptr;
916     }
917     auto interface = AidlServiceManager::asInterface(binder);
918     if (interface == nullptr) {
919         ALOGE("getDeviceService(\"manager\") returns non service manager");
920         return nullptr;
921     }
922     return sp<CppServiceManagerHostShim>::make(interface, options);
923 }
924 #endif
925 
926 } // namespace android
927