blob: 05db7743f2be848114912b36dd901e1eaeb10edf [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
Steven Morelanda4853cd2019-07-12 15:44:37 -070043#include "Static.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080044
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080045namespace android {
46
Jayant Chowdhary30700942022-01-31 14:12:40 -080047using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
48
Steven Moreland80e1e6d2019-06-21 12:35:59 -070049using AidlServiceManager = android::os::IServiceManager;
50using android::binder::Status;
51
Steven Moreland635a2912019-10-02 15:50:10 -070052// libbinder's IServiceManager.h can't rely on the values generated by AIDL
53// because many places use its headers via include_dirs (meaning, without
54// declaring the dependency in the build system). So, for now, we can just check
55// the values here.
56static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
57static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
58static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
59static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
60static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
61static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
62
Steven Moreland583685e2019-10-02 16:45:11 -070063const String16& IServiceManager::getInterfaceDescriptor() const {
64 return AidlServiceManager::descriptor;
65}
66IServiceManager::IServiceManager() {}
67IServiceManager::~IServiceManager() {}
68
69// From the old libbinder IServiceManager interface to IServiceManager.
70class ServiceManagerShim : public IServiceManager
71{
72public:
73 explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
74
75 sp<IBinder> getService(const String16& name) const override;
76 sp<IBinder> checkService(const String16& name) const override;
77 status_t addService(const String16& name, const sp<IBinder>& service,
78 bool allowIsolated, int dumpsysPriority) override;
79 Vector<String16> listServices(int dumpsysPriority) override;
80 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070081 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +000082 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +000083 std::optional<String16> updatableViaApex(const String16& name) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +000084 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -080085 class RegistrationWaiter : public android::os::BnServiceCallback {
86 public:
87 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
88 : mImpl(callback) {}
89 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
90 mImpl->onServiceRegistration(String16(name.c_str()), binder);
91 return Status::ok();
92 }
Steven Moreland583685e2019-10-02 16:45:11 -070093
Jayant Chowdhary30700942022-01-31 14:12:40 -080094 private:
95 sp<AidlRegistrationCallback> mImpl;
96 };
97
98 status_t registerForNotifications(const String16& service,
99 const sp<AidlRegistrationCallback>& cb) override;
100
101 status_t unregisterForNotifications(const String16& service,
102 const sp<AidlRegistrationCallback>& cb) override;
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000103
104 std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
Steven Moreland583685e2019-10-02 16:45:11 -0700105 // for legacy ABI
106 const String16& getInterfaceDescriptor() const override {
107 return mTheRealServiceManager->getInterfaceDescriptor();
108 }
109 IBinder* onAsBinder() override {
110 return IInterface::asBinder(mTheRealServiceManager).get();
111 }
Yifan Hongf7760012021-06-04 16:04:42 -0700112
113protected:
Steven Moreland583685e2019-10-02 16:45:11 -0700114 sp<AidlServiceManager> mTheRealServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800115 // AidlRegistrationCallback -> services that its been registered for
116 // notifications.
117 using LocalRegistrationAndWaiter =
118 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
119 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
120 ServiceCallbackMap mNameToRegistrationCallback;
121 std::mutex mNameToRegistrationLock;
122
123 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
124 ServiceCallbackMap::iterator* it,
125 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700126
127 // Directly get the service in a way that, for lazy services, requests the service to be started
128 // if it is not currently started. This way, calls directly to ServiceManagerShim::getService
129 // will still have the 5s delay that is expected by a large amount of Android code.
130 //
131 // When implementing ServiceManagerShim, use realGetService instead of
132 // mTheRealServiceManager->getService so that it can be overridden in ServiceManagerHostShim.
133 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
134 return mTheRealServiceManager->getService(name, _aidl_return);
135 }
Steven Moreland583685e2019-10-02 16:45:11 -0700136};
137
Steven Moreland1698ffd2020-05-15 23:43:52 +0000138[[clang::no_destroy]] static std::once_flag gSmOnce;
139[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Brett Chabot38dbade2020-01-24 12:59:43 -0800140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141sp<IServiceManager> defaultServiceManager()
142{
Martijn Coenen402c8672020-02-03 10:01:36 +0100143 std::call_once(gSmOnce, []() {
Steven Moreland454bfd92022-07-20 20:53:36 +0000144#if defined(__BIONIC__) && !defined(__ANDROID_VNDK__)
145 /* wait for service manager */ {
146 using std::literals::chrono_literals::operator""s;
147 using android::base::WaitForProperty;
148 while (!WaitForProperty("servicemanager.ready", "true", 1s)) {
149 ALOGE("Waited for servicemanager.ready for a second, waiting another...");
150 }
151 }
152#endif
153
Martijn Coenen402c8672020-02-03 10:01:36 +0100154 sp<AidlServiceManager> sm = nullptr;
155 while (sm == nullptr) {
156 sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));
157 if (sm == nullptr) {
Steven Moreland39a57212020-05-19 18:10:07 +0000158 ALOGE("Waiting 1s on context object on %s.", ProcessState::self()->getDriverName().c_str());
Todd Poynora7b0f042013-06-18 17:25:37 -0700159 sleep(1);
Martijn Coenen402c8672020-02-03 10:01:36 +0100160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161 }
Martijn Coenen402c8672020-02-03 10:01:36 +0100162
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000163 gDefaultServiceManager = sp<ServiceManagerShim>::make(sm);
Martijn Coenen402c8672020-02-03 10:01:36 +0100164 });
Daniel Eratc2832702015-10-13 15:29:32 -0600165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166 return gDefaultServiceManager;
167}
168
Brett Chabot38dbade2020-01-24 12:59:43 -0800169void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100170 bool called = false;
171 std::call_once(gSmOnce, [&]() {
172 gDefaultServiceManager = sm;
173 called = true;
174 });
175
176 if (!called) {
177 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
178 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800179}
180
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400181#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900182// IPermissionController is not accessible to vendors
183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184bool checkCallingPermission(const String16& permission)
185{
Yi Kongfdd8da92018-06-07 17:52:27 -0700186 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800187}
188
Steven Moreland1b264072021-06-03 23:04:02 +0000189static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800191bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
192{
193 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700194 pid_t pid = ipcState->getCallingPid();
195 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700197 if (outUid) *outUid = uid;
198 return checkPermission(permission, pid, uid);
199}
200
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000201bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Steven Moreland92b17c62019-04-02 15:46:24 -0700202 static Mutex gPermissionControllerLock;
203 static sp<IPermissionController> gPermissionController;
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700206 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700208 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600209
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210 int64_t startTime = 0;
211
212 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700213 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 bool res = pc->checkPermission(permission, pid, uid);
215 if (res) {
216 if (startTime != 0) {
Steve Blocka19954a2012-01-04 20:05:49 +0000217 ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218 (int)((uptimeMillis()-startTime)/1000),
219 String8(permission).string(), uid, pid);
220 }
221 return res;
222 }
Daniel Eratc2832702015-10-13 15:29:32 -0600223
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800225 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000226 if (logPermissionFailure) {
227 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).string(),
228 uid, pid);
229 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 return false;
231 }
Daniel Eratc2832702015-10-13 15:29:32 -0600232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700234 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700236 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700238 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 }
Daniel Eratc2832702015-10-13 15:29:32 -0600240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241 // Need to retrieve the permission controller.
242 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700243 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 // Wait for the permission controller to come back...
245 if (startTime == 0) {
246 startTime = uptimeMillis();
Steve Blocka19954a2012-01-04 20:05:49 +0000247 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248 String8(permission).string(), uid, pid);
249 }
250 sleep(1);
251 } else {
252 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600253 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700254 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700256 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 }
258 }
259}
260
Jiyong Park47f876b2018-04-17 13:56:46 +0900261#endif //__ANDROID_VNDK__
262
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800263// ----------------------------------------------------------------------
264
Steven Moreland583685e2019-10-02 16:45:11 -0700265ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl)
266 : mTheRealServiceManager(impl)
267{}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700268
Steven Moreland5af7d852020-04-29 15:40:29 -0700269// This implementation could be simplified and made more efficient by delegating
270// to waitForService. However, this changes the threading structure in some
271// cases and could potentially break prebuilts. Once we have higher logistical
272// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700273sp<IBinder> ServiceManagerShim::getService(const String16& name) const
274{
275 static bool gSystemBootCompleted = false;
276
277 sp<IBinder> svc = checkService(name);
278 if (svc != nullptr) return svc;
279
280 const bool isVendorService =
281 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Jiyong Park16c6e702020-11-13 20:53:12 +0900282 constexpr int64_t timeout = 5000;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700283 int64_t startTime = uptimeMillis();
Steven Moreland583685e2019-10-02 16:45:11 -0700284 // Vendor code can't access system properties
285 if (!gSystemBootCompleted && !isVendorService) {
286#ifdef __ANDROID__
287 char bootCompleted[PROPERTY_VALUE_MAX];
288 property_get("sys.boot_completed", bootCompleted, "0");
289 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
290#else
291 gSystemBootCompleted = true;
292#endif
293 }
294 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900295 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700296
Tom Cherry8fda97f2020-07-22 17:15:44 -0700297 ALOGI("Waiting for service '%s' on '%s'...", String8(name).string(),
298 ProcessState::self()->getDriverName().c_str());
299
Steven Moreland583685e2019-10-02 16:45:11 -0700300 int n = 0;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700301 while (uptimeMillis() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700302 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700303 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700304
Yunfan Chen788e1c42018-03-29 16:52:09 +0900305 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700306 if (svc != nullptr) {
307 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
308 String8(name).string(), ProcessState::self()->getDriverName().c_str(),
309 uptimeMillis() - startTime);
310 return svc;
311 }
Steven Moreland583685e2019-10-02 16:45:11 -0700312 }
313 ALOGW("Service %s didn't start. Returning NULL", String8(name).string());
314 return nullptr;
315}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900316
Steven Moreland583685e2019-10-02 16:45:11 -0700317sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
318{
319 sp<IBinder> ret;
320 if (!mTheRealServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
321 return nullptr;
322 }
323 return ret;
324}
325
326status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
327 bool allowIsolated, int dumpsysPriority)
328{
329 Status status = mTheRealServiceManager->addService(
330 String8(name).c_str(), service, allowIsolated, dumpsysPriority);
331 return status.exceptionCode();
332}
333
334Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
335{
336 std::vector<std::string> ret;
337 if (!mTheRealServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
338 return {};
339 }
340
341 Vector<String16> res;
342 res.setCapacity(ret.size());
343 for (const std::string& name : ret) {
344 res.push(String16(name.c_str()));
345 }
346 return res;
347}
348
349sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
350{
351 class Waiter : public android::os::BnServiceCallback {
352 Status onRegistration(const std::string& /*name*/,
353 const sp<IBinder>& binder) override {
354 std::unique_lock<std::mutex> lock(mMutex);
355 mBinder = binder;
356 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700357 // Flushing here helps ensure the service's ref count remains accurate
358 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700359 mCv.notify_one();
360 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900361 }
Steven Moreland583685e2019-10-02 16:45:11 -0700362 public:
363 sp<IBinder> mBinder;
364 std::mutex mMutex;
365 std::condition_variable mCv;
366 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900367
Jon Spivackfed6db42019-11-18 16:43:59 -0800368 // Simple RAII object to ensure a function call immediately before going out of scope
369 class Defer {
370 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900371 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800372 ~Defer() { mF(); }
373 private:
374 std::function<void()> mF;
375 };
376
Steven Moreland583685e2019-10-02 16:45:11 -0700377 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900378
Steven Moreland583685e2019-10-02 16:45:11 -0700379 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700380 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000381 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
382 status.toString8().c_str());
Elie Kheirallah27c26952022-09-07 21:45:26 +0000383 if (0 == ProcessState::self()->getThreadPoolMaxTotalThreadCount()) {
384 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
385 "Threadpool has 0 guaranteed threads. "
386 "Is the threadpool configured properly? "
387 "See ProcessState::startThreadPool and "
388 "ProcessState::setThreadPoolMaxThreadCount.");
389 }
Steven Moreland583685e2019-10-02 16:45:11 -0700390 return nullptr;
391 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800392 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700393
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000394 sp<Waiter> waiter = sp<Waiter>::make();
Steven Morelanda1d70172021-05-24 22:03:42 +0000395 if (Status status = mTheRealServiceManager->registerForNotifications(name, waiter);
396 !status.isOk()) {
397 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
398 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700399 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800401 Defer unregister ([&] {
402 mTheRealServiceManager->unregisterForNotifications(name, waiter);
403 });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700404
Steven Moreland583685e2019-10-02 16:45:11 -0700405 while(true) {
406 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000407 // It would be really nice if we could read binder commands on this
408 // thread instead of needing a threadpool to be started, but for
409 // instance, if we call getAndExecuteCommand, it might be the case
410 // that another thread serves the callback, and we never get a
411 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700412 std::unique_lock<std::mutex> lock(waiter->mMutex);
413 using std::literals::chrono_literals::operator""s;
414 waiter->mCv.wait_for(lock, 1s, [&] {
415 return waiter->mBinder != nullptr;
416 });
417 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700418 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419
Elie Kheirallah27c26952022-09-07 21:45:26 +0000420 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
421 "threadpool: %zu. Are binder threads started and available?)",
422 name.c_str(), ProcessState::self()->getThreadPoolMaxTotalThreadCount());
Steven Morelandf2677e22020-07-14 19:58:08 +0000423
Steven Moreland583685e2019-10-02 16:45:11 -0700424 // Handle race condition for lazy services. Here is what can happen:
425 // - the service dies (not processed by init yet).
426 // - sm processes death notification.
427 // - sm gets getService and calls init to start service.
428 // - init gets the start signal, but the service already appears
429 // started, so it does nothing.
430 // - init gets death signal, but doesn't know it needs to restart
431 // the service
432 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700433 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000434 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
435 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700436 return nullptr;
437 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800438 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700439 }
Steven Moreland583685e2019-10-02 16:45:11 -0700440}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800441
Steven Morelandb82b8f82019-10-28 10:52:34 -0700442bool ServiceManagerShim::isDeclared(const String16& name) {
443 bool declared;
Steven Morelanda1d70172021-05-24 22:03:42 +0000444 if (Status status = mTheRealServiceManager->isDeclared(String8(name).c_str(), &declared);
445 !status.isOk()) {
446 ALOGW("Failed to get isDeclard for %s: %s", String8(name).c_str(),
447 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700448 return false;
449 }
450 return declared;
451}
452
Steven Moreland2e293aa2020-09-23 00:25:16 +0000453Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
454 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000455 if (Status status =
456 mTheRealServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
457 !status.isOk()) {
458 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
459 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000460 return {};
461 }
462
463 Vector<String16> res;
464 res.setCapacity(out.size());
465 for (const std::string& instance : out) {
466 res.push(String16(instance.c_str()));
467 }
468 return res;
469}
470
Steven Morelandedd4e072021-04-21 00:27:29 +0000471std::optional<String16> ServiceManagerShim::updatableViaApex(const String16& name) {
472 std::optional<std::string> declared;
Steven Morelanda1d70172021-05-24 22:03:42 +0000473 if (Status status = mTheRealServiceManager->updatableViaApex(String8(name).c_str(), &declared);
474 !status.isOk()) {
475 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
476 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000477 return std::nullopt;
478 }
479 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
480}
481
Devin Moore5e4c2f12021-09-09 22:36:33 +0000482std::optional<IServiceManager::ConnectionInfo> ServiceManagerShim::getConnectionInfo(
483 const String16& name) {
484 std::optional<os::ConnectionInfo> connectionInfo;
485 if (Status status =
486 mTheRealServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
487 !status.isOk()) {
488 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
489 status.toString8().c_str());
490 }
491 return connectionInfo.has_value()
492 ? std::make_optional<IServiceManager::ConnectionInfo>(
493 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
494 : std::nullopt;
495}
496
Jayant Chowdhary30700942022-01-31 14:12:40 -0800497status_t ServiceManagerShim::registerForNotifications(const String16& name,
498 const sp<AidlRegistrationCallback>& cb) {
499 if (cb == nullptr) {
500 ALOGE("%s: null cb passed", __FUNCTION__);
501 return BAD_VALUE;
502 }
503 std::string nameStr = String8(name).c_str();
504 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
505 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
506 if (Status status =
507 mTheRealServiceManager->registerForNotifications(nameStr, registrationWaiter);
508 !status.isOk()) {
509 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
510 status.toString8().c_str());
511 return UNKNOWN_ERROR;
512 }
513 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
514 return OK;
515}
516
517void ServiceManagerShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
518 ServiceCallbackMap::iterator* it,
519 sp<RegistrationWaiter>* waiter) {
520 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
521 for (auto lit = localRegistrationAndWaiters.begin();
522 lit != localRegistrationAndWaiters.end();) {
523 if (lit->first == cb) {
524 if (waiter) {
525 *waiter = lit->second;
526 }
527 lit = localRegistrationAndWaiters.erase(lit);
528 } else {
529 ++lit;
530 }
531 }
532
533 if (localRegistrationAndWaiters.empty()) {
534 mNameToRegistrationCallback.erase(*it);
535 }
536}
537
538status_t ServiceManagerShim::unregisterForNotifications(const String16& name,
539 const sp<AidlRegistrationCallback>& cb) {
540 if (cb == nullptr) {
541 ALOGE("%s: null cb passed", __FUNCTION__);
542 return BAD_VALUE;
543 }
544 std::string nameStr = String8(name).c_str();
545 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
546 auto it = mNameToRegistrationCallback.find(nameStr);
547 sp<RegistrationWaiter> registrationWaiter;
548 if (it != mNameToRegistrationCallback.end()) {
549 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
550 } else {
551 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
552 return BAD_VALUE;
553 }
554 if (registrationWaiter == nullptr) {
555 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
556 return BAD_VALUE;
557 }
558 if (Status status = mTheRealServiceManager->unregisterForNotifications(String8(name).c_str(),
559 registrationWaiter);
560 !status.isOk()) {
561 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
562 String8(name).c_str(), status.toString8().c_str());
563 return UNKNOWN_ERROR;
564 }
565 return OK;
566}
567
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000568std::vector<IServiceManager::ServiceDebugInfo> ServiceManagerShim::getServiceDebugInfo() {
569 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
570 std::vector<IServiceManager::ServiceDebugInfo> ret;
571 if (Status status = mTheRealServiceManager->getServiceDebugInfo(&serviceDebugInfos);
572 !status.isOk()) {
573 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
574 return ret;
575 }
576 for (const auto& serviceDebugInfo : serviceDebugInfos) {
577 IServiceManager::ServiceDebugInfo retInfo;
578 retInfo.pid = serviceDebugInfo.debugPid;
579 retInfo.name = serviceDebugInfo.name;
580 ret.emplace_back(retInfo);
581 }
582 return ret;
583}
584
Yifan Hongf7760012021-06-04 16:04:42 -0700585#ifndef __ANDROID__
586// ServiceManagerShim for host. Implements the old libbinder android::IServiceManager API.
587// The internal implementation of the AIDL interface android::os::IServiceManager calls into
588// on-device service manager.
589class ServiceManagerHostShim : public ServiceManagerShim {
590public:
Yifan Hong5a05ef72021-10-08 17:33:47 -0700591 ServiceManagerHostShim(const sp<AidlServiceManager>& impl,
592 const RpcDelegateServiceManagerOptions& options)
593 : ServiceManagerShim(impl), mOptions(options) {}
Yifan Hongf7760012021-06-04 16:04:42 -0700594 // ServiceManagerShim::getService is based on checkService, so no need to override it.
595 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700596 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700597 }
598
599protected:
600 // Override realGetService for ServiceManagerShim::waitForService.
601 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700602 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700603 return Status::ok();
604 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700605
606private:
607 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700608};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700609sp<IServiceManager> createRpcDelegateServiceManager(
610 const RpcDelegateServiceManagerOptions& options) {
611 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700612 if (binder == nullptr) {
613 ALOGE("getDeviceService(\"manager\") returns null");
614 return nullptr;
615 }
616 auto interface = AidlServiceManager::asInterface(binder);
617 if (interface == nullptr) {
618 ALOGE("getDeviceService(\"manager\") returns non service manager");
619 return nullptr;
620 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700621 return sp<ServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700622}
623#endif
624
Steven Moreland61ff8492019-09-26 16:05:45 -0700625} // namespace android