blob: 82d4a98209f9591dd74e74bd5ae3c44e461f4782 [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) {
282 if (interfaceEntry.arch != ARCH_UNKNOWN) {
283 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 Hongb2d096a2018-05-01 15:25:23 -0700335 arch = vintf::Arch::ARCH_EMPTY;
Yifan Hong8304e412018-05-25 15:05:36 -0700336 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700337 switch (entry.arch) {
338 case lshal::ARCH32:
339 arch = vintf::Arch::ARCH_32;
340 break;
341 case lshal::ARCH64:
342 arch = vintf::Arch::ARCH_64;
343 break;
344 case lshal::ARCH_BOTH:
345 arch = vintf::Arch::ARCH_32_64;
346 break;
347 case lshal::ARCH_UNKNOWN: // fallthrough
348 default:
349 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
350 return false;
351 }
352 } else {
353 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
354 return false;
355 }
356
357 std::string e;
Yifan Hong8304e412018-05-25 15:05:36 -0700358 if (!manifest->insertInstance(fqInstance, entry.transport, arch, vintf::HalFormat::HIDL, &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700359 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
360 return false;
361 }
362 return true;
363}
364
365bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
366 const vintf::HalManifest* manifest) const {
367 const auto& packageAndVersion = splitFirst(splitFirst(entry.interfaceName, ':').first, '@');
368 const auto& package = packageAndVersion.first;
369 vintf::Version version;
370 if (!vintf::parse(packageAndVersion.second, &version)) {
371 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
372 << entry.interfaceName << "'" << std::endl;
373 return false;
374 }
375
376 bool found = false;
377 (void)manifest->forEachInstanceOfVersion(package, version, [&found](const auto&) {
378 found = true;
379 return false; // break
380 });
381 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700382}
383
Yifan Hongca3b6602017-09-07 16:44:27 -0700384void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700385 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800386 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700387 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700388
389 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800390 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700391
Yifan Hongb2d096a2018-05-01 15:25:23 -0700392 std::vector<std::string> error;
393 for (const TableEntry& entry : mServicesTable)
394 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
395 for (const TableEntry& entry : mPassthroughRefTable)
396 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700397
Yifan Hongb2d096a2018-05-01 15:25:23 -0700398 std::vector<std::string> passthrough;
399 for (const TableEntry& entry : mImplementationsTable)
400 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800401
Yifan Hongf31aa052018-02-02 15:17:51 -0800402 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700403 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
404 << INIT_VINTF_NOTES;
405 if (!error.empty()) {
406 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
407 for (const auto& e : error) {
408 out << " " << e << std::endl;
409 }
410 }
411 if (!passthrough.empty()) {
412 out << std::endl
413 << " The following HALs are passthrough and no interface or instance " << std::endl
414 << " names can be inferred." << std::endl;
415 for (const auto& e : passthrough) {
416 out << " " << e << std::endl;
417 }
418 }
419 out << "-->" << std::endl;
420 out << vintf::gHalManifestConverter(manifest, vintf::SerializeFlag::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700421}
422
Yifan Hongf31aa052018-02-02 15:17:51 -0800423std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700424 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800425 " only hwbinder is shown.\n"
426 " 2. It is likely that HALs in passthrough transport does not have\n"
427 " <interface> declared; users will have to write them by hand.\n"
428 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
429 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700430 " 4. This output is intended for launch devices.\n"
431 " Upgrading devices should not use this tool to generate device\n"
432 " manifest and replace the existing manifest directly, but should\n"
433 " edit the existing manifest manually.\n"
434 " Specifically, devices which launched at Android O-MR1 or earlier\n"
435 " should not use the 'fqname' format for required HAL entries and\n"
436 " should instead use the legacy package, name, instance-name format\n"
437 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800438};
439
Yifan Hong443df792017-05-09 18:49:45 -0700440static Architecture fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
441 switch (a) {
442 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
443 return ARCH64;
444 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
445 return ARCH32;
446 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
447 default:
448 return ARCH_UNKNOWN;
449 }
450}
451
Yifan Hongca3b6602017-09-07 16:44:27 -0700452void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700453 if (mNeat) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700454 MergedTable({&mServicesTable, &mPassthroughRefTable, &mImplementationsTable})
Yifan Hongca3b6602017-09-07 16:44:27 -0700455 .createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700456 return;
457 }
458
Yifan Hongca3b6602017-09-07 16:44:27 -0700459 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700460
Yifan Hongd4a77e82017-09-06 19:40:24 -0700461 // We're only interested in dumping debug info for already
462 // instantiated services. There's little value in dumping the
463 // debug info for a service we create on the fly, so we only operate
464 // on the "mServicesTable".
465 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
466 if (mEmitDebugInfo && &table == &mServicesTable) {
467 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700468 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700469 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800470 mLshal.emitDebugInfo(pair.first, pair.second, {},
471 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700472 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700473 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700474 };
Yifan Hong443df792017-05-09 18:49:45 -0700475 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700476 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
477 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700478 });
Yifan Hong443df792017-05-09 18:49:45 -0700479}
480
Yifan Hongca3b6602017-09-07 16:44:27 -0700481Status ListCommand::dump() {
482 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
483
484 if (mFileOutputPath.empty()) {
485 (*this.*dump)(out());
486 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700487 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700488
489 std::ofstream fileOutput(mFileOutputPath);
490 if (!fileOutput.is_open()) {
491 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
492 return IO_ERROR;
493 }
494 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
495
496 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
497
498 fileOutput.flush();
499 fileOutput.close();
500 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700501}
502
503void ListCommand::putEntry(TableEntrySource source, TableEntry &&entry) {
504 Table *table = nullptr;
505 switch (source) {
506 case HWSERVICEMANAGER_LIST :
507 table = &mServicesTable; break;
508 case PTSERVICEMANAGER_REG_CLIENT :
509 table = &mPassthroughRefTable; break;
510 case LIST_DLLIB :
511 table = &mImplementationsTable; break;
512 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700513 err() << "Error: Unknown source of entry " << source << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700514 }
515 if (table) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700516 table->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700517 }
518}
519
520Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700521 if (!shouldReportHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
522
Yifan Hong443df792017-05-09 18:49:45 -0700523 using namespace ::android::hardware;
524 using namespace ::android::hidl::manager::V1_0;
525 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700526 using std::literals::chrono_literals::operator""s;
527 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700528 std::map<std::string, TableEntry> entries;
529 for (const auto &info : infos) {
530 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
531 std::string{info.instanceName.c_str()};
532 entries.emplace(interfaceName, TableEntry{
533 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700534 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700535 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700536 }).first->second.arch |= fromBaseArchitecture(info.arch);
537 }
538 for (auto &&pair : entries) {
539 putEntry(LIST_DLLIB, std::move(pair.second));
540 }
541 });
542 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700543 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700544 << ret.description() << std::endl;
545 return DUMP_ALL_LIBS_ERROR;
546 }
547 return OK;
548}
549
550Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700551 if (!shouldReportHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
552
Yifan Hong443df792017-05-09 18:49:45 -0700553 using namespace ::android::hardware;
554 using namespace ::android::hardware::details;
555 using namespace ::android::hidl::manager::V1_0;
556 using namespace ::android::hidl::base::V1_0;
557 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
558 for (const auto &info : infos) {
559 if (info.clientPids.size() <= 0) {
560 continue;
561 }
562 putEntry(PTSERVICEMANAGER_REG_CLIENT, {
563 .interfaceName =
564 std::string{info.interfaceName.c_str()} + "/" +
565 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700566 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700567 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700568 .clientPids = info.clientPids,
569 .arch = fromBaseArchitecture(info.arch)
570 });
571 }
572 });
573 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700574 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700575 << ret.description() << std::endl;
576 return DUMP_PASSTHROUGH_ERROR;
577 }
578 return OK;
579}
580
581Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700582 using vintf::operator<<;
583
Nirav Atrecce988d2018-05-16 11:14:46 -0700584 if (!shouldReportHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700585
Yifan Hong8304e412018-05-25 15:05:36 -0700586 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700587 hidl_vec<hidl_string> fqInstanceNames;
588 // copying out for timeoutIPC
589 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
590 fqInstanceNames = names;
591 });
592 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700593 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700594 << listRet.description() << std::endl;
595 return DUMP_BINDERIZED_ERROR;
596 }
597
598 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700599 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700600 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700601 // create entry and default assign all fields.
602 TableEntry& entry = allTableEntries[fqInstanceName];
603 entry.interfaceName = fqInstanceName;
604 entry.transport = mode;
605
606 status |= fetchBinderizedEntry(manager, &entry);
607 }
608
609 for (auto& pair : allTableEntries) {
610 putEntry(HWSERVICEMANAGER_LIST, std::move(pair.second));
611 }
612 return status;
613}
614
615Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
616 TableEntry *entry) {
617 Status status = OK;
618 const auto handleError = [&](Status additionalError, const std::string& msg) {
619 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
620 status |= DUMP_BINDERIZED_ERROR | additionalError;
621 };
622
623 const auto pair = splitFirst(entry->interfaceName, '/');
624 const auto &serviceName = pair.first;
625 const auto &instanceName = pair.second;
626 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
627 if (!getRet.isOk()) {
628 handleError(TRANSACTION_ERROR,
629 "cannot be fetched from service manager:" + getRet.description());
630 return status;
631 }
632 sp<IBase> service = getRet;
633 if (service == nullptr) {
634 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
635 return status;
636 }
637
638 // getDebugInfo
639 do {
640 DebugInfo debugInfo;
641 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
642 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700643 });
644 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700645 handleError(TRANSACTION_ERROR,
646 "debugging information cannot be retrieved: " + debugRet.description());
647 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700648 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700649
Yifan Hong22ea7b82017-09-14 18:07:43 -0700650 entry->serverPid = debugInfo.pid;
651 entry->serverObjectAddress = debugInfo.ptr;
652 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700653
Yifan Hong22ea7b82017-09-14 18:07:43 -0700654 if (debugInfo.pid != NO_PID) {
655 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
656 if (pidInfo == nullptr) {
657 handleError(IO_ERROR,
658 "no information for PID " + std::to_string(debugInfo.pid) +
659 ", are you root?");
660 break;
661 }
662 if (debugInfo.ptr != NO_PTR) {
663 auto it = pidInfo->refPids.find(debugInfo.ptr);
664 if (it != pidInfo->refPids.end()) {
665 entry->clientPids = it->second;
666 }
667 }
668 entry->threadUsage = pidInfo->threadUsage;
669 entry->threadCount = pidInfo->threadCount;
670 }
671 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700672
673 // hash
674 do {
675 ssize_t hashIndex = -1;
676 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
677 for (size_t i = 0; i < c.size(); ++i) {
678 if (serviceName == c[i]) {
679 hashIndex = static_cast<ssize_t>(i);
680 break;
681 }
682 }
683 });
684 if (!ifaceChainRet.isOk()) {
685 handleError(TRANSACTION_ERROR,
686 "interfaceChain fails: " + ifaceChainRet.description());
687 break; // skip getHashChain
688 }
689 if (hashIndex < 0) {
690 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
691 break; // skip getHashChain
692 }
693 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
694 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
695 handleError(BAD_IMPL,
696 "interfaceChain indicates position " + std::to_string(hashIndex) +
697 " but getHashChain returns " + std::to_string(hashChain.size()) +
698 " hashes");
699 return;
700 }
701
702 auto&& hashArray = hashChain[hashIndex];
703 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
704 entry->hash = Hash::hexString(hashVec);
705 });
706 if (!hashRet.isOk()) {
707 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
708 }
709 } while (0);
Yifan Hong443df792017-05-09 18:49:45 -0700710 return status;
711}
712
713Status ListCommand::fetch() {
714 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700715 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700716 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700717 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700718 status |= NO_BINDERIZED_MANAGER;
719 } else {
720 status |= fetchBinderized(bManager);
721 // Passthrough PIDs are registered to the binderized manager as well.
722 status |= fetchPassthrough(bManager);
723 }
724
Yifan Hong9881df92017-05-10 14:33:05 -0700725 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700726 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700727 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700728 status |= NO_PASSTHROUGH_MANAGER;
729 } else {
730 status |= fetchAllLibraries(pManager);
731 }
732 return status;
733}
734
Yifan Honga6b93f02017-09-13 16:53:37 -0700735void ListCommand::registerAllOptions() {
736 int v = mOptions.size();
737 // A list of acceptable command line options
738 // key: value returned by getopt_long
739 // long options with short alternatives
740 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
741 return USAGE;
742 }, ""});
743 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
744 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
745 return OK;
746 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700747 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
748 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
749 return OK;
750 }, "print the 'is released?' column\n(Y=released, empty=unreleased or unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700751 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
752 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
753 return OK;
754 }, "print the transport mode column"});
755 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
756 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
757 return OK;
758 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700759 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
760 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
761 return OK;
762 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700763 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
764 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
765 return OK;
766 }, "print the server PID, or server cmdline if -m is set"});
767 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
768 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
769 return OK;
770 }, "print the server object address column"});
771 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
772 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
773 return OK;
774 }, "print the client PIDs, or client cmdlines if -m is set"});
775 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
776 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
777 return OK;
778 }, "print currently used/available threads\n(note, available threads created lazily)"});
779 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
780 thiz->mEnableCmdlines = true;
781 return OK;
782 }, "print cmdline instead of PIDs"});
783 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
784 thiz->mEmitDebugInfo = true;
785 if (arg) thiz->mFileOutputPath = arg;
786 return OK;
787 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
788 "Writes to specified file if 'arg' is provided, otherwise stdout."});
789
790 // long options without short alternatives
791 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
792 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800793 if (thiz->mVintfPartition == Partition::UNKNOWN)
794 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700795 if (arg) thiz->mFileOutputPath = arg;
796 return OK;
797 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800798 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
799 if (!arg) return USAGE;
800 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
801 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
802 return OK;
803 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
804 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700805 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
806 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
807 thiz->mSortColumn = TableEntry::sortByInterfaceName;
808 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
809 thiz->mSortColumn = TableEntry::sortByServerPid;
810 } else {
811 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
812 return USAGE;
813 }
814 return OK;
815 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
816 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
817 thiz->mNeat = true;
818 return OK;
819 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Nirav Atrecce988d2018-05-16 11:14:46 -0700820 mOptions.push_back({'\0', "types", required_argument, v++, [](ListCommand* thiz, const char* arg) {
821 if (!arg) { return USAGE; }
822
823 static const std::map<std::string, HalType> kHalTypeMap {
824 {"binderized", HalType::BINDERIZED_SERVICES},
825 {"b", HalType::BINDERIZED_SERVICES},
826 {"passthrough_clients", HalType::PASSTHROUGH_CLIENTS},
827 {"c", HalType::PASSTHROUGH_CLIENTS},
828 {"passthrough_libs", HalType::PASSTHROUGH_LIBRARIES},
829 {"l", HalType::PASSTHROUGH_LIBRARIES}
830 };
831
832 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
833 for (const auto& halTypeArg : halTypesArgs) {
834 if (halTypeArg.empty()) continue;
835
836 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
837 if (halTypeIter == kHalTypeMap.end()) {
838
839 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
840 return USAGE;
841 }
842
843 // Append unique (non-repeated) HAL types to the reporting list
844 HalType halType = halTypeIter->second;
845 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
846 thiz->mListTypes.end()) {
847 thiz->mListTypes.push_back(halType);
848 }
849 }
850
851 if (thiz->mListTypes.empty()) { return USAGE; }
852 return OK;
853 }, "comma-separated list of one or more HAL types.\nThe output is restricted to the selected "
854 "association(s). Valid options\nare: (b|binderized), (c|passthrough_clients), and (l|"
855 "passthrough_libs).\nBy default, lists all available HALs."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700856}
857
858// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
859// the lifetime of "options" during the usage of the returned array.
860static std::unique_ptr<struct option[]> getLongOptions(
861 const ListCommand::RegisteredOptions& options,
862 int* longOptFlag) {
863 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
864 int i = 0;
865 for (const auto& e : options) {
866 ret[i].name = e.longOption.c_str();
867 ret[i].has_arg = e.hasArg;
868 ret[i].flag = longOptFlag;
869 ret[i].val = e.val;
870
871 i++;
872 }
873 // getopt_long last option has all zeros
874 ret[i].name = NULL;
875 ret[i].has_arg = 0;
876 ret[i].flag = NULL;
877 ret[i].val = 0;
878
879 return ret;
880}
881
882// Create 'optstring' argument to getopt_long.
883static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
884 std::stringstream ss;
885 for (const auto& e : options) {
886 if (e.shortOption != '\0') {
887 ss << e.shortOption;
888 }
889 }
890 return ss.str();
891}
892
Yifan Honga8bedc62017-09-08 18:00:31 -0700893Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700894 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -0700895
Yifan Honga6b93f02017-09-13 16:53:37 -0700896 if (mOptions.empty()) {
897 registerAllOptions();
898 }
899 int longOptFlag;
900 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
901 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700902
Yifan Honga8bedc62017-09-08 18:00:31 -0700903 // suppress output to std::err for unknown options
904 opterr = 0;
905
Yifan Hong443df792017-05-09 18:49:45 -0700906 int optionIndex;
907 int c;
908 // Lshal::parseArgs has set optind to the next option to parse
909 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700910 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700911 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700912 if (c == -1) {
913 break;
914 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700915 const RegisteredOption* found = nullptr;
916 if (c == 0) {
917 // see long option
918 for (const auto& e : mOptions) {
919 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700920 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700921 } else {
922 // see short option
923 for (const auto& e : mOptions) {
924 if (c == e.shortOption) found = &e;
925 }
Yifan Hong443df792017-05-09 18:49:45 -0700926 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700927
928 if (found == nullptr) {
929 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700930 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700931 return USAGE;
932 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700933
934 Status status = found->op(this, optarg);
935 if (status != OK) {
936 return status;
937 }
Yifan Hong443df792017-05-09 18:49:45 -0700938 }
939 if (optind < arg.argc) {
940 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700941 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700942 return USAGE;
943 }
944
945 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700946 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700947 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700948 }
949
Yifan Honga6b93f02017-09-13 16:53:37 -0700950 if (mSelectedColumns.empty()) {
Yifan Hongfee209d2017-09-14 18:23:38 -0700951 mSelectedColumns = {TableColumnType::RELEASED,
952 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -0700953 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -0700954 }
Yifan Hongd4a77e82017-09-06 19:40:24 -0700955
Yifan Honga6b93f02017-09-13 16:53:37 -0700956 if (mEnableCmdlines) {
957 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
958 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
959 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700960 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700961 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
962 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700963 }
964 }
965 }
966
Nirav Atrecce988d2018-05-16 11:14:46 -0700967 // By default, list all HAL types
968 if (mListTypes.empty()) {
969 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
970 HalType::PASSTHROUGH_LIBRARIES};
971 }
972
Yifan Honga6b93f02017-09-13 16:53:37 -0700973 forEachTable([this] (Table& table) {
974 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700975 });
976
Yifan Hong443df792017-05-09 18:49:45 -0700977 return OK;
978}
979
Yifan Honga8bedc62017-09-08 18:00:31 -0700980Status ListCommand::main(const Arg &arg) {
981 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -0700982 if (status != OK) {
983 return status;
984 }
985 status = fetch();
986 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -0700987 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -0700988 return status;
989}
990
Yifan Honga6b93f02017-09-13 16:53:37 -0700991const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
992 static const std::string empty{};
993 static const std::string optional{"[=<arg>]"};
994 static const std::string required{"=<arg>"};
995
996 if (hasArg == optional_argument) {
997 return optional;
998 }
999 if (hasArg == required_argument) {
1000 return required;
1001 }
1002 return empty;
1003}
1004
Yifan Honga8bedc62017-09-08 18:00:31 -07001005void ListCommand::usage() const {
1006
Yifan Honga6b93f02017-09-13 16:53:37 -07001007 err() << "list:" << std::endl
1008 << " lshal" << std::endl
1009 << " lshal list" << std::endl
Yifan Hongfee209d2017-09-14 18:23:38 -07001010 << " List all hals with default ordering and columns (`lshal list -riepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001011 << " lshal list [-h|--help]" << std::endl
1012 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1013 << " lshal [list] [OPTIONS...]" << std::endl;
1014 for (const auto& e : mOptions) {
1015 if (e.help.empty()) {
1016 continue;
1017 }
1018 err() << " ";
1019 if (e.shortOption != '\0')
1020 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1021 if (e.shortOption != '\0' && !e.longOption.empty())
1022 err() << ", ";
1023 if (!e.longOption.empty())
1024 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1025 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001026 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001027 for (const auto& line : lines) {
1028 if (&line != &lines.front())
1029 err() << " ";
1030 err() << line << std::endl;
1031 }
1032 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001033}
1034
Yifan Hong443df792017-05-09 18:49:45 -07001035} // namespace lshal
1036} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001037