blob: c68d1972de42bb2caf00d8dd9b3706b7522aa8ca [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 Hongd4a77e82017-09-06 19:40:24 -0700505 MergedTable({&mServicesTable, &mPassthroughRefTable, &mImplementationsTable})
Yifan Hongca3b6602017-09-07 16:44:27 -0700506 .createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700507 return;
508 }
509
Yifan Hongca3b6602017-09-07 16:44:27 -0700510 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700511
Yifan Hongd4a77e82017-09-06 19:40:24 -0700512 // We're only interested in dumping debug info for already
513 // instantiated services. There's little value in dumping the
514 // debug info for a service we create on the fly, so we only operate
515 // on the "mServicesTable".
516 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
517 if (mEmitDebugInfo && &table == &mServicesTable) {
518 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700519 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700520 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800521 mLshal.emitDebugInfo(pair.first, pair.second, {},
522 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700523 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700524 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700525 };
Yifan Hong443df792017-05-09 18:49:45 -0700526 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700527 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
528 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700529 });
Yifan Hong443df792017-05-09 18:49:45 -0700530}
531
Yifan Hongca3b6602017-09-07 16:44:27 -0700532Status ListCommand::dump() {
533 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
534
535 if (mFileOutputPath.empty()) {
536 (*this.*dump)(out());
537 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700538 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700539
540 std::ofstream fileOutput(mFileOutputPath);
541 if (!fileOutput.is_open()) {
542 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
543 return IO_ERROR;
544 }
545 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
546
547 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
548
549 fileOutput.flush();
550 fileOutput.close();
551 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700552}
553
Yifan Hong20f4ee82018-06-25 16:21:29 -0700554void ListCommand::putEntry(HalType type, TableEntry &&entry) {
Yifan Hongdb730532018-06-25 16:32:01 -0700555 tableForType(type)->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700556}
557
558Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700559 if (!shouldReportHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
560
Yifan Hong443df792017-05-09 18:49:45 -0700561 using namespace ::android::hardware;
562 using namespace ::android::hidl::manager::V1_0;
563 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700564 using std::literals::chrono_literals::operator""s;
565 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700566 std::map<std::string, TableEntry> entries;
567 for (const auto &info : infos) {
568 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
569 std::string{info.instanceName.c_str()};
570 entries.emplace(interfaceName, TableEntry{
571 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700572 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700573 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700574 }).first->second.arch |= fromBaseArchitecture(info.arch);
575 }
576 for (auto &&pair : entries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700577 putEntry(HalType::PASSTHROUGH_LIBRARIES, std::move(pair.second));
Yifan Hong443df792017-05-09 18:49:45 -0700578 }
579 });
580 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700581 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700582 << ret.description() << std::endl;
583 return DUMP_ALL_LIBS_ERROR;
584 }
585 return OK;
586}
587
588Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700589 if (!shouldReportHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
590
Yifan Hong443df792017-05-09 18:49:45 -0700591 using namespace ::android::hardware;
592 using namespace ::android::hardware::details;
593 using namespace ::android::hidl::manager::V1_0;
594 using namespace ::android::hidl::base::V1_0;
595 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
596 for (const auto &info : infos) {
597 if (info.clientPids.size() <= 0) {
598 continue;
599 }
Yifan Hong20f4ee82018-06-25 16:21:29 -0700600 putEntry(HalType::PASSTHROUGH_CLIENTS, {
Yifan Hong443df792017-05-09 18:49:45 -0700601 .interfaceName =
602 std::string{info.interfaceName.c_str()} + "/" +
603 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700604 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700605 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700606 .clientPids = info.clientPids,
607 .arch = fromBaseArchitecture(info.arch)
608 });
609 }
610 });
611 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700612 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700613 << ret.description() << std::endl;
614 return DUMP_PASSTHROUGH_ERROR;
615 }
616 return OK;
617}
618
619Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700620 using vintf::operator<<;
621
Nirav Atrecce988d2018-05-16 11:14:46 -0700622 if (!shouldReportHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700623
Yifan Hong8304e412018-05-25 15:05:36 -0700624 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700625 hidl_vec<hidl_string> fqInstanceNames;
626 // copying out for timeoutIPC
627 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
628 fqInstanceNames = names;
629 });
630 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700631 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700632 << listRet.description() << std::endl;
633 return DUMP_BINDERIZED_ERROR;
634 }
635
636 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700637 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700638 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700639 // create entry and default assign all fields.
640 TableEntry& entry = allTableEntries[fqInstanceName];
641 entry.interfaceName = fqInstanceName;
642 entry.transport = mode;
643
644 status |= fetchBinderizedEntry(manager, &entry);
645 }
646
647 for (auto& pair : allTableEntries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700648 putEntry(HalType::BINDERIZED_SERVICES, std::move(pair.second));
Yifan Hong22ea7b82017-09-14 18:07:43 -0700649 }
650 return status;
651}
652
653Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
654 TableEntry *entry) {
655 Status status = OK;
656 const auto handleError = [&](Status additionalError, const std::string& msg) {
657 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
658 status |= DUMP_BINDERIZED_ERROR | additionalError;
659 };
660
661 const auto pair = splitFirst(entry->interfaceName, '/');
662 const auto &serviceName = pair.first;
663 const auto &instanceName = pair.second;
664 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
665 if (!getRet.isOk()) {
666 handleError(TRANSACTION_ERROR,
667 "cannot be fetched from service manager:" + getRet.description());
668 return status;
669 }
670 sp<IBase> service = getRet;
671 if (service == nullptr) {
672 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
673 return status;
674 }
675
676 // getDebugInfo
677 do {
678 DebugInfo debugInfo;
679 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
680 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700681 });
682 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700683 handleError(TRANSACTION_ERROR,
684 "debugging information cannot be retrieved: " + debugRet.description());
685 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700686 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700687
Yifan Hong22ea7b82017-09-14 18:07:43 -0700688 entry->serverPid = debugInfo.pid;
689 entry->serverObjectAddress = debugInfo.ptr;
690 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700691
Yifan Hong22ea7b82017-09-14 18:07:43 -0700692 if (debugInfo.pid != NO_PID) {
693 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
694 if (pidInfo == nullptr) {
695 handleError(IO_ERROR,
696 "no information for PID " + std::to_string(debugInfo.pid) +
697 ", are you root?");
698 break;
699 }
700 if (debugInfo.ptr != NO_PTR) {
701 auto it = pidInfo->refPids.find(debugInfo.ptr);
702 if (it != pidInfo->refPids.end()) {
703 entry->clientPids = it->second;
704 }
705 }
706 entry->threadUsage = pidInfo->threadUsage;
707 entry->threadCount = pidInfo->threadCount;
708 }
709 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700710
711 // hash
712 do {
713 ssize_t hashIndex = -1;
714 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
715 for (size_t i = 0; i < c.size(); ++i) {
716 if (serviceName == c[i]) {
717 hashIndex = static_cast<ssize_t>(i);
718 break;
719 }
720 }
721 });
722 if (!ifaceChainRet.isOk()) {
723 handleError(TRANSACTION_ERROR,
724 "interfaceChain fails: " + ifaceChainRet.description());
725 break; // skip getHashChain
726 }
727 if (hashIndex < 0) {
728 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
729 break; // skip getHashChain
730 }
731 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
732 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
733 handleError(BAD_IMPL,
734 "interfaceChain indicates position " + std::to_string(hashIndex) +
735 " but getHashChain returns " + std::to_string(hashChain.size()) +
736 " hashes");
737 return;
738 }
739
740 auto&& hashArray = hashChain[hashIndex];
741 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
742 entry->hash = Hash::hexString(hashVec);
743 });
744 if (!hashRet.isOk()) {
745 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
746 }
747 } while (0);
Yifan Hong443df792017-05-09 18:49:45 -0700748 return status;
749}
750
751Status ListCommand::fetch() {
752 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700753 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700754 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700755 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700756 status |= NO_BINDERIZED_MANAGER;
757 } else {
758 status |= fetchBinderized(bManager);
759 // Passthrough PIDs are registered to the binderized manager as well.
760 status |= fetchPassthrough(bManager);
761 }
762
Yifan Hong9881df92017-05-10 14:33:05 -0700763 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700764 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700765 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700766 status |= NO_PASSTHROUGH_MANAGER;
767 } else {
768 status |= fetchAllLibraries(pManager);
769 }
770 return status;
771}
772
Yifan Honga6b93f02017-09-13 16:53:37 -0700773void ListCommand::registerAllOptions() {
774 int v = mOptions.size();
775 // A list of acceptable command line options
776 // key: value returned by getopt_long
777 // long options with short alternatives
778 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
779 return USAGE;
780 }, ""});
781 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
782 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
783 return OK;
784 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700785 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
786 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
787 return OK;
Yifan Hong430f8982018-05-25 17:28:39 -0700788 }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700789 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
790 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
791 return OK;
792 }, "print the transport mode column"});
793 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
794 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
795 return OK;
796 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700797 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
798 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
799 return OK;
800 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700801 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
802 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
803 return OK;
804 }, "print the server PID, or server cmdline if -m is set"});
805 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
806 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
807 return OK;
808 }, "print the server object address column"});
809 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
810 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
811 return OK;
812 }, "print the client PIDs, or client cmdlines if -m is set"});
813 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
814 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
815 return OK;
816 }, "print currently used/available threads\n(note, available threads created lazily)"});
817 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
818 thiz->mEnableCmdlines = true;
819 return OK;
820 }, "print cmdline instead of PIDs"});
821 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
822 thiz->mEmitDebugInfo = true;
823 if (arg) thiz->mFileOutputPath = arg;
824 return OK;
825 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
826 "Writes to specified file if 'arg' is provided, otherwise stdout."});
827
Yifan Hongbdf44f82018-05-25 14:20:00 -0700828 mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
829 thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
830 return OK;
831 }, "print VINTF info. This column contains a comma-separated list of:\n"
832 " - DM: device manifest\n"
833 " - DC: device compatibility matrix\n"
834 " - FM: framework manifest\n"
835 " - FC: framework compatibility matrix"});
836
Yifan Honga6b93f02017-09-13 16:53:37 -0700837 // long options without short alternatives
838 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
839 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800840 if (thiz->mVintfPartition == Partition::UNKNOWN)
841 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700842 if (arg) thiz->mFileOutputPath = arg;
843 return OK;
844 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800845 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
846 if (!arg) return USAGE;
847 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
848 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
849 return OK;
850 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
851 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700852 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
853 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
854 thiz->mSortColumn = TableEntry::sortByInterfaceName;
855 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
856 thiz->mSortColumn = TableEntry::sortByServerPid;
857 } else {
858 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
859 return USAGE;
860 }
861 return OK;
862 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
863 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
864 thiz->mNeat = true;
865 return OK;
866 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Nirav Atrecce988d2018-05-16 11:14:46 -0700867 mOptions.push_back({'\0', "types", required_argument, v++, [](ListCommand* thiz, const char* arg) {
868 if (!arg) { return USAGE; }
869
870 static const std::map<std::string, HalType> kHalTypeMap {
871 {"binderized", HalType::BINDERIZED_SERVICES},
872 {"b", HalType::BINDERIZED_SERVICES},
873 {"passthrough_clients", HalType::PASSTHROUGH_CLIENTS},
874 {"c", HalType::PASSTHROUGH_CLIENTS},
875 {"passthrough_libs", HalType::PASSTHROUGH_LIBRARIES},
876 {"l", HalType::PASSTHROUGH_LIBRARIES}
877 };
878
879 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
880 for (const auto& halTypeArg : halTypesArgs) {
881 if (halTypeArg.empty()) continue;
882
883 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
884 if (halTypeIter == kHalTypeMap.end()) {
885
886 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
887 return USAGE;
888 }
889
890 // Append unique (non-repeated) HAL types to the reporting list
891 HalType halType = halTypeIter->second;
892 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
893 thiz->mListTypes.end()) {
894 thiz->mListTypes.push_back(halType);
895 }
896 }
897
898 if (thiz->mListTypes.empty()) { return USAGE; }
899 return OK;
900 }, "comma-separated list of one or more HAL types.\nThe output is restricted to the selected "
901 "association(s). Valid options\nare: (b|binderized), (c|passthrough_clients), and (l|"
902 "passthrough_libs).\nBy default, lists all available HALs."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700903}
904
905// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
906// the lifetime of "options" during the usage of the returned array.
907static std::unique_ptr<struct option[]> getLongOptions(
908 const ListCommand::RegisteredOptions& options,
909 int* longOptFlag) {
910 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
911 int i = 0;
912 for (const auto& e : options) {
913 ret[i].name = e.longOption.c_str();
914 ret[i].has_arg = e.hasArg;
915 ret[i].flag = longOptFlag;
916 ret[i].val = e.val;
917
918 i++;
919 }
920 // getopt_long last option has all zeros
921 ret[i].name = NULL;
922 ret[i].has_arg = 0;
923 ret[i].flag = NULL;
924 ret[i].val = 0;
925
926 return ret;
927}
928
929// Create 'optstring' argument to getopt_long.
930static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
931 std::stringstream ss;
932 for (const auto& e : options) {
933 if (e.shortOption != '\0') {
934 ss << e.shortOption;
935 }
936 }
937 return ss.str();
938}
939
Yifan Honga8bedc62017-09-08 18:00:31 -0700940Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700941 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -0700942
Yifan Honga6b93f02017-09-13 16:53:37 -0700943 if (mOptions.empty()) {
944 registerAllOptions();
945 }
946 int longOptFlag;
947 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
948 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700949
Yifan Honga8bedc62017-09-08 18:00:31 -0700950 // suppress output to std::err for unknown options
951 opterr = 0;
952
Yifan Hong443df792017-05-09 18:49:45 -0700953 int optionIndex;
954 int c;
955 // Lshal::parseArgs has set optind to the next option to parse
956 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700957 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700958 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700959 if (c == -1) {
960 break;
961 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700962 const RegisteredOption* found = nullptr;
963 if (c == 0) {
964 // see long option
965 for (const auto& e : mOptions) {
966 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700967 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700968 } else {
969 // see short option
970 for (const auto& e : mOptions) {
971 if (c == e.shortOption) found = &e;
972 }
Yifan Hong443df792017-05-09 18:49:45 -0700973 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700974
975 if (found == nullptr) {
976 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700977 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700978 return USAGE;
979 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700980
981 Status status = found->op(this, optarg);
982 if (status != OK) {
983 return status;
984 }
Yifan Hong443df792017-05-09 18:49:45 -0700985 }
986 if (optind < arg.argc) {
987 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700988 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700989 return USAGE;
990 }
991
992 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700993 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700994 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700995 }
996
Yifan Honga6b93f02017-09-13 16:53:37 -0700997 if (mSelectedColumns.empty()) {
Yifan Hongfee209d2017-09-14 18:23:38 -0700998 mSelectedColumns = {TableColumnType::RELEASED,
999 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -07001000 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -07001001 }
Yifan Hongd4a77e82017-09-06 19:40:24 -07001002
Yifan Honga6b93f02017-09-13 16:53:37 -07001003 if (mEnableCmdlines) {
1004 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
1005 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
1006 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001007 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001008 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
1009 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001010 }
1011 }
1012 }
1013
Nirav Atrecce988d2018-05-16 11:14:46 -07001014 // By default, list all HAL types
1015 if (mListTypes.empty()) {
1016 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
1017 HalType::PASSTHROUGH_LIBRARIES};
1018 }
1019
Yifan Honga6b93f02017-09-13 16:53:37 -07001020 forEachTable([this] (Table& table) {
1021 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001022 });
1023
Yifan Hong443df792017-05-09 18:49:45 -07001024 return OK;
1025}
1026
Yifan Honga8bedc62017-09-08 18:00:31 -07001027Status ListCommand::main(const Arg &arg) {
1028 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -07001029 if (status != OK) {
1030 return status;
1031 }
1032 status = fetch();
1033 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -07001034 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -07001035 return status;
1036}
1037
Yifan Honga6b93f02017-09-13 16:53:37 -07001038const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
1039 static const std::string empty{};
1040 static const std::string optional{"[=<arg>]"};
1041 static const std::string required{"=<arg>"};
1042
1043 if (hasArg == optional_argument) {
1044 return optional;
1045 }
1046 if (hasArg == required_argument) {
1047 return required;
1048 }
1049 return empty;
1050}
1051
Yifan Honga8bedc62017-09-08 18:00:31 -07001052void ListCommand::usage() const {
1053
Yifan Honga6b93f02017-09-13 16:53:37 -07001054 err() << "list:" << std::endl
1055 << " lshal" << std::endl
1056 << " lshal list" << std::endl
Yifan Hongaa864572018-06-26 13:27:29 -07001057 << " List all hals with default ordering and columns (`lshal list -liepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001058 << " lshal list [-h|--help]" << std::endl
1059 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1060 << " lshal [list] [OPTIONS...]" << std::endl;
1061 for (const auto& e : mOptions) {
1062 if (e.help.empty()) {
1063 continue;
1064 }
1065 err() << " ";
1066 if (e.shortOption != '\0')
1067 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1068 if (e.shortOption != '\0' && !e.longOption.empty())
1069 err() << ", ";
1070 if (!e.longOption.empty())
1071 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1072 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001073 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001074 for (const auto& line : lines) {
1075 if (&line != &lines.front())
1076 err() << " ";
1077 err() << line << std::endl;
1078 }
1079 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001080}
1081
Yifan Hong443df792017-05-09 18:49:45 -07001082} // namespace lshal
1083} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001084