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