dumpstate.cpp revision a960bc95b2430ba01fc4b04b4527d32e00eeb4b5
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
116//
117//  stat offsets
118// Name            units         description
119// ----            -----         -----------
120// read I/Os       requests      number of read I/Os processed
121#define __STAT_READ_IOS      0
122// read merges     requests      number of read I/Os merged with in-queue I/O
123#define __STAT_READ_MERGES   1
124// read sectors    sectors       number of sectors read
125#define __STAT_READ_SECTORS  2
126// read ticks      milliseconds  total wait time for read requests
127#define __STAT_READ_TICKS    3
128// write I/Os      requests      number of write I/Os processed
129#define __STAT_WRITE_IOS     4
130// write merges    requests      number of write I/Os merged with in-queue I/O
131#define __STAT_WRITE_MERGES  5
132// write sectors   sectors       number of sectors written
133#define __STAT_WRITE_SECTORS 6
134// write ticks     milliseconds  total wait time for write requests
135#define __STAT_WRITE_TICKS   7
136// in_flight       requests      number of I/Os currently in flight
137#define __STAT_IN_FLIGHT     8
138// io_ticks        milliseconds  total time this block device has been active
139#define __STAT_IO_TICKS      9
140// time_in_queue   milliseconds  total wait time for all requests
141#define __STAT_IN_QUEUE     10
142#define __STAT_NUMBER_FIELD 11
143//
144// read I/Os, write I/Os
145// =====================
146//
147// These values increment when an I/O request completes.
148//
149// read merges, write merges
150// =========================
151//
152// These values increment when an I/O request is merged with an
153// already-queued I/O request.
154//
155// read sectors, write sectors
156// ===========================
157//
158// These values count the number of sectors read from or written to this
159// block device.  The "sectors" in question are the standard UNIX 512-byte
160// sectors, not any device- or filesystem-specific block size.  The
161// counters are incremented when the I/O completes.
162#define SECTOR_SIZE 512
163//
164// read ticks, write ticks
165// =======================
166//
167// These values count the number of milliseconds that I/O requests have
168// waited on this block device.  If there are multiple I/O requests waiting,
169// these values will increase at a rate greater than 1000/second; for
170// example, if 60 read requests wait for an average of 30 ms, the read_ticks
171// field will increase by 60*30 = 1800.
172//
173// in_flight
174// =========
175//
176// This value counts the number of I/O requests that have been issued to
177// the device driver but have not yet completed.  It does not include I/O
178// requests that are in the queue but not yet issued to the device driver.
179//
180// io_ticks
181// ========
182//
183// This value counts the number of milliseconds during which the device has
184// had I/O requests queued.
185//
186// time_in_queue
187// =============
188//
189// This value counts the number of milliseconds that I/O requests have waited
190// on this block device.  If there are multiple I/O requests waiting, this
191// value will increase as the product of the number of milliseconds times the
192// number of requests waiting (see "read ticks" above for an example).
193#define S_TO_MS 1000
194//
195
196static int dump_stat_from_fd(const char *title __unused, const char *path, int fd) {
197    unsigned long long fields[__STAT_NUMBER_FIELD];
198    bool z;
199    char *cp, *buffer = NULL;
200    size_t i = 0;
201    FILE *fp = fdopen(fd, "rb");
202    getline(&buffer, &i, fp);
203    fclose(fp);
204    if (!buffer) {
205        return -errno;
206    }
207    i = strlen(buffer);
208    while ((i > 0) && (buffer[i - 1] == '\n')) {
209        buffer[--i] = '\0';
210    }
211    if (!*buffer) {
212        free(buffer);
213        return 0;
214    }
215    z = true;
216    for (cp = buffer, i = 0; i < (sizeof(fields) / sizeof(fields[0])); ++i) {
217        fields[i] = strtoull(cp, &cp, 10);
218        if (fields[i] != 0) {
219            z = false;
220        }
221    }
222    if (z) { /* never accessed */
223        free(buffer);
224        return 0;
225    }
226
227    if (!strncmp(path, mmcblk0, sizeof(mmcblk0) - 1)) {
228        path += sizeof(mmcblk0) - 1;
229    }
230
231    printf("%s: %s\n", path, buffer);
232    free(buffer);
233
234    if (fields[__STAT_IO_TICKS]) {
235        unsigned long read_perf = 0;
236        unsigned long read_ios = 0;
237        if (fields[__STAT_READ_TICKS]) {
238            unsigned long long divisor = fields[__STAT_READ_TICKS]
239                                       * fields[__STAT_IO_TICKS];
240            read_perf = ((unsigned long long)SECTOR_SIZE
241                           * fields[__STAT_READ_SECTORS]
242                           * fields[__STAT_IN_QUEUE] + (divisor >> 1))
243                                        / divisor;
244            read_ios = ((unsigned long long)S_TO_MS * fields[__STAT_READ_IOS]
245                           * fields[__STAT_IN_QUEUE] + (divisor >> 1))
246                                        / divisor;
247        }
248
249        unsigned long write_perf = 0;
250        unsigned long write_ios = 0;
251        if (fields[__STAT_WRITE_TICKS]) {
252            unsigned long long divisor = fields[__STAT_WRITE_TICKS]
253                                       * fields[__STAT_IO_TICKS];
254            write_perf = ((unsigned long long)SECTOR_SIZE
255                           * fields[__STAT_WRITE_SECTORS]
256                           * fields[__STAT_IN_QUEUE] + (divisor >> 1))
257                                        / divisor;
258            write_ios = ((unsigned long long)S_TO_MS * fields[__STAT_WRITE_IOS]
259                           * fields[__STAT_IN_QUEUE] + (divisor >> 1))
260                                        / divisor;
261        }
262
263        unsigned queue = (fields[__STAT_IN_QUEUE]
264                             + (fields[__STAT_IO_TICKS] >> 1))
265                                 / fields[__STAT_IO_TICKS];
266
267        if (!write_perf && !write_ios) {
268            printf("%s: perf(ios) rd: %luKB/s(%lu/s) q: %u\n",
269                   path, read_perf, read_ios, queue);
270        } else {
271            printf("%s: perf(ios) rd: %luKB/s(%lu/s) wr: %luKB/s(%lu/s) q: %u\n",
272                   path, read_perf, read_ios, write_perf, write_ios, queue);
273        }
274
275        /* bugreport timeout factor adjustment */
276        if ((write_perf > 1) && (write_perf < worst_write_perf)) {
277            worst_write_perf = write_perf;
278        }
279    }
280    return 0;
281}
282
283/* Copied policy from system/core/logd/LogBuffer.cpp */
284
285#define LOG_BUFFER_SIZE (256 * 1024)
286#define LOG_BUFFER_MIN_SIZE (64 * 1024UL)
287#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL)
288
289static bool valid_size(unsigned long value) {
290    if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) {
291        return false;
292    }
293
294    long pages = sysconf(_SC_PHYS_PAGES);
295    if (pages < 1) {
296        return true;
297    }
298
299    long pagesize = sysconf(_SC_PAGESIZE);
300    if (pagesize <= 1) {
301        pagesize = PAGE_SIZE;
302    }
303
304    // maximum memory impact a somewhat arbitrary ~3%
305    pages = (pages + 31) / 32;
306    unsigned long maximum = pages * pagesize;
307
308    if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) {
309        return true;
310    }
311
312    return value <= maximum;
313}
314
315static unsigned long property_get_size(const char *key) {
316    unsigned long value;
317    char *cp, property[PROPERTY_VALUE_MAX];
318
319    property_get(key, property, "");
320    value = strtoul(property, &cp, 10);
321
322    switch(*cp) {
323    case 'm':
324    case 'M':
325        value *= 1024;
326    /* FALLTHRU */
327    case 'k':
328    case 'K':
329        value *= 1024;
330    /* FALLTHRU */
331    case '\0':
332        break;
333
334    default:
335        value = 0;
336    }
337
338    if (!valid_size(value)) {
339        value = 0;
340    }
341
342    return value;
343}
344
345/* timeout in ms */
346static unsigned long logcat_timeout(const char *name) {
347    static const char global_tuneable[] = "persist.logd.size"; // Settings App
348    static const char global_default[] = "ro.logd.size";       // BoardConfig.mk
349    char key[PROP_NAME_MAX];
350    unsigned long property_size, default_size;
351
352    default_size = property_get_size(global_tuneable);
353    if (!default_size) {
354        default_size = property_get_size(global_default);
355    }
356
357    snprintf(key, sizeof(key), "%s.%s", global_tuneable, name);
358    property_size = property_get_size(key);
359
360    if (!property_size) {
361        snprintf(key, sizeof(key), "%s.%s", global_default, name);
362        property_size = property_get_size(key);
363    }
364
365    if (!property_size) {
366        property_size = default_size;
367    }
368
369    if (!property_size) {
370        property_size = LOG_BUFFER_SIZE;
371    }
372
373    /* Engineering margin is ten-fold our guess */
374    return 10 * (property_size + worst_write_perf) / worst_write_perf;
375}
376
377/* End copy from system/core/logd/LogBuffer.cpp */
378
379/* dumps the current system state to stdout */
380static void dumpstate() {
381    unsigned long timeout;
382    time_t now = time(NULL);
383    char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX];
384    char radio[PROPERTY_VALUE_MAX], bootloader[PROPERTY_VALUE_MAX];
385    char network[PROPERTY_VALUE_MAX], date[80];
386    char build_type[PROPERTY_VALUE_MAX];
387
388    property_get("ro.build.display.id", build, "(unknown)");
389    property_get("ro.build.fingerprint", fingerprint, "(unknown)");
390    property_get("ro.build.type", build_type, "(unknown)");
391    property_get("ro.baseband", radio, "(unknown)");
392    property_get("ro.bootloader", bootloader, "(unknown)");
393    property_get("gsm.operator.alpha", network, "(unknown)");
394    strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now));
395
396    printf("========================================================\n");
397    printf("== dumpstate: %s\n", date);
398    printf("========================================================\n");
399
400    printf("\n");
401    printf("Build: %s\n", build);
402    printf("Build fingerprint: '%s'\n", fingerprint); /* format is important for other tools */
403    printf("Bootloader: %s\n", bootloader);
404    printf("Radio: %s\n", radio);
405    printf("Network: %s\n", network);
406
407    printf("Kernel: ");
408    dump_file(NULL, "/proc/version");
409    printf("Command line: %s\n", strtok(cmdline_buf, "\n"));
410    printf("\n");
411
412    dump_dev_files("TRUSTY VERSION", "/sys/bus/platform/drivers/trusty", "trusty_version");
413    run_command("UPTIME", 10, "uptime", NULL);
414    dump_files("UPTIME MMC PERF", mmcblk0, skip_not_stat, dump_stat_from_fd);
415    dump_emmc_ecsd("/d/mmc0/mmc0:0001/ext_csd");
416    dump_file("MEMORY INFO", "/proc/meminfo");
417    run_command("CPU INFO", 10, "top", "-n", "1", "-d", "1", "-m", "30", "-H", NULL);
418    run_command("PROCRANK", 20, SU_PATH, "root", "procrank", NULL);
419    dump_file("VIRTUAL MEMORY STATS", "/proc/vmstat");
420    dump_file("VMALLOC INFO", "/proc/vmallocinfo");
421    dump_file("SLAB INFO", "/proc/slabinfo");
422    dump_file("ZONEINFO", "/proc/zoneinfo");
423    dump_file("PAGETYPEINFO", "/proc/pagetypeinfo");
424    dump_file("BUDDYINFO", "/proc/buddyinfo");
425    dump_file("FRAGMENTATION INFO", "/d/extfrag/unusable_index");
426
427    dump_file("KERNEL WAKELOCKS", "/proc/wakelocks");
428    dump_file("KERNEL WAKE SOURCES", "/d/wakeup_sources");
429    dump_file("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
430    dump_file("KERNEL SYNC", "/d/sync");
431
432    run_command("PROCESSES AND THREADS", 10, "ps", "-Z", "-t", "-p", "-P", NULL);
433    run_command("LIBRANK", 10, "librank", NULL);
434
435    do_dmesg();
436
437    run_command("LIST OF OPEN FILES", 10, SU_PATH, "root", "lsof", NULL);
438    for_each_pid(do_showmap, "SMAPS OF ALL PROCESSES");
439    for_each_tid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS");
440
441    if (screenshot_path[0]) {
442        ALOGI("taking screenshot\n");
443        run_command(NULL, 10, "/system/bin/screencap", "-p", screenshot_path, NULL);
444        ALOGI("wrote screenshot: %s\n", screenshot_path);
445    }
446
447    // dump_file("EVENT LOG TAGS", "/etc/event-log-tags");
448    // calculate timeout
449    timeout = logcat_timeout("main") + logcat_timeout("system") + logcat_timeout("crash");
450    if (timeout < 20000) {
451        timeout = 20000;
452    }
453    run_command("SYSTEM LOG", timeout / 1000, "logcat", "-v", "threadtime",
454                                                        "-v", "printable",
455                                                        "-d",
456                                                        "*:v", NULL);
457    timeout = logcat_timeout("events");
458    if (timeout < 20000) {
459        timeout = 20000;
460    }
461    run_command("EVENT LOG", timeout / 1000, "logcat", "-b", "events",
462                                                       "-v", "threadtime",
463                                                       "-v", "printable",
464                                                       "-d",
465                                                       "*:v", NULL);
466    timeout = logcat_timeout("radio");
467    if (timeout < 20000) {
468        timeout = 20000;
469    }
470    run_command("RADIO LOG", timeout / 1000, "logcat", "-b", "radio",
471                                                       "-v", "threadtime",
472                                                       "-v", "printable",
473                                                       "-d",
474                                                       "*:v", NULL);
475
476    run_command("LOG STATISTICS", 10, "logcat", "-b", "all", "-S", NULL);
477
478    run_command("RAFT LOGS", 600, SU_PATH, "root", "logcompressor", "-r", RAFT_DIR, NULL);
479
480    /* show the traces we collected in main(), if that was done */
481    if (dump_traces_path != NULL) {
482        dump_file("VM TRACES JUST NOW", dump_traces_path);
483    }
484
485    /* only show ANR traces if they're less than 15 minutes old */
486    struct stat st;
487    char anr_traces_path[PATH_MAX];
488    property_get("dalvik.vm.stack-trace-file", anr_traces_path, "");
489    if (!anr_traces_path[0]) {
490        printf("*** NO VM TRACES FILE DEFINED (dalvik.vm.stack-trace-file)\n\n");
491    } else {
492      int fd = TEMP_FAILURE_RETRY(open(anr_traces_path,
493                                       O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK));
494      if (fd < 0) {
495          printf("*** NO ANR VM TRACES FILE (%s): %s\n\n", anr_traces_path, strerror(errno));
496      } else {
497          dump_file_from_fd("VM TRACES AT LAST ANR", anr_traces_path, fd);
498      }
499    }
500
501    /* slow traces for slow operations */
502    if (anr_traces_path[0] != 0) {
503        int tail = strlen(anr_traces_path)-1;
504        while (tail > 0 && anr_traces_path[tail] != '/') {
505            tail--;
506        }
507        int i = 0;
508        while (1) {
509            sprintf(anr_traces_path+tail+1, "slow%02d.txt", i);
510            if (stat(anr_traces_path, &st)) {
511                // No traces file at this index, done with the files.
512                break;
513            }
514            dump_file("VM TRACES WHEN SLOW", anr_traces_path);
515            i++;
516        }
517    }
518
519    int dumped = 0;
520    for (size_t i = 0; i < NUM_TOMBSTONES; i++) {
521        if (tombstone_data[i].fd != -1) {
522            dumped = 1;
523            dump_file_from_fd("TOMBSTONE", tombstone_data[i].name, tombstone_data[i].fd);
524            tombstone_data[i].fd = -1;
525        }
526    }
527    if (!dumped) {
528        printf("*** NO TOMBSTONES to dump in %s\n\n", TOMBSTONE_DIR);
529    }
530
531    dump_file("NETWORK DEV INFO", "/proc/net/dev");
532    dump_file("QTAGUID NETWORK INTERFACES INFO", "/proc/net/xt_qtaguid/iface_stat_all");
533    dump_file("QTAGUID NETWORK INTERFACES INFO (xt)", "/proc/net/xt_qtaguid/iface_stat_fmt");
534    dump_file("QTAGUID CTRL INFO", "/proc/net/xt_qtaguid/ctrl");
535    dump_file("QTAGUID STATS INFO", "/proc/net/xt_qtaguid/stats");
536
537    if (!stat(PSTORE_LAST_KMSG, &st)) {
538        /* Also TODO: Make console-ramoops CAP_SYSLOG protected. */
539        dump_file("LAST KMSG", PSTORE_LAST_KMSG);
540    } else {
541        /* TODO: Make last_kmsg CAP_SYSLOG protected. b/5555691 */
542        dump_file("LAST KMSG", "/proc/last_kmsg");
543    }
544
545    /* kernels must set CONFIG_PSTORE_PMSG, slice up pstore with device tree */
546    run_command("LAST LOGCAT", 10, "logcat", "-L",
547                                             "-b", "all",
548                                             "-v", "threadtime",
549                                             "-v", "printable",
550                                             "-d",
551                                             "*:v", NULL);
552
553    /* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */
554
555    run_command("NETWORK INTERFACES", 10, "ip", "link", NULL);
556
557    run_command("IPv4 ADDRESSES", 10, "ip", "-4", "addr", "show", NULL);
558    run_command("IPv6 ADDRESSES", 10, "ip", "-6", "addr", "show", NULL);
559
560    run_command("IP RULES", 10, "ip", "rule", "show", NULL);
561    run_command("IP RULES v6", 10, "ip", "-6", "rule", "show", NULL);
562
563    dump_route_tables();
564
565    run_command("ARP CACHE", 10, "ip", "-4", "neigh", "show", NULL);
566    run_command("IPv6 ND CACHE", 10, "ip", "-6", "neigh", "show", NULL);
567
568    run_command("IPTABLES", 10, SU_PATH, "root", "iptables", "-L", "-nvx", NULL);
569    run_command("IP6TABLES", 10, SU_PATH, "root", "ip6tables", "-L", "-nvx", NULL);
570    run_command("IPTABLE NAT", 10, SU_PATH, "root", "iptables", "-t", "nat", "-L", "-nvx", NULL);
571    /* no ip6 nat */
572    run_command("IPTABLE RAW", 10, SU_PATH, "root", "iptables", "-t", "raw", "-L", "-nvx", NULL);
573    run_command("IP6TABLE RAW", 10, SU_PATH, "root", "ip6tables", "-t", "raw", "-L", "-nvx", NULL);
574
575    run_command("WIFI NETWORKS", 20,
576            SU_PATH, "root", "wpa_cli", "IFNAME=wlan0", "list_networks", NULL);
577
578#ifdef FWDUMP_bcmdhd
579    run_command("ND OFFLOAD TABLE", 5,
580            SU_PATH, "root", "wlutil", "nd_hostip", NULL);
581
582    run_command("DUMP WIFI INTERNAL COUNTERS (1)", 20,
583            SU_PATH, "root", "wlutil", "counters", NULL);
584
585    run_command("ND OFFLOAD STATUS (1)", 5,
586            SU_PATH, "root", "wlutil", "nd_status", NULL);
587
588#endif
589    dump_file("INTERRUPTS (1)", "/proc/interrupts");
590
591    run_command("NETWORK DIAGNOSTICS", 10, "dumpsys", "connectivity", "--diag", NULL);
592
593#ifdef FWDUMP_bcmdhd
594    run_command("DUMP WIFI STATUS", 20,
595            SU_PATH, "root", "dhdutil", "-i", "wlan0", "dump", NULL);
596
597    run_command("DUMP WIFI INTERNAL COUNTERS (2)", 20,
598            SU_PATH, "root", "wlutil", "counters", NULL);
599
600    run_command("ND OFFLOAD STATUS (2)", 5,
601            SU_PATH, "root", "wlutil", "nd_status", NULL);
602#endif
603    dump_file("INTERRUPTS (2)", "/proc/interrupts");
604
605    print_properties();
606
607    run_command("VOLD DUMP", 10, "vdc", "dump", NULL);
608    run_command("SECURE CONTAINERS", 10, "vdc", "asec", "list", NULL);
609
610    run_command("FILESYSTEMS & FREE SPACE", 10, "df", NULL);
611
612    run_command("LAST RADIO LOG", 10, "parse_radio_log", "/proc/last_radio_log", NULL);
613
614    printf("------ BACKLIGHTS ------\n");
615    printf("LCD brightness=");
616    dump_file(NULL, "/sys/class/leds/lcd-backlight/brightness");
617    printf("Button brightness=");
618    dump_file(NULL, "/sys/class/leds/button-backlight/brightness");
619    printf("Keyboard brightness=");
620    dump_file(NULL, "/sys/class/leds/keyboard-backlight/brightness");
621    printf("ALS mode=");
622    dump_file(NULL, "/sys/class/leds/lcd-backlight/als");
623    printf("LCD driver registers:\n");
624    dump_file(NULL, "/sys/class/leds/lcd-backlight/registers");
625    printf("\n");
626
627    /* Binder state is expensive to look at as it uses a lot of memory. */
628    dump_file("BINDER FAILED TRANSACTION LOG", "/sys/kernel/debug/binder/failed_transaction_log");
629    dump_file("BINDER TRANSACTION LOG", "/sys/kernel/debug/binder/transaction_log");
630    dump_file("BINDER TRANSACTIONS", "/sys/kernel/debug/binder/transactions");
631    dump_file("BINDER STATS", "/sys/kernel/debug/binder/stats");
632    dump_file("BINDER STATE", "/sys/kernel/debug/binder/state");
633
634    printf("========================================================\n");
635    printf("== Board\n");
636    printf("========================================================\n");
637
638    dumpstate_board();
639    printf("\n");
640
641    /* Migrate the ril_dumpstate to a dumpstate_board()? */
642    char ril_dumpstate_timeout[PROPERTY_VALUE_MAX] = {0};
643    property_get("ril.dumpstate.timeout", ril_dumpstate_timeout, "30");
644    if (strnlen(ril_dumpstate_timeout, PROPERTY_VALUE_MAX - 1) > 0) {
645        if (0 == strncmp(build_type, "user", PROPERTY_VALUE_MAX - 1)) {
646            // su does not exist on user builds, so try running without it.
647            // This way any implementations of vril-dump that do not require
648            // root can run on user builds.
649            run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout),
650                    "vril-dump", NULL);
651        } else {
652            run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout),
653                    SU_PATH, "root", "vril-dump", NULL);
654        }
655    }
656
657    printf("========================================================\n");
658    printf("== Android Framework Services\n");
659    printf("========================================================\n");
660
661    /* the full dumpsys is starting to take a long time, so we need
662       to increase its timeout.  we really need to do the timeouts in
663       dumpsys itself... */
664    run_command("DUMPSYS", 60, "dumpsys", NULL);
665
666    printf("========================================================\n");
667    printf("== Checkins\n");
668    printf("========================================================\n");
669
670    run_command("CHECKIN BATTERYSTATS", 30, "dumpsys", "batterystats", "-c", NULL);
671    run_command("CHECKIN MEMINFO", 30, "dumpsys", "meminfo", "--checkin", NULL);
672    run_command("CHECKIN NETSTATS", 30, "dumpsys", "netstats", "--checkin", NULL);
673    run_command("CHECKIN PROCSTATS", 30, "dumpsys", "procstats", "-c", NULL);
674    run_command("CHECKIN USAGESTATS", 30, "dumpsys", "usagestats", "-c", NULL);
675    run_command("CHECKIN PACKAGE", 30, "dumpsys", "package", "--checkin", NULL);
676
677    printf("========================================================\n");
678    printf("== Running Application Activities\n");
679    printf("========================================================\n");
680
681    run_command("APP ACTIVITIES", 30, "dumpsys", "activity", "all", NULL);
682
683    printf("========================================================\n");
684    printf("== Running Application Services\n");
685    printf("========================================================\n");
686
687    run_command("APP SERVICES", 30, "dumpsys", "activity", "service", "all", NULL);
688
689    printf("========================================================\n");
690    printf("== Running Application Providers\n");
691    printf("========================================================\n");
692
693    run_command("APP SERVICES", 30, "dumpsys", "activity", "provider", "all", NULL);
694
695
696    printf("========================================================\n");
697    printf("== dumpstate: done\n");
698    printf("========================================================\n");
699}
700
701static void usage() {
702    fprintf(stderr, "usage: dumpstate [-b soundfile] [-e soundfile] [-o file [-d] [-p] [-z]] [-s] [-q]\n"
703            "  -o: write to file (instead of stdout)\n"
704            "  -d: append date to filename (requires -o)\n"
705            "  -p: capture screenshot to filename.png (requires -o)\n"
706            "  -s: write output to control socket (for init)\n"
707            "  -b: play sound file instead of vibrate, at beginning of job\n"
708            "  -e: play sound file instead of vibrate, at end of job\n"
709            "  -q: disable vibrate\n"
710            "  -B: send broadcast when finished (requires -o and -p)\n"
711                );
712}
713
714static void sigpipe_handler(int n) {
715    // don't complain to stderr or stdout
716    _exit(EXIT_FAILURE);
717}
718
719static void vibrate(FILE* vibrator, int ms) {
720    fprintf(vibrator, "%d\n", ms);
721    fflush(vibrator);
722}
723
724int main(int argc, char *argv[]) {
725    struct sigaction sigact;
726    int do_add_date = 0;
727    int do_vibrate = 1;
728    char* use_outfile = 0;
729    int use_socket = 0;
730    int do_fb = 0;
731    int do_broadcast = 0;
732
733    if (getuid() != 0) {
734        // Old versions of the adb client would call the
735        // dumpstate command directly. Newer clients
736        // call /system/bin/bugreport instead. If we detect
737        // we're being called incorrectly, then exec the
738        // correct program.
739        return execl("/system/bin/bugreport", "/system/bin/bugreport", NULL);
740    }
741
742    ALOGI("begin\n");
743
744    /* clear SIGPIPE handler */
745    memset(&sigact, 0, sizeof(sigact));
746    sigact.sa_handler = sigpipe_handler;
747    sigaction(SIGPIPE, &sigact, NULL);
748
749    /* set as high priority, and protect from OOM killer */
750    setpriority(PRIO_PROCESS, 0, -20);
751    FILE *oom_adj = fopen("/proc/self/oom_adj", "we");
752    if (oom_adj) {
753        fputs("-17", oom_adj);
754        fclose(oom_adj);
755    }
756
757    /* parse arguments */
758    int c;
759    while ((c = getopt(argc, argv, "dho:svqzpB")) != -1) {
760        switch (c) {
761            case 'd': do_add_date = 1;       break;
762            case 'o': use_outfile = optarg;  break;
763            case 's': use_socket = 1;        break;
764            case 'v': break;  // compatibility no-op
765            case 'q': do_vibrate = 0;        break;
766            case 'p': do_fb = 1;             break;
767            case 'B': do_broadcast = 1;      break;
768            case '?': printf("\n");
769            case 'h':
770                usage();
771                exit(1);
772        }
773    }
774
775    // If we are going to use a socket, do it as early as possible
776    // to avoid timeouts from bugreport.
777    if (use_socket) {
778        redirect_to_socket(stdout, "dumpstate");
779    }
780
781    /* open the vibrator before dropping root */
782    FILE *vibrator = 0;
783    if (do_vibrate) {
784        vibrator = fopen("/sys/class/timed_output/vibrator/enable", "we");
785        if (vibrator) {
786            vibrate(vibrator, 150);
787        }
788    }
789
790    /* read /proc/cmdline before dropping root */
791    FILE *cmdline = fopen("/proc/cmdline", "re");
792    if (cmdline != NULL) {
793        fgets(cmdline_buf, sizeof(cmdline_buf), cmdline);
794        fclose(cmdline);
795    }
796
797    /* collect stack traces from Dalvik and native processes (needs root) */
798    dump_traces_path = dump_traces();
799
800    /* Get the tombstone fds here while we are running as root. */
801    get_tombstone_fds(tombstone_data);
802
803    /* ensure we will keep capabilities when we drop root */
804    if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
805        ALOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
806        return -1;
807    }
808
809    /* switch to non-root user and group */
810    gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
811            AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC };
812    if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
813        ALOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
814        return -1;
815    }
816    if (setgid(AID_SHELL) != 0) {
817        ALOGE("Unable to setgid, aborting: %s\n", strerror(errno));
818        return -1;
819    }
820    if (setuid(AID_SHELL) != 0) {
821        ALOGE("Unable to setuid, aborting: %s\n", strerror(errno));
822        return -1;
823    }
824
825    struct __user_cap_header_struct capheader;
826    struct __user_cap_data_struct capdata[2];
827    memset(&capheader, 0, sizeof(capheader));
828    memset(&capdata, 0, sizeof(capdata));
829    capheader.version = _LINUX_CAPABILITY_VERSION_3;
830    capheader.pid = 0;
831
832    capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
833    capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG);
834    capdata[0].inheritable = 0;
835    capdata[1].inheritable = 0;
836
837    if (capset(&capheader, &capdata[0]) < 0) {
838        ALOGE("capset failed: %s\n", strerror(errno));
839        return -1;
840    }
841
842    /* redirect output if needed */
843    char path[PATH_MAX], tmp_path[PATH_MAX];
844    pid_t gzip_pid = -1;
845
846    if (!use_socket && use_outfile) {
847        strlcpy(path, use_outfile, sizeof(path));
848        if (do_add_date) {
849            char date[80];
850            time_t now = time(NULL);
851            strftime(date, sizeof(date), "-%Y-%m-%d-%H-%M-%S", localtime(&now));
852            strlcat(path, date, sizeof(path));
853        }
854        if (do_fb) {
855            strlcpy(screenshot_path, path, sizeof(screenshot_path));
856            strlcat(screenshot_path, ".png", sizeof(screenshot_path));
857        }
858        strlcat(path, ".txt", sizeof(path));
859        strlcpy(tmp_path, path, sizeof(tmp_path));
860        strlcat(tmp_path, ".tmp", sizeof(tmp_path));
861        redirect_to_file(stdout, tmp_path);
862    }
863
864    dumpstate();
865
866    /* done */
867    if (vibrator) {
868        for (int i = 0; i < 3; i++) {
869            vibrate(vibrator, 75);
870            usleep((75 + 50) * 1000);
871        }
872        fclose(vibrator);
873    }
874
875    /* wait for gzip to finish, otherwise it might get killed when we exit */
876    if (gzip_pid > 0) {
877        fclose(stdout);
878        waitpid(gzip_pid, NULL, 0);
879    }
880
881    /* rename the (now complete) .tmp file to its final location */
882    if (use_outfile && rename(tmp_path, path)) {
883        fprintf(stderr, "rename(%s, %s): %s\n", tmp_path, path, strerror(errno));
884    }
885
886    /* tell activity manager we're done */
887    if (do_broadcast && use_outfile && do_fb) {
888        run_command(NULL, 5, "/system/bin/am", "broadcast", "--user", "0",
889                "-a", "android.intent.action.BUGREPORT_FINISHED",
890                "--es", "android.intent.extra.BUGREPORT", path,
891                "--es", "android.intent.extra.SCREENSHOT", screenshot_path,
892                "--receiver-permission", "android.permission.DUMP", NULL);
893    }
894
895    ALOGI("done\n");
896
897    return 0;
898}
899