blob: 509353b1db393ee19aa8dc2f8a2ccc25bb6ff094 [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
Yifan Hong1243dde2017-09-14 17:49:30 -070088static bool scanBinderContext(pid_t pid,
Steven Morelandd8e20192017-05-24 11:23:08 -070089 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 Hong1243dde2017-09-14 17:49:30 -0700174const PidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
175 auto pair = mCachedPidInfos.insert({serverPid, PidInfo{}});
176 if (pair.second /* did insertion take place? */) {
177 if (!getPidInfo(serverPid, &pair.first->second)) {
178 return nullptr;
179 }
180 }
181 return &pair.first->second;
182}
183
Yifan Hong443df792017-05-09 18:49:45 -0700184// Must process hwbinder services first, then passthrough services.
185void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
186 f(mServicesTable);
187 f(mPassthroughRefTable);
188 f(mImplementationsTable);
189}
190void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
191 f(mServicesTable);
192 f(mPassthroughRefTable);
193 f(mImplementationsTable);
194}
195
196void ListCommand::postprocess() {
197 forEachTable([this](Table &table) {
198 if (mSortColumn) {
199 std::sort(table.begin(), table.end(), mSortColumn);
200 }
201 for (TableEntry &entry : table) {
202 entry.serverCmdline = getCmdline(entry.serverPid);
203 removeDeadProcesses(&entry.clientPids);
204 for (auto pid : entry.clientPids) {
205 entry.clientCmdlines.push_back(this->getCmdline(pid));
206 }
207 }
208 });
209 // use a double for loop here because lshal doesn't care about efficiency.
210 for (TableEntry &packageEntry : mImplementationsTable) {
211 std::string packageName = packageEntry.interfaceName;
212 FQName fqPackageName{packageName.substr(0, packageName.find("::"))};
213 if (!fqPackageName.isValid()) {
214 continue;
215 }
216 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
217 if (interfaceEntry.arch != ARCH_UNKNOWN) {
218 continue;
219 }
220 FQName interfaceName{splitFirst(interfaceEntry.interfaceName, '/').first};
221 if (!interfaceName.isValid()) {
222 continue;
223 }
224 if (interfaceName.getPackageAndVersion() == fqPackageName) {
225 interfaceEntry.arch = packageEntry.arch;
226 }
227 }
228 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700229
230 mServicesTable.setDescription(
231 "All binderized services (registered services through hwservicemanager)");
232 mPassthroughRefTable.setDescription(
233 "All interfaces that getService() has ever return as a passthrough interface;\n"
234 "PIDs / processes shown below might be inaccurate because the process\n"
235 "might have relinquished the interface or might have died.\n"
236 "The Server / Server CMD column can be ignored.\n"
237 "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
238 "the library and successfully fetched the passthrough implementation.");
239 mImplementationsTable.setDescription(
240 "All available passthrough implementations (all -impl.so files)");
Yifan Hong443df792017-05-09 18:49:45 -0700241}
242
Yifan Hong77c87822017-06-19 15:47:39 -0700243static inline bool findAndBumpVersion(vintf::ManifestHal* hal, const vintf::Version& version) {
244 for (vintf::Version& v : hal->versions) {
245 if (v.majorVer == version.majorVer) {
246 v.minorVer = std::max(v.minorVer, version.minorVer);
247 return true;
248 }
249 }
250 return false;
251}
252
Yifan Hongca3b6602017-09-07 16:44:27 -0700253void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700254 using vintf::operator|=;
Yifan Hongca3b6602017-09-07 16:44:27 -0700255 out << "<!-- " << std::endl
Yifan Hong443df792017-05-09 18:49:45 -0700256 << " This is a skeleton device manifest. Notes: " << std::endl
257 << " 1. android.hidl.*, android.frameworks.*, android.system.* are not included." << std::endl
258 << " 2. If a HAL is supported in both hwbinder and passthrough transport, " << std::endl
259 << " only hwbinder is shown." << std::endl
260 << " 3. It is likely that HALs in passthrough transport does not have" << std::endl
261 << " <interface> declared; users will have to write them by hand." << std::endl
Yifan Hong77c87822017-06-19 15:47:39 -0700262 << " 4. A HAL with lower minor version can be overridden by a HAL with" << std::endl
263 << " higher minor version if they have the same name and major version." << std::endl
264 << " 5. sepolicy version is set to 0.0. It is recommended that the entry" << std::endl
Yifan Hong443df792017-05-09 18:49:45 -0700265 << " is removed from the manifest file and written by assemble_vintf" << std::endl
266 << " at build time." << std::endl
267 << "-->" << std::endl;
268
269 vintf::HalManifest manifest;
270 forEachTable([this, &manifest] (const Table &table) {
271 for (const TableEntry &entry : table) {
272
273 std::string fqInstanceName = entry.interfaceName;
274
275 if (&table == &mImplementationsTable) {
276 // Quick hack to work around *'s
277 replaceAll(&fqInstanceName, '*', 'D');
278 }
279 auto splittedFqInstanceName = splitFirst(fqInstanceName, '/');
280 FQName fqName(splittedFqInstanceName.first);
281 if (!fqName.isValid()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700282 err() << "Warning: '" << splittedFqInstanceName.first
Yifan Hong443df792017-05-09 18:49:45 -0700283 << "' is not a valid FQName." << std::endl;
284 continue;
285 }
286 // Strip out system libs.
287 if (fqName.inPackage("android.hidl") ||
288 fqName.inPackage("android.frameworks") ||
289 fqName.inPackage("android.system")) {
290 continue;
291 }
292 std::string interfaceName =
293 &table == &mImplementationsTable ? "" : fqName.name();
294 std::string instanceName =
295 &table == &mImplementationsTable ? "" : splittedFqInstanceName.second;
296
297 vintf::Version version{fqName.getPackageMajorVersion(),
298 fqName.getPackageMinorVersion()};
299 vintf::Transport transport;
300 vintf::Arch arch;
301 if (entry.transport == "hwbinder") {
302 transport = vintf::Transport::HWBINDER;
303 arch = vintf::Arch::ARCH_EMPTY;
304 } else if (entry.transport == "passthrough") {
305 transport = vintf::Transport::PASSTHROUGH;
306 switch (entry.arch) {
307 case lshal::ARCH32:
308 arch = vintf::Arch::ARCH_32; break;
309 case lshal::ARCH64:
310 arch = vintf::Arch::ARCH_64; break;
311 case lshal::ARCH_BOTH:
312 arch = vintf::Arch::ARCH_32_64; break;
313 case lshal::ARCH_UNKNOWN: // fallthrough
314 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700315 err() << "Warning: '" << fqName.package()
Yifan Hong443df792017-05-09 18:49:45 -0700316 << "' doesn't have bitness info, assuming 32+64." << std::endl;
317 arch = vintf::Arch::ARCH_32_64;
318 }
319 } else {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700320 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700321 continue;
322 }
323
324 bool done = false;
325 for (vintf::ManifestHal *hal : manifest.getHals(fqName.package())) {
326 if (hal->transport() != transport) {
327 if (transport != vintf::Transport::PASSTHROUGH) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700328 err() << "Fatal: should not reach here. Generated result may be wrong for '"
Yifan Hong236301c2017-06-19 12:27:08 -0700329 << hal->name << "'."
Yifan Hong443df792017-05-09 18:49:45 -0700330 << std::endl;
331 }
332 done = true;
333 break;
334 }
Yifan Hong77c87822017-06-19 15:47:39 -0700335 if (findAndBumpVersion(hal, version)) {
Yifan Hong443df792017-05-09 18:49:45 -0700336 if (&table != &mImplementationsTable) {
337 hal->interfaces[interfaceName].name = interfaceName;
338 hal->interfaces[interfaceName].instances.insert(instanceName);
339 }
Yifan Hong236301c2017-06-19 12:27:08 -0700340 hal->transportArch.arch |= arch;
Yifan Hong443df792017-05-09 18:49:45 -0700341 done = true;
342 break;
343 }
344 }
345 if (done) {
346 continue; // to next TableEntry
347 }
348 decltype(vintf::ManifestHal::interfaces) interfaces;
349 if (&table != &mImplementationsTable) {
350 interfaces[interfaceName].name = interfaceName;
351 interfaces[interfaceName].instances.insert(instanceName);
352 }
353 if (!manifest.add(vintf::ManifestHal{
354 .format = vintf::HalFormat::HIDL,
355 .name = fqName.package(),
356 .versions = {version},
357 .transportArch = {transport, arch},
358 .interfaces = interfaces})) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700359 err() << "Warning: cannot add hal '" << fqInstanceName << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700360 }
361 }
362 });
Yifan Hongca3b6602017-09-07 16:44:27 -0700363 out << vintf::gHalManifestConverter(manifest);
Yifan Hong443df792017-05-09 18:49:45 -0700364}
365
Yifan Hong443df792017-05-09 18:49:45 -0700366static Architecture fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
367 switch (a) {
368 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
369 return ARCH64;
370 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
371 return ARCH32;
372 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
373 default:
374 return ARCH_UNKNOWN;
375 }
376}
377
Yifan Hongca3b6602017-09-07 16:44:27 -0700378void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700379 if (mNeat) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700380 MergedTable({&mServicesTable, &mPassthroughRefTable, &mImplementationsTable})
Yifan Hongca3b6602017-09-07 16:44:27 -0700381 .createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700382 return;
383 }
384
Yifan Hongca3b6602017-09-07 16:44:27 -0700385 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700386
Yifan Hongd4a77e82017-09-06 19:40:24 -0700387 // We're only interested in dumping debug info for already
388 // instantiated services. There's little value in dumping the
389 // debug info for a service we create on the fly, so we only operate
390 // on the "mServicesTable".
391 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
392 if (mEmitDebugInfo && &table == &mServicesTable) {
393 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700394 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700395 auto pair = splitFirst(iName, '/');
Yifan Hongca3b6602017-09-07 16:44:27 -0700396 mLshal.emitDebugInfo(pair.first, pair.second, {}, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700397 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700398 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700399 };
Yifan Hong443df792017-05-09 18:49:45 -0700400 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700401 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
402 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700403 });
Yifan Hong443df792017-05-09 18:49:45 -0700404}
405
Yifan Hongca3b6602017-09-07 16:44:27 -0700406Status ListCommand::dump() {
407 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
408
409 if (mFileOutputPath.empty()) {
410 (*this.*dump)(out());
411 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700412 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700413
414 std::ofstream fileOutput(mFileOutputPath);
415 if (!fileOutput.is_open()) {
416 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
417 return IO_ERROR;
418 }
419 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
420
421 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
422
423 fileOutput.flush();
424 fileOutput.close();
425 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700426}
427
428void ListCommand::putEntry(TableEntrySource source, TableEntry &&entry) {
429 Table *table = nullptr;
430 switch (source) {
431 case HWSERVICEMANAGER_LIST :
432 table = &mServicesTable; break;
433 case PTSERVICEMANAGER_REG_CLIENT :
434 table = &mPassthroughRefTable; break;
435 case LIST_DLLIB :
436 table = &mImplementationsTable; break;
437 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700438 err() << "Error: Unknown source of entry " << source << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700439 }
440 if (table) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700441 table->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700442 }
443}
444
445Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
446 using namespace ::android::hardware;
447 using namespace ::android::hidl::manager::V1_0;
448 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700449 using std::literals::chrono_literals::operator""s;
450 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700451 std::map<std::string, TableEntry> entries;
452 for (const auto &info : infos) {
453 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
454 std::string{info.instanceName.c_str()};
455 entries.emplace(interfaceName, TableEntry{
456 .interfaceName = interfaceName,
457 .transport = "passthrough",
458 .serverPid = NO_PID,
459 .serverObjectAddress = NO_PTR,
Yifan Hongf2d557b2017-05-24 19:45:02 -0700460 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700461 .arch = ARCH_UNKNOWN
462 }).first->second.arch |= fromBaseArchitecture(info.arch);
463 }
464 for (auto &&pair : entries) {
465 putEntry(LIST_DLLIB, std::move(pair.second));
466 }
467 });
468 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700469 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700470 << ret.description() << std::endl;
471 return DUMP_ALL_LIBS_ERROR;
472 }
473 return OK;
474}
475
476Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
477 using namespace ::android::hardware;
478 using namespace ::android::hardware::details;
479 using namespace ::android::hidl::manager::V1_0;
480 using namespace ::android::hidl::base::V1_0;
481 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
482 for (const auto &info : infos) {
483 if (info.clientPids.size() <= 0) {
484 continue;
485 }
486 putEntry(PTSERVICEMANAGER_REG_CLIENT, {
487 .interfaceName =
488 std::string{info.interfaceName.c_str()} + "/" +
489 std::string{info.instanceName.c_str()},
490 .transport = "passthrough",
491 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
492 .serverObjectAddress = NO_PTR,
493 .clientPids = info.clientPids,
494 .arch = fromBaseArchitecture(info.arch)
495 });
496 }
497 });
498 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700499 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700500 << ret.description() << std::endl;
501 return DUMP_PASSTHROUGH_ERROR;
502 }
503 return OK;
504}
505
506Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
507 using namespace ::std;
508 using namespace ::android::hardware;
509 using namespace ::android::hidl::manager::V1_0;
510 using namespace ::android::hidl::base::V1_0;
511 const std::string mode = "hwbinder";
512
513 hidl_vec<hidl_string> fqInstanceNames;
514 // copying out for timeoutIPC
515 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
516 fqInstanceNames = names;
517 });
518 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700519 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700520 << listRet.description() << std::endl;
521 return DUMP_BINDERIZED_ERROR;
522 }
523
524 Status status = OK;
525 // server pid, .ptr value of binder object, child pids
526 std::map<std::string, DebugInfo> allDebugInfos;
Steven Morelandd8e20192017-05-24 11:23:08 -0700527 std::map<pid_t, PidInfo> allPids;
Yifan Hong443df792017-05-09 18:49:45 -0700528 for (const auto &fqInstanceName : fqInstanceNames) {
529 const auto pair = splitFirst(fqInstanceName, '/');
530 const auto &serviceName = pair.first;
531 const auto &instanceName = pair.second;
532 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
533 if (!getRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700534 err() << "Warning: Skipping \"" << fqInstanceName << "\": "
Yifan Hong443df792017-05-09 18:49:45 -0700535 << "cannot be fetched from service manager:"
536 << getRet.description() << std::endl;
537 status |= DUMP_BINDERIZED_ERROR;
538 continue;
539 }
540 sp<IBase> service = getRet;
541 if (service == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700542 err() << "Warning: Skipping \"" << fqInstanceName << "\": "
Yifan Hong443df792017-05-09 18:49:45 -0700543 << "cannot be fetched from service manager (null)"
544 << std::endl;
545 status |= DUMP_BINDERIZED_ERROR;
546 continue;
547 }
548 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &debugInfo) {
549 allDebugInfos[fqInstanceName] = debugInfo;
550 if (debugInfo.pid >= 0) {
Steven Morelandd8e20192017-05-24 11:23:08 -0700551 allPids[static_cast<pid_t>(debugInfo.pid)] = PidInfo();
Yifan Hong443df792017-05-09 18:49:45 -0700552 }
553 });
554 if (!debugRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700555 err() << "Warning: Skipping \"" << fqInstanceName << "\": "
Yifan Hong443df792017-05-09 18:49:45 -0700556 << "debugging information cannot be retrieved:"
557 << debugRet.description() << std::endl;
558 status |= DUMP_BINDERIZED_ERROR;
559 }
560 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700561
Yifan Hong443df792017-05-09 18:49:45 -0700562 for (auto &pair : allPids) {
563 pid_t serverPid = pair.first;
Steven Morelandd8e20192017-05-24 11:23:08 -0700564 if (!getPidInfo(serverPid, &allPids[serverPid])) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700565 err() << "Warning: no information for PID " << serverPid
Yifan Hong443df792017-05-09 18:49:45 -0700566 << ", are you root?" << std::endl;
567 status |= DUMP_BINDERIZED_ERROR;
568 }
569 }
570 for (const auto &fqInstanceName : fqInstanceNames) {
571 auto it = allDebugInfos.find(fqInstanceName);
572 if (it == allDebugInfos.end()) {
573 putEntry(HWSERVICEMANAGER_LIST, {
574 .interfaceName = fqInstanceName,
575 .transport = mode,
576 .serverPid = NO_PID,
577 .serverObjectAddress = NO_PTR,
578 .clientPids = {},
Steven Morelandd8e20192017-05-24 11:23:08 -0700579 .threadUsage = 0,
580 .threadCount = 0,
Yifan Hong443df792017-05-09 18:49:45 -0700581 .arch = ARCH_UNKNOWN
582 });
583 continue;
584 }
585 const DebugInfo &info = it->second;
Steven Morelandd8e20192017-05-24 11:23:08 -0700586 bool writePidInfo = info.pid != NO_PID && info.ptr != NO_PTR;
587
Yifan Hong443df792017-05-09 18:49:45 -0700588 putEntry(HWSERVICEMANAGER_LIST, {
589 .interfaceName = fqInstanceName,
590 .transport = mode,
591 .serverPid = info.pid,
592 .serverObjectAddress = info.ptr,
Steven Morelandd8e20192017-05-24 11:23:08 -0700593 .clientPids = writePidInfo ? allPids[info.pid].refPids[info.ptr] : Pids{},
594 .threadUsage = writePidInfo ? allPids[info.pid].threadUsage : 0,
595 .threadCount = writePidInfo ? allPids[info.pid].threadCount : 0,
Yifan Hong443df792017-05-09 18:49:45 -0700596 .arch = fromBaseArchitecture(info.arch),
597 });
598 }
599 return status;
600}
601
602Status ListCommand::fetch() {
603 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700604 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700605 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700606 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700607 status |= NO_BINDERIZED_MANAGER;
608 } else {
609 status |= fetchBinderized(bManager);
610 // Passthrough PIDs are registered to the binderized manager as well.
611 status |= fetchPassthrough(bManager);
612 }
613
Yifan Hong9881df92017-05-10 14:33:05 -0700614 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700615 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700616 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700617 status |= NO_PASSTHROUGH_MANAGER;
618 } else {
619 status |= fetchAllLibraries(pManager);
620 }
621 return status;
622}
623
Yifan Honga6b93f02017-09-13 16:53:37 -0700624void ListCommand::registerAllOptions() {
625 int v = mOptions.size();
626 // A list of acceptable command line options
627 // key: value returned by getopt_long
628 // long options with short alternatives
629 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
630 return USAGE;
631 }, ""});
632 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
633 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
634 return OK;
635 }, "print the instance name column"});
636 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
637 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
638 return OK;
639 }, "print the transport mode column"});
640 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
641 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
642 return OK;
643 }, "print the bitness column"});
644 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
645 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
646 return OK;
647 }, "print the server PID, or server cmdline if -m is set"});
648 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
649 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
650 return OK;
651 }, "print the server object address column"});
652 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
653 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
654 return OK;
655 }, "print the client PIDs, or client cmdlines if -m is set"});
656 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
657 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
658 return OK;
659 }, "print currently used/available threads\n(note, available threads created lazily)"});
660 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
661 thiz->mEnableCmdlines = true;
662 return OK;
663 }, "print cmdline instead of PIDs"});
664 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
665 thiz->mEmitDebugInfo = true;
666 if (arg) thiz->mFileOutputPath = arg;
667 return OK;
668 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
669 "Writes to specified file if 'arg' is provided, otherwise stdout."});
670
671 // long options without short alternatives
672 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
673 thiz->mVintf = true;
674 if (arg) thiz->mFileOutputPath = arg;
675 return OK;
676 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
677 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
678 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
679 thiz->mSortColumn = TableEntry::sortByInterfaceName;
680 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
681 thiz->mSortColumn = TableEntry::sortByServerPid;
682 } else {
683 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
684 return USAGE;
685 }
686 return OK;
687 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
688 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
689 thiz->mNeat = true;
690 return OK;
691 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
692}
693
694// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
695// the lifetime of "options" during the usage of the returned array.
696static std::unique_ptr<struct option[]> getLongOptions(
697 const ListCommand::RegisteredOptions& options,
698 int* longOptFlag) {
699 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
700 int i = 0;
701 for (const auto& e : options) {
702 ret[i].name = e.longOption.c_str();
703 ret[i].has_arg = e.hasArg;
704 ret[i].flag = longOptFlag;
705 ret[i].val = e.val;
706
707 i++;
708 }
709 // getopt_long last option has all zeros
710 ret[i].name = NULL;
711 ret[i].has_arg = 0;
712 ret[i].flag = NULL;
713 ret[i].val = 0;
714
715 return ret;
716}
717
718// Create 'optstring' argument to getopt_long.
719static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
720 std::stringstream ss;
721 for (const auto& e : options) {
722 if (e.shortOption != '\0') {
723 ss << e.shortOption;
724 }
725 }
726 return ss.str();
727}
728
Yifan Honga8bedc62017-09-08 18:00:31 -0700729Status ListCommand::parseArgs(const Arg &arg) {
Yifan Hong443df792017-05-09 18:49:45 -0700730
Yifan Honga6b93f02017-09-13 16:53:37 -0700731 if (mOptions.empty()) {
732 registerAllOptions();
733 }
734 int longOptFlag;
735 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
736 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700737
Yifan Honga8bedc62017-09-08 18:00:31 -0700738 // suppress output to std::err for unknown options
739 opterr = 0;
740
Yifan Hong443df792017-05-09 18:49:45 -0700741 int optionIndex;
742 int c;
743 // Lshal::parseArgs has set optind to the next option to parse
744 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700745 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700746 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700747 if (c == -1) {
748 break;
749 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700750 const RegisteredOption* found = nullptr;
751 if (c == 0) {
752 // see long option
753 for (const auto& e : mOptions) {
754 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700755 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700756 } else {
757 // see short option
758 for (const auto& e : mOptions) {
759 if (c == e.shortOption) found = &e;
760 }
Yifan Hong443df792017-05-09 18:49:45 -0700761 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700762
763 if (found == nullptr) {
764 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700765 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700766 return USAGE;
767 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700768
769 Status status = found->op(this, optarg);
770 if (status != OK) {
771 return status;
772 }
Yifan Hong443df792017-05-09 18:49:45 -0700773 }
774 if (optind < arg.argc) {
775 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700776 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700777 return USAGE;
778 }
779
780 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700781 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700782 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700783 }
784
Yifan Honga6b93f02017-09-13 16:53:37 -0700785 if (mSelectedColumns.empty()) {
786 mSelectedColumns = {TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -0700787 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -0700788 }
Yifan Hongd4a77e82017-09-06 19:40:24 -0700789
Yifan Honga6b93f02017-09-13 16:53:37 -0700790 if (mEnableCmdlines) {
791 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
792 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
793 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700794 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700795 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
796 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700797 }
798 }
799 }
800
Yifan Honga6b93f02017-09-13 16:53:37 -0700801 forEachTable([this] (Table& table) {
802 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700803 });
804
Yifan Hong443df792017-05-09 18:49:45 -0700805 return OK;
806}
807
Yifan Honga8bedc62017-09-08 18:00:31 -0700808Status ListCommand::main(const Arg &arg) {
809 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -0700810 if (status != OK) {
811 return status;
812 }
813 status = fetch();
814 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -0700815 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -0700816 return status;
817}
818
Yifan Honga6b93f02017-09-13 16:53:37 -0700819static std::vector<std::string> splitString(const std::string &s, char c) {
820 std::vector<std::string> components;
821
822 size_t startPos = 0;
823 size_t matchPos;
824 while ((matchPos = s.find(c, startPos)) != std::string::npos) {
825 components.push_back(s.substr(startPos, matchPos - startPos));
826 startPos = matchPos + 1;
827 }
828
829 if (startPos <= s.length()) {
830 components.push_back(s.substr(startPos));
831 }
832 return components;
833}
834
835const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
836 static const std::string empty{};
837 static const std::string optional{"[=<arg>]"};
838 static const std::string required{"=<arg>"};
839
840 if (hasArg == optional_argument) {
841 return optional;
842 }
843 if (hasArg == required_argument) {
844 return required;
845 }
846 return empty;
847}
848
Yifan Honga8bedc62017-09-08 18:00:31 -0700849void ListCommand::usage() const {
850
Yifan Honga6b93f02017-09-13 16:53:37 -0700851 err() << "list:" << std::endl
852 << " lshal" << std::endl
853 << " lshal list" << std::endl
854 << " List all hals with default ordering and columns (`lshal list -iepc`)" << std::endl
855 << " lshal list [-h|--help]" << std::endl
856 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
857 << " lshal [list] [OPTIONS...]" << std::endl;
858 for (const auto& e : mOptions) {
859 if (e.help.empty()) {
860 continue;
861 }
862 err() << " ";
863 if (e.shortOption != '\0')
864 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
865 if (e.shortOption != '\0' && !e.longOption.empty())
866 err() << ", ";
867 if (!e.longOption.empty())
868 err() << "--" << e.longOption << e.getHelpMessageForArgument();
869 err() << ": ";
870 std::vector<std::string> lines = splitString(e.help, '\n');
871 for (const auto& line : lines) {
872 if (&line != &lines.front())
873 err() << " ";
874 err() << line << std::endl;
875 }
876 }
Yifan Honga8bedc62017-09-08 18:00:31 -0700877}
878
Yifan Hong443df792017-05-09 18:49:45 -0700879} // namespace lshal
880} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -0700881