utils.cpp revision 36b3f6ff17e456dea81501006e33d5fdd1d3b480
1/* 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> 27#include <string.h> 28#include <sys/inotify.h> 29#include <sys/stat.h> 30#include <sys/time.h> 31#include <sys/wait.h> 32#include <sys/klog.h> 33#include <time.h> 34#include <unistd.h> 35#include <vector> 36#include <sys/prctl.h> 37 38#include <cutils/debugger.h> 39#include <cutils/properties.h> 40#include <cutils/sockets.h> 41#include <private/android_filesystem_config.h> 42 43#include <selinux/android.h> 44 45#include "dumpstate.h" 46 47static const int64_t NANOS_PER_SEC = 1000000000; 48 49/* list of native processes to include in the native dumps */ 50static const char* native_processes_to_dump[] = { 51 "/system/bin/drmserver", 52 "/system/bin/mediaserver", 53 "/system/bin/sdcard", 54 "/system/bin/surfaceflinger", 55 "/system/bin/vehicle_network_service", 56 NULL, 57}; 58 59static uint64_t nanotime() { 60 struct timespec ts; 61 clock_gettime(CLOCK_MONOTONIC, &ts); 62 return (uint64_t)ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec; 63} 64 65void for_each_userid(void (*func)(int), const char *header) { 66 ON_DRY_RUN_RETURN(); 67 DIR *d; 68 struct dirent *de; 69 70 if (header) printf("\n------ %s ------\n", header); 71 func(0); 72 73 if (!(d = opendir("/data/system/users"))) { 74 printf("Failed to open /data/system/users (%s)\n", strerror(errno)); 75 return; 76 } 77 78 while ((de = readdir(d))) { 79 int userid; 80 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) { 81 continue; 82 } 83 func(userid); 84 } 85 86 closedir(d); 87} 88 89static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) { 90 DIR *d; 91 struct dirent *de; 92 93 if (!(d = opendir("/proc"))) { 94 printf("Failed to open /proc (%s)\n", strerror(errno)); 95 return; 96 } 97 98 printf("\n------ %s ------\n", header); 99 while ((de = readdir(d))) { 100 int pid; 101 int fd; 102 char cmdpath[255]; 103 char cmdline[255]; 104 105 if (!(pid = atoi(de->d_name))) { 106 continue; 107 } 108 109 sprintf(cmdpath,"/proc/%d/cmdline", pid); 110 memset(cmdline, 0, sizeof(cmdline)); 111 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) < 0) { 112 strcpy(cmdline, "N/A"); 113 } else { 114 read(fd, cmdline, sizeof(cmdline) - 1); 115 close(fd); 116 } 117 helper(pid, cmdline, arg); 118 } 119 120 closedir(d); 121} 122 123static void for_each_pid_helper(int pid, const char *cmdline, void *arg) { 124 for_each_pid_func *func = (for_each_pid_func*) arg; 125 func(pid, cmdline); 126} 127 128void for_each_pid(for_each_pid_func func, const char *header) { 129 ON_DRY_RUN_RETURN(); 130 __for_each_pid(for_each_pid_helper, header, (void *)func); 131} 132 133static void for_each_tid_helper(int pid, const char *cmdline, void *arg) { 134 DIR *d; 135 struct dirent *de; 136 char taskpath[255]; 137 for_each_tid_func *func = (for_each_tid_func *) arg; 138 139 sprintf(taskpath, "/proc/%d/task", pid); 140 141 if (!(d = opendir(taskpath))) { 142 printf("Failed to open %s (%s)\n", taskpath, strerror(errno)); 143 return; 144 } 145 146 func(pid, pid, cmdline); 147 148 while ((de = readdir(d))) { 149 int tid; 150 int fd; 151 char commpath[255]; 152 char comm[255]; 153 154 if (!(tid = atoi(de->d_name))) { 155 continue; 156 } 157 158 if (tid == pid) 159 continue; 160 161 sprintf(commpath,"/proc/%d/comm", tid); 162 memset(comm, 0, sizeof(comm)); 163 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) { 164 strcpy(comm, "N/A"); 165 } else { 166 char *c; 167 read(fd, comm, sizeof(comm) - 1); 168 close(fd); 169 170 c = strrchr(comm, '\n'); 171 if (c) { 172 *c = '\0'; 173 } 174 } 175 func(pid, tid, comm); 176 } 177 178 closedir(d); 179} 180 181void for_each_tid(for_each_tid_func func, const char *header) { 182 ON_DRY_RUN_RETURN(); 183 __for_each_pid(for_each_tid_helper, header, (void *) func); 184} 185 186void show_wchan(int pid, int tid, const char *name) { 187 ON_DRY_RUN_RETURN(); 188 char path[255]; 189 char buffer[255]; 190 int fd; 191 char name_buffer[255]; 192 193 memset(buffer, 0, sizeof(buffer)); 194 195 sprintf(path, "/proc/%d/wchan", tid); 196 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) { 197 printf("Failed to open '%s' (%s)\n", path, strerror(errno)); 198 return; 199 } 200 201 if (read(fd, buffer, sizeof(buffer)) < 0) { 202 printf("Failed to read '%s' (%s)\n", path, strerror(errno)); 203 goto out_close; 204 } 205 206 snprintf(name_buffer, sizeof(name_buffer), "%*s%s", 207 pid == tid ? 0 : 3, "", name); 208 209 printf("%-7d %-32s %s\n", tid, name_buffer, buffer); 210 211out_close: 212 close(fd); 213 return; 214} 215 216void do_dmesg() { 217 printf("------ KERNEL LOG (dmesg) ------\n"); 218 ON_DRY_RUN_RETURN(); 219 /* Get size of kernel buffer */ 220 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0); 221 if (size <= 0) { 222 printf("Unexpected klogctl return value: %d\n\n", size); 223 return; 224 } 225 char *buf = (char *) malloc(size + 1); 226 if (buf == NULL) { 227 printf("memory allocation failed\n\n"); 228 return; 229 } 230 int retval = klogctl(KLOG_READ_ALL, buf, size); 231 if (retval < 0) { 232 printf("klogctl failure\n\n"); 233 free(buf); 234 return; 235 } 236 buf[retval] = '\0'; 237 printf("%s\n\n", buf); 238 free(buf); 239 return; 240} 241 242void do_showmap(int pid, const char *name) { 243 char title[255]; 244 char arg[255]; 245 246 sprintf(title, "SHOW MAP %d (%s)", pid, name); 247 sprintf(arg, "%d", pid); 248 run_command(title, 10, SU_PATH, "root", "showmap", arg, NULL); 249} 250 251static int _dump_file_from_fd(const char *title, const char *path, int fd) { 252 if (title) { 253 printf("------ %s (%s", title, path); 254 255 struct stat st; 256 // Only show the modification time of non-device files. 257 size_t path_len = strlen(path); 258 if ((path_len < 6 || memcmp(path, "/proc/", 6)) && 259 (path_len < 5 || memcmp(path, "/sys/", 5)) && 260 (path_len < 3 || memcmp(path, "/d/", 3)) && 261 !fstat(fd, &st)) { 262 char stamp[80]; 263 time_t mtime = st.st_mtime; 264 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime)); 265 printf(": %s", stamp); 266 } 267 printf(") ------\n"); 268 } 269 ON_DRY_RUN({ close(fd); return 0; }); 270 271 bool newline = false; 272 fd_set read_set; 273 struct timeval tm; 274 while (1) { 275 FD_ZERO(&read_set); 276 FD_SET(fd, &read_set); 277 /* Timeout if no data is read for 30 seconds. */ 278 tm.tv_sec = 30; 279 tm.tv_usec = 0; 280 uint64_t elapsed = nanotime(); 281 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm)); 282 if (ret == -1) { 283 printf("*** %s: select failed: %s\n", path, strerror(errno)); 284 newline = true; 285 break; 286 } else if (ret == 0) { 287 elapsed = nanotime() - elapsed; 288 printf("*** %s: Timed out after %.3fs\n", path, 289 (float) elapsed / NANOS_PER_SEC); 290 newline = true; 291 break; 292 } else { 293 char buffer[65536]; 294 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer))); 295 if (bytes_read > 0) { 296 fwrite(buffer, bytes_read, 1, stdout); 297 newline = (buffer[bytes_read-1] == '\n'); 298 } else { 299 if (bytes_read == -1) { 300 printf("*** %s: Failed to read from fd: %s", path, strerror(errno)); 301 newline = true; 302 } 303 break; 304 } 305 } 306 } 307 close(fd); 308 309 if (!newline) printf("\n"); 310 if (title) printf("\n"); 311 return 0; 312} 313 314/* prints the contents of a file */ 315int dump_file(const char *title, const char *path) { 316 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC)); 317 if (fd < 0) { 318 int err = errno; 319 printf("*** %s: %s\n", path, strerror(err)); 320 if (title) printf("\n"); 321 return -1; 322 } 323 return _dump_file_from_fd(title, path, fd); 324} 325 326/* calls skip to gate calling dump_from_fd recursively 327 * in the specified directory. dump_from_fd defaults to 328 * dump_file_from_fd above when set to NULL. skip defaults 329 * to false when set to NULL. dump_from_fd will always be 330 * called with title NULL. 331 */ 332int dump_files(const char *title, const char *dir, 333 bool (*skip)(const char *path), 334 int (*dump_from_fd)(const char *title, const char *path, int fd)) { 335 DIR *dirp; 336 struct dirent *d; 337 char *newpath = NULL; 338 const char *slash = "/"; 339 int fd, retval = 0; 340 341 if (title) { 342 printf("------ %s (%s) ------\n", title, dir); 343 } 344 ON_DRY_RUN_RETURN(0); 345 346 if (dir[strlen(dir) - 1] == '/') { 347 ++slash; 348 } 349 dirp = opendir(dir); 350 if (dirp == NULL) { 351 retval = -errno; 352 fprintf(stderr, "%s: %s\n", dir, strerror(errno)); 353 return retval; 354 } 355 356 if (!dump_from_fd) { 357 dump_from_fd = dump_file_from_fd; 358 } 359 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) { 360 if ((d->d_name[0] == '.') 361 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0')) 362 || (d->d_name[1] == '\0'))) { 363 continue; 364 } 365 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name, 366 (d->d_type == DT_DIR) ? "/" : ""); 367 if (!newpath) { 368 retval = -errno; 369 continue; 370 } 371 if (skip && (*skip)(newpath)) { 372 continue; 373 } 374 if (d->d_type == DT_DIR) { 375 int ret = dump_files(NULL, newpath, skip, dump_from_fd); 376 if (ret < 0) { 377 retval = ret; 378 } 379 continue; 380 } 381 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)); 382 if (fd < 0) { 383 retval = fd; 384 printf("*** %s: %s\n", newpath, strerror(errno)); 385 continue; 386 } 387 (*dump_from_fd)(NULL, newpath, fd); 388 } 389 closedir(dirp); 390 if (title) { 391 printf("\n"); 392 } 393 return retval; 394} 395 396/* fd must have been opened with the flag O_NONBLOCK. With this flag set, 397 * it's possible to avoid issues where opening the file itself can get 398 * stuck. 399 */ 400int dump_file_from_fd(const char *title, const char *path, int fd) { 401 int flags = fcntl(fd, F_GETFL); 402 if (flags == -1) { 403 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno)); 404 close(fd); 405 return -1; 406 } else if (!(flags & O_NONBLOCK)) { 407 printf("*** %s: fd must have O_NONBLOCK set.\n", path); 408 close(fd); 409 return -1; 410 } 411 return _dump_file_from_fd(title, path, fd); 412} 413 414bool 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 458/* forks a command and waits for it to finish */ 459int run_command(const char *title, int timeout_seconds, const char *command, ...) { 460 fflush(stdout); 461 462 const char *args[1024] = {command}; 463 size_t arg; 464 va_list ap; 465 va_start(ap, command); 466 if (title) printf("------ %s (%s", title, command); 467 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) { 468 args[arg] = va_arg(ap, const char *); 469 if (args[arg] == NULL) break; 470 if (title) printf(" %s", args[arg]); 471 } 472 if (title) printf(") ------\n"); 473 fflush(stdout); 474 475 ON_DRY_RUN_RETURN(0); 476 477 return run_command_always(title, timeout_seconds, args); 478} 479 480/* forks a command and waits for it to finish */ 481int run_command_always(const char *title, int timeout_seconds, const char *args[]) { 482 483 const char *command = args[0]; 484 uint64_t start = nanotime(); 485 pid_t pid = fork(); 486 487 /* handle error case */ 488 if (pid < 0) { 489 printf("*** fork: %s\n", strerror(errno)); 490 return pid; 491 } 492 493 /* handle child case */ 494 if (pid == 0) { 495 496 /* make sure the child dies when dumpstate dies */ 497 prctl(PR_SET_PDEATHSIG, SIGKILL); 498 499 /* just ignore SIGPIPE, will go down with parent's */ 500 struct sigaction sigact; 501 memset(&sigact, 0, sizeof(sigact)); 502 sigact.sa_handler = SIG_IGN; 503 sigaction(SIGPIPE, &sigact, NULL); 504 505 execvp(command, (char**) args); 506 printf("*** exec(%s): %s\n", command, strerror(errno)); 507 fflush(stdout); 508 _exit(-1); 509 } 510 511 /* handle parent case */ 512 int status; 513 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status); 514 uint64_t elapsed = nanotime() - start; 515 if (!ret) { 516 if (errno == ETIMEDOUT) { 517 printf("*** %s: Timed out after %.3fs (killing pid %d)\n", command, 518 (float) elapsed / NANOS_PER_SEC, pid); 519 } else { 520 printf("*** %s: Error after %.4fs (killing pid %d)\n", command, 521 (float) elapsed / NANOS_PER_SEC, pid); 522 } 523 kill(pid, SIGTERM); 524 if (!waitpid_with_timeout(pid, 5, NULL)) { 525 kill(pid, SIGKILL); 526 if (!waitpid_with_timeout(pid, 5, NULL)) { 527 printf("*** %s: Cannot kill %d even with SIGKILL.\n", command, pid); 528 } 529 } 530 return -1; 531 } 532 533 if (WIFSIGNALED(status)) { 534 printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status)); 535 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) { 536 printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status)); 537 } 538 if (title) printf("[%s: %.3fs elapsed]\n\n", command, (float)elapsed / NANOS_PER_SEC); 539 540 return status; 541} 542 543void send_broadcast(const std::string& action, const std::vector<std::string>& args) { 544 if (args.size() > 1000) { 545 fprintf(stderr, "send_broadcast: too many arguments (%d)\n", args.size()); 546 return; 547 } 548 const char *am_args[1024] = { "/system/bin/am", "broadcast", "--user", "0", 549 "-a", action.c_str() }; 550 size_t am_index = 5; // Starts at the index of last initial value above. 551 for (const std::string& arg : args) { 552 am_args[++am_index] = arg.c_str(); 553 } 554 // Always terminate with NULL. 555 am_args[am_index + 1] = NULL; 556 run_command_always(NULL, 5, am_args); 557} 558 559size_t num_props = 0; 560static char* props[2000]; 561 562static void print_prop(const char *key, const char *name, void *user) { 563 (void) user; 564 if (num_props < sizeof(props) / sizeof(props[0])) { 565 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10]; 566 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name); 567 props[num_props++] = strdup(buf); 568 } 569} 570 571static int compare_prop(const void *a, const void *b) { 572 return strcmp(*(char * const *) a, *(char * const *) b); 573} 574 575/* prints all the system properties */ 576void print_properties() { 577 printf("------ SYSTEM PROPERTIES ------\n"); 578 ON_DRY_RUN_RETURN(); 579 size_t i; 580 num_props = 0; 581 property_list(print_prop, NULL); 582 qsort(&props, num_props, sizeof(props[0]), compare_prop); 583 584 for (i = 0; i < num_props; ++i) { 585 fputs(props[i], stdout); 586 free(props[i]); 587 } 588 printf("\n"); 589} 590 591/* redirect output to a service control socket */ 592void redirect_to_socket(FILE *redirect, const char *service) { 593 int s = android_get_control_socket(service); 594 if (s < 0) { 595 fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno)); 596 exit(1); 597 } 598 fcntl(s, F_SETFD, FD_CLOEXEC); 599 if (listen(s, 4) < 0) { 600 fprintf(stderr, "listen(control socket): %s\n", strerror(errno)); 601 exit(1); 602 } 603 604 struct sockaddr addr; 605 socklen_t alen = sizeof(addr); 606 int fd = accept(s, &addr, &alen); 607 if (fd < 0) { 608 fprintf(stderr, "accept(control socket): %s\n", strerror(errno)); 609 exit(1); 610 } 611 612 fflush(redirect); 613 dup2(fd, fileno(redirect)); 614 close(fd); 615} 616 617/* redirect output to a file */ 618void redirect_to_file(FILE *redirect, char *path) { 619 char *chp = path; 620 621 /* skip initial slash */ 622 if (chp[0] == '/') 623 chp++; 624 625 /* create leading directories, if necessary */ 626 while (chp && chp[0]) { 627 chp = strchr(chp, '/'); 628 if (chp) { 629 *chp = 0; 630 mkdir(path, 0770); /* drwxrwx--- */ 631 *chp++ = '/'; 632 } 633 } 634 635 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 636 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)); 637 if (fd < 0) { 638 fprintf(stderr, "%s: %s\n", path, strerror(errno)); 639 exit(1); 640 } 641 642 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect))); 643 close(fd); 644} 645 646static bool should_dump_native_traces(const char* path) { 647 for (const char** p = native_processes_to_dump; *p; p++) { 648 if (!strcmp(*p, path)) { 649 return true; 650 } 651 } 652 return false; 653} 654 655/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */ 656const char *dump_traces() { 657 ON_DRY_RUN_RETURN(NULL); 658 const char* result = NULL; 659 660 char traces_path[PROPERTY_VALUE_MAX] = ""; 661 property_get("dalvik.vm.stack-trace-file", traces_path, ""); 662 if (!traces_path[0]) return NULL; 663 664 /* move the old traces.txt (if any) out of the way temporarily */ 665 char anr_traces_path[PATH_MAX]; 666 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path)); 667 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path)); 668 if (rename(traces_path, anr_traces_path) && errno != ENOENT) { 669 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno)); 670 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead 671 } 672 673 /* create a new, empty traces.txt file to receive stack dumps */ 674 int fd = TEMP_FAILURE_RETRY(open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 675 0666)); /* -rw-rw-rw- */ 676 if (fd < 0) { 677 fprintf(stderr, "%s: %s\n", traces_path, strerror(errno)); 678 return NULL; 679 } 680 int chmod_ret = fchmod(fd, 0666); 681 if (chmod_ret < 0) { 682 fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno)); 683 close(fd); 684 return NULL; 685 } 686 687 /* Variables below must be initialized before 'goto' statements */ 688 int dalvik_found = 0; 689 int ifd, wfd = -1; 690 691 /* walk /proc and kill -QUIT all Dalvik processes */ 692 DIR *proc = opendir("/proc"); 693 if (proc == NULL) { 694 fprintf(stderr, "/proc: %s\n", strerror(errno)); 695 goto error_close_fd; 696 } 697 698 /* use inotify to find when processes are done dumping */ 699 ifd = inotify_init(); 700 if (ifd < 0) { 701 fprintf(stderr, "inotify_init: %s\n", strerror(errno)); 702 goto error_close_fd; 703 } 704 705 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE); 706 if (wfd < 0) { 707 fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno)); 708 goto error_close_ifd; 709 } 710 711 struct dirent *d; 712 while ((d = readdir(proc))) { 713 int pid = atoi(d->d_name); 714 if (pid <= 0) continue; 715 716 char path[PATH_MAX]; 717 char data[PATH_MAX]; 718 snprintf(path, sizeof(path), "/proc/%d/exe", pid); 719 ssize_t len = readlink(path, data, sizeof(data) - 1); 720 if (len <= 0) { 721 continue; 722 } 723 data[len] = '\0'; 724 725 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) { 726 /* skip zygote -- it won't dump its stack anyway */ 727 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid); 728 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC)); 729 len = read(cfd, data, sizeof(data) - 1); 730 close(cfd); 731 if (len <= 0) { 732 continue; 733 } 734 data[len] = '\0'; 735 if (!strncmp(data, "zygote", strlen("zygote"))) { 736 continue; 737 } 738 739 ++dalvik_found; 740 uint64_t start = nanotime(); 741 if (kill(pid, SIGQUIT)) { 742 fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno)); 743 continue; 744 } 745 746 /* wait for the writable-close notification from inotify */ 747 struct pollfd pfd = { ifd, POLLIN, 0 }; 748 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */ 749 if (ret < 0) { 750 fprintf(stderr, "poll: %s\n", strerror(errno)); 751 } else if (ret == 0) { 752 fprintf(stderr, "warning: timed out dumping pid %d\n", pid); 753 } else { 754 struct inotify_event ie; 755 read(ifd, &ie, sizeof(ie)); 756 } 757 758 if (lseek(fd, 0, SEEK_END) < 0) { 759 fprintf(stderr, "lseek: %s\n", strerror(errno)); 760 } else { 761 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", 762 pid, (float)(nanotime() - start) / NANOS_PER_SEC); 763 } 764 } else if (should_dump_native_traces(data)) { 765 /* dump native process if appropriate */ 766 if (lseek(fd, 0, SEEK_END) < 0) { 767 fprintf(stderr, "lseek: %s\n", strerror(errno)); 768 } else { 769 static uint16_t timeout_failures = 0; 770 uint64_t start = nanotime(); 771 772 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */ 773 if (timeout_failures == 3) { 774 dprintf(fd, "too many stack dump failures, skipping...\n"); 775 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) { 776 dprintf(fd, "dumping failed, likely due to a timeout\n"); 777 timeout_failures++; 778 } else { 779 timeout_failures = 0; 780 } 781 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", 782 pid, (float)(nanotime() - start) / NANOS_PER_SEC); 783 } 784 } 785 } 786 787 if (dalvik_found == 0) { 788 fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n"); 789 } 790 791 static char dump_traces_path[PATH_MAX]; 792 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path)); 793 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path)); 794 if (rename(traces_path, dump_traces_path)) { 795 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno)); 796 goto error_close_ifd; 797 } 798 result = dump_traces_path; 799 800 /* replace the saved [ANR] traces.txt file */ 801 rename(anr_traces_path, traces_path); 802 803error_close_ifd: 804 close(ifd); 805error_close_fd: 806 close(fd); 807 return result; 808} 809 810void dump_route_tables() { 811 ON_DRY_RUN_RETURN(); 812 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables"; 813 dump_file("RT_TABLES", RT_TABLES_PATH); 814 FILE* fp = fopen(RT_TABLES_PATH, "re"); 815 if (!fp) { 816 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno)); 817 return; 818 } 819 char table[16]; 820 // Each line has an integer (the table number), a space, and a string (the table name). We only 821 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name. 822 // Add a fixed max limit so this doesn't go awry. 823 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) { 824 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL); 825 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL); 826 } 827 fclose(fp); 828} 829