dumpstate.cpp revision ad5f6c475934ac6a658a203069a9f055540946e7
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 <libgen.h> 21#include <limits.h> 22#include <memory> 23#include <regex> 24#include <stdbool.h> 25#include <stdio.h> 26#include <stdlib.h> 27#include <string> 28#include <string.h> 29#include <sys/capability.h> 30#include <sys/prctl.h> 31#include <sys/resource.h> 32#include <sys/stat.h> 33#include <sys/time.h> 34#include <sys/wait.h> 35#include <unistd.h> 36 37#include <base/stringprintf.h> 38#include <cutils/properties.h> 39 40#include "private/android_filesystem_config.h" 41 42#define LOG_TAG "dumpstate" 43#include <cutils/log.h> 44 45#include "dumpstate.h" 46#include "ScopedFd.h" 47#include "ziparchive/zip_writer.h" 48 49using android::base::StringPrintf; 50 51/* read before root is shed */ 52static char cmdline_buf[16384] = "(unknown)"; 53static const char *dump_traces_path = NULL; 54 55static std::string screenshot_path; 56 57#define PSTORE_LAST_KMSG "/sys/fs/pstore/console-ramoops" 58 59#define RAFT_DIR "/data/misc/raft/" 60#define TOMBSTONE_DIR "/data/tombstones" 61#define TOMBSTONE_FILE_PREFIX TOMBSTONE_DIR "/tombstone_" 62/* Can accomodate a tombstone number up to 9999. */ 63#define TOMBSTONE_MAX_LEN (sizeof(TOMBSTONE_FILE_PREFIX) + 4) 64#define NUM_TOMBSTONES 10 65 66typedef struct { 67 char name[TOMBSTONE_MAX_LEN]; 68 int fd; 69} tombstone_data_t; 70 71static tombstone_data_t tombstone_data[NUM_TOMBSTONES]; 72 73/* Get the fds of any tombstone that was modified in the last half an hour. */ 74static void get_tombstone_fds(tombstone_data_t data[NUM_TOMBSTONES]) { 75 time_t thirty_minutes_ago = time(NULL) - 60*30; 76 for (size_t i = 0; i < NUM_TOMBSTONES; i++) { 77 snprintf(data[i].name, sizeof(data[i].name), "%s%02zu", TOMBSTONE_FILE_PREFIX, i); 78 int fd = TEMP_FAILURE_RETRY(open(data[i].name, 79 O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); 80 struct stat st; 81 if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && 82 (time_t) st.st_mtime >= thirty_minutes_ago) { 83 data[i].fd = fd; 84 } else { 85 close(fd); 86 data[i].fd = -1; 87 } 88 } 89} 90 91static void dump_dev_files(const char *title, const char *driverpath, const char *filename) 92{ 93 DIR *d; 94 struct dirent *de; 95 char path[PATH_MAX]; 96 97 d = opendir(driverpath); 98 if (d == NULL) { 99 return; 100 } 101 102 while ((de = readdir(d))) { 103 if (de->d_type != DT_LNK) { 104 continue; 105 } 106 snprintf(path, sizeof(path), "%s/%s/%s", driverpath, de->d_name, filename); 107 dump_file(title, path); 108 } 109 110 closedir(d); 111} 112 113static bool skip_not_stat(const char *path) { 114 static const char stat[] = "/stat"; 115 size_t len = strlen(path); 116 if (path[len - 1] == '/') { /* Directory? */ 117 return false; 118 } 119 return strcmp(path + len - sizeof(stat) + 1, stat); /* .../stat? */ 120} 121 122static const char mmcblk0[] = "/sys/block/mmcblk0/"; 123unsigned long worst_write_perf = 20000; /* in KB/s */ 124 125static int dump_stat_from_fd(const char *title __unused, const char *path, int fd) { 126 unsigned long fields[11], read_perf, write_perf; 127 bool z; 128 char *cp, *buffer = NULL; 129 size_t i = 0; 130 FILE *fp = fdopen(fd, "rb"); 131 getline(&buffer, &i, fp); 132 fclose(fp); 133 if (!buffer) { 134 return -errno; 135 } 136 i = strlen(buffer); 137 while ((i > 0) && (buffer[i - 1] == '\n')) { 138 buffer[--i] = '\0'; 139 } 140 if (!*buffer) { 141 free(buffer); 142 return 0; 143 } 144 z = true; 145 for (cp = buffer, i = 0; i < (sizeof(fields) / sizeof(fields[0])); ++i) { 146 fields[i] = strtol(cp, &cp, 0); 147 if (fields[i] != 0) { 148 z = false; 149 } 150 } 151 if (z) { /* never accessed */ 152 free(buffer); 153 return 0; 154 } 155 156 if (!strncmp(path, mmcblk0, sizeof(mmcblk0) - 1)) { 157 path += sizeof(mmcblk0) - 1; 158 } 159 160 printf("%s: %s\n", path, buffer); 161 free(buffer); 162 163 read_perf = 0; 164 if (fields[3]) { 165 read_perf = 512 * fields[2] / fields[3]; 166 } 167 write_perf = 0; 168 if (fields[7]) { 169 write_perf = 512 * fields[6] / fields[7]; 170 } 171 printf("%s: read: %luKB/s write: %luKB/s\n", path, read_perf, write_perf); 172 if ((write_perf > 1) && (write_perf < worst_write_perf)) { 173 worst_write_perf = write_perf; 174 } 175 return 0; 176} 177 178/* Copied policy from system/core/logd/LogBuffer.cpp */ 179 180#define LOG_BUFFER_SIZE (256 * 1024) 181#define LOG_BUFFER_MIN_SIZE (64 * 1024UL) 182#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL) 183 184static bool valid_size(unsigned long value) { 185 if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) { 186 return false; 187 } 188 189 long pages = sysconf(_SC_PHYS_PAGES); 190 if (pages < 1) { 191 return true; 192 } 193 194 long pagesize = sysconf(_SC_PAGESIZE); 195 if (pagesize <= 1) { 196 pagesize = PAGE_SIZE; 197 } 198 199 // maximum memory impact a somewhat arbitrary ~3% 200 pages = (pages + 31) / 32; 201 unsigned long maximum = pages * pagesize; 202 203 if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) { 204 return true; 205 } 206 207 return value <= maximum; 208} 209 210static unsigned long property_get_size(const char *key) { 211 unsigned long value; 212 char *cp, property[PROPERTY_VALUE_MAX]; 213 214 property_get(key, property, ""); 215 value = strtoul(property, &cp, 10); 216 217 switch(*cp) { 218 case 'm': 219 case 'M': 220 value *= 1024; 221 /* FALLTHRU */ 222 case 'k': 223 case 'K': 224 value *= 1024; 225 /* FALLTHRU */ 226 case '\0': 227 break; 228 229 default: 230 value = 0; 231 } 232 233 if (!valid_size(value)) { 234 value = 0; 235 } 236 237 return value; 238} 239 240/* timeout in ms */ 241static unsigned long logcat_timeout(const char *name) { 242 static const char global_tuneable[] = "persist.logd.size"; // Settings App 243 static const char global_default[] = "ro.logd.size"; // BoardConfig.mk 244 char key[PROP_NAME_MAX]; 245 unsigned long property_size, default_size; 246 247 default_size = property_get_size(global_tuneable); 248 if (!default_size) { 249 default_size = property_get_size(global_default); 250 } 251 252 snprintf(key, sizeof(key), "%s.%s", global_tuneable, name); 253 property_size = property_get_size(key); 254 255 if (!property_size) { 256 snprintf(key, sizeof(key), "%s.%s", global_default, name); 257 property_size = property_get_size(key); 258 } 259 260 if (!property_size) { 261 property_size = default_size; 262 } 263 264 if (!property_size) { 265 property_size = LOG_BUFFER_SIZE; 266 } 267 268 /* Engineering margin is ten-fold our guess */ 269 return 10 * (property_size + worst_write_perf) / worst_write_perf; 270} 271 272/* End copy from system/core/logd/LogBuffer.cpp */ 273 274/* dumps the current system state to stdout */ 275static void dumpstate() { 276 unsigned long timeout; 277 time_t now = time(NULL); 278 char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX]; 279 char radio[PROPERTY_VALUE_MAX], bootloader[PROPERTY_VALUE_MAX]; 280 char network[PROPERTY_VALUE_MAX], date[80]; 281 char build_type[PROPERTY_VALUE_MAX]; 282 283 property_get("ro.build.display.id", build, "(unknown)"); 284 property_get("ro.build.fingerprint", fingerprint, "(unknown)"); 285 property_get("ro.build.type", build_type, "(unknown)"); 286 property_get("ro.baseband", radio, "(unknown)"); 287 property_get("ro.bootloader", bootloader, "(unknown)"); 288 property_get("gsm.operator.alpha", network, "(unknown)"); 289 strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now)); 290 291 printf("========================================================\n"); 292 printf("== dumpstate: %s\n", date); 293 printf("========================================================\n"); 294 295 printf("\n"); 296 printf("Build: %s\n", build); 297 printf("Build fingerprint: '%s'\n", fingerprint); /* format is important for other tools */ 298 printf("Bootloader: %s\n", bootloader); 299 printf("Radio: %s\n", radio); 300 printf("Network: %s\n", network); 301 302 printf("Kernel: "); 303 dump_file(NULL, "/proc/version"); 304 printf("Command line: %s\n", strtok(cmdline_buf, "\n")); 305 printf("\n"); 306 307 dump_dev_files("TRUSTY VERSION", "/sys/bus/platform/drivers/trusty", "trusty_version"); 308 run_command("UPTIME", 10, "uptime", NULL); 309 dump_files("UPTIME MMC PERF", mmcblk0, skip_not_stat, dump_stat_from_fd); 310 dump_file("MEMORY INFO", "/proc/meminfo"); 311 run_command("CPU INFO", 10, "top", "-n", "1", "-d", "1", "-m", "30", "-H", NULL); 312 run_command("PROCRANK", 20, SU_PATH, "root", "procrank", NULL); 313 dump_file("VIRTUAL MEMORY STATS", "/proc/vmstat"); 314 dump_file("VMALLOC INFO", "/proc/vmallocinfo"); 315 dump_file("SLAB INFO", "/proc/slabinfo"); 316 dump_file("ZONEINFO", "/proc/zoneinfo"); 317 dump_file("PAGETYPEINFO", "/proc/pagetypeinfo"); 318 dump_file("BUDDYINFO", "/proc/buddyinfo"); 319 dump_file("FRAGMENTATION INFO", "/d/extfrag/unusable_index"); 320 321 dump_file("KERNEL WAKELOCKS", "/proc/wakelocks"); 322 dump_file("KERNEL WAKE SOURCES", "/d/wakeup_sources"); 323 dump_file("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state"); 324 dump_file("KERNEL SYNC", "/d/sync"); 325 326 run_command("PROCESSES AND THREADS", 10, "ps", "-Z", "-t", "-p", "-P", NULL); 327 run_command("LIBRANK", 10, SU_PATH, "root", "librank", NULL); 328 329 do_dmesg(); 330 331 run_command("LIST OF OPEN FILES", 10, SU_PATH, "root", "lsof", NULL); 332 for_each_pid(do_showmap, "SMAPS OF ALL PROCESSES"); 333 for_each_tid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS"); 334 335 if (!screenshot_path.empty()) { 336 ALOGI("taking screenshot\n"); 337 const char *args[] = { "/system/bin/screencap", "-p", screenshot_path.c_str(), NULL }; 338 run_command_always(NULL, 10, args); 339 ALOGI("wrote screenshot: %s\n", screenshot_path.c_str()); 340 } 341 342 // dump_file("EVENT LOG TAGS", "/etc/event-log-tags"); 343 // calculate timeout 344 timeout = logcat_timeout("main") + logcat_timeout("system") + logcat_timeout("crash"); 345 if (timeout < 20000) { 346 timeout = 20000; 347 } 348 run_command("SYSTEM LOG", timeout / 1000, "logcat", "-v", "threadtime", 349 "-v", "printable", 350 "-d", 351 "*:v", NULL); 352 timeout = logcat_timeout("events"); 353 if (timeout < 20000) { 354 timeout = 20000; 355 } 356 run_command("EVENT LOG", timeout / 1000, "logcat", "-b", "events", 357 "-v", "threadtime", 358 "-v", "printable", 359 "-d", 360 "*:v", NULL); 361 timeout = logcat_timeout("radio"); 362 if (timeout < 20000) { 363 timeout = 20000; 364 } 365 run_command("RADIO LOG", timeout / 1000, "logcat", "-b", "radio", 366 "-v", "threadtime", 367 "-v", "printable", 368 "-d", 369 "*:v", NULL); 370 371 run_command("LOG STATISTICS", 10, "logcat", "-b", "all", "-S", NULL); 372 373 run_command("RAFT LOGS", 600, SU_PATH, "root", "logcompressor", "-r", RAFT_DIR, NULL); 374 375 /* show the traces we collected in main(), if that was done */ 376 if (dump_traces_path != NULL) { 377 dump_file("VM TRACES JUST NOW", dump_traces_path); 378 } 379 380 /* only show ANR traces if they're less than 15 minutes old */ 381 struct stat st; 382 char anr_traces_path[PATH_MAX]; 383 property_get("dalvik.vm.stack-trace-file", anr_traces_path, ""); 384 if (!anr_traces_path[0]) { 385 printf("*** NO VM TRACES FILE DEFINED (dalvik.vm.stack-trace-file)\n\n"); 386 } else { 387 int fd = TEMP_FAILURE_RETRY(open(anr_traces_path, 388 O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); 389 if (fd < 0) { 390 printf("*** NO ANR VM TRACES FILE (%s): %s\n\n", anr_traces_path, strerror(errno)); 391 } else { 392 dump_file_from_fd("VM TRACES AT LAST ANR", anr_traces_path, fd); 393 } 394 } 395 396 /* slow traces for slow operations */ 397 if (anr_traces_path[0] != 0) { 398 int tail = strlen(anr_traces_path)-1; 399 while (tail > 0 && anr_traces_path[tail] != '/') { 400 tail--; 401 } 402 int i = 0; 403 while (1) { 404 sprintf(anr_traces_path+tail+1, "slow%02d.txt", i); 405 if (stat(anr_traces_path, &st)) { 406 // No traces file at this index, done with the files. 407 break; 408 } 409 dump_file("VM TRACES WHEN SLOW", anr_traces_path); 410 i++; 411 } 412 } 413 414 int dumped = 0; 415 for (size_t i = 0; i < NUM_TOMBSTONES; i++) { 416 if (tombstone_data[i].fd != -1) { 417 dumped = 1; 418 dump_file_from_fd("TOMBSTONE", tombstone_data[i].name, tombstone_data[i].fd); 419 tombstone_data[i].fd = -1; 420 } 421 } 422 if (!dumped) { 423 printf("*** NO TOMBSTONES to dump in %s\n\n", TOMBSTONE_DIR); 424 } 425 426 dump_file("NETWORK DEV INFO", "/proc/net/dev"); 427 dump_file("QTAGUID NETWORK INTERFACES INFO", "/proc/net/xt_qtaguid/iface_stat_all"); 428 dump_file("QTAGUID NETWORK INTERFACES INFO (xt)", "/proc/net/xt_qtaguid/iface_stat_fmt"); 429 dump_file("QTAGUID CTRL INFO", "/proc/net/xt_qtaguid/ctrl"); 430 dump_file("QTAGUID STATS INFO", "/proc/net/xt_qtaguid/stats"); 431 432 if (!stat(PSTORE_LAST_KMSG, &st)) { 433 /* Also TODO: Make console-ramoops CAP_SYSLOG protected. */ 434 dump_file("LAST KMSG", PSTORE_LAST_KMSG); 435 } else { 436 /* TODO: Make last_kmsg CAP_SYSLOG protected. b/5555691 */ 437 dump_file("LAST KMSG", "/proc/last_kmsg"); 438 } 439 440 /* kernels must set CONFIG_PSTORE_PMSG, slice up pstore with device tree */ 441 run_command("LAST LOGCAT", 10, "logcat", "-L", 442 "-b", "all", 443 "-v", "threadtime", 444 "-v", "printable", 445 "-d", 446 "*:v", NULL); 447 448 /* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */ 449 450 run_command("NETWORK INTERFACES", 10, "ip", "link", NULL); 451 452 run_command("IPv4 ADDRESSES", 10, "ip", "-4", "addr", "show", NULL); 453 run_command("IPv6 ADDRESSES", 10, "ip", "-6", "addr", "show", NULL); 454 455 run_command("IP RULES", 10, "ip", "rule", "show", NULL); 456 run_command("IP RULES v6", 10, "ip", "-6", "rule", "show", NULL); 457 458 dump_route_tables(); 459 460 run_command("ARP CACHE", 10, "ip", "-4", "neigh", "show", NULL); 461 run_command("IPv6 ND CACHE", 10, "ip", "-6", "neigh", "show", NULL); 462 463 run_command("IPTABLES", 10, SU_PATH, "root", "iptables", "-L", "-nvx", NULL); 464 run_command("IP6TABLES", 10, SU_PATH, "root", "ip6tables", "-L", "-nvx", NULL); 465 run_command("IPTABLE NAT", 10, SU_PATH, "root", "iptables", "-t", "nat", "-L", "-nvx", NULL); 466 /* no ip6 nat */ 467 run_command("IPTABLE RAW", 10, SU_PATH, "root", "iptables", "-t", "raw", "-L", "-nvx", NULL); 468 run_command("IP6TABLE RAW", 10, SU_PATH, "root", "ip6tables", "-t", "raw", "-L", "-nvx", NULL); 469 470 run_command("WIFI NETWORKS", 20, 471 SU_PATH, "root", "wpa_cli", "IFNAME=wlan0", "list_networks", NULL); 472 473#ifdef FWDUMP_bcmdhd 474 run_command("ND OFFLOAD TABLE", 5, 475 SU_PATH, "root", "wlutil", "nd_hostip", NULL); 476 477 run_command("DUMP WIFI INTERNAL COUNTERS (1)", 20, 478 SU_PATH, "root", "wlutil", "counters", NULL); 479 480 run_command("ND OFFLOAD STATUS (1)", 5, 481 SU_PATH, "root", "wlutil", "nd_status", NULL); 482 483#endif 484 dump_file("INTERRUPTS (1)", "/proc/interrupts"); 485 486 run_command("NETWORK DIAGNOSTICS", 10, "dumpsys", "connectivity", "--diag", NULL); 487 488#ifdef FWDUMP_bcmdhd 489 run_command("DUMP WIFI STATUS", 20, 490 SU_PATH, "root", "dhdutil", "-i", "wlan0", "dump", NULL); 491 492 run_command("DUMP WIFI INTERNAL COUNTERS (2)", 20, 493 SU_PATH, "root", "wlutil", "counters", NULL); 494 495 run_command("ND OFFLOAD STATUS (2)", 5, 496 SU_PATH, "root", "wlutil", "nd_status", NULL); 497#endif 498 dump_file("INTERRUPTS (2)", "/proc/interrupts"); 499 500 print_properties(); 501 502 run_command("VOLD DUMP", 10, "vdc", "dump", NULL); 503 run_command("SECURE CONTAINERS", 10, "vdc", "asec", "list", NULL); 504 505 run_command("FILESYSTEMS & FREE SPACE", 10, "df", NULL); 506 507 run_command("LAST RADIO LOG", 10, "parse_radio_log", "/proc/last_radio_log", NULL); 508 509 printf("------ BACKLIGHTS ------\n"); 510 printf("LCD brightness="); 511 dump_file(NULL, "/sys/class/leds/lcd-backlight/brightness"); 512 printf("Button brightness="); 513 dump_file(NULL, "/sys/class/leds/button-backlight/brightness"); 514 printf("Keyboard brightness="); 515 dump_file(NULL, "/sys/class/leds/keyboard-backlight/brightness"); 516 printf("ALS mode="); 517 dump_file(NULL, "/sys/class/leds/lcd-backlight/als"); 518 printf("LCD driver registers:\n"); 519 dump_file(NULL, "/sys/class/leds/lcd-backlight/registers"); 520 printf("\n"); 521 522 /* Binder state is expensive to look at as it uses a lot of memory. */ 523 dump_file("BINDER FAILED TRANSACTION LOG", "/sys/kernel/debug/binder/failed_transaction_log"); 524 dump_file("BINDER TRANSACTION LOG", "/sys/kernel/debug/binder/transaction_log"); 525 dump_file("BINDER TRANSACTIONS", "/sys/kernel/debug/binder/transactions"); 526 dump_file("BINDER STATS", "/sys/kernel/debug/binder/stats"); 527 dump_file("BINDER STATE", "/sys/kernel/debug/binder/state"); 528 529 printf("========================================================\n"); 530 printf("== Board\n"); 531 printf("========================================================\n"); 532 533 dumpstate_board(); 534 printf("\n"); 535 536 /* Migrate the ril_dumpstate to a dumpstate_board()? */ 537 char ril_dumpstate_timeout[PROPERTY_VALUE_MAX] = {0}; 538 property_get("ril.dumpstate.timeout", ril_dumpstate_timeout, "30"); 539 if (strnlen(ril_dumpstate_timeout, PROPERTY_VALUE_MAX - 1) > 0) { 540 if (0 == strncmp(build_type, "user", PROPERTY_VALUE_MAX - 1)) { 541 // su does not exist on user builds, so try running without it. 542 // This way any implementations of vril-dump that do not require 543 // root can run on user builds. 544 run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout), 545 "vril-dump", NULL); 546 } else { 547 run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout), 548 SU_PATH, "root", "vril-dump", NULL); 549 } 550 } 551 552 printf("========================================================\n"); 553 printf("== Android Framework Services\n"); 554 printf("========================================================\n"); 555 556 /* the full dumpsys is starting to take a long time, so we need 557 to increase its timeout. we really need to do the timeouts in 558 dumpsys itself... */ 559 run_command("DUMPSYS", 60, "dumpsys", NULL); 560 561 printf("========================================================\n"); 562 printf("== Checkins\n"); 563 printf("========================================================\n"); 564 565 run_command("CHECKIN BATTERYSTATS", 30, "dumpsys", "batterystats", "-c", NULL); 566 run_command("CHECKIN MEMINFO", 30, "dumpsys", "meminfo", "--checkin", NULL); 567 run_command("CHECKIN NETSTATS", 30, "dumpsys", "netstats", "--checkin", NULL); 568 run_command("CHECKIN PROCSTATS", 30, "dumpsys", "procstats", "-c", NULL); 569 run_command("CHECKIN USAGESTATS", 30, "dumpsys", "usagestats", "-c", NULL); 570 run_command("CHECKIN PACKAGE", 30, "dumpsys", "package", "--checkin", NULL); 571 572 printf("========================================================\n"); 573 printf("== Running Application Activities\n"); 574 printf("========================================================\n"); 575 576 run_command("APP ACTIVITIES", 30, "dumpsys", "activity", "all", NULL); 577 578 printf("========================================================\n"); 579 printf("== Running Application Services\n"); 580 printf("========================================================\n"); 581 582 run_command("APP SERVICES", 30, "dumpsys", "activity", "service", "all", NULL); 583 584 printf("========================================================\n"); 585 printf("== Running Application Providers\n"); 586 printf("========================================================\n"); 587 588 run_command("APP SERVICES", 30, "dumpsys", "activity", "provider", "all", NULL); 589 590 591 printf("========================================================\n"); 592 printf("== dumpstate: done\n"); 593 printf("========================================================\n"); 594} 595 596static void usage() { 597 fprintf(stderr, "usage: dumpstate [-b soundfile] [-e soundfile] [-o file [-d] [-p] [-z]] [-s] [-q]\n" 598 " -o: write to file (instead of stdout)\n" 599 " -d: append date to filename (requires -o)\n" 600 " -z: generates zipped file (requires -o)\n" 601 " -p: capture screenshot to filename.png (requires -o)\n" 602 " -s: write output to control socket (for init)\n" 603 " -b: play sound file instead of vibrate, at beginning of job\n" 604 " -e: play sound file instead of vibrate, at end of job\n" 605 " -q: disable vibrate\n" 606 " -B: send broadcast when finished (requires -o)\n" 607 " -P: send broadacast when started and update system properties on progress (requires -o and -B)\n" 608 ); 609} 610 611static void sigpipe_handler(int n) { 612 // don't complain to stderr or stdout 613 _exit(EXIT_FAILURE); 614} 615 616static void vibrate(FILE* vibrator, int ms) { 617 fprintf(vibrator, "%d\n", ms); 618 fflush(vibrator); 619} 620 621/* generates a zipfile on 'path' with an entry with the contents of 'tmp_path' 622 and removes the temporary file. 623 */ 624static bool generate_zip_file(std::string tmp_path, std::string path, 625 std::string entry_name, time_t entry_time) { 626 std::unique_ptr<FILE, int(*)(FILE*)> file(fopen(path.c_str(), "wb"), fclose); 627 if (!file) { 628 ALOGE("fopen(%s, 'wb'): %s\n", path.c_str(), strerror(errno)); 629 return false; 630 } 631 632 ZipWriter writer(file.get()); 633 int32_t err = writer.StartEntryWithTime(entry_name.c_str(), ZipWriter::kCompress, entry_time); 634 if (err) { 635 ALOGE("writer.StartEntryWithTime(%s): %s\n", entry_name.c_str(), ZipWriter::ErrorCodeString(err)); 636 return false; 637 } 638 639 ScopedFd fd(TEMP_FAILURE_RETRY(open(tmp_path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC))); 640 if (fd.get() == -1) { 641 ALOGE("open(%s): %s\n", tmp_path.c_str(), strerror(errno)); 642 return false; 643 } 644 645 while (1) { 646 std::vector<uint8_t> buffer(65536); 647 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd.get(), buffer.data(), sizeof(buffer))); 648 if (bytes_read == 0) { 649 break; 650 } else if (bytes_read == -1) { 651 ALOGE("read(%s): %s\n", tmp_path.c_str(), strerror(errno)); 652 return false; 653 } 654 err = writer.WriteBytes(buffer.data(), bytes_read); 655 if (err) { 656 ALOGE("writer.WriteBytes(): %s\n", ZipWriter::ErrorCodeString(err)); 657 return false; 658 } 659 } 660 661 err = writer.FinishEntry(); 662 if (err) { 663 ALOGE("writer.FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err)); 664 return false; 665 } 666 667 err = writer.Finish(); 668 if (err) { 669 ALOGE("writer.Finish(): %s\n", ZipWriter::ErrorCodeString(err)); 670 return false; 671 } 672 673 if (remove(tmp_path.c_str())) { 674 ALOGE("remove(%s): %s\n", tmp_path.c_str(), strerror(errno)); 675 return false; 676 } 677 678 return true; 679} 680 681 682int main(int argc, char *argv[]) { 683 struct sigaction sigact; 684 int do_add_date = 0; 685 int do_zip_file = 0; 686 int do_vibrate = 1; 687 char* use_outfile = 0; 688 int use_socket = 0; 689 int do_fb = 0; 690 int do_broadcast = 0; 691 692 if (getuid() != 0) { 693 // Old versions of the adb client would call the 694 // dumpstate command directly. Newer clients 695 // call /system/bin/bugreport instead. If we detect 696 // we're being called incorrectly, then exec the 697 // correct program. 698 return execl("/system/bin/bugreport", "/system/bin/bugreport", NULL); 699 } 700 701 ALOGI("begin\n"); 702 703 /* clear SIGPIPE handler */ 704 memset(&sigact, 0, sizeof(sigact)); 705 sigact.sa_handler = sigpipe_handler; 706 sigaction(SIGPIPE, &sigact, NULL); 707 708 /* set as high priority, and protect from OOM killer */ 709 setpriority(PRIO_PROCESS, 0, -20); 710 FILE *oom_adj = fopen("/proc/self/oom_adj", "we"); 711 if (oom_adj) { 712 fputs("-17", oom_adj); 713 fclose(oom_adj); 714 } 715 716 /* parse arguments */ 717 int c; 718 while ((c = getopt(argc, argv, "dho:svqzpPB")) != -1) { 719 switch (c) { 720 case 'd': do_add_date = 1; break; 721 case 'z': do_zip_file = 1; break; 722 case 'o': use_outfile = optarg; break; 723 case 's': use_socket = 1; break; 724 case 'v': break; // compatibility no-op 725 case 'q': do_vibrate = 0; break; 726 case 'p': do_fb = 1; break; 727 case 'P': do_update_progress = 1; break; 728 case 'B': do_broadcast = 1; break; 729 case '?': printf("\n"); 730 case 'h': 731 usage(); 732 exit(1); 733 } 734 } 735 736 if ((do_zip_file || do_add_date || do_update_progress || do_broadcast) && !use_outfile) { 737 usage(); 738 exit(1); 739 } 740 741 if (do_update_progress && !do_broadcast) { 742 usage(); 743 exit(1); 744 } 745 746 // If we are going to use a socket, do it as early as possible 747 // to avoid timeouts from bugreport. 748 if (use_socket) { 749 redirect_to_socket(stdout, "dumpstate"); 750 } 751 752 /* full path of the directory where the bug report files will be written */ 753 std::string bugreport_dir; 754 755 /* full path of the temporary file containing the bug report */ 756 std::string tmp_path; 757 758 /* base name (without suffix or extensions) of the bug report files */ 759 std::string base_name; 760 761 /* suffix of the bug report files - it's typically the date (when invoked with -d), 762 * although it could be changed by the user using a system property */ 763 std::string suffix; 764 765 /* pointer to the actual path, be it zip or text */ 766 std::string path; 767 768 time_t now = time(NULL); 769 770 /* redirect output if needed */ 771 bool is_redirecting = !use_socket && use_outfile; 772 773 if (is_redirecting) { 774 bugreport_dir = dirname(use_outfile); 775 base_name = basename(use_outfile); 776 if (do_add_date) { 777 char date[80]; 778 strftime(date, sizeof(date), "%Y-%m-%d-%H-%M-%S", localtime(&now)); 779 suffix = date; 780 } else { 781 suffix = "undated"; 782 } 783 if (do_fb) { 784 // TODO: if dumpstate was an object, the paths could be internal variables and then 785 // we could have a function to calculate the derived values, such as: 786 // screenshot_path = GetPath(".png"); 787 screenshot_path = bugreport_dir + "/" + base_name + "-" + suffix + ".png"; 788 } 789 tmp_path = bugreport_dir + "/" + base_name + "-" + suffix + ".tmp"; 790 791 ALOGD("Bugreport dir: %s\nBase name: %s\nSuffix: %s\nTemporary path: %s\n" 792 "Screenshot path: %s\n", bugreport_dir.c_str(), base_name.c_str(), suffix.c_str(), 793 tmp_path.c_str(), screenshot_path.c_str()); 794 795 if (do_update_progress) { 796 std::vector<std::string> am_args = { 797 "--receiver-permission", "android.permission.DUMP", 798 "--es", "android.intent.extra.NAME", suffix, 799 "--ei", "android.intent.extra.PID", std::to_string(getpid()), 800 "--ei", "android.intent.extra.MAX", std::to_string(WEIGHT_TOTAL), 801 }; 802 send_broadcast("android.intent.action.BUGREPORT_STARTED", am_args); 803 } 804 } 805 806 /* open the vibrator before dropping root */ 807 std::unique_ptr<FILE, int(*)(FILE*)> vibrator(NULL, fclose); 808 if (do_vibrate) { 809 vibrator.reset(fopen("/sys/class/timed_output/vibrator/enable", "we")); 810 if (vibrator) { 811 vibrate(vibrator.get(), 150); 812 } 813 } 814 815 /* read /proc/cmdline before dropping root */ 816 FILE *cmdline = fopen("/proc/cmdline", "re"); 817 if (cmdline) { 818 fgets(cmdline_buf, sizeof(cmdline_buf), cmdline); 819 fclose(cmdline); 820 } 821 822 /* collect stack traces from Dalvik and native processes (needs root) */ 823 dump_traces_path = dump_traces(); 824 825 /* Get the tombstone fds here while we are running as root. */ 826 get_tombstone_fds(tombstone_data); 827 828 /* ensure we will keep capabilities when we drop root */ 829 if (prctl(PR_SET_KEEPCAPS, 1) < 0) { 830 ALOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno)); 831 return -1; 832 } 833 834 /* switch to non-root user and group */ 835 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW, 836 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC }; 837 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) { 838 ALOGE("Unable to setgroups, aborting: %s\n", strerror(errno)); 839 return -1; 840 } 841 if (setgid(AID_SHELL) != 0) { 842 ALOGE("Unable to setgid, aborting: %s\n", strerror(errno)); 843 return -1; 844 } 845 if (setuid(AID_SHELL) != 0) { 846 ALOGE("Unable to setuid, aborting: %s\n", strerror(errno)); 847 return -1; 848 } 849 850 struct __user_cap_header_struct capheader; 851 struct __user_cap_data_struct capdata[2]; 852 memset(&capheader, 0, sizeof(capheader)); 853 memset(&capdata, 0, sizeof(capdata)); 854 capheader.version = _LINUX_CAPABILITY_VERSION_3; 855 capheader.pid = 0; 856 857 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG); 858 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG); 859 capdata[0].inheritable = 0; 860 capdata[1].inheritable = 0; 861 862 if (capset(&capheader, &capdata[0]) < 0) { 863 ALOGE("capset failed: %s\n", strerror(errno)); 864 return -1; 865 } 866 867 if (is_redirecting) { 868 /* TODO: rather than generating a text file now and zipping it later, 869 it would be more efficient to redirect stdout to the zip entry 870 directly, but the libziparchive doesn't support that option yet. */ 871 redirect_to_file(stdout, const_cast<char*>(tmp_path.c_str())); 872 } 873 874 dumpstate(); 875 876 /* done */ 877 if (vibrator) { 878 for (int i = 0; i < 3; i++) { 879 vibrate(vibrator.get(), 75); 880 usleep((75 + 50) * 1000); 881 } 882 } 883 884 /* close output if needed */ 885 if (is_redirecting) { 886 fclose(stdout); 887 } 888 889 /* rename or zip the (now complete) .tmp file to its final location */ 890 if (use_outfile) { 891 892 /* check if user changed the suffix using system properties */ 893 char key[PROPERTY_KEY_MAX]; 894 char value[PROPERTY_VALUE_MAX]; 895 sprintf(key, "dumpstate.%d.name", getpid()); 896 property_get(key, value, ""); 897 bool change_suffix= false; 898 if (value[0]) { 899 /* must whitelist which characters are allowed, otherwise it could cross directories */ 900 std::regex valid_regex("^[-_a-zA-Z0-9]+$"); 901 if (std::regex_match(value, valid_regex)) { 902 change_suffix = true; 903 } else { 904 ALOGE("invalid suffix provided by user: %s", value); 905 } 906 } 907 if (change_suffix) { 908 ALOGI("changing suffix from %s to %s", suffix.c_str(), value); 909 suffix = value; 910 if (!screenshot_path.empty()) { 911 std::string new_screenshot_path = 912 bugreport_dir + "/" + base_name + "-" + suffix + ".png"; 913 if (rename(screenshot_path.c_str(), new_screenshot_path.c_str())) { 914 ALOGE("rename(%s, %s): %s\n", screenshot_path.c_str(), 915 new_screenshot_path.c_str(), strerror(errno)); 916 } else { 917 screenshot_path = new_screenshot_path; 918 } 919 } 920 } 921 922 bool do_text_file = true; 923 if (do_zip_file) { 924 ALOGD("Generating .zip bugreport"); 925 path = bugreport_dir + "/" + base_name + "-" + suffix + ".zip"; 926 if (!generate_zip_file(tmp_path, path, base_name + "-" + suffix + ".txt", now)) { 927 ALOGE("Failed to generate zip file; sending text bugreport instead\n"); 928 do_text_file = true; 929 } else { 930 do_text_file = false; 931 } 932 } 933 if (do_text_file) { 934 ALOGD("Generating .txt bugreport"); 935 path = bugreport_dir + "/" + base_name + "-" + suffix + ".txt"; 936 if (rename(tmp_path.c_str(), path.c_str())) { 937 ALOGE("rename(%s, %s): %s\n", tmp_path.c_str(), path.c_str(), strerror(errno)); 938 path.clear(); 939 } 940 } 941 } 942 943 /* tell activity manager we're done */ 944 if (do_broadcast) { 945 if (!path.empty()) { 946 ALOGI("Final bugreport path: %s\n", path.c_str()); 947 std::vector<std::string> am_args = { 948 "--receiver-permission", "android.permission.DUMP", 949 "--ei", "android.intent.extra.PID", std::to_string(getpid()), 950 "--es", "android.intent.extra.BUGREPORT", path 951 }; 952 if (do_fb) { 953 am_args.push_back("--es"); 954 am_args.push_back("android.intent.extra.SCREENSHOT"); 955 am_args.push_back(screenshot_path); 956 } 957 send_broadcast("android.intent.action.BUGREPORT_FINISHED", am_args); 958 } else { 959 ALOGE("Skipping finished broadcast because bugreport could not be generated\n"); 960 } 961 } 962 963 ALOGI("done\n"); 964 965 return 0; 966} 967