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