blob: 9aa82d908c2b90443dd7163af3e89c0013339535 [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 Moreland583685e2019-10-02 16:45:11 -070077
78 // for legacy ABI
79 const String16& getInterfaceDescriptor() const override {
80 return mTheRealServiceManager->getInterfaceDescriptor();
81 }
82 IBinder* onAsBinder() override {
83 return IInterface::asBinder(mTheRealServiceManager).get();
84 }
85private:
86 sp<AidlServiceManager> mTheRealServiceManager;
87};
88
Steven Moreland1698ffd2020-05-15 23:43:52 +000089[[clang::no_destroy]] static std::once_flag gSmOnce;
90[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Brett Chabot38dbade2020-01-24 12:59:43 -080091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092sp<IServiceManager> defaultServiceManager()
93{
Martijn Coenen402c8672020-02-03 10:01:36 +010094 std::call_once(gSmOnce, []() {
95 sp<AidlServiceManager> sm = nullptr;
96 while (sm == nullptr) {
97 sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));
98 if (sm == nullptr) {
Steven Moreland39a57212020-05-19 18:10:07 +000099 ALOGE("Waiting 1s on context object on %s.", ProcessState::self()->getDriverName().c_str());
Todd Poynora7b0f042013-06-18 17:25:37 -0700100 sleep(1);
Martijn Coenen402c8672020-02-03 10:01:36 +0100101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102 }
Martijn Coenen402c8672020-02-03 10:01:36 +0100103
104 gDefaultServiceManager = new ServiceManagerShim(sm);
105 });
Daniel Eratc2832702015-10-13 15:29:32 -0600106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107 return gDefaultServiceManager;
108}
109
Brett Chabot38dbade2020-01-24 12:59:43 -0800110void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100111 bool called = false;
112 std::call_once(gSmOnce, [&]() {
113 gDefaultServiceManager = sm;
114 called = true;
115 });
116
117 if (!called) {
118 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
119 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800120}
121
Steven Morelanded3b5632019-09-20 11:24:28 -0700122#if !defined(__ANDROID_VNDK__) && defined(__ANDROID__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900123// IPermissionController is not accessible to vendors
124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125bool checkCallingPermission(const String16& permission)
126{
Yi Kongfdd8da92018-06-07 17:52:27 -0700127 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128}
129
130static String16 _permission("permission");
131
Mathias Agopian375f5632009-06-15 18:24:59 -0700132
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
134{
135 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700136 pid_t pid = ipcState->getCallingPid();
137 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700139 if (outUid) *outUid = uid;
140 return checkPermission(permission, pid, uid);
141}
142
143bool checkPermission(const String16& permission, pid_t pid, uid_t uid)
144{
Steven Moreland92b17c62019-04-02 15:46:24 -0700145 static Mutex gPermissionControllerLock;
146 static sp<IPermissionController> gPermissionController;
147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800148 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700149 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700151 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600152
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800153 int64_t startTime = 0;
154
155 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700156 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157 bool res = pc->checkPermission(permission, pid, uid);
158 if (res) {
159 if (startTime != 0) {
Steve Blocka19954a2012-01-04 20:05:49 +0000160 ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161 (int)((uptimeMillis()-startTime)/1000),
162 String8(permission).string(), uid, pid);
163 }
164 return res;
165 }
Daniel Eratc2832702015-10-13 15:29:32 -0600166
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800168 if (IInterface::asBinder(pc)->isBinderAlive()) {
Steve Block32397c12012-01-05 23:22:43 +0000169 ALOGW("Permission failure: %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 String8(permission).string(), uid, pid);
171 return false;
172 }
Daniel Eratc2832702015-10-13 15:29:32 -0600173
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700175 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700177 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700179 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800180 }
Daniel Eratc2832702015-10-13 15:29:32 -0600181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182 // Need to retrieve the permission controller.
183 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700184 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185 // Wait for the permission controller to come back...
186 if (startTime == 0) {
187 startTime = uptimeMillis();
Steve Blocka19954a2012-01-04 20:05:49 +0000188 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189 String8(permission).string(), uid, pid);
190 }
191 sleep(1);
192 } else {
193 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600194 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700195 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700197 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198 }
199 }
200}
201
Jiyong Park47f876b2018-04-17 13:56:46 +0900202#endif //__ANDROID_VNDK__
203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204// ----------------------------------------------------------------------
205
Steven Moreland583685e2019-10-02 16:45:11 -0700206ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl)
207 : mTheRealServiceManager(impl)
208{}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700209
Steven Moreland5af7d852020-04-29 15:40:29 -0700210// This implementation could be simplified and made more efficient by delegating
211// to waitForService. However, this changes the threading structure in some
212// cases and could potentially break prebuilts. Once we have higher logistical
213// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700214sp<IBinder> ServiceManagerShim::getService(const String16& name) const
215{
216 static bool gSystemBootCompleted = false;
217
218 sp<IBinder> svc = checkService(name);
219 if (svc != nullptr) return svc;
220
221 const bool isVendorService =
222 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700223 const long timeout = 5000;
224 int64_t startTime = uptimeMillis();
Steven Moreland583685e2019-10-02 16:45:11 -0700225 // Vendor code can't access system properties
226 if (!gSystemBootCompleted && !isVendorService) {
227#ifdef __ANDROID__
228 char bootCompleted[PROPERTY_VALUE_MAX];
229 property_get("sys.boot_completed", bootCompleted, "0");
230 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
231#else
232 gSystemBootCompleted = true;
233#endif
234 }
235 // retry interval in millisecond; note that vendor services stay at 100ms
236 const long sleepTime = gSystemBootCompleted ? 1000 : 100;
237
Tom Cherry8fda97f2020-07-22 17:15:44 -0700238 ALOGI("Waiting for service '%s' on '%s'...", String8(name).string(),
239 ProcessState::self()->getDriverName().c_str());
240
Steven Moreland583685e2019-10-02 16:45:11 -0700241 int n = 0;
Tom Cherry8fda97f2020-07-22 17:15:44 -0700242 while (uptimeMillis() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700243 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700244 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700245
Yunfan Chen788e1c42018-03-29 16:52:09 +0900246 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700247 if (svc != nullptr) {
248 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
249 String8(name).string(), ProcessState::self()->getDriverName().c_str(),
250 uptimeMillis() - startTime);
251 return svc;
252 }
Steven Moreland583685e2019-10-02 16:45:11 -0700253 }
254 ALOGW("Service %s didn't start. Returning NULL", String8(name).string());
255 return nullptr;
256}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900257
Steven Moreland583685e2019-10-02 16:45:11 -0700258sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
259{
260 sp<IBinder> ret;
261 if (!mTheRealServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
262 return nullptr;
263 }
264 return ret;
265}
266
267status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
268 bool allowIsolated, int dumpsysPriority)
269{
270 Status status = mTheRealServiceManager->addService(
271 String8(name).c_str(), service, allowIsolated, dumpsysPriority);
272 return status.exceptionCode();
273}
274
275Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
276{
277 std::vector<std::string> ret;
278 if (!mTheRealServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
279 return {};
280 }
281
282 Vector<String16> res;
283 res.setCapacity(ret.size());
284 for (const std::string& name : ret) {
285 res.push(String16(name.c_str()));
286 }
287 return res;
288}
289
290sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
291{
292 class Waiter : public android::os::BnServiceCallback {
293 Status onRegistration(const std::string& /*name*/,
294 const sp<IBinder>& binder) override {
295 std::unique_lock<std::mutex> lock(mMutex);
296 mBinder = binder;
297 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700298 // Flushing here helps ensure the service's ref count remains accurate
299 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700300 mCv.notify_one();
301 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900302 }
Steven Moreland583685e2019-10-02 16:45:11 -0700303 public:
304 sp<IBinder> mBinder;
305 std::mutex mMutex;
306 std::condition_variable mCv;
307 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900308
Jon Spivackfed6db42019-11-18 16:43:59 -0800309 // Simple RAII object to ensure a function call immediately before going out of scope
310 class Defer {
311 public:
312 Defer(std::function<void()>&& f) : mF(std::move(f)) {}
313 ~Defer() { mF(); }
314 private:
315 std::function<void()> mF;
316 };
317
Steven Moreland583685e2019-10-02 16:45:11 -0700318 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900319
Steven Moreland583685e2019-10-02 16:45:11 -0700320 sp<IBinder> out;
321 if (!mTheRealServiceManager->getService(name, &out).isOk()) {
322 return nullptr;
323 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800324 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700325
326 sp<Waiter> waiter = new Waiter;
327 if (!mTheRealServiceManager->registerForNotifications(
328 name, waiter).isOk()) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700329 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800330 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800331 Defer unregister ([&] {
332 mTheRealServiceManager->unregisterForNotifications(name, waiter);
333 });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700334
Steven Moreland583685e2019-10-02 16:45:11 -0700335 while(true) {
336 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000337 // It would be really nice if we could read binder commands on this
338 // thread instead of needing a threadpool to be started, but for
339 // instance, if we call getAndExecuteCommand, it might be the case
340 // that another thread serves the callback, and we never get a
341 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700342 std::unique_lock<std::mutex> lock(waiter->mMutex);
343 using std::literals::chrono_literals::operator""s;
344 waiter->mCv.wait_for(lock, 1s, [&] {
345 return waiter->mBinder != nullptr;
346 });
347 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349
Steven Morelandf2677e22020-07-14 19:58:08 +0000350 ALOGW("Waited one second for %s (is service started? are binder threads started and available?)", name.c_str());
351
Steven Moreland583685e2019-10-02 16:45:11 -0700352 // Handle race condition for lazy services. Here is what can happen:
353 // - the service dies (not processed by init yet).
354 // - sm processes death notification.
355 // - sm gets getService and calls init to start service.
356 // - init gets the start signal, but the service already appears
357 // started, so it does nothing.
358 // - init gets death signal, but doesn't know it needs to restart
359 // the service
360 // - we need to request service again to get it to start
Jon Spivack0d844302019-07-22 18:40:34 -0700361 if (!mTheRealServiceManager->getService(name, &out).isOk()) {
Steven Moreland1c47b582019-08-27 18:05:27 -0700362 return nullptr;
363 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800364 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700365 }
Steven Moreland583685e2019-10-02 16:45:11 -0700366}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800367
Steven Morelandb82b8f82019-10-28 10:52:34 -0700368bool ServiceManagerShim::isDeclared(const String16& name) {
369 bool declared;
370 if (!mTheRealServiceManager->isDeclared(String8(name).c_str(), &declared).isOk()) {
371 return false;
372 }
373 return declared;
374}
375
Steven Moreland61ff8492019-09-26 16:05:45 -0700376} // namespace android