blob: 39573ec54d7f3fc3679d647419f6e644f4eb2893 [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>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020
Tom Cherry8fda97f2020-07-22 17:15:44 -070021#include <inttypes.h>
22#include <unistd.h>
23
Steven Moreland454bfd92022-07-20 20:53:36 +000024#include <android-base/properties.h>
Steven Moreland1c47b582019-08-27 18:05:27 -070025#include <android/os/BnServiceCallback.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070026#include <android/os/IServiceManager.h>
Mathias Agopian375f5632009-06-15 18:24:59 -070027#include <binder/IPCThreadState.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070028#include <binder/Parcel.h>
29#include <utils/Log.h>
30#include <utils/String8.h>
31#include <utils/SystemClock.h>
32
Jiyong Park47f876b2018-04-17 13:56:46 +090033#ifndef __ANDROID_VNDK__
34#include <binder/IPermissionController.h>
35#endif
Steven Moreland28723ae2019-04-01 18:52:30 -070036
Steven Morelanded3b5632019-09-20 11:24:28 -070037#ifdef __ANDROID__
Yunfan Chen788e1c42018-03-29 16:52:09 +090038#include <cutils/properties.h>
Yifan Hongf7760012021-06-04 16:04:42 -070039#else
40#include "ServiceManagerHost.h"
Steven Moreland28723ae2019-04-01 18:52:30 -070041#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
Jooyung Han75fc06f2024-02-03 03:56:59 +090043#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
44#include <android/apexsupport.h>
45#include <vndksupport/linker.h>
46#endif
47
Steven Morelanda4853cd2019-07-12 15:44:37 -070048#include "Static.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080049
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050namespace android {
51
Jayant Chowdhary30700942022-01-31 14:12:40 -080052using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
53
Steven Moreland80e1e6d2019-06-21 12:35:59 -070054using AidlServiceManager = android::os::IServiceManager;
55using android::binder::Status;
56
Steven Moreland635a2912019-10-02 15:50:10 -070057// libbinder's IServiceManager.h can't rely on the values generated by AIDL
58// because many places use its headers via include_dirs (meaning, without
59// declaring the dependency in the build system). So, for now, we can just check
60// the values here.
61static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
62static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
63static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
64static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
65static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
66static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
67
Steven Moreland583685e2019-10-02 16:45:11 -070068const String16& IServiceManager::getInterfaceDescriptor() const {
69 return AidlServiceManager::descriptor;
70}
71IServiceManager::IServiceManager() {}
72IServiceManager::~IServiceManager() {}
73
74// From the old libbinder IServiceManager interface to IServiceManager.
75class ServiceManagerShim : public IServiceManager
76{
77public:
78 explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
79
80 sp<IBinder> getService(const String16& name) const override;
81 sp<IBinder> checkService(const String16& name) const override;
82 status_t addService(const String16& name, const sp<IBinder>& service,
83 bool allowIsolated, int dumpsysPriority) override;
84 Vector<String16> listServices(int dumpsysPriority) override;
85 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070086 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +000087 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +000088 std::optional<String16> updatableViaApex(const String16& name) override;
Jooyung Han76944fe2022-10-25 17:02:45 +090089 Vector<String16> getUpdatableNames(const String16& apexName) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +000090 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -080091 class RegistrationWaiter : public android::os::BnServiceCallback {
92 public:
93 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
94 : mImpl(callback) {}
95 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
96 mImpl->onServiceRegistration(String16(name.c_str()), binder);
97 return Status::ok();
98 }
Steven Moreland583685e2019-10-02 16:45:11 -070099
Jayant Chowdhary30700942022-01-31 14:12:40 -0800100 private:
101 sp<AidlRegistrationCallback> mImpl;
102 };
103
104 status_t registerForNotifications(const String16& service,
105 const sp<AidlRegistrationCallback>& cb) override;
106
107 status_t unregisterForNotifications(const String16& service,
108 const sp<AidlRegistrationCallback>& cb) override;
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000109
110 std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
Steven Moreland583685e2019-10-02 16:45:11 -0700111 // for legacy ABI
112 const String16& getInterfaceDescriptor() const override {
113 return mTheRealServiceManager->getInterfaceDescriptor();
114 }
115 IBinder* onAsBinder() override {
116 return IInterface::asBinder(mTheRealServiceManager).get();
117 }
Yifan Hongf7760012021-06-04 16:04:42 -0700118
119protected:
Steven Moreland583685e2019-10-02 16:45:11 -0700120 sp<AidlServiceManager> mTheRealServiceManager;
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
138 // mTheRealServiceManager->getService so that it can be overridden in ServiceManagerHostShim.
139 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
140 return mTheRealServiceManager->getService(name, _aidl_return);
141 }
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, []() {
Steven Moreland454bfd92022-07-20 20:53:36 +0000150#if defined(__BIONIC__) && !defined(__ANDROID_VNDK__)
151 /* wait for service manager */ {
152 using std::literals::chrono_literals::operator""s;
153 using android::base::WaitForProperty;
154 while (!WaitForProperty("servicemanager.ready", "true", 1s)) {
155 ALOGE("Waited for servicemanager.ready for a second, waiting another...");
156 }
157 }
158#endif
159
Martijn Coenen402c8672020-02-03 10:01:36 +0100160 sp<AidlServiceManager> sm = nullptr;
161 while (sm == nullptr) {
162 sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));
163 if (sm == nullptr) {
Steven Moreland39a57212020-05-19 18:10:07 +0000164 ALOGE("Waiting 1s on context object on %s.", ProcessState::self()->getDriverName().c_str());
Todd Poynora7b0f042013-06-18 17:25:37 -0700165 sleep(1);
Martijn Coenen402c8672020-02-03 10:01:36 +0100166 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 }
Martijn Coenen402c8672020-02-03 10:01:36 +0100168
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000169 gDefaultServiceManager = sp<ServiceManagerShim>::make(sm);
Martijn Coenen402c8672020-02-03 10:01:36 +0100170 });
Daniel Eratc2832702015-10-13 15:29:32 -0600171
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 return gDefaultServiceManager;
173}
174
Brett Chabot38dbade2020-01-24 12:59:43 -0800175void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100176 bool called = false;
177 std::call_once(gSmOnce, [&]() {
178 gDefaultServiceManager = sm;
179 called = true;
180 });
181
182 if (!called) {
183 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
184 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800185}
186
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400187#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900188// IPermissionController is not accessible to vendors
189
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190bool checkCallingPermission(const String16& permission)
191{
Yi Kongfdd8da92018-06-07 17:52:27 -0700192 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193}
194
Steven Moreland1b264072021-06-03 23:04:02 +0000195static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
198{
199 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700200 pid_t pid = ipcState->getCallingPid();
201 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700203 if (outUid) *outUid = uid;
204 return checkPermission(permission, pid, uid);
205}
206
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000207bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700208 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700209 static sp<IPermissionController> gPermissionController;
210
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700212 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700214 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600215
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216 int64_t startTime = 0;
217
218 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700219 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 bool res = pc->checkPermission(permission, pid, uid);
221 if (res) {
222 if (startTime != 0) {
Steve Blocka19954a2012-01-04 20:05:49 +0000223 ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000224 (int)((uptimeMillis() - startTime) / 1000), String8(permission).c_str(),
225 uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 }
227 return res;
228 }
Daniel Eratc2832702015-10-13 15:29:32 -0600229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800231 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000232 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000233 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000234 uid, pid);
235 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 return false;
237 }
Daniel Eratc2832702015-10-13 15:29:32 -0600238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700240 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700242 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700244 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800245 }
Daniel Eratc2832702015-10-13 15:29:32 -0600246
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 // Need to retrieve the permission controller.
248 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700249 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250 // Wait for the permission controller to come back...
251 if (startTime == 0) {
252 startTime = uptimeMillis();
Steve Blocka19954a2012-01-04 20:05:49 +0000253 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000254 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 }
256 sleep(1);
257 } else {
258 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600259 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700260 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700262 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800263 }
264 }
265}
266
Jooyung Han75fc06f2024-02-03 03:56:59 +0900267void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
268#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
269 sp<IServiceManager> sm = defaultServiceManager();
270 String16 name = interface + String16("/") + instance;
271 if (!sm->isDeclared(name)) {
272 return nullptr;
273 }
274 String16 libraryName = interface + String16(".") + instance + String16(".so");
275 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
276 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
277 String8(*updatableViaApex).c_str(), flag);
278 }
279 return android_load_sphal_library(String8(libraryName).c_str(), flag);
280#else
281 (void)interface;
282 (void)instance;
283 (void)flag;
284 return nullptr;
285#endif
286}
287
Jiyong Park47f876b2018-04-17 13:56:46 +0900288#endif //__ANDROID_VNDK__
289
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290// ----------------------------------------------------------------------
291
Steven Moreland583685e2019-10-02 16:45:11 -0700292ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl)
293 : mTheRealServiceManager(impl)
294{}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700295
Steven Moreland5af7d852020-04-29 15:40:29 -0700296// This implementation could be simplified and made more efficient by delegating
297// to waitForService. However, this changes the threading structure in some
298// cases and could potentially break prebuilts. Once we have higher logistical
299// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700300sp<IBinder> ServiceManagerShim::getService(const String16& name) const
301{
302 static bool gSystemBootCompleted = false;
303
304 sp<IBinder> svc = checkService(name);
305 if (svc != nullptr) return svc;
306
307 const bool isVendorService =
308 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Jiyong Park16c6e702020-11-13 20:53:12 +0900309 constexpr int64_t timeout = 5000;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700310 int64_t startTime = uptimeMillis();
Steven Moreland583685e2019-10-02 16:45:11 -0700311 // Vendor code can't access system properties
312 if (!gSystemBootCompleted && !isVendorService) {
313#ifdef __ANDROID__
314 char bootCompleted[PROPERTY_VALUE_MAX];
315 property_get("sys.boot_completed", bootCompleted, "0");
316 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
317#else
318 gSystemBootCompleted = true;
319#endif
320 }
321 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900322 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700323
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000324 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700325 ProcessState::self()->getDriverName().c_str());
326
Steven Moreland583685e2019-10-02 16:45:11 -0700327 int n = 0;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700328 while (uptimeMillis() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700329 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700330 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700331
Yunfan Chen788e1c42018-03-29 16:52:09 +0900332 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700333 if (svc != nullptr) {
334 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000335 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700336 uptimeMillis() - startTime);
337 return svc;
338 }
Steven Moreland583685e2019-10-02 16:45:11 -0700339 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000340 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700341 return nullptr;
342}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900343
Steven Moreland583685e2019-10-02 16:45:11 -0700344sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
345{
346 sp<IBinder> ret;
347 if (!mTheRealServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
348 return nullptr;
349 }
350 return ret;
351}
352
353status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
354 bool allowIsolated, int dumpsysPriority)
355{
356 Status status = mTheRealServiceManager->addService(
357 String8(name).c_str(), service, allowIsolated, dumpsysPriority);
358 return status.exceptionCode();
359}
360
361Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
362{
363 std::vector<std::string> ret;
364 if (!mTheRealServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
365 return {};
366 }
367
368 Vector<String16> res;
369 res.setCapacity(ret.size());
370 for (const std::string& name : ret) {
371 res.push(String16(name.c_str()));
372 }
373 return res;
374}
375
376sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
377{
378 class Waiter : public android::os::BnServiceCallback {
379 Status onRegistration(const std::string& /*name*/,
380 const sp<IBinder>& binder) override {
381 std::unique_lock<std::mutex> lock(mMutex);
382 mBinder = binder;
383 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700384 // Flushing here helps ensure the service's ref count remains accurate
385 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700386 mCv.notify_one();
387 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900388 }
Steven Moreland583685e2019-10-02 16:45:11 -0700389 public:
390 sp<IBinder> mBinder;
391 std::mutex mMutex;
392 std::condition_variable mCv;
393 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900394
Jon Spivackfed6db42019-11-18 16:43:59 -0800395 // Simple RAII object to ensure a function call immediately before going out of scope
396 class Defer {
397 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900398 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800399 ~Defer() { mF(); }
400 private:
401 std::function<void()> mF;
402 };
403
Steven Moreland583685e2019-10-02 16:45:11 -0700404 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900405
Steven Moreland583685e2019-10-02 16:45:11 -0700406 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700407 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000408 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
409 status.toString8().c_str());
Elie Kheirallah27c26952022-09-07 21:45:26 +0000410 if (0 == ProcessState::self()->getThreadPoolMaxTotalThreadCount()) {
411 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
412 "Threadpool has 0 guaranteed threads. "
413 "Is the threadpool configured properly? "
414 "See ProcessState::startThreadPool and "
415 "ProcessState::setThreadPoolMaxThreadCount.");
416 }
Steven Moreland583685e2019-10-02 16:45:11 -0700417 return nullptr;
418 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800419 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700420
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000421 sp<Waiter> waiter = sp<Waiter>::make();
Steven Morelanda1d70172021-05-24 22:03:42 +0000422 if (Status status = mTheRealServiceManager->registerForNotifications(name, waiter);
423 !status.isOk()) {
424 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
425 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700426 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800428 Defer unregister ([&] {
429 mTheRealServiceManager->unregisterForNotifications(name, waiter);
430 });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700431
Steven Moreland583685e2019-10-02 16:45:11 -0700432 while(true) {
433 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000434 // It would be really nice if we could read binder commands on this
435 // thread instead of needing a threadpool to be started, but for
436 // instance, if we call getAndExecuteCommand, it might be the case
437 // that another thread serves the callback, and we never get a
438 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700439 std::unique_lock<std::mutex> lock(waiter->mMutex);
440 using std::literals::chrono_literals::operator""s;
Steven Moreland3d37ef22023-04-25 18:25:14 +0000441 waiter->mCv.wait_for(lock, 1s, [&] {
442 return waiter->mBinder != nullptr;
443 });
Steven Moreland583685e2019-10-02 16:45:11 -0700444 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446
Steven Moreland3d37ef22023-04-25 18:25:14 +0000447 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000448 "threadpool: %zu. Are binder threads started and available?)",
449 name.c_str(), ProcessState::self()->getThreadPoolMaxTotalThreadCount());
Steven Morelandf2677e22020-07-14 19:58:08 +0000450
Steven Moreland583685e2019-10-02 16:45:11 -0700451 // Handle race condition for lazy services. Here is what can happen:
452 // - the service dies (not processed by init yet).
453 // - sm processes death notification.
454 // - sm gets getService and calls init to start service.
455 // - init gets the start signal, but the service already appears
456 // started, so it does nothing.
457 // - init gets death signal, but doesn't know it needs to restart
458 // the service
459 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700460 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000461 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
462 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700463 return nullptr;
464 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800465 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700466 }
Steven Moreland583685e2019-10-02 16:45:11 -0700467}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800468
Steven Morelandb82b8f82019-10-28 10:52:34 -0700469bool ServiceManagerShim::isDeclared(const String16& name) {
470 bool declared;
Steven Morelanda1d70172021-05-24 22:03:42 +0000471 if (Status status = mTheRealServiceManager->isDeclared(String8(name).c_str(), &declared);
472 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000473 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000474 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700475 return false;
476 }
477 return declared;
478}
479
Steven Moreland2e293aa2020-09-23 00:25:16 +0000480Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
481 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000482 if (Status status =
483 mTheRealServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
484 !status.isOk()) {
485 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
486 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000487 return {};
488 }
489
490 Vector<String16> res;
491 res.setCapacity(out.size());
492 for (const std::string& instance : out) {
493 res.push(String16(instance.c_str()));
494 }
495 return res;
496}
497
Steven Morelandedd4e072021-04-21 00:27:29 +0000498std::optional<String16> ServiceManagerShim::updatableViaApex(const String16& name) {
499 std::optional<std::string> declared;
Steven Morelanda1d70172021-05-24 22:03:42 +0000500 if (Status status = mTheRealServiceManager->updatableViaApex(String8(name).c_str(), &declared);
501 !status.isOk()) {
502 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
503 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000504 return std::nullopt;
505 }
506 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
507}
508
Jooyung Han76944fe2022-10-25 17:02:45 +0900509Vector<String16> ServiceManagerShim::getUpdatableNames(const String16& apexName) {
510 std::vector<std::string> out;
511 if (Status status = mTheRealServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
512 !status.isOk()) {
513 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
514 status.toString8().c_str());
515 return {};
516 }
517
518 Vector<String16> res;
519 res.setCapacity(out.size());
520 for (const std::string& instance : out) {
521 res.push(String16(instance.c_str()));
522 }
523 return res;
524}
525
Devin Moore5e4c2f12021-09-09 22:36:33 +0000526std::optional<IServiceManager::ConnectionInfo> ServiceManagerShim::getConnectionInfo(
527 const String16& name) {
528 std::optional<os::ConnectionInfo> connectionInfo;
529 if (Status status =
530 mTheRealServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
531 !status.isOk()) {
532 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
533 status.toString8().c_str());
534 }
535 return connectionInfo.has_value()
536 ? std::make_optional<IServiceManager::ConnectionInfo>(
537 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
538 : std::nullopt;
539}
540
Jayant Chowdhary30700942022-01-31 14:12:40 -0800541status_t ServiceManagerShim::registerForNotifications(const String16& name,
542 const sp<AidlRegistrationCallback>& cb) {
543 if (cb == nullptr) {
544 ALOGE("%s: null cb passed", __FUNCTION__);
545 return BAD_VALUE;
546 }
547 std::string nameStr = String8(name).c_str();
548 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
549 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
550 if (Status status =
551 mTheRealServiceManager->registerForNotifications(nameStr, registrationWaiter);
552 !status.isOk()) {
553 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
554 status.toString8().c_str());
555 return UNKNOWN_ERROR;
556 }
557 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
558 return OK;
559}
560
561void ServiceManagerShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
562 ServiceCallbackMap::iterator* it,
563 sp<RegistrationWaiter>* waiter) {
564 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
565 for (auto lit = localRegistrationAndWaiters.begin();
566 lit != localRegistrationAndWaiters.end();) {
567 if (lit->first == cb) {
568 if (waiter) {
569 *waiter = lit->second;
570 }
571 lit = localRegistrationAndWaiters.erase(lit);
572 } else {
573 ++lit;
574 }
575 }
576
577 if (localRegistrationAndWaiters.empty()) {
578 mNameToRegistrationCallback.erase(*it);
579 }
580}
581
582status_t ServiceManagerShim::unregisterForNotifications(const String16& name,
583 const sp<AidlRegistrationCallback>& cb) {
584 if (cb == nullptr) {
585 ALOGE("%s: null cb passed", __FUNCTION__);
586 return BAD_VALUE;
587 }
588 std::string nameStr = String8(name).c_str();
589 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
590 auto it = mNameToRegistrationCallback.find(nameStr);
591 sp<RegistrationWaiter> registrationWaiter;
592 if (it != mNameToRegistrationCallback.end()) {
593 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
594 } else {
595 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
596 return BAD_VALUE;
597 }
598 if (registrationWaiter == nullptr) {
599 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
600 return BAD_VALUE;
601 }
602 if (Status status = mTheRealServiceManager->unregisterForNotifications(String8(name).c_str(),
603 registrationWaiter);
604 !status.isOk()) {
605 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
606 String8(name).c_str(), status.toString8().c_str());
607 return UNKNOWN_ERROR;
608 }
609 return OK;
610}
611
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000612std::vector<IServiceManager::ServiceDebugInfo> ServiceManagerShim::getServiceDebugInfo() {
613 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
614 std::vector<IServiceManager::ServiceDebugInfo> ret;
615 if (Status status = mTheRealServiceManager->getServiceDebugInfo(&serviceDebugInfos);
616 !status.isOk()) {
617 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
618 return ret;
619 }
620 for (const auto& serviceDebugInfo : serviceDebugInfos) {
621 IServiceManager::ServiceDebugInfo retInfo;
622 retInfo.pid = serviceDebugInfo.debugPid;
623 retInfo.name = serviceDebugInfo.name;
624 ret.emplace_back(retInfo);
625 }
626 return ret;
627}
628
Yifan Hongf7760012021-06-04 16:04:42 -0700629#ifndef __ANDROID__
630// ServiceManagerShim for host. Implements the old libbinder android::IServiceManager API.
631// The internal implementation of the AIDL interface android::os::IServiceManager calls into
632// on-device service manager.
633class ServiceManagerHostShim : public ServiceManagerShim {
634public:
Yifan Hong5a05ef72021-10-08 17:33:47 -0700635 ServiceManagerHostShim(const sp<AidlServiceManager>& impl,
636 const RpcDelegateServiceManagerOptions& options)
637 : ServiceManagerShim(impl), mOptions(options) {}
Yifan Hongf7760012021-06-04 16:04:42 -0700638 // ServiceManagerShim::getService is based on checkService, so no need to override it.
639 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700640 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700641 }
642
643protected:
644 // Override realGetService for ServiceManagerShim::waitForService.
645 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700646 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700647 return Status::ok();
648 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700649
650private:
651 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700652};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700653sp<IServiceManager> createRpcDelegateServiceManager(
654 const RpcDelegateServiceManagerOptions& options) {
655 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700656 if (binder == nullptr) {
657 ALOGE("getDeviceService(\"manager\") returns null");
658 return nullptr;
659 }
660 auto interface = AidlServiceManager::asInterface(binder);
661 if (interface == nullptr) {
662 ALOGE("getDeviceService(\"manager\") returns non service manager");
663 return nullptr;
664 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700665 return sp<ServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700666}
667#endif
668
Steven Moreland61ff8492019-09-26 16:05:45 -0700669} // namespace android