move dumpstate and dumpsys from frameworks/base to frameworks/native

Change-Id: I8a5318022ce5cd3e7c8055f21fe5da74639aa6c0
diff --git a/cmds/dumpstate/Android.mk b/cmds/dumpstate/Android.mk
new file mode 100644
index 0000000..d602500
--- /dev/null
+++ b/cmds/dumpstate/Android.mk
@@ -0,0 +1,19 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+ifdef BOARD_WLAN_DEVICE
+LOCAL_CFLAGS := -DFWDUMP_$(BOARD_WLAN_DEVICE)
+endif
+
+LOCAL_SRC_FILES := dumpstate.c utils.c
+
+LOCAL_MODULE := dumpstate
+
+LOCAL_SHARED_LIBRARIES := libcutils
+
+ifdef BOARD_LIB_DUMPSTATE
+LOCAL_STATIC_LIBRARIES := $(BOARD_LIB_DUMPSTATE)
+LOCAL_CFLAGS += -DBOARD_HAS_DUMPSTATE
+endif
+
+include $(BUILD_EXECUTABLE)
diff --git a/cmds/dumpstate/dumpstate.c b/cmds/dumpstate/dumpstate.c
new file mode 100644
index 0000000..aa95b35
--- /dev/null
+++ b/cmds/dumpstate/dumpstate.c
@@ -0,0 +1,452 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <linux/capability.h>
+#include <linux/prctl.h>
+
+#include <cutils/properties.h>
+
+#include "private/android_filesystem_config.h"
+
+#define LOG_TAG "dumpstate"
+#include <utils/Log.h>
+
+#include "dumpstate.h"
+
+/* read before root is shed */
+static char cmdline_buf[16384] = "(unknown)";
+static const char *dump_traces_path = NULL;
+
+static char screenshot_path[PATH_MAX] = "";
+
+/* dumps the current system state to stdout */
+static void dumpstate() {
+    time_t now = time(NULL);
+    char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX];
+    char radio[PROPERTY_VALUE_MAX], bootloader[PROPERTY_VALUE_MAX];
+    char network[PROPERTY_VALUE_MAX], date[80];
+    char build_type[PROPERTY_VALUE_MAX];
+
+    property_get("ro.build.display.id", build, "(unknown)");
+    property_get("ro.build.fingerprint", fingerprint, "(unknown)");
+    property_get("ro.build.type", build_type, "(unknown)");
+    property_get("ro.baseband", radio, "(unknown)");
+    property_get("ro.bootloader", bootloader, "(unknown)");
+    property_get("gsm.operator.alpha", network, "(unknown)");
+    strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now));
+
+    printf("========================================================\n");
+    printf("== dumpstate: %s\n", date);
+    printf("========================================================\n");
+
+    printf("\n");
+    printf("Build: %s\n", build);
+    printf("Build fingerprint: '%s'\n", fingerprint); /* format is important for other tools */
+    printf("Bootloader: %s\n", bootloader);
+    printf("Radio: %s\n", radio);
+    printf("Network: %s\n", network);
+
+    printf("Kernel: ");
+    dump_file(NULL, "/proc/version");
+    printf("Command line: %s\n", strtok(cmdline_buf, "\n"));
+    printf("\n");
+
+    run_command("UPTIME", 10, "uptime", NULL);
+    dump_file("MEMORY INFO", "/proc/meminfo");
+    run_command("CPU INFO", 10, "top", "-n", "1", "-d", "1", "-m", "30", "-t", NULL);
+    run_command("PROCRANK", 20, "procrank", NULL);
+    dump_file("VIRTUAL MEMORY STATS", "/proc/vmstat");
+    dump_file("VMALLOC INFO", "/proc/vmallocinfo");
+    dump_file("SLAB INFO", "/proc/slabinfo");
+    dump_file("ZONEINFO", "/proc/zoneinfo");
+    dump_file("PAGETYPEINFO", "/proc/pagetypeinfo");
+    dump_file("BUDDYINFO", "/proc/buddyinfo");
+
+
+    dump_file("KERNEL WAKELOCKS", "/proc/wakelocks");
+    dump_file("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
+
+    run_command("PROCESSES", 10, "ps", "-P", NULL);
+    run_command("PROCESSES AND THREADS", 10, "ps", "-t", "-p", "-P", NULL);
+    run_command("LIBRANK", 10, "librank", NULL);
+
+    do_dmesg();
+
+    run_command("LIST OF OPEN FILES", 10, SU_PATH, "root", "lsof", NULL);
+
+    for_each_pid(do_showmap, "SMAPS OF ALL PROCESSES");
+    for_each_pid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS");
+
+    // dump_file("EVENT LOG TAGS", "/etc/event-log-tags");
+    run_command("SYSTEM LOG", 20, "logcat", "-v", "threadtime", "-d", "*:v", NULL);
+    run_command("EVENT LOG", 20, "logcat", "-b", "events", "-v", "threadtime", "-d", "*:v", NULL);
+    run_command("RADIO LOG", 20, "logcat", "-b", "radio", "-v", "threadtime", "-d", "*:v", NULL);
+
+
+    /* show the traces we collected in main(), if that was done */
+    if (dump_traces_path != NULL) {
+        dump_file("VM TRACES JUST NOW", dump_traces_path);
+    }
+
+    /* only show ANR traces if they're less than 15 minutes old */
+    struct stat st;
+    char anr_traces_path[PATH_MAX];
+    property_get("dalvik.vm.stack-trace-file", anr_traces_path, "");
+    if (!anr_traces_path[0]) {
+        printf("*** NO VM TRACES FILE DEFINED (dalvik.vm.stack-trace-file)\n\n");
+    } else if (stat(anr_traces_path, &st)) {
+        printf("*** NO ANR VM TRACES FILE (%s): %s\n\n", anr_traces_path, strerror(errno));
+    } else {
+        dump_file("VM TRACES AT LAST ANR", anr_traces_path);
+    }
+
+    /* slow traces for slow operations */
+    if (anr_traces_path[0] != 0) {
+        int tail = strlen(anr_traces_path)-1;
+        while (tail > 0 && anr_traces_path[tail] != '/') {
+            tail--;
+        }
+        int i = 0;
+        while (1) {
+            sprintf(anr_traces_path+tail+1, "slow%02d.txt", i);
+            if (stat(anr_traces_path, &st)) {
+                // No traces file at this index, done with the files.
+                break;
+            }
+            dump_file("VM TRACES WHEN SLOW", anr_traces_path);
+            i++;
+        }
+    }
+
+    dump_file("NETWORK DEV INFO", "/proc/net/dev");
+    dump_file("QTAGUID NETWORK INTERFACES INFO", "/proc/net/xt_qtaguid/iface_stat_all");
+    dump_file("QTAGUID CTRL INFO", "/proc/net/xt_qtaguid/ctrl");
+    dump_file("QTAGUID STATS INFO", "/proc/net/xt_qtaguid/stats");
+
+    dump_file("NETWORK ROUTES", "/proc/net/route");
+    dump_file("NETWORK ROUTES IPV6", "/proc/net/ipv6_route");
+
+    /* TODO: Make last_kmsg CAP_SYSLOG protected. b/5555691 */
+    dump_file("LAST KMSG", "/proc/last_kmsg");
+    dump_file("LAST PANIC CONSOLE", "/data/dontpanic/apanic_console");
+    dump_file("LAST PANIC THREADS", "/data/dontpanic/apanic_threads");
+
+    if (screenshot_path[0]) {
+        ALOGI("taking screenshot\n");
+        run_command(NULL, 5, SU_PATH, "root", "screenshot", screenshot_path, NULL);
+        ALOGI("wrote screenshot: %s\n", screenshot_path);
+    }
+
+    run_command("SYSTEM SETTINGS", 20, SU_PATH, "root", "sqlite3",
+            "/data/data/com.android.providers.settings/databases/settings.db",
+            "pragma user_version; select * from system; select * from secure;", NULL);
+
+    /* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */
+    run_command("NETWORK INTERFACES", 10, SU_PATH, "root", "netcfg", NULL);
+    run_command("IP RULES", 10, "ip", "rule", "show", NULL);
+    run_command("IP RULES v6", 10, "ip", "-6", "rule", "show", NULL);
+    run_command("ROUTE TABLE 60", 10, "ip", "route", "show", "table", "60", NULL);
+    run_command("ROUTE TABLE 61 v6", 10, "ip", "-6", "route", "show", "table", "60", NULL);
+    run_command("ROUTE TABLE 61", 10, "ip", "route", "show", "table", "61", NULL);
+    run_command("ROUTE TABLE 61 v6", 10, "ip", "-6", "route", "show", "table", "61", NULL);
+    dump_file("ARP CACHE", "/proc/net/arp");
+    run_command("IPTABLES", 10, SU_PATH, "root", "iptables", "-L", "-nvx", NULL);
+    run_command("IP6TABLES", 10, SU_PATH, "root", "ip6tables", "-L", "-nvx", NULL);
+    run_command("IPTABLE NAT", 10, SU_PATH, "root", "iptables", "-t", "nat", "-L", "-n", NULL);
+    run_command("IPT6ABLE NAT", 10, SU_PATH, "root", "ip6tables", "-t", "nat", "-L", "-n", NULL);
+
+    run_command("WIFI NETWORKS", 20,
+            SU_PATH, "root", "wpa_cli", "list_networks", NULL);
+
+    property_get("dhcp.wlan0.gateway", network, "");
+    if (network[0])
+        run_command("PING GATEWAY", 10, SU_PATH, "root", "ping", "-c", "3", "-i", ".5", network, NULL);
+    property_get("dhcp.wlan0.dns1", network, "");
+    if (network[0])
+        run_command("PING DNS1", 10, SU_PATH, "root", "ping", "-c", "3", "-i", ".5", network, NULL);
+    property_get("dhcp.wlan0.dns2", network, "");
+    if (network[0])
+        run_command("PING DNS2", 10, SU_PATH, "root", "ping", "-c", "3", "-i", ".5", network, NULL);
+#ifdef FWDUMP_bcm4329
+    run_command("DUMP WIFI STATUS", 20,
+            SU_PATH, "root", "dhdutil", "-i", "wlan0", "dump", NULL);
+    run_command("DUMP WIFI INTERNAL COUNTERS", 20,
+            SU_PATH, "root", "wlutil", "counters", NULL);
+#endif
+
+    print_properties();
+
+    run_command("VOLD DUMP", 10, "vdc", "dump", NULL);
+    run_command("SECURE CONTAINERS", 10, "vdc", "asec", "list", NULL);
+
+    run_command("FILESYSTEMS & FREE SPACE", 10, SU_PATH, "root", "df", NULL);
+
+    dump_file("PACKAGE SETTINGS", "/data/system/packages.xml");
+    dump_file("PACKAGE UID ERRORS", "/data/system/uiderrors.txt");
+
+    run_command("LAST RADIO LOG", 10, "parse_radio_log", "/proc/last_radio_log", NULL);
+
+    printf("------ BACKLIGHTS ------\n");
+    printf("LCD brightness=");
+    dump_file(NULL, "/sys/class/leds/lcd-backlight/brightness");
+    printf("Button brightness=");
+    dump_file(NULL, "/sys/class/leds/button-backlight/brightness");
+    printf("Keyboard brightness=");
+    dump_file(NULL, "/sys/class/leds/keyboard-backlight/brightness");
+    printf("ALS mode=");
+    dump_file(NULL, "/sys/class/leds/lcd-backlight/als");
+    printf("LCD driver registers:\n");
+    dump_file(NULL, "/sys/class/leds/lcd-backlight/registers");
+    printf("\n");
+
+    /* Binder state is expensive to look at as it uses a lot of memory. */
+    dump_file("BINDER FAILED TRANSACTION LOG", "/sys/kernel/debug/binder/failed_transaction_log");
+    dump_file("BINDER TRANSACTION LOG", "/sys/kernel/debug/binder/transaction_log");
+    dump_file("BINDER TRANSACTIONS", "/sys/kernel/debug/binder/transactions");
+    dump_file("BINDER STATS", "/sys/kernel/debug/binder/stats");
+    dump_file("BINDER STATE", "/sys/kernel/debug/binder/state");
+
+#ifdef BOARD_HAS_DUMPSTATE
+    printf("========================================================\n");
+    printf("== Board\n");
+    printf("========================================================\n");
+
+    dumpstate_board();
+    printf("\n");
+#endif
+
+    /* Migrate the ril_dumpstate to a dumpstate_board()? */
+    char ril_dumpstate_timeout[PROPERTY_VALUE_MAX] = {0};
+    property_get("ril.dumpstate.timeout", ril_dumpstate_timeout, "30");
+    if (strnlen(ril_dumpstate_timeout, PROPERTY_VALUE_MAX - 1) > 0) {
+        if (0 == strncmp(build_type, "user", PROPERTY_VALUE_MAX - 1)) {
+            // su does not exist on user builds, so try running without it.
+            // This way any implementations of vril-dump that do not require
+            // root can run on user builds.
+            run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout),
+                    "vril-dump", NULL);
+        } else {
+            run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout),
+                    SU_PATH, "root", "vril-dump", NULL);
+        }
+    }
+
+    printf("========================================================\n");
+    printf("== Android Framework Services\n");
+    printf("========================================================\n");
+
+    /* the full dumpsys is starting to take a long time, so we need
+       to increase its timeout.  we really need to do the timeouts in
+       dumpsys itself... */
+    run_command("DUMPSYS", 60, "dumpsys", NULL);
+
+    printf("========================================================\n");
+    printf("== Running Application Activities\n");
+    printf("========================================================\n");
+
+    run_command("APP ACTIVITIES", 30, "dumpsys", "activity", "all", NULL);
+
+    printf("========================================================\n");
+    printf("== Running Application Services\n");
+    printf("========================================================\n");
+
+    run_command("APP SERVICES", 30, "dumpsys", "activity", "service", "all", NULL);
+
+    printf("========================================================\n");
+    printf("== Running Application Providers\n");
+    printf("========================================================\n");
+
+    run_command("APP SERVICES", 30, "dumpsys", "activity", "provider", "all", NULL);
+
+
+    printf("========================================================\n");
+    printf("== dumpstate: done\n");
+    printf("========================================================\n");
+}
+
+static void usage() {
+    fprintf(stderr, "usage: dumpstate [-b soundfile] [-e soundfile] [-o file [-d] [-p] [-z]] [-s]\n"
+            "  -o: write to file (instead of stdout)\n"
+            "  -d: append date to filename (requires -o)\n"
+            "  -z: gzip output (requires -o)\n"
+            "  -p: capture screenshot to filename.png (requires -o)\n"
+            "  -s: write output to control socket (for init)\n"
+            "  -b: play sound file instead of vibrate, at beginning of job\n"
+            "  -e: play sound file instead of vibrate, at end of job\n"
+		);
+}
+
+int main(int argc, char *argv[]) {
+    int do_add_date = 0;
+    int do_compress = 0;
+    char* use_outfile = 0;
+    char* begin_sound = 0;
+    char* end_sound = 0;
+    int use_socket = 0;
+    int do_fb = 0;
+
+    ALOGI("begin\n");
+
+    /* set as high priority, and protect from OOM killer */
+    setpriority(PRIO_PROCESS, 0, -20);
+    FILE *oom_adj = fopen("/proc/self/oom_adj", "w");
+    if (oom_adj) {
+        fputs("-17", oom_adj);
+        fclose(oom_adj);
+    }
+
+    /* very first thing, collect VM traces from Dalvik (needs root) */
+    dump_traces_path = dump_vm_traces();
+
+    int c;
+    while ((c = getopt(argc, argv, "b:de:ho:svzp")) != -1) {
+        switch (c) {
+            case 'b': begin_sound = optarg;  break;
+            case 'd': do_add_date = 1;       break;
+            case 'e': end_sound = optarg;    break;
+            case 'o': use_outfile = optarg;  break;
+            case 's': use_socket = 1;        break;
+            case 'v': break;  // compatibility no-op
+            case 'z': do_compress = 6;       break;
+            case 'p': do_fb = 1;             break;
+            case '?': printf("\n");
+            case 'h':
+                usage();
+                exit(1);
+        }
+    }
+
+    /* open the vibrator before dropping root */
+    FILE *vibrator = fopen("/sys/class/timed_output/vibrator/enable", "w");
+    if (vibrator) fcntl(fileno(vibrator), F_SETFD, FD_CLOEXEC);
+
+    /* read /proc/cmdline before dropping root */
+    FILE *cmdline = fopen("/proc/cmdline", "r");
+    if (cmdline != NULL) {
+        fgets(cmdline_buf, sizeof(cmdline_buf), cmdline);
+        fclose(cmdline);
+    }
+
+    if (getuid() == 0) {
+        if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
+            ALOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
+            return -1;
+        }
+
+        /* switch to non-root user and group */
+        gid_t groups[] = { AID_LOG, AID_SDCARD_RW, AID_MOUNT, AID_INET, AID_NET_BW_STATS };
+        if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
+            ALOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
+            return -1;
+        }
+        if (setgid(AID_SHELL) != 0) {
+            ALOGE("Unable to setgid, aborting: %s\n", strerror(errno));
+            return -1;
+        }
+        if (setuid(AID_SHELL) != 0) {
+            ALOGE("Unable to setuid, aborting: %s\n", strerror(errno));
+            return -1;
+        }
+
+        struct __user_cap_header_struct capheader;
+        struct __user_cap_data_struct capdata[2];
+        memset(&capheader, 0, sizeof(capheader));
+        memset(&capdata, 0, sizeof(capdata));
+        capheader.version = _LINUX_CAPABILITY_VERSION_3;
+        capheader.pid = 0;
+
+        capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
+        capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG);
+        capdata[0].inheritable = 0;
+        capdata[1].inheritable = 0;
+
+        if (capset(&capheader, &capdata[0]) < 0) {
+            ALOGE("capset failed: %s\n", strerror(errno));
+            return -1;
+        }
+    }
+
+    char path[PATH_MAX], tmp_path[PATH_MAX];
+    pid_t gzip_pid = -1;
+
+    if (use_socket) {
+        redirect_to_socket(stdout, "dumpstate");
+    } else if (use_outfile) {
+        strlcpy(path, use_outfile, sizeof(path));
+        if (do_add_date) {
+            char date[80];
+            time_t now = time(NULL);
+            strftime(date, sizeof(date), "-%Y-%m-%d-%H-%M-%S", localtime(&now));
+            strlcat(path, date, sizeof(path));
+        }
+        if (do_fb) {
+            strlcpy(screenshot_path, path, sizeof(screenshot_path));
+            strlcat(screenshot_path, ".png", sizeof(screenshot_path));
+        }
+        strlcat(path, ".txt", sizeof(path));
+        if (do_compress) strlcat(path, ".gz", sizeof(path));
+        strlcpy(tmp_path, path, sizeof(tmp_path));
+        strlcat(tmp_path, ".tmp", sizeof(tmp_path));
+        gzip_pid = redirect_to_file(stdout, tmp_path, do_compress);
+    }
+
+    if (begin_sound) {
+        play_sound(begin_sound);
+    } else if (vibrator) {
+        fputs("150", vibrator);
+        fflush(vibrator);
+    }
+
+    dumpstate();
+
+    if (end_sound) {
+        play_sound(end_sound);
+    } else if (vibrator) {
+        int i;
+        for (i = 0; i < 3; i++) {
+            fputs("75\n", vibrator);
+            fflush(vibrator);
+            usleep((75 + 50) * 1000);
+        }
+        fclose(vibrator);
+    }
+
+    /* wait for gzip to finish, otherwise it might get killed when we exit */
+    if (gzip_pid > 0) {
+        fclose(stdout);
+        waitpid(gzip_pid, NULL, 0);
+    }
+
+    /* rename the (now complete) .tmp file to its final location */
+    if (use_outfile && rename(tmp_path, path)) {
+        fprintf(stderr, "rename(%s, %s): %s\n", tmp_path, path, strerror(errno));
+    }
+
+    ALOGI("done\n");
+
+    return 0;
+}
diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h
new file mode 100644
index 0000000..c1c2ad8
--- /dev/null
+++ b/cmds/dumpstate/dumpstate.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _DUMPSTATE_H_
+#define _DUMPSTATE_H_
+
+#include <time.h>
+#include <unistd.h>
+#include <stdio.h>
+
+#define SU_PATH "/system/xbin/su"
+
+/* prints the contents of a file */
+int dump_file(const char *title, const char* path);
+
+/* forks a command and waits for it to finish -- terminate args with NULL */
+int run_command(const char *title, int timeout_seconds, const char *command, ...);
+
+/* prints all the system properties */
+void print_properties();
+
+/* redirect output to a service control socket */
+void redirect_to_socket(FILE *redirect, const char *service);
+
+/* redirect output to a file, optionally gzipping; returns gzip pid */
+pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level);
+
+/* dump Dalvik stack traces, return the trace file location (NULL if none) */
+const char *dump_vm_traces();
+
+/* for each process in the system, run the specified function */
+void for_each_pid(void (*func)(int, const char *), const char *header);
+
+/* Displays a blocked processes in-kernel wait channel */
+void show_wchan(int pid, const char *name);
+
+/* Runs "showmap" for a process */
+void do_showmap(int pid, const char *name);
+
+/* Gets the dmesg output for the kernel */
+void do_dmesg();
+
+/* Play a sound via Stagefright */
+void play_sound(const char* path);
+
+/* Implemented by libdumpstate_board to dump board-specific info */
+void dumpstate_board();
+
+#endif /* _DUMPSTATE_H_ */
diff --git a/cmds/dumpstate/utils.c b/cmds/dumpstate/utils.c
new file mode 100644
index 0000000..0d5ab90
--- /dev/null
+++ b/cmds/dumpstate/utils.c
@@ -0,0 +1,470 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/inotify.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <sys/klog.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <cutils/properties.h>
+#include <cutils/sockets.h>
+#include <private/android_filesystem_config.h>
+
+#include "dumpstate.h"
+
+void for_each_pid(void (*func)(int, const char *), const char *header) {
+    DIR *d;
+    struct dirent *de;
+
+    if (!(d = opendir("/proc"))) {
+        printf("Failed to open /proc (%s)\n", strerror(errno));
+        return;
+    }
+
+    printf("\n------ %s ------\n", header);
+    while ((de = readdir(d))) {
+        int pid;
+        int fd;
+        char cmdpath[255];
+        char cmdline[255];
+
+        if (!(pid = atoi(de->d_name))) {
+            continue;
+        }
+
+        sprintf(cmdpath,"/proc/%d/cmdline", pid);
+        memset(cmdline, 0, sizeof(cmdline));
+        if ((fd = open(cmdpath, O_RDONLY)) < 0) {
+            strcpy(cmdline, "N/A");
+        } else {
+            read(fd, cmdline, sizeof(cmdline));
+            close(fd);
+        }
+        func(pid, cmdline);
+    }
+
+    closedir(d);
+}
+
+void show_wchan(int pid, const char *name) {
+    char path[255];
+    char buffer[255];
+    int fd;
+
+    memset(buffer, 0, sizeof(buffer));
+
+    sprintf(path, "/proc/%d/wchan", pid);
+    if ((fd = open(path, O_RDONLY)) < 0) {
+        printf("Failed to open '%s' (%s)\n", path, strerror(errno));
+        return;
+    }
+
+    if (read(fd, buffer, sizeof(buffer)) < 0) {
+        printf("Failed to read '%s' (%s)\n", path, strerror(errno));
+        goto out_close;
+    }
+
+    printf("%-7d %-32s %s\n", pid, name, buffer);
+
+out_close:
+    close(fd);
+    return;
+}
+
+void do_dmesg() {
+    printf("------ KERNEL LOG (dmesg) ------\n");
+    int size = klogctl(10, NULL, 0); /* Get size of kernel buffer */
+    if (size <= 0) {
+        printf("Unexpected klogctl return value: %d\n\n", size);
+        return;
+    }
+    char *buf = (char *) malloc(size + 1);
+    if (buf == NULL) {
+        printf("memory allocation failed\n\n");
+        return;
+    }
+    int retval = klogctl(KLOG_READ_ALL, buf, size);
+    if (retval < 0) {
+        printf("klogctl failure\n\n");
+        free(buf);
+        return;
+    }
+    buf[retval] = '\0';
+    printf("%s\n\n", buf);
+    free(buf);
+    return;
+}
+
+void do_showmap(int pid, const char *name) {
+    char title[255];
+    char arg[255];
+
+    sprintf(title, "SHOW MAP %d (%s)", pid, name);
+    sprintf(arg, "%d", pid);
+    run_command(title, 10, SU_PATH, "root", "showmap", arg, NULL);
+}
+
+/* prints the contents of a file */
+int dump_file(const char *title, const char* path) {
+    char buffer[32768];
+    int fd = open(path, O_RDONLY);
+    if (fd < 0) {
+        int err = errno;
+        if (title) printf("------ %s (%s) ------\n", title, path);
+        printf("*** %s: %s\n", path, strerror(err));
+        if (title) printf("\n");
+        return -1;
+    }
+
+    if (title) printf("------ %s (%s", title, path);
+
+    if (title) {
+        struct stat st;
+        if (memcmp(path, "/proc/", 6) && memcmp(path, "/sys/", 5) && !fstat(fd, &st)) {
+            char stamp[80];
+            time_t mtime = st.st_mtime;
+            strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
+            printf(": %s", stamp);
+        }
+        printf(") ------\n");
+    }
+
+    int newline = 0;
+    for (;;) {
+        int ret = read(fd, buffer, sizeof(buffer));
+        if (ret > 0) {
+            newline = (buffer[ret - 1] == '\n');
+            ret = fwrite(buffer, ret, 1, stdout);
+        }
+        if (ret <= 0) break;
+    }
+
+    close(fd);
+    if (!newline) printf("\n");
+    if (title) printf("\n");
+    return 0;
+}
+
+/* forks a command and waits for it to finish */
+int run_command(const char *title, int timeout_seconds, const char *command, ...) {
+    fflush(stdout);
+    clock_t start = clock();
+    pid_t pid = fork();
+
+    /* handle error case */
+    if (pid < 0) {
+        printf("*** fork: %s\n", strerror(errno));
+        return pid;
+    }
+
+    /* handle child case */
+    if (pid == 0) {
+        const char *args[1024] = {command};
+        size_t arg;
+
+        va_list ap;
+        va_start(ap, command);
+        if (title) printf("------ %s (%s", title, command);
+        for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
+            args[arg] = va_arg(ap, const char *);
+            if (args[arg] == NULL) break;
+            if (title) printf(" %s", args[arg]);
+        }
+        if (title) printf(") ------\n");
+        fflush(stdout);
+
+        execvp(command, (char**) args);
+        printf("*** exec(%s): %s\n", command, strerror(errno));
+        fflush(stdout);
+        _exit(-1);
+    }
+
+    /* handle parent case */
+    for (;;) {
+        int status;
+        pid_t p = waitpid(pid, &status, WNOHANG);
+        float elapsed = (float) (clock() - start) / CLOCKS_PER_SEC;
+        if (p == pid) {
+            if (WIFSIGNALED(status)) {
+                printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
+            } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
+                printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
+            }
+            if (title) printf("[%s: %.1fs elapsed]\n\n", command, elapsed);
+            return status;
+        }
+
+        if (timeout_seconds && elapsed > timeout_seconds) {
+            printf("*** %s: Timed out after %.1fs (killing pid %d)\n", command, elapsed, pid);
+            kill(pid, SIGTERM);
+            return -1;
+        }
+
+        usleep(100000);  // poll every 0.1 sec
+    }
+}
+
+size_t num_props = 0;
+static char* props[2000];
+
+static void print_prop(const char *key, const char *name, void *user) {
+    (void) user;
+    if (num_props < sizeof(props) / sizeof(props[0])) {
+        char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
+        snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
+        props[num_props++] = strdup(buf);
+    }
+}
+
+static int compare_prop(const void *a, const void *b) {
+    return strcmp(*(char * const *) a, *(char * const *) b);
+}
+
+/* prints all the system properties */
+void print_properties() {
+    size_t i;
+    num_props = 0;
+    property_list(print_prop, NULL);
+    qsort(&props, num_props, sizeof(props[0]), compare_prop);
+
+    printf("------ SYSTEM PROPERTIES ------\n");
+    for (i = 0; i < num_props; ++i) {
+        fputs(props[i], stdout);
+        free(props[i]);
+    }
+    printf("\n");
+}
+
+/* redirect output to a service control socket */
+void redirect_to_socket(FILE *redirect, const char *service) {
+    int s = android_get_control_socket(service);
+    if (s < 0) {
+        fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno));
+        exit(1);
+    }
+    if (listen(s, 4) < 0) {
+        fprintf(stderr, "listen(control socket): %s\n", strerror(errno));
+        exit(1);
+    }
+
+    struct sockaddr addr;
+    socklen_t alen = sizeof(addr);
+    int fd = accept(s, &addr, &alen);
+    if (fd < 0) {
+        fprintf(stderr, "accept(control socket): %s\n", strerror(errno));
+        exit(1);
+    }
+
+    fflush(redirect);
+    dup2(fd, fileno(redirect));
+    close(fd);
+}
+
+/* redirect output to a file, optionally gzipping; returns gzip pid (or -1) */
+pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level) {
+    char *chp = path;
+
+    /* skip initial slash */
+    if (chp[0] == '/')
+        chp++;
+
+    /* create leading directories, if necessary */
+    while (chp && chp[0]) {
+        chp = strchr(chp, '/');
+        if (chp) {
+            *chp = 0;
+            mkdir(path, 0775);  /* drwxrwxr-x */
+            *chp++ = '/';
+        }
+    }
+
+    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
+    if (fd < 0) {
+        fprintf(stderr, "%s: %s\n", path, strerror(errno));
+        exit(1);
+    }
+
+    pid_t gzip_pid = -1;
+    if (gzip_level > 0) {
+        int fds[2];
+        if (pipe(fds)) {
+            fprintf(stderr, "pipe: %s\n", strerror(errno));
+            exit(1);
+        }
+
+        fflush(redirect);
+        fflush(stdout);
+
+        gzip_pid = fork();
+        if (gzip_pid < 0) {
+            fprintf(stderr, "fork: %s\n", strerror(errno));
+            exit(1);
+        }
+
+        if (gzip_pid == 0) {
+            dup2(fds[0], STDIN_FILENO);
+            dup2(fd, STDOUT_FILENO);
+
+            close(fd);
+            close(fds[0]);
+            close(fds[1]);
+
+            char level[10];
+            snprintf(level, sizeof(level), "-%d", gzip_level);
+            execlp("gzip", "gzip", level, NULL);
+            fprintf(stderr, "exec(gzip): %s\n", strerror(errno));
+            _exit(-1);
+        }
+
+        close(fd);
+        close(fds[0]);
+        fd = fds[1];
+    }
+
+    dup2(fd, fileno(redirect));
+    close(fd);
+    return gzip_pid;
+}
+
+/* dump Dalvik stack traces, return the trace file location (NULL if none) */
+const char *dump_vm_traces() {
+    char traces_path[PROPERTY_VALUE_MAX] = "";
+    property_get("dalvik.vm.stack-trace-file", traces_path, "");
+    if (!traces_path[0]) return NULL;
+
+    /* move the old traces.txt (if any) out of the way temporarily */
+    char anr_traces_path[PATH_MAX];
+    strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
+    strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
+    if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
+        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
+        return NULL;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
+    }
+
+    /* make the directory if necessary */
+    char anr_traces_dir[PATH_MAX];
+    strlcpy(anr_traces_dir, traces_path, sizeof(anr_traces_dir));
+    char *slash = strrchr(anr_traces_dir, '/');
+    if (slash != NULL) {
+        *slash = '\0';
+        if (!mkdir(anr_traces_dir, 0775)) {
+            chown(anr_traces_dir, AID_SYSTEM, AID_SYSTEM);
+        } else if (errno != EEXIST) {
+            fprintf(stderr, "mkdir(%s): %s\n", anr_traces_dir, strerror(errno));
+            return NULL;
+        }
+    }
+
+    /* create a new, empty traces.txt file to receive stack dumps */
+    int fd = open(traces_path, O_CREAT | O_WRONLY | O_TRUNC, 0666);  /* -rw-rw-rw- */
+    if (fd < 0) {
+        fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
+        return NULL;
+    }
+    close(fd);
+
+    /* walk /proc and kill -QUIT all Dalvik processes */
+    DIR *proc = opendir("/proc");
+    if (proc == NULL) {
+        fprintf(stderr, "/proc: %s\n", strerror(errno));
+        return NULL;
+    }
+
+    /* use inotify to find when processes are done dumping */
+    int ifd = inotify_init();
+    if (ifd < 0) {
+        fprintf(stderr, "inotify_init: %s\n", strerror(errno));
+        return NULL;
+    }
+
+    int wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
+    if (wfd < 0) {
+        fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
+        return NULL;
+    }
+
+    struct dirent *d;
+    int dalvik_found = 0;
+    while ((d = readdir(proc))) {
+        int pid = atoi(d->d_name);
+        if (pid <= 0) continue;
+
+        /* identify Dalvik: /proc/(pid)/exe = /system/bin/app_process */
+        char path[PATH_MAX], data[PATH_MAX];
+        snprintf(path, sizeof(path), "/proc/%d/exe", pid);
+        size_t len = readlink(path, data, sizeof(data) - 1);
+        if (len <= 0 || memcmp(data, "/system/bin/app_process", 23)) continue;
+
+        /* skip zygote -- it won't dump its stack anyway */
+        snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
+        int fd = open(path, O_RDONLY);
+        len = read(fd, data, sizeof(data) - 1);
+        close(fd);
+        if (len <= 0 || !memcmp(data, "zygote", 6)) continue;
+
+        ++dalvik_found;
+        if (kill(pid, SIGQUIT)) {
+            fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
+            continue;
+        }
+
+        /* wait for the writable-close notification from inotify */
+        struct pollfd pfd = { ifd, POLLIN, 0 };
+        int ret = poll(&pfd, 1, 200);  /* 200 msec timeout */
+        if (ret < 0) {
+            fprintf(stderr, "poll: %s\n", strerror(errno));
+        } else if (ret == 0) {
+            fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
+        } else {
+            struct inotify_event ie;
+            read(ifd, &ie, sizeof(ie));
+        }
+    }
+
+    close(ifd);
+    if (dalvik_found == 0) {
+        fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
+    }
+
+    static char dump_traces_path[PATH_MAX];
+    strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
+    strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
+    if (rename(traces_path, dump_traces_path)) {
+        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
+        return NULL;
+    }
+
+    /* replace the saved [ANR] traces.txt file */
+    rename(anr_traces_path, traces_path);
+    return dump_traces_path;
+}
+
+void play_sound(const char* path) {
+    run_command(NULL, 5, "/system/bin/stagefright", "-o", "-a", path, NULL);
+}