blob: 8b59fb867d3b70aa931640c23ee3f67a611050d3 [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 Honga6b93f02017-09-13 16:53:37 -0700614void ListCommand::registerAllOptions() {
615 int v = mOptions.size();
616 // A list of acceptable command line options
617 // key: value returned by getopt_long
618 // long options with short alternatives
619 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
620 return USAGE;
621 }, ""});
622 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
623 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
624 return OK;
625 }, "print the instance name column"});
626 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
627 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
628 return OK;
629 }, "print the transport mode column"});
630 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
631 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
632 return OK;
633 }, "print the bitness column"});
634 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
635 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
636 return OK;
637 }, "print the server PID, or server cmdline if -m is set"});
638 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
639 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
640 return OK;
641 }, "print the server object address column"});
642 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
643 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
644 return OK;
645 }, "print the client PIDs, or client cmdlines if -m is set"});
646 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
647 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
648 return OK;
649 }, "print currently used/available threads\n(note, available threads created lazily)"});
650 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
651 thiz->mEnableCmdlines = true;
652 return OK;
653 }, "print cmdline instead of PIDs"});
654 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
655 thiz->mEmitDebugInfo = true;
656 if (arg) thiz->mFileOutputPath = arg;
657 return OK;
658 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
659 "Writes to specified file if 'arg' is provided, otherwise stdout."});
660
661 // long options without short alternatives
662 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
663 thiz->mVintf = true;
664 if (arg) thiz->mFileOutputPath = arg;
665 return OK;
666 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
667 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
668 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
669 thiz->mSortColumn = TableEntry::sortByInterfaceName;
670 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
671 thiz->mSortColumn = TableEntry::sortByServerPid;
672 } else {
673 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
674 return USAGE;
675 }
676 return OK;
677 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
678 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
679 thiz->mNeat = true;
680 return OK;
681 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
682}
683
684// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
685// the lifetime of "options" during the usage of the returned array.
686static std::unique_ptr<struct option[]> getLongOptions(
687 const ListCommand::RegisteredOptions& options,
688 int* longOptFlag) {
689 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
690 int i = 0;
691 for (const auto& e : options) {
692 ret[i].name = e.longOption.c_str();
693 ret[i].has_arg = e.hasArg;
694 ret[i].flag = longOptFlag;
695 ret[i].val = e.val;
696
697 i++;
698 }
699 // getopt_long last option has all zeros
700 ret[i].name = NULL;
701 ret[i].has_arg = 0;
702 ret[i].flag = NULL;
703 ret[i].val = 0;
704
705 return ret;
706}
707
708// Create 'optstring' argument to getopt_long.
709static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
710 std::stringstream ss;
711 for (const auto& e : options) {
712 if (e.shortOption != '\0') {
713 ss << e.shortOption;
714 }
715 }
716 return ss.str();
717}
718
Yifan Honga8bedc62017-09-08 18:00:31 -0700719Status ListCommand::parseArgs(const Arg &arg) {
Yifan Hong443df792017-05-09 18:49:45 -0700720
Yifan Honga6b93f02017-09-13 16:53:37 -0700721 if (mOptions.empty()) {
722 registerAllOptions();
723 }
724 int longOptFlag;
725 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
726 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700727
Yifan Honga8bedc62017-09-08 18:00:31 -0700728 // suppress output to std::err for unknown options
729 opterr = 0;
730
Yifan Hong443df792017-05-09 18:49:45 -0700731 int optionIndex;
732 int c;
733 // Lshal::parseArgs has set optind to the next option to parse
734 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700735 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700736 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700737 if (c == -1) {
738 break;
739 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700740 const RegisteredOption* found = nullptr;
741 if (c == 0) {
742 // see long option
743 for (const auto& e : mOptions) {
744 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700745 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700746 } else {
747 // see short option
748 for (const auto& e : mOptions) {
749 if (c == e.shortOption) found = &e;
750 }
Yifan Hong443df792017-05-09 18:49:45 -0700751 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700752
753 if (found == nullptr) {
754 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700755 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700756 return USAGE;
757 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700758
759 Status status = found->op(this, optarg);
760 if (status != OK) {
761 return status;
762 }
Yifan Hong443df792017-05-09 18:49:45 -0700763 }
764 if (optind < arg.argc) {
765 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700766 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700767 return USAGE;
768 }
769
770 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700771 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700772 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700773 }
774
Yifan Honga6b93f02017-09-13 16:53:37 -0700775 if (mSelectedColumns.empty()) {
776 mSelectedColumns = {TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -0700777 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -0700778 }
Yifan Hongd4a77e82017-09-06 19:40:24 -0700779
Yifan Honga6b93f02017-09-13 16:53:37 -0700780 if (mEnableCmdlines) {
781 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
782 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
783 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700784 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700785 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
786 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700787 }
788 }
789 }
790
Yifan Honga6b93f02017-09-13 16:53:37 -0700791 forEachTable([this] (Table& table) {
792 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700793 });
794
Yifan Hong443df792017-05-09 18:49:45 -0700795 return OK;
796}
797
Yifan Honga8bedc62017-09-08 18:00:31 -0700798Status ListCommand::main(const Arg &arg) {
799 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -0700800 if (status != OK) {
801 return status;
802 }
803 status = fetch();
804 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -0700805 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -0700806 return status;
807}
808
Yifan Honga6b93f02017-09-13 16:53:37 -0700809static std::vector<std::string> splitString(const std::string &s, char c) {
810 std::vector<std::string> components;
811
812 size_t startPos = 0;
813 size_t matchPos;
814 while ((matchPos = s.find(c, startPos)) != std::string::npos) {
815 components.push_back(s.substr(startPos, matchPos - startPos));
816 startPos = matchPos + 1;
817 }
818
819 if (startPos <= s.length()) {
820 components.push_back(s.substr(startPos));
821 }
822 return components;
823}
824
825const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
826 static const std::string empty{};
827 static const std::string optional{"[=<arg>]"};
828 static const std::string required{"=<arg>"};
829
830 if (hasArg == optional_argument) {
831 return optional;
832 }
833 if (hasArg == required_argument) {
834 return required;
835 }
836 return empty;
837}
838
Yifan Honga8bedc62017-09-08 18:00:31 -0700839void ListCommand::usage() const {
840
Yifan Honga6b93f02017-09-13 16:53:37 -0700841 err() << "list:" << std::endl
842 << " lshal" << std::endl
843 << " lshal list" << std::endl
844 << " List all hals with default ordering and columns (`lshal list -iepc`)" << std::endl
845 << " lshal list [-h|--help]" << std::endl
846 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
847 << " lshal [list] [OPTIONS...]" << std::endl;
848 for (const auto& e : mOptions) {
849 if (e.help.empty()) {
850 continue;
851 }
852 err() << " ";
853 if (e.shortOption != '\0')
854 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
855 if (e.shortOption != '\0' && !e.longOption.empty())
856 err() << ", ";
857 if (!e.longOption.empty())
858 err() << "--" << e.longOption << e.getHelpMessageForArgument();
859 err() << ": ";
860 std::vector<std::string> lines = splitString(e.help, '\n');
861 for (const auto& line : lines) {
862 if (&line != &lines.front())
863 err() << " ";
864 err() << line << std::endl;
865 }
866 }
Yifan Honga8bedc62017-09-08 18:00:31 -0700867}
868
Yifan Hong443df792017-05-09 18:49:45 -0700869} // namespace lshal
870} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -0700871