blob: fab13a0617ffe70e79f4b2000ac42646b38b26bb [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 Hongfee209d2017-09-14 18:23:38 -070030#include <hidl-hash/Hash.h>
Yifan Hong443df792017-05-09 18:49:45 -070031#include <hidl-util/FQName.h>
32#include <private/android_filesystem_config.h>
33#include <sys/stat.h>
34#include <vintf/HalManifest.h>
35#include <vintf/parse_xml.h>
36
37#include "Lshal.h"
38#include "PipeRelay.h"
39#include "Timeout.h"
40#include "utils.h"
41
42using ::android::hardware::hidl_string;
Yifan Hong22ea7b82017-09-14 18:07:43 -070043using ::android::hardware::hidl_vec;
44using ::android::hidl::base::V1_0::DebugInfo;
45using ::android::hidl::base::V1_0::IBase;
Yifan Hong443df792017-05-09 18:49:45 -070046using ::android::hidl::manager::V1_0::IServiceManager;
47
48namespace android {
49namespace lshal {
50
Yifan Hong76ac14a2017-09-08 14:59:04 -070051NullableOStream<std::ostream> ListCommand::out() const {
52 return mLshal.out();
53}
54
55NullableOStream<std::ostream> ListCommand::err() const {
56 return mLshal.err();
Yifan Hong443df792017-05-09 18:49:45 -070057}
58
Yifan Hong795b6ec2017-09-13 11:25:28 -070059std::string ListCommand::GetName() {
60 return "list";
61}
62std::string ListCommand::getSimpleDescription() const {
63 return "List HALs.";
64}
65
Yifan Hong8bf73162017-09-07 18:06:13 -070066std::string ListCommand::parseCmdline(pid_t pid) const {
Yifan Hong443df792017-05-09 18:49:45 -070067 std::ifstream ifs("/proc/" + std::to_string(pid) + "/cmdline");
68 std::string cmdline;
69 if (!ifs.is_open()) {
70 return "";
71 }
72 ifs >> cmdline;
73 return cmdline;
74}
75
76const std::string &ListCommand::getCmdline(pid_t pid) {
77 auto pair = mCmdlines.find(pid);
78 if (pair != mCmdlines.end()) {
79 return pair->second;
80 }
Yifan Hong8bf73162017-09-07 18:06:13 -070081 mCmdlines[pid] = parseCmdline(pid);
Yifan Hong443df792017-05-09 18:49:45 -070082 return mCmdlines[pid];
83}
84
85void ListCommand::removeDeadProcesses(Pids *pids) {
86 static const pid_t myPid = getpid();
Yifan Hong61fb7bc2017-05-12 16:33:57 -070087 pids->erase(std::remove_if(pids->begin(), pids->end(), [this](auto pid) {
Yifan Hong443df792017-05-09 18:49:45 -070088 return pid == myPid || this->getCmdline(pid).empty();
Yifan Hong61fb7bc2017-05-12 16:33:57 -070089 }), pids->end());
Yifan Hong443df792017-05-09 18:49:45 -070090}
91
Yifan Hong1243dde2017-09-14 17:49:30 -070092static bool scanBinderContext(pid_t pid,
Steven Morelandd8e20192017-05-24 11:23:08 -070093 const std::string &contextName,
94 std::function<void(const std::string&)> eachLine) {
95 std::ifstream ifs("/d/binder/proc/" + std::to_string(pid));
Yifan Hong443df792017-05-09 18:49:45 -070096 if (!ifs.is_open()) {
97 return false;
98 }
99
Steven Morelandd8e20192017-05-24 11:23:08 -0700100 static const std::regex kContextLine("^context (\\w+)$");
Yifan Hong443df792017-05-09 18:49:45 -0700101
Steven Morelandd8e20192017-05-24 11:23:08 -0700102 bool isDesiredContext = false;
Yifan Hong443df792017-05-09 18:49:45 -0700103 std::string line;
104 std::smatch match;
105 while(getline(ifs, line)) {
Steven Morelandd8e20192017-05-24 11:23:08 -0700106 if (std::regex_search(line, match, kContextLine)) {
107 isDesiredContext = match.str(1) == contextName;
Yifan Hong443df792017-05-09 18:49:45 -0700108 continue;
109 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700110
111 if (!isDesiredContext) {
Yifan Hong443df792017-05-09 18:49:45 -0700112 continue;
113 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700114
115 eachLine(line);
Yifan Hong443df792017-05-09 18:49:45 -0700116 }
117 return true;
118}
119
Steven Morelandd8e20192017-05-24 11:23:08 -0700120bool ListCommand::getPidInfo(
121 pid_t serverPid, PidInfo *pidInfo) const {
122 static const std::regex kReferencePrefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
123 static const std::regex kThreadPrefix("^\\s*thread \\d+:\\s+l\\s+(\\d)(\\d)");
124
125 std::smatch match;
126 return scanBinderContext(serverPid, "hwbinder", [&](const std::string& line) {
127 if (std::regex_search(line, match, kReferencePrefix)) {
128 const std::string &ptrString = "0x" + match.str(2); // use number after c
129 uint64_t ptr;
130 if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
131 // Should not reach here, but just be tolerant.
Yifan Hong76ac14a2017-09-08 14:59:04 -0700132 err() << "Could not parse number " << ptrString << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700133 return;
134 }
135 const std::string proc = " proc ";
136 auto pos = line.rfind(proc);
137 if (pos != std::string::npos) {
138 for (const std::string &pidStr : split(line.substr(pos + proc.size()), ' ')) {
139 int32_t pid;
140 if (!::android::base::ParseInt(pidStr, &pid)) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700141 err() << "Could not parse number " << pidStr << std::endl;
Steven Morelandd8e20192017-05-24 11:23:08 -0700142 return;
143 }
144 pidInfo->refPids[ptr].push_back(pid);
145 }
146 }
147
148 return;
149 }
150
151 if (std::regex_search(line, match, kThreadPrefix)) {
152 // "1" is waiting in binder driver
153 // "2" is poll. It's impossible to tell if these are in use.
154 // and HIDL default code doesn't use it.
155 bool isInUse = match.str(1) != "1";
156 // "0" is a thread that has called into binder
157 // "1" is looper thread
158 // "2" is main looper thread
159 bool isHwbinderThread = match.str(2) != "0";
160
161 if (!isHwbinderThread) {
162 return;
163 }
164
165 if (isInUse) {
166 pidInfo->threadUsage++;
167 }
168
169 pidInfo->threadCount++;
170 return;
171 }
172
173 // not reference or thread line
174 return;
175 });
176}
177
Yifan Hong1243dde2017-09-14 17:49:30 -0700178const PidInfo* ListCommand::getPidInfoCached(pid_t serverPid) {
179 auto pair = mCachedPidInfos.insert({serverPid, PidInfo{}});
180 if (pair.second /* did insertion take place? */) {
181 if (!getPidInfo(serverPid, &pair.first->second)) {
182 return nullptr;
183 }
184 }
185 return &pair.first->second;
186}
187
Yifan Hong443df792017-05-09 18:49:45 -0700188// Must process hwbinder services first, then passthrough services.
189void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
190 f(mServicesTable);
191 f(mPassthroughRefTable);
192 f(mImplementationsTable);
193}
194void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
195 f(mServicesTable);
196 f(mPassthroughRefTable);
197 f(mImplementationsTable);
198}
199
200void ListCommand::postprocess() {
201 forEachTable([this](Table &table) {
202 if (mSortColumn) {
203 std::sort(table.begin(), table.end(), mSortColumn);
204 }
205 for (TableEntry &entry : table) {
206 entry.serverCmdline = getCmdline(entry.serverPid);
207 removeDeadProcesses(&entry.clientPids);
208 for (auto pid : entry.clientPids) {
209 entry.clientCmdlines.push_back(this->getCmdline(pid));
210 }
211 }
212 });
213 // use a double for loop here because lshal doesn't care about efficiency.
214 for (TableEntry &packageEntry : mImplementationsTable) {
215 std::string packageName = packageEntry.interfaceName;
216 FQName fqPackageName{packageName.substr(0, packageName.find("::"))};
217 if (!fqPackageName.isValid()) {
218 continue;
219 }
220 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
221 if (interfaceEntry.arch != ARCH_UNKNOWN) {
222 continue;
223 }
224 FQName interfaceName{splitFirst(interfaceEntry.interfaceName, '/').first};
225 if (!interfaceName.isValid()) {
226 continue;
227 }
228 if (interfaceName.getPackageAndVersion() == fqPackageName) {
229 interfaceEntry.arch = packageEntry.arch;
230 }
231 }
232 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700233
234 mServicesTable.setDescription(
235 "All binderized services (registered services through hwservicemanager)");
236 mPassthroughRefTable.setDescription(
237 "All interfaces that getService() has ever return as a passthrough interface;\n"
238 "PIDs / processes shown below might be inaccurate because the process\n"
239 "might have relinquished the interface or might have died.\n"
240 "The Server / Server CMD column can be ignored.\n"
241 "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
242 "the library and successfully fetched the passthrough implementation.");
243 mImplementationsTable.setDescription(
244 "All available passthrough implementations (all -impl.so files)");
Yifan Hong443df792017-05-09 18:49:45 -0700245}
246
Yifan Hong77c87822017-06-19 15:47:39 -0700247static inline bool findAndBumpVersion(vintf::ManifestHal* hal, const vintf::Version& version) {
248 for (vintf::Version& v : hal->versions) {
249 if (v.majorVer == version.majorVer) {
250 v.minorVer = std::max(v.minorVer, version.minorVer);
251 return true;
252 }
253 }
254 return false;
255}
256
Yifan Hongca3b6602017-09-07 16:44:27 -0700257void ListCommand::dumpVintf(const NullableOStream<std::ostream>& out) const {
Yifan Hong236301c2017-06-19 12:27:08 -0700258 using vintf::operator|=;
Yifan Hongca3b6602017-09-07 16:44:27 -0700259 out << "<!-- " << std::endl
Yifan Hong443df792017-05-09 18:49:45 -0700260 << " This is a skeleton device manifest. Notes: " << std::endl
261 << " 1. android.hidl.*, android.frameworks.*, android.system.* are not included." << std::endl
262 << " 2. If a HAL is supported in both hwbinder and passthrough transport, " << std::endl
263 << " only hwbinder is shown." << std::endl
264 << " 3. It is likely that HALs in passthrough transport does not have" << std::endl
265 << " <interface> declared; users will have to write them by hand." << std::endl
Yifan Hong77c87822017-06-19 15:47:39 -0700266 << " 4. A HAL with lower minor version can be overridden by a HAL with" << std::endl
267 << " higher minor version if they have the same name and major version." << std::endl
Yifan Hong443df792017-05-09 18:49:45 -0700268 << "-->" << std::endl;
269
270 vintf::HalManifest manifest;
271 forEachTable([this, &manifest] (const Table &table) {
272 for (const TableEntry &entry : table) {
273
274 std::string fqInstanceName = entry.interfaceName;
275
276 if (&table == &mImplementationsTable) {
277 // Quick hack to work around *'s
278 replaceAll(&fqInstanceName, '*', 'D');
279 }
280 auto splittedFqInstanceName = splitFirst(fqInstanceName, '/');
281 FQName fqName(splittedFqInstanceName.first);
282 if (!fqName.isValid()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700283 err() << "Warning: '" << splittedFqInstanceName.first
Yifan Hong443df792017-05-09 18:49:45 -0700284 << "' is not a valid FQName." << std::endl;
285 continue;
286 }
287 // Strip out system libs.
288 if (fqName.inPackage("android.hidl") ||
289 fqName.inPackage("android.frameworks") ||
290 fqName.inPackage("android.system")) {
291 continue;
292 }
293 std::string interfaceName =
294 &table == &mImplementationsTable ? "" : fqName.name();
295 std::string instanceName =
296 &table == &mImplementationsTable ? "" : splittedFqInstanceName.second;
297
298 vintf::Version version{fqName.getPackageMajorVersion(),
299 fqName.getPackageMinorVersion()};
300 vintf::Transport transport;
301 vintf::Arch arch;
302 if (entry.transport == "hwbinder") {
303 transport = vintf::Transport::HWBINDER;
304 arch = vintf::Arch::ARCH_EMPTY;
305 } else if (entry.transport == "passthrough") {
306 transport = vintf::Transport::PASSTHROUGH;
307 switch (entry.arch) {
308 case lshal::ARCH32:
309 arch = vintf::Arch::ARCH_32; break;
310 case lshal::ARCH64:
311 arch = vintf::Arch::ARCH_64; break;
312 case lshal::ARCH_BOTH:
313 arch = vintf::Arch::ARCH_32_64; break;
314 case lshal::ARCH_UNKNOWN: // fallthrough
315 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700316 err() << "Warning: '" << fqName.package()
Yifan Hong443df792017-05-09 18:49:45 -0700317 << "' doesn't have bitness info, assuming 32+64." << std::endl;
318 arch = vintf::Arch::ARCH_32_64;
319 }
320 } else {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700321 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700322 continue;
323 }
324
325 bool done = false;
326 for (vintf::ManifestHal *hal : manifest.getHals(fqName.package())) {
327 if (hal->transport() != transport) {
328 if (transport != vintf::Transport::PASSTHROUGH) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700329 err() << "Fatal: should not reach here. Generated result may be wrong for '"
Yifan Hong236301c2017-06-19 12:27:08 -0700330 << hal->name << "'."
Yifan Hong443df792017-05-09 18:49:45 -0700331 << std::endl;
332 }
333 done = true;
334 break;
335 }
Yifan Hong77c87822017-06-19 15:47:39 -0700336 if (findAndBumpVersion(hal, version)) {
Yifan Hong443df792017-05-09 18:49:45 -0700337 if (&table != &mImplementationsTable) {
338 hal->interfaces[interfaceName].name = interfaceName;
339 hal->interfaces[interfaceName].instances.insert(instanceName);
340 }
Yifan Hong236301c2017-06-19 12:27:08 -0700341 hal->transportArch.arch |= arch;
Yifan Hong443df792017-05-09 18:49:45 -0700342 done = true;
343 break;
344 }
345 }
346 if (done) {
347 continue; // to next TableEntry
348 }
349 decltype(vintf::ManifestHal::interfaces) interfaces;
350 if (&table != &mImplementationsTable) {
351 interfaces[interfaceName].name = interfaceName;
352 interfaces[interfaceName].instances.insert(instanceName);
353 }
354 if (!manifest.add(vintf::ManifestHal{
355 .format = vintf::HalFormat::HIDL,
356 .name = fqName.package(),
357 .versions = {version},
358 .transportArch = {transport, arch},
359 .interfaces = interfaces})) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700360 err() << "Warning: cannot add hal '" << fqInstanceName << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700361 }
362 }
363 });
Yifan Hongacc12122018-01-25 10:49:39 -0800364 out << vintf::gHalManifestConverter(manifest, vintf::SerializeFlag::HALS_ONLY);
Yifan Hong443df792017-05-09 18:49:45 -0700365}
366
Yifan Hong443df792017-05-09 18:49:45 -0700367static Architecture fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
368 switch (a) {
369 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
370 return ARCH64;
371 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
372 return ARCH32;
373 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
374 default:
375 return ARCH_UNKNOWN;
376 }
377}
378
Yifan Hongca3b6602017-09-07 16:44:27 -0700379void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700380 if (mNeat) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700381 MergedTable({&mServicesTable, &mPassthroughRefTable, &mImplementationsTable})
Yifan Hongca3b6602017-09-07 16:44:27 -0700382 .createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700383 return;
384 }
385
Yifan Hongca3b6602017-09-07 16:44:27 -0700386 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700387
Yifan Hongd4a77e82017-09-06 19:40:24 -0700388 // We're only interested in dumping debug info for already
389 // instantiated services. There's little value in dumping the
390 // debug info for a service we create on the fly, so we only operate
391 // on the "mServicesTable".
392 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
393 if (mEmitDebugInfo && &table == &mServicesTable) {
394 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700395 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700396 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800397 mLshal.emitDebugInfo(pair.first, pair.second, {},
398 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700399 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700400 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700401 };
Yifan Hong443df792017-05-09 18:49:45 -0700402 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700403 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
404 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700405 });
Yifan Hong443df792017-05-09 18:49:45 -0700406}
407
Yifan Hongca3b6602017-09-07 16:44:27 -0700408Status ListCommand::dump() {
409 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
410
411 if (mFileOutputPath.empty()) {
412 (*this.*dump)(out());
413 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700414 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700415
416 std::ofstream fileOutput(mFileOutputPath);
417 if (!fileOutput.is_open()) {
418 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
419 return IO_ERROR;
420 }
421 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
422
423 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
424
425 fileOutput.flush();
426 fileOutput.close();
427 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700428}
429
430void ListCommand::putEntry(TableEntrySource source, TableEntry &&entry) {
431 Table *table = nullptr;
432 switch (source) {
433 case HWSERVICEMANAGER_LIST :
434 table = &mServicesTable; break;
435 case PTSERVICEMANAGER_REG_CLIENT :
436 table = &mPassthroughRefTable; break;
437 case LIST_DLLIB :
438 table = &mImplementationsTable; break;
439 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700440 err() << "Error: Unknown source of entry " << source << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700441 }
442 if (table) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700443 table->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700444 }
445}
446
447Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
448 using namespace ::android::hardware;
449 using namespace ::android::hidl::manager::V1_0;
450 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700451 using std::literals::chrono_literals::operator""s;
452 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700453 std::map<std::string, TableEntry> entries;
454 for (const auto &info : infos) {
455 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
456 std::string{info.instanceName.c_str()};
457 entries.emplace(interfaceName, TableEntry{
458 .interfaceName = interfaceName,
459 .transport = "passthrough",
Yifan Hongf2d557b2017-05-24 19:45:02 -0700460 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700461 }).first->second.arch |= fromBaseArchitecture(info.arch);
462 }
463 for (auto &&pair : entries) {
464 putEntry(LIST_DLLIB, std::move(pair.second));
465 }
466 });
467 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700468 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700469 << ret.description() << std::endl;
470 return DUMP_ALL_LIBS_ERROR;
471 }
472 return OK;
473}
474
475Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
476 using namespace ::android::hardware;
477 using namespace ::android::hardware::details;
478 using namespace ::android::hidl::manager::V1_0;
479 using namespace ::android::hidl::base::V1_0;
480 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
481 for (const auto &info : infos) {
482 if (info.clientPids.size() <= 0) {
483 continue;
484 }
485 putEntry(PTSERVICEMANAGER_REG_CLIENT, {
486 .interfaceName =
487 std::string{info.interfaceName.c_str()} + "/" +
488 std::string{info.instanceName.c_str()},
489 .transport = "passthrough",
490 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700491 .clientPids = info.clientPids,
492 .arch = fromBaseArchitecture(info.arch)
493 });
494 }
495 });
496 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700497 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700498 << ret.description() << std::endl;
499 return DUMP_PASSTHROUGH_ERROR;
500 }
501 return OK;
502}
503
504Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong443df792017-05-09 18:49:45 -0700505 const std::string mode = "hwbinder";
506
507 hidl_vec<hidl_string> fqInstanceNames;
508 // copying out for timeoutIPC
509 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
510 fqInstanceNames = names;
511 });
512 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700513 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700514 << listRet.description() << std::endl;
515 return DUMP_BINDERIZED_ERROR;
516 }
517
518 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700519 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700520 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700521 // create entry and default assign all fields.
522 TableEntry& entry = allTableEntries[fqInstanceName];
523 entry.interfaceName = fqInstanceName;
524 entry.transport = mode;
525
526 status |= fetchBinderizedEntry(manager, &entry);
527 }
528
529 for (auto& pair : allTableEntries) {
530 putEntry(HWSERVICEMANAGER_LIST, std::move(pair.second));
531 }
532 return status;
533}
534
535Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
536 TableEntry *entry) {
537 Status status = OK;
538 const auto handleError = [&](Status additionalError, const std::string& msg) {
539 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
540 status |= DUMP_BINDERIZED_ERROR | additionalError;
541 };
542
543 const auto pair = splitFirst(entry->interfaceName, '/');
544 const auto &serviceName = pair.first;
545 const auto &instanceName = pair.second;
546 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
547 if (!getRet.isOk()) {
548 handleError(TRANSACTION_ERROR,
549 "cannot be fetched from service manager:" + getRet.description());
550 return status;
551 }
552 sp<IBase> service = getRet;
553 if (service == nullptr) {
554 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
555 return status;
556 }
557
558 // getDebugInfo
559 do {
560 DebugInfo debugInfo;
561 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
562 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700563 });
564 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700565 handleError(TRANSACTION_ERROR,
566 "debugging information cannot be retrieved: " + debugRet.description());
567 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700568 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700569
Yifan Hong22ea7b82017-09-14 18:07:43 -0700570 entry->serverPid = debugInfo.pid;
571 entry->serverObjectAddress = debugInfo.ptr;
572 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700573
Yifan Hong22ea7b82017-09-14 18:07:43 -0700574 if (debugInfo.pid != NO_PID) {
575 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
576 if (pidInfo == nullptr) {
577 handleError(IO_ERROR,
578 "no information for PID " + std::to_string(debugInfo.pid) +
579 ", are you root?");
580 break;
581 }
582 if (debugInfo.ptr != NO_PTR) {
583 auto it = pidInfo->refPids.find(debugInfo.ptr);
584 if (it != pidInfo->refPids.end()) {
585 entry->clientPids = it->second;
586 }
587 }
588 entry->threadUsage = pidInfo->threadUsage;
589 entry->threadCount = pidInfo->threadCount;
590 }
591 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700592
593 // hash
594 do {
595 ssize_t hashIndex = -1;
596 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
597 for (size_t i = 0; i < c.size(); ++i) {
598 if (serviceName == c[i]) {
599 hashIndex = static_cast<ssize_t>(i);
600 break;
601 }
602 }
603 });
604 if (!ifaceChainRet.isOk()) {
605 handleError(TRANSACTION_ERROR,
606 "interfaceChain fails: " + ifaceChainRet.description());
607 break; // skip getHashChain
608 }
609 if (hashIndex < 0) {
610 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
611 break; // skip getHashChain
612 }
613 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
614 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
615 handleError(BAD_IMPL,
616 "interfaceChain indicates position " + std::to_string(hashIndex) +
617 " but getHashChain returns " + std::to_string(hashChain.size()) +
618 " hashes");
619 return;
620 }
621
622 auto&& hashArray = hashChain[hashIndex];
623 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
624 entry->hash = Hash::hexString(hashVec);
625 });
626 if (!hashRet.isOk()) {
627 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
628 }
629 } while (0);
Yifan Hong443df792017-05-09 18:49:45 -0700630 return status;
631}
632
633Status ListCommand::fetch() {
634 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700635 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700636 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700637 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700638 status |= NO_BINDERIZED_MANAGER;
639 } else {
640 status |= fetchBinderized(bManager);
641 // Passthrough PIDs are registered to the binderized manager as well.
642 status |= fetchPassthrough(bManager);
643 }
644
Yifan Hong9881df92017-05-10 14:33:05 -0700645 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700646 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700647 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700648 status |= NO_PASSTHROUGH_MANAGER;
649 } else {
650 status |= fetchAllLibraries(pManager);
651 }
652 return status;
653}
654
Yifan Honga6b93f02017-09-13 16:53:37 -0700655void ListCommand::registerAllOptions() {
656 int v = mOptions.size();
657 // A list of acceptable command line options
658 // key: value returned by getopt_long
659 // long options with short alternatives
660 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
661 return USAGE;
662 }, ""});
663 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
664 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
665 return OK;
666 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700667 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
668 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
669 return OK;
670 }, "print the 'is released?' column\n(Y=released, empty=unreleased or unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700671 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
672 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
673 return OK;
674 }, "print the transport mode column"});
675 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
676 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
677 return OK;
678 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700679 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
680 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
681 return OK;
682 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700683 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
684 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
685 return OK;
686 }, "print the server PID, or server cmdline if -m is set"});
687 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
688 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
689 return OK;
690 }, "print the server object address column"});
691 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
692 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
693 return OK;
694 }, "print the client PIDs, or client cmdlines if -m is set"});
695 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
696 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
697 return OK;
698 }, "print currently used/available threads\n(note, available threads created lazily)"});
699 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
700 thiz->mEnableCmdlines = true;
701 return OK;
702 }, "print cmdline instead of PIDs"});
703 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
704 thiz->mEmitDebugInfo = true;
705 if (arg) thiz->mFileOutputPath = arg;
706 return OK;
707 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
708 "Writes to specified file if 'arg' is provided, otherwise stdout."});
709
710 // long options without short alternatives
711 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
712 thiz->mVintf = true;
713 if (arg) thiz->mFileOutputPath = arg;
714 return OK;
715 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
716 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
717 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
718 thiz->mSortColumn = TableEntry::sortByInterfaceName;
719 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
720 thiz->mSortColumn = TableEntry::sortByServerPid;
721 } else {
722 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
723 return USAGE;
724 }
725 return OK;
726 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
727 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
728 thiz->mNeat = true;
729 return OK;
730 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
731}
732
733// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
734// the lifetime of "options" during the usage of the returned array.
735static std::unique_ptr<struct option[]> getLongOptions(
736 const ListCommand::RegisteredOptions& options,
737 int* longOptFlag) {
738 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
739 int i = 0;
740 for (const auto& e : options) {
741 ret[i].name = e.longOption.c_str();
742 ret[i].has_arg = e.hasArg;
743 ret[i].flag = longOptFlag;
744 ret[i].val = e.val;
745
746 i++;
747 }
748 // getopt_long last option has all zeros
749 ret[i].name = NULL;
750 ret[i].has_arg = 0;
751 ret[i].flag = NULL;
752 ret[i].val = 0;
753
754 return ret;
755}
756
757// Create 'optstring' argument to getopt_long.
758static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
759 std::stringstream ss;
760 for (const auto& e : options) {
761 if (e.shortOption != '\0') {
762 ss << e.shortOption;
763 }
764 }
765 return ss.str();
766}
767
Yifan Honga8bedc62017-09-08 18:00:31 -0700768Status ListCommand::parseArgs(const Arg &arg) {
Yifan Hong443df792017-05-09 18:49:45 -0700769
Yifan Honga6b93f02017-09-13 16:53:37 -0700770 if (mOptions.empty()) {
771 registerAllOptions();
772 }
773 int longOptFlag;
774 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
775 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700776
Yifan Honga8bedc62017-09-08 18:00:31 -0700777 // suppress output to std::err for unknown options
778 opterr = 0;
779
Yifan Hong443df792017-05-09 18:49:45 -0700780 int optionIndex;
781 int c;
782 // Lshal::parseArgs has set optind to the next option to parse
783 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700784 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700785 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700786 if (c == -1) {
787 break;
788 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700789 const RegisteredOption* found = nullptr;
790 if (c == 0) {
791 // see long option
792 for (const auto& e : mOptions) {
793 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700794 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700795 } else {
796 // see short option
797 for (const auto& e : mOptions) {
798 if (c == e.shortOption) found = &e;
799 }
Yifan Hong443df792017-05-09 18:49:45 -0700800 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700801
802 if (found == nullptr) {
803 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700804 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700805 return USAGE;
806 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700807
808 Status status = found->op(this, optarg);
809 if (status != OK) {
810 return status;
811 }
Yifan Hong443df792017-05-09 18:49:45 -0700812 }
813 if (optind < arg.argc) {
814 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700815 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700816 return USAGE;
817 }
818
819 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700820 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700821 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700822 }
823
Yifan Honga6b93f02017-09-13 16:53:37 -0700824 if (mSelectedColumns.empty()) {
Yifan Hongfee209d2017-09-14 18:23:38 -0700825 mSelectedColumns = {TableColumnType::RELEASED,
826 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -0700827 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -0700828 }
Yifan Hongd4a77e82017-09-06 19:40:24 -0700829
Yifan Honga6b93f02017-09-13 16:53:37 -0700830 if (mEnableCmdlines) {
831 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
832 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
833 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700834 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700835 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
836 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700837 }
838 }
839 }
840
Yifan Honga6b93f02017-09-13 16:53:37 -0700841 forEachTable([this] (Table& table) {
842 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700843 });
844
Yifan Hong443df792017-05-09 18:49:45 -0700845 return OK;
846}
847
Yifan Honga8bedc62017-09-08 18:00:31 -0700848Status ListCommand::main(const Arg &arg) {
849 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -0700850 if (status != OK) {
851 return status;
852 }
853 status = fetch();
854 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -0700855 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -0700856 return status;
857}
858
Yifan Honga6b93f02017-09-13 16:53:37 -0700859static std::vector<std::string> splitString(const std::string &s, char c) {
860 std::vector<std::string> components;
861
862 size_t startPos = 0;
863 size_t matchPos;
864 while ((matchPos = s.find(c, startPos)) != std::string::npos) {
865 components.push_back(s.substr(startPos, matchPos - startPos));
866 startPos = matchPos + 1;
867 }
868
869 if (startPos <= s.length()) {
870 components.push_back(s.substr(startPos));
871 }
872 return components;
873}
874
875const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
876 static const std::string empty{};
877 static const std::string optional{"[=<arg>]"};
878 static const std::string required{"=<arg>"};
879
880 if (hasArg == optional_argument) {
881 return optional;
882 }
883 if (hasArg == required_argument) {
884 return required;
885 }
886 return empty;
887}
888
Yifan Honga8bedc62017-09-08 18:00:31 -0700889void ListCommand::usage() const {
890
Yifan Honga6b93f02017-09-13 16:53:37 -0700891 err() << "list:" << std::endl
892 << " lshal" << std::endl
893 << " lshal list" << std::endl
Yifan Hongfee209d2017-09-14 18:23:38 -0700894 << " List all hals with default ordering and columns (`lshal list -riepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -0700895 << " lshal list [-h|--help]" << std::endl
896 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
897 << " lshal [list] [OPTIONS...]" << std::endl;
898 for (const auto& e : mOptions) {
899 if (e.help.empty()) {
900 continue;
901 }
902 err() << " ";
903 if (e.shortOption != '\0')
904 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
905 if (e.shortOption != '\0' && !e.longOption.empty())
906 err() << ", ";
907 if (!e.longOption.empty())
908 err() << "--" << e.longOption << e.getHelpMessageForArgument();
909 err() << ": ";
910 std::vector<std::string> lines = splitString(e.help, '\n');
911 for (const auto& line : lines) {
912 if (&line != &lines.front())
913 err() << " ";
914 err() << line << std::endl;
915 }
916 }
Yifan Honga8bedc62017-09-08 18:00:31 -0700917}
918
Yifan Hong443df792017-05-09 18:49:45 -0700919} // namespace lshal
920} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -0700921