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