blob: 92e915181b9825b8d66587e3c5a2ca32efe467f1 [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 Hongbdf44f82018-05-25 14:20:00 -0700129bool match(const vintf::ManifestInstance& instance, const FqInstance& fqInstance,
130 vintf::TransportArch ta) {
131 // For hwbinder libs, allow missing arch in manifest.
132 // For passthrough libs, allow missing interface/instance in table.
133 return (ta.transport == instance.transport()) &&
134 (ta.transport == vintf::Transport::HWBINDER ||
135 vintf::contains(instance.arch(), ta.arch)) &&
136 (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
137 (!fqInstance.hasInstance() || fqInstance.getInstance() == instance.instance());
138}
139
140bool match(const vintf::MatrixInstance& instance, const FqInstance& fqInstance,
141 vintf::TransportArch /* ta */) {
142 return (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
143 (!fqInstance.hasInstance() || instance.matchInstance(fqInstance.getInstance()));
144}
145
146template <typename ObjectType>
147VintfInfo getVintfInfo(const std::shared_ptr<const ObjectType>& object,
148 const FqInstance& fqInstance, vintf::TransportArch ta, VintfInfo value) {
149 bool found = false;
150 (void)object->forEachInstanceOfVersion(fqInstance.getPackage(), fqInstance.getVersion(),
151 [&](const auto& instance) {
152 found = match(instance, fqInstance, ta);
153 return !found; // continue if not found
154 });
155 return found ? value : VINTF_INFO_EMPTY;
156}
157
158std::shared_ptr<const vintf::HalManifest> ListCommand::getDeviceManifest() const {
159 return vintf::VintfObject::GetDeviceHalManifest();
160}
161
162std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getDeviceMatrix() const {
163 return vintf::VintfObject::GetDeviceCompatibilityMatrix();
164}
165
166std::shared_ptr<const vintf::HalManifest> ListCommand::getFrameworkManifest() const {
167 return vintf::VintfObject::GetFrameworkHalManifest();
168}
169
170std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getFrameworkMatrix() const {
171 return vintf::VintfObject::GetFrameworkCompatibilityMatrix();
172}
173
174VintfInfo ListCommand::getVintfInfo(const std::string& fqInstanceName,
175 vintf::TransportArch ta) const {
176 FqInstance fqInstance;
177 if (!fqInstance.setTo(fqInstanceName) &&
178 // Ignore interface / instance for passthrough libs
179 !fqInstance.setTo(splitFirst(fqInstanceName, ':').first)) {
180 err() << "Warning: Cannot parse '" << fqInstanceName << "'; no VINTF info." << std::endl;
181 return VINTF_INFO_EMPTY;
182 }
183
184 return lshal::getVintfInfo(getDeviceManifest(), fqInstance, ta, DEVICE_MANIFEST) |
185 lshal::getVintfInfo(getFrameworkManifest(), fqInstance, ta, FRAMEWORK_MANIFEST) |
186 lshal::getVintfInfo(getDeviceMatrix(), fqInstance, ta, DEVICE_MATRIX) |
187 lshal::getVintfInfo(getFrameworkMatrix(), fqInstance, ta, FRAMEWORK_MATRIX);
188}
189
Yifan Hong1243dde2017-09-14 17:49:30 -0700190static bool scanBinderContext(pid_t pid,
Steven Morelandd8e20192017-05-24 11:23:08 -0700191 const std::string &contextName,
192 std::function<void(const std::string&)> eachLine) {
193 std::ifstream ifs("/d/binder/proc/" + std::to_string(pid));
Yifan Hong443df792017-05-09 18:49:45 -0700194 if (!ifs.is_open()) {
195 return false;
196 }
197
Steven Morelandd8e20192017-05-24 11:23:08 -0700198 static const std::regex kContextLine("^context (\\w+)$");
Yifan Hong443df792017-05-09 18:49:45 -0700199
Steven Morelandd8e20192017-05-24 11:23:08 -0700200 bool isDesiredContext = false;
Yifan Hong443df792017-05-09 18:49:45 -0700201 std::string line;
202 std::smatch match;
203 while(getline(ifs, line)) {
Steven Morelandd8e20192017-05-24 11:23:08 -0700204 if (std::regex_search(line, match, kContextLine)) {
205 isDesiredContext = match.str(1) == contextName;
Yifan Hong443df792017-05-09 18:49:45 -0700206 continue;
207 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700208
209 if (!isDesiredContext) {
Yifan Hong443df792017-05-09 18:49:45 -0700210 continue;
211 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700212
213 eachLine(line);
Yifan Hong443df792017-05-09 18:49:45 -0700214 }
215 return true;
216}
217
Steven Morelandd8e20192017-05-24 11:23:08 -0700218bool ListCommand::getPidInfo(
219 pid_t serverPid, PidInfo *pidInfo) const {
220 static const std::regex kReferencePrefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
221 static const std::regex kThreadPrefix("^\\s*thread \\d+:\\s+l\\s+(\\d)(\\d)");
222
223 std::smatch match;
224 return scanBinderContext(serverPid, "hwbinder", [&](const std::string& line) {
225 if (std::regex_search(line, match, kReferencePrefix)) {
226 const std::string &ptrString = "0x" + match.str(2); // use number after c
227 uint64_t ptr;
228 if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
229 // Should not reach here, but just be tolerant.
Yifan Hong76ac14a2017-09-08 14:59:04 -0700230 err() << "Could not parse number " << ptrString << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700231 return;
232 }
233 const std::string proc = " proc ";
234 auto pos = line.rfind(proc);
235 if (pos != std::string::npos) {
236 for (const std::string &pidStr : split(line.substr(pos + proc.size()), ' ')) {
237 int32_t pid;
238 if (!::android::base::ParseInt(pidStr, &pid)) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700239 err() << "Could not parse number " << pidStr << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700240 return;
241 }
242 pidInfo->refPids[ptr].push_back(pid);
243 }
244 }
245
246 return;
247 }
248
249 if (std::regex_search(line, match, kThreadPrefix)) {
250 // "1" is waiting in binder driver
251 // "2" is poll. It's impossible to tell if these are in use.
252 // and HIDL default code doesn't use it.
253 bool isInUse = match.str(1) != "1";
254 // "0" is a thread that has called into binder
255 // "1" is looper thread
256 // "2" is main looper thread
257 bool isHwbinderThread = match.str(2) != "0";
258
259 if (!isHwbinderThread) {
260 return;
261 }
262
263 if (isInUse) {
264 pidInfo->threadUsage++;
265 }
266
267 pidInfo->threadCount++;
268 return;
269 }
270
271 // not reference or thread line
272 return;
273 });
274}
275
Yifan Hong1243dde2017-09-14 17:49:30 -0700276const PidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
277 auto pair = mCachedPidInfos.insert({serverPid, PidInfo{}});
278 if (pair.second /* did insertion take place? */) {
279 if (!getPidInfo(serverPid, &pair.first->second)) {
280 return nullptr;
281 }
282 }
283 return &pair.first->second;
284}
285
Nirav Atrecce988d2018-05-16 11:14:46 -0700286bool ListCommand::shouldReportHalType(const HalType &type) const {
287 return (std::find(mListTypes.begin(), mListTypes.end(), type) != mListTypes.end());
288}
289
Yifan Hong443df792017-05-09 18:49:45 -0700290void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700291 for (const auto& type : mListTypes) {
292 switch (type) {
293 case HalType::BINDERIZED_SERVICES:
294 f(mServicesTable); break;
295 case HalType::PASSTHROUGH_CLIENTS:
296 f(mPassthroughRefTable); break;
297 case HalType::PASSTHROUGH_LIBRARIES:
298 f(mImplementationsTable); break;
299 default:
300 LOG(FATAL) << __func__ << "Unknown HAL type.";
301 }
302 }
Yifan Hong443df792017-05-09 18:49:45 -0700303}
304void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
Nirav Atrecce988d2018-05-16 11:14:46 -0700305 for (const auto& type : mListTypes) {
306 switch (type) {
307 case HalType::BINDERIZED_SERVICES:
308 f(mServicesTable); break;
309 case HalType::PASSTHROUGH_CLIENTS:
310 f(mPassthroughRefTable); break;
311 case HalType::PASSTHROUGH_LIBRARIES:
312 f(mImplementationsTable); break;
313 default:
314 LOG(FATAL) << __func__ << "Unknown HAL type.";
315 }
316 }
Yifan Hong443df792017-05-09 18:49:45 -0700317}
318
319void ListCommand::postprocess() {
320 forEachTable([this](Table &table) {
321 if (mSortColumn) {
322 std::sort(table.begin(), table.end(), mSortColumn);
323 }
324 for (TableEntry &entry : table) {
325 entry.serverCmdline = getCmdline(entry.serverPid);
326 removeDeadProcesses(&entry.clientPids);
327 for (auto pid : entry.clientPids) {
328 entry.clientCmdlines.push_back(this->getCmdline(pid));
329 }
330 }
Yifan Hongf31aa052018-02-02 15:17:51 -0800331 for (TableEntry& entry : table) {
332 entry.partition = getPartition(entry.serverPid);
Yifan Hongbdf44f82018-05-25 14:20:00 -0700333 entry.vintfInfo = getVintfInfo(entry.interfaceName, {entry.transport, entry.arch});
Yifan Hongf31aa052018-02-02 15:17:51 -0800334 }
Yifan Hong443df792017-05-09 18:49:45 -0700335 });
336 // use a double for loop here because lshal doesn't care about efficiency.
337 for (TableEntry &packageEntry : mImplementationsTable) {
338 std::string packageName = packageEntry.interfaceName;
Steven Morelandd4f32b32018-03-06 14:47:58 -0800339 FQName fqPackageName;
340 if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700341 continue;
342 }
343 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700344 if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
Yifan Hong443df792017-05-09 18:49:45 -0700345 continue;
346 }
Steven Morelandd4f32b32018-03-06 14:47:58 -0800347 FQName interfaceName;
348 if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700349 continue;
350 }
351 if (interfaceName.getPackageAndVersion() == fqPackageName) {
352 interfaceEntry.arch = packageEntry.arch;
353 }
354 }
355 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700356
357 mServicesTable.setDescription(
358 "All binderized services (registered services through hwservicemanager)");
359 mPassthroughRefTable.setDescription(
360 "All interfaces that getService() has ever return as a passthrough interface;\n"
361 "PIDs / processes shown below might be inaccurate because the process\n"
362 "might have relinquished the interface or might have died.\n"
363 "The Server / Server CMD column can be ignored.\n"
364 "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
365 "the library and successfully fetched the passthrough implementation.");
366 mImplementationsTable.setDescription(
Steven Moreland3d2c1e12018-03-14 10:41:13 -0700367 "All available passthrough implementations (all -impl.so files).\n"
368 "These may return subclasses through their respective HIDL_FETCH_I* functions.");
Yifan Hong443df792017-05-09 18:49:45 -0700369}
370
Yifan Hongb2d096a2018-05-01 15:25:23 -0700371bool ListCommand::addEntryWithInstance(const TableEntry& entry,
372 vintf::HalManifest* manifest) const {
373 FqInstance fqInstance;
374 if (!fqInstance.setTo(entry.interfaceName)) {
375 err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
376 return false;
Yifan Hong77c87822017-06-19 15:47:39 -0700377 }
Yifan Hongb2d096a2018-05-01 15:25:23 -0700378
379 if (fqInstance.getPackage() == gIBaseFqName.package()) {
380 return true; // always remove IBase from manifest
381 }
382
383 Partition partition = resolvePartition(entry.partition, fqInstance);
384
385 if (partition == Partition::UNKNOWN) {
386 err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
387 << std::endl;
388 return false;
389 }
390
391 if (partition != mVintfPartition) {
392 return true; // strip out instances that is in a different partition.
393 }
394
Yifan Hongb2d096a2018-05-01 15:25:23 -0700395 vintf::Arch arch;
Yifan Hong8304e412018-05-25 15:05:36 -0700396 if (entry.transport == vintf::Transport::HWBINDER) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700397 arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
Yifan Hong8304e412018-05-25 15:05:36 -0700398 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700399 if (entry.arch == vintf::Arch::ARCH_EMPTY) {
400 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
401 return false;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700402 }
Yifan Hong0ad64f52018-05-25 15:29:17 -0700403 arch = entry.arch;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700404 } else {
405 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
406 return false;
407 }
408
409 std::string e;
Yifan Hong8304e412018-05-25 15:05:36 -0700410 if (!manifest->insertInstance(fqInstance, entry.transport, arch, vintf::HalFormat::HIDL, &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700411 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
412 return false;
413 }
414 return true;
415}
416
417bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
418 const vintf::HalManifest* manifest) const {
419 const auto& packageAndVersion = splitFirst(splitFirst(entry.interfaceName, ':').first, '@');
420 const auto& package = packageAndVersion.first;
421 vintf::Version version;
422 if (!vintf::parse(packageAndVersion.second, &version)) {
423 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
424 << entry.interfaceName << "'" << std::endl;
425 return false;
426 }
427
428 bool found = false;
429 (void)manifest->forEachInstanceOfVersion(package, version, [&found](const auto&) {
430 found = true;
431 return false; // break
432 });
433 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700434}
435
Yifan Hongca3b6602017-09-07 16:44:27 -0700436void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700437 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800438 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700439 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700440
441 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800442 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700443
Yifan Hongb2d096a2018-05-01 15:25:23 -0700444 std::vector<std::string> error;
445 for (const TableEntry& entry : mServicesTable)
446 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
447 for (const TableEntry& entry : mPassthroughRefTable)
448 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700449
Yifan Hongb2d096a2018-05-01 15:25:23 -0700450 std::vector<std::string> passthrough;
451 for (const TableEntry& entry : mImplementationsTable)
452 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800453
Yifan Hongf31aa052018-02-02 15:17:51 -0800454 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700455 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
456 << INIT_VINTF_NOTES;
457 if (!error.empty()) {
458 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
459 for (const auto& e : error) {
460 out << " " << e << std::endl;
461 }
462 }
463 if (!passthrough.empty()) {
464 out << std::endl
465 << " The following HALs are passthrough and no interface or instance " << std::endl
466 << " names can be inferred." << std::endl;
467 for (const auto& e : passthrough) {
468 out << " " << e << std::endl;
469 }
470 }
471 out << "-->" << std::endl;
472 out << vintf::gHalManifestConverter(manifest, vintf::SerializeFlag::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700473}
474
Yifan Hongf31aa052018-02-02 15:17:51 -0800475std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700476 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800477 " only hwbinder is shown.\n"
478 " 2. It is likely that HALs in passthrough transport does not have\n"
479 " <interface> declared; users will have to write them by hand.\n"
480 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
481 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700482 " 4. This output is intended for launch devices.\n"
483 " Upgrading devices should not use this tool to generate device\n"
484 " manifest and replace the existing manifest directly, but should\n"
485 " edit the existing manifest manually.\n"
486 " Specifically, devices which launched at Android O-MR1 or earlier\n"
487 " should not use the 'fqname' format for required HAL entries and\n"
488 " should instead use the legacy package, name, instance-name format\n"
489 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800490};
491
Yifan Hong0ad64f52018-05-25 15:29:17 -0700492static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
Yifan Hong443df792017-05-09 18:49:45 -0700493 switch (a) {
494 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700495 return vintf::Arch::ARCH_64;
Yifan Hong443df792017-05-09 18:49:45 -0700496 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700497 return vintf::Arch::ARCH_32;
Yifan Hong443df792017-05-09 18:49:45 -0700498 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
499 default:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700500 return vintf::Arch::ARCH_EMPTY;
Yifan Hong443df792017-05-09 18:49:45 -0700501 }
502}
503
Yifan Hongca3b6602017-09-07 16:44:27 -0700504void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700505 if (mNeat) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700506 MergedTable({&mServicesTable, &mPassthroughRefTable, &mImplementationsTable})
Yifan Hongca3b6602017-09-07 16:44:27 -0700507 .createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700508 return;
509 }
510
Yifan Hongca3b6602017-09-07 16:44:27 -0700511 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700512
Yifan Hongd4a77e82017-09-06 19:40:24 -0700513 // We're only interested in dumping debug info for already
514 // instantiated services. There's little value in dumping the
515 // debug info for a service we create on the fly, so we only operate
516 // on the "mServicesTable".
517 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
518 if (mEmitDebugInfo && &table == &mServicesTable) {
519 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700520 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700521 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800522 mLshal.emitDebugInfo(pair.first, pair.second, {},
523 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700524 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700525 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700526 };
Yifan Hong443df792017-05-09 18:49:45 -0700527 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700528 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
529 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700530 });
Yifan Hong443df792017-05-09 18:49:45 -0700531}
532
Yifan Hongca3b6602017-09-07 16:44:27 -0700533Status ListCommand::dump() {
534 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
535
536 if (mFileOutputPath.empty()) {
537 (*this.*dump)(out());
538 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700539 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700540
541 std::ofstream fileOutput(mFileOutputPath);
542 if (!fileOutput.is_open()) {
543 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
544 return IO_ERROR;
545 }
546 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
547
548 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
549
550 fileOutput.flush();
551 fileOutput.close();
552 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700553}
554
555void ListCommand::putEntry(TableEntrySource source, TableEntry &&entry) {
556 Table *table = nullptr;
557 switch (source) {
558 case HWSERVICEMANAGER_LIST :
559 table = &mServicesTable; break;
560 case PTSERVICEMANAGER_REG_CLIENT :
561 table = &mPassthroughRefTable; break;
562 case LIST_DLLIB :
563 table = &mImplementationsTable; break;
564 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700565 err() << "Error: Unknown source of entry " << source << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700566 }
567 if (table) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700568 table->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700569 }
570}
571
572Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700573 if (!shouldReportHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
574
Yifan Hong443df792017-05-09 18:49:45 -0700575 using namespace ::android::hardware;
576 using namespace ::android::hidl::manager::V1_0;
577 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700578 using std::literals::chrono_literals::operator""s;
Yifan Hongaf582192018-04-10 17:45:06 -0700579 auto ret = timeoutIPC(10s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700580 std::map<std::string, TableEntry> entries;
581 for (const auto &info : infos) {
582 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
583 std::string{info.instanceName.c_str()};
584 entries.emplace(interfaceName, TableEntry{
585 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700586 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700587 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700588 }).first->second.arch |= fromBaseArchitecture(info.arch);
589 }
590 for (auto &&pair : entries) {
591 putEntry(LIST_DLLIB, std::move(pair.second));
592 }
593 });
594 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700595 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700596 << ret.description() << std::endl;
597 return DUMP_ALL_LIBS_ERROR;
598 }
599 return OK;
600}
601
602Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700603 if (!shouldReportHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
604
Yifan Hong443df792017-05-09 18:49:45 -0700605 using namespace ::android::hardware;
606 using namespace ::android::hardware::details;
607 using namespace ::android::hidl::manager::V1_0;
608 using namespace ::android::hidl::base::V1_0;
609 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
610 for (const auto &info : infos) {
611 if (info.clientPids.size() <= 0) {
612 continue;
613 }
614 putEntry(PTSERVICEMANAGER_REG_CLIENT, {
615 .interfaceName =
616 std::string{info.interfaceName.c_str()} + "/" +
617 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700618 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700619 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700620 .clientPids = info.clientPids,
621 .arch = fromBaseArchitecture(info.arch)
622 });
623 }
624 });
625 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700626 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700627 << ret.description() << std::endl;
628 return DUMP_PASSTHROUGH_ERROR;
629 }
630 return OK;
631}
632
633Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700634 using vintf::operator<<;
635
Nirav Atrecce988d2018-05-16 11:14:46 -0700636 if (!shouldReportHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700637
Yifan Hong8304e412018-05-25 15:05:36 -0700638 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700639 hidl_vec<hidl_string> fqInstanceNames;
640 // copying out for timeoutIPC
641 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
642 fqInstanceNames = names;
643 });
644 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700645 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700646 << listRet.description() << std::endl;
647 return DUMP_BINDERIZED_ERROR;
648 }
649
650 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700651 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700652 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700653 // create entry and default assign all fields.
654 TableEntry& entry = allTableEntries[fqInstanceName];
655 entry.interfaceName = fqInstanceName;
656 entry.transport = mode;
657
658 status |= fetchBinderizedEntry(manager, &entry);
659 }
660
661 for (auto& pair : allTableEntries) {
662 putEntry(HWSERVICEMANAGER_LIST, std::move(pair.second));
663 }
664 return status;
665}
666
667Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
668 TableEntry *entry) {
669 Status status = OK;
670 const auto handleError = [&](Status additionalError, const std::string& msg) {
671 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
672 status |= DUMP_BINDERIZED_ERROR | additionalError;
673 };
674
675 const auto pair = splitFirst(entry->interfaceName, '/');
676 const auto &serviceName = pair.first;
677 const auto &instanceName = pair.second;
678 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
679 if (!getRet.isOk()) {
680 handleError(TRANSACTION_ERROR,
681 "cannot be fetched from service manager:" + getRet.description());
682 return status;
683 }
684 sp<IBase> service = getRet;
685 if (service == nullptr) {
686 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
687 return status;
688 }
689
690 // getDebugInfo
691 do {
692 DebugInfo debugInfo;
693 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
694 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700695 });
696 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700697 handleError(TRANSACTION_ERROR,
698 "debugging information cannot be retrieved: " + debugRet.description());
699 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700700 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700701
Yifan Hong22ea7b82017-09-14 18:07:43 -0700702 entry->serverPid = debugInfo.pid;
703 entry->serverObjectAddress = debugInfo.ptr;
704 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700705
Yifan Hong22ea7b82017-09-14 18:07:43 -0700706 if (debugInfo.pid != NO_PID) {
707 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
708 if (pidInfo == nullptr) {
709 handleError(IO_ERROR,
710 "no information for PID " + std::to_string(debugInfo.pid) +
711 ", are you root?");
712 break;
713 }
714 if (debugInfo.ptr != NO_PTR) {
715 auto it = pidInfo->refPids.find(debugInfo.ptr);
716 if (it != pidInfo->refPids.end()) {
717 entry->clientPids = it->second;
718 }
719 }
720 entry->threadUsage = pidInfo->threadUsage;
721 entry->threadCount = pidInfo->threadCount;
722 }
723 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700724
725 // hash
726 do {
727 ssize_t hashIndex = -1;
728 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
729 for (size_t i = 0; i < c.size(); ++i) {
730 if (serviceName == c[i]) {
731 hashIndex = static_cast<ssize_t>(i);
732 break;
733 }
734 }
735 });
736 if (!ifaceChainRet.isOk()) {
737 handleError(TRANSACTION_ERROR,
738 "interfaceChain fails: " + ifaceChainRet.description());
739 break; // skip getHashChain
740 }
741 if (hashIndex < 0) {
742 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
743 break; // skip getHashChain
744 }
745 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
746 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
747 handleError(BAD_IMPL,
748 "interfaceChain indicates position " + std::to_string(hashIndex) +
749 " but getHashChain returns " + std::to_string(hashChain.size()) +
750 " hashes");
751 return;
752 }
753
754 auto&& hashArray = hashChain[hashIndex];
755 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
756 entry->hash = Hash::hexString(hashVec);
757 });
758 if (!hashRet.isOk()) {
759 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
760 }
761 } while (0);
Yifan Hong443df792017-05-09 18:49:45 -0700762 return status;
763}
764
765Status ListCommand::fetch() {
766 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700767 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700768 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700769 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700770 status |= NO_BINDERIZED_MANAGER;
771 } else {
772 status |= fetchBinderized(bManager);
773 // Passthrough PIDs are registered to the binderized manager as well.
774 status |= fetchPassthrough(bManager);
775 }
776
Yifan Hong9881df92017-05-10 14:33:05 -0700777 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700778 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700779 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700780 status |= NO_PASSTHROUGH_MANAGER;
781 } else {
782 status |= fetchAllLibraries(pManager);
783 }
784 return status;
785}
786
Yifan Honga6b93f02017-09-13 16:53:37 -0700787void ListCommand::registerAllOptions() {
788 int v = mOptions.size();
789 // A list of acceptable command line options
790 // key: value returned by getopt_long
791 // long options with short alternatives
792 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
793 return USAGE;
794 }, ""});
795 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
796 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
797 return OK;
798 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700799 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
800 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
801 return OK;
Yifan Hong430f8982018-05-25 17:28:39 -0700802 }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700803 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
804 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
805 return OK;
806 }, "print the transport mode column"});
807 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
808 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
809 return OK;
810 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700811 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
812 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
813 return OK;
814 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700815 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
816 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
817 return OK;
818 }, "print the server PID, or server cmdline if -m is set"});
819 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
820 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
821 return OK;
822 }, "print the server object address column"});
823 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
824 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
825 return OK;
826 }, "print the client PIDs, or client cmdlines if -m is set"});
827 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
828 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
829 return OK;
830 }, "print currently used/available threads\n(note, available threads created lazily)"});
831 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
832 thiz->mEnableCmdlines = true;
833 return OK;
834 }, "print cmdline instead of PIDs"});
835 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
836 thiz->mEmitDebugInfo = true;
837 if (arg) thiz->mFileOutputPath = arg;
838 return OK;
839 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
840 "Writes to specified file if 'arg' is provided, otherwise stdout."});
841
Yifan Hongbdf44f82018-05-25 14:20:00 -0700842 mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
843 thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
844 return OK;
845 }, "print VINTF info. This column contains a comma-separated list of:\n"
846 " - DM: device manifest\n"
847 " - DC: device compatibility matrix\n"
848 " - FM: framework manifest\n"
849 " - FC: framework compatibility matrix"});
850
Yifan Honga6b93f02017-09-13 16:53:37 -0700851 // long options without short alternatives
852 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
853 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800854 if (thiz->mVintfPartition == Partition::UNKNOWN)
855 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700856 if (arg) thiz->mFileOutputPath = arg;
857 return OK;
858 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800859 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
860 if (!arg) return USAGE;
861 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
862 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
863 return OK;
864 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
865 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700866 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
867 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
868 thiz->mSortColumn = TableEntry::sortByInterfaceName;
869 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
870 thiz->mSortColumn = TableEntry::sortByServerPid;
871 } else {
872 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
873 return USAGE;
874 }
875 return OK;
876 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
877 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
878 thiz->mNeat = true;
879 return OK;
880 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Nirav Atrecce988d2018-05-16 11:14:46 -0700881 mOptions.push_back({'\0', "types", required_argument, v++, [](ListCommand* thiz, const char* arg) {
882 if (!arg) { return USAGE; }
883
884 static const std::map<std::string, HalType> kHalTypeMap {
885 {"binderized", HalType::BINDERIZED_SERVICES},
886 {"b", HalType::BINDERIZED_SERVICES},
887 {"passthrough_clients", HalType::PASSTHROUGH_CLIENTS},
888 {"c", HalType::PASSTHROUGH_CLIENTS},
889 {"passthrough_libs", HalType::PASSTHROUGH_LIBRARIES},
890 {"l", HalType::PASSTHROUGH_LIBRARIES}
891 };
892
893 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
894 for (const auto& halTypeArg : halTypesArgs) {
895 if (halTypeArg.empty()) continue;
896
897 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
898 if (halTypeIter == kHalTypeMap.end()) {
899
900 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
901 return USAGE;
902 }
903
904 // Append unique (non-repeated) HAL types to the reporting list
905 HalType halType = halTypeIter->second;
906 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
907 thiz->mListTypes.end()) {
908 thiz->mListTypes.push_back(halType);
909 }
910 }
911
912 if (thiz->mListTypes.empty()) { return USAGE; }
913 return OK;
914 }, "comma-separated list of one or more HAL types.\nThe output is restricted to the selected "
915 "association(s). Valid options\nare: (b|binderized), (c|passthrough_clients), and (l|"
916 "passthrough_libs).\nBy default, lists all available HALs."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700917}
918
919// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
920// the lifetime of "options" during the usage of the returned array.
921static std::unique_ptr<struct option[]> getLongOptions(
922 const ListCommand::RegisteredOptions& options,
923 int* longOptFlag) {
924 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
925 int i = 0;
926 for (const auto& e : options) {
927 ret[i].name = e.longOption.c_str();
928 ret[i].has_arg = e.hasArg;
929 ret[i].flag = longOptFlag;
930 ret[i].val = e.val;
931
932 i++;
933 }
934 // getopt_long last option has all zeros
935 ret[i].name = NULL;
936 ret[i].has_arg = 0;
937 ret[i].flag = NULL;
938 ret[i].val = 0;
939
940 return ret;
941}
942
943// Create 'optstring' argument to getopt_long.
944static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
945 std::stringstream ss;
946 for (const auto& e : options) {
947 if (e.shortOption != '\0') {
948 ss << e.shortOption;
949 }
950 }
951 return ss.str();
952}
953
Yifan Honga8bedc62017-09-08 18:00:31 -0700954Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700955 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -0700956
Yifan Honga6b93f02017-09-13 16:53:37 -0700957 if (mOptions.empty()) {
958 registerAllOptions();
959 }
960 int longOptFlag;
961 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
962 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700963
Yifan Honga8bedc62017-09-08 18:00:31 -0700964 // suppress output to std::err for unknown options
965 opterr = 0;
966
Yifan Hong443df792017-05-09 18:49:45 -0700967 int optionIndex;
968 int c;
969 // Lshal::parseArgs has set optind to the next option to parse
970 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700971 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700972 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700973 if (c == -1) {
974 break;
975 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700976 const RegisteredOption* found = nullptr;
977 if (c == 0) {
978 // see long option
979 for (const auto& e : mOptions) {
980 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700981 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700982 } else {
983 // see short option
984 for (const auto& e : mOptions) {
985 if (c == e.shortOption) found = &e;
986 }
Yifan Hong443df792017-05-09 18:49:45 -0700987 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700988
989 if (found == nullptr) {
990 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700991 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700992 return USAGE;
993 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700994
995 Status status = found->op(this, optarg);
996 if (status != OK) {
997 return status;
998 }
Yifan Hong443df792017-05-09 18:49:45 -0700999 }
1000 if (optind < arg.argc) {
1001 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -07001002 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001003 return USAGE;
1004 }
1005
1006 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -07001007 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001008 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -07001009 }
1010
Yifan Honga6b93f02017-09-13 16:53:37 -07001011 if (mSelectedColumns.empty()) {
Yifan Hongfee209d2017-09-14 18:23:38 -07001012 mSelectedColumns = {TableColumnType::RELEASED,
1013 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -07001014 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -07001015 }
Yifan Hongd4a77e82017-09-06 19:40:24 -07001016
Yifan Honga6b93f02017-09-13 16:53:37 -07001017 if (mEnableCmdlines) {
1018 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
1019 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
1020 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001021 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001022 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
1023 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001024 }
1025 }
1026 }
1027
Nirav Atrecce988d2018-05-16 11:14:46 -07001028 // By default, list all HAL types
1029 if (mListTypes.empty()) {
1030 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
1031 HalType::PASSTHROUGH_LIBRARIES};
1032 }
1033
Yifan Honga6b93f02017-09-13 16:53:37 -07001034 forEachTable([this] (Table& table) {
1035 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001036 });
1037
Yifan Hong443df792017-05-09 18:49:45 -07001038 return OK;
1039}
1040
Yifan Honga8bedc62017-09-08 18:00:31 -07001041Status ListCommand::main(const Arg &arg) {
1042 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -07001043 if (status != OK) {
1044 return status;
1045 }
1046 status = fetch();
1047 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -07001048 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -07001049 return status;
1050}
1051
Yifan Honga6b93f02017-09-13 16:53:37 -07001052const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
1053 static const std::string empty{};
1054 static const std::string optional{"[=<arg>]"};
1055 static const std::string required{"=<arg>"};
1056
1057 if (hasArg == optional_argument) {
1058 return optional;
1059 }
1060 if (hasArg == required_argument) {
1061 return required;
1062 }
1063 return empty;
1064}
1065
Yifan Honga8bedc62017-09-08 18:00:31 -07001066void ListCommand::usage() const {
1067
Yifan Honga6b93f02017-09-13 16:53:37 -07001068 err() << "list:" << std::endl
1069 << " lshal" << std::endl
1070 << " lshal list" << std::endl
Yifan Hongfee209d2017-09-14 18:23:38 -07001071 << " List all hals with default ordering and columns (`lshal list -riepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001072 << " lshal list [-h|--help]" << std::endl
1073 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1074 << " lshal [list] [OPTIONS...]" << std::endl;
1075 for (const auto& e : mOptions) {
1076 if (e.help.empty()) {
1077 continue;
1078 }
1079 err() << " ";
1080 if (e.shortOption != '\0')
1081 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1082 if (e.shortOption != '\0' && !e.longOption.empty())
1083 err() << ", ";
1084 if (!e.longOption.empty())
1085 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1086 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001087 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001088 for (const auto& line : lines) {
1089 if (&line != &lines.front())
1090 err() << " ";
1091 err() << line << std::endl;
1092 }
1093 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001094}
1095
Yifan Hong443df792017-05-09 18:49:45 -07001096} // namespace lshal
1097} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001098