blob: 5560463b1eb6150adaecfc97991c4011969754f9 [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
Yifan Hongb670dd72023-12-18 18:08:18 -080047using ::android::hardware::hidl_array;
Yifan Hong443df792017-05-09 18:49:45 -070048using ::android::hardware::hidl_string;
Yifan Hong22ea7b82017-09-14 18:07:43 -070049using ::android::hardware::hidl_vec;
50using ::android::hidl::base::V1_0::DebugInfo;
51using ::android::hidl::base::V1_0::IBase;
Yifan Hong443df792017-05-09 18:49:45 -070052using ::android::hidl::manager::V1_0::IServiceManager;
53
54namespace android {
55namespace lshal {
56
Yifan Hongf31aa052018-02-02 15:17:51 -080057vintf::SchemaType toSchemaType(Partition p) {
58 return (p == Partition::SYSTEM) ? vintf::SchemaType::FRAMEWORK : vintf::SchemaType::DEVICE;
59}
60
Yifan Hong13ba0a92018-06-25 16:15:56 -070061Partition toPartition(vintf::SchemaType t) {
62 switch (t) {
63 case vintf::SchemaType::FRAMEWORK: return Partition::SYSTEM;
64 // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
65 case vintf::SchemaType::DEVICE: return Partition::VENDOR;
66 }
67 return Partition::UNKNOWN;
68}
69
70std::string getPackageAndVersion(const std::string& fqInstance) {
71 return splitFirst(fqInstance, ':').first;
72}
73
Yifan Hong76ac14a2017-09-08 14:59:04 -070074NullableOStream<std::ostream> ListCommand::out() const {
75 return mLshal.out();
76}
77
78NullableOStream<std::ostream> ListCommand::err() const {
79 return mLshal.err();
Yifan Hong443df792017-05-09 18:49:45 -070080}
81
Yifan Hong795b6ec2017-09-13 11:25:28 -070082std::string ListCommand::GetName() {
83 return "list";
84}
85std::string ListCommand::getSimpleDescription() const {
Steven Morelanddbbbc652021-02-02 23:02:38 +000086 return "List HIDL HALs.";
Yifan Hong795b6ec2017-09-13 11:25:28 -070087}
88
Yifan Hong8bf73162017-09-07 18:06:13 -070089std::string ListCommand::parseCmdline(pid_t pid) const {
Yifan Hongf31aa052018-02-02 15:17:51 -080090 return android::procpartition::getCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -070091}
92
93const std::string &ListCommand::getCmdline(pid_t pid) {
Yifan Hong13ba0a92018-06-25 16:15:56 -070094 static const std::string kEmptyString{};
95 if (pid == NO_PID) return kEmptyString;
Yifan Hong443df792017-05-09 18:49:45 -070096 auto pair = mCmdlines.find(pid);
97 if (pair != mCmdlines.end()) {
98 return pair->second;
99 }
Yifan Hong8bf73162017-09-07 18:06:13 -0700100 mCmdlines[pid] = parseCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -0700101 return mCmdlines[pid];
102}
103
104void ListCommand::removeDeadProcesses(Pids *pids) {
105 static const pid_t myPid = getpid();
Yifan Hong61fb7bc2017-05-12 16:33:57 -0700106 pids->erase(std::remove_if(pids->begin(), pids->end(), [this](auto pid) {
Yifan Hong443df792017-05-09 18:49:45 -0700107 return pid == myPid || this->getCmdline(pid).empty();
Yifan Hong61fb7bc2017-05-12 16:33:57 -0700108 }), pids->end());
Yifan Hong443df792017-05-09 18:49:45 -0700109}
110
Yifan Hongf31aa052018-02-02 15:17:51 -0800111Partition ListCommand::getPartition(pid_t pid) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700112 if (pid == NO_PID) return Partition::UNKNOWN;
Yifan Hongf31aa052018-02-02 15:17:51 -0800113 auto it = mPartitions.find(pid);
114 if (it != mPartitions.end()) {
115 return it->second;
116 }
117 Partition partition = android::procpartition::getPartition(pid);
118 mPartitions.emplace(pid, partition);
119 return partition;
120}
121
122// Give sensible defaults when nothing can be inferred from runtime.
123// process: Partition inferred from executable location or cmdline.
Yifan Hongb2d096a2018-05-01 15:25:23 -0700124Partition ListCommand::resolvePartition(Partition process, const FqInstance& fqInstance) const {
125 if (fqInstance.inPackage("vendor") || fqInstance.inPackage("com")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800126 return Partition::VENDOR;
127 }
128
Yifan Hongb2d096a2018-05-01 15:25:23 -0700129 if (fqInstance.inPackage("android.frameworks") || fqInstance.inPackage("android.system") ||
130 fqInstance.inPackage("android.hidl")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800131 return Partition::SYSTEM;
132 }
133
134 // Some android.hardware HALs are served from system. Check the value from executable
135 // location / cmdline first.
Yifan Hongb2d096a2018-05-01 15:25:23 -0700136 if (fqInstance.inPackage("android.hardware")) {
Yifan Hongf31aa052018-02-02 15:17:51 -0800137 if (process != Partition::UNKNOWN) {
138 return process;
139 }
140 return Partition::VENDOR;
141 }
142
143 return process;
144}
145
Yifan Hongbdf44f82018-05-25 14:20:00 -0700146bool match(const vintf::ManifestInstance& instance, const FqInstance& fqInstance,
147 vintf::TransportArch ta) {
148 // For hwbinder libs, allow missing arch in manifest.
149 // For passthrough libs, allow missing interface/instance in table.
150 return (ta.transport == instance.transport()) &&
151 (ta.transport == vintf::Transport::HWBINDER ||
152 vintf::contains(instance.arch(), ta.arch)) &&
153 (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
154 (!fqInstance.hasInstance() || fqInstance.getInstance() == instance.instance());
155}
156
157bool match(const vintf::MatrixInstance& instance, const FqInstance& fqInstance,
158 vintf::TransportArch /* ta */) {
159 return (!fqInstance.hasInterface() || fqInstance.getInterface() == instance.interface()) &&
160 (!fqInstance.hasInstance() || instance.matchInstance(fqInstance.getInstance()));
161}
162
163template <typename ObjectType>
164VintfInfo getVintfInfo(const std::shared_ptr<const ObjectType>& object,
165 const FqInstance& fqInstance, vintf::TransportArch ta, VintfInfo value) {
166 bool found = false;
Yifan Hongc346a162019-09-10 19:35:55 -0700167 (void)object->forEachHidlInstanceOfVersion(fqInstance.getPackage(), fqInstance.getVersion(),
168 [&](const auto& instance) {
169 found = match(instance, fqInstance, ta);
170 return !found; // continue if not found
171 });
Yifan Hongbdf44f82018-05-25 14:20:00 -0700172 return found ? value : VINTF_INFO_EMPTY;
173}
174
175std::shared_ptr<const vintf::HalManifest> ListCommand::getDeviceManifest() const {
176 return vintf::VintfObject::GetDeviceHalManifest();
177}
178
179std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getDeviceMatrix() const {
180 return vintf::VintfObject::GetDeviceCompatibilityMatrix();
181}
182
183std::shared_ptr<const vintf::HalManifest> ListCommand::getFrameworkManifest() const {
184 return vintf::VintfObject::GetFrameworkHalManifest();
185}
186
187std::shared_ptr<const vintf::CompatibilityMatrix> ListCommand::getFrameworkMatrix() const {
188 return vintf::VintfObject::GetFrameworkCompatibilityMatrix();
189}
190
191VintfInfo ListCommand::getVintfInfo(const std::string& fqInstanceName,
192 vintf::TransportArch ta) const {
193 FqInstance fqInstance;
194 if (!fqInstance.setTo(fqInstanceName) &&
195 // Ignore interface / instance for passthrough libs
Yifan Hong13ba0a92018-06-25 16:15:56 -0700196 !fqInstance.setTo(getPackageAndVersion(fqInstanceName))) {
Yifan Hongbdf44f82018-05-25 14:20:00 -0700197 err() << "Warning: Cannot parse '" << fqInstanceName << "'; no VINTF info." << std::endl;
198 return VINTF_INFO_EMPTY;
199 }
200
201 return lshal::getVintfInfo(getDeviceManifest(), fqInstance, ta, DEVICE_MANIFEST) |
202 lshal::getVintfInfo(getFrameworkManifest(), fqInstance, ta, FRAMEWORK_MANIFEST) |
203 lshal::getVintfInfo(getDeviceMatrix(), fqInstance, ta, DEVICE_MATRIX) |
204 lshal::getVintfInfo(getFrameworkMatrix(), fqInstance, ta, FRAMEWORK_MATRIX);
205}
206
Steven Morelandd8e20192017-05-24 11:23:08 -0700207bool ListCommand::getPidInfo(
Devin Moorec03e3aa2020-12-11 15:11:17 -0800208 pid_t serverPid, BinderPidInfo *pidInfo) const {
209 const auto& status = getBinderPidInfo(BinderDebugContext::HWBINDER, serverPid, pidInfo);
210 return status == OK;
Steven Morelandd8e20192017-05-24 11:23:08 -0700211}
212
Devin Moorec03e3aa2020-12-11 15:11:17 -0800213const BinderPidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
214 auto pair = mCachedPidInfos.insert({serverPid, BinderPidInfo{}});
Yifan Hong1243dde2017-09-14 17:49:30 -0700215 if (pair.second /* did insertion take place? */) {
216 if (!getPidInfo(serverPid, &pair.first->second)) {
217 return nullptr;
218 }
219 }
220 return &pair.first->second;
221}
222
Yifan Hong13ba0a92018-06-25 16:15:56 -0700223bool ListCommand::shouldFetchHalType(const HalType &type) const {
224 return (std::find(mFetchTypes.begin(), mFetchTypes.end(), type) != mFetchTypes.end());
Nirav Atrecce988d2018-05-16 11:14:46 -0700225}
226
Yifan Hongdb730532018-06-25 16:32:01 -0700227Table* ListCommand::tableForType(HalType type) {
228 switch (type) {
229 case HalType::BINDERIZED_SERVICES:
230 return &mServicesTable;
231 case HalType::PASSTHROUGH_CLIENTS:
232 return &mPassthroughRefTable;
233 case HalType::PASSTHROUGH_LIBRARIES:
234 return &mImplementationsTable;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700235 case HalType::VINTF_MANIFEST:
236 return &mManifestHalsTable;
Yifan Hong3212f172018-06-28 12:39:50 -0700237 case HalType::LAZY_HALS:
238 return &mLazyHalsTable;
Yifan Hongdb730532018-06-25 16:32:01 -0700239 default:
240 LOG(FATAL) << "Unknown HAL type " << static_cast<int64_t>(type);
241 return nullptr;
242 }
243}
244const Table* ListCommand::tableForType(HalType type) const {
245 return const_cast<ListCommand*>(this)->tableForType(type);
Yifan Hong443df792017-05-09 18:49:45 -0700246}
247
248void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700249 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700250 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700251 }
Yifan Hong443df792017-05-09 18:49:45 -0700252}
253void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
Nirav Atrecce988d2018-05-16 11:14:46 -0700254 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700255 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700256 }
Yifan Hong443df792017-05-09 18:49:45 -0700257}
258
259void ListCommand::postprocess() {
260 forEachTable([this](Table &table) {
261 if (mSortColumn) {
262 std::sort(table.begin(), table.end(), mSortColumn);
263 }
264 for (TableEntry &entry : table) {
265 entry.serverCmdline = getCmdline(entry.serverPid);
266 removeDeadProcesses(&entry.clientPids);
267 for (auto pid : entry.clientPids) {
268 entry.clientCmdlines.push_back(this->getCmdline(pid));
269 }
270 }
Yifan Hongf31aa052018-02-02 15:17:51 -0800271 for (TableEntry& entry : table) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700272 if (entry.partition == Partition::UNKNOWN) {
273 entry.partition = getPartition(entry.serverPid);
274 }
Yifan Hongbdf44f82018-05-25 14:20:00 -0700275 entry.vintfInfo = getVintfInfo(entry.interfaceName, {entry.transport, entry.arch});
Yifan Hongf31aa052018-02-02 15:17:51 -0800276 }
Yifan Hong443df792017-05-09 18:49:45 -0700277 });
278 // use a double for loop here because lshal doesn't care about efficiency.
279 for (TableEntry &packageEntry : mImplementationsTable) {
280 std::string packageName = packageEntry.interfaceName;
Steven Morelandd4f32b32018-03-06 14:47:58 -0800281 FQName fqPackageName;
282 if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700283 continue;
284 }
285 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700286 if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
Yifan Hong443df792017-05-09 18:49:45 -0700287 continue;
288 }
Steven Morelandd4f32b32018-03-06 14:47:58 -0800289 FQName interfaceName;
290 if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700291 continue;
292 }
293 if (interfaceName.getPackageAndVersion() == fqPackageName) {
294 interfaceEntry.arch = packageEntry.arch;
295 }
296 }
297 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700298
299 mServicesTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000300 "| All HIDL binderized services (registered with hwservicemanager)");
Yifan Hongca3b6602017-09-07 16:44:27 -0700301 mPassthroughRefTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000302 "| All HIDL interfaces getService() has ever returned as a passthrough interface;\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800303 "| PIDs / processes shown below might be inaccurate because the process\n"
304 "| might have relinquished the interface or might have died.\n"
305 "| The Server / Server CMD column can be ignored.\n"
306 "| The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
307 "| the library and successfully fetched the passthrough implementation.");
Yifan Hongca3b6602017-09-07 16:44:27 -0700308 mImplementationsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000309 "| All available HIDL passthrough implementations (all -impl.so files).\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800310 "| These may return subclasses through their respective HIDL_FETCH_I* functions.");
Yifan Hong13ba0a92018-06-25 16:15:56 -0700311 mManifestHalsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000312 "| All HIDL HALs that are in VINTF manifest.");
Yifan Hong3212f172018-06-28 12:39:50 -0700313 mLazyHalsTable.setDescription(
Steven Morelanddbbbc652021-02-02 23:02:38 +0000314 "| All HIDL HALs that are declared in VINTF manifest:\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800315 "| - as hwbinder HALs but are not registered to hwservicemanager, and\n"
316 "| - as hwbinder/passthrough HALs with no implementation.");
Yifan Hong443df792017-05-09 18:49:45 -0700317}
318
Yifan Hongb2d096a2018-05-01 15:25:23 -0700319bool ListCommand::addEntryWithInstance(const TableEntry& entry,
320 vintf::HalManifest* manifest) const {
321 FqInstance fqInstance;
322 if (!fqInstance.setTo(entry.interfaceName)) {
323 err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
324 return false;
Yifan Hong77c87822017-06-19 15:47:39 -0700325 }
Yifan Hongb2d096a2018-05-01 15:25:23 -0700326
Steven Moreland7a99e042020-02-26 13:16:34 -0800327 if (fqInstance.getPackage() == "android.hidl.base") {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700328 return true; // always remove IBase from manifest
329 }
330
331 Partition partition = resolvePartition(entry.partition, fqInstance);
332
333 if (partition == Partition::UNKNOWN) {
334 err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
335 << std::endl;
336 return false;
337 }
338
339 if (partition != mVintfPartition) {
340 return true; // strip out instances that is in a different partition.
341 }
342
Yifan Hongb2d096a2018-05-01 15:25:23 -0700343 vintf::Arch arch;
Yifan Hong8304e412018-05-25 15:05:36 -0700344 if (entry.transport == vintf::Transport::HWBINDER) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700345 arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
Yifan Hong8304e412018-05-25 15:05:36 -0700346 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700347 if (entry.arch == vintf::Arch::ARCH_EMPTY) {
348 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
349 return false;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700350 }
Yifan Hong0ad64f52018-05-25 15:29:17 -0700351 arch = entry.arch;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700352 } else {
353 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
354 return false;
355 }
356
Yifan Hongcb5a1ab2023-01-12 14:55:55 -0800357 auto vintfFqInstance = vintf::FqInstance::from(fqInstance.string());
358 if (!vintfFqInstance.has_value()) {
359 err() << "Unable to convert " << fqInstance.string() << " to vintf::FqInstance"
360 << std::endl;
361 return false;
362 }
363
Yifan Hongb2d096a2018-05-01 15:25:23 -0700364 std::string e;
Yifan Hongcb5a1ab2023-01-12 14:55:55 -0800365 if (!manifest->insertInstance(*vintfFqInstance, entry.transport, arch, vintf::HalFormat::HIDL,
366 &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700367 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
368 return false;
369 }
370 return true;
371}
372
373bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
374 const vintf::HalManifest* manifest) const {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700375 const auto& packageAndVersion = splitFirst(getPackageAndVersion(entry.interfaceName), '@');
Yifan Hongb2d096a2018-05-01 15:25:23 -0700376 const auto& package = packageAndVersion.first;
377 vintf::Version version;
378 if (!vintf::parse(packageAndVersion.second, &version)) {
379 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
380 << entry.interfaceName << "'" << std::endl;
381 return false;
382 }
383
384 bool found = false;
Yifan Hongc346a162019-09-10 19:35:55 -0700385 (void)manifest->forEachHidlInstanceOfVersion(package, version, [&found](const auto&) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700386 found = true;
387 return false; // break
388 });
389 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700390}
391
Yifan Hongca3b6602017-09-07 16:44:27 -0700392void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700393 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800394 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700395 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700396
397 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800398 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700399
Yifan Hongb2d096a2018-05-01 15:25:23 -0700400 std::vector<std::string> error;
401 for (const TableEntry& entry : mServicesTable)
402 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
403 for (const TableEntry& entry : mPassthroughRefTable)
404 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700405 for (const TableEntry& entry : mManifestHalsTable)
406 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700407
Yifan Hongb2d096a2018-05-01 15:25:23 -0700408 std::vector<std::string> passthrough;
409 for (const TableEntry& entry : mImplementationsTable)
410 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800411
Yifan Hongf31aa052018-02-02 15:17:51 -0800412 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700413 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
414 << INIT_VINTF_NOTES;
415 if (!error.empty()) {
416 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
417 for (const auto& e : error) {
418 out << " " << e << std::endl;
419 }
420 }
421 if (!passthrough.empty()) {
422 out << std::endl
423 << " The following HALs are passthrough and no interface or instance " << std::endl
424 << " names can be inferred." << std::endl;
425 for (const auto& e : passthrough) {
426 out << " " << e << std::endl;
427 }
428 }
429 out << "-->" << std::endl;
Yifan Honga96f87f2021-04-16 18:59:27 -0700430 out << vintf::toXml(manifest, vintf::SerializeFlags::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700431}
432
Yifan Hongf31aa052018-02-02 15:17:51 -0800433std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700434 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800435 " only hwbinder is shown.\n"
436 " 2. It is likely that HALs in passthrough transport does not have\n"
437 " <interface> declared; users will have to write them by hand.\n"
438 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
439 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700440 " 4. This output is intended for launch devices.\n"
441 " Upgrading devices should not use this tool to generate device\n"
442 " manifest and replace the existing manifest directly, but should\n"
443 " edit the existing manifest manually.\n"
444 " Specifically, devices which launched at Android O-MR1 or earlier\n"
445 " should not use the 'fqname' format for required HAL entries and\n"
446 " should instead use the legacy package, name, instance-name format\n"
447 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800448};
449
Yifan Hong0ad64f52018-05-25 15:29:17 -0700450static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
Yifan Hong443df792017-05-09 18:49:45 -0700451 switch (a) {
452 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700453 return vintf::Arch::ARCH_64;
Yifan Hong443df792017-05-09 18:49:45 -0700454 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700455 return vintf::Arch::ARCH_32;
Yifan Hong443df792017-05-09 18:49:45 -0700456 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
457 default:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700458 return vintf::Arch::ARCH_EMPTY;
Yifan Hong443df792017-05-09 18:49:45 -0700459 }
460}
461
Yifan Hongca3b6602017-09-07 16:44:27 -0700462void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700463 if (mNeat) {
Yifan Hongb72f19e2018-06-27 16:58:56 -0700464 std::vector<const Table*> tables;
465 forEachTable([&tables](const Table &table) {
466 tables.push_back(&table);
467 });
468 MergedTable(std::move(tables)).createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700469 return;
470 }
471
Yifan Hongca3b6602017-09-07 16:44:27 -0700472 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700473
Yifan Hongd4a77e82017-09-06 19:40:24 -0700474 // We're only interested in dumping debug info for already
475 // instantiated services. There's little value in dumping the
476 // debug info for a service we create on the fly, so we only operate
477 // on the "mServicesTable".
478 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
479 if (mEmitDebugInfo && &table == &mServicesTable) {
480 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700481 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700482 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800483 mLshal.emitDebugInfo(pair.first, pair.second, {},
Yifan Hong6884b872020-07-09 16:38:18 -0700484 ParentDebugInfoLevel::FQNAME_ONLY, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700485 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700486 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700487 };
Yifan Hong443df792017-05-09 18:49:45 -0700488 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700489 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
490 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700491 });
Yifan Hong443df792017-05-09 18:49:45 -0700492}
493
Yifan Hongca3b6602017-09-07 16:44:27 -0700494Status ListCommand::dump() {
495 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
496
497 if (mFileOutputPath.empty()) {
498 (*this.*dump)(out());
499 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700500 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700501
502 std::ofstream fileOutput(mFileOutputPath);
503 if (!fileOutput.is_open()) {
504 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
505 return IO_ERROR;
506 }
507 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
508
509 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
510
511 fileOutput.flush();
512 fileOutput.close();
513 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700514}
515
Yifan Hong20f4ee82018-06-25 16:21:29 -0700516void ListCommand::putEntry(HalType type, TableEntry &&entry) {
Yifan Hongdb730532018-06-25 16:32:01 -0700517 tableForType(type)->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700518}
519
520Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700521 if (!shouldFetchHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700522
Yifan Hong443df792017-05-09 18:49:45 -0700523 using namespace ::android::hardware;
524 using namespace ::android::hidl::manager::V1_0;
525 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700526 using std::literals::chrono_literals::operator""s;
Yifan Hongb670dd72023-12-18 18:08:18 -0800527
528 // The lambda function may be executed asynchrounously because it is passed to timeoutIPC,
529 // even though the interface function call is synchronous.
530 // However, there's no need to lock because if ret.isOk(), the background thread has
531 // already ended, so it is safe to dereference entries.
532 auto entries = std::make_shared<std::map<std::string, TableEntry>>();
533 auto ret = timeoutIPC(10s, manager, &IServiceManager::debugDump, [entries](const auto& infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700534 for (const auto &info : infos) {
535 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
536 std::string{info.instanceName.c_str()};
Yifan Hongb670dd72023-12-18 18:08:18 -0800537 entries->emplace(interfaceName,
538 TableEntry{
539 .interfaceName = interfaceName,
540 .transport = vintf::Transport::PASSTHROUGH,
541 .clientPids = info.clientPids,
542 })
543 .first->second.arch |= fromBaseArchitecture(info.arch);
Yifan Hong443df792017-05-09 18:49:45 -0700544 }
545 });
546 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700547 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700548 << ret.description() << std::endl;
549 return DUMP_ALL_LIBS_ERROR;
550 }
Yifan Hongb670dd72023-12-18 18:08:18 -0800551 for (auto&& pair : *entries) {
552 putEntry(HalType::PASSTHROUGH_LIBRARIES, std::move(pair.second));
553 }
Yifan Hong443df792017-05-09 18:49:45 -0700554 return OK;
555}
556
557Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700558 if (!shouldFetchHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700559
Yifan Hong443df792017-05-09 18:49:45 -0700560 using namespace ::android::hardware;
561 using namespace ::android::hardware::details;
562 using namespace ::android::hidl::manager::V1_0;
563 using namespace ::android::hidl::base::V1_0;
Yifan Hongb670dd72023-12-18 18:08:18 -0800564
565 // The lambda function may be executed asynchrounously because it is passed to timeoutIPC,
566 // even though the interface function call is synchronous.
567 // However, there's no need to lock because if ret.isOk(), the background thread has
568 // already ended, so it is safe to dereference entries.
569 auto entries = std::make_shared<std::vector<TableEntry>>();
570 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [entries](const auto& infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700571 for (const auto &info : infos) {
572 if (info.clientPids.size() <= 0) {
573 continue;
574 }
Yifan Hongb670dd72023-12-18 18:08:18 -0800575 entries->emplace_back(
576 TableEntry{.interfaceName = std::string{info.interfaceName.c_str()} + "/" +
577 std::string{info.instanceName.c_str()},
578 .transport = vintf::Transport::PASSTHROUGH,
579 .serverPid =
580 info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
581 .clientPids = info.clientPids,
582 .arch = fromBaseArchitecture(info.arch)});
Yifan Hong443df792017-05-09 18:49:45 -0700583 }
584 });
585 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700586 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700587 << ret.description() << std::endl;
588 return DUMP_PASSTHROUGH_ERROR;
589 }
Yifan Hongb670dd72023-12-18 18:08:18 -0800590 for (auto&& entry : *entries) {
591 putEntry(HalType::PASSTHROUGH_CLIENTS, std::move(entry));
592 }
Yifan Hong443df792017-05-09 18:49:45 -0700593 return OK;
594}
595
596Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700597 using vintf::operator<<;
598
Yifan Hong13ba0a92018-06-25 16:15:56 -0700599 if (!shouldFetchHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700600
Yifan Hong8304e412018-05-25 15:05:36 -0700601 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hongb670dd72023-12-18 18:08:18 -0800602
603 // The lambda function may be executed asynchrounously because it is passed to timeoutIPC,
604 // even though the interface function call is synchronous.
605 // However, there's no need to lock because if listRet.isOk(), the background thread has
606 // already ended, so it is safe to dereference fqInstanceNames.
607 auto fqInstanceNames = std::make_shared<hidl_vec<hidl_string>>();
608 auto listRet = timeoutIPC(manager, &IServiceManager::list,
609 [fqInstanceNames](const auto& names) { *fqInstanceNames = names; });
Yifan Hong443df792017-05-09 18:49:45 -0700610 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700611 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700612 << listRet.description() << std::endl;
613 return DUMP_BINDERIZED_ERROR;
614 }
615
616 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700617 std::map<std::string, TableEntry> allTableEntries;
Yifan Hongb670dd72023-12-18 18:08:18 -0800618 for (const auto& fqInstanceName : *fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700619 // create entry and default assign all fields.
620 TableEntry& entry = allTableEntries[fqInstanceName];
621 entry.interfaceName = fqInstanceName;
622 entry.transport = mode;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700623 entry.serviceStatus = ServiceStatus::NON_RESPONSIVE;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700624
625 status |= fetchBinderizedEntry(manager, &entry);
626 }
627
628 for (auto& pair : allTableEntries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700629 putEntry(HalType::BINDERIZED_SERVICES, std::move(pair.second));
Yifan Hong22ea7b82017-09-14 18:07:43 -0700630 }
631 return status;
632}
633
634Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
635 TableEntry *entry) {
636 Status status = OK;
637 const auto handleError = [&](Status additionalError, const std::string& msg) {
638 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
639 status |= DUMP_BINDERIZED_ERROR | additionalError;
640 };
641
642 const auto pair = splitFirst(entry->interfaceName, '/');
643 const auto &serviceName = pair.first;
644 const auto &instanceName = pair.second;
645 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
646 if (!getRet.isOk()) {
647 handleError(TRANSACTION_ERROR,
648 "cannot be fetched from service manager:" + getRet.description());
649 return status;
650 }
651 sp<IBase> service = getRet;
652 if (service == nullptr) {
653 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
654 return status;
655 }
656
657 // getDebugInfo
658 do {
Yifan Hongb670dd72023-12-18 18:08:18 -0800659 // The lambda function may be executed asynchrounously because it is passed to timeoutIPC,
660 // even though the interface function call is synchronous.
661 // However, there's no need to lock because if debugRet.isOk(), the background thread has
662 // already ended, so it is safe to dereference debugInfo.
663 auto debugInfo = std::make_shared<DebugInfo>();
664 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo,
665 [debugInfo](const auto& received) { *debugInfo = received; });
Yifan Hong443df792017-05-09 18:49:45 -0700666 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700667 handleError(TRANSACTION_ERROR,
668 "debugging information cannot be retrieved: " + debugRet.description());
669 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700670 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700671
Yifan Hongb670dd72023-12-18 18:08:18 -0800672 entry->serverPid = debugInfo->pid;
673 entry->serverObjectAddress = debugInfo->ptr;
674 entry->arch = fromBaseArchitecture(debugInfo->arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700675
Yifan Hongb670dd72023-12-18 18:08:18 -0800676 if (debugInfo->pid != NO_PID) {
677 const BinderPidInfo* pidInfo = getPidInfoCached(debugInfo->pid);
Yifan Hong22ea7b82017-09-14 18:07:43 -0700678 if (pidInfo == nullptr) {
679 handleError(IO_ERROR,
Yifan Hongb670dd72023-12-18 18:08:18 -0800680 "no information for PID " + std::to_string(debugInfo->pid) +
681 ", are you root?");
Yifan Hong22ea7b82017-09-14 18:07:43 -0700682 break;
683 }
Yifan Hongb670dd72023-12-18 18:08:18 -0800684 if (debugInfo->ptr != NO_PTR) {
685 auto it = pidInfo->refPids.find(debugInfo->ptr);
Yifan Hong22ea7b82017-09-14 18:07:43 -0700686 if (it != pidInfo->refPids.end()) {
687 entry->clientPids = it->second;
688 }
689 }
690 entry->threadUsage = pidInfo->threadUsage;
691 entry->threadCount = pidInfo->threadCount;
692 }
693 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700694
695 // hash
696 do {
Yifan Hongb670dd72023-12-18 18:08:18 -0800697 // The lambda function may be executed asynchrounously because it is passed to timeoutIPC,
698 // even though the interface function call is synchronous.
699 auto hashIndexStore = std::make_shared<ssize_t>(-1);
700 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain,
701 [hashIndexStore, serviceName](const auto& c) {
702 for (size_t i = 0; i < c.size(); ++i) {
703 if (serviceName == c[i]) {
704 *hashIndexStore = static_cast<ssize_t>(i);
705 break;
706 }
707 }
708 });
Yifan Hongfee209d2017-09-14 18:23:38 -0700709 if (!ifaceChainRet.isOk()) {
710 handleError(TRANSACTION_ERROR,
711 "interfaceChain fails: " + ifaceChainRet.description());
712 break; // skip getHashChain
713 }
Yifan Hongb670dd72023-12-18 18:08:18 -0800714 // if ifaceChainRet.isOk(), the background thread has already ended, so it is safe to
715 // dereference hashIndex without any locking.
716 auto hashIndex = *hashIndexStore;
Yifan Hongfee209d2017-09-14 18:23:38 -0700717 if (hashIndex < 0) {
718 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
719 break; // skip getHashChain
720 }
Yifan Hongb670dd72023-12-18 18:08:18 -0800721 // See comments about hashIndex above.
722 auto hashChain = std::make_shared<hidl_vec<hidl_array<uint8_t, 32>>>();
723 auto hashRet = timeoutIPC(service, &IBase::getHashChain,
724 [hashChain](const auto& ret) { *hashChain = std::move(ret); });
Yifan Hongfee209d2017-09-14 18:23:38 -0700725 if (!hashRet.isOk()) {
726 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
727 }
Yifan Hongb670dd72023-12-18 18:08:18 -0800728 if (static_cast<size_t>(hashIndex) >= hashChain->size()) {
729 handleError(BAD_IMPL,
730 "interfaceChain indicates position " + std::to_string(hashIndex) +
731 " but getHashChain returns " + std::to_string(hashChain->size()) +
732 " hashes");
733 } else {
734 auto&& hashArray = (*hashChain)[hashIndex];
735 entry->hash = android::base::HexString(hashArray.data(), hashArray.size());
736 }
Yifan Hongfee209d2017-09-14 18:23:38 -0700737 } while (0);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700738 if (status == OK) {
739 entry->serviceStatus = ServiceStatus::ALIVE;
740 }
Yifan Hong443df792017-05-09 18:49:45 -0700741 return status;
742}
743
Yifan Hong13ba0a92018-06-25 16:15:56 -0700744Status ListCommand::fetchManifestHals() {
745 if (!shouldFetchHalType(HalType::VINTF_MANIFEST)) { return OK; }
746 Status status = OK;
747
748 for (auto manifest : {getDeviceManifest(), getFrameworkManifest()}) {
749 if (manifest == nullptr) {
750 status |= VINTF_ERROR;
751 continue;
752 }
753
754 std::map<std::string, TableEntry> entries;
755
Yifan Hongc346a162019-09-10 19:35:55 -0700756 manifest->forEachHidlInstance([&] (const vintf::ManifestInstance& manifestInstance) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700757 TableEntry entry{
Yifan Hongc346a162019-09-10 19:35:55 -0700758 .interfaceName = manifestInstance.description(),
Yifan Hong13ba0a92018-06-25 16:15:56 -0700759 .transport = manifestInstance.transport(),
760 .arch = manifestInstance.arch(),
761 // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
762 .partition = toPartition(manifest->type()),
763 .serviceStatus = ServiceStatus::DECLARED};
764 std::string key = entry.interfaceName;
765 entries.emplace(std::move(key), std::move(entry));
766 return true;
767 });
768
769 for (auto&& pair : entries)
770 mManifestHalsTable.add(std::move(pair.second));
771 }
Yifan Hong443df792017-05-09 18:49:45 -0700772 return status;
773}
774
Yifan Hong3212f172018-06-28 12:39:50 -0700775Status ListCommand::fetchLazyHals() {
776 using vintf::operator<<;
777
778 if (!shouldFetchHalType(HalType::LAZY_HALS)) { return OK; }
779 Status status = OK;
780
781 for (const TableEntry& manifestEntry : mManifestHalsTable) {
782 if (manifestEntry.transport == vintf::Transport::HWBINDER) {
783 if (!hasHwbinderEntry(manifestEntry)) {
784 mLazyHalsTable.add(TableEntry(manifestEntry));
785 }
786 continue;
787 }
788 if (manifestEntry.transport == vintf::Transport::PASSTHROUGH) {
789 if (!hasPassthroughEntry(manifestEntry)) {
790 mLazyHalsTable.add(TableEntry(manifestEntry));
791 }
792 continue;
793 }
794 err() << "Warning: unrecognized transport in VINTF manifest: "
795 << manifestEntry.transport;
796 status |= VINTF_ERROR;
797 }
798 return status;
799}
800
801bool ListCommand::hasHwbinderEntry(const TableEntry& entry) const {
802 for (const TableEntry& existing : mServicesTable) {
803 if (existing.interfaceName == entry.interfaceName) {
804 return true;
805 }
806 }
807 return false;
808}
809
810bool ListCommand::hasPassthroughEntry(const TableEntry& entry) const {
811 FqInstance entryFqInstance;
812 if (!entryFqInstance.setTo(entry.interfaceName)) {
813 return false; // cannot parse, so add it anyway.
814 }
815 for (const TableEntry& existing : mImplementationsTable) {
816 FqInstance existingFqInstance;
817 if (!existingFqInstance.setTo(getPackageAndVersion(existing.interfaceName))) {
818 continue;
819 }
820
821 // For example, manifest may say graphics.mapper@2.1 but passthroughServiceManager
822 // can only list graphics.mapper@2.0.
823 if (entryFqInstance.getPackage() == existingFqInstance.getPackage() &&
824 vintf::Version{entryFqInstance.getVersion()}
825 .minorAtLeast(vintf::Version{existingFqInstance.getVersion()})) {
826 return true;
827 }
828 }
829 return false;
830}
831
Yifan Hong443df792017-05-09 18:49:45 -0700832Status ListCommand::fetch() {
833 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700834 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700835 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700836 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700837 status |= NO_BINDERIZED_MANAGER;
838 } else {
839 status |= fetchBinderized(bManager);
840 // Passthrough PIDs are registered to the binderized manager as well.
841 status |= fetchPassthrough(bManager);
842 }
843
Yifan Hong9881df92017-05-10 14:33:05 -0700844 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700845 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700846 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700847 status |= NO_PASSTHROUGH_MANAGER;
848 } else {
849 status |= fetchAllLibraries(pManager);
850 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700851 status |= fetchManifestHals();
Yifan Hong3212f172018-06-28 12:39:50 -0700852 status |= fetchLazyHals();
Yifan Hong443df792017-05-09 18:49:45 -0700853 return status;
854}
855
Yifan Hong13ba0a92018-06-25 16:15:56 -0700856void ListCommand::initFetchTypes() {
Yifan Hong3212f172018-06-28 12:39:50 -0700857 // TODO: refactor to do polymorphism on each table (so that dependency graph is not hardcoded).
858 static const std::map<HalType, std::set<HalType>> kDependencyGraph{
859 {HalType::LAZY_HALS, {HalType::BINDERIZED_SERVICES,
860 HalType::PASSTHROUGH_LIBRARIES,
861 HalType::VINTF_MANIFEST}},
862 };
Yifan Hong13ba0a92018-06-25 16:15:56 -0700863 mFetchTypes.insert(mListTypes.begin(), mListTypes.end());
Yifan Hong3212f172018-06-28 12:39:50 -0700864 for (HalType listType : mListTypes) {
865 auto it = kDependencyGraph.find(listType);
866 if (it != kDependencyGraph.end()) {
867 mFetchTypes.insert(it->second.begin(), it->second.end());
868 }
869 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700870}
871
Yifan Hong30528a22020-08-07 18:24:06 -0700872// Get all values of enum type T, assuming the first value is 0 and the last value is T::LAST.
873// T::LAST is not included in the returned list.
874template <typename T>
875std::vector<T> GetAllValues() {
876 using BaseType = std::underlying_type_t<T>;
877 std::vector<T> ret;
878 for (BaseType i = 0; i < static_cast<BaseType>(T::LAST); ++i) {
879 ret.push_back(static_cast<T>(i));
880 }
881 return ret;
882}
883
Yifan Honga6b93f02017-09-13 16:53:37 -0700884void ListCommand::registerAllOptions() {
885 int v = mOptions.size();
886 // A list of acceptable command line options
887 // key: value returned by getopt_long
888 // long options with short alternatives
889 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
890 return USAGE;
891 }, ""});
892 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
893 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
894 return OK;
895 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700896 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
897 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
898 return OK;
Yifan Hong430f8982018-05-25 17:28:39 -0700899 }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700900 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
901 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
902 return OK;
903 }, "print the transport mode column"});
904 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
905 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
906 return OK;
907 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700908 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
909 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
910 return OK;
911 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700912 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
913 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
914 return OK;
915 }, "print the server PID, or server cmdline if -m is set"});
916 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
917 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
918 return OK;
919 }, "print the server object address column"});
920 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
921 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
922 return OK;
923 }, "print the client PIDs, or client cmdlines if -m is set"});
924 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
925 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
926 return OK;
927 }, "print currently used/available threads\n(note, available threads created lazily)"});
928 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
929 thiz->mEnableCmdlines = true;
930 return OK;
931 }, "print cmdline instead of PIDs"});
932 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
933 thiz->mEmitDebugInfo = true;
934 if (arg) thiz->mFileOutputPath = arg;
935 return OK;
936 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
937 "Writes to specified file if 'arg' is provided, otherwise stdout."});
938
Yifan Hongbdf44f82018-05-25 14:20:00 -0700939 mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
940 thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
941 return OK;
942 }, "print VINTF info. This column contains a comma-separated list of:\n"
Steven Morelanddbbbc652021-02-02 23:02:38 +0000943 " - DM: if the HIDL HAL is in the device manifest\n"
944 " - DC: if the HIDL HAL is in the device compatibility matrix\n"
945 " - FM: if the HIDL HAL is in the framework manifest\n"
946 " - FC: if the HIDL HAL is in the framework compatibility matrix\n"
947 " - X: if the HIDL HAL is in none of the above lists"});
Yifan Hong13ba0a92018-06-25 16:15:56 -0700948 mOptions.push_back({'S', "service-status", no_argument, v++, [](ListCommand* thiz, const char*) {
949 thiz->mSelectedColumns.push_back(TableColumnType::SERVICE_STATUS);
950 return OK;
951 }, "print service status column. Possible values are:\n"
952 " - alive: alive and running hwbinder service;\n"
953 " - registered;dead: registered to hwservicemanager but is not responsive;\n"
954 " - declared: only declared in VINTF manifest but is not registered to hwservicemanager;\n"
955 " - N/A: no information for passthrough HALs."});
Yifan Hongbdf44f82018-05-25 14:20:00 -0700956
Yifan Hong30528a22020-08-07 18:24:06 -0700957 mOptions.push_back({'A', "all", no_argument, v++,
958 [](ListCommand* thiz, const char*) {
959 auto allColumns = GetAllValues<TableColumnType>();
960 thiz->mSelectedColumns.insert(thiz->mSelectedColumns.end(),
961 allColumns.begin(), allColumns.end());
962 return OK;
963 },
964 "print all columns"});
965
Yifan Honga6b93f02017-09-13 16:53:37 -0700966 // long options without short alternatives
967 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
968 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800969 if (thiz->mVintfPartition == Partition::UNKNOWN)
970 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700971 if (arg) thiz->mFileOutputPath = arg;
972 return OK;
973 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800974 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
975 if (!arg) return USAGE;
976 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
977 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
978 return OK;
979 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
980 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700981 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
982 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
983 thiz->mSortColumn = TableEntry::sortByInterfaceName;
984 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
985 thiz->mSortColumn = TableEntry::sortByServerPid;
986 } else {
987 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
988 return USAGE;
989 }
990 return OK;
991 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
992 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
993 thiz->mNeat = true;
994 return OK;
995 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Yifan Hong30528a22020-08-07 18:24:06 -0700996 mOptions.push_back(
997 {'\0', "types", required_argument, v++,
998 [](ListCommand* thiz, const char* arg) {
999 if (!arg) {
1000 return USAGE;
1001 }
Nirav Atrecce988d2018-05-16 11:14:46 -07001002
Yifan Hong30528a22020-08-07 18:24:06 -07001003 static const std::map<std::string, std::vector<HalType>> kHalTypeMap{
1004 {"binderized", {HalType::BINDERIZED_SERVICES}},
1005 {"b", {HalType::BINDERIZED_SERVICES}},
1006 {"passthrough_clients", {HalType::PASSTHROUGH_CLIENTS}},
1007 {"c", {HalType::PASSTHROUGH_CLIENTS}},
1008 {"passthrough_libs", {HalType::PASSTHROUGH_LIBRARIES}},
1009 {"l", {HalType::PASSTHROUGH_LIBRARIES}},
1010 {"vintf", {HalType::VINTF_MANIFEST}},
1011 {"v", {HalType::VINTF_MANIFEST}},
1012 {"lazy", {HalType::LAZY_HALS}},
1013 {"z", {HalType::LAZY_HALS}},
1014 {"all", GetAllValues<HalType>()},
1015 {"a", GetAllValues<HalType>()},
1016 };
Nirav Atrecce988d2018-05-16 11:14:46 -07001017
Yifan Hong30528a22020-08-07 18:24:06 -07001018 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
1019 for (const auto& halTypeArg : halTypesArgs) {
1020 if (halTypeArg.empty()) continue;
Nirav Atrecce988d2018-05-16 11:14:46 -07001021
Yifan Hong30528a22020-08-07 18:24:06 -07001022 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
1023 if (halTypeIter == kHalTypeMap.end()) {
1024 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
1025 return USAGE;
1026 }
Nirav Atrecce988d2018-05-16 11:14:46 -07001027
Yifan Hong30528a22020-08-07 18:24:06 -07001028 // Append unique (non-repeated) HAL types to the reporting list
1029 for (auto halType : halTypeIter->second) {
1030 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
1031 thiz->mListTypes.end()) {
1032 thiz->mListTypes.push_back(halType);
1033 }
1034 }
1035 }
Nirav Atrecce988d2018-05-16 11:14:46 -07001036
Yifan Hong30528a22020-08-07 18:24:06 -07001037 if (thiz->mListTypes.empty()) {
1038 return USAGE;
1039 }
1040 return OK;
1041 },
1042 "comma-separated list of one or more sections.\nThe output is restricted to the "
1043 "selected section(s). Valid options\nare: (b|binderized), (c|passthrough_clients), (l|"
1044 "passthrough_libs), (v|vintf), (z|lazy), and (a|all).\nDefault is `b,c,l`."});
Yifan Honga6b93f02017-09-13 16:53:37 -07001045}
1046
1047// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
1048// the lifetime of "options" during the usage of the returned array.
1049static std::unique_ptr<struct option[]> getLongOptions(
1050 const ListCommand::RegisteredOptions& options,
1051 int* longOptFlag) {
1052 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
1053 int i = 0;
1054 for (const auto& e : options) {
1055 ret[i].name = e.longOption.c_str();
1056 ret[i].has_arg = e.hasArg;
1057 ret[i].flag = longOptFlag;
1058 ret[i].val = e.val;
1059
1060 i++;
1061 }
1062 // getopt_long last option has all zeros
Yi Kong19d5c002018-07-20 13:39:55 -07001063 ret[i].name = nullptr;
Yifan Honga6b93f02017-09-13 16:53:37 -07001064 ret[i].has_arg = 0;
Yi Kong19d5c002018-07-20 13:39:55 -07001065 ret[i].flag = nullptr;
Yifan Honga6b93f02017-09-13 16:53:37 -07001066 ret[i].val = 0;
1067
1068 return ret;
1069}
1070
1071// Create 'optstring' argument to getopt_long.
1072static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
1073 std::stringstream ss;
1074 for (const auto& e : options) {
1075 if (e.shortOption != '\0') {
1076 ss << e.shortOption;
1077 }
1078 }
1079 return ss.str();
1080}
1081
Yifan Honga8bedc62017-09-08 18:00:31 -07001082Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -07001083 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -07001084
Yifan Honga6b93f02017-09-13 16:53:37 -07001085 if (mOptions.empty()) {
1086 registerAllOptions();
1087 }
1088 int longOptFlag;
1089 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
1090 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001091
Yifan Honga8bedc62017-09-08 18:00:31 -07001092 // suppress output to std::err for unknown options
1093 opterr = 0;
1094
Yifan Hong443df792017-05-09 18:49:45 -07001095 int optionIndex;
1096 int c;
1097 // Lshal::parseArgs has set optind to the next option to parse
1098 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -07001099 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -07001100 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -07001101 if (c == -1) {
1102 break;
1103 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001104 const RegisteredOption* found = nullptr;
1105 if (c == 0) {
1106 // see long option
1107 for (const auto& e : mOptions) {
1108 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -07001109 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001110 } else {
1111 // see short option
1112 for (const auto& e : mOptions) {
1113 if (c == e.shortOption) found = &e;
1114 }
Yifan Hong443df792017-05-09 18:49:45 -07001115 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001116
1117 if (found == nullptr) {
1118 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -07001119 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -07001120 return USAGE;
1121 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001122
1123 Status status = found->op(this, optarg);
1124 if (status != OK) {
1125 return status;
1126 }
Yifan Hong443df792017-05-09 18:49:45 -07001127 }
1128 if (optind < arg.argc) {
1129 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -07001130 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001131 return USAGE;
1132 }
1133
1134 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -07001135 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001136 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -07001137 }
1138
Yifan Honga6b93f02017-09-13 16:53:37 -07001139 if (mSelectedColumns.empty()) {
Steven Moreland8e0f5392018-12-12 14:27:24 -08001140 mSelectedColumns = {TableColumnType::VINTF, TableColumnType::RELEASED,
Yifan Hongfee209d2017-09-14 18:23:38 -07001141 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -07001142 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -07001143 }
Yifan Hongd4a77e82017-09-06 19:40:24 -07001144
Yifan Honga6b93f02017-09-13 16:53:37 -07001145 if (mEnableCmdlines) {
1146 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
1147 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
1148 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001149 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001150 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
1151 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001152 }
1153 }
1154 }
1155
Nirav Atrecce988d2018-05-16 11:14:46 -07001156 // By default, list all HAL types
1157 if (mListTypes.empty()) {
1158 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
1159 HalType::PASSTHROUGH_LIBRARIES};
1160 }
Yifan Hong13ba0a92018-06-25 16:15:56 -07001161 initFetchTypes();
Nirav Atrecce988d2018-05-16 11:14:46 -07001162
Yifan Honga6b93f02017-09-13 16:53:37 -07001163 forEachTable([this] (Table& table) {
1164 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001165 });
1166
Yifan Hong443df792017-05-09 18:49:45 -07001167 return OK;
1168}
1169
Yifan Honga8bedc62017-09-08 18:00:31 -07001170Status ListCommand::main(const Arg &arg) {
1171 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -07001172 if (status != OK) {
1173 return status;
1174 }
1175 status = fetch();
1176 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -07001177 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -07001178 return status;
1179}
1180
Yifan Honga6b93f02017-09-13 16:53:37 -07001181const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
1182 static const std::string empty{};
1183 static const std::string optional{"[=<arg>]"};
1184 static const std::string required{"=<arg>"};
1185
1186 if (hasArg == optional_argument) {
1187 return optional;
1188 }
1189 if (hasArg == required_argument) {
1190 return required;
1191 }
1192 return empty;
1193}
1194
Yifan Honga8bedc62017-09-08 18:00:31 -07001195void ListCommand::usage() const {
1196
Yifan Honga6b93f02017-09-13 16:53:37 -07001197 err() << "list:" << std::endl
1198 << " lshal" << std::endl
1199 << " lshal list" << std::endl
Steven Moreland8e0f5392018-12-12 14:27:24 -08001200 << " List all hals with default ordering and columns (`lshal list -Vliepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001201 << " lshal list [-h|--help]" << std::endl
1202 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1203 << " lshal [list] [OPTIONS...]" << std::endl;
1204 for (const auto& e : mOptions) {
1205 if (e.help.empty()) {
1206 continue;
1207 }
1208 err() << " ";
1209 if (e.shortOption != '\0')
1210 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1211 if (e.shortOption != '\0' && !e.longOption.empty())
1212 err() << ", ";
1213 if (!e.longOption.empty())
1214 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1215 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001216 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001217 for (const auto& line : lines) {
1218 if (&line != &lines.front())
1219 err() << " ";
1220 err() << line << std::endl;
1221 }
1222 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001223}
1224
Yifan Hong443df792017-05-09 18:49:45 -07001225} // namespace lshal
1226} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001227