blob: d497e5ccda5540cdca7b3974a9dd13d978f33f0f [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 Hongdb730532018-06-25 16:32:01 -0700290Table* ListCommand::tableForType(HalType type) {
291 switch (type) {
292 case HalType::BINDERIZED_SERVICES:
293 return &mServicesTable;
294 case HalType::PASSTHROUGH_CLIENTS:
295 return &mPassthroughRefTable;
296 case HalType::PASSTHROUGH_LIBRARIES:
297 return &mImplementationsTable;
298 default:
299 LOG(FATAL) << "Unknown HAL type " << static_cast<int64_t>(type);
300 return nullptr;
301 }
302}
303const Table* ListCommand::tableForType(HalType type) const {
304 return const_cast<ListCommand*>(this)->tableForType(type);
305}
306
Yifan Hong443df792017-05-09 18:49:45 -0700307void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700308 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700309 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700310 }
Yifan Hong443df792017-05-09 18:49:45 -0700311}
312void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
Nirav Atrecce988d2018-05-16 11:14:46 -0700313 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700314 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700315 }
Yifan Hong443df792017-05-09 18:49:45 -0700316}
317
318void ListCommand::postprocess() {
319 forEachTable([this](Table &table) {
320 if (mSortColumn) {
321 std::sort(table.begin(), table.end(), mSortColumn);
322 }
323 for (TableEntry &entry : table) {
324 entry.serverCmdline = getCmdline(entry.serverPid);
325 removeDeadProcesses(&entry.clientPids);
326 for (auto pid : entry.clientPids) {
327 entry.clientCmdlines.push_back(this->getCmdline(pid));
328 }
329 }
Yifan Hongf31aa052018-02-02 15:17:51 -0800330 for (TableEntry& entry : table) {
331 entry.partition = getPartition(entry.serverPid);
Yifan Hongbdf44f82018-05-25 14:20:00 -0700332 entry.vintfInfo = getVintfInfo(entry.interfaceName, {entry.transport, entry.arch});
Yifan Hongf31aa052018-02-02 15:17:51 -0800333 }
Yifan Hong443df792017-05-09 18:49:45 -0700334 });
335 // use a double for loop here because lshal doesn't care about efficiency.
336 for (TableEntry &packageEntry : mImplementationsTable) {
337 std::string packageName = packageEntry.interfaceName;
Steven Morelandd4f32b32018-03-06 14:47:58 -0800338 FQName fqPackageName;
339 if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700340 continue;
341 }
342 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700343 if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
Yifan Hong443df792017-05-09 18:49:45 -0700344 continue;
345 }
Steven Morelandd4f32b32018-03-06 14:47:58 -0800346 FQName interfaceName;
347 if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700348 continue;
349 }
350 if (interfaceName.getPackageAndVersion() == fqPackageName) {
351 interfaceEntry.arch = packageEntry.arch;
352 }
353 }
354 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700355
356 mServicesTable.setDescription(
357 "All binderized services (registered services through hwservicemanager)");
358 mPassthroughRefTable.setDescription(
359 "All interfaces that getService() has ever return as a passthrough interface;\n"
360 "PIDs / processes shown below might be inaccurate because the process\n"
361 "might have relinquished the interface or might have died.\n"
362 "The Server / Server CMD column can be ignored.\n"
363 "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
364 "the library and successfully fetched the passthrough implementation.");
365 mImplementationsTable.setDescription(
Steven Moreland3d2c1e12018-03-14 10:41:13 -0700366 "All available passthrough implementations (all -impl.so files).\n"
367 "These may return subclasses through their respective HIDL_FETCH_I* functions.");
Yifan Hong443df792017-05-09 18:49:45 -0700368}
369
Yifan Hongb2d096a2018-05-01 15:25:23 -0700370bool ListCommand::addEntryWithInstance(const TableEntry& entry,
371 vintf::HalManifest* manifest) const {
372 FqInstance fqInstance;
373 if (!fqInstance.setTo(entry.interfaceName)) {
374 err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
375 return false;
Yifan Hong77c87822017-06-19 15:47:39 -0700376 }
Yifan Hongb2d096a2018-05-01 15:25:23 -0700377
378 if (fqInstance.getPackage() == gIBaseFqName.package()) {
379 return true; // always remove IBase from manifest
380 }
381
382 Partition partition = resolvePartition(entry.partition, fqInstance);
383
384 if (partition == Partition::UNKNOWN) {
385 err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
386 << std::endl;
387 return false;
388 }
389
390 if (partition != mVintfPartition) {
391 return true; // strip out instances that is in a different partition.
392 }
393
Yifan Hongb2d096a2018-05-01 15:25:23 -0700394 vintf::Arch arch;
Yifan Hong8304e412018-05-25 15:05:36 -0700395 if (entry.transport == vintf::Transport::HWBINDER) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700396 arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
Yifan Hong8304e412018-05-25 15:05:36 -0700397 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700398 if (entry.arch == vintf::Arch::ARCH_EMPTY) {
399 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
400 return false;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700401 }
Yifan Hong0ad64f52018-05-25 15:29:17 -0700402 arch = entry.arch;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700403 } else {
404 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
405 return false;
406 }
407
408 std::string e;
Yifan Hong8304e412018-05-25 15:05:36 -0700409 if (!manifest->insertInstance(fqInstance, entry.transport, arch, vintf::HalFormat::HIDL, &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700410 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
411 return false;
412 }
413 return true;
414}
415
416bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
417 const vintf::HalManifest* manifest) const {
418 const auto& packageAndVersion = splitFirst(splitFirst(entry.interfaceName, ':').first, '@');
419 const auto& package = packageAndVersion.first;
420 vintf::Version version;
421 if (!vintf::parse(packageAndVersion.second, &version)) {
422 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
423 << entry.interfaceName << "'" << std::endl;
424 return false;
425 }
426
427 bool found = false;
428 (void)manifest->forEachInstanceOfVersion(package, version, [&found](const auto&) {
429 found = true;
430 return false; // break
431 });
432 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700433}
434
Yifan Hongca3b6602017-09-07 16:44:27 -0700435void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700436 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800437 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700438 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700439
440 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800441 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700442
Yifan Hongb2d096a2018-05-01 15:25:23 -0700443 std::vector<std::string> error;
444 for (const TableEntry& entry : mServicesTable)
445 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
446 for (const TableEntry& entry : mPassthroughRefTable)
447 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700448
Yifan Hongb2d096a2018-05-01 15:25:23 -0700449 std::vector<std::string> passthrough;
450 for (const TableEntry& entry : mImplementationsTable)
451 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800452
Yifan Hongf31aa052018-02-02 15:17:51 -0800453 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700454 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
455 << INIT_VINTF_NOTES;
456 if (!error.empty()) {
457 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
458 for (const auto& e : error) {
459 out << " " << e << std::endl;
460 }
461 }
462 if (!passthrough.empty()) {
463 out << std::endl
464 << " The following HALs are passthrough and no interface or instance " << std::endl
465 << " names can be inferred." << std::endl;
466 for (const auto& e : passthrough) {
467 out << " " << e << std::endl;
468 }
469 }
470 out << "-->" << std::endl;
471 out << vintf::gHalManifestConverter(manifest, vintf::SerializeFlag::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700472}
473
Yifan Hongf31aa052018-02-02 15:17:51 -0800474std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700475 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800476 " only hwbinder is shown.\n"
477 " 2. It is likely that HALs in passthrough transport does not have\n"
478 " <interface> declared; users will have to write them by hand.\n"
479 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
480 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700481 " 4. This output is intended for launch devices.\n"
482 " Upgrading devices should not use this tool to generate device\n"
483 " manifest and replace the existing manifest directly, but should\n"
484 " edit the existing manifest manually.\n"
485 " Specifically, devices which launched at Android O-MR1 or earlier\n"
486 " should not use the 'fqname' format for required HAL entries and\n"
487 " should instead use the legacy package, name, instance-name format\n"
488 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800489};
490
Yifan Hong0ad64f52018-05-25 15:29:17 -0700491static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
Yifan Hong443df792017-05-09 18:49:45 -0700492 switch (a) {
493 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700494 return vintf::Arch::ARCH_64;
Yifan Hong443df792017-05-09 18:49:45 -0700495 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700496 return vintf::Arch::ARCH_32;
Yifan Hong443df792017-05-09 18:49:45 -0700497 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
498 default:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700499 return vintf::Arch::ARCH_EMPTY;
Yifan Hong443df792017-05-09 18:49:45 -0700500 }
501}
502
Yifan Hongca3b6602017-09-07 16:44:27 -0700503void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700504 if (mNeat) {
Yifan Hongb72f19e2018-06-27 16:58:56 -0700505 std::vector<const Table*> tables;
506 forEachTable([&tables](const Table &table) {
507 tables.push_back(&table);
508 });
509 MergedTable(std::move(tables)).createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700510 return;
511 }
512
Yifan Hongca3b6602017-09-07 16:44:27 -0700513 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700514
Yifan Hongd4a77e82017-09-06 19:40:24 -0700515 // We're only interested in dumping debug info for already
516 // instantiated services. There's little value in dumping the
517 // debug info for a service we create on the fly, so we only operate
518 // on the "mServicesTable".
519 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
520 if (mEmitDebugInfo && &table == &mServicesTable) {
521 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700522 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700523 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800524 mLshal.emitDebugInfo(pair.first, pair.second, {},
525 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700526 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700527 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700528 };
Yifan Hong443df792017-05-09 18:49:45 -0700529 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700530 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
531 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700532 });
Yifan Hong443df792017-05-09 18:49:45 -0700533}
534
Yifan Hongca3b6602017-09-07 16:44:27 -0700535Status ListCommand::dump() {
536 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
537
538 if (mFileOutputPath.empty()) {
539 (*this.*dump)(out());
540 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700541 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700542
543 std::ofstream fileOutput(mFileOutputPath);
544 if (!fileOutput.is_open()) {
545 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
546 return IO_ERROR;
547 }
548 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
549
550 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
551
552 fileOutput.flush();
553 fileOutput.close();
554 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700555}
556
Yifan Hong20f4ee82018-06-25 16:21:29 -0700557void ListCommand::putEntry(HalType type, TableEntry &&entry) {
Yifan Hongdb730532018-06-25 16:32:01 -0700558 tableForType(type)->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700559}
560
561Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700562 if (!shouldReportHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
563
Yifan Hong443df792017-05-09 18:49:45 -0700564 using namespace ::android::hardware;
565 using namespace ::android::hidl::manager::V1_0;
566 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700567 using std::literals::chrono_literals::operator""s;
568 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700569 std::map<std::string, TableEntry> entries;
570 for (const auto &info : infos) {
571 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
572 std::string{info.instanceName.c_str()};
573 entries.emplace(interfaceName, TableEntry{
574 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700575 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700576 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700577 }).first->second.arch |= fromBaseArchitecture(info.arch);
578 }
579 for (auto &&pair : entries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700580 putEntry(HalType::PASSTHROUGH_LIBRARIES, std::move(pair.second));
Yifan Hong443df792017-05-09 18:49:45 -0700581 }
582 });
583 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700584 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700585 << ret.description() << std::endl;
586 return DUMP_ALL_LIBS_ERROR;
587 }
588 return OK;
589}
590
591Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700592 if (!shouldReportHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
593
Yifan Hong443df792017-05-09 18:49:45 -0700594 using namespace ::android::hardware;
595 using namespace ::android::hardware::details;
596 using namespace ::android::hidl::manager::V1_0;
597 using namespace ::android::hidl::base::V1_0;
598 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
599 for (const auto &info : infos) {
600 if (info.clientPids.size() <= 0) {
601 continue;
602 }
Yifan Hong20f4ee82018-06-25 16:21:29 -0700603 putEntry(HalType::PASSTHROUGH_CLIENTS, {
Yifan Hong443df792017-05-09 18:49:45 -0700604 .interfaceName =
605 std::string{info.interfaceName.c_str()} + "/" +
606 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700607 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700608 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700609 .clientPids = info.clientPids,
610 .arch = fromBaseArchitecture(info.arch)
611 });
612 }
613 });
614 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700615 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700616 << ret.description() << std::endl;
617 return DUMP_PASSTHROUGH_ERROR;
618 }
619 return OK;
620}
621
622Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700623 using vintf::operator<<;
624
Nirav Atrecce988d2018-05-16 11:14:46 -0700625 if (!shouldReportHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700626
Yifan Hong8304e412018-05-25 15:05:36 -0700627 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700628 hidl_vec<hidl_string> fqInstanceNames;
629 // copying out for timeoutIPC
630 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
631 fqInstanceNames = names;
632 });
633 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700634 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700635 << listRet.description() << std::endl;
636 return DUMP_BINDERIZED_ERROR;
637 }
638
639 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700640 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700641 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700642 // create entry and default assign all fields.
643 TableEntry& entry = allTableEntries[fqInstanceName];
644 entry.interfaceName = fqInstanceName;
645 entry.transport = mode;
646
647 status |= fetchBinderizedEntry(manager, &entry);
648 }
649
650 for (auto& pair : allTableEntries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700651 putEntry(HalType::BINDERIZED_SERVICES, std::move(pair.second));
Yifan Hong22ea7b82017-09-14 18:07:43 -0700652 }
653 return status;
654}
655
656Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
657 TableEntry *entry) {
658 Status status = OK;
659 const auto handleError = [&](Status additionalError, const std::string& msg) {
660 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
661 status |= DUMP_BINDERIZED_ERROR | additionalError;
662 };
663
664 const auto pair = splitFirst(entry->interfaceName, '/');
665 const auto &serviceName = pair.first;
666 const auto &instanceName = pair.second;
667 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
668 if (!getRet.isOk()) {
669 handleError(TRANSACTION_ERROR,
670 "cannot be fetched from service manager:" + getRet.description());
671 return status;
672 }
673 sp<IBase> service = getRet;
674 if (service == nullptr) {
675 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
676 return status;
677 }
678
679 // getDebugInfo
680 do {
681 DebugInfo debugInfo;
682 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
683 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700684 });
685 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700686 handleError(TRANSACTION_ERROR,
687 "debugging information cannot be retrieved: " + debugRet.description());
688 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700689 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700690
Yifan Hong22ea7b82017-09-14 18:07:43 -0700691 entry->serverPid = debugInfo.pid;
692 entry->serverObjectAddress = debugInfo.ptr;
693 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700694
Yifan Hong22ea7b82017-09-14 18:07:43 -0700695 if (debugInfo.pid != NO_PID) {
696 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
697 if (pidInfo == nullptr) {
698 handleError(IO_ERROR,
699 "no information for PID " + std::to_string(debugInfo.pid) +
700 ", are you root?");
701 break;
702 }
703 if (debugInfo.ptr != NO_PTR) {
704 auto it = pidInfo->refPids.find(debugInfo.ptr);
705 if (it != pidInfo->refPids.end()) {
706 entry->clientPids = it->second;
707 }
708 }
709 entry->threadUsage = pidInfo->threadUsage;
710 entry->threadCount = pidInfo->threadCount;
711 }
712 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700713
714 // hash
715 do {
716 ssize_t hashIndex = -1;
717 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
718 for (size_t i = 0; i < c.size(); ++i) {
719 if (serviceName == c[i]) {
720 hashIndex = static_cast<ssize_t>(i);
721 break;
722 }
723 }
724 });
725 if (!ifaceChainRet.isOk()) {
726 handleError(TRANSACTION_ERROR,
727 "interfaceChain fails: " + ifaceChainRet.description());
728 break; // skip getHashChain
729 }
730 if (hashIndex < 0) {
731 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
732 break; // skip getHashChain
733 }
734 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
735 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
736 handleError(BAD_IMPL,
737 "interfaceChain indicates position " + std::to_string(hashIndex) +
738 " but getHashChain returns " + std::to_string(hashChain.size()) +
739 " hashes");
740 return;
741 }
742
743 auto&& hashArray = hashChain[hashIndex];
744 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
745 entry->hash = Hash::hexString(hashVec);
746 });
747 if (!hashRet.isOk()) {
748 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
749 }
750 } while (0);
Yifan Hong443df792017-05-09 18:49:45 -0700751 return status;
752}
753
754Status ListCommand::fetch() {
755 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700756 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700757 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700758 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700759 status |= NO_BINDERIZED_MANAGER;
760 } else {
761 status |= fetchBinderized(bManager);
762 // Passthrough PIDs are registered to the binderized manager as well.
763 status |= fetchPassthrough(bManager);
764 }
765
Yifan Hong9881df92017-05-10 14:33:05 -0700766 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700767 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700768 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700769 status |= NO_PASSTHROUGH_MANAGER;
770 } else {
771 status |= fetchAllLibraries(pManager);
772 }
773 return status;
774}
775
Yifan Honga6b93f02017-09-13 16:53:37 -0700776void ListCommand::registerAllOptions() {
777 int v = mOptions.size();
778 // A list of acceptable command line options
779 // key: value returned by getopt_long
780 // long options with short alternatives
781 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
782 return USAGE;
783 }, ""});
784 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
785 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
786 return OK;
787 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700788 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
789 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
790 return OK;
Yifan Hong430f8982018-05-25 17:28:39 -0700791 }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700792 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
793 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
794 return OK;
795 }, "print the transport mode column"});
796 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
797 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
798 return OK;
799 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700800 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
801 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
802 return OK;
803 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700804 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
805 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
806 return OK;
807 }, "print the server PID, or server cmdline if -m is set"});
808 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
809 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
810 return OK;
811 }, "print the server object address column"});
812 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
813 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
814 return OK;
815 }, "print the client PIDs, or client cmdlines if -m is set"});
816 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
817 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
818 return OK;
819 }, "print currently used/available threads\n(note, available threads created lazily)"});
820 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
821 thiz->mEnableCmdlines = true;
822 return OK;
823 }, "print cmdline instead of PIDs"});
824 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
825 thiz->mEmitDebugInfo = true;
826 if (arg) thiz->mFileOutputPath = arg;
827 return OK;
828 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
829 "Writes to specified file if 'arg' is provided, otherwise stdout."});
830
Yifan Hongbdf44f82018-05-25 14:20:00 -0700831 mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
832 thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
833 return OK;
834 }, "print VINTF info. This column contains a comma-separated list of:\n"
835 " - DM: device manifest\n"
836 " - DC: device compatibility matrix\n"
837 " - FM: framework manifest\n"
838 " - FC: framework compatibility matrix"});
839
Yifan Honga6b93f02017-09-13 16:53:37 -0700840 // long options without short alternatives
841 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
842 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800843 if (thiz->mVintfPartition == Partition::UNKNOWN)
844 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700845 if (arg) thiz->mFileOutputPath = arg;
846 return OK;
847 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800848 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
849 if (!arg) return USAGE;
850 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
851 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
852 return OK;
853 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
854 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700855 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
856 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
857 thiz->mSortColumn = TableEntry::sortByInterfaceName;
858 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
859 thiz->mSortColumn = TableEntry::sortByServerPid;
860 } else {
861 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
862 return USAGE;
863 }
864 return OK;
865 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
866 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
867 thiz->mNeat = true;
868 return OK;
869 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Nirav Atrecce988d2018-05-16 11:14:46 -0700870 mOptions.push_back({'\0', "types", required_argument, v++, [](ListCommand* thiz, const char* arg) {
871 if (!arg) { return USAGE; }
872
873 static const std::map<std::string, HalType> kHalTypeMap {
874 {"binderized", HalType::BINDERIZED_SERVICES},
875 {"b", HalType::BINDERIZED_SERVICES},
876 {"passthrough_clients", HalType::PASSTHROUGH_CLIENTS},
877 {"c", HalType::PASSTHROUGH_CLIENTS},
878 {"passthrough_libs", HalType::PASSTHROUGH_LIBRARIES},
879 {"l", HalType::PASSTHROUGH_LIBRARIES}
880 };
881
882 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
883 for (const auto& halTypeArg : halTypesArgs) {
884 if (halTypeArg.empty()) continue;
885
886 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
887 if (halTypeIter == kHalTypeMap.end()) {
888
889 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
890 return USAGE;
891 }
892
893 // Append unique (non-repeated) HAL types to the reporting list
894 HalType halType = halTypeIter->second;
895 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
896 thiz->mListTypes.end()) {
897 thiz->mListTypes.push_back(halType);
898 }
899 }
900
901 if (thiz->mListTypes.empty()) { return USAGE; }
902 return OK;
903 }, "comma-separated list of one or more HAL types.\nThe output is restricted to the selected "
904 "association(s). Valid options\nare: (b|binderized), (c|passthrough_clients), and (l|"
905 "passthrough_libs).\nBy default, lists all available HALs."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700906}
907
908// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
909// the lifetime of "options" during the usage of the returned array.
910static std::unique_ptr<struct option[]> getLongOptions(
911 const ListCommand::RegisteredOptions& options,
912 int* longOptFlag) {
913 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
914 int i = 0;
915 for (const auto& e : options) {
916 ret[i].name = e.longOption.c_str();
917 ret[i].has_arg = e.hasArg;
918 ret[i].flag = longOptFlag;
919 ret[i].val = e.val;
920
921 i++;
922 }
923 // getopt_long last option has all zeros
924 ret[i].name = NULL;
925 ret[i].has_arg = 0;
926 ret[i].flag = NULL;
927 ret[i].val = 0;
928
929 return ret;
930}
931
932// Create 'optstring' argument to getopt_long.
933static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
934 std::stringstream ss;
935 for (const auto& e : options) {
936 if (e.shortOption != '\0') {
937 ss << e.shortOption;
938 }
939 }
940 return ss.str();
941}
942
Yifan Honga8bedc62017-09-08 18:00:31 -0700943Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700944 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -0700945
Yifan Honga6b93f02017-09-13 16:53:37 -0700946 if (mOptions.empty()) {
947 registerAllOptions();
948 }
949 int longOptFlag;
950 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
951 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700952
Yifan Honga8bedc62017-09-08 18:00:31 -0700953 // suppress output to std::err for unknown options
954 opterr = 0;
955
Yifan Hong443df792017-05-09 18:49:45 -0700956 int optionIndex;
957 int c;
958 // Lshal::parseArgs has set optind to the next option to parse
959 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700960 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700961 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700962 if (c == -1) {
963 break;
964 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700965 const RegisteredOption* found = nullptr;
966 if (c == 0) {
967 // see long option
968 for (const auto& e : mOptions) {
969 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700970 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700971 } else {
972 // see short option
973 for (const auto& e : mOptions) {
974 if (c == e.shortOption) found = &e;
975 }
Yifan Hong443df792017-05-09 18:49:45 -0700976 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700977
978 if (found == nullptr) {
979 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700980 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700981 return USAGE;
982 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700983
984 Status status = found->op(this, optarg);
985 if (status != OK) {
986 return status;
987 }
Yifan Hong443df792017-05-09 18:49:45 -0700988 }
989 if (optind < arg.argc) {
990 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700991 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700992 return USAGE;
993 }
994
995 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700996 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700997 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700998 }
999
Yifan Honga6b93f02017-09-13 16:53:37 -07001000 if (mSelectedColumns.empty()) {
Yifan Hongfee209d2017-09-14 18:23:38 -07001001 mSelectedColumns = {TableColumnType::RELEASED,
1002 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -07001003 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -07001004 }
Yifan Hongd4a77e82017-09-06 19:40:24 -07001005
Yifan Honga6b93f02017-09-13 16:53:37 -07001006 if (mEnableCmdlines) {
1007 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
1008 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
1009 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001010 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001011 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
1012 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001013 }
1014 }
1015 }
1016
Nirav Atrecce988d2018-05-16 11:14:46 -07001017 // By default, list all HAL types
1018 if (mListTypes.empty()) {
1019 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
1020 HalType::PASSTHROUGH_LIBRARIES};
1021 }
1022
Yifan Honga6b93f02017-09-13 16:53:37 -07001023 forEachTable([this] (Table& table) {
1024 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001025 });
1026
Yifan Hong443df792017-05-09 18:49:45 -07001027 return OK;
1028}
1029
Yifan Honga8bedc62017-09-08 18:00:31 -07001030Status ListCommand::main(const Arg &arg) {
1031 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -07001032 if (status != OK) {
1033 return status;
1034 }
1035 status = fetch();
1036 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -07001037 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -07001038 return status;
1039}
1040
Yifan Honga6b93f02017-09-13 16:53:37 -07001041const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
1042 static const std::string empty{};
1043 static const std::string optional{"[=<arg>]"};
1044 static const std::string required{"=<arg>"};
1045
1046 if (hasArg == optional_argument) {
1047 return optional;
1048 }
1049 if (hasArg == required_argument) {
1050 return required;
1051 }
1052 return empty;
1053}
1054
Yifan Honga8bedc62017-09-08 18:00:31 -07001055void ListCommand::usage() const {
1056
Yifan Honga6b93f02017-09-13 16:53:37 -07001057 err() << "list:" << std::endl
1058 << " lshal" << std::endl
1059 << " lshal list" << std::endl
Yifan Hongaa864572018-06-26 13:27:29 -07001060 << " List all hals with default ordering and columns (`lshal list -liepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001061 << " lshal list [-h|--help]" << std::endl
1062 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1063 << " lshal [list] [OPTIONS...]" << std::endl;
1064 for (const auto& e : mOptions) {
1065 if (e.help.empty()) {
1066 continue;
1067 }
1068 err() << " ";
1069 if (e.shortOption != '\0')
1070 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1071 if (e.shortOption != '\0' && !e.longOption.empty())
1072 err() << ", ";
1073 if (!e.longOption.empty())
1074 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1075 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001076 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001077 for (const auto& line : lines) {
1078 if (&line != &lines.front())
1079 err() << " ";
1080 err() << line << std::endl;
1081 }
1082 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001083}
1084
Yifan Hong443df792017-05-09 18:49:45 -07001085} // namespace lshal
1086} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001087