• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
19 #include <binder/IServiceManager.h>
20 
21 #include <inttypes.h>
22 #include <unistd.h>
23 
24 #include <android/os/BnServiceCallback.h>
25 #include <android/os/IServiceManager.h>
26 #include <binder/IPCThreadState.h>
27 #include <binder/Parcel.h>
28 #include <utils/Log.h>
29 #include <utils/String8.h>
30 #include <utils/SystemClock.h>
31 
32 #ifndef __ANDROID_VNDK__
33 #include <binder/IPermissionController.h>
34 #endif
35 
36 #ifdef __ANDROID__
37 #include <cutils/properties.h>
38 #endif
39 
40 #include "Static.h"
41 
42 namespace android {
43 
44 using AidlServiceManager = android::os::IServiceManager;
45 using android::binder::Status;
46 
47 // 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.
51 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
52 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
53 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
54 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
55 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
56 static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
57 
getInterfaceDescriptor() const58 const String16& IServiceManager::getInterfaceDescriptor() const {
59     return AidlServiceManager::descriptor;
60 }
IServiceManager()61 IServiceManager::IServiceManager() {}
~IServiceManager()62 IServiceManager::~IServiceManager() {}
63 
64 // From the old libbinder IServiceManager interface to IServiceManager.
65 class ServiceManagerShim : public IServiceManager
66 {
67 public:
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;
76     bool isDeclared(const String16& name) override;
77     Vector<String16> getDeclaredInstances(const String16& interface) override;
78     std::optional<String16> updatableViaApex(const String16& name) override;
79 
80     // for legacy ABI
getInterfaceDescriptor() const81     const String16& getInterfaceDescriptor() const override {
82         return mTheRealServiceManager->getInterfaceDescriptor();
83     }
onAsBinder()84     IBinder* onAsBinder() override {
85         return IInterface::asBinder(mTheRealServiceManager).get();
86     }
87 private:
88     sp<AidlServiceManager> mTheRealServiceManager;
89 };
90 
91 [[clang::no_destroy]] static std::once_flag gSmOnce;
92 [[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
93 
defaultServiceManager()94 sp<IServiceManager> defaultServiceManager()
95 {
96     std::call_once(gSmOnce, []() {
97         sp<AidlServiceManager> sm = nullptr;
98         while (sm == nullptr) {
99             sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));
100             if (sm == nullptr) {
101                 ALOGE("Waiting 1s on context object on %s.", ProcessState::self()->getDriverName().c_str());
102                 sleep(1);
103             }
104         }
105 
106         gDefaultServiceManager = sp<ServiceManagerShim>::make(sm);
107     });
108 
109     return gDefaultServiceManager;
110 }
111 
setDefaultServiceManager(const sp<IServiceManager> & sm)112 void setDefaultServiceManager(const sp<IServiceManager>& sm) {
113     bool called = false;
114     std::call_once(gSmOnce, [&]() {
115         gDefaultServiceManager = sm;
116         called = true;
117     });
118 
119     if (!called) {
120         LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
121     }
122 }
123 
124 #if !defined(__ANDROID_VNDK__) && defined(__ANDROID__)
125 // IPermissionController is not accessible to vendors
126 
checkCallingPermission(const String16 & permission)127 bool checkCallingPermission(const String16& permission)
128 {
129     return checkCallingPermission(permission, nullptr, nullptr);
130 }
131 
132 static String16 _permission("permission");
133 
134 
checkCallingPermission(const String16 & permission,int32_t * outPid,int32_t * outUid)135 bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
136 {
137     IPCThreadState* ipcState = IPCThreadState::self();
138     pid_t pid = ipcState->getCallingPid();
139     uid_t uid = ipcState->getCallingUid();
140     if (outPid) *outPid = pid;
141     if (outUid) *outUid = uid;
142     return checkPermission(permission, pid, uid);
143 }
144 
checkPermission(const String16 & permission,pid_t pid,uid_t uid)145 bool checkPermission(const String16& permission, pid_t pid, uid_t uid)
146 {
147     static Mutex gPermissionControllerLock;
148     static sp<IPermissionController> gPermissionController;
149 
150     sp<IPermissionController> pc;
151     gPermissionControllerLock.lock();
152     pc = gPermissionController;
153     gPermissionControllerLock.unlock();
154 
155     int64_t startTime = 0;
156 
157     while (true) {
158         if (pc != nullptr) {
159             bool res = pc->checkPermission(permission, pid, uid);
160             if (res) {
161                 if (startTime != 0) {
162                     ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
163                             (int)((uptimeMillis()-startTime)/1000),
164                             String8(permission).string(), uid, pid);
165                 }
166                 return res;
167             }
168 
169             // Is this a permission failure, or did the controller go away?
170             if (IInterface::asBinder(pc)->isBinderAlive()) {
171                 ALOGW("Permission failure: %s from uid=%d pid=%d",
172                         String8(permission).string(), uid, pid);
173                 return false;
174             }
175 
176             // Object is dead!
177             gPermissionControllerLock.lock();
178             if (gPermissionController == pc) {
179                 gPermissionController = nullptr;
180             }
181             gPermissionControllerLock.unlock();
182         }
183 
184         // Need to retrieve the permission controller.
185         sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
186         if (binder == nullptr) {
187             // Wait for the permission controller to come back...
188             if (startTime == 0) {
189                 startTime = uptimeMillis();
190                 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
191                         String8(permission).string(), uid, pid);
192             }
193             sleep(1);
194         } else {
195             pc = interface_cast<IPermissionController>(binder);
196             // Install the new permission controller, and try again.
197             gPermissionControllerLock.lock();
198             gPermissionController = pc;
199             gPermissionControllerLock.unlock();
200         }
201     }
202 }
203 
204 #endif //__ANDROID_VNDK__
205 
206 // ----------------------------------------------------------------------
207 
ServiceManagerShim(const sp<AidlServiceManager> & impl)208 ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl)
209  : mTheRealServiceManager(impl)
210 {}
211 
212 // This implementation could be simplified and made more efficient by delegating
213 // to waitForService. However, this changes the threading structure in some
214 // cases and could potentially break prebuilts. Once we have higher logistical
215 // complexity, this could be attempted.
getService(const String16 & name) const216 sp<IBinder> ServiceManagerShim::getService(const String16& name) const
217 {
218     static bool gSystemBootCompleted = false;
219 
220     sp<IBinder> svc = checkService(name);
221     if (svc != nullptr) return svc;
222 
223     const bool isVendorService =
224         strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
225     constexpr int64_t timeout = 5000;
226     int64_t startTime = uptimeMillis();
227     // Vendor code can't access system properties
228     if (!gSystemBootCompleted && !isVendorService) {
229 #ifdef __ANDROID__
230         char bootCompleted[PROPERTY_VALUE_MAX];
231         property_get("sys.boot_completed", bootCompleted, "0");
232         gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
233 #else
234         gSystemBootCompleted = true;
235 #endif
236     }
237     // retry interval in millisecond; note that vendor services stay at 100ms
238     const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
239 
240     ALOGI("Waiting for service '%s' on '%s'...", String8(name).string(),
241           ProcessState::self()->getDriverName().c_str());
242 
243     int n = 0;
244     while (uptimeMillis() - startTime < timeout) {
245         n++;
246         usleep(1000*sleepTime);
247 
248         sp<IBinder> svc = checkService(name);
249         if (svc != nullptr) {
250             ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
251                   String8(name).string(), ProcessState::self()->getDriverName().c_str(),
252                   uptimeMillis() - startTime);
253             return svc;
254         }
255     }
256     ALOGW("Service %s didn't start. Returning NULL", String8(name).string());
257     return nullptr;
258 }
259 
checkService(const String16 & name) const260 sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
261 {
262     sp<IBinder> ret;
263     if (!mTheRealServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
264         return nullptr;
265     }
266     return ret;
267 }
268 
addService(const String16 & name,const sp<IBinder> & service,bool allowIsolated,int dumpsysPriority)269 status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
270                                         bool allowIsolated, int dumpsysPriority)
271 {
272     Status status = mTheRealServiceManager->addService(
273         String8(name).c_str(), service, allowIsolated, dumpsysPriority);
274     return status.exceptionCode();
275 }
276 
listServices(int dumpsysPriority)277 Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
278 {
279     std::vector<std::string> ret;
280     if (!mTheRealServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
281         return {};
282     }
283 
284     Vector<String16> res;
285     res.setCapacity(ret.size());
286     for (const std::string& name : ret) {
287         res.push(String16(name.c_str()));
288     }
289     return res;
290 }
291 
waitForService(const String16 & name16)292 sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
293 {
294     class Waiter : public android::os::BnServiceCallback {
295         Status onRegistration(const std::string& /*name*/,
296                               const sp<IBinder>& binder) override {
297             std::unique_lock<std::mutex> lock(mMutex);
298             mBinder = binder;
299             lock.unlock();
300             // Flushing here helps ensure the service's ref count remains accurate
301             IPCThreadState::self()->flushCommands();
302             mCv.notify_one();
303             return Status::ok();
304         }
305     public:
306         sp<IBinder> mBinder;
307         std::mutex mMutex;
308         std::condition_variable mCv;
309     };
310 
311     // Simple RAII object to ensure a function call immediately before going out of scope
312     class Defer {
313     public:
314         explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
315         ~Defer() { mF(); }
316     private:
317         std::function<void()> mF;
318     };
319 
320     const std::string name = String8(name16).c_str();
321 
322     sp<IBinder> out;
323     if (!mTheRealServiceManager->getService(name, &out).isOk()) {
324         return nullptr;
325     }
326     if (out != nullptr) return out;
327 
328     sp<Waiter> waiter = sp<Waiter>::make();
329     if (!mTheRealServiceManager->registerForNotifications(
330             name, waiter).isOk()) {
331         return nullptr;
332     }
333     Defer unregister ([&] {
334         mTheRealServiceManager->unregisterForNotifications(name, waiter);
335     });
336 
337     while(true) {
338         {
339             // It would be really nice if we could read binder commands on this
340             // thread instead of needing a threadpool to be started, but for
341             // instance, if we call getAndExecuteCommand, it might be the case
342             // that another thread serves the callback, and we never get a
343             // command, so we hang indefinitely.
344             std::unique_lock<std::mutex> lock(waiter->mMutex);
345             using std::literals::chrono_literals::operator""s;
346             waiter->mCv.wait_for(lock, 1s, [&] {
347                 return waiter->mBinder != nullptr;
348             });
349             if (waiter->mBinder != nullptr) return waiter->mBinder;
350         }
351 
352         ALOGW("Waited one second for %s (is service started? are binder threads started and available?)", name.c_str());
353 
354         // Handle race condition for lazy services. Here is what can happen:
355         // - the service dies (not processed by init yet).
356         // - sm processes death notification.
357         // - sm gets getService and calls init to start service.
358         // - init gets the start signal, but the service already appears
359         //   started, so it does nothing.
360         // - init gets death signal, but doesn't know it needs to restart
361         //   the service
362         // - we need to request service again to get it to start
363         if (!mTheRealServiceManager->getService(name, &out).isOk()) {
364             return nullptr;
365         }
366         if (out != nullptr) return out;
367     }
368 }
369 
isDeclared(const String16 & name)370 bool ServiceManagerShim::isDeclared(const String16& name) {
371     bool declared;
372     if (!mTheRealServiceManager->isDeclared(String8(name).c_str(), &declared).isOk()) {
373         return false;
374     }
375     return declared;
376 }
377 
getDeclaredInstances(const String16 & interface)378 Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
379     std::vector<std::string> out;
380     if (!mTheRealServiceManager->getDeclaredInstances(String8(interface).c_str(), &out).isOk()) {
381         return {};
382     }
383 
384     Vector<String16> res;
385     res.setCapacity(out.size());
386     for (const std::string& instance : out) {
387         res.push(String16(instance.c_str()));
388     }
389     return res;
390 }
391 
updatableViaApex(const String16 & name)392 std::optional<String16> ServiceManagerShim::updatableViaApex(const String16& name) {
393     std::optional<std::string> declared;
394     if (!mTheRealServiceManager->updatableViaApex(String8(name).c_str(), &declared).isOk()) {
395         return std::nullopt;
396     }
397     return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
398 }
399 
400 } // namespace android
401