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