blob: 5dbac1b9a3c46575f6d12beab97539e8a25af153 [file] [log] [blame]
Yifan Hong443df792017-05-09 18:49:45 -07001/*
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
Nirav Atrecce988d2018-05-16 11:14:46 -070021#include <algorithm>
Yifan Hong443df792017-05-09 18:49:45 -070022#include <fstream>
Yifan Hongb2d096a2018-05-01 15:25:23 -070023#include <functional>
Yifan Hong443df792017-05-09 18:49:45 -070024#include <iomanip>
25#include <iostream>
26#include <map>
Yifan Hong443df792017-05-09 18:49:45 -070027#include <regex>
Yifan Hongb2d096a2018-05-01 15:25:23 -070028#include <sstream>
Yifan Hong443df792017-05-09 18:49:45 -070029
Yifan Hongf31aa052018-02-02 15:17:51 -080030#include <android-base/file.h>
Nirav Atrecce988d2018-05-16 11:14:46 -070031#include <android-base/logging.h>
Yifan Hong443df792017-05-09 18:49:45 -070032#include <android-base/parseint.h>
33#include <android/hidl/manager/1.0/IServiceManager.h>
Yifan Hongfee209d2017-09-14 18:23:38 -070034#include <hidl-hash/Hash.h>
Yifan Hong443df792017-05-09 18:49:45 -070035#include <hidl-util/FQName.h>
36#include <private/android_filesystem_config.h>
37#include <sys/stat.h>
38#include <vintf/HalManifest.h>
Yifan Hongf31aa052018-02-02 15:17:51 -080039#include <vintf/parse_string.h>
Yifan Hong443df792017-05-09 18:49:45 -070040#include <vintf/parse_xml.h>
41
42#include "Lshal.h"
43#include "PipeRelay.h"
44#include "Timeout.h"
45#include "utils.h"
46
47using ::android::hardware::hidl_string;
Yifan Hong22ea7b82017-09-14 18:07:43 -070048using ::android::hardware::hidl_vec;
49using ::android::hidl::base::V1_0::DebugInfo;
50using ::android::hidl::base::V1_0::IBase;
Yifan Hong443df792017-05-09 18:49:45 -070051using ::android::hidl::manager::V1_0::IServiceManager;
52
53namespace android {
54namespace lshal {
55
Yifan Hongf31aa052018-02-02 15:17:51 -080056vintf::SchemaType toSchemaType(Partition p) {
57 return (p == Partition::SYSTEM) ? vintf::SchemaType::FRAMEWORK : vintf::SchemaType::DEVICE;
58}
59
Yifan Hong76ac14a2017-09-08 14:59:04 -070060NullableOStream<std::ostream> ListCommand::out() const {
61 return mLshal.out();
62}
63
64NullableOStream<std::ostream> ListCommand::err() const {
65 return mLshal.err();
Yifan Hong443df792017-05-09 18:49:45 -070066}
67
Yifan Hong795b6ec2017-09-13 11:25:28 -070068std::string ListCommand::GetName() {
69 return "list";
70}
71std::string ListCommand::getSimpleDescription() const {
72 return "List HALs.";
73}
74
Yifan Hong8bf73162017-09-07 18:06:13 -070075std::string ListCommand::parseCmdline(pid_t pid) const {
Yifan Hongf31aa052018-02-02 15:17:51 -080076 return android::procpartition::getCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -070077}
78
79const std::string &ListCommand::getCmdline(pid_t pid) {
80 auto pair = mCmdlines.find(pid);
81 if (pair != mCmdlines.end()) {
82 return pair->second;
83 }
Yifan Hong8bf73162017-09-07 18:06:13 -070084 mCmdlines[pid] = parseCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -070085 return mCmdlines[pid];
86}
87
88void ListCommand::removeDeadProcesses(Pids *pids) {
89 static const pid_t myPid = getpid();
Yifan Hong61fb7bc2017-05-12 16:33:57 -070090 pids->erase(std::remove_if(pids->begin(), pids->end(), [this](auto pid) {
Yifan Hong443df792017-05-09 18:49:45 -070091 return pid == myPid || this->getCmdline(pid).empty();
Yifan Hong61fb7bc2017-05-12 16:33:57 -070092 }), pids->end());
Yifan Hong443df792017-05-09 18:49:45 -070093}
94
Yifan Hongf31aa052018-02-02 15:17:51 -080095Partition ListCommand::getPartition(pid_t pid) {
96 auto it = mPartitions.find(pid);
97 if (it != mPartitions.end()) {
98 return it->second;
99 }
100 Partition partition = android::procpartition::getPartition(pid);
101 mPartitions.emplace(pid, partition);
102 return partition;
103}
104
105// Give sensible defaults when nothing can be inferred from runtime.
106// process: Partition inferred from executable location or cmdline.
Yifan Hongb2d096a2018-05-01 15:25:23 -0700107Partition ListCommand::resolvePartition(Partition process, const FqInstance& fqInstance) const {
108 if (fqInstance.inPackage("vendor") || fqInstance.inPackage("com")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800109 return Partition::VENDOR;
110 }
111
Yifan Hongb2d096a2018-05-01 15:25:23 -0700112 if (fqInstance.inPackage("android.frameworks") || fqInstance.inPackage("android.system") ||
113 fqInstance.inPackage("android.hidl")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800114 return Partition::SYSTEM;
115 }
116
117 // Some android.hardware HALs are served from system. Check the value from executable
118 // location / cmdline first.
Yifan Hongb2d096a2018-05-01 15:25:23 -0700119 if (fqInstance.inPackage("android.hardware")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800120 if (process != Partition::UNKNOWN) {
121 return process;
122 }
123 return Partition::VENDOR;
124 }
125
126 return process;
127}
128
Yifan Hong1243dde2017-09-14 17:49:30 -0700129static bool scanBinderContext(pid_t pid,
Steven Morelandd8e20192017-05-24 11:23:08 -0700130 const std::string &contextName,
131 std::function<void(const std::string&)> eachLine) {
132 std::ifstream ifs("/d/binder/proc/" + std::to_string(pid));
Yifan Hong443df792017-05-09 18:49:45 -0700133 if (!ifs.is_open()) {
134 return false;
135 }
136
Steven Morelandd8e20192017-05-24 11:23:08 -0700137 static const std::regex kContextLine("^context (\\w+)$");
Yifan Hong443df792017-05-09 18:49:45 -0700138
Steven Morelandd8e20192017-05-24 11:23:08 -0700139 bool isDesiredContext = false;
Yifan Hong443df792017-05-09 18:49:45 -0700140 std::string line;
141 std::smatch match;
142 while(getline(ifs, line)) {
Steven Morelandd8e20192017-05-24 11:23:08 -0700143 if (std::regex_search(line, match, kContextLine)) {
144 isDesiredContext = match.str(1) == contextName;
Yifan Hong443df792017-05-09 18:49:45 -0700145 continue;
146 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700147
148 if (!isDesiredContext) {
Yifan Hong443df792017-05-09 18:49:45 -0700149 continue;
150 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700151
152 eachLine(line);
Yifan Hong443df792017-05-09 18:49:45 -0700153 }
154 return true;
155}
156
Steven Morelandd8e20192017-05-24 11:23:08 -0700157bool ListCommand::getPidInfo(
158 pid_t serverPid, PidInfo *pidInfo) const {
159 static const std::regex kReferencePrefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
160 static const std::regex kThreadPrefix("^\\s*thread \\d+:\\s+l\\s+(\\d)(\\d)");
161
162 std::smatch match;
163 return scanBinderContext(serverPid, "hwbinder", [&](const std::string& line) {
164 if (std::regex_search(line, match, kReferencePrefix)) {
165 const std::string &ptrString = "0x" + match.str(2); // use number after c
166 uint64_t ptr;
167 if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
168 // Should not reach here, but just be tolerant.
Yifan Hong76ac14a2017-09-08 14:59:04 -0700169 err() << "Could not parse number " << ptrString << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700170 return;
171 }
172 const std::string proc = " proc ";
173 auto pos = line.rfind(proc);
174 if (pos != std::string::npos) {
175 for (const std::string &pidStr : split(line.substr(pos + proc.size()), ' ')) {
176 int32_t pid;
177 if (!::android::base::ParseInt(pidStr, &pid)) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700178 err() << "Could not parse number " << pidStr << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700179 return;
180 }
181 pidInfo->refPids[ptr].push_back(pid);
182 }
183 }
184
185 return;
186 }
187
188 if (std::regex_search(line, match, kThreadPrefix)) {
189 // "1" is waiting in binder driver
190 // "2" is poll. It's impossible to tell if these are in use.
191 // and HIDL default code doesn't use it.
192 bool isInUse = match.str(1) != "1";
193 // "0" is a thread that has called into binder
194 // "1" is looper thread
195 // "2" is main looper thread
196 bool isHwbinderThread = match.str(2) != "0";
197
198 if (!isHwbinderThread) {
199 return;
200 }
201
202 if (isInUse) {
203 pidInfo->threadUsage++;
204 }
205
206 pidInfo->threadCount++;
207 return;
208 }
209
210 // not reference or thread line
211 return;
212 });
213}
214
Yifan Hong1243dde2017-09-14 17:49:30 -0700215const PidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
216 auto pair = mCachedPidInfos.insert({serverPid, PidInfo{}});
217 if (pair.second /* did insertion take place? */) {
218 if (!getPidInfo(serverPid, &pair.first->second)) {
219 return nullptr;
220 }
221 }
222 return &pair.first->second;
223}
224
Nirav Atrecce988d2018-05-16 11:14:46 -0700225bool ListCommand::shouldReportHalType(const HalType &type) const {
226 return (std::find(mListTypes.begin(), mListTypes.end(), type) != mListTypes.end());
227}
228
Yifan Hong443df792017-05-09 18:49:45 -0700229void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700230 for (const auto& type : mListTypes) {
231 switch (type) {
232 case HalType::BINDERIZED_SERVICES:
233 f(mServicesTable); break;
234 case HalType::PASSTHROUGH_CLIENTS:
235 f(mPassthroughRefTable); break;
236 case HalType::PASSTHROUGH_LIBRARIES:
237 f(mImplementationsTable); break;
238 default:
239 LOG(FATAL) << __func__ << "Unknown HAL type.";
240 }
241 }
Yifan Hong443df792017-05-09 18:49:45 -0700242}
243void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
Nirav Atrecce988d2018-05-16 11:14:46 -0700244 for (const auto& type : mListTypes) {
245 switch (type) {
246 case HalType::BINDERIZED_SERVICES:
247 f(mServicesTable); break;
248 case HalType::PASSTHROUGH_CLIENTS:
249 f(mPassthroughRefTable); break;
250 case HalType::PASSTHROUGH_LIBRARIES:
251 f(mImplementationsTable); break;
252 default:
253 LOG(FATAL) << __func__ << "Unknown HAL type.";
254 }
255 }
Yifan Hong443df792017-05-09 18:49:45 -0700256}
257
258void 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 }
Yifan Hongf31aa052018-02-02 15:17:51 -0800270 for (TableEntry& entry : table) {
271 entry.partition = getPartition(entry.serverPid);
272 }
Yifan Hong443df792017-05-09 18:49:45 -0700273 });
274 // use a double for loop here because lshal doesn't care about efficiency.
275 for (TableEntry &packageEntry : mImplementationsTable) {
276 std::string packageName = packageEntry.interfaceName;
Steven Morelandd4f32b32018-03-06 14:47:58 -0800277 FQName fqPackageName;
278 if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700279 continue;
280 }
281 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700282 if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
Yifan Hong443df792017-05-09 18:49:45 -0700283 continue;
284 }
Steven Morelandd4f32b32018-03-06 14:47:58 -0800285 FQName interfaceName;
286 if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700287 continue;
288 }
289 if (interfaceName.getPackageAndVersion() == fqPackageName) {
290 interfaceEntry.arch = packageEntry.arch;
291 }
292 }
293 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700294
295 mServicesTable.setDescription(
296 "All binderized services (registered services through hwservicemanager)");
297 mPassthroughRefTable.setDescription(
298 "All interfaces that getService() has ever return as a passthrough interface;\n"
299 "PIDs / processes shown below might be inaccurate because the process\n"
300 "might have relinquished the interface or might have died.\n"
301 "The Server / Server CMD column can be ignored.\n"
302 "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
303 "the library and successfully fetched the passthrough implementation.");
304 mImplementationsTable.setDescription(
Steven Moreland3d2c1e12018-03-14 10:41:13 -0700305 "All available passthrough implementations (all -impl.so files).\n"
306 "These may return subclasses through their respective HIDL_FETCH_I* functions.");
Yifan Hong443df792017-05-09 18:49:45 -0700307}
308
Yifan Hongb2d096a2018-05-01 15:25:23 -0700309bool ListCommand::addEntryWithInstance(const TableEntry& entry,
310 vintf::HalManifest* manifest) const {
311 FqInstance fqInstance;
312 if (!fqInstance.setTo(entry.interfaceName)) {
313 err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
314 return false;
Yifan Hong77c87822017-06-19 15:47:39 -0700315 }
Yifan Hongb2d096a2018-05-01 15:25:23 -0700316
317 if (fqInstance.getPackage() == gIBaseFqName.package()) {
318 return true; // always remove IBase from manifest
319 }
320
321 Partition partition = resolvePartition(entry.partition, fqInstance);
322
323 if (partition == Partition::UNKNOWN) {
324 err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
325 << std::endl;
326 return false;
327 }
328
329 if (partition != mVintfPartition) {
330 return true; // strip out instances that is in a different partition.
331 }
332
Yifan Hongb2d096a2018-05-01 15:25:23 -0700333 vintf::Arch arch;
Yifan Hong8304e412018-05-25 15:05:36 -0700334 if (entry.transport == vintf::Transport::HWBINDER) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700335 arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
Yifan Hong8304e412018-05-25 15:05:36 -0700336 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700337 if (entry.arch == vintf::Arch::ARCH_EMPTY) {
338 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
339 return false;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700340 }
Yifan Hong0ad64f52018-05-25 15:29:17 -0700341 arch = entry.arch;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700342 } else {
343 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
344 return false;
345 }
346
347 std::string e;
Yifan Hong8304e412018-05-25 15:05:36 -0700348 if (!manifest->insertInstance(fqInstance, entry.transport, arch, vintf::HalFormat::HIDL, &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700349 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
350 return false;
351 }
352 return true;
353}
354
355bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
356 const vintf::HalManifest* manifest) const {
357 const auto& packageAndVersion = splitFirst(splitFirst(entry.interfaceName, ':').first, '@');
358 const auto& package = packageAndVersion.first;
359 vintf::Version version;
360 if (!vintf::parse(packageAndVersion.second, &version)) {
361 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
362 << entry.interfaceName << "'" << std::endl;
363 return false;
364 }
365
366 bool found = false;
367 (void)manifest->forEachInstanceOfVersion(package, version, [&found](const auto&) {
368 found = true;
369 return false; // break
370 });
371 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700372}
373
Yifan Hongca3b6602017-09-07 16:44:27 -0700374void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700375 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800376 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700377 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700378
379 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800380 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700381
Yifan Hongb2d096a2018-05-01 15:25:23 -0700382 std::vector<std::string> error;
383 for (const TableEntry& entry : mServicesTable)
384 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
385 for (const TableEntry& entry : mPassthroughRefTable)
386 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700387
Yifan Hongb2d096a2018-05-01 15:25:23 -0700388 std::vector<std::string> passthrough;
389 for (const TableEntry& entry : mImplementationsTable)
390 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800391
Yifan Hongf31aa052018-02-02 15:17:51 -0800392 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700393 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
394 << INIT_VINTF_NOTES;
395 if (!error.empty()) {
396 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
397 for (const auto& e : error) {
398 out << " " << e << std::endl;
399 }
400 }
401 if (!passthrough.empty()) {
402 out << std::endl
403 << " The following HALs are passthrough and no interface or instance " << std::endl
404 << " names can be inferred." << std::endl;
405 for (const auto& e : passthrough) {
406 out << " " << e << std::endl;
407 }
408 }
409 out << "-->" << std::endl;
410 out << vintf::gHalManifestConverter(manifest, vintf::SerializeFlag::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700411}
412
Yifan Hongf31aa052018-02-02 15:17:51 -0800413std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700414 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800415 " only hwbinder is shown.\n"
416 " 2. It is likely that HALs in passthrough transport does not have\n"
417 " <interface> declared; users will have to write them by hand.\n"
418 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
419 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700420 " 4. This output is intended for launch devices.\n"
421 " Upgrading devices should not use this tool to generate device\n"
422 " manifest and replace the existing manifest directly, but should\n"
423 " edit the existing manifest manually.\n"
424 " Specifically, devices which launched at Android O-MR1 or earlier\n"
425 " should not use the 'fqname' format for required HAL entries and\n"
426 " should instead use the legacy package, name, instance-name format\n"
427 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800428};
429
Yifan Hong0ad64f52018-05-25 15:29:17 -0700430static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
Yifan Hong443df792017-05-09 18:49:45 -0700431 switch (a) {
432 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700433 return vintf::Arch::ARCH_64;
Yifan Hong443df792017-05-09 18:49:45 -0700434 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700435 return vintf::Arch::ARCH_32;
Yifan Hong443df792017-05-09 18:49:45 -0700436 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
437 default:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700438 return vintf::Arch::ARCH_EMPTY;
Yifan Hong443df792017-05-09 18:49:45 -0700439 }
440}
441
Yifan Hongca3b6602017-09-07 16:44:27 -0700442void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700443 if (mNeat) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700444 MergedTable({&mServicesTable, &mPassthroughRefTable, &mImplementationsTable})
Yifan Hongca3b6602017-09-07 16:44:27 -0700445 .createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700446 return;
447 }
448
Yifan Hongca3b6602017-09-07 16:44:27 -0700449 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700450
Yifan Hongd4a77e82017-09-06 19:40:24 -0700451 // We're only interested in dumping debug info for already
452 // instantiated services. There's little value in dumping the
453 // debug info for a service we create on the fly, so we only operate
454 // on the "mServicesTable".
455 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
456 if (mEmitDebugInfo && &table == &mServicesTable) {
457 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700458 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700459 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800460 mLshal.emitDebugInfo(pair.first, pair.second, {},
461 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700462 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700463 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700464 };
Yifan Hong443df792017-05-09 18:49:45 -0700465 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700466 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
467 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700468 });
Yifan Hong443df792017-05-09 18:49:45 -0700469}
470
Yifan Hongca3b6602017-09-07 16:44:27 -0700471Status ListCommand::dump() {
472 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
473
474 if (mFileOutputPath.empty()) {
475 (*this.*dump)(out());
476 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700477 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700478
479 std::ofstream fileOutput(mFileOutputPath);
480 if (!fileOutput.is_open()) {
481 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
482 return IO_ERROR;
483 }
484 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
485
486 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
487
488 fileOutput.flush();
489 fileOutput.close();
490 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700491}
492
493void ListCommand::putEntry(TableEntrySource source, TableEntry &&entry) {
494 Table *table = nullptr;
495 switch (source) {
496 case HWSERVICEMANAGER_LIST :
497 table = &mServicesTable; break;
498 case PTSERVICEMANAGER_REG_CLIENT :
499 table = &mPassthroughRefTable; break;
500 case LIST_DLLIB :
501 table = &mImplementationsTable; break;
502 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700503 err() << "Error: Unknown source of entry " << source << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700504 }
505 if (table) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700506 table->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700507 }
508}
509
510Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700511 if (!shouldReportHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
512
Yifan Hong443df792017-05-09 18:49:45 -0700513 using namespace ::android::hardware;
514 using namespace ::android::hidl::manager::V1_0;
515 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700516 using std::literals::chrono_literals::operator""s;
517 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700518 std::map<std::string, TableEntry> entries;
519 for (const auto &info : infos) {
520 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
521 std::string{info.instanceName.c_str()};
522 entries.emplace(interfaceName, TableEntry{
523 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700524 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700525 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700526 }).first->second.arch |= fromBaseArchitecture(info.arch);
527 }
528 for (auto &&pair : entries) {
529 putEntry(LIST_DLLIB, std::move(pair.second));
530 }
531 });
532 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700533 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700534 << ret.description() << std::endl;
535 return DUMP_ALL_LIBS_ERROR;
536 }
537 return OK;
538}
539
540Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700541 if (!shouldReportHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
542
Yifan Hong443df792017-05-09 18:49:45 -0700543 using namespace ::android::hardware;
544 using namespace ::android::hardware::details;
545 using namespace ::android::hidl::manager::V1_0;
546 using namespace ::android::hidl::base::V1_0;
547 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
548 for (const auto &info : infos) {
549 if (info.clientPids.size() <= 0) {
550 continue;
551 }
552 putEntry(PTSERVICEMANAGER_REG_CLIENT, {
553 .interfaceName =
554 std::string{info.interfaceName.c_str()} + "/" +
555 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700556 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700557 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700558 .clientPids = info.clientPids,
559 .arch = fromBaseArchitecture(info.arch)
560 });
561 }
562 });
563 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700564 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700565 << ret.description() << std::endl;
566 return DUMP_PASSTHROUGH_ERROR;
567 }
568 return OK;
569}
570
571Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700572 using vintf::operator<<;
573
Nirav Atrecce988d2018-05-16 11:14:46 -0700574 if (!shouldReportHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700575
Yifan Hong8304e412018-05-25 15:05:36 -0700576 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700577 hidl_vec<hidl_string> fqInstanceNames;
578 // copying out for timeoutIPC
579 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
580 fqInstanceNames = names;
581 });
582 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700583 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700584 << listRet.description() << std::endl;
585 return DUMP_BINDERIZED_ERROR;
586 }
587
588 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700589 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700590 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700591 // create entry and default assign all fields.
592 TableEntry& entry = allTableEntries[fqInstanceName];
593 entry.interfaceName = fqInstanceName;
594 entry.transport = mode;
595
596 status |= fetchBinderizedEntry(manager, &entry);
597 }
598
599 for (auto& pair : allTableEntries) {
600 putEntry(HWSERVICEMANAGER_LIST, std::move(pair.second));
601 }
602 return status;
603}
604
605Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
606 TableEntry *entry) {
607 Status status = OK;
608 const auto handleError = [&](Status additionalError, const std::string& msg) {
609 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
610 status |= DUMP_BINDERIZED_ERROR | additionalError;
611 };
612
613 const auto pair = splitFirst(entry->interfaceName, '/');
614 const auto &serviceName = pair.first;
615 const auto &instanceName = pair.second;
616 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
617 if (!getRet.isOk()) {
618 handleError(TRANSACTION_ERROR,
619 "cannot be fetched from service manager:" + getRet.description());
620 return status;
621 }
622 sp<IBase> service = getRet;
623 if (service == nullptr) {
624 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
625 return status;
626 }
627
628 // getDebugInfo
629 do {
630 DebugInfo debugInfo;
631 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
632 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700633 });
634 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700635 handleError(TRANSACTION_ERROR,
636 "debugging information cannot be retrieved: " + debugRet.description());
637 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700638 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700639
Yifan Hong22ea7b82017-09-14 18:07:43 -0700640 entry->serverPid = debugInfo.pid;
641 entry->serverObjectAddress = debugInfo.ptr;
642 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700643
Yifan Hong22ea7b82017-09-14 18:07:43 -0700644 if (debugInfo.pid != NO_PID) {
645 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
646 if (pidInfo == nullptr) {
647 handleError(IO_ERROR,
648 "no information for PID " + std::to_string(debugInfo.pid) +
649 ", are you root?");
650 break;
651 }
652 if (debugInfo.ptr != NO_PTR) {
653 auto it = pidInfo->refPids.find(debugInfo.ptr);
654 if (it != pidInfo->refPids.end()) {
655 entry->clientPids = it->second;
656 }
657 }
658 entry->threadUsage = pidInfo->threadUsage;
659 entry->threadCount = pidInfo->threadCount;
660 }
661 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700662
663 // hash
664 do {
665 ssize_t hashIndex = -1;
666 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
667 for (size_t i = 0; i < c.size(); ++i) {
668 if (serviceName == c[i]) {
669 hashIndex = static_cast<ssize_t>(i);
670 break;
671 }
672 }
673 });
674 if (!ifaceChainRet.isOk()) {
675 handleError(TRANSACTION_ERROR,
676 "interfaceChain fails: " + ifaceChainRet.description());
677 break; // skip getHashChain
678 }
679 if (hashIndex < 0) {
680 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
681 break; // skip getHashChain
682 }
683 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
684 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
685 handleError(BAD_IMPL,
686 "interfaceChain indicates position " + std::to_string(hashIndex) +
687 " but getHashChain returns " + std::to_string(hashChain.size()) +
688 " hashes");
689 return;
690 }
691
692 auto&& hashArray = hashChain[hashIndex];
693 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
694 entry->hash = Hash::hexString(hashVec);
695 });
696 if (!hashRet.isOk()) {
697 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
698 }
699 } while (0);
Yifan Hong443df792017-05-09 18:49:45 -0700700 return status;
701}
702
703Status ListCommand::fetch() {
704 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700705 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700706 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700707 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700708 status |= NO_BINDERIZED_MANAGER;
709 } else {
710 status |= fetchBinderized(bManager);
711 // Passthrough PIDs are registered to the binderized manager as well.
712 status |= fetchPassthrough(bManager);
713 }
714
Yifan Hong9881df92017-05-10 14:33:05 -0700715 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700716 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700717 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700718 status |= NO_PASSTHROUGH_MANAGER;
719 } else {
720 status |= fetchAllLibraries(pManager);
721 }
722 return status;
723}
724
Yifan Honga6b93f02017-09-13 16:53:37 -0700725void ListCommand::registerAllOptions() {
726 int v = mOptions.size();
727 // A list of acceptable command line options
728 // key: value returned by getopt_long
729 // long options with short alternatives
730 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
731 return USAGE;
732 }, ""});
733 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
734 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
735 return OK;
736 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700737 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
738 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
739 return OK;
740 }, "print the 'is released?' column\n(Y=released, empty=unreleased or unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700741 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
742 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
743 return OK;
744 }, "print the transport mode column"});
745 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
746 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
747 return OK;
748 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700749 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
750 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
751 return OK;
752 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700753 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
754 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
755 return OK;
756 }, "print the server PID, or server cmdline if -m is set"});
757 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
758 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
759 return OK;
760 }, "print the server object address column"});
761 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
762 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
763 return OK;
764 }, "print the client PIDs, or client cmdlines if -m is set"});
765 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
766 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
767 return OK;
768 }, "print currently used/available threads\n(note, available threads created lazily)"});
769 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
770 thiz->mEnableCmdlines = true;
771 return OK;
772 }, "print cmdline instead of PIDs"});
773 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
774 thiz->mEmitDebugInfo = true;
775 if (arg) thiz->mFileOutputPath = arg;
776 return OK;
777 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
778 "Writes to specified file if 'arg' is provided, otherwise stdout."});
779
780 // long options without short alternatives
781 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
782 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800783 if (thiz->mVintfPartition == Partition::UNKNOWN)
784 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700785 if (arg) thiz->mFileOutputPath = arg;
786 return OK;
787 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800788 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
789 if (!arg) return USAGE;
790 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
791 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
792 return OK;
793 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
794 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700795 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
796 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
797 thiz->mSortColumn = TableEntry::sortByInterfaceName;
798 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
799 thiz->mSortColumn = TableEntry::sortByServerPid;
800 } else {
801 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
802 return USAGE;
803 }
804 return OK;
805 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
806 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
807 thiz->mNeat = true;
808 return OK;
809 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Nirav Atrecce988d2018-05-16 11:14:46 -0700810 mOptions.push_back({'\0', "types", required_argument, v++, [](ListCommand* thiz, const char* arg) {
811 if (!arg) { return USAGE; }
812
813 static const std::map<std::string, HalType> kHalTypeMap {
814 {"binderized", HalType::BINDERIZED_SERVICES},
815 {"b", HalType::BINDERIZED_SERVICES},
816 {"passthrough_clients", HalType::PASSTHROUGH_CLIENTS},
817 {"c", HalType::PASSTHROUGH_CLIENTS},
818 {"passthrough_libs", HalType::PASSTHROUGH_LIBRARIES},
819 {"l", HalType::PASSTHROUGH_LIBRARIES}
820 };
821
822 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
823 for (const auto& halTypeArg : halTypesArgs) {
824 if (halTypeArg.empty()) continue;
825
826 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
827 if (halTypeIter == kHalTypeMap.end()) {
828
829 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
830 return USAGE;
831 }
832
833 // Append unique (non-repeated) HAL types to the reporting list
834 HalType halType = halTypeIter->second;
835 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
836 thiz->mListTypes.end()) {
837 thiz->mListTypes.push_back(halType);
838 }
839 }
840
841 if (thiz->mListTypes.empty()) { return USAGE; }
842 return OK;
843 }, "comma-separated list of one or more HAL types.\nThe output is restricted to the selected "
844 "association(s). Valid options\nare: (b|binderized), (c|passthrough_clients), and (l|"
845 "passthrough_libs).\nBy default, lists all available HALs."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700846}
847
848// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
849// the lifetime of "options" during the usage of the returned array.
850static std::unique_ptr<struct option[]> getLongOptions(
851 const ListCommand::RegisteredOptions& options,
852 int* longOptFlag) {
853 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
854 int i = 0;
855 for (const auto& e : options) {
856 ret[i].name = e.longOption.c_str();
857 ret[i].has_arg = e.hasArg;
858 ret[i].flag = longOptFlag;
859 ret[i].val = e.val;
860
861 i++;
862 }
863 // getopt_long last option has all zeros
864 ret[i].name = NULL;
865 ret[i].has_arg = 0;
866 ret[i].flag = NULL;
867 ret[i].val = 0;
868
869 return ret;
870}
871
872// Create 'optstring' argument to getopt_long.
873static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
874 std::stringstream ss;
875 for (const auto& e : options) {
876 if (e.shortOption != '\0') {
877 ss << e.shortOption;
878 }
879 }
880 return ss.str();
881}
882
Yifan Honga8bedc62017-09-08 18:00:31 -0700883Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700884 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -0700885
Yifan Honga6b93f02017-09-13 16:53:37 -0700886 if (mOptions.empty()) {
887 registerAllOptions();
888 }
889 int longOptFlag;
890 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
891 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700892
Yifan Honga8bedc62017-09-08 18:00:31 -0700893 // suppress output to std::err for unknown options
894 opterr = 0;
895
Yifan Hong443df792017-05-09 18:49:45 -0700896 int optionIndex;
897 int c;
898 // Lshal::parseArgs has set optind to the next option to parse
899 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700900 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700901 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700902 if (c == -1) {
903 break;
904 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700905 const RegisteredOption* found = nullptr;
906 if (c == 0) {
907 // see long option
908 for (const auto& e : mOptions) {
909 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700910 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700911 } else {
912 // see short option
913 for (const auto& e : mOptions) {
914 if (c == e.shortOption) found = &e;
915 }
Yifan Hong443df792017-05-09 18:49:45 -0700916 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700917
918 if (found == nullptr) {
919 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700920 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700921 return USAGE;
922 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700923
924 Status status = found->op(this, optarg);
925 if (status != OK) {
926 return status;
927 }
Yifan Hong443df792017-05-09 18:49:45 -0700928 }
929 if (optind < arg.argc) {
930 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700931 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700932 return USAGE;
933 }
934
935 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700936 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700937 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700938 }
939
Yifan Honga6b93f02017-09-13 16:53:37 -0700940 if (mSelectedColumns.empty()) {
Yifan Hongfee209d2017-09-14 18:23:38 -0700941 mSelectedColumns = {TableColumnType::RELEASED,
942 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -0700943 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -0700944 }
Yifan Hongd4a77e82017-09-06 19:40:24 -0700945
Yifan Honga6b93f02017-09-13 16:53:37 -0700946 if (mEnableCmdlines) {
947 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
948 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
949 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700950 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700951 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
952 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700953 }
954 }
955 }
956
Nirav Atrecce988d2018-05-16 11:14:46 -0700957 // By default, list all HAL types
958 if (mListTypes.empty()) {
959 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
960 HalType::PASSTHROUGH_LIBRARIES};
961 }
962
Yifan Honga6b93f02017-09-13 16:53:37 -0700963 forEachTable([this] (Table& table) {
964 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700965 });
966
Yifan Hong443df792017-05-09 18:49:45 -0700967 return OK;
968}
969
Yifan Honga8bedc62017-09-08 18:00:31 -0700970Status ListCommand::main(const Arg &arg) {
971 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -0700972 if (status != OK) {
973 return status;
974 }
975 status = fetch();
976 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -0700977 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -0700978 return status;
979}
980
Yifan Honga6b93f02017-09-13 16:53:37 -0700981const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
982 static const std::string empty{};
983 static const std::string optional{"[=<arg>]"};
984 static const std::string required{"=<arg>"};
985
986 if (hasArg == optional_argument) {
987 return optional;
988 }
989 if (hasArg == required_argument) {
990 return required;
991 }
992 return empty;
993}
994
Yifan Honga8bedc62017-09-08 18:00:31 -0700995void ListCommand::usage() const {
996
Yifan Honga6b93f02017-09-13 16:53:37 -0700997 err() << "list:" << std::endl
998 << " lshal" << std::endl
999 << " lshal list" << std::endl
Yifan Hongfee209d2017-09-14 18:23:38 -07001000 << " List all hals with default ordering and columns (`lshal list -riepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001001 << " lshal list [-h|--help]" << std::endl
1002 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1003 << " lshal [list] [OPTIONS...]" << std::endl;
1004 for (const auto& e : mOptions) {
1005 if (e.help.empty()) {
1006 continue;
1007 }
1008 err() << " ";
1009 if (e.shortOption != '\0')
1010 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1011 if (e.shortOption != '\0' && !e.longOption.empty())
1012 err() << ", ";
1013 if (!e.longOption.empty())
1014 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1015 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001016 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001017 for (const auto& line : lines) {
1018 if (&line != &lines.front())
1019 err() << " ";
1020 err() << line << std::endl;
1021 }
1022 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001023}
1024
Yifan Hong443df792017-05-09 18:49:45 -07001025} // namespace lshal
1026} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001027