• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 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 <algorithm>
18 #include <chrono>
19 #include <iomanip>
20 #include <thread>
21 
22 #include <android-base/file.h>
23 #include <android-base/stringprintf.h>
24 #include <android-base/unique_fd.h>
25 #include <binder/Parcel.h>
26 #include <binder/ProcessState.h>
27 #include <binder/TextOutput.h>
28 #include <binderdebug/BinderDebug.h>
29 #include <serviceutils/PriorityDumper.h>
30 #include <utils/Log.h>
31 #include <utils/Vector.h>
32 
33 #include <iostream>
34 #include <fcntl.h>
35 #include <getopt.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <sys/poll.h>
40 #include <sys/socket.h>
41 #include <sys/time.h>
42 #include <sys/types.h>
43 #include <unistd.h>
44 
45 #include "dumpsys.h"
46 
47 using namespace android;
48 using ::android::base::StringAppendF;
49 using ::android::base::StringPrintf;
50 using ::android::base::unique_fd;
51 using ::android::base::WriteFully;
52 using ::android::base::WriteStringToFd;
53 
sort_func(const String16 * lhs,const String16 * rhs)54 static int sort_func(const String16* lhs, const String16* rhs)
55 {
56     return lhs->compare(*rhs);
57 }
58 
usage()59 static void usage() {
60     fprintf(stderr,
61             "usage: dumpsys\n"
62             "         To dump all services.\n"
63             "or:\n"
64             "       dumpsys [-t TIMEOUT] [--priority LEVEL] [--pid] [--thread] [--help | -l | "
65             "--skip SERVICES "
66             "| SERVICE [ARGS]]\n"
67             "         --help: shows this help\n"
68             "         -l: only list services, do not dump them\n"
69             "         -t TIMEOUT_SEC: TIMEOUT to use in seconds instead of default 10 seconds\n"
70             "         -T TIMEOUT_MS: TIMEOUT to use in milliseconds instead of default 10 seconds\n"
71             "         --pid: dump PID instead of usual dump\n"
72             "         --thread: dump thread usage instead of usual dump\n"
73             "         --proto: filter services that support dumping data in proto format. Dumps\n"
74             "               will be in proto format.\n"
75             "         --priority LEVEL: filter services based on specified priority\n"
76             "               LEVEL must be one of CRITICAL | HIGH | NORMAL\n"
77             "         --skip SERVICES: dumps all services but SERVICES (comma-separated list)\n"
78             "         SERVICE [ARGS]: dumps only service SERVICE, optionally passing ARGS to it\n");
79 }
80 
IsSkipped(const Vector<String16> & skipped,const String16 & service)81 static bool IsSkipped(const Vector<String16>& skipped, const String16& service) {
82     for (const auto& candidate : skipped) {
83         if (candidate == service) {
84             return true;
85         }
86     }
87     return false;
88 }
89 
ConvertPriorityTypeToBitmask(const String16 & type,int & bitmask)90 static bool ConvertPriorityTypeToBitmask(const String16& type, int& bitmask) {
91     if (type == PriorityDumper::PRIORITY_ARG_CRITICAL) {
92         bitmask = IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL;
93         return true;
94     }
95     if (type == PriorityDumper::PRIORITY_ARG_HIGH) {
96         bitmask = IServiceManager::DUMP_FLAG_PRIORITY_HIGH;
97         return true;
98     }
99     if (type == PriorityDumper::PRIORITY_ARG_NORMAL) {
100         bitmask = IServiceManager::DUMP_FLAG_PRIORITY_NORMAL;
101         return true;
102     }
103     return false;
104 }
105 
ConvertBitmaskToPriorityType(int bitmask)106 String16 ConvertBitmaskToPriorityType(int bitmask) {
107     if (bitmask == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL) {
108         return String16(PriorityDumper::PRIORITY_ARG_CRITICAL);
109     }
110     if (bitmask == IServiceManager::DUMP_FLAG_PRIORITY_HIGH) {
111         return String16(PriorityDumper::PRIORITY_ARG_HIGH);
112     }
113     if (bitmask == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL) {
114         return String16(PriorityDumper::PRIORITY_ARG_NORMAL);
115     }
116     return String16("");
117 }
118 
main(int argc,char * const argv[])119 int Dumpsys::main(int argc, char* const argv[]) {
120     Vector<String16> services;
121     Vector<String16> args;
122     String16 priorityType;
123     Vector<String16> skippedServices;
124     Vector<String16> protoServices;
125     bool showListOnly = false;
126     bool skipServices = false;
127     bool asProto = false;
128     Type type = Type::DUMP;
129     int timeoutArgMs = 10000;
130     int priorityFlags = IServiceManager::DUMP_FLAG_PRIORITY_ALL;
131     static struct option longOptions[] = {{"thread", no_argument, 0, 0},
132                                           {"pid", no_argument, 0, 0},
133                                           {"priority", required_argument, 0, 0},
134                                           {"proto", no_argument, 0, 0},
135                                           {"skip", no_argument, 0, 0},
136                                           {"help", no_argument, 0, 0},
137                                           {0, 0, 0, 0}};
138 
139     // Must reset optind, otherwise subsequent calls will fail (wouldn't happen on main.cpp, but
140     // happens on test cases).
141     optind = 1;
142     while (1) {
143         int c;
144         int optionIndex = 0;
145 
146         c = getopt_long(argc, argv, "+t:T:l", longOptions, &optionIndex);
147 
148         if (c == -1) {
149             break;
150         }
151 
152         switch (c) {
153         case 0:
154             if (!strcmp(longOptions[optionIndex].name, "skip")) {
155                 skipServices = true;
156             } else if (!strcmp(longOptions[optionIndex].name, "proto")) {
157                 asProto = true;
158             } else if (!strcmp(longOptions[optionIndex].name, "help")) {
159                 usage();
160                 return 0;
161             } else if (!strcmp(longOptions[optionIndex].name, "priority")) {
162                 priorityType = String16(String8(optarg));
163                 if (!ConvertPriorityTypeToBitmask(priorityType, priorityFlags)) {
164                     fprintf(stderr, "\n");
165                     usage();
166                     return -1;
167                 }
168             } else if (!strcmp(longOptions[optionIndex].name, "pid")) {
169                 type = Type::PID;
170             } else if (!strcmp(longOptions[optionIndex].name, "thread")) {
171                 type = Type::THREAD;
172             }
173             break;
174 
175         case 't':
176             {
177                 char* endptr;
178                 timeoutArgMs = strtol(optarg, &endptr, 10);
179                 timeoutArgMs = timeoutArgMs * 1000;
180                 if (*endptr != '\0' || timeoutArgMs <= 0) {
181                     fprintf(stderr, "Error: invalid timeout(seconds) number: '%s'\n", optarg);
182                     return -1;
183                 }
184             }
185             break;
186 
187         case 'T':
188             {
189                 char* endptr;
190                 timeoutArgMs = strtol(optarg, &endptr, 10);
191                 if (*endptr != '\0' || timeoutArgMs <= 0) {
192                     fprintf(stderr, "Error: invalid timeout(milliseconds) number: '%s'\n", optarg);
193                     return -1;
194                 }
195             }
196             break;
197 
198         case 'l':
199             showListOnly = true;
200             break;
201 
202         default:
203             fprintf(stderr, "\n");
204             usage();
205             return -1;
206         }
207     }
208 
209     for (int i = optind; i < argc; i++) {
210         if (skipServices) {
211             skippedServices.add(String16(argv[i]));
212         } else {
213             if (i == optind) {
214                 services.add(String16(argv[i]));
215             } else {
216                 const String16 arg(argv[i]);
217                 args.add(arg);
218                 // For backward compatible, if the proto argument is passed to the service, the
219                 // dump request is also considered to use proto.
220                 if (!asProto && !arg.compare(String16(PriorityDumper::PROTO_ARG))) {
221                     asProto = true;
222                 }
223             }
224         }
225     }
226 
227     if ((skipServices && skippedServices.empty()) ||
228             (showListOnly && (!services.empty() || !skippedServices.empty()))) {
229         usage();
230         return -1;
231     }
232 
233     if (services.empty() || showListOnly) {
234         services = listServices(priorityFlags, asProto);
235         setServiceArgs(args, asProto, priorityFlags);
236     }
237 
238     const size_t N = services.size();
239     if (N > 1 || showListOnly) {
240         // first print a list of the current services
241         std::cout << "Currently running services:" << std::endl;
242 
243         for (size_t i=0; i<N; i++) {
244             sp<IBinder> service = sm_->checkService(services[i]);
245 
246             if (service != nullptr) {
247                 bool skipped = IsSkipped(skippedServices, services[i]);
248                 std::cout << "  " << services[i] << (skipped ? " (skipped)" : "") << std::endl;
249             }
250         }
251     }
252 
253     if (showListOnly) {
254         return 0;
255     }
256 
257     for (size_t i = 0; i < N; i++) {
258         const String16& serviceName = services[i];
259         if (IsSkipped(skippedServices, serviceName)) continue;
260 
261         if (startDumpThread(type, serviceName, args) == OK) {
262             bool addSeparator = (N > 1);
263             if (addSeparator) {
264                 writeDumpHeader(STDOUT_FILENO, serviceName, priorityFlags);
265             }
266             std::chrono::duration<double> elapsedDuration;
267             size_t bytesWritten = 0;
268             status_t status =
269                 writeDump(STDOUT_FILENO, serviceName, std::chrono::milliseconds(timeoutArgMs),
270                           asProto, elapsedDuration, bytesWritten);
271 
272             if (status == TIMED_OUT) {
273                 std::cout << std::endl
274                      << "*** SERVICE '" << serviceName << "' DUMP TIMEOUT (" << timeoutArgMs
275                      << "ms) EXPIRED ***" << std::endl
276                      << std::endl;
277             }
278 
279             if (addSeparator) {
280                 writeDumpFooter(STDOUT_FILENO, serviceName, elapsedDuration);
281             }
282             bool dumpComplete = (status == OK);
283             stopDumpThread(dumpComplete);
284         }
285     }
286 
287     return 0;
288 }
289 
listServices(int priorityFilterFlags,bool filterByProto) const290 Vector<String16> Dumpsys::listServices(int priorityFilterFlags, bool filterByProto) const {
291     Vector<String16> services = sm_->listServices(priorityFilterFlags);
292     services.sort(sort_func);
293     if (filterByProto) {
294         Vector<String16> protoServices = sm_->listServices(IServiceManager::DUMP_FLAG_PROTO);
295         protoServices.sort(sort_func);
296         Vector<String16> intersection;
297         std::set_intersection(services.begin(), services.end(), protoServices.begin(),
298                               protoServices.end(), std::back_inserter(intersection));
299         services = std::move(intersection);
300     }
301     return services;
302 }
303 
setServiceArgs(Vector<String16> & args,bool asProto,int priorityFlags)304 void Dumpsys::setServiceArgs(Vector<String16>& args, bool asProto, int priorityFlags) {
305     // Add proto flag if dumping service as proto.
306     if (asProto) {
307         args.insertAt(String16(PriorityDumper::PROTO_ARG), 0);
308     }
309 
310     // Add -a (dump all) flag if dumping all services, dumping normal services or
311     // services not explicitly registered to a priority bucket (default services).
312     if ((priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_ALL) ||
313         (priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL) ||
314         (priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT)) {
315         args.insertAt(String16("-a"), 0);
316     }
317 
318     // Add priority flags when dumping services registered to a specific priority bucket.
319     if ((priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL) ||
320         (priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_HIGH) ||
321         (priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL)) {
322         String16 priorityType = ConvertBitmaskToPriorityType(priorityFlags);
323         args.insertAt(String16(PriorityDumper::PRIORITY_ARG), 0);
324         args.insertAt(priorityType, 1);
325     }
326 }
327 
dumpPidToFd(const sp<IBinder> & service,const unique_fd & fd)328 static status_t dumpPidToFd(const sp<IBinder>& service, const unique_fd& fd) {
329      pid_t pid;
330      status_t status = service->getDebugPid(&pid);
331      if (status != OK) {
332          return status;
333      }
334      WriteStringToFd(std::to_string(pid) + "\n", fd.get());
335      return OK;
336 }
337 
dumpThreadsToFd(const sp<IBinder> & service,const unique_fd & fd)338 static status_t dumpThreadsToFd(const sp<IBinder>& service, const unique_fd& fd) {
339     pid_t pid;
340     status_t status = service->getDebugPid(&pid);
341     if (status != OK) {
342         return status;
343     }
344     BinderPidInfo pidInfo;
345     status = getBinderPidInfo(BinderDebugContext::BINDER, pid, &pidInfo);
346     if (status != OK) {
347         return status;
348     }
349     WriteStringToFd("Threads in use: " + std::to_string(pidInfo.threadUsage) + "/" +
350                         std::to_string(pidInfo.threadCount) + "\n",
351                     fd.get());
352     return OK;
353 }
354 
startDumpThread(Type type,const String16 & serviceName,const Vector<String16> & args)355 status_t Dumpsys::startDumpThread(Type type, const String16& serviceName,
356                                   const Vector<String16>& args) {
357     sp<IBinder> service = sm_->checkService(serviceName);
358     if (service == nullptr) {
359         std::cerr << "Can't find service: " << serviceName << std::endl;
360         return NAME_NOT_FOUND;
361     }
362 
363     int sfd[2];
364     if (pipe(sfd) != 0) {
365         std::cerr << "Failed to create pipe to dump service info for " << serviceName << ": "
366              << strerror(errno) << std::endl;
367         return -errno;
368     }
369 
370     redirectFd_ = unique_fd(sfd[0]);
371     unique_fd remote_end(sfd[1]);
372     sfd[0] = sfd[1] = -1;
373 
374     // dump blocks until completion, so spawn a thread..
375     activeThread_ = std::thread([=, remote_end{std::move(remote_end)}]() mutable {
376         status_t err = 0;
377 
378         switch (type) {
379         case Type::DUMP:
380             err = service->dump(remote_end.get(), args);
381             break;
382         case Type::PID:
383             err = dumpPidToFd(service, remote_end);
384             break;
385         case Type::THREAD:
386             err = dumpThreadsToFd(service, remote_end);
387             break;
388         default:
389             std::cerr << "Unknown dump type" << static_cast<int>(type) << std::endl;
390             return;
391         }
392 
393         if (err != OK) {
394             std::cerr << "Error dumping service info status_t: " << statusToString(err) << " "
395                  << serviceName << std::endl;
396         }
397     });
398     return OK;
399 }
400 
stopDumpThread(bool dumpComplete)401 void Dumpsys::stopDumpThread(bool dumpComplete) {
402     if (dumpComplete) {
403         activeThread_.join();
404     } else {
405         activeThread_.detach();
406     }
407     /* close read end of the dump output redirection pipe */
408     redirectFd_.reset();
409 }
410 
writeDumpHeader(int fd,const String16 & serviceName,int priorityFlags) const411 void Dumpsys::writeDumpHeader(int fd, const String16& serviceName, int priorityFlags) const {
412     std::string msg(
413         "----------------------------------------"
414         "---------------------------------------\n");
415     if (priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_ALL ||
416         priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL ||
417         priorityFlags == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT) {
418         StringAppendF(&msg, "DUMP OF SERVICE %s:\n", String8(serviceName).c_str());
419     } else {
420         String16 priorityType = ConvertBitmaskToPriorityType(priorityFlags);
421         StringAppendF(&msg, "DUMP OF SERVICE %s %s:\n", String8(priorityType).c_str(),
422                       String8(serviceName).c_str());
423     }
424     WriteStringToFd(msg, fd);
425 }
426 
writeDump(int fd,const String16 & serviceName,std::chrono::milliseconds timeout,bool asProto,std::chrono::duration<double> & elapsedDuration,size_t & bytesWritten) const427 status_t Dumpsys::writeDump(int fd, const String16& serviceName, std::chrono::milliseconds timeout,
428                             bool asProto, std::chrono::duration<double>& elapsedDuration,
429                             size_t& bytesWritten) const {
430     status_t status = OK;
431     size_t totalBytes = 0;
432     auto start = std::chrono::steady_clock::now();
433     auto end = start + timeout;
434 
435     int serviceDumpFd = redirectFd_.get();
436     if (serviceDumpFd == -1) {
437         return INVALID_OPERATION;
438     }
439 
440     struct pollfd pfd = {.fd = serviceDumpFd, .events = POLLIN};
441 
442     while (true) {
443         // Wrap this in a lambda so that TEMP_FAILURE_RETRY recalculates the timeout.
444         auto time_left_ms = [end]() {
445             auto now = std::chrono::steady_clock::now();
446             auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end - now);
447             return std::max(diff.count(), 0LL);
448         };
449 
450         int rc = TEMP_FAILURE_RETRY(poll(&pfd, 1, time_left_ms()));
451         if (rc < 0) {
452             std::cerr << "Error in poll while dumping service " << serviceName << " : "
453                  << strerror(errno) << std::endl;
454             status = -errno;
455             break;
456         } else if (rc == 0 || time_left_ms() == 0) {
457             status = TIMED_OUT;
458             break;
459         }
460 
461         char buf[4096];
462         rc = TEMP_FAILURE_RETRY(read(redirectFd_.get(), buf, sizeof(buf)));
463         if (rc < 0) {
464             std::cerr << "Failed to read while dumping service " << serviceName << ": "
465                  << strerror(errno) << std::endl;
466             status = -errno;
467             break;
468         } else if (rc == 0) {
469             // EOF.
470             break;
471         }
472 
473         if (!WriteFully(fd, buf, rc)) {
474             std::cerr << "Failed to write while dumping service " << serviceName << ": "
475                  << strerror(errno) << std::endl;
476             status = -errno;
477             break;
478         }
479         totalBytes += rc;
480     }
481 
482     if ((status == TIMED_OUT) && (!asProto)) {
483         std::string msg = StringPrintf("\n*** SERVICE '%s' DUMP TIMEOUT (%llums) EXPIRED ***\n\n",
484                                        String8(serviceName).string(), timeout.count());
485         WriteStringToFd(msg, fd);
486     }
487 
488     elapsedDuration = std::chrono::steady_clock::now() - start;
489     bytesWritten = totalBytes;
490     return status;
491 }
492 
writeDumpFooter(int fd,const String16 & serviceName,const std::chrono::duration<double> & elapsedDuration) const493 void Dumpsys::writeDumpFooter(int fd, const String16& serviceName,
494                               const std::chrono::duration<double>& elapsedDuration) const {
495     using std::chrono::system_clock;
496     const auto finish = system_clock::to_time_t(system_clock::now());
497     std::tm finish_tm;
498     localtime_r(&finish, &finish_tm);
499     std::stringstream oss;
500     oss << std::put_time(&finish_tm, "%Y-%m-%d %H:%M:%S");
501     std::string msg =
502         StringPrintf("--------- %.3fs was the duration of dumpsys %s, ending at: %s\n",
503                      elapsedDuration.count(), String8(serviceName).string(), oss.str().c_str());
504     WriteStringToFd(msg, fd);
505 }
506