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