blob: 880789813eb0024c8bdc452b7b9ac9faeaa57440 [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
Steven Morelandbb9eb2a2018-10-11 12:10:01 -070074static void waitForHwServiceManager() {
Steven Moreland2056cf32019-09-17 17:41:02 -070075 // TODO(b/31559095): need bionic host so that we can use 'prop_info' returned
76 // from WaitForProperty
77#ifdef __ANDROID__
78 static const char* kHwServicemanagerReadyProperty = "hwservicemanager.ready";
79
Steven Morelandc1cee2c2017-03-24 16:23:11 +000080 using std::literals::chrono_literals::operator""s;
81
Steven Moreland2056cf32019-09-17 17:41:02 -070082 using android::base::WaitForProperty;
Steven Morelandc1cee2c2017-03-24 16:23:11 +000083 while (!WaitForProperty(kHwServicemanagerReadyProperty, "true", 1s)) {
84 LOG(WARNING) << "Waited for hwservicemanager.ready for a second, waiting another...";
85 }
Steven Moreland2056cf32019-09-17 17:41:02 -070086#endif // __ANDROID__
Steven Morelandc1cee2c2017-03-24 16:23:11 +000087}
88
Steven Morelandbb9eb2a2018-10-11 12:10:01 -070089static std::string binaryName() {
Steven Moreland405d7612017-04-07 20:31:22 -070090 std::ifstream ifs("/proc/self/cmdline");
91 std::string cmdline;
Steven Morelandd682c0e2020-07-21 17:47:32 +000092 if (!ifs) {
Steven Moreland405d7612017-04-07 20:31:22 -070093 return "";
94 }
95 ifs >> cmdline;
96
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -070097 size_t idx = cmdline.rfind('/');
Steven Moreland405d7612017-04-07 20:31:22 -070098 if (idx != std::string::npos) {
99 cmdline = cmdline.substr(idx + 1);
100 }
101
102 return cmdline;
103}
104
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700105static std::string packageWithoutVersion(const std::string& packageAndVersion) {
Steven Moreland7d09a402018-04-06 10:44:05 -0700106 size_t at = packageAndVersion.find('@');
107 if (at == std::string::npos) return packageAndVersion;
108 return packageAndVersion.substr(0, at);
109}
110
Steven Morelandd682c0e2020-07-21 17:47:32 +0000111__attribute__((noinline)) static void tryShortenProcessName(const std::string& descriptor) {
Steven Moreland7d09a402018-04-06 10:44:05 -0700112 const static std::string kTasks = "/proc/self/task/";
113
114 // make sure that this binary name is in the same package
Steven Moreland405d7612017-04-07 20:31:22 -0700115 std::string processName = binaryName();
116
Steven Moreland7d09a402018-04-06 10:44:05 -0700117 // e.x. android.hardware.foo is this package
Steven Moreland8092aa02018-10-12 15:54:56 -0700118 if (!base::StartsWith(packageWithoutVersion(processName), packageWithoutVersion(descriptor))) {
Steven Moreland405d7612017-04-07 20:31:22 -0700119 return;
120 }
121
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700122 // e.x. android.hardware.module.foo@1.2::IFoo -> foo@1.2
123 size_t lastDot = descriptor.rfind('.');
Steven Moreland7d09a402018-04-06 10:44:05 -0700124 if (lastDot == std::string::npos) return;
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700125 size_t secondDot = descriptor.rfind('.', lastDot - 1);
Steven Moreland7d09a402018-04-06 10:44:05 -0700126 if (secondDot == std::string::npos) return;
Steven Moreland405d7612017-04-07 20:31:22 -0700127
Steven Moreland7d09a402018-04-06 10:44:05 -0700128 std::string newName = processName.substr(secondDot + 1, std::string::npos);
129 ALOGI("Removing namespace from process name %s to %s.", processName.c_str(), newName.c_str());
130
131 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kTasks.c_str()), closedir);
132 if (dir == nullptr) return;
133
134 dirent* dp;
135 while ((dp = readdir(dir.get())) != nullptr) {
136 if (dp->d_type != DT_DIR) continue;
137 if (dp->d_name[0] == '.') continue;
138
139 std::fstream fs(kTasks + dp->d_name + "/comm");
Steven Morelandd682c0e2020-07-21 17:47:32 +0000140 if (!fs) {
Steven Moreland7d09a402018-04-06 10:44:05 -0700141 ALOGI("Could not rename process, failed read comm for %s.", dp->d_name);
142 continue;
143 }
144
145 std::string oldComm;
Steven Morelandd682c0e2020-07-21 17:47:32 +0000146 if (!(fs >> oldComm)) continue;
Steven Moreland7d09a402018-04-06 10:44:05 -0700147
148 // don't rename if it already has an explicit name
Steven Moreland8092aa02018-10-12 15:54:56 -0700149 if (base::StartsWith(descriptor, oldComm)) {
Steven Morelandd682c0e2020-07-21 17:47:32 +0000150 if (!fs.seekg(0, fs.beg)) continue;
Steven Moreland7d09a402018-04-06 10:44:05 -0700151 fs << newName;
152 }
Steven Moreland405d7612017-04-07 20:31:22 -0700153 }
Steven Moreland405d7612017-04-07 20:31:22 -0700154}
155
156namespace details {
157
Steven Morelandb939e7e2020-07-08 01:04:23 +0000158#ifdef ENFORCE_VINTF_MANIFEST
159static constexpr bool kEnforceVintfManifest = true;
160#else
161static constexpr bool kEnforceVintfManifest = false;
162#endif
163
Steven Moreland206d2812020-07-08 21:21:48 +0000164static bool* getTrebleTestingOverridePtr() {
165 static bool gTrebleTestingOverride = false;
166 return &gTrebleTestingOverride;
167}
Steven Morelandb939e7e2020-07-08 01:04:23 +0000168
169void setTrebleTestingOverride(bool testingOverride) {
Steven Moreland206d2812020-07-08 21:21:48 +0000170 *getTrebleTestingOverridePtr() = testingOverride;
Steven Morelandb939e7e2020-07-08 01:04:23 +0000171}
172
Steven Morelandf47cdf72021-04-07 22:13:13 +0000173static bool isDebuggable() {
174 static bool debuggable = base::GetBoolProperty("ro.debuggable", false);
175 return debuggable;
176}
177
Steven Morelandb939e7e2020-07-08 01:04:23 +0000178static inline bool isTrebleTestingOverride() {
Steven Moreland4acdab72022-08-09 16:27:46 +0000179 // return false early so we don't need to check the debuggable property
180 if (!*getTrebleTestingOverridePtr()) return false;
181
Steven Morelandf47cdf72021-04-07 22:13:13 +0000182 if (kEnforceVintfManifest && !isDebuggable()) {
Steven Morelandb939e7e2020-07-08 01:04:23 +0000183 // don't allow testing override in production
184 return false;
185 }
186
Steven Moreland4acdab72022-08-09 16:27:46 +0000187 return true;
Steven Morelandb939e7e2020-07-08 01:04:23 +0000188}
189
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700190static void onRegistrationImpl(const std::string& descriptor, const std::string& instanceName) {
Steven Moreland489e7572021-01-21 19:02:54 +0000191 LOG(INFO) << "Registered " << descriptor << "/" << instanceName;
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700192 tryShortenProcessName(descriptor);
193}
194
Steven Moreland911852c2020-05-11 10:51:26 -0700195// only used by prebuilts - should be able to remove
Steven Morelandbb9eb2a2018-10-11 12:10:01 -0700196void onRegistration(const std::string& packageName, const std::string& interfaceName,
197 const std::string& instanceName) {
198 return onRegistrationImpl(packageName + "::" + interfaceName, instanceName);
Steven Moreland405d7612017-04-07 20:31:22 -0700199}
200
201} // details
202
Steven Moreland2a2678e2017-07-21 18:07:38 -0700203sp<IServiceManager1_0> defaultServiceManager() {
Steven Moreland89909692018-05-30 14:11:19 -0700204 return defaultServiceManager1_2();
Steven Moreland2a2678e2017-07-21 18:07:38 -0700205}
206sp<IServiceManager1_1> defaultServiceManager1_1() {
Steven Moreland89909692018-05-30 14:11:19 -0700207 return defaultServiceManager1_2();
208}
Devin Mooree1973ce2022-04-15 20:54:03 +0000209static bool isServiceManager(const hidl_string& fqName) {
210 return fqName == IServiceManager1_0::descriptor || fqName == IServiceManager1_1::descriptor ||
211 fqName == IServiceManager1_2::descriptor;
212}
Devin Moore22e6f1e2023-11-22 22:29:54 +0000213
Devin Mooreadb13202023-12-04 17:04:27 +0000214static bool isHwServiceManagerInstalled() {
215 return access("/system_ext/bin/hwservicemanager", F_OK) == 0 ||
216 access("/system/system_ext/bin/hwservicemanager", F_OK) == 0 ||
217 access("/system/bin/hwservicemanager", F_OK) == 0;
218}
219
Devin Moore22e6f1e2023-11-22 22:29:54 +0000220bool isHidlSupported() {
Devin Mooreadb13202023-12-04 17:04:27 +0000221 if (!isHwServiceManagerInstalled()) {
222 return false;
223 }
Devin Moore22e6f1e2023-11-22 22:29:54 +0000224#ifdef __ANDROID__
Devin Moore22e6f1e2023-11-22 22:29:54 +0000225 static const char* kVendorApiProperty = "ro.vendor.api_level";
226 // HIDL and hwservicemanager are not supported in Android V+
Devin Moore4e0961b2024-03-26 20:30:08 +0000227 // This is also set with `max-level="8"` in the framework manifest fragment
228 // for android.hidl.manager. We don't check for android.hidl.manager to be
229 // declared through defaultServiceManager1_2() because the fake
230 // servicemaanger will say it is declared.
231 return android::base::GetIntProperty(kVendorApiProperty, 0) < __ANDROID_API_V__;
Devin Moore22e6f1e2023-11-22 22:29:54 +0000232#else
233 // No access to properties and no requirement for dropping HIDL support if
234 // this isn't Android
235 return true;
236#endif // __ANDROID__
Devin Mooree1973ce2022-04-15 20:54:03 +0000237}
238
239/*
240 * A replacement for hwservicemanager when it is not installed on a device.
241 *
242 * Clients in the framework need to continue supporting HIDL services through
243 * hwservicemanager for upgrading devices. Being unable to get an instance of
244 * hardware service manager is a hard error, so this implementation is returned
245 * to be able service the requests and tell clients there are no services
246 * registered.
247 */
Devin Moore2d2e4c02023-11-28 00:24:19 +0000248struct NoHwServiceManager : public IServiceManager1_2, hidl_death_recipient {
Devin Mooree1973ce2022-04-15 20:54:03 +0000249 Return<sp<IBase>> get(const hidl_string& fqName, const hidl_string&) override {
250 sp<IBase> ret = nullptr;
251
252 if (isServiceManager(fqName)) {
253 ret = defaultServiceManager1_2();
254 }
255 return ret;
256 }
257
258 Return<bool> add(const hidl_string& name, const sp<IBase>& /* service */) override {
259 LOG(INFO) << "Cannot add " << name << " without hwservicemanager";
260 return false;
261 }
262
263 Return<Transport> getTransport(const hidl_string& fqName, const hidl_string& name) {
Devin Moore0d309172023-11-28 00:20:32 +0000264 // We pretend like IServiceManager is declared for
265 // IServiceManager::getService to return this NoHwServiceManager
266 // instance
267 if (isServiceManager(fqName)) {
268 return Transport::HWBINDER;
269 }
Devin Mooree1973ce2022-04-15 20:54:03 +0000270 LOG(INFO) << "Trying to get transport of " << fqName << "/" << name
271 << " without hwservicemanager";
Devin Mooreadbf9a52023-06-06 23:07:08 +0000272 return Transport::EMPTY;
Devin Mooree1973ce2022-04-15 20:54:03 +0000273 }
274
275 Return<void> list(list_cb _hidl_cb) override {
276 _hidl_cb({});
277 LOG(INFO) << "Cannot list all services without hwservicemanager";
278 return Void();
279 }
280 Return<void> listByInterface(const hidl_string& fqName, listByInterface_cb _hidl_cb) override {
281 _hidl_cb({});
282 LOG(INFO) << "Cannot list service " << fqName << " without hwservicemanager";
283 return Void();
284 }
285
Devin Moore2d2e4c02023-11-28 00:24:19 +0000286 void serviceDied(uint64_t /* cookie */, const wp<IBase>& who) override {
287 sp<IBase> promoted = who.promote();
288 if (promoted) {
289 bool removed = false;
290 for (auto [name, callbacks] : mServiceNotifications) {
291 for (auto it = callbacks.begin(); it != callbacks.end();) {
292 if (interfacesEqual(*it, promoted)) {
293 callbacks.erase(it);
294 removed = true;
295 }
296 it++;
297 }
298 if (removed) return;
299 }
300 }
301 LOG(ERROR) << "Could not find a registered callback for a service who died. "
302 << "Service pointer: " << who.promote().get();
303 }
304
Devin Mooree1973ce2022-04-15 20:54:03 +0000305 Return<bool> registerForNotifications(const hidl_string& fqName, const hidl_string& name,
Devin Moore2d2e4c02023-11-28 00:24:19 +0000306 const sp<IServiceNotification>& callback) override {
307 LOG(INFO) << "Will not get any notifications for " << fqName << "/" << name
308 << " without hwservicemanager but keeping the callback.";
309 if (callback == nullptr) {
310 LOG(ERROR) << "Cannot register a null callback for " << fqName << "/" << name;
311 return false;
312 }
313 bool ret = callback->linkToDeath(this, 0);
314 if (!ret) {
315 LOG(ERROR) << "Failed to register death recipient for " << fqName << "/" << name;
316 return false;
317 }
318
319 auto [it, inserted] = mServiceNotifications[static_cast<std::string>(fqName) + "/" +
320 static_cast<std::string>(name)]
321 .insert(callback);
322 if (!inserted) {
323 LOG(WARNING) << "This callback for " << fqName << "/" << name
324 << " was already registered so "
325 << "we are not keeping a reference to this one.";
326 return false;
327 }
328 return true;
Devin Mooree1973ce2022-04-15 20:54:03 +0000329 }
330
331 Return<void> debugDump(debugDump_cb _hidl_cb) override {
332 _hidl_cb({});
333 return Void();
334 }
335
336 Return<void> registerPassthroughClient(const hidl_string& fqName,
337 const hidl_string& name) override {
338 LOG(INFO) << "This process is a client of " << fqName << "/" << name
339 << " passthrough HAL, but it won't show up in lshal because hwservicemanager is "
340 "not installed";
341 return Void();
342 }
343
Devin Moore2d2e4c02023-11-28 00:24:19 +0000344 Return<bool> unregisterForNotifications(const hidl_string& fqName, const hidl_string& name,
345 const sp<IServiceNotification>& callback) override {
346 auto ret = mServiceNotifications[static_cast<std::string>(fqName) + "/" +
347 static_cast<std::string>(name)]
348 .erase(callback);
349 if (!ret) {
350 LOG(WARNING) << "This callback for " << fqName << "/" << name << " was not previously "
351 << "registered so there is nothing to do.";
352 return false;
353 }
354 return true;
Devin Mooree1973ce2022-04-15 20:54:03 +0000355 }
Devin Moore2d2e4c02023-11-28 00:24:19 +0000356
Devin Mooree1973ce2022-04-15 20:54:03 +0000357 Return<bool> registerClientCallback(const hidl_string& fqName, const hidl_string& name,
358 const sp<IBase>&, const sp<IClientCallback>&) {
359 LOG(INFO) << "Cannot add client callback for " << fqName << "/" << name
360 << " without hwservicemanager";
361 return false;
362 }
363 Return<bool> unregisterClientCallback(const sp<IBase>&, const sp<IClientCallback>&) {
364 LOG(INFO) << "Cannot unregister client callbacks without hwservicemanager";
365 return false;
366 }
367 Return<bool> addWithChain(const hidl_string& fqName, const sp<IBase>&,
368 const hidl_vec<hidl_string>&) {
369 LOG(INFO) << "Cannot add " << fqName << " with chain without hwservicemanager";
370 return false;
371 }
372 Return<void> listManifestByInterface(const hidl_string& fqName, listManifestByInterface_cb) {
373 LOG(INFO) << "Cannot list manifest for " << fqName << " without hwservicemanager";
374 return Void();
375 }
376 Return<bool> tryUnregister(const hidl_string& fqName, const hidl_string& name,
377 const sp<IBase>&) {
378 LOG(INFO) << "Cannot unregister service " << fqName << "/" << name
379 << " without hwservicemanager";
380 return false;
381 }
Devin Moore2d2e4c02023-11-28 00:24:19 +0000382
383 private:
384 std::map<std::string, std::set<sp<IServiceNotification>>> mServiceNotifications;
Devin Mooree1973ce2022-04-15 20:54:03 +0000385};
386
Steven Moreland89909692018-05-30 14:11:19 -0700387sp<IServiceManager1_2> defaultServiceManager1_2() {
388 using android::hidl::manager::V1_2::BnHwServiceManager;
389 using android::hidl::manager::V1_2::BpHwServiceManager;
390
Steven Moreland10d55632020-04-21 14:10:53 -0700391 static std::mutex& gDefaultServiceManagerLock = *new std::mutex;
392 static sp<IServiceManager1_2>& gDefaultServiceManager = *new sp<IServiceManager1_2>;
Steven Moreland89909692018-05-30 14:11:19 -0700393
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700394 {
Steven Moreland89909692018-05-30 14:11:19 -0700395 std::lock_guard<std::mutex> _l(gDefaultServiceManagerLock);
396 if (gDefaultServiceManager != nullptr) {
397 return gDefaultServiceManager;
Yifan Hong8fb656b2017-03-16 14:30:40 -0700398 }
Steven Moreland405d7612017-04-07 20:31:22 -0700399
Devin Moore22e6f1e2023-11-22 22:29:54 +0000400 if (!isHidlSupported()) {
Devin Mooree1973ce2022-04-15 20:54:03 +0000401 // hwservicemanager is not available on this device.
Devin Moore22e6f1e2023-11-22 22:29:54 +0000402 LOG(WARNING) << "hwservicemanager is not supported on the device.";
Devin Mooree1973ce2022-04-15 20:54:03 +0000403 gDefaultServiceManager = sp<NoHwServiceManager>::make();
404 return gDefaultServiceManager;
405 }
406
Yifan Hong8fb656b2017-03-16 14:30:40 -0700407 if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
408 // HwBinder not available on this device or not accessible to
409 // this process.
410 return nullptr;
411 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000412
413 waitForHwServiceManager();
414
Steven Moreland89909692018-05-30 14:11:19 -0700415 while (gDefaultServiceManager == nullptr) {
416 gDefaultServiceManager =
417 fromBinder<IServiceManager1_2, BpHwServiceManager, BnHwServiceManager>(
418 ProcessState::self()->getContextObject(nullptr));
419 if (gDefaultServiceManager == nullptr) {
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000420 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700421 sleep(1);
Yifan Hong8fb656b2017-03-16 14:30:40 -0700422 }
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700423 }
424 }
425
Steven Moreland89909692018-05-30 14:11:19 -0700426 return gDefaultServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700427}
428
Elliott Hughes19306142018-10-26 13:13:04 -0700429static std::vector<std::string> findFiles(const std::string& path, const std::string& prefix,
430 const std::string& suffix) {
Steven Moreland0091c092017-01-20 23:15:18 +0000431 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
432 if (!dir) return {};
433
434 std::vector<std::string> results{};
435
436 dirent* dp;
437 while ((dp = readdir(dir.get())) != nullptr) {
438 std::string name = dp->d_name;
439
Steven Moreland8092aa02018-10-12 15:54:56 -0700440 if (base::StartsWith(name, prefix) && base::EndsWith(name, suffix)) {
Steven Moreland0091c092017-01-20 23:15:18 +0000441 results.push_back(name);
442 }
443 }
444
445 return results;
446}
447
Steven Morelandccc3a972020-02-26 16:38:31 -0800448static bool matchPackageName(const std::string& lib, std::string* matchedName,
449 std::string* implName) {
450#define RE_COMPONENT "[a-zA-Z_][a-zA-Z_0-9]*"
451#define RE_PATH RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
452 static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
453#undef RE_PATH
454#undef RE_COMPONENT
455
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800456 std::smatch match;
457 if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
458 *matchedName = match.str(1) + "::I*";
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700459 *implName = match.str(2);
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800460 return true;
461 }
462 return false;
463}
464
Yifan Hong7f49f592017-02-03 15:11:44 -0800465static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
Yifan Hongdeacf142018-07-10 17:33:34 -0700466 if (kIsRecovery) {
467 // No hwservicemanager in recovery.
468 return;
469 }
470
Steven Moreland2a2678e2017-07-21 18:07:38 -0700471 sp<IServiceManager1_0> binderizedManager = defaultServiceManager();
Yifan Hong7f49f592017-02-03 15:11:44 -0800472 if (binderizedManager == nullptr) {
473 LOG(WARNING) << "Could not registerReference for "
474 << interfaceName << "/" << instanceName
475 << ": null binderized manager.";
476 return;
477 }
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700478 auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
Yifan Hong7f49f592017-02-03 15:11:44 -0800479 if (!ret.isOk()) {
480 LOG(WARNING) << "Could not registerReference for "
481 << interfaceName << "/" << instanceName
482 << ": " << ret.description();
Steven Moreland0aeaa782017-03-22 08:11:07 -0700483 return;
Yifan Hong7f49f592017-02-03 15:11:44 -0800484 }
Steven Morelande681aa52017-02-15 16:22:37 -0800485 LOG(VERBOSE) << "Successfully registerReference for "
486 << interfaceName << "/" << instanceName;
Yifan Hong7f49f592017-02-03 15:11:44 -0800487}
488
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700489using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
490static inline void fetchPidsForPassthroughLibraries(
491 std::map<std::string, InstanceDebugInfo>* infos) {
492 static const std::string proc = "/proc/";
493
494 std::map<std::string, std::set<pid_t>> pids;
495 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
496 if (!dir) return;
497 dirent* dp;
498 while ((dp = readdir(dir.get())) != nullptr) {
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700499 pid_t pid = strtoll(dp->d_name, nullptr, 0);
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700500 if (pid == 0) continue;
501 std::string mapsPath = proc + dp->d_name + "/maps";
502 std::ifstream ifs{mapsPath};
503 if (!ifs.is_open()) continue;
504
505 for (std::string line; std::getline(ifs, line);) {
506 // The last token of line should look like
507 // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
508 // Use some simple filters to ignore bad lines before extracting libFileName
509 // and checking the key in info to make parsing faster.
510 if (line.back() != 'o') continue;
511 if (line.rfind('@') == std::string::npos) continue;
512
513 auto spacePos = line.rfind(' ');
514 if (spacePos == std::string::npos) continue;
515 auto libFileName = line.substr(spacePos + 1);
516 auto it = infos->find(libFileName);
517 if (it == infos->end()) continue;
518 pids[libFileName].insert(pid);
519 }
520 }
521 for (auto& pair : *infos) {
522 pair.second.clientPids =
523 std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
524 }
525}
526
Steven Moreland2a2678e2017-07-21 18:07:38 -0700527struct PassthroughServiceManager : IServiceManager1_1 {
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -0700528 static void openLibs(
529 const std::string& fqName,
530 const std::function<bool /* continue */ (void* /* handle */, const std::string& /* lib */,
531 const std::string& /* sym */)>& eachLib) {
Steven Moreland819c05d2017-04-06 17:24:22 -0700532 //fqName looks like android.hardware.foo@1.0::IFoo
Steven Moreland519306f2017-06-06 17:14:12 -0700533 size_t idx = fqName.find("::");
Steven Moreland819c05d2017-04-06 17:24:22 -0700534
535 if (idx == std::string::npos ||
Steven Moreland519306f2017-06-06 17:14:12 -0700536 idx + strlen("::") + 1 >= fqName.size()) {
Steven Moreland337e6b62017-01-18 17:25:13 -0800537 LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
Steven Moreland519306f2017-06-06 17:14:12 -0700538 return;
Steven Moreland337e6b62017-01-18 17:25:13 -0800539 }
540
Steven Moreland519306f2017-06-06 17:14:12 -0700541 std::string packageAndVersion = fqName.substr(0, idx);
542 std::string ifaceName = fqName.substr(idx + strlen("::"));
Steven Moreland819c05d2017-04-06 17:24:22 -0700543
544 const std::string prefix = packageAndVersion + "-impl";
545 const std::string sym = "HIDL_FETCH_" + ifaceName;
Steven Moreland348802d2017-02-23 12:48:55 -0800546
Steven Moreland77f4c852017-10-12 11:05:53 -0700547 constexpr int dlMode = RTLD_LAZY;
548 void* handle = nullptr;
Steven Moreland337e6b62017-01-18 17:25:13 -0800549
Steven Morelanda29905c2017-03-01 10:42:35 -0800550 dlerror(); // clear
551
Jooyung Han219106c2020-07-17 15:01:19 +0900552 static std::string halLibPathVndkSp = details::getVndkSpHwPath();
Justin Yun6a323ed2018-10-18 18:41:56 +0900553 std::vector<std::string> paths = {
554 HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, halLibPathVndkSp,
555#ifndef __ANDROID_VNDK__
556 HAL_LIBRARY_PATH_SYSTEM,
557#endif
558 };
Steven Moreland77f4c852017-10-12 11:05:53 -0700559
Steven Morelandb939e7e2020-07-08 01:04:23 +0000560 if (details::isTrebleTestingOverride()) {
Steven Moreland77f4c852017-10-12 11:05:53 -0700561 // Load HAL implementations that are statically linked
562 handle = dlopen(nullptr, dlMode);
563 if (handle == nullptr) {
564 const char* error = dlerror();
565 LOG(ERROR) << "Failed to dlopen self: "
566 << (error == nullptr ? "unknown error" : error);
567 } else if (!eachLib(handle, "SELF", sym)) {
568 return;
569 }
Steven Morelandf7dea692017-07-14 12:49:28 -0700570 }
Steven Moreland77f4c852017-10-12 11:05:53 -0700571
Steven Morelandf7dea692017-07-14 12:49:28 -0700572 for (const std::string& path : paths) {
Elliott Hughes19306142018-10-26 13:13:04 -0700573 std::vector<std::string> libs = findFiles(path, prefix, ".so");
Steven Moreland0091c092017-01-20 23:15:18 +0000574
Steven Moreland0091c092017-01-20 23:15:18 +0000575 for (const std::string &lib : libs) {
Steven Moreland348802d2017-02-23 12:48:55 -0800576 const std::string fullPath = path + lib;
577
Yifan Hongdeacf142018-07-10 17:33:34 -0700578 if (kIsRecovery || path == HAL_LIBRARY_PATH_SYSTEM) {
Jiyong Park3ab546c2017-04-06 20:28:07 +0900579 handle = dlopen(fullPath.c_str(), dlMode);
Steven Moreland65c00cb2017-10-12 11:35:22 -0700580 } else {
Steven Moreland2056cf32019-09-17 17:41:02 -0700581#if !defined(__ANDROID_RECOVERY__) && defined(__ANDROID__)
Steven Moreland65c00cb2017-10-12 11:35:22 -0700582 handle = android_load_sphal_library(fullPath.c_str(), dlMode);
Jerry Zhang86ae9992018-05-30 17:11:09 -0700583#endif
Jiyong Park3ab546c2017-04-06 20:28:07 +0900584 }
585
Steven Moreland348802d2017-02-23 12:48:55 -0800586 if (handle == nullptr) {
587 const char* error = dlerror();
588 LOG(ERROR) << "Failed to dlopen " << lib << ": "
589 << (error == nullptr ? "unknown error" : error);
590 continue;
Steven Moreland0091c092017-01-20 23:15:18 +0000591 }
Steven Moreland348802d2017-02-23 12:48:55 -0800592
Steven Moreland519306f2017-06-06 17:14:12 -0700593 if (!eachLib(handle, lib, sym)) {
594 return;
Steven Moreland348802d2017-02-23 12:48:55 -0800595 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800596 }
597 }
Steven Moreland519306f2017-06-06 17:14:12 -0700598 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800599
Steven Moreland519306f2017-06-06 17:14:12 -0700600 Return<sp<IBase>> get(const hidl_string& fqName,
601 const hidl_string& name) override {
602 sp<IBase> ret = nullptr;
Devin Mooree1973ce2022-04-15 20:54:03 +0000603 // This is required to run without hwservicemanager while we have
604 // passthrough HIDL services. Once the passthrough HIDL services have
605 // been removed, the PassthroughServiceManager will no longer be needed.
Devin Moore22e6f1e2023-11-22 22:29:54 +0000606 if (!isHidlSupported() && isServiceManager(fqName)) {
Devin Mooree1973ce2022-04-15 20:54:03 +0000607 return defaultServiceManager1_2();
608 }
Steven Moreland519306f2017-06-06 17:14:12 -0700609
610 openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
611 IBase* (*generator)(const char* name);
612 *(void **)(&generator) = dlsym(handle, sym.c_str());
613 if(!generator) {
614 const char* error = dlerror();
Steven Morelandedd49122021-02-17 22:41:51 +0000615 LOG(ERROR) << "Passthrough lookup opened " << lib << " but could not find symbol "
616 << sym << ": " << (error == nullptr ? "unknown error" : error)
617 << ". Keeping library open.";
618
619 // dlclose too problematic in multi-threaded environment
620 // dlclose(handle);
621
622 return true; // continue
Steven Moreland519306f2017-06-06 17:14:12 -0700623 }
624
625 ret = (*generator)(name.c_str());
626
627 if (ret == nullptr) {
Steven Morelandedd49122021-02-17 22:41:51 +0000628 LOG(ERROR) << "Could not find instance '" << name.c_str() << "' in library " << lib
629 << ". Keeping library open.";
630
631 // dlclose too problematic in multi-threaded environment
632 // dlclose(handle);
633
634 // this module doesn't provide this particular instance
635 return true; // continue
Steven Moreland519306f2017-06-06 17:14:12 -0700636 }
637
Steven Morelande69e8d32018-03-14 10:55:42 -0700638 // Actual fqname might be a subclass.
639 // This assumption is tested in vts_treble_vintf_test
640 using ::android::hardware::details::getDescriptor;
641 std::string actualFqName = getDescriptor(ret.get());
642 CHECK(actualFqName.size() > 0);
643 registerReference(actualFqName, name);
Steven Moreland519306f2017-06-06 17:14:12 -0700644 return false;
645 });
646
647 return ret;
Steven Moreland337e6b62017-01-18 17:25:13 -0800648 }
649
Martijn Coenen67a02492017-03-06 13:04:48 +0100650 Return<bool> add(const hidl_string& /* name */,
Steven Moreland337e6b62017-01-18 17:25:13 -0800651 const sp<IBase>& /* service */) override {
652 LOG(FATAL) << "Cannot register services with passthrough service manager.";
653 return false;
654 }
655
Steven Morelandc601c5f2017-04-06 09:26:07 -0700656 Return<Transport> getTransport(const hidl_string& /* fqName */,
657 const hidl_string& /* name */) {
658 LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
659 return Transport::EMPTY;
660 }
661
Yifan Hong705e5da2017-03-02 16:59:39 -0800662 Return<void> list(list_cb /* _hidl_cb */) override {
663 LOG(FATAL) << "Cannot list services with passthrough service manager.";
Steven Moreland337e6b62017-01-18 17:25:13 -0800664 return Void();
665 }
666 Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
667 listByInterface_cb /* _hidl_cb */) override {
668 // TODO: add this functionality
669 LOG(FATAL) << "Cannot list services with passthrough service manager.";
670 return Void();
671 }
672
673 Return<bool> registerForNotifications(const hidl_string& /* fqName */,
674 const hidl_string& /* name */,
675 const sp<IServiceNotification>& /* callback */) override {
676 // This makes no sense.
677 LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
678 return false;
679 }
680
Yifan Hong705e5da2017-03-02 16:59:39 -0800681 Return<void> debugDump(debugDump_cb _hidl_cb) override {
682 using Arch = ::android::hidl::base::V1_0::DebugInfo::Architecture;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700683 using std::literals::string_literals::operator""s;
Jooyung Han219106c2020-07-17 15:01:19 +0900684 static std::string halLibPathVndkSp64 = details::getVndkSpHwPath("lib64");
685 static std::string halLibPathVndkSp32 = details::getVndkSpHwPath("lib");
Jiyong Park56eb1492017-08-04 16:16:13 +0900686 static std::vector<std::pair<Arch, std::vector<const char*>>> sAllPaths{
687 {Arch::IS_64BIT,
Justin Yun6a323ed2018-10-18 18:41:56 +0900688 {
689 HAL_LIBRARY_PATH_ODM_64BIT, HAL_LIBRARY_PATH_VENDOR_64BIT,
690 halLibPathVndkSp64.c_str(),
691#ifndef __ANDROID_VNDK__
692 HAL_LIBRARY_PATH_SYSTEM_64BIT,
693#endif
694 }},
Jiyong Park56eb1492017-08-04 16:16:13 +0900695 {Arch::IS_32BIT,
Justin Yun6a323ed2018-10-18 18:41:56 +0900696 {
697 HAL_LIBRARY_PATH_ODM_32BIT, HAL_LIBRARY_PATH_VENDOR_32BIT,
698 halLibPathVndkSp32.c_str(),
699#ifndef __ANDROID_VNDK__
700 HAL_LIBRARY_PATH_SYSTEM_32BIT,
701#endif
702 }}};
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700703 std::map<std::string, InstanceDebugInfo> map;
Yifan Hong705e5da2017-03-02 16:59:39 -0800704 for (const auto &pair : sAllPaths) {
705 Arch arch = pair.first;
706 for (const auto &path : pair.second) {
Elliott Hughes19306142018-10-26 13:13:04 -0700707 std::vector<std::string> libs = findFiles(path, "", ".so");
Yifan Hong705e5da2017-03-02 16:59:39 -0800708 for (const std::string &lib : libs) {
709 std::string matchedName;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700710 std::string implName;
711 if (matchPackageName(lib, &matchedName, &implName)) {
712 std::string instanceName{"* ("s + path + ")"s};
713 if (!implName.empty()) instanceName += " ("s + implName + ")"s;
714 map.emplace(path + lib, InstanceDebugInfo{.interfaceName = matchedName,
715 .instanceName = instanceName,
716 .clientPids = {},
717 .arch = arch});
Yifan Hong705e5da2017-03-02 16:59:39 -0800718 }
719 }
720 }
721 }
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700722 fetchPidsForPassthroughLibraries(&map);
723 hidl_vec<InstanceDebugInfo> vec;
724 vec.resize(map.size());
725 size_t idx = 0;
726 for (auto&& pair : map) {
727 vec[idx++] = std::move(pair.second);
728 }
Yifan Hong705e5da2017-03-02 16:59:39 -0800729 _hidl_cb(vec);
Yifan Hong7f49f592017-02-03 15:11:44 -0800730 return Void();
731 }
732
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700733 Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
Yifan Hong7f49f592017-02-03 15:11:44 -0800734 // This makes no sense.
735 LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
736 << "Call it on defaultServiceManager() instead.";
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800737 return Void();
738 }
739
Steven Moreland2a2678e2017-07-21 18:07:38 -0700740 Return<bool> unregisterForNotifications(const hidl_string& /* fqName */,
741 const hidl_string& /* name */,
742 const sp<IServiceNotification>& /* callback */) override {
743 // This makes no sense.
744 LOG(FATAL) << "Cannot unregister for notifications with passthrough service manager.";
745 return false;
746 }
747
Steven Moreland337e6b62017-01-18 17:25:13 -0800748};
749
Steven Moreland2a2678e2017-07-21 18:07:38 -0700750sp<IServiceManager1_0> getPassthroughServiceManager() {
751 return getPassthroughServiceManager1_1();
752}
753sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
Steven Moreland337e6b62017-01-18 17:25:13 -0800754 static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
755 return manager;
756}
757
Steven Moreland92b247c2019-08-21 14:53:11 -0700758std::vector<std::string> getAllHalInstanceNames(const std::string& descriptor) {
759 std::vector<std::string> ret;
760 auto sm = defaultServiceManager1_2();
761 sm->listManifestByInterface(descriptor, [&](const auto& instances) {
762 ret.reserve(instances.size());
763 for (const auto& i : instances) {
764 ret.push_back(i);
765 }
766 });
767 return ret;
768}
769
Steven Morelandcbefd352017-01-23 20:29:05 -0800770namespace details {
771
Steven Moreland519306f2017-06-06 17:14:12 -0700772void preloadPassthroughService(const std::string &descriptor) {
773 PassthroughServiceManager::openLibs(descriptor,
774 [&](void* /* handle */, const std::string& /* lib */, const std::string& /* sym */) {
775 // do nothing
776 return true; // open all libs
777 });
778}
779
Steven Morelandcbefd352017-01-23 20:29:05 -0800780struct Waiter : IServiceNotification {
Martijn Coenen773609e2017-10-24 09:57:53 +0200781 Waiter(const std::string& interface, const std::string& instanceName,
782 const sp<IServiceManager1_1>& sm) : mInterfaceName(interface),
783 mInstanceName(instanceName), mSm(sm) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100784 }
785
786 void onFirstRef() override {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200787 // If this process only has one binder thread, and we're calling wait() from
788 // that thread, it will block forever because we hung up the one and only
789 // binder thread on a condition variable that can only be notified by an
790 // incoming binder call.
Tobias Lindskog88e886f2018-01-05 10:32:43 +0100791 if (IPCThreadState::self()->isOnlyBinderThread()) {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200792 LOG(WARNING) << "Can't efficiently wait for " << mInterfaceName << "/"
793 << mInstanceName << ", because we are called from "
794 << "the only binder thread in this process.";
795 return;
796 }
797
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100798 Return<bool> ret = mSm->registerForNotifications(mInterfaceName, mInstanceName, this);
Martijn Coenen773609e2017-10-24 09:57:53 +0200799
800 if (!ret.isOk()) {
801 LOG(ERROR) << "Transport error, " << ret.description()
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100802 << ", during notification registration for " << mInterfaceName << "/"
803 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200804 return;
805 }
806
807 if (!ret) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100808 LOG(ERROR) << "Could not register for notifications for " << mInterfaceName << "/"
809 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200810 return;
811 }
812
813 mRegisteredForNotifications = true;
814 }
815
816 ~Waiter() {
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100817 if (!mDoneCalled) {
818 LOG(FATAL)
819 << "Waiter still registered for notifications, call done() before dropping ref!";
Martijn Coenen773609e2017-10-24 09:57:53 +0200820 }
821 }
822
Steven Morelandcbefd352017-01-23 20:29:05 -0800823 Return<void> onRegistration(const hidl_string& /* fqName */,
824 const hidl_string& /* name */,
825 bool /* preexisting */) override {
826 std::unique_lock<std::mutex> lock(mMutex);
827 if (mRegistered) {
828 return Void();
829 }
830 mRegistered = true;
831 lock.unlock();
832
833 mCondition.notify_one();
834 return Void();
835 }
836
Steven Moreland0771d8a2018-05-09 13:29:14 -0700837 void wait(bool timeout) {
Steven Moreland49605102017-03-28 09:33:06 -0700838 using std::literals::chrono_literals::operator""s;
839
Martijn Coenen773609e2017-10-24 09:57:53 +0200840 if (!mRegisteredForNotifications) {
841 // As an alternative, just sleep for a second and return
842 LOG(WARNING) << "Waiting one second for " << mInterfaceName << "/" << mInstanceName;
843 sleep(1);
844 return;
845 }
846
Steven Morelandcbefd352017-01-23 20:29:05 -0800847 std::unique_lock<std::mutex> lock(mMutex);
Steven Moreland0771d8a2018-05-09 13:29:14 -0700848 do {
Steven Moreland49605102017-03-28 09:33:06 -0700849 mCondition.wait_for(lock, 1s, [this]{
850 return mRegistered;
851 });
852
853 if (mRegistered) {
854 break;
855 }
856
Steven Moreland0771d8a2018-05-09 13:29:14 -0700857 LOG(WARNING) << "Waited one second for " << mInterfaceName << "/" << mInstanceName;
858 } while (!timeout);
Steven Morelandcbefd352017-01-23 20:29:05 -0800859 }
860
Martijn Coenen773609e2017-10-24 09:57:53 +0200861 // Be careful when using this; after calling reset(), you must always try to retrieve
862 // the corresponding service before blocking on the waiter; otherwise, you might run
863 // into a race-condition where the service has just (re-)registered, you clear the state
864 // here, and subsequently calling waiter->wait() will block forever.
865 void reset() {
866 std::unique_lock<std::mutex> lock(mMutex);
867 mRegistered = false;
868 }
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100869
870 // done() must be called before dropping the last strong ref to the Waiter, to make
871 // sure we can properly unregister with hwservicemanager.
872 void done() {
873 if (mRegisteredForNotifications) {
874 if (!mSm->unregisterForNotifications(mInterfaceName, mInstanceName, this)
875 .withDefault(false)) {
876 LOG(ERROR) << "Could not unregister service notification for " << mInterfaceName
877 << "/" << mInstanceName << ".";
878 } else {
879 mRegisteredForNotifications = false;
880 }
881 }
882 mDoneCalled = true;
883 }
884
885 private:
Martijn Coenen773609e2017-10-24 09:57:53 +0200886 const std::string mInterfaceName;
887 const std::string mInstanceName;
Steven Morelandad1f9922018-10-02 19:37:05 -0700888 sp<IServiceManager1_1> mSm;
Steven Morelandcbefd352017-01-23 20:29:05 -0800889 std::mutex mMutex;
890 std::condition_variable mCondition;
891 bool mRegistered = false;
Martijn Coenen773609e2017-10-24 09:57:53 +0200892 bool mRegisteredForNotifications = false;
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100893 bool mDoneCalled = false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800894};
895
896void waitForHwService(
897 const std::string &interface, const std::string &instanceName) {
Martijn Coenen773609e2017-10-24 09:57:53 +0200898 sp<Waiter> waiter = new Waiter(interface, instanceName, defaultServiceManager1_1());
Steven Moreland0771d8a2018-05-09 13:29:14 -0700899 waiter->wait(false /* timeout */);
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100900 waiter->done();
Martijn Coenen773609e2017-10-24 09:57:53 +0200901}
Steven Morelandcbefd352017-01-23 20:29:05 -0800902
Martijn Coenen773609e2017-10-24 09:57:53 +0200903// Prints relevant error/warning messages for error return values from
904// details::canCastInterface(), both transaction errors (!castReturn.isOk())
905// as well as actual cast failures (castReturn.isOk() && castReturn = false).
906// Returns 'true' if the error is non-fatal and it's useful to retry
907bool handleCastError(const Return<bool>& castReturn, const std::string& descriptor,
908 const std::string& instance) {
909 if (castReturn.isOk()) {
910 if (castReturn) {
911 details::logAlwaysFatal("Successful cast value passed into handleCastError.");
912 }
913 // This should never happen, and there's not really a point in retrying.
914 ALOGE("getService: received incompatible service (bug in hwservicemanager?) for "
915 "%s/%s.", descriptor.c_str(), instance.c_str());
916 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800917 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200918 if (castReturn.isDeadObject()) {
919 ALOGW("getService: found dead hwbinder service for %s/%s.", descriptor.c_str(),
920 instance.c_str());
921 return true;
Steven Morelandcbefd352017-01-23 20:29:05 -0800922 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200923 // This can happen due to:
924 // 1) No SELinux permissions
925 // 2) Other transaction failure (no buffer space, kernel error)
926 // The first isn't recoverable, but the second is.
927 // Since we can't yet differentiate between the two, and clients depend
928 // on us not blocking in case 1), treat this as a fatal error for now.
929 ALOGW("getService: unable to call into hwbinder service for %s/%s.",
930 descriptor.c_str(), instance.c_str());
931 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800932}
933
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200934sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
935 const std::string& instance,
936 bool retry, bool getStub) {
Steven Moreland84fe49e2019-08-20 17:47:26 +0000937 using Transport = IServiceManager1_0::Transport;
Martijn Coenend35678f2018-03-07 09:51:01 +0100938 sp<Waiter> waiter;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200939
Yifan Hongdeacf142018-07-10 17:33:34 -0700940 sp<IServiceManager1_1> sm;
941 Transport transport = Transport::EMPTY;
942 if (kIsRecovery) {
Yifan Hongdeacf142018-07-10 17:33:34 -0700943 transport = Transport::PASSTHROUGH;
Yifan Hongdeacf142018-07-10 17:33:34 -0700944 } else {
945 sm = defaultServiceManager1_1();
946 if (sm == nullptr) {
947 ALOGE("getService: defaultServiceManager() is null");
948 return nullptr;
949 }
950
951 Return<Transport> transportRet = sm->getTransport(descriptor, instance);
952
953 if (!transportRet.isOk()) {
954 ALOGE("getService: defaultServiceManager()->getTransport returns %s",
955 transportRet.description().c_str());
956 return nullptr;
957 }
958 transport = transportRet;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200959 }
960
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200961 const bool vintfHwbinder = (transport == Transport::HWBINDER);
962 const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
Steven Moreland84fe49e2019-08-20 17:47:26 +0000963 const bool trebleTestingOverride = isTrebleTestingOverride();
Steven Morelandf47cdf72021-04-07 22:13:13 +0000964 const bool allowLegacy = !kEnforceVintfManifest || (trebleTestingOverride && isDebuggable());
Steven Moreland84fe49e2019-08-20 17:47:26 +0000965 const bool vintfLegacy = (transport == Transport::EMPTY) && allowLegacy;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200966
Steven Moreland84fe49e2019-08-20 17:47:26 +0000967 if (!kEnforceVintfManifest) {
968 ALOGE("getService: Potential race detected. The VINTF manifest is not being enforced. If "
969 "a HAL server has a delay in starting and it is not in the manifest, it will not be "
970 "retrieved. Please make sure all HALs on this device are in the VINTF manifest and "
971 "enable PRODUCT_ENFORCE_VINTF_MANIFEST on this device (this is also enabled by "
972 "PRODUCT_FULL_TREBLE). PRODUCT_ENFORCE_VINTF_MANIFEST will ensure that no race "
973 "condition is possible here.");
Steven Morelandaadec3c2019-08-22 17:06:48 -0700974 sleep(1);
Steven Moreland84fe49e2019-08-20 17:47:26 +0000975 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200976
Steven Moreland76371242018-04-19 17:11:39 -0700977 for (int tries = 0; !getStub && (vintfHwbinder || vintfLegacy); tries++) {
978 if (waiter == nullptr && tries > 0) {
Martijn Coenend35678f2018-03-07 09:51:01 +0100979 waiter = new Waiter(descriptor, instance, sm);
980 }
Steven Moreland76371242018-04-19 17:11:39 -0700981 if (waiter != nullptr) {
982 waiter->reset(); // don't reorder this -- see comments on reset()
983 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200984 Return<sp<IBase>> ret = sm->get(descriptor, instance);
985 if (!ret.isOk()) {
986 ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.",
987 ret.description().c_str(), descriptor.c_str(), instance.c_str());
988 break;
989 }
990 sp<IBase> base = ret;
Martijn Coenen773609e2017-10-24 09:57:53 +0200991 if (base != nullptr) {
992 Return<bool> canCastRet =
993 details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
994
995 if (canCastRet.isOk() && canCastRet) {
Steven Moreland76371242018-04-19 17:11:39 -0700996 if (waiter != nullptr) {
997 waiter->done();
998 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200999 return base; // still needs to be wrapped by Bp class.
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001000 }
Martijn Coenen773609e2017-10-24 09:57:53 +02001001
1002 if (!handleCastError(canCastRet, descriptor, instance)) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001003 }
1004
Martijn Coenen773609e2017-10-24 09:57:53 +02001005 // In case of legacy or we were not asked to retry, don't.
1006 if (vintfLegacy || !retry) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001007
Steven Moreland76371242018-04-19 17:11:39 -07001008 if (waiter != nullptr) {
1009 ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
Steven Moreland0771d8a2018-05-09 13:29:14 -07001010 waiter->wait(true /* timeout */);
Steven Moreland76371242018-04-19 17:11:39 -07001011 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001012 }
1013
Martijn Coenend35678f2018-03-07 09:51:01 +01001014 if (waiter != nullptr) {
1015 waiter->done();
1016 }
Martijn Coenen3fa15c22018-02-10 11:30:00 +01001017
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001018 if (getStub || vintfPassthru || vintfLegacy) {
Steven Moreland84fe49e2019-08-20 17:47:26 +00001019 const sp<IServiceManager1_0> pm = getPassthroughServiceManager();
Martijn Coenen86c3abb2017-10-24 09:33:28 +02001020 if (pm != nullptr) {
1021 sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
1022 if (!getStub || trebleTestingOverride) {
1023 base = wrapPassthrough(base);
1024 }
1025 return base;
1026 }
1027 }
1028
1029 return nullptr;
1030}
1031
Steven Morelandbb9eb2a2018-10-11 12:10:01 -07001032status_t registerAsServiceInternal(const sp<IBase>& service, const std::string& name) {
1033 if (service == nullptr) {
1034 return UNEXPECTED_NULL;
1035 }
1036
1037 sp<IServiceManager1_2> sm = defaultServiceManager1_2();
1038 if (sm == nullptr) {
1039 return INVALID_OPERATION;
1040 }
1041
Steven Moreland84fe49e2019-08-20 17:47:26 +00001042 const std::string descriptor = getDescriptor(service.get());
1043
1044 if (kEnforceVintfManifest && !isTrebleTestingOverride()) {
1045 using Transport = IServiceManager1_0::Transport;
Steven Moreland7d1b0732021-01-21 22:47:40 +00001046 Return<Transport> transport = sm->getTransport(descriptor, name);
1047
1048 if (!transport.isOk()) {
1049 LOG(ERROR) << "Could not get transport for " << descriptor << "/" << name << ": "
1050 << transport.description();
1051 return UNKNOWN_ERROR;
1052 }
Steven Moreland84fe49e2019-08-20 17:47:26 +00001053
1054 if (transport != Transport::HWBINDER) {
1055 LOG(ERROR) << "Service " << descriptor << "/" << name
1056 << " must be in VINTF manifest in order to register/get.";
1057 return UNKNOWN_ERROR;
1058 }
1059 }
1060
Steven Morelandbb9eb2a2018-10-11 12:10:01 -07001061 bool registered = false;
1062 Return<void> ret = service->interfaceChain([&](const auto& chain) {
1063 registered = sm->addWithChain(name.c_str(), service, chain).withDefault(false);
1064 });
1065
1066 if (!ret.isOk()) {
1067 LOG(ERROR) << "Could not retrieve interface chain: " << ret.description();
1068 }
1069
1070 if (registered) {
Steven Moreland84fe49e2019-08-20 17:47:26 +00001071 onRegistrationImpl(descriptor, name);
Steven Morelandbb9eb2a2018-10-11 12:10:01 -07001072 }
1073
1074 return registered ? OK : UNKNOWN_ERROR;
1075}
1076
Bernhard Rosenkränzer0c28fd22018-06-04 16:01:47 +02001077} // namespace details
Steven Morelandcbefd352017-01-23 20:29:05 -08001078
Bernhard Rosenkränzer0c28fd22018-06-04 16:01:47 +02001079} // namespace hardware
1080} // namespace android