blob: 44ba025ca0f39a610a8f1497d9ec26ad40e3cacc [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>
26#include <string.h>
27#include <sys/inotify.h>
28#include <sys/stat.h>
29#include <sys/time.h>
30#include <sys/wait.h>
31#include <sys/klog.h>
32#include <time.h>
33#include <unistd.h>
John Michelaue7b6cf12013-03-07 15:35:35 -060034#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070035
Jeff Brownbf7f4922012-06-07 16:40:01 -070036#include <cutils/debugger.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070037#include <cutils/properties.h>
38#include <cutils/sockets.h>
39#include <private/android_filesystem_config.h>
40
Robert Craig95798372013-04-04 06:33:10 -040041#include <selinux/android.h>
42
Colin Crossf45fa6b2012-03-26 12:38:26 -070043#include "dumpstate.h"
44
Jeff Brown1dc94e32014-09-11 14:15:27 -070045static const int64_t NANOS_PER_SEC = 1000000000;
46
Jeff Brownbf7f4922012-06-07 16:40:01 -070047/* list of native processes to include in the native dumps */
48static const char* native_processes_to_dump[] = {
James Dong1fc4f802012-09-10 16:08:48 -070049 "/system/bin/drmserver",
Jeff Brownbf7f4922012-06-07 16:40:01 -070050 "/system/bin/mediaserver",
51 "/system/bin/sdcard",
52 "/system/bin/surfaceflinger",
53 NULL,
54};
55
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080056static uint64_t nanotime() {
57 struct timespec ts;
58 clock_gettime(CLOCK_MONOTONIC, &ts);
59 return (uint64_t)ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
60}
61
John Spurlock5ecd4be2014-01-29 14:14:40 -050062void for_each_userid(void (*func)(int), const char *header) {
63 DIR *d;
64 struct dirent *de;
65
66 if (header) printf("\n------ %s ------\n", header);
67 func(0);
68
69 if (!(d = opendir("/data/system/users"))) {
70 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
71 return;
72 }
73
74 while ((de = readdir(d))) {
75 int userid;
76 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
77 continue;
78 }
79 func(userid);
80 }
81
82 closedir(d);
83}
84
Colin Cross0c22e8b2012-11-02 15:46:56 -070085static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -070086 DIR *d;
87 struct dirent *de;
88
89 if (!(d = opendir("/proc"))) {
90 printf("Failed to open /proc (%s)\n", strerror(errno));
91 return;
92 }
93
94 printf("\n------ %s ------\n", header);
95 while ((de = readdir(d))) {
96 int pid;
97 int fd;
98 char cmdpath[255];
99 char cmdline[255];
100
101 if (!(pid = atoi(de->d_name))) {
102 continue;
103 }
104
105 sprintf(cmdpath,"/proc/%d/cmdline", pid);
106 memset(cmdline, 0, sizeof(cmdline));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700107 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700108 strcpy(cmdline, "N/A");
109 } else {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700110 read(fd, cmdline, sizeof(cmdline) - 1);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700111 close(fd);
112 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700113 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700114 }
115
116 closedir(d);
117}
118
Colin Cross0c22e8b2012-11-02 15:46:56 -0700119static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
120 for_each_pid_func *func = arg;
121 func(pid, cmdline);
122}
123
124void for_each_pid(for_each_pid_func func, const char *header) {
125 __for_each_pid(for_each_pid_helper, header, func);
126}
127
128static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
129 DIR *d;
130 struct dirent *de;
131 char taskpath[255];
132 for_each_tid_func *func = arg;
133
134 sprintf(taskpath, "/proc/%d/task", pid);
135
136 if (!(d = opendir(taskpath))) {
137 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
138 return;
139 }
140
141 func(pid, pid, cmdline);
142
143 while ((de = readdir(d))) {
144 int tid;
145 int fd;
146 char commpath[255];
147 char comm[255];
148
149 if (!(tid = atoi(de->d_name))) {
150 continue;
151 }
152
153 if (tid == pid)
154 continue;
155
156 sprintf(commpath,"/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800157 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700158 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700159 strcpy(comm, "N/A");
160 } else {
161 char *c;
162 read(fd, comm, sizeof(comm) - 1);
163 close(fd);
164
165 c = strrchr(comm, '\n');
166 if (c) {
167 *c = '\0';
168 }
169 }
170 func(pid, tid, comm);
171 }
172
173 closedir(d);
174}
175
176void for_each_tid(for_each_tid_func func, const char *header) {
177 __for_each_pid(for_each_tid_helper, header, func);
178}
179
180void show_wchan(int pid, int tid, const char *name) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700181 char path[255];
182 char buffer[255];
183 int fd;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700184 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700185
186 memset(buffer, 0, sizeof(buffer));
187
Colin Cross0c22e8b2012-11-02 15:46:56 -0700188 sprintf(path, "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700189 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700190 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
191 return;
192 }
193
194 if (read(fd, buffer, sizeof(buffer)) < 0) {
195 printf("Failed to read '%s' (%s)\n", path, strerror(errno));
196 goto out_close;
197 }
198
Colin Cross0c22e8b2012-11-02 15:46:56 -0700199 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
200 pid == tid ? 0 : 3, "", name);
201
202 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700203
204out_close:
205 close(fd);
206 return;
207}
208
John Spurlock5ecd4be2014-01-29 14:14:40 -0500209void do_dump_settings(int userid) {
210 char title[255];
211 char dbpath[255];
212 char sql[255];
213 sprintf(title, "SYSTEM SETTINGS (user %d)", userid);
214 if (userid == 0) {
215 strcpy(dbpath, "/data/data/com.android.providers.settings/databases/settings.db");
216 strcpy(sql, "pragma user_version; select * from system; select * from secure; select * from global;");
217 } else {
218 sprintf(dbpath, "/data/system/users/%d/settings.db", userid);
219 strcpy(sql, "pragma user_version; select * from system; select * from secure;");
220 }
221 run_command(title, 20, SU_PATH, "root", "sqlite3", dbpath, sql, NULL);
222 return;
223}
224
Colin Crossf45fa6b2012-03-26 12:38:26 -0700225void do_dmesg() {
226 printf("------ KERNEL LOG (dmesg) ------\n");
Elliott Hughes5f87b312012-09-17 11:43:40 -0700227 /* Get size of kernel buffer */
228 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700229 if (size <= 0) {
230 printf("Unexpected klogctl return value: %d\n\n", size);
231 return;
232 }
233 char *buf = (char *) malloc(size + 1);
234 if (buf == NULL) {
235 printf("memory allocation failed\n\n");
236 return;
237 }
238 int retval = klogctl(KLOG_READ_ALL, buf, size);
239 if (retval < 0) {
240 printf("klogctl failure\n\n");
241 free(buf);
242 return;
243 }
244 buf[retval] = '\0';
245 printf("%s\n\n", buf);
246 free(buf);
247 return;
248}
249
250void do_showmap(int pid, const char *name) {
251 char title[255];
252 char arg[255];
253
254 sprintf(title, "SHOW MAP %d (%s)", pid, name);
255 sprintf(arg, "%d", pid);
256 run_command(title, 10, SU_PATH, "root", "showmap", arg, NULL);
257}
258
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800259static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700260 if (title) printf("------ %s (%s", title, path);
261
262 if (title) {
263 struct stat st;
264 if (memcmp(path, "/proc/", 6) && memcmp(path, "/sys/", 5) && !fstat(fd, &st)) {
265 char stamp[80];
266 time_t mtime = st.st_mtime;
267 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
268 printf(": %s", stamp);
269 }
270 printf(") ------\n");
271 }
272
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800273 bool newline = false;
274 fd_set read_set;
275 struct timeval tm;
276 while (1) {
277 FD_ZERO(&read_set);
278 FD_SET(fd, &read_set);
279 /* Timeout if no data is read for 30 seconds. */
280 tm.tv_sec = 30;
281 tm.tv_usec = 0;
282 uint64_t elapsed = nanotime();
283 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
284 if (ret == -1) {
285 printf("*** %s: select failed: %s\n", path, strerror(errno));
286 newline = true;
287 break;
288 } else if (ret == 0) {
289 elapsed = nanotime() - elapsed;
290 printf("*** %s: Timed out after %.3fs\n", path,
291 (float) elapsed / NANOS_PER_SEC);
292 newline = true;
293 break;
294 } else {
295 char buffer[65536];
296 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
297 if (bytes_read > 0) {
298 fwrite(buffer, bytes_read, 1, stdout);
299 newline = (buffer[bytes_read-1] == '\n');
300 } else {
301 if (bytes_read == -1) {
302 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
303 newline = true;
304 }
305 break;
306 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700307 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700308 }
Elliott Hughes997abb62015-05-15 17:05:40 -0700309 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700310
Colin Crossf45fa6b2012-03-26 12:38:26 -0700311 if (!newline) printf("\n");
312 if (title) printf("\n");
313 return 0;
314}
315
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800316/* prints the contents of a file */
317int dump_file(const char *title, const char *path) {
318 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
319 if (fd < 0) {
320 int err = errno;
321 if (title) printf("------ %s (%s) ------\n", title, path);
322 printf("*** %s: %s\n", path, strerror(err));
323 if (title) printf("\n");
324 return -1;
325 }
326 return _dump_file_from_fd(title, path, fd);
327}
328
Mark Salyzyn540e3de2015-04-30 09:49:41 -0700329/* calls skip to gate calling dump_from_fd recursively
330 * in the specified directory. dump_from_fd defaults to
331 * dump_file_from_fd above when set to NULL. skip defaults
332 * to false when set to NULL. dump_from_fd will always be
333 * called with title NULL.
334 */
335int dump_files(const char *title, const char *dir,
336 bool (*skip)(const char *path),
337 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
338 DIR *dirp;
339 struct dirent *d;
340 char *newpath = NULL;
341 char *slash = "/";
342 int fd, retval = 0;
343
344 if (title) {
345 printf("------ %s (%s) ------\n", title, dir);
346 }
347
348 if (dir[strlen(dir) - 1] == '/') {
349 ++slash;
350 }
351 dirp = opendir(dir);
352 if (dirp == NULL) {
353 retval = -errno;
354 fprintf(stderr, "%s: %s\n", dir, strerror(errno));
355 return retval;
356 }
357
358 if (!dump_from_fd) {
359 dump_from_fd = dump_file_from_fd;
360 }
361 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
362 if ((d->d_name[0] == '.')
363 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
364 || (d->d_name[1] == '\0'))) {
365 continue;
366 }
367 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
368 (d->d_type == DT_DIR) ? "/" : "");
369 if (!newpath) {
370 retval = -errno;
371 continue;
372 }
373 if (skip && (*skip)(newpath)) {
374 continue;
375 }
376 if (d->d_type == DT_DIR) {
377 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
378 if (ret < 0) {
379 retval = ret;
380 }
381 continue;
382 }
383 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
384 if (fd < 0) {
385 retval = fd;
386 printf("*** %s: %s\n", newpath, strerror(errno));
387 continue;
388 }
389 (*dump_from_fd)(NULL, newpath, fd);
390 }
391 closedir(dirp);
392 if (title) {
393 printf("\n");
394 }
395 return retval;
396}
397
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800398/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
399 * it's possible to avoid issues where opening the file itself can get
400 * stuck.
401 */
402int dump_file_from_fd(const char *title, const char *path, int fd) {
403 int flags = fcntl(fd, F_GETFL);
404 if (flags == -1) {
405 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
406 return -1;
407 } else if (!(flags & O_NONBLOCK)) {
408 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
409 return -1;
410 }
411 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700412}
413
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800414bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
415 sigset_t child_mask, old_mask;
416 sigemptyset(&child_mask);
417 sigaddset(&child_mask, SIGCHLD);
418
419 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
420 printf("*** sigprocmask failed: %s\n", strerror(errno));
421 return false;
422 }
423
424 struct timespec ts;
425 ts.tv_sec = timeout_seconds;
426 ts.tv_nsec = 0;
427 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
428 int saved_errno = errno;
429 // Set the signals back the way they were.
430 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
431 printf("*** sigprocmask failed: %s\n", strerror(errno));
432 if (ret == 0) {
433 return false;
434 }
435 }
436 if (ret == -1) {
437 errno = saved_errno;
438 if (errno == EAGAIN) {
439 errno = ETIMEDOUT;
440 } else {
441 printf("*** sigtimedwait failed: %s\n", strerror(errno));
442 }
443 return false;
444 }
445
446 pid_t child_pid = waitpid(pid, status, WNOHANG);
447 if (child_pid != pid) {
448 if (child_pid != -1) {
449 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
450 } else {
451 printf("*** waitpid failed: %s\n", strerror(errno));
452 }
453 return false;
454 }
455 return true;
456}
457
Colin Crossf45fa6b2012-03-26 12:38:26 -0700458/* forks a command and waits for it to finish */
459int run_command(const char *title, int timeout_seconds, const char *command, ...) {
460 fflush(stdout);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800461 uint64_t start = nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700462 pid_t pid = fork();
463
464 /* handle error case */
465 if (pid < 0) {
466 printf("*** fork: %s\n", strerror(errno));
467 return pid;
468 }
469
470 /* handle child case */
471 if (pid == 0) {
472 const char *args[1024] = {command};
473 size_t arg;
474
John Michelaue7b6cf12013-03-07 15:35:35 -0600475 /* make sure the child dies when dumpstate dies */
476 prctl(PR_SET_PDEATHSIG, SIGKILL);
477
Andres Morales2e671bb2014-08-21 12:38:22 -0700478 /* just ignore SIGPIPE, will go down with parent's */
479 struct sigaction sigact;
480 memset(&sigact, 0, sizeof(sigact));
481 sigact.sa_handler = SIG_IGN;
482 sigaction(SIGPIPE, &sigact, NULL);
483
Colin Crossf45fa6b2012-03-26 12:38:26 -0700484 va_list ap;
485 va_start(ap, command);
486 if (title) printf("------ %s (%s", title, command);
487 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
488 args[arg] = va_arg(ap, const char *);
489 if (args[arg] == NULL) break;
490 if (title) printf(" %s", args[arg]);
491 }
492 if (title) printf(") ------\n");
493 fflush(stdout);
494
495 execvp(command, (char**) args);
496 printf("*** exec(%s): %s\n", command, strerror(errno));
497 fflush(stdout);
498 _exit(-1);
499 }
500
501 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800502 int status;
503 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
504 uint64_t elapsed = nanotime() - start;
505 if (!ret) {
506 if (errno == ETIMEDOUT) {
507 printf("*** %s: Timed out after %.3fs (killing pid %d)\n", command,
508 (float) elapsed / NANOS_PER_SEC, pid);
509 } else {
510 printf("*** %s: Error after %.4fs (killing pid %d)\n", command,
511 (float) elapsed / NANOS_PER_SEC, pid);
512 }
513 kill(pid, SIGTERM);
514 if (!waitpid_with_timeout(pid, 5, NULL)) {
515 kill(pid, SIGKILL);
516 if (!waitpid_with_timeout(pid, 5, NULL)) {
517 printf("*** %s: Cannot kill %d even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700518 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700519 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800520 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700521 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800522
523 if (WIFSIGNALED(status)) {
524 printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
525 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
526 printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
527 }
528 if (title) printf("[%s: %.3fs elapsed]\n\n", command, (float)elapsed / NANOS_PER_SEC);
529
530 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700531}
532
533size_t num_props = 0;
534static char* props[2000];
535
536static void print_prop(const char *key, const char *name, void *user) {
537 (void) user;
538 if (num_props < sizeof(props) / sizeof(props[0])) {
539 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
540 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
541 props[num_props++] = strdup(buf);
542 }
543}
544
545static int compare_prop(const void *a, const void *b) {
546 return strcmp(*(char * const *) a, *(char * const *) b);
547}
548
549/* prints all the system properties */
550void print_properties() {
551 size_t i;
552 num_props = 0;
553 property_list(print_prop, NULL);
554 qsort(&props, num_props, sizeof(props[0]), compare_prop);
555
556 printf("------ SYSTEM PROPERTIES ------\n");
557 for (i = 0; i < num_props; ++i) {
558 fputs(props[i], stdout);
559 free(props[i]);
560 }
561 printf("\n");
562}
563
564/* redirect output to a service control socket */
565void redirect_to_socket(FILE *redirect, const char *service) {
566 int s = android_get_control_socket(service);
567 if (s < 0) {
568 fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno));
569 exit(1);
570 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700571 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700572 if (listen(s, 4) < 0) {
573 fprintf(stderr, "listen(control socket): %s\n", strerror(errno));
574 exit(1);
575 }
576
577 struct sockaddr addr;
578 socklen_t alen = sizeof(addr);
579 int fd = accept(s, &addr, &alen);
580 if (fd < 0) {
581 fprintf(stderr, "accept(control socket): %s\n", strerror(errno));
582 exit(1);
583 }
584
585 fflush(redirect);
586 dup2(fd, fileno(redirect));
587 close(fd);
588}
589
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800590/* redirect output to a file */
591void redirect_to_file(FILE *redirect, char *path) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700592 char *chp = path;
593
594 /* skip initial slash */
595 if (chp[0] == '/')
596 chp++;
597
598 /* create leading directories, if necessary */
599 while (chp && chp[0]) {
600 chp = strchr(chp, '/');
601 if (chp) {
602 *chp = 0;
Jeff Sharkey27f9e6d2013-03-13 15:45:50 -0700603 mkdir(path, 0770); /* drwxrwx--- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700604 *chp++ = '/';
605 }
606 }
607
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700608 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800609 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700610 if (fd < 0) {
611 fprintf(stderr, "%s: %s\n", path, strerror(errno));
612 exit(1);
613 }
614
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800615 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700616 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700617}
618
Jeff Brownbf7f4922012-06-07 16:40:01 -0700619static bool should_dump_native_traces(const char* path) {
620 for (const char** p = native_processes_to_dump; *p; p++) {
621 if (!strcmp(*p, path)) {
622 return true;
623 }
624 }
625 return false;
626}
627
628/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
629const char *dump_traces() {
630 const char* result = NULL;
631
Colin Crossf45fa6b2012-03-26 12:38:26 -0700632 char traces_path[PROPERTY_VALUE_MAX] = "";
633 property_get("dalvik.vm.stack-trace-file", traces_path, "");
634 if (!traces_path[0]) return NULL;
635
636 /* move the old traces.txt (if any) out of the way temporarily */
637 char anr_traces_path[PATH_MAX];
638 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
639 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
640 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
641 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
642 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
643 }
644
645 /* make the directory if necessary */
646 char anr_traces_dir[PATH_MAX];
647 strlcpy(anr_traces_dir, traces_path, sizeof(anr_traces_dir));
648 char *slash = strrchr(anr_traces_dir, '/');
649 if (slash != NULL) {
650 *slash = '\0';
651 if (!mkdir(anr_traces_dir, 0775)) {
652 chown(anr_traces_dir, AID_SYSTEM, AID_SYSTEM);
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700653 chmod(anr_traces_dir, 0775);
Stephen Smalley26288202014-02-07 09:16:46 -0500654 if (selinux_android_restorecon(anr_traces_dir, 0) == -1) {
Robert Craig95798372013-04-04 06:33:10 -0400655 fprintf(stderr, "restorecon failed for %s: %s\n", anr_traces_dir, strerror(errno));
656 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700657 } else if (errno != EEXIST) {
658 fprintf(stderr, "mkdir(%s): %s\n", anr_traces_dir, strerror(errno));
659 return NULL;
660 }
661 }
662
663 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700664 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 -0800665 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700666 if (fd < 0) {
667 fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
668 return NULL;
669 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700670 int chmod_ret = fchmod(fd, 0666);
671 if (chmod_ret < 0) {
672 fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
673 close(fd);
674 return NULL;
675 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700676
677 /* walk /proc and kill -QUIT all Dalvik processes */
678 DIR *proc = opendir("/proc");
679 if (proc == NULL) {
680 fprintf(stderr, "/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700681 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700682 }
683
684 /* use inotify to find when processes are done dumping */
685 int ifd = inotify_init();
686 if (ifd < 0) {
687 fprintf(stderr, "inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700688 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700689 }
690
691 int wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
692 if (wfd < 0) {
693 fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700694 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700695 }
696
697 struct dirent *d;
698 int dalvik_found = 0;
699 while ((d = readdir(proc))) {
700 int pid = atoi(d->d_name);
701 if (pid <= 0) continue;
702
Jeff Brownbf7f4922012-06-07 16:40:01 -0700703 char path[PATH_MAX];
704 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700705 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700706 ssize_t len = readlink(path, data, sizeof(data) - 1);
707 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700708 continue;
709 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700710 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -0700711
Colin Cross0d6180f2014-07-16 19:00:46 -0700712 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700713 /* skip zygote -- it won't dump its stack anyway */
714 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700715 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700716 len = read(cfd, data, sizeof(data) - 1);
717 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700718 if (len <= 0) {
719 continue;
720 }
721 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -0700722 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700723 continue;
724 }
725
726 ++dalvik_found;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800727 uint64_t start = nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -0700728 if (kill(pid, SIGQUIT)) {
729 fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
730 continue;
731 }
732
733 /* wait for the writable-close notification from inotify */
734 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -0700735 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -0700736 if (ret < 0) {
737 fprintf(stderr, "poll: %s\n", strerror(errno));
738 } else if (ret == 0) {
739 fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
740 } else {
741 struct inotify_event ie;
742 read(ifd, &ie, sizeof(ie));
743 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700744
745 if (lseek(fd, 0, SEEK_END) < 0) {
746 fprintf(stderr, "lseek: %s\n", strerror(errno));
747 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800748 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Jeff Brown1dc94e32014-09-11 14:15:27 -0700749 pid, (float)(nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700750 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700751 } else if (should_dump_native_traces(data)) {
752 /* dump native process if appropriate */
753 if (lseek(fd, 0, SEEK_END) < 0) {
754 fprintf(stderr, "lseek: %s\n", strerror(errno));
755 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800756 static uint16_t timeout_failures = 0;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800757 uint64_t start = nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -0800758
759 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
760 if (timeout_failures == 3) {
761 dprintf(fd, "too many stack dump failures, skipping...\n");
762 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
763 dprintf(fd, "dumping failed, likely due to a timeout\n");
764 timeout_failures++;
765 } else {
766 timeout_failures = 0;
767 }
768 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Jeff Brown1dc94e32014-09-11 14:15:27 -0700769 pid, (float)(nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700770 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700771 }
772 }
773
Colin Crossf45fa6b2012-03-26 12:38:26 -0700774 if (dalvik_found == 0) {
775 fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
776 }
777
778 static char dump_traces_path[PATH_MAX];
779 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
780 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
781 if (rename(traces_path, dump_traces_path)) {
782 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700783 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700784 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700785 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700786
787 /* replace the saved [ANR] traces.txt file */
788 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700789
790error_close_ifd:
791 close(ifd);
792error_close_fd:
793 close(fd);
794 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700795}
796
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700797void dump_route_tables() {
798 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
799 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700800 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700801 if (!fp) {
802 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
803 return;
804 }
805 char table[16];
806 // Each line has an integer (the table number), a space, and a string (the table name). We only
807 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
808 // Add a fixed max limit so this doesn't go awry.
809 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
810 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
811 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
812 }
813 fclose(fp);
814}