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