blob: 88761d772f54968413fb931befc4a99b6fcfa10b [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>
Parth Saneb6ed0eb2024-06-25 14:38:42 +000021#include <binder/IServiceManagerUnitTestHelper.h>
Tomasz Wasilczykfe25f122024-06-26 12:45:57 -070022#include "BackendUnifiedServiceManager.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023
Tom Cherry8fda97f2020-07-22 17:15:44 -070024#include <inttypes.h>
25#include <unistd.h>
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070026#include <chrono>
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -070027#include <condition_variable>
Tom Cherry8fda97f2020-07-22 17:15:44 -070028
Devin Moore18f63752024-08-08 21:01:24 +000029#include <FdTrigger.h>
30#include <RpcSocketAddress.h>
Steven Moreland454bfd92022-07-20 20:53:36 +000031#include <android-base/properties.h>
Devin Moore18f63752024-08-08 21:01:24 +000032#include <android/os/BnAccessor.h>
Steven Moreland1c47b582019-08-27 18:05:27 -070033#include <android/os/BnServiceCallback.h>
Devin Moore18f63752024-08-08 21:01:24 +000034#include <android/os/BnServiceManager.h>
Alice Wang8578f132024-05-03 09:01:56 +000035#include <android/os/IAccessor.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070036#include <android/os/IServiceManager.h>
Mathias Agopian375f5632009-06-15 18:24:59 -070037#include <binder/IPCThreadState.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070038#include <binder/Parcel.h>
Devin Moore18f63752024-08-08 21:01:24 +000039#include <binder/RpcSession.h>
Steven Moreland28723ae2019-04-01 18:52:30 -070040#include <utils/String8.h>
Devin Moore18f63752024-08-08 21:01:24 +000041#include <variant>
Jiyong Park47f876b2018-04-17 13:56:46 +090042#ifndef __ANDROID_VNDK__
43#include <binder/IPermissionController.h>
44#endif
Steven Moreland28723ae2019-04-01 18:52:30 -070045
Steven Morelanded3b5632019-09-20 11:24:28 -070046#ifdef __ANDROID__
Yunfan Chen788e1c42018-03-29 16:52:09 +090047#include <cutils/properties.h>
Yifan Hongf7760012021-06-04 16:04:42 -070048#else
49#include "ServiceManagerHost.h"
Steven Moreland28723ae2019-04-01 18:52:30 -070050#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051
Jooyung Han75fc06f2024-02-03 03:56:59 +090052#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
53#include <android/apexsupport.h>
54#include <vndksupport/linker.h>
55#endif
56
Steven Morelanda4853cd2019-07-12 15:44:37 -070057#include "Static.h"
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070058#include "Utils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060namespace android {
61
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070062using namespace std::chrono_literals;
63
Jayant Chowdhary30700942022-01-31 14:12:40 -080064using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
65
Steven Moreland80e1e6d2019-06-21 12:35:59 -070066using AidlServiceManager = android::os::IServiceManager;
67using android::binder::Status;
Alice Wang8578f132024-05-03 09:01:56 +000068using android::os::IAccessor;
69using android::os::Service;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070070
Steven Moreland635a2912019-10-02 15:50:10 -070071// libbinder's IServiceManager.h can't rely on the values generated by AIDL
72// because many places use its headers via include_dirs (meaning, without
73// declaring the dependency in the build system). So, for now, we can just check
74// the values here.
75static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
76static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
77static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
78static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
79static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
80static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
81
Steven Moreland583685e2019-10-02 16:45:11 -070082const String16& IServiceManager::getInterfaceDescriptor() const {
83 return AidlServiceManager::descriptor;
84}
85IServiceManager::IServiceManager() {}
86IServiceManager::~IServiceManager() {}
87
88// From the old libbinder IServiceManager interface to IServiceManager.
Parth Sanec7b58642024-08-07 10:31:15 +000089class CppBackendShim : public IServiceManager {
Steven Moreland583685e2019-10-02 16:45:11 -070090public:
Parth Sanec7b58642024-08-07 10:31:15 +000091 explicit CppBackendShim(const sp<BackendUnifiedServiceManager>& impl);
Steven Moreland583685e2019-10-02 16:45:11 -070092
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
Parth Sanec7b58642024-08-07 10:31:15 +0000145 // if it is not currently started. This way, calls directly to CppBackendShim::getService
Yifan Hongf7760012021-06-04 16:04:42 -0700146 // will still have the 5s delay that is expected by a large amount of Android code.
147 //
Parth Sanec7b58642024-08-07 10:31:15 +0000148 // When implementing CppBackendShim, use realGetService instead of
149 // mUnifiedServiceManager->getService so that it can be overridden in CppServiceManagerHostShim.
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:
Devin Moore5c0b8352024-09-05 19:45:27 +0000160 AccessorProvider(RpcAccessorProvider&& provider) : mProvider(std::move(provider)) {}
Devin Moore18f63752024-08-08 21:01:24 +0000161 sp<IBinder> provide(const String16& name) { return mProvider(name); }
162
163private:
164 AccessorProvider() = delete;
165
166 RpcAccessorProvider mProvider;
167};
168
169class AccessorProviderEntry {
170public:
Devin Moore5c0b8352024-09-05 19:45:27 +0000171 AccessorProviderEntry(std::shared_ptr<AccessorProvider>&& provider)
172 : mProvider(std::move(provider)) {}
Devin Moore18f63752024-08-08 21:01:24 +0000173 std::shared_ptr<AccessorProvider> mProvider;
174
175private:
176 AccessorProviderEntry() = delete;
177};
178
Steven Moreland1698ffd2020-05-15 23:43:52 +0000179[[clang::no_destroy]] static std::once_flag gSmOnce;
180[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Devin Moore18f63752024-08-08 21:01:24 +0000181[[clang::no_destroy]] static std::mutex gAccessorProvidersMutex;
182[[clang::no_destroy]] static std::vector<AccessorProviderEntry> gAccessorProviders;
183
184class LocalAccessor : public android::os::BnAccessor {
185public:
186 LocalAccessor(const String16& instance, RpcSocketAddressProvider&& connectionInfoProvider)
Devin Moore5c0b8352024-09-05 19:45:27 +0000187 : mInstance(instance), mConnectionInfoProvider(std::move(connectionInfoProvider)) {
Devin Moore18f63752024-08-08 21:01:24 +0000188 LOG_ALWAYS_FATAL_IF(!mConnectionInfoProvider,
189 "LocalAccessor object needs a valid connection info provider");
190 }
191
192 ~LocalAccessor() {
193 if (mOnDelete) mOnDelete();
194 }
195
196 ::android::binder::Status addConnection(::android::os::ParcelFileDescriptor* outFd) {
197 using android::os::IAccessor;
198 sockaddr_storage addrStorage;
199 std::unique_ptr<FdTrigger> trigger = FdTrigger::make();
200 RpcTransportFd fd;
201 status_t status =
202 mConnectionInfoProvider(mInstance, reinterpret_cast<sockaddr*>(&addrStorage),
203 sizeof(addrStorage));
204 if (status != OK) {
205 const std::string error = "The connection info provider was unable to provide "
206 "connection info for instance " +
207 std::string(String8(mInstance).c_str()) +
208 " with status: " + statusToString(status);
209 ALOGE("%s", error.c_str());
210 return Status::fromServiceSpecificError(IAccessor::ERROR_CONNECTION_INFO_NOT_FOUND,
211 error.c_str());
212 }
213 if (addrStorage.ss_family == AF_VSOCK) {
214 sockaddr_vm* addr = reinterpret_cast<sockaddr_vm*>(&addrStorage);
215 status = singleSocketConnection(VsockSocketAddress(addr->svm_cid, addr->svm_port),
216 trigger, &fd);
217 } else if (addrStorage.ss_family == AF_UNIX) {
218 sockaddr_un* addr = reinterpret_cast<sockaddr_un*>(&addrStorage);
219 status = singleSocketConnection(UnixSocketAddress(addr->sun_path), trigger, &fd);
220 } else if (addrStorage.ss_family == AF_INET) {
221 sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(&addrStorage);
222 status = singleSocketConnection(InetSocketAddress(reinterpret_cast<sockaddr*>(addr),
223 sizeof(sockaddr_in),
224 inet_ntoa(addr->sin_addr),
225 ntohs(addr->sin_port)),
226 trigger, &fd);
227 } else {
228 const std::string error =
229 "Unsupported socket family type or the ConnectionInfoProvider failed to find a "
230 "valid address. Family type: " +
231 std::to_string(addrStorage.ss_family);
232 ALOGE("%s", error.c_str());
233 return Status::fromServiceSpecificError(IAccessor::ERROR_UNSUPPORTED_SOCKET_FAMILY,
234 error.c_str());
235 }
236 if (status != OK) {
237 const std::string error = "Failed to connect to socket for " +
238 std::string(String8(mInstance).c_str()) +
239 " with status: " + statusToString(status);
240 ALOGE("%s", error.c_str());
241 int err = 0;
242 if (status == -EACCES) {
243 err = IAccessor::ERROR_FAILED_TO_CONNECT_EACCES;
244 } else {
245 err = IAccessor::ERROR_FAILED_TO_CONNECT_TO_SOCKET;
246 }
247 return Status::fromServiceSpecificError(err, error.c_str());
248 }
249 *outFd = os::ParcelFileDescriptor(std::move(fd.fd));
250 return Status::ok();
251 }
252
253 ::android::binder::Status getInstanceName(String16* instance) {
254 *instance = mInstance;
255 return Status::ok();
256 }
257
258private:
259 LocalAccessor() = delete;
260 String16 mInstance;
261 RpcSocketAddressProvider mConnectionInfoProvider;
262 std::function<void()> mOnDelete;
263};
264
265android::binder::Status getInjectedAccessor(const std::string& name,
266 android::os::Service* service) {
267 std::vector<AccessorProviderEntry> copiedProviders;
268 {
269 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
270 copiedProviders.insert(copiedProviders.begin(), gAccessorProviders.begin(),
271 gAccessorProviders.end());
272 }
273
274 // Unlocked to call the providers. This requires the providers to be
275 // threadsafe and not contain any references to objects that could be
276 // deleted.
277 for (const auto& provider : copiedProviders) {
278 sp<IBinder> binder = provider.mProvider->provide(String16(name.c_str()));
279 if (binder == nullptr) continue;
280 status_t status = validateAccessor(String16(name.c_str()), binder);
281 if (status != OK) {
282 ALOGE("A provider returned a binder that is not an IAccessor for instance %s. Status: "
283 "%s",
284 name.c_str(), statusToString(status).c_str());
285 return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
286 }
287 *service = os::Service::make<os::Service::Tag::accessor>(binder);
288 return android::binder::Status::ok();
289 }
290
291 *service = os::Service::make<os::Service::Tag::accessor>(nullptr);
292 return android::binder::Status::ok();
293}
Brett Chabot38dbade2020-01-24 12:59:43 -0800294
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800295sp<IServiceManager> defaultServiceManager()
296{
Martijn Coenen402c8672020-02-03 10:01:36 +0100297 std::call_once(gSmOnce, []() {
Parth Sanec7b58642024-08-07 10:31:15 +0000298 gDefaultServiceManager = sp<CppBackendShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100299 });
Daniel Eratc2832702015-10-13 15:29:32 -0600300
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 return gDefaultServiceManager;
302}
303
Brett Chabot38dbade2020-01-24 12:59:43 -0800304void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100305 bool called = false;
306 std::call_once(gSmOnce, [&]() {
307 gDefaultServiceManager = sm;
308 called = true;
309 });
310
311 if (!called) {
312 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
313 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800314}
315
Parth Saneb6ed0eb2024-06-25 14:38:42 +0000316sp<IServiceManager> getServiceManagerShimFromAidlServiceManagerForTests(
317 const sp<AidlServiceManager>& sm) {
318 return sp<CppBackendShim>::make(sp<BackendUnifiedServiceManager>::make(sm));
319}
320
Devin Moore18f63752024-08-08 21:01:24 +0000321std::weak_ptr<AccessorProvider> addAccessorProvider(RpcAccessorProvider&& providerCallback) {
322 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
323 std::shared_ptr<AccessorProvider> provider =
324 std::make_shared<AccessorProvider>(std::move(providerCallback));
Devin Moore5c0b8352024-09-05 19:45:27 +0000325 std::weak_ptr<AccessorProvider> receipt = provider;
Devin Moore18f63752024-08-08 21:01:24 +0000326 gAccessorProviders.push_back(AccessorProviderEntry(std::move(provider)));
327
Devin Moore5c0b8352024-09-05 19:45:27 +0000328 return receipt;
Devin Moore18f63752024-08-08 21:01:24 +0000329}
330
331status_t removeAccessorProvider(std::weak_ptr<AccessorProvider> wProvider) {
332 std::shared_ptr<AccessorProvider> provider = wProvider.lock();
333 if (provider == nullptr) {
334 ALOGE("The provider supplied to removeAccessorProvider has already been removed.");
335 return NAME_NOT_FOUND;
336 }
337 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
338 size_t sizeBefore = gAccessorProviders.size();
339 gAccessorProviders.erase(std::remove_if(gAccessorProviders.begin(), gAccessorProviders.end(),
340 [&](AccessorProviderEntry entry) {
341 return entry.mProvider == provider;
342 }),
343 gAccessorProviders.end());
344 if (sizeBefore == gAccessorProviders.size()) {
345 ALOGE("Failed to find an AccessorProvider for removeAccessorProvider");
346 return NAME_NOT_FOUND;
347 }
348
349 return OK;
350}
351
352status_t validateAccessor(const String16& instance, const sp<IBinder>& binder) {
353 if (binder == nullptr) {
354 ALOGE("Binder is null");
355 return BAD_VALUE;
356 }
357 sp<IAccessor> accessor = interface_cast<IAccessor>(binder);
358 if (accessor == nullptr) {
359 ALOGE("This binder for %s is not an IAccessor binder", String8(instance).c_str());
360 return BAD_TYPE;
361 }
362 String16 reportedInstance;
363 Status status = accessor->getInstanceName(&reportedInstance);
364 if (!status.isOk()) {
365 ALOGE("Failed to validate the binder being used to create a new ARpc_Accessor for %s with "
366 "status: %s",
367 String8(instance).c_str(), status.toString8().c_str());
368 return NAME_NOT_FOUND;
369 }
370 if (reportedInstance != instance) {
371 ALOGE("Instance %s doesn't match the Accessor's instance of %s", String8(instance).c_str(),
372 String8(reportedInstance).c_str());
373 return NAME_NOT_FOUND;
374 }
375 return OK;
376}
377
378sp<IBinder> createAccessor(const String16& instance,
379 RpcSocketAddressProvider&& connectionInfoProvider) {
380 // Try to create a new accessor
381 if (!connectionInfoProvider) {
382 ALOGE("Could not find an Accessor for %s and no ConnectionInfoProvider provided to "
383 "create a new one",
384 String8(instance).c_str());
385 return nullptr;
386 }
387 sp<IBinder> binder = sp<LocalAccessor>::make(instance, std::move(connectionInfoProvider));
388 return binder;
389}
390
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400391#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900392// IPermissionController is not accessible to vendors
393
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394bool checkCallingPermission(const String16& permission)
395{
Yi Kongfdd8da92018-06-07 17:52:27 -0700396 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397}
398
Steven Moreland1b264072021-06-03 23:04:02 +0000399static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700400
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
402{
403 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700404 pid_t pid = ipcState->getCallingPid();
405 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700407 if (outUid) *outUid = uid;
408 return checkPermission(permission, pid, uid);
409}
410
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000411bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700412 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700413 static sp<IPermissionController> gPermissionController;
414
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700416 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700418 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600419
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700420 auto startTime = std::chrono::steady_clock::now().min();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421
422 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700423 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 bool res = pc->checkPermission(permission, pid, uid);
425 if (res) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700426 if (startTime != startTime.min()) {
427 const auto waitTime = std::chrono::steady_clock::now() - startTime;
428 ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
429 to_ms(waitTime), String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430 }
431 return res;
432 }
Daniel Eratc2832702015-10-13 15:29:32 -0600433
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800435 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000436 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000437 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000438 uid, pid);
439 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440 return false;
441 }
Daniel Eratc2832702015-10-13 15:29:32 -0600442
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700444 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700446 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700448 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 }
Daniel Eratc2832702015-10-13 15:29:32 -0600450
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451 // Need to retrieve the permission controller.
452 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700453 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454 // Wait for the permission controller to come back...
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700455 if (startTime == startTime.min()) {
456 startTime = std::chrono::steady_clock::now();
Steve Blocka19954a2012-01-04 20:05:49 +0000457 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000458 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800459 }
460 sleep(1);
461 } else {
462 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600463 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700464 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800465 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700466 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800467 }
468 }
469}
470
Steven Moreland576662a2024-08-09 23:12:03 +0000471#endif //__ANDROID_VNDK__
472
Jooyung Han75fc06f2024-02-03 03:56:59 +0900473void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
Steven Moreland576662a2024-08-09 23:12:03 +0000474#if defined(__ANDROID__) && !defined(__ANDROID_VENDOR__) && !defined(__ANDROID_RECOVERY__) && \
475 !defined(__ANDROID_NATIVE_BRIDGE__)
Jooyung Han75fc06f2024-02-03 03:56:59 +0900476 sp<IServiceManager> sm = defaultServiceManager();
477 String16 name = interface + String16("/") + instance;
478 if (!sm->isDeclared(name)) {
479 return nullptr;
480 }
481 String16 libraryName = interface + String16(".") + instance + String16(".so");
482 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
483 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
484 String8(*updatableViaApex).c_str(), flag);
485 }
486 return android_load_sphal_library(String8(libraryName).c_str(), flag);
487#else
488 (void)interface;
489 (void)instance;
490 (void)flag;
491 return nullptr;
492#endif
493}
494
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800495// ----------------------------------------------------------------------
496
Parth Sanec7b58642024-08-07 10:31:15 +0000497CppBackendShim::CppBackendShim(const sp<BackendUnifiedServiceManager>& impl)
Parth Sane43e3b8b2024-08-05 13:39:04 +0000498 : mUnifiedServiceManager(impl) {}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700499
Steven Moreland5af7d852020-04-29 15:40:29 -0700500// This implementation could be simplified and made more efficient by delegating
501// to waitForService. However, this changes the threading structure in some
502// cases and could potentially break prebuilts. Once we have higher logistical
503// complexity, this could be attempted.
Parth Sanec7b58642024-08-07 10:31:15 +0000504sp<IBinder> CppBackendShim::getService(const String16& name) const {
Steven Moreland583685e2019-10-02 16:45:11 -0700505 static bool gSystemBootCompleted = false;
506
507 sp<IBinder> svc = checkService(name);
508 if (svc != nullptr) return svc;
509
510 const bool isVendorService =
511 strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700512 constexpr auto timeout = 5s;
513 const auto startTime = std::chrono::steady_clock::now();
Steven Moreland583685e2019-10-02 16:45:11 -0700514 // Vendor code can't access system properties
515 if (!gSystemBootCompleted && !isVendorService) {
516#ifdef __ANDROID__
517 char bootCompleted[PROPERTY_VALUE_MAX];
518 property_get("sys.boot_completed", bootCompleted, "0");
519 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
520#else
521 gSystemBootCompleted = true;
522#endif
523 }
524 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900525 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700526
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000527 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Tom Cherry8fda97f2020-07-22 17:15:44 -0700528 ProcessState::self()->getDriverName().c_str());
529
Steven Moreland583685e2019-10-02 16:45:11 -0700530 int n = 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700531 while (std::chrono::steady_clock::now() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700532 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700533 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700534
Yunfan Chen788e1c42018-03-29 16:52:09 +0900535 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700536 if (svc != nullptr) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700537 const auto waitTime = std::chrono::steady_clock::now() - startTime;
538 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000539 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700540 to_ms(waitTime));
Tom Cherry8fda97f2020-07-22 17:15:44 -0700541 return svc;
542 }
Steven Moreland583685e2019-10-02 16:45:11 -0700543 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000544 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700545 return nullptr;
546}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900547
Parth Sanec7b58642024-08-07 10:31:15 +0000548sp<IBinder> CppBackendShim::checkService(const String16& name) const {
Alice Wang8578f132024-05-03 09:01:56 +0000549 Service ret;
Parth Sane56a04712024-04-22 14:21:07 +0000550 if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700551 return nullptr;
552 }
Alice Wang8578f132024-05-03 09:01:56 +0000553 return ret.get<Service::Tag::binder>();
Steven Moreland583685e2019-10-02 16:45:11 -0700554}
555
Parth Sanec7b58642024-08-07 10:31:15 +0000556status_t CppBackendShim::addService(const String16& name, const sp<IBinder>& service,
557 bool allowIsolated, int dumpsysPriority) {
Parth Sane56a04712024-04-22 14:21:07 +0000558 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
559 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700560 return status.exceptionCode();
561}
562
Parth Sanec7b58642024-08-07 10:31:15 +0000563Vector<String16> CppBackendShim::listServices(int dumpsysPriority) {
Steven Moreland583685e2019-10-02 16:45:11 -0700564 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000565 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700566 return {};
567 }
568
569 Vector<String16> res;
570 res.setCapacity(ret.size());
571 for (const std::string& name : ret) {
572 res.push(String16(name.c_str()));
573 }
574 return res;
575}
576
Parth Sanec7b58642024-08-07 10:31:15 +0000577sp<IBinder> CppBackendShim::waitForService(const String16& name16) {
Steven Moreland583685e2019-10-02 16:45:11 -0700578 class Waiter : public android::os::BnServiceCallback {
579 Status onRegistration(const std::string& /*name*/,
580 const sp<IBinder>& binder) override {
581 std::unique_lock<std::mutex> lock(mMutex);
582 mBinder = binder;
583 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700584 // Flushing here helps ensure the service's ref count remains accurate
585 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700586 mCv.notify_one();
587 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900588 }
Steven Moreland583685e2019-10-02 16:45:11 -0700589 public:
590 sp<IBinder> mBinder;
591 std::mutex mMutex;
592 std::condition_variable mCv;
593 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900594
Jon Spivackfed6db42019-11-18 16:43:59 -0800595 // Simple RAII object to ensure a function call immediately before going out of scope
596 class Defer {
597 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900598 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800599 ~Defer() { mF(); }
600 private:
601 std::function<void()> mF;
602 };
603
Steven Moreland583685e2019-10-02 16:45:11 -0700604 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900605
Steven Moreland583685e2019-10-02 16:45:11 -0700606 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700607 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000608 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
609 status.toString8().c_str());
Elie Kheirallah27c26952022-09-07 21:45:26 +0000610 if (0 == ProcessState::self()->getThreadPoolMaxTotalThreadCount()) {
611 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
612 "Threadpool has 0 guaranteed threads. "
613 "Is the threadpool configured properly? "
614 "See ProcessState::startThreadPool and "
615 "ProcessState::setThreadPoolMaxThreadCount.");
616 }
Steven Moreland583685e2019-10-02 16:45:11 -0700617 return nullptr;
618 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800619 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700620
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000621 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000622 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000623 !status.isOk()) {
624 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
625 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700626 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800627 }
Parth Sane56a04712024-04-22 14:21:07 +0000628 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700629
Steven Moreland583685e2019-10-02 16:45:11 -0700630 while(true) {
631 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000632 // It would be really nice if we could read binder commands on this
633 // thread instead of needing a threadpool to be started, but for
634 // instance, if we call getAndExecuteCommand, it might be the case
635 // that another thread serves the callback, and we never get a
636 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700637 std::unique_lock<std::mutex> lock(waiter->mMutex);
Steven Moreland3d37ef22023-04-25 18:25:14 +0000638 waiter->mCv.wait_for(lock, 1s, [&] {
639 return waiter->mBinder != nullptr;
640 });
Steven Moreland583685e2019-10-02 16:45:11 -0700641 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700642 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800643
Steven Moreland3d37ef22023-04-25 18:25:14 +0000644 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000645 "threadpool: %zu. Are binder threads started and available?)",
646 name.c_str(), ProcessState::self()->getThreadPoolMaxTotalThreadCount());
Steven Morelandf2677e22020-07-14 19:58:08 +0000647
Steven Moreland583685e2019-10-02 16:45:11 -0700648 // Handle race condition for lazy services. Here is what can happen:
649 // - the service dies (not processed by init yet).
650 // - sm processes death notification.
651 // - sm gets getService and calls init to start service.
652 // - init gets the start signal, but the service already appears
653 // started, so it does nothing.
654 // - init gets death signal, but doesn't know it needs to restart
655 // the service
656 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700657 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000658 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
659 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700660 return nullptr;
661 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800662 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700663 }
Steven Moreland583685e2019-10-02 16:45:11 -0700664}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800665
Parth Sanec7b58642024-08-07 10:31:15 +0000666bool CppBackendShim::isDeclared(const String16& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700667 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000668 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000669 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000670 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000671 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700672 return false;
673 }
674 return declared;
675}
676
Parth Sanec7b58642024-08-07 10:31:15 +0000677Vector<String16> CppBackendShim::getDeclaredInstances(const String16& interface) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000678 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000679 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000680 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000681 !status.isOk()) {
682 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
683 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000684 return {};
685 }
686
687 Vector<String16> res;
688 res.setCapacity(out.size());
689 for (const std::string& instance : out) {
690 res.push(String16(instance.c_str()));
691 }
692 return res;
693}
694
Parth Sanec7b58642024-08-07 10:31:15 +0000695std::optional<String16> CppBackendShim::updatableViaApex(const String16& name) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000696 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000697 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000698 !status.isOk()) {
699 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
700 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000701 return std::nullopt;
702 }
703 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
704}
705
Parth Sanec7b58642024-08-07 10:31:15 +0000706Vector<String16> CppBackendShim::getUpdatableNames(const String16& apexName) {
Jooyung Han76944fe2022-10-25 17:02:45 +0900707 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000708 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900709 !status.isOk()) {
710 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
711 status.toString8().c_str());
712 return {};
713 }
714
715 Vector<String16> res;
716 res.setCapacity(out.size());
717 for (const std::string& instance : out) {
718 res.push(String16(instance.c_str()));
719 }
720 return res;
721}
722
Parth Sanec7b58642024-08-07 10:31:15 +0000723std::optional<IServiceManager::ConnectionInfo> CppBackendShim::getConnectionInfo(
Devin Moore5e4c2f12021-09-09 22:36:33 +0000724 const String16& name) {
725 std::optional<os::ConnectionInfo> connectionInfo;
726 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000727 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000728 !status.isOk()) {
729 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
730 status.toString8().c_str());
731 }
732 return connectionInfo.has_value()
733 ? std::make_optional<IServiceManager::ConnectionInfo>(
734 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
735 : std::nullopt;
736}
737
Parth Sanec7b58642024-08-07 10:31:15 +0000738status_t CppBackendShim::registerForNotifications(const String16& name,
739 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800740 if (cb == nullptr) {
741 ALOGE("%s: null cb passed", __FUNCTION__);
742 return BAD_VALUE;
743 }
744 std::string nameStr = String8(name).c_str();
745 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
746 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
747 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000748 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800749 !status.isOk()) {
750 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
751 status.toString8().c_str());
752 return UNKNOWN_ERROR;
753 }
754 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
755 return OK;
756}
757
Parth Sanec7b58642024-08-07 10:31:15 +0000758void CppBackendShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
759 ServiceCallbackMap::iterator* it,
760 sp<RegistrationWaiter>* waiter) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800761 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
762 for (auto lit = localRegistrationAndWaiters.begin();
763 lit != localRegistrationAndWaiters.end();) {
764 if (lit->first == cb) {
765 if (waiter) {
766 *waiter = lit->second;
767 }
768 lit = localRegistrationAndWaiters.erase(lit);
769 } else {
770 ++lit;
771 }
772 }
773
774 if (localRegistrationAndWaiters.empty()) {
775 mNameToRegistrationCallback.erase(*it);
776 }
777}
778
Parth Sanec7b58642024-08-07 10:31:15 +0000779status_t CppBackendShim::unregisterForNotifications(const String16& name,
780 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800781 if (cb == nullptr) {
782 ALOGE("%s: null cb passed", __FUNCTION__);
783 return BAD_VALUE;
784 }
785 std::string nameStr = String8(name).c_str();
786 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
787 auto it = mNameToRegistrationCallback.find(nameStr);
788 sp<RegistrationWaiter> registrationWaiter;
789 if (it != mNameToRegistrationCallback.end()) {
790 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
791 } else {
792 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
793 return BAD_VALUE;
794 }
795 if (registrationWaiter == nullptr) {
796 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
797 return BAD_VALUE;
798 }
Parth Sane56a04712024-04-22 14:21:07 +0000799 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800800 registrationWaiter);
801 !status.isOk()) {
802 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
803 String8(name).c_str(), status.toString8().c_str());
804 return UNKNOWN_ERROR;
805 }
806 return OK;
807}
808
Parth Sanec7b58642024-08-07 10:31:15 +0000809std::vector<IServiceManager::ServiceDebugInfo> CppBackendShim::getServiceDebugInfo() {
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000810 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
811 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000812 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000813 !status.isOk()) {
814 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
815 return ret;
816 }
817 for (const auto& serviceDebugInfo : serviceDebugInfos) {
818 IServiceManager::ServiceDebugInfo retInfo;
819 retInfo.pid = serviceDebugInfo.debugPid;
820 retInfo.name = serviceDebugInfo.name;
821 ret.emplace_back(retInfo);
822 }
823 return ret;
824}
825
Yifan Hongf7760012021-06-04 16:04:42 -0700826#ifndef __ANDROID__
Parth Sanec7b58642024-08-07 10:31:15 +0000827// CppBackendShim for host. Implements the old libbinder android::IServiceManager API.
Yifan Hongf7760012021-06-04 16:04:42 -0700828// The internal implementation of the AIDL interface android::os::IServiceManager calls into
829// on-device service manager.
Parth Sanec7b58642024-08-07 10:31:15 +0000830class CppServiceManagerHostShim : public CppBackendShim {
Yifan Hongf7760012021-06-04 16:04:42 -0700831public:
Parth Sanec7b58642024-08-07 10:31:15 +0000832 CppServiceManagerHostShim(const sp<AidlServiceManager>& impl,
833 const RpcDelegateServiceManagerOptions& options)
834 : CppBackendShim(sp<BackendUnifiedServiceManager>::make(impl)), mOptions(options) {}
835 // CppBackendShim::getService is based on checkService, so no need to override it.
Yifan Hongf7760012021-06-04 16:04:42 -0700836 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700837 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700838 }
839
840protected:
Parth Sanec7b58642024-08-07 10:31:15 +0000841 // Override realGetService for CppBackendShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700842 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700843 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700844 return Status::ok();
845 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700846
847private:
848 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700849};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700850sp<IServiceManager> createRpcDelegateServiceManager(
851 const RpcDelegateServiceManagerOptions& options) {
852 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700853 if (binder == nullptr) {
854 ALOGE("getDeviceService(\"manager\") returns null");
855 return nullptr;
856 }
857 auto interface = AidlServiceManager::asInterface(binder);
858 if (interface == nullptr) {
859 ALOGE("getDeviceService(\"manager\") returns non service manager");
860 return nullptr;
861 }
Parth Sanec7b58642024-08-07 10:31:15 +0000862 return sp<CppServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700863}
864#endif
865
Steven Moreland61ff8492019-09-26 16:05:45 -0700866} // namespace android