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