blob: c9ca64647264152f5b3610c7f59bd91e697388df [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
Kevin Lindkviste8e12432022-11-23 13:23:42 +010046#if !(defined(__ANDROID__) || defined(__FUCHSIA))
47#define BINDER_SERVICEMANAGEMENT_DELEGATION_SUPPORT
48#endif
49
50#if !defined(BINDER_SERVICEMANAGEMENT_DELEGATION_SUPPORT)
Yunfan Chen788e1c42018-03-29 16:52:09 +090051#include <cutils/properties.h>
Yifan Hongf7760012021-06-04 16:04:42 -070052#else
53#include "ServiceManagerHost.h"
Steven Moreland28723ae2019-04-01 18:52:30 -070054#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055
Jooyung Han75fc06f2024-02-03 03:56:59 +090056#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__) && !defined(__ANDROID_NATIVE_BRIDGE__)
57#include <android/apexsupport.h>
58#include <vndksupport/linker.h>
59#endif
60
Steven Morelanda4853cd2019-07-12 15:44:37 -070061#include "Static.h"
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070062#include "Utils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064namespace android {
65
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -070066using namespace std::chrono_literals;
67
Jayant Chowdhary30700942022-01-31 14:12:40 -080068using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
69
Steven Moreland80e1e6d2019-06-21 12:35:59 -070070using AidlServiceManager = android::os::IServiceManager;
71using android::binder::Status;
Alice Wang8578f132024-05-03 09:01:56 +000072using android::os::IAccessor;
73using android::os::Service;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070074
Steven Moreland635a2912019-10-02 15:50:10 -070075// libbinder's IServiceManager.h can't rely on the values generated by AIDL
76// because many places use its headers via include_dirs (meaning, without
77// declaring the dependency in the build system). So, for now, we can just check
78// the values here.
79static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
80static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
81static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
82static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
83static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
84static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
85
Steven Moreland583685e2019-10-02 16:45:11 -070086const String16& IServiceManager::getInterfaceDescriptor() const {
87 return AidlServiceManager::descriptor;
88}
89IServiceManager::IServiceManager() {}
90IServiceManager::~IServiceManager() {}
91
92// From the old libbinder IServiceManager interface to IServiceManager.
Parth Sanec7b58642024-08-07 10:31:15 +000093class CppBackendShim : public IServiceManager {
Steven Moreland583685e2019-10-02 16:45:11 -070094public:
Parth Sanec7b58642024-08-07 10:31:15 +000095 explicit CppBackendShim(const sp<BackendUnifiedServiceManager>& impl);
Steven Moreland583685e2019-10-02 16:45:11 -070096
97 sp<IBinder> getService(const String16& name) const override;
98 sp<IBinder> checkService(const String16& name) const override;
99 status_t addService(const String16& name, const sp<IBinder>& service,
100 bool allowIsolated, int dumpsysPriority) override;
101 Vector<String16> listServices(int dumpsysPriority) override;
102 sp<IBinder> waitForService(const String16& name16) override;
Steven Morelandb82b8f82019-10-28 10:52:34 -0700103 bool isDeclared(const String16& name) override;
Steven Moreland2e293aa2020-09-23 00:25:16 +0000104 Vector<String16> getDeclaredInstances(const String16& interface) override;
Steven Morelandedd4e072021-04-21 00:27:29 +0000105 std::optional<String16> updatableViaApex(const String16& name) override;
Jooyung Han76944fe2022-10-25 17:02:45 +0900106 Vector<String16> getUpdatableNames(const String16& apexName) override;
Devin Moore5e4c2f12021-09-09 22:36:33 +0000107 std::optional<IServiceManager::ConnectionInfo> getConnectionInfo(const String16& name) override;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800108 class RegistrationWaiter : public android::os::BnServiceCallback {
109 public:
110 explicit RegistrationWaiter(const sp<AidlRegistrationCallback>& callback)
111 : mImpl(callback) {}
112 Status onRegistration(const std::string& name, const sp<IBinder>& binder) override {
113 mImpl->onServiceRegistration(String16(name.c_str()), binder);
114 return Status::ok();
115 }
Steven Moreland583685e2019-10-02 16:45:11 -0700116
Jayant Chowdhary30700942022-01-31 14:12:40 -0800117 private:
118 sp<AidlRegistrationCallback> mImpl;
119 };
120
121 status_t registerForNotifications(const String16& service,
122 const sp<AidlRegistrationCallback>& cb) override;
123
124 status_t unregisterForNotifications(const String16& service,
125 const sp<AidlRegistrationCallback>& cb) override;
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000126
127 std::vector<IServiceManager::ServiceDebugInfo> getServiceDebugInfo() override;
Steven Moreland583685e2019-10-02 16:45:11 -0700128 // for legacy ABI
129 const String16& getInterfaceDescriptor() const override {
Parth Sane56a04712024-04-22 14:21:07 +0000130 return mUnifiedServiceManager->getInterfaceDescriptor();
Steven Moreland583685e2019-10-02 16:45:11 -0700131 }
Parth Sane56a04712024-04-22 14:21:07 +0000132 IBinder* onAsBinder() override { return IInterface::asBinder(mUnifiedServiceManager).get(); }
Yifan Hongf7760012021-06-04 16:04:42 -0700133
Parth Sanedc207542024-11-14 11:49:08 +0000134 void enableAddServiceCache(bool value) { mUnifiedServiceManager->enableAddServiceCache(value); }
135
Yifan Hongf7760012021-06-04 16:04:42 -0700136protected:
Parth Sane56a04712024-04-22 14:21:07 +0000137 sp<BackendUnifiedServiceManager> mUnifiedServiceManager;
Jayant Chowdhary30700942022-01-31 14:12:40 -0800138 // AidlRegistrationCallback -> services that its been registered for
139 // notifications.
140 using LocalRegistrationAndWaiter =
141 std::pair<sp<LocalRegistrationCallback>, sp<RegistrationWaiter>>;
142 using ServiceCallbackMap = std::map<std::string, std::vector<LocalRegistrationAndWaiter>>;
143 ServiceCallbackMap mNameToRegistrationCallback;
144 std::mutex mNameToRegistrationLock;
145
146 void removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
147 ServiceCallbackMap::iterator* it,
148 sp<RegistrationWaiter>* waiter);
Yifan Hongf7760012021-06-04 16:04:42 -0700149
150 // Directly get the service in a way that, for lazy services, requests the service to be started
Parth Sanec7b58642024-08-07 10:31:15 +0000151 // if it is not currently started. This way, calls directly to CppBackendShim::getService
Yifan Hongf7760012021-06-04 16:04:42 -0700152 // will still have the 5s delay that is expected by a large amount of Android code.
153 //
Parth Sanec7b58642024-08-07 10:31:15 +0000154 // When implementing CppBackendShim, use realGetService instead of
155 // mUnifiedServiceManager->getService so that it can be overridden in CppServiceManagerHostShim.
Yifan Hongf7760012021-06-04 16:04:42 -0700156 virtual Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) {
Alice Wang8578f132024-05-03 09:01:56 +0000157 Service service;
Alice Wang11da1502024-07-25 12:03:22 +0000158 Status status = mUnifiedServiceManager->getService2(name, &service);
Parth Sane5e1b7e12024-11-29 10:40:41 +0000159 auto serviceWithMetadata = service.get<Service::Tag::serviceWithMetadata>();
160 *_aidl_return = serviceWithMetadata.service;
Alice Wang8578f132024-05-03 09:01:56 +0000161 return status;
Yifan Hongf7760012021-06-04 16:04:42 -0700162 }
Steven Moreland583685e2019-10-02 16:45:11 -0700163};
164
Devin Moore18f63752024-08-08 21:01:24 +0000165class AccessorProvider {
166public:
Devin Moorec370db42024-08-09 23:18:05 +0000167 AccessorProvider(std::set<std::string>&& instances, RpcAccessorProvider&& provider)
168 : mInstances(std::move(instances)), mProvider(std::move(provider)) {}
169 sp<IBinder> provide(const String16& name) {
170 if (mInstances.count(String8(name).c_str()) > 0) {
171 return mProvider(name);
172 } else {
173 return nullptr;
174 }
175 }
176 const std::set<std::string>& instances() { return mInstances; }
Devin Moore18f63752024-08-08 21:01:24 +0000177
178private:
179 AccessorProvider() = delete;
180
Devin Moorec370db42024-08-09 23:18:05 +0000181 std::set<std::string> mInstances;
Devin Moore18f63752024-08-08 21:01:24 +0000182 RpcAccessorProvider mProvider;
183};
184
185class AccessorProviderEntry {
186public:
Devin Moore5c0b8352024-09-05 19:45:27 +0000187 AccessorProviderEntry(std::shared_ptr<AccessorProvider>&& provider)
188 : mProvider(std::move(provider)) {}
Devin Moore18f63752024-08-08 21:01:24 +0000189 std::shared_ptr<AccessorProvider> mProvider;
190
191private:
192 AccessorProviderEntry() = delete;
193};
194
Steven Moreland1698ffd2020-05-15 23:43:52 +0000195[[clang::no_destroy]] static std::once_flag gSmOnce;
196[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Devin Moore18f63752024-08-08 21:01:24 +0000197[[clang::no_destroy]] static std::mutex gAccessorProvidersMutex;
198[[clang::no_destroy]] static std::vector<AccessorProviderEntry> gAccessorProviders;
199
200class LocalAccessor : public android::os::BnAccessor {
201public:
202 LocalAccessor(const String16& instance, RpcSocketAddressProvider&& connectionInfoProvider)
Devin Moore5c0b8352024-09-05 19:45:27 +0000203 : mInstance(instance), mConnectionInfoProvider(std::move(connectionInfoProvider)) {
Devin Moore18f63752024-08-08 21:01:24 +0000204 LOG_ALWAYS_FATAL_IF(!mConnectionInfoProvider,
205 "LocalAccessor object needs a valid connection info provider");
206 }
207
208 ~LocalAccessor() {
209 if (mOnDelete) mOnDelete();
210 }
211
212 ::android::binder::Status addConnection(::android::os::ParcelFileDescriptor* outFd) {
213 using android::os::IAccessor;
214 sockaddr_storage addrStorage;
215 std::unique_ptr<FdTrigger> trigger = FdTrigger::make();
216 RpcTransportFd fd;
217 status_t status =
218 mConnectionInfoProvider(mInstance, reinterpret_cast<sockaddr*>(&addrStorage),
219 sizeof(addrStorage));
220 if (status != OK) {
221 const std::string error = "The connection info provider was unable to provide "
222 "connection info for instance " +
223 std::string(String8(mInstance).c_str()) +
224 " with status: " + statusToString(status);
225 ALOGE("%s", error.c_str());
226 return Status::fromServiceSpecificError(IAccessor::ERROR_CONNECTION_INFO_NOT_FOUND,
227 error.c_str());
228 }
229 if (addrStorage.ss_family == AF_VSOCK) {
230 sockaddr_vm* addr = reinterpret_cast<sockaddr_vm*>(&addrStorage);
231 status = singleSocketConnection(VsockSocketAddress(addr->svm_cid, addr->svm_port),
232 trigger, &fd);
233 } else if (addrStorage.ss_family == AF_UNIX) {
234 sockaddr_un* addr = reinterpret_cast<sockaddr_un*>(&addrStorage);
235 status = singleSocketConnection(UnixSocketAddress(addr->sun_path), trigger, &fd);
236 } else if (addrStorage.ss_family == AF_INET) {
237 sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(&addrStorage);
238 status = singleSocketConnection(InetSocketAddress(reinterpret_cast<sockaddr*>(addr),
239 sizeof(sockaddr_in),
240 inet_ntoa(addr->sin_addr),
241 ntohs(addr->sin_port)),
242 trigger, &fd);
243 } else {
244 const std::string error =
245 "Unsupported socket family type or the ConnectionInfoProvider failed to find a "
246 "valid address. Family type: " +
247 std::to_string(addrStorage.ss_family);
248 ALOGE("%s", error.c_str());
249 return Status::fromServiceSpecificError(IAccessor::ERROR_UNSUPPORTED_SOCKET_FAMILY,
250 error.c_str());
251 }
252 if (status != OK) {
253 const std::string error = "Failed to connect to socket for " +
254 std::string(String8(mInstance).c_str()) +
255 " with status: " + statusToString(status);
256 ALOGE("%s", error.c_str());
257 int err = 0;
258 if (status == -EACCES) {
259 err = IAccessor::ERROR_FAILED_TO_CONNECT_EACCES;
260 } else {
261 err = IAccessor::ERROR_FAILED_TO_CONNECT_TO_SOCKET;
262 }
263 return Status::fromServiceSpecificError(err, error.c_str());
264 }
265 *outFd = os::ParcelFileDescriptor(std::move(fd.fd));
266 return Status::ok();
267 }
268
269 ::android::binder::Status getInstanceName(String16* instance) {
270 *instance = mInstance;
271 return Status::ok();
272 }
273
274private:
275 LocalAccessor() = delete;
276 String16 mInstance;
277 RpcSocketAddressProvider mConnectionInfoProvider;
278 std::function<void()> mOnDelete;
279};
280
281android::binder::Status getInjectedAccessor(const std::string& name,
282 android::os::Service* service) {
283 std::vector<AccessorProviderEntry> copiedProviders;
284 {
285 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
286 copiedProviders.insert(copiedProviders.begin(), gAccessorProviders.begin(),
287 gAccessorProviders.end());
288 }
289
290 // Unlocked to call the providers. This requires the providers to be
291 // threadsafe and not contain any references to objects that could be
292 // deleted.
293 for (const auto& provider : copiedProviders) {
294 sp<IBinder> binder = provider.mProvider->provide(String16(name.c_str()));
295 if (binder == nullptr) continue;
296 status_t status = validateAccessor(String16(name.c_str()), binder);
297 if (status != OK) {
298 ALOGE("A provider returned a binder that is not an IAccessor for instance %s. Status: "
299 "%s",
300 name.c_str(), statusToString(status).c_str());
301 return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
302 }
303 *service = os::Service::make<os::Service::Tag::accessor>(binder);
304 return android::binder::Status::ok();
305 }
306
307 *service = os::Service::make<os::Service::Tag::accessor>(nullptr);
308 return android::binder::Status::ok();
309}
Brett Chabot38dbade2020-01-24 12:59:43 -0800310
Devin Moorea3867c72024-10-23 19:29:49 +0000311void appendInjectedAccessorServices(std::vector<std::string>* list) {
312 LOG_ALWAYS_FATAL_IF(list == nullptr,
313 "Attempted to get list of services from Accessors with nullptr");
314 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
315 for (const auto& entry : gAccessorProviders) {
316 list->insert(list->end(), entry.mProvider->instances().begin(),
317 entry.mProvider->instances().end());
318 }
319}
320
321void forEachInjectedAccessorService(const std::function<void(const std::string&)>& f) {
322 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
323 for (const auto& entry : gAccessorProviders) {
324 for (const auto& instance : entry.mProvider->instances()) {
325 f(instance);
326 }
327 }
328}
329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800330sp<IServiceManager> defaultServiceManager()
331{
Martijn Coenen402c8672020-02-03 10:01:36 +0100332 std::call_once(gSmOnce, []() {
Parth Sanec7b58642024-08-07 10:31:15 +0000333 gDefaultServiceManager = sp<CppBackendShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100334 });
Daniel Eratc2832702015-10-13 15:29:32 -0600335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 return gDefaultServiceManager;
337}
338
Brett Chabot38dbade2020-01-24 12:59:43 -0800339void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100340 bool called = false;
341 std::call_once(gSmOnce, [&]() {
342 gDefaultServiceManager = sm;
343 called = true;
344 });
345
346 if (!called) {
347 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
348 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800349}
350
Parth Saneb6ed0eb2024-06-25 14:38:42 +0000351sp<IServiceManager> getServiceManagerShimFromAidlServiceManagerForTests(
352 const sp<AidlServiceManager>& sm) {
353 return sp<CppBackendShim>::make(sp<BackendUnifiedServiceManager>::make(sm));
354}
355
Devin Moorec370db42024-08-09 23:18:05 +0000356// gAccessorProvidersMutex must be locked already
357static bool isInstanceProvidedLocked(const std::string& instance) {
358 return gAccessorProviders.end() !=
359 std::find_if(gAccessorProviders.begin(), gAccessorProviders.end(),
360 [&instance](const AccessorProviderEntry& entry) {
361 return entry.mProvider->instances().count(instance) > 0;
362 });
363}
364
365std::weak_ptr<AccessorProvider> addAccessorProvider(std::set<std::string>&& instances,
366 RpcAccessorProvider&& providerCallback) {
367 if (instances.empty()) {
368 ALOGE("Set of instances is empty! Need a non empty set of instances to provide for.");
369 return std::weak_ptr<AccessorProvider>();
370 }
Devin Moore18f63752024-08-08 21:01:24 +0000371 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
Devin Moorec370db42024-08-09 23:18:05 +0000372 for (const auto& instance : instances) {
373 if (isInstanceProvidedLocked(instance)) {
374 ALOGE("The instance %s is already provided for by a previously added "
375 "RpcAccessorProvider.",
376 instance.c_str());
377 return std::weak_ptr<AccessorProvider>();
378 }
379 }
Devin Moore18f63752024-08-08 21:01:24 +0000380 std::shared_ptr<AccessorProvider> provider =
Devin Moorec370db42024-08-09 23:18:05 +0000381 std::make_shared<AccessorProvider>(std::move(instances), std::move(providerCallback));
Devin Moore5c0b8352024-09-05 19:45:27 +0000382 std::weak_ptr<AccessorProvider> receipt = provider;
Devin Moore18f63752024-08-08 21:01:24 +0000383 gAccessorProviders.push_back(AccessorProviderEntry(std::move(provider)));
384
Devin Moore5c0b8352024-09-05 19:45:27 +0000385 return receipt;
Devin Moore18f63752024-08-08 21:01:24 +0000386}
387
388status_t removeAccessorProvider(std::weak_ptr<AccessorProvider> wProvider) {
389 std::shared_ptr<AccessorProvider> provider = wProvider.lock();
390 if (provider == nullptr) {
Devin Moorec370db42024-08-09 23:18:05 +0000391 ALOGE("The provider supplied to removeAccessorProvider has already been removed or the "
392 "argument to this function was nullptr.");
393 return BAD_VALUE;
Devin Moore18f63752024-08-08 21:01:24 +0000394 }
395 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
396 size_t sizeBefore = gAccessorProviders.size();
397 gAccessorProviders.erase(std::remove_if(gAccessorProviders.begin(), gAccessorProviders.end(),
398 [&](AccessorProviderEntry entry) {
399 return entry.mProvider == provider;
400 }),
401 gAccessorProviders.end());
402 if (sizeBefore == gAccessorProviders.size()) {
403 ALOGE("Failed to find an AccessorProvider for removeAccessorProvider");
404 return NAME_NOT_FOUND;
405 }
406
407 return OK;
408}
409
410status_t validateAccessor(const String16& instance, const sp<IBinder>& binder) {
411 if (binder == nullptr) {
412 ALOGE("Binder is null");
413 return BAD_VALUE;
414 }
Devin Moore0555fbf2024-08-29 15:51:50 +0000415 sp<IAccessor> accessor = checked_interface_cast<IAccessor>(binder);
Devin Moore18f63752024-08-08 21:01:24 +0000416 if (accessor == nullptr) {
417 ALOGE("This binder for %s is not an IAccessor binder", String8(instance).c_str());
418 return BAD_TYPE;
419 }
420 String16 reportedInstance;
421 Status status = accessor->getInstanceName(&reportedInstance);
422 if (!status.isOk()) {
423 ALOGE("Failed to validate the binder being used to create a new ARpc_Accessor for %s with "
424 "status: %s",
425 String8(instance).c_str(), status.toString8().c_str());
426 return NAME_NOT_FOUND;
427 }
428 if (reportedInstance != instance) {
429 ALOGE("Instance %s doesn't match the Accessor's instance of %s", String8(instance).c_str(),
430 String8(reportedInstance).c_str());
431 return NAME_NOT_FOUND;
432 }
433 return OK;
434}
435
436sp<IBinder> createAccessor(const String16& instance,
437 RpcSocketAddressProvider&& connectionInfoProvider) {
438 // Try to create a new accessor
439 if (!connectionInfoProvider) {
440 ALOGE("Could not find an Accessor for %s and no ConnectionInfoProvider provided to "
441 "create a new one",
442 String8(instance).c_str());
443 return nullptr;
444 }
445 sp<IBinder> binder = sp<LocalAccessor>::make(instance, std::move(connectionInfoProvider));
446 return binder;
447}
448
Devin Moore0555fbf2024-08-29 15:51:50 +0000449status_t delegateAccessor(const String16& name, const sp<IBinder>& accessor,
450 sp<IBinder>* delegator) {
451 LOG_ALWAYS_FATAL_IF(delegator == nullptr, "delegateAccessor called with a null out param");
452 if (accessor == nullptr) {
453 ALOGW("Accessor argument to delegateAccessor is null.");
454 *delegator = nullptr;
455 return OK;
456 }
457 status_t status = validateAccessor(name, accessor);
458 if (status != OK) {
459 ALOGE("The provided accessor binder is not an IAccessor for instance %s. Status: "
460 "%s",
461 String8(name).c_str(), statusToString(status).c_str());
462 return status;
463 }
464 // validateAccessor already called checked_interface_cast and made sure this
465 // is a valid accessor object.
466 *delegator = sp<android::os::IAccessorDelegator>::make(interface_cast<IAccessor>(accessor));
467
468 return OK;
469}
470
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400471#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900472// IPermissionController is not accessible to vendors
473
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800474bool checkCallingPermission(const String16& permission)
475{
Yi Kongfdd8da92018-06-07 17:52:27 -0700476 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477}
478
Steven Moreland1b264072021-06-03 23:04:02 +0000479static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700480
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800481bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
482{
483 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700484 pid_t pid = ipcState->getCallingPid();
485 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800486 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700487 if (outUid) *outUid = uid;
488 return checkPermission(permission, pid, uid);
489}
490
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000491bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700492 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700493 static sp<IPermissionController> gPermissionController;
494
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800495 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700496 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800497 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700498 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600499
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700500 auto startTime = std::chrono::steady_clock::now().min();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501
502 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700503 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800504 bool res = pc->checkPermission(permission, pid, uid);
505 if (res) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700506 if (startTime != startTime.min()) {
507 const auto waitTime = std::chrono::steady_clock::now() - startTime;
508 ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
509 to_ms(waitTime), String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800510 }
511 return res;
512 }
Daniel Eratc2832702015-10-13 15:29:32 -0600513
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800514 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800515 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000516 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000517 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000518 uid, pid);
519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520 return false;
521 }
Daniel Eratc2832702015-10-13 15:29:32 -0600522
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700524 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700526 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700528 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529 }
Daniel Eratc2832702015-10-13 15:29:32 -0600530
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531 // Need to retrieve the permission controller.
532 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700533 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 // Wait for the permission controller to come back...
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700535 if (startTime == startTime.min()) {
536 startTime = std::chrono::steady_clock::now();
Steve Blocka19954a2012-01-04 20:05:49 +0000537 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000538 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800539 }
540 sleep(1);
541 } else {
542 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600543 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700544 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700546 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547 }
548 }
549}
550
Steven Moreland576662a2024-08-09 23:12:03 +0000551#endif //__ANDROID_VNDK__
552
Jooyung Han75fc06f2024-02-03 03:56:59 +0900553void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
Steven Moreland576662a2024-08-09 23:12:03 +0000554#if defined(__ANDROID__) && !defined(__ANDROID_VENDOR__) && !defined(__ANDROID_RECOVERY__) && \
555 !defined(__ANDROID_NATIVE_BRIDGE__)
Jooyung Han75fc06f2024-02-03 03:56:59 +0900556 sp<IServiceManager> sm = defaultServiceManager();
557 String16 name = interface + String16("/") + instance;
558 if (!sm->isDeclared(name)) {
559 return nullptr;
560 }
561 String16 libraryName = interface + String16(".") + instance + String16(".so");
562 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
563 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
564 String8(*updatableViaApex).c_str(), flag);
565 }
566 return android_load_sphal_library(String8(libraryName).c_str(), flag);
567#else
568 (void)interface;
569 (void)instance;
570 (void)flag;
571 return nullptr;
572#endif
573}
574
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800575// ----------------------------------------------------------------------
576
Parth Sanec7b58642024-08-07 10:31:15 +0000577CppBackendShim::CppBackendShim(const sp<BackendUnifiedServiceManager>& impl)
Parth Sane43e3b8b2024-08-05 13:39:04 +0000578 : mUnifiedServiceManager(impl) {}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700579
Steven Moreland5af7d852020-04-29 15:40:29 -0700580// This implementation could be simplified and made more efficient by delegating
581// to waitForService. However, this changes the threading structure in some
582// cases and could potentially break prebuilts. Once we have higher logistical
583// complexity, this could be attempted.
Parth Sanec7b58642024-08-07 10:31:15 +0000584sp<IBinder> CppBackendShim::getService(const String16& name) const {
Steven Moreland583685e2019-10-02 16:45:11 -0700585 static bool gSystemBootCompleted = false;
586
587 sp<IBinder> svc = checkService(name);
588 if (svc != nullptr) return svc;
589
Devin Moore74bc5892024-10-23 17:12:19 +0000590 sp<ProcessState> self = ProcessState::selfOrNull();
Steven Moreland583685e2019-10-02 16:45:11 -0700591 const bool isVendorService =
Devin Moore74bc5892024-10-23 17:12:19 +0000592 self && strcmp(self->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700593 constexpr auto timeout = 5s;
594 const auto startTime = std::chrono::steady_clock::now();
Steven Moreland583685e2019-10-02 16:45:11 -0700595 // Vendor code can't access system properties
596 if (!gSystemBootCompleted && !isVendorService) {
597#ifdef __ANDROID__
598 char bootCompleted[PROPERTY_VALUE_MAX];
599 property_get("sys.boot_completed", bootCompleted, "0");
600 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
601#else
602 gSystemBootCompleted = true;
603#endif
604 }
605 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900606 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700607
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000608 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Devin Moore74bc5892024-10-23 17:12:19 +0000609 self ? self->getDriverName().c_str() : "RPC accessors only");
Tom Cherry8fda97f2020-07-22 17:15:44 -0700610
Steven Moreland583685e2019-10-02 16:45:11 -0700611 int n = 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700612 while (std::chrono::steady_clock::now() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700613 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700614 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700615
Yunfan Chen788e1c42018-03-29 16:52:09 +0900616 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700617 if (svc != nullptr) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700618 const auto waitTime = std::chrono::steady_clock::now() - startTime;
619 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000620 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700621 to_ms(waitTime));
Tom Cherry8fda97f2020-07-22 17:15:44 -0700622 return svc;
623 }
Steven Moreland583685e2019-10-02 16:45:11 -0700624 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000625 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700626 return nullptr;
627}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900628
Parth Sanec7b58642024-08-07 10:31:15 +0000629sp<IBinder> CppBackendShim::checkService(const String16& name) const {
Alice Wang8578f132024-05-03 09:01:56 +0000630 Service ret;
Alice Wang2b613442025-01-02 11:53:05 +0000631 if (!mUnifiedServiceManager->checkService2(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700632 return nullptr;
633 }
Parth Sane5e1b7e12024-11-29 10:40:41 +0000634 return ret.get<Service::Tag::serviceWithMetadata>().service;
Steven Moreland583685e2019-10-02 16:45:11 -0700635}
636
Parth Sanec7b58642024-08-07 10:31:15 +0000637status_t CppBackendShim::addService(const String16& name, const sp<IBinder>& service,
638 bool allowIsolated, int dumpsysPriority) {
Parth Sane56a04712024-04-22 14:21:07 +0000639 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
640 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700641 return status.exceptionCode();
642}
643
Parth Sanec7b58642024-08-07 10:31:15 +0000644Vector<String16> CppBackendShim::listServices(int dumpsysPriority) {
Steven Moreland583685e2019-10-02 16:45:11 -0700645 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000646 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700647 return {};
648 }
649
650 Vector<String16> res;
651 res.setCapacity(ret.size());
652 for (const std::string& name : ret) {
653 res.push(String16(name.c_str()));
654 }
655 return res;
656}
657
Parth Sanec7b58642024-08-07 10:31:15 +0000658sp<IBinder> CppBackendShim::waitForService(const String16& name16) {
Steven Moreland583685e2019-10-02 16:45:11 -0700659 class Waiter : public android::os::BnServiceCallback {
660 Status onRegistration(const std::string& /*name*/,
661 const sp<IBinder>& binder) override {
662 std::unique_lock<std::mutex> lock(mMutex);
663 mBinder = binder;
664 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700665 // Flushing here helps ensure the service's ref count remains accurate
666 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700667 mCv.notify_one();
668 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900669 }
Steven Moreland583685e2019-10-02 16:45:11 -0700670 public:
671 sp<IBinder> mBinder;
672 std::mutex mMutex;
673 std::condition_variable mCv;
674 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900675
Jon Spivackfed6db42019-11-18 16:43:59 -0800676 // Simple RAII object to ensure a function call immediately before going out of scope
677 class Defer {
678 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900679 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800680 ~Defer() { mF(); }
681 private:
682 std::function<void()> mF;
683 };
684
Steven Moreland583685e2019-10-02 16:45:11 -0700685 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900686
Steven Moreland583685e2019-10-02 16:45:11 -0700687 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700688 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000689 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
690 status.toString8().c_str());
Devin Moore74bc5892024-10-23 17:12:19 +0000691 sp<ProcessState> self = ProcessState::selfOrNull();
692 if (self && 0 == self->getThreadPoolMaxTotalThreadCount()) {
Elie Kheirallah27c26952022-09-07 21:45:26 +0000693 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
694 "Threadpool has 0 guaranteed threads. "
695 "Is the threadpool configured properly? "
696 "See ProcessState::startThreadPool and "
697 "ProcessState::setThreadPoolMaxThreadCount.");
698 }
Steven Moreland583685e2019-10-02 16:45:11 -0700699 return nullptr;
700 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800701 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700702
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000703 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000704 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000705 !status.isOk()) {
706 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
707 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700708 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800709 }
Parth Sane56a04712024-04-22 14:21:07 +0000710 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700711
Steven Moreland583685e2019-10-02 16:45:11 -0700712 while(true) {
713 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000714 // It would be really nice if we could read binder commands on this
715 // thread instead of needing a threadpool to be started, but for
716 // instance, if we call getAndExecuteCommand, it might be the case
717 // that another thread serves the callback, and we never get a
718 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700719 std::unique_lock<std::mutex> lock(waiter->mMutex);
Steven Moreland3d37ef22023-04-25 18:25:14 +0000720 waiter->mCv.wait_for(lock, 1s, [&] {
721 return waiter->mBinder != nullptr;
722 });
Steven Moreland583685e2019-10-02 16:45:11 -0700723 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700724 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800725
Devin Moore74bc5892024-10-23 17:12:19 +0000726 sp<ProcessState> self = ProcessState::selfOrNull();
Steven Moreland3d37ef22023-04-25 18:25:14 +0000727 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000728 "threadpool: %zu. Are binder threads started and available?)",
Devin Moore74bc5892024-10-23 17:12:19 +0000729 name.c_str(), self ? self->getThreadPoolMaxTotalThreadCount() : 0);
Steven Morelandf2677e22020-07-14 19:58:08 +0000730
Steven Moreland583685e2019-10-02 16:45:11 -0700731 // Handle race condition for lazy services. Here is what can happen:
732 // - the service dies (not processed by init yet).
733 // - sm processes death notification.
734 // - sm gets getService and calls init to start service.
735 // - init gets the start signal, but the service already appears
736 // started, so it does nothing.
737 // - init gets death signal, but doesn't know it needs to restart
738 // the service
739 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700740 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000741 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
742 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700743 return nullptr;
744 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800745 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700746 }
Steven Moreland583685e2019-10-02 16:45:11 -0700747}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800748
Parth Sanec7b58642024-08-07 10:31:15 +0000749bool CppBackendShim::isDeclared(const String16& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700750 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000751 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000752 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000753 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000754 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700755 return false;
756 }
757 return declared;
758}
759
Parth Sanec7b58642024-08-07 10:31:15 +0000760Vector<String16> CppBackendShim::getDeclaredInstances(const String16& interface) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000761 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000762 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000763 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000764 !status.isOk()) {
765 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
766 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000767 return {};
768 }
769
770 Vector<String16> res;
771 res.setCapacity(out.size());
772 for (const std::string& instance : out) {
773 res.push(String16(instance.c_str()));
774 }
775 return res;
776}
777
Parth Sanec7b58642024-08-07 10:31:15 +0000778std::optional<String16> CppBackendShim::updatableViaApex(const String16& name) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000779 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000780 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000781 !status.isOk()) {
782 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
783 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000784 return std::nullopt;
785 }
786 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
787}
788
Parth Sanec7b58642024-08-07 10:31:15 +0000789Vector<String16> CppBackendShim::getUpdatableNames(const String16& apexName) {
Jooyung Han76944fe2022-10-25 17:02:45 +0900790 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000791 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900792 !status.isOk()) {
793 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
794 status.toString8().c_str());
795 return {};
796 }
797
798 Vector<String16> res;
799 res.setCapacity(out.size());
800 for (const std::string& instance : out) {
801 res.push(String16(instance.c_str()));
802 }
803 return res;
804}
805
Parth Sanec7b58642024-08-07 10:31:15 +0000806std::optional<IServiceManager::ConnectionInfo> CppBackendShim::getConnectionInfo(
Devin Moore5e4c2f12021-09-09 22:36:33 +0000807 const String16& name) {
808 std::optional<os::ConnectionInfo> connectionInfo;
809 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000810 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000811 !status.isOk()) {
812 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
813 status.toString8().c_str());
814 }
815 return connectionInfo.has_value()
816 ? std::make_optional<IServiceManager::ConnectionInfo>(
817 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
818 : std::nullopt;
819}
820
Parth Sanec7b58642024-08-07 10:31:15 +0000821status_t CppBackendShim::registerForNotifications(const String16& name,
822 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800823 if (cb == nullptr) {
824 ALOGE("%s: null cb passed", __FUNCTION__);
825 return BAD_VALUE;
826 }
827 std::string nameStr = String8(name).c_str();
828 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
829 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
830 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000831 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800832 !status.isOk()) {
833 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
834 status.toString8().c_str());
835 return UNKNOWN_ERROR;
836 }
837 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
838 return OK;
839}
840
Parth Sanec7b58642024-08-07 10:31:15 +0000841void CppBackendShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
842 ServiceCallbackMap::iterator* it,
843 sp<RegistrationWaiter>* waiter) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800844 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
845 for (auto lit = localRegistrationAndWaiters.begin();
846 lit != localRegistrationAndWaiters.end();) {
847 if (lit->first == cb) {
848 if (waiter) {
849 *waiter = lit->second;
850 }
851 lit = localRegistrationAndWaiters.erase(lit);
852 } else {
853 ++lit;
854 }
855 }
856
857 if (localRegistrationAndWaiters.empty()) {
858 mNameToRegistrationCallback.erase(*it);
859 }
860}
861
Parth Sanec7b58642024-08-07 10:31:15 +0000862status_t CppBackendShim::unregisterForNotifications(const String16& name,
863 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800864 if (cb == nullptr) {
865 ALOGE("%s: null cb passed", __FUNCTION__);
866 return BAD_VALUE;
867 }
868 std::string nameStr = String8(name).c_str();
869 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
870 auto it = mNameToRegistrationCallback.find(nameStr);
871 sp<RegistrationWaiter> registrationWaiter;
872 if (it != mNameToRegistrationCallback.end()) {
873 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
874 } else {
875 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
876 return BAD_VALUE;
877 }
878 if (registrationWaiter == nullptr) {
879 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
880 return BAD_VALUE;
881 }
Parth Sane56a04712024-04-22 14:21:07 +0000882 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800883 registrationWaiter);
884 !status.isOk()) {
885 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
886 String8(name).c_str(), status.toString8().c_str());
887 return UNKNOWN_ERROR;
888 }
889 return OK;
890}
891
Parth Sanec7b58642024-08-07 10:31:15 +0000892std::vector<IServiceManager::ServiceDebugInfo> CppBackendShim::getServiceDebugInfo() {
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000893 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
894 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000895 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000896 !status.isOk()) {
897 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
898 return ret;
899 }
900 for (const auto& serviceDebugInfo : serviceDebugInfos) {
901 IServiceManager::ServiceDebugInfo retInfo;
902 retInfo.pid = serviceDebugInfo.debugPid;
903 retInfo.name = serviceDebugInfo.name;
904 ret.emplace_back(retInfo);
905 }
906 return ret;
907}
908
Kevin Lindkviste8e12432022-11-23 13:23:42 +0100909#if defined(BINDER_SERVICEMANAGEMENT_DELEGATION_SUPPORT)
Parth Sanec7b58642024-08-07 10:31:15 +0000910// CppBackendShim for host. Implements the old libbinder android::IServiceManager API.
Yifan Hongf7760012021-06-04 16:04:42 -0700911// The internal implementation of the AIDL interface android::os::IServiceManager calls into
912// on-device service manager.
Parth Sanec7b58642024-08-07 10:31:15 +0000913class CppServiceManagerHostShim : public CppBackendShim {
Yifan Hongf7760012021-06-04 16:04:42 -0700914public:
Parth Sanec7b58642024-08-07 10:31:15 +0000915 CppServiceManagerHostShim(const sp<AidlServiceManager>& impl,
916 const RpcDelegateServiceManagerOptions& options)
917 : CppBackendShim(sp<BackendUnifiedServiceManager>::make(impl)), mOptions(options) {}
918 // CppBackendShim::getService is based on checkService, so no need to override it.
Yifan Hongf7760012021-06-04 16:04:42 -0700919 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700920 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700921 }
922
923protected:
Parth Sanec7b58642024-08-07 10:31:15 +0000924 // Override realGetService for CppBackendShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700925 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700926 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700927 return Status::ok();
928 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700929
930private:
931 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700932};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700933sp<IServiceManager> createRpcDelegateServiceManager(
934 const RpcDelegateServiceManagerOptions& options) {
935 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700936 if (binder == nullptr) {
937 ALOGE("getDeviceService(\"manager\") returns null");
938 return nullptr;
939 }
940 auto interface = AidlServiceManager::asInterface(binder);
941 if (interface == nullptr) {
942 ALOGE("getDeviceService(\"manager\") returns non service manager");
943 return nullptr;
944 }
Parth Sanec7b58642024-08-07 10:31:15 +0000945 return sp<CppServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700946}
947#endif
948
Steven Moreland61ff8492019-09-26 16:05:45 -0700949} // namespace android