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