blob: 34e6ea4bb01cb9846192a48782df625f716ca8c5 [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>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070032#include <hidl/ServiceManagement.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070033#include <hidl/Status.h>
34
Steven Moreland337e6b62017-01-18 17:25:13 -080035#include <android-base/logging.h>
Steven Morelandc1cee2c2017-03-24 16:23:11 +000036#include <android-base/properties.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070037#include <hwbinder/IPCThreadState.h>
38#include <hwbinder/Parcel.h>
Jiyong Parkba8ace12017-05-15 15:44:39 +090039#include <vndksupport/linker.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070040
Steven Moreland2a2678e2017-07-21 18:07:38 -070041#include <android/hidl/manager/1.1/IServiceManager.h>
42#include <android/hidl/manager/1.1/BpHwServiceManager.h>
43#include <android/hidl/manager/1.1/BnHwServiceManager.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070044
Yifan Hong9a22d1d2017-01-25 14:19:26 -080045#define RE_COMPONENT "[a-zA-Z_][a-zA-Z_0-9]*"
46#define RE_PATH RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
47static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
48
Steven Morelandc1cee2c2017-03-24 16:23:11 +000049using android::base::WaitForProperty;
50
Steven Moreland2a2678e2017-07-21 18:07:38 -070051using IServiceManager1_0 = android::hidl::manager::V1_0::IServiceManager;
52using IServiceManager1_1 = android::hidl::manager::V1_1::IServiceManager;
Steven Moreland337e6b62017-01-18 17:25:13 -080053using android::hidl::manager::V1_0::IServiceNotification;
Steven Moreland2a2678e2017-07-21 18:07:38 -070054using android::hidl::manager::V1_1::BpHwServiceManager;
55using android::hidl::manager::V1_1::BnHwServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070056
57namespace android {
58namespace hardware {
59
Yifan Hong953e6b02017-03-16 14:52:40 -070060namespace details {
61extern Mutex gDefaultServiceManagerLock;
Steven Moreland2a2678e2017-07-21 18:07:38 -070062extern sp<android::hidl::manager::V1_1::IServiceManager> gDefaultServiceManager;
Yifan Hong953e6b02017-03-16 14:52:40 -070063} // namespace details
64
Steven Morelandc1cee2c2017-03-24 16:23:11 +000065static const char* kHwServicemanagerReadyProperty = "hwservicemanager.ready";
66
67void waitForHwServiceManager() {
68 using std::literals::chrono_literals::operator""s;
69
70 while (!WaitForProperty(kHwServicemanagerReadyProperty, "true", 1s)) {
71 LOG(WARNING) << "Waited for hwservicemanager.ready for a second, waiting another...";
72 }
73}
74
Steven Moreland405d7612017-04-07 20:31:22 -070075bool endsWith(const std::string &in, const std::string &suffix) {
76 return in.size() >= suffix.size() &&
77 in.substr(in.size() - suffix.size()) == suffix;
78}
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070079
Steven Moreland405d7612017-04-07 20:31:22 -070080bool startsWith(const std::string &in, const std::string &prefix) {
81 return in.size() >= prefix.size() &&
82 in.substr(0, prefix.size()) == prefix;
83}
84
85std::string binaryName() {
86 std::ifstream ifs("/proc/self/cmdline");
87 std::string cmdline;
88 if (!ifs.is_open()) {
89 return "";
90 }
91 ifs >> cmdline;
92
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -070093 size_t idx = cmdline.rfind('/');
Steven Moreland405d7612017-04-07 20:31:22 -070094 if (idx != std::string::npos) {
95 cmdline = cmdline.substr(idx + 1);
96 }
97
98 return cmdline;
99}
100
101void tryShortenProcessName(const std::string &packageName) {
102 std::string processName = binaryName();
103
104 if (!startsWith(processName, packageName)) {
105 return;
106 }
107
108 // e.x. android.hardware.module.foo@1.0 -> foo@1.0
109 size_t lastDot = packageName.rfind('.');
110 size_t secondDot = packageName.rfind('.', lastDot - 1);
111
112 if (secondDot == std::string::npos) {
113 return;
114 }
115
116 std::string newName = processName.substr(secondDot + 1,
117 16 /* TASK_COMM_LEN */ - 1);
118 ALOGI("Removing namespace from process name %s to %s.",
119 processName.c_str(), newName.c_str());
120
121 int rc = pthread_setname_np(pthread_self(), newName.c_str());
122 ALOGI_IF(rc != 0, "Removing namespace from process name %s failed.",
123 processName.c_str());
124}
125
126namespace details {
127
128void onRegistration(const std::string &packageName,
129 const std::string& /* interfaceName */,
130 const std::string& /* instanceName */) {
131 tryShortenProcessName(packageName);
132}
133
134} // details
135
Steven Moreland2a2678e2017-07-21 18:07:38 -0700136sp<IServiceManager1_0> defaultServiceManager() {
137 return defaultServiceManager1_1();
138}
139sp<IServiceManager1_1> defaultServiceManager1_1() {
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700140 {
Yifan Hong953e6b02017-03-16 14:52:40 -0700141 AutoMutex _l(details::gDefaultServiceManagerLock);
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700142 if (details::gDefaultServiceManager != nullptr) {
Yifan Hong953e6b02017-03-16 14:52:40 -0700143 return details::gDefaultServiceManager;
Yifan Hong8fb656b2017-03-16 14:30:40 -0700144 }
Steven Moreland405d7612017-04-07 20:31:22 -0700145
Yifan Hong8fb656b2017-03-16 14:30:40 -0700146 if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
147 // HwBinder not available on this device or not accessible to
148 // this process.
149 return nullptr;
150 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000151
152 waitForHwServiceManager();
153
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700154 while (details::gDefaultServiceManager == nullptr) {
Yifan Hong953e6b02017-03-16 14:52:40 -0700155 details::gDefaultServiceManager =
Steven Moreland2a2678e2017-07-21 18:07:38 -0700156 fromBinder<IServiceManager1_1, BpHwServiceManager, BnHwServiceManager>(
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700157 ProcessState::self()->getContextObject(nullptr));
158 if (details::gDefaultServiceManager == nullptr) {
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000159 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700160 sleep(1);
Yifan Hong8fb656b2017-03-16 14:30:40 -0700161 }
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700162 }
163 }
164
Yifan Hong953e6b02017-03-16 14:52:40 -0700165 return details::gDefaultServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700166}
167
Steven Moreland0091c092017-01-20 23:15:18 +0000168std::vector<std::string> search(const std::string &path,
169 const std::string &prefix,
170 const std::string &suffix) {
171 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
172 if (!dir) return {};
173
174 std::vector<std::string> results{};
175
176 dirent* dp;
177 while ((dp = readdir(dir.get())) != nullptr) {
178 std::string name = dp->d_name;
179
Steven Moreland819c05d2017-04-06 17:24:22 -0700180 if (startsWith(name, prefix) &&
181 endsWith(name, suffix)) {
Steven Moreland0091c092017-01-20 23:15:18 +0000182 results.push_back(name);
183 }
184 }
185
186 return results;
187}
188
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700189bool matchPackageName(const std::string& lib, std::string* matchedName, std::string* implName) {
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800190 std::smatch match;
191 if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
192 *matchedName = match.str(1) + "::I*";
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700193 *implName = match.str(2);
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800194 return true;
195 }
196 return false;
197}
198
Yifan Hong7f49f592017-02-03 15:11:44 -0800199static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
Steven Moreland2a2678e2017-07-21 18:07:38 -0700200 sp<IServiceManager1_0> binderizedManager = defaultServiceManager();
Yifan Hong7f49f592017-02-03 15:11:44 -0800201 if (binderizedManager == nullptr) {
202 LOG(WARNING) << "Could not registerReference for "
203 << interfaceName << "/" << instanceName
204 << ": null binderized manager.";
205 return;
206 }
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700207 auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
Yifan Hong7f49f592017-02-03 15:11:44 -0800208 if (!ret.isOk()) {
209 LOG(WARNING) << "Could not registerReference for "
210 << interfaceName << "/" << instanceName
211 << ": " << ret.description();
Steven Moreland0aeaa782017-03-22 08:11:07 -0700212 return;
Yifan Hong7f49f592017-02-03 15:11:44 -0800213 }
Steven Morelande681aa52017-02-15 16:22:37 -0800214 LOG(VERBOSE) << "Successfully registerReference for "
215 << interfaceName << "/" << instanceName;
Yifan Hong7f49f592017-02-03 15:11:44 -0800216}
217
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700218using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
219static inline void fetchPidsForPassthroughLibraries(
220 std::map<std::string, InstanceDebugInfo>* infos) {
221 static const std::string proc = "/proc/";
222
223 std::map<std::string, std::set<pid_t>> pids;
224 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
225 if (!dir) return;
226 dirent* dp;
227 while ((dp = readdir(dir.get())) != nullptr) {
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700228 pid_t pid = strtoll(dp->d_name, nullptr, 0);
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700229 if (pid == 0) continue;
230 std::string mapsPath = proc + dp->d_name + "/maps";
231 std::ifstream ifs{mapsPath};
232 if (!ifs.is_open()) continue;
233
234 for (std::string line; std::getline(ifs, line);) {
235 // The last token of line should look like
236 // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
237 // Use some simple filters to ignore bad lines before extracting libFileName
238 // and checking the key in info to make parsing faster.
239 if (line.back() != 'o') continue;
240 if (line.rfind('@') == std::string::npos) continue;
241
242 auto spacePos = line.rfind(' ');
243 if (spacePos == std::string::npos) continue;
244 auto libFileName = line.substr(spacePos + 1);
245 auto it = infos->find(libFileName);
246 if (it == infos->end()) continue;
247 pids[libFileName].insert(pid);
248 }
249 }
250 for (auto& pair : *infos) {
251 pair.second.clientPids =
252 std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
253 }
254}
255
Steven Moreland2a2678e2017-07-21 18:07:38 -0700256struct PassthroughServiceManager : IServiceManager1_1 {
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -0700257 static void openLibs(
258 const std::string& fqName,
259 const std::function<bool /* continue */ (void* /* handle */, const std::string& /* lib */,
260 const std::string& /* sym */)>& eachLib) {
Steven Moreland819c05d2017-04-06 17:24:22 -0700261 //fqName looks like android.hardware.foo@1.0::IFoo
Steven Moreland519306f2017-06-06 17:14:12 -0700262 size_t idx = fqName.find("::");
Steven Moreland819c05d2017-04-06 17:24:22 -0700263
264 if (idx == std::string::npos ||
Steven Moreland519306f2017-06-06 17:14:12 -0700265 idx + strlen("::") + 1 >= fqName.size()) {
Steven Moreland337e6b62017-01-18 17:25:13 -0800266 LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
Steven Moreland519306f2017-06-06 17:14:12 -0700267 return;
Steven Moreland337e6b62017-01-18 17:25:13 -0800268 }
269
Steven Moreland519306f2017-06-06 17:14:12 -0700270 std::string packageAndVersion = fqName.substr(0, idx);
271 std::string ifaceName = fqName.substr(idx + strlen("::"));
Steven Moreland819c05d2017-04-06 17:24:22 -0700272
273 const std::string prefix = packageAndVersion + "-impl";
274 const std::string sym = "HIDL_FETCH_" + ifaceName;
Steven Moreland348802d2017-02-23 12:48:55 -0800275
Steven Moreland77f4c852017-10-12 11:05:53 -0700276 constexpr int dlMode = RTLD_LAZY;
277 void* handle = nullptr;
Steven Moreland337e6b62017-01-18 17:25:13 -0800278
Steven Morelanda29905c2017-03-01 10:42:35 -0800279 dlerror(); // clear
280
Steven Morelandf7dea692017-07-14 12:49:28 -0700281 std::vector<std::string> paths = {HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR,
Jiyong Park56eb1492017-08-04 16:16:13 +0900282 HAL_LIBRARY_PATH_VNDK_SP, HAL_LIBRARY_PATH_SYSTEM};
Steven Moreland77f4c852017-10-12 11:05:53 -0700283
Steven Morelandf7dea692017-07-14 12:49:28 -0700284#ifdef LIBHIDL_TARGET_DEBUGGABLE
285 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
286 const bool trebleTestingOverride = env && !strcmp(env, "true");
287 if (trebleTestingOverride) {
Steven Moreland77f4c852017-10-12 11:05:53 -0700288 // Load HAL implementations that are statically linked
289 handle = dlopen(nullptr, dlMode);
290 if (handle == nullptr) {
291 const char* error = dlerror();
292 LOG(ERROR) << "Failed to dlopen self: "
293 << (error == nullptr ? "unknown error" : error);
294 } else if (!eachLib(handle, "SELF", sym)) {
295 return;
296 }
297
Steven Morelandf7dea692017-07-14 12:49:28 -0700298 const char* vtsRootPath = std::getenv("VTS_ROOT_PATH");
299 if (vtsRootPath && strlen(vtsRootPath) > 0) {
300 const std::string halLibraryPathVtsOverride =
301 std::string(vtsRootPath) + HAL_LIBRARY_PATH_SYSTEM;
Steven Moreland77f4c852017-10-12 11:05:53 -0700302 paths.insert(paths.begin(), halLibraryPathVtsOverride);
Steven Morelandf7dea692017-07-14 12:49:28 -0700303 }
304 }
305#endif
Steven Moreland77f4c852017-10-12 11:05:53 -0700306
Steven Morelandf7dea692017-07-14 12:49:28 -0700307 for (const std::string& path : paths) {
Steven Moreland0091c092017-01-20 23:15:18 +0000308 std::vector<std::string> libs = search(path, prefix, ".so");
309
Steven Moreland0091c092017-01-20 23:15:18 +0000310 for (const std::string &lib : libs) {
Steven Moreland348802d2017-02-23 12:48:55 -0800311 const std::string fullPath = path + lib;
312
Steven Moreland65c00cb2017-10-12 11:35:22 -0700313 if (path == HAL_LIBRARY_PATH_SYSTEM) {
Jiyong Park3ab546c2017-04-06 20:28:07 +0900314 handle = dlopen(fullPath.c_str(), dlMode);
Steven Moreland65c00cb2017-10-12 11:35:22 -0700315 } else {
316 handle = android_load_sphal_library(fullPath.c_str(), dlMode);
Jiyong Park3ab546c2017-04-06 20:28:07 +0900317 }
318
Steven Moreland348802d2017-02-23 12:48:55 -0800319 if (handle == nullptr) {
320 const char* error = dlerror();
321 LOG(ERROR) << "Failed to dlopen " << lib << ": "
322 << (error == nullptr ? "unknown error" : error);
323 continue;
Steven Moreland0091c092017-01-20 23:15:18 +0000324 }
Steven Moreland348802d2017-02-23 12:48:55 -0800325
Steven Moreland519306f2017-06-06 17:14:12 -0700326 if (!eachLib(handle, lib, sym)) {
327 return;
Steven Moreland348802d2017-02-23 12:48:55 -0800328 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800329 }
330 }
Steven Moreland519306f2017-06-06 17:14:12 -0700331 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800332
Steven Moreland519306f2017-06-06 17:14:12 -0700333 Return<sp<IBase>> get(const hidl_string& fqName,
334 const hidl_string& name) override {
335 sp<IBase> ret = nullptr;
336
337 openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
338 IBase* (*generator)(const char* name);
339 *(void **)(&generator) = dlsym(handle, sym.c_str());
340 if(!generator) {
341 const char* error = dlerror();
342 LOG(ERROR) << "Passthrough lookup opened " << lib
343 << " but could not find symbol " << sym << ": "
344 << (error == nullptr ? "unknown error" : error);
345 dlclose(handle);
346 return true;
347 }
348
349 ret = (*generator)(name.c_str());
350
351 if (ret == nullptr) {
352 dlclose(handle);
353 return true; // this module doesn't provide this instance name
354 }
355
356 registerReference(fqName, name);
357 return false;
358 });
359
360 return ret;
Steven Moreland337e6b62017-01-18 17:25:13 -0800361 }
362
Martijn Coenen67a02492017-03-06 13:04:48 +0100363 Return<bool> add(const hidl_string& /* name */,
Steven Moreland337e6b62017-01-18 17:25:13 -0800364 const sp<IBase>& /* service */) override {
365 LOG(FATAL) << "Cannot register services with passthrough service manager.";
366 return false;
367 }
368
Steven Morelandc601c5f2017-04-06 09:26:07 -0700369 Return<Transport> getTransport(const hidl_string& /* fqName */,
370 const hidl_string& /* name */) {
371 LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
372 return Transport::EMPTY;
373 }
374
Yifan Hong705e5da2017-03-02 16:59:39 -0800375 Return<void> list(list_cb /* _hidl_cb */) override {
376 LOG(FATAL) << "Cannot list services with passthrough service manager.";
Steven Moreland337e6b62017-01-18 17:25:13 -0800377 return Void();
378 }
379 Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
380 listByInterface_cb /* _hidl_cb */) override {
381 // TODO: add this functionality
382 LOG(FATAL) << "Cannot list services with passthrough service manager.";
383 return Void();
384 }
385
386 Return<bool> registerForNotifications(const hidl_string& /* fqName */,
387 const hidl_string& /* name */,
388 const sp<IServiceNotification>& /* callback */) override {
389 // This makes no sense.
390 LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
391 return false;
392 }
393
Yifan Hong705e5da2017-03-02 16:59:39 -0800394 Return<void> debugDump(debugDump_cb _hidl_cb) override {
395 using Arch = ::android::hidl::base::V1_0::DebugInfo::Architecture;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700396 using std::literals::string_literals::operator""s;
Jiyong Park56eb1492017-08-04 16:16:13 +0900397 static std::vector<std::pair<Arch, std::vector<const char*>>> sAllPaths{
398 {Arch::IS_64BIT,
399 {HAL_LIBRARY_PATH_ODM_64BIT, HAL_LIBRARY_PATH_VENDOR_64BIT,
400 HAL_LIBRARY_PATH_VNDK_SP_64BIT, HAL_LIBRARY_PATH_SYSTEM_64BIT}},
401 {Arch::IS_32BIT,
402 {HAL_LIBRARY_PATH_ODM_32BIT, HAL_LIBRARY_PATH_VENDOR_32BIT,
403 HAL_LIBRARY_PATH_VNDK_SP_32BIT, HAL_LIBRARY_PATH_SYSTEM_32BIT}}};
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700404 std::map<std::string, InstanceDebugInfo> map;
Yifan Hong705e5da2017-03-02 16:59:39 -0800405 for (const auto &pair : sAllPaths) {
406 Arch arch = pair.first;
407 for (const auto &path : pair.second) {
408 std::vector<std::string> libs = search(path, "", ".so");
409 for (const std::string &lib : libs) {
410 std::string matchedName;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700411 std::string implName;
412 if (matchPackageName(lib, &matchedName, &implName)) {
413 std::string instanceName{"* ("s + path + ")"s};
414 if (!implName.empty()) instanceName += " ("s + implName + ")"s;
415 map.emplace(path + lib, InstanceDebugInfo{.interfaceName = matchedName,
416 .instanceName = instanceName,
417 .clientPids = {},
418 .arch = arch});
Yifan Hong705e5da2017-03-02 16:59:39 -0800419 }
420 }
421 }
422 }
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700423 fetchPidsForPassthroughLibraries(&map);
424 hidl_vec<InstanceDebugInfo> vec;
425 vec.resize(map.size());
426 size_t idx = 0;
427 for (auto&& pair : map) {
428 vec[idx++] = std::move(pair.second);
429 }
Yifan Hong705e5da2017-03-02 16:59:39 -0800430 _hidl_cb(vec);
Yifan Hong7f49f592017-02-03 15:11:44 -0800431 return Void();
432 }
433
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700434 Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
Yifan Hong7f49f592017-02-03 15:11:44 -0800435 // This makes no sense.
436 LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
437 << "Call it on defaultServiceManager() instead.";
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800438 return Void();
439 }
440
Steven Moreland2a2678e2017-07-21 18:07:38 -0700441 Return<bool> unregisterForNotifications(const hidl_string& /* fqName */,
442 const hidl_string& /* name */,
443 const sp<IServiceNotification>& /* callback */) override {
444 // This makes no sense.
445 LOG(FATAL) << "Cannot unregister for notifications with passthrough service manager.";
446 return false;
447 }
448
Steven Moreland337e6b62017-01-18 17:25:13 -0800449};
450
Steven Moreland2a2678e2017-07-21 18:07:38 -0700451sp<IServiceManager1_0> getPassthroughServiceManager() {
452 return getPassthroughServiceManager1_1();
453}
454sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
Steven Moreland337e6b62017-01-18 17:25:13 -0800455 static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
456 return manager;
457}
458
Steven Morelandcbefd352017-01-23 20:29:05 -0800459namespace details {
460
Steven Moreland519306f2017-06-06 17:14:12 -0700461void preloadPassthroughService(const std::string &descriptor) {
462 PassthroughServiceManager::openLibs(descriptor,
463 [&](void* /* handle */, const std::string& /* lib */, const std::string& /* sym */) {
464 // do nothing
465 return true; // open all libs
466 });
467}
468
Steven Morelandcbefd352017-01-23 20:29:05 -0800469struct Waiter : IServiceNotification {
Martijn Coenen773609e2017-10-24 09:57:53 +0200470 Waiter(const std::string& interface, const std::string& instanceName,
471 const sp<IServiceManager1_1>& sm) : mInterfaceName(interface),
472 mInstanceName(instanceName), mSm(sm) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100473 }
474
475 void onFirstRef() override {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200476 // If this process only has one binder thread, and we're calling wait() from
477 // that thread, it will block forever because we hung up the one and only
478 // binder thread on a condition variable that can only be notified by an
479 // incoming binder call.
480 if (ProcessState::self()->getMaxThreads() <= 1 &&
481 IPCThreadState::self()->isLooperThread()) {
482 LOG(WARNING) << "Can't efficiently wait for " << mInterfaceName << "/"
483 << mInstanceName << ", because we are called from "
484 << "the only binder thread in this process.";
485 return;
486 }
487
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100488 Return<bool> ret = mSm->registerForNotifications(mInterfaceName, mInstanceName, this);
Martijn Coenen773609e2017-10-24 09:57:53 +0200489
490 if (!ret.isOk()) {
491 LOG(ERROR) << "Transport error, " << ret.description()
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100492 << ", during notification registration for " << mInterfaceName << "/"
493 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200494 return;
495 }
496
497 if (!ret) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100498 LOG(ERROR) << "Could not register for notifications for " << mInterfaceName << "/"
499 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200500 return;
501 }
502
503 mRegisteredForNotifications = true;
504 }
505
506 ~Waiter() {
507 if (mRegisteredForNotifications) {
508 if (!mSm->unregisterForNotifications(mInterfaceName, mInstanceName, this).
509 withDefault(false)) {
510 LOG(ERROR) << "Could not unregister service notification for "
511 << mInterfaceName << "/" << mInstanceName << ".";
512 }
513 }
514 }
515
Steven Morelandcbefd352017-01-23 20:29:05 -0800516 Return<void> onRegistration(const hidl_string& /* fqName */,
517 const hidl_string& /* name */,
518 bool /* preexisting */) override {
519 std::unique_lock<std::mutex> lock(mMutex);
520 if (mRegistered) {
521 return Void();
522 }
523 mRegistered = true;
524 lock.unlock();
525
526 mCondition.notify_one();
527 return Void();
528 }
529
Martijn Coenen773609e2017-10-24 09:57:53 +0200530 void wait() {
Steven Moreland49605102017-03-28 09:33:06 -0700531 using std::literals::chrono_literals::operator""s;
532
Martijn Coenen773609e2017-10-24 09:57:53 +0200533 if (!mRegisteredForNotifications) {
534 // As an alternative, just sleep for a second and return
535 LOG(WARNING) << "Waiting one second for " << mInterfaceName << "/" << mInstanceName;
536 sleep(1);
537 return;
538 }
539
Steven Morelandcbefd352017-01-23 20:29:05 -0800540 std::unique_lock<std::mutex> lock(mMutex);
Steven Moreland49605102017-03-28 09:33:06 -0700541 while(true) {
542 mCondition.wait_for(lock, 1s, [this]{
543 return mRegistered;
544 });
545
546 if (mRegistered) {
547 break;
548 }
549
Martijn Coenen773609e2017-10-24 09:57:53 +0200550 LOG(WARNING) << "Waited one second for " << mInterfaceName << "/" << mInstanceName
Steven Moreland49605102017-03-28 09:33:06 -0700551 << ". Waiting another...";
552 }
Steven Morelandcbefd352017-01-23 20:29:05 -0800553 }
554
Martijn Coenen773609e2017-10-24 09:57:53 +0200555 // Be careful when using this; after calling reset(), you must always try to retrieve
556 // the corresponding service before blocking on the waiter; otherwise, you might run
557 // into a race-condition where the service has just (re-)registered, you clear the state
558 // here, and subsequently calling waiter->wait() will block forever.
559 void reset() {
560 std::unique_lock<std::mutex> lock(mMutex);
561 mRegistered = false;
562 }
Steven Morelandcbefd352017-01-23 20:29:05 -0800563private:
Martijn Coenen773609e2017-10-24 09:57:53 +0200564 const std::string mInterfaceName;
565 const std::string mInstanceName;
566 const sp<IServiceManager1_1>& mSm;
Steven Morelandcbefd352017-01-23 20:29:05 -0800567 std::mutex mMutex;
568 std::condition_variable mCondition;
569 bool mRegistered = false;
Martijn Coenen773609e2017-10-24 09:57:53 +0200570 bool mRegisteredForNotifications = false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800571};
572
573void waitForHwService(
574 const std::string &interface, const std::string &instanceName) {
Martijn Coenen773609e2017-10-24 09:57:53 +0200575 sp<Waiter> waiter = new Waiter(interface, instanceName, defaultServiceManager1_1());
576 waiter->wait();
577}
Steven Morelandcbefd352017-01-23 20:29:05 -0800578
Martijn Coenen773609e2017-10-24 09:57:53 +0200579// Prints relevant error/warning messages for error return values from
580// details::canCastInterface(), both transaction errors (!castReturn.isOk())
581// as well as actual cast failures (castReturn.isOk() && castReturn = false).
582// Returns 'true' if the error is non-fatal and it's useful to retry
583bool handleCastError(const Return<bool>& castReturn, const std::string& descriptor,
584 const std::string& instance) {
585 if (castReturn.isOk()) {
586 if (castReturn) {
587 details::logAlwaysFatal("Successful cast value passed into handleCastError.");
588 }
589 // This should never happen, and there's not really a point in retrying.
590 ALOGE("getService: received incompatible service (bug in hwservicemanager?) for "
591 "%s/%s.", descriptor.c_str(), instance.c_str());
592 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800593 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200594 if (castReturn.isDeadObject()) {
595 ALOGW("getService: found dead hwbinder service for %s/%s.", descriptor.c_str(),
596 instance.c_str());
597 return true;
Steven Morelandcbefd352017-01-23 20:29:05 -0800598 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200599 // This can happen due to:
600 // 1) No SELinux permissions
601 // 2) Other transaction failure (no buffer space, kernel error)
602 // The first isn't recoverable, but the second is.
603 // Since we can't yet differentiate between the two, and clients depend
604 // on us not blocking in case 1), treat this as a fatal error for now.
605 ALOGW("getService: unable to call into hwbinder service for %s/%s.",
606 descriptor.c_str(), instance.c_str());
607 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800608}
609
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200610sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
611 const std::string& instance,
612 bool retry, bool getStub) {
613 using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
614 using ::android::hidl::base::V1_0::IBase;
615 using ::android::hidl::manager::V1_0::IServiceManager;
616
Martijn Coenen773609e2017-10-24 09:57:53 +0200617 const sp<IServiceManager1_1> sm = defaultServiceManager1_1();
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200618 if (sm == nullptr) {
619 ALOGE("getService: defaultServiceManager() is null");
620 return nullptr;
621 }
622
623 Return<Transport> transportRet = sm->getTransport(descriptor, instance);
624
625 if (!transportRet.isOk()) {
626 ALOGE("getService: defaultServiceManager()->getTransport returns %s",
627 transportRet.description().c_str());
628 return nullptr;
629 }
630 Transport transport = transportRet;
631 const bool vintfHwbinder = (transport == Transport::HWBINDER);
632 const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
633
634#ifdef LIBHIDL_TARGET_TREBLE
635
636#ifdef LIBHIDL_TARGET_DEBUGGABLE
637 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
638 const bool trebleTestingOverride = env && !strcmp(env, "true");
639 const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
640#else // LIBHIDL_TARGET_TREBLE but not LIBHIDL_TARGET_DEBUGGABLE
641 const bool trebleTestingOverride = false;
642 const bool vintfLegacy = false;
643#endif // LIBHIDL_TARGET_DEBUGGABLE
644
645#else // not LIBHIDL_TARGET_TREBLE
646 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
647 const bool trebleTestingOverride = env && !strcmp(env, "true");
648 const bool vintfLegacy = (transport == Transport::EMPTY);
649#endif // LIBHIDL_TARGET_TREBLE
650
Martijn Coenen773609e2017-10-24 09:57:53 +0200651 sp<Waiter> waiter = new Waiter(descriptor, instance, sm);
652 while (!getStub && (vintfHwbinder || vintfLegacy)) {
653 waiter->reset(); // don't reorder this -- see comments on reset()
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200654 Return<sp<IBase>> ret = sm->get(descriptor, instance);
655 if (!ret.isOk()) {
656 ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.",
657 ret.description().c_str(), descriptor.c_str(), instance.c_str());
658 break;
659 }
660 sp<IBase> base = ret;
Martijn Coenen773609e2017-10-24 09:57:53 +0200661 if (base != nullptr) {
662 Return<bool> canCastRet =
663 details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
664
665 if (canCastRet.isOk() && canCastRet) {
666 return base; // still needs to be wrapped by Bp class.
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200667 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200668
669 if (!handleCastError(canCastRet, descriptor, instance)) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200670 }
671
Martijn Coenen773609e2017-10-24 09:57:53 +0200672 // In case of legacy or we were not asked to retry, don't.
673 if (vintfLegacy || !retry) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200674
Martijn Coenen773609e2017-10-24 09:57:53 +0200675 ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
676 waiter->wait();
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200677 }
678
679 if (getStub || vintfPassthru || vintfLegacy) {
680 const sp<IServiceManager> pm = getPassthroughServiceManager();
681 if (pm != nullptr) {
682 sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
683 if (!getStub || trebleTestingOverride) {
684 base = wrapPassthrough(base);
685 }
686 return base;
687 }
688 }
689
690 return nullptr;
691}
692
Steven Morelandcbefd352017-01-23 20:29:05 -0800693}; // namespace details
694
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700695}; // namespace hardware
696}; // namespace android