blob: ea2f8d2274b5c9022fb56aa598a8b02033aed76c [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
17#define LOG_TAG "ServiceManager"
18
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 Moreland1c47b582019-08-27 18:05:27 -070024#include <android/os/BnServiceCallback.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070025#include <android/os/IServiceManager.h>
Mathias Agopian375f5632009-06-15 18:24:59 -070026#include <binder/IPCThreadState.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070027#include <binder/Parcel.h>
28#include <utils/Log.h>
29#include <utils/String8.h>
30#include <utils/SystemClock.h>
31
Jiyong Park47f876b2018-04-17 13:56:46 +090032#ifndef __ANDROID_VNDK__
33#include <binder/IPermissionController.h>
34#endif
Steven Moreland28723ae2019-04-01 18:52:30 -070035
Steven Morelanded3b5632019-09-20 11:24:28 -070036#ifdef __ANDROID__
Yunfan Chen788e1c42018-03-29 16:52:09 +090037#include <cutils/properties.h>
Yifan Hongf7760012021-06-04 16:04:42 -070038#else
39#include "ServiceManagerHost.h"
Steven Moreland28723ae2019-04-01 18:52:30 -070040#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080041
Steven Morelanda4853cd2019-07-12 15:44:37 -070042#include "Static.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080043
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080044namespace android {
45
Jayant Chowdhary30700942022-01-31 14:12:40 -080046using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
47
Steven Moreland80e1e6d2019-06-21 12:35:59 -070048using AidlServiceManager = android::os::IServiceManager;
49using android::binder::Status;
50
Steven Moreland635a2912019-10-02 15:50:10 -070051// libbinder's IServiceManager.h can't rely on the values generated by AIDL
52// because many places use its headers via include_dirs (meaning, without
53// declaring the dependency in the build system). So, for now, we can just check
54// the values here.
55static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
56static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
57static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
58static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
59static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
60static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
61
Steven Moreland583685e2019-10-02 16:45:11 -070062const String16& IServiceManager::getInterfaceDescriptor() const {
63 return AidlServiceManager::descriptor;
64}
65IServiceManager::IServiceManager() {}
66IServiceManager::~IServiceManager() {}
67
68// From the old libbinder IServiceManager interface to IServiceManager.
69class ServiceManagerShim : public IServiceManager
70{
71public:
72 explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
73
74 sp<IBinder> getService(const String16& name) const override;
75 sp<IBinder> checkService(const String16& name) const override;
76 status_t addService(const String16& name, const sp<IBinder>& service,
77 bool allowIsolated, int dumpsysPriority) override;
78 Vector<String16> listServices(int dumpsysPriority) override;
79 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070080 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +000081 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +000082 std::optional<String16> updatableViaApex(const String16& name) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +000083 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -080084 class RegistrationWaiter : public android::os::BnServiceCallback {
85 public:
86 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
87 : mImpl(callback) {}
88 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
89 mImpl->onServiceRegistration(String16(name.c_str()), binder);
90 return Status::ok();
91 }
Steven Moreland583685e2019-10-02 16:45:11 -070092
Jayant Chowdhary30700942022-01-31 14:12:40 -080093 private:
94 sp<AidlRegistrationCallback> mImpl;
95 };
96
97 status_t registerForNotifications(const String16& service,
98 const sp<AidlRegistrationCallback>& cb) override;
99
100 status_t unregisterForNotifications(const String16& service,
101 const sp<AidlRegistrationCallback>& cb) override;
Steven Moreland583685e2019-10-02 16:45:11 -0700102 // for legacy ABI
103 const String16& getInterfaceDescriptor() const override {
104 return mTheRealServiceManager->getInterfaceDescriptor();
105 }
106 IBinder* onAsBinder() override {
107 return IInterface::asBinder(mTheRealServiceManager).get();
108 }
Yifan Hongf7760012021-06-04 16:04:42 -0700109
110protected:
Steven Moreland583685e2019-10-02 16:45:11 -0700111 sp<AidlServiceManager> mTheRealServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800112 // AidlRegistrationCallback -> services that its been registered for
113 // notifications.
114 using LocalRegistrationAndWaiter =
115 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
116 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
117 ServiceCallbackMap mNameToRegistrationCallback;
118 std::mutex mNameToRegistrationLock;
119
120 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
121 ServiceCallbackMap::iterator* it,
122 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700123
124 // Directly get the service in a way that, for lazy services, requests the service to be started
125 // if it is not currently started. This way, calls directly to ServiceManagerShim::getService
126 // will still have the 5s delay that is expected by a large amount of Android code.
127 //
128 // When implementing ServiceManagerShim, use realGetService instead of
129 // mTheRealServiceManager->getService so that it can be overridden in ServiceManagerHostShim.
130 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
131 return mTheRealServiceManager->getService(name, _aidl_return);
132 }
Steven Moreland583685e2019-10-02 16:45:11 -0700133};
134
Steven Moreland1698ffd2020-05-15 23:43:52 +0000135[[clang::no_destroy]] static std::once_flag gSmOnce;
136[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Brett Chabot38dbade2020-01-24 12:59:43 -0800137
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138sp<IServiceManager> defaultServiceManager()
139{
Martijn Coenen402c8672020-02-03 10:01:36 +0100140 std::call_once(gSmOnce, []() {
141 sp<AidlServiceManager> sm = nullptr;
142 while (sm == nullptr) {
143 sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));
144 if (sm == nullptr) {
Steven Moreland39a57212020-05-19 18:10:07 +0000145 ALOGE("Waiting 1s on context object on %s.", ProcessState::self()->getDriverName().c_str());
Todd Poynora7b0f042013-06-18 17:25:37 -0700146 sleep(1);
Martijn Coenen402c8672020-02-03 10:01:36 +0100147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800148 }
Martijn Coenen402c8672020-02-03 10:01:36 +0100149
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000150 gDefaultServiceManager = sp<ServiceManagerShim>::make(sm);
Martijn Coenen402c8672020-02-03 10:01:36 +0100151 });
Daniel Eratc2832702015-10-13 15:29:32 -0600152
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800153 return gDefaultServiceManager;
154}
155
Brett Chabot38dbade2020-01-24 12:59:43 -0800156void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100157 bool called = false;
158 std::call_once(gSmOnce, [&]() {
159 gDefaultServiceManager = sm;
160 called = true;
161 });
162
163 if (!called) {
164 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
165 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800166}
167
Steven Morelanded3b5632019-09-20 11:24:28 -0700168#if !defined(__ANDROID_VNDK__) && defined(__ANDROID__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900169// IPermissionController is not accessible to vendors
170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171bool checkCallingPermission(const String16& permission)
172{
Yi Kongfdd8da92018-06-07 17:52:27 -0700173 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174}
175
Steven Moreland1b264072021-06-03 23:04:02 +0000176static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
179{
180 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700181 pid_t pid = ipcState->getCallingPid();
182 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700184 if (outUid) *outUid = uid;
185 return checkPermission(permission, pid, uid);
186}
187
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000188bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Steven Moreland92b17c62019-04-02 15:46:24 -0700189 static Mutex gPermissionControllerLock;
190 static sp<IPermissionController> gPermissionController;
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700193 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700195 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 int64_t startTime = 0;
198
199 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700200 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 bool res = pc->checkPermission(permission, pid, uid);
202 if (res) {
203 if (startTime != 0) {
Steve Blocka19954a2012-01-04 20:05:49 +0000204 ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 (int)((uptimeMillis()-startTime)/1000),
206 String8(permission).string(), uid, pid);
207 }
208 return res;
209 }
Daniel Eratc2832702015-10-13 15:29:32 -0600210
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800212 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000213 if (logPermissionFailure) {
214 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).string(),
215 uid, pid);
216 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217 return false;
218 }
Daniel Eratc2832702015-10-13 15:29:32 -0600219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700221 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700223 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700225 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 }
Daniel Eratc2832702015-10-13 15:29:32 -0600227
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 // Need to retrieve the permission controller.
229 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700230 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // Wait for the permission controller to come back...
232 if (startTime == 0) {
233 startTime = uptimeMillis();
Steve Blocka19954a2012-01-04 20:05:49 +0000234 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235 String8(permission).string(), uid, pid);
236 }
237 sleep(1);
238 } else {
239 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600240 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700241 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800242 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700243 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 }
245 }
246}
247
Jiyong Park47f876b2018-04-17 13:56:46 +0900248#endif //__ANDROID_VNDK__
249
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250// ----------------------------------------------------------------------
251
Steven Moreland583685e2019-10-02 16:45:11 -0700252ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl)
253 : mTheRealServiceManager(impl)
254{}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700255
Steven Moreland5af7d852020-04-29 15:40:29 -0700256// This implementation could be simplified and made more efficient by delegating
257// to waitForService. However, this changes the threading structure in some
258// cases and could potentially break prebuilts. Once we have higher logistical
259// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700260sp<IBinder> ServiceManagerShim::getService(const String16& name) const
261{
262 static bool gSystemBootCompleted = false;
263
264 sp<IBinder> svc = checkService(name);
265 if (svc != nullptr) return svc;
266
267 const bool isVendorService =
268 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Jiyong Park16c6e702020-11-13 20:53:12 +0900269 constexpr int64_t timeout = 5000;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700270 int64_t startTime = uptimeMillis();
Steven Moreland583685e2019-10-02 16:45:11 -0700271 // Vendor code can't access system properties
272 if (!gSystemBootCompleted && !isVendorService) {
273#ifdef __ANDROID__
274 char bootCompleted[PROPERTY_VALUE_MAX];
275 property_get("sys.boot_completed", bootCompleted, "0");
276 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
277#else
278 gSystemBootCompleted = true;
279#endif
280 }
281 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900282 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700283
Tom Cherry8fda97f2020-07-22 17:15:44 -0700284 ALOGI("Waiting for service '%s' on '%s'...", String8(name).string(),
285 ProcessState::self()->getDriverName().c_str());
286
Steven Moreland583685e2019-10-02 16:45:11 -0700287 int n = 0;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700288 while (uptimeMillis() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700289 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700290 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700291
Yunfan Chen788e1c42018-03-29 16:52:09 +0900292 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700293 if (svc != nullptr) {
294 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
295 String8(name).string(), ProcessState::self()->getDriverName().c_str(),
296 uptimeMillis() - startTime);
297 return svc;
298 }
Steven Moreland583685e2019-10-02 16:45:11 -0700299 }
300 ALOGW("Service %s didn't start. Returning NULL", String8(name).string());
301 return nullptr;
302}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900303
Steven Moreland583685e2019-10-02 16:45:11 -0700304sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
305{
306 sp<IBinder> ret;
307 if (!mTheRealServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
308 return nullptr;
309 }
310 return ret;
311}
312
313status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
314 bool allowIsolated, int dumpsysPriority)
315{
316 Status status = mTheRealServiceManager->addService(
317 String8(name).c_str(), service, allowIsolated, dumpsysPriority);
318 return status.exceptionCode();
319}
320
321Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
322{
323 std::vector<std::string> ret;
324 if (!mTheRealServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
325 return {};
326 }
327
328 Vector<String16> res;
329 res.setCapacity(ret.size());
330 for (const std::string& name : ret) {
331 res.push(String16(name.c_str()));
332 }
333 return res;
334}
335
336sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
337{
338 class Waiter : public android::os::BnServiceCallback {
339 Status onRegistration(const std::string& /*name*/,
340 const sp<IBinder>& binder) override {
341 std::unique_lock<std::mutex> lock(mMutex);
342 mBinder = binder;
343 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700344 // Flushing here helps ensure the service's ref count remains accurate
345 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700346 mCv.notify_one();
347 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900348 }
Steven Moreland583685e2019-10-02 16:45:11 -0700349 public:
350 sp<IBinder> mBinder;
351 std::mutex mMutex;
352 std::condition_variable mCv;
353 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900354
Jon Spivackfed6db42019-11-18 16:43:59 -0800355 // Simple RAII object to ensure a function call immediately before going out of scope
356 class Defer {
357 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900358 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800359 ~Defer() { mF(); }
360 private:
361 std::function<void()> mF;
362 };
363
Steven Moreland583685e2019-10-02 16:45:11 -0700364 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900365
Steven Moreland583685e2019-10-02 16:45:11 -0700366 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700367 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000368 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
369 status.toString8().c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700370 return nullptr;
371 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800372 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700373
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000374 sp<Waiter> waiter = sp<Waiter>::make();
Steven Morelanda1d70172021-05-24 22:03:42 +0000375 if (Status status = mTheRealServiceManager->registerForNotifications(name, waiter);
376 !status.isOk()) {
377 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
378 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700379 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800381 Defer unregister ([&] {
382 mTheRealServiceManager->unregisterForNotifications(name, waiter);
383 });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700384
Steven Moreland583685e2019-10-02 16:45:11 -0700385 while(true) {
386 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000387 // It would be really nice if we could read binder commands on this
388 // thread instead of needing a threadpool to be started, but for
389 // instance, if we call getAndExecuteCommand, it might be the case
390 // that another thread serves the callback, and we never get a
391 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700392 std::unique_lock<std::mutex> lock(waiter->mMutex);
393 using std::literals::chrono_literals::operator""s;
394 waiter->mCv.wait_for(lock, 1s, [&] {
395 return waiter->mBinder != nullptr;
396 });
397 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700398 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399
Steven Morelandf2677e22020-07-14 19:58:08 +0000400 ALOGW("Waited one second for %s (is service started? are binder threads started and available?)", name.c_str());
401
Steven Moreland583685e2019-10-02 16:45:11 -0700402 // Handle race condition for lazy services. Here is what can happen:
403 // - the service dies (not processed by init yet).
404 // - sm processes death notification.
405 // - sm gets getService and calls init to start service.
406 // - init gets the start signal, but the service already appears
407 // started, so it does nothing.
408 // - init gets death signal, but doesn't know it needs to restart
409 // the service
410 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700411 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000412 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
413 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700414 return nullptr;
415 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800416 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700417 }
Steven Moreland583685e2019-10-02 16:45:11 -0700418}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419
Steven Morelandb82b8f82019-10-28 10:52:34 -0700420bool ServiceManagerShim::isDeclared(const String16& name) {
421 bool declared;
Steven Morelanda1d70172021-05-24 22:03:42 +0000422 if (Status status = mTheRealServiceManager->isDeclared(String8(name).c_str(), &declared);
423 !status.isOk()) {
424 ALOGW("Failed to get isDeclard for %s: %s", String8(name).c_str(),
425 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700426 return false;
427 }
428 return declared;
429}
430
Steven Moreland2e293aa2020-09-23 00:25:16 +0000431Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
432 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000433 if (Status status =
434 mTheRealServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
435 !status.isOk()) {
436 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
437 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000438 return {};
439 }
440
441 Vector<String16> res;
442 res.setCapacity(out.size());
443 for (const std::string& instance : out) {
444 res.push(String16(instance.c_str()));
445 }
446 return res;
447}
448
Steven Morelandedd4e072021-04-21 00:27:29 +0000449std::optional<String16> ServiceManagerShim::updatableViaApex(const String16& name) {
450 std::optional<std::string> declared;
Steven Morelanda1d70172021-05-24 22:03:42 +0000451 if (Status status = mTheRealServiceManager->updatableViaApex(String8(name).c_str(), &declared);
452 !status.isOk()) {
453 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
454 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000455 return std::nullopt;
456 }
457 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
458}
459
Devin Moore5e4c2f12021-09-09 22:36:33 +0000460std::optional<IServiceManager::ConnectionInfo> ServiceManagerShim::getConnectionInfo(
461 const String16& name) {
462 std::optional<os::ConnectionInfo> connectionInfo;
463 if (Status status =
464 mTheRealServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
465 !status.isOk()) {
466 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
467 status.toString8().c_str());
468 }
469 return connectionInfo.has_value()
470 ? std::make_optional<IServiceManager::ConnectionInfo>(
471 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
472 : std::nullopt;
473}
474
Jayant Chowdhary30700942022-01-31 14:12:40 -0800475status_t ServiceManagerShim::registerForNotifications(const String16& name,
476 const sp<AidlRegistrationCallback>& cb) {
477 if (cb == nullptr) {
478 ALOGE("%s: null cb passed", __FUNCTION__);
479 return BAD_VALUE;
480 }
481 std::string nameStr = String8(name).c_str();
482 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
483 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
484 if (Status status =
485 mTheRealServiceManager->registerForNotifications(nameStr, registrationWaiter);
486 !status.isOk()) {
487 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
488 status.toString8().c_str());
489 return UNKNOWN_ERROR;
490 }
491 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
492 return OK;
493}
494
495void ServiceManagerShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
496 ServiceCallbackMap::iterator* it,
497 sp<RegistrationWaiter>* waiter) {
498 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
499 for (auto lit = localRegistrationAndWaiters.begin();
500 lit != localRegistrationAndWaiters.end();) {
501 if (lit->first == cb) {
502 if (waiter) {
503 *waiter = lit->second;
504 }
505 lit = localRegistrationAndWaiters.erase(lit);
506 } else {
507 ++lit;
508 }
509 }
510
511 if (localRegistrationAndWaiters.empty()) {
512 mNameToRegistrationCallback.erase(*it);
513 }
514}
515
516status_t ServiceManagerShim::unregisterForNotifications(const String16& name,
517 const sp<AidlRegistrationCallback>& cb) {
518 if (cb == nullptr) {
519 ALOGE("%s: null cb passed", __FUNCTION__);
520 return BAD_VALUE;
521 }
522 std::string nameStr = String8(name).c_str();
523 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
524 auto it = mNameToRegistrationCallback.find(nameStr);
525 sp<RegistrationWaiter> registrationWaiter;
526 if (it != mNameToRegistrationCallback.end()) {
527 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
528 } else {
529 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
530 return BAD_VALUE;
531 }
532 if (registrationWaiter == nullptr) {
533 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
534 return BAD_VALUE;
535 }
536 if (Status status = mTheRealServiceManager->unregisterForNotifications(String8(name).c_str(),
537 registrationWaiter);
538 !status.isOk()) {
539 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
540 String8(name).c_str(), status.toString8().c_str());
541 return UNKNOWN_ERROR;
542 }
543 return OK;
544}
545
Yifan Hongf7760012021-06-04 16:04:42 -0700546#ifndef __ANDROID__
547// ServiceManagerShim for host. Implements the old libbinder android::IServiceManager API.
548// The internal implementation of the AIDL interface android::os::IServiceManager calls into
549// on-device service manager.
550class ServiceManagerHostShim : public ServiceManagerShim {
551public:
Yifan Hong5a05ef72021-10-08 17:33:47 -0700552 ServiceManagerHostShim(const sp<AidlServiceManager>& impl,
553 const RpcDelegateServiceManagerOptions& options)
554 : ServiceManagerShim(impl), mOptions(options) {}
Yifan Hongf7760012021-06-04 16:04:42 -0700555 // ServiceManagerShim::getService is based on checkService, so no need to override it.
556 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700557 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700558 }
559
560protected:
561 // Override realGetService for ServiceManagerShim::waitForService.
562 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700563 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700564 return Status::ok();
565 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700566
567private:
568 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700569};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700570sp<IServiceManager> createRpcDelegateServiceManager(
571 const RpcDelegateServiceManagerOptions& options) {
572 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700573 if (binder == nullptr) {
574 ALOGE("getDeviceService(\"manager\") returns null");
575 return nullptr;
576 }
577 auto interface = AidlServiceManager::asInterface(binder);
578 if (interface == nullptr) {
579 ALOGE("getDeviceService(\"manager\") returns non service manager");
580 return nullptr;
581 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700582 return sp<ServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700583}
584#endif
585
Steven Moreland61ff8492019-09-26 16:05:45 -0700586} // namespace android