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