blob: 0b7ec34840951c16ba03c0750ddbc7c02ff35ed0 [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
Yifan Hong9a22d1d2017-01-25 14:19:26 -080019#include <condition_variable>
20#include <dlfcn.h>
21#include <dirent.h>
Steven Morelandcd4dbdf2017-04-07 20:31:22 -070022#include <fstream>
23#include <pthread.h>
Yifan Hong9a22d1d2017-01-25 14:19:26 -080024#include <unistd.h>
25
26#include <mutex>
27#include <regex>
Yifan Hongbd0d8f72017-05-24 19:43:51 -070028#include <set>
Yifan Hong9a22d1d2017-01-25 14:19:26 -080029
Martijn Coenen12f04d92016-12-07 17:29:41 +010030#include <hidl/HidlBinderSupport.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070031#include <hidl/ServiceManagement.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070032#include <hidl/Status.h>
33
Steven Moreland337e6b62017-01-18 17:25:13 -080034#include <android-base/logging.h>
Steven Morelandc1cee2c2017-03-24 16:23:11 +000035#include <android-base/properties.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070036#include <hwbinder/IPCThreadState.h>
37#include <hwbinder/Parcel.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070038
39#include <android/hidl/manager/1.0/IServiceManager.h>
Yifan Hong4e925992017-01-09 17:47:17 -080040#include <android/hidl/manager/1.0/BpHwServiceManager.h>
41#include <android/hidl/manager/1.0/BnHwServiceManager.h>
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070042
Yifan Hong9a22d1d2017-01-25 14:19:26 -080043#define RE_COMPONENT "[a-zA-Z_][a-zA-Z_0-9]*"
44#define RE_PATH RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
45static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
46
Steven Morelandc1cee2c2017-03-24 16:23:11 +000047using android::base::WaitForProperty;
48
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070049using android::hidl::manager::V1_0::IServiceManager;
Steven Moreland337e6b62017-01-18 17:25:13 -080050using android::hidl::manager::V1_0::IServiceNotification;
Yifan Hong4e925992017-01-09 17:47:17 -080051using android::hidl::manager::V1_0::BpHwServiceManager;
52using android::hidl::manager::V1_0::BnHwServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070053
54namespace android {
55namespace hardware {
56
Yifan Hong953e6b02017-03-16 14:52:40 -070057namespace details {
58extern Mutex gDefaultServiceManagerLock;
59extern sp<android::hidl::manager::V1_0::IServiceManager> gDefaultServiceManager;
60} // namespace details
61
Steven Morelandc1cee2c2017-03-24 16:23:11 +000062static const char* kHwServicemanagerReadyProperty = "hwservicemanager.ready";
63
64void waitForHwServiceManager() {
65 using std::literals::chrono_literals::operator""s;
66
67 while (!WaitForProperty(kHwServicemanagerReadyProperty, "true", 1s)) {
68 LOG(WARNING) << "Waited for hwservicemanager.ready for a second, waiting another...";
69 }
70}
71
Steven Morelandcd4dbdf2017-04-07 20:31:22 -070072bool endsWith(const std::string &in, const std::string &suffix) {
73 return in.size() >= suffix.size() &&
74 in.substr(in.size() - suffix.size()) == suffix;
75}
Steven Moreland5d5ef7f2016-10-20 19:19:55 -070076
Steven Morelandcd4dbdf2017-04-07 20:31:22 -070077bool startsWith(const std::string &in, const std::string &prefix) {
78 return in.size() >= prefix.size() &&
79 in.substr(0, prefix.size()) == prefix;
80}
81
82std::string binaryName() {
83 std::ifstream ifs("/proc/self/cmdline");
84 std::string cmdline;
85 if (!ifs.is_open()) {
86 return "";
87 }
88 ifs >> cmdline;
89
90 size_t idx = cmdline.rfind("/");
91 if (idx != std::string::npos) {
92 cmdline = cmdline.substr(idx + 1);
93 }
94
95 return cmdline;
96}
97
98void tryShortenProcessName(const std::string &packageName) {
99 std::string processName = binaryName();
100
101 if (!startsWith(processName, packageName)) {
102 return;
103 }
104
105 // e.x. android.hardware.module.foo@1.0 -> foo@1.0
106 size_t lastDot = packageName.rfind('.');
107 size_t secondDot = packageName.rfind('.', lastDot - 1);
108
109 if (secondDot == std::string::npos) {
110 return;
111 }
112
113 std::string newName = processName.substr(secondDot + 1,
114 16 /* TASK_COMM_LEN */ - 1);
115 ALOGI("Removing namespace from process name %s to %s.",
116 processName.c_str(), newName.c_str());
117
118 int rc = pthread_setname_np(pthread_self(), newName.c_str());
119 ALOGI_IF(rc != 0, "Removing namespace from process name %s failed.",
120 processName.c_str());
121}
122
123namespace details {
124
125void onRegistration(const std::string &packageName,
126 const std::string& /* interfaceName */,
127 const std::string& /* instanceName */) {
128 tryShortenProcessName(packageName);
129}
130
131} // details
132
133sp<IServiceManager> defaultServiceManager() {
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700134 {
Yifan Hong953e6b02017-03-16 14:52:40 -0700135 AutoMutex _l(details::gDefaultServiceManagerLock);
136 if (details::gDefaultServiceManager != NULL) {
137 return details::gDefaultServiceManager;
Yifan Hong8fb656b2017-03-16 14:30:40 -0700138 }
Steven Morelandcd4dbdf2017-04-07 20:31:22 -0700139
Yifan Hong8fb656b2017-03-16 14:30:40 -0700140 if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
141 // HwBinder not available on this device or not accessible to
142 // this process.
143 return nullptr;
144 }
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000145
146 waitForHwServiceManager();
147
Yifan Hong953e6b02017-03-16 14:52:40 -0700148 while (details::gDefaultServiceManager == NULL) {
149 details::gDefaultServiceManager =
Yifan Hong8fb656b2017-03-16 14:30:40 -0700150 fromBinder<IServiceManager, BpHwServiceManager, BnHwServiceManager>(
151 ProcessState::self()->getContextObject(NULL));
Yifan Hong953e6b02017-03-16 14:52:40 -0700152 if (details::gDefaultServiceManager == NULL) {
Steven Morelandc1cee2c2017-03-24 16:23:11 +0000153 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700154 sleep(1);
Yifan Hong8fb656b2017-03-16 14:30:40 -0700155 }
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700156 }
157 }
158
Yifan Hong953e6b02017-03-16 14:52:40 -0700159 return details::gDefaultServiceManager;
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700160}
161
Steven Moreland0091c092017-01-20 23:15:18 +0000162std::vector<std::string> search(const std::string &path,
163 const std::string &prefix,
164 const std::string &suffix) {
165 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
166 if (!dir) return {};
167
168 std::vector<std::string> results{};
169
170 dirent* dp;
171 while ((dp = readdir(dir.get())) != nullptr) {
172 std::string name = dp->d_name;
173
Steven Morelandda8e6172017-04-06 17:24:22 -0700174 if (startsWith(name, prefix) &&
175 endsWith(name, suffix)) {
Steven Moreland0091c092017-01-20 23:15:18 +0000176 results.push_back(name);
177 }
178 }
179
180 return results;
181}
182
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700183bool matchPackageName(const std::string& lib, std::string* matchedName, std::string* implName) {
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800184 std::smatch match;
185 if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
186 *matchedName = match.str(1) + "::I*";
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700187 *implName = match.str(2);
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800188 return true;
189 }
190 return false;
191}
192
Yifan Hong7f49f592017-02-03 15:11:44 -0800193static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
194 sp<IServiceManager> binderizedManager = defaultServiceManager();
195 if (binderizedManager == nullptr) {
196 LOG(WARNING) << "Could not registerReference for "
197 << interfaceName << "/" << instanceName
198 << ": null binderized manager.";
199 return;
200 }
Martijn Coenenbf13ad02017-04-27 09:41:13 -0700201 auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
Yifan Hong7f49f592017-02-03 15:11:44 -0800202 if (!ret.isOk()) {
203 LOG(WARNING) << "Could not registerReference for "
204 << interfaceName << "/" << instanceName
205 << ": " << ret.description();
Steven Moreland0aeaa782017-03-22 08:11:07 -0700206 return;
Yifan Hong7f49f592017-02-03 15:11:44 -0800207 }
Steven Morelande681aa52017-02-15 16:22:37 -0800208 LOG(VERBOSE) << "Successfully registerReference for "
209 << interfaceName << "/" << instanceName;
Yifan Hong7f49f592017-02-03 15:11:44 -0800210}
211
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700212using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
213static inline void fetchPidsForPassthroughLibraries(
214 std::map<std::string, InstanceDebugInfo>* infos) {
215 static const std::string proc = "/proc/";
216
217 std::map<std::string, std::set<pid_t>> pids;
218 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
219 if (!dir) return;
220 dirent* dp;
221 while ((dp = readdir(dir.get())) != nullptr) {
222 pid_t pid = strtoll(dp->d_name, NULL, 0);
223 if (pid == 0) continue;
224 std::string mapsPath = proc + dp->d_name + "/maps";
225 std::ifstream ifs{mapsPath};
226 if (!ifs.is_open()) continue;
227
228 for (std::string line; std::getline(ifs, line);) {
229 // The last token of line should look like
230 // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
231 // Use some simple filters to ignore bad lines before extracting libFileName
232 // and checking the key in info to make parsing faster.
233 if (line.back() != 'o') continue;
234 if (line.rfind('@') == std::string::npos) continue;
235
236 auto spacePos = line.rfind(' ');
237 if (spacePos == std::string::npos) continue;
238 auto libFileName = line.substr(spacePos + 1);
239 auto it = infos->find(libFileName);
240 if (it == infos->end()) continue;
241 pids[libFileName].insert(pid);
242 }
243 }
244 for (auto& pair : *infos) {
245 pair.second.clientPids =
246 std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
247 }
248}
249
Steven Moreland337e6b62017-01-18 17:25:13 -0800250struct PassthroughServiceManager : IServiceManager {
251 Return<sp<IBase>> get(const hidl_string& fqName,
Steven Morelandda8e6172017-04-06 17:24:22 -0700252 const hidl_string& name) override {
253 std::string stdFqName(fqName.c_str());
Steven Moreland337e6b62017-01-18 17:25:13 -0800254
Steven Morelandda8e6172017-04-06 17:24:22 -0700255 //fqName looks like android.hardware.foo@1.0::IFoo
256 size_t idx = stdFqName.find("::");
257
258 if (idx == std::string::npos ||
259 idx + strlen("::") + 1 >= stdFqName.size()) {
Steven Moreland337e6b62017-01-18 17:25:13 -0800260 LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
261 return nullptr;
262 }
263
Steven Morelandda8e6172017-04-06 17:24:22 -0700264 std::string packageAndVersion = stdFqName.substr(0, idx);
265 std::string ifaceName = stdFqName.substr(idx + strlen("::"));
266
267 const std::string prefix = packageAndVersion + "-impl";
268 const std::string sym = "HIDL_FETCH_" + ifaceName;
Steven Moreland348802d2017-02-23 12:48:55 -0800269
Steven Moreland337e6b62017-01-18 17:25:13 -0800270 const int dlMode = RTLD_LAZY;
271 void *handle = nullptr;
272
Steven Moreland0091c092017-01-20 23:15:18 +0000273 // TODO: lookup in VINTF instead
274 // TODO(b/34135607): Remove HAL_LIBRARY_PATH_SYSTEM
275
Steven Morelanda29905c2017-03-01 10:42:35 -0800276 dlerror(); // clear
277
Steven Moreland337e6b62017-01-18 17:25:13 -0800278 for (const std::string &path : {
279 HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM
280 }) {
Steven Moreland0091c092017-01-20 23:15:18 +0000281 std::vector<std::string> libs = search(path, prefix, ".so");
282
Steven Moreland0091c092017-01-20 23:15:18 +0000283 for (const std::string &lib : libs) {
Steven Moreland348802d2017-02-23 12:48:55 -0800284 const std::string fullPath = path + lib;
285
286 handle = dlopen(fullPath.c_str(), dlMode);
287 if (handle == nullptr) {
288 const char* error = dlerror();
289 LOG(ERROR) << "Failed to dlopen " << lib << ": "
290 << (error == nullptr ? "unknown error" : error);
291 continue;
Steven Moreland0091c092017-01-20 23:15:18 +0000292 }
Steven Moreland348802d2017-02-23 12:48:55 -0800293
294 IBase* (*generator)(const char* name);
295 *(void **)(&generator) = dlsym(handle, sym.c_str());
296 if(!generator) {
297 const char* error = dlerror();
298 LOG(ERROR) << "Passthrough lookup opened " << lib
299 << " but could not find symbol " << sym << ": "
300 << (error == nullptr ? "unknown error" : error);
301 dlclose(handle);
302 continue;
303 }
304
Scott Randolpheb0c3372017-04-03 14:07:14 -0700305 IBase *interface = (*generator)(name.c_str());
Steven Moreland348802d2017-02-23 12:48:55 -0800306
307 if (interface == nullptr) {
308 dlclose(handle);
309 continue; // this module doesn't provide this instance name
310 }
311
312 registerReference(fqName, name);
313
314 return interface;
Steven Moreland337e6b62017-01-18 17:25:13 -0800315 }
316 }
317
Steven Moreland348802d2017-02-23 12:48:55 -0800318 return nullptr;
Steven Moreland337e6b62017-01-18 17:25:13 -0800319 }
320
Martijn Coenen67a02492017-03-06 13:04:48 +0100321 Return<bool> add(const hidl_string& /* name */,
Steven Moreland337e6b62017-01-18 17:25:13 -0800322 const sp<IBase>& /* service */) override {
323 LOG(FATAL) << "Cannot register services with passthrough service manager.";
324 return false;
325 }
326
Steven Moreland330e3e22017-04-06 09:26:07 -0700327 Return<Transport> getTransport(const hidl_string& /* fqName */,
328 const hidl_string& /* name */) {
329 LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
330 return Transport::EMPTY;
331 }
332
Yifan Hong705e5da2017-03-02 16:59:39 -0800333 Return<void> list(list_cb /* _hidl_cb */) override {
334 LOG(FATAL) << "Cannot list services with passthrough service manager.";
Steven Moreland337e6b62017-01-18 17:25:13 -0800335 return Void();
336 }
337 Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
338 listByInterface_cb /* _hidl_cb */) override {
339 // TODO: add this functionality
340 LOG(FATAL) << "Cannot list services with passthrough service manager.";
341 return Void();
342 }
343
344 Return<bool> registerForNotifications(const hidl_string& /* fqName */,
345 const hidl_string& /* name */,
346 const sp<IServiceNotification>& /* callback */) override {
347 // This makes no sense.
348 LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
349 return false;
350 }
351
Yifan Hong705e5da2017-03-02 16:59:39 -0800352 Return<void> debugDump(debugDump_cb _hidl_cb) override {
353 using Arch = ::android::hidl::base::V1_0::DebugInfo::Architecture;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700354 using std::literals::string_literals::operator""s;
Yifan Hong705e5da2017-03-02 16:59:39 -0800355 static std::vector<std::pair<Arch, std::vector<const char *>>> sAllPaths{
356 {Arch::IS_64BIT, {HAL_LIBRARY_PATH_ODM_64BIT,
357 HAL_LIBRARY_PATH_VENDOR_64BIT,
358 HAL_LIBRARY_PATH_SYSTEM_64BIT}},
359 {Arch::IS_32BIT, {HAL_LIBRARY_PATH_ODM_32BIT,
360 HAL_LIBRARY_PATH_VENDOR_32BIT,
361 HAL_LIBRARY_PATH_SYSTEM_32BIT}}
362 };
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700363 std::map<std::string, InstanceDebugInfo> map;
Yifan Hong705e5da2017-03-02 16:59:39 -0800364 for (const auto &pair : sAllPaths) {
365 Arch arch = pair.first;
366 for (const auto &path : pair.second) {
367 std::vector<std::string> libs = search(path, "", ".so");
368 for (const std::string &lib : libs) {
369 std::string matchedName;
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700370 std::string implName;
371 if (matchPackageName(lib, &matchedName, &implName)) {
372 std::string instanceName{"* ("s + path + ")"s};
373 if (!implName.empty()) instanceName += " ("s + implName + ")"s;
374 map.emplace(path + lib, InstanceDebugInfo{.interfaceName = matchedName,
375 .instanceName = instanceName,
376 .clientPids = {},
377 .arch = arch});
Yifan Hong705e5da2017-03-02 16:59:39 -0800378 }
379 }
380 }
381 }
Yifan Hongbd0d8f72017-05-24 19:43:51 -0700382 fetchPidsForPassthroughLibraries(&map);
383 hidl_vec<InstanceDebugInfo> vec;
384 vec.resize(map.size());
385 size_t idx = 0;
386 for (auto&& pair : map) {
387 vec[idx++] = std::move(pair.second);
388 }
Yifan Hong705e5da2017-03-02 16:59:39 -0800389 _hidl_cb(vec);
Yifan Hong7f49f592017-02-03 15:11:44 -0800390 return Void();
391 }
392
Martijn Coenenbf13ad02017-04-27 09:41:13 -0700393 Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
Yifan Hong7f49f592017-02-03 15:11:44 -0800394 // This makes no sense.
395 LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
396 << "Call it on defaultServiceManager() instead.";
Yifan Hong9a22d1d2017-01-25 14:19:26 -0800397 return Void();
398 }
399
Steven Moreland337e6b62017-01-18 17:25:13 -0800400};
401
402sp<IServiceManager> getPassthroughServiceManager() {
403 static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
404 return manager;
405}
406
Steven Morelandcbefd352017-01-23 20:29:05 -0800407namespace details {
408
409struct Waiter : IServiceNotification {
410 Return<void> onRegistration(const hidl_string& /* fqName */,
411 const hidl_string& /* name */,
412 bool /* preexisting */) override {
413 std::unique_lock<std::mutex> lock(mMutex);
414 if (mRegistered) {
415 return Void();
416 }
417 mRegistered = true;
418 lock.unlock();
419
420 mCondition.notify_one();
421 return Void();
422 }
423
Steven Morelandf1e14f22017-03-28 09:33:06 -0700424 void wait(const std::string &interface, const std::string &instanceName) {
425 using std::literals::chrono_literals::operator""s;
426
Steven Morelandcbefd352017-01-23 20:29:05 -0800427 std::unique_lock<std::mutex> lock(mMutex);
Steven Morelandf1e14f22017-03-28 09:33:06 -0700428 while(true) {
429 mCondition.wait_for(lock, 1s, [this]{
430 return mRegistered;
431 });
432
433 if (mRegistered) {
434 break;
435 }
436
437 LOG(WARNING) << "Waited one second for "
438 << interface << "/" << instanceName
439 << ". Waiting another...";
440 }
Steven Morelandcbefd352017-01-23 20:29:05 -0800441 }
442
443private:
444 std::mutex mMutex;
445 std::condition_variable mCondition;
446 bool mRegistered = false;
447};
448
449void waitForHwService(
450 const std::string &interface, const std::string &instanceName) {
451 const sp<IServiceManager> manager = defaultServiceManager();
452
453 if (manager == nullptr) {
454 LOG(ERROR) << "Could not get default service manager.";
455 return;
456 }
457
458 sp<Waiter> waiter = new Waiter();
459 Return<bool> ret = manager->registerForNotifications(interface, instanceName, waiter);
460
461 if (!ret.isOk()) {
462 LOG(ERROR) << "Transport error, " << ret.description()
463 << ", during notification registration for "
464 << interface << "/" << instanceName << ".";
465 return;
466 }
467
468 if (!ret) {
469 LOG(ERROR) << "Could not register for notifications for "
470 << interface << "/" << instanceName << ".";
471 return;
472 }
473
Steven Morelandf1e14f22017-03-28 09:33:06 -0700474 waiter->wait(interface, instanceName);
Steven Morelandcbefd352017-01-23 20:29:05 -0800475}
476
477}; // namespace details
478
Steven Moreland5d5ef7f2016-10-20 19:19:55 -0700479}; // namespace hardware
480}; // namespace android