blob: 57434d7643f6f9b9a2b1b5e6859d92d60484e689 [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>
36
Steven Moreland337e6b62017-01-18 17:25:13 -080037#include <android-base/logging.h>
Steven Morelandc1cee2c2017-03-24 16:23:11 +000038#include <android-base/properties.h>
Justin Yun1f048102017-12-01 15:30:08 +090039#include <android-base/stringprintf.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070040#include <hwbinder/IPCThreadState.h>
41#include <hwbinder/Parcel.h>
Jerry Zhang86ae9992018-05-30 17:11:09 -070042#if !defined(__ANDROID_RECOVERY__)
Jiyong Parkba8ace12017-05-15 15:44:39 +090043#include <vndksupport/linker.h>
Jerry Zhang86ae9992018-05-30 17:11:09 -070044#endif
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070045
Steven Moreland89909692018-05-30 14:11:19 -070046#include <android/hidl/manager/1.2/BnHwServiceManager.h>
47#include <android/hidl/manager/1.2/BpHwServiceManager.h>
48#include <android/hidl/manager/1.2/IServiceManager.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070049
Yifan Hong9a22d1d2017-01-25 14:19:26 -080050#define RE_COMPONENT "[a-zA-Z_][a-zA-Z_0-9]*"
51#define RE_PATH RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
52static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
53
Steven Morelandc1cee2c2017-03-24 16:23:11 +000054using android::base::WaitForProperty;
55
Steven Moreland2a2678e2017-07-21 18:07:38 -070056using IServiceManager1_0 = android::hidl::manager::V1_0::IServiceManager;
57using IServiceManager1_1 = android::hidl::manager::V1_1::IServiceManager;
Steven Moreland89909692018-05-30 14:11:19 -070058using IServiceManager1_2 = android::hidl::manager::V1_2::IServiceManager;
Steven Moreland337e6b62017-01-18 17:25:13 -080059using android::hidl::manager::V1_0::IServiceNotification;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070060
61namespace android {
62namespace hardware {
63
Steven Morelandc1cee2c2017-03-24 16:23:11 +000064static const char* kHwServicemanagerReadyProperty = "hwservicemanager.ready";
65
Yifan Hongdeacf142018-07-10 17:33:34 -070066#if defined(__ANDROID_RECOVERY__)
67static constexpr bool kIsRecovery = true;
68#else
69static constexpr bool kIsRecovery = false;
70#endif
71
Steven Morelandc1cee2c2017-03-24 16:23:11 +000072void waitForHwServiceManager() {
73 using std::literals::chrono_literals::operator""s;
74
75 while (!WaitForProperty(kHwServicemanagerReadyProperty, "true", 1s)) {
76 LOG(WARNING) << "Waited for hwservicemanager.ready for a second, waiting another...";
77 }
78}
79
Steven Moreland405d7612017-04-07 20:31:22 -070080bool endsWith(const std::string &in, const std::string &suffix) {
81 return in.size() >= suffix.size() &&
82 in.substr(in.size() - suffix.size()) == suffix;
83}
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070084
Steven Moreland405d7612017-04-07 20:31:22 -070085bool startsWith(const std::string &in, const std::string &prefix) {
86 return in.size() >= prefix.size() &&
87 in.substr(0, prefix.size()) == prefix;
88}
89
90std::string binaryName() {
91 std::ifstream ifs("/proc/self/cmdline");
92 std::string cmdline;
93 if (!ifs.is_open()) {
94 return "";
95 }
96 ifs >> cmdline;
97
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -070098 size_t idx = cmdline.rfind('/');
Steven Moreland405d7612017-04-07 20:31:22 -070099 if (idx != std::string::npos) {
100 cmdline = cmdline.substr(idx + 1);
101 }
102
103 return cmdline;
104}
105
Steven Moreland7d09a402018-04-06 10:44:05 -0700106std::string packageWithoutVersion(const std::string& packageAndVersion) {
107 size_t at = packageAndVersion.find('@');
108 if (at == std::string::npos) return packageAndVersion;
109 return packageAndVersion.substr(0, at);
110}
111
112void tryShortenProcessName(const std::string& packageAndVersion) {
113 const static std::string kTasks = "/proc/self/task/";
114
115 // make sure that this binary name is in the same package
Steven Moreland405d7612017-04-07 20:31:22 -0700116 std::string processName = binaryName();
117
Steven Moreland7d09a402018-04-06 10:44:05 -0700118 // e.x. android.hardware.foo is this package
119 if (!startsWith(packageWithoutVersion(processName), packageWithoutVersion(packageAndVersion))) {
Steven Moreland405d7612017-04-07 20:31:22 -0700120 return;
121 }
122
Steven Moreland7d09a402018-04-06 10:44:05 -0700123 // e.x. android.hardware.module.foo@1.2 -> foo@1.2
124 size_t lastDot = packageAndVersion.rfind('.');
125 if (lastDot == std::string::npos) return;
126 size_t secondDot = packageAndVersion.rfind('.', lastDot - 1);
127 if (secondDot == std::string::npos) return;
Steven Moreland405d7612017-04-07 20:31:22 -0700128
Steven Moreland7d09a402018-04-06 10:44:05 -0700129 std::string newName = processName.substr(secondDot + 1, std::string::npos);
130 ALOGI("Removing namespace from process name %s to %s.", processName.c_str(), newName.c_str());
131
132 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kTasks.c_str()), closedir);
133 if (dir == nullptr) return;
134
135 dirent* dp;
136 while ((dp = readdir(dir.get())) != nullptr) {
137 if (dp->d_type != DT_DIR) continue;
138 if (dp->d_name[0] == '.') continue;
139
140 std::fstream fs(kTasks + dp->d_name + "/comm");
141 if (!fs.is_open()) {
142 ALOGI("Could not rename process, failed read comm for %s.", dp->d_name);
143 continue;
144 }
145
146 std::string oldComm;
147 fs >> oldComm;
148
149 // don't rename if it already has an explicit name
150 if (startsWith(packageAndVersion, oldComm)) {
151 fs.seekg(0, fs.beg);
152 fs << newName;
153 }
Steven Moreland405d7612017-04-07 20:31:22 -0700154 }
Steven Moreland405d7612017-04-07 20:31:22 -0700155}
156
157namespace details {
158
159void onRegistration(const std::string &packageName,
160 const std::string& /* interfaceName */,
161 const std::string& /* instanceName */) {
162 tryShortenProcessName(packageName);
163}
164
165} // details
166
Steven Moreland2a2678e2017-07-21 18:07:38 -0700167sp<IServiceManager1_0> defaultServiceManager() {
Steven Moreland89909692018-05-30 14:11:19 -0700168 return defaultServiceManager1_2();
Steven Moreland2a2678e2017-07-21 18:07:38 -0700169}
170sp<IServiceManager1_1> defaultServiceManager1_1() {
Steven Moreland89909692018-05-30 14:11:19 -0700171 return defaultServiceManager1_2();
172}
173sp<IServiceManager1_2> defaultServiceManager1_2() {
174 using android::hidl::manager::V1_2::BnHwServiceManager;
175 using android::hidl::manager::V1_2::BpHwServiceManager;
176
177 static std::mutex gDefaultServiceManagerLock;
178 static sp<IServiceManager1_2> gDefaultServiceManager;
179
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700180 {
Steven Moreland89909692018-05-30 14:11:19 -0700181 std::lock_guard<std::mutex> _l(gDefaultServiceManagerLock);
182 if (gDefaultServiceManager != nullptr) {
183 return gDefaultServiceManager;
Yifan Hong8fb656b2017-03-16 14:30:40 -0700184 }
Steven Moreland405d7612017-04-07 20:31:22 -0700185
Yifan Hong8fb656b2017-03-16 14:30:40 -0700186 if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
187 // HwBinder not available on this device or not accessible to
188 // this process.
189 return nullptr;
190 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000191
192 waitForHwServiceManager();
193
Steven Moreland89909692018-05-30 14:11:19 -0700194 while (gDefaultServiceManager == nullptr) {
195 gDefaultServiceManager =
196 fromBinder<IServiceManager1_2, BpHwServiceManager, BnHwServiceManager>(
197 ProcessState::self()->getContextObject(nullptr));
198 if (gDefaultServiceManager == nullptr) {
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000199 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700200 sleep(1);
Yifan Hong8fb656b2017-03-16 14:30:40 -0700201 }
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700202 }
203 }
204
Steven Moreland89909692018-05-30 14:11:19 -0700205 return gDefaultServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700206}
207
Steven Moreland0091c092017-01-20 23:15:18 +0000208std::vector<std::string> search(const std::string &path,
209 const std::string &prefix,
210 const std::string &suffix) {
211 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
212 if (!dir) return {};
213
214 std::vector<std::string> results{};
215
216 dirent* dp;
217 while ((dp = readdir(dir.get())) != nullptr) {
218 std::string name = dp->d_name;
219
Steven Moreland819c05d2017-04-06 17:24:22 -0700220 if (startsWith(name, prefix) &&
221 endsWith(name, suffix)) {
Steven Moreland0091c092017-01-20 23:15:18 +0000222 results.push_back(name);
223 }
224 }
225
226 return results;
227}
228
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700229bool matchPackageName(const std::string& lib, std::string* matchedName, std::string* implName) {
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800230 std::smatch match;
231 if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
232 *matchedName = match.str(1) + "::I*";
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700233 *implName = match.str(2);
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800234 return true;
235 }
236 return false;
237}
238
Yifan Hong7f49f592017-02-03 15:11:44 -0800239static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
Yifan Hongdeacf142018-07-10 17:33:34 -0700240 if (kIsRecovery) {
241 // No hwservicemanager in recovery.
242 return;
243 }
244
Steven Moreland2a2678e2017-07-21 18:07:38 -0700245 sp<IServiceManager1_0> binderizedManager = defaultServiceManager();
Yifan Hong7f49f592017-02-03 15:11:44 -0800246 if (binderizedManager == nullptr) {
247 LOG(WARNING) << "Could not registerReference for "
248 << interfaceName << "/" << instanceName
249 << ": null binderized manager.";
250 return;
251 }
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700252 auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
Yifan Hong7f49f592017-02-03 15:11:44 -0800253 if (!ret.isOk()) {
254 LOG(WARNING) << "Could not registerReference for "
255 << interfaceName << "/" << instanceName
256 << ": " << ret.description();
Steven Moreland0aeaa782017-03-22 08:11:07 -0700257 return;
Yifan Hong7f49f592017-02-03 15:11:44 -0800258 }
Steven Morelande681aa52017-02-15 16:22:37 -0800259 LOG(VERBOSE) << "Successfully registerReference for "
260 << interfaceName << "/" << instanceName;
Yifan Hong7f49f592017-02-03 15:11:44 -0800261}
262
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700263using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
264static inline void fetchPidsForPassthroughLibraries(
265 std::map<std::string, InstanceDebugInfo>* infos) {
266 static const std::string proc = "/proc/";
267
268 std::map<std::string, std::set<pid_t>> pids;
269 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
270 if (!dir) return;
271 dirent* dp;
272 while ((dp = readdir(dir.get())) != nullptr) {
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700273 pid_t pid = strtoll(dp->d_name, nullptr, 0);
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700274 if (pid == 0) continue;
275 std::string mapsPath = proc + dp->d_name + "/maps";
276 std::ifstream ifs{mapsPath};
277 if (!ifs.is_open()) continue;
278
279 for (std::string line; std::getline(ifs, line);) {
280 // The last token of line should look like
281 // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
282 // Use some simple filters to ignore bad lines before extracting libFileName
283 // and checking the key in info to make parsing faster.
284 if (line.back() != 'o') continue;
285 if (line.rfind('@') == std::string::npos) continue;
286
287 auto spacePos = line.rfind(' ');
288 if (spacePos == std::string::npos) continue;
289 auto libFileName = line.substr(spacePos + 1);
290 auto it = infos->find(libFileName);
291 if (it == infos->end()) continue;
292 pids[libFileName].insert(pid);
293 }
294 }
295 for (auto& pair : *infos) {
296 pair.second.clientPids =
297 std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
298 }
299}
300
Steven Moreland2a2678e2017-07-21 18:07:38 -0700301struct PassthroughServiceManager : IServiceManager1_1 {
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -0700302 static void openLibs(
303 const std::string& fqName,
304 const std::function<bool /* continue */ (void* /* handle */, const std::string& /* lib */,
305 const std::string& /* sym */)>& eachLib) {
Steven Moreland819c05d2017-04-06 17:24:22 -0700306 //fqName looks like android.hardware.foo@1.0::IFoo
Steven Moreland519306f2017-06-06 17:14:12 -0700307 size_t idx = fqName.find("::");
Steven Moreland819c05d2017-04-06 17:24:22 -0700308
309 if (idx == std::string::npos ||
Steven Moreland519306f2017-06-06 17:14:12 -0700310 idx + strlen("::") + 1 >= fqName.size()) {
Steven Moreland337e6b62017-01-18 17:25:13 -0800311 LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
Steven Moreland519306f2017-06-06 17:14:12 -0700312 return;
Steven Moreland337e6b62017-01-18 17:25:13 -0800313 }
314
Steven Moreland519306f2017-06-06 17:14:12 -0700315 std::string packageAndVersion = fqName.substr(0, idx);
316 std::string ifaceName = fqName.substr(idx + strlen("::"));
Steven Moreland819c05d2017-04-06 17:24:22 -0700317
318 const std::string prefix = packageAndVersion + "-impl";
319 const std::string sym = "HIDL_FETCH_" + ifaceName;
Steven Moreland348802d2017-02-23 12:48:55 -0800320
Steven Moreland77f4c852017-10-12 11:05:53 -0700321 constexpr int dlMode = RTLD_LAZY;
322 void* handle = nullptr;
Steven Moreland337e6b62017-01-18 17:25:13 -0800323
Steven Morelanda29905c2017-03-01 10:42:35 -0800324 dlerror(); // clear
325
Justin Yun1f048102017-12-01 15:30:08 +0900326 static std::string halLibPathVndkSp = android::base::StringPrintf(
327 HAL_LIBRARY_PATH_VNDK_SP_FOR_VERSION, details::getVndkVersionStr().c_str());
Steven Morelandf7dea692017-07-14 12:49:28 -0700328 std::vector<std::string> paths = {HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR,
Justin Yun1f048102017-12-01 15:30:08 +0900329 halLibPathVndkSp, HAL_LIBRARY_PATH_SYSTEM};
Steven Moreland77f4c852017-10-12 11:05:53 -0700330
Steven Morelandf7dea692017-07-14 12:49:28 -0700331#ifdef LIBHIDL_TARGET_DEBUGGABLE
332 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
333 const bool trebleTestingOverride = env && !strcmp(env, "true");
334 if (trebleTestingOverride) {
Steven Moreland77f4c852017-10-12 11:05:53 -0700335 // Load HAL implementations that are statically linked
336 handle = dlopen(nullptr, dlMode);
337 if (handle == nullptr) {
338 const char* error = dlerror();
339 LOG(ERROR) << "Failed to dlopen self: "
340 << (error == nullptr ? "unknown error" : error);
341 } else if (!eachLib(handle, "SELF", sym)) {
342 return;
343 }
344
Steven Morelandf7dea692017-07-14 12:49:28 -0700345 const char* vtsRootPath = std::getenv("VTS_ROOT_PATH");
346 if (vtsRootPath && strlen(vtsRootPath) > 0) {
347 const std::string halLibraryPathVtsOverride =
348 std::string(vtsRootPath) + HAL_LIBRARY_PATH_SYSTEM;
Steven Moreland77f4c852017-10-12 11:05:53 -0700349 paths.insert(paths.begin(), halLibraryPathVtsOverride);
Steven Morelandf7dea692017-07-14 12:49:28 -0700350 }
351 }
352#endif
Steven Moreland77f4c852017-10-12 11:05:53 -0700353
Steven Morelandf7dea692017-07-14 12:49:28 -0700354 for (const std::string& path : paths) {
Steven Moreland0091c092017-01-20 23:15:18 +0000355 std::vector<std::string> libs = search(path, prefix, ".so");
356
Steven Moreland0091c092017-01-20 23:15:18 +0000357 for (const std::string &lib : libs) {
Steven Moreland348802d2017-02-23 12:48:55 -0800358 const std::string fullPath = path + lib;
359
Yifan Hongdeacf142018-07-10 17:33:34 -0700360 if (kIsRecovery || path == HAL_LIBRARY_PATH_SYSTEM) {
Jiyong Park3ab546c2017-04-06 20:28:07 +0900361 handle = dlopen(fullPath.c_str(), dlMode);
Steven Moreland65c00cb2017-10-12 11:35:22 -0700362 } else {
Jerry Zhang86ae9992018-05-30 17:11:09 -0700363#if !defined(__ANDROID_RECOVERY__)
Steven Moreland65c00cb2017-10-12 11:35:22 -0700364 handle = android_load_sphal_library(fullPath.c_str(), dlMode);
Jerry Zhang86ae9992018-05-30 17:11:09 -0700365#endif
Jiyong Park3ab546c2017-04-06 20:28:07 +0900366 }
367
Steven Moreland348802d2017-02-23 12:48:55 -0800368 if (handle == nullptr) {
369 const char* error = dlerror();
370 LOG(ERROR) << "Failed to dlopen " << lib << ": "
371 << (error == nullptr ? "unknown error" : error);
372 continue;
Steven Moreland0091c092017-01-20 23:15:18 +0000373 }
Steven Moreland348802d2017-02-23 12:48:55 -0800374
Steven Moreland519306f2017-06-06 17:14:12 -0700375 if (!eachLib(handle, lib, sym)) {
376 return;
Steven Moreland348802d2017-02-23 12:48:55 -0800377 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800378 }
379 }
Steven Moreland519306f2017-06-06 17:14:12 -0700380 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800381
Steven Moreland519306f2017-06-06 17:14:12 -0700382 Return<sp<IBase>> get(const hidl_string& fqName,
383 const hidl_string& name) override {
384 sp<IBase> ret = nullptr;
385
386 openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
387 IBase* (*generator)(const char* name);
388 *(void **)(&generator) = dlsym(handle, sym.c_str());
389 if(!generator) {
390 const char* error = dlerror();
391 LOG(ERROR) << "Passthrough lookup opened " << lib
392 << " but could not find symbol " << sym << ": "
393 << (error == nullptr ? "unknown error" : error);
394 dlclose(handle);
395 return true;
396 }
397
398 ret = (*generator)(name.c_str());
399
400 if (ret == nullptr) {
401 dlclose(handle);
402 return true; // this module doesn't provide this instance name
403 }
404
Steven Morelande69e8d32018-03-14 10:55:42 -0700405 // Actual fqname might be a subclass.
406 // This assumption is tested in vts_treble_vintf_test
407 using ::android::hardware::details::getDescriptor;
408 std::string actualFqName = getDescriptor(ret.get());
409 CHECK(actualFqName.size() > 0);
410 registerReference(actualFqName, name);
Steven Moreland519306f2017-06-06 17:14:12 -0700411 return false;
412 });
413
414 return ret;
Steven Moreland337e6b62017-01-18 17:25:13 -0800415 }
416
Martijn Coenen67a02492017-03-06 13:04:48 +0100417 Return<bool> add(const hidl_string& /* name */,
Steven Moreland337e6b62017-01-18 17:25:13 -0800418 const sp<IBase>& /* service */) override {
419 LOG(FATAL) << "Cannot register services with passthrough service manager.";
420 return false;
421 }
422
Steven Morelandc601c5f2017-04-06 09:26:07 -0700423 Return<Transport> getTransport(const hidl_string& /* fqName */,
424 const hidl_string& /* name */) {
425 LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
426 return Transport::EMPTY;
427 }
428
Yifan Hong705e5da2017-03-02 16:59:39 -0800429 Return<void> list(list_cb /* _hidl_cb */) override {
430 LOG(FATAL) << "Cannot list services with passthrough service manager.";
Steven Moreland337e6b62017-01-18 17:25:13 -0800431 return Void();
432 }
433 Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
434 listByInterface_cb /* _hidl_cb */) override {
435 // TODO: add this functionality
436 LOG(FATAL) << "Cannot list services with passthrough service manager.";
437 return Void();
438 }
439
440 Return<bool> registerForNotifications(const hidl_string& /* fqName */,
441 const hidl_string& /* name */,
442 const sp<IServiceNotification>& /* callback */) override {
443 // This makes no sense.
444 LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
445 return false;
446 }
447
Yifan Hong705e5da2017-03-02 16:59:39 -0800448 Return<void> debugDump(debugDump_cb _hidl_cb) override {
449 using Arch = ::android::hidl::base::V1_0::DebugInfo::Architecture;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700450 using std::literals::string_literals::operator""s;
Justin Yun1f048102017-12-01 15:30:08 +0900451 static std::string halLibPathVndkSp64 = android::base::StringPrintf(
452 HAL_LIBRARY_PATH_VNDK_SP_64BIT_FOR_VERSION, details::getVndkVersionStr().c_str());
453 static std::string halLibPathVndkSp32 = android::base::StringPrintf(
454 HAL_LIBRARY_PATH_VNDK_SP_32BIT_FOR_VERSION, details::getVndkVersionStr().c_str());
Jiyong Park56eb1492017-08-04 16:16:13 +0900455 static std::vector<std::pair<Arch, std::vector<const char*>>> sAllPaths{
456 {Arch::IS_64BIT,
457 {HAL_LIBRARY_PATH_ODM_64BIT, HAL_LIBRARY_PATH_VENDOR_64BIT,
Justin Yun1f048102017-12-01 15:30:08 +0900458 halLibPathVndkSp64.c_str(), HAL_LIBRARY_PATH_SYSTEM_64BIT}},
Jiyong Park56eb1492017-08-04 16:16:13 +0900459 {Arch::IS_32BIT,
460 {HAL_LIBRARY_PATH_ODM_32BIT, HAL_LIBRARY_PATH_VENDOR_32BIT,
Justin Yun1f048102017-12-01 15:30:08 +0900461 halLibPathVndkSp32.c_str(), HAL_LIBRARY_PATH_SYSTEM_32BIT}}};
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700462 std::map<std::string, InstanceDebugInfo> map;
Yifan Hong705e5da2017-03-02 16:59:39 -0800463 for (const auto &pair : sAllPaths) {
464 Arch arch = pair.first;
465 for (const auto &path : pair.second) {
466 std::vector<std::string> libs = search(path, "", ".so");
467 for (const std::string &lib : libs) {
468 std::string matchedName;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700469 std::string implName;
470 if (matchPackageName(lib, &matchedName, &implName)) {
471 std::string instanceName{"* ("s + path + ")"s};
472 if (!implName.empty()) instanceName += " ("s + implName + ")"s;
473 map.emplace(path + lib, InstanceDebugInfo{.interfaceName = matchedName,
474 .instanceName = instanceName,
475 .clientPids = {},
476 .arch = arch});
Yifan Hong705e5da2017-03-02 16:59:39 -0800477 }
478 }
479 }
480 }
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700481 fetchPidsForPassthroughLibraries(&map);
482 hidl_vec<InstanceDebugInfo> vec;
483 vec.resize(map.size());
484 size_t idx = 0;
485 for (auto&& pair : map) {
486 vec[idx++] = std::move(pair.second);
487 }
Yifan Hong705e5da2017-03-02 16:59:39 -0800488 _hidl_cb(vec);
Yifan Hong7f49f592017-02-03 15:11:44 -0800489 return Void();
490 }
491
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700492 Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
Yifan Hong7f49f592017-02-03 15:11:44 -0800493 // This makes no sense.
494 LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
495 << "Call it on defaultServiceManager() instead.";
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800496 return Void();
497 }
498
Steven Moreland2a2678e2017-07-21 18:07:38 -0700499 Return<bool> unregisterForNotifications(const hidl_string& /* fqName */,
500 const hidl_string& /* name */,
501 const sp<IServiceNotification>& /* callback */) override {
502 // This makes no sense.
503 LOG(FATAL) << "Cannot unregister for notifications with passthrough service manager.";
504 return false;
505 }
506
Steven Moreland337e6b62017-01-18 17:25:13 -0800507};
508
Steven Moreland2a2678e2017-07-21 18:07:38 -0700509sp<IServiceManager1_0> getPassthroughServiceManager() {
510 return getPassthroughServiceManager1_1();
511}
512sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
Steven Moreland337e6b62017-01-18 17:25:13 -0800513 static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
514 return manager;
515}
516
Steven Morelandcbefd352017-01-23 20:29:05 -0800517namespace details {
518
Steven Moreland519306f2017-06-06 17:14:12 -0700519void preloadPassthroughService(const std::string &descriptor) {
520 PassthroughServiceManager::openLibs(descriptor,
521 [&](void* /* handle */, const std::string& /* lib */, const std::string& /* sym */) {
522 // do nothing
523 return true; // open all libs
524 });
525}
526
Steven Morelandcbefd352017-01-23 20:29:05 -0800527struct Waiter : IServiceNotification {
Martijn Coenen773609e2017-10-24 09:57:53 +0200528 Waiter(const std::string& interface, const std::string& instanceName,
529 const sp<IServiceManager1_1>& sm) : mInterfaceName(interface),
530 mInstanceName(instanceName), mSm(sm) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100531 }
532
533 void onFirstRef() override {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200534 // If this process only has one binder thread, and we're calling wait() from
535 // that thread, it will block forever because we hung up the one and only
536 // binder thread on a condition variable that can only be notified by an
537 // incoming binder call.
Tobias Lindskog88e886f2018-01-05 10:32:43 +0100538 if (IPCThreadState::self()->isOnlyBinderThread()) {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200539 LOG(WARNING) << "Can't efficiently wait for " << mInterfaceName << "/"
540 << mInstanceName << ", because we are called from "
541 << "the only binder thread in this process.";
542 return;
543 }
544
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100545 Return<bool> ret = mSm->registerForNotifications(mInterfaceName, mInstanceName, this);
Martijn Coenen773609e2017-10-24 09:57:53 +0200546
547 if (!ret.isOk()) {
548 LOG(ERROR) << "Transport error, " << ret.description()
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100549 << ", during notification registration for " << mInterfaceName << "/"
550 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200551 return;
552 }
553
554 if (!ret) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100555 LOG(ERROR) << "Could not register for notifications for " << mInterfaceName << "/"
556 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200557 return;
558 }
559
560 mRegisteredForNotifications = true;
561 }
562
563 ~Waiter() {
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100564 if (!mDoneCalled) {
565 LOG(FATAL)
566 << "Waiter still registered for notifications, call done() before dropping ref!";
Martijn Coenen773609e2017-10-24 09:57:53 +0200567 }
568 }
569
Steven Morelandcbefd352017-01-23 20:29:05 -0800570 Return<void> onRegistration(const hidl_string& /* fqName */,
571 const hidl_string& /* name */,
572 bool /* preexisting */) override {
573 std::unique_lock<std::mutex> lock(mMutex);
574 if (mRegistered) {
575 return Void();
576 }
577 mRegistered = true;
578 lock.unlock();
579
580 mCondition.notify_one();
581 return Void();
582 }
583
Steven Moreland0771d8a2018-05-09 13:29:14 -0700584 void wait(bool timeout) {
Steven Moreland49605102017-03-28 09:33:06 -0700585 using std::literals::chrono_literals::operator""s;
586
Martijn Coenen773609e2017-10-24 09:57:53 +0200587 if (!mRegisteredForNotifications) {
588 // As an alternative, just sleep for a second and return
589 LOG(WARNING) << "Waiting one second for " << mInterfaceName << "/" << mInstanceName;
590 sleep(1);
591 return;
592 }
593
Steven Morelandcbefd352017-01-23 20:29:05 -0800594 std::unique_lock<std::mutex> lock(mMutex);
Steven Moreland0771d8a2018-05-09 13:29:14 -0700595 do {
Steven Moreland49605102017-03-28 09:33:06 -0700596 mCondition.wait_for(lock, 1s, [this]{
597 return mRegistered;
598 });
599
600 if (mRegistered) {
601 break;
602 }
603
Steven Moreland0771d8a2018-05-09 13:29:14 -0700604 LOG(WARNING) << "Waited one second for " << mInterfaceName << "/" << mInstanceName;
605 } while (!timeout);
Steven Morelandcbefd352017-01-23 20:29:05 -0800606 }
607
Martijn Coenen773609e2017-10-24 09:57:53 +0200608 // Be careful when using this; after calling reset(), you must always try to retrieve
609 // the corresponding service before blocking on the waiter; otherwise, you might run
610 // into a race-condition where the service has just (re-)registered, you clear the state
611 // here, and subsequently calling waiter->wait() will block forever.
612 void reset() {
613 std::unique_lock<std::mutex> lock(mMutex);
614 mRegistered = false;
615 }
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100616
617 // done() must be called before dropping the last strong ref to the Waiter, to make
618 // sure we can properly unregister with hwservicemanager.
619 void done() {
620 if (mRegisteredForNotifications) {
621 if (!mSm->unregisterForNotifications(mInterfaceName, mInstanceName, this)
622 .withDefault(false)) {
623 LOG(ERROR) << "Could not unregister service notification for " << mInterfaceName
624 << "/" << mInstanceName << ".";
625 } else {
626 mRegisteredForNotifications = false;
627 }
628 }
629 mDoneCalled = true;
630 }
631
632 private:
Martijn Coenen773609e2017-10-24 09:57:53 +0200633 const std::string mInterfaceName;
634 const std::string mInstanceName;
635 const sp<IServiceManager1_1>& mSm;
Steven Morelandcbefd352017-01-23 20:29:05 -0800636 std::mutex mMutex;
637 std::condition_variable mCondition;
638 bool mRegistered = false;
Martijn Coenen773609e2017-10-24 09:57:53 +0200639 bool mRegisteredForNotifications = false;
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100640 bool mDoneCalled = false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800641};
642
643void waitForHwService(
644 const std::string &interface, const std::string &instanceName) {
Martijn Coenen773609e2017-10-24 09:57:53 +0200645 sp<Waiter> waiter = new Waiter(interface, instanceName, defaultServiceManager1_1());
Steven Moreland0771d8a2018-05-09 13:29:14 -0700646 waiter->wait(false /* timeout */);
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100647 waiter->done();
Martijn Coenen773609e2017-10-24 09:57:53 +0200648}
Steven Morelandcbefd352017-01-23 20:29:05 -0800649
Martijn Coenen773609e2017-10-24 09:57:53 +0200650// Prints relevant error/warning messages for error return values from
651// details::canCastInterface(), both transaction errors (!castReturn.isOk())
652// as well as actual cast failures (castReturn.isOk() && castReturn = false).
653// Returns 'true' if the error is non-fatal and it's useful to retry
654bool handleCastError(const Return<bool>& castReturn, const std::string& descriptor,
655 const std::string& instance) {
656 if (castReturn.isOk()) {
657 if (castReturn) {
658 details::logAlwaysFatal("Successful cast value passed into handleCastError.");
659 }
660 // This should never happen, and there's not really a point in retrying.
661 ALOGE("getService: received incompatible service (bug in hwservicemanager?) for "
662 "%s/%s.", descriptor.c_str(), instance.c_str());
663 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800664 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200665 if (castReturn.isDeadObject()) {
666 ALOGW("getService: found dead hwbinder service for %s/%s.", descriptor.c_str(),
667 instance.c_str());
668 return true;
Steven Morelandcbefd352017-01-23 20:29:05 -0800669 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200670 // This can happen due to:
671 // 1) No SELinux permissions
672 // 2) Other transaction failure (no buffer space, kernel error)
673 // The first isn't recoverable, but the second is.
674 // Since we can't yet differentiate between the two, and clients depend
675 // on us not blocking in case 1), treat this as a fatal error for now.
676 ALOGW("getService: unable to call into hwbinder service for %s/%s.",
677 descriptor.c_str(), instance.c_str());
678 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800679}
680
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200681sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
682 const std::string& instance,
683 bool retry, bool getStub) {
684 using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
685 using ::android::hidl::base::V1_0::IBase;
686 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenend35678f2018-03-07 09:51:01 +0100687 sp<Waiter> waiter;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200688
Yifan Hongdeacf142018-07-10 17:33:34 -0700689 sp<IServiceManager1_1> sm;
690 Transport transport = Transport::EMPTY;
691 if (kIsRecovery) {
692 // TODO(b/80132328): Should check manifest in recovery as well.
693 transport = Transport::PASSTHROUGH;
694 // No hwbinder HALs in recovery.
695 getStub = true;
696 } else {
697 sm = defaultServiceManager1_1();
698 if (sm == nullptr) {
699 ALOGE("getService: defaultServiceManager() is null");
700 return nullptr;
701 }
702
703 Return<Transport> transportRet = sm->getTransport(descriptor, instance);
704
705 if (!transportRet.isOk()) {
706 ALOGE("getService: defaultServiceManager()->getTransport returns %s",
707 transportRet.description().c_str());
708 return nullptr;
709 }
710 transport = transportRet;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200711 }
712
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200713 const bool vintfHwbinder = (transport == Transport::HWBINDER);
714 const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
715
Steven Moreland757394b2017-12-13 14:09:24 -0800716#ifdef ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200717
718#ifdef LIBHIDL_TARGET_DEBUGGABLE
719 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
720 const bool trebleTestingOverride = env && !strcmp(env, "true");
721 const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
Steven Moreland757394b2017-12-13 14:09:24 -0800722#else // ENFORCE_VINTF_MANIFEST but not LIBHIDL_TARGET_DEBUGGABLE
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200723 const bool trebleTestingOverride = false;
724 const bool vintfLegacy = false;
725#endif // LIBHIDL_TARGET_DEBUGGABLE
726
Steven Moreland757394b2017-12-13 14:09:24 -0800727#else // not ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200728 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
729 const bool trebleTestingOverride = env && !strcmp(env, "true");
730 const bool vintfLegacy = (transport == Transport::EMPTY);
Steven Moreland757394b2017-12-13 14:09:24 -0800731#endif // ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200732
Steven Moreland76371242018-04-19 17:11:39 -0700733 for (int tries = 0; !getStub && (vintfHwbinder || vintfLegacy); tries++) {
734 if (waiter == nullptr && tries > 0) {
Martijn Coenend35678f2018-03-07 09:51:01 +0100735 waiter = new Waiter(descriptor, instance, sm);
736 }
Steven Moreland76371242018-04-19 17:11:39 -0700737 if (waiter != nullptr) {
738 waiter->reset(); // don't reorder this -- see comments on reset()
739 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200740 Return<sp<IBase>> ret = sm->get(descriptor, instance);
741 if (!ret.isOk()) {
742 ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.",
743 ret.description().c_str(), descriptor.c_str(), instance.c_str());
744 break;
745 }
746 sp<IBase> base = ret;
Martijn Coenen773609e2017-10-24 09:57:53 +0200747 if (base != nullptr) {
748 Return<bool> canCastRet =
749 details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
750
751 if (canCastRet.isOk() && canCastRet) {
Steven Moreland76371242018-04-19 17:11:39 -0700752 if (waiter != nullptr) {
753 waiter->done();
754 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200755 return base; // still needs to be wrapped by Bp class.
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200756 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200757
758 if (!handleCastError(canCastRet, descriptor, instance)) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200759 }
760
Martijn Coenen773609e2017-10-24 09:57:53 +0200761 // In case of legacy or we were not asked to retry, don't.
762 if (vintfLegacy || !retry) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200763
Steven Moreland76371242018-04-19 17:11:39 -0700764 if (waiter != nullptr) {
765 ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
Steven Moreland0771d8a2018-05-09 13:29:14 -0700766 waiter->wait(true /* timeout */);
Steven Moreland76371242018-04-19 17:11:39 -0700767 }
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200768 }
769
Martijn Coenend35678f2018-03-07 09:51:01 +0100770 if (waiter != nullptr) {
771 waiter->done();
772 }
Martijn Coenen3fa15c22018-02-10 11:30:00 +0100773
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200774 if (getStub || vintfPassthru || vintfLegacy) {
775 const sp<IServiceManager> pm = getPassthroughServiceManager();
776 if (pm != nullptr) {
777 sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
778 if (!getStub || trebleTestingOverride) {
779 base = wrapPassthrough(base);
780 }
781 return base;
782 }
783 }
784
785 return nullptr;
786}
787
Bernhard Rosenkränzer0c28fd22018-06-04 16:01:47 +0200788} // namespace details
Steven Morelandcbefd352017-01-23 20:29:05 -0800789
Bernhard Rosenkränzer0c28fd22018-06-04 16:01:47 +0200790} // namespace hardware
791} // namespace android