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