Overhaul of dumpstate (aka bugreport) with cleanups & enhancements:

- include basic build & timestamp information in the header
- collect stack traces immediately at bugreport time
- *also* show stack traces from last ANR (as before), if in the last 15 minutes
- alphabetize system properties dump
- remove now-obsolete (and always questionable) "dumpcrash" functionality
- write to a .tmp file first, then rename to the final filename
- friendly usage message
- output sections include the exact file/command run
- source de-weirdification -- it's several hundred lines shorter now

The same data is present in the same order as before, and I've tried
to preserve all the grep/search targets people might use to find their
way through the file.
diff --git a/cmds/dumpstate/Android.mk b/cmds/dumpstate/Android.mk
index 27891ec..431a556 100644
--- a/cmds/dumpstate/Android.mk
+++ b/cmds/dumpstate/Android.mk
@@ -15,15 +15,4 @@
 
 include $(BUILD_EXECUTABLE)
 
-COMMANDS = dumpcrash
-SYMLINKS := $(addprefix $(TARGET_OUT_EXECUTABLES)/,$(COMMANDS))
-$(SYMLINKS): DUMPSTATE_BINARY := dumpstate
-$(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk
-	@echo "Symlink: $@ -> $(DUMPSTATE_BINARY)"
-	@mkdir -p $(dir $@)
-	@rm -rf $@
-	$(hide) ln -sf $(DUMPSTATE_BINARY) $@
-
-ALL_DEFAULT_INSTALLED_MODULES += $(SYMLINKS)
-
 endif
diff --git a/cmds/dumpstate/dumpstate.c b/cmds/dumpstate/dumpstate.c
index a2b5d8d..9300915 100644
--- a/cmds/dumpstate/dumpstate.c
+++ b/cmds/dumpstate/dumpstate.c
@@ -14,361 +14,254 @@
  * limitations under the License.
  */
 
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <limits.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/time.h>
 #include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <unistd.h>
 
-#include <cutils/sockets.h>
+#include <cutils/properties.h>
+
 #include "private/android_filesystem_config.h"
 
-
 #define LOG_TAG "dumpstate"
 #include <utils/Log.h>
 
 #include "dumpstate.h"
 
-static char* const gzip_args[] = { "gzip", "-6", 0 };
-static int start_pattern[] = { 150, 0 };
-static int end_pattern[] = { 75, 50, 75, 50, 75, 0 };
-
-static struct tm now;
-
-static void dump_kernel_log(const char *path, const char *title) ;
+/* read before root is shed */
+static char cmdline_buf[16384] = "(unknown)";
+static const char *dump_traces_path = NULL;
 
 /* dumps the current system state to stdout */
-static void dumpstate(int full) {
-    if (full) {
-        PRINT("========================================================");
-        PRINT("== dumpstate");
-        PRINT("========================================================");
-        PRINT("------ MEMORY INFO ------");
-        DUMP("/proc/meminfo");
-        PRINT("------ CPU INFO ------");
-        EXEC7("top", "-n", "1", "-d", "1", "-m", "30", "-t");
-        PRINT("------ PROCRANK ------");
-        EXEC_XBIN("procrank");
-        PRINT("------ VIRTUAL MEMORY STATS ------");
-        DUMP("/proc/vmstat");
-        PRINT("------ VMALLOC INFO ------");
-        DUMP("/proc/vmallocinfo");
-        PRINT("------ SLAB INFO ------");
-        DUMP("/proc/slabinfo");
-        PRINT("------ ZONEINFO ------");
-        DUMP("/proc/zoneinfo");
-        PRINT("------ SYSTEM LOG ------");
-        EXEC4("logcat", "-v", "time", "-d", "*:v");
-        PRINT("------ VM TRACES ------");
-        DUMP("/data/anr/traces.txt");
-        PRINT("------ EVENT LOG TAGS ------");
-        DUMP("/etc/event-log-tags");
-        PRINT("------ EVENT LOG ------");
-        EXEC6("logcat", "-b", "events", "-v", "time", "-d", "*:v");
-        PRINT("------ RADIO LOG ------");
-        EXEC6("logcat", "-b", "radio", "-v", "time", "-d", "*:v");
-        PRINT("------ NETWORK STATE ------");
-        PRINT("Interfaces:");
-        EXEC("netcfg");
-        PRINT("");
-        PRINT("Routes:");
-        DUMP("/proc/net/route");
+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];
+
+    property_get("ro.build.display.id", build, "(unknown)");
+    property_get("ro.build.fingerprint", fingerprint, "(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("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");
+
+    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");
+
+    run_command("SYSTEM LOG", 20, "logcat", "-v", "time", "-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] && !stat(anr_traces_path, &st) && time(NULL) - st.st_mtime < 15 * 60) {
+        dump_file("VM TRACES AT LAST ANR", anr_traces_path);
+    }
+
+    // dump_file("EVENT LOG TAGS", "/etc/event-log-tags");
+    run_command("EVENT LOG", 20, "logcat", "-b", "events", "-v", "time", "-d", "*:v", NULL);
+    run_command("RADIO LOG", 20, "logcat", "-b", "radio", "-v", "time", "-d", "*:v", NULL);
+
+    run_command("NETWORK INTERFACES", 10, "netcfg", NULL);
+    dump_file("NETWORK ROUTES", "/proc/net/route");
+
 #ifdef FWDUMP_bcm4329
-        PRINT("Dump wlan FW log");
-        EXEC_XBIN6("su", "root","dhdutil","-i","eth0","upload","/data/local/tmp/wlan_crash.dump");
+    run_command("DUMP WIFI FIRMWARE LOG", 60,
+            "dhdutil", "-i", "eth0", "upload", "/data/local/tmp/wlan_crash.dump", NULL);
 #endif
-        PRINT("------ SYSTEM PROPERTIES ------");
-        print_properties();
-        PRINT("------ KERNEL LOG ------");
-        EXEC("dmesg");
-        PRINT("------ KERNEL WAKELOCKS ------");
-        DUMP("/proc/wakelocks");
-        PRINT("------ KERNEL CPUFREQ ------");
-        DUMP("/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
-        PRINT("");
-        PRINT("------ PROCESSES ------");
-        EXEC1("ps", "-P");
-        PRINT("------ PROCESSES AND THREADS ------");
-        EXEC3("ps", "-t", "-p", "-P");
-        PRINT("------ LIBRANK ------");
-        EXEC_XBIN("librank");
-        PRINT("------ BINDER FAILED TRANSACTION LOG ------");
-        DUMP("/proc/binder/failed_transaction_log");
-        PRINT("");
-        PRINT("------ BINDER TRANSACTION LOG ------");
-        DUMP("/proc/binder/transaction_log");
-        PRINT("");
-        PRINT("------ BINDER TRANSACTIONS ------");
-        DUMP("/proc/binder/transactions");
-        PRINT("");
-        PRINT("------ BINDER STATS ------");
-        DUMP("/proc/binder/stats");
-        PRINT("");
-        PRINT("------ BINDER PROCESS STATE: $i ------");
-        DUMP_FILES("/proc/binder/proc");
-        PRINT("------ FILESYSTEMS ------");
-        EXEC("df");
-        PRINT("------ PACKAGE SETTINGS ------");
-        DUMP("/data/system/packages.xml");
-        PRINT("------ PACKAGE UID ERRORS ------");
-        DUMP("/data/system/uiderrors.txt");
 
-        dump_kernel_log("/proc/last_kmsg", "LAST KMSG");
+    print_properties();
 
-        PRINT("------ LAST RADIO LOG ------");
-        EXEC1("parse_radio_log", "/proc/last_radio_log");
+    run_command("KERNEL LOG", 20, "dmesg", NULL);
 
-        dump_kernel_log("/data/dontpanic/apanic_console",
-                        "PANIC CONSOLE");
-        dump_kernel_log("/data/dontpanic/apanic_threads",
-                        "PANIC THREADS");
+    dump_file("KERNEL WAKELOCKS", "/proc/wakelocks");
+    dump_file("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
 
-        PRINT("------ BACKLIGHTS ------");
-        DUMP_PROMPT("LCD brightness=", "/sys/class/leds/lcd-backlight/brightness");
-        DUMP_PROMPT("Button brightness=", "/sys/class/leds/button-backlight/brightness");
-        DUMP_PROMPT("Keyboard brightness=", "/sys/class/leds/keyboard-backlight/brightness");
-        DUMP_PROMPT("ALS mode=", "/sys/class/leds/lcd-backlight/als");
-        DUMP_PROMPT("LCD driver registers:\n", "/sys/class/leds/lcd-backlight/registers");
-    }
-    PRINT("========================================================");
-    PRINT("== build.prop");
-    PRINT("========================================================");
+    run_command("PROCESSES", 10, "ps", "-P", NULL);
+    run_command("PROCESSES AND THREADS", 10, "ps", "-t", "-p", "-P", NULL);
+    run_command("LIBRANK", 10, "librank", NULL);
 
-    /* the crash server parses key-value pairs between the VERSION INFO and
-     * END lines so we can aggregate crash reports based on this data.
-     */
-    PRINT("------ VERSION INFO ------");
-    print_date("currenttime=", &now);
-    DUMP_PROMPT("kernel.version=", "/proc/version");
-    DUMP_PROMPT("kernel.cmdline=", "/proc/cmdline");
-    DUMP("/system/build.prop");
-    PROPERTY("gsm.version.ril-impl");
-    PROPERTY("gsm.version.baseband");
-    PROPERTY("gsm.imei");
-    PROPERTY("gsm.sim.operator.numeric");
-    PROPERTY("gsm.operator.alpha");
-    PRINT("------ END ------");
+    dump_file("BINDER FAILED TRANSACTION LOG", "/proc/binder/failed_transaction_log");
+    dump_file("BINDER TRANSACTION LOG", "/proc/binder/transaction_log");
+    dump_file("BINDER TRANSACTIONS", "/proc/binder/transactions");
+    dump_file("BINDER STATS", "/proc/binder/stats");
+    run_command("BINDER PROCESS STATE", 10, "sh", "-c", "cat /proc/binder/proc/*");
 
-    if (full) {
-        PRINT("========================================================");
-        PRINT("== dumpsys");
-        PRINT("========================================================");
-        /* 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... */
-        EXEC_TIMEOUT("dumpsys", 60);
-    }
+    run_command("FILESYSTEMS & FREE SPACE", 10, "df", NULL);
+
+    dump_file("PACKAGE SETTINGS", "/data/system/packages.xml");
+    dump_file("PACKAGE UID ERRORS", "/data/system/uiderrors.txt");
+
+    dump_file("LAST KMSG", "/proc/last_kmsg");
+    run_command("LAST RADIO LOG", 10, "parse_radio_log", "/proc/last_radio_log", NULL);
+    dump_file("LAST PANIC CONSOLE", "/data/dontpanic/apanic_console");
+    dump_file("LAST PANIC THREADS", "/data/dontpanic/apanic_threads");
+
+    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");
+
+    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);
 }
 
-/* used to check the file name passed via argv[0] */
-static int check_command_name(const char* name, const char* test) {
-    int name_length, test_length;
 
-    if (!strcmp(name, test))
-        return 1;
-
-    name_length = strlen(name);
-    test_length = strlen(test);
-
-    if (name_length > test_length + 2) {
-        name += (name_length - test_length);
-        if (name[-1] != '/')
-            return 0;
-        if (!strcmp(name, test))
-            return 1;
-    }
-
-    return 0;
+static void usage() {
+    fprintf(stderr, "usage: dumpstate [-d] [-o file] [-s] [-z]\n"
+            "  -d: append date to filename (requires -o)\n"
+            "  -o: write to file (instead of stdout)\n"
+            "  -s: write output to control socket (for init)\n"
+            "  -z: gzip output (requires -o)\n");
 }
 
 int main(int argc, char *argv[]) {
-    int dumpcrash = check_command_name(argv[0], "dumpcrash");
-    int add_date = 0;
-    char* outfile = 0;
-    int vibrate = 0;
-    int compress = 0;
-    int socket = 0;
-    int c, fd, vibrate_fd, fds[2];
-    char path[PATH_MAX];
-    pid_t   pid;
-    gid_t groups[] = { AID_LOG, AID_SDCARD_RW };
+    int do_add_date = 0;
+    int do_compress = 0;
+    char* use_outfile = 0;
+    int use_socket = 0;
 
     LOGI("begin\n");
 
     /* set as high priority, and protect from OOM killer */
     setpriority(PRIO_PROCESS, 0, -20);
-    protect_from_oom_killer();
+    FILE *oom_adj = fopen("/proc/self/oom_adj", "w");
+    if (oom_adj) {
+        fputs("-17", oom_adj);
+        fclose(oom_adj);
+    }
 
-    get_time(&now);
+    /* very first thing, collect VM traces from Dalvik (needs root) */
+    dump_traces_path = dump_vm_traces();
 
-    do {
-        c = getopt(argc, argv, "do:svz");
-        if (c == EOF)
-            break;
+    int c;
+    while ((c = getopt(argc, argv, "dho:svz")) != -1) {
         switch (c) {
-            case 'd':
-                add_date = 1;
-                break;
-            case 'o':
-                outfile = optarg;
-                break;
-            case 'v':
-                vibrate = 1;
-                break;
-            case 'z':
-                compress = 1;
-                break;
-            case 's':
-                socket = 1;
-                break;
-            case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
+            case 'd': do_add_date = 1;       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 '?': printf("\n");
+            case 'h':
+                usage();
                 exit(1);
         }
-    } while (1);
+    }
 
-    /* open vibrator before switching user */
-    if (vibrate) {
-        vibrate_fd = open("/sys/class/timed_output/vibrator/enable", O_WRONLY);
-        if (vibrate_fd > 0)
-            fcntl(vibrate_fd, F_SETFD, FD_CLOEXEC);
-    } else
-        vibrate_fd = -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);
+    }
 
     /* switch to non-root user and group */
+    gid_t groups[] = { AID_LOG, AID_SDCARD_RW };
     setgroups(sizeof(groups)/sizeof(groups[0]), groups);
     setuid(AID_SHELL);
 
-    /* make it safe to use both printf and STDOUT_FILENO */ 
-    setvbuf(stdout, 0, _IONBF, 0);
+    char path[PATH_MAX], tmp_path[PATH_MAX];
+    pid_t gzip_pid = -1;
 
-    if (socket) {
-        struct sockaddr addr;
-        socklen_t alen;
-
-        int s = android_get_control_socket("dumpstate");
-        if (s < 0) {
-            fprintf(stderr, "could not open dumpstate socket\n");
-            exit(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 (listen(s, 4) < 0) {
-            fprintf(stderr, "could not listen on dumpstate socket\n");
-            exit(1);
-        }
-
-        alen = sizeof(addr);
-        fd = accept(s, &addr, &alen);
-        if (fd < 0) {
-            fprintf(stderr, "could not accept dumpstate socket\n");
-            exit(1);
-        }
-
-        /* redirect stdout to the socket */
-        dup2(fd, STDOUT_FILENO);
-        close(fd);
-    } else if (outfile) {
-        if (strlen(outfile) > sizeof(path) - 100)
-            exit(1);
-
-        strcpy(path, outfile);
-        if (add_date) {
-            char date[260];
-            strftime(date, sizeof(date),
-                "-%Y-%m-%d-%H-%M-%S",
-                &now);
-            strcat(path, date);
-        }
-        if (compress)
-            strcat(path, ".gz");
-        else
-            strcat(path, ".txt");
-
-        /* ensure that all directories in the path exist */ 
-        create_directories(path);
-        fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
-        if (fd < 0)
-            return fd;
-
-        if (compress) {
-            pipe(fds);
-
-            /* redirect our stdout to the pipe */
-            dup2(fds[1], STDOUT_FILENO);
-            close(fds[1]);
-
-            if ((pid = fork()) < 0)
-            {
-                fprintf(stderr, "fork error\n");
-                exit(1);
-            }
-
-            if (pid) {
-                /* parent case */
-
-                /* close our copy of the input to gzip */
-                close(fds[0]);
-                /* close our copy of the output file */
-                close(fd);
-            } else {
-                /* child case */
-
-               /* redirect our input pipe to stdin */
-                dup2(fds[0], STDIN_FILENO);
-                close(fds[0]);
-
-                /* redirect stdout to the output file */
-                dup2(fd, STDOUT_FILENO);
-                close(fd);
-
-                /* run gzip to postprocess our output */
-                execv("/system/bin/gzip", gzip_args);
-                fprintf(stderr, "execv returned\n");
-            }
-        } else {
-            /* redirect stdout to the output file */
-            dup2(fd, STDOUT_FILENO);
-            close(fd);
-        }
-    }
-    /* else everything will print to stdout */
-
-    if (vibrate) {
-        vibrate_pattern(vibrate_fd, start_pattern);
-    }
-    dumpstate(!dumpcrash);
-    if (vibrate) {
-        vibrate_pattern(vibrate_fd, end_pattern);
-        close(vibrate_fd);
+        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);
     }
 
-    /* so gzip will terminate */
-    close(STDOUT_FILENO);
+    /* bzzzzzz */
+    if (vibrator) {
+        fputs("150", vibrator);
+        fflush(vibrator);
+    }
+
+    dumpstate();
+
+    /* bzzz bzzz bzzz */
+    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));
+    }
 
     LOGI("done\n");
 
     return 0;
 }
-
-static void dump_kernel_log(const char *path, const char *title) 
-
-{
-    printf("------ KERNEL %s LOG ------\n", title);
-    if (access(path, R_OK) < 0)
-        printf("%s: %s\n", path, strerror(errno));
-    else {
-        struct stat sbuf;
-
-        if (stat(path, &sbuf) < 0)
-            printf("%s: stat failed (%s)\n", path, strerror(errno));
-        else
-            printf("Harvested %s", ctime(&sbuf.st_mtime));
-    
-        DUMP(path);
-    }
-}
diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h
index ed1f005..6d48a85 100644
--- a/cmds/dumpstate/dumpstate.h
+++ b/cmds/dumpstate/dumpstate.h
@@ -18,157 +18,24 @@
 #define _DUMPSTATE_H_
 
 #include <time.h>
-
-// Commands time out after 60 seconds
-#define TIMEOUT     60
-
-#define PRINT(s) printf("%s\n", s)
-
-#define DUMP(file) dump_file(file)
-
-#define DUMP_FILES(path) dump_files(path)
-
-#define DUMP_PROMPT(prompt, file)   \
-{                                   \
-    printf(prompt);                 \
-    dump_file(file);                \
-}
-
-#define EXEC(cmd)               \
-{                               \
-    static struct Command c = { \
-        "/system/bin/" cmd,     \
-        { cmd, 0 }              \
-    };                          \
-    run_command(&c, TIMEOUT);   \
-}
-
-#define EXEC_TIMEOUT(cmd, tmout)\
-{                               \
-    static struct Command c = { \
-        "/system/bin/" cmd,     \
-        { cmd, 0 }              \
-    };                          \
-    run_command(&c, tmout);     \
-}
-
-#define EXEC_XBIN(cmd)          \
-{                               \
-    static struct Command c = { \
-        "/system/xbin/" cmd,    \
-        { cmd, 0 }              \
-    };                          \
-    run_command(&c, TIMEOUT);   \
-}
-
-#define EXEC1(cmd, a1)          \
-{                               \
-    static struct Command c = { \
-        "/system/bin/" cmd,     \
-        { cmd, a1, 0 }          \
-    };                          \
-    run_command(&c, TIMEOUT);   \
-}
-
-#define EXEC2(cmd, a1, a2)      \
-{                               \
-    static struct Command c = { \
-        "/system/bin/" cmd,     \
-        { cmd, a1, a2, 0 }      \
-    };                          \
-    run_command(&c, TIMEOUT);   \
-}
-
-#define EXEC3(cmd, a1, a2, a3)      \
-{                                   \
-    static struct Command c = {     \
-        "/system/bin/" cmd,         \
-        { cmd, a1, a2, a3, 0 }      \
-    };                              \
-    run_command(&c, TIMEOUT);       \
-}
-
-#define EXEC4(cmd, a1, a2, a3, a4)  \
-{                                   \
-    static struct Command c = {     \
-        "/system/bin/" cmd,         \
-        { cmd, a1, a2, a3, a4, 0 }  \
-    };                              \
-    run_command(&c, TIMEOUT);       \
-}
-
-#define EXEC6(cmd, a1, a2, a3, a4, a5, a6)  \
-{                                           \
-    static struct Command c = {             \
-        "/system/bin/" cmd,                 \
-        { cmd, a1, a2, a3, a4, a5, a6, 0 }  \
-    };                                      \
-    run_command(&c, TIMEOUT);               \
-}
-
-#define EXEC7(cmd, a1, a2, a3, a4, a5, a6, a7)  \
-{                                               \
-    static struct Command c = {                 \
-        "/system/bin/" cmd,                     \
-        { cmd, a1, a2, a3, a4, a5, a6, a7, 0 }  \
-    };                                          \
-    run_command(&c, TIMEOUT);                   \
-}
-
-#define EXEC8(cmd, a1, a2, a3, a4, a5, a6, a7, a8)  \
-{                                                   \
-    static struct Command c = {                     \
-        "/system/bin/" cmd,                         \
-        { cmd, a1, a2, a3, a4, a5, a6, a7, a8, 0 }  \
-    };                                              \
-    run_command(&c, TIMEOUT);                       \
-}
-
-#define EXEC_XBIN6(cmd, a1, a2, a3, a4, a5, a6)  \
-{                                           \
-    static struct Command c = {             \
-        "/system/xbin/" cmd,                \
-        { cmd, a1, a2, a3, a4, a5, a6, 0 }  \
-    };                                      \
-    run_command(&c, TIMEOUT);               \
-}
-
-#define PROPERTY(name) print_property(name)
-
-struct Command {
-    const char* path;
-    char* const args[];
-};
-typedef struct Command Command;
+#include <unistd.h>
 
 /* prints the contents of a file */
-int dump_file(const char* path);
+int dump_file(const char *title, const char* path);
 
-/* prints the contents of all files in a directory */
-void dump_files(const char* path);
-
-/* forks a command and waits for it to finish */
-int run_command(struct Command* cmd, int timeout);
-
-/* reads the current time into tm */
-void get_time(struct tm *tm);
-
-/* prints the date in tm */
-void print_date(const char* prompt, struct tm *tm);
-
-/* prints the name and value of a system property */
-int print_property(const char* name);
+/* 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();
 
-/* creates directories as needed for the given path */
-void create_directories(char *path);
+/* redirect output to a service control socket */
+void redirect_to_socket(FILE *redirect, const char *service);
 
-/* runs the vibrator using the given pattern */
-void vibrate_pattern(int fd, int* pattern);
+/* redirect output to a file, optionally gzipping; returns gzip pid */
+pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level);
 
-/* prevents the OOM killer from killing us */
-void protect_from_oom_killer();
+/* dump Dalvik stack traces, return the trace file location (NULL if none) */
+const char *dump_vm_traces();
 
 #endif /* _DUMPSTATE_H_ */
diff --git a/cmds/dumpstate/utils.c b/cmds/dumpstate/utils.c
index 60d845f..fda618c 100644
--- a/cmds/dumpstate/utils.c
+++ b/cmds/dumpstate/utils.c
@@ -14,217 +14,337 @@
  * 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 <time.h>
-#include <unistd.h>
+#include <sys/inotify.h>
 #include <sys/stat.h>
-#include <dirent.h>
-#include <limits.h>
-#include <fcntl.h>
-#include <signal.h>
 #include <sys/time.h>
 #include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
 
 #include <cutils/properties.h>
-#include <sys/system_properties.h>
+#include <cutils/sockets.h>
 
 #include "dumpstate.h"
 
 
 /* prints the contents of a file */
-int dump_file(const char* path) {
-    char    buffer[32768];
-    int fd, amount_read;
-    int ret = 0;
+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;
+    }
 
-    fd = open(path, O_RDONLY);
-    if (fd < 0)
-        return fd;
+    if (title) printf("----- %s (%s", title, path);
 
-    do {
-        ret = read(fd, buffer, sizeof(buffer));
-        if (ret > 0)
-            ret = write(STDOUT_FILENO, buffer, ret);
-    } while (ret > 0);
+    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");
+    }
 
-    buffer[0] = '\n';
-    write(STDOUT_FILENO, buffer, 1);
+    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);
-    return ret;
-}
-
-/* prints the contents of all files in a directory */
-void dump_files(const char* path) {
-    DIR* dir;
-    struct dirent* entry;
-    char buffer[PATH_MAX];
-
-    dir = opendir(path);
-    if (!dir) {
-        fprintf(stderr, "could not open directory %s\n", path);
-        return;
-    }
-
-    while ((entry = readdir(dir))) {
-        if (entry->d_type == DT_REG) {
-            snprintf(buffer, sizeof(buffer), "%s/%s", path, entry->d_name);
-            dump_file(path);
-            printf("\n");
-        }
-    }
-
-    closedir(dir);
-}
-
-/* prints the name and value of a system property */
-int print_property(const char* name) {
-    char    value[PROP_VALUE_MAX];
-
-    __system_property_get(name, value);
-    printf("%s=%s\n", name, value);
+    if (!newline) printf("\n");
+    if (title) printf("\n");
     return 0;
 }
 
-static pid_t alarm_pid = 0;
-static int timed_out = 0;
-static void sig_alarm(int sig)
-{
-    if (alarm_pid) {
-        kill(alarm_pid, SIGKILL);
-        timed_out = 1;
-        alarm_pid = 0;
-    }
-}
-
 /* forks a command and waits for it to finish */
-int run_command(struct Command* cmd, int timeout) {
-    struct sigaction sa;
-    pid_t pid;
-    int status;
+int run_command(const char *title, int timeout_seconds, const char *command, ...) {
+    fflush(stdout);
+    clock_t start = clock();
+    pid_t pid = fork();
 
-    pid = fork();
     /* handle error case */
-    if (pid < 0)
+    if (pid < 0) {
+        printf("*** fork: %s\n", strerror(errno));
         return pid;
+    }
 
     /* handle child case */
     if (pid == 0) {
-        int ret = execv(cmd->path, cmd->args);
-        if (ret)
-            fprintf(stderr, "execv %s returned %d\n", cmd->path, ret);
-        exit(ret);
+        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));
+        _exit(-1);
     }
 
     /* handle parent case */
-    timed_out = 0;
-    if (timeout) {
-        memset(&sa, 0, sizeof(sa));
-        sa.sa_flags = SA_RESETHAND;
-        sa.sa_handler = sig_alarm;
-        sigaction(SIGALRM, &sa, NULL);
+    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 (WEXITSTATUS(status) > 0) {
+                printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
+            }
+            if (title) printf("[%s: %.1fs elapsed]\n\n", command, elapsed);
+            return status;
+        }
 
-        /* set an alarm so we don't hang forever */
-        alarm_pid = pid;
-        alarm(timeout);
+        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
     }
-
-    waitpid(pid, &status, 0);
-
-    if (timed_out)
-        printf("ERROR: command %s timed out\n", cmd->path);
-
-    return status;
 }
 
-/* reads the current time into tm */
-void get_time(struct tm *tm) {
-    time_t t;
+size_t num_props = 0;
+static char* props[2000];
 
-    tzset();
-    time(&t);
-    localtime_r(&t, tm);
+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);
+    }
 }
 
-/* prints the date in tm */
-void print_date(const char* prompt, struct tm *tm) {
-    char strbuf[260];
-
-    strftime(strbuf, sizeof(strbuf),
-             "%a %b %e %H:%M:%S %Z %Y",
-             tm);
-    printf("%s%s\n", prompt, strbuf);
-}
-
-
-static void print_prop(const char *key, const char *name, 
-                     void *user __attribute__((unused)))
-{
-    printf("[%s]: [%s]\n", key, name);
+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");
 }
 
-/* creates directories as needed for the given path */
-void create_directories(char *path)
-{
+/* 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, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
-            *chp = '/';
-            chp++;
+            mkdir(path, 0775);  /* drwxrwxr-x */
+            *chp++ = '/';
         }
     }
-}
 
-/* runs the vibrator using the given pattern */
-void vibrate_pattern(int fd, int* pattern)
-{
-    struct timespec tm;
-    char    buffer[10];
-
-    while (*pattern) {
-        /* read vibrate on time */
-        int on_time = *pattern++;
-        snprintf(buffer, sizeof(buffer), "%d", on_time);
-        write(fd, buffer, strlen(buffer));
-
-        /* read vibrate off time */
-        int delay = *pattern++;
-        if (delay) {
-            delay += on_time;
-
-            tm.tv_sec = delay / 1000;
-            tm.tv_nsec = (delay % 1000) * 1000000;
-            nanosleep(&tm, NULL);
-        } else
-            break;
+    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);
     }
-}
 
-/* prevents the OOM killer from killing us */
-void protect_from_oom_killer()
-{
-    int fd;
+    pid_t gzip_pid = -1;
+    if (gzip_level > 0) {
+        int fds[2];
+        if (pipe(fds)) {
+            fprintf(stderr, "pipe: %s\n", strerror(errno));
+            exit(1);
+        }
 
-    fd = open("/proc/self/oom_adj", O_WRONLY);
-    if (fd >= 0) {
-        // -17 should make us immune to OOM
-        const char* text = "-17";
-        write(fd, text, strlen(text));
+        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));
+    rename(traces_path, anr_traces_path);
+
+    /* 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;
+    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;
+
+        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);
+
+    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;
 }