ListCommand.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. /*
  2. * Copyright (C) 2017 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. #include "ListCommand.h"
  17. #include <getopt.h>
  18. #include <algorithm>
  19. #include <fstream>
  20. #include <functional>
  21. #include <iomanip>
  22. #include <iostream>
  23. #include <map>
  24. #include <regex>
  25. #include <sstream>
  26. #include <android-base/file.h>
  27. #include <android-base/logging.h>
  28. #include <android-base/parseint.h>
  29. #include <android/hidl/manager/1.0/IServiceManager.h>
  30. #include <hidl-hash/Hash.h>
  31. #include <hidl-util/FQName.h>
  32. #include <private/android_filesystem_config.h>
  33. #include <sys/stat.h>
  34. #include <vintf/HalManifest.h>
  35. #include <vintf/parse_string.h>
  36. #include <vintf/parse_xml.h>
  37. #include "Lshal.h"
  38. #include "PipeRelay.h"
  39. #include "Timeout.h"
  40. #include "utils.h"
  41. using ::android::hardware::hidl_string;
  42. using ::android::hardware::hidl_vec;
  43. using ::android::hidl::base::V1_0::DebugInfo;
  44. using ::android::hidl::base::V1_0::IBase;
  45. using ::android::hidl::manager::V1_0::IServiceManager;
  46. namespace android {
  47. namespace lshal {
  48. vintf::SchemaType toSchemaType(Partition p) {
  49. return (p == Partition::SYSTEM) ? vintf::SchemaType::FRAMEWORK : vintf::SchemaType::DEVICE;
  50. }
  51. Partition toPartition(vintf::SchemaType t) {
  52. switch (t) {
  53. case vintf::SchemaType::FRAMEWORK: return Partition::SYSTEM;
  54. // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
  55. case vintf::SchemaType::DEVICE: return Partition::VENDOR;
  56. }
  57. return Partition::UNKNOWN;
  58. }
  59. std::string getPackageAndVersion(const std::string& fqInstance) {
  60. return splitFirst(fqInstance, ':').first;
  61. }
  62. NullableOStream<std::ostream> ListCommand::out() const {
  63. return mLshal.out();
  64. }
  65. NullableOStream<std::ostream> ListCommand::err() const {
  66. return mLshal.err();
  67. }
  68. std::string ListCommand::GetName() {
  69. return "list";
  70. }
  71. std::string ListCommand::getSimpleDescription() const {
  72. return "List HALs.";
  73. }
  74. std::string ListCommand::parseCmdline(pid_t pid) const {
  75. return android::procpartition::getCmdline(pid);
  76. }
  77. const std::string &ListCommand::getCmdline(pid_t pid) {
  78. static const std::string kEmptyString{};
  79. if (pid == NO_PID) return kEmptyString;
  80. auto pair = mCmdlines.find(pid);
  81. if (pair != mCmdlines.end()) {
  82. return pair->second;
  83. }
  84. mCmdlines[pid] = parseCmdline(pid);
  85. return mCmdlines[pid];
  86. }
  87. void ListCommand::removeDeadProcesses(Pids *pids) {
  88. static const pid_t myPid = getpid();
  89. pids->erase(std::remove_if(pids->begin(), pids->end(), [this](auto pid) {
  90. return pid == myPid || this->getCmdline(pid).empty();
  91. }), pids->end());
  92. }
  93. Partition ListCommand::getPartition(pid_t pid) {
  94. if (pid == NO_PID) return Partition::UNKNOWN;
  95. auto it = mPartitions.find(pid);
  96. if (it != mPartitions.end()) {
  97. return it->second;
  98. }
  99. Partition partition = android::procpartition::getPartition(pid);
  100. mPartitions.emplace(pid, partition);
  101. return partition;
  102. }
  103. // Give sensible defaults when nothing can be inferred from runtime.
  104. // process: Partition inferred from executable location or cmdline.
  105. Partition ListCommand::resolvePartition(Partition process, const FqInstance& fqInstance) const {
  106. if (fqInstance.inPackage("vendor") || fqInstance.inPackage("com")) {
  107. return Partition::VENDOR;
  108. }
  109. if (fqInstance.inPackage("android.frameworks") || fqInstance.inPackage("android.system") ||
  110. fqInstance.inPackage("android.hidl")) {
  111. return Partition::SYSTEM;
  112. }
  113. // Some android.hardware HALs are served from system. Check the value from executable
  114. // location / cmdline first.
  115. if (fqInstance.inPackage("android.hardware")) {
  116. if (process != Partition::UNKNOWN) {
  117. return process;
  118. }
  119. return Partition::VENDOR;
  120. }
  121. return process;
  122. }
  123. bool match(const vintf::ManifestInstance& instance, const FqInstance& fqInstance,
  124. vintf::TransportArch ta) {
  125. // For hwbinder libs, allow missing arch in manifest.
  126. // For passthrough libs, allow missing interface/instance in table.
  127. return (ta.transport == instance.transport()) &&
  128. (ta.transport == vintf::Transport::HWBINDER ||
  129. vintf::contains(instance.arch(), ta.arch)) &&
  130. (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
  131. (!fqInstance.hasInstance() || fqInstance.getInstance() == instance.instance());
  132. }
  133. bool match(const vintf::MatrixInstance& instance, const FqInstance& fqInstance,
  134. vintf::TransportArch /* ta */) {
  135. return (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
  136. (!fqInstance.hasInstance() || instance.matchInstance(fqInstance.getInstance()));
  137. }
  138. template <typename ObjectType>
  139. VintfInfo getVintfInfo(const std::shared_ptr<const ObjectType>& object,
  140. const FqInstance& fqInstance, vintf::TransportArch ta, VintfInfo value) {
  141. bool found = false;
  142. (void)object->forEachInstanceOfVersion(fqInstance.getPackage(), fqInstance.getVersion(),
  143. [&](const auto& instance) {
  144. found = match(instance, fqInstance, ta);
  145. return !found; // continue if not found
  146. });
  147. return found ? value : VINTF_INFO_EMPTY;
  148. }
  149. std::shared_ptr<const vintf::HalManifest> ListCommand::getDeviceManifest() const {
  150. return vintf::VintfObject::GetDeviceHalManifest();
  151. }
  152. std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getDeviceMatrix() const {
  153. return vintf::VintfObject::GetDeviceCompatibilityMatrix();
  154. }
  155. std::shared_ptr<const vintf::HalManifest> ListCommand::getFrameworkManifest() const {
  156. return vintf::VintfObject::GetFrameworkHalManifest();
  157. }
  158. std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getFrameworkMatrix() const {
  159. return vintf::VintfObject::GetFrameworkCompatibilityMatrix();
  160. }
  161. VintfInfo ListCommand::getVintfInfo(const std::string& fqInstanceName,
  162. vintf::TransportArch ta) const {
  163. FqInstance fqInstance;
  164. if (!fqInstance.setTo(fqInstanceName) &&
  165. // Ignore interface / instance for passthrough libs
  166. !fqInstance.setTo(getPackageAndVersion(fqInstanceName))) {
  167. err() << "Warning: Cannot parse '" << fqInstanceName << "'; no VINTF info." << std::endl;
  168. return VINTF_INFO_EMPTY;
  169. }
  170. return lshal::getVintfInfo(getDeviceManifest(), fqInstance, ta, DEVICE_MANIFEST) |
  171. lshal::getVintfInfo(getFrameworkManifest(), fqInstance, ta, FRAMEWORK_MANIFEST) |
  172. lshal::getVintfInfo(getDeviceMatrix(), fqInstance, ta, DEVICE_MATRIX) |
  173. lshal::getVintfInfo(getFrameworkMatrix(), fqInstance, ta, FRAMEWORK_MATRIX);
  174. }
  175. static bool scanBinderContext(pid_t pid,
  176. const std::string &contextName,
  177. std::function<void(const std::string&)> eachLine) {
  178. std::ifstream ifs("/d/binder/proc/" + std::to_string(pid));
  179. if (!ifs.is_open()) {
  180. return false;
  181. }
  182. static const std::regex kContextLine("^context (\\w+)$");
  183. bool isDesiredContext = false;
  184. std::string line;
  185. std::smatch match;
  186. while(getline(ifs, line)) {
  187. if (std::regex_search(line, match, kContextLine)) {
  188. isDesiredContext = match.str(1) == contextName;
  189. continue;
  190. }
  191. if (!isDesiredContext) {
  192. continue;
  193. }
  194. eachLine(line);
  195. }
  196. return true;
  197. }
  198. bool ListCommand::getPidInfo(
  199. pid_t serverPid, PidInfo *pidInfo) const {
  200. static const std::regex kReferencePrefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
  201. static const std::regex kThreadPrefix("^\\s*thread \\d+:\\s+l\\s+(\\d)(\\d)");
  202. std::smatch match;
  203. return scanBinderContext(serverPid, "hwbinder", [&](const std::string& line) {
  204. if (std::regex_search(line, match, kReferencePrefix)) {
  205. const std::string &ptrString = "0x" + match.str(2); // use number after c
  206. uint64_t ptr;
  207. if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
  208. // Should not reach here, but just be tolerant.
  209. err() << "Could not parse number " << ptrString << std::endl;
  210. return;
  211. }
  212. const std::string proc = " proc ";
  213. auto pos = line.rfind(proc);
  214. if (pos != std::string::npos) {
  215. for (const std::string &pidStr : split(line.substr(pos + proc.size()), ' ')) {
  216. int32_t pid;
  217. if (!::android::base::ParseInt(pidStr, &pid)) {
  218. err() << "Could not parse number " << pidStr << std::endl;
  219. return;
  220. }
  221. pidInfo->refPids[ptr].push_back(pid);
  222. }
  223. }
  224. return;
  225. }
  226. if (std::regex_search(line, match, kThreadPrefix)) {
  227. // "1" is waiting in binder driver
  228. // "2" is poll. It's impossible to tell if these are in use.
  229. // and HIDL default code doesn't use it.
  230. bool isInUse = match.str(1) != "1";
  231. // "0" is a thread that has called into binder
  232. // "1" is looper thread
  233. // "2" is main looper thread
  234. bool isHwbinderThread = match.str(2) != "0";
  235. if (!isHwbinderThread) {
  236. return;
  237. }
  238. if (isInUse) {
  239. pidInfo->threadUsage++;
  240. }
  241. pidInfo->threadCount++;
  242. return;
  243. }
  244. // not reference or thread line
  245. return;
  246. });
  247. }
  248. const PidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
  249. auto pair = mCachedPidInfos.insert({serverPid, PidInfo{}});
  250. if (pair.second /* did insertion take place? */) {
  251. if (!getPidInfo(serverPid, &pair.first->second)) {
  252. return nullptr;
  253. }
  254. }
  255. return &pair.first->second;
  256. }
  257. bool ListCommand::shouldFetchHalType(const HalType &type) const {
  258. return (std::find(mFetchTypes.begin(), mFetchTypes.end(), type) != mFetchTypes.end());
  259. }
  260. Table* ListCommand::tableForType(HalType type) {
  261. switch (type) {
  262. case HalType::BINDERIZED_SERVICES:
  263. return &mServicesTable;
  264. case HalType::PASSTHROUGH_CLIENTS:
  265. return &mPassthroughRefTable;
  266. case HalType::PASSTHROUGH_LIBRARIES:
  267. return &mImplementationsTable;
  268. case HalType::VINTF_MANIFEST:
  269. return &mManifestHalsTable;
  270. case HalType::LAZY_HALS:
  271. return &mLazyHalsTable;
  272. default:
  273. LOG(FATAL) << "Unknown HAL type " << static_cast<int64_t>(type);
  274. return nullptr;
  275. }
  276. }
  277. const Table* ListCommand::tableForType(HalType type) const {
  278. return const_cast<ListCommand*>(this)->tableForType(type);
  279. }
  280. void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
  281. for (const auto& type : mListTypes) {
  282. f(*tableForType(type));
  283. }
  284. }
  285. void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
  286. for (const auto& type : mListTypes) {
  287. f(*tableForType(type));
  288. }
  289. }
  290. void ListCommand::postprocess() {
  291. forEachTable([this](Table &table) {
  292. if (mSortColumn) {
  293. std::sort(table.begin(), table.end(), mSortColumn);
  294. }
  295. for (TableEntry &entry : table) {
  296. entry.serverCmdline = getCmdline(entry.serverPid);
  297. removeDeadProcesses(&entry.clientPids);
  298. for (auto pid : entry.clientPids) {
  299. entry.clientCmdlines.push_back(this->getCmdline(pid));
  300. }
  301. }
  302. for (TableEntry& entry : table) {
  303. if (entry.partition == Partition::UNKNOWN) {
  304. entry.partition = getPartition(entry.serverPid);
  305. }
  306. entry.vintfInfo = getVintfInfo(entry.interfaceName, {entry.transport, entry.arch});
  307. }
  308. });
  309. // use a double for loop here because lshal doesn't care about efficiency.
  310. for (TableEntry &packageEntry : mImplementationsTable) {
  311. std::string packageName = packageEntry.interfaceName;
  312. FQName fqPackageName;
  313. if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
  314. continue;
  315. }
  316. for (TableEntry &interfaceEntry : mPassthroughRefTable) {
  317. if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
  318. continue;
  319. }
  320. FQName interfaceName;
  321. if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
  322. continue;
  323. }
  324. if (interfaceName.getPackageAndVersion() == fqPackageName) {
  325. interfaceEntry.arch = packageEntry.arch;
  326. }
  327. }
  328. }
  329. mServicesTable.setDescription(
  330. "| All binderized services (registered with hwservicemanager)");
  331. mPassthroughRefTable.setDescription(
  332. "| All interfaces that getService() has ever returned as a passthrough interface;\n"
  333. "| PIDs / processes shown below might be inaccurate because the process\n"
  334. "| might have relinquished the interface or might have died.\n"
  335. "| The Server / Server CMD column can be ignored.\n"
  336. "| The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
  337. "| the library and successfully fetched the passthrough implementation.");
  338. mImplementationsTable.setDescription(
  339. "| All available passthrough implementations (all -impl.so files).\n"
  340. "| These may return subclasses through their respective HIDL_FETCH_I* functions.");
  341. mManifestHalsTable.setDescription(
  342. "| All HALs that are in VINTF manifest.");
  343. mLazyHalsTable.setDescription(
  344. "| All HALs that are declared in VINTF manifest:\n"
  345. "| - as hwbinder HALs but are not registered to hwservicemanager, and\n"
  346. "| - as hwbinder/passthrough HALs with no implementation.");
  347. }
  348. bool ListCommand::addEntryWithInstance(const TableEntry& entry,
  349. vintf::HalManifest* manifest) const {
  350. FqInstance fqInstance;
  351. if (!fqInstance.setTo(entry.interfaceName)) {
  352. err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
  353. return false;
  354. }
  355. if (fqInstance.getPackage() == gIBaseFqName.package()) {
  356. return true; // always remove IBase from manifest
  357. }
  358. Partition partition = resolvePartition(entry.partition, fqInstance);
  359. if (partition == Partition::UNKNOWN) {
  360. err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
  361. << std::endl;
  362. return false;
  363. }
  364. if (partition != mVintfPartition) {
  365. return true; // strip out instances that is in a different partition.
  366. }
  367. vintf::Arch arch;
  368. if (entry.transport == vintf::Transport::HWBINDER) {
  369. arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
  370. } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
  371. if (entry.arch == vintf::Arch::ARCH_EMPTY) {
  372. err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
  373. return false;
  374. }
  375. arch = entry.arch;
  376. } else {
  377. err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
  378. return false;
  379. }
  380. std::string e;
  381. if (!manifest->insertInstance(fqInstance, entry.transport, arch, vintf::HalFormat::HIDL, &e)) {
  382. err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
  383. return false;
  384. }
  385. return true;
  386. }
  387. bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
  388. const vintf::HalManifest* manifest) const {
  389. const auto& packageAndVersion = splitFirst(getPackageAndVersion(entry.interfaceName), '@');
  390. const auto& package = packageAndVersion.first;
  391. vintf::Version version;
  392. if (!vintf::parse(packageAndVersion.second, &version)) {
  393. err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
  394. << entry.interfaceName << "'" << std::endl;
  395. return false;
  396. }
  397. bool found = false;
  398. (void)manifest->forEachInstanceOfVersion(package, version, [&found](const auto&) {
  399. found = true;
  400. return false; // break
  401. });
  402. return found;
  403. }
  404. void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
  405. using vintf::operator|=;
  406. using vintf::operator<<;
  407. using namespace std::placeholders;
  408. vintf::HalManifest manifest;
  409. manifest.setType(toSchemaType(mVintfPartition));
  410. std::vector<std::string> error;
  411. for (const TableEntry& entry : mServicesTable)
  412. if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
  413. for (const TableEntry& entry : mPassthroughRefTable)
  414. if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
  415. for (const TableEntry& entry : mManifestHalsTable)
  416. if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
  417. std::vector<std::string> passthrough;
  418. for (const TableEntry& entry : mImplementationsTable)
  419. if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
  420. out << "<!-- " << std::endl
  421. << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
  422. << INIT_VINTF_NOTES;
  423. if (!error.empty()) {
  424. out << std::endl << " The following HALs are not added; see warnings." << std::endl;
  425. for (const auto& e : error) {
  426. out << " " << e << std::endl;
  427. }
  428. }
  429. if (!passthrough.empty()) {
  430. out << std::endl
  431. << " The following HALs are passthrough and no interface or instance " << std::endl
  432. << " names can be inferred." << std::endl;
  433. for (const auto& e : passthrough) {
  434. out << " " << e << std::endl;
  435. }
  436. }
  437. out << "-->" << std::endl;
  438. out << vintf::gHalManifestConverter(manifest, vintf::SerializeFlags::HALS_ONLY);
  439. }
  440. std::string ListCommand::INIT_VINTF_NOTES{
  441. " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
  442. " only hwbinder is shown.\n"
  443. " 2. It is likely that HALs in passthrough transport does not have\n"
  444. " <interface> declared; users will have to write them by hand.\n"
  445. " 3. A HAL with lower minor version can be overridden by a HAL with\n"
  446. " higher minor version if they have the same name and major version.\n"
  447. " 4. This output is intended for launch devices.\n"
  448. " Upgrading devices should not use this tool to generate device\n"
  449. " manifest and replace the existing manifest directly, but should\n"
  450. " edit the existing manifest manually.\n"
  451. " Specifically, devices which launched at Android O-MR1 or earlier\n"
  452. " should not use the 'fqname' format for required HAL entries and\n"
  453. " should instead use the legacy package, name, instance-name format\n"
  454. " until they are updated.\n"
  455. };
  456. static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
  457. switch (a) {
  458. case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
  459. return vintf::Arch::ARCH_64;
  460. case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
  461. return vintf::Arch::ARCH_32;
  462. case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
  463. default:
  464. return vintf::Arch::ARCH_EMPTY;
  465. }
  466. }
  467. void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
  468. if (mNeat) {
  469. std::vector<const Table*> tables;
  470. forEachTable([&tables](const Table &table) {
  471. tables.push_back(&table);
  472. });
  473. MergedTable(std::move(tables)).createTextTable().dump(out.buf());
  474. return;
  475. }
  476. forEachTable([this, &out](const Table &table) {
  477. // We're only interested in dumping debug info for already
  478. // instantiated services. There's little value in dumping the
  479. // debug info for a service we create on the fly, so we only operate
  480. // on the "mServicesTable".
  481. std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
  482. if (mEmitDebugInfo && &table == &mServicesTable) {
  483. emitDebugInfo = [this](const auto& iName) {
  484. std::stringstream ss;
  485. auto pair = splitFirst(iName, '/');
  486. mLshal.emitDebugInfo(pair.first, pair.second, {},
  487. false /* excludesParentInstances */, ss,
  488. NullableOStream<std::ostream>(nullptr));
  489. return ss.str();
  490. };
  491. }
  492. table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
  493. out << std::endl;
  494. });
  495. }
  496. Status ListCommand::dump() {
  497. auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
  498. if (mFileOutputPath.empty()) {
  499. (*this.*dump)(out());
  500. return OK;
  501. }
  502. std::ofstream fileOutput(mFileOutputPath);
  503. if (!fileOutput.is_open()) {
  504. err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
  505. return IO_ERROR;
  506. }
  507. chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
  508. (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
  509. fileOutput.flush();
  510. fileOutput.close();
  511. return OK;
  512. }
  513. void ListCommand::putEntry(HalType type, TableEntry &&entry) {
  514. tableForType(type)->add(std::forward<TableEntry>(entry));
  515. }
  516. Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
  517. if (!shouldFetchHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
  518. using namespace ::android::hardware;
  519. using namespace ::android::hidl::manager::V1_0;
  520. using namespace ::android::hidl::base::V1_0;
  521. using std::literals::chrono_literals::operator""s;
  522. auto ret = timeoutIPC(10s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
  523. std::map<std::string, TableEntry> entries;
  524. for (const auto &info : infos) {
  525. std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
  526. std::string{info.instanceName.c_str()};
  527. entries.emplace(interfaceName, TableEntry{
  528. .interfaceName = interfaceName,
  529. .transport = vintf::Transport::PASSTHROUGH,
  530. .clientPids = info.clientPids,
  531. }).first->second.arch |= fromBaseArchitecture(info.arch);
  532. }
  533. for (auto &&pair : entries) {
  534. putEntry(HalType::PASSTHROUGH_LIBRARIES, std::move(pair.second));
  535. }
  536. });
  537. if (!ret.isOk()) {
  538. err() << "Error: Failed to call list on getPassthroughServiceManager(): "
  539. << ret.description() << std::endl;
  540. return DUMP_ALL_LIBS_ERROR;
  541. }
  542. return OK;
  543. }
  544. Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
  545. if (!shouldFetchHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
  546. using namespace ::android::hardware;
  547. using namespace ::android::hardware::details;
  548. using namespace ::android::hidl::manager::V1_0;
  549. using namespace ::android::hidl::base::V1_0;
  550. auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
  551. for (const auto &info : infos) {
  552. if (info.clientPids.size() <= 0) {
  553. continue;
  554. }
  555. putEntry(HalType::PASSTHROUGH_CLIENTS, {
  556. .interfaceName =
  557. std::string{info.interfaceName.c_str()} + "/" +
  558. std::string{info.instanceName.c_str()},
  559. .transport = vintf::Transport::PASSTHROUGH,
  560. .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
  561. .clientPids = info.clientPids,
  562. .arch = fromBaseArchitecture(info.arch)
  563. });
  564. }
  565. });
  566. if (!ret.isOk()) {
  567. err() << "Error: Failed to call debugDump on defaultServiceManager(): "
  568. << ret.description() << std::endl;
  569. return DUMP_PASSTHROUGH_ERROR;
  570. }
  571. return OK;
  572. }
  573. Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
  574. using vintf::operator<<;
  575. if (!shouldFetchHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
  576. const vintf::Transport mode = vintf::Transport::HWBINDER;
  577. hidl_vec<hidl_string> fqInstanceNames;
  578. // copying out for timeoutIPC
  579. auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
  580. fqInstanceNames = names;
  581. });
  582. if (!listRet.isOk()) {
  583. err() << "Error: Failed to list services for " << mode << ": "
  584. << listRet.description() << std::endl;
  585. return DUMP_BINDERIZED_ERROR;
  586. }
  587. Status status = OK;
  588. std::map<std::string, TableEntry> allTableEntries;
  589. for (const auto &fqInstanceName : fqInstanceNames) {
  590. // create entry and default assign all fields.
  591. TableEntry& entry = allTableEntries[fqInstanceName];
  592. entry.interfaceName = fqInstanceName;
  593. entry.transport = mode;
  594. entry.serviceStatus = ServiceStatus::NON_RESPONSIVE;
  595. status |= fetchBinderizedEntry(manager, &entry);
  596. }
  597. for (auto& pair : allTableEntries) {
  598. putEntry(HalType::BINDERIZED_SERVICES, std::move(pair.second));
  599. }
  600. return status;
  601. }
  602. Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
  603. TableEntry *entry) {
  604. Status status = OK;
  605. const auto handleError = [&](Status additionalError, const std::string& msg) {
  606. err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
  607. status |= DUMP_BINDERIZED_ERROR | additionalError;
  608. };
  609. const auto pair = splitFirst(entry->interfaceName, '/');
  610. const auto &serviceName = pair.first;
  611. const auto &instanceName = pair.second;
  612. auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
  613. if (!getRet.isOk()) {
  614. handleError(TRANSACTION_ERROR,
  615. "cannot be fetched from service manager:" + getRet.description());
  616. return status;
  617. }
  618. sp<IBase> service = getRet;
  619. if (service == nullptr) {
  620. handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
  621. return status;
  622. }
  623. // getDebugInfo
  624. do {
  625. DebugInfo debugInfo;
  626. auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
  627. debugInfo = received;
  628. });
  629. if (!debugRet.isOk()) {
  630. handleError(TRANSACTION_ERROR,
  631. "debugging information cannot be retrieved: " + debugRet.description());
  632. break; // skip getPidInfo
  633. }
  634. entry->serverPid = debugInfo.pid;
  635. entry->serverObjectAddress = debugInfo.ptr;
  636. entry->arch = fromBaseArchitecture(debugInfo.arch);
  637. if (debugInfo.pid != NO_PID) {
  638. const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
  639. if (pidInfo == nullptr) {
  640. handleError(IO_ERROR,
  641. "no information for PID " + std::to_string(debugInfo.pid) +
  642. ", are you root?");
  643. break;
  644. }
  645. if (debugInfo.ptr != NO_PTR) {
  646. auto it = pidInfo->refPids.find(debugInfo.ptr);
  647. if (it != pidInfo->refPids.end()) {
  648. entry->clientPids = it->second;
  649. }
  650. }
  651. entry->threadUsage = pidInfo->threadUsage;
  652. entry->threadCount = pidInfo->threadCount;
  653. }
  654. } while (0);
  655. // hash
  656. do {
  657. ssize_t hashIndex = -1;
  658. auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
  659. for (size_t i = 0; i < c.size(); ++i) {
  660. if (serviceName == c[i]) {
  661. hashIndex = static_cast<ssize_t>(i);
  662. break;
  663. }
  664. }
  665. });
  666. if (!ifaceChainRet.isOk()) {
  667. handleError(TRANSACTION_ERROR,
  668. "interfaceChain fails: " + ifaceChainRet.description());
  669. break; // skip getHashChain
  670. }
  671. if (hashIndex < 0) {
  672. handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
  673. break; // skip getHashChain
  674. }
  675. auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
  676. if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
  677. handleError(BAD_IMPL,
  678. "interfaceChain indicates position " + std::to_string(hashIndex) +
  679. " but getHashChain returns " + std::to_string(hashChain.size()) +
  680. " hashes");
  681. return;
  682. }
  683. auto&& hashArray = hashChain[hashIndex];
  684. std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
  685. entry->hash = Hash::hexString(hashVec);
  686. });
  687. if (!hashRet.isOk()) {
  688. handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
  689. }
  690. } while (0);
  691. if (status == OK) {
  692. entry->serviceStatus = ServiceStatus::ALIVE;
  693. }
  694. return status;
  695. }
  696. Status ListCommand::fetchManifestHals() {
  697. if (!shouldFetchHalType(HalType::VINTF_MANIFEST)) { return OK; }
  698. Status status = OK;
  699. for (auto manifest : {getDeviceManifest(), getFrameworkManifest()}) {
  700. if (manifest == nullptr) {
  701. status |= VINTF_ERROR;
  702. continue;
  703. }
  704. std::map<std::string, TableEntry> entries;
  705. manifest->forEachInstance([&] (const vintf::ManifestInstance& manifestInstance) {
  706. TableEntry entry{
  707. .interfaceName = manifestInstance.getFqInstance().string(),
  708. .transport = manifestInstance.transport(),
  709. .arch = manifestInstance.arch(),
  710. // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
  711. .partition = toPartition(manifest->type()),
  712. .serviceStatus = ServiceStatus::DECLARED};
  713. std::string key = entry.interfaceName;
  714. entries.emplace(std::move(key), std::move(entry));
  715. return true;
  716. });
  717. for (auto&& pair : entries)
  718. mManifestHalsTable.add(std::move(pair.second));
  719. }
  720. return status;
  721. }
  722. Status ListCommand::fetchLazyHals() {
  723. using vintf::operator<<;
  724. if (!shouldFetchHalType(HalType::LAZY_HALS)) { return OK; }
  725. Status status = OK;
  726. for (const TableEntry& manifestEntry : mManifestHalsTable) {
  727. if (manifestEntry.transport == vintf::Transport::HWBINDER) {
  728. if (!hasHwbinderEntry(manifestEntry)) {
  729. mLazyHalsTable.add(TableEntry(manifestEntry));
  730. }
  731. continue;
  732. }
  733. if (manifestEntry.transport == vintf::Transport::PASSTHROUGH) {
  734. if (!hasPassthroughEntry(manifestEntry)) {
  735. mLazyHalsTable.add(TableEntry(manifestEntry));
  736. }
  737. continue;
  738. }
  739. err() << "Warning: unrecognized transport in VINTF manifest: "
  740. << manifestEntry.transport;
  741. status |= VINTF_ERROR;
  742. }
  743. return status;
  744. }
  745. bool ListCommand::hasHwbinderEntry(const TableEntry& entry) const {
  746. for (const TableEntry& existing : mServicesTable) {
  747. if (existing.interfaceName == entry.interfaceName) {
  748. return true;
  749. }
  750. }
  751. return false;
  752. }
  753. bool ListCommand::hasPassthroughEntry(const TableEntry& entry) const {
  754. FqInstance entryFqInstance;
  755. if (!entryFqInstance.setTo(entry.interfaceName)) {
  756. return false; // cannot parse, so add it anyway.
  757. }
  758. for (const TableEntry& existing : mImplementationsTable) {
  759. FqInstance existingFqInstance;
  760. if (!existingFqInstance.setTo(getPackageAndVersion(existing.interfaceName))) {
  761. continue;
  762. }
  763. // For example, manifest may say [email protected] but passthroughServiceManager
  764. // can only list [email protected].
  765. if (entryFqInstance.getPackage() == existingFqInstance.getPackage() &&
  766. vintf::Version{entryFqInstance.getVersion()}
  767. .minorAtLeast(vintf::Version{existingFqInstance.getVersion()})) {
  768. return true;
  769. }
  770. }
  771. return false;
  772. }
  773. Status ListCommand::fetch() {
  774. Status status = OK;
  775. auto bManager = mLshal.serviceManager();
  776. if (bManager == nullptr) {
  777. err() << "Failed to get defaultServiceManager()!" << std::endl;
  778. status |= NO_BINDERIZED_MANAGER;
  779. } else {
  780. status |= fetchBinderized(bManager);
  781. // Passthrough PIDs are registered to the binderized manager as well.
  782. status |= fetchPassthrough(bManager);
  783. }
  784. auto pManager = mLshal.passthroughManager();
  785. if (pManager == nullptr) {
  786. err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
  787. status |= NO_PASSTHROUGH_MANAGER;
  788. } else {
  789. status |= fetchAllLibraries(pManager);
  790. }
  791. status |= fetchManifestHals();
  792. status |= fetchLazyHals();
  793. return status;
  794. }
  795. void ListCommand::initFetchTypes() {
  796. // TODO: refactor to do polymorphism on each table (so that dependency graph is not hardcoded).
  797. static const std::map<HalType, std::set<HalType>> kDependencyGraph{
  798. {HalType::LAZY_HALS, {HalType::BINDERIZED_SERVICES,
  799. HalType::PASSTHROUGH_LIBRARIES,
  800. HalType::VINTF_MANIFEST}},
  801. };
  802. mFetchTypes.insert(mListTypes.begin(), mListTypes.end());
  803. for (HalType listType : mListTypes) {
  804. auto it = kDependencyGraph.find(listType);
  805. if (it != kDependencyGraph.end()) {
  806. mFetchTypes.insert(it->second.begin(), it->second.end());
  807. }
  808. }
  809. }
  810. void ListCommand::registerAllOptions() {
  811. int v = mOptions.size();
  812. // A list of acceptable command line options
  813. // key: value returned by getopt_long
  814. // long options with short alternatives
  815. mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
  816. return USAGE;
  817. }, ""});
  818. mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
  819. thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
  820. return OK;
  821. }, "print the instance name column"});
  822. mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
  823. thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
  824. return OK;
  825. }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
  826. mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
  827. thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
  828. return OK;
  829. }, "print the transport mode column"});
  830. mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
  831. thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
  832. return OK;
  833. }, "print the bitness column"});
  834. mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
  835. thiz->mSelectedColumns.push_back(TableColumnType::HASH);
  836. return OK;
  837. }, "print hash of the interface"});
  838. mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
  839. thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
  840. return OK;
  841. }, "print the server PID, or server cmdline if -m is set"});
  842. mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
  843. thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
  844. return OK;
  845. }, "print the server object address column"});
  846. mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
  847. thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
  848. return OK;
  849. }, "print the client PIDs, or client cmdlines if -m is set"});
  850. mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
  851. thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
  852. return OK;
  853. }, "print currently used/available threads\n(note, available threads created lazily)"});
  854. mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
  855. thiz->mEnableCmdlines = true;
  856. return OK;
  857. }, "print cmdline instead of PIDs"});
  858. mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
  859. thiz->mEmitDebugInfo = true;
  860. if (arg) thiz->mFileOutputPath = arg;
  861. return OK;
  862. }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
  863. "Writes to specified file if 'arg' is provided, otherwise stdout."});
  864. mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
  865. thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
  866. return OK;
  867. }, "print VINTF info. This column contains a comma-separated list of:\n"
  868. " - DM: if the HAL is in the device manifest\n"
  869. " - DC: if the HAL is in the device compatibility matrix\n"
  870. " - FM: if the HAL is in the framework manifest\n"
  871. " - FC: if the HAL is in the framework compatibility matrix"});
  872. mOptions.push_back({'S', "service-status", no_argument, v++, [](ListCommand* thiz, const char*) {
  873. thiz->mSelectedColumns.push_back(TableColumnType::SERVICE_STATUS);
  874. return OK;
  875. }, "print service status column. Possible values are:\n"
  876. " - alive: alive and running hwbinder service;\n"
  877. " - registered;dead: registered to hwservicemanager but is not responsive;\n"
  878. " - declared: only declared in VINTF manifest but is not registered to hwservicemanager;\n"
  879. " - N/A: no information for passthrough HALs."});
  880. // long options without short alternatives
  881. mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
  882. thiz->mVintf = true;
  883. if (thiz->mVintfPartition == Partition::UNKNOWN)
  884. thiz->mVintfPartition = Partition::VENDOR;
  885. if (arg) thiz->mFileOutputPath = arg;
  886. return OK;
  887. }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
  888. mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
  889. if (!arg) return USAGE;
  890. thiz->mVintfPartition = android::procpartition::parsePartition(arg);
  891. if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
  892. return OK;
  893. }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
  894. "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
  895. mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
  896. if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
  897. thiz->mSortColumn = TableEntry::sortByInterfaceName;
  898. } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
  899. thiz->mSortColumn = TableEntry::sortByServerPid;
  900. } else {
  901. thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
  902. return USAGE;
  903. }
  904. return OK;
  905. }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
  906. mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
  907. thiz->mNeat = true;
  908. return OK;
  909. }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
  910. mOptions.push_back({'\0', "types", required_argument, v++, [](ListCommand* thiz, const char* arg) {
  911. if (!arg) { return USAGE; }
  912. static const std::map<std::string, HalType> kHalTypeMap {
  913. {"binderized", HalType::BINDERIZED_SERVICES},
  914. {"b", HalType::BINDERIZED_SERVICES},
  915. {"passthrough_clients", HalType::PASSTHROUGH_CLIENTS},
  916. {"c", HalType::PASSTHROUGH_CLIENTS},
  917. {"passthrough_libs", HalType::PASSTHROUGH_LIBRARIES},
  918. {"l", HalType::PASSTHROUGH_LIBRARIES},
  919. {"vintf", HalType::VINTF_MANIFEST},
  920. {"v", HalType::VINTF_MANIFEST},
  921. {"lazy", HalType::LAZY_HALS},
  922. {"z", HalType::LAZY_HALS},
  923. };
  924. std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
  925. for (const auto& halTypeArg : halTypesArgs) {
  926. if (halTypeArg.empty()) continue;
  927. const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
  928. if (halTypeIter == kHalTypeMap.end()) {
  929. thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
  930. return USAGE;
  931. }
  932. // Append unique (non-repeated) HAL types to the reporting list
  933. HalType halType = halTypeIter->second;
  934. if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
  935. thiz->mListTypes.end()) {
  936. thiz->mListTypes.push_back(halType);
  937. }
  938. }
  939. if (thiz->mListTypes.empty()) { return USAGE; }
  940. return OK;
  941. }, "comma-separated list of one or more sections.\nThe output is restricted to the selected "
  942. "section(s). Valid options\nare: (b|binderized), (c|passthrough_clients), (l|"
  943. "passthrough_libs), (v|vintf), and (z|lazy).\nDefault is `bcl`."});
  944. }
  945. // Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
  946. // the lifetime of "options" during the usage of the returned array.
  947. static std::unique_ptr<struct option[]> getLongOptions(
  948. const ListCommand::RegisteredOptions& options,
  949. int* longOptFlag) {
  950. std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
  951. int i = 0;
  952. for (const auto& e : options) {
  953. ret[i].name = e.longOption.c_str();
  954. ret[i].has_arg = e.hasArg;
  955. ret[i].flag = longOptFlag;
  956. ret[i].val = e.val;
  957. i++;
  958. }
  959. // getopt_long last option has all zeros
  960. ret[i].name = nullptr;
  961. ret[i].has_arg = 0;
  962. ret[i].flag = nullptr;
  963. ret[i].val = 0;
  964. return ret;
  965. }
  966. // Create 'optstring' argument to getopt_long.
  967. static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
  968. std::stringstream ss;
  969. for (const auto& e : options) {
  970. if (e.shortOption != '\0') {
  971. ss << e.shortOption;
  972. }
  973. }
  974. return ss.str();
  975. }
  976. Status ListCommand::parseArgs(const Arg &arg) {
  977. mListTypes.clear();
  978. if (mOptions.empty()) {
  979. registerAllOptions();
  980. }
  981. int longOptFlag;
  982. std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
  983. std::string shortOptions = getShortOptions(mOptions);
  984. // suppress output to std::err for unknown options
  985. opterr = 0;
  986. int optionIndex;
  987. int c;
  988. // Lshal::parseArgs has set optind to the next option to parse
  989. for (;;) {
  990. c = getopt_long(arg.argc, arg.argv,
  991. shortOptions.c_str(), longOptions.get(), &optionIndex);
  992. if (c == -1) {
  993. break;
  994. }
  995. const RegisteredOption* found = nullptr;
  996. if (c == 0) {
  997. // see long option
  998. for (const auto& e : mOptions) {
  999. if (longOptFlag == e.val) found = &e;
  1000. }
  1001. } else {
  1002. // see short option
  1003. for (const auto& e : mOptions) {
  1004. if (c == e.shortOption) found = &e;
  1005. }
  1006. }
  1007. if (found == nullptr) {
  1008. // see unrecognized options
  1009. err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
  1010. return USAGE;
  1011. }
  1012. Status status = found->op(this, optarg);
  1013. if (status != OK) {
  1014. return status;
  1015. }
  1016. }
  1017. if (optind < arg.argc) {
  1018. // see non option
  1019. err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
  1020. return USAGE;
  1021. }
  1022. if (mNeat && mEmitDebugInfo) {
  1023. err() << "Error: --neat should not be used with --debug." << std::endl;
  1024. return USAGE;
  1025. }
  1026. if (mSelectedColumns.empty()) {
  1027. mSelectedColumns = {TableColumnType::VINTF, TableColumnType::RELEASED,
  1028. TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
  1029. TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
  1030. }
  1031. if (mEnableCmdlines) {
  1032. for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
  1033. if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
  1034. mSelectedColumns[i] = TableColumnType::SERVER_CMD;
  1035. }
  1036. if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
  1037. mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
  1038. }
  1039. }
  1040. }
  1041. // By default, list all HAL types
  1042. if (mListTypes.empty()) {
  1043. mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
  1044. HalType::PASSTHROUGH_LIBRARIES};
  1045. }
  1046. initFetchTypes();
  1047. forEachTable([this] (Table& table) {
  1048. table.setSelectedColumns(this->mSelectedColumns);
  1049. });
  1050. return OK;
  1051. }
  1052. Status ListCommand::main(const Arg &arg) {
  1053. Status status = parseArgs(arg);
  1054. if (status != OK) {
  1055. return status;
  1056. }
  1057. status = fetch();
  1058. postprocess();
  1059. status |= dump();
  1060. return status;
  1061. }
  1062. const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
  1063. static const std::string empty{};
  1064. static const std::string optional{"[=<arg>]"};
  1065. static const std::string required{"=<arg>"};
  1066. if (hasArg == optional_argument) {
  1067. return optional;
  1068. }
  1069. if (hasArg == required_argument) {
  1070. return required;
  1071. }
  1072. return empty;
  1073. }
  1074. void ListCommand::usage() const {
  1075. err() << "list:" << std::endl
  1076. << " lshal" << std::endl
  1077. << " lshal list" << std::endl
  1078. << " List all hals with default ordering and columns (`lshal list -Vliepc`)" << std::endl
  1079. << " lshal list [-h|--help]" << std::endl
  1080. << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
  1081. << " lshal [list] [OPTIONS...]" << std::endl;
  1082. for (const auto& e : mOptions) {
  1083. if (e.help.empty()) {
  1084. continue;
  1085. }
  1086. err() << " ";
  1087. if (e.shortOption != '\0')
  1088. err() << "-" << e.shortOption << e.getHelpMessageForArgument();
  1089. if (e.shortOption != '\0' && !e.longOption.empty())
  1090. err() << ", ";
  1091. if (!e.longOption.empty())
  1092. err() << "--" << e.longOption << e.getHelpMessageForArgument();
  1093. err() << ": ";
  1094. std::vector<std::string> lines = split(e.help, '\n');
  1095. for (const auto& line : lines) {
  1096. if (&line != &lines.front())
  1097. err() << " ";
  1098. err() << line << std::endl;
  1099. }
  1100. }
  1101. }
  1102. } // namespace lshal
  1103. } // namespace android