blob: 38b406ce86e71a924cb4858f2abb65ed9a39de2e [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
47ListCommand::ListCommand(Lshal &lshal) : mLshal(lshal), mErr(lshal.err()), mOut(lshal.out()) {
48}
49
50std::string getCmdline(pid_t pid) {
51 std::ifstream ifs("/proc/" + std::to_string(pid) + "/cmdline");
52 std::string cmdline;
53 if (!ifs.is_open()) {
54 return "";
55 }
56 ifs >> cmdline;
57 return cmdline;
58}
59
60const std::string &ListCommand::getCmdline(pid_t pid) {
61 auto pair = mCmdlines.find(pid);
62 if (pair != mCmdlines.end()) {
63 return pair->second;
64 }
65 mCmdlines[pid] = ::android::lshal::getCmdline(pid);
66 return mCmdlines[pid];
67}
68
69void ListCommand::removeDeadProcesses(Pids *pids) {
70 static const pid_t myPid = getpid();
Yifan Hong61fb7bc2017-05-12 16:33:57 -070071 pids->erase(std::remove_if(pids->begin(), pids->end(), [this](auto pid) {
Yifan Hong443df792017-05-09 18:49:45 -070072 return pid == myPid || this->getCmdline(pid).empty();
Yifan Hong61fb7bc2017-05-12 16:33:57 -070073 }), pids->end());
Yifan Hong443df792017-05-09 18:49:45 -070074}
75
76bool ListCommand::getReferencedPids(
77 pid_t serverPid, std::map<uint64_t, Pids> *objects) const {
78
79 std::ifstream ifs("/d/binder/proc/" + std::to_string(serverPid));
80 if (!ifs.is_open()) {
81 return false;
82 }
83
84 static const std::regex prefix("^\\s*node \\d+:\\s+u([0-9a-f]+)\\s+c([0-9a-f]+)\\s+");
85
86 std::string line;
87 std::smatch match;
88 while(getline(ifs, line)) {
89 if (!std::regex_search(line, match, prefix)) {
90 // the line doesn't start with the correct prefix
91 continue;
92 }
93 std::string ptrString = "0x" + match.str(2); // use number after c
94 uint64_t ptr;
95 if (!::android::base::ParseUint(ptrString.c_str(), &ptr)) {
96 // Should not reach here, but just be tolerant.
97 mErr << "Could not parse number " << ptrString << std::endl;
98 continue;
99 }
100 const std::string proc = " proc ";
101 auto pos = line.rfind(proc);
102 if (pos != std::string::npos) {
103 for (const std::string &pidStr : split(line.substr(pos + proc.size()), ' ')) {
104 int32_t pid;
105 if (!::android::base::ParseInt(pidStr, &pid)) {
106 mErr << "Could not parse number " << pidStr << std::endl;
107 continue;
108 }
109 (*objects)[ptr].push_back(pid);
110 }
111 }
112 }
113 return true;
114}
115
116// Must process hwbinder services first, then passthrough services.
117void ListCommand::forEachTable(const std::function<void(Table &)> &f) {
118 f(mServicesTable);
119 f(mPassthroughRefTable);
120 f(mImplementationsTable);
121}
122void ListCommand::forEachTable(const std::function<void(const Table &)> &f) const {
123 f(mServicesTable);
124 f(mPassthroughRefTable);
125 f(mImplementationsTable);
126}
127
128void ListCommand::postprocess() {
129 forEachTable([this](Table &table) {
130 if (mSortColumn) {
131 std::sort(table.begin(), table.end(), mSortColumn);
132 }
133 for (TableEntry &entry : table) {
134 entry.serverCmdline = getCmdline(entry.serverPid);
135 removeDeadProcesses(&entry.clientPids);
136 for (auto pid : entry.clientPids) {
137 entry.clientCmdlines.push_back(this->getCmdline(pid));
138 }
139 }
140 });
141 // use a double for loop here because lshal doesn't care about efficiency.
142 for (TableEntry &packageEntry : mImplementationsTable) {
143 std::string packageName = packageEntry.interfaceName;
144 FQName fqPackageName{packageName.substr(0, packageName.find("::"))};
145 if (!fqPackageName.isValid()) {
146 continue;
147 }
148 for (TableEntry &interfaceEntry : mPassthroughRefTable) {
149 if (interfaceEntry.arch != ARCH_UNKNOWN) {
150 continue;
151 }
152 FQName interfaceName{splitFirst(interfaceEntry.interfaceName, '/').first};
153 if (!interfaceName.isValid()) {
154 continue;
155 }
156 if (interfaceName.getPackageAndVersion() == fqPackageName) {
157 interfaceEntry.arch = packageEntry.arch;
158 }
159 }
160 }
161}
162
163void ListCommand::printLine(
164 const std::string &interfaceName,
165 const std::string &transport,
166 const std::string &arch,
167 const std::string &server,
168 const std::string &serverCmdline,
169 const std::string &address, const std::string &clients,
170 const std::string &clientCmdlines) const {
171 if (mSelectedColumns & ENABLE_INTERFACE_NAME)
172 mOut << std::setw(80) << interfaceName << "\t";
173 if (mSelectedColumns & ENABLE_TRANSPORT)
174 mOut << std::setw(10) << transport << "\t";
175 if (mSelectedColumns & ENABLE_ARCH)
176 mOut << std::setw(5) << arch << "\t";
177 if (mSelectedColumns & ENABLE_SERVER_PID) {
178 if (mEnableCmdlines) {
179 mOut << std::setw(15) << serverCmdline << "\t";
180 } else {
181 mOut << std::setw(5) << server << "\t";
182 }
183 }
184 if (mSelectedColumns & ENABLE_SERVER_ADDR)
185 mOut << std::setw(16) << address << "\t";
186 if (mSelectedColumns & ENABLE_CLIENT_PIDS) {
187 if (mEnableCmdlines) {
188 mOut << std::setw(0) << clientCmdlines;
189 } else {
190 mOut << std::setw(0) << clients;
191 }
192 }
193 mOut << std::endl;
194}
195
196void ListCommand::dumpVintf() const {
197 mOut << "<!-- " << std::endl
198 << " This is a skeleton device manifest. Notes: " << std::endl
199 << " 1. android.hidl.*, android.frameworks.*, android.system.* are not included." << std::endl
200 << " 2. If a HAL is supported in both hwbinder and passthrough transport, " << std::endl
201 << " only hwbinder is shown." << std::endl
202 << " 3. It is likely that HALs in passthrough transport does not have" << std::endl
203 << " <interface> declared; users will have to write them by hand." << std::endl
204 << " 4. sepolicy version is set to 0.0. It is recommended that the entry" << std::endl
205 << " is removed from the manifest file and written by assemble_vintf" << std::endl
206 << " at build time." << std::endl
207 << "-->" << std::endl;
208
209 vintf::HalManifest manifest;
210 forEachTable([this, &manifest] (const Table &table) {
211 for (const TableEntry &entry : table) {
212
213 std::string fqInstanceName = entry.interfaceName;
214
215 if (&table == &mImplementationsTable) {
216 // Quick hack to work around *'s
217 replaceAll(&fqInstanceName, '*', 'D');
218 }
219 auto splittedFqInstanceName = splitFirst(fqInstanceName, '/');
220 FQName fqName(splittedFqInstanceName.first);
221 if (!fqName.isValid()) {
222 mErr << "Warning: '" << splittedFqInstanceName.first
223 << "' is not a valid FQName." << std::endl;
224 continue;
225 }
226 // Strip out system libs.
227 if (fqName.inPackage("android.hidl") ||
228 fqName.inPackage("android.frameworks") ||
229 fqName.inPackage("android.system")) {
230 continue;
231 }
232 std::string interfaceName =
233 &table == &mImplementationsTable ? "" : fqName.name();
234 std::string instanceName =
235 &table == &mImplementationsTable ? "" : splittedFqInstanceName.second;
236
237 vintf::Version version{fqName.getPackageMajorVersion(),
238 fqName.getPackageMinorVersion()};
239 vintf::Transport transport;
240 vintf::Arch arch;
241 if (entry.transport == "hwbinder") {
242 transport = vintf::Transport::HWBINDER;
243 arch = vintf::Arch::ARCH_EMPTY;
244 } else if (entry.transport == "passthrough") {
245 transport = vintf::Transport::PASSTHROUGH;
246 switch (entry.arch) {
247 case lshal::ARCH32:
248 arch = vintf::Arch::ARCH_32; break;
249 case lshal::ARCH64:
250 arch = vintf::Arch::ARCH_64; break;
251 case lshal::ARCH_BOTH:
252 arch = vintf::Arch::ARCH_32_64; break;
253 case lshal::ARCH_UNKNOWN: // fallthrough
254 default:
255 mErr << "Warning: '" << fqName.package()
256 << "' doesn't have bitness info, assuming 32+64." << std::endl;
257 arch = vintf::Arch::ARCH_32_64;
258 }
259 } else {
260 mErr << "Warning: '" << entry.transport << "' is not a valid transport." << std::endl;
261 continue;
262 }
263
264 bool done = false;
265 for (vintf::ManifestHal *hal : manifest.getHals(fqName.package())) {
266 if (hal->transport() != transport) {
267 if (transport != vintf::Transport::PASSTHROUGH) {
268 mErr << "Fatal: should not reach here. Generated result may be wrong."
269 << std::endl;
270 }
271 done = true;
272 break;
273 }
274 if (hal->hasVersion(version)) {
275 if (&table != &mImplementationsTable) {
276 hal->interfaces[interfaceName].name = interfaceName;
277 hal->interfaces[interfaceName].instances.insert(instanceName);
278 }
279 done = true;
280 break;
281 }
282 }
283 if (done) {
284 continue; // to next TableEntry
285 }
286 decltype(vintf::ManifestHal::interfaces) interfaces;
287 if (&table != &mImplementationsTable) {
288 interfaces[interfaceName].name = interfaceName;
289 interfaces[interfaceName].instances.insert(instanceName);
290 }
291 if (!manifest.add(vintf::ManifestHal{
292 .format = vintf::HalFormat::HIDL,
293 .name = fqName.package(),
294 .versions = {version},
295 .transportArch = {transport, arch},
296 .interfaces = interfaces})) {
297 mErr << "Warning: cannot add hal '" << fqInstanceName << "'" << std::endl;
298 }
299 }
300 });
301 mOut << vintf::gHalManifestConverter(manifest);
302}
303
304static const std::string &getArchString(Architecture arch) {
305 static const std::string sStr64 = "64";
306 static const std::string sStr32 = "32";
307 static const std::string sStrBoth = "32+64";
308 static const std::string sStrUnknown = "";
309 switch (arch) {
310 case ARCH64:
311 return sStr64;
312 case ARCH32:
313 return sStr32;
314 case ARCH_BOTH:
315 return sStrBoth;
316 case ARCH_UNKNOWN: // fall through
317 default:
318 return sStrUnknown;
319 }
320}
321
322static Architecture fromBaseArchitecture(::android::hidl::base::V1_0::DebugInfo::Architecture a) {
323 switch (a) {
324 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_64BIT:
325 return ARCH64;
326 case ::android::hidl::base::V1_0::DebugInfo::Architecture::IS_32BIT:
327 return ARCH32;
328 case ::android::hidl::base::V1_0::DebugInfo::Architecture::UNKNOWN: // fallthrough
329 default:
330 return ARCH_UNKNOWN;
331 }
332}
333
334void ListCommand::dumpTable() {
335 mServicesTable.description =
336 "All binderized services (registered services through hwservicemanager)";
337 mPassthroughRefTable.description =
338 "All interfaces that getService() has ever return as a passthrough interface;\n"
339 "PIDs / processes shown below might be inaccurate because the process\n"
340 "might have relinquished the interface or might have died.\n"
341 "The Server / Server CMD column can be ignored.\n"
342 "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
343 "the library and successfully fetched the passthrough implementation.";
344 mImplementationsTable.description =
345 "All available passthrough implementations (all -impl.so files)";
346 forEachTable([this] (const Table &table) {
Yifan Hong6da06912017-05-12 16:56:43 -0700347 if (!mNeat) {
348 mOut << table.description << std::endl;
349 }
Yifan Hong443df792017-05-09 18:49:45 -0700350 mOut << std::left;
Yifan Hong6da06912017-05-12 16:56:43 -0700351 if (!mNeat) {
352 printLine("Interface", "Transport", "Arch", "Server", "Server CMD",
353 "PTR", "Clients", "Clients CMD");
354 }
Yifan Hong443df792017-05-09 18:49:45 -0700355
Yifan Hong443df792017-05-09 18:49:45 -0700356 for (const auto &entry : table) {
357 printLine(entry.interfaceName,
358 entry.transport,
359 getArchString(entry.arch),
360 entry.serverPid == NO_PID ? "N/A" : std::to_string(entry.serverPid),
361 entry.serverCmdline,
362 entry.serverObjectAddress == NO_PTR ? "N/A" : toHexString(entry.serverObjectAddress),
363 join(entry.clientPids, " "),
364 join(entry.clientCmdlines, ";"));
365
Yifan Hong48dc9f82017-05-09 19:33:08 -0700366 // We're only interested in dumping debug info for already
367 // instantiated services. There's little value in dumping the
368 // debug info for a service we create on the fly, so we only operate
369 // on the "mServicesTable".
370 if (mEmitDebugInfo && &table == &mServicesTable) {
Yifan Hong443df792017-05-09 18:49:45 -0700371 auto pair = splitFirst(entry.interfaceName, '/');
Yifan Hong48dc9f82017-05-09 19:33:08 -0700372 mLshal.emitDebugInfo(pair.first, pair.second, {}, mOut.buf(),
373 NullableOStream<std::ostream>(nullptr));
Yifan Hong443df792017-05-09 18:49:45 -0700374 }
375 }
Yifan Hong6da06912017-05-12 16:56:43 -0700376 if (!mNeat) {
377 mOut << std::endl;
378 }
Yifan Hong443df792017-05-09 18:49:45 -0700379 });
380
381}
382
383void ListCommand::dump() {
384 if (mVintf) {
385 dumpVintf();
386 if (!!mFileOutput) {
387 mFileOutput.buf().close();
388 delete &mFileOutput.buf();
389 mFileOutput = nullptr;
390 }
391 mOut = std::cout;
392 } else {
393 dumpTable();
394 }
395}
396
397void ListCommand::putEntry(TableEntrySource source, TableEntry &&entry) {
398 Table *table = nullptr;
399 switch (source) {
400 case HWSERVICEMANAGER_LIST :
401 table = &mServicesTable; break;
402 case PTSERVICEMANAGER_REG_CLIENT :
403 table = &mPassthroughRefTable; break;
404 case LIST_DLLIB :
405 table = &mImplementationsTable; break;
406 default:
407 mErr << "Error: Unknown source of entry " << source << std::endl;
408 }
409 if (table) {
410 table->entries.push_back(std::forward<TableEntry>(entry));
411 }
412}
413
414Status ListCommand::fetchAllLibraries(const sp<IServiceManager> &manager) {
415 using namespace ::android::hardware;
416 using namespace ::android::hidl::manager::V1_0;
417 using namespace ::android::hidl::base::V1_0;
418 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
419 std::map<std::string, TableEntry> entries;
420 for (const auto &info : infos) {
421 std::string interfaceName = std::string{info.interfaceName.c_str()} + "/" +
422 std::string{info.instanceName.c_str()};
423 entries.emplace(interfaceName, TableEntry{
424 .interfaceName = interfaceName,
425 .transport = "passthrough",
426 .serverPid = NO_PID,
427 .serverObjectAddress = NO_PTR,
428 .clientPids = {},
429 .arch = ARCH_UNKNOWN
430 }).first->second.arch |= fromBaseArchitecture(info.arch);
431 }
432 for (auto &&pair : entries) {
433 putEntry(LIST_DLLIB, std::move(pair.second));
434 }
435 });
436 if (!ret.isOk()) {
437 mErr << "Error: Failed to call list on getPassthroughServiceManager(): "
438 << ret.description() << std::endl;
439 return DUMP_ALL_LIBS_ERROR;
440 }
441 return OK;
442}
443
444Status ListCommand::fetchPassthrough(const sp<IServiceManager> &manager) {
445 using namespace ::android::hardware;
446 using namespace ::android::hardware::details;
447 using namespace ::android::hidl::manager::V1_0;
448 using namespace ::android::hidl::base::V1_0;
449 auto ret = timeoutIPC(manager, &IServiceManager::debugDump, [&] (const auto &infos) {
450 for (const auto &info : infos) {
451 if (info.clientPids.size() <= 0) {
452 continue;
453 }
454 putEntry(PTSERVICEMANAGER_REG_CLIENT, {
455 .interfaceName =
456 std::string{info.interfaceName.c_str()} + "/" +
457 std::string{info.instanceName.c_str()},
458 .transport = "passthrough",
459 .serverPid = info.clientPids.size() == 1 ? info.clientPids[0] : NO_PID,
460 .serverObjectAddress = NO_PTR,
461 .clientPids = info.clientPids,
462 .arch = fromBaseArchitecture(info.arch)
463 });
464 }
465 });
466 if (!ret.isOk()) {
467 mErr << "Error: Failed to call debugDump on defaultServiceManager(): "
468 << ret.description() << std::endl;
469 return DUMP_PASSTHROUGH_ERROR;
470 }
471 return OK;
472}
473
474Status ListCommand::fetchBinderized(const sp<IServiceManager> &manager) {
475 using namespace ::std;
476 using namespace ::android::hardware;
477 using namespace ::android::hidl::manager::V1_0;
478 using namespace ::android::hidl::base::V1_0;
479 const std::string mode = "hwbinder";
480
481 hidl_vec<hidl_string> fqInstanceNames;
482 // copying out for timeoutIPC
483 auto listRet = timeoutIPC(manager, &IServiceManager::list, [&] (const auto &names) {
484 fqInstanceNames = names;
485 });
486 if (!listRet.isOk()) {
487 mErr << "Error: Failed to list services for " << mode << ": "
488 << listRet.description() << std::endl;
489 return DUMP_BINDERIZED_ERROR;
490 }
491
492 Status status = OK;
493 // server pid, .ptr value of binder object, child pids
494 std::map<std::string, DebugInfo> allDebugInfos;
495 std::map<pid_t, std::map<uint64_t, Pids>> allPids;
496 for (const auto &fqInstanceName : fqInstanceNames) {
497 const auto pair = splitFirst(fqInstanceName, '/');
498 const auto &serviceName = pair.first;
499 const auto &instanceName = pair.second;
500 auto getRet = timeoutIPC(manager, &IServiceManager::get, serviceName, instanceName);
501 if (!getRet.isOk()) {
502 mErr << "Warning: Skipping \"" << fqInstanceName << "\": "
503 << "cannot be fetched from service manager:"
504 << getRet.description() << std::endl;
505 status |= DUMP_BINDERIZED_ERROR;
506 continue;
507 }
508 sp<IBase> service = getRet;
509 if (service == nullptr) {
510 mErr << "Warning: Skipping \"" << fqInstanceName << "\": "
511 << "cannot be fetched from service manager (null)"
512 << std::endl;
513 status |= DUMP_BINDERIZED_ERROR;
514 continue;
515 }
516 auto debugRet = timeoutIPC(service, &IBase::getDebugInfo, [&] (const auto &debugInfo) {
517 allDebugInfos[fqInstanceName] = debugInfo;
518 if (debugInfo.pid >= 0) {
519 allPids[static_cast<pid_t>(debugInfo.pid)].clear();
520 }
521 });
522 if (!debugRet.isOk()) {
523 mErr << "Warning: Skipping \"" << fqInstanceName << "\": "
524 << "debugging information cannot be retrieved:"
525 << debugRet.description() << std::endl;
526 status |= DUMP_BINDERIZED_ERROR;
527 }
528 }
529 for (auto &pair : allPids) {
530 pid_t serverPid = pair.first;
531 if (!getReferencedPids(serverPid, &allPids[serverPid])) {
532 mErr << "Warning: no information for PID " << serverPid
533 << ", are you root?" << std::endl;
534 status |= DUMP_BINDERIZED_ERROR;
535 }
536 }
537 for (const auto &fqInstanceName : fqInstanceNames) {
538 auto it = allDebugInfos.find(fqInstanceName);
539 if (it == allDebugInfos.end()) {
540 putEntry(HWSERVICEMANAGER_LIST, {
541 .interfaceName = fqInstanceName,
542 .transport = mode,
543 .serverPid = NO_PID,
544 .serverObjectAddress = NO_PTR,
545 .clientPids = {},
546 .arch = ARCH_UNKNOWN
547 });
548 continue;
549 }
550 const DebugInfo &info = it->second;
551 putEntry(HWSERVICEMANAGER_LIST, {
552 .interfaceName = fqInstanceName,
553 .transport = mode,
554 .serverPid = info.pid,
555 .serverObjectAddress = info.ptr,
556 .clientPids = info.pid == NO_PID || info.ptr == NO_PTR
557 ? Pids{} : allPids[info.pid][info.ptr],
558 .arch = fromBaseArchitecture(info.arch),
559 });
560 }
561 return status;
562}
563
564Status ListCommand::fetch() {
565 Status status = OK;
Yifan Hong9881df92017-05-10 14:33:05 -0700566 auto bManager = mLshal.serviceManager();
Yifan Hong443df792017-05-09 18:49:45 -0700567 if (bManager == nullptr) {
568 mErr << "Failed to get defaultServiceManager()!" << std::endl;
569 status |= NO_BINDERIZED_MANAGER;
570 } else {
571 status |= fetchBinderized(bManager);
572 // Passthrough PIDs are registered to the binderized manager as well.
573 status |= fetchPassthrough(bManager);
574 }
575
Yifan Hong9881df92017-05-10 14:33:05 -0700576 auto pManager = mLshal.passthroughManager();
Yifan Hong443df792017-05-09 18:49:45 -0700577 if (pManager == nullptr) {
578 mErr << "Failed to get getPassthroughServiceManager()!" << std::endl;
579 status |= NO_PASSTHROUGH_MANAGER;
580 } else {
581 status |= fetchAllLibraries(pManager);
582 }
583 return status;
584}
585
586Status ListCommand::parseArgs(const std::string &command, const Arg &arg) {
587 static struct option longOptions[] = {
588 // long options with short alternatives
589 {"help", no_argument, 0, 'h' },
590 {"interface", no_argument, 0, 'i' },
591 {"transport", no_argument, 0, 't' },
592 {"arch", no_argument, 0, 'r' },
593 {"pid", no_argument, 0, 'p' },
594 {"address", no_argument, 0, 'a' },
595 {"clients", no_argument, 0, 'c' },
596 {"cmdline", no_argument, 0, 'm' },
597 {"debug", optional_argument, 0, 'd' },
598
599 // long options without short alternatives
600 {"sort", required_argument, 0, 's' },
601 {"init-vintf",optional_argument, 0, 'v' },
Yifan Hong6da06912017-05-12 16:56:43 -0700602 {"neat", no_argument, 0, 'n' },
Yifan Hong443df792017-05-09 18:49:45 -0700603 { 0, 0, 0, 0 }
604 };
605
606 int optionIndex;
607 int c;
608 // Lshal::parseArgs has set optind to the next option to parse
609 for (;;) {
610 // using getopt_long in case we want to add other options in the future
611 c = getopt_long(arg.argc, arg.argv,
612 "hitrpacmd", longOptions, &optionIndex);
613 if (c == -1) {
614 break;
615 }
616 switch (c) {
617 case 's': {
618 if (strcmp(optarg, "interface") == 0 || strcmp(optarg, "i") == 0) {
619 mSortColumn = TableEntry::sortByInterfaceName;
620 } else if (strcmp(optarg, "pid") == 0 || strcmp(optarg, "p") == 0) {
621 mSortColumn = TableEntry::sortByServerPid;
622 } else {
623 mErr << "Unrecognized sorting column: " << optarg << std::endl;
624 mLshal.usage(command);
625 return USAGE;
626 }
627 break;
628 }
629 case 'v': {
630 if (optarg) {
631 mFileOutput = new std::ofstream{optarg};
632 mOut = mFileOutput;
633 if (!mFileOutput.buf().is_open()) {
634 mErr << "Could not open file '" << optarg << "'." << std::endl;
635 return IO_ERROR;
636 }
637 }
638 mVintf = true;
639 }
640 case 'i': {
641 mSelectedColumns |= ENABLE_INTERFACE_NAME;
642 break;
643 }
644 case 't': {
645 mSelectedColumns |= ENABLE_TRANSPORT;
646 break;
647 }
648 case 'r': {
649 mSelectedColumns |= ENABLE_ARCH;
650 break;
651 }
652 case 'p': {
653 mSelectedColumns |= ENABLE_SERVER_PID;
654 break;
655 }
656 case 'a': {
657 mSelectedColumns |= ENABLE_SERVER_ADDR;
658 break;
659 }
660 case 'c': {
661 mSelectedColumns |= ENABLE_CLIENT_PIDS;
662 break;
663 }
664 case 'm': {
665 mEnableCmdlines = true;
666 break;
667 }
668 case 'd': {
669 mEmitDebugInfo = true;
670
671 if (optarg) {
672 mFileOutput = new std::ofstream{optarg};
673 mOut = mFileOutput;
674 if (!mFileOutput.buf().is_open()) {
675 mErr << "Could not open file '" << optarg << "'." << std::endl;
676 return IO_ERROR;
677 }
678 chown(optarg, AID_SHELL, AID_SHELL);
679 }
680 break;
681 }
Yifan Hong6da06912017-05-12 16:56:43 -0700682 case 'n': {
683 mNeat = true;
684 break;
685 }
Yifan Hong443df792017-05-09 18:49:45 -0700686 case 'h': // falls through
687 default: // see unrecognized options
688 mLshal.usage(command);
689 return USAGE;
690 }
691 }
692 if (optind < arg.argc) {
693 // see non option
694 mErr << "Unrecognized option `" << arg.argv[optind] << "`" << std::endl;
695 }
696
697 if (mSelectedColumns == 0) {
698 mSelectedColumns = ENABLE_INTERFACE_NAME | ENABLE_SERVER_PID | ENABLE_CLIENT_PIDS;
699 }
700 return OK;
701}
702
703Status ListCommand::main(const std::string &command, const Arg &arg) {
704 Status status = parseArgs(command, arg);
705 if (status != OK) {
706 return status;
707 }
708 status = fetch();
709 postprocess();
710 dump();
711 return status;
712}
713
714} // namespace lshal
715} // namespace android
716