blob: 7ed51ab035ffc23f4358788990a3b0e6513c3147 [file] [log] [blame]
Colin Crossf45fa6b2012-03-26 12:38:26 -07001/*
2 * Copyright (C) 2008 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 <dirent.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <limits.h>
21#include <poll.h>
22#include <signal.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080026#include <string>
Colin Crossf45fa6b2012-03-26 12:38:26 -070027#include <string.h>
28#include <sys/inotify.h>
29#include <sys/stat.h>
Mark Salyzyna297c322016-02-05 15:33:17 -080030#include <sys/sysconf.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070031#include <sys/time.h>
32#include <sys/wait.h>
33#include <sys/klog.h>
34#include <time.h>
35#include <unistd.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080036#include <vector>
John Michelaue7b6cf12013-03-07 15:35:35 -060037#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070038
Felipe Leme71bbfc52015-11-23 14:14:51 -080039#define LOG_TAG "dumpstate"
Jeff Brownbf7f4922012-06-07 16:40:01 -070040#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080041#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070042#include <cutils/properties.h>
43#include <cutils/sockets.h>
44#include <private/android_filesystem_config.h>
45
Robert Craig95798372013-04-04 06:33:10 -040046#include <selinux/android.h>
47
Colin Crossf45fa6b2012-03-26 12:38:26 -070048#include "dumpstate.h"
49
Jeff Brown1dc94e32014-09-11 14:15:27 -070050static const int64_t NANOS_PER_SEC = 1000000000;
51
Jeff Brownbf7f4922012-06-07 16:40:01 -070052/* list of native processes to include in the native dumps */
53static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080054 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080055 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070056 "/system/bin/drmserver",
Jeff Brownbf7f4922012-06-07 16:40:01 -070057 "/system/bin/mediaserver",
58 "/system/bin/sdcard",
59 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070060 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070061 NULL,
62};
63
Felipe Leme608385d2016-02-01 10:35:38 -080064DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
65
66DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme78f2c862015-12-21 09:55:22 -080067 title_ = title;
68 if (title) {
69 started_ = DurationReporter::nanotime();
70 }
Felipe Leme608385d2016-02-01 10:35:38 -080071 out_ = out;
Felipe Leme78f2c862015-12-21 09:55:22 -080072}
73
74DurationReporter::~DurationReporter() {
75 if (title_) {
76 uint64_t elapsed = DurationReporter::nanotime() - started_;
77 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme608385d2016-02-01 10:35:38 -080078 if (out_) {
79 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
80 (float) elapsed / NANOS_PER_SEC, title_);
81 } else {
Felipe Lemecbce55d2016-02-08 09:53:18 -080082 MYLOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -080083 }
Felipe Leme78f2c862015-12-21 09:55:22 -080084 }
85}
86
87uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080088 struct timespec ts;
89 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -080090 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080091}
92
John Spurlock5ecd4be2014-01-29 14:14:40 -050093void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -080094 ON_DRY_RUN_RETURN();
John Spurlock5ecd4be2014-01-29 14:14:40 -050095 DIR *d;
96 struct dirent *de;
97
98 if (header) printf("\n------ %s ------\n", header);
99 func(0);
100
101 if (!(d = opendir("/data/system/users"))) {
102 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
103 return;
104 }
105
106 while ((de = readdir(d))) {
107 int userid;
108 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
109 continue;
110 }
111 func(userid);
112 }
113
114 closedir(d);
115}
116
Colin Cross0c22e8b2012-11-02 15:46:56 -0700117static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700118 DIR *d;
119 struct dirent *de;
120
121 if (!(d = opendir("/proc"))) {
122 printf("Failed to open /proc (%s)\n", strerror(errno));
123 return;
124 }
125
Felipe Leme635ca312016-01-05 14:23:02 -0800126 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700127 while ((de = readdir(d))) {
128 int pid;
129 int fd;
130 char cmdpath[255];
131 char cmdline[255];
132
133 if (!(pid = atoi(de->d_name))) {
134 continue;
135 }
136
Colin Crossf45fa6b2012-03-26 12:38:26 -0700137 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyna297c322016-02-05 15:33:17 -0800138
139 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
140 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
141 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700142 close(fd);
Mark Salyzyna297c322016-02-05 15:33:17 -0800143 if (cmdline[0]) {
144 helper(pid, cmdline, arg);
145 continue;
146 }
147 }
148
149 // if no cmdline, a kernel thread has comm
150 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
151 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
152 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
153 close(fd);
154 if (cmdline[1]) {
155 cmdline[0] = '[';
156 size_t len = strcspn(cmdline, "\f\b\r\n");
157 cmdline[len] = ']';
158 cmdline[len+1] = '\0';
159 }
160 }
161 if (!cmdline[0]) {
162 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700163 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700164 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700165 }
166
167 closedir(d);
168}
169
Colin Cross0c22e8b2012-11-02 15:46:56 -0700170static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800171 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700172 func(pid, cmdline);
173}
174
175void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800176 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800177 __for_each_pid(for_each_pid_helper, header, (void *)func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700178}
179
180static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
181 DIR *d;
182 struct dirent *de;
183 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800184 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700185
186 sprintf(taskpath, "/proc/%d/task", pid);
187
188 if (!(d = opendir(taskpath))) {
189 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
190 return;
191 }
192
193 func(pid, pid, cmdline);
194
195 while ((de = readdir(d))) {
196 int tid;
197 int fd;
198 char commpath[255];
199 char comm[255];
200
201 if (!(tid = atoi(de->d_name))) {
202 continue;
203 }
204
205 if (tid == pid)
206 continue;
207
208 sprintf(commpath,"/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800209 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700210 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700211 strcpy(comm, "N/A");
212 } else {
213 char *c;
Mark Salyzyna297c322016-02-05 15:33:17 -0800214 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700215 close(fd);
216
217 c = strrchr(comm, '\n');
218 if (c) {
219 *c = '\0';
220 }
221 }
222 func(pid, tid, comm);
223 }
224
225 closedir(d);
226}
227
228void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800229 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800230 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700231}
232
233void show_wchan(int pid, int tid, const char *name) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800234 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700235 char path[255];
236 char buffer[255];
Mark Salyzyna297c322016-02-05 15:33:17 -0800237 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700238 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700239
240 memset(buffer, 0, sizeof(buffer));
241
Colin Cross0c22e8b2012-11-02 15:46:56 -0700242 sprintf(path, "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700243 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700244 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
245 return;
246 }
247
Mark Salyzyna297c322016-02-05 15:33:17 -0800248 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
249 save_errno = errno;
250 close(fd);
251
252 if (ret < 0) {
253 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
254 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700255 }
256
Colin Cross0c22e8b2012-11-02 15:46:56 -0700257 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
258 pid == tid ? 0 : 3, "", name);
259
260 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700261
Mark Salyzyna297c322016-02-05 15:33:17 -0800262 return;
263}
264
265// print time in centiseconds
266static void snprcent(char *buffer, size_t len, size_t spc,
267 unsigned long long time) {
268 static long hz; // cache discovered hz
269
270 if (hz <= 0) {
271 hz = sysconf(_SC_CLK_TCK);
272 if (hz <= 0) {
273 hz = 1000;
274 }
275 }
276
277 // convert to centiseconds
278 time = (time * 100 + (hz / 2)) / hz;
279
280 char str[16];
281
282 snprintf(str, sizeof(str), " %llu.%02u",
283 time / 100, (unsigned)(time % 100));
284 size_t offset = strlen(buffer);
285 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
286 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
287}
288
289// print permille as a percent
290static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
291 char str[16];
292
293 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
294 size_t offset = strlen(buffer);
295 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
296 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
297}
298
299void show_showtime(int pid, const char *name) {
300 ON_DRY_RUN_RETURN();
301 char path[255];
302 char buffer[1023];
303 int fd, ret, save_errno;
304
305 memset(buffer, 0, sizeof(buffer));
306
307 sprintf(path, "/proc/%d/stat", pid);
308 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
309 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
310 return;
311 }
312
313 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
314 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700315 close(fd);
Mark Salyzyna297c322016-02-05 15:33:17 -0800316
317 if (ret < 0) {
318 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
319 return;
320 }
321
322 // field 14 is utime
323 // field 15 is stime
324 // field 42 is iotime
325 unsigned long long utime = 0, stime = 0, iotime = 0;
326 if (sscanf(buffer,
Xia Yang60292e52016-02-16 03:05:18 -0800327 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
328 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
329 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
330 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyna297c322016-02-05 15:33:17 -0800331 &utime, &stime, &iotime) != 3) {
332 return;
333 }
334
335 unsigned long long total = utime + stime;
336 if (!total) {
337 return;
338 }
339
340 unsigned permille = (iotime * 1000 + (total / 2)) / total;
341 if (permille > 1000) {
342 permille = 1000;
343 }
344
345 // try to beautify and stabilize columns at <80 characters
346 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
347 if ((name[0] != '[') || utime) {
348 snprcent(buffer, sizeof(buffer), 57, utime);
349 }
350 snprcent(buffer, sizeof(buffer), 65, stime);
351 if ((name[0] != '[') || iotime) {
352 snprcent(buffer, sizeof(buffer), 73, iotime);
353 }
354 if (iotime) {
355 snprdec(buffer, sizeof(buffer), 79, permille);
356 }
357 puts(buffer); // adds a trailing newline
358
Colin Crossf45fa6b2012-03-26 12:38:26 -0700359 return;
360}
361
362void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800363 const char *title = "KERNEL LOG (dmesg)";
364 DurationReporter duration_reporter(title);
365 printf("------ %s ------\n", title);
366
Felipe Leme93d705b2015-11-10 20:10:25 -0800367 ON_DRY_RUN_RETURN();
Elliott Hughes5f87b312012-09-17 11:43:40 -0700368 /* Get size of kernel buffer */
369 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700370 if (size <= 0) {
371 printf("Unexpected klogctl return value: %d\n\n", size);
372 return;
373 }
374 char *buf = (char *) malloc(size + 1);
375 if (buf == NULL) {
376 printf("memory allocation failed\n\n");
377 return;
378 }
379 int retval = klogctl(KLOG_READ_ALL, buf, size);
380 if (retval < 0) {
381 printf("klogctl failure\n\n");
382 free(buf);
383 return;
384 }
385 buf[retval] = '\0';
386 printf("%s\n\n", buf);
387 free(buf);
388 return;
389}
390
391void do_showmap(int pid, const char *name) {
392 char title[255];
393 char arg[255];
394
395 sprintf(title, "SHOW MAP %d (%s)", pid, name);
396 sprintf(arg, "%d", pid);
Felipe Leme3dba69a2016-03-17 14:59:13 -0700397 run_command(title, 10, SU_PATH, "root", "showmap", "-q", arg, NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700398}
399
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800400static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700401 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800402 printf("------ %s (%s", title, path);
403
Colin Crossf45fa6b2012-03-26 12:38:26 -0700404 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800405 // Only show the modification time of non-device files.
406 size_t path_len = strlen(path);
407 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
408 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
409 (path_len < 3 || memcmp(path, "/d/", 3)) &&
410 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700411 char stamp[80];
412 time_t mtime = st.st_mtime;
413 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
414 printf(": %s", stamp);
415 }
416 printf(") ------\n");
417 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800418 ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
Colin Crossf45fa6b2012-03-26 12:38:26 -0700419
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800420 bool newline = false;
421 fd_set read_set;
422 struct timeval tm;
423 while (1) {
424 FD_ZERO(&read_set);
425 FD_SET(fd, &read_set);
426 /* Timeout if no data is read for 30 seconds. */
427 tm.tv_sec = 30;
428 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800429 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800430 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
431 if (ret == -1) {
432 printf("*** %s: select failed: %s\n", path, strerror(errno));
433 newline = true;
434 break;
435 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800436 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800437 printf("*** %s: Timed out after %.3fs\n", path,
438 (float) elapsed / NANOS_PER_SEC);
439 newline = true;
440 break;
441 } else {
442 char buffer[65536];
443 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
444 if (bytes_read > 0) {
445 fwrite(buffer, bytes_read, 1, stdout);
446 newline = (buffer[bytes_read-1] == '\n');
447 } else {
448 if (bytes_read == -1) {
449 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
450 newline = true;
451 }
452 break;
453 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700454 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700455 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800456 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700457 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700458
Colin Crossf45fa6b2012-03-26 12:38:26 -0700459 if (!newline) printf("\n");
460 if (title) printf("\n");
461 return 0;
462}
463
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800464/* prints the contents of a file */
465int dump_file(const char *title, const char *path) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800466 DurationReporter duration_reporter(title);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800467 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
468 if (fd < 0) {
469 int err = errno;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800470 printf("*** %s: %s\n", path, strerror(err));
471 if (title) printf("\n");
472 return -1;
473 }
474 return _dump_file_from_fd(title, path, fd);
475}
476
Felipe Leme71a74ac2016-03-17 15:43:25 -0700477int read_file_as_long(const char *path, long int *output) {
478 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
479 if (fd < 0) {
480 int err = errno;
481 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
482 return -1;
483 }
484 char buffer[50];
485 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
486 if (bytes_read == -1) {
487 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
488 return -2;
489 }
490 if (bytes_read == 0) {
491 MYLOGE("File %s is empty\n", path);
492 return -3;
493 }
494 *output = atoi(buffer);
495 return 0;
496}
497
Mark Salyzyn326842f2015-04-30 09:49:41 -0700498/* calls skip to gate calling dump_from_fd recursively
499 * in the specified directory. dump_from_fd defaults to
500 * dump_file_from_fd above when set to NULL. skip defaults
501 * to false when set to NULL. dump_from_fd will always be
502 * called with title NULL.
503 */
504int dump_files(const char *title, const char *dir,
505 bool (*skip)(const char *path),
506 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800507 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700508 DIR *dirp;
509 struct dirent *d;
510 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800511 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700512 int fd, retval = 0;
513
514 if (title) {
515 printf("------ %s (%s) ------\n", title, dir);
516 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800517 ON_DRY_RUN_RETURN(0);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700518
519 if (dir[strlen(dir) - 1] == '/') {
520 ++slash;
521 }
522 dirp = opendir(dir);
523 if (dirp == NULL) {
524 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800525 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700526 return retval;
527 }
528
529 if (!dump_from_fd) {
530 dump_from_fd = dump_file_from_fd;
531 }
532 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
533 if ((d->d_name[0] == '.')
534 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
535 || (d->d_name[1] == '\0'))) {
536 continue;
537 }
538 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
539 (d->d_type == DT_DIR) ? "/" : "");
540 if (!newpath) {
541 retval = -errno;
542 continue;
543 }
544 if (skip && (*skip)(newpath)) {
545 continue;
546 }
547 if (d->d_type == DT_DIR) {
548 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
549 if (ret < 0) {
550 retval = ret;
551 }
552 continue;
553 }
554 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
555 if (fd < 0) {
556 retval = fd;
557 printf("*** %s: %s\n", newpath, strerror(errno));
558 continue;
559 }
560 (*dump_from_fd)(NULL, newpath, fd);
561 }
562 closedir(dirp);
563 if (title) {
564 printf("\n");
565 }
566 return retval;
567}
568
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800569/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
570 * it's possible to avoid issues where opening the file itself can get
571 * stuck.
572 */
573int dump_file_from_fd(const char *title, const char *path, int fd) {
574 int flags = fcntl(fd, F_GETFL);
575 if (flags == -1) {
576 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800577 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800578 return -1;
579 } else if (!(flags & O_NONBLOCK)) {
580 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800581 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800582 return -1;
583 }
584 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700585}
586
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800587bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
588 sigset_t child_mask, old_mask;
589 sigemptyset(&child_mask);
590 sigaddset(&child_mask, SIGCHLD);
591
592 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
593 printf("*** sigprocmask failed: %s\n", strerror(errno));
594 return false;
595 }
596
597 struct timespec ts;
598 ts.tv_sec = timeout_seconds;
599 ts.tv_nsec = 0;
600 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
601 int saved_errno = errno;
602 // Set the signals back the way they were.
603 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
604 printf("*** sigprocmask failed: %s\n", strerror(errno));
605 if (ret == 0) {
606 return false;
607 }
608 }
609 if (ret == -1) {
610 errno = saved_errno;
611 if (errno == EAGAIN) {
612 errno = ETIMEDOUT;
613 } else {
614 printf("*** sigtimedwait failed: %s\n", strerror(errno));
615 }
616 return false;
617 }
618
619 pid_t child_pid = waitpid(pid, status, WNOHANG);
620 if (child_pid != pid) {
621 if (child_pid != -1) {
622 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
623 } else {
624 printf("*** waitpid failed: %s\n", strerror(errno));
625 }
626 return false;
627 }
628 return true;
629}
630
Felipe Lemea34efb72016-03-11 09:33:32 -0800631// TODO: refactor all those commands that convert args
632void format_args(const char* command, const char *args[], std::string *string);
633
Colin Crossf45fa6b2012-03-26 12:38:26 -0700634int run_command(const char *title, int timeout_seconds, const char *command, ...) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800635 DurationReporter duration_reporter(title);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700636 fflush(stdout);
Felipe Leme93d705b2015-11-10 20:10:25 -0800637
638 const char *args[1024] = {command};
639 size_t arg;
640 va_list ap;
641 va_start(ap, command);
642 if (title) printf("------ %s (%s", title, command);
Felipe Lemea34efb72016-03-11 09:33:32 -0800643 bool null_terminated = false;
Felipe Leme93d705b2015-11-10 20:10:25 -0800644 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
645 args[arg] = va_arg(ap, const char *);
Felipe Lemea34efb72016-03-11 09:33:32 -0800646 if (args[arg] == nullptr) {
647 null_terminated = true;
648 break;
649 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800650 if (title) printf(" %s", args[arg]);
651 }
652 if (title) printf(") ------\n");
653 fflush(stdout);
Felipe Lemea34efb72016-03-11 09:33:32 -0800654 if (!null_terminated) {
655 // Fail now, otherwise execvp() call on run_command_always() might hang.
656 std::string cmd;
657 format_args(command, args, &cmd);
658 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
659 return -1;
660 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800661
Felipe Leme71bbfc52015-11-23 14:14:51 -0800662 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
Felipe Leme93d705b2015-11-10 20:10:25 -0800663
Felipe Leme71bbfc52015-11-23 14:14:51 -0800664 int status = run_command_always(title, timeout_seconds, args);
665 va_end(ap);
666 return status;
Felipe Leme93d705b2015-11-10 20:10:25 -0800667}
668
669/* forks a command and waits for it to finish */
670int run_command_always(const char *title, int timeout_seconds, const char *args[]) {
Felipe Leme71bbfc52015-11-23 14:14:51 -0800671 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
672 * It's a good approximation for most cases, except when calling dumpsys, where its weight
673 * should be much higher proportionally to its timeout. */
674 int weight = timeout_seconds;
Felipe Leme93d705b2015-11-10 20:10:25 -0800675
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800676 const char *command = args[0];
Felipe Leme78f2c862015-12-21 09:55:22 -0800677 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700678 pid_t pid = fork();
679
680 /* handle error case */
681 if (pid < 0) {
682 printf("*** fork: %s\n", strerror(errno));
683 return pid;
684 }
685
686 /* handle child case */
687 if (pid == 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700688
John Michelaue7b6cf12013-03-07 15:35:35 -0600689 /* make sure the child dies when dumpstate dies */
690 prctl(PR_SET_PDEATHSIG, SIGKILL);
691
Andres Morales2e671bb2014-08-21 12:38:22 -0700692 /* just ignore SIGPIPE, will go down with parent's */
693 struct sigaction sigact;
694 memset(&sigact, 0, sizeof(sigact));
695 sigact.sa_handler = SIG_IGN;
696 sigaction(SIGPIPE, &sigact, NULL);
697
Colin Crossf45fa6b2012-03-26 12:38:26 -0700698 execvp(command, (char**) args);
Felipe Lemea34efb72016-03-11 09:33:32 -0800699 // execvp's result will be handled after waitpid_with_timeout() below...
Colin Crossf45fa6b2012-03-26 12:38:26 -0700700 }
701
702 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800703 int status;
704 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800705 uint64_t elapsed = DurationReporter::nanotime() - start;
Felipe Lemea34efb72016-03-11 09:33:32 -0800706 std::string cmd; // used to log command and its args
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800707 if (!ret) {
708 if (errno == ETIMEDOUT) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800709 format_args(command, args, &cmd);
710 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
711 (float) elapsed / NANOS_PER_SEC, pid);
712 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800713 (float) elapsed / NANOS_PER_SEC, pid);
714 } else {
Felipe Lemea34efb72016-03-11 09:33:32 -0800715 format_args(command, args, &cmd);
716 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
717 (float) elapsed / NANOS_PER_SEC, pid);
718 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800719 (float) elapsed / NANOS_PER_SEC, pid);
720 }
721 kill(pid, SIGTERM);
722 if (!waitpid_with_timeout(pid, 5, NULL)) {
723 kill(pid, SIGKILL);
724 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800725 printf("couldn not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
726 MYLOGE("couldn not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700727 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700728 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800729 return -1;
Felipe Lemea34efb72016-03-11 09:33:32 -0800730 } else if (status) {
731 format_args(command, args, &cmd);
732 printf("*** command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
733 MYLOGE("command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
734 return -2;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700735 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800736
737 if (WIFSIGNALED(status)) {
738 printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
739 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
740 printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
741 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800742
Felipe Leme71bbfc52015-11-23 14:14:51 -0800743 if (weight > 0) {
744 update_progress(weight);
745 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800746 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700747}
748
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800749void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
750 if (args.size() > 1000) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800751 MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800752 return;
753 }
Felipe Lemed5e724a2016-02-11 09:12:39 -0800754 const char *am_args[1024] = { SU_PATH, "shell", "/system/bin/am", "broadcast",
Felipe Lemeedb0b0c2016-01-27 11:27:28 -0800755 "--user", "0", "-a", action.c_str() };
Felipe Lemed5e724a2016-02-11 09:12:39 -0800756 size_t am_index = 7; // Starts at the index of last initial value above.
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800757 for (const std::string& arg : args) {
758 am_args[++am_index] = arg.c_str();
759 }
760 // Always terminate with NULL.
761 am_args[am_index + 1] = NULL;
Felipe Lemea34efb72016-03-11 09:33:32 -0800762 std::string args_string;
763 format_args(am_index + 1, am_args, &args_string);
764 MYLOGD("send_broadcast command: %s\n", args_string.c_str());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800765 run_command_always(NULL, 5, am_args);
766}
767
Colin Crossf45fa6b2012-03-26 12:38:26 -0700768size_t num_props = 0;
769static char* props[2000];
770
771static void print_prop(const char *key, const char *name, void *user) {
772 (void) user;
773 if (num_props < sizeof(props) / sizeof(props[0])) {
774 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
775 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
776 props[num_props++] = strdup(buf);
777 }
778}
779
780static int compare_prop(const void *a, const void *b) {
781 return strcmp(*(char * const *) a, *(char * const *) b);
782}
783
784/* prints all the system properties */
785void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800786 const char* title = "SYSTEM PROPERTIES";
787 DurationReporter duration_reporter(title);
788 printf("------ %s ------\n", title);
Felipe Leme93d705b2015-11-10 20:10:25 -0800789 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700790 size_t i;
791 num_props = 0;
792 property_list(print_prop, NULL);
793 qsort(&props, num_props, sizeof(props[0]), compare_prop);
794
Colin Crossf45fa6b2012-03-26 12:38:26 -0700795 for (i = 0; i < num_props; ++i) {
796 fputs(props[i], stdout);
797 free(props[i]);
798 }
799 printf("\n");
800}
801
802/* redirect output to a service control socket */
803void redirect_to_socket(FILE *redirect, const char *service) {
804 int s = android_get_control_socket(service);
805 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800806 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700807 exit(1);
808 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700809 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700810 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800811 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700812 exit(1);
813 }
814
815 struct sockaddr addr;
816 socklen_t alen = sizeof(addr);
817 int fd = accept(s, &addr, &alen);
818 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800819 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700820 exit(1);
821 }
822
823 fflush(redirect);
824 dup2(fd, fileno(redirect));
825 close(fd);
826}
827
Felipe Leme111b9d02016-02-03 09:28:24 -0800828void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800829 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700830
831 /* skip initial slash */
832 if (chp[0] == '/')
833 chp++;
834
835 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800836 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700837 while (chp && chp[0]) {
838 chp = strchr(chp, '/');
839 if (chp) {
840 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800841 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800842 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800843 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800844 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800845 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800846 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800847 }
848 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700849 *chp++ = '/';
850 }
851 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800852}
853
854/* redirect output to a file */
855void redirect_to_file(FILE *redirect, char *path) {
856 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700857
Felipe Leme608385d2016-02-01 10:35:38 -0800858 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800859 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700860 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800861 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700862 exit(1);
863 }
864
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800865 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700866 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700867}
868
Jeff Brownbf7f4922012-06-07 16:40:01 -0700869static bool should_dump_native_traces(const char* path) {
870 for (const char** p = native_processes_to_dump; *p; p++) {
871 if (!strcmp(*p, path)) {
872 return true;
873 }
874 }
875 return false;
876}
877
878/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
879const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -0800880 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Leme93d705b2015-11-10 20:10:25 -0800881 ON_DRY_RUN_RETURN(NULL);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700882 const char* result = NULL;
883
Colin Crossf45fa6b2012-03-26 12:38:26 -0700884 char traces_path[PROPERTY_VALUE_MAX] = "";
885 property_get("dalvik.vm.stack-trace-file", traces_path, "");
886 if (!traces_path[0]) return NULL;
887
888 /* move the old traces.txt (if any) out of the way temporarily */
889 char anr_traces_path[PATH_MAX];
890 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
891 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
892 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800893 MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700894 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
895 }
896
Colin Crossf45fa6b2012-03-26 12:38:26 -0700897 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700898 int fd = TEMP_FAILURE_RETRY(open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800899 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700900 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800901 MYLOGE("%s: %s\n", traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700902 return NULL;
903 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700904 int chmod_ret = fchmod(fd, 0666);
905 if (chmod_ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800906 MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700907 close(fd);
908 return NULL;
909 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700910
Felipe Leme8620bb42015-11-10 11:04:45 -0800911 /* Variables below must be initialized before 'goto' statements */
912 int dalvik_found = 0;
913 int ifd, wfd = -1;
914
Colin Crossf45fa6b2012-03-26 12:38:26 -0700915 /* walk /proc and kill -QUIT all Dalvik processes */
916 DIR *proc = opendir("/proc");
917 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800918 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700919 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700920 }
921
922 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -0800923 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700924 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800925 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700926 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700927 }
928
Felipe Leme8620bb42015-11-10 11:04:45 -0800929 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700930 if (wfd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800931 MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700932 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700933 }
934
935 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700936 while ((d = readdir(proc))) {
937 int pid = atoi(d->d_name);
938 if (pid <= 0) continue;
939
Jeff Brownbf7f4922012-06-07 16:40:01 -0700940 char path[PATH_MAX];
941 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700942 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700943 ssize_t len = readlink(path, data, sizeof(data) - 1);
944 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700945 continue;
946 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700947 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -0700948
Colin Cross0d6180f2014-07-16 19:00:46 -0700949 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700950 /* skip zygote -- it won't dump its stack anyway */
951 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700952 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700953 len = read(cfd, data, sizeof(data) - 1);
954 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700955 if (len <= 0) {
956 continue;
957 }
958 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -0700959 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700960 continue;
961 }
962
963 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -0800964 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -0700965 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800966 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700967 continue;
968 }
969
970 /* wait for the writable-close notification from inotify */
971 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -0700972 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -0700973 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800974 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700975 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800976 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700977 } else {
978 struct inotify_event ie;
979 read(ifd, &ie, sizeof(ie));
980 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700981
982 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800983 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700984 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800985 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -0800986 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700987 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700988 } else if (should_dump_native_traces(data)) {
989 /* dump native process if appropriate */
990 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800991 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700992 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800993 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800994 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -0800995
996 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
997 if (timeout_failures == 3) {
998 dprintf(fd, "too many stack dump failures, skipping...\n");
999 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1000 dprintf(fd, "dumping failed, likely due to a timeout\n");
1001 timeout_failures++;
1002 } else {
1003 timeout_failures = 0;
1004 }
1005 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001006 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001007 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001008 }
1009 }
1010
Colin Crossf45fa6b2012-03-26 12:38:26 -07001011 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001012 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001013 }
1014
1015 static char dump_traces_path[PATH_MAX];
1016 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
1017 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
1018 if (rename(traces_path, dump_traces_path)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001019 MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001020 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001021 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001022 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001023
1024 /* replace the saved [ANR] traces.txt file */
1025 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001026
1027error_close_ifd:
1028 close(ifd);
1029error_close_fd:
1030 close(fd);
1031 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001032}
1033
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001034void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001035 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme93d705b2015-11-10 20:10:25 -08001036 ON_DRY_RUN_RETURN();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001037 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1038 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001039 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001040 if (!fp) {
1041 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1042 return;
1043 }
1044 char table[16];
1045 // Each line has an integer (the table number), a space, and a string (the table name). We only
1046 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1047 // Add a fixed max limit so this doesn't go awry.
1048 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
1049 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
1050 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
1051 }
1052 fclose(fp);
1053}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001054
1055/* overall progress */
1056int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -08001057int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -08001058int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001059
1060// TODO: make this function thread safe if sections are generated in parallel.
1061void update_progress(int delta) {
1062 if (!do_update_progress) return;
1063
1064 progress += delta;
1065
1066 char key[PROPERTY_KEY_MAX];
1067 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001068
1069 // adjusts max on the fly
1070 if (progress > weight_total) {
1071 int new_total = weight_total * 1.2;
Felipe Leme107a05f2016-03-08 15:11:15 -08001072 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001073 weight_total = new_total;
1074 sprintf(key, "dumpstate.%d.max", getpid());
1075 sprintf(value, "%d", weight_total);
1076 int status = property_set(key, value);
1077 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001078 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001079 key, value, status);
1080 }
1081 }
1082
Felipe Leme71bbfc52015-11-23 14:14:51 -08001083 sprintf(key, "dumpstate.%d.progress", getpid());
1084 sprintf(value, "%d", progress);
1085
Felipe Leme107a05f2016-03-08 15:11:15 -08001086 if (progress % 100 == 0) {
1087 // We don't want to spam logcat, so only log multiples of 100.
1088 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1089 } else {
1090 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1091 // directly for debuggging.
1092 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1093 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001094
1095 int status = property_set(key, value);
1096 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001097 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001098 key, value, status);
1099 }
1100}
Felipe Lemee338bf62015-12-07 14:03:50 -08001101
Felipe Leme3634a1e2015-12-09 10:11:47 -08001102void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -08001103 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
1104 run_command_always(NULL, 10, args);
1105}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001106
Felipe Leme0c80cf02016-01-05 13:25:34 -08001107void vibrate(FILE* vibrator, int ms) {
1108 fprintf(vibrator, "%d\n", ms);
1109 fflush(vibrator);
1110}
1111
1112bool is_dir(const char* pathname) {
1113 struct stat info;
1114 if (stat(pathname, &info) == -1) {
1115 return false;
1116 }
1117 return S_ISDIR(info.st_mode);
1118}
1119
1120time_t get_mtime(int fd, time_t default_mtime) {
1121 struct stat info;
1122 if (fstat(fd, &info) == -1) {
1123 return default_mtime;
1124 }
1125 return info.st_mtime;
1126}
1127
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001128void dump_emmc_ecsd(const char *ext_csd_path) {
1129 static const size_t EXT_CSD_REV = 192;
1130 static const size_t EXT_PRE_EOL_INFO = 267;
1131 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
1132 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
1133 struct hex {
1134 char str[2];
1135 } buffer[512];
1136 int fd, ext_csd_rev, ext_pre_eol_info;
1137 ssize_t bytes_read;
1138 static const char *ver_str[] = {
1139 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1140 };
1141 static const char *eol_str[] = {
1142 "Undefined",
1143 "Normal",
1144 "Warning (consumed 80% of reserve)",
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001145 "Urgent (consumed 90% of reserve)"
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001146 };
1147
1148 printf("------ %s Extended CSD ------\n", ext_csd_path);
1149
1150 fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
1151 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
1152 if (fd < 0) {
1153 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1154 return;
1155 }
1156
1157 bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
1158 close(fd);
1159 if (bytes_read < 0) {
1160 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1161 return;
1162 }
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001163 if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001164 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1165 return;
1166 }
1167
1168 ext_csd_rev = 0;
1169 if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
1170 printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
1171 ext_csd_path, buffer[EXT_CSD_REV].str);
1172 return;
1173 }
1174
1175 printf("rev 1.%d (MMC %s)\n",
1176 ext_csd_rev,
1177 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1178 ver_str[ext_csd_rev] :
1179 "Unknown");
1180 if (ext_csd_rev < 7) {
1181 printf("\n");
1182 return;
1183 }
1184
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001185 if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001186 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1187 return;
1188 }
1189
1190 ext_pre_eol_info = 0;
1191 if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1192 printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1193 ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1194 return;
1195 }
1196 printf("PRE_EOL_INFO %d (MMC %s)\n",
1197 ext_pre_eol_info,
1198 eol_str[(ext_pre_eol_info < (int)
1199 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1200 ext_pre_eol_info : 0]);
1201
1202 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1203 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1204 ++lifetime) {
1205 int ext_device_life_time_est;
1206 static const char *est_str[] = {
1207 "Undefined",
1208 "0-10% of device lifetime used",
1209 "10-20% of device lifetime used",
1210 "20-30% of device lifetime used",
1211 "30-40% of device lifetime used",
1212 "40-50% of device lifetime used",
1213 "50-60% of device lifetime used",
1214 "60-70% of device lifetime used",
1215 "70-80% of device lifetime used",
1216 "80-90% of device lifetime used",
1217 "90-100% of device lifetime used",
1218 "Exceeded the maximum estimated device lifetime",
1219 };
1220
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001221 if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001222 printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1223 break;
1224 }
1225
1226 ext_device_life_time_est = 0;
1227 if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1228 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1229 ext_csd_path,
1230 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1231 buffer[lifetime].str);
1232 continue;
1233 }
1234 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1235 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1236 ext_device_life_time_est,
1237 est_str[(ext_device_life_time_est < (int)
1238 (sizeof(est_str) / sizeof(est_str[0]))) ?
1239 ext_device_life_time_est : 0]);
1240 }
1241
1242 printf("\n");
1243}
Felipe Leme88c79332016-02-22 11:06:49 -08001244
Felipe Lemea34efb72016-03-11 09:33:32 -08001245// TODO: refactor all those commands that convert args
1246void format_args(int argc, const char *argv[], std::string *args) {
1247 LOG_ALWAYS_FATAL_IF(args == nullptr);
Felipe Leme88c79332016-02-22 11:06:49 -08001248 for (int i = 0; i < argc; i++) {
Felipe Lemea34efb72016-03-11 09:33:32 -08001249 args->append(argv[i]);
1250 if (i < argc -1) {
1251 args->append(" ");
1252 }
Felipe Leme88c79332016-02-22 11:06:49 -08001253 }
Felipe Lemea34efb72016-03-11 09:33:32 -08001254}
1255void format_args(const char* command, const char *args[], std::string *string) {
1256 LOG_ALWAYS_FATAL_IF(args == nullptr || command == nullptr);
1257 string->append(command);
1258 if (args[0] == nullptr) return;
1259 string->append(" ");
1260
1261 for (int arg = 1; arg <= 1000; ++arg) {
1262 if (args[arg] == nullptr) return;
1263 string->append(args[arg]);
1264 if (args[arg+1] != nullptr) {
1265 string->append(" ");
1266 }
1267 }
1268 MYLOGE("internal error: missing NULL entry on %s", string->c_str());
Felipe Leme88c79332016-02-22 11:06:49 -08001269}