blob: 61d32cf2f78c2d965e65c59d2e953565926fd6eb [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
Devin Moore18f63752024-08-08 21:01:24 +000017#include <sys/socket.h>
Steven Moreland85d985c2022-09-12 20:57:51 +000018#define LOG_TAG "ServiceManagerCppClient"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080019
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070020#include <binder/IServiceManager.h>
Tomasz Wasilczykfe25f122024-06-26 12:45:57 -070021#include "BackendUnifiedServiceManager.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022
Tom Cherry8fda97f2020-07-22 17:15:44 -070023#include <inttypes.h>
24#include <unistd.h>
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070025#include <chrono>
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -070026#include <condition_variable>
Tom Cherry8fda97f2020-07-22 17:15:44 -070027
Devin Moore18f63752024-08-08 21:01:24 +000028#include <FdTrigger.h>
29#include <RpcSocketAddress.h>
Steven Moreland454bfd92022-07-20 20:53:36 +000030#include <android-base/properties.h>
Devin Moore18f63752024-08-08 21:01:24 +000031#include <android/os/BnAccessor.h>
Steven Moreland1c47b582019-08-27 18:05:27 -070032#include <android/os/BnServiceCallback.h>
Devin Moore18f63752024-08-08 21:01:24 +000033#include <android/os/BnServiceManager.h>
Alice Wang8578f132024-05-03 09:01:56 +000034#include <android/os/IAccessor.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070035#include <android/os/IServiceManager.h>
Mathias Agopian375f5632009-06-15 18:24:59 -070036#include <binder/IPCThreadState.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070037#include <binder/Parcel.h>
Devin Moore18f63752024-08-08 21:01:24 +000038#include <binder/RpcSession.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070039#include <utils/String8.h>
Devin Moore18f63752024-08-08 21:01:24 +000040#include <variant>
Jiyong Park47f876b2018-04-17 13:56:46 +090041#ifndef __ANDROID_VNDK__
42#include <binder/IPermissionController.h>
43#endif
Steven Moreland28723ae2019-04-01 18:52:30 -070044
Steven Morelanded3b5632019-09-20 11:24:28 -070045#ifdef __ANDROID__
Yunfan Chen788e1c42018-03-29 16:52:09 +090046#include <cutils/properties.h>
Yifan Hongf7760012021-06-04 16:04:42 -070047#else
48#include "ServiceManagerHost.h"
Steven Moreland28723ae2019-04-01 18:52:30 -070049#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050
Jooyung Han75fc06f2024-02-03 03:56:59 +090051#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
52#include <android/apexsupport.h>
53#include <vndksupport/linker.h>
54#endif
55
Steven Morelanda4853cd2019-07-12 15:44:37 -070056#include "Static.h"
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070057#include "Utils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059namespace android {
60
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070061using namespace std::chrono_literals;
62
Jayant Chowdhary30700942022-01-31 14:12:40 -080063using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
64
Steven Moreland80e1e6d2019-06-21 12:35:59 -070065using AidlServiceManager = android::os::IServiceManager;
66using android::binder::Status;
Alice Wang8578f132024-05-03 09:01:56 +000067using android::os::IAccessor;
68using android::os::Service;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070069
Steven Moreland635a2912019-10-02 15:50:10 -070070// libbinder's IServiceManager.h can't rely on the values generated by AIDL
71// because many places use its headers via include_dirs (meaning, without
72// declaring the dependency in the build system). So, for now, we can just check
73// the values here.
74static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
75static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
76static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
77static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
78static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
79static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
80
Steven Moreland583685e2019-10-02 16:45:11 -070081const String16& IServiceManager::getInterfaceDescriptor() const {
82 return AidlServiceManager::descriptor;
83}
84IServiceManager::IServiceManager() {}
85IServiceManager::~IServiceManager() {}
86
87// From the old libbinder IServiceManager interface to IServiceManager.
88class ServiceManagerShim : public IServiceManager
89{
90public:
91 explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
92
93 sp<IBinder> getService(const String16& name) const override;
94 sp<IBinder> checkService(const String16& name) const override;
95 status_t addService(const String16& name, const sp<IBinder>& service,
96 bool allowIsolated, int dumpsysPriority) override;
97 Vector<String16> listServices(int dumpsysPriority) override;
98 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070099 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +0000100 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +0000101 std::optional<String16> updatableViaApex(const String16& name) override;
Jooyung Han76944fe2022-10-25 17:02:45 +0900102 Vector<String16> getUpdatableNames(const String16& apexName) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +0000103 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800104 class RegistrationWaiter : public android::os::BnServiceCallback {
105 public:
106 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
107 : mImpl(callback) {}
108 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
109 mImpl->onServiceRegistration(String16(name.c_str()), binder);
110 return Status::ok();
111 }
Steven Moreland583685e2019-10-02 16:45:11 -0700112
Jayant Chowdhary30700942022-01-31 14:12:40 -0800113 private:
114 sp<AidlRegistrationCallback> mImpl;
115 };
116
117 status_t registerForNotifications(const String16& service,
118 const sp<AidlRegistrationCallback>& cb) override;
119
120 status_t unregisterForNotifications(const String16& service,
121 const sp<AidlRegistrationCallback>& cb) override;
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000122
123 std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
Steven Moreland583685e2019-10-02 16:45:11 -0700124 // for legacy ABI
125 const String16& getInterfaceDescriptor() const override {
Parth Sane56a04712024-04-22 14:21:07 +0000126 return mUnifiedServiceManager->getInterfaceDescriptor();
Steven Moreland583685e2019-10-02 16:45:11 -0700127 }
Parth Sane56a04712024-04-22 14:21:07 +0000128 IBinder* onAsBinder() override { return IInterface::asBinder(mUnifiedServiceManager).get(); }
Yifan Hongf7760012021-06-04 16:04:42 -0700129
130protected:
Parth Sane56a04712024-04-22 14:21:07 +0000131 sp<BackendUnifiedServiceManager> mUnifiedServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800132 // AidlRegistrationCallback -> services that its been registered for
133 // notifications.
134 using LocalRegistrationAndWaiter =
135 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
136 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
137 ServiceCallbackMap mNameToRegistrationCallback;
138 std::mutex mNameToRegistrationLock;
139
140 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
141 ServiceCallbackMap::iterator* it,
142 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700143
144 // Directly get the service in a way that, for lazy services, requests the service to be started
145 // if it is not currently started. This way, calls directly to ServiceManagerShim::getService
146 // will still have the 5s delay that is expected by a large amount of Android code.
147 //
148 // When implementing ServiceManagerShim, use realGetService instead of
Parth Sane56a04712024-04-22 14:21:07 +0000149 // mUnifiedServiceManager->getService so that it can be overridden in ServiceManagerHostShim.
Yifan Hongf7760012021-06-04 16:04:42 -0700150 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Alice Wang8578f132024-05-03 09:01:56 +0000151 Service service;
Alice Wang11da1502024-07-25 12:03:22 +0000152 Status status = mUnifiedServiceManager->getService2(name, &service);
Alice Wang8578f132024-05-03 09:01:56 +0000153 *_aidl_return = service.get<Service::Tag::binder>();
154 return status;
Yifan Hongf7760012021-06-04 16:04:42 -0700155 }
Steven Moreland583685e2019-10-02 16:45:11 -0700156};
157
Devin Moore18f63752024-08-08 21:01:24 +0000158class AccessorProvider {
159public:
160 AccessorProvider(RpcAccessorProvider&& provider) : mProvider(provider) {}
161 sp<IBinder> provide(const String16& name) { return mProvider(name); }
162
163private:
164 AccessorProvider() = delete;
165
166 RpcAccessorProvider mProvider;
167};
168
169class AccessorProviderEntry {
170public:
171 AccessorProviderEntry(std::shared_ptr<AccessorProvider>&& provider) : mProvider(provider) {}
172 std::shared_ptr<AccessorProvider> mProvider;
173
174private:
175 AccessorProviderEntry() = delete;
176};
177
Steven Moreland1698ffd2020-05-15 23:43:52 +0000178[[clang::no_destroy]] static std::once_flag gSmOnce;
179[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Devin Moore18f63752024-08-08 21:01:24 +0000180[[clang::no_destroy]] static std::mutex gAccessorProvidersMutex;
181[[clang::no_destroy]] static std::vector<AccessorProviderEntry> gAccessorProviders;
182
183class LocalAccessor : public android::os::BnAccessor {
184public:
185 LocalAccessor(const String16& instance, RpcSocketAddressProvider&& connectionInfoProvider)
186 : mInstance(instance), mConnectionInfoProvider(connectionInfoProvider) {
187 LOG_ALWAYS_FATAL_IF(!mConnectionInfoProvider,
188 "LocalAccessor object needs a valid connection info provider");
189 }
190
191 ~LocalAccessor() {
192 if (mOnDelete) mOnDelete();
193 }
194
195 ::android::binder::Status addConnection(::android::os::ParcelFileDescriptor* outFd) {
196 using android::os::IAccessor;
197 sockaddr_storage addrStorage;
198 std::unique_ptr<FdTrigger> trigger = FdTrigger::make();
199 RpcTransportFd fd;
200 status_t status =
201 mConnectionInfoProvider(mInstance, reinterpret_cast<sockaddr*>(&addrStorage),
202 sizeof(addrStorage));
203 if (status != OK) {
204 const std::string error = "The connection info provider was unable to provide "
205 "connection info for instance " +
206 std::string(String8(mInstance).c_str()) +
207 " with status: " + statusToString(status);
208 ALOGE("%s", error.c_str());
209 return Status::fromServiceSpecificError(IAccessor::ERROR_CONNECTION_INFO_NOT_FOUND,
210 error.c_str());
211 }
212 if (addrStorage.ss_family == AF_VSOCK) {
213 sockaddr_vm* addr = reinterpret_cast<sockaddr_vm*>(&addrStorage);
214 status = singleSocketConnection(VsockSocketAddress(addr->svm_cid, addr->svm_port),
215 trigger, &fd);
216 } else if (addrStorage.ss_family == AF_UNIX) {
217 sockaddr_un* addr = reinterpret_cast<sockaddr_un*>(&addrStorage);
218 status = singleSocketConnection(UnixSocketAddress(addr->sun_path), trigger, &fd);
219 } else if (addrStorage.ss_family == AF_INET) {
220 sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(&addrStorage);
221 status = singleSocketConnection(InetSocketAddress(reinterpret_cast<sockaddr*>(addr),
222 sizeof(sockaddr_in),
223 inet_ntoa(addr->sin_addr),
224 ntohs(addr->sin_port)),
225 trigger, &fd);
226 } else {
227 const std::string error =
228 "Unsupported socket family type or the ConnectionInfoProvider failed to find a "
229 "valid address. Family type: " +
230 std::to_string(addrStorage.ss_family);
231 ALOGE("%s", error.c_str());
232 return Status::fromServiceSpecificError(IAccessor::ERROR_UNSUPPORTED_SOCKET_FAMILY,
233 error.c_str());
234 }
235 if (status != OK) {
236 const std::string error = "Failed to connect to socket for " +
237 std::string(String8(mInstance).c_str()) +
238 " with status: " + statusToString(status);
239 ALOGE("%s", error.c_str());
240 int err = 0;
241 if (status == -EACCES) {
242 err = IAccessor::ERROR_FAILED_TO_CONNECT_EACCES;
243 } else {
244 err = IAccessor::ERROR_FAILED_TO_CONNECT_TO_SOCKET;
245 }
246 return Status::fromServiceSpecificError(err, error.c_str());
247 }
248 *outFd = os::ParcelFileDescriptor(std::move(fd.fd));
249 return Status::ok();
250 }
251
252 ::android::binder::Status getInstanceName(String16* instance) {
253 *instance = mInstance;
254 return Status::ok();
255 }
256
257private:
258 LocalAccessor() = delete;
259 String16 mInstance;
260 RpcSocketAddressProvider mConnectionInfoProvider;
261 std::function<void()> mOnDelete;
262};
263
264android::binder::Status getInjectedAccessor(const std::string& name,
265 android::os::Service* service) {
266 std::vector<AccessorProviderEntry> copiedProviders;
267 {
268 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
269 copiedProviders.insert(copiedProviders.begin(), gAccessorProviders.begin(),
270 gAccessorProviders.end());
271 }
272
273 // Unlocked to call the providers. This requires the providers to be
274 // threadsafe and not contain any references to objects that could be
275 // deleted.
276 for (const auto& provider : copiedProviders) {
277 sp<IBinder> binder = provider.mProvider->provide(String16(name.c_str()));
278 if (binder == nullptr) continue;
279 status_t status = validateAccessor(String16(name.c_str()), binder);
280 if (status != OK) {
281 ALOGE("A provider returned a binder that is not an IAccessor for instance %s. Status: "
282 "%s",
283 name.c_str(), statusToString(status).c_str());
284 return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
285 }
286 *service = os::Service::make<os::Service::Tag::accessor>(binder);
287 return android::binder::Status::ok();
288 }
289
290 *service = os::Service::make<os::Service::Tag::accessor>(nullptr);
291 return android::binder::Status::ok();
292}
Brett Chabot38dbade2020-01-24 12:59:43 -0800293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294sp<IServiceManager> defaultServiceManager()
295{
Martijn Coenen402c8672020-02-03 10:01:36 +0100296 std::call_once(gSmOnce, []() {
Parth Sane56a04712024-04-22 14:21:07 +0000297 gDefaultServiceManager = sp<ServiceManagerShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100298 });
Daniel Eratc2832702015-10-13 15:29:32 -0600299
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800300 return gDefaultServiceManager;
301}
302
Brett Chabot38dbade2020-01-24 12:59:43 -0800303void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100304 bool called = false;
305 std::call_once(gSmOnce, [&]() {
306 gDefaultServiceManager = sm;
307 called = true;
308 });
309
310 if (!called) {
311 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
312 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800313}
314
Devin Moore18f63752024-08-08 21:01:24 +0000315std::weak_ptr<AccessorProvider> addAccessorProvider(RpcAccessorProvider&& providerCallback) {
316 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
317 std::shared_ptr<AccessorProvider> provider =
318 std::make_shared<AccessorProvider>(std::move(providerCallback));
319 gAccessorProviders.push_back(AccessorProviderEntry(std::move(provider)));
320
321 return provider;
322}
323
324status_t removeAccessorProvider(std::weak_ptr<AccessorProvider> wProvider) {
325 std::shared_ptr<AccessorProvider> provider = wProvider.lock();
326 if (provider == nullptr) {
327 ALOGE("The provider supplied to removeAccessorProvider has already been removed.");
328 return NAME_NOT_FOUND;
329 }
330 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
331 size_t sizeBefore = gAccessorProviders.size();
332 gAccessorProviders.erase(std::remove_if(gAccessorProviders.begin(), gAccessorProviders.end(),
333 [&](AccessorProviderEntry entry) {
334 return entry.mProvider == provider;
335 }),
336 gAccessorProviders.end());
337 if (sizeBefore == gAccessorProviders.size()) {
338 ALOGE("Failed to find an AccessorProvider for removeAccessorProvider");
339 return NAME_NOT_FOUND;
340 }
341
342 return OK;
343}
344
345status_t validateAccessor(const String16& instance, const sp<IBinder>& binder) {
346 if (binder == nullptr) {
347 ALOGE("Binder is null");
348 return BAD_VALUE;
349 }
350 sp<IAccessor> accessor = interface_cast<IAccessor>(binder);
351 if (accessor == nullptr) {
352 ALOGE("This binder for %s is not an IAccessor binder", String8(instance).c_str());
353 return BAD_TYPE;
354 }
355 String16 reportedInstance;
356 Status status = accessor->getInstanceName(&reportedInstance);
357 if (!status.isOk()) {
358 ALOGE("Failed to validate the binder being used to create a new ARpc_Accessor for %s with "
359 "status: %s",
360 String8(instance).c_str(), status.toString8().c_str());
361 return NAME_NOT_FOUND;
362 }
363 if (reportedInstance != instance) {
364 ALOGE("Instance %s doesn't match the Accessor's instance of %s", String8(instance).c_str(),
365 String8(reportedInstance).c_str());
366 return NAME_NOT_FOUND;
367 }
368 return OK;
369}
370
371sp<IBinder> createAccessor(const String16& instance,
372 RpcSocketAddressProvider&& connectionInfoProvider) {
373 // Try to create a new accessor
374 if (!connectionInfoProvider) {
375 ALOGE("Could not find an Accessor for %s and no ConnectionInfoProvider provided to "
376 "create a new one",
377 String8(instance).c_str());
378 return nullptr;
379 }
380 sp<IBinder> binder = sp<LocalAccessor>::make(instance, std::move(connectionInfoProvider));
381 return binder;
382}
383
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400384#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900385// IPermissionController is not accessible to vendors
386
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800387bool checkCallingPermission(const String16& permission)
388{
Yi Kongfdd8da92018-06-07 17:52:27 -0700389 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800390}
391
Steven Moreland1b264072021-06-03 23:04:02 +0000392static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700393
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
395{
396 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700397 pid_t pid = ipcState->getCallingPid();
398 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700400 if (outUid) *outUid = uid;
401 return checkPermission(permission, pid, uid);
402}
403
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000404bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700405 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700406 static sp<IPermissionController> gPermissionController;
407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700409 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700411 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600412
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700413 auto startTime = std::chrono::steady_clock::now().min();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414
415 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700416 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417 bool res = pc->checkPermission(permission, pid, uid);
418 if (res) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700419 if (startTime != startTime.min()) {
420 const auto waitTime = std::chrono::steady_clock::now() - startTime;
421 ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
422 to_ms(waitTime), String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423 }
424 return res;
425 }
Daniel Eratc2832702015-10-13 15:29:32 -0600426
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800428 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000429 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000430 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000431 uid, pid);
432 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433 return false;
434 }
Daniel Eratc2832702015-10-13 15:29:32 -0600435
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700437 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800438 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700439 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700441 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800442 }
Daniel Eratc2832702015-10-13 15:29:32 -0600443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444 // Need to retrieve the permission controller.
445 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700446 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 // Wait for the permission controller to come back...
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700448 if (startTime == startTime.min()) {
449 startTime = std::chrono::steady_clock::now();
Steve Blocka19954a2012-01-04 20:05:49 +0000450 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000451 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452 }
453 sleep(1);
454 } else {
455 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600456 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700457 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800458 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700459 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800460 }
461 }
462}
463
Jooyung Han75fc06f2024-02-03 03:56:59 +0900464void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
465#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
466 sp<IServiceManager> sm = defaultServiceManager();
467 String16 name = interface + String16("/") + instance;
468 if (!sm->isDeclared(name)) {
469 return nullptr;
470 }
471 String16 libraryName = interface + String16(".") + instance + String16(".so");
472 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
473 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
474 String8(*updatableViaApex).c_str(), flag);
475 }
476 return android_load_sphal_library(String8(libraryName).c_str(), flag);
477#else
478 (void)interface;
479 (void)instance;
480 (void)flag;
481 return nullptr;
482#endif
483}
484
Jiyong Park47f876b2018-04-17 13:56:46 +0900485#endif //__ANDROID_VNDK__
486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487// ----------------------------------------------------------------------
488
Parth Sane56a04712024-04-22 14:21:07 +0000489ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl) {
490 mUnifiedServiceManager = sp<BackendUnifiedServiceManager>::make(impl);
491}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700492
Steven Moreland5af7d852020-04-29 15:40:29 -0700493// This implementation could be simplified and made more efficient by delegating
494// to waitForService. However, this changes the threading structure in some
495// cases and could potentially break prebuilts. Once we have higher logistical
496// complexity, this could be attempted.
Steven Moreland583685e2019-10-02 16:45:11 -0700497sp<IBinder> ServiceManagerShim::getService(const String16& name) const
498{
499 static bool gSystemBootCompleted = false;
500
501 sp<IBinder> svc = checkService(name);
502 if (svc != nullptr) return svc;
503
504 const bool isVendorService =
505 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700506 constexpr auto timeout = 5s;
507 const auto startTime = std::chrono::steady_clock::now();
Steven Moreland583685e2019-10-02 16:45:11 -0700508 // Vendor code can't access system properties
509 if (!gSystemBootCompleted && !isVendorService) {
510#ifdef __ANDROID__
511 char bootCompleted[PROPERTY_VALUE_MAX];
512 property_get("sys.boot_completed", bootCompleted, "0");
513 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
514#else
515 gSystemBootCompleted = true;
516#endif
517 }
518 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900519 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700520
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000521 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700522 ProcessState::self()->getDriverName().c_str());
523
Steven Moreland583685e2019-10-02 16:45:11 -0700524 int n = 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700525 while (std::chrono::steady_clock::now() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700526 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700527 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700528
Yunfan Chen788e1c42018-03-29 16:52:09 +0900529 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700530 if (svc != nullptr) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700531 const auto waitTime = std::chrono::steady_clock::now() - startTime;
532 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000533 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700534 to_ms(waitTime));
Tom Cherry8fda97f2020-07-22 17:15:44 -0700535 return svc;
536 }
Steven Moreland583685e2019-10-02 16:45:11 -0700537 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000538 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700539 return nullptr;
540}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900541
Steven Moreland583685e2019-10-02 16:45:11 -0700542sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
543{
Alice Wang8578f132024-05-03 09:01:56 +0000544 Service ret;
Parth Sane56a04712024-04-22 14:21:07 +0000545 if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700546 return nullptr;
547 }
Alice Wang8578f132024-05-03 09:01:56 +0000548 return ret.get<Service::Tag::binder>();
Steven Moreland583685e2019-10-02 16:45:11 -0700549}
550
551status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
552 bool allowIsolated, int dumpsysPriority)
553{
Parth Sane56a04712024-04-22 14:21:07 +0000554 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
555 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700556 return status.exceptionCode();
557}
558
559Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
560{
561 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000562 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700563 return {};
564 }
565
566 Vector<String16> res;
567 res.setCapacity(ret.size());
568 for (const std::string& name : ret) {
569 res.push(String16(name.c_str()));
570 }
571 return res;
572}
573
574sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
575{
576 class Waiter : public android::os::BnServiceCallback {
577 Status onRegistration(const std::string& /*name*/,
578 const sp<IBinder>& binder) override {
579 std::unique_lock<std::mutex> lock(mMutex);
580 mBinder = binder;
581 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700582 // Flushing here helps ensure the service's ref count remains accurate
583 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700584 mCv.notify_one();
585 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900586 }
Steven Moreland583685e2019-10-02 16:45:11 -0700587 public:
588 sp<IBinder> mBinder;
589 std::mutex mMutex;
590 std::condition_variable mCv;
591 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900592
Jon Spivackfed6db42019-11-18 16:43:59 -0800593 // Simple RAII object to ensure a function call immediately before going out of scope
594 class Defer {
595 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900596 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800597 ~Defer() { mF(); }
598 private:
599 std::function<void()> mF;
600 };
601
Steven Moreland583685e2019-10-02 16:45:11 -0700602 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900603
Steven Moreland583685e2019-10-02 16:45:11 -0700604 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700605 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000606 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
607 status.toString8().c_str());
Elie Kheirallah27c26952022-09-07 21:45:26 +0000608 if (0 == ProcessState::self()->getThreadPoolMaxTotalThreadCount()) {
609 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
610 "Threadpool has 0 guaranteed threads. "
611 "Is the threadpool configured properly? "
612 "See ProcessState::startThreadPool and "
613 "ProcessState::setThreadPoolMaxThreadCount.");
614 }
Steven Moreland583685e2019-10-02 16:45:11 -0700615 return nullptr;
616 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800617 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700618
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000619 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000620 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000621 !status.isOk()) {
622 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
623 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700624 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800625 }
Parth Sane56a04712024-04-22 14:21:07 +0000626 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700627
Steven Moreland583685e2019-10-02 16:45:11 -0700628 while(true) {
629 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000630 // It would be really nice if we could read binder commands on this
631 // thread instead of needing a threadpool to be started, but for
632 // instance, if we call getAndExecuteCommand, it might be the case
633 // that another thread serves the callback, and we never get a
634 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700635 std::unique_lock<std::mutex> lock(waiter->mMutex);
Steven Moreland3d37ef22023-04-25 18:25:14 +0000636 waiter->mCv.wait_for(lock, 1s, [&] {
637 return waiter->mBinder != nullptr;
638 });
Steven Moreland583685e2019-10-02 16:45:11 -0700639 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700640 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800641
Steven Moreland3d37ef22023-04-25 18:25:14 +0000642 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000643 "threadpool: %zu. Are binder threads started and available?)",
644 name.c_str(), ProcessState::self()->getThreadPoolMaxTotalThreadCount());
Steven Morelandf2677e22020-07-14 19:58:08 +0000645
Steven Moreland583685e2019-10-02 16:45:11 -0700646 // Handle race condition for lazy services. Here is what can happen:
647 // - the service dies (not processed by init yet).
648 // - sm processes death notification.
649 // - sm gets getService and calls init to start service.
650 // - init gets the start signal, but the service already appears
651 // started, so it does nothing.
652 // - init gets death signal, but doesn't know it needs to restart
653 // the service
654 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700655 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000656 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
657 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700658 return nullptr;
659 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800660 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700661 }
Steven Moreland583685e2019-10-02 16:45:11 -0700662}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800663
Steven Morelandb82b8f82019-10-28 10:52:34 -0700664bool ServiceManagerShim::isDeclared(const String16& name) {
665 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000666 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000667 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000668 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000669 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700670 return false;
671 }
672 return declared;
673}
674
Steven Moreland2e293aa2020-09-23 00:25:16 +0000675Vector<String16> ServiceManagerShim::getDeclaredInstances(const String16& interface) {
676 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000677 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000678 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000679 !status.isOk()) {
680 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
681 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000682 return {};
683 }
684
685 Vector<String16> res;
686 res.setCapacity(out.size());
687 for (const std::string& instance : out) {
688 res.push(String16(instance.c_str()));
689 }
690 return res;
691}
692
Steven Morelandedd4e072021-04-21 00:27:29 +0000693std::optional<String16> ServiceManagerShim::updatableViaApex(const String16& name) {
694 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000695 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000696 !status.isOk()) {
697 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
698 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000699 return std::nullopt;
700 }
701 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
702}
703
Jooyung Han76944fe2022-10-25 17:02:45 +0900704Vector<String16> ServiceManagerShim::getUpdatableNames(const String16& apexName) {
705 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000706 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900707 !status.isOk()) {
708 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
709 status.toString8().c_str());
710 return {};
711 }
712
713 Vector<String16> res;
714 res.setCapacity(out.size());
715 for (const std::string& instance : out) {
716 res.push(String16(instance.c_str()));
717 }
718 return res;
719}
720
Devin Moore5e4c2f12021-09-09 22:36:33 +0000721std::optional<IServiceManager::ConnectionInfo> ServiceManagerShim::getConnectionInfo(
722 const String16& name) {
723 std::optional<os::ConnectionInfo> connectionInfo;
724 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000725 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000726 !status.isOk()) {
727 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
728 status.toString8().c_str());
729 }
730 return connectionInfo.has_value()
731 ? std::make_optional<IServiceManager::ConnectionInfo>(
732 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
733 : std::nullopt;
734}
735
Jayant Chowdhary30700942022-01-31 14:12:40 -0800736status_t ServiceManagerShim::registerForNotifications(const String16& name,
737 const sp<AidlRegistrationCallback>& cb) {
738 if (cb == nullptr) {
739 ALOGE("%s: null cb passed", __FUNCTION__);
740 return BAD_VALUE;
741 }
742 std::string nameStr = String8(name).c_str();
743 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
744 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
745 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000746 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800747 !status.isOk()) {
748 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
749 status.toString8().c_str());
750 return UNKNOWN_ERROR;
751 }
752 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
753 return OK;
754}
755
756void ServiceManagerShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
757 ServiceCallbackMap::iterator* it,
758 sp<RegistrationWaiter>* waiter) {
759 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
760 for (auto lit = localRegistrationAndWaiters.begin();
761 lit != localRegistrationAndWaiters.end();) {
762 if (lit->first == cb) {
763 if (waiter) {
764 *waiter = lit->second;
765 }
766 lit = localRegistrationAndWaiters.erase(lit);
767 } else {
768 ++lit;
769 }
770 }
771
772 if (localRegistrationAndWaiters.empty()) {
773 mNameToRegistrationCallback.erase(*it);
774 }
775}
776
777status_t ServiceManagerShim::unregisterForNotifications(const String16& name,
778 const sp<AidlRegistrationCallback>& cb) {
779 if (cb == nullptr) {
780 ALOGE("%s: null cb passed", __FUNCTION__);
781 return BAD_VALUE;
782 }
783 std::string nameStr = String8(name).c_str();
784 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
785 auto it = mNameToRegistrationCallback.find(nameStr);
786 sp<RegistrationWaiter> registrationWaiter;
787 if (it != mNameToRegistrationCallback.end()) {
788 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
789 } else {
790 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
791 return BAD_VALUE;
792 }
793 if (registrationWaiter == nullptr) {
794 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
795 return BAD_VALUE;
796 }
Parth Sane56a04712024-04-22 14:21:07 +0000797 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800798 registrationWaiter);
799 !status.isOk()) {
800 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
801 String8(name).c_str(), status.toString8().c_str());
802 return UNKNOWN_ERROR;
803 }
804 return OK;
805}
806
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000807std::vector<IServiceManager::ServiceDebugInfo> ServiceManagerShim::getServiceDebugInfo() {
808 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
809 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000810 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000811 !status.isOk()) {
812 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
813 return ret;
814 }
815 for (const auto& serviceDebugInfo : serviceDebugInfos) {
816 IServiceManager::ServiceDebugInfo retInfo;
817 retInfo.pid = serviceDebugInfo.debugPid;
818 retInfo.name = serviceDebugInfo.name;
819 ret.emplace_back(retInfo);
820 }
821 return ret;
822}
823
Yifan Hongf7760012021-06-04 16:04:42 -0700824#ifndef __ANDROID__
825// ServiceManagerShim for host. Implements the old libbinder android::IServiceManager API.
826// The internal implementation of the AIDL interface android::os::IServiceManager calls into
827// on-device service manager.
828class ServiceManagerHostShim : public ServiceManagerShim {
829public:
Yifan Hong5a05ef72021-10-08 17:33:47 -0700830 ServiceManagerHostShim(const sp<AidlServiceManager>& impl,
831 const RpcDelegateServiceManagerOptions& options)
832 : ServiceManagerShim(impl), mOptions(options) {}
Yifan Hongf7760012021-06-04 16:04:42 -0700833 // ServiceManagerShim::getService is based on checkService, so no need to override it.
834 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700835 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700836 }
837
838protected:
839 // Override realGetService for ServiceManagerShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700840 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700841 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700842 return Status::ok();
843 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700844
845private:
846 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700847};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700848sp<IServiceManager> createRpcDelegateServiceManager(
849 const RpcDelegateServiceManagerOptions& options) {
850 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700851 if (binder == nullptr) {
852 ALOGE("getDeviceService(\"manager\") returns null");
853 return nullptr;
854 }
855 auto interface = AidlServiceManager::asInterface(binder);
856 if (interface == nullptr) {
857 ALOGE("getDeviceService(\"manager\") returns non service manager");
858 return nullptr;
859 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700860 return sp<ServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700861}
862#endif
863
Steven Moreland61ff8492019-09-26 16:05:45 -0700864} // namespace android