blob: ca067e2d7f480a8ee671cf0725aa7ac8f32d37ed [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>
Steven Moreland28723ae2019-04-01 18:52:30 -070038#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039
Steven Morelanda4853cd2019-07-12 15:44:37 -070040#include "Static.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080041
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042namespace android {
43
Steven Moreland80e1e6d2019-06-21 12:35:59 -070044using AidlServiceManager = android::os::IServiceManager;
45using android::binder::Status;
46
Steven Moreland635a2912019-10-02 15:50:10 -070047// libbinder's IServiceManager.h can't rely on the values generated by AIDL
48// because many places use its headers via include_dirs (meaning, without
49// declaring the dependency in the build system). So, for now, we can just check
50// the values here.
51static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
52static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
53static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
54static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
55static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
56static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
57
Steven Moreland583685e2019-10-02 16:45:11 -070058const String16& IServiceManager::getInterfaceDescriptor() const {
59 return AidlServiceManager::descriptor;
60}
61IServiceManager::IServiceManager() {}
62IServiceManager::~IServiceManager() {}
63
64// From the old libbinder IServiceManager interface to IServiceManager.
65class ServiceManagerShim : public IServiceManager
66{
67public:
68 explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
69
70 sp<IBinder> getService(const String16& name) const override;
71 sp<IBinder> checkService(const String16& name) const override;
72 status_t addService(const String16& name, const sp<IBinder>& service,
73 bool allowIsolated, int dumpsysPriority) override;
74 Vector<String16> listServices(int dumpsysPriority) override;
75 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070076 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +000077 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Moreland583685e2019-10-02 16:45:11 -070078
79 // for legacy ABI
80 const String16& getInterfaceDescriptor() const override {
81 return mTheRealServiceManager->getInterfaceDescriptor();
82 }
83 IBinder* onAsBinder() override {
84 return IInterface::asBinder(mTheRealServiceManager).get();
85 }
86private:
87 sp<AidlServiceManager> mTheRealServiceManager;
88};
89
Steven Moreland1698ffd2020-05-15 23:43:52 +000090[[clang::no_destroy]] static std::once_flag gSmOnce;
91[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Brett Chabot38dbade2020-01-24 12:59:43 -080092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093sp<IServiceManager> defaultServiceManager()
94{
Martijn Coenen402c8672020-02-03 10:01:36 +010095 std::call_once(gSmOnce, []() {
96 sp<AidlServiceManager> sm = nullptr;
97 while (sm == nullptr) {
98 sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));
99 if (sm == nullptr) {
Steven Moreland39a57212020-05-19 18:10:07 +0000100 ALOGE("Waiting 1s on context object on %s.", ProcessState::self()->getDriverName().c_str());
Todd Poynora7b0f042013-06-18 17:25:37 -0700101 sleep(1);
Martijn Coenen402c8672020-02-03 10:01:36 +0100102 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103 }
Martijn Coenen402c8672020-02-03 10:01:36 +0100104
105 gDefaultServiceManager = new ServiceManagerShim(sm);
106 });
Daniel Eratc2832702015-10-13 15:29:32 -0600107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108 return gDefaultServiceManager;
109}
110
Brett Chabot38dbade2020-01-24 12:59:43 -0800111void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100112 bool called = false;
113 std::call_once(gSmOnce, [&]() {
114 gDefaultServiceManager = sm;
115 called = true;
116 });
117
118 if (!called) {
119 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
120 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800121}
122
Steven Morelanded3b5632019-09-20 11:24:28 -0700123#if !defined(__ANDROID_VNDK__) && defined(__ANDROID__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900124// IPermissionController is not accessible to vendors
125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126bool checkCallingPermission(const String16& permission)
127{
Yi Kongfdd8da92018-06-07 17:52:27 -0700128 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129}
130
131static String16 _permission("permission");
132
Mathias Agopian375f5632009-06-15 18:24:59 -0700133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
135{
136 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700137 pid_t pid = ipcState->getCallingPid();
138 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700140 if (outUid) *outUid = uid;
141 return checkPermission(permission, pid, uid);
142}
143
144bool checkPermission(const String16& permission, pid_t pid, uid_t uid)
145{
Steven Moreland92b17c62019-04-02 15:46:24 -0700146 static Mutex gPermissionControllerLock;
147 static sp<IPermissionController> gPermissionController;
148
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800149 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700150 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800151 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700152 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600153
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800154 int64_t startTime = 0;
155
156 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700157 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158 bool res = pc->checkPermission(permission, pid, uid);
159 if (res) {
160 if (startTime != 0) {
Steve Blocka19954a2012-01-04 20:05:49 +0000161 ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162 (int)((uptimeMillis()-startTime)/1000),
163 String8(permission).string(), uid, pid);
164 }
165 return res;
166 }
Daniel Eratc2832702015-10-13 15:29:32 -0600167
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800169 if (IInterface::asBinder(pc)->isBinderAlive()) {
Steve Block32397c12012-01-05 23:22:43 +0000170 ALOGW("Permission failure: %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 String8(permission).string(), uid, pid);
172 return false;
173 }
Daniel Eratc2832702015-10-13 15:29:32 -0600174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700176 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700178 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700180 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181 }
Daniel Eratc2832702015-10-13 15:29:32 -0600182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183 // Need to retrieve the permission controller.
184 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700185 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186 // Wait for the permission controller to come back...
187 if (startTime == 0) {
188 startTime = uptimeMillis();
Steve Blocka19954a2012-01-04 20:05:49 +0000189 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190 String8(permission).string(), uid, pid);
191 }
192 sleep(1);
193 } else {
194 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600195 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700196 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700198 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199 }
200 }
201}
202
Jiyong Park47f876b2018-04-17 13:56:46 +0900203#endif //__ANDROID_VNDK__
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205// ----------------------------------------------------------------------
206
Steven Moreland583685e2019-10-02 16:45:11 -0700207ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl)
208 : mTheRealServiceManager(impl)
209{}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700210
Steven Moreland5af7d852020-04-29 15:40:29 -0700211// This implementation could be simplified and made more efficient by delegating
212// to waitForService. However, this changes the threading structure in some
213// cases and could potentially break prebuilts. Once we have higher logistical
214// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700215sp<IBinder> ServiceManagerShim::getService(const String16& name) const
216{
217 static bool gSystemBootCompleted = false;
218
219 sp<IBinder> svc = checkService(name);
220 if (svc != nullptr) return svc;
221
222 const bool isVendorService =
223 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Jiyong Park16c6e702020-11-13 20:53:12 +0900224 constexpr int64_t timeout = 5000;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700225 int64_t startTime = uptimeMillis();
Steven Moreland583685e2019-10-02 16:45:11 -0700226 // Vendor code can't access system properties
227 if (!gSystemBootCompleted && !isVendorService) {
228#ifdef __ANDROID__
229 char bootCompleted[PROPERTY_VALUE_MAX];
230 property_get("sys.boot_completed", bootCompleted, "0");
231 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
232#else
233 gSystemBootCompleted = true;
234#endif
235 }
236 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900237 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700238
Tom Cherry8fda97f2020-07-22 17:15:44 -0700239 ALOGI("Waiting for service '%s' on '%s'...", String8(name).string(),
240 ProcessState::self()->getDriverName().c_str());
241
Steven Moreland583685e2019-10-02 16:45:11 -0700242 int n = 0;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700243 while (uptimeMillis() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700244 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700245 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700246
Yunfan Chen788e1c42018-03-29 16:52:09 +0900247 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700248 if (svc != nullptr) {
249 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
250 String8(name).string(), ProcessState::self()->getDriverName().c_str(),
251 uptimeMillis() - startTime);
252 return svc;
253 }
Steven Moreland583685e2019-10-02 16:45:11 -0700254 }
255 ALOGW("Service %s didn't start. Returning NULL", String8(name).string());
256 return nullptr;
257}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900258
Steven Moreland583685e2019-10-02 16:45:11 -0700259sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
260{
261 sp<IBinder> ret;
262 if (!mTheRealServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
263 return nullptr;
264 }
265 return ret;
266}
267
268status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
269 bool allowIsolated, int dumpsysPriority)
270{
271 Status status = mTheRealServiceManager->addService(
272 String8(name).c_str(), service, allowIsolated, dumpsysPriority);
273 return status.exceptionCode();
274}
275
276Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
277{
278 std::vector<std::string> ret;
279 if (!mTheRealServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
280 return {};
281 }
282
283 Vector<String16> res;
284 res.setCapacity(ret.size());
285 for (const std::string& name : ret) {
286 res.push(String16(name.c_str()));
287 }
288 return res;
289}
290
291sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
292{
293 class Waiter : public android::os::BnServiceCallback {
294 Status onRegistration(const std::string& /*name*/,
295 const sp<IBinder>& binder) override {
296 std::unique_lock<std::mutex> lock(mMutex);
297 mBinder = binder;
298 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700299 // Flushing here helps ensure the service's ref count remains accurate
300 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700301 mCv.notify_one();
302 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900303 }
Steven Moreland583685e2019-10-02 16:45:11 -0700304 public:
305 sp<IBinder> mBinder;
306 std::mutex mMutex;
307 std::condition_variable mCv;
308 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900309
Jon Spivackfed6db42019-11-18 16:43:59 -0800310 // Simple RAII object to ensure a function call immediately before going out of scope
311 class Defer {
312 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900313 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800314 ~Defer() { mF(); }
315 private:
316 std::function<void()> mF;
317 };
318
Steven Moreland583685e2019-10-02 16:45:11 -0700319 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900320
Steven Moreland583685e2019-10-02 16:45:11 -0700321 sp<IBinder> out;
322 if (!mTheRealServiceManager->getService(name, &out).isOk()) {
323 return nullptr;
324 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800325 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700326
327 sp<Waiter> waiter = new Waiter;
328 if (!mTheRealServiceManager->registerForNotifications(
329 name, waiter).isOk()) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700330 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800332 Defer unregister ([&] {
333 mTheRealServiceManager->unregisterForNotifications(name, waiter);
334 });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700335
Steven Moreland583685e2019-10-02 16:45:11 -0700336 while(true) {
337 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000338 // It would be really nice if we could read binder commands on this
339 // thread instead of needing a threadpool to be started, but for
340 // instance, if we call getAndExecuteCommand, it might be the case
341 // that another thread serves the callback, and we never get a
342 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700343 std::unique_lock<std::mutex> lock(waiter->mMutex);
344 using std::literals::chrono_literals::operator""s;
345 waiter->mCv.wait_for(lock, 1s, [&] {
346 return waiter->mBinder != nullptr;
347 });
348 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700349 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350
Steven Morelandf2677e22020-07-14 19:58:08 +0000351 ALOGW("Waited one second for %s (is service started? are binder threads started and available?)", name.c_str());
352
Steven Moreland583685e2019-10-02 16:45:11 -0700353 // Handle race condition for lazy services. Here is what can happen:
354 // - the service dies (not processed by init yet).
355 // - sm processes death notification.
356 // - sm gets getService and calls init to start service.
357 // - init gets the start signal, but the service already appears
358 // started, so it does nothing.
359 // - init gets death signal, but doesn't know it needs to restart
360 // the service
361 // - we need to request service again to get it to start
Jon Spivack0d844302019-07-22 18:40:34 -0700362 if (!mTheRealServiceManager->getService(name, &out).isOk()) {
Steven Moreland1c47b582019-08-27 18:05:27 -0700363 return nullptr;
364 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800365 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700366 }
Steven Moreland583685e2019-10-02 16:45:11 -0700367}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368
Steven Morelandb82b8f82019-10-28 10:52:34 -0700369bool ServiceManagerShim::isDeclared(const String16& name) {
370 bool declared;
371 if (!mTheRealServiceManager->isDeclared(String8(name).c_str(), &declared).isOk()) {
372 return false;
373 }
374 return declared;
375}
376
Steven Moreland2e293aa2020-09-23 00:25:16 +0000377Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
378 std::vector<std::string> out;
379 if (!mTheRealServiceManager->getDeclaredInstances(String8(interface).c_str(), &out).isOk()) {
380 return {};
381 }
382
383 Vector<String16> res;
384 res.setCapacity(out.size());
385 for (const std::string& instance : out) {
386 res.push(String16(instance.c_str()));
387 }
388 return res;
389}
390
Steven Moreland61ff8492019-09-26 16:05:45 -0700391} // namespace android