blob: cba21b209476018ad9fc3e3655fdafd9a40c770d [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.
Parth Sanec7b58642024-08-07 10:31:15 +000088class CppBackendShim : public IServiceManager {
Steven Moreland583685e2019-10-02 16:45:11 -070089public:
Parth Sanec7b58642024-08-07 10:31:15 +000090 explicit CppBackendShim(const sp<BackendUnifiedServiceManager>& impl);
Steven Moreland583685e2019-10-02 16:45:11 -070091
92 sp<IBinder> getService(const String16& name) const override;
93 sp<IBinder> checkService(const String16& name) const override;
94 status_t addService(const String16& name, const sp<IBinder>& service,
95 bool allowIsolated, int dumpsysPriority) override;
96 Vector<String16> listServices(int dumpsysPriority) override;
97 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -070098 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +000099 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +0000100 std::optional<String16> updatableViaApex(const String16& name) override;
Jooyung Han76944fe2022-10-25 17:02:45 +0900101 Vector<String16> getUpdatableNames(const String16& apexName) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +0000102 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800103 class RegistrationWaiter : public android::os::BnServiceCallback {
104 public:
105 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
106 : mImpl(callback) {}
107 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
108 mImpl->onServiceRegistration(String16(name.c_str()), binder);
109 return Status::ok();
110 }
Steven Moreland583685e2019-10-02 16:45:11 -0700111
Jayant Chowdhary30700942022-01-31 14:12:40 -0800112 private:
113 sp<AidlRegistrationCallback> mImpl;
114 };
115
116 status_t registerForNotifications(const String16& service,
117 const sp<AidlRegistrationCallback>& cb) override;
118
119 status_t unregisterForNotifications(const String16& service,
120 const sp<AidlRegistrationCallback>& cb) override;
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000121
122 std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
Steven Moreland583685e2019-10-02 16:45:11 -0700123 // for legacy ABI
124 const String16& getInterfaceDescriptor() const override {
Parth Sane56a04712024-04-22 14:21:07 +0000125 return mUnifiedServiceManager->getInterfaceDescriptor();
Steven Moreland583685e2019-10-02 16:45:11 -0700126 }
Parth Sane56a04712024-04-22 14:21:07 +0000127 IBinder* onAsBinder() override { return IInterface::asBinder(mUnifiedServiceManager).get(); }
Yifan Hongf7760012021-06-04 16:04:42 -0700128
129protected:
Parth Sane56a04712024-04-22 14:21:07 +0000130 sp<BackendUnifiedServiceManager> mUnifiedServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800131 // AidlRegistrationCallback -> services that its been registered for
132 // notifications.
133 using LocalRegistrationAndWaiter =
134 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
135 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
136 ServiceCallbackMap mNameToRegistrationCallback;
137 std::mutex mNameToRegistrationLock;
138
139 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
140 ServiceCallbackMap::iterator* it,
141 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700142
143 // Directly get the service in a way that, for lazy services, requests the service to be started
Parth Sanec7b58642024-08-07 10:31:15 +0000144 // if it is not currently started. This way, calls directly to CppBackendShim::getService
Yifan Hongf7760012021-06-04 16:04:42 -0700145 // will still have the 5s delay that is expected by a large amount of Android code.
146 //
Parth Sanec7b58642024-08-07 10:31:15 +0000147 // When implementing CppBackendShim, use realGetService instead of
148 // mUnifiedServiceManager->getService so that it can be overridden in CppServiceManagerHostShim.
Yifan Hongf7760012021-06-04 16:04:42 -0700149 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Alice Wang8578f132024-05-03 09:01:56 +0000150 Service service;
Alice Wang11da1502024-07-25 12:03:22 +0000151 Status status = mUnifiedServiceManager->getService2(name, &service);
Alice Wang8578f132024-05-03 09:01:56 +0000152 *_aidl_return = service.get<Service::Tag::binder>();
153 return status;
Yifan Hongf7760012021-06-04 16:04:42 -0700154 }
Steven Moreland583685e2019-10-02 16:45:11 -0700155};
156
Devin Moore18f63752024-08-08 21:01:24 +0000157class AccessorProvider {
158public:
159 AccessorProvider(RpcAccessorProvider&& provider) : mProvider(provider) {}
160 sp<IBinder> provide(const String16& name) { return mProvider(name); }
161
162private:
163 AccessorProvider() = delete;
164
165 RpcAccessorProvider mProvider;
166};
167
168class AccessorProviderEntry {
169public:
170 AccessorProviderEntry(std::shared_ptr<AccessorProvider>&& provider) : mProvider(provider) {}
171 std::shared_ptr<AccessorProvider> mProvider;
172
173private:
174 AccessorProviderEntry() = delete;
175};
176
Steven Moreland1698ffd2020-05-15 23:43:52 +0000177[[clang::no_destroy]] static std::once_flag gSmOnce;
178[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Devin Moore18f63752024-08-08 21:01:24 +0000179[[clang::no_destroy]] static std::mutex gAccessorProvidersMutex;
180[[clang::no_destroy]] static std::vector<AccessorProviderEntry> gAccessorProviders;
181
182class LocalAccessor : public android::os::BnAccessor {
183public:
184 LocalAccessor(const String16& instance, RpcSocketAddressProvider&& connectionInfoProvider)
185 : mInstance(instance), mConnectionInfoProvider(connectionInfoProvider) {
186 LOG_ALWAYS_FATAL_IF(!mConnectionInfoProvider,
187 "LocalAccessor object needs a valid connection info provider");
188 }
189
190 ~LocalAccessor() {
191 if (mOnDelete) mOnDelete();
192 }
193
194 ::android::binder::Status addConnection(::android::os::ParcelFileDescriptor* outFd) {
195 using android::os::IAccessor;
196 sockaddr_storage addrStorage;
197 std::unique_ptr<FdTrigger> trigger = FdTrigger::make();
198 RpcTransportFd fd;
199 status_t status =
200 mConnectionInfoProvider(mInstance, reinterpret_cast<sockaddr*>(&addrStorage),
201 sizeof(addrStorage));
202 if (status != OK) {
203 const std::string error = "The connection info provider was unable to provide "
204 "connection info for instance " +
205 std::string(String8(mInstance).c_str()) +
206 " with status: " + statusToString(status);
207 ALOGE("%s", error.c_str());
208 return Status::fromServiceSpecificError(IAccessor::ERROR_CONNECTION_INFO_NOT_FOUND,
209 error.c_str());
210 }
211 if (addrStorage.ss_family == AF_VSOCK) {
212 sockaddr_vm* addr = reinterpret_cast<sockaddr_vm*>(&addrStorage);
213 status = singleSocketConnection(VsockSocketAddress(addr->svm_cid, addr->svm_port),
214 trigger, &fd);
215 } else if (addrStorage.ss_family == AF_UNIX) {
216 sockaddr_un* addr = reinterpret_cast<sockaddr_un*>(&addrStorage);
217 status = singleSocketConnection(UnixSocketAddress(addr->sun_path), trigger, &fd);
218 } else if (addrStorage.ss_family == AF_INET) {
219 sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(&addrStorage);
220 status = singleSocketConnection(InetSocketAddress(reinterpret_cast<sockaddr*>(addr),
221 sizeof(sockaddr_in),
222 inet_ntoa(addr->sin_addr),
223 ntohs(addr->sin_port)),
224 trigger, &fd);
225 } else {
226 const std::string error =
227 "Unsupported socket family type or the ConnectionInfoProvider failed to find a "
228 "valid address. Family type: " +
229 std::to_string(addrStorage.ss_family);
230 ALOGE("%s", error.c_str());
231 return Status::fromServiceSpecificError(IAccessor::ERROR_UNSUPPORTED_SOCKET_FAMILY,
232 error.c_str());
233 }
234 if (status != OK) {
235 const std::string error = "Failed to connect to socket for " +
236 std::string(String8(mInstance).c_str()) +
237 " with status: " + statusToString(status);
238 ALOGE("%s", error.c_str());
239 int err = 0;
240 if (status == -EACCES) {
241 err = IAccessor::ERROR_FAILED_TO_CONNECT_EACCES;
242 } else {
243 err = IAccessor::ERROR_FAILED_TO_CONNECT_TO_SOCKET;
244 }
245 return Status::fromServiceSpecificError(err, error.c_str());
246 }
247 *outFd = os::ParcelFileDescriptor(std::move(fd.fd));
248 return Status::ok();
249 }
250
251 ::android::binder::Status getInstanceName(String16* instance) {
252 *instance = mInstance;
253 return Status::ok();
254 }
255
256private:
257 LocalAccessor() = delete;
258 String16 mInstance;
259 RpcSocketAddressProvider mConnectionInfoProvider;
260 std::function<void()> mOnDelete;
261};
262
263android::binder::Status getInjectedAccessor(const std::string& name,
264 android::os::Service* service) {
265 std::vector<AccessorProviderEntry> copiedProviders;
266 {
267 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
268 copiedProviders.insert(copiedProviders.begin(), gAccessorProviders.begin(),
269 gAccessorProviders.end());
270 }
271
272 // Unlocked to call the providers. This requires the providers to be
273 // threadsafe and not contain any references to objects that could be
274 // deleted.
275 for (const auto& provider : copiedProviders) {
276 sp<IBinder> binder = provider.mProvider->provide(String16(name.c_str()));
277 if (binder == nullptr) continue;
278 status_t status = validateAccessor(String16(name.c_str()), binder);
279 if (status != OK) {
280 ALOGE("A provider returned a binder that is not an IAccessor for instance %s. Status: "
281 "%s",
282 name.c_str(), statusToString(status).c_str());
283 return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
284 }
285 *service = os::Service::make<os::Service::Tag::accessor>(binder);
286 return android::binder::Status::ok();
287 }
288
289 *service = os::Service::make<os::Service::Tag::accessor>(nullptr);
290 return android::binder::Status::ok();
291}
Brett Chabot38dbade2020-01-24 12:59:43 -0800292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293sp<IServiceManager> defaultServiceManager()
294{
Martijn Coenen402c8672020-02-03 10:01:36 +0100295 std::call_once(gSmOnce, []() {
Parth Sanec7b58642024-08-07 10:31:15 +0000296 gDefaultServiceManager = sp<CppBackendShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100297 });
Daniel Eratc2832702015-10-13 15:29:32 -0600298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 return gDefaultServiceManager;
300}
301
Brett Chabot38dbade2020-01-24 12:59:43 -0800302void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100303 bool called = false;
304 std::call_once(gSmOnce, [&]() {
305 gDefaultServiceManager = sm;
306 called = true;
307 });
308
309 if (!called) {
310 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
311 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800312}
313
Devin Moore18f63752024-08-08 21:01:24 +0000314std::weak_ptr<AccessorProvider> addAccessorProvider(RpcAccessorProvider&& providerCallback) {
315 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
316 std::shared_ptr<AccessorProvider> provider =
317 std::make_shared<AccessorProvider>(std::move(providerCallback));
318 gAccessorProviders.push_back(AccessorProviderEntry(std::move(provider)));
319
320 return provider;
321}
322
323status_t removeAccessorProvider(std::weak_ptr<AccessorProvider> wProvider) {
324 std::shared_ptr<AccessorProvider> provider = wProvider.lock();
325 if (provider == nullptr) {
326 ALOGE("The provider supplied to removeAccessorProvider has already been removed.");
327 return NAME_NOT_FOUND;
328 }
329 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
330 size_t sizeBefore = gAccessorProviders.size();
331 gAccessorProviders.erase(std::remove_if(gAccessorProviders.begin(), gAccessorProviders.end(),
332 [&](AccessorProviderEntry entry) {
333 return entry.mProvider == provider;
334 }),
335 gAccessorProviders.end());
336 if (sizeBefore == gAccessorProviders.size()) {
337 ALOGE("Failed to find an AccessorProvider for removeAccessorProvider");
338 return NAME_NOT_FOUND;
339 }
340
341 return OK;
342}
343
344status_t validateAccessor(const String16& instance, const sp<IBinder>& binder) {
345 if (binder == nullptr) {
346 ALOGE("Binder is null");
347 return BAD_VALUE;
348 }
349 sp<IAccessor> accessor = interface_cast<IAccessor>(binder);
350 if (accessor == nullptr) {
351 ALOGE("This binder for %s is not an IAccessor binder", String8(instance).c_str());
352 return BAD_TYPE;
353 }
354 String16 reportedInstance;
355 Status status = accessor->getInstanceName(&reportedInstance);
356 if (!status.isOk()) {
357 ALOGE("Failed to validate the binder being used to create a new ARpc_Accessor for %s with "
358 "status: %s",
359 String8(instance).c_str(), status.toString8().c_str());
360 return NAME_NOT_FOUND;
361 }
362 if (reportedInstance != instance) {
363 ALOGE("Instance %s doesn't match the Accessor's instance of %s", String8(instance).c_str(),
364 String8(reportedInstance).c_str());
365 return NAME_NOT_FOUND;
366 }
367 return OK;
368}
369
370sp<IBinder> createAccessor(const String16& instance,
371 RpcSocketAddressProvider&& connectionInfoProvider) {
372 // Try to create a new accessor
373 if (!connectionInfoProvider) {
374 ALOGE("Could not find an Accessor for %s and no ConnectionInfoProvider provided to "
375 "create a new one",
376 String8(instance).c_str());
377 return nullptr;
378 }
379 sp<IBinder> binder = sp<LocalAccessor>::make(instance, std::move(connectionInfoProvider));
380 return binder;
381}
382
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400383#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900384// IPermissionController is not accessible to vendors
385
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386bool checkCallingPermission(const String16& permission)
387{
Yi Kongfdd8da92018-06-07 17:52:27 -0700388 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389}
390
Steven Moreland1b264072021-06-03 23:04:02 +0000391static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700392
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
394{
395 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700396 pid_t pid = ipcState->getCallingPid();
397 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700399 if (outUid) *outUid = uid;
400 return checkPermission(permission, pid, uid);
401}
402
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000403bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700404 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700405 static sp<IPermissionController> gPermissionController;
406
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700408 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700410 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600411
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700412 auto startTime = std::chrono::steady_clock::now().min();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413
414 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700415 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416 bool res = pc->checkPermission(permission, pid, uid);
417 if (res) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700418 if (startTime != startTime.min()) {
419 const auto waitTime = std::chrono::steady_clock::now() - startTime;
420 ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
421 to_ms(waitTime), String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422 }
423 return res;
424 }
Daniel Eratc2832702015-10-13 15:29:32 -0600425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800427 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000428 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000429 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000430 uid, pid);
431 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432 return false;
433 }
Daniel Eratc2832702015-10-13 15:29:32 -0600434
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800435 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700436 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700438 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700440 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800441 }
Daniel Eratc2832702015-10-13 15:29:32 -0600442
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443 // Need to retrieve the permission controller.
444 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700445 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446 // Wait for the permission controller to come back...
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700447 if (startTime == startTime.min()) {
448 startTime = std::chrono::steady_clock::now();
Steve Blocka19954a2012-01-04 20:05:49 +0000449 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000450 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451 }
452 sleep(1);
453 } else {
454 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600455 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700456 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700458 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800459 }
460 }
461}
462
Steven Moreland576662a2024-08-09 23:12:03 +0000463#endif //__ANDROID_VNDK__
464
Jooyung Han75fc06f2024-02-03 03:56:59 +0900465void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
Steven Moreland576662a2024-08-09 23:12:03 +0000466#if defined(__ANDROID__) && !defined(__ANDROID_VENDOR__) && !defined(__ANDROID_RECOVERY__) && \
467 !defined(__ANDROID_NATIVE_BRIDGE__)
Jooyung Han75fc06f2024-02-03 03:56:59 +0900468 sp<IServiceManager> sm = defaultServiceManager();
469 String16 name = interface + String16("/") + instance;
470 if (!sm->isDeclared(name)) {
471 return nullptr;
472 }
473 String16 libraryName = interface + String16(".") + instance + String16(".so");
474 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
475 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
476 String8(*updatableViaApex).c_str(), flag);
477 }
478 return android_load_sphal_library(String8(libraryName).c_str(), flag);
479#else
480 (void)interface;
481 (void)instance;
482 (void)flag;
483 return nullptr;
484#endif
485}
486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487// ----------------------------------------------------------------------
488
Parth Sanec7b58642024-08-07 10:31:15 +0000489CppBackendShim::CppBackendShim(const sp<BackendUnifiedServiceManager>& impl)
Parth Sane43e3b8b2024-08-05 13:39:04 +0000490 : mUnifiedServiceManager(impl) {}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700491
Steven Moreland5af7d852020-04-29 15:40:29 -0700492// This implementation could be simplified and made more efficient by delegating
493// to waitForService. However, this changes the threading structure in some
494// cases and could potentially break prebuilts. Once we have higher logistical
495// complexity, this could be attempted.
Parth Sanec7b58642024-08-07 10:31:15 +0000496sp<IBinder> CppBackendShim::getService(const String16& name) const {
Steven Moreland583685e2019-10-02 16:45:11 -0700497 static bool gSystemBootCompleted = false;
498
499 sp<IBinder> svc = checkService(name);
500 if (svc != nullptr) return svc;
501
502 const bool isVendorService =
503 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700504 constexpr auto timeout = 5s;
505 const auto startTime = std::chrono::steady_clock::now();
Steven Moreland583685e2019-10-02 16:45:11 -0700506 // Vendor code can't access system properties
507 if (!gSystemBootCompleted && !isVendorService) {
508#ifdef __ANDROID__
509 char bootCompleted[PROPERTY_VALUE_MAX];
510 property_get("sys.boot_completed", bootCompleted, "0");
511 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
512#else
513 gSystemBootCompleted = true;
514#endif
515 }
516 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900517 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700518
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000519 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700520 ProcessState::self()->getDriverName().c_str());
521
Steven Moreland583685e2019-10-02 16:45:11 -0700522 int n = 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700523 while (std::chrono::steady_clock::now() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700524 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700525 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700526
Yunfan Chen788e1c42018-03-29 16:52:09 +0900527 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700528 if (svc != nullptr) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700529 const auto waitTime = std::chrono::steady_clock::now() - startTime;
530 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000531 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700532 to_ms(waitTime));
Tom Cherry8fda97f2020-07-22 17:15:44 -0700533 return svc;
534 }
Steven Moreland583685e2019-10-02 16:45:11 -0700535 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000536 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700537 return nullptr;
538}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900539
Parth Sanec7b58642024-08-07 10:31:15 +0000540sp<IBinder> CppBackendShim::checkService(const String16& name) const {
Alice Wang8578f132024-05-03 09:01:56 +0000541 Service ret;
Parth Sane56a04712024-04-22 14:21:07 +0000542 if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700543 return nullptr;
544 }
Alice Wang8578f132024-05-03 09:01:56 +0000545 return ret.get<Service::Tag::binder>();
Steven Moreland583685e2019-10-02 16:45:11 -0700546}
547
Parth Sanec7b58642024-08-07 10:31:15 +0000548status_t CppBackendShim::addService(const String16& name, const sp<IBinder>& service,
549 bool allowIsolated, int dumpsysPriority) {
Parth Sane56a04712024-04-22 14:21:07 +0000550 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
551 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700552 return status.exceptionCode();
553}
554
Parth Sanec7b58642024-08-07 10:31:15 +0000555Vector<String16> CppBackendShim::listServices(int dumpsysPriority) {
Steven Moreland583685e2019-10-02 16:45:11 -0700556 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000557 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700558 return {};
559 }
560
561 Vector<String16> res;
562 res.setCapacity(ret.size());
563 for (const std::string& name : ret) {
564 res.push(String16(name.c_str()));
565 }
566 return res;
567}
568
Parth Sanec7b58642024-08-07 10:31:15 +0000569sp<IBinder> CppBackendShim::waitForService(const String16& name16) {
Steven Moreland583685e2019-10-02 16:45:11 -0700570 class Waiter : public android::os::BnServiceCallback {
571 Status onRegistration(const std::string& /*name*/,
572 const sp<IBinder>& binder) override {
573 std::unique_lock<std::mutex> lock(mMutex);
574 mBinder = binder;
575 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700576 // Flushing here helps ensure the service's ref count remains accurate
577 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700578 mCv.notify_one();
579 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900580 }
Steven Moreland583685e2019-10-02 16:45:11 -0700581 public:
582 sp<IBinder> mBinder;
583 std::mutex mMutex;
584 std::condition_variable mCv;
585 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900586
Jon Spivackfed6db42019-11-18 16:43:59 -0800587 // Simple RAII object to ensure a function call immediately before going out of scope
588 class Defer {
589 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900590 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800591 ~Defer() { mF(); }
592 private:
593 std::function<void()> mF;
594 };
595
Steven Moreland583685e2019-10-02 16:45:11 -0700596 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900597
Steven Moreland583685e2019-10-02 16:45:11 -0700598 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700599 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000600 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
601 status.toString8().c_str());
Elie Kheirallah27c26952022-09-07 21:45:26 +0000602 if (0 == ProcessState::self()->getThreadPoolMaxTotalThreadCount()) {
603 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
604 "Threadpool has 0 guaranteed threads. "
605 "Is the threadpool configured properly? "
606 "See ProcessState::startThreadPool and "
607 "ProcessState::setThreadPoolMaxThreadCount.");
608 }
Steven Moreland583685e2019-10-02 16:45:11 -0700609 return nullptr;
610 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800611 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700612
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000613 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000614 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000615 !status.isOk()) {
616 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
617 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700618 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800619 }
Parth Sane56a04712024-04-22 14:21:07 +0000620 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700621
Steven Moreland583685e2019-10-02 16:45:11 -0700622 while(true) {
623 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000624 // It would be really nice if we could read binder commands on this
625 // thread instead of needing a threadpool to be started, but for
626 // instance, if we call getAndExecuteCommand, it might be the case
627 // that another thread serves the callback, and we never get a
628 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700629 std::unique_lock<std::mutex> lock(waiter->mMutex);
Steven Moreland3d37ef22023-04-25 18:25:14 +0000630 waiter->mCv.wait_for(lock, 1s, [&] {
631 return waiter->mBinder != nullptr;
632 });
Steven Moreland583685e2019-10-02 16:45:11 -0700633 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700634 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800635
Steven Moreland3d37ef22023-04-25 18:25:14 +0000636 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000637 "threadpool: %zu. Are binder threads started and available?)",
638 name.c_str(), ProcessState::self()->getThreadPoolMaxTotalThreadCount());
Steven Morelandf2677e22020-07-14 19:58:08 +0000639
Steven Moreland583685e2019-10-02 16:45:11 -0700640 // Handle race condition for lazy services. Here is what can happen:
641 // - the service dies (not processed by init yet).
642 // - sm processes death notification.
643 // - sm gets getService and calls init to start service.
644 // - init gets the start signal, but the service already appears
645 // started, so it does nothing.
646 // - init gets death signal, but doesn't know it needs to restart
647 // the service
648 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700649 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000650 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
651 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700652 return nullptr;
653 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800654 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700655 }
Steven Moreland583685e2019-10-02 16:45:11 -0700656}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657
Parth Sanec7b58642024-08-07 10:31:15 +0000658bool CppBackendShim::isDeclared(const String16& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700659 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000660 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000661 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000662 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000663 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700664 return false;
665 }
666 return declared;
667}
668
Parth Sanec7b58642024-08-07 10:31:15 +0000669Vector<String16> CppBackendShim::getDeclaredInstances(const String16& interface) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000670 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000671 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000672 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000673 !status.isOk()) {
674 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
675 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000676 return {};
677 }
678
679 Vector<String16> res;
680 res.setCapacity(out.size());
681 for (const std::string& instance : out) {
682 res.push(String16(instance.c_str()));
683 }
684 return res;
685}
686
Parth Sanec7b58642024-08-07 10:31:15 +0000687std::optional<String16> CppBackendShim::updatableViaApex(const String16& name) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000688 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000689 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000690 !status.isOk()) {
691 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
692 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000693 return std::nullopt;
694 }
695 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
696}
697
Parth Sanec7b58642024-08-07 10:31:15 +0000698Vector<String16> CppBackendShim::getUpdatableNames(const String16& apexName) {
Jooyung Han76944fe2022-10-25 17:02:45 +0900699 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000700 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900701 !status.isOk()) {
702 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
703 status.toString8().c_str());
704 return {};
705 }
706
707 Vector<String16> res;
708 res.setCapacity(out.size());
709 for (const std::string& instance : out) {
710 res.push(String16(instance.c_str()));
711 }
712 return res;
713}
714
Parth Sanec7b58642024-08-07 10:31:15 +0000715std::optional<IServiceManager::ConnectionInfo> CppBackendShim::getConnectionInfo(
Devin Moore5e4c2f12021-09-09 22:36:33 +0000716 const String16& name) {
717 std::optional<os::ConnectionInfo> connectionInfo;
718 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000719 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000720 !status.isOk()) {
721 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
722 status.toString8().c_str());
723 }
724 return connectionInfo.has_value()
725 ? std::make_optional<IServiceManager::ConnectionInfo>(
726 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
727 : std::nullopt;
728}
729
Parth Sanec7b58642024-08-07 10:31:15 +0000730status_t CppBackendShim::registerForNotifications(const String16& name,
731 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800732 if (cb == nullptr) {
733 ALOGE("%s: null cb passed", __FUNCTION__);
734 return BAD_VALUE;
735 }
736 std::string nameStr = String8(name).c_str();
737 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
738 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
739 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000740 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800741 !status.isOk()) {
742 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
743 status.toString8().c_str());
744 return UNKNOWN_ERROR;
745 }
746 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
747 return OK;
748}
749
Parth Sanec7b58642024-08-07 10:31:15 +0000750void CppBackendShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
751 ServiceCallbackMap::iterator* it,
752 sp<RegistrationWaiter>* waiter) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800753 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
754 for (auto lit = localRegistrationAndWaiters.begin();
755 lit != localRegistrationAndWaiters.end();) {
756 if (lit->first == cb) {
757 if (waiter) {
758 *waiter = lit->second;
759 }
760 lit = localRegistrationAndWaiters.erase(lit);
761 } else {
762 ++lit;
763 }
764 }
765
766 if (localRegistrationAndWaiters.empty()) {
767 mNameToRegistrationCallback.erase(*it);
768 }
769}
770
Parth Sanec7b58642024-08-07 10:31:15 +0000771status_t CppBackendShim::unregisterForNotifications(const String16& name,
772 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800773 if (cb == nullptr) {
774 ALOGE("%s: null cb passed", __FUNCTION__);
775 return BAD_VALUE;
776 }
777 std::string nameStr = String8(name).c_str();
778 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
779 auto it = mNameToRegistrationCallback.find(nameStr);
780 sp<RegistrationWaiter> registrationWaiter;
781 if (it != mNameToRegistrationCallback.end()) {
782 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
783 } else {
784 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
785 return BAD_VALUE;
786 }
787 if (registrationWaiter == nullptr) {
788 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
789 return BAD_VALUE;
790 }
Parth Sane56a04712024-04-22 14:21:07 +0000791 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800792 registrationWaiter);
793 !status.isOk()) {
794 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
795 String8(name).c_str(), status.toString8().c_str());
796 return UNKNOWN_ERROR;
797 }
798 return OK;
799}
800
Parth Sanec7b58642024-08-07 10:31:15 +0000801std::vector<IServiceManager::ServiceDebugInfo> CppBackendShim::getServiceDebugInfo() {
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000802 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
803 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000804 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000805 !status.isOk()) {
806 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
807 return ret;
808 }
809 for (const auto& serviceDebugInfo : serviceDebugInfos) {
810 IServiceManager::ServiceDebugInfo retInfo;
811 retInfo.pid = serviceDebugInfo.debugPid;
812 retInfo.name = serviceDebugInfo.name;
813 ret.emplace_back(retInfo);
814 }
815 return ret;
816}
817
Yifan Hongf7760012021-06-04 16:04:42 -0700818#ifndef __ANDROID__
Parth Sanec7b58642024-08-07 10:31:15 +0000819// CppBackendShim for host. Implements the old libbinder android::IServiceManager API.
Yifan Hongf7760012021-06-04 16:04:42 -0700820// The internal implementation of the AIDL interface android::os::IServiceManager calls into
821// on-device service manager.
Parth Sanec7b58642024-08-07 10:31:15 +0000822class CppServiceManagerHostShim : public CppBackendShim {
Yifan Hongf7760012021-06-04 16:04:42 -0700823public:
Parth Sanec7b58642024-08-07 10:31:15 +0000824 CppServiceManagerHostShim(const sp<AidlServiceManager>& impl,
825 const RpcDelegateServiceManagerOptions& options)
826 : CppBackendShim(sp<BackendUnifiedServiceManager>::make(impl)), mOptions(options) {}
827 // CppBackendShim::getService is based on checkService, so no need to override it.
Yifan Hongf7760012021-06-04 16:04:42 -0700828 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700829 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700830 }
831
832protected:
Parth Sanec7b58642024-08-07 10:31:15 +0000833 // Override realGetService for CppBackendShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700834 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700835 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700836 return Status::ok();
837 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700838
839private:
840 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700841};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700842sp<IServiceManager> createRpcDelegateServiceManager(
843 const RpcDelegateServiceManagerOptions& options) {
844 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700845 if (binder == nullptr) {
846 ALOGE("getDeviceService(\"manager\") returns null");
847 return nullptr;
848 }
849 auto interface = AidlServiceManager::asInterface(binder);
850 if (interface == nullptr) {
851 ALOGE("getDeviceService(\"manager\") returns non service manager");
852 return nullptr;
853 }
Parth Sanec7b58642024-08-07 10:31:15 +0000854 return sp<CppServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700855}
856#endif
857
Steven Moreland61ff8492019-09-26 16:05:45 -0700858} // namespace android