blob: 61866d70d32e1b45cd7fd87943b4a59615951d27 [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
Parth Sanedc207542024-11-14 11:49:08 +0000130 void enableAddServiceCache(bool value) { mUnifiedServiceManager->enableAddServiceCache(value); }
131
Yifan Hongf7760012021-06-04 16:04:42 -0700132protected:
Parth Sane56a04712024-04-22 14:21:07 +0000133 sp<BackendUnifiedServiceManager> mUnifiedServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800134 // AidlRegistrationCallback -> services that its been registered for
135 // notifications.
136 using LocalRegistrationAndWaiter =
137 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
138 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
139 ServiceCallbackMap mNameToRegistrationCallback;
140 std::mutex mNameToRegistrationLock;
141
142 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
143 ServiceCallbackMap::iterator* it,
144 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700145
146 // Directly get the service in a way that, for lazy services, requests the service to be started
Parth Sanec7b58642024-08-07 10:31:15 +0000147 // if it is not currently started. This way, calls directly to CppBackendShim::getService
Yifan Hongf7760012021-06-04 16:04:42 -0700148 // will still have the 5s delay that is expected by a large amount of Android code.
149 //
Parth Sanec7b58642024-08-07 10:31:15 +0000150 // When implementing CppBackendShim, use realGetService instead of
151 // mUnifiedServiceManager->getService so that it can be overridden in CppServiceManagerHostShim.
Yifan Hongf7760012021-06-04 16:04:42 -0700152 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Alice Wang8578f132024-05-03 09:01:56 +0000153 Service service;
Alice Wang11da1502024-07-25 12:03:22 +0000154 Status status = mUnifiedServiceManager->getService2(name, &service);
Alice Wang8578f132024-05-03 09:01:56 +0000155 *_aidl_return = service.get<Service::Tag::binder>();
156 return status;
Yifan Hongf7760012021-06-04 16:04:42 -0700157 }
Steven Moreland583685e2019-10-02 16:45:11 -0700158};
159
Devin Moore18f63752024-08-08 21:01:24 +0000160class AccessorProvider {
161public:
Devin Moorec370db42024-08-09 23:18:05 +0000162 AccessorProvider(std::set<std::string>&& instances, RpcAccessorProvider&& provider)
163 : mInstances(std::move(instances)), mProvider(std::move(provider)) {}
164 sp<IBinder> provide(const String16& name) {
165 if (mInstances.count(String8(name).c_str()) > 0) {
166 return mProvider(name);
167 } else {
168 return nullptr;
169 }
170 }
171 const std::set<std::string>& instances() { return mInstances; }
Devin Moore18f63752024-08-08 21:01:24 +0000172
173private:
174 AccessorProvider() = delete;
175
Devin Moorec370db42024-08-09 23:18:05 +0000176 std::set<std::string> mInstances;
Devin Moore18f63752024-08-08 21:01:24 +0000177 RpcAccessorProvider mProvider;
178};
179
180class AccessorProviderEntry {
181public:
Devin Moore5c0b8352024-09-05 19:45:27 +0000182 AccessorProviderEntry(std::shared_ptr<AccessorProvider>&& provider)
183 : mProvider(std::move(provider)) {}
Devin Moore18f63752024-08-08 21:01:24 +0000184 std::shared_ptr<AccessorProvider> mProvider;
185
186private:
187 AccessorProviderEntry() = delete;
188};
189
Steven Moreland1698ffd2020-05-15 23:43:52 +0000190[[clang::no_destroy]] static std::once_flag gSmOnce;
191[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Devin Moore18f63752024-08-08 21:01:24 +0000192[[clang::no_destroy]] static std::mutex gAccessorProvidersMutex;
193[[clang::no_destroy]] static std::vector<AccessorProviderEntry> gAccessorProviders;
194
195class LocalAccessor : public android::os::BnAccessor {
196public:
197 LocalAccessor(const String16& instance, RpcSocketAddressProvider&& connectionInfoProvider)
Devin Moore5c0b8352024-09-05 19:45:27 +0000198 : mInstance(instance), mConnectionInfoProvider(std::move(connectionInfoProvider)) {
Devin Moore18f63752024-08-08 21:01:24 +0000199 LOG_ALWAYS_FATAL_IF(!mConnectionInfoProvider,
200 "LocalAccessor object needs a valid connection info provider");
201 }
202
203 ~LocalAccessor() {
204 if (mOnDelete) mOnDelete();
205 }
206
207 ::android::binder::Status addConnection(::android::os::ParcelFileDescriptor* outFd) {
208 using android::os::IAccessor;
209 sockaddr_storage addrStorage;
210 std::unique_ptr<FdTrigger> trigger = FdTrigger::make();
211 RpcTransportFd fd;
212 status_t status =
213 mConnectionInfoProvider(mInstance, reinterpret_cast<sockaddr*>(&addrStorage),
214 sizeof(addrStorage));
215 if (status != OK) {
216 const std::string error = "The connection info provider was unable to provide "
217 "connection info for instance " +
218 std::string(String8(mInstance).c_str()) +
219 " with status: " + statusToString(status);
220 ALOGE("%s", error.c_str());
221 return Status::fromServiceSpecificError(IAccessor::ERROR_CONNECTION_INFO_NOT_FOUND,
222 error.c_str());
223 }
224 if (addrStorage.ss_family == AF_VSOCK) {
225 sockaddr_vm* addr = reinterpret_cast<sockaddr_vm*>(&addrStorage);
226 status = singleSocketConnection(VsockSocketAddress(addr->svm_cid, addr->svm_port),
227 trigger, &fd);
228 } else if (addrStorage.ss_family == AF_UNIX) {
229 sockaddr_un* addr = reinterpret_cast<sockaddr_un*>(&addrStorage);
230 status = singleSocketConnection(UnixSocketAddress(addr->sun_path), trigger, &fd);
231 } else if (addrStorage.ss_family == AF_INET) {
232 sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(&addrStorage);
233 status = singleSocketConnection(InetSocketAddress(reinterpret_cast<sockaddr*>(addr),
234 sizeof(sockaddr_in),
235 inet_ntoa(addr->sin_addr),
236 ntohs(addr->sin_port)),
237 trigger, &fd);
238 } else {
239 const std::string error =
240 "Unsupported socket family type or the ConnectionInfoProvider failed to find a "
241 "valid address. Family type: " +
242 std::to_string(addrStorage.ss_family);
243 ALOGE("%s", error.c_str());
244 return Status::fromServiceSpecificError(IAccessor::ERROR_UNSUPPORTED_SOCKET_FAMILY,
245 error.c_str());
246 }
247 if (status != OK) {
248 const std::string error = "Failed to connect to socket for " +
249 std::string(String8(mInstance).c_str()) +
250 " with status: " + statusToString(status);
251 ALOGE("%s", error.c_str());
252 int err = 0;
253 if (status == -EACCES) {
254 err = IAccessor::ERROR_FAILED_TO_CONNECT_EACCES;
255 } else {
256 err = IAccessor::ERROR_FAILED_TO_CONNECT_TO_SOCKET;
257 }
258 return Status::fromServiceSpecificError(err, error.c_str());
259 }
260 *outFd = os::ParcelFileDescriptor(std::move(fd.fd));
261 return Status::ok();
262 }
263
264 ::android::binder::Status getInstanceName(String16* instance) {
265 *instance = mInstance;
266 return Status::ok();
267 }
268
269private:
270 LocalAccessor() = delete;
271 String16 mInstance;
272 RpcSocketAddressProvider mConnectionInfoProvider;
273 std::function<void()> mOnDelete;
274};
275
276android::binder::Status getInjectedAccessor(const std::string& name,
277 android::os::Service* service) {
278 std::vector<AccessorProviderEntry> copiedProviders;
279 {
280 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
281 copiedProviders.insert(copiedProviders.begin(), gAccessorProviders.begin(),
282 gAccessorProviders.end());
283 }
284
285 // Unlocked to call the providers. This requires the providers to be
286 // threadsafe and not contain any references to objects that could be
287 // deleted.
288 for (const auto& provider : copiedProviders) {
289 sp<IBinder> binder = provider.mProvider->provide(String16(name.c_str()));
290 if (binder == nullptr) continue;
291 status_t status = validateAccessor(String16(name.c_str()), binder);
292 if (status != OK) {
293 ALOGE("A provider returned a binder that is not an IAccessor for instance %s. Status: "
294 "%s",
295 name.c_str(), statusToString(status).c_str());
296 return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
297 }
298 *service = os::Service::make<os::Service::Tag::accessor>(binder);
299 return android::binder::Status::ok();
300 }
301
302 *service = os::Service::make<os::Service::Tag::accessor>(nullptr);
303 return android::binder::Status::ok();
304}
Brett Chabot38dbade2020-01-24 12:59:43 -0800305
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306sp<IServiceManager> defaultServiceManager()
307{
Martijn Coenen402c8672020-02-03 10:01:36 +0100308 std::call_once(gSmOnce, []() {
Parth Sanec7b58642024-08-07 10:31:15 +0000309 gDefaultServiceManager = sp<CppBackendShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100310 });
Daniel Eratc2832702015-10-13 15:29:32 -0600311
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312 return gDefaultServiceManager;
313}
314
Brett Chabot38dbade2020-01-24 12:59:43 -0800315void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100316 bool called = false;
317 std::call_once(gSmOnce, [&]() {
318 gDefaultServiceManager = sm;
319 called = true;
320 });
321
322 if (!called) {
323 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
324 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800325}
326
Parth Saneb6ed0eb2024-06-25 14:38:42 +0000327sp<IServiceManager> getServiceManagerShimFromAidlServiceManagerForTests(
328 const sp<AidlServiceManager>& sm) {
329 return sp<CppBackendShim>::make(sp<BackendUnifiedServiceManager>::make(sm));
330}
331
Devin Moorec370db42024-08-09 23:18:05 +0000332// gAccessorProvidersMutex must be locked already
333static bool isInstanceProvidedLocked(const std::string& instance) {
334 return gAccessorProviders.end() !=
335 std::find_if(gAccessorProviders.begin(), gAccessorProviders.end(),
336 [&instance](const AccessorProviderEntry& entry) {
337 return entry.mProvider->instances().count(instance) > 0;
338 });
339}
340
341std::weak_ptr<AccessorProvider> addAccessorProvider(std::set<std::string>&& instances,
342 RpcAccessorProvider&& providerCallback) {
343 if (instances.empty()) {
344 ALOGE("Set of instances is empty! Need a non empty set of instances to provide for.");
345 return std::weak_ptr<AccessorProvider>();
346 }
Devin Moore18f63752024-08-08 21:01:24 +0000347 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
Devin Moorec370db42024-08-09 23:18:05 +0000348 for (const auto& instance : instances) {
349 if (isInstanceProvidedLocked(instance)) {
350 ALOGE("The instance %s is already provided for by a previously added "
351 "RpcAccessorProvider.",
352 instance.c_str());
353 return std::weak_ptr<AccessorProvider>();
354 }
355 }
Devin Moore18f63752024-08-08 21:01:24 +0000356 std::shared_ptr<AccessorProvider> provider =
Devin Moorec370db42024-08-09 23:18:05 +0000357 std::make_shared<AccessorProvider>(std::move(instances), std::move(providerCallback));
Devin Moore5c0b8352024-09-05 19:45:27 +0000358 std::weak_ptr<AccessorProvider> receipt = provider;
Devin Moore18f63752024-08-08 21:01:24 +0000359 gAccessorProviders.push_back(AccessorProviderEntry(std::move(provider)));
360
Devin Moore5c0b8352024-09-05 19:45:27 +0000361 return receipt;
Devin Moore18f63752024-08-08 21:01:24 +0000362}
363
364status_t removeAccessorProvider(std::weak_ptr<AccessorProvider> wProvider) {
365 std::shared_ptr<AccessorProvider> provider = wProvider.lock();
366 if (provider == nullptr) {
Devin Moorec370db42024-08-09 23:18:05 +0000367 ALOGE("The provider supplied to removeAccessorProvider has already been removed or the "
368 "argument to this function was nullptr.");
369 return BAD_VALUE;
Devin Moore18f63752024-08-08 21:01:24 +0000370 }
371 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
372 size_t sizeBefore = gAccessorProviders.size();
373 gAccessorProviders.erase(std::remove_if(gAccessorProviders.begin(), gAccessorProviders.end(),
374 [&](AccessorProviderEntry entry) {
375 return entry.mProvider == provider;
376 }),
377 gAccessorProviders.end());
378 if (sizeBefore == gAccessorProviders.size()) {
379 ALOGE("Failed to find an AccessorProvider for removeAccessorProvider");
380 return NAME_NOT_FOUND;
381 }
382
383 return OK;
384}
385
386status_t validateAccessor(const String16& instance, const sp<IBinder>& binder) {
387 if (binder == nullptr) {
388 ALOGE("Binder is null");
389 return BAD_VALUE;
390 }
Devin Moore0555fbf2024-08-29 15:51:50 +0000391 sp<IAccessor> accessor = checked_interface_cast<IAccessor>(binder);
Devin Moore18f63752024-08-08 21:01:24 +0000392 if (accessor == nullptr) {
393 ALOGE("This binder for %s is not an IAccessor binder", String8(instance).c_str());
394 return BAD_TYPE;
395 }
396 String16 reportedInstance;
397 Status status = accessor->getInstanceName(&reportedInstance);
398 if (!status.isOk()) {
399 ALOGE("Failed to validate the binder being used to create a new ARpc_Accessor for %s with "
400 "status: %s",
401 String8(instance).c_str(), status.toString8().c_str());
402 return NAME_NOT_FOUND;
403 }
404 if (reportedInstance != instance) {
405 ALOGE("Instance %s doesn't match the Accessor's instance of %s", String8(instance).c_str(),
406 String8(reportedInstance).c_str());
407 return NAME_NOT_FOUND;
408 }
409 return OK;
410}
411
412sp<IBinder> createAccessor(const String16& instance,
413 RpcSocketAddressProvider&& connectionInfoProvider) {
414 // Try to create a new accessor
415 if (!connectionInfoProvider) {
416 ALOGE("Could not find an Accessor for %s and no ConnectionInfoProvider provided to "
417 "create a new one",
418 String8(instance).c_str());
419 return nullptr;
420 }
421 sp<IBinder> binder = sp<LocalAccessor>::make(instance, std::move(connectionInfoProvider));
422 return binder;
423}
424
Devin Moore0555fbf2024-08-29 15:51:50 +0000425status_t delegateAccessor(const String16& name, const sp<IBinder>& accessor,
426 sp<IBinder>* delegator) {
427 LOG_ALWAYS_FATAL_IF(delegator == nullptr, "delegateAccessor called with a null out param");
428 if (accessor == nullptr) {
429 ALOGW("Accessor argument to delegateAccessor is null.");
430 *delegator = nullptr;
431 return OK;
432 }
433 status_t status = validateAccessor(name, accessor);
434 if (status != OK) {
435 ALOGE("The provided accessor binder is not an IAccessor for instance %s. Status: "
436 "%s",
437 String8(name).c_str(), statusToString(status).c_str());
438 return status;
439 }
440 // validateAccessor already called checked_interface_cast and made sure this
441 // is a valid accessor object.
442 *delegator = sp<android::os::IAccessorDelegator>::make(interface_cast<IAccessor>(accessor));
443
444 return OK;
445}
446
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400447#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900448// IPermissionController is not accessible to vendors
449
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450bool checkCallingPermission(const String16& permission)
451{
Yi Kongfdd8da92018-06-07 17:52:27 -0700452 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453}
454
Steven Moreland1b264072021-06-03 23:04:02 +0000455static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700456
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
458{
459 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700460 pid_t pid = ipcState->getCallingPid();
461 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800462 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700463 if (outUid) *outUid = uid;
464 return checkPermission(permission, pid, uid);
465}
466
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000467bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700468 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700469 static sp<IPermissionController> gPermissionController;
470
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800471 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700472 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800473 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700474 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600475
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700476 auto startTime = std::chrono::steady_clock::now().min();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477
478 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700479 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800480 bool res = pc->checkPermission(permission, pid, uid);
481 if (res) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700482 if (startTime != startTime.min()) {
483 const auto waitTime = std::chrono::steady_clock::now() - startTime;
484 ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
485 to_ms(waitTime), String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800486 }
487 return res;
488 }
Daniel Eratc2832702015-10-13 15:29:32 -0600489
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800491 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000492 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000493 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000494 uid, pid);
495 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800496 return false;
497 }
Daniel Eratc2832702015-10-13 15:29:32 -0600498
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800499 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700500 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700502 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800503 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700504 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800505 }
Daniel Eratc2832702015-10-13 15:29:32 -0600506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507 // Need to retrieve the permission controller.
508 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700509 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800510 // Wait for the permission controller to come back...
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700511 if (startTime == startTime.min()) {
512 startTime = std::chrono::steady_clock::now();
Steve Blocka19954a2012-01-04 20:05:49 +0000513 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000514 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515 }
516 sleep(1);
517 } else {
518 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600519 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700520 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700522 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523 }
524 }
525}
526
Steven Moreland576662a2024-08-09 23:12:03 +0000527#endif //__ANDROID_VNDK__
528
Jooyung Han75fc06f2024-02-03 03:56:59 +0900529void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
Steven Moreland576662a2024-08-09 23:12:03 +0000530#if defined(__ANDROID__) && !defined(__ANDROID_VENDOR__) && !defined(__ANDROID_RECOVERY__) && \
531 !defined(__ANDROID_NATIVE_BRIDGE__)
Jooyung Han75fc06f2024-02-03 03:56:59 +0900532 sp<IServiceManager> sm = defaultServiceManager();
533 String16 name = interface + String16("/") + instance;
534 if (!sm->isDeclared(name)) {
535 return nullptr;
536 }
537 String16 libraryName = interface + String16(".") + instance + String16(".so");
538 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
539 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
540 String8(*updatableViaApex).c_str(), flag);
541 }
542 return android_load_sphal_library(String8(libraryName).c_str(), flag);
543#else
544 (void)interface;
545 (void)instance;
546 (void)flag;
547 return nullptr;
548#endif
549}
550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551// ----------------------------------------------------------------------
552
Parth Sanec7b58642024-08-07 10:31:15 +0000553CppBackendShim::CppBackendShim(const sp<BackendUnifiedServiceManager>& impl)
Parth Sane43e3b8b2024-08-05 13:39:04 +0000554 : mUnifiedServiceManager(impl) {}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700555
Steven Moreland5af7d852020-04-29 15:40:29 -0700556// This implementation could be simplified and made more efficient by delegating
557// to waitForService. However, this changes the threading structure in some
558// cases and could potentially break prebuilts. Once we have higher logistical
559// complexity, this could be attempted.
Parth Sanec7b58642024-08-07 10:31:15 +0000560sp<IBinder> CppBackendShim::getService(const String16& name) const {
Steven Moreland583685e2019-10-02 16:45:11 -0700561 static bool gSystemBootCompleted = false;
562
563 sp<IBinder> svc = checkService(name);
564 if (svc != nullptr) return svc;
565
Devin Moore74bc5892024-10-23 17:12:19 +0000566 sp<ProcessState> self = ProcessState::selfOrNull();
Steven Moreland583685e2019-10-02 16:45:11 -0700567 const bool isVendorService =
Devin Moore74bc5892024-10-23 17:12:19 +0000568 self && strcmp(self->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700569 constexpr auto timeout = 5s;
570 const auto startTime = std::chrono::steady_clock::now();
Steven Moreland583685e2019-10-02 16:45:11 -0700571 // Vendor code can't access system properties
572 if (!gSystemBootCompleted && !isVendorService) {
573#ifdef __ANDROID__
574 char bootCompleted[PROPERTY_VALUE_MAX];
575 property_get("sys.boot_completed", bootCompleted, "0");
576 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
577#else
578 gSystemBootCompleted = true;
579#endif
580 }
581 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900582 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700583
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000584 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Devin Moore74bc5892024-10-23 17:12:19 +0000585 self ? self->getDriverName().c_str() : "RPC accessors only");
Tom Cherry8fda97f2020-07-22 17:15:44 -0700586
Steven Moreland583685e2019-10-02 16:45:11 -0700587 int n = 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700588 while (std::chrono::steady_clock::now() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700589 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700590 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700591
Yunfan Chen788e1c42018-03-29 16:52:09 +0900592 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700593 if (svc != nullptr) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700594 const auto waitTime = std::chrono::steady_clock::now() - startTime;
595 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000596 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700597 to_ms(waitTime));
Tom Cherry8fda97f2020-07-22 17:15:44 -0700598 return svc;
599 }
Steven Moreland583685e2019-10-02 16:45:11 -0700600 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000601 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700602 return nullptr;
603}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900604
Parth Sanec7b58642024-08-07 10:31:15 +0000605sp<IBinder> CppBackendShim::checkService(const String16& name) const {
Alice Wang8578f132024-05-03 09:01:56 +0000606 Service ret;
Parth Sane56a04712024-04-22 14:21:07 +0000607 if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700608 return nullptr;
609 }
Alice Wang8578f132024-05-03 09:01:56 +0000610 return ret.get<Service::Tag::binder>();
Steven Moreland583685e2019-10-02 16:45:11 -0700611}
612
Parth Sanec7b58642024-08-07 10:31:15 +0000613status_t CppBackendShim::addService(const String16& name, const sp<IBinder>& service,
614 bool allowIsolated, int dumpsysPriority) {
Parth Sane56a04712024-04-22 14:21:07 +0000615 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
616 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700617 return status.exceptionCode();
618}
619
Parth Sanec7b58642024-08-07 10:31:15 +0000620Vector<String16> CppBackendShim::listServices(int dumpsysPriority) {
Steven Moreland583685e2019-10-02 16:45:11 -0700621 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000622 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700623 return {};
624 }
625
626 Vector<String16> res;
627 res.setCapacity(ret.size());
628 for (const std::string& name : ret) {
629 res.push(String16(name.c_str()));
630 }
631 return res;
632}
633
Parth Sanec7b58642024-08-07 10:31:15 +0000634sp<IBinder> CppBackendShim::waitForService(const String16& name16) {
Steven Moreland583685e2019-10-02 16:45:11 -0700635 class Waiter : public android::os::BnServiceCallback {
636 Status onRegistration(const std::string& /*name*/,
637 const sp<IBinder>& binder) override {
638 std::unique_lock<std::mutex> lock(mMutex);
639 mBinder = binder;
640 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700641 // Flushing here helps ensure the service's ref count remains accurate
642 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700643 mCv.notify_one();
644 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900645 }
Steven Moreland583685e2019-10-02 16:45:11 -0700646 public:
647 sp<IBinder> mBinder;
648 std::mutex mMutex;
649 std::condition_variable mCv;
650 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900651
Jon Spivackfed6db42019-11-18 16:43:59 -0800652 // Simple RAII object to ensure a function call immediately before going out of scope
653 class Defer {
654 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900655 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800656 ~Defer() { mF(); }
657 private:
658 std::function<void()> mF;
659 };
660
Steven Moreland583685e2019-10-02 16:45:11 -0700661 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900662
Steven Moreland583685e2019-10-02 16:45:11 -0700663 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700664 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000665 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
666 status.toString8().c_str());
Devin Moore74bc5892024-10-23 17:12:19 +0000667 sp<ProcessState> self = ProcessState::selfOrNull();
668 if (self && 0 == self->getThreadPoolMaxTotalThreadCount()) {
Elie Kheirallah27c26952022-09-07 21:45:26 +0000669 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
670 "Threadpool has 0 guaranteed threads. "
671 "Is the threadpool configured properly? "
672 "See ProcessState::startThreadPool and "
673 "ProcessState::setThreadPoolMaxThreadCount.");
674 }
Steven Moreland583685e2019-10-02 16:45:11 -0700675 return nullptr;
676 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800677 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700678
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000679 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000680 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000681 !status.isOk()) {
682 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
683 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700684 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800685 }
Parth Sane56a04712024-04-22 14:21:07 +0000686 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700687
Steven Moreland583685e2019-10-02 16:45:11 -0700688 while(true) {
689 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000690 // It would be really nice if we could read binder commands on this
691 // thread instead of needing a threadpool to be started, but for
692 // instance, if we call getAndExecuteCommand, it might be the case
693 // that another thread serves the callback, and we never get a
694 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700695 std::unique_lock<std::mutex> lock(waiter->mMutex);
Steven Moreland3d37ef22023-04-25 18:25:14 +0000696 waiter->mCv.wait_for(lock, 1s, [&] {
697 return waiter->mBinder != nullptr;
698 });
Steven Moreland583685e2019-10-02 16:45:11 -0700699 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701
Devin Moore74bc5892024-10-23 17:12:19 +0000702 sp<ProcessState> self = ProcessState::selfOrNull();
Steven Moreland3d37ef22023-04-25 18:25:14 +0000703 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000704 "threadpool: %zu. Are binder threads started and available?)",
Devin Moore74bc5892024-10-23 17:12:19 +0000705 name.c_str(), self ? self->getThreadPoolMaxTotalThreadCount() : 0);
Steven Morelandf2677e22020-07-14 19:58:08 +0000706
Steven Moreland583685e2019-10-02 16:45:11 -0700707 // Handle race condition for lazy services. Here is what can happen:
708 // - the service dies (not processed by init yet).
709 // - sm processes death notification.
710 // - sm gets getService and calls init to start service.
711 // - init gets the start signal, but the service already appears
712 // started, so it does nothing.
713 // - init gets death signal, but doesn't know it needs to restart
714 // the service
715 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700716 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000717 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
718 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700719 return nullptr;
720 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800721 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700722 }
Steven Moreland583685e2019-10-02 16:45:11 -0700723}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724
Parth Sanec7b58642024-08-07 10:31:15 +0000725bool CppBackendShim::isDeclared(const String16& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700726 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000727 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000728 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000729 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000730 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700731 return false;
732 }
733 return declared;
734}
735
Parth Sanec7b58642024-08-07 10:31:15 +0000736Vector<String16> CppBackendShim::getDeclaredInstances(const String16& interface) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000737 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000738 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000739 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000740 !status.isOk()) {
741 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
742 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000743 return {};
744 }
745
746 Vector<String16> res;
747 res.setCapacity(out.size());
748 for (const std::string& instance : out) {
749 res.push(String16(instance.c_str()));
750 }
751 return res;
752}
753
Parth Sanec7b58642024-08-07 10:31:15 +0000754std::optional<String16> CppBackendShim::updatableViaApex(const String16& name) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000755 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000756 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000757 !status.isOk()) {
758 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
759 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000760 return std::nullopt;
761 }
762 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
763}
764
Parth Sanec7b58642024-08-07 10:31:15 +0000765Vector<String16> CppBackendShim::getUpdatableNames(const String16& apexName) {
Jooyung Han76944fe2022-10-25 17:02:45 +0900766 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000767 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900768 !status.isOk()) {
769 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
770 status.toString8().c_str());
771 return {};
772 }
773
774 Vector<String16> res;
775 res.setCapacity(out.size());
776 for (const std::string& instance : out) {
777 res.push(String16(instance.c_str()));
778 }
779 return res;
780}
781
Parth Sanec7b58642024-08-07 10:31:15 +0000782std::optional<IServiceManager::ConnectionInfo> CppBackendShim::getConnectionInfo(
Devin Moore5e4c2f12021-09-09 22:36:33 +0000783 const String16& name) {
784 std::optional<os::ConnectionInfo> connectionInfo;
785 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000786 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000787 !status.isOk()) {
788 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
789 status.toString8().c_str());
790 }
791 return connectionInfo.has_value()
792 ? std::make_optional<IServiceManager::ConnectionInfo>(
793 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
794 : std::nullopt;
795}
796
Parth Sanec7b58642024-08-07 10:31:15 +0000797status_t CppBackendShim::registerForNotifications(const String16& name,
798 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800799 if (cb == nullptr) {
800 ALOGE("%s: null cb passed", __FUNCTION__);
801 return BAD_VALUE;
802 }
803 std::string nameStr = String8(name).c_str();
804 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
805 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
806 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000807 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800808 !status.isOk()) {
809 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
810 status.toString8().c_str());
811 return UNKNOWN_ERROR;
812 }
813 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
814 return OK;
815}
816
Parth Sanec7b58642024-08-07 10:31:15 +0000817void CppBackendShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
818 ServiceCallbackMap::iterator* it,
819 sp<RegistrationWaiter>* waiter) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800820 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
821 for (auto lit = localRegistrationAndWaiters.begin();
822 lit != localRegistrationAndWaiters.end();) {
823 if (lit->first == cb) {
824 if (waiter) {
825 *waiter = lit->second;
826 }
827 lit = localRegistrationAndWaiters.erase(lit);
828 } else {
829 ++lit;
830 }
831 }
832
833 if (localRegistrationAndWaiters.empty()) {
834 mNameToRegistrationCallback.erase(*it);
835 }
836}
837
Parth Sanec7b58642024-08-07 10:31:15 +0000838status_t CppBackendShim::unregisterForNotifications(const String16& name,
839 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800840 if (cb == nullptr) {
841 ALOGE("%s: null cb passed", __FUNCTION__);
842 return BAD_VALUE;
843 }
844 std::string nameStr = String8(name).c_str();
845 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
846 auto it = mNameToRegistrationCallback.find(nameStr);
847 sp<RegistrationWaiter> registrationWaiter;
848 if (it != mNameToRegistrationCallback.end()) {
849 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
850 } else {
851 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
852 return BAD_VALUE;
853 }
854 if (registrationWaiter == nullptr) {
855 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
856 return BAD_VALUE;
857 }
Parth Sane56a04712024-04-22 14:21:07 +0000858 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800859 registrationWaiter);
860 !status.isOk()) {
861 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
862 String8(name).c_str(), status.toString8().c_str());
863 return UNKNOWN_ERROR;
864 }
865 return OK;
866}
867
Parth Sanec7b58642024-08-07 10:31:15 +0000868std::vector<IServiceManager::ServiceDebugInfo> CppBackendShim::getServiceDebugInfo() {
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000869 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
870 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000871 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000872 !status.isOk()) {
873 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
874 return ret;
875 }
876 for (const auto& serviceDebugInfo : serviceDebugInfos) {
877 IServiceManager::ServiceDebugInfo retInfo;
878 retInfo.pid = serviceDebugInfo.debugPid;
879 retInfo.name = serviceDebugInfo.name;
880 ret.emplace_back(retInfo);
881 }
882 return ret;
883}
884
Yifan Hongf7760012021-06-04 16:04:42 -0700885#ifndef __ANDROID__
Parth Sanec7b58642024-08-07 10:31:15 +0000886// CppBackendShim for host. Implements the old libbinder android::IServiceManager API.
Yifan Hongf7760012021-06-04 16:04:42 -0700887// The internal implementation of the AIDL interface android::os::IServiceManager calls into
888// on-device service manager.
Parth Sanec7b58642024-08-07 10:31:15 +0000889class CppServiceManagerHostShim : public CppBackendShim {
Yifan Hongf7760012021-06-04 16:04:42 -0700890public:
Parth Sanec7b58642024-08-07 10:31:15 +0000891 CppServiceManagerHostShim(const sp<AidlServiceManager>& impl,
892 const RpcDelegateServiceManagerOptions& options)
893 : CppBackendShim(sp<BackendUnifiedServiceManager>::make(impl)), mOptions(options) {}
894 // CppBackendShim::getService is based on checkService, so no need to override it.
Yifan Hongf7760012021-06-04 16:04:42 -0700895 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700896 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700897 }
898
899protected:
Parth Sanec7b58642024-08-07 10:31:15 +0000900 // Override realGetService for CppBackendShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700901 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700902 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700903 return Status::ok();
904 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700905
906private:
907 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700908};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700909sp<IServiceManager> createRpcDelegateServiceManager(
910 const RpcDelegateServiceManagerOptions& options) {
911 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700912 if (binder == nullptr) {
913 ALOGE("getDeviceService(\"manager\") returns null");
914 return nullptr;
915 }
916 auto interface = AidlServiceManager::asInterface(binder);
917 if (interface == nullptr) {
918 ALOGE("getDeviceService(\"manager\") returns non service manager");
919 return nullptr;
920 }
Parth Sanec7b58642024-08-07 10:31:15 +0000921 return sp<CppServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700922}
923#endif
924
Steven Moreland61ff8492019-09-26 16:05:45 -0700925} // namespace android