• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
19 #include <android/dlext.h>
20 #include <condition_variable>
21 #include <dlfcn.h>
22 #include <dirent.h>
23 #include <fstream>
24 #include <pthread.h>
25 #include <unistd.h>
26 
27 #include <mutex>
28 #include <regex>
29 #include <set>
30 
31 #include <hidl/HidlBinderSupport.h>
32 #include <hidl/HidlInternal.h>
33 #include <hidl/HidlTransportUtils.h>
34 #include <hidl/ServiceManagement.h>
35 #include <hidl/Status.h>
36 #include <utils/SystemClock.h>
37 
38 #include <android-base/file.h>
39 #include <android-base/logging.h>
40 #include <android-base/parseint.h>
41 #include <android-base/properties.h>
42 #include <android-base/stringprintf.h>
43 #include <android-base/strings.h>
44 #include <hwbinder/IPCThreadState.h>
45 #include <hwbinder/Parcel.h>
46 #if !defined(__ANDROID_RECOVERY__)
47 #include <vndksupport/linker.h>
48 #endif
49 
50 #include <android/hidl/manager/1.2/BnHwServiceManager.h>
51 #include <android/hidl/manager/1.2/BpHwServiceManager.h>
52 #include <android/hidl/manager/1.2/IServiceManager.h>
53 
54 #define RE_COMPONENT    "[a-zA-Z_][a-zA-Z_0-9]*"
55 #define RE_PATH         RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
56 static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
57 
58 using android::base::WaitForProperty;
59 
60 using ::android::hidl::base::V1_0::IBase;
61 using IServiceManager1_0 = android::hidl::manager::V1_0::IServiceManager;
62 using IServiceManager1_1 = android::hidl::manager::V1_1::IServiceManager;
63 using IServiceManager1_2 = android::hidl::manager::V1_2::IServiceManager;
64 using ::android::hidl::manager::V1_0::IServiceNotification;
65 
66 namespace android {
67 namespace hardware {
68 
69 static const char* kHwServicemanagerReadyProperty = "hwservicemanager.ready";
70 
71 #if defined(__ANDROID_RECOVERY__)
72 static constexpr bool kIsRecovery = true;
73 #else
74 static constexpr bool kIsRecovery = false;
75 #endif
76 
waitForHwServiceManager()77 static void waitForHwServiceManager() {
78     using std::literals::chrono_literals::operator""s;
79 
80     while (!WaitForProperty(kHwServicemanagerReadyProperty, "true", 1s)) {
81         LOG(WARNING) << "Waited for hwservicemanager.ready for a second, waiting another...";
82     }
83 }
84 
binaryName()85 static std::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 
93     size_t idx = cmdline.rfind('/');
94     if (idx != std::string::npos) {
95         cmdline = cmdline.substr(idx + 1);
96     }
97 
98     return cmdline;
99 }
100 
packageWithoutVersion(const std::string & packageAndVersion)101 static std::string packageWithoutVersion(const std::string& packageAndVersion) {
102     size_t at = packageAndVersion.find('@');
103     if (at == std::string::npos) return packageAndVersion;
104     return packageAndVersion.substr(0, at);
105 }
106 
tryShortenProcessName(const std::string & descriptor)107 static void tryShortenProcessName(const std::string& descriptor) {
108     const static std::string kTasks = "/proc/self/task/";
109 
110     // make sure that this binary name is in the same package
111     std::string processName = binaryName();
112 
113     // e.x. android.hardware.foo is this package
114     if (!base::StartsWith(packageWithoutVersion(processName), packageWithoutVersion(descriptor))) {
115         return;
116     }
117 
118     // e.x. android.hardware.module.foo@1.2::IFoo -> foo@1.2
119     size_t lastDot = descriptor.rfind('.');
120     if (lastDot == std::string::npos) return;
121     size_t secondDot = descriptor.rfind('.', lastDot - 1);
122     if (secondDot == std::string::npos) return;
123 
124     std::string newName = processName.substr(secondDot + 1, std::string::npos);
125     ALOGI("Removing namespace from process name %s to %s.", processName.c_str(), newName.c_str());
126 
127     std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kTasks.c_str()), closedir);
128     if (dir == nullptr) return;
129 
130     dirent* dp;
131     while ((dp = readdir(dir.get())) != nullptr) {
132         if (dp->d_type != DT_DIR) continue;
133         if (dp->d_name[0] == '.') continue;
134 
135         std::fstream fs(kTasks + dp->d_name + "/comm");
136         if (!fs.is_open()) {
137             ALOGI("Could not rename process, failed read comm for %s.", dp->d_name);
138             continue;
139         }
140 
141         std::string oldComm;
142         fs >> oldComm;
143 
144         // don't rename if it already has an explicit name
145         if (base::StartsWith(descriptor, oldComm)) {
146             fs.seekg(0, fs.beg);
147             fs << newName;
148         }
149     }
150 }
151 
152 namespace details {
153 
154 /*
155  * Returns the age of the current process by reading /proc/self/stat and comparing starttime to the
156  * current time. This is useful for measuring how long it took a HAL to register itself.
157  */
getProcessAgeMs()158 static long getProcessAgeMs() {
159     constexpr const int PROCFS_STAT_STARTTIME_INDEX = 21;
160     std::string content;
161     android::base::ReadFileToString("/proc/self/stat", &content, false);
162     auto stats = android::base::Split(content, " ");
163     if (stats.size() <= PROCFS_STAT_STARTTIME_INDEX) {
164         LOG(INFO) << "Could not read starttime from /proc/self/stat";
165         return -1;
166     }
167     const std::string& startTimeString = stats[PROCFS_STAT_STARTTIME_INDEX];
168     static const int64_t ticksPerSecond = sysconf(_SC_CLK_TCK);
169     const int64_t uptime = android::uptimeMillis();
170 
171     unsigned long long startTimeInClockTicks = 0;
172     if (android::base::ParseUint(startTimeString, &startTimeInClockTicks)) {
173         long startTimeMs = 1000ULL * startTimeInClockTicks / ticksPerSecond;
174         return uptime - startTimeMs;
175     }
176     return -1;
177 }
178 
onRegistrationImpl(const std::string & descriptor,const std::string & instanceName)179 static void onRegistrationImpl(const std::string& descriptor, const std::string& instanceName) {
180     long halStartDelay = getProcessAgeMs();
181     if (halStartDelay >= 0) {
182         // The "start delay" printed here is an estimate of how long it took the HAL to go from
183         // process creation to registering itself as a HAL.  Actual start time could be longer
184         // because the process might not have joined the threadpool yet, so it might not be ready to
185         // process transactions.
186         LOG(INFO) << "Registered " << descriptor << "/" << instanceName << " (start delay of "
187                   << halStartDelay << "ms)";
188     }
189 
190     tryShortenProcessName(descriptor);
191 }
192 
onRegistration(const std::string & packageName,const std::string & interfaceName,const std::string & instanceName)193 void onRegistration(const std::string& packageName, const std::string& interfaceName,
194                     const std::string& instanceName) {
195     return onRegistrationImpl(packageName + "::" + interfaceName, instanceName);
196 }
197 
198 }  // details
199 
defaultServiceManager()200 sp<IServiceManager1_0> defaultServiceManager() {
201     return defaultServiceManager1_2();
202 }
defaultServiceManager1_1()203 sp<IServiceManager1_1> defaultServiceManager1_1() {
204     return defaultServiceManager1_2();
205 }
defaultServiceManager1_2()206 sp<IServiceManager1_2> defaultServiceManager1_2() {
207     using android::hidl::manager::V1_2::BnHwServiceManager;
208     using android::hidl::manager::V1_2::BpHwServiceManager;
209 
210     static std::mutex gDefaultServiceManagerLock;
211     static sp<IServiceManager1_2> gDefaultServiceManager;
212 
213     {
214         std::lock_guard<std::mutex> _l(gDefaultServiceManagerLock);
215         if (gDefaultServiceManager != nullptr) {
216             return gDefaultServiceManager;
217         }
218 
219         if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
220             // HwBinder not available on this device or not accessible to
221             // this process.
222             return nullptr;
223         }
224 
225         waitForHwServiceManager();
226 
227         while (gDefaultServiceManager == nullptr) {
228             gDefaultServiceManager =
229                 fromBinder<IServiceManager1_2, BpHwServiceManager, BnHwServiceManager>(
230                     ProcessState::self()->getContextObject(nullptr));
231             if (gDefaultServiceManager == nullptr) {
232                 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
233                 sleep(1);
234             }
235         }
236     }
237 
238     return gDefaultServiceManager;
239 }
240 
findFiles(const std::string & path,const std::string & prefix,const std::string & suffix)241 static std::vector<std::string> findFiles(const std::string& path, const std::string& prefix,
242                                           const std::string& suffix) {
243     std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
244     if (!dir) return {};
245 
246     std::vector<std::string> results{};
247 
248     dirent* dp;
249     while ((dp = readdir(dir.get())) != nullptr) {
250         std::string name = dp->d_name;
251 
252         if (base::StartsWith(name, prefix) && base::EndsWith(name, suffix)) {
253             results.push_back(name);
254         }
255     }
256 
257     return results;
258 }
259 
matchPackageName(const std::string & lib,std::string * matchedName,std::string * implName)260 bool matchPackageName(const std::string& lib, std::string* matchedName, std::string* implName) {
261     std::smatch match;
262     if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
263         *matchedName = match.str(1) + "::I*";
264         *implName = match.str(2);
265         return true;
266     }
267     return false;
268 }
269 
registerReference(const hidl_string & interfaceName,const hidl_string & instanceName)270 static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
271     if (kIsRecovery) {
272         // No hwservicemanager in recovery.
273         return;
274     }
275 
276     sp<IServiceManager1_0> binderizedManager = defaultServiceManager();
277     if (binderizedManager == nullptr) {
278         LOG(WARNING) << "Could not registerReference for "
279                      << interfaceName << "/" << instanceName
280                      << ": null binderized manager.";
281         return;
282     }
283     auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
284     if (!ret.isOk()) {
285         LOG(WARNING) << "Could not registerReference for "
286                      << interfaceName << "/" << instanceName
287                      << ": " << ret.description();
288         return;
289     }
290     LOG(VERBOSE) << "Successfully registerReference for "
291                  << interfaceName << "/" << instanceName;
292 }
293 
294 using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
fetchPidsForPassthroughLibraries(std::map<std::string,InstanceDebugInfo> * infos)295 static inline void fetchPidsForPassthroughLibraries(
296     std::map<std::string, InstanceDebugInfo>* infos) {
297     static const std::string proc = "/proc/";
298 
299     std::map<std::string, std::set<pid_t>> pids;
300     std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
301     if (!dir) return;
302     dirent* dp;
303     while ((dp = readdir(dir.get())) != nullptr) {
304         pid_t pid = strtoll(dp->d_name, nullptr, 0);
305         if (pid == 0) continue;
306         std::string mapsPath = proc + dp->d_name + "/maps";
307         std::ifstream ifs{mapsPath};
308         if (!ifs.is_open()) continue;
309 
310         for (std::string line; std::getline(ifs, line);) {
311             // The last token of line should look like
312             // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
313             // Use some simple filters to ignore bad lines before extracting libFileName
314             // and checking the key in info to make parsing faster.
315             if (line.back() != 'o') continue;
316             if (line.rfind('@') == std::string::npos) continue;
317 
318             auto spacePos = line.rfind(' ');
319             if (spacePos == std::string::npos) continue;
320             auto libFileName = line.substr(spacePos + 1);
321             auto it = infos->find(libFileName);
322             if (it == infos->end()) continue;
323             pids[libFileName].insert(pid);
324         }
325     }
326     for (auto& pair : *infos) {
327         pair.second.clientPids =
328             std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
329     }
330 }
331 
332 struct PassthroughServiceManager : IServiceManager1_1 {
openLibsandroid::hardware::PassthroughServiceManager333     static void openLibs(
334         const std::string& fqName,
335         const std::function<bool /* continue */ (void* /* handle */, const std::string& /* lib */,
336                                                  const std::string& /* sym */)>& eachLib) {
337         //fqName looks like android.hardware.foo@1.0::IFoo
338         size_t idx = fqName.find("::");
339 
340         if (idx == std::string::npos ||
341                 idx + strlen("::") + 1 >= fqName.size()) {
342             LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
343             return;
344         }
345 
346         std::string packageAndVersion = fqName.substr(0, idx);
347         std::string ifaceName = fqName.substr(idx + strlen("::"));
348 
349         const std::string prefix = packageAndVersion + "-impl";
350         const std::string sym = "HIDL_FETCH_" + ifaceName;
351 
352         constexpr int dlMode = RTLD_LAZY;
353         void* handle = nullptr;
354 
355         dlerror(); // clear
356 
357         static std::string halLibPathVndkSp = android::base::StringPrintf(
358             HAL_LIBRARY_PATH_VNDK_SP_FOR_VERSION, details::getVndkVersionStr().c_str());
359         std::vector<std::string> paths = {
360             HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, halLibPathVndkSp,
361 #ifndef __ANDROID_VNDK__
362             HAL_LIBRARY_PATH_SYSTEM,
363 #endif
364         };
365 
366 #ifdef LIBHIDL_TARGET_DEBUGGABLE
367         const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
368         const bool trebleTestingOverride = env && !strcmp(env, "true");
369         if (trebleTestingOverride) {
370             // Load HAL implementations that are statically linked
371             handle = dlopen(nullptr, dlMode);
372             if (handle == nullptr) {
373                 const char* error = dlerror();
374                 LOG(ERROR) << "Failed to dlopen self: "
375                            << (error == nullptr ? "unknown error" : error);
376             } else if (!eachLib(handle, "SELF", sym)) {
377                 return;
378             }
379 
380             const char* vtsRootPath = std::getenv("VTS_ROOT_PATH");
381             if (vtsRootPath && strlen(vtsRootPath) > 0) {
382                 const std::string halLibraryPathVtsOverride =
383                     std::string(vtsRootPath) + HAL_LIBRARY_PATH_SYSTEM;
384                 paths.insert(paths.begin(), halLibraryPathVtsOverride);
385             }
386         }
387 #endif
388 
389         for (const std::string& path : paths) {
390             std::vector<std::string> libs = findFiles(path, prefix, ".so");
391 
392             for (const std::string &lib : libs) {
393                 const std::string fullPath = path + lib;
394 
395                 if (kIsRecovery || path == HAL_LIBRARY_PATH_SYSTEM) {
396                     handle = dlopen(fullPath.c_str(), dlMode);
397                 } else {
398 #if !defined(__ANDROID_RECOVERY__)
399                     handle = android_load_sphal_library(fullPath.c_str(), dlMode);
400 #endif
401                 }
402 
403                 if (handle == nullptr) {
404                     const char* error = dlerror();
405                     LOG(ERROR) << "Failed to dlopen " << lib << ": "
406                                << (error == nullptr ? "unknown error" : error);
407                     continue;
408                 }
409 
410                 if (!eachLib(handle, lib, sym)) {
411                     return;
412                 }
413             }
414         }
415     }
416 
getandroid::hardware::PassthroughServiceManager417     Return<sp<IBase>> get(const hidl_string& fqName,
418                           const hidl_string& name) override {
419         sp<IBase> ret = nullptr;
420 
421         openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
422             IBase* (*generator)(const char* name);
423             *(void **)(&generator) = dlsym(handle, sym.c_str());
424             if(!generator) {
425                 const char* error = dlerror();
426                 LOG(ERROR) << "Passthrough lookup opened " << lib
427                            << " but could not find symbol " << sym << ": "
428                            << (error == nullptr ? "unknown error" : error);
429                 dlclose(handle);
430                 return true;
431             }
432 
433             ret = (*generator)(name.c_str());
434 
435             if (ret == nullptr) {
436                 dlclose(handle);
437                 return true; // this module doesn't provide this instance name
438             }
439 
440             // Actual fqname might be a subclass.
441             // This assumption is tested in vts_treble_vintf_test
442             using ::android::hardware::details::getDescriptor;
443             std::string actualFqName = getDescriptor(ret.get());
444             CHECK(actualFqName.size() > 0);
445             registerReference(actualFqName, name);
446             return false;
447         });
448 
449         return ret;
450     }
451 
addandroid::hardware::PassthroughServiceManager452     Return<bool> add(const hidl_string& /* name */,
453                      const sp<IBase>& /* service */) override {
454         LOG(FATAL) << "Cannot register services with passthrough service manager.";
455         return false;
456     }
457 
getTransportandroid::hardware::PassthroughServiceManager458     Return<Transport> getTransport(const hidl_string& /* fqName */,
459                                    const hidl_string& /* name */) {
460         LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
461         return Transport::EMPTY;
462     }
463 
listandroid::hardware::PassthroughServiceManager464     Return<void> list(list_cb /* _hidl_cb */) override {
465         LOG(FATAL) << "Cannot list services with passthrough service manager.";
466         return Void();
467     }
listByInterfaceandroid::hardware::PassthroughServiceManager468     Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
469                                  listByInterface_cb /* _hidl_cb */) override {
470         // TODO: add this functionality
471         LOG(FATAL) << "Cannot list services with passthrough service manager.";
472         return Void();
473     }
474 
registerForNotificationsandroid::hardware::PassthroughServiceManager475     Return<bool> registerForNotifications(const hidl_string& /* fqName */,
476                                           const hidl_string& /* name */,
477                                           const sp<IServiceNotification>& /* callback */) override {
478         // This makes no sense.
479         LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
480         return false;
481     }
482 
debugDumpandroid::hardware::PassthroughServiceManager483     Return<void> debugDump(debugDump_cb _hidl_cb) override {
484         using Arch = ::android::hidl::base::V1_0::DebugInfo::Architecture;
485         using std::literals::string_literals::operator""s;
486         static std::string halLibPathVndkSp64 = android::base::StringPrintf(
487             HAL_LIBRARY_PATH_VNDK_SP_64BIT_FOR_VERSION, details::getVndkVersionStr().c_str());
488         static std::string halLibPathVndkSp32 = android::base::StringPrintf(
489             HAL_LIBRARY_PATH_VNDK_SP_32BIT_FOR_VERSION, details::getVndkVersionStr().c_str());
490         static std::vector<std::pair<Arch, std::vector<const char*>>> sAllPaths{
491             {Arch::IS_64BIT,
492              {
493                  HAL_LIBRARY_PATH_ODM_64BIT, HAL_LIBRARY_PATH_VENDOR_64BIT,
494                  halLibPathVndkSp64.c_str(),
495 #ifndef __ANDROID_VNDK__
496                  HAL_LIBRARY_PATH_SYSTEM_64BIT,
497 #endif
498              }},
499             {Arch::IS_32BIT,
500              {
501                  HAL_LIBRARY_PATH_ODM_32BIT, HAL_LIBRARY_PATH_VENDOR_32BIT,
502                  halLibPathVndkSp32.c_str(),
503 #ifndef __ANDROID_VNDK__
504                  HAL_LIBRARY_PATH_SYSTEM_32BIT,
505 #endif
506              }}};
507         std::map<std::string, InstanceDebugInfo> map;
508         for (const auto &pair : sAllPaths) {
509             Arch arch = pair.first;
510             for (const auto &path : pair.second) {
511                 std::vector<std::string> libs = findFiles(path, "", ".so");
512                 for (const std::string &lib : libs) {
513                     std::string matchedName;
514                     std::string implName;
515                     if (matchPackageName(lib, &matchedName, &implName)) {
516                         std::string instanceName{"* ("s + path + ")"s};
517                         if (!implName.empty()) instanceName += " ("s + implName + ")"s;
518                         map.emplace(path + lib, InstanceDebugInfo{.interfaceName = matchedName,
519                                                                   .instanceName = instanceName,
520                                                                   .clientPids = {},
521                                                                   .arch = arch});
522                     }
523                 }
524             }
525         }
526         fetchPidsForPassthroughLibraries(&map);
527         hidl_vec<InstanceDebugInfo> vec;
528         vec.resize(map.size());
529         size_t idx = 0;
530         for (auto&& pair : map) {
531             vec[idx++] = std::move(pair.second);
532         }
533         _hidl_cb(vec);
534         return Void();
535     }
536 
registerPassthroughClientandroid::hardware::PassthroughServiceManager537     Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
538         // This makes no sense.
539         LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
540                    << "Call it on defaultServiceManager() instead.";
541         return Void();
542     }
543 
unregisterForNotificationsandroid::hardware::PassthroughServiceManager544     Return<bool> unregisterForNotifications(const hidl_string& /* fqName */,
545                                             const hidl_string& /* name */,
546                                             const sp<IServiceNotification>& /* callback */) override {
547         // This makes no sense.
548         LOG(FATAL) << "Cannot unregister for notifications with passthrough service manager.";
549         return false;
550     }
551 
552 };
553 
getPassthroughServiceManager()554 sp<IServiceManager1_0> getPassthroughServiceManager() {
555     return getPassthroughServiceManager1_1();
556 }
getPassthroughServiceManager1_1()557 sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
558     static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
559     return manager;
560 }
561 
562 namespace details {
563 
preloadPassthroughService(const std::string & descriptor)564 void preloadPassthroughService(const std::string &descriptor) {
565     PassthroughServiceManager::openLibs(descriptor,
566         [&](void* /* handle */, const std::string& /* lib */, const std::string& /* sym */) {
567             // do nothing
568             return true; // open all libs
569         });
570 }
571 
572 struct Waiter : IServiceNotification {
Waiterandroid::hardware::details::Waiter573     Waiter(const std::string& interface, const std::string& instanceName,
574            const sp<IServiceManager1_1>& sm) : mInterfaceName(interface),
575                                                mInstanceName(instanceName), mSm(sm) {
576     }
577 
onFirstRefandroid::hardware::details::Waiter578     void onFirstRef() override {
579         // If this process only has one binder thread, and we're calling wait() from
580         // that thread, it will block forever because we hung up the one and only
581         // binder thread on a condition variable that can only be notified by an
582         // incoming binder call.
583         if (IPCThreadState::self()->isOnlyBinderThread()) {
584             LOG(WARNING) << "Can't efficiently wait for " << mInterfaceName << "/"
585                          << mInstanceName << ", because we are called from "
586                          << "the only binder thread in this process.";
587             return;
588         }
589 
590         Return<bool> ret = mSm->registerForNotifications(mInterfaceName, mInstanceName, this);
591 
592         if (!ret.isOk()) {
593             LOG(ERROR) << "Transport error, " << ret.description()
594                        << ", during notification registration for " << mInterfaceName << "/"
595                        << mInstanceName << ".";
596             return;
597         }
598 
599         if (!ret) {
600             LOG(ERROR) << "Could not register for notifications for " << mInterfaceName << "/"
601                        << mInstanceName << ".";
602             return;
603         }
604 
605         mRegisteredForNotifications = true;
606     }
607 
~Waiterandroid::hardware::details::Waiter608     ~Waiter() {
609         if (!mDoneCalled) {
610             LOG(FATAL)
611                 << "Waiter still registered for notifications, call done() before dropping ref!";
612         }
613     }
614 
onRegistrationandroid::hardware::details::Waiter615     Return<void> onRegistration(const hidl_string& /* fqName */,
616                                 const hidl_string& /* name */,
617                                 bool /* preexisting */) override {
618         std::unique_lock<std::mutex> lock(mMutex);
619         if (mRegistered) {
620             return Void();
621         }
622         mRegistered = true;
623         lock.unlock();
624 
625         mCondition.notify_one();
626         return Void();
627     }
628 
waitandroid::hardware::details::Waiter629     void wait(bool timeout) {
630         using std::literals::chrono_literals::operator""s;
631 
632         if (!mRegisteredForNotifications) {
633             // As an alternative, just sleep for a second and return
634             LOG(WARNING) << "Waiting one second for " << mInterfaceName << "/" << mInstanceName;
635             sleep(1);
636             return;
637         }
638 
639         std::unique_lock<std::mutex> lock(mMutex);
640         do {
641             mCondition.wait_for(lock, 1s, [this]{
642                 return mRegistered;
643             });
644 
645             if (mRegistered) {
646                 break;
647             }
648 
649             LOG(WARNING) << "Waited one second for " << mInterfaceName << "/" << mInstanceName;
650         } while (!timeout);
651     }
652 
653     // Be careful when using this; after calling reset(), you must always try to retrieve
654     // the corresponding service before blocking on the waiter; otherwise, you might run
655     // into a race-condition where the service has just (re-)registered, you clear the state
656     // here, and subsequently calling waiter->wait() will block forever.
resetandroid::hardware::details::Waiter657     void reset() {
658         std::unique_lock<std::mutex> lock(mMutex);
659         mRegistered = false;
660     }
661 
662     // done() must be called before dropping the last strong ref to the Waiter, to make
663     // sure we can properly unregister with hwservicemanager.
doneandroid::hardware::details::Waiter664     void done() {
665         if (mRegisteredForNotifications) {
666             if (!mSm->unregisterForNotifications(mInterfaceName, mInstanceName, this)
667                      .withDefault(false)) {
668                 LOG(ERROR) << "Could not unregister service notification for " << mInterfaceName
669                            << "/" << mInstanceName << ".";
670             } else {
671                 mRegisteredForNotifications = false;
672             }
673         }
674         mDoneCalled = true;
675     }
676 
677    private:
678     const std::string mInterfaceName;
679     const std::string mInstanceName;
680     sp<IServiceManager1_1> mSm;
681     std::mutex mMutex;
682     std::condition_variable mCondition;
683     bool mRegistered = false;
684     bool mRegisteredForNotifications = false;
685     bool mDoneCalled = false;
686 };
687 
waitForHwService(const std::string & interface,const std::string & instanceName)688 void waitForHwService(
689         const std::string &interface, const std::string &instanceName) {
690     sp<Waiter> waiter = new Waiter(interface, instanceName, defaultServiceManager1_1());
691     waiter->wait(false /* timeout */);
692     waiter->done();
693 }
694 
695 // Prints relevant error/warning messages for error return values from
696 // details::canCastInterface(), both transaction errors (!castReturn.isOk())
697 // as well as actual cast failures (castReturn.isOk() && castReturn = false).
698 // Returns 'true' if the error is non-fatal and it's useful to retry
handleCastError(const Return<bool> & castReturn,const std::string & descriptor,const std::string & instance)699 bool handleCastError(const Return<bool>& castReturn, const std::string& descriptor,
700                      const std::string& instance) {
701     if (castReturn.isOk()) {
702         if (castReturn) {
703             details::logAlwaysFatal("Successful cast value passed into handleCastError.");
704         }
705         // This should never happen, and there's not really a point in retrying.
706         ALOGE("getService: received incompatible service (bug in hwservicemanager?) for "
707             "%s/%s.", descriptor.c_str(), instance.c_str());
708         return false;
709     }
710     if (castReturn.isDeadObject()) {
711         ALOGW("getService: found dead hwbinder service for %s/%s.", descriptor.c_str(),
712               instance.c_str());
713         return true;
714     }
715     // This can happen due to:
716     // 1) No SELinux permissions
717     // 2) Other transaction failure (no buffer space, kernel error)
718     // The first isn't recoverable, but the second is.
719     // Since we can't yet differentiate between the two, and clients depend
720     // on us not blocking in case 1), treat this as a fatal error for now.
721     ALOGW("getService: unable to call into hwbinder service for %s/%s.",
722           descriptor.c_str(), instance.c_str());
723     return false;
724 }
725 
getRawServiceInternal(const std::string & descriptor,const std::string & instance,bool retry,bool getStub)726 sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
727                                                              const std::string& instance,
728                                                              bool retry, bool getStub) {
729     using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
730     using ::android::hidl::manager::V1_0::IServiceManager;
731     sp<Waiter> waiter;
732 
733     sp<IServiceManager1_1> sm;
734     Transport transport = Transport::EMPTY;
735     if (kIsRecovery) {
736         transport = Transport::PASSTHROUGH;
737     } else {
738         sm = defaultServiceManager1_1();
739         if (sm == nullptr) {
740             ALOGE("getService: defaultServiceManager() is null");
741             return nullptr;
742         }
743 
744         Return<Transport> transportRet = sm->getTransport(descriptor, instance);
745 
746         if (!transportRet.isOk()) {
747             ALOGE("getService: defaultServiceManager()->getTransport returns %s",
748                   transportRet.description().c_str());
749             return nullptr;
750         }
751         transport = transportRet;
752     }
753 
754     const bool vintfHwbinder = (transport == Transport::HWBINDER);
755     const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
756 
757 #ifdef ENFORCE_VINTF_MANIFEST
758 
759 #ifdef LIBHIDL_TARGET_DEBUGGABLE
760     const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
761     const bool trebleTestingOverride = env && !strcmp(env, "true");
762     const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
763 #else   // ENFORCE_VINTF_MANIFEST but not LIBHIDL_TARGET_DEBUGGABLE
764     const bool trebleTestingOverride = false;
765     const bool vintfLegacy = false;
766 #endif  // LIBHIDL_TARGET_DEBUGGABLE
767 
768 #else   // not ENFORCE_VINTF_MANIFEST
769     const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
770     const bool trebleTestingOverride = env && !strcmp(env, "true");
771     const bool vintfLegacy = (transport == Transport::EMPTY);
772 #endif  // ENFORCE_VINTF_MANIFEST
773 
774     for (int tries = 0; !getStub && (vintfHwbinder || vintfLegacy); tries++) {
775         if (waiter == nullptr && tries > 0) {
776             waiter = new Waiter(descriptor, instance, sm);
777         }
778         if (waiter != nullptr) {
779             waiter->reset();  // don't reorder this -- see comments on reset()
780         }
781         Return<sp<IBase>> ret = sm->get(descriptor, instance);
782         if (!ret.isOk()) {
783             ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.",
784                   ret.description().c_str(), descriptor.c_str(), instance.c_str());
785             break;
786         }
787         sp<IBase> base = ret;
788         if (base != nullptr) {
789             Return<bool> canCastRet =
790                 details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
791 
792             if (canCastRet.isOk() && canCastRet) {
793                 if (waiter != nullptr) {
794                     waiter->done();
795                 }
796                 return base; // still needs to be wrapped by Bp class.
797             }
798 
799             if (!handleCastError(canCastRet, descriptor, instance)) break;
800         }
801 
802         // In case of legacy or we were not asked to retry, don't.
803         if (vintfLegacy || !retry) break;
804 
805         if (waiter != nullptr) {
806             ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
807             waiter->wait(true /* timeout */);
808         }
809     }
810 
811     if (waiter != nullptr) {
812         waiter->done();
813     }
814 
815     if (getStub || vintfPassthru || vintfLegacy) {
816         const sp<IServiceManager> pm = getPassthroughServiceManager();
817         if (pm != nullptr) {
818             sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
819             if (!getStub || trebleTestingOverride) {
820                 base = wrapPassthrough(base);
821             }
822             return base;
823         }
824     }
825 
826     return nullptr;
827 }
828 
registerAsServiceInternal(const sp<IBase> & service,const std::string & name)829 status_t registerAsServiceInternal(const sp<IBase>& service, const std::string& name) {
830     if (service == nullptr) {
831         return UNEXPECTED_NULL;
832     }
833 
834     sp<IServiceManager1_2> sm = defaultServiceManager1_2();
835     if (sm == nullptr) {
836         return INVALID_OPERATION;
837     }
838 
839     bool registered = false;
840     Return<void> ret = service->interfaceChain([&](const auto& chain) {
841         registered = sm->addWithChain(name.c_str(), service, chain).withDefault(false);
842     });
843 
844     if (!ret.isOk()) {
845         LOG(ERROR) << "Could not retrieve interface chain: " << ret.description();
846     }
847 
848     if (registered) {
849         onRegistrationImpl(getDescriptor(service.get()), name);
850     }
851 
852     return registered ? OK : UNKNOWN_ERROR;
853 }
854 
855 } // namespace details
856 
857 } // namespace hardware
858 } // namespace android
859