blob: 4bdeb6eefc95269abd5227bdd0de51ec7c1b4ee9 [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 Moreland5d5ef7f2016-10-20 19:19:55 -070033#include <hidl/ServiceManagement.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070034#include <hidl/Status.h>
35
Steven Moreland337e6b62017-01-18 17:25:13 -080036#include <android-base/logging.h>
Steven Morelandc1cee2c2017-03-24 16:23:11 +000037#include <android-base/properties.h>
Justin Yun1f048102017-12-01 15:30:08 +090038#include <android-base/stringprintf.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070039#include <hwbinder/IPCThreadState.h>
40#include <hwbinder/Parcel.h>
Jiyong Parkba8ace12017-05-15 15:44:39 +090041#include <vndksupport/linker.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070042
Steven Moreland2a2678e2017-07-21 18:07:38 -070043#include <android/hidl/manager/1.1/IServiceManager.h>
44#include <android/hidl/manager/1.1/BpHwServiceManager.h>
45#include <android/hidl/manager/1.1/BnHwServiceManager.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070046
Yifan Hong9a22d1d2017-01-25 14:19:26 -080047#define RE_COMPONENT "[a-zA-Z_][a-zA-Z_0-9]*"
48#define RE_PATH RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
49static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
50
Steven Morelandc1cee2c2017-03-24 16:23:11 +000051using android::base::WaitForProperty;
52
Steven Moreland2a2678e2017-07-21 18:07:38 -070053using IServiceManager1_0 = android::hidl::manager::V1_0::IServiceManager;
54using IServiceManager1_1 = android::hidl::manager::V1_1::IServiceManager;
Steven Moreland337e6b62017-01-18 17:25:13 -080055using android::hidl::manager::V1_0::IServiceNotification;
Steven Moreland2a2678e2017-07-21 18:07:38 -070056using android::hidl::manager::V1_1::BpHwServiceManager;
57using android::hidl::manager::V1_1::BnHwServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070058
59namespace android {
60namespace hardware {
61
Yifan Hong953e6b02017-03-16 14:52:40 -070062namespace details {
63extern Mutex gDefaultServiceManagerLock;
Steven Moreland2a2678e2017-07-21 18:07:38 -070064extern sp<android::hidl::manager::V1_1::IServiceManager> gDefaultServiceManager;
Yifan Hong953e6b02017-03-16 14:52:40 -070065} // namespace details
66
Steven Morelandc1cee2c2017-03-24 16:23:11 +000067static const char* kHwServicemanagerReadyProperty = "hwservicemanager.ready";
68
69void waitForHwServiceManager() {
70 using std::literals::chrono_literals::operator""s;
71
72 while (!WaitForProperty(kHwServicemanagerReadyProperty, "true", 1s)) {
73 LOG(WARNING) << "Waited for hwservicemanager.ready for a second, waiting another...";
74 }
75}
76
Steven Moreland405d7612017-04-07 20:31:22 -070077bool endsWith(const std::string &in, const std::string &suffix) {
78 return in.size() >= suffix.size() &&
79 in.substr(in.size() - suffix.size()) == suffix;
80}
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070081
Steven Moreland405d7612017-04-07 20:31:22 -070082bool startsWith(const std::string &in, const std::string &prefix) {
83 return in.size() >= prefix.size() &&
84 in.substr(0, prefix.size()) == prefix;
85}
86
87std::string binaryName() {
88 std::ifstream ifs("/proc/self/cmdline");
89 std::string cmdline;
90 if (!ifs.is_open()) {
91 return "";
92 }
93 ifs >> cmdline;
94
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -070095 size_t idx = cmdline.rfind('/');
Steven Moreland405d7612017-04-07 20:31:22 -070096 if (idx != std::string::npos) {
97 cmdline = cmdline.substr(idx + 1);
98 }
99
100 return cmdline;
101}
102
103void tryShortenProcessName(const std::string &packageName) {
104 std::string processName = binaryName();
105
106 if (!startsWith(processName, packageName)) {
107 return;
108 }
109
110 // e.x. android.hardware.module.foo@1.0 -> foo@1.0
111 size_t lastDot = packageName.rfind('.');
112 size_t secondDot = packageName.rfind('.', lastDot - 1);
113
114 if (secondDot == std::string::npos) {
115 return;
116 }
117
118 std::string newName = processName.substr(secondDot + 1,
119 16 /* TASK_COMM_LEN */ - 1);
120 ALOGI("Removing namespace from process name %s to %s.",
121 processName.c_str(), newName.c_str());
122
123 int rc = pthread_setname_np(pthread_self(), newName.c_str());
124 ALOGI_IF(rc != 0, "Removing namespace from process name %s failed.",
125 processName.c_str());
126}
127
128namespace details {
129
130void onRegistration(const std::string &packageName,
131 const std::string& /* interfaceName */,
132 const std::string& /* instanceName */) {
133 tryShortenProcessName(packageName);
134}
135
136} // details
137
Steven Moreland2a2678e2017-07-21 18:07:38 -0700138sp<IServiceManager1_0> defaultServiceManager() {
139 return defaultServiceManager1_1();
140}
141sp<IServiceManager1_1> defaultServiceManager1_1() {
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700142 {
Yifan Hong953e6b02017-03-16 14:52:40 -0700143 AutoMutex _l(details::gDefaultServiceManagerLock);
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700144 if (details::gDefaultServiceManager != nullptr) {
Yifan Hong953e6b02017-03-16 14:52:40 -0700145 return details::gDefaultServiceManager;
Yifan Hong8fb656b2017-03-16 14:30:40 -0700146 }
Steven Moreland405d7612017-04-07 20:31:22 -0700147
Yifan Hong8fb656b2017-03-16 14:30:40 -0700148 if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
149 // HwBinder not available on this device or not accessible to
150 // this process.
151 return nullptr;
152 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000153
154 waitForHwServiceManager();
155
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700156 while (details::gDefaultServiceManager == nullptr) {
Yifan Hong953e6b02017-03-16 14:52:40 -0700157 details::gDefaultServiceManager =
Steven Moreland2a2678e2017-07-21 18:07:38 -0700158 fromBinder<IServiceManager1_1, BpHwServiceManager, BnHwServiceManager>(
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700159 ProcessState::self()->getContextObject(nullptr));
160 if (details::gDefaultServiceManager == nullptr) {
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000161 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700162 sleep(1);
Yifan Hong8fb656b2017-03-16 14:30:40 -0700163 }
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700164 }
165 }
166
Yifan Hong953e6b02017-03-16 14:52:40 -0700167 return details::gDefaultServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700168}
169
Steven Moreland0091c092017-01-20 23:15:18 +0000170std::vector<std::string> search(const std::string &path,
171 const std::string &prefix,
172 const std::string &suffix) {
173 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
174 if (!dir) return {};
175
176 std::vector<std::string> results{};
177
178 dirent* dp;
179 while ((dp = readdir(dir.get())) != nullptr) {
180 std::string name = dp->d_name;
181
Steven Moreland819c05d2017-04-06 17:24:22 -0700182 if (startsWith(name, prefix) &&
183 endsWith(name, suffix)) {
Steven Moreland0091c092017-01-20 23:15:18 +0000184 results.push_back(name);
185 }
186 }
187
188 return results;
189}
190
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700191bool matchPackageName(const std::string& lib, std::string* matchedName, std::string* implName) {
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800192 std::smatch match;
193 if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
194 *matchedName = match.str(1) + "::I*";
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700195 *implName = match.str(2);
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800196 return true;
197 }
198 return false;
199}
200
Yifan Hong7f49f592017-02-03 15:11:44 -0800201static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
Steven Moreland2a2678e2017-07-21 18:07:38 -0700202 sp<IServiceManager1_0> binderizedManager = defaultServiceManager();
Yifan Hong7f49f592017-02-03 15:11:44 -0800203 if (binderizedManager == nullptr) {
204 LOG(WARNING) << "Could not registerReference for "
205 << interfaceName << "/" << instanceName
206 << ": null binderized manager.";
207 return;
208 }
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700209 auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
Yifan Hong7f49f592017-02-03 15:11:44 -0800210 if (!ret.isOk()) {
211 LOG(WARNING) << "Could not registerReference for "
212 << interfaceName << "/" << instanceName
213 << ": " << ret.description();
Steven Moreland0aeaa782017-03-22 08:11:07 -0700214 return;
Yifan Hong7f49f592017-02-03 15:11:44 -0800215 }
Steven Morelande681aa52017-02-15 16:22:37 -0800216 LOG(VERBOSE) << "Successfully registerReference for "
217 << interfaceName << "/" << instanceName;
Yifan Hong7f49f592017-02-03 15:11:44 -0800218}
219
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700220using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
221static inline void fetchPidsForPassthroughLibraries(
222 std::map<std::string, InstanceDebugInfo>* infos) {
223 static const std::string proc = "/proc/";
224
225 std::map<std::string, std::set<pid_t>> pids;
226 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
227 if (!dir) return;
228 dirent* dp;
229 while ((dp = readdir(dir.get())) != nullptr) {
Stephen Hinesfd9ecee2017-09-27 18:52:52 -0700230 pid_t pid = strtoll(dp->d_name, nullptr, 0);
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700231 if (pid == 0) continue;
232 std::string mapsPath = proc + dp->d_name + "/maps";
233 std::ifstream ifs{mapsPath};
234 if (!ifs.is_open()) continue;
235
236 for (std::string line; std::getline(ifs, line);) {
237 // The last token of line should look like
238 // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
239 // Use some simple filters to ignore bad lines before extracting libFileName
240 // and checking the key in info to make parsing faster.
241 if (line.back() != 'o') continue;
242 if (line.rfind('@') == std::string::npos) continue;
243
244 auto spacePos = line.rfind(' ');
245 if (spacePos == std::string::npos) continue;
246 auto libFileName = line.substr(spacePos + 1);
247 auto it = infos->find(libFileName);
248 if (it == infos->end()) continue;
249 pids[libFileName].insert(pid);
250 }
251 }
252 for (auto& pair : *infos) {
253 pair.second.clientPids =
254 std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
255 }
256}
257
Steven Moreland2a2678e2017-07-21 18:07:38 -0700258struct PassthroughServiceManager : IServiceManager1_1 {
Chih-Hung Hsieh41649d52017-08-03 14:27:21 -0700259 static void openLibs(
260 const std::string& fqName,
261 const std::function<bool /* continue */ (void* /* handle */, const std::string& /* lib */,
262 const std::string& /* sym */)>& eachLib) {
Steven Moreland819c05d2017-04-06 17:24:22 -0700263 //fqName looks like android.hardware.foo@1.0::IFoo
Steven Moreland519306f2017-06-06 17:14:12 -0700264 size_t idx = fqName.find("::");
Steven Moreland819c05d2017-04-06 17:24:22 -0700265
266 if (idx == std::string::npos ||
Steven Moreland519306f2017-06-06 17:14:12 -0700267 idx + strlen("::") + 1 >= fqName.size()) {
Steven Moreland337e6b62017-01-18 17:25:13 -0800268 LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
Steven Moreland519306f2017-06-06 17:14:12 -0700269 return;
Steven Moreland337e6b62017-01-18 17:25:13 -0800270 }
271
Steven Moreland519306f2017-06-06 17:14:12 -0700272 std::string packageAndVersion = fqName.substr(0, idx);
273 std::string ifaceName = fqName.substr(idx + strlen("::"));
Steven Moreland819c05d2017-04-06 17:24:22 -0700274
275 const std::string prefix = packageAndVersion + "-impl";
276 const std::string sym = "HIDL_FETCH_" + ifaceName;
Steven Moreland348802d2017-02-23 12:48:55 -0800277
Steven Moreland77f4c852017-10-12 11:05:53 -0700278 constexpr int dlMode = RTLD_LAZY;
279 void* handle = nullptr;
Steven Moreland337e6b62017-01-18 17:25:13 -0800280
Steven Morelanda29905c2017-03-01 10:42:35 -0800281 dlerror(); // clear
282
Justin Yun1f048102017-12-01 15:30:08 +0900283 static std::string halLibPathVndkSp = android::base::StringPrintf(
284 HAL_LIBRARY_PATH_VNDK_SP_FOR_VERSION, details::getVndkVersionStr().c_str());
Steven Morelandf7dea692017-07-14 12:49:28 -0700285 std::vector<std::string> paths = {HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR,
Justin Yun1f048102017-12-01 15:30:08 +0900286 halLibPathVndkSp, HAL_LIBRARY_PATH_SYSTEM};
Steven Moreland77f4c852017-10-12 11:05:53 -0700287
Steven Morelandf7dea692017-07-14 12:49:28 -0700288#ifdef LIBHIDL_TARGET_DEBUGGABLE
289 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
290 const bool trebleTestingOverride = env && !strcmp(env, "true");
291 if (trebleTestingOverride) {
Steven Moreland77f4c852017-10-12 11:05:53 -0700292 // Load HAL implementations that are statically linked
293 handle = dlopen(nullptr, dlMode);
294 if (handle == nullptr) {
295 const char* error = dlerror();
296 LOG(ERROR) << "Failed to dlopen self: "
297 << (error == nullptr ? "unknown error" : error);
298 } else if (!eachLib(handle, "SELF", sym)) {
299 return;
300 }
301
Steven Morelandf7dea692017-07-14 12:49:28 -0700302 const char* vtsRootPath = std::getenv("VTS_ROOT_PATH");
303 if (vtsRootPath && strlen(vtsRootPath) > 0) {
304 const std::string halLibraryPathVtsOverride =
305 std::string(vtsRootPath) + HAL_LIBRARY_PATH_SYSTEM;
Steven Moreland77f4c852017-10-12 11:05:53 -0700306 paths.insert(paths.begin(), halLibraryPathVtsOverride);
Steven Morelandf7dea692017-07-14 12:49:28 -0700307 }
308 }
309#endif
Steven Moreland77f4c852017-10-12 11:05:53 -0700310
Steven Morelandf7dea692017-07-14 12:49:28 -0700311 for (const std::string& path : paths) {
Steven Moreland0091c092017-01-20 23:15:18 +0000312 std::vector<std::string> libs = search(path, prefix, ".so");
313
Steven Moreland0091c092017-01-20 23:15:18 +0000314 for (const std::string &lib : libs) {
Steven Moreland348802d2017-02-23 12:48:55 -0800315 const std::string fullPath = path + lib;
316
Steven Moreland65c00cb2017-10-12 11:35:22 -0700317 if (path == HAL_LIBRARY_PATH_SYSTEM) {
Jiyong Park3ab546c2017-04-06 20:28:07 +0900318 handle = dlopen(fullPath.c_str(), dlMode);
Steven Moreland65c00cb2017-10-12 11:35:22 -0700319 } else {
320 handle = android_load_sphal_library(fullPath.c_str(), dlMode);
Jiyong Park3ab546c2017-04-06 20:28:07 +0900321 }
322
Steven Moreland348802d2017-02-23 12:48:55 -0800323 if (handle == nullptr) {
324 const char* error = dlerror();
325 LOG(ERROR) << "Failed to dlopen " << lib << ": "
326 << (error == nullptr ? "unknown error" : error);
327 continue;
Steven Moreland0091c092017-01-20 23:15:18 +0000328 }
Steven Moreland348802d2017-02-23 12:48:55 -0800329
Steven Moreland519306f2017-06-06 17:14:12 -0700330 if (!eachLib(handle, lib, sym)) {
331 return;
Steven Moreland348802d2017-02-23 12:48:55 -0800332 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800333 }
334 }
Steven Moreland519306f2017-06-06 17:14:12 -0700335 }
Steven Moreland337e6b62017-01-18 17:25:13 -0800336
Steven Moreland519306f2017-06-06 17:14:12 -0700337 Return<sp<IBase>> get(const hidl_string& fqName,
338 const hidl_string& name) override {
339 sp<IBase> ret = nullptr;
340
341 openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
342 IBase* (*generator)(const char* name);
343 *(void **)(&generator) = dlsym(handle, sym.c_str());
344 if(!generator) {
345 const char* error = dlerror();
346 LOG(ERROR) << "Passthrough lookup opened " << lib
347 << " but could not find symbol " << sym << ": "
348 << (error == nullptr ? "unknown error" : error);
349 dlclose(handle);
350 return true;
351 }
352
353 ret = (*generator)(name.c_str());
354
355 if (ret == nullptr) {
356 dlclose(handle);
357 return true; // this module doesn't provide this instance name
358 }
359
360 registerReference(fqName, name);
361 return false;
362 });
363
364 return ret;
Steven Moreland337e6b62017-01-18 17:25:13 -0800365 }
366
Martijn Coenen67a02492017-03-06 13:04:48 +0100367 Return<bool> add(const hidl_string& /* name */,
Steven Moreland337e6b62017-01-18 17:25:13 -0800368 const sp<IBase>& /* service */) override {
369 LOG(FATAL) << "Cannot register services with passthrough service manager.";
370 return false;
371 }
372
Steven Morelandc601c5f2017-04-06 09:26:07 -0700373 Return<Transport> getTransport(const hidl_string& /* fqName */,
374 const hidl_string& /* name */) {
375 LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
376 return Transport::EMPTY;
377 }
378
Yifan Hong705e5da2017-03-02 16:59:39 -0800379 Return<void> list(list_cb /* _hidl_cb */) override {
380 LOG(FATAL) << "Cannot list services with passthrough service manager.";
Steven Moreland337e6b62017-01-18 17:25:13 -0800381 return Void();
382 }
383 Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
384 listByInterface_cb /* _hidl_cb */) override {
385 // TODO: add this functionality
386 LOG(FATAL) << "Cannot list services with passthrough service manager.";
387 return Void();
388 }
389
390 Return<bool> registerForNotifications(const hidl_string& /* fqName */,
391 const hidl_string& /* name */,
392 const sp<IServiceNotification>& /* callback */) override {
393 // This makes no sense.
394 LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
395 return false;
396 }
397
Yifan Hong705e5da2017-03-02 16:59:39 -0800398 Return<void> debugDump(debugDump_cb _hidl_cb) override {
399 using Arch = ::android::hidl::base::V1_0::DebugInfo::Architecture;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700400 using std::literals::string_literals::operator""s;
Justin Yun1f048102017-12-01 15:30:08 +0900401 static std::string halLibPathVndkSp64 = android::base::StringPrintf(
402 HAL_LIBRARY_PATH_VNDK_SP_64BIT_FOR_VERSION, details::getVndkVersionStr().c_str());
403 static std::string halLibPathVndkSp32 = android::base::StringPrintf(
404 HAL_LIBRARY_PATH_VNDK_SP_32BIT_FOR_VERSION, details::getVndkVersionStr().c_str());
Jiyong Park56eb1492017-08-04 16:16:13 +0900405 static std::vector<std::pair<Arch, std::vector<const char*>>> sAllPaths{
406 {Arch::IS_64BIT,
407 {HAL_LIBRARY_PATH_ODM_64BIT, HAL_LIBRARY_PATH_VENDOR_64BIT,
Justin Yun1f048102017-12-01 15:30:08 +0900408 halLibPathVndkSp64.c_str(), HAL_LIBRARY_PATH_SYSTEM_64BIT}},
Jiyong Park56eb1492017-08-04 16:16:13 +0900409 {Arch::IS_32BIT,
410 {HAL_LIBRARY_PATH_ODM_32BIT, HAL_LIBRARY_PATH_VENDOR_32BIT,
Justin Yun1f048102017-12-01 15:30:08 +0900411 halLibPathVndkSp32.c_str(), HAL_LIBRARY_PATH_SYSTEM_32BIT}}};
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700412 std::map<std::string, InstanceDebugInfo> map;
Yifan Hong705e5da2017-03-02 16:59:39 -0800413 for (const auto &pair : sAllPaths) {
414 Arch arch = pair.first;
415 for (const auto &path : pair.second) {
416 std::vector<std::string> libs = search(path, "", ".so");
417 for (const std::string &lib : libs) {
418 std::string matchedName;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700419 std::string implName;
420 if (matchPackageName(lib, &matchedName, &implName)) {
421 std::string instanceName{"* ("s + path + ")"s};
422 if (!implName.empty()) instanceName += " ("s + implName + ")"s;
423 map.emplace(path + lib, InstanceDebugInfo{.interfaceName = matchedName,
424 .instanceName = instanceName,
425 .clientPids = {},
426 .arch = arch});
Yifan Hong705e5da2017-03-02 16:59:39 -0800427 }
428 }
429 }
430 }
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700431 fetchPidsForPassthroughLibraries(&map);
432 hidl_vec<InstanceDebugInfo> vec;
433 vec.resize(map.size());
434 size_t idx = 0;
435 for (auto&& pair : map) {
436 vec[idx++] = std::move(pair.second);
437 }
Yifan Hong705e5da2017-03-02 16:59:39 -0800438 _hidl_cb(vec);
Yifan Hong7f49f592017-02-03 15:11:44 -0800439 return Void();
440 }
441
Martijn Coenenaf4aba52017-04-27 09:41:13 -0700442 Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
Yifan Hong7f49f592017-02-03 15:11:44 -0800443 // This makes no sense.
444 LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
445 << "Call it on defaultServiceManager() instead.";
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800446 return Void();
447 }
448
Steven Moreland2a2678e2017-07-21 18:07:38 -0700449 Return<bool> unregisterForNotifications(const hidl_string& /* fqName */,
450 const hidl_string& /* name */,
451 const sp<IServiceNotification>& /* callback */) override {
452 // This makes no sense.
453 LOG(FATAL) << "Cannot unregister for notifications with passthrough service manager.";
454 return false;
455 }
456
Steven Moreland337e6b62017-01-18 17:25:13 -0800457};
458
Steven Moreland2a2678e2017-07-21 18:07:38 -0700459sp<IServiceManager1_0> getPassthroughServiceManager() {
460 return getPassthroughServiceManager1_1();
461}
462sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
Steven Moreland337e6b62017-01-18 17:25:13 -0800463 static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
464 return manager;
465}
466
Steven Morelandcbefd352017-01-23 20:29:05 -0800467namespace details {
468
Steven Moreland519306f2017-06-06 17:14:12 -0700469void preloadPassthroughService(const std::string &descriptor) {
470 PassthroughServiceManager::openLibs(descriptor,
471 [&](void* /* handle */, const std::string& /* lib */, const std::string& /* sym */) {
472 // do nothing
473 return true; // open all libs
474 });
475}
476
Steven Morelandcbefd352017-01-23 20:29:05 -0800477struct Waiter : IServiceNotification {
Martijn Coenen773609e2017-10-24 09:57:53 +0200478 Waiter(const std::string& interface, const std::string& instanceName,
479 const sp<IServiceManager1_1>& sm) : mInterfaceName(interface),
480 mInstanceName(instanceName), mSm(sm) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100481 }
482
483 void onFirstRef() override {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200484 // If this process only has one binder thread, and we're calling wait() from
485 // that thread, it will block forever because we hung up the one and only
486 // binder thread on a condition variable that can only be notified by an
487 // incoming binder call.
Tobias Lindskog88e886f2018-01-05 10:32:43 +0100488 if (IPCThreadState::self()->isOnlyBinderThread()) {
Martijn Coenenb88ae7f2017-10-24 11:45:41 +0200489 LOG(WARNING) << "Can't efficiently wait for " << mInterfaceName << "/"
490 << mInstanceName << ", because we are called from "
491 << "the only binder thread in this process.";
492 return;
493 }
494
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100495 Return<bool> ret = mSm->registerForNotifications(mInterfaceName, mInstanceName, this);
Martijn Coenen773609e2017-10-24 09:57:53 +0200496
497 if (!ret.isOk()) {
498 LOG(ERROR) << "Transport error, " << ret.description()
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100499 << ", during notification registration for " << mInterfaceName << "/"
500 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200501 return;
502 }
503
504 if (!ret) {
Martijn Coenene6cdfd32017-11-13 14:03:05 +0100505 LOG(ERROR) << "Could not register for notifications for " << mInterfaceName << "/"
506 << mInstanceName << ".";
Martijn Coenen773609e2017-10-24 09:57:53 +0200507 return;
508 }
509
510 mRegisteredForNotifications = true;
511 }
512
513 ~Waiter() {
514 if (mRegisteredForNotifications) {
515 if (!mSm->unregisterForNotifications(mInterfaceName, mInstanceName, this).
516 withDefault(false)) {
517 LOG(ERROR) << "Could not unregister service notification for "
518 << mInterfaceName << "/" << mInstanceName << ".";
519 }
520 }
521 }
522
Steven Morelandcbefd352017-01-23 20:29:05 -0800523 Return<void> onRegistration(const hidl_string& /* fqName */,
524 const hidl_string& /* name */,
525 bool /* preexisting */) override {
526 std::unique_lock<std::mutex> lock(mMutex);
527 if (mRegistered) {
528 return Void();
529 }
530 mRegistered = true;
531 lock.unlock();
532
533 mCondition.notify_one();
534 return Void();
535 }
536
Martijn Coenen773609e2017-10-24 09:57:53 +0200537 void wait() {
Steven Moreland49605102017-03-28 09:33:06 -0700538 using std::literals::chrono_literals::operator""s;
539
Martijn Coenen773609e2017-10-24 09:57:53 +0200540 if (!mRegisteredForNotifications) {
541 // As an alternative, just sleep for a second and return
542 LOG(WARNING) << "Waiting one second for " << mInterfaceName << "/" << mInstanceName;
543 sleep(1);
544 return;
545 }
546
Steven Morelandcbefd352017-01-23 20:29:05 -0800547 std::unique_lock<std::mutex> lock(mMutex);
Steven Moreland49605102017-03-28 09:33:06 -0700548 while(true) {
549 mCondition.wait_for(lock, 1s, [this]{
550 return mRegistered;
551 });
552
553 if (mRegistered) {
554 break;
555 }
556
Martijn Coenen773609e2017-10-24 09:57:53 +0200557 LOG(WARNING) << "Waited one second for " << mInterfaceName << "/" << mInstanceName
Steven Moreland49605102017-03-28 09:33:06 -0700558 << ". Waiting another...";
559 }
Steven Morelandcbefd352017-01-23 20:29:05 -0800560 }
561
Martijn Coenen773609e2017-10-24 09:57:53 +0200562 // Be careful when using this; after calling reset(), you must always try to retrieve
563 // the corresponding service before blocking on the waiter; otherwise, you might run
564 // into a race-condition where the service has just (re-)registered, you clear the state
565 // here, and subsequently calling waiter->wait() will block forever.
566 void reset() {
567 std::unique_lock<std::mutex> lock(mMutex);
568 mRegistered = false;
569 }
Steven Morelandcbefd352017-01-23 20:29:05 -0800570private:
Martijn Coenen773609e2017-10-24 09:57:53 +0200571 const std::string mInterfaceName;
572 const std::string mInstanceName;
573 const sp<IServiceManager1_1>& mSm;
Steven Morelandcbefd352017-01-23 20:29:05 -0800574 std::mutex mMutex;
575 std::condition_variable mCondition;
576 bool mRegistered = false;
Martijn Coenen773609e2017-10-24 09:57:53 +0200577 bool mRegisteredForNotifications = false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800578};
579
580void waitForHwService(
581 const std::string &interface, const std::string &instanceName) {
Martijn Coenen773609e2017-10-24 09:57:53 +0200582 sp<Waiter> waiter = new Waiter(interface, instanceName, defaultServiceManager1_1());
583 waiter->wait();
584}
Steven Morelandcbefd352017-01-23 20:29:05 -0800585
Martijn Coenen773609e2017-10-24 09:57:53 +0200586// Prints relevant error/warning messages for error return values from
587// details::canCastInterface(), both transaction errors (!castReturn.isOk())
588// as well as actual cast failures (castReturn.isOk() && castReturn = false).
589// Returns 'true' if the error is non-fatal and it's useful to retry
590bool handleCastError(const Return<bool>& castReturn, const std::string& descriptor,
591 const std::string& instance) {
592 if (castReturn.isOk()) {
593 if (castReturn) {
594 details::logAlwaysFatal("Successful cast value passed into handleCastError.");
595 }
596 // This should never happen, and there's not really a point in retrying.
597 ALOGE("getService: received incompatible service (bug in hwservicemanager?) for "
598 "%s/%s.", descriptor.c_str(), instance.c_str());
599 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800600 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200601 if (castReturn.isDeadObject()) {
602 ALOGW("getService: found dead hwbinder service for %s/%s.", descriptor.c_str(),
603 instance.c_str());
604 return true;
Steven Morelandcbefd352017-01-23 20:29:05 -0800605 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200606 // This can happen due to:
607 // 1) No SELinux permissions
608 // 2) Other transaction failure (no buffer space, kernel error)
609 // The first isn't recoverable, but the second is.
610 // Since we can't yet differentiate between the two, and clients depend
611 // on us not blocking in case 1), treat this as a fatal error for now.
612 ALOGW("getService: unable to call into hwbinder service for %s/%s.",
613 descriptor.c_str(), instance.c_str());
614 return false;
Steven Morelandcbefd352017-01-23 20:29:05 -0800615}
616
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200617sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
618 const std::string& instance,
619 bool retry, bool getStub) {
620 using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
621 using ::android::hidl::base::V1_0::IBase;
622 using ::android::hidl::manager::V1_0::IServiceManager;
623
Martijn Coenen773609e2017-10-24 09:57:53 +0200624 const sp<IServiceManager1_1> sm = defaultServiceManager1_1();
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200625 if (sm == nullptr) {
626 ALOGE("getService: defaultServiceManager() is null");
627 return nullptr;
628 }
629
630 Return<Transport> transportRet = sm->getTransport(descriptor, instance);
631
632 if (!transportRet.isOk()) {
633 ALOGE("getService: defaultServiceManager()->getTransport returns %s",
634 transportRet.description().c_str());
635 return nullptr;
636 }
637 Transport transport = transportRet;
638 const bool vintfHwbinder = (transport == Transport::HWBINDER);
639 const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
640
Steven Moreland757394b2017-12-13 14:09:24 -0800641#ifdef ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200642
643#ifdef LIBHIDL_TARGET_DEBUGGABLE
644 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
645 const bool trebleTestingOverride = env && !strcmp(env, "true");
646 const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
Steven Moreland757394b2017-12-13 14:09:24 -0800647#else // ENFORCE_VINTF_MANIFEST but not LIBHIDL_TARGET_DEBUGGABLE
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200648 const bool trebleTestingOverride = false;
649 const bool vintfLegacy = false;
650#endif // LIBHIDL_TARGET_DEBUGGABLE
651
Steven Moreland757394b2017-12-13 14:09:24 -0800652#else // not ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200653 const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
654 const bool trebleTestingOverride = env && !strcmp(env, "true");
655 const bool vintfLegacy = (transport == Transport::EMPTY);
Steven Moreland757394b2017-12-13 14:09:24 -0800656#endif // ENFORCE_VINTF_MANIFEST
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200657
Martijn Coenen773609e2017-10-24 09:57:53 +0200658 sp<Waiter> waiter = new Waiter(descriptor, instance, sm);
659 while (!getStub && (vintfHwbinder || vintfLegacy)) {
660 waiter->reset(); // don't reorder this -- see comments on reset()
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200661 Return<sp<IBase>> ret = sm->get(descriptor, instance);
662 if (!ret.isOk()) {
663 ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.",
664 ret.description().c_str(), descriptor.c_str(), instance.c_str());
665 break;
666 }
667 sp<IBase> base = ret;
Martijn Coenen773609e2017-10-24 09:57:53 +0200668 if (base != nullptr) {
669 Return<bool> canCastRet =
670 details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
671
672 if (canCastRet.isOk() && canCastRet) {
673 return base; // still needs to be wrapped by Bp class.
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200674 }
Martijn Coenen773609e2017-10-24 09:57:53 +0200675
676 if (!handleCastError(canCastRet, descriptor, instance)) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200677 }
678
Martijn Coenen773609e2017-10-24 09:57:53 +0200679 // In case of legacy or we were not asked to retry, don't.
680 if (vintfLegacy || !retry) break;
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200681
Martijn Coenen773609e2017-10-24 09:57:53 +0200682 ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
683 waiter->wait();
Martijn Coenen86c3abb2017-10-24 09:33:28 +0200684 }
685
686 if (getStub || vintfPassthru || vintfLegacy) {
687 const sp<IServiceManager> pm = getPassthroughServiceManager();
688 if (pm != nullptr) {
689 sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
690 if (!getStub || trebleTestingOverride) {
691 base = wrapPassthrough(base);
692 }
693 return base;
694 }
695 }
696
697 return nullptr;
698}
699
Steven Morelandcbefd352017-01-23 20:29:05 -0800700}; // namespace details
701
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700702}; // namespace hardware
703}; // namespace android