blob: 5c72ed3197003268ce98d23ea8db32ee6454905c [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);
Parth Sane5e1b7e12024-11-29 10:40:41 +0000155 auto serviceWithMetadata = service.get<Service::Tag::serviceWithMetadata>();
156 *_aidl_return = serviceWithMetadata.service;
Alice Wang8578f132024-05-03 09:01:56 +0000157 return status;
Yifan Hongf7760012021-06-04 16:04:42 -0700158 }
Steven Moreland583685e2019-10-02 16:45:11 -0700159};
160
Devin Moore18f63752024-08-08 21:01:24 +0000161class AccessorProvider {
162public:
Devin Moorec370db42024-08-09 23:18:05 +0000163 AccessorProvider(std::set<std::string>&& instances, RpcAccessorProvider&& provider)
164 : mInstances(std::move(instances)), mProvider(std::move(provider)) {}
165 sp<IBinder> provide(const String16& name) {
166 if (mInstances.count(String8(name).c_str()) > 0) {
167 return mProvider(name);
168 } else {
169 return nullptr;
170 }
171 }
172 const std::set<std::string>& instances() { return mInstances; }
Devin Moore18f63752024-08-08 21:01:24 +0000173
174private:
175 AccessorProvider() = delete;
176
Devin Moorec370db42024-08-09 23:18:05 +0000177 std::set<std::string> mInstances;
Devin Moore18f63752024-08-08 21:01:24 +0000178 RpcAccessorProvider mProvider;
179};
180
181class AccessorProviderEntry {
182public:
Devin Moore5c0b8352024-09-05 19:45:27 +0000183 AccessorProviderEntry(std::shared_ptr<AccessorProvider>&& provider)
184 : mProvider(std::move(provider)) {}
Devin Moore18f63752024-08-08 21:01:24 +0000185 std::shared_ptr<AccessorProvider> mProvider;
186
187private:
188 AccessorProviderEntry() = delete;
189};
190
Steven Moreland1698ffd2020-05-15 23:43:52 +0000191[[clang::no_destroy]] static std::once_flag gSmOnce;
192[[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
Devin Moore18f63752024-08-08 21:01:24 +0000193[[clang::no_destroy]] static std::mutex gAccessorProvidersMutex;
194[[clang::no_destroy]] static std::vector<AccessorProviderEntry> gAccessorProviders;
195
196class LocalAccessor : public android::os::BnAccessor {
197public:
198 LocalAccessor(const String16& instance, RpcSocketAddressProvider&& connectionInfoProvider)
Devin Moore5c0b8352024-09-05 19:45:27 +0000199 : mInstance(instance), mConnectionInfoProvider(std::move(connectionInfoProvider)) {
Devin Moore18f63752024-08-08 21:01:24 +0000200 LOG_ALWAYS_FATAL_IF(!mConnectionInfoProvider,
201 "LocalAccessor object needs a valid connection info provider");
202 }
203
204 ~LocalAccessor() {
205 if (mOnDelete) mOnDelete();
206 }
207
208 ::android::binder::Status addConnection(::android::os::ParcelFileDescriptor* outFd) {
209 using android::os::IAccessor;
210 sockaddr_storage addrStorage;
211 std::unique_ptr<FdTrigger> trigger = FdTrigger::make();
212 RpcTransportFd fd;
213 status_t status =
214 mConnectionInfoProvider(mInstance, reinterpret_cast<sockaddr*>(&addrStorage),
215 sizeof(addrStorage));
216 if (status != OK) {
217 const std::string error = "The connection info provider was unable to provide "
218 "connection info for instance " +
219 std::string(String8(mInstance).c_str()) +
220 " with status: " + statusToString(status);
221 ALOGE("%s", error.c_str());
222 return Status::fromServiceSpecificError(IAccessor::ERROR_CONNECTION_INFO_NOT_FOUND,
223 error.c_str());
224 }
225 if (addrStorage.ss_family == AF_VSOCK) {
226 sockaddr_vm* addr = reinterpret_cast<sockaddr_vm*>(&addrStorage);
227 status = singleSocketConnection(VsockSocketAddress(addr->svm_cid, addr->svm_port),
228 trigger, &fd);
229 } else if (addrStorage.ss_family == AF_UNIX) {
230 sockaddr_un* addr = reinterpret_cast<sockaddr_un*>(&addrStorage);
231 status = singleSocketConnection(UnixSocketAddress(addr->sun_path), trigger, &fd);
232 } else if (addrStorage.ss_family == AF_INET) {
233 sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(&addrStorage);
234 status = singleSocketConnection(InetSocketAddress(reinterpret_cast<sockaddr*>(addr),
235 sizeof(sockaddr_in),
236 inet_ntoa(addr->sin_addr),
237 ntohs(addr->sin_port)),
238 trigger, &fd);
239 } else {
240 const std::string error =
241 "Unsupported socket family type or the ConnectionInfoProvider failed to find a "
242 "valid address. Family type: " +
243 std::to_string(addrStorage.ss_family);
244 ALOGE("%s", error.c_str());
245 return Status::fromServiceSpecificError(IAccessor::ERROR_UNSUPPORTED_SOCKET_FAMILY,
246 error.c_str());
247 }
248 if (status != OK) {
249 const std::string error = "Failed to connect to socket for " +
250 std::string(String8(mInstance).c_str()) +
251 " with status: " + statusToString(status);
252 ALOGE("%s", error.c_str());
253 int err = 0;
254 if (status == -EACCES) {
255 err = IAccessor::ERROR_FAILED_TO_CONNECT_EACCES;
256 } else {
257 err = IAccessor::ERROR_FAILED_TO_CONNECT_TO_SOCKET;
258 }
259 return Status::fromServiceSpecificError(err, error.c_str());
260 }
261 *outFd = os::ParcelFileDescriptor(std::move(fd.fd));
262 return Status::ok();
263 }
264
265 ::android::binder::Status getInstanceName(String16* instance) {
266 *instance = mInstance;
267 return Status::ok();
268 }
269
270private:
271 LocalAccessor() = delete;
272 String16 mInstance;
273 RpcSocketAddressProvider mConnectionInfoProvider;
274 std::function<void()> mOnDelete;
275};
276
277android::binder::Status getInjectedAccessor(const std::string& name,
278 android::os::Service* service) {
279 std::vector<AccessorProviderEntry> copiedProviders;
280 {
281 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
282 copiedProviders.insert(copiedProviders.begin(), gAccessorProviders.begin(),
283 gAccessorProviders.end());
284 }
285
286 // Unlocked to call the providers. This requires the providers to be
287 // threadsafe and not contain any references to objects that could be
288 // deleted.
289 for (const auto& provider : copiedProviders) {
290 sp<IBinder> binder = provider.mProvider->provide(String16(name.c_str()));
291 if (binder == nullptr) continue;
292 status_t status = validateAccessor(String16(name.c_str()), binder);
293 if (status != OK) {
294 ALOGE("A provider returned a binder that is not an IAccessor for instance %s. Status: "
295 "%s",
296 name.c_str(), statusToString(status).c_str());
297 return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
298 }
299 *service = os::Service::make<os::Service::Tag::accessor>(binder);
300 return android::binder::Status::ok();
301 }
302
303 *service = os::Service::make<os::Service::Tag::accessor>(nullptr);
304 return android::binder::Status::ok();
305}
Brett Chabot38dbade2020-01-24 12:59:43 -0800306
Devin Moorea3867c72024-10-23 19:29:49 +0000307void appendInjectedAccessorServices(std::vector<std::string>* list) {
308 LOG_ALWAYS_FATAL_IF(list == nullptr,
309 "Attempted to get list of services from Accessors with nullptr");
310 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
311 for (const auto& entry : gAccessorProviders) {
312 list->insert(list->end(), entry.mProvider->instances().begin(),
313 entry.mProvider->instances().end());
314 }
315}
316
317void forEachInjectedAccessorService(const std::function<void(const std::string&)>& f) {
318 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
319 for (const auto& entry : gAccessorProviders) {
320 for (const auto& instance : entry.mProvider->instances()) {
321 f(instance);
322 }
323 }
324}
325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326sp<IServiceManager> defaultServiceManager()
327{
Martijn Coenen402c8672020-02-03 10:01:36 +0100328 std::call_once(gSmOnce, []() {
Parth Sanec7b58642024-08-07 10:31:15 +0000329 gDefaultServiceManager = sp<CppBackendShim>::make(getBackendUnifiedServiceManager());
Martijn Coenen402c8672020-02-03 10:01:36 +0100330 });
Daniel Eratc2832702015-10-13 15:29:32 -0600331
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800332 return gDefaultServiceManager;
333}
334
Brett Chabot38dbade2020-01-24 12:59:43 -0800335void setDefaultServiceManager(const sp<IServiceManager>& sm) {
Martijn Coenen402c8672020-02-03 10:01:36 +0100336 bool called = false;
337 std::call_once(gSmOnce, [&]() {
338 gDefaultServiceManager = sm;
339 called = true;
340 });
341
342 if (!called) {
343 LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
344 }
Brett Chabot38dbade2020-01-24 12:59:43 -0800345}
346
Parth Saneb6ed0eb2024-06-25 14:38:42 +0000347sp<IServiceManager> getServiceManagerShimFromAidlServiceManagerForTests(
348 const sp<AidlServiceManager>& sm) {
349 return sp<CppBackendShim>::make(sp<BackendUnifiedServiceManager>::make(sm));
350}
351
Devin Moorec370db42024-08-09 23:18:05 +0000352// gAccessorProvidersMutex must be locked already
353static bool isInstanceProvidedLocked(const std::string& instance) {
354 return gAccessorProviders.end() !=
355 std::find_if(gAccessorProviders.begin(), gAccessorProviders.end(),
356 [&instance](const AccessorProviderEntry& entry) {
357 return entry.mProvider->instances().count(instance) > 0;
358 });
359}
360
361std::weak_ptr<AccessorProvider> addAccessorProvider(std::set<std::string>&& instances,
362 RpcAccessorProvider&& providerCallback) {
363 if (instances.empty()) {
364 ALOGE("Set of instances is empty! Need a non empty set of instances to provide for.");
365 return std::weak_ptr<AccessorProvider>();
366 }
Devin Moore18f63752024-08-08 21:01:24 +0000367 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
Devin Moorec370db42024-08-09 23:18:05 +0000368 for (const auto& instance : instances) {
369 if (isInstanceProvidedLocked(instance)) {
370 ALOGE("The instance %s is already provided for by a previously added "
371 "RpcAccessorProvider.",
372 instance.c_str());
373 return std::weak_ptr<AccessorProvider>();
374 }
375 }
Devin Moore18f63752024-08-08 21:01:24 +0000376 std::shared_ptr<AccessorProvider> provider =
Devin Moorec370db42024-08-09 23:18:05 +0000377 std::make_shared<AccessorProvider>(std::move(instances), std::move(providerCallback));
Devin Moore5c0b8352024-09-05 19:45:27 +0000378 std::weak_ptr<AccessorProvider> receipt = provider;
Devin Moore18f63752024-08-08 21:01:24 +0000379 gAccessorProviders.push_back(AccessorProviderEntry(std::move(provider)));
380
Devin Moore5c0b8352024-09-05 19:45:27 +0000381 return receipt;
Devin Moore18f63752024-08-08 21:01:24 +0000382}
383
384status_t removeAccessorProvider(std::weak_ptr<AccessorProvider> wProvider) {
385 std::shared_ptr<AccessorProvider> provider = wProvider.lock();
386 if (provider == nullptr) {
Devin Moorec370db42024-08-09 23:18:05 +0000387 ALOGE("The provider supplied to removeAccessorProvider has already been removed or the "
388 "argument to this function was nullptr.");
389 return BAD_VALUE;
Devin Moore18f63752024-08-08 21:01:24 +0000390 }
391 std::lock_guard<std::mutex> lock(gAccessorProvidersMutex);
392 size_t sizeBefore = gAccessorProviders.size();
393 gAccessorProviders.erase(std::remove_if(gAccessorProviders.begin(), gAccessorProviders.end(),
394 [&](AccessorProviderEntry entry) {
395 return entry.mProvider == provider;
396 }),
397 gAccessorProviders.end());
398 if (sizeBefore == gAccessorProviders.size()) {
399 ALOGE("Failed to find an AccessorProvider for removeAccessorProvider");
400 return NAME_NOT_FOUND;
401 }
402
403 return OK;
404}
405
406status_t validateAccessor(const String16& instance, const sp<IBinder>& binder) {
407 if (binder == nullptr) {
408 ALOGE("Binder is null");
409 return BAD_VALUE;
410 }
Devin Moore0555fbf2024-08-29 15:51:50 +0000411 sp<IAccessor> accessor = checked_interface_cast<IAccessor>(binder);
Devin Moore18f63752024-08-08 21:01:24 +0000412 if (accessor == nullptr) {
413 ALOGE("This binder for %s is not an IAccessor binder", String8(instance).c_str());
414 return BAD_TYPE;
415 }
416 String16 reportedInstance;
417 Status status = accessor->getInstanceName(&reportedInstance);
418 if (!status.isOk()) {
419 ALOGE("Failed to validate the binder being used to create a new ARpc_Accessor for %s with "
420 "status: %s",
421 String8(instance).c_str(), status.toString8().c_str());
422 return NAME_NOT_FOUND;
423 }
424 if (reportedInstance != instance) {
425 ALOGE("Instance %s doesn't match the Accessor's instance of %s", String8(instance).c_str(),
426 String8(reportedInstance).c_str());
427 return NAME_NOT_FOUND;
428 }
429 return OK;
430}
431
432sp<IBinder> createAccessor(const String16& instance,
433 RpcSocketAddressProvider&& connectionInfoProvider) {
434 // Try to create a new accessor
435 if (!connectionInfoProvider) {
436 ALOGE("Could not find an Accessor for %s and no ConnectionInfoProvider provided to "
437 "create a new one",
438 String8(instance).c_str());
439 return nullptr;
440 }
441 sp<IBinder> binder = sp<LocalAccessor>::make(instance, std::move(connectionInfoProvider));
442 return binder;
443}
444
Devin Moore0555fbf2024-08-29 15:51:50 +0000445status_t delegateAccessor(const String16& name, const sp<IBinder>& accessor,
446 sp<IBinder>* delegator) {
447 LOG_ALWAYS_FATAL_IF(delegator == nullptr, "delegateAccessor called with a null out param");
448 if (accessor == nullptr) {
449 ALOGW("Accessor argument to delegateAccessor is null.");
450 *delegator = nullptr;
451 return OK;
452 }
453 status_t status = validateAccessor(name, accessor);
454 if (status != OK) {
455 ALOGE("The provided accessor binder is not an IAccessor for instance %s. Status: "
456 "%s",
457 String8(name).c_str(), statusToString(status).c_str());
458 return status;
459 }
460 // validateAccessor already called checked_interface_cast and made sure this
461 // is a valid accessor object.
462 *delegator = sp<android::os::IAccessorDelegator>::make(interface_cast<IAccessor>(accessor));
463
464 return OK;
465}
466
Atneya Nair5b9cbbf2022-05-24 20:39:48 -0400467#if !defined(__ANDROID_VNDK__)
Jiyong Park47f876b2018-04-17 13:56:46 +0900468// IPermissionController is not accessible to vendors
469
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470bool checkCallingPermission(const String16& permission)
471{
Yi Kongfdd8da92018-06-07 17:52:27 -0700472 return checkCallingPermission(permission, nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800473}
474
Steven Moreland1b264072021-06-03 23:04:02 +0000475static StaticString16 _permission(u"permission");
Mathias Agopian375f5632009-06-15 18:24:59 -0700476
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
478{
479 IPCThreadState* ipcState = IPCThreadState::self();
Mathias Agopian375f5632009-06-15 18:24:59 -0700480 pid_t pid = ipcState->getCallingPid();
481 uid_t uid = ipcState->getCallingUid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800482 if (outPid) *outPid = pid;
Mathias Agopian375f5632009-06-15 18:24:59 -0700483 if (outUid) *outUid = uid;
484 return checkPermission(permission, pid, uid);
485}
486
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000487bool checkPermission(const String16& permission, pid_t pid, uid_t uid, bool logPermissionFailure) {
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700488 static std::mutex gPermissionControllerLock;
Steven Moreland92b17c62019-04-02 15:46:24 -0700489 static sp<IPermissionController> gPermissionController;
490
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800491 sp<IPermissionController> pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700492 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800493 pc = gPermissionController;
Steven Moreland92b17c62019-04-02 15:46:24 -0700494 gPermissionControllerLock.unlock();
Daniel Eratc2832702015-10-13 15:29:32 -0600495
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700496 auto startTime = std::chrono::steady_clock::now().min();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800497
498 while (true) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700499 if (pc != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800500 bool res = pc->checkPermission(permission, pid, uid);
501 if (res) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700502 if (startTime != startTime.min()) {
503 const auto waitTime = std::chrono::steady_clock::now() - startTime;
504 ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
505 to_ms(waitTime), String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 }
507 return res;
508 }
Daniel Eratc2832702015-10-13 15:29:32 -0600509
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800510 // Is this a permission failure, or did the controller go away?
Marco Nelissen097ca272014-11-14 08:01:01 -0800511 if (IInterface::asBinder(pc)->isBinderAlive()) {
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000512 if (logPermissionFailure) {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000513 ALOGW("Permission failure: %s from uid=%d pid=%d", String8(permission).c_str(),
Jayant Chowdhary49bc34b2021-07-28 20:27:21 +0000514 uid, pid);
515 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516 return false;
517 }
Daniel Eratc2832702015-10-13 15:29:32 -0600518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519 // Object is dead!
Steven Moreland92b17c62019-04-02 15:46:24 -0700520 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 if (gPermissionController == pc) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700522 gPermissionController = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523 }
Steven Moreland92b17c62019-04-02 15:46:24 -0700524 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525 }
Daniel Eratc2832702015-10-13 15:29:32 -0600526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527 // Need to retrieve the permission controller.
528 sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
Yi Kongfdd8da92018-06-07 17:52:27 -0700529 if (binder == nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530 // Wait for the permission controller to come back...
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700531 if (startTime == startTime.min()) {
532 startTime = std::chrono::steady_clock::now();
Steve Blocka19954a2012-01-04 20:05:49 +0000533 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000534 String8(permission).c_str(), uid, pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535 }
536 sleep(1);
537 } else {
538 pc = interface_cast<IPermissionController>(binder);
Daniel Eratc2832702015-10-13 15:29:32 -0600539 // Install the new permission controller, and try again.
Steven Moreland92b17c62019-04-02 15:46:24 -0700540 gPermissionControllerLock.lock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541 gPermissionController = pc;
Steven Moreland92b17c62019-04-02 15:46:24 -0700542 gPermissionControllerLock.unlock();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543 }
544 }
545}
546
Steven Moreland576662a2024-08-09 23:12:03 +0000547#endif //__ANDROID_VNDK__
548
Jooyung Han75fc06f2024-02-03 03:56:59 +0900549void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag) {
Steven Moreland576662a2024-08-09 23:12:03 +0000550#if defined(__ANDROID__) && !defined(__ANDROID_VENDOR__) && !defined(__ANDROID_RECOVERY__) && \
551 !defined(__ANDROID_NATIVE_BRIDGE__)
Jooyung Han75fc06f2024-02-03 03:56:59 +0900552 sp<IServiceManager> sm = defaultServiceManager();
553 String16 name = interface + String16("/") + instance;
554 if (!sm->isDeclared(name)) {
555 return nullptr;
556 }
557 String16 libraryName = interface + String16(".") + instance + String16(".so");
558 if (auto updatableViaApex = sm->updatableViaApex(name); updatableViaApex.has_value()) {
559 return AApexSupport_loadLibrary(String8(libraryName).c_str(),
560 String8(*updatableViaApex).c_str(), flag);
561 }
562 return android_load_sphal_library(String8(libraryName).c_str(), flag);
563#else
564 (void)interface;
565 (void)instance;
566 (void)flag;
567 return nullptr;
568#endif
569}
570
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800571// ----------------------------------------------------------------------
572
Parth Sanec7b58642024-08-07 10:31:15 +0000573CppBackendShim::CppBackendShim(const sp<BackendUnifiedServiceManager>& impl)
Parth Sane43e3b8b2024-08-05 13:39:04 +0000574 : mUnifiedServiceManager(impl) {}
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700575
Steven Moreland5af7d852020-04-29 15:40:29 -0700576// This implementation could be simplified and made more efficient by delegating
577// to waitForService. However, this changes the threading structure in some
578// cases and could potentially break prebuilts. Once we have higher logistical
579// complexity, this could be attempted.
Parth Sanec7b58642024-08-07 10:31:15 +0000580sp<IBinder> CppBackendShim::getService(const String16& name) const {
Steven Moreland583685e2019-10-02 16:45:11 -0700581 static bool gSystemBootCompleted = false;
582
583 sp<IBinder> svc = checkService(name);
584 if (svc != nullptr) return svc;
585
Devin Moore74bc5892024-10-23 17:12:19 +0000586 sp<ProcessState> self = ProcessState::selfOrNull();
Steven Moreland583685e2019-10-02 16:45:11 -0700587 const bool isVendorService =
Devin Moore74bc5892024-10-23 17:12:19 +0000588 self && strcmp(self->getDriverName().c_str(), "/dev/vndbinder") == 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700589 constexpr auto timeout = 5s;
590 const auto startTime = std::chrono::steady_clock::now();
Steven Moreland583685e2019-10-02 16:45:11 -0700591 // Vendor code can't access system properties
592 if (!gSystemBootCompleted && !isVendorService) {
593#ifdef __ANDROID__
594 char bootCompleted[PROPERTY_VALUE_MAX];
595 property_get("sys.boot_completed", bootCompleted, "0");
596 gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
597#else
598 gSystemBootCompleted = true;
599#endif
600 }
601 // retry interval in millisecond; note that vendor services stay at 100ms
Jiyong Park16c6e702020-11-13 20:53:12 +0900602 const useconds_t sleepTime = gSystemBootCompleted ? 1000 : 100;
Steven Moreland583685e2019-10-02 16:45:11 -0700603
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000604 ALOGI("Waiting for service '%s' on '%s'...", String8(name).c_str(),
Devin Moore74bc5892024-10-23 17:12:19 +0000605 self ? self->getDriverName().c_str() : "RPC accessors only");
Tom Cherry8fda97f2020-07-22 17:15:44 -0700606
Steven Moreland583685e2019-10-02 16:45:11 -0700607 int n = 0;
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700608 while (std::chrono::steady_clock::now() - startTime < timeout) {
Steven Moreland583685e2019-10-02 16:45:11 -0700609 n++;
Steven Moreland583685e2019-10-02 16:45:11 -0700610 usleep(1000*sleepTime);
Steven Moreland92b17c62019-04-02 15:46:24 -0700611
Yunfan Chen788e1c42018-03-29 16:52:09 +0900612 sp<IBinder> svc = checkService(name);
Tom Cherry8fda97f2020-07-22 17:15:44 -0700613 if (svc != nullptr) {
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700614 const auto waitTime = std::chrono::steady_clock::now() - startTime;
615 ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000616 String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700617 to_ms(waitTime));
Tom Cherry8fda97f2020-07-22 17:15:44 -0700618 return svc;
619 }
Steven Moreland583685e2019-10-02 16:45:11 -0700620 }
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000621 ALOGW("Service %s didn't start. Returning NULL", String8(name).c_str());
Steven Moreland583685e2019-10-02 16:45:11 -0700622 return nullptr;
623}
Yunfan Chen788e1c42018-03-29 16:52:09 +0900624
Parth Sanec7b58642024-08-07 10:31:15 +0000625sp<IBinder> CppBackendShim::checkService(const String16& name) const {
Alice Wang8578f132024-05-03 09:01:56 +0000626 Service ret;
Parth Sane56a04712024-04-22 14:21:07 +0000627 if (!mUnifiedServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700628 return nullptr;
629 }
Parth Sane5e1b7e12024-11-29 10:40:41 +0000630 return ret.get<Service::Tag::serviceWithMetadata>().service;
Steven Moreland583685e2019-10-02 16:45:11 -0700631}
632
Parth Sanec7b58642024-08-07 10:31:15 +0000633status_t CppBackendShim::addService(const String16& name, const sp<IBinder>& service,
634 bool allowIsolated, int dumpsysPriority) {
Parth Sane56a04712024-04-22 14:21:07 +0000635 Status status = mUnifiedServiceManager->addService(String8(name).c_str(), service,
636 allowIsolated, dumpsysPriority);
Steven Moreland583685e2019-10-02 16:45:11 -0700637 return status.exceptionCode();
638}
639
Parth Sanec7b58642024-08-07 10:31:15 +0000640Vector<String16> CppBackendShim::listServices(int dumpsysPriority) {
Steven Moreland583685e2019-10-02 16:45:11 -0700641 std::vector<std::string> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000642 if (!mUnifiedServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
Steven Moreland583685e2019-10-02 16:45:11 -0700643 return {};
644 }
645
646 Vector<String16> res;
647 res.setCapacity(ret.size());
648 for (const std::string& name : ret) {
649 res.push(String16(name.c_str()));
650 }
651 return res;
652}
653
Parth Sanec7b58642024-08-07 10:31:15 +0000654sp<IBinder> CppBackendShim::waitForService(const String16& name16) {
Steven Moreland583685e2019-10-02 16:45:11 -0700655 class Waiter : public android::os::BnServiceCallback {
656 Status onRegistration(const std::string& /*name*/,
657 const sp<IBinder>& binder) override {
658 std::unique_lock<std::mutex> lock(mMutex);
659 mBinder = binder;
660 lock.unlock();
Jon Spivack9f503a42019-10-22 16:49:19 -0700661 // Flushing here helps ensure the service's ref count remains accurate
662 IPCThreadState::self()->flushCommands();
Steven Moreland583685e2019-10-02 16:45:11 -0700663 mCv.notify_one();
664 return Status::ok();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900665 }
Steven Moreland583685e2019-10-02 16:45:11 -0700666 public:
667 sp<IBinder> mBinder;
668 std::mutex mMutex;
669 std::condition_variable mCv;
670 };
Yunfan Chen788e1c42018-03-29 16:52:09 +0900671
Jon Spivackfed6db42019-11-18 16:43:59 -0800672 // Simple RAII object to ensure a function call immediately before going out of scope
673 class Defer {
674 public:
Jiyong Park70072fd2020-11-13 17:19:14 +0900675 explicit Defer(std::function<void()>&& f) : mF(std::move(f)) {}
Jon Spivackfed6db42019-11-18 16:43:59 -0800676 ~Defer() { mF(); }
677 private:
678 std::function<void()> mF;
679 };
680
Steven Moreland583685e2019-10-02 16:45:11 -0700681 const std::string name = String8(name16).c_str();
Yunfan Chen788e1c42018-03-29 16:52:09 +0900682
Steven Moreland583685e2019-10-02 16:45:11 -0700683 sp<IBinder> out;
Yifan Hongf7760012021-06-04 16:04:42 -0700684 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000685 ALOGW("Failed to getService in waitForService for %s: %s", name.c_str(),
686 status.toString8().c_str());
Devin Moore74bc5892024-10-23 17:12:19 +0000687 sp<ProcessState> self = ProcessState::selfOrNull();
688 if (self && 0 == self->getThreadPoolMaxTotalThreadCount()) {
Elie Kheirallah27c26952022-09-07 21:45:26 +0000689 ALOGW("Got service, but may be racey because we could not wait efficiently for it. "
690 "Threadpool has 0 guaranteed threads. "
691 "Is the threadpool configured properly? "
692 "See ProcessState::startThreadPool and "
693 "ProcessState::setThreadPoolMaxThreadCount.");
694 }
Steven Moreland583685e2019-10-02 16:45:11 -0700695 return nullptr;
696 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800697 if (out != nullptr) return out;
Steven Moreland583685e2019-10-02 16:45:11 -0700698
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000699 sp<Waiter> waiter = sp<Waiter>::make();
Parth Sane56a04712024-04-22 14:21:07 +0000700 if (Status status = mUnifiedServiceManager->registerForNotifications(name, waiter);
Steven Morelanda1d70172021-05-24 22:03:42 +0000701 !status.isOk()) {
702 ALOGW("Failed to registerForNotifications in waitForService for %s: %s", name.c_str(),
703 status.toString8().c_str());
Yi Kongfdd8da92018-06-07 17:52:27 -0700704 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705 }
Parth Sane56a04712024-04-22 14:21:07 +0000706 Defer unregister([&] { mUnifiedServiceManager->unregisterForNotifications(name, waiter); });
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700707
Steven Moreland583685e2019-10-02 16:45:11 -0700708 while(true) {
709 {
Steven Morelandf2677e22020-07-14 19:58:08 +0000710 // It would be really nice if we could read binder commands on this
711 // thread instead of needing a threadpool to be started, but for
712 // instance, if we call getAndExecuteCommand, it might be the case
713 // that another thread serves the callback, and we never get a
714 // command, so we hang indefinitely.
Steven Moreland583685e2019-10-02 16:45:11 -0700715 std::unique_lock<std::mutex> lock(waiter->mMutex);
Steven Moreland3d37ef22023-04-25 18:25:14 +0000716 waiter->mCv.wait_for(lock, 1s, [&] {
717 return waiter->mBinder != nullptr;
718 });
Steven Moreland583685e2019-10-02 16:45:11 -0700719 if (waiter->mBinder != nullptr) return waiter->mBinder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721
Devin Moore74bc5892024-10-23 17:12:19 +0000722 sp<ProcessState> self = ProcessState::selfOrNull();
Steven Moreland3d37ef22023-04-25 18:25:14 +0000723 ALOGW("Waited one second for %s (is service started? Number of threads started in the "
Elie Kheirallah27c26952022-09-07 21:45:26 +0000724 "threadpool: %zu. Are binder threads started and available?)",
Devin Moore74bc5892024-10-23 17:12:19 +0000725 name.c_str(), self ? self->getThreadPoolMaxTotalThreadCount() : 0);
Steven Morelandf2677e22020-07-14 19:58:08 +0000726
Steven Moreland583685e2019-10-02 16:45:11 -0700727 // Handle race condition for lazy services. Here is what can happen:
728 // - the service dies (not processed by init yet).
729 // - sm processes death notification.
730 // - sm gets getService and calls init to start service.
731 // - init gets the start signal, but the service already appears
732 // started, so it does nothing.
733 // - init gets death signal, but doesn't know it needs to restart
734 // the service
735 // - we need to request service again to get it to start
Yifan Hongf7760012021-06-04 16:04:42 -0700736 if (Status status = realGetService(name, &out); !status.isOk()) {
Steven Morelanda1d70172021-05-24 22:03:42 +0000737 ALOGW("Failed to getService in waitForService on later try for %s: %s", name.c_str(),
738 status.toString8().c_str());
Steven Moreland1c47b582019-08-27 18:05:27 -0700739 return nullptr;
740 }
Jon Spivackfed6db42019-11-18 16:43:59 -0800741 if (out != nullptr) return out;
Steven Moreland1c47b582019-08-27 18:05:27 -0700742 }
Steven Moreland583685e2019-10-02 16:45:11 -0700743}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800744
Parth Sanec7b58642024-08-07 10:31:15 +0000745bool CppBackendShim::isDeclared(const String16& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700746 bool declared;
Parth Sane56a04712024-04-22 14:21:07 +0000747 if (Status status = mUnifiedServiceManager->isDeclared(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000748 !status.isOk()) {
Vova Sharaienkoca71b452022-12-08 01:38:29 +0000749 ALOGW("Failed to get isDeclared for %s: %s", String8(name).c_str(),
Steven Morelanda1d70172021-05-24 22:03:42 +0000750 status.toString8().c_str());
Steven Morelandb82b8f82019-10-28 10:52:34 -0700751 return false;
752 }
753 return declared;
754}
755
Parth Sanec7b58642024-08-07 10:31:15 +0000756Vector<String16> CppBackendShim::getDeclaredInstances(const String16& interface) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000757 std::vector<std::string> out;
Steven Morelanda1d70172021-05-24 22:03:42 +0000758 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000759 mUnifiedServiceManager->getDeclaredInstances(String8(interface).c_str(), &out);
Steven Morelanda1d70172021-05-24 22:03:42 +0000760 !status.isOk()) {
761 ALOGW("Failed to getDeclaredInstances for %s: %s", String8(interface).c_str(),
762 status.toString8().c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000763 return {};
764 }
765
766 Vector<String16> res;
767 res.setCapacity(out.size());
768 for (const std::string& instance : out) {
769 res.push(String16(instance.c_str()));
770 }
771 return res;
772}
773
Parth Sanec7b58642024-08-07 10:31:15 +0000774std::optional<String16> CppBackendShim::updatableViaApex(const String16& name) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000775 std::optional<std::string> declared;
Parth Sane56a04712024-04-22 14:21:07 +0000776 if (Status status = mUnifiedServiceManager->updatableViaApex(String8(name).c_str(), &declared);
Steven Morelanda1d70172021-05-24 22:03:42 +0000777 !status.isOk()) {
778 ALOGW("Failed to get updatableViaApex for %s: %s", String8(name).c_str(),
779 status.toString8().c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000780 return std::nullopt;
781 }
782 return declared ? std::optional<String16>(String16(declared.value().c_str())) : std::nullopt;
783}
784
Parth Sanec7b58642024-08-07 10:31:15 +0000785Vector<String16> CppBackendShim::getUpdatableNames(const String16& apexName) {
Jooyung Han76944fe2022-10-25 17:02:45 +0900786 std::vector<std::string> out;
Parth Sane56a04712024-04-22 14:21:07 +0000787 if (Status status = mUnifiedServiceManager->getUpdatableNames(String8(apexName).c_str(), &out);
Jooyung Han76944fe2022-10-25 17:02:45 +0900788 !status.isOk()) {
789 ALOGW("Failed to getUpdatableNames for %s: %s", String8(apexName).c_str(),
790 status.toString8().c_str());
791 return {};
792 }
793
794 Vector<String16> res;
795 res.setCapacity(out.size());
796 for (const std::string& instance : out) {
797 res.push(String16(instance.c_str()));
798 }
799 return res;
800}
801
Parth Sanec7b58642024-08-07 10:31:15 +0000802std::optional<IServiceManager::ConnectionInfo> CppBackendShim::getConnectionInfo(
Devin Moore5e4c2f12021-09-09 22:36:33 +0000803 const String16& name) {
804 std::optional<os::ConnectionInfo> connectionInfo;
805 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000806 mUnifiedServiceManager->getConnectionInfo(String8(name).c_str(), &connectionInfo);
Devin Moore5e4c2f12021-09-09 22:36:33 +0000807 !status.isOk()) {
808 ALOGW("Failed to get ConnectionInfo for %s: %s", String8(name).c_str(),
809 status.toString8().c_str());
810 }
811 return connectionInfo.has_value()
812 ? std::make_optional<IServiceManager::ConnectionInfo>(
813 {connectionInfo->ipAddress, static_cast<unsigned int>(connectionInfo->port)})
814 : std::nullopt;
815}
816
Parth Sanec7b58642024-08-07 10:31:15 +0000817status_t CppBackendShim::registerForNotifications(const String16& name,
818 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800819 if (cb == nullptr) {
820 ALOGE("%s: null cb passed", __FUNCTION__);
821 return BAD_VALUE;
822 }
823 std::string nameStr = String8(name).c_str();
824 sp<RegistrationWaiter> registrationWaiter = sp<RegistrationWaiter>::make(cb);
825 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
826 if (Status status =
Parth Sane56a04712024-04-22 14:21:07 +0000827 mUnifiedServiceManager->registerForNotifications(nameStr, registrationWaiter);
Jayant Chowdhary30700942022-01-31 14:12:40 -0800828 !status.isOk()) {
829 ALOGW("Failed to registerForNotifications for %s: %s", nameStr.c_str(),
830 status.toString8().c_str());
831 return UNKNOWN_ERROR;
832 }
833 mNameToRegistrationCallback[nameStr].push_back(std::make_pair(cb, registrationWaiter));
834 return OK;
835}
836
Parth Sanec7b58642024-08-07 10:31:15 +0000837void CppBackendShim::removeRegistrationCallbackLocked(const sp<AidlRegistrationCallback>& cb,
838 ServiceCallbackMap::iterator* it,
839 sp<RegistrationWaiter>* waiter) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800840 std::vector<LocalRegistrationAndWaiter>& localRegistrationAndWaiters = (*it)->second;
841 for (auto lit = localRegistrationAndWaiters.begin();
842 lit != localRegistrationAndWaiters.end();) {
843 if (lit->first == cb) {
844 if (waiter) {
845 *waiter = lit->second;
846 }
847 lit = localRegistrationAndWaiters.erase(lit);
848 } else {
849 ++lit;
850 }
851 }
852
853 if (localRegistrationAndWaiters.empty()) {
854 mNameToRegistrationCallback.erase(*it);
855 }
856}
857
Parth Sanec7b58642024-08-07 10:31:15 +0000858status_t CppBackendShim::unregisterForNotifications(const String16& name,
859 const sp<AidlRegistrationCallback>& cb) {
Jayant Chowdhary30700942022-01-31 14:12:40 -0800860 if (cb == nullptr) {
861 ALOGE("%s: null cb passed", __FUNCTION__);
862 return BAD_VALUE;
863 }
864 std::string nameStr = String8(name).c_str();
865 std::lock_guard<std::mutex> lock(mNameToRegistrationLock);
866 auto it = mNameToRegistrationCallback.find(nameStr);
867 sp<RegistrationWaiter> registrationWaiter;
868 if (it != mNameToRegistrationCallback.end()) {
869 removeRegistrationCallbackLocked(cb, &it, &registrationWaiter);
870 } else {
871 ALOGE("%s no callback registered for notifications on %s", __FUNCTION__, nameStr.c_str());
872 return BAD_VALUE;
873 }
874 if (registrationWaiter == nullptr) {
875 ALOGE("%s Callback passed wasn't used to register for notifications", __FUNCTION__);
876 return BAD_VALUE;
877 }
Parth Sane56a04712024-04-22 14:21:07 +0000878 if (Status status = mUnifiedServiceManager->unregisterForNotifications(String8(name).c_str(),
Jayant Chowdhary30700942022-01-31 14:12:40 -0800879 registrationWaiter);
880 !status.isOk()) {
881 ALOGW("Failed to get service manager to unregisterForNotifications for %s: %s",
882 String8(name).c_str(), status.toString8().c_str());
883 return UNKNOWN_ERROR;
884 }
885 return OK;
886}
887
Parth Sanec7b58642024-08-07 10:31:15 +0000888std::vector<IServiceManager::ServiceDebugInfo> CppBackendShim::getServiceDebugInfo() {
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000889 std::vector<os::ServiceDebugInfo> serviceDebugInfos;
890 std::vector<IServiceManager::ServiceDebugInfo> ret;
Parth Sane56a04712024-04-22 14:21:07 +0000891 if (Status status = mUnifiedServiceManager->getServiceDebugInfo(&serviceDebugInfos);
Jayant Chowdharya0a8eb22022-05-20 03:30:09 +0000892 !status.isOk()) {
893 ALOGW("%s Failed to get ServiceDebugInfo", __FUNCTION__);
894 return ret;
895 }
896 for (const auto& serviceDebugInfo : serviceDebugInfos) {
897 IServiceManager::ServiceDebugInfo retInfo;
898 retInfo.pid = serviceDebugInfo.debugPid;
899 retInfo.name = serviceDebugInfo.name;
900 ret.emplace_back(retInfo);
901 }
902 return ret;
903}
904
Yifan Hongf7760012021-06-04 16:04:42 -0700905#ifndef __ANDROID__
Parth Sanec7b58642024-08-07 10:31:15 +0000906// CppBackendShim for host. Implements the old libbinder android::IServiceManager API.
Yifan Hongf7760012021-06-04 16:04:42 -0700907// The internal implementation of the AIDL interface android::os::IServiceManager calls into
908// on-device service manager.
Parth Sanec7b58642024-08-07 10:31:15 +0000909class CppServiceManagerHostShim : public CppBackendShim {
Yifan Hongf7760012021-06-04 16:04:42 -0700910public:
Parth Sanec7b58642024-08-07 10:31:15 +0000911 CppServiceManagerHostShim(const sp<AidlServiceManager>& impl,
912 const RpcDelegateServiceManagerOptions& options)
913 : CppBackendShim(sp<BackendUnifiedServiceManager>::make(impl)), mOptions(options) {}
914 // CppBackendShim::getService is based on checkService, so no need to override it.
Yifan Hongf7760012021-06-04 16:04:42 -0700915 sp<IBinder> checkService(const String16& name) const override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700916 return getDeviceService({String8(name).c_str()}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700917 }
918
919protected:
Parth Sanec7b58642024-08-07 10:31:15 +0000920 // Override realGetService for CppBackendShim::waitForService.
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700921 Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override {
Yifan Hong5a05ef72021-10-08 17:33:47 -0700922 *_aidl_return = getDeviceService({"-g", name}, mOptions);
Yifan Hongf7760012021-06-04 16:04:42 -0700923 return Status::ok();
924 }
Yifan Hong5a05ef72021-10-08 17:33:47 -0700925
926private:
927 RpcDelegateServiceManagerOptions mOptions;
Yifan Hongf7760012021-06-04 16:04:42 -0700928};
Yifan Hong5a05ef72021-10-08 17:33:47 -0700929sp<IServiceManager> createRpcDelegateServiceManager(
930 const RpcDelegateServiceManagerOptions& options) {
931 auto binder = getDeviceService({"manager"}, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700932 if (binder == nullptr) {
933 ALOGE("getDeviceService(\"manager\") returns null");
934 return nullptr;
935 }
936 auto interface = AidlServiceManager::asInterface(binder);
937 if (interface == nullptr) {
938 ALOGE("getDeviceService(\"manager\") returns non service manager");
939 return nullptr;
940 }
Parth Sanec7b58642024-08-07 10:31:15 +0000941 return sp<CppServiceManagerHostShim>::make(interface, options);
Yifan Hongf7760012021-06-04 16:04:42 -0700942}
943#endif
944
Steven Moreland61ff8492019-09-26 16:05:45 -0700945} // namespace android