blob: 333f9565565b261772f54e60a1b492bd2bb98746 [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>
Alice Wang8578f132024-05-03 09:01:56 +000029#include <android/os/IAccessor.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070030#include <android/os/IServiceManager.h>
Mathias Agopian375f5632009-06-15 18:24:59 -070031#include <binder/IPCThreadState.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070032#include <binder/Parcel.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070033#include <utils/String8.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070034
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"
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070051#include "Utils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053namespace android {
54
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070055using namespace std::chrono_literals;
56
Jayant Chowdhary30700942022-01-31 14:12:40 -080057using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
58
Steven Moreland80e1e6d2019-06-21 12:35:59 -070059using AidlServiceManager = android::os::IServiceManager;
60using android::binder::Status;
Alice Wang8578f132024-05-03 09:01:56 +000061using android::os::IAccessor;
62using android::os::Service;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070063
Steven Moreland635a2912019-10-02 15:50:10 -070064// libbinder's IServiceManager.h can't rely on the values generated by AIDL
65// because many places use its headers via include_dirs (meaning, without
66// declaring the dependency in the build system). So, for now, we can just check
67// the values here.
68static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
69static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
70static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
71static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
72static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
73static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
74
Steven Moreland583685e2019-10-02 16:45:11 -070075const String16& IServiceManager::getInterfaceDescriptor() const {
76 return AidlServiceManager::descriptor;
77}
78IServiceManager::IServiceManager() {}
79IServiceManager::~IServiceManager() {}
80
81// From the old libbinder IServiceManager interface to IServiceManager.
82class ServiceManagerShim : public IServiceManager
83{
84public:
85 explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
86
87 sp<IBinder> getService(const String16& name) const override;
88 sp<IBinder> checkService(const String16& name) const override;
89 status_t addService(const String16& name, const sp<IBinder>& service,
90 bool allowIsolated, int dumpsysPriority) override;
91 Vector<String16> listServices(int dumpsysPriority) override;
92 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070093 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +000094 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +000095 std::optional<String16> updatableViaApex(const String16& name) override;
Jooyung Han76944fe2022-10-25 17:02:45 +090096 Vector<String16> getUpdatableNames(const String16& apexName) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +000097 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -080098 class RegistrationWaiter : public android::os::BnServiceCallback {
99 public:
100 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
101 : mImpl(callback) {}
102 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
103 mImpl->onServiceRegistration(String16(name.c_str()), binder);
104 return Status::ok();
105 }
Steven Moreland583685e2019-10-02 16:45:11 -0700106
Jayant Chowdhary30700942022-01-31 14:12:40 -0800107 private:
108 sp<AidlRegistrationCallback> mImpl;
109 };
110
111 status_t registerForNotifications(const String16& service,
112 const sp<AidlRegistrationCallback>& cb) override;
113
114 status_t unregisterForNotifications(const String16& service,
115 const sp<AidlRegistrationCallback>& cb) override;
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000116
117 std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
Steven Moreland583685e2019-10-02 16:45:11 -0700118 // for legacy ABI
119 const String16& getInterfaceDescriptor() const override {
Parth Sane56a04712024-04-22 14:21:07 +0000120 return mUnifiedServiceManager->getInterfaceDescriptor();
Steven Moreland583685e2019-10-02 16:45:11 -0700121 }
Parth Sane56a04712024-04-22 14:21:07 +0000122 IBinder* onAsBinder() override { return IInterface::asBinder(mUnifiedServiceManager).get(); }
Yifan Hongf7760012021-06-04 16:04:42 -0700123
124protected:
Parth Sane56a04712024-04-22 14:21:07 +0000125 sp<BackendUnifiedServiceManager> mUnifiedServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800126 // AidlRegistrationCallback -> services that its been registered for
127 // notifications.
128 using LocalRegistrationAndWaiter =
129 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
130 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
131 ServiceCallbackMap mNameToRegistrationCallback;
132 std::mutex mNameToRegistrationLock;
133
134 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
135 ServiceCallbackMap::iterator* it,
136 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700137
138 // Directly get the service in a way that, for lazy services, requests the service to be started
139 // if it is not currently started. This way, calls directly to ServiceManagerShim::getService
140 // will still have the 5s delay that is expected by a large amount of Android code.
141 //
142 // When implementing ServiceManagerShim, use realGetService instead of
Parth Sane56a04712024-04-22 14:21:07 +0000143 // mUnifiedServiceManager->getService so that it can be overridden in ServiceManagerHostShim.
Yifan Hongf7760012021-06-04 16:04:42 -0700144 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Alice Wang8578f132024-05-03 09:01:56 +0000145 Service service;
Alice Wang11da1502024-07-25 12:03:22 +0000146 Status status = mUnifiedServiceManager->getService2(name, &service);
Alice Wang8578f132024-05-03 09:01:56 +0000147 *_aidl_return = service.get<Service::Tag::binder>();
148 return status;
Yifan Hongf7760012021-06-04 16:04:42 -0700149 }
Steven Moreland583685e2019-10-02 16:45:11 -0700150};
151
Steven Moreland1698ffd2020-05-15 23:43:52 +0000152[[clang::no_destroy]] static std::once_flag gSmOnce;
153[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Brett Chabot38dbade2020-01-24 12:59:43 -0800154
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155sp<IServiceManager> defaultServiceManager()
156{
Martijn Coenen402c8672020-02-03 10:01:36 +0100157 std::call_once(gSmOnce, []() {
Parth Sane56a04712024-04-22 14:21:07 +0000158 gDefaultServiceManager = sp<ServiceManagerShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100159 });
Daniel Eratc2832702015-10-13 15:29:32 -0600160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161 return gDefaultServiceManager;
162}
163
Brett Chabot38dbade2020-01-24 12:59:43 -0800164void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100165 bool called = false;
166 std::call_once(gSmOnce, [&]() {
167 gDefaultServiceManager = sm;
168 called = true;
169 });
170
171 if (!called) {
172 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
173 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800174}
175
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400176#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900177// IPermissionController is not accessible to vendors
178
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179bool checkCallingPermission(const String16& permission)
180{
Yi Kongfdd8da92018-06-07 17:52:27 -0700181 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182}
183
Steven Moreland1b264072021-06-03 23:04:02 +0000184static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
187{
188 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700189 pid_t pid = ipcState->getCallingPid();
190 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800191 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700192 if (outUid) *outUid = uid;
193 return checkPermission(permission, pid, uid);
194}
195
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000196bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700197 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700198 static sp<IPermissionController> gPermissionController;
199
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700201 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700203 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600204
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700205 auto startTime = std::chrono::steady_clock::now().min();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206
207 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700208 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209 bool res = pc->checkPermission(permission, pid, uid);
210 if (res) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700211 if (startTime != startTime.min()) {
212 const auto waitTime = std::chrono::steady_clock::now() - startTime;
213 ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
214 to_ms(waitTime), String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 }
216 return res;
217 }
Daniel Eratc2832702015-10-13 15:29:32 -0600218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800220 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000221 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000222 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000223 uid, pid);
224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225 return false;
226 }
Daniel Eratc2832702015-10-13 15:29:32 -0600227
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700229 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700231 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700233 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 }
Daniel Eratc2832702015-10-13 15:29:32 -0600235
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 // Need to retrieve the permission controller.
237 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700238 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 // Wait for the permission controller to come back...
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700240 if (startTime == startTime.min()) {
241 startTime = std::chrono::steady_clock::now();
Steve Blocka19954a2012-01-04 20:05:49 +0000242 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000243 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 }
245 sleep(1);
246 } else {
247 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600248 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700249 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700251 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 }
253 }
254}
255
Steven Moreland576662a2024-08-09 23:12:03 +0000256#endif //__ANDROID_VNDK__
257
Jooyung Han75fc06f2024-02-03 03:56:59 +0900258void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
Steven Moreland576662a2024-08-09 23:12:03 +0000259#if defined(__ANDROID__) && !defined(__ANDROID_VENDOR__) && !defined(__ANDROID_RECOVERY__) && \
260 !defined(__ANDROID_NATIVE_BRIDGE__)
Jooyung Han75fc06f2024-02-03 03:56:59 +0900261 sp<IServiceManager> sm = defaultServiceManager();
262 String16 name = interface + String16("/") + instance;
263 if (!sm->isDeclared(name)) {
264 return nullptr;
265 }
266 String16 libraryName = interface + String16(".") + instance + String16(".so");
267 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
268 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
269 String8(*updatableViaApex).c_str(), flag);
270 }
271 return android_load_sphal_library(String8(libraryName).c_str(), flag);
272#else
273 (void)interface;
274 (void)instance;
275 (void)flag;
276 return nullptr;
277#endif
278}
279
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280// ----------------------------------------------------------------------
281
Parth Sane56a04712024-04-22 14:21:07 +0000282ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl) {
283 mUnifiedServiceManager = sp<BackendUnifiedServiceManager>::make(impl);
284}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700285
Steven Moreland5af7d852020-04-29 15:40:29 -0700286// This implementation could be simplified and made more efficient by delegating
287// to waitForService. However, this changes the threading structure in some
288// cases and could potentially break prebuilts. Once we have higher logistical
289// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700290sp<IBinder> ServiceManagerShim::getService(const String16& name) const
291{
292 static bool gSystemBootCompleted = false;
293
294 sp<IBinder> svc = checkService(name);
295 if (svc != nullptr) return svc;
296
297 const bool isVendorService =
298 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700299 constexpr auto timeout = 5s;
300 const auto startTime = std::chrono::steady_clock::now();
Steven Moreland583685e2019-10-02 16:45:11 -0700301 // Vendor code can't access system properties
302 if (!gSystemBootCompleted && !isVendorService) {
303#ifdef __ANDROID__
304 char bootCompleted[PROPERTY_VALUE_MAX];
305 property_get("sys.boot_completed", bootCompleted, "0");
306 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
307#else
308 gSystemBootCompleted = true;
309#endif
310 }
311 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900312 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700313
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000314 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700315 ProcessState::self()->getDriverName().c_str());
316
Steven Moreland583685e2019-10-02 16:45:11 -0700317 int n = 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700318 while (std::chrono::steady_clock::now() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700319 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700320 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700321
Yunfan Chen788e1c42018-03-29 16:52:09 +0900322 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700323 if (svc != nullptr) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700324 const auto waitTime = std::chrono::steady_clock::now() - startTime;
325 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000326 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700327 to_ms(waitTime));
Tom Cherry8fda97f2020-07-22 17:15:44 -0700328 return svc;
329 }
Steven Moreland583685e2019-10-02 16:45:11 -0700330 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000331 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700332 return nullptr;
333}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900334
Steven Moreland583685e2019-10-02 16:45:11 -0700335sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
336{
Alice Wang8578f132024-05-03 09:01:56 +0000337 Service ret;
Parth Sane56a04712024-04-22 14:21:07 +0000338 if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700339 return nullptr;
340 }
Alice Wang8578f132024-05-03 09:01:56 +0000341 return ret.get<Service::Tag::binder>();
Steven Moreland583685e2019-10-02 16:45:11 -0700342}
343
344status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
345 bool allowIsolated, int dumpsysPriority)
346{
Parth Sane56a04712024-04-22 14:21:07 +0000347 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
348 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700349 return status.exceptionCode();
350}
351
352Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
353{
354 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000355 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700356 return {};
357 }
358
359 Vector<String16> res;
360 res.setCapacity(ret.size());
361 for (const std::string& name : ret) {
362 res.push(String16(name.c_str()));
363 }
364 return res;
365}
366
367sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
368{
369 class Waiter : public android::os::BnServiceCallback {
370 Status onRegistration(const std::string& /*name*/,
371 const sp<IBinder>& binder) override {
372 std::unique_lock<std::mutex> lock(mMutex);
373 mBinder = binder;
374 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700375 // Flushing here helps ensure the service's ref count remains accurate
376 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700377 mCv.notify_one();
378 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900379 }
Steven Moreland583685e2019-10-02 16:45:11 -0700380 public:
381 sp<IBinder> mBinder;
382 std::mutex mMutex;
383 std::condition_variable mCv;
384 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900385
Jon Spivackfed6db42019-11-18 16:43:59 -0800386 // Simple RAII object to ensure a function call immediately before going out of scope
387 class Defer {
388 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900389 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800390 ~Defer() { mF(); }
391 private:
392 std::function<void()> mF;
393 };
394
Steven Moreland583685e2019-10-02 16:45:11 -0700395 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900396
Steven Moreland583685e2019-10-02 16:45:11 -0700397 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700398 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000399 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
400 status.toString8().c_str());
Elie Kheirallah27c26952022-09-07 21:45:26 +0000401 if (0 == ProcessState::self()->getThreadPoolMaxTotalThreadCount()) {
402 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
403 "Threadpool has 0 guaranteed threads. "
404 "Is the threadpool configured properly? "
405 "See ProcessState::startThreadPool and "
406 "ProcessState::setThreadPoolMaxThreadCount.");
407 }
Steven Moreland583685e2019-10-02 16:45:11 -0700408 return nullptr;
409 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800410 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700411
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000412 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000413 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000414 !status.isOk()) {
415 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
416 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700417 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418 }
Parth Sane56a04712024-04-22 14:21:07 +0000419 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700420
Steven Moreland583685e2019-10-02 16:45:11 -0700421 while(true) {
422 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000423 // It would be really nice if we could read binder commands on this
424 // thread instead of needing a threadpool to be started, but for
425 // instance, if we call getAndExecuteCommand, it might be the case
426 // that another thread serves the callback, and we never get a
427 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700428 std::unique_lock<std::mutex> lock(waiter->mMutex);
Steven Moreland3d37ef22023-04-25 18:25:14 +0000429 waiter->mCv.wait_for(lock, 1s, [&] {
430 return waiter->mBinder != nullptr;
431 });
Steven Moreland583685e2019-10-02 16:45:11 -0700432 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700433 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434
Steven Moreland3d37ef22023-04-25 18:25:14 +0000435 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000436 "threadpool: %zu. Are binder threads started and available?)",
437 name.c_str(), ProcessState::self()->getThreadPoolMaxTotalThreadCount());
Steven Morelandf2677e22020-07-14 19:58:08 +0000438
Steven Moreland583685e2019-10-02 16:45:11 -0700439 // Handle race condition for lazy services. Here is what can happen:
440 // - the service dies (not processed by init yet).
441 // - sm processes death notification.
442 // - sm gets getService and calls init to start service.
443 // - init gets the start signal, but the service already appears
444 // started, so it does nothing.
445 // - init gets death signal, but doesn't know it needs to restart
446 // the service
447 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700448 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000449 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
450 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700451 return nullptr;
452 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800453 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700454 }
Steven Moreland583685e2019-10-02 16:45:11 -0700455}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800456
Steven Morelandb82b8f82019-10-28 10:52:34 -0700457bool ServiceManagerShim::isDeclared(const String16& name) {
458 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000459 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000460 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000461 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000462 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700463 return false;
464 }
465 return declared;
466}
467
Steven Moreland2e293aa2020-09-23 00:25:16 +0000468Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
469 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000470 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000471 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000472 !status.isOk()) {
473 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
474 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000475 return {};
476 }
477
478 Vector<String16> res;
479 res.setCapacity(out.size());
480 for (const std::string& instance : out) {
481 res.push(String16(instance.c_str()));
482 }
483 return res;
484}
485
Steven Morelandedd4e072021-04-21 00:27:29 +0000486std::optional<String16> ServiceManagerShim::updatableViaApex(const String16& name) {
487 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000488 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000489 !status.isOk()) {
490 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
491 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000492 return std::nullopt;
493 }
494 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
495}
496
Jooyung Han76944fe2022-10-25 17:02:45 +0900497Vector<String16> ServiceManagerShim::getUpdatableNames(const String16& apexName) {
498 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000499 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900500 !status.isOk()) {
501 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
502 status.toString8().c_str());
503 return {};
504 }
505
506 Vector<String16> res;
507 res.setCapacity(out.size());
508 for (const std::string& instance : out) {
509 res.push(String16(instance.c_str()));
510 }
511 return res;
512}
513
Devin Moore5e4c2f12021-09-09 22:36:33 +0000514std::optional<IServiceManager::ConnectionInfo> ServiceManagerShim::getConnectionInfo(
515 const String16& name) {
516 std::optional<os::ConnectionInfo> connectionInfo;
517 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000518 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000519 !status.isOk()) {
520 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
521 status.toString8().c_str());
522 }
523 return connectionInfo.has_value()
524 ? std::make_optional<IServiceManager::ConnectionInfo>(
525 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
526 : std::nullopt;
527}
528
Jayant Chowdhary30700942022-01-31 14:12:40 -0800529status_t ServiceManagerShim::registerForNotifications(const String16& name,
530 const sp<AidlRegistrationCallback>& cb) {
531 if (cb == nullptr) {
532 ALOGE("%s: null cb passed", __FUNCTION__);
533 return BAD_VALUE;
534 }
535 std::string nameStr = String8(name).c_str();
536 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
537 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
538 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000539 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800540 !status.isOk()) {
541 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
542 status.toString8().c_str());
543 return UNKNOWN_ERROR;
544 }
545 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
546 return OK;
547}
548
549void ServiceManagerShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
550 ServiceCallbackMap::iterator* it,
551 sp<RegistrationWaiter>* waiter) {
552 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
553 for (auto lit = localRegistrationAndWaiters.begin();
554 lit != localRegistrationAndWaiters.end();) {
555 if (lit->first == cb) {
556 if (waiter) {
557 *waiter = lit->second;
558 }
559 lit = localRegistrationAndWaiters.erase(lit);
560 } else {
561 ++lit;
562 }
563 }
564
565 if (localRegistrationAndWaiters.empty()) {
566 mNameToRegistrationCallback.erase(*it);
567 }
568}
569
570status_t ServiceManagerShim::unregisterForNotifications(const String16& name,
571 const sp<AidlRegistrationCallback>& cb) {
572 if (cb == nullptr) {
573 ALOGE("%s: null cb passed", __FUNCTION__);
574 return BAD_VALUE;
575 }
576 std::string nameStr = String8(name).c_str();
577 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
578 auto it = mNameToRegistrationCallback.find(nameStr);
579 sp<RegistrationWaiter> registrationWaiter;
580 if (it != mNameToRegistrationCallback.end()) {
581 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
582 } else {
583 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
584 return BAD_VALUE;
585 }
586 if (registrationWaiter == nullptr) {
587 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
588 return BAD_VALUE;
589 }
Parth Sane56a04712024-04-22 14:21:07 +0000590 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800591 registrationWaiter);
592 !status.isOk()) {
593 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
594 String8(name).c_str(), status.toString8().c_str());
595 return UNKNOWN_ERROR;
596 }
597 return OK;
598}
599
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000600std::vector<IServiceManager::ServiceDebugInfo> ServiceManagerShim::getServiceDebugInfo() {
601 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
602 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000603 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000604 !status.isOk()) {
605 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
606 return ret;
607 }
608 for (const auto& serviceDebugInfo : serviceDebugInfos) {
609 IServiceManager::ServiceDebugInfo retInfo;
610 retInfo.pid = serviceDebugInfo.debugPid;
611 retInfo.name = serviceDebugInfo.name;
612 ret.emplace_back(retInfo);
613 }
614 return ret;
615}
616
Yifan Hongf7760012021-06-04 16:04:42 -0700617#ifndef __ANDROID__
618// ServiceManagerShim for host. Implements the old libbinder android::IServiceManager API.
619// The internal implementation of the AIDL interface android::os::IServiceManager calls into
620// on-device service manager.
621class ServiceManagerHostShim : public ServiceManagerShim {
622public:
Yifan Hong5a05ef72021-10-08 17:33:47 -0700623 ServiceManagerHostShim(const sp<AidlServiceManager>& impl,
624 const RpcDelegateServiceManagerOptions& options)
625 : ServiceManagerShim(impl), mOptions(options) {}
Yifan Hongf7760012021-06-04 16:04:42 -0700626 // ServiceManagerShim::getService is based on checkService, so no need to override it.
627 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700628 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700629 }
630
631protected:
632 // Override realGetService for ServiceManagerShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700633 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700634 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700635 return Status::ok();
636 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700637
638private:
639 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700640};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700641sp<IServiceManager> createRpcDelegateServiceManager(
642 const RpcDelegateServiceManagerOptions& options) {
643 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700644 if (binder == nullptr) {
645 ALOGE("getDeviceService(\"manager\") returns null");
646 return nullptr;
647 }
648 auto interface = AidlServiceManager::asInterface(binder);
649 if (interface == nullptr) {
650 ALOGE("getDeviceService(\"manager\") returns non service manager");
651 return nullptr;
652 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700653 return sp<ServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700654}
655#endif
656
Steven Moreland61ff8492019-09-26 16:05:45 -0700657} // namespace android