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 
waitForHwServiceManager()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 
binaryName()87 static std::string binaryName() {
88     std::ifstream ifs("/proc/self/cmdline");
89     std::string cmdline;
90     if (!ifs) {
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 
packageWithoutVersion(const std::string & packageAndVersion)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 
tryShortenProcessName(const std::string & descriptor)109 __attribute__((noinline)) 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. android.hardware.module.foo@1.2::IFoo -> foo@1.2
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) {
139             ALOGI("Could not rename process, failed read comm for %s.", dp->d_name);
140             continue;
141         }
142 
143         std::string oldComm;
144         if (!(fs >> oldComm)) continue;
145 
146         // don't rename if it already has an explicit name
147         if (base::StartsWith(descriptor, oldComm)) {
148             if (!fs.seekg(0, fs.beg)) continue;
149             fs << newName;
150         }
151     }
152 }
153 
154 namespace details {
155 
156 #ifdef ENFORCE_VINTF_MANIFEST
157 static constexpr bool kEnforceVintfManifest = true;
158 #else
159 static constexpr bool kEnforceVintfManifest = false;
160 #endif
161 
getTrebleTestingOverridePtr()162 static bool* getTrebleTestingOverridePtr() {
163     static bool gTrebleTestingOverride = false;
164     return &gTrebleTestingOverride;
165 }
166 
setTrebleTestingOverride(bool testingOverride)167 void setTrebleTestingOverride(bool testingOverride) {
168     *getTrebleTestingOverridePtr() = testingOverride;
169 }
170 
isDebuggable()171 static bool isDebuggable() {
172     static bool debuggable = base::GetBoolProperty("ro.debuggable", false);
173     return debuggable;
174 }
175 
isTrebleTestingOverride()176 static inline bool isTrebleTestingOverride() {
177     if (kEnforceVintfManifest && !isDebuggable()) {
178         // don't allow testing override in production
179         return false;
180     }
181 
182     return *getTrebleTestingOverridePtr();
183 }
184 
onRegistrationImpl(const std::string & descriptor,const std::string & instanceName)185 static void onRegistrationImpl(const std::string& descriptor, const std::string& instanceName) {
186     LOG(INFO) << "Registered " << descriptor << "/" << instanceName;
187     tryShortenProcessName(descriptor);
188 }
189 
190 // only used by prebuilts - should be able to remove
onRegistration(const std::string & packageName,const std::string & interfaceName,const std::string & instanceName)191 void onRegistration(const std::string& packageName, const std::string& interfaceName,
192                     const std::string& instanceName) {
193     return onRegistrationImpl(packageName + "::" + interfaceName, instanceName);
194 }
195 
196 }  // details
197 
defaultServiceManager()198 sp<IServiceManager1_0> defaultServiceManager() {
199     return defaultServiceManager1_2();
200 }
defaultServiceManager1_1()201 sp<IServiceManager1_1> defaultServiceManager1_1() {
202     return defaultServiceManager1_2();
203 }
defaultServiceManager1_2()204 sp<IServiceManager1_2> defaultServiceManager1_2() {
205     using android::hidl::manager::V1_2::BnHwServiceManager;
206     using android::hidl::manager::V1_2::BpHwServiceManager;
207 
208     static std::mutex& gDefaultServiceManagerLock = *new std::mutex;
209     static sp<IServiceManager1_2>& gDefaultServiceManager = *new sp<IServiceManager1_2>;
210 
211     {
212         std::lock_guard<std::mutex> _l(gDefaultServiceManagerLock);
213         if (gDefaultServiceManager != nullptr) {
214             return gDefaultServiceManager;
215         }
216 
217         if (access("/dev/hwbinder", F_OK|R_OK|W_OK) != 0) {
218             // HwBinder not available on this device or not accessible to
219             // this process.
220             return nullptr;
221         }
222 
223         waitForHwServiceManager();
224 
225         while (gDefaultServiceManager == nullptr) {
226             gDefaultServiceManager =
227                 fromBinder<IServiceManager1_2, BpHwServiceManager, BnHwServiceManager>(
228                     ProcessState::self()->getContextObject(nullptr));
229             if (gDefaultServiceManager == nullptr) {
230                 LOG(ERROR) << "Waited for hwservicemanager, but got nullptr.";
231                 sleep(1);
232             }
233         }
234     }
235 
236     return gDefaultServiceManager;
237 }
238 
findFiles(const std::string & path,const std::string & prefix,const std::string & suffix)239 static std::vector<std::string> findFiles(const std::string& path, const std::string& prefix,
240                                           const std::string& suffix) {
241     std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
242     if (!dir) return {};
243 
244     std::vector<std::string> results{};
245 
246     dirent* dp;
247     while ((dp = readdir(dir.get())) != nullptr) {
248         std::string name = dp->d_name;
249 
250         if (base::StartsWith(name, prefix) && base::EndsWith(name, suffix)) {
251             results.push_back(name);
252         }
253     }
254 
255     return results;
256 }
257 
matchPackageName(const std::string & lib,std::string * matchedName,std::string * implName)258 static bool matchPackageName(const std::string& lib, std::string* matchedName,
259                              std::string* implName) {
260 #define RE_COMPONENT "[a-zA-Z_][a-zA-Z_0-9]*"
261 #define RE_PATH RE_COMPONENT "(?:[.]" RE_COMPONENT ")*"
262     static const std::regex gLibraryFileNamePattern("(" RE_PATH "@[0-9]+[.][0-9]+)-impl(.*?).so");
263 #undef RE_PATH
264 #undef RE_COMPONENT
265 
266     std::smatch match;
267     if (std::regex_match(lib, match, gLibraryFileNamePattern)) {
268         *matchedName = match.str(1) + "::I*";
269         *implName = match.str(2);
270         return true;
271     }
272     return false;
273 }
274 
registerReference(const hidl_string & interfaceName,const hidl_string & instanceName)275 static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
276     if (kIsRecovery) {
277         // No hwservicemanager in recovery.
278         return;
279     }
280 
281     sp<IServiceManager1_0> binderizedManager = defaultServiceManager();
282     if (binderizedManager == nullptr) {
283         LOG(WARNING) << "Could not registerReference for "
284                      << interfaceName << "/" << instanceName
285                      << ": null binderized manager.";
286         return;
287     }
288     auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
289     if (!ret.isOk()) {
290         LOG(WARNING) << "Could not registerReference for "
291                      << interfaceName << "/" << instanceName
292                      << ": " << ret.description();
293         return;
294     }
295     LOG(VERBOSE) << "Successfully registerReference for "
296                  << interfaceName << "/" << instanceName;
297 }
298 
299 using InstanceDebugInfo = hidl::manager::V1_0::IServiceManager::InstanceDebugInfo;
fetchPidsForPassthroughLibraries(std::map<std::string,InstanceDebugInfo> * infos)300 static inline void fetchPidsForPassthroughLibraries(
301     std::map<std::string, InstanceDebugInfo>* infos) {
302     static const std::string proc = "/proc/";
303 
304     std::map<std::string, std::set<pid_t>> pids;
305     std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(proc.c_str()), closedir);
306     if (!dir) return;
307     dirent* dp;
308     while ((dp = readdir(dir.get())) != nullptr) {
309         pid_t pid = strtoll(dp->d_name, nullptr, 0);
310         if (pid == 0) continue;
311         std::string mapsPath = proc + dp->d_name + "/maps";
312         std::ifstream ifs{mapsPath};
313         if (!ifs.is_open()) continue;
314 
315         for (std::string line; std::getline(ifs, line);) {
316             // The last token of line should look like
317             // vendor/lib64/hw/android.hardware.foo@1.0-impl-extra.so
318             // Use some simple filters to ignore bad lines before extracting libFileName
319             // and checking the key in info to make parsing faster.
320             if (line.back() != 'o') continue;
321             if (line.rfind('@') == std::string::npos) continue;
322 
323             auto spacePos = line.rfind(' ');
324             if (spacePos == std::string::npos) continue;
325             auto libFileName = line.substr(spacePos + 1);
326             auto it = infos->find(libFileName);
327             if (it == infos->end()) continue;
328             pids[libFileName].insert(pid);
329         }
330     }
331     for (auto& pair : *infos) {
332         pair.second.clientPids =
333             std::vector<pid_t>{pids[pair.first].begin(), pids[pair.first].end()};
334     }
335 }
336 
337 struct PassthroughServiceManager : IServiceManager1_1 {
openLibsandroid::hardware::PassthroughServiceManager338     static void openLibs(
339         const std::string& fqName,
340         const std::function<bool /* continue */ (void* /* handle */, const std::string& /* lib */,
341                                                  const std::string& /* sym */)>& eachLib) {
342         //fqName looks like android.hardware.foo@1.0::IFoo
343         size_t idx = fqName.find("::");
344 
345         if (idx == std::string::npos ||
346                 idx + strlen("::") + 1 >= fqName.size()) {
347             LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
348             return;
349         }
350 
351         std::string packageAndVersion = fqName.substr(0, idx);
352         std::string ifaceName = fqName.substr(idx + strlen("::"));
353 
354         const std::string prefix = packageAndVersion + "-impl";
355         const std::string sym = "HIDL_FETCH_" + ifaceName;
356 
357         constexpr int dlMode = RTLD_LAZY;
358         void* handle = nullptr;
359 
360         dlerror(); // clear
361 
362         static std::string halLibPathVndkSp = details::getVndkSpHwPath();
363         std::vector<std::string> paths = {
364             HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, halLibPathVndkSp,
365 #ifndef __ANDROID_VNDK__
366             HAL_LIBRARY_PATH_SYSTEM,
367 #endif
368         };
369 
370         if (details::isTrebleTestingOverride()) {
371             // Load HAL implementations that are statically linked
372             handle = dlopen(nullptr, dlMode);
373             if (handle == nullptr) {
374                 const char* error = dlerror();
375                 LOG(ERROR) << "Failed to dlopen self: "
376                            << (error == nullptr ? "unknown error" : error);
377             } else if (!eachLib(handle, "SELF", sym)) {
378                 return;
379             }
380         }
381 
382         for (const std::string& path : paths) {
383             std::vector<std::string> libs = findFiles(path, prefix, ".so");
384 
385             for (const std::string &lib : libs) {
386                 const std::string fullPath = path + lib;
387 
388                 if (kIsRecovery || path == HAL_LIBRARY_PATH_SYSTEM) {
389                     handle = dlopen(fullPath.c_str(), dlMode);
390                 } else {
391 #if !defined(__ANDROID_RECOVERY__) && defined(__ANDROID__)
392                     handle = android_load_sphal_library(fullPath.c_str(), dlMode);
393 #endif
394                 }
395 
396                 if (handle == nullptr) {
397                     const char* error = dlerror();
398                     LOG(ERROR) << "Failed to dlopen " << lib << ": "
399                                << (error == nullptr ? "unknown error" : error);
400                     continue;
401                 }
402 
403                 if (!eachLib(handle, lib, sym)) {
404                     return;
405                 }
406             }
407         }
408     }
409 
getandroid::hardware::PassthroughServiceManager410     Return<sp<IBase>> get(const hidl_string& fqName,
411                           const hidl_string& name) override {
412         sp<IBase> ret = nullptr;
413 
414         openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
415             IBase* (*generator)(const char* name);
416             *(void **)(&generator) = dlsym(handle, sym.c_str());
417             if(!generator) {
418                 const char* error = dlerror();
419                 LOG(ERROR) << "Passthrough lookup opened " << lib << " but could not find symbol "
420                            << sym << ": " << (error == nullptr ? "unknown error" : error)
421                            << ". Keeping library open.";
422 
423                 // dlclose too problematic in multi-threaded environment
424                 // dlclose(handle);
425 
426                 return true;  // continue
427             }
428 
429             ret = (*generator)(name.c_str());
430 
431             if (ret == nullptr) {
432                 LOG(ERROR) << "Could not find instance '" << name.c_str() << "' in library " << lib
433                            << ". Keeping library open.";
434 
435                 // dlclose too problematic in multi-threaded environment
436                 // dlclose(handle);
437 
438                 // this module doesn't provide this particular instance
439                 return true;  // continue
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 
addandroid::hardware::PassthroughServiceManager454     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 
getTransportandroid::hardware::PassthroughServiceManager460     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 
listandroid::hardware::PassthroughServiceManager466     Return<void> list(list_cb /* _hidl_cb */) override {
467         LOG(FATAL) << "Cannot list services with passthrough service manager.";
468         return Void();
469     }
listByInterfaceandroid::hardware::PassthroughServiceManager470     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 
registerForNotificationsandroid::hardware::PassthroughServiceManager477     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 
debugDumpandroid::hardware::PassthroughServiceManager485     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 = details::getVndkSpHwPath("lib64");
489         static std::string halLibPathVndkSp32 = details::getVndkSpHwPath("lib");
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 
getAllHalInstanceNames(const std::string & descriptor)562 std::vector<std::string> getAllHalInstanceNames(const std::string& descriptor) {
563     std::vector<std::string> ret;
564     auto sm = defaultServiceManager1_2();
565     sm->listManifestByInterface(descriptor, [&](const auto& instances) {
566         ret.reserve(instances.size());
567         for (const auto& i : instances) {
568             ret.push_back(i);
569         }
570     });
571     return ret;
572 }
573 
574 namespace details {
575 
preloadPassthroughService(const std::string & descriptor)576 void preloadPassthroughService(const std::string &descriptor) {
577     PassthroughServiceManager::openLibs(descriptor,
578         [&](void* /* handle */, const std::string& /* lib */, const std::string& /* sym */) {
579             // do nothing
580             return true; // open all libs
581         });
582 }
583 
584 struct Waiter : IServiceNotification {
Waiterandroid::hardware::details::Waiter585     Waiter(const std::string& interface, const std::string& instanceName,
586            const sp<IServiceManager1_1>& sm) : mInterfaceName(interface),
587                                                mInstanceName(instanceName), mSm(sm) {
588     }
589 
onFirstRefandroid::hardware::details::Waiter590     void onFirstRef() override {
591         // If this process only has one binder thread, and we're calling wait() from
592         // that thread, it will block forever because we hung up the one and only
593         // binder thread on a condition variable that can only be notified by an
594         // incoming binder call.
595         if (IPCThreadState::self()->isOnlyBinderThread()) {
596             LOG(WARNING) << "Can't efficiently wait for " << mInterfaceName << "/"
597                          << mInstanceName << ", because we are called from "
598                          << "the only binder thread in this process.";
599             return;
600         }
601 
602         Return<bool> ret = mSm->registerForNotifications(mInterfaceName, mInstanceName, this);
603 
604         if (!ret.isOk()) {
605             LOG(ERROR) << "Transport error, " << ret.description()
606                        << ", during notification registration for " << mInterfaceName << "/"
607                        << mInstanceName << ".";
608             return;
609         }
610 
611         if (!ret) {
612             LOG(ERROR) << "Could not register for notifications for " << mInterfaceName << "/"
613                        << mInstanceName << ".";
614             return;
615         }
616 
617         mRegisteredForNotifications = true;
618     }
619 
~Waiterandroid::hardware::details::Waiter620     ~Waiter() {
621         if (!mDoneCalled) {
622             LOG(FATAL)
623                 << "Waiter still registered for notifications, call done() before dropping ref!";
624         }
625     }
626 
onRegistrationandroid::hardware::details::Waiter627     Return<void> onRegistration(const hidl_string& /* fqName */,
628                                 const hidl_string& /* name */,
629                                 bool /* preexisting */) override {
630         std::unique_lock<std::mutex> lock(mMutex);
631         if (mRegistered) {
632             return Void();
633         }
634         mRegistered = true;
635         lock.unlock();
636 
637         mCondition.notify_one();
638         return Void();
639     }
640 
waitandroid::hardware::details::Waiter641     void wait(bool timeout) {
642         using std::literals::chrono_literals::operator""s;
643 
644         if (!mRegisteredForNotifications) {
645             // As an alternative, just sleep for a second and return
646             LOG(WARNING) << "Waiting one second for " << mInterfaceName << "/" << mInstanceName;
647             sleep(1);
648             return;
649         }
650 
651         std::unique_lock<std::mutex> lock(mMutex);
652         do {
653             mCondition.wait_for(lock, 1s, [this]{
654                 return mRegistered;
655             });
656 
657             if (mRegistered) {
658                 break;
659             }
660 
661             LOG(WARNING) << "Waited one second for " << mInterfaceName << "/" << mInstanceName;
662         } while (!timeout);
663     }
664 
665     // Be careful when using this; after calling reset(), you must always try to retrieve
666     // the corresponding service before blocking on the waiter; otherwise, you might run
667     // into a race-condition where the service has just (re-)registered, you clear the state
668     // here, and subsequently calling waiter->wait() will block forever.
resetandroid::hardware::details::Waiter669     void reset() {
670         std::unique_lock<std::mutex> lock(mMutex);
671         mRegistered = false;
672     }
673 
674     // done() must be called before dropping the last strong ref to the Waiter, to make
675     // sure we can properly unregister with hwservicemanager.
doneandroid::hardware::details::Waiter676     void done() {
677         if (mRegisteredForNotifications) {
678             if (!mSm->unregisterForNotifications(mInterfaceName, mInstanceName, this)
679                      .withDefault(false)) {
680                 LOG(ERROR) << "Could not unregister service notification for " << mInterfaceName
681                            << "/" << mInstanceName << ".";
682             } else {
683                 mRegisteredForNotifications = false;
684             }
685         }
686         mDoneCalled = true;
687     }
688 
689    private:
690     const std::string mInterfaceName;
691     const std::string mInstanceName;
692     sp<IServiceManager1_1> mSm;
693     std::mutex mMutex;
694     std::condition_variable mCondition;
695     bool mRegistered = false;
696     bool mRegisteredForNotifications = false;
697     bool mDoneCalled = false;
698 };
699 
waitForHwService(const std::string & interface,const std::string & instanceName)700 void waitForHwService(
701         const std::string &interface, const std::string &instanceName) {
702     sp<Waiter> waiter = new Waiter(interface, instanceName, defaultServiceManager1_1());
703     waiter->wait(false /* timeout */);
704     waiter->done();
705 }
706 
707 // Prints relevant error/warning messages for error return values from
708 // details::canCastInterface(), both transaction errors (!castReturn.isOk())
709 // as well as actual cast failures (castReturn.isOk() && castReturn = false).
710 // 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)711 bool handleCastError(const Return<bool>& castReturn, const std::string& descriptor,
712                      const std::string& instance) {
713     if (castReturn.isOk()) {
714         if (castReturn) {
715             details::logAlwaysFatal("Successful cast value passed into handleCastError.");
716         }
717         // This should never happen, and there's not really a point in retrying.
718         ALOGE("getService: received incompatible service (bug in hwservicemanager?) for "
719             "%s/%s.", descriptor.c_str(), instance.c_str());
720         return false;
721     }
722     if (castReturn.isDeadObject()) {
723         ALOGW("getService: found dead hwbinder service for %s/%s.", descriptor.c_str(),
724               instance.c_str());
725         return true;
726     }
727     // This can happen due to:
728     // 1) No SELinux permissions
729     // 2) Other transaction failure (no buffer space, kernel error)
730     // The first isn't recoverable, but the second is.
731     // Since we can't yet differentiate between the two, and clients depend
732     // on us not blocking in case 1), treat this as a fatal error for now.
733     ALOGW("getService: unable to call into hwbinder service for %s/%s.",
734           descriptor.c_str(), instance.c_str());
735     return false;
736 }
737 
getRawServiceInternal(const std::string & descriptor,const std::string & instance,bool retry,bool getStub)738 sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
739                                                              const std::string& instance,
740                                                              bool retry, bool getStub) {
741     using Transport = IServiceManager1_0::Transport;
742     sp<Waiter> waiter;
743 
744     sp<IServiceManager1_1> sm;
745     Transport transport = Transport::EMPTY;
746     if (kIsRecovery) {
747         transport = Transport::PASSTHROUGH;
748     } else {
749         sm = defaultServiceManager1_1();
750         if (sm == nullptr) {
751             ALOGE("getService: defaultServiceManager() is null");
752             return nullptr;
753         }
754 
755         Return<Transport> transportRet = sm->getTransport(descriptor, instance);
756 
757         if (!transportRet.isOk()) {
758             ALOGE("getService: defaultServiceManager()->getTransport returns %s",
759                   transportRet.description().c_str());
760             return nullptr;
761         }
762         transport = transportRet;
763     }
764 
765     const bool vintfHwbinder = (transport == Transport::HWBINDER);
766     const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
767     const bool trebleTestingOverride = isTrebleTestingOverride();
768     const bool allowLegacy = !kEnforceVintfManifest || (trebleTestingOverride && isDebuggable());
769     const bool vintfLegacy = (transport == Transport::EMPTY) && allowLegacy;
770 
771     if (!kEnforceVintfManifest) {
772         ALOGE("getService: Potential race detected. The VINTF manifest is not being enforced. If "
773               "a HAL server has a delay in starting and it is not in the manifest, it will not be "
774               "retrieved. Please make sure all HALs on this device are in the VINTF manifest and "
775               "enable PRODUCT_ENFORCE_VINTF_MANIFEST on this device (this is also enabled by "
776               "PRODUCT_FULL_TREBLE). PRODUCT_ENFORCE_VINTF_MANIFEST will ensure that no race "
777               "condition is possible here.");
778         sleep(1);
779     }
780 
781     for (int tries = 0; !getStub && (vintfHwbinder || vintfLegacy); tries++) {
782         if (waiter == nullptr && tries > 0) {
783             waiter = new Waiter(descriptor, instance, sm);
784         }
785         if (waiter != nullptr) {
786             waiter->reset();  // don't reorder this -- see comments on reset()
787         }
788         Return<sp<IBase>> ret = sm->get(descriptor, instance);
789         if (!ret.isOk()) {
790             ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.",
791                   ret.description().c_str(), descriptor.c_str(), instance.c_str());
792             break;
793         }
794         sp<IBase> base = ret;
795         if (base != nullptr) {
796             Return<bool> canCastRet =
797                 details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
798 
799             if (canCastRet.isOk() && canCastRet) {
800                 if (waiter != nullptr) {
801                     waiter->done();
802                 }
803                 return base; // still needs to be wrapped by Bp class.
804             }
805 
806             if (!handleCastError(canCastRet, descriptor, instance)) break;
807         }
808 
809         // In case of legacy or we were not asked to retry, don't.
810         if (vintfLegacy || !retry) break;
811 
812         if (waiter != nullptr) {
813             ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
814             waiter->wait(true /* timeout */);
815         }
816     }
817 
818     if (waiter != nullptr) {
819         waiter->done();
820     }
821 
822     if (getStub || vintfPassthru || vintfLegacy) {
823         const sp<IServiceManager1_0> pm = getPassthroughServiceManager();
824         if (pm != nullptr) {
825             sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
826             if (!getStub || trebleTestingOverride) {
827                 base = wrapPassthrough(base);
828             }
829             return base;
830         }
831     }
832 
833     return nullptr;
834 }
835 
registerAsServiceInternal(const sp<IBase> & service,const std::string & name)836 status_t registerAsServiceInternal(const sp<IBase>& service, const std::string& name) {
837     if (service == nullptr) {
838         return UNEXPECTED_NULL;
839     }
840 
841     sp<IServiceManager1_2> sm = defaultServiceManager1_2();
842     if (sm == nullptr) {
843         return INVALID_OPERATION;
844     }
845 
846     const std::string descriptor = getDescriptor(service.get());
847 
848     if (kEnforceVintfManifest && !isTrebleTestingOverride()) {
849         using Transport = IServiceManager1_0::Transport;
850         Return<Transport> transport = sm->getTransport(descriptor, name);
851 
852         if (!transport.isOk()) {
853             LOG(ERROR) << "Could not get transport for " << descriptor << "/" << name << ": "
854                        << transport.description();
855             return UNKNOWN_ERROR;
856         }
857 
858         if (transport != Transport::HWBINDER) {
859             LOG(ERROR) << "Service " << descriptor << "/" << name
860                        << " must be in VINTF manifest in order to register/get.";
861             return UNKNOWN_ERROR;
862         }
863     }
864 
865     bool registered = false;
866     Return<void> ret = service->interfaceChain([&](const auto& chain) {
867         registered = sm->addWithChain(name.c_str(), service, chain).withDefault(false);
868     });
869 
870     if (!ret.isOk()) {
871         LOG(ERROR) << "Could not retrieve interface chain: " << ret.description();
872     }
873 
874     if (registered) {
875         onRegistrationImpl(descriptor, name);
876     }
877 
878     return registered ? OK : UNKNOWN_ERROR;
879 }
880 
881 } // namespace details
882 
883 } // namespace hardware
884 } // namespace android
885