blob: 1a412b2db60693743cdc839e2618ce446551de48 [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;
166 (void)object->forEachInstanceOfVersion(fqInstance.getPackage(), fqInstance.getVersion(),
167 [&](const auto& instance) {
168 found = match(instance, fqInstance, ta);
169 return !found; // continue if not found
170 });
171 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) {
209 std::ifstream ifs("/d/binder/proc/" + std::to_string(pid));
Yifan Hong443df792017-05-09 18:49:45 -0700210 if (!ifs.is_open()) {
211 return false;
212 }
213
Steven Morelandd8e20192017-05-24 11:23:08 -0700214 static const std::regex kContextLine("^context (\\w+)$");
Yifan Hong443df792017-05-09 18:49:45 -0700215
Steven Morelandd8e20192017-05-24 11:23:08 -0700216 bool isDesiredContext = false;
Yifan Hong443df792017-05-09 18:49:45 -0700217 std::string line;
218 std::smatch match;
219 while(getline(ifs, line)) {
Steven Morelandd8e20192017-05-24 11:23:08 -0700220 if (std::regex_search(line, match, kContextLine)) {
221 isDesiredContext = match.str(1) == contextName;
Yifan Hong443df792017-05-09 18:49:45 -0700222 continue;
223 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700224
225 if (!isDesiredContext) {
Yifan Hong443df792017-05-09 18:49:45 -0700226 continue;
227 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700228
229 eachLine(line);
Yifan Hong443df792017-05-09 18:49:45 -0700230 }
231 return true;
232}
233
Steven Morelandd8e20192017-05-24 11:23:08 -0700234bool ListCommand::getPidInfo(
235 pid_t serverPid, PidInfo *pidInfo) const {
236 static const std::regex kReferencePrefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
237 static const std::regex kThreadPrefix("^\\s*thread \\d+:\\s+l\\s+(\\d)(\\d)");
238
239 std::smatch match;
240 return scanBinderContext(serverPid, "hwbinder", [&](const std::string& line) {
241 if (std::regex_search(line, match, kReferencePrefix)) {
242 const std::string &ptrString = "0x" + match.str(2); // use number after c
243 uint64_t ptr;
244 if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
245 // Should not reach here, but just be tolerant.
Yifan Hong76ac14a2017-09-08 14:59:04 -0700246 err() << "Could not parse number " << ptrString << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700247 return;
248 }
249 const std::string proc = " proc ";
250 auto pos = line.rfind(proc);
251 if (pos != std::string::npos) {
252 for (const std::string &pidStr : split(line.substr(pos + proc.size()), ' ')) {
253 int32_t pid;
254 if (!::android::base::ParseInt(pidStr, &pid)) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700255 err() << "Could not parse number " << pidStr << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700256 return;
257 }
258 pidInfo->refPids[ptr].push_back(pid);
259 }
260 }
261
262 return;
263 }
264
265 if (std::regex_search(line, match, kThreadPrefix)) {
266 // "1" is waiting in binder driver
267 // "2" is poll. It's impossible to tell if these are in use.
268 // and HIDL default code doesn't use it.
269 bool isInUse = match.str(1) != "1";
270 // "0" is a thread that has called into binder
271 // "1" is looper thread
272 // "2" is main looper thread
273 bool isHwbinderThread = match.str(2) != "0";
274
275 if (!isHwbinderThread) {
276 return;
277 }
278
279 if (isInUse) {
280 pidInfo->threadUsage++;
281 }
282
283 pidInfo->threadCount++;
284 return;
285 }
286
287 // not reference or thread line
288 return;
289 });
290}
291
Yifan Hong1243dde2017-09-14 17:49:30 -0700292const PidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
293 auto pair = mCachedPidInfos.insert({serverPid, PidInfo{}});
294 if (pair.second /* did insertion take place? */) {
295 if (!getPidInfo(serverPid, &pair.first->second)) {
296 return nullptr;
297 }
298 }
299 return &pair.first->second;
300}
301
Yifan Hong13ba0a92018-06-25 16:15:56 -0700302bool ListCommand::shouldFetchHalType(const HalType &type) const {
303 return (std::find(mFetchTypes.begin(), mFetchTypes.end(), type) != mFetchTypes.end());
Nirav Atrecce988d2018-05-16 11:14:46 -0700304}
305
Yifan Hongdb730532018-06-25 16:32:01 -0700306Table* ListCommand::tableForType(HalType type) {
307 switch (type) {
308 case HalType::BINDERIZED_SERVICES:
309 return &mServicesTable;
310 case HalType::PASSTHROUGH_CLIENTS:
311 return &mPassthroughRefTable;
312 case HalType::PASSTHROUGH_LIBRARIES:
313 return &mImplementationsTable;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700314 case HalType::VINTF_MANIFEST:
315 return &mManifestHalsTable;
Yifan Hongdb730532018-06-25 16:32:01 -0700316 default:
317 LOG(FATAL) << "Unknown HAL type " << static_cast<int64_t>(type);
318 return nullptr;
319 }
320}
321const Table* ListCommand::tableForType(HalType type) const {
322 return const_cast<ListCommand*>(this)->tableForType(type);
323}
324
Yifan Hong443df792017-05-09 18:49:45 -0700325void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
Nirav Atrecce988d2018-05-16 11:14:46 -0700326 for (const auto& type : mListTypes) {
Yifan Hongdb730532018-06-25 16:32:01 -0700327 f(*tableForType(type));
Nirav Atrecce988d2018-05-16 11:14:46 -0700328 }
Yifan Hong443df792017-05-09 18:49:45 -0700329}
330void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
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}
335
336void ListCommand::postprocess() {
337 forEachTable([this](Table &table) {
338 if (mSortColumn) {
339 std::sort(table.begin(), table.end(), mSortColumn);
340 }
341 for (TableEntry &entry : table) {
342 entry.serverCmdline = getCmdline(entry.serverPid);
343 removeDeadProcesses(&entry.clientPids);
344 for (auto pid : entry.clientPids) {
345 entry.clientCmdlines.push_back(this->getCmdline(pid));
346 }
347 }
Yifan Hongf31aa052018-02-02 15:17:51 -0800348 for (TableEntry& entry : table) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700349 if (entry.partition == Partition::UNKNOWN) {
350 entry.partition = getPartition(entry.serverPid);
351 }
Yifan Hongbdf44f82018-05-25 14:20:00 -0700352 entry.vintfInfo = getVintfInfo(entry.interfaceName, {entry.transport, entry.arch});
Yifan Hongf31aa052018-02-02 15:17:51 -0800353 }
Yifan Hong443df792017-05-09 18:49:45 -0700354 });
355 // use a double for loop here because lshal doesn't care about efficiency.
356 for (TableEntry &packageEntry : mImplementationsTable) {
357 std::string packageName = packageEntry.interfaceName;
Steven Morelandd4f32b32018-03-06 14:47:58 -0800358 FQName fqPackageName;
359 if (!FQName::parse(packageName.substr(0, packageName.find("::")), &fqPackageName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700360 continue;
361 }
362 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700363 if (interfaceEntry.arch != vintf::Arch::ARCH_EMPTY) {
Yifan Hong443df792017-05-09 18:49:45 -0700364 continue;
365 }
Steven Morelandd4f32b32018-03-06 14:47:58 -0800366 FQName interfaceName;
367 if (!FQName::parse(splitFirst(interfaceEntry.interfaceName, '/').first, &interfaceName)) {
Yifan Hong443df792017-05-09 18:49:45 -0700368 continue;
369 }
370 if (interfaceName.getPackageAndVersion() == fqPackageName) {
371 interfaceEntry.arch = packageEntry.arch;
372 }
373 }
374 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700375
376 mServicesTable.setDescription(
377 "All binderized services (registered services through hwservicemanager)");
378 mPassthroughRefTable.setDescription(
379 "All interfaces that getService() has ever return as a passthrough interface;\n"
380 "PIDs / processes shown below might be inaccurate because the process\n"
381 "might have relinquished the interface or might have died.\n"
382 "The Server / Server CMD column can be ignored.\n"
383 "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
384 "the library and successfully fetched the passthrough implementation.");
385 mImplementationsTable.setDescription(
Steven Moreland3d2c1e12018-03-14 10:41:13 -0700386 "All available passthrough implementations (all -impl.so files).\n"
387 "These may return subclasses through their respective HIDL_FETCH_I* functions.");
Yifan Hong13ba0a92018-06-25 16:15:56 -0700388 mManifestHalsTable.setDescription(
389 "All HALs that are in VINTF manifest.");
Yifan Hong443df792017-05-09 18:49:45 -0700390}
391
Yifan Hongb2d096a2018-05-01 15:25:23 -0700392bool ListCommand::addEntryWithInstance(const TableEntry& entry,
393 vintf::HalManifest* manifest) const {
394 FqInstance fqInstance;
395 if (!fqInstance.setTo(entry.interfaceName)) {
396 err() << "Warning: '" << entry.interfaceName << "' is not a valid FqInstance." << std::endl;
397 return false;
Yifan Hong77c87822017-06-19 15:47:39 -0700398 }
Yifan Hongb2d096a2018-05-01 15:25:23 -0700399
400 if (fqInstance.getPackage() == gIBaseFqName.package()) {
401 return true; // always remove IBase from manifest
402 }
403
404 Partition partition = resolvePartition(entry.partition, fqInstance);
405
406 if (partition == Partition::UNKNOWN) {
407 err() << "Warning: Cannot guess the partition of FqInstance " << fqInstance.string()
408 << std::endl;
409 return false;
410 }
411
412 if (partition != mVintfPartition) {
413 return true; // strip out instances that is in a different partition.
414 }
415
Yifan Hongb2d096a2018-05-01 15:25:23 -0700416 vintf::Arch arch;
Yifan Hong8304e412018-05-25 15:05:36 -0700417 if (entry.transport == vintf::Transport::HWBINDER) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700418 arch = vintf::Arch::ARCH_EMPTY; // no need to specify arch in manifest
Yifan Hong8304e412018-05-25 15:05:36 -0700419 } else if (entry.transport == vintf::Transport::PASSTHROUGH) {
Yifan Hong0ad64f52018-05-25 15:29:17 -0700420 if (entry.arch == vintf::Arch::ARCH_EMPTY) {
421 err() << "Warning: '" << entry.interfaceName << "' doesn't have bitness info.";
422 return false;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700423 }
Yifan Hong0ad64f52018-05-25 15:29:17 -0700424 arch = entry.arch;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700425 } else {
426 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
427 return false;
428 }
429
430 std::string e;
Yifan Hong8304e412018-05-25 15:05:36 -0700431 if (!manifest->insertInstance(fqInstance, entry.transport, arch, vintf::HalFormat::HIDL, &e)) {
Yifan Hongb2d096a2018-05-01 15:25:23 -0700432 err() << "Warning: Cannot insert '" << fqInstance.string() << ": " << e << std::endl;
433 return false;
434 }
435 return true;
436}
437
438bool ListCommand::addEntryWithoutInstance(const TableEntry& entry,
439 const vintf::HalManifest* manifest) const {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700440 const auto& packageAndVersion = splitFirst(getPackageAndVersion(entry.interfaceName), '@');
Yifan Hongb2d096a2018-05-01 15:25:23 -0700441 const auto& package = packageAndVersion.first;
442 vintf::Version version;
443 if (!vintf::parse(packageAndVersion.second, &version)) {
444 err() << "Warning: Cannot parse version '" << packageAndVersion.second << "' for entry '"
445 << entry.interfaceName << "'" << std::endl;
446 return false;
447 }
448
449 bool found = false;
450 (void)manifest->forEachInstanceOfVersion(package, version, [&found](const auto&) {
451 found = true;
452 return false; // break
453 });
454 return found;
Yifan Hong77c87822017-06-19 15:47:39 -0700455}
456
Yifan Hongca3b6602017-09-07 16:44:27 -0700457void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700458 using vintf::operator|=;
Yifan Hongf31aa052018-02-02 15:17:51 -0800459 using vintf::operator<<;
Yifan Hongb2d096a2018-05-01 15:25:23 -0700460 using namespace std::placeholders;
Yifan Hong443df792017-05-09 18:49:45 -0700461
462 vintf::HalManifest manifest;
Yifan Hongf31aa052018-02-02 15:17:51 -0800463 manifest.setType(toSchemaType(mVintfPartition));
Yifan Hong443df792017-05-09 18:49:45 -0700464
Yifan Hongb2d096a2018-05-01 15:25:23 -0700465 std::vector<std::string> error;
466 for (const TableEntry& entry : mServicesTable)
467 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
468 for (const TableEntry& entry : mPassthroughRefTable)
469 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700470 for (const TableEntry& entry : mManifestHalsTable)
471 if (!addEntryWithInstance(entry, &manifest)) error.push_back(entry.interfaceName);
Yifan Hong443df792017-05-09 18:49:45 -0700472
Yifan Hongb2d096a2018-05-01 15:25:23 -0700473 std::vector<std::string> passthrough;
474 for (const TableEntry& entry : mImplementationsTable)
475 if (!addEntryWithoutInstance(entry, &manifest)) passthrough.push_back(entry.interfaceName);
Yifan Hongf31aa052018-02-02 15:17:51 -0800476
Yifan Hongf31aa052018-02-02 15:17:51 -0800477 out << "<!-- " << std::endl
Yifan Hongb2d096a2018-05-01 15:25:23 -0700478 << " This is a skeleton " << manifest.type() << " manifest. Notes: " << std::endl
479 << INIT_VINTF_NOTES;
480 if (!error.empty()) {
481 out << std::endl << " The following HALs are not added; see warnings." << std::endl;
482 for (const auto& e : error) {
483 out << " " << e << std::endl;
484 }
485 }
486 if (!passthrough.empty()) {
487 out << std::endl
488 << " The following HALs are passthrough and no interface or instance " << std::endl
489 << " names can be inferred." << std::endl;
490 for (const auto& e : passthrough) {
491 out << " " << e << std::endl;
492 }
493 }
494 out << "-->" << std::endl;
495 out << vintf::gHalManifestConverter(manifest, vintf::SerializeFlag::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700496}
497
Yifan Hongf31aa052018-02-02 15:17:51 -0800498std::string ListCommand::INIT_VINTF_NOTES{
Yifan Hongb2d096a2018-05-01 15:25:23 -0700499 " 1. If a HAL is supported in both hwbinder and passthrough transport,\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800500 " only hwbinder is shown.\n"
501 " 2. It is likely that HALs in passthrough transport does not have\n"
502 " <interface> declared; users will have to write them by hand.\n"
503 " 3. A HAL with lower minor version can be overridden by a HAL with\n"
504 " higher minor version if they have the same name and major version.\n"
Yifan Hongb2d096a2018-05-01 15:25:23 -0700505 " 4. This output is intended for launch devices.\n"
506 " Upgrading devices should not use this tool to generate device\n"
507 " manifest and replace the existing manifest directly, but should\n"
508 " edit the existing manifest manually.\n"
509 " Specifically, devices which launched at Android O-MR1 or earlier\n"
510 " should not use the 'fqname' format for required HAL entries and\n"
511 " should instead use the legacy package, name, instance-name format\n"
512 " until they are updated.\n"
Yifan Hongf31aa052018-02-02 15:17:51 -0800513};
514
Yifan Hong0ad64f52018-05-25 15:29:17 -0700515static vintf::Arch fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
Yifan Hong443df792017-05-09 18:49:45 -0700516 switch (a) {
517 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700518 return vintf::Arch::ARCH_64;
Yifan Hong443df792017-05-09 18:49:45 -0700519 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700520 return vintf::Arch::ARCH_32;
Yifan Hong443df792017-05-09 18:49:45 -0700521 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
522 default:
Yifan Hong0ad64f52018-05-25 15:29:17 -0700523 return vintf::Arch::ARCH_EMPTY;
Yifan Hong443df792017-05-09 18:49:45 -0700524 }
525}
526
Yifan Hongca3b6602017-09-07 16:44:27 -0700527void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700528 if (mNeat) {
Yifan Hongb72f19e2018-06-27 16:58:56 -0700529 std::vector<const Table*> tables;
530 forEachTable([&tables](const Table &table) {
531 tables.push_back(&table);
532 });
533 MergedTable(std::move(tables)).createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700534 return;
535 }
536
Yifan Hongca3b6602017-09-07 16:44:27 -0700537 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700538
Yifan Hongd4a77e82017-09-06 19:40:24 -0700539 // We're only interested in dumping debug info for already
540 // instantiated services. There's little value in dumping the
541 // debug info for a service we create on the fly, so we only operate
542 // on the "mServicesTable".
543 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
544 if (mEmitDebugInfo && &table == &mServicesTable) {
545 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700546 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700547 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800548 mLshal.emitDebugInfo(pair.first, pair.second, {},
549 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700550 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700551 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700552 };
Yifan Hong443df792017-05-09 18:49:45 -0700553 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700554 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
555 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700556 });
Yifan Hong443df792017-05-09 18:49:45 -0700557}
558
Yifan Hongca3b6602017-09-07 16:44:27 -0700559Status ListCommand::dump() {
560 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
561
562 if (mFileOutputPath.empty()) {
563 (*this.*dump)(out());
564 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700565 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700566
567 std::ofstream fileOutput(mFileOutputPath);
568 if (!fileOutput.is_open()) {
569 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
570 return IO_ERROR;
571 }
572 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
573
574 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
575
576 fileOutput.flush();
577 fileOutput.close();
578 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700579}
580
Yifan Hong20f4ee82018-06-25 16:21:29 -0700581void ListCommand::putEntry(HalType type, TableEntry &&entry) {
Yifan Hongdb730532018-06-25 16:32:01 -0700582 tableForType(type)->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700583}
584
585Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700586 if (!shouldFetchHalType(HalType::PASSTHROUGH_LIBRARIES)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700587
Yifan Hong443df792017-05-09 18:49:45 -0700588 using namespace ::android::hardware;
589 using namespace ::android::hidl::manager::V1_0;
590 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700591 using std::literals::chrono_literals::operator""s;
592 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700593 std::map<std::string, TableEntry> entries;
594 for (const auto &info : infos) {
595 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
596 std::string{info.instanceName.c_str()};
597 entries.emplace(interfaceName, TableEntry{
598 .interfaceName = interfaceName,
Yifan Hong8304e412018-05-25 15:05:36 -0700599 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700600 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700601 }).first->second.arch |= fromBaseArchitecture(info.arch);
602 }
603 for (auto &&pair : entries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700604 putEntry(HalType::PASSTHROUGH_LIBRARIES, std::move(pair.second));
Yifan Hong443df792017-05-09 18:49:45 -0700605 }
606 });
607 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700608 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700609 << ret.description() << std::endl;
610 return DUMP_ALL_LIBS_ERROR;
611 }
612 return OK;
613}
614
615Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
Yifan Hong13ba0a92018-06-25 16:15:56 -0700616 if (!shouldFetchHalType(HalType::PASSTHROUGH_CLIENTS)) { return OK; }
Nirav Atrecce988d2018-05-16 11:14:46 -0700617
Yifan Hong443df792017-05-09 18:49:45 -0700618 using namespace ::android::hardware;
619 using namespace ::android::hardware::details;
620 using namespace ::android::hidl::manager::V1_0;
621 using namespace ::android::hidl::base::V1_0;
622 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
623 for (const auto &info : infos) {
624 if (info.clientPids.size() <= 0) {
625 continue;
626 }
Yifan Hong20f4ee82018-06-25 16:21:29 -0700627 putEntry(HalType::PASSTHROUGH_CLIENTS, {
Yifan Hong443df792017-05-09 18:49:45 -0700628 .interfaceName =
629 std::string{info.interfaceName.c_str()} + "/" +
630 std::string{info.instanceName.c_str()},
Yifan Hong8304e412018-05-25 15:05:36 -0700631 .transport = vintf::Transport::PASSTHROUGH,
Yifan Hong443df792017-05-09 18:49:45 -0700632 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700633 .clientPids = info.clientPids,
634 .arch = fromBaseArchitecture(info.arch)
635 });
636 }
637 });
638 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700639 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700640 << ret.description() << std::endl;
641 return DUMP_PASSTHROUGH_ERROR;
642 }
643 return OK;
644}
645
646Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong8304e412018-05-25 15:05:36 -0700647 using vintf::operator<<;
648
Yifan Hong13ba0a92018-06-25 16:15:56 -0700649 if (!shouldFetchHalType(HalType::BINDERIZED_SERVICES)) { return OK; }
Yifan Hong443df792017-05-09 18:49:45 -0700650
Yifan Hong8304e412018-05-25 15:05:36 -0700651 const vintf::Transport mode = vintf::Transport::HWBINDER;
Yifan Hong443df792017-05-09 18:49:45 -0700652 hidl_vec<hidl_string> fqInstanceNames;
653 // copying out for timeoutIPC
654 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
655 fqInstanceNames = names;
656 });
657 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700658 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700659 << listRet.description() << std::endl;
660 return DUMP_BINDERIZED_ERROR;
661 }
662
663 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700664 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700665 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700666 // create entry and default assign all fields.
667 TableEntry& entry = allTableEntries[fqInstanceName];
668 entry.interfaceName = fqInstanceName;
669 entry.transport = mode;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700670 entry.serviceStatus = ServiceStatus::NON_RESPONSIVE;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700671
672 status |= fetchBinderizedEntry(manager, &entry);
673 }
674
675 for (auto& pair : allTableEntries) {
Yifan Hong20f4ee82018-06-25 16:21:29 -0700676 putEntry(HalType::BINDERIZED_SERVICES, std::move(pair.second));
Yifan Hong22ea7b82017-09-14 18:07:43 -0700677 }
678 return status;
679}
680
681Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
682 TableEntry *entry) {
683 Status status = OK;
684 const auto handleError = [&](Status additionalError, const std::string& msg) {
685 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
686 status |= DUMP_BINDERIZED_ERROR | additionalError;
687 };
688
689 const auto pair = splitFirst(entry->interfaceName, '/');
690 const auto &serviceName = pair.first;
691 const auto &instanceName = pair.second;
692 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
693 if (!getRet.isOk()) {
694 handleError(TRANSACTION_ERROR,
695 "cannot be fetched from service manager:" + getRet.description());
696 return status;
697 }
698 sp<IBase> service = getRet;
699 if (service == nullptr) {
700 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
701 return status;
702 }
703
704 // getDebugInfo
705 do {
706 DebugInfo debugInfo;
707 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
708 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700709 });
710 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700711 handleError(TRANSACTION_ERROR,
712 "debugging information cannot be retrieved: " + debugRet.description());
713 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700714 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700715
Yifan Hong22ea7b82017-09-14 18:07:43 -0700716 entry->serverPid = debugInfo.pid;
717 entry->serverObjectAddress = debugInfo.ptr;
718 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700719
Yifan Hong22ea7b82017-09-14 18:07:43 -0700720 if (debugInfo.pid != NO_PID) {
721 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
722 if (pidInfo == nullptr) {
723 handleError(IO_ERROR,
724 "no information for PID " + std::to_string(debugInfo.pid) +
725 ", are you root?");
726 break;
727 }
728 if (debugInfo.ptr != NO_PTR) {
729 auto it = pidInfo->refPids.find(debugInfo.ptr);
730 if (it != pidInfo->refPids.end()) {
731 entry->clientPids = it->second;
732 }
733 }
734 entry->threadUsage = pidInfo->threadUsage;
735 entry->threadCount = pidInfo->threadCount;
736 }
737 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700738
739 // hash
740 do {
741 ssize_t hashIndex = -1;
742 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
743 for (size_t i = 0; i < c.size(); ++i) {
744 if (serviceName == c[i]) {
745 hashIndex = static_cast<ssize_t>(i);
746 break;
747 }
748 }
749 });
750 if (!ifaceChainRet.isOk()) {
751 handleError(TRANSACTION_ERROR,
752 "interfaceChain fails: " + ifaceChainRet.description());
753 break; // skip getHashChain
754 }
755 if (hashIndex < 0) {
756 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
757 break; // skip getHashChain
758 }
759 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
760 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
761 handleError(BAD_IMPL,
762 "interfaceChain indicates position " + std::to_string(hashIndex) +
763 " but getHashChain returns " + std::to_string(hashChain.size()) +
764 " hashes");
765 return;
766 }
767
768 auto&& hashArray = hashChain[hashIndex];
769 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
770 entry->hash = Hash::hexString(hashVec);
771 });
772 if (!hashRet.isOk()) {
773 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
774 }
775 } while (0);
Yifan Hong13ba0a92018-06-25 16:15:56 -0700776 if (status == OK) {
777 entry->serviceStatus = ServiceStatus::ALIVE;
778 }
779 return status;
780}
781
782Status ListCommand::fetchManifestHals() {
783 if (!shouldFetchHalType(HalType::VINTF_MANIFEST)) { return OK; }
784 Status status = OK;
785
786 for (auto manifest : {getDeviceManifest(), getFrameworkManifest()}) {
787 if (manifest == nullptr) {
788 status |= VINTF_ERROR;
789 continue;
790 }
791
792 std::map<std::string, TableEntry> entries;
793
794 manifest->forEachInstance([&] (const vintf::ManifestInstance& manifestInstance) {
795 TableEntry entry{
796 .interfaceName = manifestInstance.getFqInstance().string(),
797 .transport = manifestInstance.transport(),
798 .arch = manifestInstance.arch(),
799 // TODO(b/71555570): Device manifest does not distinguish HALs from vendor or ODM.
800 .partition = toPartition(manifest->type()),
801 .serviceStatus = ServiceStatus::DECLARED};
802 std::string key = entry.interfaceName;
803 entries.emplace(std::move(key), std::move(entry));
804 return true;
805 });
806
807 for (auto&& pair : entries)
808 mManifestHalsTable.add(std::move(pair.second));
809 }
Yifan Hong443df792017-05-09 18:49:45 -0700810 return status;
811}
812
813Status ListCommand::fetch() {
814 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700815 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700816 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700817 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700818 status |= NO_BINDERIZED_MANAGER;
819 } else {
820 status |= fetchBinderized(bManager);
821 // Passthrough PIDs are registered to the binderized manager as well.
822 status |= fetchPassthrough(bManager);
823 }
824
Yifan Hong9881df92017-05-10 14:33:05 -0700825 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700826 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700827 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700828 status |= NO_PASSTHROUGH_MANAGER;
829 } else {
830 status |= fetchAllLibraries(pManager);
831 }
Yifan Hong13ba0a92018-06-25 16:15:56 -0700832 status |= fetchManifestHals();
Yifan Hong443df792017-05-09 18:49:45 -0700833 return status;
834}
835
Yifan Hong13ba0a92018-06-25 16:15:56 -0700836void ListCommand::initFetchTypes() {
837 mFetchTypes.insert(mListTypes.begin(), mListTypes.end());
838}
839
Yifan Honga6b93f02017-09-13 16:53:37 -0700840void ListCommand::registerAllOptions() {
841 int v = mOptions.size();
842 // A list of acceptable command line options
843 // key: value returned by getopt_long
844 // long options with short alternatives
845 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
846 return USAGE;
847 }, ""});
848 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
849 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
850 return OK;
851 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700852 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
853 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
854 return OK;
Yifan Hong430f8982018-05-25 17:28:39 -0700855 }, "print the 'is released?' column\n(Y=released, N=unreleased, ?=unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700856 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
857 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
858 return OK;
859 }, "print the transport mode column"});
860 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
861 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
862 return OK;
863 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700864 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
865 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
866 return OK;
867 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700868 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
869 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
870 return OK;
871 }, "print the server PID, or server cmdline if -m is set"});
872 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
873 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
874 return OK;
875 }, "print the server object address column"});
876 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
877 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
878 return OK;
879 }, "print the client PIDs, or client cmdlines if -m is set"});
880 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
881 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
882 return OK;
883 }, "print currently used/available threads\n(note, available threads created lazily)"});
884 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
885 thiz->mEnableCmdlines = true;
886 return OK;
887 }, "print cmdline instead of PIDs"});
888 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
889 thiz->mEmitDebugInfo = true;
890 if (arg) thiz->mFileOutputPath = arg;
891 return OK;
892 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
893 "Writes to specified file if 'arg' is provided, otherwise stdout."});
894
Yifan Hongbdf44f82018-05-25 14:20:00 -0700895 mOptions.push_back({'V', "vintf", no_argument, v++, [](ListCommand* thiz, const char*) {
896 thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
897 return OK;
898 }, "print VINTF info. This column contains a comma-separated list of:\n"
899 " - DM: device manifest\n"
900 " - DC: device compatibility matrix\n"
901 " - FM: framework manifest\n"
902 " - FC: framework compatibility matrix"});
Yifan Hong13ba0a92018-06-25 16:15:56 -0700903 mOptions.push_back({'S', "service-status", no_argument, v++, [](ListCommand* thiz, const char*) {
904 thiz->mSelectedColumns.push_back(TableColumnType::SERVICE_STATUS);
905 return OK;
906 }, "print service status column. Possible values are:\n"
907 " - alive: alive and running hwbinder service;\n"
908 " - registered;dead: registered to hwservicemanager but is not responsive;\n"
909 " - declared: only declared in VINTF manifest but is not registered to hwservicemanager;\n"
910 " - N/A: no information for passthrough HALs."});
Yifan Hongbdf44f82018-05-25 14:20:00 -0700911
Yifan Honga6b93f02017-09-13 16:53:37 -0700912 // long options without short alternatives
913 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
914 thiz->mVintf = true;
Yifan Hongf31aa052018-02-02 15:17:51 -0800915 if (thiz->mVintfPartition == Partition::UNKNOWN)
916 thiz->mVintfPartition = Partition::VENDOR;
Yifan Honga6b93f02017-09-13 16:53:37 -0700917 if (arg) thiz->mFileOutputPath = arg;
918 return OK;
919 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
Yifan Hongf31aa052018-02-02 15:17:51 -0800920 mOptions.push_back({'\0', "init-vintf-partition", required_argument, v++, [](ListCommand* thiz, const char* arg) {
921 if (!arg) return USAGE;
922 thiz->mVintfPartition = android::procpartition::parsePartition(arg);
923 if (thiz->mVintfPartition == Partition::UNKNOWN) return USAGE;
924 return OK;
925 }, "Specify the partition of the HAL manifest\ngenerated by --init-vintf.\n"
926 "Valid values are 'system', 'vendor', and 'odm'. Default is 'vendor'."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700927 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
928 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
929 thiz->mSortColumn = TableEntry::sortByInterfaceName;
930 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
931 thiz->mSortColumn = TableEntry::sortByServerPid;
932 } else {
933 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
934 return USAGE;
935 }
936 return OK;
937 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
938 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
939 thiz->mNeat = true;
940 return OK;
941 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
Nirav Atrecce988d2018-05-16 11:14:46 -0700942 mOptions.push_back({'\0', "types", required_argument, v++, [](ListCommand* thiz, const char* arg) {
943 if (!arg) { return USAGE; }
944
945 static const std::map<std::string, HalType> kHalTypeMap {
946 {"binderized", HalType::BINDERIZED_SERVICES},
947 {"b", HalType::BINDERIZED_SERVICES},
948 {"passthrough_clients", HalType::PASSTHROUGH_CLIENTS},
949 {"c", HalType::PASSTHROUGH_CLIENTS},
950 {"passthrough_libs", HalType::PASSTHROUGH_LIBRARIES},
Yifan Hong13ba0a92018-06-25 16:15:56 -0700951 {"l", HalType::PASSTHROUGH_LIBRARIES},
952 {"vintf", HalType::VINTF_MANIFEST},
953 {"v", HalType::VINTF_MANIFEST},
Nirav Atrecce988d2018-05-16 11:14:46 -0700954 };
955
956 std::vector<std::string> halTypesArgs = split(std::string(arg), ',');
957 for (const auto& halTypeArg : halTypesArgs) {
958 if (halTypeArg.empty()) continue;
959
960 const auto& halTypeIter = kHalTypeMap.find(halTypeArg);
961 if (halTypeIter == kHalTypeMap.end()) {
962
963 thiz->err() << "Unrecognized HAL type: " << halTypeArg << std::endl;
964 return USAGE;
965 }
966
967 // Append unique (non-repeated) HAL types to the reporting list
968 HalType halType = halTypeIter->second;
969 if (std::find(thiz->mListTypes.begin(), thiz->mListTypes.end(), halType) ==
970 thiz->mListTypes.end()) {
971 thiz->mListTypes.push_back(halType);
972 }
973 }
974
975 if (thiz->mListTypes.empty()) { return USAGE; }
976 return OK;
Yifan Hong13ba0a92018-06-25 16:15:56 -0700977 }, "comma-separated list of one or more sections.\nThe output is restricted to the selected "
978 "section(s). Valid options\nare: (b|binderized), (c|passthrough_clients), (l|"
979 "passthrough_libs), and (v|vintf).\nDefault is `bcl`."});
Yifan Honga6b93f02017-09-13 16:53:37 -0700980}
981
982// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
983// the lifetime of "options" during the usage of the returned array.
984static std::unique_ptr<struct option[]> getLongOptions(
985 const ListCommand::RegisteredOptions& options,
986 int* longOptFlag) {
987 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
988 int i = 0;
989 for (const auto& e : options) {
990 ret[i].name = e.longOption.c_str();
991 ret[i].has_arg = e.hasArg;
992 ret[i].flag = longOptFlag;
993 ret[i].val = e.val;
994
995 i++;
996 }
997 // getopt_long last option has all zeros
998 ret[i].name = NULL;
999 ret[i].has_arg = 0;
1000 ret[i].flag = NULL;
1001 ret[i].val = 0;
1002
1003 return ret;
1004}
1005
1006// Create 'optstring' argument to getopt_long.
1007static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
1008 std::stringstream ss;
1009 for (const auto& e : options) {
1010 if (e.shortOption != '\0') {
1011 ss << e.shortOption;
1012 }
1013 }
1014 return ss.str();
1015}
1016
Yifan Honga8bedc62017-09-08 18:00:31 -07001017Status ListCommand::parseArgs(const Arg &arg) {
Nirav Atrecce988d2018-05-16 11:14:46 -07001018 mListTypes.clear();
Yifan Hong443df792017-05-09 18:49:45 -07001019
Yifan Honga6b93f02017-09-13 16:53:37 -07001020 if (mOptions.empty()) {
1021 registerAllOptions();
1022 }
1023 int longOptFlag;
1024 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
1025 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001026
Yifan Honga8bedc62017-09-08 18:00:31 -07001027 // suppress output to std::err for unknown options
1028 opterr = 0;
1029
Yifan Hong443df792017-05-09 18:49:45 -07001030 int optionIndex;
1031 int c;
1032 // Lshal::parseArgs has set optind to the next option to parse
1033 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -07001034 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -07001035 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -07001036 if (c == -1) {
1037 break;
1038 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001039 const RegisteredOption* found = nullptr;
1040 if (c == 0) {
1041 // see long option
1042 for (const auto& e : mOptions) {
1043 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -07001044 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001045 } else {
1046 // see short option
1047 for (const auto& e : mOptions) {
1048 if (c == e.shortOption) found = &e;
1049 }
Yifan Hong443df792017-05-09 18:49:45 -07001050 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001051
1052 if (found == nullptr) {
1053 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -07001054 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -07001055 return USAGE;
1056 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001057
1058 Status status = found->op(this, optarg);
1059 if (status != OK) {
1060 return status;
1061 }
Yifan Hong443df792017-05-09 18:49:45 -07001062 }
1063 if (optind < arg.argc) {
1064 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -07001065 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001066 return USAGE;
1067 }
1068
1069 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -07001070 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -07001071 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -07001072 }
1073
Yifan Honga6b93f02017-09-13 16:53:37 -07001074 if (mSelectedColumns.empty()) {
Yifan Hongfee209d2017-09-14 18:23:38 -07001075 mSelectedColumns = {TableColumnType::RELEASED,
1076 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -07001077 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -07001078 }
Yifan Hongd4a77e82017-09-06 19:40:24 -07001079
Yifan Honga6b93f02017-09-13 16:53:37 -07001080 if (mEnableCmdlines) {
1081 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
1082 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
1083 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001084 }
Yifan Honga6b93f02017-09-13 16:53:37 -07001085 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
1086 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -07001087 }
1088 }
1089 }
1090
Nirav Atrecce988d2018-05-16 11:14:46 -07001091 // By default, list all HAL types
1092 if (mListTypes.empty()) {
1093 mListTypes = {HalType::BINDERIZED_SERVICES, HalType::PASSTHROUGH_CLIENTS,
1094 HalType::PASSTHROUGH_LIBRARIES};
1095 }
Yifan Hong13ba0a92018-06-25 16:15:56 -07001096 initFetchTypes();
Nirav Atrecce988d2018-05-16 11:14:46 -07001097
Yifan Honga6b93f02017-09-13 16:53:37 -07001098 forEachTable([this] (Table& table) {
1099 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -07001100 });
1101
Yifan Hong443df792017-05-09 18:49:45 -07001102 return OK;
1103}
1104
Yifan Honga8bedc62017-09-08 18:00:31 -07001105Status ListCommand::main(const Arg &arg) {
1106 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -07001107 if (status != OK) {
1108 return status;
1109 }
1110 status = fetch();
1111 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -07001112 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -07001113 return status;
1114}
1115
Yifan Honga6b93f02017-09-13 16:53:37 -07001116const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
1117 static const std::string empty{};
1118 static const std::string optional{"[=<arg>]"};
1119 static const std::string required{"=<arg>"};
1120
1121 if (hasArg == optional_argument) {
1122 return optional;
1123 }
1124 if (hasArg == required_argument) {
1125 return required;
1126 }
1127 return empty;
1128}
1129
Yifan Honga8bedc62017-09-08 18:00:31 -07001130void ListCommand::usage() const {
1131
Yifan Honga6b93f02017-09-13 16:53:37 -07001132 err() << "list:" << std::endl
1133 << " lshal" << std::endl
1134 << " lshal list" << std::endl
Yifan Hongaa864572018-06-26 13:27:29 -07001135 << " List all hals with default ordering and columns (`lshal list -liepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -07001136 << " lshal list [-h|--help]" << std::endl
1137 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
1138 << " lshal [list] [OPTIONS...]" << std::endl;
1139 for (const auto& e : mOptions) {
1140 if (e.help.empty()) {
1141 continue;
1142 }
1143 err() << " ";
1144 if (e.shortOption != '\0')
1145 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
1146 if (e.shortOption != '\0' && !e.longOption.empty())
1147 err() << ", ";
1148 if (!e.longOption.empty())
1149 err() << "--" << e.longOption << e.getHelpMessageForArgument();
1150 err() << ": ";
Nirav Atrecce988d2018-05-16 11:14:46 -07001151 std::vector<std::string> lines = split(e.help, '\n');
Yifan Honga6b93f02017-09-13 16:53:37 -07001152 for (const auto& line : lines) {
1153 if (&line != &lines.front())
1154 err() << " ";
1155 err() << line << std::endl;
1156 }
1157 }
Yifan Honga8bedc62017-09-08 18:00:31 -07001158}
1159
Yifan Hong443df792017-05-09 18:49:45 -07001160} // namespace lshal
1161} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -07001162