blob: e54f9d3df720428b58db1f914230ea81cad71aff [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>
Steven Morelandb4d6c572021-07-29 12:17:25 -070031#include <android-base/hex.h>
Nirav Atrecce988d2018-05-16 11:14:46 -070032#include <android-base/logging.h>
Yifan Hong443df792017-05-09 18:49:45 -070033#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 Hong13ba0a92018-06-25 16:15:56 -070060Partition toPartition(vintf::SchemaType t) {
61 switch (t) {
62 case vintf::SchemaType::FRAMEWORK: return Partition::SYSTEM;
63 // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
64 case vintf::SchemaType::DEVICE: return Partition::VENDOR;
65 }
66 return Partition::UNKNOWN;
67}
68
69std::string getPackageAndVersion(const std::string& fqInstance) {
70 return splitFirst(fqInstance, ':').first;
71}
72
Yifan Hong76ac14a2017-09-08 14:59:04 -070073NullableOStream<std::ostream> ListCommand::out() const {
74 return mLshal.out();
75}
76
77NullableOStream<std::ostream> ListCommand::err() const {
78 return mLshal.err();
Yifan Hong443df792017-05-09 18:49:45 -070079}
80
Yifan Hong795b6ec2017-09-13 11:25:28 -070081std::string ListCommand::GetName() {
82 return "list";
83}
84std::string ListCommand::getSimpleDescription() const {
Steven Morelanddbbbc652021-02-02 23:02:38 +000085 return "List HIDL HALs.";
Yifan Hong795b6ec2017-09-13 11:25:28 -070086}
87
Yifan Hong8bf73162017-09-07 18:06:13 -070088std::string ListCommand::parseCmdline(pid_t pid) const {
Yifan Hongf31aa052018-02-02 15:17:51 -080089 return android::procpartition::getCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -070090}
91
92const std::string &ListCommand::getCmdline(pid_t pid) {
Yifan Hong13ba0a92018-06-25 16:15:56 -070093 static const std::string kEmptyString{};
94 if (pid == NO_PID) return kEmptyString;
Yifan Hong443df792017-05-09 18:49:45 -070095 auto pair = mCmdlines.find(pid);
96 if (pair != mCmdlines.end()) {
97 return pair->second;
98 }
Yifan Hong8bf73162017-09-07 18:06:13 -070099 mCmdlines[pid] = parseCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -0700100 return mCmdlines[pid];
101}
102
103void ListCommand::removeDeadProcesses(Pids *pids) {
104 static const pid_t myPid = getpid();
Yifan Hong61fb7bc2017-05-12 16:33:57 -0700105 pids->erase(std::remove_if(pids->begin(), pids->end(), [this](auto pid) {
Yifan Hong443df792017-05-09 18:49:45 -0700106 return pid == myPid || this->getCmdline(pid).empty();
Yifan Hong61fb7bc2017-05-12 16:33:57 -0700107 }), pids->end());
Yifan Hong443df792017-05-09 18:49:45 -0700108}
109
Yifan Hongf31aa052018-02-02 15:17:51 -0800110Partition ListCommand::getPartition(pid_t pid) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700111 if (pid == NO_PID) return Partition::UNKNOWN;
Yifan Hongf31aa052018-02-02 15:17:51 -0800112 auto it = mPartitions.find(pid);
113 if (it != mPartitions.end()) {
114 return it->second;
115 }
116 Partition partition = android::procpartition::getPartition(pid);
117 mPartitions.emplace(pid, partition);
118 return partition;
119}
120
121// Give sensible defaults when nothing can be inferred from runtime.
122// process: Partition inferred from executable location or cmdline.
Yifan Hongb2d096a2018-05-01 15:25:23 -0700123Partition ListCommand::resolvePartition(Partition process, const FqInstance& fqInstance) const {
124 if (fqInstance.inPackage("vendor") || fqInstance.inPackage("com")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800125 return Partition::VENDOR;
126 }
127
Yifan Hongb2d096a2018-05-01 15:25:23 -0700128 if (fqInstance.inPackage("android.frameworks") || fqInstance.inPackage("android.system") ||
129 fqInstance.inPackage("android.hidl")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800130 return Partition::SYSTEM;
131 }
132
133 // Some android.hardware HALs are served from system. Check the value from executable
134 // location / cmdline first.
Yifan Hongb2d096a2018-05-01 15:25:23 -0700135 if (fqInstance.inPackage("android.hardware")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800136 if (process != Partition::UNKNOWN) {
137 return process;
138 }
139 return Partition::VENDOR;
140 }
141
142 return process;
143}
144
Yifan Hongbdf44f82018-05-25 14:20:00 -0700145bool match(const vintf::ManifestInstance& instance, const FqInstance& fqInstance,
146 vintf::TransportArch ta) {
147 // For hwbinder libs, allow missing arch in manifest.
148 // For passthrough libs, allow missing interface/instance in table.
149 return (ta.transport == instance.transport()) &&
150 (ta.transport == vintf::Transport::HWBINDER ||
151 vintf::contains(instance.arch(), ta.arch)) &&
152 (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
153 (!fqInstance.hasInstance() || fqInstance.getInstance() == instance.instance());
154}
155
156bool match(const vintf::MatrixInstance& instance, const FqInstance& fqInstance,
157 vintf::TransportArch /* ta */) {
158 return (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
159 (!fqInstance.hasInstance() || instance.matchInstance(fqInstance.getInstance()));
160}
161
162template <typename ObjectType>
163VintfInfo getVintfInfo(const std::shared_ptr<const ObjectType>& object,
164 const FqInstance& fqInstance, vintf::TransportArch ta, VintfInfo value) {
165 bool found = false;
Yifan Hongc346a162019-09-10 19:35:55 -0700166 (void)object->forEachHidlInstanceOfVersion(fqInstance.getPackage(), fqInstance.getVersion(),
167 [&](const auto& instance) {
168 found = match(instance, fqInstance, ta);
169 return !found; // continue if not found
170 });
Yifan Hongbdf44f82018-05-25 14:20:00 -0700171 return found ? value : VINTF_INFO_EMPTY;
172}
173
174std::shared_ptr<const vintf::HalManifest> ListCommand::getDeviceManifest() const {
175 return vintf::VintfObject::GetDeviceHalManifest();
176}
177
178std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getDeviceMatrix() const {
179 return vintf::VintfObject::GetDeviceCompatibilityMatrix();
180}
181
182std::shared_ptr<const vintf::HalManifest> ListCommand::getFrameworkManifest() const {
183 return vintf::VintfObject::GetFrameworkHalManifest();
184}
185
186std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getFrameworkMatrix() const {
187 return vintf::VintfObject::GetFrameworkCompatibilityMatrix();
188}
189
190VintfInfo ListCommand::getVintfInfo(const std::string& fqInstanceName,
191 vintf::TransportArch ta) const {
192 FqInstance fqInstance;
193 if (!fqInstance.setTo(fqInstanceName) &&
194 // Ignore interface / instance for passthrough libs
Yifan Hong13ba0a92018-06-25 16:15:56 -0700195 !fqInstance.setTo(getPackageAndVersion(fqInstanceName))) {
Yifan Hongbdf44f82018-05-25 14:20:00 -0700196 err() << "Warning: Cannot parse '" << fqInstanceName << "'; no VINTF info." << std::endl;
197 return VINTF_INFO_EMPTY;
198 }
199
200 return lshal::getVintfInfo(getDeviceManifest(), fqInstance, ta, DEVICE_MANIFEST) |
201 lshal::getVintfInfo(getFrameworkManifest(), fqInstance, ta, FRAMEWORK_MANIFEST) |
202 lshal::getVintfInfo(getDeviceMatrix(), fqInstance, ta, DEVICE_MATRIX) |
203 lshal::getVintfInfo(getFrameworkMatrix(), fqInstance, ta, FRAMEWORK_MATRIX);
204}
205
Steven Morelandd8e20192017-05-24 11:23:08 -0700206bool ListCommand::getPidInfo(
Devin Moorec03e3aa2020-12-11 15:11:17 -0800207 pid_t serverPid, BinderPidInfo *pidInfo) const {
208 const auto& status = getBinderPidInfo(BinderDebugContext::HWBINDER, serverPid, pidInfo);
209 return status == OK;
Steven Morelandd8e20192017-05-24 11:23:08 -0700210}
211
Devin Moorec03e3aa2020-12-11 15:11:17 -0800212const BinderPidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
213 auto pair = mCachedPidInfos.insert({serverPid, BinderPidInfo{}});
Yifan Hong1243dde2017-09-14 17:49:30 -0700214 if (pair.second /* did insertion take place? */) {
215 if (!getPidInfo(serverPid, &pair.first->second)) {
216 return nullptr;
217 }
218 }
219 return &pair.first->second;
220}
221
Yifan Hong13ba0a92018-06-25 16:15:56 -0700222bool ListCommand::shouldFetchHalType(const HalType &type) const {
223 return (std::find(mFetchTypes.begin(), mFetchTypes.end(), type) != mFetchTypes.end());
Nirav Atrecce988d2018-05-16 11:14:46 -0700224}
225
Yifan Hongdb730532018-06-25 16:32:01 -0700226Table* ListCommand::tableForType(HalType type) {
227 switch (type) {
228 case HalType::BINDERIZED_SERVICES:
229 return &mServicesTable;
230 case HalType::PASSTHROUGH_CLIENTS:
231 return &mPassthroughRefTable;
232 case HalType::PASSTHROUGH_LIBRARIES:
233 return &mImplementationsTable;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700234 case HalType::VINTF_MANIFEST:
235 return &mManifestHalsTable;
Yifan Hong3212f172018-06-28 12:39:50 -0700236 case HalType::LAZY_HALS:
237 return &mLazyHalsTable;
Yifan Hongdb730532018-06-25 16:32:01 -0700238 default:
239 LOG(FATAL) << "Unknown HAL type " << static_cast<int64_t>(type);
240 return nullptr;
241 }
242}
243const Table* ListCommand::tableForType(HalType type) const {
244 return const_cast<ListCommand*>(this)->tableForType(type);
Yifan Hong443df792017-05-09 18:49:45 -0700245}
246
247void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700248 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700249 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700250 }
Yifan Hong443df792017-05-09 18:49:45 -0700251}
252void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
Nirav Atrecce988d2018-05-16 11:14:46 -0700253 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700254 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700255 }
Yifan Hong443df792017-05-09 18:49:45 -0700256}
257
258void ListCommand::postprocess() {
259 forEachTable([this](Table &table) {
260 if (mSortColumn) {
261 std::sort(table.begin(), table.end(), mSortColumn);
262 }
263 for (TableEntry &entry : table) {
264 entry.serverCmdline = getCmdline(entry.serverPid);
265 removeDeadProcesses(&entry.clientPids);
266 for (auto pid : entry.clientPids) {
267 entry.clientCmdlines.push_back(this->getCmdline(pid));
268 }
269 }
Yifan Hongf31aa052018-02-02 15:17:51 -0800270 for (TableEntry& entry : table) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700271 if (entry.partition == Partition::UNKNOWN) {
272 entry.partition = getPartition(entry.serverPid);
273 }
Yifan Hongbdf44f82018-05-25 14:20:00 -0700274 entry.vintfInfo = getVintfInfo(entry.interfaceName, {entry.transport, entry.arch});
Yifan Hongf31aa052018-02-02 15:17:51 -0800275 }
Yifan Hong443df792017-05-09 18:49:45 -0700276 });
277 // use a double for loop here because lshal doesn't care about efficiency.
278 for (TableEntry &packageEntry : mImplementationsTable) {
279 std::string packageName = packageEntry.interfaceName;
Steven Morelandd4f32b32018-03-06 14:47:58 -0800280 FQName fqPackageName;
281 if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700282 continue;
283 }
284 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700285 if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
Yifan Hong443df792017-05-09 18:49:45 -0700286 continue;
287 }
Steven Morelandd4f32b32018-03-06 14:47:58 -0800288 FQName interfaceName;
289 if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700290 continue;
291 }
292 if (interfaceName.getPackageAndVersion() == fqPackageName) {
293 interfaceEntry.arch = packageEntry.arch;
294 }
295 }
296 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700297
298 mServicesTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000299 "| All HIDL binderized services (registered with hwservicemanager)");
Yifan Hongca3b6602017-09-07 16:44:27 -0700300 mPassthroughRefTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000301 "| All HIDL interfaces getService() has ever returned as a passthrough interface;\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800302 "| PIDs / processes shown below might be inaccurate because the process\n"
303 "| might have relinquished the interface or might have died.\n"
304 "| The Server / Server CMD column can be ignored.\n"
305 "| The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
306 "| the library and successfully fetched the passthrough implementation.");
Yifan Hongca3b6602017-09-07 16:44:27 -0700307 mImplementationsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000308 "| All available HIDL passthrough implementations (all -impl.so files).\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800309 "| These may return subclasses through their respective HIDL_FETCH_I* functions.");
Yifan Hong13ba0a92018-06-25 16:15:56 -0700310 mManifestHalsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000311 "| All HIDL HALs that are in VINTF manifest.");
Yifan Hong3212f172018-06-28 12:39:50 -0700312 mLazyHalsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000313 "| All HIDL HALs that are declared in VINTF manifest:\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800314 "| - as hwbinder HALs but are not registered to hwservicemanager, and\n"
315 "| - as hwbinder/passthrough HALs with no implementation.");
Yifan Hong443df792017-05-09 18:49:45 -0700316}
317
Yifan Hongb2d096a2018-05-01 15:25:23 -0700318bool ListCommand::addEntryWithInstance(const TableEntry& entry,
319 vintf::HalManifest* manifest) const {
320 FqInstance fqInstance;
321 if (!fqInstance.setTo(entry.interfaceName)) {
322 err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
323 return false;
Yifan Hong77c87822017-06-19 15:47:39 -0700324 }
Yifan Hongb2d096a2018-05-01 15:25:23 -0700325
Steven Moreland7a99e042020-02-26 13:16:34 -0800326 if (fqInstance.getPackage() == "android.hidl.base") {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700327 return true; // always remove IBase from manifest
328 }
329
330 Partition partition = resolvePartition(entry.partition, fqInstance);
331
332 if (partition == Partition::UNKNOWN) {
333 err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
334 << std::endl;
335 return false;
336 }
337
338 if (partition != mVintfPartition) {
339 return true; // strip out instances that is in a different partition.
340 }
341
Yifan Hongb2d096a2018-05-01 15:25:23 -0700342 vintf::Arch arch;
Yifan Hong8304e412018-05-25 15:05:36 -0700343 if (entry.transport == vintf::Transport::HWBINDER) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700344 arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
Yifan Hong8304e412018-05-25 15:05:36 -0700345 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700346 if (entry.arch == vintf::Arch::ARCH_EMPTY) {
347 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
348 return false;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700349 }
Yifan Hong0ad64f52018-05-25 15:29:17 -0700350 arch = entry.arch;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700351 } else {
352 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
353 return false;
354 }
355
Yifan Hongcb5a1ab2023-01-12 14:55:55 -0800356 auto vintfFqInstance = vintf::FqInstance::from(fqInstance.string());
357 if (!vintfFqInstance.has_value()) {
358 err() << "Unable to convert " << fqInstance.string() << " to vintf::FqInstance"
359 << std::endl;
360 return false;
361 }
362
Yifan Hongb2d096a2018-05-01 15:25:23 -0700363 std::string e;
Yifan Hongcb5a1ab2023-01-12 14:55:55 -0800364 if (!manifest->insertInstance(*vintfFqInstance, entry.transport, arch, vintf::HalFormat::HIDL,
365 &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700366 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
367 return false;
368 }
369 return true;
370}
371
372bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
373 const vintf::HalManifest* manifest) const {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700374 const auto& packageAndVersion = splitFirst(getPackageAndVersion(entry.interfaceName), '@');
Yifan Hongb2d096a2018-05-01 15:25:23 -0700375 const auto& package = packageAndVersion.first;
376 vintf::Version version;
377 if (!vintf::parse(packageAndVersion.second, &version)) {
378 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
379 << entry.interfaceName << "'" << std::endl;
380 return false;
381 }
382
383 bool found = false;
Yifan Hongc346a162019-09-10 19:35:55 -0700384 (void)manifest->forEachHidlInstanceOfVersion(package, version, [&found](const auto&) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700385 found = true;
386 return false; // break
387 });
388 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700389}
390
Yifan Hongca3b6602017-09-07 16:44:27 -0700391void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700392 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800393 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700394 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700395
396 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800397 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700398
Yifan Hongb2d096a2018-05-01 15:25:23 -0700399 std::vector<std::string> error;
400 for (const TableEntry& entry : mServicesTable)
401 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
402 for (const TableEntry& entry : mPassthroughRefTable)
403 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700404 for (const TableEntry& entry : mManifestHalsTable)
405 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700406
Yifan Hongb2d096a2018-05-01 15:25:23 -0700407 std::vector<std::string> passthrough;
408 for (const TableEntry& entry : mImplementationsTable)
409 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800410
Yifan Hongf31aa052018-02-02 15:17:51 -0800411 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700412 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
413 << INIT_VINTF_NOTES;
414 if (!error.empty()) {
415 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
416 for (const auto& e : error) {
417 out << " " << e << std::endl;
418 }
419 }
420 if (!passthrough.empty()) {
421 out << std::endl
422 << " The following HALs are passthrough and no interface or instance " << std::endl
423 << " names can be inferred." << std::endl;
424 for (const auto& e : passthrough) {
425 out << " " << e << std::endl;
426 }
427 }
428 out << "-->" << std::endl;
Yifan Honga96f87f2021-04-16 18:59:27 -0700429 out << vintf::toXml(manifest, vintf::SerializeFlags::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700430}
431
Yifan Hongf31aa052018-02-02 15:17:51 -0800432std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700433 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800434 " only hwbinder is shown.\n"
435 " 2. It is likely that HALs in passthrough transport does not have\n"
436 " <interface> declared; users will have to write them by hand.\n"
437 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
438 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700439 " 4. This output is intended for launch devices.\n"
440 " Upgrading devices should not use this tool to generate device\n"
441 " manifest and replace the existing manifest directly, but should\n"
442 " edit the existing manifest manually.\n"
443 " Specifically, devices which launched at Android O-MR1 or earlier\n"
444 " should not use the 'fqname' format for required HAL entries and\n"
445 " should instead use the legacy package, name, instance-name format\n"
446 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800447};
448
Yifan Hong0ad64f52018-05-25 15:29:17 -0700449static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
Yifan Hong443df792017-05-09 18:49:45 -0700450 switch (a) {
451 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700452 return vintf::Arch::ARCH_64;
Yifan Hong443df792017-05-09 18:49:45 -0700453 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700454 return vintf::Arch::ARCH_32;
Yifan Hong443df792017-05-09 18:49:45 -0700455 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
456 default:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700457 return vintf::Arch::ARCH_EMPTY;
Yifan Hong443df792017-05-09 18:49:45 -0700458 }
459}
460
Yifan Hongca3b6602017-09-07 16:44:27 -0700461void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700462 if (mNeat) {
Yifan Hongb72f19e2018-06-27 16:58:56 -0700463 std::vector<const Table*> tables;
464 forEachTable([&tables](const Table &table) {
465 tables.push_back(&table);
466 });
467 MergedTable(std::move(tables)).createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700468 return;
469 }
470
Yifan Hongca3b6602017-09-07 16:44:27 -0700471 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700472
Yifan Hongd4a77e82017-09-06 19:40:24 -0700473 // We're only interested in dumping debug info for already
474 // instantiated services. There's little value in dumping the
475 // debug info for a service we create on the fly, so we only operate
476 // on the "mServicesTable".
477 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
478 if (mEmitDebugInfo && &table == &mServicesTable) {
479 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700480 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700481 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800482 mLshal.emitDebugInfo(pair.first, pair.second, {},
Yifan Hong6884b872020-07-09 16:38:18 -0700483 ParentDebugInfoLevel::FQNAME_ONLY, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700484 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700485 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700486 };
Yifan Hong443df792017-05-09 18:49:45 -0700487 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700488 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
489 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700490 });
Yifan Hong443df792017-05-09 18:49:45 -0700491}
492
Yifan Hongca3b6602017-09-07 16:44:27 -0700493Status ListCommand::dump() {
494 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
495
496 if (mFileOutputPath.empty()) {
497 (*this.*dump)(out());
498 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700499 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700500
501 std::ofstream fileOutput(mFileOutputPath);
502 if (!fileOutput.is_open()) {
503 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
504 return IO_ERROR;
505 }
506 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
507
508 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
509
510 fileOutput.flush();
511 fileOutput.close();
512 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700513}
514
Yifan Hong20f4ee82018-06-25 16:21:29 -0700515void ListCommand::putEntry(HalType type, TableEntry &&entry) {
Yifan Hongdb730532018-06-25 16:32:01 -0700516 tableForType(type)->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700517}
518
519Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700520 if (!shouldFetchHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700521
Yifan Hong443df792017-05-09 18:49:45 -0700522 using namespace ::android::hardware;
523 using namespace ::android::hidl::manager::V1_0;
524 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700525 using std::literals::chrono_literals::operator""s;
Yifan Hongaf582192018-04-10 17:45:06 -0700526 auto ret = timeoutIPC(10s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700527 std::map<std::string, TableEntry> entries;
528 for (const auto &info : infos) {
529 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
530 std::string{info.instanceName.c_str()};
531 entries.emplace(interfaceName, TableEntry{
532 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700533 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700534 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700535 }).first->second.arch |= fromBaseArchitecture(info.arch);
536 }
537 for (auto &&pair : entries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700538 putEntry(HalType::PASSTHROUGH_LIBRARIES, std::move(pair.second));
Yifan Hong443df792017-05-09 18:49:45 -0700539 }
540 });
541 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700542 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700543 << ret.description() << std::endl;
544 return DUMP_ALL_LIBS_ERROR;
545 }
546 return OK;
547}
548
549Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700550 if (!shouldFetchHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700551
Yifan Hong443df792017-05-09 18:49:45 -0700552 using namespace ::android::hardware;
553 using namespace ::android::hardware::details;
554 using namespace ::android::hidl::manager::V1_0;
555 using namespace ::android::hidl::base::V1_0;
556 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
557 for (const auto &info : infos) {
558 if (info.clientPids.size() <= 0) {
559 continue;
560 }
Yifan Hong20f4ee82018-06-25 16:21:29 -0700561 putEntry(HalType::PASSTHROUGH_CLIENTS, {
Yifan Hong443df792017-05-09 18:49:45 -0700562 .interfaceName =
563 std::string{info.interfaceName.c_str()} + "/" +
564 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700565 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700566 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700567 .clientPids = info.clientPids,
568 .arch = fromBaseArchitecture(info.arch)
569 });
570 }
571 });
572 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700573 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700574 << ret.description() << std::endl;
575 return DUMP_PASSTHROUGH_ERROR;
576 }
577 return OK;
578}
579
580Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700581 using vintf::operator<<;
582
Yifan Hong13ba0a92018-06-25 16:15:56 -0700583 if (!shouldFetchHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700584
Yifan Hong8304e412018-05-25 15:05:36 -0700585 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700586 hidl_vec<hidl_string> fqInstanceNames;
587 // copying out for timeoutIPC
588 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
589 fqInstanceNames = names;
590 });
591 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700592 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700593 << listRet.description() << std::endl;
594 return DUMP_BINDERIZED_ERROR;
595 }
596
597 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700598 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700599 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700600 // create entry and default assign all fields.
601 TableEntry& entry = allTableEntries[fqInstanceName];
602 entry.interfaceName = fqInstanceName;
603 entry.transport = mode;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700604 entry.serviceStatus = ServiceStatus::NON_RESPONSIVE;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700605
606 status |= fetchBinderizedEntry(manager, &entry);
607 }
608
609 for (auto& pair : allTableEntries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700610 putEntry(HalType::BINDERIZED_SERVICES, std::move(pair.second));
Yifan Hong22ea7b82017-09-14 18:07:43 -0700611 }
612 return status;
613}
614
615Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
616 TableEntry *entry) {
617 Status status = OK;
618 const auto handleError = [&](Status additionalError, const std::string& msg) {
619 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
620 status |= DUMP_BINDERIZED_ERROR | additionalError;
621 };
622
623 const auto pair = splitFirst(entry->interfaceName, '/');
624 const auto &serviceName = pair.first;
625 const auto &instanceName = pair.second;
626 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
627 if (!getRet.isOk()) {
628 handleError(TRANSACTION_ERROR,
629 "cannot be fetched from service manager:" + getRet.description());
630 return status;
631 }
632 sp<IBase> service = getRet;
633 if (service == nullptr) {
634 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
635 return status;
636 }
637
638 // getDebugInfo
639 do {
640 DebugInfo debugInfo;
641 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
642 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700643 });
644 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700645 handleError(TRANSACTION_ERROR,
646 "debugging information cannot be retrieved: " + debugRet.description());
647 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700648 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700649
Yifan Hong22ea7b82017-09-14 18:07:43 -0700650 entry->serverPid = debugInfo.pid;
651 entry->serverObjectAddress = debugInfo.ptr;
652 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700653
Yifan Hong22ea7b82017-09-14 18:07:43 -0700654 if (debugInfo.pid != NO_PID) {
Devin Moorec03e3aa2020-12-11 15:11:17 -0800655 const BinderPidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
Yifan Hong22ea7b82017-09-14 18:07:43 -0700656 if (pidInfo == nullptr) {
657 handleError(IO_ERROR,
658 "no information for PID " + std::to_string(debugInfo.pid) +
659 ", are you root?");
660 break;
661 }
662 if (debugInfo.ptr != NO_PTR) {
663 auto it = pidInfo->refPids.find(debugInfo.ptr);
664 if (it != pidInfo->refPids.end()) {
665 entry->clientPids = it->second;
666 }
667 }
668 entry->threadUsage = pidInfo->threadUsage;
669 entry->threadCount = pidInfo->threadCount;
670 }
671 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700672
673 // hash
674 do {
675 ssize_t hashIndex = -1;
676 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
677 for (size_t i = 0; i < c.size(); ++i) {
678 if (serviceName == c[i]) {
679 hashIndex = static_cast<ssize_t>(i);
680 break;
681 }
682 }
683 });
684 if (!ifaceChainRet.isOk()) {
685 handleError(TRANSACTION_ERROR,
686 "interfaceChain fails: " + ifaceChainRet.description());
687 break; // skip getHashChain
688 }
689 if (hashIndex < 0) {
690 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
691 break; // skip getHashChain
692 }
693 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
694 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
695 handleError(BAD_IMPL,
696 "interfaceChain indicates position " + std::to_string(hashIndex) +
697 " but getHashChain returns " + std::to_string(hashChain.size()) +
698 " hashes");
699 return;
700 }
701
702 auto&& hashArray = hashChain[hashIndex];
Steven Morelandb4d6c572021-07-29 12:17:25 -0700703 entry->hash = android::base::HexString(hashArray.data(), hashArray.size());
Yifan Hongfee209d2017-09-14 18:23:38 -0700704 });
705 if (!hashRet.isOk()) {
706 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
707 }
708 } while (0);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700709 if (status == OK) {
710 entry->serviceStatus = ServiceStatus::ALIVE;
711 }
Yifan Hong443df792017-05-09 18:49:45 -0700712 return status;
713}
714
Yifan Hong13ba0a92018-06-25 16:15:56 -0700715Status ListCommand::fetchManifestHals() {
716 if (!shouldFetchHalType(HalType::VINTF_MANIFEST)) { return OK; }
717 Status status = OK;
718
719 for (auto manifest : {getDeviceManifest(), getFrameworkManifest()}) {
720 if (manifest == nullptr) {
721 status |= VINTF_ERROR;
722 continue;
723 }
724
725 std::map<std::string, TableEntry> entries;
726
Yifan Hongc346a162019-09-10 19:35:55 -0700727 manifest->forEachHidlInstance([&] (const vintf::ManifestInstance& manifestInstance) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700728 TableEntry entry{
Yifan Hongc346a162019-09-10 19:35:55 -0700729 .interfaceName = manifestInstance.description(),
Yifan Hong13ba0a92018-06-25 16:15:56 -0700730 .transport = manifestInstance.transport(),
731 .arch = manifestInstance.arch(),
732 // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
733 .partition = toPartition(manifest->type()),
734 .serviceStatus = ServiceStatus::DECLARED};
735 std::string key = entry.interfaceName;
736 entries.emplace(std::move(key), std::move(entry));
737 return true;
738 });
739
740 for (auto&& pair : entries)
741 mManifestHalsTable.add(std::move(pair.second));
742 }
Yifan Hong443df792017-05-09 18:49:45 -0700743 return status;
744}
745
Yifan Hong3212f172018-06-28 12:39:50 -0700746Status ListCommand::fetchLazyHals() {
747 using vintf::operator<<;
748
749 if (!shouldFetchHalType(HalType::LAZY_HALS)) { return OK; }
750 Status status = OK;
751
752 for (const TableEntry& manifestEntry : mManifestHalsTable) {
753 if (manifestEntry.transport == vintf::Transport::HWBINDER) {
754 if (!hasHwbinderEntry(manifestEntry)) {
755 mLazyHalsTable.add(TableEntry(manifestEntry));
756 }
757 continue;
758 }
759 if (manifestEntry.transport == vintf::Transport::PASSTHROUGH) {
760 if (!hasPassthroughEntry(manifestEntry)) {
761 mLazyHalsTable.add(TableEntry(manifestEntry));
762 }
763 continue;
764 }
765 err() << "Warning: unrecognized transport in VINTF manifest: "
766 << manifestEntry.transport;
767 status |= VINTF_ERROR;
768 }
769 return status;
770}
771
772bool ListCommand::hasHwbinderEntry(const TableEntry& entry) const {
773 for (const TableEntry& existing : mServicesTable) {
774 if (existing.interfaceName == entry.interfaceName) {
775 return true;
776 }
777 }
778 return false;
779}
780
781bool ListCommand::hasPassthroughEntry(const TableEntry& entry) const {
782 FqInstance entryFqInstance;
783 if (!entryFqInstance.setTo(entry.interfaceName)) {
784 return false; // cannot parse, so add it anyway.
785 }
786 for (const TableEntry& existing : mImplementationsTable) {
787 FqInstance existingFqInstance;
788 if (!existingFqInstance.setTo(getPackageAndVersion(existing.interfaceName))) {
789 continue;
790 }
791
792 // For example, manifest may say graphics.mapper@2.1 but passthroughServiceManager
793 // can only list graphics.mapper@2.0.
794 if (entryFqInstance.getPackage() == existingFqInstance.getPackage() &&
795 vintf::Version{entryFqInstance.getVersion()}
796 .minorAtLeast(vintf::Version{existingFqInstance.getVersion()})) {
797 return true;
798 }
799 }
800 return false;
801}
802
Yifan Hong443df792017-05-09 18:49:45 -0700803Status ListCommand::fetch() {
804 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700805 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700806 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700807 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700808 status |= NO_BINDERIZED_MANAGER;
809 } else {
810 status |= fetchBinderized(bManager);
811 // Passthrough PIDs are registered to the binderized manager as well.
812 status |= fetchPassthrough(bManager);
813 }
814
Yifan Hong9881df92017-05-10 14:33:05 -0700815 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700816 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700817 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700818 status |= NO_PASSTHROUGH_MANAGER;
819 } else {
820 status |= fetchAllLibraries(pManager);
821 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700822 status |= fetchManifestHals();
Yifan Hong3212f172018-06-28 12:39:50 -0700823 status |= fetchLazyHals();
Yifan Hong443df792017-05-09 18:49:45 -0700824 return status;
825}
826
Yifan Hong13ba0a92018-06-25 16:15:56 -0700827void ListCommand::initFetchTypes() {
Yifan Hong3212f172018-06-28 12:39:50 -0700828 // TODO: refactor to do polymorphism on each table (so that dependency graph is not hardcoded).
829 static const std::map<HalType, std::set<HalType>> kDependencyGraph{
830 {HalType::LAZY_HALS, {HalType::BINDERIZED_SERVICES,
831 HalType::PASSTHROUGH_LIBRARIES,
832 HalType::VINTF_MANIFEST}},
833 };
Yifan Hong13ba0a92018-06-25 16:15:56 -0700834 mFetchTypes.insert(mListTypes.begin(), mListTypes.end());
Yifan Hong3212f172018-06-28 12:39:50 -0700835 for (HalType listType : mListTypes) {
836 auto it = kDependencyGraph.find(listType);
837 if (it != kDependencyGraph.end()) {
838 mFetchTypes.insert(it->second.begin(), it->second.end());
839 }
840 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700841}
842
Yifan Hong30528a22020-08-07 18:24:06 -0700843// Get all values of enum type T, assuming the first value is 0 and the last value is T::LAST.
844// T::LAST is not included in the returned list.
845template <typename T>
846std::vector<T> GetAllValues() {
847 using BaseType = std::underlying_type_t<T>;
848 std::vector<T> ret;
849 for (BaseType i = 0; i < static_cast<BaseType>(T::LAST); ++i) {
850 ret.push_back(static_cast<T>(i));
851 }
852 return ret;
853}
854
Yifan Honga6b93f02017-09-13 16:53:37 -0700855void ListCommand::registerAllOptions() {
856 int v = mOptions.size();
857 // A list of acceptable command line options
858 // key: value returned by getopt_long
859 // long options with short alternatives
860 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
861 return USAGE;
862 }, ""});
863 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
864 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
865 return OK;
866 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700867 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
868 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
869 return OK;
Yifan Hong430f8982018-05-25 17:28:39 -0700870 }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700871 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
872 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
873 return OK;
874 }, "print the transport mode column"});
875 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
876 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
877 return OK;
878 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700879 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
880 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
881 return OK;
882 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700883 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
884 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
885 return OK;
886 }, "print the server PID, or server cmdline if -m is set"});
887 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
888 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
889 return OK;
890 }, "print the server object address column"});
891 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
892 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
893 return OK;
894 }, "print the client PIDs, or client cmdlines if -m is set"});
895 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
896 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
897 return OK;
898 }, "print currently used/available threads\n(note, available threads created lazily)"});
899 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
900 thiz->mEnableCmdlines = true;
901 return OK;
902 }, "print cmdline instead of PIDs"});
903 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
904 thiz->mEmitDebugInfo = true;
905 if (arg) thiz->mFileOutputPath = arg;
906 return OK;
907 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
908 "Writes to specified file if 'arg' is provided, otherwise stdout."});
909
Yifan Hongbdf44f82018-05-25 14:20:00 -0700910 mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
911 thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
912 return OK;
913 }, "print VINTF info. This column contains a comma-separated list of:\n"
Steven Morelanddbbbc652021-02-02 23:02:38 +0000914 " - DM: if the HIDL HAL is in the device manifest\n"
915 " - DC: if the HIDL HAL is in the device compatibility matrix\n"
916 " - FM: if the HIDL HAL is in the framework manifest\n"
917 " - FC: if the HIDL HAL is in the framework compatibility matrix\n"
918 " - X: if the HIDL HAL is in none of the above lists"});
Yifan Hong13ba0a92018-06-25 16:15:56 -0700919 mOptions.push_back({'S', "service-status", no_argument, v++, [](ListCommand* thiz, const char*) {
920 thiz->mSelectedColumns.push_back(TableColumnType::SERVICE_STATUS);
921 return OK;
922 }, "print service status column. Possible values are:\n"
923 " - alive: alive and running hwbinder service;\n"
924 " - registered;dead: registered to hwservicemanager but is not responsive;\n"
925 " - declared: only declared in VINTF manifest but is not registered to hwservicemanager;\n"
926 " - N/A: no information for passthrough HALs."});
Yifan Hongbdf44f82018-05-25 14:20:00 -0700927
Yifan Hong30528a22020-08-07 18:24:06 -0700928 mOptions.push_back({'A', "all", no_argument, v++,
929 [](ListCommand* thiz, const char*) {
930 auto allColumns = GetAllValues<TableColumnType>();
931 thiz->mSelectedColumns.insert(thiz->mSelectedColumns.end(),
932 allColumns.begin(), allColumns.end());
933 return OK;
934 },
935 "print all columns"});
936
Yifan Honga6b93f02017-09-13 16:53:37 -0700937 // long options without short alternatives
938 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
939 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800940 if (thiz->mVintfPartition == Partition::UNKNOWN)
941 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700942 if (arg) thiz->mFileOutputPath = arg;
943 return OK;
944 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800945 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
946 if (!arg) return USAGE;
947 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
948 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
949 return OK;
950 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
951 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700952 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
953 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
954 thiz->mSortColumn = TableEntry::sortByInterfaceName;
955 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
956 thiz->mSortColumn = TableEntry::sortByServerPid;
957 } else {
958 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
959 return USAGE;
960 }
961 return OK;
962 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
963 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
964 thiz->mNeat = true;
965 return OK;
966 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Yifan Hong30528a22020-08-07 18:24:06 -0700967 mOptions.push_back(
968 {'\0', "types", required_argument, v++,
969 [](ListCommand* thiz, const char* arg) {
970 if (!arg) {
971 return USAGE;
972 }
Nirav Atrecce988d2018-05-16 11:14:46 -0700973
Yifan Hong30528a22020-08-07 18:24:06 -0700974 static const std::map<std::string, std::vector<HalType>> kHalTypeMap{
975 {"binderized", {HalType::BINDERIZED_SERVICES}},
976 {"b", {HalType::BINDERIZED_SERVICES}},
977 {"passthrough_clients", {HalType::PASSTHROUGH_CLIENTS}},
978 {"c", {HalType::PASSTHROUGH_CLIENTS}},
979 {"passthrough_libs", {HalType::PASSTHROUGH_LIBRARIES}},
980 {"l", {HalType::PASSTHROUGH_LIBRARIES}},
981 {"vintf", {HalType::VINTF_MANIFEST}},
982 {"v", {HalType::VINTF_MANIFEST}},
983 {"lazy", {HalType::LAZY_HALS}},
984 {"z", {HalType::LAZY_HALS}},
985 {"all", GetAllValues<HalType>()},
986 {"a", GetAllValues<HalType>()},
987 };
Nirav Atrecce988d2018-05-16 11:14:46 -0700988
Yifan Hong30528a22020-08-07 18:24:06 -0700989 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
990 for (const auto& halTypeArg : halTypesArgs) {
991 if (halTypeArg.empty()) continue;
Nirav Atrecce988d2018-05-16 11:14:46 -0700992
Yifan Hong30528a22020-08-07 18:24:06 -0700993 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
994 if (halTypeIter == kHalTypeMap.end()) {
995 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
996 return USAGE;
997 }
Nirav Atrecce988d2018-05-16 11:14:46 -0700998
Yifan Hong30528a22020-08-07 18:24:06 -0700999 // Append unique (non-repeated) HAL types to the reporting list
1000 for (auto halType : halTypeIter->second) {
1001 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
1002 thiz->mListTypes.end()) {
1003 thiz->mListTypes.push_back(halType);
1004 }
1005 }
1006 }
Nirav Atrecce988d2018-05-16 11:14:46 -07001007
Yifan Hong30528a22020-08-07 18:24:06 -07001008 if (thiz->mListTypes.empty()) {
1009 return USAGE;
1010 }
1011 return OK;
1012 },
1013 "comma-separated list of one or more sections.\nThe output is restricted to the "
1014 "selected section(s). Valid options\nare: (b|binderized), (c|passthrough_clients), (l|"
1015 "passthrough_libs), (v|vintf), (z|lazy), and (a|all).\nDefault is `b,c,l`."});
Yifan Honga6b93f02017-09-13 16:53:37 -07001016}
1017
1018// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
1019// the lifetime of "options" during the usage of the returned array.
1020static std::unique_ptr<struct option[]> getLongOptions(
1021 const ListCommand::RegisteredOptions& options,
1022 int* longOptFlag) {
1023 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
1024 int i = 0;
1025 for (const auto& e : options) {
1026 ret[i].name = e.longOption.c_str();
1027 ret[i].has_arg = e.hasArg;
1028 ret[i].flag = longOptFlag;
1029 ret[i].val = e.val;
1030
1031 i++;
1032 }
1033 // getopt_long last option has all zeros
Yi Kong19d5c002018-07-20 13:39:55 -07001034 ret[i].name = nullptr;
Yifan Honga6b93f02017-09-13 16:53:37 -07001035 ret[i].has_arg = 0;
Yi Kong19d5c002018-07-20 13:39:55 -07001036 ret[i].flag = nullptr;
Yifan Honga6b93f02017-09-13 16:53:37 -07001037 ret[i].val = 0;
1038
1039 return ret;
1040}
1041
1042// Create 'optstring' argument to getopt_long.
1043static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
1044 std::stringstream ss;
1045 for (const auto& e : options) {
1046 if (e.shortOption != '\0') {
1047 ss << e.shortOption;
1048 }
1049 }
1050 return ss.str();
1051}
1052
Yifan Honga8bedc62017-09-08 18:00:31 -07001053Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -07001054 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -07001055
Yifan Honga6b93f02017-09-13 16:53:37 -07001056 if (mOptions.empty()) {
1057 registerAllOptions();
1058 }
1059 int longOptFlag;
1060 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
1061 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001062
Yifan Honga8bedc62017-09-08 18:00:31 -07001063 // suppress output to std::err for unknown options
1064 opterr = 0;
1065
Yifan Hong443df792017-05-09 18:49:45 -07001066 int optionIndex;
1067 int c;
1068 // Lshal::parseArgs has set optind to the next option to parse
1069 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -07001070 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -07001071 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -07001072 if (c == -1) {
1073 break;
1074 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001075 const RegisteredOption* found = nullptr;
1076 if (c == 0) {
1077 // see long option
1078 for (const auto& e : mOptions) {
1079 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -07001080 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001081 } else {
1082 // see short option
1083 for (const auto& e : mOptions) {
1084 if (c == e.shortOption) found = &e;
1085 }
Yifan Hong443df792017-05-09 18:49:45 -07001086 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001087
1088 if (found == nullptr) {
1089 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -07001090 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -07001091 return USAGE;
1092 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001093
1094 Status status = found->op(this, optarg);
1095 if (status != OK) {
1096 return status;
1097 }
Yifan Hong443df792017-05-09 18:49:45 -07001098 }
1099 if (optind < arg.argc) {
1100 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -07001101 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001102 return USAGE;
1103 }
1104
1105 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -07001106 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001107 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -07001108 }
1109
Yifan Honga6b93f02017-09-13 16:53:37 -07001110 if (mSelectedColumns.empty()) {
Steven Moreland8e0f5392018-12-12 14:27:24 -08001111 mSelectedColumns = {TableColumnType::VINTF, TableColumnType::RELEASED,
Yifan Hongfee209d2017-09-14 18:23:38 -07001112 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -07001113 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -07001114 }
Yifan Hongd4a77e82017-09-06 19:40:24 -07001115
Yifan Honga6b93f02017-09-13 16:53:37 -07001116 if (mEnableCmdlines) {
1117 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
1118 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
1119 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001120 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001121 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
1122 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001123 }
1124 }
1125 }
1126
Nirav Atrecce988d2018-05-16 11:14:46 -07001127 // By default, list all HAL types
1128 if (mListTypes.empty()) {
1129 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
1130 HalType::PASSTHROUGH_LIBRARIES};
1131 }
Yifan Hong13ba0a92018-06-25 16:15:56 -07001132 initFetchTypes();
Nirav Atrecce988d2018-05-16 11:14:46 -07001133
Yifan Honga6b93f02017-09-13 16:53:37 -07001134 forEachTable([this] (Table& table) {
1135 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001136 });
1137
Yifan Hong443df792017-05-09 18:49:45 -07001138 return OK;
1139}
1140
Yifan Honga8bedc62017-09-08 18:00:31 -07001141Status ListCommand::main(const Arg &arg) {
1142 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -07001143 if (status != OK) {
1144 return status;
1145 }
1146 status = fetch();
1147 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -07001148 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -07001149 return status;
1150}
1151
Yifan Honga6b93f02017-09-13 16:53:37 -07001152const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
1153 static const std::string empty{};
1154 static const std::string optional{"[=<arg>]"};
1155 static const std::string required{"=<arg>"};
1156
1157 if (hasArg == optional_argument) {
1158 return optional;
1159 }
1160 if (hasArg == required_argument) {
1161 return required;
1162 }
1163 return empty;
1164}
1165
Yifan Honga8bedc62017-09-08 18:00:31 -07001166void ListCommand::usage() const {
1167
Yifan Honga6b93f02017-09-13 16:53:37 -07001168 err() << "list:" << std::endl
1169 << " lshal" << std::endl
1170 << " lshal list" << std::endl
Steven Moreland8e0f5392018-12-12 14:27:24 -08001171 << " List all hals with default ordering and columns (`lshal list -Vliepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001172 << " lshal list [-h|--help]" << std::endl
1173 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1174 << " lshal [list] [OPTIONS...]" << std::endl;
1175 for (const auto& e : mOptions) {
1176 if (e.help.empty()) {
1177 continue;
1178 }
1179 err() << " ";
1180 if (e.shortOption != '\0')
1181 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1182 if (e.shortOption != '\0' && !e.longOption.empty())
1183 err() << ", ";
1184 if (!e.longOption.empty())
1185 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1186 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001187 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001188 for (const auto& line : lines) {
1189 if (&line != &lines.front())
1190 err() << " ";
1191 err() << line << std::endl;
1192 }
1193 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001194}
1195
Yifan Hong443df792017-05-09 18:49:45 -07001196} // namespace lshal
1197} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001198