blob: fb11cee33e0731cd557ea63fc0c08ae9791ee0f4 [file] [log] [blame]
Yifan Hong443df792017-05-09 18:49:45 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "ListCommand.h"
18
19#include <getopt.h>
20
Nirav Atrecce988d2018-05-16 11:14:46 -070021#include <algorithm>
Yifan Hong443df792017-05-09 18:49:45 -070022#include <fstream>
Yifan Hongb2d096a2018-05-01 15:25:23 -070023#include <functional>
Yifan Hong443df792017-05-09 18:49:45 -070024#include <iomanip>
25#include <iostream>
26#include <map>
Yifan Hong443df792017-05-09 18:49:45 -070027#include <regex>
Yifan Hongb2d096a2018-05-01 15:25:23 -070028#include <sstream>
Yifan Hong443df792017-05-09 18:49:45 -070029
Yifan Hongf31aa052018-02-02 15:17:51 -080030#include <android-base/file.h>
Nirav Atrecce988d2018-05-16 11:14:46 -070031#include <android-base/logging.h>
Yifan Hong443df792017-05-09 18:49:45 -070032#include <android-base/parseint.h>
33#include <android/hidl/manager/1.0/IServiceManager.h>
Yifan Hongfee209d2017-09-14 18:23:38 -070034#include <hidl-hash/Hash.h>
Yifan Hong443df792017-05-09 18:49:45 -070035#include <hidl-util/FQName.h>
36#include <private/android_filesystem_config.h>
37#include <sys/stat.h>
38#include <vintf/HalManifest.h>
Yifan Hongf31aa052018-02-02 15:17:51 -080039#include <vintf/parse_string.h>
Yifan Hong443df792017-05-09 18:49:45 -070040#include <vintf/parse_xml.h>
41
42#include "Lshal.h"
43#include "PipeRelay.h"
44#include "Timeout.h"
45#include "utils.h"
46
47using ::android::hardware::hidl_string;
Yifan Hong22ea7b82017-09-14 18:07:43 -070048using ::android::hardware::hidl_vec;
49using ::android::hidl::base::V1_0::DebugInfo;
50using ::android::hidl::base::V1_0::IBase;
Yifan Hong443df792017-05-09 18:49:45 -070051using ::android::hidl::manager::V1_0::IServiceManager;
52
53namespace android {
54namespace lshal {
55
Yifan Hongf31aa052018-02-02 15:17:51 -080056vintf::SchemaType toSchemaType(Partition p) {
57 return (p == Partition::SYSTEM) ? vintf::SchemaType::FRAMEWORK : vintf::SchemaType::DEVICE;
58}
59
Yifan 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 {
85 return "List HALs.";
86}
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
Yifan Hong1243dde2017-09-14 17:49:30 -0700206static bool scanBinderContext(pid_t pid,
Steven Morelandd8e20192017-05-24 11:23:08 -0700207 const std::string &contextName,
208 std::function<void(const std::string&)> eachLine) {
Hridya Valsarajub49b0b12020-02-25 12:27:14 -0800209 std::ifstream ifs("/dev/binderfs/binder_logs/proc/" + std::to_string(pid));
Yifan Hong443df792017-05-09 18:49:45 -0700210 if (!ifs.is_open()) {
Hridya Valsarajub49b0b12020-02-25 12:27:14 -0800211 ifs.open("/d/binder/proc/" + std::to_string(pid));
212 if (!ifs.is_open()) {
213 return false;
214 }
Yifan Hong443df792017-05-09 18:49:45 -0700215 }
216
Steven Morelandd8e20192017-05-24 11:23:08 -0700217 static const std::regex kContextLine("^context (\\w+)$");
Yifan Hong443df792017-05-09 18:49:45 -0700218
Steven Morelandd8e20192017-05-24 11:23:08 -0700219 bool isDesiredContext = false;
Yifan Hong443df792017-05-09 18:49:45 -0700220 std::string line;
221 std::smatch match;
222 while(getline(ifs, line)) {
Steven Morelandd8e20192017-05-24 11:23:08 -0700223 if (std::regex_search(line, match, kContextLine)) {
224 isDesiredContext = match.str(1) == contextName;
Yifan Hong443df792017-05-09 18:49:45 -0700225 continue;
226 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700227
228 if (!isDesiredContext) {
Yifan Hong443df792017-05-09 18:49:45 -0700229 continue;
230 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700231
232 eachLine(line);
Yifan Hong443df792017-05-09 18:49:45 -0700233 }
234 return true;
235}
236
Steven Morelandd8e20192017-05-24 11:23:08 -0700237bool ListCommand::getPidInfo(
238 pid_t serverPid, PidInfo *pidInfo) const {
239 static const std::regex kReferencePrefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
240 static const std::regex kThreadPrefix("^\\s*thread \\d+:\\s+l\\s+(\\d)(\\d)");
241
242 std::smatch match;
243 return scanBinderContext(serverPid, "hwbinder", [&](const std::string& line) {
244 if (std::regex_search(line, match, kReferencePrefix)) {
245 const std::string &ptrString = "0x" + match.str(2); // use number after c
246 uint64_t ptr;
247 if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
248 // Should not reach here, but just be tolerant.
Yifan Hong76ac14a2017-09-08 14:59:04 -0700249 err() << "Could not parse number " << ptrString << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700250 return;
251 }
252 const std::string proc = " proc ";
253 auto pos = line.rfind(proc);
254 if (pos != std::string::npos) {
255 for (const std::string &pidStr : split(line.substr(pos + proc.size()), ' ')) {
256 int32_t pid;
257 if (!::android::base::ParseInt(pidStr, &pid)) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700258 err() << "Could not parse number " << pidStr << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700259 return;
260 }
261 pidInfo->refPids[ptr].push_back(pid);
262 }
263 }
264
265 return;
266 }
267
268 if (std::regex_search(line, match, kThreadPrefix)) {
269 // "1" is waiting in binder driver
270 // "2" is poll. It's impossible to tell if these are in use.
271 // and HIDL default code doesn't use it.
272 bool isInUse = match.str(1) != "1";
273 // "0" is a thread that has called into binder
274 // "1" is looper thread
275 // "2" is main looper thread
276 bool isHwbinderThread = match.str(2) != "0";
277
278 if (!isHwbinderThread) {
279 return;
280 }
281
282 if (isInUse) {
283 pidInfo->threadUsage++;
284 }
285
286 pidInfo->threadCount++;
287 return;
288 }
289
290 // not reference or thread line
291 return;
292 });
293}
294
Yifan Hong1243dde2017-09-14 17:49:30 -0700295const PidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
296 auto pair = mCachedPidInfos.insert({serverPid, PidInfo{}});
297 if (pair.second /* did insertion take place? */) {
298 if (!getPidInfo(serverPid, &pair.first->second)) {
299 return nullptr;
300 }
301 }
302 return &pair.first->second;
303}
304
Yifan Hong13ba0a92018-06-25 16:15:56 -0700305bool ListCommand::shouldFetchHalType(const HalType &type) const {
306 return (std::find(mFetchTypes.begin(), mFetchTypes.end(), type) != mFetchTypes.end());
Nirav Atrecce988d2018-05-16 11:14:46 -0700307}
308
Yifan Hongdb730532018-06-25 16:32:01 -0700309Table* ListCommand::tableForType(HalType type) {
310 switch (type) {
311 case HalType::BINDERIZED_SERVICES:
312 return &mServicesTable;
313 case HalType::PASSTHROUGH_CLIENTS:
314 return &mPassthroughRefTable;
315 case HalType::PASSTHROUGH_LIBRARIES:
316 return &mImplementationsTable;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700317 case HalType::VINTF_MANIFEST:
318 return &mManifestHalsTable;
Yifan Hong3212f172018-06-28 12:39:50 -0700319 case HalType::LAZY_HALS:
320 return &mLazyHalsTable;
Yifan Hongdb730532018-06-25 16:32:01 -0700321 default:
322 LOG(FATAL) << "Unknown HAL type " << static_cast<int64_t>(type);
323 return nullptr;
324 }
325}
326const Table* ListCommand::tableForType(HalType type) const {
327 return const_cast<ListCommand*>(this)->tableForType(type);
Yifan Hong443df792017-05-09 18:49:45 -0700328}
329
330void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700331 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700332 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700333 }
Yifan Hong443df792017-05-09 18:49:45 -0700334}
335void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
Nirav Atrecce988d2018-05-16 11:14:46 -0700336 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700337 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700338 }
Yifan Hong443df792017-05-09 18:49:45 -0700339}
340
341void ListCommand::postprocess() {
342 forEachTable([this](Table &table) {
343 if (mSortColumn) {
344 std::sort(table.begin(), table.end(), mSortColumn);
345 }
346 for (TableEntry &entry : table) {
347 entry.serverCmdline = getCmdline(entry.serverPid);
348 removeDeadProcesses(&entry.clientPids);
349 for (auto pid : entry.clientPids) {
350 entry.clientCmdlines.push_back(this->getCmdline(pid));
351 }
352 }
Yifan Hongf31aa052018-02-02 15:17:51 -0800353 for (TableEntry& entry : table) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700354 if (entry.partition == Partition::UNKNOWN) {
355 entry.partition = getPartition(entry.serverPid);
356 }
Yifan Hongbdf44f82018-05-25 14:20:00 -0700357 entry.vintfInfo = getVintfInfo(entry.interfaceName, {entry.transport, entry.arch});
Yifan Hongf31aa052018-02-02 15:17:51 -0800358 }
Yifan Hong443df792017-05-09 18:49:45 -0700359 });
360 // use a double for loop here because lshal doesn't care about efficiency.
361 for (TableEntry &packageEntry : mImplementationsTable) {
362 std::string packageName = packageEntry.interfaceName;
Steven Morelandd4f32b32018-03-06 14:47:58 -0800363 FQName fqPackageName;
364 if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700365 continue;
366 }
367 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700368 if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
Yifan Hong443df792017-05-09 18:49:45 -0700369 continue;
370 }
Steven Morelandd4f32b32018-03-06 14:47:58 -0800371 FQName interfaceName;
372 if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700373 continue;
374 }
375 if (interfaceName.getPackageAndVersion() == fqPackageName) {
376 interfaceEntry.arch = packageEntry.arch;
377 }
378 }
379 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700380
381 mServicesTable.setDescription(
Steven Moreland8e0f5392018-12-12 14:27:24 -0800382 "| All binderized services (registered with hwservicemanager)");
Yifan Hongca3b6602017-09-07 16:44:27 -0700383 mPassthroughRefTable.setDescription(
Steven Moreland8e0f5392018-12-12 14:27:24 -0800384 "| All interfaces that getService() has ever returned as a passthrough interface;\n"
385 "| PIDs / processes shown below might be inaccurate because the process\n"
386 "| might have relinquished the interface or might have died.\n"
387 "| The Server / Server CMD column can be ignored.\n"
388 "| The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
389 "| the library and successfully fetched the passthrough implementation.");
Yifan Hongca3b6602017-09-07 16:44:27 -0700390 mImplementationsTable.setDescription(
Steven Moreland8e0f5392018-12-12 14:27:24 -0800391 "| All available passthrough implementations (all -impl.so files).\n"
392 "| These may return subclasses through their respective HIDL_FETCH_I* functions.");
Yifan Hong13ba0a92018-06-25 16:15:56 -0700393 mManifestHalsTable.setDescription(
Steven Moreland8e0f5392018-12-12 14:27:24 -0800394 "| All HALs that are in VINTF manifest.");
Yifan Hong3212f172018-06-28 12:39:50 -0700395 mLazyHalsTable.setDescription(
Steven Moreland8e0f5392018-12-12 14:27:24 -0800396 "| All HALs that are declared in VINTF manifest:\n"
397 "| - as hwbinder HALs but are not registered to hwservicemanager, and\n"
398 "| - as hwbinder/passthrough HALs with no implementation.");
Yifan Hong443df792017-05-09 18:49:45 -0700399}
400
Yifan Hongb2d096a2018-05-01 15:25:23 -0700401bool ListCommand::addEntryWithInstance(const TableEntry& entry,
402 vintf::HalManifest* manifest) const {
403 FqInstance fqInstance;
404 if (!fqInstance.setTo(entry.interfaceName)) {
405 err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
406 return false;
Yifan Hong77c87822017-06-19 15:47:39 -0700407 }
Yifan Hongb2d096a2018-05-01 15:25:23 -0700408
Steven Moreland7a99e042020-02-26 13:16:34 -0800409 if (fqInstance.getPackage() == "android.hidl.base") {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700410 return true; // always remove IBase from manifest
411 }
412
413 Partition partition = resolvePartition(entry.partition, fqInstance);
414
415 if (partition == Partition::UNKNOWN) {
416 err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
417 << std::endl;
418 return false;
419 }
420
421 if (partition != mVintfPartition) {
422 return true; // strip out instances that is in a different partition.
423 }
424
Yifan Hongb2d096a2018-05-01 15:25:23 -0700425 vintf::Arch arch;
Yifan Hong8304e412018-05-25 15:05:36 -0700426 if (entry.transport == vintf::Transport::HWBINDER) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700427 arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
Yifan Hong8304e412018-05-25 15:05:36 -0700428 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700429 if (entry.arch == vintf::Arch::ARCH_EMPTY) {
430 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
431 return false;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700432 }
Yifan Hong0ad64f52018-05-25 15:29:17 -0700433 arch = entry.arch;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700434 } else {
435 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
436 return false;
437 }
438
439 std::string e;
Yifan Hong8304e412018-05-25 15:05:36 -0700440 if (!manifest->insertInstance(fqInstance, entry.transport, arch, vintf::HalFormat::HIDL, &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700441 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
442 return false;
443 }
444 return true;
445}
446
447bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
448 const vintf::HalManifest* manifest) const {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700449 const auto& packageAndVersion = splitFirst(getPackageAndVersion(entry.interfaceName), '@');
Yifan Hongb2d096a2018-05-01 15:25:23 -0700450 const auto& package = packageAndVersion.first;
451 vintf::Version version;
452 if (!vintf::parse(packageAndVersion.second, &version)) {
453 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
454 << entry.interfaceName << "'" << std::endl;
455 return false;
456 }
457
458 bool found = false;
Yifan Hongc346a162019-09-10 19:35:55 -0700459 (void)manifest->forEachHidlInstanceOfVersion(package, version, [&found](const auto&) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700460 found = true;
461 return false; // break
462 });
463 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700464}
465
Yifan Hongca3b6602017-09-07 16:44:27 -0700466void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700467 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800468 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700469 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700470
471 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800472 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700473
Yifan Hongb2d096a2018-05-01 15:25:23 -0700474 std::vector<std::string> error;
475 for (const TableEntry& entry : mServicesTable)
476 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
477 for (const TableEntry& entry : mPassthroughRefTable)
478 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700479 for (const TableEntry& entry : mManifestHalsTable)
480 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700481
Yifan Hongb2d096a2018-05-01 15:25:23 -0700482 std::vector<std::string> passthrough;
483 for (const TableEntry& entry : mImplementationsTable)
484 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800485
Yifan Hongf31aa052018-02-02 15:17:51 -0800486 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700487 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
488 << INIT_VINTF_NOTES;
489 if (!error.empty()) {
490 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
491 for (const auto& e : error) {
492 out << " " << e << std::endl;
493 }
494 }
495 if (!passthrough.empty()) {
496 out << std::endl
497 << " The following HALs are passthrough and no interface or instance " << std::endl
498 << " names can be inferred." << std::endl;
499 for (const auto& e : passthrough) {
500 out << " " << e << std::endl;
501 }
502 }
503 out << "-->" << std::endl;
Yifan Hong86971682018-08-07 17:02:53 -0700504 out << vintf::gHalManifestConverter(manifest, vintf::SerializeFlags::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700505}
506
Yifan Hongf31aa052018-02-02 15:17:51 -0800507std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700508 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800509 " only hwbinder is shown.\n"
510 " 2. It is likely that HALs in passthrough transport does not have\n"
511 " <interface> declared; users will have to write them by hand.\n"
512 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
513 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700514 " 4. This output is intended for launch devices.\n"
515 " Upgrading devices should not use this tool to generate device\n"
516 " manifest and replace the existing manifest directly, but should\n"
517 " edit the existing manifest manually.\n"
518 " Specifically, devices which launched at Android O-MR1 or earlier\n"
519 " should not use the 'fqname' format for required HAL entries and\n"
520 " should instead use the legacy package, name, instance-name format\n"
521 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800522};
523
Yifan Hong0ad64f52018-05-25 15:29:17 -0700524static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
Yifan Hong443df792017-05-09 18:49:45 -0700525 switch (a) {
526 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700527 return vintf::Arch::ARCH_64;
Yifan Hong443df792017-05-09 18:49:45 -0700528 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700529 return vintf::Arch::ARCH_32;
Yifan Hong443df792017-05-09 18:49:45 -0700530 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
531 default:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700532 return vintf::Arch::ARCH_EMPTY;
Yifan Hong443df792017-05-09 18:49:45 -0700533 }
534}
535
Yifan Hongca3b6602017-09-07 16:44:27 -0700536void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700537 if (mNeat) {
Yifan Hongb72f19e2018-06-27 16:58:56 -0700538 std::vector<const Table*> tables;
539 forEachTable([&tables](const Table &table) {
540 tables.push_back(&table);
541 });
542 MergedTable(std::move(tables)).createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700543 return;
544 }
545
Yifan Hongca3b6602017-09-07 16:44:27 -0700546 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700547
Yifan Hongd4a77e82017-09-06 19:40:24 -0700548 // We're only interested in dumping debug info for already
549 // instantiated services. There's little value in dumping the
550 // debug info for a service we create on the fly, so we only operate
551 // on the "mServicesTable".
552 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
553 if (mEmitDebugInfo && &table == &mServicesTable) {
554 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700555 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700556 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800557 mLshal.emitDebugInfo(pair.first, pair.second, {},
558 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700559 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700560 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700561 };
Yifan Hong443df792017-05-09 18:49:45 -0700562 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700563 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
564 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700565 });
Yifan Hong443df792017-05-09 18:49:45 -0700566}
567
Yifan Hongca3b6602017-09-07 16:44:27 -0700568Status ListCommand::dump() {
569 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
570
571 if (mFileOutputPath.empty()) {
572 (*this.*dump)(out());
573 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700574 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700575
576 std::ofstream fileOutput(mFileOutputPath);
577 if (!fileOutput.is_open()) {
578 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
579 return IO_ERROR;
580 }
581 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
582
583 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
584
585 fileOutput.flush();
586 fileOutput.close();
587 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700588}
589
Yifan Hong20f4ee82018-06-25 16:21:29 -0700590void ListCommand::putEntry(HalType type, TableEntry &&entry) {
Yifan Hongdb730532018-06-25 16:32:01 -0700591 tableForType(type)->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700592}
593
594Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700595 if (!shouldFetchHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700596
Yifan Hong443df792017-05-09 18:49:45 -0700597 using namespace ::android::hardware;
598 using namespace ::android::hidl::manager::V1_0;
599 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700600 using std::literals::chrono_literals::operator""s;
Yifan Hongaf582192018-04-10 17:45:06 -0700601 auto ret = timeoutIPC(10s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700602 std::map<std::string, TableEntry> entries;
603 for (const auto &info : infos) {
604 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
605 std::string{info.instanceName.c_str()};
606 entries.emplace(interfaceName, TableEntry{
607 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700608 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700609 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700610 }).first->second.arch |= fromBaseArchitecture(info.arch);
611 }
612 for (auto &&pair : entries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700613 putEntry(HalType::PASSTHROUGH_LIBRARIES, std::move(pair.second));
Yifan Hong443df792017-05-09 18:49:45 -0700614 }
615 });
616 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700617 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700618 << ret.description() << std::endl;
619 return DUMP_ALL_LIBS_ERROR;
620 }
621 return OK;
622}
623
624Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700625 if (!shouldFetchHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700626
Yifan Hong443df792017-05-09 18:49:45 -0700627 using namespace ::android::hardware;
628 using namespace ::android::hardware::details;
629 using namespace ::android::hidl::manager::V1_0;
630 using namespace ::android::hidl::base::V1_0;
631 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
632 for (const auto &info : infos) {
633 if (info.clientPids.size() <= 0) {
634 continue;
635 }
Yifan Hong20f4ee82018-06-25 16:21:29 -0700636 putEntry(HalType::PASSTHROUGH_CLIENTS, {
Yifan Hong443df792017-05-09 18:49:45 -0700637 .interfaceName =
638 std::string{info.interfaceName.c_str()} + "/" +
639 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700640 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700641 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700642 .clientPids = info.clientPids,
643 .arch = fromBaseArchitecture(info.arch)
644 });
645 }
646 });
647 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700648 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700649 << ret.description() << std::endl;
650 return DUMP_PASSTHROUGH_ERROR;
651 }
652 return OK;
653}
654
655Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700656 using vintf::operator<<;
657
Yifan Hong13ba0a92018-06-25 16:15:56 -0700658 if (!shouldFetchHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700659
Yifan Hong8304e412018-05-25 15:05:36 -0700660 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700661 hidl_vec<hidl_string> fqInstanceNames;
662 // copying out for timeoutIPC
663 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
664 fqInstanceNames = names;
665 });
666 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700667 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700668 << listRet.description() << std::endl;
669 return DUMP_BINDERIZED_ERROR;
670 }
671
672 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700673 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700674 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700675 // create entry and default assign all fields.
676 TableEntry& entry = allTableEntries[fqInstanceName];
677 entry.interfaceName = fqInstanceName;
678 entry.transport = mode;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700679 entry.serviceStatus = ServiceStatus::NON_RESPONSIVE;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700680
681 status |= fetchBinderizedEntry(manager, &entry);
682 }
683
684 for (auto& pair : allTableEntries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700685 putEntry(HalType::BINDERIZED_SERVICES, std::move(pair.second));
Yifan Hong22ea7b82017-09-14 18:07:43 -0700686 }
687 return status;
688}
689
690Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
691 TableEntry *entry) {
692 Status status = OK;
693 const auto handleError = [&](Status additionalError, const std::string& msg) {
694 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
695 status |= DUMP_BINDERIZED_ERROR | additionalError;
696 };
697
698 const auto pair = splitFirst(entry->interfaceName, '/');
699 const auto &serviceName = pair.first;
700 const auto &instanceName = pair.second;
701 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
702 if (!getRet.isOk()) {
703 handleError(TRANSACTION_ERROR,
704 "cannot be fetched from service manager:" + getRet.description());
705 return status;
706 }
707 sp<IBase> service = getRet;
708 if (service == nullptr) {
709 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
710 return status;
711 }
712
713 // getDebugInfo
714 do {
715 DebugInfo debugInfo;
716 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
717 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700718 });
719 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700720 handleError(TRANSACTION_ERROR,
721 "debugging information cannot be retrieved: " + debugRet.description());
722 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700723 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700724
Yifan Hong22ea7b82017-09-14 18:07:43 -0700725 entry->serverPid = debugInfo.pid;
726 entry->serverObjectAddress = debugInfo.ptr;
727 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700728
Yifan Hong22ea7b82017-09-14 18:07:43 -0700729 if (debugInfo.pid != NO_PID) {
730 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
731 if (pidInfo == nullptr) {
732 handleError(IO_ERROR,
733 "no information for PID " + std::to_string(debugInfo.pid) +
734 ", are you root?");
735 break;
736 }
737 if (debugInfo.ptr != NO_PTR) {
738 auto it = pidInfo->refPids.find(debugInfo.ptr);
739 if (it != pidInfo->refPids.end()) {
740 entry->clientPids = it->second;
741 }
742 }
743 entry->threadUsage = pidInfo->threadUsage;
744 entry->threadCount = pidInfo->threadCount;
745 }
746 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700747
748 // hash
749 do {
750 ssize_t hashIndex = -1;
751 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
752 for (size_t i = 0; i < c.size(); ++i) {
753 if (serviceName == c[i]) {
754 hashIndex = static_cast<ssize_t>(i);
755 break;
756 }
757 }
758 });
759 if (!ifaceChainRet.isOk()) {
760 handleError(TRANSACTION_ERROR,
761 "interfaceChain fails: " + ifaceChainRet.description());
762 break; // skip getHashChain
763 }
764 if (hashIndex < 0) {
765 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
766 break; // skip getHashChain
767 }
768 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
769 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
770 handleError(BAD_IMPL,
771 "interfaceChain indicates position " + std::to_string(hashIndex) +
772 " but getHashChain returns " + std::to_string(hashChain.size()) +
773 " hashes");
774 return;
775 }
776
777 auto&& hashArray = hashChain[hashIndex];
778 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
779 entry->hash = Hash::hexString(hashVec);
780 });
781 if (!hashRet.isOk()) {
782 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
783 }
784 } while (0);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700785 if (status == OK) {
786 entry->serviceStatus = ServiceStatus::ALIVE;
787 }
Yifan Hong443df792017-05-09 18:49:45 -0700788 return status;
789}
790
Yifan Hong13ba0a92018-06-25 16:15:56 -0700791Status ListCommand::fetchManifestHals() {
792 if (!shouldFetchHalType(HalType::VINTF_MANIFEST)) { return OK; }
793 Status status = OK;
794
795 for (auto manifest : {getDeviceManifest(), getFrameworkManifest()}) {
796 if (manifest == nullptr) {
797 status |= VINTF_ERROR;
798 continue;
799 }
800
801 std::map<std::string, TableEntry> entries;
802
Yifan Hongc346a162019-09-10 19:35:55 -0700803 manifest->forEachHidlInstance([&] (const vintf::ManifestInstance& manifestInstance) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700804 TableEntry entry{
Yifan Hongc346a162019-09-10 19:35:55 -0700805 .interfaceName = manifestInstance.description(),
Yifan Hong13ba0a92018-06-25 16:15:56 -0700806 .transport = manifestInstance.transport(),
807 .arch = manifestInstance.arch(),
808 // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
809 .partition = toPartition(manifest->type()),
810 .serviceStatus = ServiceStatus::DECLARED};
811 std::string key = entry.interfaceName;
812 entries.emplace(std::move(key), std::move(entry));
813 return true;
814 });
815
816 for (auto&& pair : entries)
817 mManifestHalsTable.add(std::move(pair.second));
818 }
Yifan Hong443df792017-05-09 18:49:45 -0700819 return status;
820}
821
Yifan Hong3212f172018-06-28 12:39:50 -0700822Status ListCommand::fetchLazyHals() {
823 using vintf::operator<<;
824
825 if (!shouldFetchHalType(HalType::LAZY_HALS)) { return OK; }
826 Status status = OK;
827
828 for (const TableEntry& manifestEntry : mManifestHalsTable) {
829 if (manifestEntry.transport == vintf::Transport::HWBINDER) {
830 if (!hasHwbinderEntry(manifestEntry)) {
831 mLazyHalsTable.add(TableEntry(manifestEntry));
832 }
833 continue;
834 }
835 if (manifestEntry.transport == vintf::Transport::PASSTHROUGH) {
836 if (!hasPassthroughEntry(manifestEntry)) {
837 mLazyHalsTable.add(TableEntry(manifestEntry));
838 }
839 continue;
840 }
841 err() << "Warning: unrecognized transport in VINTF manifest: "
842 << manifestEntry.transport;
843 status |= VINTF_ERROR;
844 }
845 return status;
846}
847
848bool ListCommand::hasHwbinderEntry(const TableEntry& entry) const {
849 for (const TableEntry& existing : mServicesTable) {
850 if (existing.interfaceName == entry.interfaceName) {
851 return true;
852 }
853 }
854 return false;
855}
856
857bool ListCommand::hasPassthroughEntry(const TableEntry& entry) const {
858 FqInstance entryFqInstance;
859 if (!entryFqInstance.setTo(entry.interfaceName)) {
860 return false; // cannot parse, so add it anyway.
861 }
862 for (const TableEntry& existing : mImplementationsTable) {
863 FqInstance existingFqInstance;
864 if (!existingFqInstance.setTo(getPackageAndVersion(existing.interfaceName))) {
865 continue;
866 }
867
868 // For example, manifest may say graphics.mapper@2.1 but passthroughServiceManager
869 // can only list graphics.mapper@2.0.
870 if (entryFqInstance.getPackage() == existingFqInstance.getPackage() &&
871 vintf::Version{entryFqInstance.getVersion()}
872 .minorAtLeast(vintf::Version{existingFqInstance.getVersion()})) {
873 return true;
874 }
875 }
876 return false;
877}
878
Yifan Hong443df792017-05-09 18:49:45 -0700879Status ListCommand::fetch() {
880 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700881 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700882 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700883 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700884 status |= NO_BINDERIZED_MANAGER;
885 } else {
886 status |= fetchBinderized(bManager);
887 // Passthrough PIDs are registered to the binderized manager as well.
888 status |= fetchPassthrough(bManager);
889 }
890
Yifan Hong9881df92017-05-10 14:33:05 -0700891 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700892 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700893 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700894 status |= NO_PASSTHROUGH_MANAGER;
895 } else {
896 status |= fetchAllLibraries(pManager);
897 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700898 status |= fetchManifestHals();
Yifan Hong3212f172018-06-28 12:39:50 -0700899 status |= fetchLazyHals();
Yifan Hong443df792017-05-09 18:49:45 -0700900 return status;
901}
902
Yifan Hong13ba0a92018-06-25 16:15:56 -0700903void ListCommand::initFetchTypes() {
Yifan Hong3212f172018-06-28 12:39:50 -0700904 // TODO: refactor to do polymorphism on each table (so that dependency graph is not hardcoded).
905 static const std::map<HalType, std::set<HalType>> kDependencyGraph{
906 {HalType::LAZY_HALS, {HalType::BINDERIZED_SERVICES,
907 HalType::PASSTHROUGH_LIBRARIES,
908 HalType::VINTF_MANIFEST}},
909 };
Yifan Hong13ba0a92018-06-25 16:15:56 -0700910 mFetchTypes.insert(mListTypes.begin(), mListTypes.end());
Yifan Hong3212f172018-06-28 12:39:50 -0700911 for (HalType listType : mListTypes) {
912 auto it = kDependencyGraph.find(listType);
913 if (it != kDependencyGraph.end()) {
914 mFetchTypes.insert(it->second.begin(), it->second.end());
915 }
916 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700917}
918
Yifan Honga6b93f02017-09-13 16:53:37 -0700919void ListCommand::registerAllOptions() {
920 int v = mOptions.size();
921 // A list of acceptable command line options
922 // key: value returned by getopt_long
923 // long options with short alternatives
924 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
925 return USAGE;
926 }, ""});
927 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
928 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
929 return OK;
930 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700931 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
932 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
933 return OK;
Yifan Hong430f8982018-05-25 17:28:39 -0700934 }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700935 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
936 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
937 return OK;
938 }, "print the transport mode column"});
939 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
940 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
941 return OK;
942 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700943 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
944 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
945 return OK;
946 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700947 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
948 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
949 return OK;
950 }, "print the server PID, or server cmdline if -m is set"});
951 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
952 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
953 return OK;
954 }, "print the server object address column"});
955 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
956 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
957 return OK;
958 }, "print the client PIDs, or client cmdlines if -m is set"});
959 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
960 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
961 return OK;
962 }, "print currently used/available threads\n(note, available threads created lazily)"});
963 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
964 thiz->mEnableCmdlines = true;
965 return OK;
966 }, "print cmdline instead of PIDs"});
967 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
968 thiz->mEmitDebugInfo = true;
969 if (arg) thiz->mFileOutputPath = arg;
970 return OK;
971 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
972 "Writes to specified file if 'arg' is provided, otherwise stdout."});
973
Yifan Hongbdf44f82018-05-25 14:20:00 -0700974 mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
975 thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
976 return OK;
977 }, "print VINTF info. This column contains a comma-separated list of:\n"
Steven Moreland8e0f5392018-12-12 14:27:24 -0800978 " - DM: if the HAL is in the device manifest\n"
979 " - DC: if the HAL is in the device compatibility matrix\n"
980 " - FM: if the HAL is in the framework manifest\n"
Steven Morelandd64ba892019-07-12 15:59:31 -0700981 " - FC: if the HAL is in the framework compatibility matrix\n"
982 " - X: if the HAL is in none of the above lists"});
Yifan Hong13ba0a92018-06-25 16:15:56 -0700983 mOptions.push_back({'S', "service-status", no_argument, v++, [](ListCommand* thiz, const char*) {
984 thiz->mSelectedColumns.push_back(TableColumnType::SERVICE_STATUS);
985 return OK;
986 }, "print service status column. Possible values are:\n"
987 " - alive: alive and running hwbinder service;\n"
988 " - registered;dead: registered to hwservicemanager but is not responsive;\n"
989 " - declared: only declared in VINTF manifest but is not registered to hwservicemanager;\n"
990 " - N/A: no information for passthrough HALs."});
Yifan Hongbdf44f82018-05-25 14:20:00 -0700991
Yifan Honga6b93f02017-09-13 16:53:37 -0700992 // long options without short alternatives
993 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
994 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800995 if (thiz->mVintfPartition == Partition::UNKNOWN)
996 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700997 if (arg) thiz->mFileOutputPath = arg;
998 return OK;
999 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -08001000 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
1001 if (!arg) return USAGE;
1002 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
1003 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
1004 return OK;
1005 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
1006 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -07001007 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
1008 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
1009 thiz->mSortColumn = TableEntry::sortByInterfaceName;
1010 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
1011 thiz->mSortColumn = TableEntry::sortByServerPid;
1012 } else {
1013 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
1014 return USAGE;
1015 }
1016 return OK;
1017 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
1018 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
1019 thiz->mNeat = true;
1020 return OK;
1021 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Nirav Atrecce988d2018-05-16 11:14:46 -07001022 mOptions.push_back({'\0', "types", required_argument, v++, [](ListCommand* thiz, const char* arg) {
1023 if (!arg) { return USAGE; }
1024
1025 static const std::map<std::string, HalType> kHalTypeMap {
1026 {"binderized", HalType::BINDERIZED_SERVICES},
1027 {"b", HalType::BINDERIZED_SERVICES},
1028 {"passthrough_clients", HalType::PASSTHROUGH_CLIENTS},
1029 {"c", HalType::PASSTHROUGH_CLIENTS},
1030 {"passthrough_libs", HalType::PASSTHROUGH_LIBRARIES},
Yifan Hong13ba0a92018-06-25 16:15:56 -07001031 {"l", HalType::PASSTHROUGH_LIBRARIES},
1032 {"vintf", HalType::VINTF_MANIFEST},
1033 {"v", HalType::VINTF_MANIFEST},
Yifan Hong3212f172018-06-28 12:39:50 -07001034 {"lazy", HalType::LAZY_HALS},
1035 {"z", HalType::LAZY_HALS},
Nirav Atrecce988d2018-05-16 11:14:46 -07001036 };
1037
1038 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
1039 for (const auto& halTypeArg : halTypesArgs) {
1040 if (halTypeArg.empty()) continue;
1041
1042 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
1043 if (halTypeIter == kHalTypeMap.end()) {
1044
1045 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
1046 return USAGE;
1047 }
1048
1049 // Append unique (non-repeated) HAL types to the reporting list
1050 HalType halType = halTypeIter->second;
1051 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
1052 thiz->mListTypes.end()) {
1053 thiz->mListTypes.push_back(halType);
1054 }
1055 }
1056
1057 if (thiz->mListTypes.empty()) { return USAGE; }
1058 return OK;
Yifan Hong13ba0a92018-06-25 16:15:56 -07001059 }, "comma-separated list of one or more sections.\nThe output is restricted to the selected "
1060 "section(s). Valid options\nare: (b|binderized), (c|passthrough_clients), (l|"
Steven Moreland8e0f5392018-12-12 14:27:24 -08001061 "passthrough_libs), (v|vintf), and (z|lazy).\nDefault is `bcl`."});
Yifan Honga6b93f02017-09-13 16:53:37 -07001062}
1063
1064// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
1065// the lifetime of "options" during the usage of the returned array.
1066static std::unique_ptr<struct option[]> getLongOptions(
1067 const ListCommand::RegisteredOptions& options,
1068 int* longOptFlag) {
1069 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
1070 int i = 0;
1071 for (const auto& e : options) {
1072 ret[i].name = e.longOption.c_str();
1073 ret[i].has_arg = e.hasArg;
1074 ret[i].flag = longOptFlag;
1075 ret[i].val = e.val;
1076
1077 i++;
1078 }
1079 // getopt_long last option has all zeros
Yi Kong19d5c002018-07-20 13:39:55 -07001080 ret[i].name = nullptr;
Yifan Honga6b93f02017-09-13 16:53:37 -07001081 ret[i].has_arg = 0;
Yi Kong19d5c002018-07-20 13:39:55 -07001082 ret[i].flag = nullptr;
Yifan Honga6b93f02017-09-13 16:53:37 -07001083 ret[i].val = 0;
1084
1085 return ret;
1086}
1087
1088// Create 'optstring' argument to getopt_long.
1089static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
1090 std::stringstream ss;
1091 for (const auto& e : options) {
1092 if (e.shortOption != '\0') {
1093 ss << e.shortOption;
1094 }
1095 }
1096 return ss.str();
1097}
1098
Yifan Honga8bedc62017-09-08 18:00:31 -07001099Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -07001100 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -07001101
Yifan Honga6b93f02017-09-13 16:53:37 -07001102 if (mOptions.empty()) {
1103 registerAllOptions();
1104 }
1105 int longOptFlag;
1106 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
1107 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001108
Yifan Honga8bedc62017-09-08 18:00:31 -07001109 // suppress output to std::err for unknown options
1110 opterr = 0;
1111
Yifan Hong443df792017-05-09 18:49:45 -07001112 int optionIndex;
1113 int c;
1114 // Lshal::parseArgs has set optind to the next option to parse
1115 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -07001116 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -07001117 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -07001118 if (c == -1) {
1119 break;
1120 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001121 const RegisteredOption* found = nullptr;
1122 if (c == 0) {
1123 // see long option
1124 for (const auto& e : mOptions) {
1125 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -07001126 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001127 } else {
1128 // see short option
1129 for (const auto& e : mOptions) {
1130 if (c == e.shortOption) found = &e;
1131 }
Yifan Hong443df792017-05-09 18:49:45 -07001132 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001133
1134 if (found == nullptr) {
1135 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -07001136 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -07001137 return USAGE;
1138 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001139
1140 Status status = found->op(this, optarg);
1141 if (status != OK) {
1142 return status;
1143 }
Yifan Hong443df792017-05-09 18:49:45 -07001144 }
1145 if (optind < arg.argc) {
1146 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -07001147 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001148 return USAGE;
1149 }
1150
1151 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -07001152 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001153 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -07001154 }
1155
Yifan Honga6b93f02017-09-13 16:53:37 -07001156 if (mSelectedColumns.empty()) {
Steven Moreland8e0f5392018-12-12 14:27:24 -08001157 mSelectedColumns = {TableColumnType::VINTF, TableColumnType::RELEASED,
Yifan Hongfee209d2017-09-14 18:23:38 -07001158 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -07001159 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -07001160 }
Yifan Hongd4a77e82017-09-06 19:40:24 -07001161
Yifan Honga6b93f02017-09-13 16:53:37 -07001162 if (mEnableCmdlines) {
1163 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
1164 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
1165 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001166 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001167 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
1168 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001169 }
1170 }
1171 }
1172
Nirav Atrecce988d2018-05-16 11:14:46 -07001173 // By default, list all HAL types
1174 if (mListTypes.empty()) {
1175 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
1176 HalType::PASSTHROUGH_LIBRARIES};
1177 }
Yifan Hong13ba0a92018-06-25 16:15:56 -07001178 initFetchTypes();
Nirav Atrecce988d2018-05-16 11:14:46 -07001179
Yifan Honga6b93f02017-09-13 16:53:37 -07001180 forEachTable([this] (Table& table) {
1181 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001182 });
1183
Yifan Hong443df792017-05-09 18:49:45 -07001184 return OK;
1185}
1186
Yifan Honga8bedc62017-09-08 18:00:31 -07001187Status ListCommand::main(const Arg &arg) {
1188 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -07001189 if (status != OK) {
1190 return status;
1191 }
1192 status = fetch();
1193 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -07001194 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -07001195 return status;
1196}
1197
Yifan Honga6b93f02017-09-13 16:53:37 -07001198const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
1199 static const std::string empty{};
1200 static const std::string optional{"[=<arg>]"};
1201 static const std::string required{"=<arg>"};
1202
1203 if (hasArg == optional_argument) {
1204 return optional;
1205 }
1206 if (hasArg == required_argument) {
1207 return required;
1208 }
1209 return empty;
1210}
1211
Yifan Honga8bedc62017-09-08 18:00:31 -07001212void ListCommand::usage() const {
1213
Yifan Honga6b93f02017-09-13 16:53:37 -07001214 err() << "list:" << std::endl
1215 << " lshal" << std::endl
1216 << " lshal list" << std::endl
Steven Moreland8e0f5392018-12-12 14:27:24 -08001217 << " List all hals with default ordering and columns (`lshal list -Vliepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001218 << " lshal list [-h|--help]" << std::endl
1219 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1220 << " lshal [list] [OPTIONS...]" << std::endl;
1221 for (const auto& e : mOptions) {
1222 if (e.help.empty()) {
1223 continue;
1224 }
1225 err() << " ";
1226 if (e.shortOption != '\0')
1227 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1228 if (e.shortOption != '\0' && !e.longOption.empty())
1229 err() << ", ";
1230 if (!e.longOption.empty())
1231 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1232 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001233 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001234 for (const auto& line : lines) {
1235 if (&line != &lines.front())
1236 err() << " ";
1237 err() << line << std::endl;
1238 }
1239 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001240}
1241
Yifan Hong443df792017-05-09 18:49:45 -07001242} // namespace lshal
1243} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001244