ServiceManagement.cpp 33 KB

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