blob: 54bb8dc37a0f525d82542f067359387b0a0fa645 [file] [log] [blame]
Steven Moreland5d5ef7f2016-10-20 19:19:55 -07001/*
2 * Copyright (C) 2016 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
Steven Morelandfcaa97f2019-06-24 12:07:22 -070017#define LOG_TAG "HidlServiceManagement"
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070018
Steven Moreland2056cf32019-09-17 17:41:02 -070019#ifdef __ANDROID__
Devin Moore22e6f1e2023-11-22 22:29:54 +000020#include <android/api-level.h>
Jiyong Park3ab546c2017-04-06 20:28:07 +090021#include <android/dlext.h>
Steven Moreland2056cf32019-09-17 17:41:02 -070022#endif // __ANDROID__
23
Yifan Hong9a22d1d2017-01-25 14:19:26 -080024#include <condition_variable>
25#include <dlfcn.h>
26#include <dirent.h>
Steven Moreland405d7612017-04-07 20:31:22 -070027#include <fstream>
28#include <pthread.h>
Yifan Hong9a22d1d2017-01-25 14:19:26 -080029#include <unistd.h>
30
31#include <mutex>
32#include <regex>
Yifan Hongbd0d8f72017-05-24 19:43:51 -070033#include <set>
Yifan Hong9a22d1d2017-01-25 14:19:26 -080034
Martijn Coenen12f04d92016-12-07 17:29:41 +010035#include <hidl/HidlBinderSupport.h>
Justin Yun1f048102017-12-01 15:30:08 +090036#include <hidl/HidlInternal.h>
Steven Morelande69e8d32018-03-14 10:55:42 -070037#include <hidl/HidlTransportUtils.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070038#include <hidl/ServiceManagement.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070039#include <hidl/Status.h>
Peter Kalauskas64ffced2018-09-05 16:41:08 -070040#include <utils/SystemClock.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070041
Peter Kalauskas64ffced2018-09-05 16:41:08 -070042#include <android-base/file.h>
Steven Moreland337e6b62017-01-18 17:25:13 -080043#include <android-base/logging.h>
Peter Kalauskas64ffced2018-09-05 16:41:08 -070044#include <android-base/parseint.h>
Steven Morelandc1cee2c2017-03-24 16:23:11 +000045#include <android-base/properties.h>
Justin Yun1f048102017-12-01 15:30:08 +090046#include <android-base/stringprintf.h>
Peter Kalauskas64ffced2018-09-05 16:41:08 -070047#include <android-base/strings.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070048#include <hwbinder/IPCThreadState.h>
49#include <hwbinder/Parcel.h>
Steven Moreland2056cf32019-09-17 17:41:02 -070050#if !defined(__ANDROID_RECOVERY__) && defined(__ANDROID__)
Jiyong Parkba8ace12017-05-15 15:44:39 +090051#include <vndksupport/linker.h>
Jerry Zhang86ae9992018-05-30 17:11:09 -070052#endif
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070053
Steven Moreland89909692018-05-30 14:11:19 -070054#include <android/hidl/manager/1.2/BnHwServiceManager.h>
55#include <android/hidl/manager/1.2/BpHwServiceManager.h>
56#include <android/hidl/manager/1.2/IServiceManager.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070057
Steven Morelandbb9eb2a2018-10-11 12:10:01 -070058using ::android::hidl::base::V1_0::IBase;
Steven Moreland2a2678e2017-07-21 18:07:38 -070059using IServiceManager1_0 = android::hidl::manager::V1_0::IServiceManager;
60using IServiceManager1_1 = android::hidl::manager::V1_1::IServiceManager;
Steven Moreland89909692018-05-30 14:11:19 -070061using IServiceManager1_2 = android::hidl::manager::V1_2::IServiceManager;
Steven Morelandbb9eb2a2018-10-11 12:10:01 -070062using ::android::hidl::manager::V1_0::IServiceNotification;
Devin Mooree1973ce2022-04-15 20:54:03 +000063using ::android::hidl::manager::V1_2::IClientCallback;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070064
65namespace android {
66namespace hardware {
67
Yifan Hongdeacf142018-07-10 17:33:34 -070068#if defined(__ANDROID_RECOVERY__)
69static constexpr bool kIsRecovery = true;
70#else
71static constexpr bool kIsRecovery = false;
72#endif
73
Devin Moore50ced9f2024-03-26 22:00:23 +000074static bool isHwServiceManagerInstalled() {
75 return access("/system_ext/bin/hwservicemanager", F_OK) == 0 ||
76 access("/system/system_ext/bin/hwservicemanager", F_OK) == 0 ||
77 access("/system/bin/hwservicemanager", F_OK) == 0;
78}
79
80static bool waitForHwServiceManager() {
81 if (!isHwServiceManagerInstalled()) {
82 return false;
83 }
Steven Moreland2056cf32019-09-17 17:41:02 -070084 // TODO(b/31559095): need bionic host so that we can use 'prop_info' returned
85 // from WaitForProperty
86#ifdef __ANDROID__
87 static const char* kHwServicemanagerReadyProperty = "hwservicemanager.ready";
88
Steven Morelandc1cee2c2017-03-24 16:23:11 +000089 using std::literals::chrono_literals::operator""s;
90
Steven Moreland2056cf32019-09-17 17:41:02 -070091 using android::base::WaitForProperty;
Devin Moore50ced9f2024-03-26 22:00:23 +000092 while (true) {
93 if (base::GetBoolProperty("hwservicemanager.disabled", false)) {
94 return false;
95 }
96 if (WaitForProperty(kHwServicemanagerReadyProperty, "true", 1s)) {
97 return true;
98 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +000099 LOG(WARNING) << "Waited for hwservicemanager.ready for a second, waiting another...";
100 }
Steven Moreland2056cf32019-09-17 17:41:02 -0700101#endif // __ANDROID__
Devin Moore50ced9f2024-03-26 22:00:23 +0000102 return true;
103}
104
105bool isHidlSupported() {
106 return waitForHwServiceManager();
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000107}
108
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700109static std::string binaryName() {
Steven Moreland405d7612017-04-07 20:31:22 -0700110 std::ifstream ifs("/proc/self/cmdline");
111 std::string cmdline;
Steven Morelandd682c0e2020-07-21 17:47:32 +0000112 if (!ifs) {
Steven Moreland405d7612017-04-07 20:31:22 -0700113 return "";
114 }
115 ifs >> cmdline;
116
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -0700117 size_t idx = cmdline.rfind('/');
Steven Moreland405d7612017-04-07 20:31:22 -0700118 if (idx != std::string::npos) {
119 cmdline = cmdline.substr(idx + 1);
120 }
121
122 return cmdline;
123}
124
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700125static std::string packageWithoutVersion(const std::string& packageAndVersion) {
Steven Moreland7d09a402018-04-06 10:44:05 -0700126 size_t at = packageAndVersion.find('@');
127 if (at == std::string::npos) return packageAndVersion;
128 return packageAndVersion.substr(0, at);
129}
130
Steven Morelandd682c0e2020-07-21 17:47:32 +0000131__attribute__((noinline)) static void tryShortenProcessName(const std::string& descriptor) {
Steven Moreland7d09a402018-04-06 10:44:05 -0700132 const static std::string kTasks = "/proc/self/task/";
133
134 // make sure that this binary name is in the same package
Steven Moreland405d7612017-04-07 20:31:22 -0700135 std::string processName = binaryName();
136
Steven Moreland7d09a402018-04-06 10:44:05 -0700137 // e.x. android.hardware.foo is this package
Steven Moreland8092aa02018-10-12 15:54:56 -0700138 if (!base::StartsWith(packageWithoutVersion(processName), packageWithoutVersion(descriptor))) {
Steven Moreland405d7612017-04-07 20:31:22 -0700139 return;
140 }
141
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700142 // e.x. android.hardware.module.foo@1.2::IFoo -> foo@1.2
143 size_t lastDot = descriptor.rfind('.');
Steven Moreland7d09a402018-04-06 10:44:05 -0700144 if (lastDot == std::string::npos) return;
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700145 size_t secondDot = descriptor.rfind('.', lastDot - 1);
Steven Moreland7d09a402018-04-06 10:44:05 -0700146 if (secondDot == std::string::npos) return;
Steven Moreland405d7612017-04-07 20:31:22 -0700147
Steven Moreland7d09a402018-04-06 10:44:05 -0700148 std::string newName = processName.substr(secondDot + 1, std::string::npos);
149 ALOGI("Removing namespace from process name %s to %s.", processName.c_str(), newName.c_str());
150
151 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kTasks.c_str()), closedir);
152 if (dir == nullptr) return;
153
154 dirent* dp;
155 while ((dp = readdir(dir.get())) != nullptr) {
156 if (dp->d_type != DT_DIR) continue;
157 if (dp->d_name[0] == '.') continue;
158
159 std::fstream fs(kTasks + dp->d_name + "/comm");
Steven Morelandd682c0e2020-07-21 17:47:32 +0000160 if (!fs) {
Steven Moreland7d09a402018-04-06 10:44:05 -0700161 ALOGI("Could not rename process, failed read comm for %s.", dp->d_name);
162 continue;
163 }
164
165 std::string oldComm;
Steven Morelandd682c0e2020-07-21 17:47:32 +0000166 if (!(fs >> oldComm)) continue;
Steven Moreland7d09a402018-04-06 10:44:05 -0700167
168 // don't rename if it already has an explicit name
Steven Moreland8092aa02018-10-12 15:54:56 -0700169 if (base::StartsWith(descriptor, oldComm)) {
Steven Morelandd682c0e2020-07-21 17:47:32 +0000170 if (!fs.seekg(0, fs.beg)) continue;
Steven Moreland7d09a402018-04-06 10:44:05 -0700171 fs << newName;
172 }
Steven Moreland405d7612017-04-07 20:31:22 -0700173 }
Steven Moreland405d7612017-04-07 20:31:22 -0700174}
175
176namespace details {
177
Steven Morelandb939e7e2020-07-08 01:04:23 +0000178#ifdef ENFORCE_VINTF_MANIFEST
179static constexpr bool kEnforceVintfManifest = true;
180#else
181static constexpr bool kEnforceVintfManifest = false;
182#endif
183
Steven Moreland206d2812020-07-08 21:21:48 +0000184static bool* getTrebleTestingOverridePtr() {
185 static bool gTrebleTestingOverride = false;
186 return &gTrebleTestingOverride;
187}
Steven Morelandb939e7e2020-07-08 01:04:23 +0000188
189void setTrebleTestingOverride(bool testingOverride) {
Steven Moreland206d2812020-07-08 21:21:48 +0000190 *getTrebleTestingOverridePtr() = testingOverride;
Steven Morelandb939e7e2020-07-08 01:04:23 +0000191}
192
Steven Morelandf47cdf72021-04-07 22:13:13 +0000193static bool isDebuggable() {
194 static bool debuggable = base::GetBoolProperty("ro.debuggable", false);
195 return debuggable;
196}
197
Steven Morelandb939e7e2020-07-08 01:04:23 +0000198static inline bool isTrebleTestingOverride() {
Steven Moreland4acdab72022-08-09 16:27:46 +0000199 // return false early so we don't need to check the debuggable property
200 if (!*getTrebleTestingOverridePtr()) return false;
201
Steven Morelandf47cdf72021-04-07 22:13:13 +0000202 if (kEnforceVintfManifest && !isDebuggable()) {
Steven Morelandb939e7e2020-07-08 01:04:23 +0000203 // don't allow testing override in production
204 return false;
205 }
206
Steven Moreland4acdab72022-08-09 16:27:46 +0000207 return true;
Steven Morelandb939e7e2020-07-08 01:04:23 +0000208}
209
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700210static void onRegistrationImpl(const std::string& descriptor, const std::string& instanceName) {
Steven Moreland489e7572021-01-21 19:02:54 +0000211 LOG(INFO) << "Registered " << descriptor << "/" << instanceName;
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700212 tryShortenProcessName(descriptor);
213}
214
Steven Moreland911852c2020-05-11 10:51:26 -0700215// only used by prebuilts - should be able to remove
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700216void onRegistration(const std::string& packageName, const std::string& interfaceName,
217 const std::string& instanceName) {
218 return onRegistrationImpl(packageName + "::" + interfaceName, instanceName);
Steven Moreland405d7612017-04-07 20:31:22 -0700219}
220
221} // details
222
Steven Moreland2a2678e2017-07-21 18:07:38 -0700223sp<IServiceManager1_0> defaultServiceManager() {
Steven Moreland89909692018-05-30 14:11:19 -0700224 return defaultServiceManager1_2();
Steven Moreland2a2678e2017-07-21 18:07:38 -0700225}
226sp<IServiceManager1_1> defaultServiceManager1_1() {
Steven Moreland89909692018-05-30 14:11:19 -0700227 return defaultServiceManager1_2();
228}
Devin Mooree1973ce2022-04-15 20:54:03 +0000229static bool isServiceManager(const hidl_string& fqName) {
230 return fqName == IServiceManager1_0::descriptor || fqName == IServiceManager1_1::descriptor ||
231 fqName == IServiceManager1_2::descriptor;
232}
Devin Moore22e6f1e2023-11-22 22:29:54 +0000233
Devin Mooree1973ce2022-04-15 20:54:03 +0000234/*
235 * A replacement for hwservicemanager when it is not installed on a device.
236 *
237 * Clients in the framework need to continue supporting HIDL services through
238 * hwservicemanager for upgrading devices. Being unable to get an instance of
239 * hardware service manager is a hard error, so this implementation is returned
240 * to be able service the requests and tell clients there are no services
241 * registered.
242 */
Devin Moore2d2e4c02023-11-28 00:24:19 +0000243struct NoHwServiceManager : public IServiceManager1_2, hidl_death_recipient {
Devin Mooree1973ce2022-04-15 20:54:03 +0000244 Return<sp<IBase>> get(const hidl_string& fqName, const hidl_string&) override {
245 sp<IBase> ret = nullptr;
246
247 if (isServiceManager(fqName)) {
248 ret = defaultServiceManager1_2();
249 }
250 return ret;
251 }
252
253 Return<bool> add(const hidl_string& name, const sp<IBase>& /* service */) override {
254 LOG(INFO) << "Cannot add " << name << " without hwservicemanager";
255 return false;
256 }
257
258 Return<Transport> getTransport(const hidl_string& fqName, const hidl_string& name) {
Devin Moore0d309172023-11-28 00:20:32 +0000259 // We pretend like IServiceManager is declared for
260 // IServiceManager::getService to return this NoHwServiceManager
261 // instance
262 if (isServiceManager(fqName)) {
263 return Transport::HWBINDER;
264 }
Devin Mooree1973ce2022-04-15 20:54:03 +0000265 LOG(INFO) << "Trying to get transport of " << fqName << "/" << name
266 << " without hwservicemanager";
Devin Mooreadbf9a52023-06-06 23:07:08 +0000267 return Transport::EMPTY;
Devin Mooree1973ce2022-04-15 20:54:03 +0000268 }
269
270 Return<void> list(list_cb _hidl_cb) override {
271 _hidl_cb({});
272 LOG(INFO) << "Cannot list all services without hwservicemanager";
273 return Void();
274 }
275 Return<void> listByInterface(const hidl_string& fqName, listByInterface_cb _hidl_cb) override {
276 _hidl_cb({});
277 LOG(INFO) << "Cannot list service " << fqName << " without hwservicemanager";
278 return Void();
279 }
280
Devin Moore2d2e4c02023-11-28 00:24:19 +0000281 void serviceDied(uint64_t /* cookie */, const wp<IBase>& who) override {
282 sp<IBase> promoted = who.promote();
283 if (promoted) {
284 bool removed = false;
285 for (auto [name, callbacks] : mServiceNotifications) {
286 for (auto it = callbacks.begin(); it != callbacks.end();) {
287 if (interfacesEqual(*it, promoted)) {
288 callbacks.erase(it);
289 removed = true;
290 }
291 it++;
292 }
293 if (removed) return;
294 }
295 }
296 LOG(ERROR) << "Could not find a registered callback for a service who died. "
297 << "Service pointer: " << who.promote().get();
298 }
299
Devin Mooree1973ce2022-04-15 20:54:03 +0000300 Return<bool> registerForNotifications(const hidl_string& fqName, const hidl_string& name,
Devin Moore2d2e4c02023-11-28 00:24:19 +0000301 const sp<IServiceNotification>& callback) override {
302 LOG(INFO) << "Will not get any notifications for " << fqName << "/" << name
303 << " without hwservicemanager but keeping the callback.";
304 if (callback == nullptr) {
305 LOG(ERROR) << "Cannot register a null callback for " << fqName << "/" << name;
306 return false;
307 }
308 bool ret = callback->linkToDeath(this, 0);
309 if (!ret) {
310 LOG(ERROR) << "Failed to register death recipient for " << fqName << "/" << name;
311 return false;
312 }
313
314 auto [it, inserted] = mServiceNotifications[static_cast<std::string>(fqName) + "/" +
315 static_cast<std::string>(name)]
316 .insert(callback);
317 if (!inserted) {
318 LOG(WARNING) << "This callback for " << fqName << "/" << name
319 << " was already registered so "
320 << "we are not keeping a reference to this one.";
321 return false;
322 }
323 return true;
Devin Mooree1973ce2022-04-15 20:54:03 +0000324 }
325
326 Return<void> debugDump(debugDump_cb _hidl_cb) override {
327 _hidl_cb({});
328 return Void();
329 }
330
331 Return<void> registerPassthroughClient(const hidl_string& fqName,
332 const hidl_string& name) override {
333 LOG(INFO) << "This process is a client of " << fqName << "/" << name
334 << " passthrough HAL, but it won't show up in lshal because hwservicemanager is "
335 "not installed";
336 return Void();
337 }
338
Devin Moore2d2e4c02023-11-28 00:24:19 +0000339 Return<bool> unregisterForNotifications(const hidl_string& fqName, const hidl_string& name,
340 const sp<IServiceNotification>& callback) override {
341 auto ret = mServiceNotifications[static_cast<std::string>(fqName) + "/" +
342 static_cast<std::string>(name)]
343 .erase(callback);
344 if (!ret) {
345 LOG(WARNING) << "This callback for " << fqName << "/" << name << " was not previously "
346 << "registered so there is nothing to do.";
347 return false;
348 }
349 return true;
Devin Mooree1973ce2022-04-15 20:54:03 +0000350 }
Devin Moore2d2e4c02023-11-28 00:24:19 +0000351
Devin Mooree1973ce2022-04-15 20:54:03 +0000352 Return<bool> registerClientCallback(const hidl_string& fqName, const hidl_string& name,
353 const sp<IBase>&, const sp<IClientCallback>&) {
354 LOG(INFO) << "Cannot add client callback for " << fqName << "/" << name
355 << " without hwservicemanager";
356 return false;
357 }
358 Return<bool> unregisterClientCallback(const sp<IBase>&, const sp<IClientCallback>&) {
359 LOG(INFO) << "Cannot unregister client callbacks without hwservicemanager";
360 return false;
361 }
362 Return<bool> addWithChain(const hidl_string& fqName, const sp<IBase>&,
363 const hidl_vec<hidl_string>&) {
364 LOG(INFO) << "Cannot add " << fqName << " with chain without hwservicemanager";
365 return false;
366 }
367 Return<void> listManifestByInterface(const hidl_string& fqName, listManifestByInterface_cb) {
368 LOG(INFO) << "Cannot list manifest for " << fqName << " without hwservicemanager";
369 return Void();
370 }
371 Return<bool> tryUnregister(const hidl_string& fqName, const hidl_string& name,
372 const sp<IBase>&) {
373 LOG(INFO) << "Cannot unregister service " << fqName << "/" << name
374 << " without hwservicemanager";
375 return false;
376 }
Devin Moore2d2e4c02023-11-28 00:24:19 +0000377
378 private:
379 std::map<std::string, std::set<sp<IServiceNotification>>> mServiceNotifications;
Devin Mooree1973ce2022-04-15 20:54:03 +0000380};
381
Steven Moreland89909692018-05-30 14:11:19 -0700382sp<IServiceManager1_2> defaultServiceManager1_2() {
383 using android::hidl::manager::V1_2::BnHwServiceManager;
384 using android::hidl::manager::V1_2::BpHwServiceManager;
385
Steven Moreland10d55632020-04-21 14:10:53 -0700386 static std::mutex& gDefaultServiceManagerLock = *new std::mutex;
387 static sp<IServiceManager1_2>& gDefaultServiceManager = *new sp<IServiceManager1_2>;
Steven Moreland89909692018-05-30 14:11:19 -0700388
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700389 {
Steven Moreland89909692018-05-30 14:11:19 -0700390 std::lock_guard<std::mutex> _l(gDefaultServiceManagerLock);
391 if (gDefaultServiceManager != nullptr) {
392 return gDefaultServiceManager;
Yifan Hong8fb656b2017-03-16 14:30:40 -0700393 }
Steven Moreland405d7612017-04-07 20:31:22 -0700394
Yifan Hong8fb656b2017-03-16 14:30:40 -0700395 if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
396 // HwBinder not available on this device or not accessible to
397 // this process.
398 return nullptr;
399 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000400
Devin Moore50ced9f2024-03-26 22:00:23 +0000401 if (!isHidlSupported()) {
402 // hwservicemanager is not available on this device.
403 LOG(WARNING) << "hwservicemanager is not supported on the device.";
404 gDefaultServiceManager = sp<NoHwServiceManager>::make();
405 return gDefaultServiceManager;
406 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000407
Steven Moreland89909692018-05-30 14:11:19 -0700408 while (gDefaultServiceManager == nullptr) {
409 gDefaultServiceManager =
410 fromBinder<IServiceManager1_2, BpHwServiceManager, BnHwServiceManager>(
411 ProcessState::self()->getContextObject(nullptr));
412 if (gDefaultServiceManager == nullptr) {
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000413 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700414 sleep(1);
Yifan Hong8fb656b2017-03-16 14:30:40 -0700415 }
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700416 }
417 }
418
Steven Moreland89909692018-05-30 14:11:19 -0700419 return gDefaultServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700420}
421
Elliott Hughes19306142018-10-26 13:13:04 -0700422static std::vector<std::string> findFiles(const std::string& path, const std::string& prefix,
423 const std::string& suffix) {
Steven Moreland0091c092017-01-20 23:15:18 +0000424 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
425 if (!dir) return {};
426
427 std::vector<std::string> results{};
428
429 dirent* dp;
430 while ((dp = readdir(dir.get())) != nullptr) {
431 std::string name = dp->d_name;
432
Steven Moreland8092aa02018-10-12 15:54:56 -0700433 if (base::StartsWith(name, prefix) && base::EndsWith(name, suffix)) {
Steven Moreland0091c092017-01-20 23:15:18 +0000434 results.push_back(name);
435 }
436 }
437
438 return results;
439}
440
Steven Morelandccc3a972020-02-26 16:38:31 -0800441static bool matchPackageName(const std::string& lib, std::string* matchedName,
442 std::string* implName) {
443#define RE_COMPONENT "[a-zA-Z_][a-zA-Z_0-9]*"
444#define RE_PATH RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
445 static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
446#undef RE_PATH
447#undef RE_COMPONENT
448
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800449 std::smatch match;
450 if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
451 *matchedName = match.str(1) + "::I*";
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700452 *implName = match.str(2);
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800453 return true;
454 }
455 return false;
456}
457
Yifan Hong7f49f592017-02-03 15:11:44 -0800458static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
Yifan Hongdeacf142018-07-10 17:33:34 -0700459 if (kIsRecovery) {
460 // No hwservicemanager in recovery.
461 return;
462 }
463
Steven Moreland2a2678e2017-07-21 18:07:38 -0700464 sp<IServiceManager1_0> binderizedManager = defaultServiceManager();
Yifan Hong7f49f592017-02-03 15:11:44 -0800465 if (binderizedManager == nullptr) {
466 LOG(WARNING) << "Could not registerReference for "
467 << interfaceName << "/" << instanceName
468 << ": null binderized manager.";
469 return;
470 }
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700471 auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
Yifan Hong7f49f592017-02-03 15:11:44 -0800472 if (!ret.isOk()) {
473 LOG(WARNING) << "Could not registerReference for "
474 << interfaceName << "/" << instanceName
475 << ": " << ret.description();
Steven Moreland0aeaa782017-03-22 08:11:07 -0700476 return;
Yifan Hong7f49f592017-02-03 15:11:44 -0800477 }
Steven Morelande681aa52017-02-15 16:22:37 -0800478 LOG(VERBOSE) << "Successfully registerReference for "
479 << interfaceName << "/" << instanceName;
Yifan Hong7f49f592017-02-03 15:11:44 -0800480}
481
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700482using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
483static inline void fetchPidsForPassthroughLibraries(
484 std::map<std::string, InstanceDebugInfo>* infos) {
485 static const std::string proc = "/proc/";
486
487 std::map<std::string, std::set<pid_t>> pids;
488 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
489 if (!dir) return;
490 dirent* dp;
491 while ((dp = readdir(dir.get())) != nullptr) {
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700492 pid_t pid = strtoll(dp->d_name, nullptr, 0);
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700493 if (pid == 0) continue;
494 std::string mapsPath = proc + dp->d_name + "/maps";
495 std::ifstream ifs{mapsPath};
496 if (!ifs.is_open()) continue;
497
498 for (std::string line; std::getline(ifs, line);) {
499 // The last token of line should look like
500 // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
501 // Use some simple filters to ignore bad lines before extracting libFileName
502 // and checking the key in info to make parsing faster.
503 if (line.back() != 'o') continue;
504 if (line.rfind('@') == std::string::npos) continue;
505
506 auto spacePos = line.rfind(' ');
507 if (spacePos == std::string::npos) continue;
508 auto libFileName = line.substr(spacePos + 1);
509 auto it = infos->find(libFileName);
510 if (it == infos->end()) continue;
511 pids[libFileName].insert(pid);
512 }
513 }
514 for (auto& pair : *infos) {
515 pair.second.clientPids =
516 std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
517 }
518}
519
Steven Moreland2a2678e2017-07-21 18:07:38 -0700520struct PassthroughServiceManager : IServiceManager1_1 {
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -0700521 static void openLibs(
522 const std::string& fqName,
523 const std::function<bool /* continue */ (void* /* handle */, const std::string& /* lib */,
524 const std::string& /* sym */)>& eachLib) {
Steven Moreland819c05d2017-04-06 17:24:22 -0700525 //fqName looks like android.hardware.foo@1.0::IFoo
Steven Moreland519306f2017-06-06 17:14:12 -0700526 size_t idx = fqName.find("::");
Steven Moreland819c05d2017-04-06 17:24:22 -0700527
528 if (idx == std::string::npos ||
Steven Moreland519306f2017-06-06 17:14:12 -0700529 idx + strlen("::") + 1 >= fqName.size()) {
Steven Moreland337e6b62017-01-18 17:25:13 -0800530 LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
Steven Moreland519306f2017-06-06 17:14:12 -0700531 return;
Steven Moreland337e6b62017-01-18 17:25:13 -0800532 }
533
Steven Moreland519306f2017-06-06 17:14:12 -0700534 std::string packageAndVersion = fqName.substr(0, idx);
535 std::string ifaceName = fqName.substr(idx + strlen("::"));
Steven Moreland819c05d2017-04-06 17:24:22 -0700536
537 const std::string prefix = packageAndVersion + "-impl";
538 const std::string sym = "HIDL_FETCH_" + ifaceName;
Steven Moreland348802d2017-02-23 12:48:55 -0800539
Steven Moreland77f4c852017-10-12 11:05:53 -0700540 constexpr int dlMode = RTLD_LAZY;
541 void* handle = nullptr;
Steven Moreland337e6b62017-01-18 17:25:13 -0800542
Steven Morelanda29905c2017-03-01 10:42:35 -0800543 dlerror(); // clear
544
Jooyung Han219106c2020-07-17 15:01:19 +0900545 static std::string halLibPathVndkSp = details::getVndkSpHwPath();
Justin Yun6a323ed2018-10-18 18:41:56 +0900546 std::vector<std::string> paths = {
547 HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, halLibPathVndkSp,
548#ifndef __ANDROID_VNDK__
549 HAL_LIBRARY_PATH_SYSTEM,
550#endif
551 };
Steven Moreland77f4c852017-10-12 11:05:53 -0700552
Steven Morelandb939e7e2020-07-08 01:04:23 +0000553 if (details::isTrebleTestingOverride()) {
Steven Moreland77f4c852017-10-12 11:05:53 -0700554 // Load HAL implementations that are statically linked
555 handle = dlopen(nullptr, dlMode);
556 if (handle == nullptr) {
557 const char* error = dlerror();
558 LOG(ERROR) << "Failed to dlopen self: "
559 << (error == nullptr ? "unknown error" : error);
560 } else if (!eachLib(handle, "SELF", sym)) {
561 return;
562 }
Steven Morelandf7dea692017-07-14 12:49:28 -0700563 }
Steven Moreland77f4c852017-10-12 11:05:53 -0700564
Steven Morelandf7dea692017-07-14 12:49:28 -0700565 for (const std::string& path : paths) {
Elliott Hughes19306142018-10-26 13:13:04 -0700566 std::vector<std::string> libs = findFiles(path, prefix, ".so");
Steven Moreland0091c092017-01-20 23:15:18 +0000567
Steven Moreland0091c092017-01-20 23:15:18 +0000568 for (const std::string &lib : libs) {
Steven Moreland348802d2017-02-23 12:48:55 -0800569 const std::string fullPath = path + lib;
570
Yifan Hongdeacf142018-07-10 17:33:34 -0700571 if (kIsRecovery || path == HAL_LIBRARY_PATH_SYSTEM) {
Jiyong Park3ab546c2017-04-06 20:28:07 +0900572 handle = dlopen(fullPath.c_str(), dlMode);
Steven Moreland65c00cb2017-10-12 11:35:22 -0700573 } else {
Steven Moreland2056cf32019-09-17 17:41:02 -0700574#if !defined(__ANDROID_RECOVERY__) && defined(__ANDROID__)
Steven Moreland65c00cb2017-10-12 11:35:22 -0700575 handle = android_load_sphal_library(fullPath.c_str(), dlMode);
Jerry Zhang86ae9992018-05-30 17:11:09 -0700576#endif
Jiyong Park3ab546c2017-04-06 20:28:07 +0900577 }
578
Steven Moreland348802d2017-02-23 12:48:55 -0800579 if (handle == nullptr) {
580 const char* error = dlerror();
581 LOG(ERROR) << "Failed to dlopen " << lib << ": "
582 << (error == nullptr ? "unknown error" : error);
583 continue;
Steven Moreland0091c092017-01-20 23:15:18 +0000584 }
Steven Moreland348802d2017-02-23 12:48:55 -0800585
Steven Moreland519306f2017-06-06 17:14:12 -0700586 if (!eachLib(handle, lib, sym)) {
587 return;
Steven Moreland348802d2017-02-23 12:48:55 -0800588 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800589 }
590 }
Steven Moreland519306f2017-06-06 17:14:12 -0700591 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800592
Steven Moreland519306f2017-06-06 17:14:12 -0700593 Return<sp<IBase>> get(const hidl_string& fqName,
594 const hidl_string& name) override {
595 sp<IBase> ret = nullptr;
Devin Mooree1973ce2022-04-15 20:54:03 +0000596 // This is required to run without hwservicemanager while we have
597 // passthrough HIDL services. Once the passthrough HIDL services have
598 // been removed, the PassthroughServiceManager will no longer be needed.
Devin Moore22e6f1e2023-11-22 22:29:54 +0000599 if (!isHidlSupported() && isServiceManager(fqName)) {
Devin Mooree1973ce2022-04-15 20:54:03 +0000600 return defaultServiceManager1_2();
601 }
Steven Moreland519306f2017-06-06 17:14:12 -0700602
603 openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
604 IBase* (*generator)(const char* name);
605 *(void **)(&generator) = dlsym(handle, sym.c_str());
606 if(!generator) {
607 const char* error = dlerror();
Steven Morelandedd49122021-02-17 22:41:51 +0000608 LOG(ERROR) << "Passthrough lookup opened " << lib << " but could not find symbol "
609 << sym << ": " << (error == nullptr ? "unknown error" : error)
610 << ". Keeping library open.";
611
612 // dlclose too problematic in multi-threaded environment
613 // dlclose(handle);
614
615 return true; // continue
Steven Moreland519306f2017-06-06 17:14:12 -0700616 }
617
618 ret = (*generator)(name.c_str());
619
620 if (ret == nullptr) {
Steven Morelandedd49122021-02-17 22:41:51 +0000621 LOG(ERROR) << "Could not find instance '" << name.c_str() << "' in library " << lib
622 << ". Keeping library open.";
623
624 // dlclose too problematic in multi-threaded environment
625 // dlclose(handle);
626
627 // this module doesn't provide this particular instance
628 return true; // continue
Steven Moreland519306f2017-06-06 17:14:12 -0700629 }
630
Steven Morelande69e8d32018-03-14 10:55:42 -0700631 // Actual fqname might be a subclass.
632 // This assumption is tested in vts_treble_vintf_test
633 using ::android::hardware::details::getDescriptor;
634 std::string actualFqName = getDescriptor(ret.get());
635 CHECK(actualFqName.size() > 0);
636 registerReference(actualFqName, name);
Steven Moreland519306f2017-06-06 17:14:12 -0700637 return false;
638 });
639
640 return ret;
Steven Moreland337e6b62017-01-18 17:25:13 -0800641 }
642
Martijn Coenen67a02492017-03-06 13:04:48 +0100643 Return<bool> add(const hidl_string& /* name */,
Steven Moreland337e6b62017-01-18 17:25:13 -0800644 const sp<IBase>& /* service */) override {
645 LOG(FATAL) << "Cannot register services with passthrough service manager.";
646 return false;
647 }
648
Steven Morelandc601c5f2017-04-06 09:26:07 -0700649 Return<Transport> getTransport(const hidl_string& /* fqName */,
650 const hidl_string& /* name */) {
651 LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
652 return Transport::EMPTY;
653 }
654
Yifan Hong705e5da2017-03-02 16:59:39 -0800655 Return<void> list(list_cb /* _hidl_cb */) override {
656 LOG(FATAL) << "Cannot list services with passthrough service manager.";
Steven Moreland337e6b62017-01-18 17:25:13 -0800657 return Void();
658 }
659 Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
660 listByInterface_cb /* _hidl_cb */) override {
661 // TODO: add this functionality
662 LOG(FATAL) << "Cannot list services with passthrough service manager.";
663 return Void();
664 }
665
666 Return<bool> registerForNotifications(const hidl_string& /* fqName */,
667 const hidl_string& /* name */,
668 const sp<IServiceNotification>& /* callback */) override {
669 // This makes no sense.
670 LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
671 return false;
672 }
673
Yifan Hong705e5da2017-03-02 16:59:39 -0800674 Return<void> debugDump(debugDump_cb _hidl_cb) override {
675 using Arch = ::android::hidl::base::V1_0::DebugInfo::Architecture;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700676 using std::literals::string_literals::operator""s;
Jooyung Han219106c2020-07-17 15:01:19 +0900677 static std::string halLibPathVndkSp64 = details::getVndkSpHwPath("lib64");
678 static std::string halLibPathVndkSp32 = details::getVndkSpHwPath("lib");
Jiyong Park56eb1492017-08-04 16:16:13 +0900679 static std::vector<std::pair<Arch, std::vector<const char*>>> sAllPaths{
680 {Arch::IS_64BIT,
Justin Yun6a323ed2018-10-18 18:41:56 +0900681 {
682 HAL_LIBRARY_PATH_ODM_64BIT, HAL_LIBRARY_PATH_VENDOR_64BIT,
683 halLibPathVndkSp64.c_str(),
684#ifndef __ANDROID_VNDK__
685 HAL_LIBRARY_PATH_SYSTEM_64BIT,
686#endif
687 }},
Jiyong Park56eb1492017-08-04 16:16:13 +0900688 {Arch::IS_32BIT,
Justin Yun6a323ed2018-10-18 18:41:56 +0900689 {
690 HAL_LIBRARY_PATH_ODM_32BIT, HAL_LIBRARY_PATH_VENDOR_32BIT,
691 halLibPathVndkSp32.c_str(),
692#ifndef __ANDROID_VNDK__
693 HAL_LIBRARY_PATH_SYSTEM_32BIT,
694#endif
695 }}};
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700696 std::map<std::string, InstanceDebugInfo> map;
Yifan Hong705e5da2017-03-02 16:59:39 -0800697 for (const auto &pair : sAllPaths) {
698 Arch arch = pair.first;
699 for (const auto &path : pair.second) {
Elliott Hughes19306142018-10-26 13:13:04 -0700700 std::vector<std::string> libs = findFiles(path, "", ".so");
Yifan Hong705e5da2017-03-02 16:59:39 -0800701 for (const std::string &lib : libs) {
702 std::string matchedName;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700703 std::string implName;
704 if (matchPackageName(lib, &matchedName, &implName)) {
705 std::string instanceName{"* ("s + path + ")"s};
706 if (!implName.empty()) instanceName += " ("s + implName + ")"s;
707 map.emplace(path + lib, InstanceDebugInfo{.interfaceName = matchedName,
708 .instanceName = instanceName,
709 .clientPids = {},
710 .arch = arch});
Yifan Hong705e5da2017-03-02 16:59:39 -0800711 }
712 }
713 }
714 }
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700715 fetchPidsForPassthroughLibraries(&map);
716 hidl_vec<InstanceDebugInfo> vec;
717 vec.resize(map.size());
718 size_t idx = 0;
719 for (auto&& pair : map) {
720 vec[idx++] = std::move(pair.second);
721 }
Yifan Hong705e5da2017-03-02 16:59:39 -0800722 _hidl_cb(vec);
Yifan Hong7f49f592017-02-03 15:11:44 -0800723 return Void();
724 }
725
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700726 Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
Yifan Hong7f49f592017-02-03 15:11:44 -0800727 // This makes no sense.
728 LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
729 << "Call it on defaultServiceManager() instead.";
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800730 return Void();
731 }
732
Steven Moreland2a2678e2017-07-21 18:07:38 -0700733 Return<bool> unregisterForNotifications(const hidl_string& /* fqName */,
734 const hidl_string& /* name */,
735 const sp<IServiceNotification>& /* callback */) override {
736 // This makes no sense.
737 LOG(FATAL) << "Cannot unregister for notifications with passthrough service manager.";
738 return false;
739 }
740
Steven Moreland337e6b62017-01-18 17:25:13 -0800741};
742
Steven Moreland2a2678e2017-07-21 18:07:38 -0700743sp<IServiceManager1_0> getPassthroughServiceManager() {
744 return getPassthroughServiceManager1_1();
745}
746sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
Steven Moreland337e6b62017-01-18 17:25:13 -0800747 static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
748 return manager;
749}
750
Steven Moreland92b247c2019-08-21 14:53:11 -0700751std::vector<std::string> getAllHalInstanceNames(const std::string& descriptor) {
752 std::vector<std::string> ret;
753 auto sm = defaultServiceManager1_2();
754 sm->listManifestByInterface(descriptor, [&](const auto& instances) {
755 ret.reserve(instances.size());
756 for (const auto& i : instances) {
757 ret.push_back(i);
758 }
759 });
760 return ret;
761}
762
Steven Morelandcbefd352017-01-23 20:29:05 -0800763namespace details {
764
Steven Moreland519306f2017-06-06 17:14:12 -0700765void preloadPassthroughService(const std::string &descriptor) {
766 PassthroughServiceManager::openLibs(descriptor,
767 [&](void* /* handle */, const std::string& /* lib */, const std::string& /* sym */) {
768 // do nothing
769 return true; // open all libs
770 });
771}
772
Steven Morelandcbefd352017-01-23 20:29:05 -0800773struct Waiter : IServiceNotification {
Martijn Coenen773609e2017-10-24 09:57:53 +0200774 Waiter(const std::string& interface, const std::string& instanceName,
775 const sp<IServiceManager1_1>& sm) : mInterfaceName(interface),
776 mInstanceName(instanceName), mSm(sm) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100777 }
778
779 void onFirstRef() override {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200780 // If this process only has one binder thread, and we're calling wait() from
781 // that thread, it will block forever because we hung up the one and only
782 // binder thread on a condition variable that can only be notified by an
783 // incoming binder call.
Tobias Lindskog88e886f2018-01-05 10:32:43 +0100784 if (IPCThreadState::self()->isOnlyBinderThread()) {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200785 LOG(WARNING) << "Can't efficiently wait for " << mInterfaceName << "/"
786 << mInstanceName << ", because we are called from "
787 << "the only binder thread in this process.";
788 return;
789 }
790
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100791 Return<bool> ret = mSm->registerForNotifications(mInterfaceName, mInstanceName, this);
Martijn Coenen773609e2017-10-24 09:57:53 +0200792
793 if (!ret.isOk()) {
794 LOG(ERROR) << "Transport error, " << ret.description()
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100795 << ", during notification registration for " << mInterfaceName << "/"
796 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200797 return;
798 }
799
800 if (!ret) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100801 LOG(ERROR) << "Could not register for notifications for " << mInterfaceName << "/"
802 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200803 return;
804 }
805
806 mRegisteredForNotifications = true;
807 }
808
809 ~Waiter() {
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100810 if (!mDoneCalled) {
811 LOG(FATAL)
812 << "Waiter still registered for notifications, call done() before dropping ref!";
Martijn Coenen773609e2017-10-24 09:57:53 +0200813 }
814 }
815
Steven Morelandcbefd352017-01-23 20:29:05 -0800816 Return<void> onRegistration(const hidl_string& /* fqName */,
817 const hidl_string& /* name */,
818 bool /* preexisting */) override {
819 std::unique_lock<std::mutex> lock(mMutex);
820 if (mRegistered) {
821 return Void();
822 }
823 mRegistered = true;
824 lock.unlock();
825
826 mCondition.notify_one();
827 return Void();
828 }
829
Steven Moreland0771d8a2018-05-09 13:29:14 -0700830 void wait(bool timeout) {
Steven Moreland49605102017-03-28 09:33:06 -0700831 using std::literals::chrono_literals::operator""s;
832
Martijn Coenen773609e2017-10-24 09:57:53 +0200833 if (!mRegisteredForNotifications) {
834 // As an alternative, just sleep for a second and return
835 LOG(WARNING) << "Waiting one second for " << mInterfaceName << "/" << mInstanceName;
836 sleep(1);
837 return;
838 }
839
Steven Morelandcbefd352017-01-23 20:29:05 -0800840 std::unique_lock<std::mutex> lock(mMutex);
Steven Moreland0771d8a2018-05-09 13:29:14 -0700841 do {
Steven Moreland49605102017-03-28 09:33:06 -0700842 mCondition.wait_for(lock, 1s, [this]{
843 return mRegistered;
844 });
845
846 if (mRegistered) {
847 break;
848 }
849
Steven Moreland0771d8a2018-05-09 13:29:14 -0700850 LOG(WARNING) << "Waited one second for " << mInterfaceName << "/" << mInstanceName;
851 } while (!timeout);
Steven Morelandcbefd352017-01-23 20:29:05 -0800852 }
853
Martijn Coenen773609e2017-10-24 09:57:53 +0200854 // Be careful when using this; after calling reset(), you must always try to retrieve
855 // the corresponding service before blocking on the waiter; otherwise, you might run
856 // into a race-condition where the service has just (re-)registered, you clear the state
857 // here, and subsequently calling waiter->wait() will block forever.
858 void reset() {
859 std::unique_lock<std::mutex> lock(mMutex);
860 mRegistered = false;
861 }
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100862
863 // done() must be called before dropping the last strong ref to the Waiter, to make
864 // sure we can properly unregister with hwservicemanager.
865 void done() {
866 if (mRegisteredForNotifications) {
867 if (!mSm->unregisterForNotifications(mInterfaceName, mInstanceName, this)
868 .withDefault(false)) {
869 LOG(ERROR) << "Could not unregister service notification for " << mInterfaceName
870 << "/" << mInstanceName << ".";
871 } else {
872 mRegisteredForNotifications = false;
873 }
874 }
875 mDoneCalled = true;
876 }
877
878 private:
Martijn Coenen773609e2017-10-24 09:57:53 +0200879 const std::string mInterfaceName;
880 const std::string mInstanceName;
Steven Morelandad1f9922018-10-02 19:37:05 -0700881 sp<IServiceManager1_1> mSm;
Steven Morelandcbefd352017-01-23 20:29:05 -0800882 std::mutex mMutex;
883 std::condition_variable mCondition;
884 bool mRegistered = false;
Martijn Coenen773609e2017-10-24 09:57:53 +0200885 bool mRegisteredForNotifications = false;
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100886 bool mDoneCalled = false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800887};
888
889void waitForHwService(
890 const std::string &interface, const std::string &instanceName) {
Martijn Coenen773609e2017-10-24 09:57:53 +0200891 sp<Waiter> waiter = new Waiter(interface, instanceName, defaultServiceManager1_1());
Steven Moreland0771d8a2018-05-09 13:29:14 -0700892 waiter->wait(false /* timeout */);
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100893 waiter->done();
Martijn Coenen773609e2017-10-24 09:57:53 +0200894}
Steven Morelandcbefd352017-01-23 20:29:05 -0800895
Martijn Coenen773609e2017-10-24 09:57:53 +0200896// Prints relevant error/warning messages for error return values from
897// details::canCastInterface(), both transaction errors (!castReturn.isOk())
898// as well as actual cast failures (castReturn.isOk() && castReturn = false).
899// Returns 'true' if the error is non-fatal and it's useful to retry
900bool handleCastError(const Return<bool>& castReturn, const std::string& descriptor,
901 const std::string& instance) {
902 if (castReturn.isOk()) {
903 if (castReturn) {
904 details::logAlwaysFatal("Successful cast value passed into handleCastError.");
905 }
906 // This should never happen, and there's not really a point in retrying.
907 ALOGE("getService: received incompatible service (bug in hwservicemanager?) for "
908 "%s/%s.", descriptor.c_str(), instance.c_str());
909 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800910 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200911 if (castReturn.isDeadObject()) {
912 ALOGW("getService: found dead hwbinder service for %s/%s.", descriptor.c_str(),
913 instance.c_str());
914 return true;
Steven Morelandcbefd352017-01-23 20:29:05 -0800915 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200916 // This can happen due to:
917 // 1) No SELinux permissions
918 // 2) Other transaction failure (no buffer space, kernel error)
919 // The first isn't recoverable, but the second is.
920 // Since we can't yet differentiate between the two, and clients depend
921 // on us not blocking in case 1), treat this as a fatal error for now.
922 ALOGW("getService: unable to call into hwbinder service for %s/%s.",
923 descriptor.c_str(), instance.c_str());
924 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800925}
926
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200927sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
928 const std::string& instance,
929 bool retry, bool getStub) {
Steven Moreland84fe49e2019-08-20 17:47:26 +0000930 using Transport = IServiceManager1_0::Transport;
Martijn Coenend35678f2018-03-07 09:51:01 +0100931 sp<Waiter> waiter;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200932
Yifan Hongdeacf142018-07-10 17:33:34 -0700933 sp<IServiceManager1_1> sm;
934 Transport transport = Transport::EMPTY;
935 if (kIsRecovery) {
Yifan Hongdeacf142018-07-10 17:33:34 -0700936 transport = Transport::PASSTHROUGH;
Yifan Hongdeacf142018-07-10 17:33:34 -0700937 } else {
938 sm = defaultServiceManager1_1();
939 if (sm == nullptr) {
940 ALOGE("getService: defaultServiceManager() is null");
941 return nullptr;
942 }
943
944 Return<Transport> transportRet = sm->getTransport(descriptor, instance);
945
946 if (!transportRet.isOk()) {
947 ALOGE("getService: defaultServiceManager()->getTransport returns %s",
948 transportRet.description().c_str());
949 return nullptr;
950 }
951 transport = transportRet;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200952 }
953
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200954 const bool vintfHwbinder = (transport == Transport::HWBINDER);
955 const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
Steven Moreland84fe49e2019-08-20 17:47:26 +0000956 const bool trebleTestingOverride = isTrebleTestingOverride();
Steven Morelandf47cdf72021-04-07 22:13:13 +0000957 const bool allowLegacy = !kEnforceVintfManifest || (trebleTestingOverride && isDebuggable());
Steven Moreland84fe49e2019-08-20 17:47:26 +0000958 const bool vintfLegacy = (transport == Transport::EMPTY) && allowLegacy;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200959
Steven Moreland84fe49e2019-08-20 17:47:26 +0000960 if (!kEnforceVintfManifest) {
961 ALOGE("getService: Potential race detected. The VINTF manifest is not being enforced. If "
962 "a HAL server has a delay in starting and it is not in the manifest, it will not be "
963 "retrieved. Please make sure all HALs on this device are in the VINTF manifest and "
964 "enable PRODUCT_ENFORCE_VINTF_MANIFEST on this device (this is also enabled by "
965 "PRODUCT_FULL_TREBLE). PRODUCT_ENFORCE_VINTF_MANIFEST will ensure that no race "
966 "condition is possible here.");
Steven Morelandaadec3c2019-08-22 17:06:48 -0700967 sleep(1);
Steven Moreland84fe49e2019-08-20 17:47:26 +0000968 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200969
Steven Moreland76371242018-04-19 17:11:39 -0700970 for (int tries = 0; !getStub && (vintfHwbinder || vintfLegacy); tries++) {
971 if (waiter == nullptr && tries > 0) {
Martijn Coenend35678f2018-03-07 09:51:01 +0100972 waiter = new Waiter(descriptor, instance, sm);
973 }
Steven Moreland76371242018-04-19 17:11:39 -0700974 if (waiter != nullptr) {
975 waiter->reset(); // don't reorder this -- see comments on reset()
976 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200977 Return<sp<IBase>> ret = sm->get(descriptor, instance);
978 if (!ret.isOk()) {
979 ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.",
980 ret.description().c_str(), descriptor.c_str(), instance.c_str());
981 break;
982 }
983 sp<IBase> base = ret;
Martijn Coenen773609e2017-10-24 09:57:53 +0200984 if (base != nullptr) {
985 Return<bool> canCastRet =
986 details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
987
988 if (canCastRet.isOk() && canCastRet) {
Steven Moreland76371242018-04-19 17:11:39 -0700989 if (waiter != nullptr) {
990 waiter->done();
991 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200992 return base; // still needs to be wrapped by Bp class.
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200993 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200994
995 if (!handleCastError(canCastRet, descriptor, instance)) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200996 }
997
Martijn Coenen773609e2017-10-24 09:57:53 +0200998 // In case of legacy or we were not asked to retry, don't.
999 if (vintfLegacy || !retry) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001000
Steven Moreland76371242018-04-19 17:11:39 -07001001 if (waiter != nullptr) {
1002 ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
Steven Moreland0771d8a2018-05-09 13:29:14 -07001003 waiter->wait(true /* timeout */);
Steven Moreland76371242018-04-19 17:11:39 -07001004 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001005 }
1006
Martijn Coenend35678f2018-03-07 09:51:01 +01001007 if (waiter != nullptr) {
1008 waiter->done();
1009 }
Martijn Coenen3fa15c22018-02-10 11:30:00 +01001010
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001011 if (getStub || vintfPassthru || vintfLegacy) {
Steven Moreland84fe49e2019-08-20 17:47:26 +00001012 const sp<IServiceManager1_0> pm = getPassthroughServiceManager();
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001013 if (pm != nullptr) {
1014 sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
1015 if (!getStub || trebleTestingOverride) {
1016 base = wrapPassthrough(base);
1017 }
1018 return base;
1019 }
1020 }
1021
1022 return nullptr;
1023}
1024
Steven Morelandbb9eb2a2018-10-11 12:10:01 -07001025status_t registerAsServiceInternal(const sp<IBase>& service, const std::string& name) {
1026 if (service == nullptr) {
1027 return UNEXPECTED_NULL;
1028 }
1029
1030 sp<IServiceManager1_2> sm = defaultServiceManager1_2();
1031 if (sm == nullptr) {
1032 return INVALID_OPERATION;
1033 }
1034
Steven Moreland84fe49e2019-08-20 17:47:26 +00001035 const std::string descriptor = getDescriptor(service.get());
1036
1037 if (kEnforceVintfManifest && !isTrebleTestingOverride()) {
1038 using Transport = IServiceManager1_0::Transport;
Steven Moreland7d1b0732021-01-21 22:47:40 +00001039 Return<Transport> transport = sm->getTransport(descriptor, name);
1040
1041 if (!transport.isOk()) {
1042 LOG(ERROR) << "Could not get transport for " << descriptor << "/" << name << ": "
1043 << transport.description();
1044 return UNKNOWN_ERROR;
1045 }
Steven Moreland84fe49e2019-08-20 17:47:26 +00001046
1047 if (transport != Transport::HWBINDER) {
1048 LOG(ERROR) << "Service " << descriptor << "/" << name
1049 << " must be in VINTF manifest in order to register/get.";
1050 return UNKNOWN_ERROR;
1051 }
1052 }
1053
Steven Morelandbb9eb2a2018-10-11 12:10:01 -07001054 bool registered = false;
1055 Return<void> ret = service->interfaceChain([&](const auto& chain) {
1056 registered = sm->addWithChain(name.c_str(), service, chain).withDefault(false);
1057 });
1058
1059 if (!ret.isOk()) {
1060 LOG(ERROR) << "Could not retrieve interface chain: " << ret.description();
1061 }
1062
1063 if (registered) {
Steven Moreland84fe49e2019-08-20 17:47:26 +00001064 onRegistrationImpl(descriptor, name);
Steven Morelandbb9eb2a2018-10-11 12:10:01 -07001065 }
1066
1067 return registered ? OK : UNKNOWN_ERROR;
1068}
1069
Bernhard Rosenkränzer0c28fd22018-06-04 16:01:47 +02001070} // namespace details
Steven Morelandcbefd352017-01-23 20:29:05 -08001071
Bernhard Rosenkränzer0c28fd22018-06-04 16:01:47 +02001072} // namespace hardware
1073} // namespace android