blob: 5844c85d213a5fb3c91bd2d2b63238721d4f40d1 [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
Parth Sane56a04712024-04-22 14:21:07 +000019#include <BackendUnifiedServiceManager.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070020#include <binder/IServiceManager.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 Wasilczyke97f3a82024-04-30 10:37:32 -070024#include <condition_variable>
Tom Cherry8fda97f2020-07-22 17:15:44 -070025
Steven Moreland454bfd92022-07-20 20:53:36 +000026#include <android-base/properties.h>
Steven Moreland1c47b582019-08-27 18:05:27 -070027#include <android/os/BnServiceCallback.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070028#include <android/os/IServiceManager.h>
Mathias Agopian375f5632009-06-15 18:24:59 -070029#include <binder/IPCThreadState.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070030#include <binder/Parcel.h>
31#include <utils/Log.h>
32#include <utils/String8.h>
33#include <utils/SystemClock.h>
34
Jiyong Park47f876b2018-04-17 13:56:46 +090035#ifndef __ANDROID_VNDK__
36#include <binder/IPermissionController.h>
37#endif
Steven Moreland28723ae2019-04-01 18:52:30 -070038
Steven Morelanded3b5632019-09-20 11:24:28 -070039#ifdef __ANDROID__
Yunfan Chen788e1c42018-03-29 16:52:09 +090040#include <cutils/properties.h>
Yifan Hongf7760012021-06-04 16:04:42 -070041#else
42#include "ServiceManagerHost.h"
Steven Moreland28723ae2019-04-01 18:52:30 -070043#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080044
Jooyung Han75fc06f2024-02-03 03:56:59 +090045#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
46#include <android/apexsupport.h>
47#include <vndksupport/linker.h>
48#endif
49
Steven Morelanda4853cd2019-07-12 15:44:37 -070050#include "Static.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
Jayant Chowdhary30700942022-01-31 14:12:40 -080054using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
55
Steven Moreland80e1e6d2019-06-21 12:35:59 -070056using AidlServiceManager = android::os::IServiceManager;
57using android::binder::Status;
58
Steven Moreland635a2912019-10-02 15:50:10 -070059// libbinder's IServiceManager.h can't rely on the values generated by AIDL
60// because many places use its headers via include_dirs (meaning, without
61// declaring the dependency in the build system). So, for now, we can just check
62// the values here.
63static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
64static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
65static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
66static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
67static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
68static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
69
Steven Moreland583685e2019-10-02 16:45:11 -070070const String16& IServiceManager::getInterfaceDescriptor() const {
71 return AidlServiceManager::descriptor;
72}
73IServiceManager::IServiceManager() {}
74IServiceManager::~IServiceManager() {}
75
76// From the old libbinder IServiceManager interface to IServiceManager.
77class ServiceManagerShim : public IServiceManager
78{
79public:
80 explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
81
82 sp<IBinder> getService(const String16& name) const override;
83 sp<IBinder> checkService(const String16& name) const override;
84 status_t addService(const String16& name, const sp<IBinder>& service,
85 bool allowIsolated, int dumpsysPriority) override;
86 Vector<String16> listServices(int dumpsysPriority) override;
87 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070088 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +000089 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +000090 std::optional<String16> updatableViaApex(const String16& name) override;
Jooyung Han76944fe2022-10-25 17:02:45 +090091 Vector<String16> getUpdatableNames(const String16& apexName) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +000092 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -080093 class RegistrationWaiter : public android::os::BnServiceCallback {
94 public:
95 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
96 : mImpl(callback) {}
97 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
98 mImpl->onServiceRegistration(String16(name.c_str()), binder);
99 return Status::ok();
100 }
Steven Moreland583685e2019-10-02 16:45:11 -0700101
Jayant Chowdhary30700942022-01-31 14:12:40 -0800102 private:
103 sp<AidlRegistrationCallback> mImpl;
104 };
105
106 status_t registerForNotifications(const String16& service,
107 const sp<AidlRegistrationCallback>& cb) override;
108
109 status_t unregisterForNotifications(const String16& service,
110 const sp<AidlRegistrationCallback>& cb) override;
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000111
112 std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
Steven Moreland583685e2019-10-02 16:45:11 -0700113 // for legacy ABI
114 const String16& getInterfaceDescriptor() const override {
Parth Sane56a04712024-04-22 14:21:07 +0000115 return mUnifiedServiceManager->getInterfaceDescriptor();
Steven Moreland583685e2019-10-02 16:45:11 -0700116 }
Parth Sane56a04712024-04-22 14:21:07 +0000117 IBinder* onAsBinder() override { return IInterface::asBinder(mUnifiedServiceManager).get(); }
Yifan Hongf7760012021-06-04 16:04:42 -0700118
119protected:
Parth Sane56a04712024-04-22 14:21:07 +0000120 sp<BackendUnifiedServiceManager> mUnifiedServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800121 // AidlRegistrationCallback -> services that its been registered for
122 // notifications.
123 using LocalRegistrationAndWaiter =
124 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
125 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
126 ServiceCallbackMap mNameToRegistrationCallback;
127 std::mutex mNameToRegistrationLock;
128
129 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
130 ServiceCallbackMap::iterator* it,
131 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700132
133 // Directly get the service in a way that, for lazy services, requests the service to be started
134 // if it is not currently started. This way, calls directly to ServiceManagerShim::getService
135 // will still have the 5s delay that is expected by a large amount of Android code.
136 //
137 // When implementing ServiceManagerShim, use realGetService instead of
Parth Sane56a04712024-04-22 14:21:07 +0000138 // mUnifiedServiceManager->getService so that it can be overridden in ServiceManagerHostShim.
Yifan Hongf7760012021-06-04 16:04:42 -0700139 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Parth Sane56a04712024-04-22 14:21:07 +0000140 return mUnifiedServiceManager->getService(name, _aidl_return);
Yifan Hongf7760012021-06-04 16:04:42 -0700141 }
Steven Moreland583685e2019-10-02 16:45:11 -0700142};
143
Steven Moreland1698ffd2020-05-15 23:43:52 +0000144[[clang::no_destroy]] static std::once_flag gSmOnce;
145[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Brett Chabot38dbade2020-01-24 12:59:43 -0800146
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800147sp<IServiceManager> defaultServiceManager()
148{
Martijn Coenen402c8672020-02-03 10:01:36 +0100149 std::call_once(gSmOnce, []() {
Parth Sane56a04712024-04-22 14:21:07 +0000150 gDefaultServiceManager = sp<ServiceManagerShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100151 });
Daniel Eratc2832702015-10-13 15:29:32 -0600152
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800153 return gDefaultServiceManager;
154}
155
Brett Chabot38dbade2020-01-24 12:59:43 -0800156void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100157 bool called = false;
158 std::call_once(gSmOnce, [&]() {
159 gDefaultServiceManager = sm;
160 called = true;
161 });
162
163 if (!called) {
164 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
165 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800166}
167
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400168#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900169// IPermissionController is not accessible to vendors
170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171bool checkCallingPermission(const String16& permission)
172{
Yi Kongfdd8da92018-06-07 17:52:27 -0700173 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174}
175
Steven Moreland1b264072021-06-03 23:04:02 +0000176static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
179{
180 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700181 pid_t pid = ipcState->getCallingPid();
182 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700184 if (outUid) *outUid = uid;
185 return checkPermission(permission, pid, uid);
186}
187
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000188bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700189 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700190 static sp<IPermissionController> gPermissionController;
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700193 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700195 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 int64_t startTime = 0;
198
199 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700200 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 bool res = pc->checkPermission(permission, pid, uid);
202 if (res) {
203 if (startTime != 0) {
Steve Blocka19954a2012-01-04 20:05:49 +0000204 ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000205 (int)((uptimeMillis() - startTime) / 1000), String8(permission).c_str(),
206 uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207 }
208 return res;
209 }
Daniel Eratc2832702015-10-13 15:29:32 -0600210
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800212 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000213 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000214 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000215 uid, pid);
216 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217 return false;
218 }
Daniel Eratc2832702015-10-13 15:29:32 -0600219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700221 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700223 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700225 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 }
Daniel Eratc2832702015-10-13 15:29:32 -0600227
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 // Need to retrieve the permission controller.
229 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700230 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // Wait for the permission controller to come back...
232 if (startTime == 0) {
233 startTime = uptimeMillis();
Steve Blocka19954a2012-01-04 20:05:49 +0000234 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000235 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 }
237 sleep(1);
238 } else {
239 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600240 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700241 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800242 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700243 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 }
245 }
246}
247
Jooyung Han75fc06f2024-02-03 03:56:59 +0900248void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
249#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
250 sp<IServiceManager> sm = defaultServiceManager();
251 String16 name = interface + String16("/") + instance;
252 if (!sm->isDeclared(name)) {
253 return nullptr;
254 }
255 String16 libraryName = interface + String16(".") + instance + String16(".so");
256 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
257 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
258 String8(*updatableViaApex).c_str(), flag);
259 }
260 return android_load_sphal_library(String8(libraryName).c_str(), flag);
261#else
262 (void)interface;
263 (void)instance;
264 (void)flag;
265 return nullptr;
266#endif
267}
268
Jiyong Park47f876b2018-04-17 13:56:46 +0900269#endif //__ANDROID_VNDK__
270
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800271// ----------------------------------------------------------------------
272
Parth Sane56a04712024-04-22 14:21:07 +0000273ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl) {
274 mUnifiedServiceManager = sp<BackendUnifiedServiceManager>::make(impl);
275}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700276
Steven Moreland5af7d852020-04-29 15:40:29 -0700277// This implementation could be simplified and made more efficient by delegating
278// to waitForService. However, this changes the threading structure in some
279// cases and could potentially break prebuilts. Once we have higher logistical
280// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700281sp<IBinder> ServiceManagerShim::getService(const String16& name) const
282{
283 static bool gSystemBootCompleted = false;
284
285 sp<IBinder> svc = checkService(name);
286 if (svc != nullptr) return svc;
287
288 const bool isVendorService =
289 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Jiyong Park16c6e702020-11-13 20:53:12 +0900290 constexpr int64_t timeout = 5000;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700291 int64_t startTime = uptimeMillis();
Steven Moreland583685e2019-10-02 16:45:11 -0700292 // Vendor code can't access system properties
293 if (!gSystemBootCompleted && !isVendorService) {
294#ifdef __ANDROID__
295 char bootCompleted[PROPERTY_VALUE_MAX];
296 property_get("sys.boot_completed", bootCompleted, "0");
297 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
298#else
299 gSystemBootCompleted = true;
300#endif
301 }
302 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900303 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700304
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000305 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700306 ProcessState::self()->getDriverName().c_str());
307
Steven Moreland583685e2019-10-02 16:45:11 -0700308 int n = 0;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700309 while (uptimeMillis() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700310 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700311 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700312
Yunfan Chen788e1c42018-03-29 16:52:09 +0900313 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700314 if (svc != nullptr) {
315 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000316 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700317 uptimeMillis() - startTime);
318 return svc;
319 }
Steven Moreland583685e2019-10-02 16:45:11 -0700320 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000321 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700322 return nullptr;
323}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900324
Steven Moreland583685e2019-10-02 16:45:11 -0700325sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
326{
327 sp<IBinder> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000328 if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700329 return nullptr;
330 }
331 return ret;
332}
333
334status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
335 bool allowIsolated, int dumpsysPriority)
336{
Parth Sane56a04712024-04-22 14:21:07 +0000337 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
338 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700339 return status.exceptionCode();
340}
341
342Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
343{
344 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000345 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700346 return {};
347 }
348
349 Vector<String16> res;
350 res.setCapacity(ret.size());
351 for (const std::string& name : ret) {
352 res.push(String16(name.c_str()));
353 }
354 return res;
355}
356
357sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
358{
359 class Waiter : public android::os::BnServiceCallback {
360 Status onRegistration(const std::string& /*name*/,
361 const sp<IBinder>& binder) override {
362 std::unique_lock<std::mutex> lock(mMutex);
363 mBinder = binder;
364 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700365 // Flushing here helps ensure the service's ref count remains accurate
366 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700367 mCv.notify_one();
368 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900369 }
Steven Moreland583685e2019-10-02 16:45:11 -0700370 public:
371 sp<IBinder> mBinder;
372 std::mutex mMutex;
373 std::condition_variable mCv;
374 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900375
Jon Spivackfed6db42019-11-18 16:43:59 -0800376 // Simple RAII object to ensure a function call immediately before going out of scope
377 class Defer {
378 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900379 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800380 ~Defer() { mF(); }
381 private:
382 std::function<void()> mF;
383 };
384
Steven Moreland583685e2019-10-02 16:45:11 -0700385 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900386
Steven Moreland583685e2019-10-02 16:45:11 -0700387 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700388 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000389 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
390 status.toString8().c_str());
Elie Kheirallah27c26952022-09-07 21:45:26 +0000391 if (0 == ProcessState::self()->getThreadPoolMaxTotalThreadCount()) {
392 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
393 "Threadpool has 0 guaranteed threads. "
394 "Is the threadpool configured properly? "
395 "See ProcessState::startThreadPool and "
396 "ProcessState::setThreadPoolMaxThreadCount.");
397 }
Steven Moreland583685e2019-10-02 16:45:11 -0700398 return nullptr;
399 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800400 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700401
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000402 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000403 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000404 !status.isOk()) {
405 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
406 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700407 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408 }
Parth Sane56a04712024-04-22 14:21:07 +0000409 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700410
Steven Moreland583685e2019-10-02 16:45:11 -0700411 while(true) {
412 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000413 // It would be really nice if we could read binder commands on this
414 // thread instead of needing a threadpool to be started, but for
415 // instance, if we call getAndExecuteCommand, it might be the case
416 // that another thread serves the callback, and we never get a
417 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700418 std::unique_lock<std::mutex> lock(waiter->mMutex);
419 using std::literals::chrono_literals::operator""s;
Steven Moreland3d37ef22023-04-25 18:25:14 +0000420 waiter->mCv.wait_for(lock, 1s, [&] {
421 return waiter->mBinder != nullptr;
422 });
Steven Moreland583685e2019-10-02 16:45:11 -0700423 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700424 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425
Steven Moreland3d37ef22023-04-25 18:25:14 +0000426 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000427 "threadpool: %zu. Are binder threads started and available?)",
428 name.c_str(), ProcessState::self()->getThreadPoolMaxTotalThreadCount());
Steven Morelandf2677e22020-07-14 19:58:08 +0000429
Steven Moreland583685e2019-10-02 16:45:11 -0700430 // Handle race condition for lazy services. Here is what can happen:
431 // - the service dies (not processed by init yet).
432 // - sm processes death notification.
433 // - sm gets getService and calls init to start service.
434 // - init gets the start signal, but the service already appears
435 // started, so it does nothing.
436 // - init gets death signal, but doesn't know it needs to restart
437 // the service
438 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700439 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000440 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
441 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700442 return nullptr;
443 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800444 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700445 }
Steven Moreland583685e2019-10-02 16:45:11 -0700446}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447
Steven Morelandb82b8f82019-10-28 10:52:34 -0700448bool ServiceManagerShim::isDeclared(const String16& name) {
449 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000450 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000451 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000452 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000453 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700454 return false;
455 }
456 return declared;
457}
458
Steven Moreland2e293aa2020-09-23 00:25:16 +0000459Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
460 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000461 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000462 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000463 !status.isOk()) {
464 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
465 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000466 return {};
467 }
468
469 Vector<String16> res;
470 res.setCapacity(out.size());
471 for (const std::string& instance : out) {
472 res.push(String16(instance.c_str()));
473 }
474 return res;
475}
476
Steven Morelandedd4e072021-04-21 00:27:29 +0000477std::optional<String16> ServiceManagerShim::updatableViaApex(const String16& name) {
478 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000479 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000480 !status.isOk()) {
481 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
482 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000483 return std::nullopt;
484 }
485 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
486}
487
Jooyung Han76944fe2022-10-25 17:02:45 +0900488Vector<String16> ServiceManagerShim::getUpdatableNames(const String16& apexName) {
489 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000490 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900491 !status.isOk()) {
492 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
493 status.toString8().c_str());
494 return {};
495 }
496
497 Vector<String16> res;
498 res.setCapacity(out.size());
499 for (const std::string& instance : out) {
500 res.push(String16(instance.c_str()));
501 }
502 return res;
503}
504
Devin Moore5e4c2f12021-09-09 22:36:33 +0000505std::optional<IServiceManager::ConnectionInfo> ServiceManagerShim::getConnectionInfo(
506 const String16& name) {
507 std::optional<os::ConnectionInfo> connectionInfo;
508 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000509 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000510 !status.isOk()) {
511 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
512 status.toString8().c_str());
513 }
514 return connectionInfo.has_value()
515 ? std::make_optional<IServiceManager::ConnectionInfo>(
516 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
517 : std::nullopt;
518}
519
Jayant Chowdhary30700942022-01-31 14:12:40 -0800520status_t ServiceManagerShim::registerForNotifications(const String16& name,
521 const sp<AidlRegistrationCallback>& cb) {
522 if (cb == nullptr) {
523 ALOGE("%s: null cb passed", __FUNCTION__);
524 return BAD_VALUE;
525 }
526 std::string nameStr = String8(name).c_str();
527 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
528 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
529 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000530 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800531 !status.isOk()) {
532 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
533 status.toString8().c_str());
534 return UNKNOWN_ERROR;
535 }
536 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
537 return OK;
538}
539
540void ServiceManagerShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
541 ServiceCallbackMap::iterator* it,
542 sp<RegistrationWaiter>* waiter) {
543 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
544 for (auto lit = localRegistrationAndWaiters.begin();
545 lit != localRegistrationAndWaiters.end();) {
546 if (lit->first == cb) {
547 if (waiter) {
548 *waiter = lit->second;
549 }
550 lit = localRegistrationAndWaiters.erase(lit);
551 } else {
552 ++lit;
553 }
554 }
555
556 if (localRegistrationAndWaiters.empty()) {
557 mNameToRegistrationCallback.erase(*it);
558 }
559}
560
561status_t ServiceManagerShim::unregisterForNotifications(const String16& name,
562 const sp<AidlRegistrationCallback>& cb) {
563 if (cb == nullptr) {
564 ALOGE("%s: null cb passed", __FUNCTION__);
565 return BAD_VALUE;
566 }
567 std::string nameStr = String8(name).c_str();
568 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
569 auto it = mNameToRegistrationCallback.find(nameStr);
570 sp<RegistrationWaiter> registrationWaiter;
571 if (it != mNameToRegistrationCallback.end()) {
572 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
573 } else {
574 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
575 return BAD_VALUE;
576 }
577 if (registrationWaiter == nullptr) {
578 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
579 return BAD_VALUE;
580 }
Parth Sane56a04712024-04-22 14:21:07 +0000581 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800582 registrationWaiter);
583 !status.isOk()) {
584 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
585 String8(name).c_str(), status.toString8().c_str());
586 return UNKNOWN_ERROR;
587 }
588 return OK;
589}
590
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000591std::vector<IServiceManager::ServiceDebugInfo> ServiceManagerShim::getServiceDebugInfo() {
592 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
593 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000594 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000595 !status.isOk()) {
596 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
597 return ret;
598 }
599 for (const auto& serviceDebugInfo : serviceDebugInfos) {
600 IServiceManager::ServiceDebugInfo retInfo;
601 retInfo.pid = serviceDebugInfo.debugPid;
602 retInfo.name = serviceDebugInfo.name;
603 ret.emplace_back(retInfo);
604 }
605 return ret;
606}
607
Yifan Hongf7760012021-06-04 16:04:42 -0700608#ifndef __ANDROID__
609// ServiceManagerShim for host. Implements the old libbinder android::IServiceManager API.
610// The internal implementation of the AIDL interface android::os::IServiceManager calls into
611// on-device service manager.
612class ServiceManagerHostShim : public ServiceManagerShim {
613public:
Yifan Hong5a05ef72021-10-08 17:33:47 -0700614 ServiceManagerHostShim(const sp<AidlServiceManager>& impl,
615 const RpcDelegateServiceManagerOptions& options)
616 : ServiceManagerShim(impl), mOptions(options) {}
Yifan Hongf7760012021-06-04 16:04:42 -0700617 // ServiceManagerShim::getService is based on checkService, so no need to override it.
618 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700619 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700620 }
621
622protected:
623 // Override realGetService for ServiceManagerShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700624 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700625 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700626 return Status::ok();
627 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700628
629private:
630 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700631};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700632sp<IServiceManager> createRpcDelegateServiceManager(
633 const RpcDelegateServiceManagerOptions& options) {
634 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700635 if (binder == nullptr) {
636 ALOGE("getDeviceService(\"manager\") returns null");
637 return nullptr;
638 }
639 auto interface = AidlServiceManager::asInterface(binder);
640 if (interface == nullptr) {
641 ALOGE("getDeviceService(\"manager\") returns non service manager");
642 return nullptr;
643 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700644 return sp<ServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700645}
646#endif
647
Steven Moreland61ff8492019-09-26 16:05:45 -0700648} // namespace android