blob: e4b3c90480eadf27acb89c2472436088f8d5b358 [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
268 << " 5. sepolicy version is set to 0.0. It is recommended that the entry" << std::endl
Yifan Hong443df792017-05-09 18:49:45 -0700269 << " is removed from the manifest file and written by assemble_vintf" << std::endl
270 << " at build time." << std::endl
271 << "-->" << std::endl;
272
273 vintf::HalManifest manifest;
274 forEachTable([this, &manifest] (const Table &table) {
275 for (const TableEntry &entry : table) {
276
277 std::string fqInstanceName = entry.interfaceName;
278
279 if (&table == &mImplementationsTable) {
280 // Quick hack to work around *'s
281 replaceAll(&fqInstanceName, '*', 'D');
282 }
283 auto splittedFqInstanceName = splitFirst(fqInstanceName, '/');
284 FQName fqName(splittedFqInstanceName.first);
285 if (!fqName.isValid()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700286 err() << "Warning: '" << splittedFqInstanceName.first
Yifan Hong443df792017-05-09 18:49:45 -0700287 << "' is not a valid FQName." << std::endl;
288 continue;
289 }
290 // Strip out system libs.
291 if (fqName.inPackage("android.hidl") ||
292 fqName.inPackage("android.frameworks") ||
293 fqName.inPackage("android.system")) {
294 continue;
295 }
296 std::string interfaceName =
297 &table == &mImplementationsTable ? "" : fqName.name();
298 std::string instanceName =
299 &table == &mImplementationsTable ? "" : splittedFqInstanceName.second;
300
301 vintf::Version version{fqName.getPackageMajorVersion(),
302 fqName.getPackageMinorVersion()};
303 vintf::Transport transport;
304 vintf::Arch arch;
305 if (entry.transport == "hwbinder") {
306 transport = vintf::Transport::HWBINDER;
307 arch = vintf::Arch::ARCH_EMPTY;
308 } else if (entry.transport == "passthrough") {
309 transport = vintf::Transport::PASSTHROUGH;
310 switch (entry.arch) {
311 case lshal::ARCH32:
312 arch = vintf::Arch::ARCH_32; break;
313 case lshal::ARCH64:
314 arch = vintf::Arch::ARCH_64; break;
315 case lshal::ARCH_BOTH:
316 arch = vintf::Arch::ARCH_32_64; break;
317 case lshal::ARCH_UNKNOWN: // fallthrough
318 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700319 err() << "Warning: '" << fqName.package()
Yifan Hong443df792017-05-09 18:49:45 -0700320 << "' doesn't have bitness info, assuming 32+64." << std::endl;
321 arch = vintf::Arch::ARCH_32_64;
322 }
323 } else {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700324 err() << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700325 continue;
326 }
327
328 bool done = false;
329 for (vintf::ManifestHal *hal : manifest.getHals(fqName.package())) {
330 if (hal->transport() != transport) {
331 if (transport != vintf::Transport::PASSTHROUGH) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700332 err() << "Fatal: should not reach here. Generated result may be wrong for '"
Yifan Hong236301c2017-06-19 12:27:08 -0700333 << hal->name << "'."
Yifan Hong443df792017-05-09 18:49:45 -0700334 << std::endl;
335 }
336 done = true;
337 break;
338 }
Yifan Hong77c87822017-06-19 15:47:39 -0700339 if (findAndBumpVersion(hal, version)) {
Yifan Hong443df792017-05-09 18:49:45 -0700340 if (&table != &mImplementationsTable) {
341 hal->interfaces[interfaceName].name = interfaceName;
342 hal->interfaces[interfaceName].instances.insert(instanceName);
343 }
Yifan Hong236301c2017-06-19 12:27:08 -0700344 hal->transportArch.arch |= arch;
Yifan Hong443df792017-05-09 18:49:45 -0700345 done = true;
346 break;
347 }
348 }
349 if (done) {
350 continue; // to next TableEntry
351 }
352 decltype(vintf::ManifestHal::interfaces) interfaces;
353 if (&table != &mImplementationsTable) {
354 interfaces[interfaceName].name = interfaceName;
355 interfaces[interfaceName].instances.insert(instanceName);
356 }
357 if (!manifest.add(vintf::ManifestHal{
358 .format = vintf::HalFormat::HIDL,
359 .name = fqName.package(),
360 .versions = {version},
361 .transportArch = {transport, arch},
362 .interfaces = interfaces})) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700363 err() << "Warning: cannot add hal '" << fqInstanceName << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700364 }
365 }
366 });
Yifan Hongca3b6602017-09-07 16:44:27 -0700367 out << vintf::gHalManifestConverter(manifest);
Yifan Hong443df792017-05-09 18:49:45 -0700368}
369
Yifan Hong443df792017-05-09 18:49:45 -0700370static Architecture fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
371 switch (a) {
372 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
373 return ARCH64;
374 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
375 return ARCH32;
376 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
377 default:
378 return ARCH_UNKNOWN;
379 }
380}
381
Yifan Hongca3b6602017-09-07 16:44:27 -0700382void ListCommand::dumpTable(const NullableOStream<std::ostream>& out) const {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700383 if (mNeat) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700384 MergedTable({&mServicesTable, &mPassthroughRefTable, &mImplementationsTable})
Yifan Hongca3b6602017-09-07 16:44:27 -0700385 .createTextTable().dump(out.buf());
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700386 return;
387 }
388
Yifan Hongca3b6602017-09-07 16:44:27 -0700389 forEachTable([this, &out](const Table &table) {
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700390
Yifan Hongd4a77e82017-09-06 19:40:24 -0700391 // We're only interested in dumping debug info for already
392 // instantiated services. There's little value in dumping the
393 // debug info for a service we create on the fly, so we only operate
394 // on the "mServicesTable".
395 std::function<std::string(const std::string&)> emitDebugInfo = nullptr;
396 if (mEmitDebugInfo && &table == &mServicesTable) {
397 emitDebugInfo = [this](const auto& iName) {
Yifan Hongca3b6602017-09-07 16:44:27 -0700398 std::stringstream ss;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700399 auto pair = splitFirst(iName, '/');
Steven Moreland5f328892018-01-18 14:38:07 -0800400 mLshal.emitDebugInfo(pair.first, pair.second, {},
401 false /* excludesParentInstances */, ss,
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700402 NullableOStream<std::ostream>(nullptr));
Yifan Hongca3b6602017-09-07 16:44:27 -0700403 return ss.str();
Yifan Hongd4a77e82017-09-06 19:40:24 -0700404 };
Yifan Hong443df792017-05-09 18:49:45 -0700405 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700406 table.createTextTable(mNeat, emitDebugInfo).dump(out.buf());
407 out << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700408 });
Yifan Hong443df792017-05-09 18:49:45 -0700409}
410
Yifan Hongca3b6602017-09-07 16:44:27 -0700411Status ListCommand::dump() {
412 auto dump = mVintf ? &ListCommand::dumpVintf : &ListCommand::dumpTable;
413
414 if (mFileOutputPath.empty()) {
415 (*this.*dump)(out());
416 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700417 }
Yifan Hongca3b6602017-09-07 16:44:27 -0700418
419 std::ofstream fileOutput(mFileOutputPath);
420 if (!fileOutput.is_open()) {
421 err() << "Could not open file '" << mFileOutputPath << "'." << std::endl;
422 return IO_ERROR;
423 }
424 chown(mFileOutputPath.c_str(), AID_SHELL, AID_SHELL);
425
426 (*this.*dump)(NullableOStream<std::ostream>(fileOutput));
427
428 fileOutput.flush();
429 fileOutput.close();
430 return OK;
Yifan Hong443df792017-05-09 18:49:45 -0700431}
432
433void ListCommand::putEntry(TableEntrySource source, TableEntry &&entry) {
434 Table *table = nullptr;
435 switch (source) {
436 case HWSERVICEMANAGER_LIST :
437 table = &mServicesTable; break;
438 case PTSERVICEMANAGER_REG_CLIENT :
439 table = &mPassthroughRefTable; break;
440 case LIST_DLLIB :
441 table = &mImplementationsTable; break;
442 default:
Yifan Hong76ac14a2017-09-08 14:59:04 -0700443 err() << "Error: Unknown source of entry " << source << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700444 }
445 if (table) {
Yifan Hongd4a77e82017-09-06 19:40:24 -0700446 table->add(std::forward<TableEntry>(entry));
Yifan Hong443df792017-05-09 18:49:45 -0700447 }
448}
449
450Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
451 using namespace ::android::hardware;
452 using namespace ::android::hidl::manager::V1_0;
453 using namespace ::android::hidl::base::V1_0;
Yifan Hongf2d557b2017-05-24 19:45:02 -0700454 using std::literals::chrono_literals::operator""s;
455 auto ret = timeoutIPC(2s, manager, &IServiceManager::debugDump, [&] (const auto &infos) {
Yifan Hong443df792017-05-09 18:49:45 -0700456 std::map<std::string, TableEntry> entries;
457 for (const auto &info : infos) {
458 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
459 std::string{info.instanceName.c_str()};
460 entries.emplace(interfaceName, TableEntry{
461 .interfaceName = interfaceName,
462 .transport = "passthrough",
Yifan Hongf2d557b2017-05-24 19:45:02 -0700463 .clientPids = info.clientPids,
Yifan Hong443df792017-05-09 18:49:45 -0700464 }).first->second.arch |= fromBaseArchitecture(info.arch);
465 }
466 for (auto &&pair : entries) {
467 putEntry(LIST_DLLIB, std::move(pair.second));
468 }
469 });
470 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700471 err() << "Error: Failed to call list on getPassthroughServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700472 << ret.description() << std::endl;
473 return DUMP_ALL_LIBS_ERROR;
474 }
475 return OK;
476}
477
478Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
479 using namespace ::android::hardware;
480 using namespace ::android::hardware::details;
481 using namespace ::android::hidl::manager::V1_0;
482 using namespace ::android::hidl::base::V1_0;
483 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
484 for (const auto &info : infos) {
485 if (info.clientPids.size() <= 0) {
486 continue;
487 }
488 putEntry(PTSERVICEMANAGER_REG_CLIENT, {
489 .interfaceName =
490 std::string{info.interfaceName.c_str()} + "/" +
491 std::string{info.instanceName.c_str()},
492 .transport = "passthrough",
493 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
Yifan Hong443df792017-05-09 18:49:45 -0700494 .clientPids = info.clientPids,
495 .arch = fromBaseArchitecture(info.arch)
496 });
497 }
498 });
499 if (!ret.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700500 err() << "Error: Failed to call debugDump on defaultServiceManager(): "
Yifan Hong443df792017-05-09 18:49:45 -0700501 << ret.description() << std::endl;
502 return DUMP_PASSTHROUGH_ERROR;
503 }
504 return OK;
505}
506
507Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
Yifan Hong443df792017-05-09 18:49:45 -0700508 const std::string mode = "hwbinder";
509
510 hidl_vec<hidl_string> fqInstanceNames;
511 // copying out for timeoutIPC
512 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
513 fqInstanceNames = names;
514 });
515 if (!listRet.isOk()) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700516 err() << "Error: Failed to list services for " << mode << ": "
Yifan Hong443df792017-05-09 18:49:45 -0700517 << listRet.description() << std::endl;
518 return DUMP_BINDERIZED_ERROR;
519 }
520
521 Status status = OK;
Yifan Hong22ea7b82017-09-14 18:07:43 -0700522 std::map<std::string, TableEntry> allTableEntries;
Yifan Hong443df792017-05-09 18:49:45 -0700523 for (const auto &fqInstanceName : fqInstanceNames) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700524 // create entry and default assign all fields.
525 TableEntry& entry = allTableEntries[fqInstanceName];
526 entry.interfaceName = fqInstanceName;
527 entry.transport = mode;
528
529 status |= fetchBinderizedEntry(manager, &entry);
530 }
531
532 for (auto& pair : allTableEntries) {
533 putEntry(HWSERVICEMANAGER_LIST, std::move(pair.second));
534 }
535 return status;
536}
537
538Status ListCommand::fetchBinderizedEntry(const sp<IServiceManager> &manager,
539 TableEntry *entry) {
540 Status status = OK;
541 const auto handleError = [&](Status additionalError, const std::string& msg) {
542 err() << "Warning: Skipping \"" << entry->interfaceName << "\": " << msg << std::endl;
543 status |= DUMP_BINDERIZED_ERROR | additionalError;
544 };
545
546 const auto pair = splitFirst(entry->interfaceName, '/');
547 const auto &serviceName = pair.first;
548 const auto &instanceName = pair.second;
549 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
550 if (!getRet.isOk()) {
551 handleError(TRANSACTION_ERROR,
552 "cannot be fetched from service manager:" + getRet.description());
553 return status;
554 }
555 sp<IBase> service = getRet;
556 if (service == nullptr) {
557 handleError(NO_INTERFACE, "cannot be fetched from service manager (null)");
558 return status;
559 }
560
561 // getDebugInfo
562 do {
563 DebugInfo debugInfo;
564 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &received) {
565 debugInfo = received;
Yifan Hong443df792017-05-09 18:49:45 -0700566 });
567 if (!debugRet.isOk()) {
Yifan Hong22ea7b82017-09-14 18:07:43 -0700568 handleError(TRANSACTION_ERROR,
569 "debugging information cannot be retrieved: " + debugRet.description());
570 break; // skip getPidInfo
Yifan Hong443df792017-05-09 18:49:45 -0700571 }
Steven Morelandd8e20192017-05-24 11:23:08 -0700572
Yifan Hong22ea7b82017-09-14 18:07:43 -0700573 entry->serverPid = debugInfo.pid;
574 entry->serverObjectAddress = debugInfo.ptr;
575 entry->arch = fromBaseArchitecture(debugInfo.arch);
Steven Morelandd8e20192017-05-24 11:23:08 -0700576
Yifan Hong22ea7b82017-09-14 18:07:43 -0700577 if (debugInfo.pid != NO_PID) {
578 const PidInfo* pidInfo = getPidInfoCached(debugInfo.pid);
579 if (pidInfo == nullptr) {
580 handleError(IO_ERROR,
581 "no information for PID " + std::to_string(debugInfo.pid) +
582 ", are you root?");
583 break;
584 }
585 if (debugInfo.ptr != NO_PTR) {
586 auto it = pidInfo->refPids.find(debugInfo.ptr);
587 if (it != pidInfo->refPids.end()) {
588 entry->clientPids = it->second;
589 }
590 }
591 entry->threadUsage = pidInfo->threadUsage;
592 entry->threadCount = pidInfo->threadCount;
593 }
594 } while (0);
Yifan Hongfee209d2017-09-14 18:23:38 -0700595
596 // hash
597 do {
598 ssize_t hashIndex = -1;
599 auto ifaceChainRet = timeoutIPC(service, &IBase::interfaceChain, [&] (const auto& c) {
600 for (size_t i = 0; i < c.size(); ++i) {
601 if (serviceName == c[i]) {
602 hashIndex = static_cast<ssize_t>(i);
603 break;
604 }
605 }
606 });
607 if (!ifaceChainRet.isOk()) {
608 handleError(TRANSACTION_ERROR,
609 "interfaceChain fails: " + ifaceChainRet.description());
610 break; // skip getHashChain
611 }
612 if (hashIndex < 0) {
613 handleError(BAD_IMPL, "Interface name does not exist in interfaceChain.");
614 break; // skip getHashChain
615 }
616 auto hashRet = timeoutIPC(service, &IBase::getHashChain, [&] (const auto& hashChain) {
617 if (static_cast<size_t>(hashIndex) >= hashChain.size()) {
618 handleError(BAD_IMPL,
619 "interfaceChain indicates position " + std::to_string(hashIndex) +
620 " but getHashChain returns " + std::to_string(hashChain.size()) +
621 " hashes");
622 return;
623 }
624
625 auto&& hashArray = hashChain[hashIndex];
626 std::vector<uint8_t> hashVec{hashArray.data(), hashArray.data() + hashArray.size()};
627 entry->hash = Hash::hexString(hashVec);
628 });
629 if (!hashRet.isOk()) {
630 handleError(TRANSACTION_ERROR, "getHashChain failed: " + hashRet.description());
631 }
632 } while (0);
Yifan Hong443df792017-05-09 18:49:45 -0700633 return status;
634}
635
636Status ListCommand::fetch() {
637 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700638 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700639 if (bManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700640 err() << "Failed to get defaultServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700641 status |= NO_BINDERIZED_MANAGER;
642 } else {
643 status |= fetchBinderized(bManager);
644 // Passthrough PIDs are registered to the binderized manager as well.
645 status |= fetchPassthrough(bManager);
646 }
647
Yifan Hong9881df92017-05-10 14:33:05 -0700648 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700649 if (pManager == nullptr) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700650 err() << "Failed to get getPassthroughServiceManager()!" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700651 status |= NO_PASSTHROUGH_MANAGER;
652 } else {
653 status |= fetchAllLibraries(pManager);
654 }
655 return status;
656}
657
Yifan Honga6b93f02017-09-13 16:53:37 -0700658void ListCommand::registerAllOptions() {
659 int v = mOptions.size();
660 // A list of acceptable command line options
661 // key: value returned by getopt_long
662 // long options with short alternatives
663 mOptions.push_back({'h', "help", no_argument, v++, [](ListCommand*, const char*) {
664 return USAGE;
665 }, ""});
666 mOptions.push_back({'i', "interface", no_argument, v++, [](ListCommand* thiz, const char*) {
667 thiz->mSelectedColumns.push_back(TableColumnType::INTERFACE_NAME);
668 return OK;
669 }, "print the instance name column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700670 mOptions.push_back({'l', "released", no_argument, v++, [](ListCommand* thiz, const char*) {
671 thiz->mSelectedColumns.push_back(TableColumnType::RELEASED);
672 return OK;
673 }, "print the 'is released?' column\n(Y=released, empty=unreleased or unknown)"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700674 mOptions.push_back({'t', "transport", no_argument, v++, [](ListCommand* thiz, const char*) {
675 thiz->mSelectedColumns.push_back(TableColumnType::TRANSPORT);
676 return OK;
677 }, "print the transport mode column"});
678 mOptions.push_back({'r', "arch", no_argument, v++, [](ListCommand* thiz, const char*) {
679 thiz->mSelectedColumns.push_back(TableColumnType::ARCH);
680 return OK;
681 }, "print the bitness column"});
Yifan Hongfee209d2017-09-14 18:23:38 -0700682 mOptions.push_back({'s', "hash", no_argument, v++, [](ListCommand* thiz, const char*) {
683 thiz->mSelectedColumns.push_back(TableColumnType::HASH);
684 return OK;
685 }, "print hash of the interface"});
Yifan Honga6b93f02017-09-13 16:53:37 -0700686 mOptions.push_back({'p', "pid", no_argument, v++, [](ListCommand* thiz, const char*) {
687 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_PID);
688 return OK;
689 }, "print the server PID, or server cmdline if -m is set"});
690 mOptions.push_back({'a', "address", no_argument, v++, [](ListCommand* thiz, const char*) {
691 thiz->mSelectedColumns.push_back(TableColumnType::SERVER_ADDR);
692 return OK;
693 }, "print the server object address column"});
694 mOptions.push_back({'c', "clients", no_argument, v++, [](ListCommand* thiz, const char*) {
695 thiz->mSelectedColumns.push_back(TableColumnType::CLIENT_PIDS);
696 return OK;
697 }, "print the client PIDs, or client cmdlines if -m is set"});
698 mOptions.push_back({'e', "threads", no_argument, v++, [](ListCommand* thiz, const char*) {
699 thiz->mSelectedColumns.push_back(TableColumnType::THREADS);
700 return OK;
701 }, "print currently used/available threads\n(note, available threads created lazily)"});
702 mOptions.push_back({'m', "cmdline", no_argument, v++, [](ListCommand* thiz, const char*) {
703 thiz->mEnableCmdlines = true;
704 return OK;
705 }, "print cmdline instead of PIDs"});
706 mOptions.push_back({'d', "debug", optional_argument, v++, [](ListCommand* thiz, const char* arg) {
707 thiz->mEmitDebugInfo = true;
708 if (arg) thiz->mFileOutputPath = arg;
709 return OK;
710 }, "Emit debug info from\nIBase::debug with empty options. Cannot be used with --neat.\n"
711 "Writes to specified file if 'arg' is provided, otherwise stdout."});
712
713 // long options without short alternatives
714 mOptions.push_back({'\0', "init-vintf", no_argument, v++, [](ListCommand* thiz, const char* arg) {
715 thiz->mVintf = true;
716 if (arg) thiz->mFileOutputPath = arg;
717 return OK;
718 }, "form a skeleton HAL manifest to specified file,\nor stdout if no file specified."});
719 mOptions.push_back({'\0', "sort", required_argument, v++, [](ListCommand* thiz, const char* arg) {
720 if (strcmp(arg, "interface") == 0 || strcmp(arg, "i") == 0) {
721 thiz->mSortColumn = TableEntry::sortByInterfaceName;
722 } else if (strcmp(arg, "pid") == 0 || strcmp(arg, "p") == 0) {
723 thiz->mSortColumn = TableEntry::sortByServerPid;
724 } else {
725 thiz->err() << "Unrecognized sorting column: " << arg << std::endl;
726 return USAGE;
727 }
728 return OK;
729 }, "sort by a column. 'arg' can be (i|interface) or (p|pid)."});
730 mOptions.push_back({'\0', "neat", no_argument, v++, [](ListCommand* thiz, const char*) {
731 thiz->mNeat = true;
732 return OK;
733 }, "output is machine parsable (no explanatory text).\nCannot be used with --debug."});
734}
735
736// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
737// the lifetime of "options" during the usage of the returned array.
738static std::unique_ptr<struct option[]> getLongOptions(
739 const ListCommand::RegisteredOptions& options,
740 int* longOptFlag) {
741 std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
742 int i = 0;
743 for (const auto& e : options) {
744 ret[i].name = e.longOption.c_str();
745 ret[i].has_arg = e.hasArg;
746 ret[i].flag = longOptFlag;
747 ret[i].val = e.val;
748
749 i++;
750 }
751 // getopt_long last option has all zeros
752 ret[i].name = NULL;
753 ret[i].has_arg = 0;
754 ret[i].flag = NULL;
755 ret[i].val = 0;
756
757 return ret;
758}
759
760// Create 'optstring' argument to getopt_long.
761static std::string getShortOptions(const ListCommand::RegisteredOptions& options) {
762 std::stringstream ss;
763 for (const auto& e : options) {
764 if (e.shortOption != '\0') {
765 ss << e.shortOption;
766 }
767 }
768 return ss.str();
769}
770
Yifan Honga8bedc62017-09-08 18:00:31 -0700771Status ListCommand::parseArgs(const Arg &arg) {
Yifan Hong443df792017-05-09 18:49:45 -0700772
Yifan Honga6b93f02017-09-13 16:53:37 -0700773 if (mOptions.empty()) {
774 registerAllOptions();
775 }
776 int longOptFlag;
777 std::unique_ptr<struct option[]> longOptions = getLongOptions(mOptions, &longOptFlag);
778 std::string shortOptions = getShortOptions(mOptions);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700779
Yifan Honga8bedc62017-09-08 18:00:31 -0700780 // suppress output to std::err for unknown options
781 opterr = 0;
782
Yifan Hong443df792017-05-09 18:49:45 -0700783 int optionIndex;
784 int c;
785 // Lshal::parseArgs has set optind to the next option to parse
786 for (;;) {
Yifan Hong443df792017-05-09 18:49:45 -0700787 c = getopt_long(arg.argc, arg.argv,
Yifan Honga6b93f02017-09-13 16:53:37 -0700788 shortOptions.c_str(), longOptions.get(), &optionIndex);
Yifan Hong443df792017-05-09 18:49:45 -0700789 if (c == -1) {
790 break;
791 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700792 const RegisteredOption* found = nullptr;
793 if (c == 0) {
794 // see long option
795 for (const auto& e : mOptions) {
796 if (longOptFlag == e.val) found = &e;
Yifan Hong443df792017-05-09 18:49:45 -0700797 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700798 } else {
799 // see short option
800 for (const auto& e : mOptions) {
801 if (c == e.shortOption) found = &e;
802 }
Yifan Hong443df792017-05-09 18:49:45 -0700803 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700804
805 if (found == nullptr) {
806 // see unrecognized options
Yifan Honga8bedc62017-09-08 18:00:31 -0700807 err() << "unrecognized option `" << arg.argv[optind - 1] << "'" << std::endl;
Yifan Hong443df792017-05-09 18:49:45 -0700808 return USAGE;
809 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700810
811 Status status = found->op(this, optarg);
812 if (status != OK) {
813 return status;
814 }
Yifan Hong443df792017-05-09 18:49:45 -0700815 }
816 if (optind < arg.argc) {
817 // see non option
Yifan Honga8bedc62017-09-08 18:00:31 -0700818 err() << "unrecognized option `" << arg.argv[optind] << "'" << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700819 return USAGE;
820 }
821
822 if (mNeat && mEmitDebugInfo) {
Yifan Hong76ac14a2017-09-08 14:59:04 -0700823 err() << "Error: --neat should not be used with --debug." << std::endl;
Yifan Hong1bc1e9f2017-08-29 17:28:12 -0700824 return USAGE;
Yifan Hong443df792017-05-09 18:49:45 -0700825 }
826
Yifan Honga6b93f02017-09-13 16:53:37 -0700827 if (mSelectedColumns.empty()) {
Yifan Hongfee209d2017-09-14 18:23:38 -0700828 mSelectedColumns = {TableColumnType::RELEASED,
829 TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
Yifan Hong05494a52017-08-29 18:50:00 -0700830 TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
Yifan Hong443df792017-05-09 18:49:45 -0700831 }
Yifan Hongd4a77e82017-09-06 19:40:24 -0700832
Yifan Honga6b93f02017-09-13 16:53:37 -0700833 if (mEnableCmdlines) {
834 for (size_t i = 0; i < mSelectedColumns.size(); ++i) {
835 if (mSelectedColumns[i] == TableColumnType::SERVER_PID) {
836 mSelectedColumns[i] = TableColumnType::SERVER_CMD;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700837 }
Yifan Honga6b93f02017-09-13 16:53:37 -0700838 if (mSelectedColumns[i] == TableColumnType::CLIENT_PIDS) {
839 mSelectedColumns[i] = TableColumnType::CLIENT_CMDS;
Yifan Hongd4a77e82017-09-06 19:40:24 -0700840 }
841 }
842 }
843
Yifan Honga6b93f02017-09-13 16:53:37 -0700844 forEachTable([this] (Table& table) {
845 table.setSelectedColumns(this->mSelectedColumns);
Yifan Hongd4a77e82017-09-06 19:40:24 -0700846 });
847
Yifan Hong443df792017-05-09 18:49:45 -0700848 return OK;
849}
850
Yifan Honga8bedc62017-09-08 18:00:31 -0700851Status ListCommand::main(const Arg &arg) {
852 Status status = parseArgs(arg);
Yifan Hong443df792017-05-09 18:49:45 -0700853 if (status != OK) {
854 return status;
855 }
856 status = fetch();
857 postprocess();
Yifan Hongca3b6602017-09-07 16:44:27 -0700858 status |= dump();
Yifan Hong443df792017-05-09 18:49:45 -0700859 return status;
860}
861
Yifan Honga6b93f02017-09-13 16:53:37 -0700862static std::vector<std::string> splitString(const std::string &s, char c) {
863 std::vector<std::string> components;
864
865 size_t startPos = 0;
866 size_t matchPos;
867 while ((matchPos = s.find(c, startPos)) != std::string::npos) {
868 components.push_back(s.substr(startPos, matchPos - startPos));
869 startPos = matchPos + 1;
870 }
871
872 if (startPos <= s.length()) {
873 components.push_back(s.substr(startPos));
874 }
875 return components;
876}
877
878const std::string& ListCommand::RegisteredOption::getHelpMessageForArgument() const {
879 static const std::string empty{};
880 static const std::string optional{"[=<arg>]"};
881 static const std::string required{"=<arg>"};
882
883 if (hasArg == optional_argument) {
884 return optional;
885 }
886 if (hasArg == required_argument) {
887 return required;
888 }
889 return empty;
890}
891
Yifan Honga8bedc62017-09-08 18:00:31 -0700892void ListCommand::usage() const {
893
Yifan Honga6b93f02017-09-13 16:53:37 -0700894 err() << "list:" << std::endl
895 << " lshal" << std::endl
896 << " lshal list" << std::endl
Yifan Hongfee209d2017-09-14 18:23:38 -0700897 << " List all hals with default ordering and columns (`lshal list -riepc`)" << std::endl
Yifan Honga6b93f02017-09-13 16:53:37 -0700898 << " lshal list [-h|--help]" << std::endl
899 << " -h, --help: Print help message for list (`lshal help list`)" << std::endl
900 << " lshal [list] [OPTIONS...]" << std::endl;
901 for (const auto& e : mOptions) {
902 if (e.help.empty()) {
903 continue;
904 }
905 err() << " ";
906 if (e.shortOption != '\0')
907 err() << "-" << e.shortOption << e.getHelpMessageForArgument();
908 if (e.shortOption != '\0' && !e.longOption.empty())
909 err() << ", ";
910 if (!e.longOption.empty())
911 err() << "--" << e.longOption << e.getHelpMessageForArgument();
912 err() << ": ";
913 std::vector<std::string> lines = splitString(e.help, '\n');
914 for (const auto& line : lines) {
915 if (&line != &lines.front())
916 err() << " ";
917 err() << line << std::endl;
918 }
919 }
Yifan Honga8bedc62017-09-08 18:00:31 -0700920}
921
Yifan Hong443df792017-05-09 18:49:45 -0700922} // namespace lshal
923} // namespace android
Yifan Hong05494a52017-08-29 18:50:00 -0700924