blob: 2722e214e8e7c3f9551f1a315dd6a9b82b6e53b2 [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/hidl/manager/1.0/IServiceManager.h>
Yifan Hongfee209d2017-09-14 18:23:38 -070033#include <hidl-hash/Hash.h>
Yifan Hong443df792017-05-09 18:49:45 -070034#include <hidl-util/FQName.h>
35#include <private/android_filesystem_config.h>
36#include <sys/stat.h>
37#include <vintf/HalManifest.h>
Yifan Hongf31aa052018-02-02 15:17:51 -080038#include <vintf/parse_string.h>
Yifan Hong443df792017-05-09 18:49:45 -070039#include <vintf/parse_xml.h>
40
41#include "Lshal.h"
42#include "PipeRelay.h"
43#include "Timeout.h"
44#include "utils.h"
45
46using ::android::hardware::hidl_string;
Yifan Hong22ea7b82017-09-14 18:07:43 -070047using ::android::hardware::hidl_vec;
48using ::android::hidl::base::V1_0::DebugInfo;
49using ::android::hidl::base::V1_0::IBase;
Yifan Hong443df792017-05-09 18:49:45 -070050using ::android::hidl::manager::V1_0::IServiceManager;
51
52namespace android {
53namespace lshal {
54
Yifan Hongf31aa052018-02-02 15:17:51 -080055vintf::SchemaType toSchemaType(Partition p) {
56 return (p == Partition::SYSTEM) ? vintf::SchemaType::FRAMEWORK : vintf::SchemaType::DEVICE;
57}
58
Yifan Hong13ba0a92018-06-25 16:15:56 -070059Partition toPartition(vintf::SchemaType t) {
60 switch (t) {
61 case vintf::SchemaType::FRAMEWORK: return Partition::SYSTEM;
62 // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
63 case vintf::SchemaType::DEVICE: return Partition::VENDOR;
64 }
65 return Partition::UNKNOWN;
66}
67
68std::string getPackageAndVersion(const std::string& fqInstance) {
69 return splitFirst(fqInstance, ':').first;
70}
71
Yifan Hong76ac14a2017-09-08 14:59:04 -070072NullableOStream<std::ostream> ListCommand::out() const {
73 return mLshal.out();
74}
75
76NullableOStream<std::ostream> ListCommand::err() const {
77 return mLshal.err();
Yifan Hong443df792017-05-09 18:49:45 -070078}
79
Yifan Hong795b6ec2017-09-13 11:25:28 -070080std::string ListCommand::GetName() {
81 return "list";
82}
83std::string ListCommand::getSimpleDescription() const {
Steven Morelanddbbbc652021-02-02 23:02:38 +000084 return "List HIDL HALs.";
Yifan Hong795b6ec2017-09-13 11:25:28 -070085}
86
Yifan Hong8bf73162017-09-07 18:06:13 -070087std::string ListCommand::parseCmdline(pid_t pid) const {
Yifan Hongf31aa052018-02-02 15:17:51 -080088 return android::procpartition::getCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -070089}
90
91const std::string &ListCommand::getCmdline(pid_t pid) {
Yifan Hong13ba0a92018-06-25 16:15:56 -070092 static const std::string kEmptyString{};
93 if (pid == NO_PID) return kEmptyString;
Yifan Hong443df792017-05-09 18:49:45 -070094 auto pair = mCmdlines.find(pid);
95 if (pair != mCmdlines.end()) {
96 return pair->second;
97 }
Yifan Hong8bf73162017-09-07 18:06:13 -070098 mCmdlines[pid] = parseCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -070099 return mCmdlines[pid];
100}
101
102void ListCommand::removeDeadProcesses(Pids *pids) {
103 static const pid_t myPid = getpid();
Yifan Hong61fb7bc2017-05-12 16:33:57 -0700104 pids->erase(std::remove_if(pids->begin(), pids->end(), [this](auto pid) {
Yifan Hong443df792017-05-09 18:49:45 -0700105 return pid == myPid || this->getCmdline(pid).empty();
Yifan Hong61fb7bc2017-05-12 16:33:57 -0700106 }), pids->end());
Yifan Hong443df792017-05-09 18:49:45 -0700107}
108
Yifan Hongf31aa052018-02-02 15:17:51 -0800109Partition ListCommand::getPartition(pid_t pid) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700110 if (pid == NO_PID) return Partition::UNKNOWN;
Yifan Hongf31aa052018-02-02 15:17:51 -0800111 auto it = mPartitions.find(pid);
112 if (it != mPartitions.end()) {
113 return it->second;
114 }
115 Partition partition = android::procpartition::getPartition(pid);
116 mPartitions.emplace(pid, partition);
117 return partition;
118}
119
120// Give sensible defaults when nothing can be inferred from runtime.
121// process: Partition inferred from executable location or cmdline.
Yifan Hongb2d096a2018-05-01 15:25:23 -0700122Partition ListCommand::resolvePartition(Partition process, const FqInstance& fqInstance) const {
123 if (fqInstance.inPackage("vendor") || fqInstance.inPackage("com")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800124 return Partition::VENDOR;
125 }
126
Yifan Hongb2d096a2018-05-01 15:25:23 -0700127 if (fqInstance.inPackage("android.frameworks") || fqInstance.inPackage("android.system") ||
128 fqInstance.inPackage("android.hidl")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800129 return Partition::SYSTEM;
130 }
131
132 // Some android.hardware HALs are served from system. Check the value from executable
133 // location / cmdline first.
Yifan Hongb2d096a2018-05-01 15:25:23 -0700134 if (fqInstance.inPackage("android.hardware")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800135 if (process != Partition::UNKNOWN) {
136 return process;
137 }
138 return Partition::VENDOR;
139 }
140
141 return process;
142}
143
Yifan Hongbdf44f82018-05-25 14:20:00 -0700144bool match(const vintf::ManifestInstance& instance, const FqInstance& fqInstance,
145 vintf::TransportArch ta) {
146 // For hwbinder libs, allow missing arch in manifest.
147 // For passthrough libs, allow missing interface/instance in table.
148 return (ta.transport == instance.transport()) &&
149 (ta.transport == vintf::Transport::HWBINDER ||
150 vintf::contains(instance.arch(), ta.arch)) &&
151 (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
152 (!fqInstance.hasInstance() || fqInstance.getInstance() == instance.instance());
153}
154
155bool match(const vintf::MatrixInstance& instance, const FqInstance& fqInstance,
156 vintf::TransportArch /* ta */) {
157 return (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
158 (!fqInstance.hasInstance() || instance.matchInstance(fqInstance.getInstance()));
159}
160
161template <typename ObjectType>
162VintfInfo getVintfInfo(const std::shared_ptr<const ObjectType>& object,
163 const FqInstance& fqInstance, vintf::TransportArch ta, VintfInfo value) {
164 bool found = false;
Yifan Hongc346a162019-09-10 19:35:55 -0700165 (void)object->forEachHidlInstanceOfVersion(fqInstance.getPackage(), fqInstance.getVersion(),
166 [&](const auto& instance) {
167 found = match(instance, fqInstance, ta);
168 return !found; // continue if not found
169 });
Yifan Hongbdf44f82018-05-25 14:20:00 -0700170 return found ? value : VINTF_INFO_EMPTY;
171}
172
173std::shared_ptr<const vintf::HalManifest> ListCommand::getDeviceManifest() const {
174 return vintf::VintfObject::GetDeviceHalManifest();
175}
176
177std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getDeviceMatrix() const {
178 return vintf::VintfObject::GetDeviceCompatibilityMatrix();
179}
180
181std::shared_ptr<const vintf::HalManifest> ListCommand::getFrameworkManifest() const {
182 return vintf::VintfObject::GetFrameworkHalManifest();
183}
184
185std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getFrameworkMatrix() const {
186 return vintf::VintfObject::GetFrameworkCompatibilityMatrix();
187}
188
189VintfInfo ListCommand::getVintfInfo(const std::string& fqInstanceName,
190 vintf::TransportArch ta) const {
191 FqInstance fqInstance;
192 if (!fqInstance.setTo(fqInstanceName) &&
193 // Ignore interface / instance for passthrough libs
Yifan Hong13ba0a92018-06-25 16:15:56 -0700194 !fqInstance.setTo(getPackageAndVersion(fqInstanceName))) {
Yifan Hongbdf44f82018-05-25 14:20:00 -0700195 err() << "Warning: Cannot parse '" << fqInstanceName << "'; no VINTF info." << std::endl;
196 return VINTF_INFO_EMPTY;
197 }
198
199 return lshal::getVintfInfo(getDeviceManifest(), fqInstance, ta, DEVICE_MANIFEST) |
200 lshal::getVintfInfo(getFrameworkManifest(), fqInstance, ta, FRAMEWORK_MANIFEST) |
201 lshal::getVintfInfo(getDeviceMatrix(), fqInstance, ta, DEVICE_MATRIX) |
202 lshal::getVintfInfo(getFrameworkMatrix(), fqInstance, ta, FRAMEWORK_MATRIX);
203}
204
Steven Morelandd8e20192017-05-24 11:23:08 -0700205bool ListCommand::getPidInfo(
Devin Moorec03e3aa2020-12-11 15:11:17 -0800206 pid_t serverPid, BinderPidInfo *pidInfo) const {
207 const auto& status = getBinderPidInfo(BinderDebugContext::HWBINDER, serverPid, pidInfo);
208 return status == OK;
Steven Morelandd8e20192017-05-24 11:23:08 -0700209}
210
Devin Moorec03e3aa2020-12-11 15:11:17 -0800211const BinderPidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
212 auto pair = mCachedPidInfos.insert({serverPid, BinderPidInfo{}});
Yifan Hong1243dde2017-09-14 17:49:30 -0700213 if (pair.second /* did insertion take place? */) {
214 if (!getPidInfo(serverPid, &pair.first->second)) {
215 return nullptr;
216 }
217 }
218 return &pair.first->second;
219}
220
Yifan Hong13ba0a92018-06-25 16:15:56 -0700221bool ListCommand::shouldFetchHalType(const HalType &type) const {
222 return (std::find(mFetchTypes.begin(), mFetchTypes.end(), type) != mFetchTypes.end());
Nirav Atrecce988d2018-05-16 11:14:46 -0700223}
224
Yifan Hongdb730532018-06-25 16:32:01 -0700225Table* ListCommand::tableForType(HalType type) {
226 switch (type) {
227 case HalType::BINDERIZED_SERVICES:
228 return &mServicesTable;
229 case HalType::PASSTHROUGH_CLIENTS:
230 return &mPassthroughRefTable;
231 case HalType::PASSTHROUGH_LIBRARIES:
232 return &mImplementationsTable;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700233 case HalType::VINTF_MANIFEST:
234 return &mManifestHalsTable;
Yifan Hong3212f172018-06-28 12:39:50 -0700235 case HalType::LAZY_HALS:
236 return &mLazyHalsTable;
Yifan Hongdb730532018-06-25 16:32:01 -0700237 default:
238 LOG(FATAL) << "Unknown HAL type " << static_cast<int64_t>(type);
239 return nullptr;
240 }
241}
242const Table* ListCommand::tableForType(HalType type) const {
243 return const_cast<ListCommand*>(this)->tableForType(type);
Yifan Hong443df792017-05-09 18:49:45 -0700244}
245
246void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700247 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700248 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700249 }
Yifan Hong443df792017-05-09 18:49:45 -0700250}
251void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
Nirav Atrecce988d2018-05-16 11:14:46 -0700252 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700253 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700254 }
Yifan Hong443df792017-05-09 18:49:45 -0700255}
256
257void ListCommand::postprocess() {
258 forEachTable([this](Table &table) {
259 if (mSortColumn) {
260 std::sort(table.begin(), table.end(), mSortColumn);
261 }
262 for (TableEntry &entry : table) {
263 entry.serverCmdline = getCmdline(entry.serverPid);
264 removeDeadProcesses(&entry.clientPids);
265 for (auto pid : entry.clientPids) {
266 entry.clientCmdlines.push_back(this->getCmdline(pid));
267 }
268 }
Yifan Hongf31aa052018-02-02 15:17:51 -0800269 for (TableEntry& entry : table) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700270 if (entry.partition == Partition::UNKNOWN) {
271 entry.partition = getPartition(entry.serverPid);
272 }
Yifan Hongbdf44f82018-05-25 14:20:00 -0700273 entry.vintfInfo = getVintfInfo(entry.interfaceName, {entry.transport, entry.arch});
Yifan Hongf31aa052018-02-02 15:17:51 -0800274 }
Yifan Hong443df792017-05-09 18:49:45 -0700275 });
276 // use a double for loop here because lshal doesn't care about efficiency.
277 for (TableEntry &packageEntry : mImplementationsTable) {
278 std::string packageName = packageEntry.interfaceName;
Steven Morelandd4f32b32018-03-06 14:47:58 -0800279 FQName fqPackageName;
280 if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700281 continue;
282 }
283 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700284 if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
Yifan Hong443df792017-05-09 18:49:45 -0700285 continue;
286 }
Steven Morelandd4f32b32018-03-06 14:47:58 -0800287 FQName interfaceName;
288 if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700289 continue;
290 }
291 if (interfaceName.getPackageAndVersion() == fqPackageName) {
292 interfaceEntry.arch = packageEntry.arch;
293 }
294 }
295 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700296
297 mServicesTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000298 "| All HIDL binderized services (registered with hwservicemanager)");
Yifan Hongca3b6602017-09-07 16:44:27 -0700299 mPassthroughRefTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000300 "| All HIDL interfaces getService() has ever returned as a passthrough interface;\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800301 "| PIDs / processes shown below might be inaccurate because the process\n"
302 "| might have relinquished the interface or might have died.\n"
303 "| The Server / Server CMD column can be ignored.\n"
304 "| The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
305 "| the library and successfully fetched the passthrough implementation.");
Yifan Hongca3b6602017-09-07 16:44:27 -0700306 mImplementationsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000307 "| All available HIDL passthrough implementations (all -impl.so files).\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800308 "| These may return subclasses through their respective HIDL_FETCH_I* functions.");
Yifan Hong13ba0a92018-06-25 16:15:56 -0700309 mManifestHalsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000310 "| All HIDL HALs that are in VINTF manifest.");
Yifan Hong3212f172018-06-28 12:39:50 -0700311 mLazyHalsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000312 "| All HIDL HALs that are declared in VINTF manifest:\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800313 "| - as hwbinder HALs but are not registered to hwservicemanager, and\n"
314 "| - as hwbinder/passthrough HALs with no implementation.");
Yifan Hong443df792017-05-09 18:49:45 -0700315}
316
Yifan Hongb2d096a2018-05-01 15:25:23 -0700317bool ListCommand::addEntryWithInstance(const TableEntry& entry,
318 vintf::HalManifest* manifest) const {
319 FqInstance fqInstance;
320 if (!fqInstance.setTo(entry.interfaceName)) {
321 err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
322 return false;
Yifan Hong77c87822017-06-19 15:47:39 -0700323 }
Yifan Hongb2d096a2018-05-01 15:25:23 -0700324
Steven Moreland7a99e042020-02-26 13:16:34 -0800325 if (fqInstance.getPackage() == "android.hidl.base") {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700326 return true; // always remove IBase from manifest
327 }
328
329 Partition partition = resolvePartition(entry.partition, fqInstance);
330
331 if (partition == Partition::UNKNOWN) {
332 err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
333 << std::endl;
334 return false;
335 }
336
337 if (partition != mVintfPartition) {
338 return true; // strip out instances that is in a different partition.
339 }
340
Yifan Hongb2d096a2018-05-01 15:25:23 -0700341 vintf::Arch arch;
Yifan Hong8304e412018-05-25 15:05:36 -0700342 if (entry.transport == vintf::Transport::HWBINDER) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700343 arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
Yifan Hong8304e412018-05-25 15:05:36 -0700344 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700345 if (entry.arch == vintf::Arch::ARCH_EMPTY) {
346 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
347 return false;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700348 }
Yifan Hong0ad64f52018-05-25 15:29:17 -0700349 arch = entry.arch;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700350 } else {
351 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
352 return false;
353 }
354
355 std::string e;
Yifan Hong8304e412018-05-25 15:05:36 -0700356 if (!manifest->insertInstance(fqInstance, entry.transport, arch, vintf::HalFormat::HIDL, &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700357 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
358 return false;
359 }
360 return true;
361}
362
363bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
364 const vintf::HalManifest* manifest) const {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700365 const auto& packageAndVersion = splitFirst(getPackageAndVersion(entry.interfaceName), '@');
Yifan Hongb2d096a2018-05-01 15:25:23 -0700366 const auto& package = packageAndVersion.first;
367 vintf::Version version;
368 if (!vintf::parse(packageAndVersion.second, &version)) {
369 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
370 << entry.interfaceName << "'" << std::endl;
371 return false;
372 }
373
374 bool found = false;
Yifan Hongc346a162019-09-10 19:35:55 -0700375 (void)manifest->forEachHidlInstanceOfVersion(package, version, [&found](const auto&) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700376 found = true;
377 return false; // break
378 });
379 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700380}
381
Yifan Hongca3b6602017-09-07 16:44:27 -0700382void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700383 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800384 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700385 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700386
387 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800388 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700389
Yifan Hongb2d096a2018-05-01 15:25:23 -0700390 std::vector<std::string> error;
391 for (const TableEntry& entry : mServicesTable)
392 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
393 for (const TableEntry& entry : mPassthroughRefTable)
394 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700395 for (const TableEntry& entry : mManifestHalsTable)
396 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700397
Yifan Hongb2d096a2018-05-01 15:25:23 -0700398 std::vector<std::string> passthrough;
399 for (const TableEntry& entry : mImplementationsTable)
400 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800401
Yifan Hongf31aa052018-02-02 15:17:51 -0800402 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700403 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
404 << INIT_VINTF_NOTES;
405 if (!error.empty()) {
406 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
407 for (const auto& e : error) {
408 out << " " << e << std::endl;
409 }
410 }
411 if (!passthrough.empty()) {
412 out << std::endl
413 << " The following HALs are passthrough and no interface or instance " << std::endl
414 << " names can be inferred." << std::endl;
415 for (const auto& e : passthrough) {
416 out << " " << e << std::endl;
417 }
418 }
419 out << "-->" << std::endl;
Yifan Honga96f87f2021-04-16 18:59:27 -0700420 out << vintf::toXml(manifest, vintf::SerializeFlags::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700421}
422
Yifan Hongf31aa052018-02-02 15:17:51 -0800423std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700424 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800425 " only hwbinder is shown.\n"
426 " 2. It is likely that HALs in passthrough transport does not have\n"
427 " <interface> declared; users will have to write them by hand.\n"
428 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
429 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700430 " 4. This output is intended for launch devices.\n"
431 " Upgrading devices should not use this tool to generate device\n"
432 " manifest and replace the existing manifest directly, but should\n"
433 " edit the existing manifest manually.\n"
434 " Specifically, devices which launched at Android O-MR1 or earlier\n"
435 " should not use the 'fqname' format for required HAL entries and\n"
436 " should instead use the legacy package, name, instance-name format\n"
437 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800438};
439
Yifan Hong0ad64f52018-05-25 15:29:17 -0700440static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
Yifan Hong443df792017-05-09 18:49:45 -0700441 switch (a) {
442 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700443 return vintf::Arch::ARCH_64;
Yifan Hong443df792017-05-09 18:49:45 -0700444 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700445 return vintf::Arch::ARCH_32;
Yifan Hong443df792017-05-09 18:49:45 -0700446 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
447 default:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700448 return vintf::Arch::ARCH_EMPTY;
Yifan Hong443df792017-05-09 18:49:45 -0700449 }
450}
451
Yifan Hongca3b6602017-09-07 16:44:27 -0700452void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700453 if (mNeat) {
Yifan Hongb72f19e2018-06-27 16:58:56 -0700454 std::vector<const Table*> tables;
455 forEachTable([&tables](const Table &table) {
456 tables.push_back(&table);
457 });
458 MergedTable(std::move(tables)).createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700459 return;
460 }
461
Yifan Hongca3b6602017-09-07 16:44:27 -0700462 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700463
Yifan Hongd4a77e82017-09-06 19:40:24 -0700464 // We're only interested in dumping debug info for already
465 // instantiated services. There's little value in dumping the
466 // debug info for a service we create on the fly, so we only operate
467 // on the "mServicesTable".
468 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
469 if (mEmitDebugInfo && &table == &mServicesTable) {
470 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700471 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700472 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800473 mLshal.emitDebugInfo(pair.first, pair.second, {},
Yifan Hong6884b872020-07-09 16:38:18 -0700474 ParentDebugInfoLevel::FQNAME_ONLY, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700475 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700476 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700477 };
Yifan Hong443df792017-05-09 18:49:45 -0700478 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700479 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
480 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700481 });
Yifan Hong443df792017-05-09 18:49:45 -0700482}
483
Yifan Hongca3b6602017-09-07 16:44:27 -0700484Status ListCommand::dump() {
485 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
486
487 if (mFileOutputPath.empty()) {
488 (*this.*dump)(out());
489 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700490 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700491
492 std::ofstream fileOutput(mFileOutputPath);
493 if (!fileOutput.is_open()) {
494 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
495 return IO_ERROR;
496 }
497 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
498
499 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
500
501 fileOutput.flush();
502 fileOutput.close();
503 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700504}
505
Yifan Hong20f4ee82018-06-25 16:21:29 -0700506void ListCommand::putEntry(HalType type, TableEntry &&entry) {
Yifan Hongdb730532018-06-25 16:32:01 -0700507 tableForType(type)->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700508}
509
510Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700511 if (!shouldFetchHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700512
Yifan Hong443df792017-05-09 18:49:45 -0700513 using namespace ::android::hardware;
514 using namespace ::android::hidl::manager::V1_0;
515 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700516 using std::literals::chrono_literals::operator""s;
Yifan Hongaf582192018-04-10 17:45:06 -0700517 auto ret = timeoutIPC(10s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700518 std::map<std::string, TableEntry> entries;
519 for (const auto &info : infos) {
520 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
521 std::string{info.instanceName.c_str()};
522 entries.emplace(interfaceName, TableEntry{
523 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700524 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700525 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700526 }).first->second.arch |= fromBaseArchitecture(info.arch);
527 }
528 for (auto &&pair : entries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700529 putEntry(HalType::PASSTHROUGH_LIBRARIES, std::move(pair.second));
Yifan Hong443df792017-05-09 18:49:45 -0700530 }
531 });
532 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700533 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700534 << ret.description() << std::endl;
535 return DUMP_ALL_LIBS_ERROR;
536 }
537 return OK;
538}
539
540Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700541 if (!shouldFetchHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700542
Yifan Hong443df792017-05-09 18:49:45 -0700543 using namespace ::android::hardware;
544 using namespace ::android::hardware::details;
545 using namespace ::android::hidl::manager::V1_0;
546 using namespace ::android::hidl::base::V1_0;
547 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
548 for (const auto &info : infos) {
549 if (info.clientPids.size() <= 0) {
550 continue;
551 }
Yifan Hong20f4ee82018-06-25 16:21:29 -0700552 putEntry(HalType::PASSTHROUGH_CLIENTS, {
Yifan Hong443df792017-05-09 18:49:45 -0700553 .interfaceName =
554 std::string{info.interfaceName.c_str()} + "/" +
555 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700556 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700557 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700558 .clientPids = info.clientPids,
559 .arch = fromBaseArchitecture(info.arch)
560 });
561 }
562 });
563 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700564 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700565 << ret.description() << std::endl;
566 return DUMP_PASSTHROUGH_ERROR;
567 }
568 return OK;
569}
570
571Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700572 using vintf::operator<<;
573
Yifan Hong13ba0a92018-06-25 16:15:56 -0700574 if (!shouldFetchHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700575
Yifan Hong8304e412018-05-25 15:05:36 -0700576 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700577 hidl_vec<hidl_string> fqInstanceNames;
578 // copying out for timeoutIPC
579 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
580 fqInstanceNames = names;
581 });
582 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700583 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700584 << listRet.description() << std::endl;
585 return DUMP_BINDERIZED_ERROR;
586 }
587
588 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700589 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700590 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700591 // create entry and default assign all fields.
592 TableEntry& entry = allTableEntries[fqInstanceName];
593 entry.interfaceName = fqInstanceName;
594 entry.transport = mode;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700595 entry.serviceStatus = ServiceStatus::NON_RESPONSIVE;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700596
597 status |= fetchBinderizedEntry(manager, &entry);
598 }
599
600 for (auto& pair : allTableEntries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700601 putEntry(HalType::BINDERIZED_SERVICES, std::move(pair.second));
Yifan Hong22ea7b82017-09-14 18:07:43 -0700602 }
603 return status;
604}
605
606Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
607 TableEntry *entry) {
608 Status status = OK;
609 const auto handleError = [&](Status additionalError, const std::string& msg) {
610 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
611 status |= DUMP_BINDERIZED_ERROR | additionalError;
612 };
613
614 const auto pair = splitFirst(entry->interfaceName, '/');
615 const auto &serviceName = pair.first;
616 const auto &instanceName = pair.second;
617 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
618 if (!getRet.isOk()) {
619 handleError(TRANSACTION_ERROR,
620 "cannot be fetched from service manager:" + getRet.description());
621 return status;
622 }
623 sp<IBase> service = getRet;
624 if (service == nullptr) {
625 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
626 return status;
627 }
628
629 // getDebugInfo
630 do {
631 DebugInfo debugInfo;
632 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
633 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700634 });
635 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700636 handleError(TRANSACTION_ERROR,
637 "debugging information cannot be retrieved: " + debugRet.description());
638 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700639 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700640
Yifan Hong22ea7b82017-09-14 18:07:43 -0700641 entry->serverPid = debugInfo.pid;
642 entry->serverObjectAddress = debugInfo.ptr;
643 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700644
Yifan Hong22ea7b82017-09-14 18:07:43 -0700645 if (debugInfo.pid != NO_PID) {
Devin Moorec03e3aa2020-12-11 15:11:17 -0800646 const BinderPidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
Yifan Hong22ea7b82017-09-14 18:07:43 -0700647 if (pidInfo == nullptr) {
648 handleError(IO_ERROR,
649 "no information for PID " + std::to_string(debugInfo.pid) +
650 ", are you root?");
651 break;
652 }
653 if (debugInfo.ptr != NO_PTR) {
654 auto it = pidInfo->refPids.find(debugInfo.ptr);
655 if (it != pidInfo->refPids.end()) {
656 entry->clientPids = it->second;
657 }
658 }
659 entry->threadUsage = pidInfo->threadUsage;
660 entry->threadCount = pidInfo->threadCount;
661 }
662 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700663
664 // hash
665 do {
666 ssize_t hashIndex = -1;
667 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
668 for (size_t i = 0; i < c.size(); ++i) {
669 if (serviceName == c[i]) {
670 hashIndex = static_cast<ssize_t>(i);
671 break;
672 }
673 }
674 });
675 if (!ifaceChainRet.isOk()) {
676 handleError(TRANSACTION_ERROR,
677 "interfaceChain fails: " + ifaceChainRet.description());
678 break; // skip getHashChain
679 }
680 if (hashIndex < 0) {
681 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
682 break; // skip getHashChain
683 }
684 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
685 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
686 handleError(BAD_IMPL,
687 "interfaceChain indicates position " + std::to_string(hashIndex) +
688 " but getHashChain returns " + std::to_string(hashChain.size()) +
689 " hashes");
690 return;
691 }
692
693 auto&& hashArray = hashChain[hashIndex];
694 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
695 entry->hash = Hash::hexString(hashVec);
696 });
697 if (!hashRet.isOk()) {
698 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
699 }
700 } while (0);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700701 if (status == OK) {
702 entry->serviceStatus = ServiceStatus::ALIVE;
703 }
Yifan Hong443df792017-05-09 18:49:45 -0700704 return status;
705}
706
Yifan Hong13ba0a92018-06-25 16:15:56 -0700707Status ListCommand::fetchManifestHals() {
708 if (!shouldFetchHalType(HalType::VINTF_MANIFEST)) { return OK; }
709 Status status = OK;
710
711 for (auto manifest : {getDeviceManifest(), getFrameworkManifest()}) {
712 if (manifest == nullptr) {
713 status |= VINTF_ERROR;
714 continue;
715 }
716
717 std::map<std::string, TableEntry> entries;
718
Yifan Hongc346a162019-09-10 19:35:55 -0700719 manifest->forEachHidlInstance([&] (const vintf::ManifestInstance& manifestInstance) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700720 TableEntry entry{
Yifan Hongc346a162019-09-10 19:35:55 -0700721 .interfaceName = manifestInstance.description(),
Yifan Hong13ba0a92018-06-25 16:15:56 -0700722 .transport = manifestInstance.transport(),
723 .arch = manifestInstance.arch(),
724 // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
725 .partition = toPartition(manifest->type()),
726 .serviceStatus = ServiceStatus::DECLARED};
727 std::string key = entry.interfaceName;
728 entries.emplace(std::move(key), std::move(entry));
729 return true;
730 });
731
732 for (auto&& pair : entries)
733 mManifestHalsTable.add(std::move(pair.second));
734 }
Yifan Hong443df792017-05-09 18:49:45 -0700735 return status;
736}
737
Yifan Hong3212f172018-06-28 12:39:50 -0700738Status ListCommand::fetchLazyHals() {
739 using vintf::operator<<;
740
741 if (!shouldFetchHalType(HalType::LAZY_HALS)) { return OK; }
742 Status status = OK;
743
744 for (const TableEntry& manifestEntry : mManifestHalsTable) {
745 if (manifestEntry.transport == vintf::Transport::HWBINDER) {
746 if (!hasHwbinderEntry(manifestEntry)) {
747 mLazyHalsTable.add(TableEntry(manifestEntry));
748 }
749 continue;
750 }
751 if (manifestEntry.transport == vintf::Transport::PASSTHROUGH) {
752 if (!hasPassthroughEntry(manifestEntry)) {
753 mLazyHalsTable.add(TableEntry(manifestEntry));
754 }
755 continue;
756 }
757 err() << "Warning: unrecognized transport in VINTF manifest: "
758 << manifestEntry.transport;
759 status |= VINTF_ERROR;
760 }
761 return status;
762}
763
764bool ListCommand::hasHwbinderEntry(const TableEntry& entry) const {
765 for (const TableEntry& existing : mServicesTable) {
766 if (existing.interfaceName == entry.interfaceName) {
767 return true;
768 }
769 }
770 return false;
771}
772
773bool ListCommand::hasPassthroughEntry(const TableEntry& entry) const {
774 FqInstance entryFqInstance;
775 if (!entryFqInstance.setTo(entry.interfaceName)) {
776 return false; // cannot parse, so add it anyway.
777 }
778 for (const TableEntry& existing : mImplementationsTable) {
779 FqInstance existingFqInstance;
780 if (!existingFqInstance.setTo(getPackageAndVersion(existing.interfaceName))) {
781 continue;
782 }
783
784 // For example, manifest may say graphics.mapper@2.1 but passthroughServiceManager
785 // can only list graphics.mapper@2.0.
786 if (entryFqInstance.getPackage() == existingFqInstance.getPackage() &&
787 vintf::Version{entryFqInstance.getVersion()}
788 .minorAtLeast(vintf::Version{existingFqInstance.getVersion()})) {
789 return true;
790 }
791 }
792 return false;
793}
794
Yifan Hong443df792017-05-09 18:49:45 -0700795Status ListCommand::fetch() {
796 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700797 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700798 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700799 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700800 status |= NO_BINDERIZED_MANAGER;
801 } else {
802 status |= fetchBinderized(bManager);
803 // Passthrough PIDs are registered to the binderized manager as well.
804 status |= fetchPassthrough(bManager);
805 }
806
Yifan Hong9881df92017-05-10 14:33:05 -0700807 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700808 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700809 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700810 status |= NO_PASSTHROUGH_MANAGER;
811 } else {
812 status |= fetchAllLibraries(pManager);
813 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700814 status |= fetchManifestHals();
Yifan Hong3212f172018-06-28 12:39:50 -0700815 status |= fetchLazyHals();
Yifan Hong443df792017-05-09 18:49:45 -0700816 return status;
817}
818
Yifan Hong13ba0a92018-06-25 16:15:56 -0700819void ListCommand::initFetchTypes() {
Yifan Hong3212f172018-06-28 12:39:50 -0700820 // TODO: refactor to do polymorphism on each table (so that dependency graph is not hardcoded).
821 static const std::map<HalType, std::set<HalType>> kDependencyGraph{
822 {HalType::LAZY_HALS, {HalType::BINDERIZED_SERVICES,
823 HalType::PASSTHROUGH_LIBRARIES,
824 HalType::VINTF_MANIFEST}},
825 };
Yifan Hong13ba0a92018-06-25 16:15:56 -0700826 mFetchTypes.insert(mListTypes.begin(), mListTypes.end());
Yifan Hong3212f172018-06-28 12:39:50 -0700827 for (HalType listType : mListTypes) {
828 auto it = kDependencyGraph.find(listType);
829 if (it != kDependencyGraph.end()) {
830 mFetchTypes.insert(it->second.begin(), it->second.end());
831 }
832 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700833}
834
Yifan Hong30528a22020-08-07 18:24:06 -0700835// Get all values of enum type T, assuming the first value is 0 and the last value is T::LAST.
836// T::LAST is not included in the returned list.
837template <typename T>
838std::vector<T> GetAllValues() {
839 using BaseType = std::underlying_type_t<T>;
840 std::vector<T> ret;
841 for (BaseType i = 0; i < static_cast<BaseType>(T::LAST); ++i) {
842 ret.push_back(static_cast<T>(i));
843 }
844 return ret;
845}
846
Yifan Honga6b93f02017-09-13 16:53:37 -0700847void ListCommand::registerAllOptions() {
848 int v = mOptions.size();
849 // A list of acceptable command line options
850 // key: value returned by getopt_long
851 // long options with short alternatives
852 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
853 return USAGE;
854 }, ""});
855 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
856 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
857 return OK;
858 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700859 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
860 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
861 return OK;
Yifan Hong430f8982018-05-25 17:28:39 -0700862 }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700863 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
864 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
865 return OK;
866 }, "print the transport mode column"});
867 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
868 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
869 return OK;
870 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700871 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
872 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
873 return OK;
874 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700875 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
876 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
877 return OK;
878 }, "print the server PID, or server cmdline if -m is set"});
879 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
880 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
881 return OK;
882 }, "print the server object address column"});
883 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
884 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
885 return OK;
886 }, "print the client PIDs, or client cmdlines if -m is set"});
887 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
888 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
889 return OK;
890 }, "print currently used/available threads\n(note, available threads created lazily)"});
891 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
892 thiz->mEnableCmdlines = true;
893 return OK;
894 }, "print cmdline instead of PIDs"});
895 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
896 thiz->mEmitDebugInfo = true;
897 if (arg) thiz->mFileOutputPath = arg;
898 return OK;
899 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
900 "Writes to specified file if 'arg' is provided, otherwise stdout."});
901
Yifan Hongbdf44f82018-05-25 14:20:00 -0700902 mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
903 thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
904 return OK;
905 }, "print VINTF info. This column contains a comma-separated list of:\n"
Steven Morelanddbbbc652021-02-02 23:02:38 +0000906 " - DM: if the HIDL HAL is in the device manifest\n"
907 " - DC: if the HIDL HAL is in the device compatibility matrix\n"
908 " - FM: if the HIDL HAL is in the framework manifest\n"
909 " - FC: if the HIDL HAL is in the framework compatibility matrix\n"
910 " - X: if the HIDL HAL is in none of the above lists"});
Yifan Hong13ba0a92018-06-25 16:15:56 -0700911 mOptions.push_back({'S', "service-status", no_argument, v++, [](ListCommand* thiz, const char*) {
912 thiz->mSelectedColumns.push_back(TableColumnType::SERVICE_STATUS);
913 return OK;
914 }, "print service status column. Possible values are:\n"
915 " - alive: alive and running hwbinder service;\n"
916 " - registered;dead: registered to hwservicemanager but is not responsive;\n"
917 " - declared: only declared in VINTF manifest but is not registered to hwservicemanager;\n"
918 " - N/A: no information for passthrough HALs."});
Yifan Hongbdf44f82018-05-25 14:20:00 -0700919
Yifan Hong30528a22020-08-07 18:24:06 -0700920 mOptions.push_back({'A', "all", no_argument, v++,
921 [](ListCommand* thiz, const char*) {
922 auto allColumns = GetAllValues<TableColumnType>();
923 thiz->mSelectedColumns.insert(thiz->mSelectedColumns.end(),
924 allColumns.begin(), allColumns.end());
925 return OK;
926 },
927 "print all columns"});
928
Yifan Honga6b93f02017-09-13 16:53:37 -0700929 // long options without short alternatives
930 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
931 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800932 if (thiz->mVintfPartition == Partition::UNKNOWN)
933 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700934 if (arg) thiz->mFileOutputPath = arg;
935 return OK;
936 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800937 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
938 if (!arg) return USAGE;
939 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
940 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
941 return OK;
942 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
943 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700944 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
945 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
946 thiz->mSortColumn = TableEntry::sortByInterfaceName;
947 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
948 thiz->mSortColumn = TableEntry::sortByServerPid;
949 } else {
950 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
951 return USAGE;
952 }
953 return OK;
954 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
955 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
956 thiz->mNeat = true;
957 return OK;
958 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Yifan Hong30528a22020-08-07 18:24:06 -0700959 mOptions.push_back(
960 {'\0', "types", required_argument, v++,
961 [](ListCommand* thiz, const char* arg) {
962 if (!arg) {
963 return USAGE;
964 }
Nirav Atrecce988d2018-05-16 11:14:46 -0700965
Yifan Hong30528a22020-08-07 18:24:06 -0700966 static const std::map<std::string, std::vector<HalType>> kHalTypeMap{
967 {"binderized", {HalType::BINDERIZED_SERVICES}},
968 {"b", {HalType::BINDERIZED_SERVICES}},
969 {"passthrough_clients", {HalType::PASSTHROUGH_CLIENTS}},
970 {"c", {HalType::PASSTHROUGH_CLIENTS}},
971 {"passthrough_libs", {HalType::PASSTHROUGH_LIBRARIES}},
972 {"l", {HalType::PASSTHROUGH_LIBRARIES}},
973 {"vintf", {HalType::VINTF_MANIFEST}},
974 {"v", {HalType::VINTF_MANIFEST}},
975 {"lazy", {HalType::LAZY_HALS}},
976 {"z", {HalType::LAZY_HALS}},
977 {"all", GetAllValues<HalType>()},
978 {"a", GetAllValues<HalType>()},
979 };
Nirav Atrecce988d2018-05-16 11:14:46 -0700980
Yifan Hong30528a22020-08-07 18:24:06 -0700981 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
982 for (const auto& halTypeArg : halTypesArgs) {
983 if (halTypeArg.empty()) continue;
Nirav Atrecce988d2018-05-16 11:14:46 -0700984
Yifan Hong30528a22020-08-07 18:24:06 -0700985 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
986 if (halTypeIter == kHalTypeMap.end()) {
987 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
988 return USAGE;
989 }
Nirav Atrecce988d2018-05-16 11:14:46 -0700990
Yifan Hong30528a22020-08-07 18:24:06 -0700991 // Append unique (non-repeated) HAL types to the reporting list
992 for (auto halType : halTypeIter->second) {
993 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
994 thiz->mListTypes.end()) {
995 thiz->mListTypes.push_back(halType);
996 }
997 }
998 }
Nirav Atrecce988d2018-05-16 11:14:46 -0700999
Yifan Hong30528a22020-08-07 18:24:06 -07001000 if (thiz->mListTypes.empty()) {
1001 return USAGE;
1002 }
1003 return OK;
1004 },
1005 "comma-separated list of one or more sections.\nThe output is restricted to the "
1006 "selected section(s). Valid options\nare: (b|binderized), (c|passthrough_clients), (l|"
1007 "passthrough_libs), (v|vintf), (z|lazy), and (a|all).\nDefault is `b,c,l`."});
Yifan Honga6b93f02017-09-13 16:53:37 -07001008}
1009
1010// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
1011// the lifetime of "options" during the usage of the returned array.
1012static std::unique_ptr<struct option[]> getLongOptions(
1013 const ListCommand::RegisteredOptions& options,
1014 int* longOptFlag) {
1015 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
1016 int i = 0;
1017 for (const auto& e : options) {
1018 ret[i].name = e.longOption.c_str();
1019 ret[i].has_arg = e.hasArg;
1020 ret[i].flag = longOptFlag;
1021 ret[i].val = e.val;
1022
1023 i++;
1024 }
1025 // getopt_long last option has all zeros
Yi Kong19d5c002018-07-20 13:39:55 -07001026 ret[i].name = nullptr;
Yifan Honga6b93f02017-09-13 16:53:37 -07001027 ret[i].has_arg = 0;
Yi Kong19d5c002018-07-20 13:39:55 -07001028 ret[i].flag = nullptr;
Yifan Honga6b93f02017-09-13 16:53:37 -07001029 ret[i].val = 0;
1030
1031 return ret;
1032}
1033
1034// Create 'optstring' argument to getopt_long.
1035static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
1036 std::stringstream ss;
1037 for (const auto& e : options) {
1038 if (e.shortOption != '\0') {
1039 ss << e.shortOption;
1040 }
1041 }
1042 return ss.str();
1043}
1044
Yifan Honga8bedc62017-09-08 18:00:31 -07001045Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -07001046 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -07001047
Yifan Honga6b93f02017-09-13 16:53:37 -07001048 if (mOptions.empty()) {
1049 registerAllOptions();
1050 }
1051 int longOptFlag;
1052 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
1053 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001054
Yifan Honga8bedc62017-09-08 18:00:31 -07001055 // suppress output to std::err for unknown options
1056 opterr = 0;
1057
Yifan Hong443df792017-05-09 18:49:45 -07001058 int optionIndex;
1059 int c;
1060 // Lshal::parseArgs has set optind to the next option to parse
1061 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -07001062 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -07001063 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -07001064 if (c == -1) {
1065 break;
1066 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001067 const RegisteredOption* found = nullptr;
1068 if (c == 0) {
1069 // see long option
1070 for (const auto& e : mOptions) {
1071 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -07001072 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001073 } else {
1074 // see short option
1075 for (const auto& e : mOptions) {
1076 if (c == e.shortOption) found = &e;
1077 }
Yifan Hong443df792017-05-09 18:49:45 -07001078 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001079
1080 if (found == nullptr) {
1081 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -07001082 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -07001083 return USAGE;
1084 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001085
1086 Status status = found->op(this, optarg);
1087 if (status != OK) {
1088 return status;
1089 }
Yifan Hong443df792017-05-09 18:49:45 -07001090 }
1091 if (optind < arg.argc) {
1092 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -07001093 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001094 return USAGE;
1095 }
1096
1097 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -07001098 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001099 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -07001100 }
1101
Yifan Honga6b93f02017-09-13 16:53:37 -07001102 if (mSelectedColumns.empty()) {
Steven Moreland8e0f5392018-12-12 14:27:24 -08001103 mSelectedColumns = {TableColumnType::VINTF, TableColumnType::RELEASED,
Yifan Hongfee209d2017-09-14 18:23:38 -07001104 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -07001105 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -07001106 }
Yifan Hongd4a77e82017-09-06 19:40:24 -07001107
Yifan Honga6b93f02017-09-13 16:53:37 -07001108 if (mEnableCmdlines) {
1109 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
1110 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
1111 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001112 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001113 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
1114 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001115 }
1116 }
1117 }
1118
Nirav Atrecce988d2018-05-16 11:14:46 -07001119 // By default, list all HAL types
1120 if (mListTypes.empty()) {
1121 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
1122 HalType::PASSTHROUGH_LIBRARIES};
1123 }
Yifan Hong13ba0a92018-06-25 16:15:56 -07001124 initFetchTypes();
Nirav Atrecce988d2018-05-16 11:14:46 -07001125
Yifan Honga6b93f02017-09-13 16:53:37 -07001126 forEachTable([this] (Table& table) {
1127 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001128 });
1129
Yifan Hong443df792017-05-09 18:49:45 -07001130 return OK;
1131}
1132
Yifan Honga8bedc62017-09-08 18:00:31 -07001133Status ListCommand::main(const Arg &arg) {
1134 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -07001135 if (status != OK) {
1136 return status;
1137 }
1138 status = fetch();
1139 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -07001140 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -07001141 return status;
1142}
1143
Yifan Honga6b93f02017-09-13 16:53:37 -07001144const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
1145 static const std::string empty{};
1146 static const std::string optional{"[=<arg>]"};
1147 static const std::string required{"=<arg>"};
1148
1149 if (hasArg == optional_argument) {
1150 return optional;
1151 }
1152 if (hasArg == required_argument) {
1153 return required;
1154 }
1155 return empty;
1156}
1157
Yifan Honga8bedc62017-09-08 18:00:31 -07001158void ListCommand::usage() const {
1159
Yifan Honga6b93f02017-09-13 16:53:37 -07001160 err() << "list:" << std::endl
1161 << " lshal" << std::endl
1162 << " lshal list" << std::endl
Steven Moreland8e0f5392018-12-12 14:27:24 -08001163 << " List all hals with default ordering and columns (`lshal list -Vliepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001164 << " lshal list [-h|--help]" << std::endl
1165 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1166 << " lshal [list] [OPTIONS...]" << std::endl;
1167 for (const auto& e : mOptions) {
1168 if (e.help.empty()) {
1169 continue;
1170 }
1171 err() << " ";
1172 if (e.shortOption != '\0')
1173 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1174 if (e.shortOption != '\0' && !e.longOption.empty())
1175 err() << ", ";
1176 if (!e.longOption.empty())
1177 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1178 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001179 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001180 for (const auto& line : lines) {
1181 if (&line != &lines.front())
1182 err() << " ";
1183 err() << line << std::endl;
1184 }
1185 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001186}
1187
Yifan Hong443df792017-05-09 18:49:45 -07001188} // namespace lshal
1189} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001190