blob: c7a41a3ba10efe2482af87f87db31209a1ffedb3 [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
21#include <fstream>
22#include <iomanip>
23#include <iostream>
24#include <map>
25#include <sstream>
26#include <regex>
27
28#include <android-base/parseint.h>
29#include <android/hidl/manager/1.0/IServiceManager.h>
Yifan Hong443df792017-05-09 18:49:45 -070030#include <hidl-util/FQName.h>
31#include <private/android_filesystem_config.h>
32#include <sys/stat.h>
33#include <vintf/HalManifest.h>
34#include <vintf/parse_xml.h>
35
36#include "Lshal.h"
37#include "PipeRelay.h"
38#include "Timeout.h"
39#include "utils.h"
40
41using ::android::hardware::hidl_string;
42using ::android::hidl::manager::V1_0::IServiceManager;
43
44namespace android {
45namespace lshal {
46
Yifan Hong76ac14a2017-09-08 14:59:04 -070047NullableOStream<std::ostream> ListCommand::out() const {
48 return mLshal.out();
49}
50
51NullableOStream<std::ostream> ListCommand::err() const {
52 return mLshal.err();
Yifan Hong443df792017-05-09 18:49:45 -070053}
54
Yifan Hong795b6ec2017-09-13 11:25:28 -070055std::string ListCommand::GetName() {
56 return "list";
57}
58std::string ListCommand::getSimpleDescription() const {
59 return "List HALs.";
60}
61
Yifan Hong8bf73162017-09-07 18:06:13 -070062std::string ListCommand::parseCmdline(pid_t pid) const {
Yifan Hong443df792017-05-09 18:49:45 -070063 std::ifstream ifs("/proc/" + std::to_string(pid) + "/cmdline");
64 std::string cmdline;
65 if (!ifs.is_open()) {
66 return "";
67 }
68 ifs >> cmdline;
69 return cmdline;
70}
71
72const std::string &ListCommand::getCmdline(pid_t pid) {
73 auto pair = mCmdlines.find(pid);
74 if (pair != mCmdlines.end()) {
75 return pair->second;
76 }
Yifan Hong8bf73162017-09-07 18:06:13 -070077 mCmdlines[pid] = parseCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -070078 return mCmdlines[pid];
79}
80
81void ListCommand::removeDeadProcesses(Pids *pids) {
82 static const pid_t myPid = getpid();
Yifan Hong61fb7bc2017-05-12 16:33:57 -070083 pids->erase(std::remove_if(pids->begin(), pids->end(), [this](auto pid) {
Yifan Hong443df792017-05-09 18:49:45 -070084 return pid == myPid || this->getCmdline(pid).empty();
Yifan Hong61fb7bc2017-05-12 16:33:57 -070085 }), pids->end());
Yifan Hong443df792017-05-09 18:49:45 -070086}
87
Steven Morelandd8e20192017-05-24 11:23:08 -070088bool scanBinderContext(pid_t pid,
89 const std::string &contextName,
90 std::function<void(const std::string&)> eachLine) {
91 std::ifstream ifs("/d/binder/proc/" + std::to_string(pid));
Yifan Hong443df792017-05-09 18:49:45 -070092 if (!ifs.is_open()) {
93 return false;
94 }
95
Steven Morelandd8e20192017-05-24 11:23:08 -070096 static const std::regex kContextLine("^context (\\w+)$");
Yifan Hong443df792017-05-09 18:49:45 -070097
Steven Morelandd8e20192017-05-24 11:23:08 -070098 bool isDesiredContext = false;
Yifan Hong443df792017-05-09 18:49:45 -070099 std::string line;
100 std::smatch match;
101 while(getline(ifs, line)) {
Steven Morelandd8e20192017-05-24 11:23:08 -0700102 if (std::regex_search(line, match, kContextLine)) {
103 isDesiredContext = match.str(1) == contextName;
Yifan Hong443df792017-05-09 18:49:45 -0700104 continue;
105 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700106
107 if (!isDesiredContext) {
Yifan Hong443df792017-05-09 18:49:45 -0700108 continue;
109 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700110
111 eachLine(line);
Yifan Hong443df792017-05-09 18:49:45 -0700112 }
113 return true;
114}
115
Steven Morelandd8e20192017-05-24 11:23:08 -0700116bool ListCommand::getPidInfo(
117 pid_t serverPid, PidInfo *pidInfo) const {
118 static const std::regex kReferencePrefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
119 static const std::regex kThreadPrefix("^\\s*thread \\d+:\\s+l\\s+(\\d)(\\d)");
120
121 std::smatch match;
122 return scanBinderContext(serverPid, "hwbinder", [&](const std::string& line) {
123 if (std::regex_search(line, match, kReferencePrefix)) {
124 const std::string &ptrString = "0x" + match.str(2); // use number after c
125 uint64_t ptr;
126 if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
127 // Should not reach here, but just be tolerant.
Yifan Hong76ac14a2017-09-08 14:59:04 -0700128 err() << "Could not parse number " << ptrString << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700129 return;
130 }
131 const std::string proc = " proc ";
132 auto pos = line.rfind(proc);
133 if (pos != std::string::npos) {
134 for (const std::string &pidStr : split(line.substr(pos + proc.size()), ' ')) {
135 int32_t pid;
136 if (!::android::base::ParseInt(pidStr, &pid)) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700137 err() << "Could not parse number " << pidStr << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700138 return;
139 }
140 pidInfo->refPids[ptr].push_back(pid);
141 }
142 }
143
144 return;
145 }
146
147 if (std::regex_search(line, match, kThreadPrefix)) {
148 // "1" is waiting in binder driver
149 // "2" is poll. It's impossible to tell if these are in use.
150 // and HIDL default code doesn't use it.
151 bool isInUse = match.str(1) != "1";
152 // "0" is a thread that has called into binder
153 // "1" is looper thread
154 // "2" is main looper thread
155 bool isHwbinderThread = match.str(2) != "0";
156
157 if (!isHwbinderThread) {
158 return;
159 }
160
161 if (isInUse) {
162 pidInfo->threadUsage++;
163 }
164
165 pidInfo->threadCount++;
166 return;
167 }
168
169 // not reference or thread line
170 return;
171 });
172}
173
Yifan Hong443df792017-05-09 18:49:45 -0700174// Must process hwbinder services first, then passthrough services.
175void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
176 f(mServicesTable);
177 f(mPassthroughRefTable);
178 f(mImplementationsTable);
179}
180void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
181 f(mServicesTable);
182 f(mPassthroughRefTable);
183 f(mImplementationsTable);
184}
185
186void ListCommand::postprocess() {
187 forEachTable([this](Table &table) {
188 if (mSortColumn) {
189 std::sort(table.begin(), table.end(), mSortColumn);
190 }
191 for (TableEntry &entry : table) {
192 entry.serverCmdline = getCmdline(entry.serverPid);
193 removeDeadProcesses(&entry.clientPids);
194 for (auto pid : entry.clientPids) {
195 entry.clientCmdlines.push_back(this->getCmdline(pid));
196 }
197 }
198 });
199 // use a double for loop here because lshal doesn't care about efficiency.
200 for (TableEntry &packageEntry : mImplementationsTable) {
201 std::string packageName = packageEntry.interfaceName;
202 FQName fqPackageName{packageName.substr(0, packageName.find("::"))};
203 if (!fqPackageName.isValid()) {
204 continue;
205 }
206 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
207 if (interfaceEntry.arch != ARCH_UNKNOWN) {
208 continue;
209 }
210 FQName interfaceName{splitFirst(interfaceEntry.interfaceName, '/').first};
211 if (!interfaceName.isValid()) {
212 continue;
213 }
214 if (interfaceName.getPackageAndVersion() == fqPackageName) {
215 interfaceEntry.arch = packageEntry.arch;
216 }
217 }
218 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700219
220 mServicesTable.setDescription(
221 "All binderized services (registered services through hwservicemanager)");
222 mPassthroughRefTable.setDescription(
223 "All interfaces that getService() has ever return as a passthrough interface;\n"
224 "PIDs / processes shown below might be inaccurate because the process\n"
225 "might have relinquished the interface or might have died.\n"
226 "The Server / Server CMD column can be ignored.\n"
227 "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
228 "the library and successfully fetched the passthrough implementation.");
229 mImplementationsTable.setDescription(
230 "All available passthrough implementations (all -impl.so files)");
Yifan Hong443df792017-05-09 18:49:45 -0700231}
232
Yifan Hong77c87822017-06-19 15:47:39 -0700233static inline bool findAndBumpVersion(vintf::ManifestHal* hal, const vintf::Version& version) {
234 for (vintf::Version& v : hal->versions) {
235 if (v.majorVer == version.majorVer) {
236 v.minorVer = std::max(v.minorVer, version.minorVer);
237 return true;
238 }
239 }
240 return false;
241}
242
Yifan Hongca3b6602017-09-07 16:44:27 -0700243void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700244 using vintf::operator|=;
Yifan Hongca3b6602017-09-07 16:44:27 -0700245 out << "<!-- " << std::endl
Yifan Hong443df792017-05-09 18:49:45 -0700246 << " This is a skeleton device manifest. Notes: " << std::endl
247 << " 1. android.hidl.*, android.frameworks.*, android.system.* are not included." << std::endl
248 << " 2. If a HAL is supported in both hwbinder and passthrough transport, " << std::endl
249 << " only hwbinder is shown." << std::endl
250 << " 3. It is likely that HALs in passthrough transport does not have" << std::endl
251 << " <interface> declared; users will have to write them by hand." << std::endl
Yifan Hong77c87822017-06-19 15:47:39 -0700252 << " 4. A HAL with lower minor version can be overridden by a HAL with" << std::endl
253 << " higher minor version if they have the same name and major version." << std::endl
254 << " 5. sepolicy version is set to 0.0. It is recommended that the entry" << std::endl
Yifan Hong443df792017-05-09 18:49:45 -0700255 << " is removed from the manifest file and written by assemble_vintf" << std::endl
256 << " at build time." << std::endl
257 << "-->" << std::endl;
258
259 vintf::HalManifest manifest;
260 forEachTable([this, &manifest] (const Table &table) {
261 for (const TableEntry &entry : table) {
262
263 std::string fqInstanceName = entry.interfaceName;
264
265 if (&table == &mImplementationsTable) {
266 // Quick hack to work around *'s
267 replaceAll(&fqInstanceName, '*', 'D');
268 }
269 auto splittedFqInstanceName = splitFirst(fqInstanceName, '/');
270 FQName fqName(splittedFqInstanceName.first);
271 if (!fqName.isValid()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700272 err() << "Warning: '" << splittedFqInstanceName.first
Yifan Hong443df792017-05-09 18:49:45 -0700273 << "' is not a valid FQName." << std::endl;
274 continue;
275 }
276 // Strip out system libs.
277 if (fqName.inPackage("android.hidl") ||
278 fqName.inPackage("android.frameworks") ||
279 fqName.inPackage("android.system")) {
280 continue;
281 }
282 std::string interfaceName =
283 &table == &mImplementationsTable ? "" : fqName.name();
284 std::string instanceName =
285 &table == &mImplementationsTable ? "" : splittedFqInstanceName.second;
286
287 vintf::Version version{fqName.getPackageMajorVersion(),
288 fqName.getPackageMinorVersion()};
289 vintf::Transport transport;
290 vintf::Arch arch;
291 if (entry.transport == "hwbinder") {
292 transport = vintf::Transport::HWBINDER;
293 arch = vintf::Arch::ARCH_EMPTY;
294 } else if (entry.transport == "passthrough") {
295 transport = vintf::Transport::PASSTHROUGH;
296 switch (entry.arch) {
297 case lshal::ARCH32:
298 arch = vintf::Arch::ARCH_32; break;
299 case lshal::ARCH64:
300 arch = vintf::Arch::ARCH_64; break;
301 case lshal::ARCH_BOTH:
302 arch = vintf::Arch::ARCH_32_64; break;
303 case lshal::ARCH_UNKNOWN: // fallthrough
304 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700305 err() << "Warning: '" << fqName.package()
Yifan Hong443df792017-05-09 18:49:45 -0700306 << "' doesn't have bitness info, assuming 32+64." << std::endl;
307 arch = vintf::Arch::ARCH_32_64;
308 }
309 } else {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700310 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700311 continue;
312 }
313
314 bool done = false;
315 for (vintf::ManifestHal *hal : manifest.getHals(fqName.package())) {
316 if (hal->transport() != transport) {
317 if (transport != vintf::Transport::PASSTHROUGH) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700318 err() << "Fatal: should not reach here. Generated result may be wrong for '"
Yifan Hong236301c2017-06-19 12:27:08 -0700319 << hal->name << "'."
Yifan Hong443df792017-05-09 18:49:45 -0700320 << std::endl;
321 }
322 done = true;
323 break;
324 }
Yifan Hong77c87822017-06-19 15:47:39 -0700325 if (findAndBumpVersion(hal, version)) {
Yifan Hong443df792017-05-09 18:49:45 -0700326 if (&table != &mImplementationsTable) {
327 hal->interfaces[interfaceName].name = interfaceName;
328 hal->interfaces[interfaceName].instances.insert(instanceName);
329 }
Yifan Hong236301c2017-06-19 12:27:08 -0700330 hal->transportArch.arch |= arch;
Yifan Hong443df792017-05-09 18:49:45 -0700331 done = true;
332 break;
333 }
334 }
335 if (done) {
336 continue; // to next TableEntry
337 }
338 decltype(vintf::ManifestHal::interfaces) interfaces;
339 if (&table != &mImplementationsTable) {
340 interfaces[interfaceName].name = interfaceName;
341 interfaces[interfaceName].instances.insert(instanceName);
342 }
343 if (!manifest.add(vintf::ManifestHal{
344 .format = vintf::HalFormat::HIDL,
345 .name = fqName.package(),
346 .versions = {version},
347 .transportArch = {transport, arch},
348 .interfaces = interfaces})) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700349 err() << "Warning: cannot add hal '" << fqInstanceName << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700350 }
351 }
352 });
Yifan Hongca3b6602017-09-07 16:44:27 -0700353 out << vintf::gHalManifestConverter(manifest);
Yifan Hong443df792017-05-09 18:49:45 -0700354}
355
Yifan Hong443df792017-05-09 18:49:45 -0700356static Architecture fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
357 switch (a) {
358 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
359 return ARCH64;
360 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
361 return ARCH32;
362 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
363 default:
364 return ARCH_UNKNOWN;
365 }
366}
367
Yifan Hongca3b6602017-09-07 16:44:27 -0700368void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700369 if (mNeat) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700370 MergedTable({&mServicesTable, &mPassthroughRefTable, &mImplementationsTable})
Yifan Hongca3b6602017-09-07 16:44:27 -0700371 .createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700372 return;
373 }
374
Yifan Hongca3b6602017-09-07 16:44:27 -0700375 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700376
Yifan Hongd4a77e82017-09-06 19:40:24 -0700377 // We're only interested in dumping debug info for already
378 // instantiated services. There's little value in dumping the
379 // debug info for a service we create on the fly, so we only operate
380 // on the "mServicesTable".
381 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
382 if (mEmitDebugInfo && &table == &mServicesTable) {
383 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700384 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700385 auto pair = splitFirst(iName, '/');
Yifan Hongca3b6602017-09-07 16:44:27 -0700386 mLshal.emitDebugInfo(pair.first, pair.second, {}, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700387 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700388 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700389 };
Yifan Hong443df792017-05-09 18:49:45 -0700390 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700391 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
392 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700393 });
Yifan Hong443df792017-05-09 18:49:45 -0700394}
395
Yifan Hongca3b6602017-09-07 16:44:27 -0700396Status ListCommand::dump() {
397 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
398
399 if (mFileOutputPath.empty()) {
400 (*this.*dump)(out());
401 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700402 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700403
404 std::ofstream fileOutput(mFileOutputPath);
405 if (!fileOutput.is_open()) {
406 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
407 return IO_ERROR;
408 }
409 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
410
411 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
412
413 fileOutput.flush();
414 fileOutput.close();
415 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700416}
417
418void ListCommand::putEntry(TableEntrySource source, TableEntry &&entry) {
419 Table *table = nullptr;
420 switch (source) {
421 case HWSERVICEMANAGER_LIST :
422 table = &mServicesTable; break;
423 case PTSERVICEMANAGER_REG_CLIENT :
424 table = &mPassthroughRefTable; break;
425 case LIST_DLLIB :
426 table = &mImplementationsTable; break;
427 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700428 err() << "Error: Unknown source of entry " << source << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700429 }
430 if (table) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700431 table->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700432 }
433}
434
435Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
436 using namespace ::android::hardware;
437 using namespace ::android::hidl::manager::V1_0;
438 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700439 using std::literals::chrono_literals::operator""s;
440 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700441 std::map<std::string, TableEntry> entries;
442 for (const auto &info : infos) {
443 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
444 std::string{info.instanceName.c_str()};
445 entries.emplace(interfaceName, TableEntry{
446 .interfaceName = interfaceName,
447 .transport = "passthrough",
448 .serverPid = NO_PID,
449 .serverObjectAddress = NO_PTR,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700450 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700451 .arch = ARCH_UNKNOWN
452 }).first->second.arch |= fromBaseArchitecture(info.arch);
453 }
454 for (auto &&pair : entries) {
455 putEntry(LIST_DLLIB, std::move(pair.second));
456 }
457 });
458 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700459 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700460 << ret.description() << std::endl;
461 return DUMP_ALL_LIBS_ERROR;
462 }
463 return OK;
464}
465
466Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
467 using namespace ::android::hardware;
468 using namespace ::android::hardware::details;
469 using namespace ::android::hidl::manager::V1_0;
470 using namespace ::android::hidl::base::V1_0;
471 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
472 for (const auto &info : infos) {
473 if (info.clientPids.size() <= 0) {
474 continue;
475 }
476 putEntry(PTSERVICEMANAGER_REG_CLIENT, {
477 .interfaceName =
478 std::string{info.interfaceName.c_str()} + "/" +
479 std::string{info.instanceName.c_str()},
480 .transport = "passthrough",
481 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
482 .serverObjectAddress = NO_PTR,
483 .clientPids = info.clientPids,
484 .arch = fromBaseArchitecture(info.arch)
485 });
486 }
487 });
488 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700489 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700490 << ret.description() << std::endl;
491 return DUMP_PASSTHROUGH_ERROR;
492 }
493 return OK;
494}
495
496Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
497 using namespace ::std;
498 using namespace ::android::hardware;
499 using namespace ::android::hidl::manager::V1_0;
500 using namespace ::android::hidl::base::V1_0;
501 const std::string mode = "hwbinder";
502
503 hidl_vec<hidl_string> fqInstanceNames;
504 // copying out for timeoutIPC
505 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
506 fqInstanceNames = names;
507 });
508 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700509 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700510 << listRet.description() << std::endl;
511 return DUMP_BINDERIZED_ERROR;
512 }
513
514 Status status = OK;
515 // server pid, .ptr value of binder object, child pids
516 std::map<std::string, DebugInfo> allDebugInfos;
Steven Morelandd8e20192017-05-24 11:23:08 -0700517 std::map<pid_t, PidInfo> allPids;
Yifan Hong443df792017-05-09 18:49:45 -0700518 for (const auto &fqInstanceName : fqInstanceNames) {
519 const auto pair = splitFirst(fqInstanceName, '/');
520 const auto &serviceName = pair.first;
521 const auto &instanceName = pair.second;
522 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
523 if (!getRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700524 err() << "Warning: Skipping \"" << fqInstanceName << "\": "
Yifan Hong443df792017-05-09 18:49:45 -0700525 << "cannot be fetched from service manager:"
526 << getRet.description() << std::endl;
527 status |= DUMP_BINDERIZED_ERROR;
528 continue;
529 }
530 sp<IBase> service = getRet;
531 if (service == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700532 err() << "Warning: Skipping \"" << fqInstanceName << "\": "
Yifan Hong443df792017-05-09 18:49:45 -0700533 << "cannot be fetched from service manager (null)"
534 << std::endl;
535 status |= DUMP_BINDERIZED_ERROR;
536 continue;
537 }
538 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &debugInfo) {
539 allDebugInfos[fqInstanceName] = debugInfo;
540 if (debugInfo.pid >= 0) {
Steven Morelandd8e20192017-05-24 11:23:08 -0700541 allPids[static_cast<pid_t>(debugInfo.pid)] = PidInfo();
Yifan Hong443df792017-05-09 18:49:45 -0700542 }
543 });
544 if (!debugRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700545 err() << "Warning: Skipping \"" << fqInstanceName << "\": "
Yifan Hong443df792017-05-09 18:49:45 -0700546 << "debugging information cannot be retrieved:"
547 << debugRet.description() << std::endl;
548 status |= DUMP_BINDERIZED_ERROR;
549 }
550 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700551
Yifan Hong443df792017-05-09 18:49:45 -0700552 for (auto &pair : allPids) {
553 pid_t serverPid = pair.first;
Steven Morelandd8e20192017-05-24 11:23:08 -0700554 if (!getPidInfo(serverPid, &allPids[serverPid])) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700555 err() << "Warning: no information for PID " << serverPid
Yifan Hong443df792017-05-09 18:49:45 -0700556 << ", are you root?" << std::endl;
557 status |= DUMP_BINDERIZED_ERROR;
558 }
559 }
560 for (const auto &fqInstanceName : fqInstanceNames) {
561 auto it = allDebugInfos.find(fqInstanceName);
562 if (it == allDebugInfos.end()) {
563 putEntry(HWSERVICEMANAGER_LIST, {
564 .interfaceName = fqInstanceName,
565 .transport = mode,
566 .serverPid = NO_PID,
567 .serverObjectAddress = NO_PTR,
568 .clientPids = {},
Steven Morelandd8e20192017-05-24 11:23:08 -0700569 .threadUsage = 0,
570 .threadCount = 0,
Yifan Hong443df792017-05-09 18:49:45 -0700571 .arch = ARCH_UNKNOWN
572 });
573 continue;
574 }
575 const DebugInfo &info = it->second;
Steven Morelandd8e20192017-05-24 11:23:08 -0700576 bool writePidInfo = info.pid != NO_PID && info.ptr != NO_PTR;
577
Yifan Hong443df792017-05-09 18:49:45 -0700578 putEntry(HWSERVICEMANAGER_LIST, {
579 .interfaceName = fqInstanceName,
580 .transport = mode,
581 .serverPid = info.pid,
582 .serverObjectAddress = info.ptr,
Steven Morelandd8e20192017-05-24 11:23:08 -0700583 .clientPids = writePidInfo ? allPids[info.pid].refPids[info.ptr] : Pids{},
584 .threadUsage = writePidInfo ? allPids[info.pid].threadUsage : 0,
585 .threadCount = writePidInfo ? allPids[info.pid].threadCount : 0,
Yifan Hong443df792017-05-09 18:49:45 -0700586 .arch = fromBaseArchitecture(info.arch),
587 });
588 }
589 return status;
590}
591
592Status ListCommand::fetch() {
593 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700594 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700595 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700596 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700597 status |= NO_BINDERIZED_MANAGER;
598 } else {
599 status |= fetchBinderized(bManager);
600 // Passthrough PIDs are registered to the binderized manager as well.
601 status |= fetchPassthrough(bManager);
602 }
603
Yifan Hong9881df92017-05-10 14:33:05 -0700604 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700605 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700606 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700607 status |= NO_PASSTHROUGH_MANAGER;
608 } else {
609 status |= fetchAllLibraries(pManager);
610 }
611 return status;
612}
613
Yifan Honga8bedc62017-09-08 18:00:31 -0700614Status ListCommand::parseArgs(const Arg &arg) {
Yifan Hong443df792017-05-09 18:49:45 -0700615 static struct option longOptions[] = {
616 // long options with short alternatives
617 {"help", no_argument, 0, 'h' },
618 {"interface", no_argument, 0, 'i' },
619 {"transport", no_argument, 0, 't' },
620 {"arch", no_argument, 0, 'r' },
621 {"pid", no_argument, 0, 'p' },
622 {"address", no_argument, 0, 'a' },
623 {"clients", no_argument, 0, 'c' },
Steven Morelandd8e20192017-05-24 11:23:08 -0700624 {"threads", no_argument, 0, 'e' },
Yifan Hong443df792017-05-09 18:49:45 -0700625 {"cmdline", no_argument, 0, 'm' },
626 {"debug", optional_argument, 0, 'd' },
627
628 // long options without short alternatives
629 {"sort", required_argument, 0, 's' },
630 {"init-vintf",optional_argument, 0, 'v' },
Yifan Hong6da06912017-05-12 16:56:43 -0700631 {"neat", no_argument, 0, 'n' },
Yifan Hong443df792017-05-09 18:49:45 -0700632 { 0, 0, 0, 0 }
633 };
634
Yifan Hongd4a77e82017-09-06 19:40:24 -0700635 std::vector<TableColumnType> selectedColumns;
636 bool enableCmdlines = false;
637
Yifan Honga8bedc62017-09-08 18:00:31 -0700638 // suppress output to std::err for unknown options
639 opterr = 0;
640
Yifan Hong443df792017-05-09 18:49:45 -0700641 int optionIndex;
642 int c;
643 // Lshal::parseArgs has set optind to the next option to parse
644 for (;;) {
645 // using getopt_long in case we want to add other options in the future
646 c = getopt_long(arg.argc, arg.argv,
Steven Morelandd8e20192017-05-24 11:23:08 -0700647 "hitrpacmde", longOptions, &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700648 if (c == -1) {
649 break;
650 }
651 switch (c) {
652 case 's': {
653 if (strcmp(optarg, "interface") == 0 || strcmp(optarg, "i") == 0) {
654 mSortColumn = TableEntry::sortByInterfaceName;
655 } else if (strcmp(optarg, "pid") == 0 || strcmp(optarg, "p") == 0) {
656 mSortColumn = TableEntry::sortByServerPid;
657 } else {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700658 err() << "Unrecognized sorting column: " << optarg << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700659 return USAGE;
660 }
661 break;
662 }
663 case 'v': {
Yifan Hong443df792017-05-09 18:49:45 -0700664 mVintf = true;
Yifan Hongca3b6602017-09-07 16:44:27 -0700665 if (optarg) mFileOutputPath = optarg;
666 break;
Yifan Hong443df792017-05-09 18:49:45 -0700667 }
668 case 'i': {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700669 selectedColumns.push_back(TableColumnType::INTERFACE_NAME);
Yifan Hong443df792017-05-09 18:49:45 -0700670 break;
671 }
672 case 't': {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700673 selectedColumns.push_back(TableColumnType::TRANSPORT);
Yifan Hong443df792017-05-09 18:49:45 -0700674 break;
675 }
676 case 'r': {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700677 selectedColumns.push_back(TableColumnType::ARCH);
Yifan Hong443df792017-05-09 18:49:45 -0700678 break;
679 }
680 case 'p': {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700681 selectedColumns.push_back(TableColumnType::SERVER_PID);
Yifan Hong443df792017-05-09 18:49:45 -0700682 break;
683 }
684 case 'a': {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700685 selectedColumns.push_back(TableColumnType::SERVER_ADDR);
Yifan Hong443df792017-05-09 18:49:45 -0700686 break;
687 }
688 case 'c': {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700689 selectedColumns.push_back(TableColumnType::CLIENT_PIDS);
Yifan Hong443df792017-05-09 18:49:45 -0700690 break;
691 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700692 case 'e': {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700693 selectedColumns.push_back(TableColumnType::THREADS);
Steven Morelandd8e20192017-05-24 11:23:08 -0700694 break;
695 }
Yifan Hong443df792017-05-09 18:49:45 -0700696 case 'm': {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700697 enableCmdlines = true;
Yifan Hong443df792017-05-09 18:49:45 -0700698 break;
699 }
700 case 'd': {
701 mEmitDebugInfo = true;
Yifan Hongca3b6602017-09-07 16:44:27 -0700702 if (optarg) mFileOutputPath = optarg;
Yifan Hong443df792017-05-09 18:49:45 -0700703 break;
704 }
Yifan Hong6da06912017-05-12 16:56:43 -0700705 case 'n': {
706 mNeat = true;
707 break;
708 }
Yifan Honga8bedc62017-09-08 18:00:31 -0700709 case 'h': {
710 return USAGE;
711 }
Yifan Hong443df792017-05-09 18:49:45 -0700712 default: // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700713 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700714 return USAGE;
715 }
716 }
717 if (optind < arg.argc) {
718 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700719 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700720 return USAGE;
721 }
722
723 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700724 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700725 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700726 }
727
Yifan Hongd4a77e82017-09-06 19:40:24 -0700728 if (selectedColumns.empty()) {
729 selectedColumns = {TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -0700730 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -0700731 }
Yifan Hongd4a77e82017-09-06 19:40:24 -0700732
733 if (enableCmdlines) {
734 for (size_t i = 0; i < selectedColumns.size(); ++i) {
735 if (selectedColumns[i] == TableColumnType::SERVER_PID) {
736 selectedColumns[i] = TableColumnType::SERVER_CMD;
737 }
738 if (selectedColumns[i] == TableColumnType::CLIENT_PIDS) {
739 selectedColumns[i] = TableColumnType::CLIENT_CMDS;
740 }
741 }
742 }
743
744 forEachTable([&selectedColumns] (Table& table) {
745 table.setSelectedColumns(selectedColumns);
746 });
747
Yifan Hong443df792017-05-09 18:49:45 -0700748 return OK;
749}
750
Yifan Honga8bedc62017-09-08 18:00:31 -0700751Status ListCommand::main(const Arg &arg) {
752 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -0700753 if (status != OK) {
754 return status;
755 }
756 status = fetch();
757 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -0700758 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -0700759 return status;
760}
761
Yifan Honga8bedc62017-09-08 18:00:31 -0700762void ListCommand::usage() const {
763
764 static const std::string list =
765 "list:\n"
766 " lshal\n"
767 " lshal list\n"
768 " List all hals with default ordering and columns (`lshal list -iepc`)\n"
769 " lshal list [-h|--help]\n"
770 " -h, --help: Print help message for list (`lshal help list`)\n"
771 " lshal [list] [--interface|-i] [--transport|-t] [-r|--arch] [-e|--threads]\n"
772 " [--pid|-p] [--address|-a] [--clients|-c] [--cmdline|-m]\n"
773 " [--sort={interface|i|pid|p}] [--init-vintf[=<output file>]]\n"
774 " [--debug|-d[=<output file>]] [--neat]\n"
775 " -i, --interface: print the interface name column\n"
776 " -n, --instance: print the instance name column\n"
777 " -t, --transport: print the transport mode column\n"
778 " -r, --arch: print if the HAL is in 64-bit or 32-bit\n"
779 " -e, --threads: print currently used/available threads\n"
780 " (note, available threads created lazily)\n"
781 " -p, --pid: print the server PID, or server cmdline if -m is set\n"
782 " -a, --address: print the server object address column\n"
783 " -c, --clients: print the client PIDs, or client cmdlines if -m is set\n"
784 " -m, --cmdline: print cmdline instead of PIDs\n"
785 " -d[=<output file>], --debug[=<output file>]: emit debug info from \n"
786 " IBase::debug with empty options. Cannot be used with --neat.\n"
787 " --sort=i, --sort=interface: sort by interface name\n"
788 " --sort=p, --sort=pid: sort by server pid\n"
789 " --neat: output is machine parsable (no explanatory text)\n"
790 " Cannot be used with --debug.\n"
791 " --init-vintf[=<output file>]: form a skeleton HAL manifest to specified\n"
792 " file, or stdout if no file specified.\n";
793
794 err() << list;
795}
796
Yifan Hong443df792017-05-09 18:49:45 -0700797} // namespace lshal
798} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -0700799