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