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