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