blob: 66fa7cbab56d407f4d62fd2ad25d2e6ae913202e [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
17#define LOG_TAG "ServiceManagement"
18
Jiyong Park3ab546c2017-04-06 20:28:07 +090019#include <android/dlext.h>
Yifan Hong9a22d1d2017-01-25 14:19:26 -080020#include <condition_variable>
21#include <dlfcn.h>
22#include <dirent.h>
Steven Moreland405d7612017-04-07 20:31:22 -070023#include <fstream>
24#include <pthread.h>
Yifan Hong9a22d1d2017-01-25 14:19:26 -080025#include <unistd.h>
26
27#include <mutex>
28#include <regex>
Yifan Hongbd0d8f72017-05-24 19:43:51 -070029#include <set>
Yifan Hong9a22d1d2017-01-25 14:19:26 -080030
Martijn Coenen12f04d92016-12-07 17:29:41 +010031#include <hidl/HidlBinderSupport.h>
Justin Yun1f048102017-12-01 15:30:08 +090032#include <hidl/HidlInternal.h>
Steven Morelande69e8d32018-03-14 10:55:42 -070033#include <hidl/HidlTransportUtils.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070034#include <hidl/ServiceManagement.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070035#include <hidl/Status.h>
Peter Kalauskas64ffced2018-09-05 16:41:08 -070036#include <utils/SystemClock.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070037
Peter Kalauskas64ffced2018-09-05 16:41:08 -070038#include <android-base/file.h>
Steven Moreland337e6b62017-01-18 17:25:13 -080039#include <android-base/logging.h>
Peter Kalauskas64ffced2018-09-05 16:41:08 -070040#include <android-base/parseint.h>
Steven Morelandc1cee2c2017-03-24 16:23:11 +000041#include <android-base/properties.h>
Justin Yun1f048102017-12-01 15:30:08 +090042#include <android-base/stringprintf.h>
Peter Kalauskas64ffced2018-09-05 16:41:08 -070043#include <android-base/strings.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070044#include <hwbinder/IPCThreadState.h>
45#include <hwbinder/Parcel.h>
Jerry Zhang86ae9992018-05-30 17:11:09 -070046#if !defined(__ANDROID_RECOVERY__)
Jiyong Parkba8ace12017-05-15 15:44:39 +090047#include <vndksupport/linker.h>
Jerry Zhang86ae9992018-05-30 17:11:09 -070048#endif
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070049
Steven Moreland89909692018-05-30 14:11:19 -070050#include <android/hidl/manager/1.2/BnHwServiceManager.h>
51#include <android/hidl/manager/1.2/BpHwServiceManager.h>
52#include <android/hidl/manager/1.2/IServiceManager.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070053
Yifan Hong9a22d1d2017-01-25 14:19:26 -080054#define RE_COMPONENT "[a-zA-Z_][a-zA-Z_0-9]*"
55#define RE_PATH RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
56static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
57
Steven Morelandc1cee2c2017-03-24 16:23:11 +000058using android::base::WaitForProperty;
59
Steven Moreland2a2678e2017-07-21 18:07:38 -070060using IServiceManager1_0 = android::hidl::manager::V1_0::IServiceManager;
61using IServiceManager1_1 = android::hidl::manager::V1_1::IServiceManager;
Steven Moreland89909692018-05-30 14:11:19 -070062using IServiceManager1_2 = android::hidl::manager::V1_2::IServiceManager;
Steven Moreland337e6b62017-01-18 17:25:13 -080063using android::hidl::manager::V1_0::IServiceNotification;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070064
65namespace android {
66namespace hardware {
67
Steven Morelandc1cee2c2017-03-24 16:23:11 +000068static const char* kHwServicemanagerReadyProperty = "hwservicemanager.ready";
69
Yifan Hongdeacf142018-07-10 17:33:34 -070070#if defined(__ANDROID_RECOVERY__)
71static constexpr bool kIsRecovery = true;
72#else
73static constexpr bool kIsRecovery = false;
74#endif
75
Steven Morelandc1cee2c2017-03-24 16:23:11 +000076void waitForHwServiceManager() {
77 using std::literals::chrono_literals::operator""s;
78
79 while (!WaitForProperty(kHwServicemanagerReadyProperty, "true", 1s)) {
80 LOG(WARNING) << "Waited for hwservicemanager.ready for a second, waiting another...";
81 }
82}
83
Steven Moreland405d7612017-04-07 20:31:22 -070084bool endsWith(const std::string &in, const std::string &suffix) {
85 return in.size() >= suffix.size() &&
86 in.substr(in.size() - suffix.size()) == suffix;
87}
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070088
Steven Moreland405d7612017-04-07 20:31:22 -070089bool startsWith(const std::string &in, const std::string &prefix) {
90 return in.size() >= prefix.size() &&
91 in.substr(0, prefix.size()) == prefix;
92}
93
94std::string binaryName() {
95 std::ifstream ifs("/proc/self/cmdline");
96 std::string cmdline;
97 if (!ifs.is_open()) {
98 return "";
99 }
100 ifs >> cmdline;
101
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -0700102 size_t idx = cmdline.rfind('/');
Steven Moreland405d7612017-04-07 20:31:22 -0700103 if (idx != std::string::npos) {
104 cmdline = cmdline.substr(idx + 1);
105 }
106
107 return cmdline;
108}
109
Steven Moreland7d09a402018-04-06 10:44:05 -0700110std::string packageWithoutVersion(const std::string& packageAndVersion) {
111 size_t at = packageAndVersion.find('@');
112 if (at == std::string::npos) return packageAndVersion;
113 return packageAndVersion.substr(0, at);
114}
115
116void tryShortenProcessName(const std::string& packageAndVersion) {
117 const static std::string kTasks = "/proc/self/task/";
118
119 // make sure that this binary name is in the same package
Steven Moreland405d7612017-04-07 20:31:22 -0700120 std::string processName = binaryName();
121
Steven Moreland7d09a402018-04-06 10:44:05 -0700122 // e.x. android.hardware.foo is this package
123 if (!startsWith(packageWithoutVersion(processName), packageWithoutVersion(packageAndVersion))) {
Steven Moreland405d7612017-04-07 20:31:22 -0700124 return;
125 }
126
Steven Moreland7d09a402018-04-06 10:44:05 -0700127 // e.x. android.hardware.module.foo@1.2 -> foo@1.2
128 size_t lastDot = packageAndVersion.rfind('.');
129 if (lastDot == std::string::npos) return;
130 size_t secondDot = packageAndVersion.rfind('.', lastDot - 1);
131 if (secondDot == std::string::npos) return;
Steven Moreland405d7612017-04-07 20:31:22 -0700132
Steven Moreland7d09a402018-04-06 10:44:05 -0700133 std::string newName = processName.substr(secondDot + 1, std::string::npos);
134 ALOGI("Removing namespace from process name %s to %s.", processName.c_str(), newName.c_str());
135
136 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kTasks.c_str()), closedir);
137 if (dir == nullptr) return;
138
139 dirent* dp;
140 while ((dp = readdir(dir.get())) != nullptr) {
141 if (dp->d_type != DT_DIR) continue;
142 if (dp->d_name[0] == '.') continue;
143
144 std::fstream fs(kTasks + dp->d_name + "/comm");
145 if (!fs.is_open()) {
146 ALOGI("Could not rename process, failed read comm for %s.", dp->d_name);
147 continue;
148 }
149
150 std::string oldComm;
151 fs >> oldComm;
152
153 // don't rename if it already has an explicit name
154 if (startsWith(packageAndVersion, oldComm)) {
155 fs.seekg(0, fs.beg);
156 fs << newName;
157 }
Steven Moreland405d7612017-04-07 20:31:22 -0700158 }
Steven Moreland405d7612017-04-07 20:31:22 -0700159}
160
161namespace details {
162
Peter Kalauskas64ffced2018-09-05 16:41:08 -0700163/*
164 * Returns the age of the current process by reading /proc/self/stat and comparing starttime to the
165 * current time. This is useful for measuring how long it took a HAL to register itself.
166 */
167long getProcessAgeMs() {
168 constexpr const int PROCFS_STAT_STARTTIME_INDEX = 21;
169 std::string content;
170 android::base::ReadFileToString("/proc/self/stat", &content, false);
171 auto stats = android::base::Split(content, " ");
172 if (stats.size() <= PROCFS_STAT_STARTTIME_INDEX) {
173 LOG(INFO) << "Could not read starttime from /proc/self/stat";
174 return -1;
175 }
176 const std::string& startTimeString = stats[PROCFS_STAT_STARTTIME_INDEX];
177 static const int64_t ticksPerSecond = sysconf(_SC_CLK_TCK);
178 const int64_t uptime = android::uptimeMillis();
179
180 unsigned long long startTimeInClockTicks = 0;
181 if (android::base::ParseUint(startTimeString, &startTimeInClockTicks)) {
182 long startTimeMs = 1000ULL * startTimeInClockTicks / ticksPerSecond;
183 return uptime - startTimeMs;
184 }
185 return -1;
186}
187
188void onRegistration(const std::string& packageName, const std::string& interfaceName,
189 const std::string& instanceName) {
190 long halStartDelay = getProcessAgeMs();
191 if (halStartDelay >= 0) {
192 // The "start delay" printed here is an estimate of how long it took the HAL to go from
193 // process creation to registering itself as a HAL. Actual start time could be longer
194 // because the process might not have joined the threadpool yet, so it might not be ready to
195 // process transactions.
196 LOG(INFO) << "Registered " << interfaceName << "/" << instanceName << " (start delay of "
197 << halStartDelay << "ms)";
198 }
Steven Moreland405d7612017-04-07 20:31:22 -0700199 tryShortenProcessName(packageName);
200}
201
202} // details
203
Steven Moreland2a2678e2017-07-21 18:07:38 -0700204sp<IServiceManager1_0> defaultServiceManager() {
Steven Moreland89909692018-05-30 14:11:19 -0700205 return defaultServiceManager1_2();
Steven Moreland2a2678e2017-07-21 18:07:38 -0700206}
207sp<IServiceManager1_1> defaultServiceManager1_1() {
Steven Moreland89909692018-05-30 14:11:19 -0700208 return defaultServiceManager1_2();
209}
210sp<IServiceManager1_2> defaultServiceManager1_2() {
211 using android::hidl::manager::V1_2::BnHwServiceManager;
212 using android::hidl::manager::V1_2::BpHwServiceManager;
213
214 static std::mutex gDefaultServiceManagerLock;
215 static sp<IServiceManager1_2> gDefaultServiceManager;
216
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700217 {
Steven Moreland89909692018-05-30 14:11:19 -0700218 std::lock_guard<std::mutex> _l(gDefaultServiceManagerLock);
219 if (gDefaultServiceManager != nullptr) {
220 return gDefaultServiceManager;
Yifan Hong8fb656b2017-03-16 14:30:40 -0700221 }
Steven Moreland405d7612017-04-07 20:31:22 -0700222
Yifan Hong8fb656b2017-03-16 14:30:40 -0700223 if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
224 // HwBinder not available on this device or not accessible to
225 // this process.
226 return nullptr;
227 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000228
229 waitForHwServiceManager();
230
Steven Moreland89909692018-05-30 14:11:19 -0700231 while (gDefaultServiceManager == nullptr) {
232 gDefaultServiceManager =
233 fromBinder<IServiceManager1_2, BpHwServiceManager, BnHwServiceManager>(
234 ProcessState::self()->getContextObject(nullptr));
235 if (gDefaultServiceManager == nullptr) {
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000236 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700237 sleep(1);
Yifan Hong8fb656b2017-03-16 14:30:40 -0700238 }
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700239 }
240 }
241
Steven Moreland89909692018-05-30 14:11:19 -0700242 return gDefaultServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700243}
244
Steven Moreland0091c092017-01-20 23:15:18 +0000245std::vector<std::string> search(const std::string &path,
246 const std::string &prefix,
247 const std::string &suffix) {
248 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
249 if (!dir) return {};
250
251 std::vector<std::string> results{};
252
253 dirent* dp;
254 while ((dp = readdir(dir.get())) != nullptr) {
255 std::string name = dp->d_name;
256
Steven Moreland819c05d2017-04-06 17:24:22 -0700257 if (startsWith(name, prefix) &&
258 endsWith(name, suffix)) {
Steven Moreland0091c092017-01-20 23:15:18 +0000259 results.push_back(name);
260 }
261 }
262
263 return results;
264}
265
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700266bool matchPackageName(const std::string& lib, std::string* matchedName, std::string* implName) {
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800267 std::smatch match;
268 if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
269 *matchedName = match.str(1) + "::I*";
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700270 *implName = match.str(2);
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800271 return true;
272 }
273 return false;
274}
275
Yifan Hong7f49f592017-02-03 15:11:44 -0800276static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
Yifan Hongdeacf142018-07-10 17:33:34 -0700277 if (kIsRecovery) {
278 // No hwservicemanager in recovery.
279 return;
280 }
281
Steven Moreland2a2678e2017-07-21 18:07:38 -0700282 sp<IServiceManager1_0> binderizedManager = defaultServiceManager();
Yifan Hong7f49f592017-02-03 15:11:44 -0800283 if (binderizedManager == nullptr) {
284 LOG(WARNING) << "Could not registerReference for "
285 << interfaceName << "/" << instanceName
286 << ": null binderized manager.";
287 return;
288 }
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700289 auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
Yifan Hong7f49f592017-02-03 15:11:44 -0800290 if (!ret.isOk()) {
291 LOG(WARNING) << "Could not registerReference for "
292 << interfaceName << "/" << instanceName
293 << ": " << ret.description();
Steven Moreland0aeaa782017-03-22 08:11:07 -0700294 return;
Yifan Hong7f49f592017-02-03 15:11:44 -0800295 }
Steven Morelande681aa52017-02-15 16:22:37 -0800296 LOG(VERBOSE) << "Successfully registerReference for "
297 << interfaceName << "/" << instanceName;
Yifan Hong7f49f592017-02-03 15:11:44 -0800298}
299
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700300using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
301static inline void fetchPidsForPassthroughLibraries(
302 std::map<std::string, InstanceDebugInfo>* infos) {
303 static const std::string proc = "/proc/";
304
305 std::map<std::string, std::set<pid_t>> pids;
306 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
307 if (!dir) return;
308 dirent* dp;
309 while ((dp = readdir(dir.get())) != nullptr) {
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700310 pid_t pid = strtoll(dp->d_name, nullptr, 0);
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700311 if (pid == 0) continue;
312 std::string mapsPath = proc + dp->d_name + "/maps";
313 std::ifstream ifs{mapsPath};
314 if (!ifs.is_open()) continue;
315
316 for (std::string line; std::getline(ifs, line);) {
317 // The last token of line should look like
318 // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
319 // Use some simple filters to ignore bad lines before extracting libFileName
320 // and checking the key in info to make parsing faster.
321 if (line.back() != 'o') continue;
322 if (line.rfind('@') == std::string::npos) continue;
323
324 auto spacePos = line.rfind(' ');
325 if (spacePos == std::string::npos) continue;
326 auto libFileName = line.substr(spacePos + 1);
327 auto it = infos->find(libFileName);
328 if (it == infos->end()) continue;
329 pids[libFileName].insert(pid);
330 }
331 }
332 for (auto& pair : *infos) {
333 pair.second.clientPids =
334 std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
335 }
336}
337
Steven Moreland2a2678e2017-07-21 18:07:38 -0700338struct PassthroughServiceManager : IServiceManager1_1 {
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -0700339 static void openLibs(
340 const std::string& fqName,
341 const std::function<bool /* continue */ (void* /* handle */, const std::string& /* lib */,
342 const std::string& /* sym */)>& eachLib) {
Steven Moreland819c05d2017-04-06 17:24:22 -0700343 //fqName looks like android.hardware.foo@1.0::IFoo
Steven Moreland519306f2017-06-06 17:14:12 -0700344 size_t idx = fqName.find("::");
Steven Moreland819c05d2017-04-06 17:24:22 -0700345
346 if (idx == std::string::npos ||
Steven Moreland519306f2017-06-06 17:14:12 -0700347 idx + strlen("::") + 1 >= fqName.size()) {
Steven Moreland337e6b62017-01-18 17:25:13 -0800348 LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
Steven Moreland519306f2017-06-06 17:14:12 -0700349 return;
Steven Moreland337e6b62017-01-18 17:25:13 -0800350 }
351
Steven Moreland519306f2017-06-06 17:14:12 -0700352 std::string packageAndVersion = fqName.substr(0, idx);
353 std::string ifaceName = fqName.substr(idx + strlen("::"));
Steven Moreland819c05d2017-04-06 17:24:22 -0700354
355 const std::string prefix = packageAndVersion + "-impl";
356 const std::string sym = "HIDL_FETCH_" + ifaceName;
Steven Moreland348802d2017-02-23 12:48:55 -0800357
Steven Moreland77f4c852017-10-12 11:05:53 -0700358 constexpr int dlMode = RTLD_LAZY;
359 void* handle = nullptr;
Steven Moreland337e6b62017-01-18 17:25:13 -0800360
Steven Morelanda29905c2017-03-01 10:42:35 -0800361 dlerror(); // clear
362
Justin Yun1f048102017-12-01 15:30:08 +0900363 static std::string halLibPathVndkSp = android::base::StringPrintf(
364 HAL_LIBRARY_PATH_VNDK_SP_FOR_VERSION, details::getVndkVersionStr().c_str());
Steven Morelandf7dea692017-07-14 12:49:28 -0700365 std::vector<std::string> paths = {HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR,
Justin Yun1f048102017-12-01 15:30:08 +0900366 halLibPathVndkSp, HAL_LIBRARY_PATH_SYSTEM};
Steven Moreland77f4c852017-10-12 11:05:53 -0700367
Steven Morelandf7dea692017-07-14 12:49:28 -0700368#ifdef LIBHIDL_TARGET_DEBUGGABLE
369 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
370 const bool trebleTestingOverride = env && !strcmp(env, "true");
371 if (trebleTestingOverride) {
Steven Moreland77f4c852017-10-12 11:05:53 -0700372 // Load HAL implementations that are statically linked
373 handle = dlopen(nullptr, dlMode);
374 if (handle == nullptr) {
375 const char* error = dlerror();
376 LOG(ERROR) << "Failed to dlopen self: "
377 << (error == nullptr ? "unknown error" : error);
378 } else if (!eachLib(handle, "SELF", sym)) {
379 return;
380 }
381
Steven Morelandf7dea692017-07-14 12:49:28 -0700382 const char* vtsRootPath = std::getenv("VTS_ROOT_PATH");
383 if (vtsRootPath && strlen(vtsRootPath) > 0) {
384 const std::string halLibraryPathVtsOverride =
385 std::string(vtsRootPath) + HAL_LIBRARY_PATH_SYSTEM;
Steven Moreland77f4c852017-10-12 11:05:53 -0700386 paths.insert(paths.begin(), halLibraryPathVtsOverride);
Steven Morelandf7dea692017-07-14 12:49:28 -0700387 }
388 }
389#endif
Steven Moreland77f4c852017-10-12 11:05:53 -0700390
Steven Morelandf7dea692017-07-14 12:49:28 -0700391 for (const std::string& path : paths) {
Steven Moreland0091c092017-01-20 23:15:18 +0000392 std::vector<std::string> libs = search(path, prefix, ".so");
393
Steven Moreland0091c092017-01-20 23:15:18 +0000394 for (const std::string &lib : libs) {
Steven Moreland348802d2017-02-23 12:48:55 -0800395 const std::string fullPath = path + lib;
396
Yifan Hongdeacf142018-07-10 17:33:34 -0700397 if (kIsRecovery || path == HAL_LIBRARY_PATH_SYSTEM) {
Jiyong Park3ab546c2017-04-06 20:28:07 +0900398 handle = dlopen(fullPath.c_str(), dlMode);
Steven Moreland65c00cb2017-10-12 11:35:22 -0700399 } else {
Jerry Zhang86ae9992018-05-30 17:11:09 -0700400#if !defined(__ANDROID_RECOVERY__)
Steven Moreland65c00cb2017-10-12 11:35:22 -0700401 handle = android_load_sphal_library(fullPath.c_str(), dlMode);
Jerry Zhang86ae9992018-05-30 17:11:09 -0700402#endif
Jiyong Park3ab546c2017-04-06 20:28:07 +0900403 }
404
Steven Moreland348802d2017-02-23 12:48:55 -0800405 if (handle == nullptr) {
406 const char* error = dlerror();
407 LOG(ERROR) << "Failed to dlopen " << lib << ": "
408 << (error == nullptr ? "unknown error" : error);
409 continue;
Steven Moreland0091c092017-01-20 23:15:18 +0000410 }
Steven Moreland348802d2017-02-23 12:48:55 -0800411
Steven Moreland519306f2017-06-06 17:14:12 -0700412 if (!eachLib(handle, lib, sym)) {
413 return;
Steven Moreland348802d2017-02-23 12:48:55 -0800414 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800415 }
416 }
Steven Moreland519306f2017-06-06 17:14:12 -0700417 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800418
Steven Moreland519306f2017-06-06 17:14:12 -0700419 Return<sp<IBase>> get(const hidl_string& fqName,
420 const hidl_string& name) override {
421 sp<IBase> ret = nullptr;
422
423 openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
424 IBase* (*generator)(const char* name);
425 *(void **)(&generator) = dlsym(handle, sym.c_str());
426 if(!generator) {
427 const char* error = dlerror();
428 LOG(ERROR) << "Passthrough lookup opened " << lib
429 << " but could not find symbol " << sym << ": "
430 << (error == nullptr ? "unknown error" : error);
431 dlclose(handle);
432 return true;
433 }
434
435 ret = (*generator)(name.c_str());
436
437 if (ret == nullptr) {
438 dlclose(handle);
439 return true; // this module doesn't provide this instance name
440 }
441
Steven Morelande69e8d32018-03-14 10:55:42 -0700442 // Actual fqname might be a subclass.
443 // This assumption is tested in vts_treble_vintf_test
444 using ::android::hardware::details::getDescriptor;
445 std::string actualFqName = getDescriptor(ret.get());
446 CHECK(actualFqName.size() > 0);
447 registerReference(actualFqName, name);
Steven Moreland519306f2017-06-06 17:14:12 -0700448 return false;
449 });
450
451 return ret;
Steven Moreland337e6b62017-01-18 17:25:13 -0800452 }
453
Martijn Coenen67a02492017-03-06 13:04:48 +0100454 Return<bool> add(const hidl_string& /* name */,
Steven Moreland337e6b62017-01-18 17:25:13 -0800455 const sp<IBase>& /* service */) override {
456 LOG(FATAL) << "Cannot register services with passthrough service manager.";
457 return false;
458 }
459
Steven Morelandc601c5f2017-04-06 09:26:07 -0700460 Return<Transport> getTransport(const hidl_string& /* fqName */,
461 const hidl_string& /* name */) {
462 LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
463 return Transport::EMPTY;
464 }
465
Yifan Hong705e5da2017-03-02 16:59:39 -0800466 Return<void> list(list_cb /* _hidl_cb */) override {
467 LOG(FATAL) << "Cannot list services with passthrough service manager.";
Steven Moreland337e6b62017-01-18 17:25:13 -0800468 return Void();
469 }
470 Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
471 listByInterface_cb /* _hidl_cb */) override {
472 // TODO: add this functionality
473 LOG(FATAL) << "Cannot list services with passthrough service manager.";
474 return Void();
475 }
476
477 Return<bool> registerForNotifications(const hidl_string& /* fqName */,
478 const hidl_string& /* name */,
479 const sp<IServiceNotification>& /* callback */) override {
480 // This makes no sense.
481 LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
482 return false;
483 }
484
Yifan Hong705e5da2017-03-02 16:59:39 -0800485 Return<void> debugDump(debugDump_cb _hidl_cb) override {
486 using Arch = ::android::hidl::base::V1_0::DebugInfo::Architecture;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700487 using std::literals::string_literals::operator""s;
Justin Yun1f048102017-12-01 15:30:08 +0900488 static std::string halLibPathVndkSp64 = android::base::StringPrintf(
489 HAL_LIBRARY_PATH_VNDK_SP_64BIT_FOR_VERSION, details::getVndkVersionStr().c_str());
490 static std::string halLibPathVndkSp32 = android::base::StringPrintf(
491 HAL_LIBRARY_PATH_VNDK_SP_32BIT_FOR_VERSION, details::getVndkVersionStr().c_str());
Jiyong Park56eb1492017-08-04 16:16:13 +0900492 static std::vector<std::pair<Arch, std::vector<const char*>>> sAllPaths{
493 {Arch::IS_64BIT,
494 {HAL_LIBRARY_PATH_ODM_64BIT, HAL_LIBRARY_PATH_VENDOR_64BIT,
Justin Yun1f048102017-12-01 15:30:08 +0900495 halLibPathVndkSp64.c_str(), HAL_LIBRARY_PATH_SYSTEM_64BIT}},
Jiyong Park56eb1492017-08-04 16:16:13 +0900496 {Arch::IS_32BIT,
497 {HAL_LIBRARY_PATH_ODM_32BIT, HAL_LIBRARY_PATH_VENDOR_32BIT,
Justin Yun1f048102017-12-01 15:30:08 +0900498 halLibPathVndkSp32.c_str(), HAL_LIBRARY_PATH_SYSTEM_32BIT}}};
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700499 std::map<std::string, InstanceDebugInfo> map;
Yifan Hong705e5da2017-03-02 16:59:39 -0800500 for (const auto &pair : sAllPaths) {
501 Arch arch = pair.first;
502 for (const auto &path : pair.second) {
503 std::vector<std::string> libs = search(path, "", ".so");
504 for (const std::string &lib : libs) {
505 std::string matchedName;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700506 std::string implName;
507 if (matchPackageName(lib, &matchedName, &implName)) {
508 std::string instanceName{"* ("s + path + ")"s};
509 if (!implName.empty()) instanceName += " ("s + implName + ")"s;
510 map.emplace(path + lib, InstanceDebugInfo{.interfaceName = matchedName,
511 .instanceName = instanceName,
512 .clientPids = {},
513 .arch = arch});
Yifan Hong705e5da2017-03-02 16:59:39 -0800514 }
515 }
516 }
517 }
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700518 fetchPidsForPassthroughLibraries(&map);
519 hidl_vec<InstanceDebugInfo> vec;
520 vec.resize(map.size());
521 size_t idx = 0;
522 for (auto&& pair : map) {
523 vec[idx++] = std::move(pair.second);
524 }
Yifan Hong705e5da2017-03-02 16:59:39 -0800525 _hidl_cb(vec);
Yifan Hong7f49f592017-02-03 15:11:44 -0800526 return Void();
527 }
528
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700529 Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
Yifan Hong7f49f592017-02-03 15:11:44 -0800530 // This makes no sense.
531 LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
532 << "Call it on defaultServiceManager() instead.";
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800533 return Void();
534 }
535
Steven Moreland2a2678e2017-07-21 18:07:38 -0700536 Return<bool> unregisterForNotifications(const hidl_string& /* fqName */,
537 const hidl_string& /* name */,
538 const sp<IServiceNotification>& /* callback */) override {
539 // This makes no sense.
540 LOG(FATAL) << "Cannot unregister for notifications with passthrough service manager.";
541 return false;
542 }
543
Steven Moreland337e6b62017-01-18 17:25:13 -0800544};
545
Steven Moreland2a2678e2017-07-21 18:07:38 -0700546sp<IServiceManager1_0> getPassthroughServiceManager() {
547 return getPassthroughServiceManager1_1();
548}
549sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
Steven Moreland337e6b62017-01-18 17:25:13 -0800550 static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
551 return manager;
552}
553
Steven Morelandcbefd352017-01-23 20:29:05 -0800554namespace details {
555
Steven Moreland519306f2017-06-06 17:14:12 -0700556void preloadPassthroughService(const std::string &descriptor) {
557 PassthroughServiceManager::openLibs(descriptor,
558 [&](void* /* handle */, const std::string& /* lib */, const std::string& /* sym */) {
559 // do nothing
560 return true; // open all libs
561 });
562}
563
Steven Morelandcbefd352017-01-23 20:29:05 -0800564struct Waiter : IServiceNotification {
Martijn Coenen773609e2017-10-24 09:57:53 +0200565 Waiter(const std::string& interface, const std::string& instanceName,
566 const sp<IServiceManager1_1>& sm) : mInterfaceName(interface),
567 mInstanceName(instanceName), mSm(sm) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100568 }
569
570 void onFirstRef() override {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200571 // If this process only has one binder thread, and we're calling wait() from
572 // that thread, it will block forever because we hung up the one and only
573 // binder thread on a condition variable that can only be notified by an
574 // incoming binder call.
Tobias Lindskog88e886f2018-01-05 10:32:43 +0100575 if (IPCThreadState::self()->isOnlyBinderThread()) {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200576 LOG(WARNING) << "Can't efficiently wait for " << mInterfaceName << "/"
577 << mInstanceName << ", because we are called from "
578 << "the only binder thread in this process.";
579 return;
580 }
581
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100582 Return<bool> ret = mSm->registerForNotifications(mInterfaceName, mInstanceName, this);
Martijn Coenen773609e2017-10-24 09:57:53 +0200583
584 if (!ret.isOk()) {
585 LOG(ERROR) << "Transport error, " << ret.description()
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100586 << ", during notification registration for " << mInterfaceName << "/"
587 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200588 return;
589 }
590
591 if (!ret) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100592 LOG(ERROR) << "Could not register for notifications for " << mInterfaceName << "/"
593 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200594 return;
595 }
596
597 mRegisteredForNotifications = true;
598 }
599
600 ~Waiter() {
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100601 if (!mDoneCalled) {
602 LOG(FATAL)
603 << "Waiter still registered for notifications, call done() before dropping ref!";
Martijn Coenen773609e2017-10-24 09:57:53 +0200604 }
605 }
606
Steven Morelandcbefd352017-01-23 20:29:05 -0800607 Return<void> onRegistration(const hidl_string& /* fqName */,
608 const hidl_string& /* name */,
609 bool /* preexisting */) override {
610 std::unique_lock<std::mutex> lock(mMutex);
611 if (mRegistered) {
612 return Void();
613 }
614 mRegistered = true;
615 lock.unlock();
616
617 mCondition.notify_one();
618 return Void();
619 }
620
Steven Moreland0771d8a2018-05-09 13:29:14 -0700621 void wait(bool timeout) {
Steven Moreland49605102017-03-28 09:33:06 -0700622 using std::literals::chrono_literals::operator""s;
623
Martijn Coenen773609e2017-10-24 09:57:53 +0200624 if (!mRegisteredForNotifications) {
625 // As an alternative, just sleep for a second and return
626 LOG(WARNING) << "Waiting one second for " << mInterfaceName << "/" << mInstanceName;
627 sleep(1);
628 return;
629 }
630
Steven Morelandcbefd352017-01-23 20:29:05 -0800631 std::unique_lock<std::mutex> lock(mMutex);
Steven Moreland0771d8a2018-05-09 13:29:14 -0700632 do {
Steven Moreland49605102017-03-28 09:33:06 -0700633 mCondition.wait_for(lock, 1s, [this]{
634 return mRegistered;
635 });
636
637 if (mRegistered) {
638 break;
639 }
640
Steven Moreland0771d8a2018-05-09 13:29:14 -0700641 LOG(WARNING) << "Waited one second for " << mInterfaceName << "/" << mInstanceName;
642 } while (!timeout);
Steven Morelandcbefd352017-01-23 20:29:05 -0800643 }
644
Martijn Coenen773609e2017-10-24 09:57:53 +0200645 // Be careful when using this; after calling reset(), you must always try to retrieve
646 // the corresponding service before blocking on the waiter; otherwise, you might run
647 // into a race-condition where the service has just (re-)registered, you clear the state
648 // here, and subsequently calling waiter->wait() will block forever.
649 void reset() {
650 std::unique_lock<std::mutex> lock(mMutex);
651 mRegistered = false;
652 }
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100653
654 // done() must be called before dropping the last strong ref to the Waiter, to make
655 // sure we can properly unregister with hwservicemanager.
656 void done() {
657 if (mRegisteredForNotifications) {
658 if (!mSm->unregisterForNotifications(mInterfaceName, mInstanceName, this)
659 .withDefault(false)) {
660 LOG(ERROR) << "Could not unregister service notification for " << mInterfaceName
661 << "/" << mInstanceName << ".";
662 } else {
663 mRegisteredForNotifications = false;
664 }
665 }
666 mDoneCalled = true;
667 }
668
669 private:
Martijn Coenen773609e2017-10-24 09:57:53 +0200670 const std::string mInterfaceName;
671 const std::string mInstanceName;
Steven Morelandad1f9922018-10-02 19:37:05 -0700672 sp<IServiceManager1_1> mSm;
Steven Morelandcbefd352017-01-23 20:29:05 -0800673 std::mutex mMutex;
674 std::condition_variable mCondition;
675 bool mRegistered = false;
Martijn Coenen773609e2017-10-24 09:57:53 +0200676 bool mRegisteredForNotifications = false;
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100677 bool mDoneCalled = false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800678};
679
680void waitForHwService(
681 const std::string &interface, const std::string &instanceName) {
Martijn Coenen773609e2017-10-24 09:57:53 +0200682 sp<Waiter> waiter = new Waiter(interface, instanceName, defaultServiceManager1_1());
Steven Moreland0771d8a2018-05-09 13:29:14 -0700683 waiter->wait(false /* timeout */);
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100684 waiter->done();
Martijn Coenen773609e2017-10-24 09:57:53 +0200685}
Steven Morelandcbefd352017-01-23 20:29:05 -0800686
Martijn Coenen773609e2017-10-24 09:57:53 +0200687// Prints relevant error/warning messages for error return values from
688// details::canCastInterface(), both transaction errors (!castReturn.isOk())
689// as well as actual cast failures (castReturn.isOk() && castReturn = false).
690// Returns 'true' if the error is non-fatal and it's useful to retry
691bool handleCastError(const Return<bool>& castReturn, const std::string& descriptor,
692 const std::string& instance) {
693 if (castReturn.isOk()) {
694 if (castReturn) {
695 details::logAlwaysFatal("Successful cast value passed into handleCastError.");
696 }
697 // This should never happen, and there's not really a point in retrying.
698 ALOGE("getService: received incompatible service (bug in hwservicemanager?) for "
699 "%s/%s.", descriptor.c_str(), instance.c_str());
700 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800701 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200702 if (castReturn.isDeadObject()) {
703 ALOGW("getService: found dead hwbinder service for %s/%s.", descriptor.c_str(),
704 instance.c_str());
705 return true;
Steven Morelandcbefd352017-01-23 20:29:05 -0800706 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200707 // This can happen due to:
708 // 1) No SELinux permissions
709 // 2) Other transaction failure (no buffer space, kernel error)
710 // The first isn't recoverable, but the second is.
711 // Since we can't yet differentiate between the two, and clients depend
712 // on us not blocking in case 1), treat this as a fatal error for now.
713 ALOGW("getService: unable to call into hwbinder service for %s/%s.",
714 descriptor.c_str(), instance.c_str());
715 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800716}
717
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200718sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
719 const std::string& instance,
720 bool retry, bool getStub) {
721 using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
722 using ::android::hidl::base::V1_0::IBase;
723 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenend35678f2018-03-07 09:51:01 +0100724 sp<Waiter> waiter;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200725
Yifan Hongdeacf142018-07-10 17:33:34 -0700726 sp<IServiceManager1_1> sm;
727 Transport transport = Transport::EMPTY;
728 if (kIsRecovery) {
Yifan Hongdeacf142018-07-10 17:33:34 -0700729 transport = Transport::PASSTHROUGH;
Yifan Hongdeacf142018-07-10 17:33:34 -0700730 } else {
731 sm = defaultServiceManager1_1();
732 if (sm == nullptr) {
733 ALOGE("getService: defaultServiceManager() is null");
734 return nullptr;
735 }
736
737 Return<Transport> transportRet = sm->getTransport(descriptor, instance);
738
739 if (!transportRet.isOk()) {
740 ALOGE("getService: defaultServiceManager()->getTransport returns %s",
741 transportRet.description().c_str());
742 return nullptr;
743 }
744 transport = transportRet;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200745 }
746
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200747 const bool vintfHwbinder = (transport == Transport::HWBINDER);
748 const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
749
Steven Moreland757394b2017-12-13 14:09:24 -0800750#ifdef ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200751
752#ifdef LIBHIDL_TARGET_DEBUGGABLE
753 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
754 const bool trebleTestingOverride = env && !strcmp(env, "true");
755 const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
Steven Moreland757394b2017-12-13 14:09:24 -0800756#else // ENFORCE_VINTF_MANIFEST but not LIBHIDL_TARGET_DEBUGGABLE
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200757 const bool trebleTestingOverride = false;
758 const bool vintfLegacy = false;
759#endif // LIBHIDL_TARGET_DEBUGGABLE
760
Steven Moreland757394b2017-12-13 14:09:24 -0800761#else // not ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200762 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
763 const bool trebleTestingOverride = env && !strcmp(env, "true");
764 const bool vintfLegacy = (transport == Transport::EMPTY);
Steven Moreland757394b2017-12-13 14:09:24 -0800765#endif // ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200766
Steven Moreland76371242018-04-19 17:11:39 -0700767 for (int tries = 0; !getStub && (vintfHwbinder || vintfLegacy); tries++) {
768 if (waiter == nullptr && tries > 0) {
Martijn Coenend35678f2018-03-07 09:51:01 +0100769 waiter = new Waiter(descriptor, instance, sm);
770 }
Steven Moreland76371242018-04-19 17:11:39 -0700771 if (waiter != nullptr) {
772 waiter->reset(); // don't reorder this -- see comments on reset()
773 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200774 Return<sp<IBase>> ret = sm->get(descriptor, instance);
775 if (!ret.isOk()) {
776 ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.",
777 ret.description().c_str(), descriptor.c_str(), instance.c_str());
778 break;
779 }
780 sp<IBase> base = ret;
Martijn Coenen773609e2017-10-24 09:57:53 +0200781 if (base != nullptr) {
782 Return<bool> canCastRet =
783 details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
784
785 if (canCastRet.isOk() && canCastRet) {
Steven Moreland76371242018-04-19 17:11:39 -0700786 if (waiter != nullptr) {
787 waiter->done();
788 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200789 return base; // still needs to be wrapped by Bp class.
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200790 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200791
792 if (!handleCastError(canCastRet, descriptor, instance)) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200793 }
794
Martijn Coenen773609e2017-10-24 09:57:53 +0200795 // In case of legacy or we were not asked to retry, don't.
796 if (vintfLegacy || !retry) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200797
Steven Moreland76371242018-04-19 17:11:39 -0700798 if (waiter != nullptr) {
799 ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
Steven Moreland0771d8a2018-05-09 13:29:14 -0700800 waiter->wait(true /* timeout */);
Steven Moreland76371242018-04-19 17:11:39 -0700801 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200802 }
803
Martijn Coenend35678f2018-03-07 09:51:01 +0100804 if (waiter != nullptr) {
805 waiter->done();
806 }
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100807
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200808 if (getStub || vintfPassthru || vintfLegacy) {
809 const sp<IServiceManager> pm = getPassthroughServiceManager();
810 if (pm != nullptr) {
811 sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
812 if (!getStub || trebleTestingOverride) {
813 base = wrapPassthrough(base);
814 }
815 return base;
816 }
817 }
818
819 return nullptr;
820}
821
Bernhard Rosenkränzer0c28fd22018-06-04 16:01:47 +0200822} // namespace details
Steven Morelandcbefd352017-01-23 20:29:05 -0800823
Bernhard Rosenkränzer0c28fd22018-06-04 16:01:47 +0200824} // namespace hardware
825} // namespace android