blob: 411163257cad87e38b0415aa6bcd6ed690b5c962 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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
Steven Moreland85d985c2022-09-12 20:57:51 +000017#define LOG_TAG "ServiceManagerCppClient"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080018
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070019#include <binder/IServiceManager.h>
Tomasz Wasilczykfe25f122024-06-26 12:45:57 -070020#include "BackendUnifiedServiceManager.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021
Tom Cherry8fda97f2020-07-22 17:15:44 -070022#include <inttypes.h>
23#include <unistd.h>
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070024#include <chrono>
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -070025#include <condition_variable>
Tom Cherry8fda97f2020-07-22 17:15:44 -070026
Steven Moreland454bfd92022-07-20 20:53:36 +000027#include <android-base/properties.h>
Steven Moreland1c47b582019-08-27 18:05:27 -070028#include <android/os/BnServiceCallback.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070029#include <android/os/IServiceManager.h>
Mathias Agopian375f5632009-06-15 18:24:59 -070030#include <binder/IPCThreadState.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070031#include <binder/Parcel.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070032#include <utils/String8.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070033
Jiyong Park47f876b2018-04-17 13:56:46 +090034#ifndef __ANDROID_VNDK__
35#include <binder/IPermissionController.h>
36#endif
Steven Moreland28723ae2019-04-01 18:52:30 -070037
Steven Morelanded3b5632019-09-20 11:24:28 -070038#ifdef __ANDROID__
Yunfan Chen788e1c42018-03-29 16:52:09 +090039#include <cutils/properties.h>
Yifan Hongf7760012021-06-04 16:04:42 -070040#else
41#include "ServiceManagerHost.h"
Steven Moreland28723ae2019-04-01 18:52:30 -070042#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080043
Jooyung Han75fc06f2024-02-03 03:56:59 +090044#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
45#include <android/apexsupport.h>
46#include <vndksupport/linker.h>
47#endif
48
Steven Morelanda4853cd2019-07-12 15:44:37 -070049#include "Static.h"
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070050#include "Utils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052namespace android {
53
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070054using namespace std::chrono_literals;
55
Jayant Chowdhary30700942022-01-31 14:12:40 -080056using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
57
Steven Moreland80e1e6d2019-06-21 12:35:59 -070058using AidlServiceManager = android::os::IServiceManager;
59using android::binder::Status;
60
Steven Moreland635a2912019-10-02 15:50:10 -070061// libbinder's IServiceManager.h can't rely on the values generated by AIDL
62// because many places use its headers via include_dirs (meaning, without
63// declaring the dependency in the build system). So, for now, we can just check
64// the values here.
65static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
66static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
67static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
68static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
69static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
70static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
71
Steven Moreland583685e2019-10-02 16:45:11 -070072const String16& IServiceManager::getInterfaceDescriptor() const {
73 return AidlServiceManager::descriptor;
74}
75IServiceManager::IServiceManager() {}
76IServiceManager::~IServiceManager() {}
77
78// From the old libbinder IServiceManager interface to IServiceManager.
79class ServiceManagerShim : public IServiceManager
80{
81public:
82 explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
83
84 sp<IBinder> getService(const String16& name) const override;
85 sp<IBinder> checkService(const String16& name) const override;
86 status_t addService(const String16& name, const sp<IBinder>& service,
87 bool allowIsolated, int dumpsysPriority) override;
88 Vector<String16> listServices(int dumpsysPriority) override;
89 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070090 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +000091 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +000092 std::optional<String16> updatableViaApex(const String16& name) override;
Jooyung Han76944fe2022-10-25 17:02:45 +090093 Vector<String16> getUpdatableNames(const String16& apexName) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +000094 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -080095 class RegistrationWaiter : public android::os::BnServiceCallback {
96 public:
97 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
98 : mImpl(callback) {}
99 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
100 mImpl->onServiceRegistration(String16(name.c_str()), binder);
101 return Status::ok();
102 }
Steven Moreland583685e2019-10-02 16:45:11 -0700103
Jayant Chowdhary30700942022-01-31 14:12:40 -0800104 private:
105 sp<AidlRegistrationCallback> mImpl;
106 };
107
108 status_t registerForNotifications(const String16& service,
109 const sp<AidlRegistrationCallback>& cb) override;
110
111 status_t unregisterForNotifications(const String16& service,
112 const sp<AidlRegistrationCallback>& cb) override;
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000113
114 std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
Steven Moreland583685e2019-10-02 16:45:11 -0700115 // for legacy ABI
116 const String16& getInterfaceDescriptor() const override {
Parth Sane56a04712024-04-22 14:21:07 +0000117 return mUnifiedServiceManager->getInterfaceDescriptor();
Steven Moreland583685e2019-10-02 16:45:11 -0700118 }
Parth Sane56a04712024-04-22 14:21:07 +0000119 IBinder* onAsBinder() override { return IInterface::asBinder(mUnifiedServiceManager).get(); }
Yifan Hongf7760012021-06-04 16:04:42 -0700120
121protected:
Parth Sane56a04712024-04-22 14:21:07 +0000122 sp<BackendUnifiedServiceManager> mUnifiedServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800123 // AidlRegistrationCallback -> services that its been registered for
124 // notifications.
125 using LocalRegistrationAndWaiter =
126 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
127 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
128 ServiceCallbackMap mNameToRegistrationCallback;
129 std::mutex mNameToRegistrationLock;
130
131 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
132 ServiceCallbackMap::iterator* it,
133 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700134
135 // Directly get the service in a way that, for lazy services, requests the service to be started
136 // if it is not currently started. This way, calls directly to ServiceManagerShim::getService
137 // will still have the 5s delay that is expected by a large amount of Android code.
138 //
139 // When implementing ServiceManagerShim, use realGetService instead of
Parth Sane56a04712024-04-22 14:21:07 +0000140 // mUnifiedServiceManager->getService so that it can be overridden in ServiceManagerHostShim.
Yifan Hongf7760012021-06-04 16:04:42 -0700141 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Parth Sane56a04712024-04-22 14:21:07 +0000142 return mUnifiedServiceManager->getService(name, _aidl_return);
Yifan Hongf7760012021-06-04 16:04:42 -0700143 }
Steven Moreland583685e2019-10-02 16:45:11 -0700144};
145
Steven Moreland1698ffd2020-05-15 23:43:52 +0000146[[clang::no_destroy]] static std::once_flag gSmOnce;
147[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Brett Chabot38dbade2020-01-24 12:59:43 -0800148
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800149sp<IServiceManager> defaultServiceManager()
150{
Martijn Coenen402c8672020-02-03 10:01:36 +0100151 std::call_once(gSmOnce, []() {
Parth Sane56a04712024-04-22 14:21:07 +0000152 gDefaultServiceManager = sp<ServiceManagerShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100153 });
Daniel Eratc2832702015-10-13 15:29:32 -0600154
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 return gDefaultServiceManager;
156}
157
Brett Chabot38dbade2020-01-24 12:59:43 -0800158void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100159 bool called = false;
160 std::call_once(gSmOnce, [&]() {
161 gDefaultServiceManager = sm;
162 called = true;
163 });
164
165 if (!called) {
166 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
167 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800168}
169
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400170#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900171// IPermissionController is not accessible to vendors
172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173bool checkCallingPermission(const String16& permission)
174{
Yi Kongfdd8da92018-06-07 17:52:27 -0700175 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176}
177
Steven Moreland1b264072021-06-03 23:04:02 +0000178static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700179
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800180bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
181{
182 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700183 pid_t pid = ipcState->getCallingPid();
184 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700186 if (outUid) *outUid = uid;
187 return checkPermission(permission, pid, uid);
188}
189
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000190bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700191 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700192 static sp<IPermissionController> gPermissionController;
193
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700195 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700197 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600198
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700199 auto startTime = std::chrono::steady_clock::now().min();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200
201 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700202 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 bool res = pc->checkPermission(permission, pid, uid);
204 if (res) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700205 if (startTime != startTime.min()) {
206 const auto waitTime = std::chrono::steady_clock::now() - startTime;
207 ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
208 to_ms(waitTime), String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209 }
210 return res;
211 }
Daniel Eratc2832702015-10-13 15:29:32 -0600212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800214 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000215 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000216 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000217 uid, pid);
218 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219 return false;
220 }
Daniel Eratc2832702015-10-13 15:29:32 -0600221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700223 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700225 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700227 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 }
Daniel Eratc2832702015-10-13 15:29:32 -0600229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 // Need to retrieve the permission controller.
231 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700232 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 // Wait for the permission controller to come back...
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700234 if (startTime == startTime.min()) {
235 startTime = std::chrono::steady_clock::now();
Steve Blocka19954a2012-01-04 20:05:49 +0000236 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000237 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 }
239 sleep(1);
240 } else {
241 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600242 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700243 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700245 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 }
247 }
248}
249
Steven Moreland576662a2024-08-09 23:12:03 +0000250#endif //__ANDROID_VNDK__
251
Jooyung Han75fc06f2024-02-03 03:56:59 +0900252void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
Steven Moreland576662a2024-08-09 23:12:03 +0000253#if defined(__ANDROID__) && !defined(__ANDROID_VENDOR__) && !defined(__ANDROID_RECOVERY__) && \
254 !defined(__ANDROID_NATIVE_BRIDGE__)
Jooyung Han75fc06f2024-02-03 03:56:59 +0900255 sp<IServiceManager> sm = defaultServiceManager();
256 String16 name = interface + String16("/") + instance;
257 if (!sm->isDeclared(name)) {
258 return nullptr;
259 }
260 String16 libraryName = interface + String16(".") + instance + String16(".so");
261 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
262 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
263 String8(*updatableViaApex).c_str(), flag);
264 }
265 return android_load_sphal_library(String8(libraryName).c_str(), flag);
266#else
267 (void)interface;
268 (void)instance;
269 (void)flag;
270 return nullptr;
271#endif
272}
273
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274// ----------------------------------------------------------------------
275
Parth Sane56a04712024-04-22 14:21:07 +0000276ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl) {
277 mUnifiedServiceManager = sp<BackendUnifiedServiceManager>::make(impl);
278}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700279
Steven Moreland5af7d852020-04-29 15:40:29 -0700280// This implementation could be simplified and made more efficient by delegating
281// to waitForService. However, this changes the threading structure in some
282// cases and could potentially break prebuilts. Once we have higher logistical
283// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700284sp<IBinder> ServiceManagerShim::getService(const String16& name) const
285{
286 static bool gSystemBootCompleted = false;
287
288 sp<IBinder> svc = checkService(name);
289 if (svc != nullptr) return svc;
290
291 const bool isVendorService =
292 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700293 constexpr auto timeout = 5s;
294 const auto startTime = std::chrono::steady_clock::now();
Steven Moreland583685e2019-10-02 16:45:11 -0700295 // Vendor code can't access system properties
296 if (!gSystemBootCompleted && !isVendorService) {
297#ifdef __ANDROID__
298 char bootCompleted[PROPERTY_VALUE_MAX];
299 property_get("sys.boot_completed", bootCompleted, "0");
300 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
301#else
302 gSystemBootCompleted = true;
303#endif
304 }
305 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900306 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700307
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000308 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700309 ProcessState::self()->getDriverName().c_str());
310
Steven Moreland583685e2019-10-02 16:45:11 -0700311 int n = 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700312 while (std::chrono::steady_clock::now() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700313 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700314 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700315
Yunfan Chen788e1c42018-03-29 16:52:09 +0900316 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700317 if (svc != nullptr) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700318 const auto waitTime = std::chrono::steady_clock::now() - startTime;
319 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000320 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700321 to_ms(waitTime));
Tom Cherry8fda97f2020-07-22 17:15:44 -0700322 return svc;
323 }
Steven Moreland583685e2019-10-02 16:45:11 -0700324 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000325 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700326 return nullptr;
327}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900328
Steven Moreland583685e2019-10-02 16:45:11 -0700329sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
330{
331 sp<IBinder> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000332 if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700333 return nullptr;
334 }
335 return ret;
336}
337
338status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
339 bool allowIsolated, int dumpsysPriority)
340{
Parth Sane56a04712024-04-22 14:21:07 +0000341 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
342 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700343 return status.exceptionCode();
344}
345
346Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
347{
348 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000349 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700350 return {};
351 }
352
353 Vector<String16> res;
354 res.setCapacity(ret.size());
355 for (const std::string& name : ret) {
356 res.push(String16(name.c_str()));
357 }
358 return res;
359}
360
361sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
362{
363 class Waiter : public android::os::BnServiceCallback {
364 Status onRegistration(const std::string& /*name*/,
365 const sp<IBinder>& binder) override {
366 std::unique_lock<std::mutex> lock(mMutex);
367 mBinder = binder;
368 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700369 // Flushing here helps ensure the service's ref count remains accurate
370 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700371 mCv.notify_one();
372 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900373 }
Steven Moreland583685e2019-10-02 16:45:11 -0700374 public:
375 sp<IBinder> mBinder;
376 std::mutex mMutex;
377 std::condition_variable mCv;
378 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900379
Jon Spivackfed6db42019-11-18 16:43:59 -0800380 // Simple RAII object to ensure a function call immediately before going out of scope
381 class Defer {
382 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900383 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800384 ~Defer() { mF(); }
385 private:
386 std::function<void()> mF;
387 };
388
Steven Moreland583685e2019-10-02 16:45:11 -0700389 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900390
Steven Moreland583685e2019-10-02 16:45:11 -0700391 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700392 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000393 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
394 status.toString8().c_str());
Elie Kheirallah27c26952022-09-07 21:45:26 +0000395 if (0 == ProcessState::self()->getThreadPoolMaxTotalThreadCount()) {
396 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
397 "Threadpool has 0 guaranteed threads. "
398 "Is the threadpool configured properly? "
399 "See ProcessState::startThreadPool and "
400 "ProcessState::setThreadPoolMaxThreadCount.");
401 }
Steven Moreland583685e2019-10-02 16:45:11 -0700402 return nullptr;
403 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800404 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700405
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000406 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000407 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000408 !status.isOk()) {
409 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
410 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700411 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412 }
Parth Sane56a04712024-04-22 14:21:07 +0000413 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700414
Steven Moreland583685e2019-10-02 16:45:11 -0700415 while(true) {
416 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000417 // It would be really nice if we could read binder commands on this
418 // thread instead of needing a threadpool to be started, but for
419 // instance, if we call getAndExecuteCommand, it might be the case
420 // that another thread serves the callback, and we never get a
421 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700422 std::unique_lock<std::mutex> lock(waiter->mMutex);
Steven Moreland3d37ef22023-04-25 18:25:14 +0000423 waiter->mCv.wait_for(lock, 1s, [&] {
424 return waiter->mBinder != nullptr;
425 });
Steven Moreland583685e2019-10-02 16:45:11 -0700426 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700427 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428
Steven Moreland3d37ef22023-04-25 18:25:14 +0000429 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000430 "threadpool: %zu. Are binder threads started and available?)",
431 name.c_str(), ProcessState::self()->getThreadPoolMaxTotalThreadCount());
Steven Morelandf2677e22020-07-14 19:58:08 +0000432
Steven Moreland583685e2019-10-02 16:45:11 -0700433 // Handle race condition for lazy services. Here is what can happen:
434 // - the service dies (not processed by init yet).
435 // - sm processes death notification.
436 // - sm gets getService and calls init to start service.
437 // - init gets the start signal, but the service already appears
438 // started, so it does nothing.
439 // - init gets death signal, but doesn't know it needs to restart
440 // the service
441 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700442 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000443 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
444 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700445 return nullptr;
446 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800447 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700448 }
Steven Moreland583685e2019-10-02 16:45:11 -0700449}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450
Steven Morelandb82b8f82019-10-28 10:52:34 -0700451bool ServiceManagerShim::isDeclared(const String16& name) {
452 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000453 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000454 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000455 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000456 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700457 return false;
458 }
459 return declared;
460}
461
Steven Moreland2e293aa2020-09-23 00:25:16 +0000462Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
463 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000464 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000465 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000466 !status.isOk()) {
467 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
468 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000469 return {};
470 }
471
472 Vector<String16> res;
473 res.setCapacity(out.size());
474 for (const std::string& instance : out) {
475 res.push(String16(instance.c_str()));
476 }
477 return res;
478}
479
Steven Morelandedd4e072021-04-21 00:27:29 +0000480std::optional<String16> ServiceManagerShim::updatableViaApex(const String16& name) {
481 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000482 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000483 !status.isOk()) {
484 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
485 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000486 return std::nullopt;
487 }
488 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
489}
490
Jooyung Han76944fe2022-10-25 17:02:45 +0900491Vector<String16> ServiceManagerShim::getUpdatableNames(const String16& apexName) {
492 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000493 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900494 !status.isOk()) {
495 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
496 status.toString8().c_str());
497 return {};
498 }
499
500 Vector<String16> res;
501 res.setCapacity(out.size());
502 for (const std::string& instance : out) {
503 res.push(String16(instance.c_str()));
504 }
505 return res;
506}
507
Devin Moore5e4c2f12021-09-09 22:36:33 +0000508std::optional<IServiceManager::ConnectionInfo> ServiceManagerShim::getConnectionInfo(
509 const String16& name) {
510 std::optional<os::ConnectionInfo> connectionInfo;
511 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000512 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000513 !status.isOk()) {
514 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
515 status.toString8().c_str());
516 }
517 return connectionInfo.has_value()
518 ? std::make_optional<IServiceManager::ConnectionInfo>(
519 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
520 : std::nullopt;
521}
522
Jayant Chowdhary30700942022-01-31 14:12:40 -0800523status_t ServiceManagerShim::registerForNotifications(const String16& name,
524 const sp<AidlRegistrationCallback>& cb) {
525 if (cb == nullptr) {
526 ALOGE("%s: null cb passed", __FUNCTION__);
527 return BAD_VALUE;
528 }
529 std::string nameStr = String8(name).c_str();
530 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
531 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
532 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000533 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800534 !status.isOk()) {
535 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
536 status.toString8().c_str());
537 return UNKNOWN_ERROR;
538 }
539 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
540 return OK;
541}
542
543void ServiceManagerShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
544 ServiceCallbackMap::iterator* it,
545 sp<RegistrationWaiter>* waiter) {
546 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
547 for (auto lit = localRegistrationAndWaiters.begin();
548 lit != localRegistrationAndWaiters.end();) {
549 if (lit->first == cb) {
550 if (waiter) {
551 *waiter = lit->second;
552 }
553 lit = localRegistrationAndWaiters.erase(lit);
554 } else {
555 ++lit;
556 }
557 }
558
559 if (localRegistrationAndWaiters.empty()) {
560 mNameToRegistrationCallback.erase(*it);
561 }
562}
563
564status_t ServiceManagerShim::unregisterForNotifications(const String16& name,
565 const sp<AidlRegistrationCallback>& cb) {
566 if (cb == nullptr) {
567 ALOGE("%s: null cb passed", __FUNCTION__);
568 return BAD_VALUE;
569 }
570 std::string nameStr = String8(name).c_str();
571 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
572 auto it = mNameToRegistrationCallback.find(nameStr);
573 sp<RegistrationWaiter> registrationWaiter;
574 if (it != mNameToRegistrationCallback.end()) {
575 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
576 } else {
577 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
578 return BAD_VALUE;
579 }
580 if (registrationWaiter == nullptr) {
581 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
582 return BAD_VALUE;
583 }
Parth Sane56a04712024-04-22 14:21:07 +0000584 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800585 registrationWaiter);
586 !status.isOk()) {
587 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
588 String8(name).c_str(), status.toString8().c_str());
589 return UNKNOWN_ERROR;
590 }
591 return OK;
592}
593
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000594std::vector<IServiceManager::ServiceDebugInfo> ServiceManagerShim::getServiceDebugInfo() {
595 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
596 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000597 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000598 !status.isOk()) {
599 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
600 return ret;
601 }
602 for (const auto& serviceDebugInfo : serviceDebugInfos) {
603 IServiceManager::ServiceDebugInfo retInfo;
604 retInfo.pid = serviceDebugInfo.debugPid;
605 retInfo.name = serviceDebugInfo.name;
606 ret.emplace_back(retInfo);
607 }
608 return ret;
609}
610
Yifan Hongf7760012021-06-04 16:04:42 -0700611#ifndef __ANDROID__
612// ServiceManagerShim for host. Implements the old libbinder android::IServiceManager API.
613// The internal implementation of the AIDL interface android::os::IServiceManager calls into
614// on-device service manager.
615class ServiceManagerHostShim : public ServiceManagerShim {
616public:
Yifan Hong5a05ef72021-10-08 17:33:47 -0700617 ServiceManagerHostShim(const sp<AidlServiceManager>& impl,
618 const RpcDelegateServiceManagerOptions& options)
619 : ServiceManagerShim(impl), mOptions(options) {}
Yifan Hongf7760012021-06-04 16:04:42 -0700620 // ServiceManagerShim::getService is based on checkService, so no need to override it.
621 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700622 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700623 }
624
625protected:
626 // Override realGetService for ServiceManagerShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700627 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700628 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700629 return Status::ok();
630 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700631
632private:
633 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700634};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700635sp<IServiceManager> createRpcDelegateServiceManager(
636 const RpcDelegateServiceManagerOptions& options) {
637 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700638 if (binder == nullptr) {
639 ALOGE("getDeviceService(\"manager\") returns null");
640 return nullptr;
641 }
642 auto interface = AidlServiceManager::asInterface(binder);
643 if (interface == nullptr) {
644 ALOGE("getDeviceService(\"manager\") returns non service manager");
645 return nullptr;
646 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700647 return sp<ServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700648}
649#endif
650
Steven Moreland61ff8492019-09-26 16:05:45 -0700651} // namespace android