am f1ab88c2: am 73c019b3: Add asus vendor id

* commit 'f1ab88c23460a608cd6d6f6492fb2b039405c0f2':
  Add asus vendor id
diff --git a/adb/Android.mk b/adb/Android.mk
index 7744d2b..248208a 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -133,6 +133,10 @@
 LOCAL_CFLAGS += -DANDROID_GADGET=1
 endif
 
+ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
+LOCAL_CFLAGS += -DALLOW_ADBD_ROOT=1
+endif
+
 LOCAL_MODULE := adbd
 
 LOCAL_FORCE_STATIC_EXECUTABLE := true
diff --git a/adb/adb.c b/adb/adb.c
index e35c334..4434524 100644
--- a/adb/adb.c
+++ b/adb/adb.c
@@ -299,6 +299,13 @@
         return;
     }
 
+    if(!strcmp(type, "sideload")) {
+        D("setting connection_state to CS_SIDELOAD\n");
+        t->connection_state = CS_SIDELOAD;
+        update_transports();
+        return;
+    }
+
     t->connection_state = CS_HOST;
 }
 
@@ -835,10 +842,43 @@
   snprintf(target_str, target_size, "tcp:%d", server_port);
 }
 
+#if !ADB_HOST
+static int should_drop_privileges() {
+#ifndef ALLOW_ADBD_ROOT
+    return 1;
+#else /* ALLOW_ADBD_ROOT */
+    int secure = 0;
+    char value[PROPERTY_VALUE_MAX];
+
+   /* run adbd in secure mode if ro.secure is set and
+    ** we are not in the emulator
+    */
+    property_get("ro.kernel.qemu", value, "");
+    if (strcmp(value, "1") != 0) {
+        property_get("ro.secure", value, "1");
+        if (strcmp(value, "1") == 0) {
+            // don't run as root if ro.secure is set...
+            secure = 1;
+
+            // ... except we allow running as root in userdebug builds if the
+            // service.adb.root property has been set by the "adb root" command
+            property_get("ro.debuggable", value, "");
+            if (strcmp(value, "1") == 0) {
+                property_get("service.adb.root", value, "");
+                if (strcmp(value, "1") == 0) {
+                    secure = 0;
+                }
+            }
+        }
+    }
+    return secure;
+#endif /* ALLOW_ADBD_ROOT */
+}
+#endif /* !ADB_HOST */
+
 int adb_main(int is_daemon, int server_port)
 {
 #if !ADB_HOST
-    int secure = 0;
     int port;
     char value[PROPERTY_VALUE_MAX];
 #endif
@@ -866,31 +906,10 @@
         exit(1);
     }
 #else
-    /* run adbd in secure mode if ro.secure is set and
-    ** we are not in the emulator
-    */
-    property_get("ro.kernel.qemu", value, "");
-    if (strcmp(value, "1") != 0) {
-        property_get("ro.secure", value, "1");
-        if (strcmp(value, "1") == 0) {
-            // don't run as root if ro.secure is set...
-            secure = 1;
-
-            // ... except we allow running as root in userdebug builds if the
-            // service.adb.root property has been set by the "adb root" command
-            property_get("ro.debuggable", value, "");
-            if (strcmp(value, "1") == 0) {
-                property_get("service.adb.root", value, "");
-                if (strcmp(value, "1") == 0) {
-                    secure = 0;
-                }
-            }
-        }
-    }
 
     /* don't listen on a port (default 5037) if running in secure mode */
     /* don't run as root if we are running in secure mode */
-    if (secure) {
+    if (should_drop_privileges()) {
         struct __user_cap_header_struct header;
         struct __user_cap_data_struct cap;
 
diff --git a/adb/adb.h b/adb/adb.h
index ac31f11..f7667c2 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -434,6 +434,7 @@
 #define CS_HOST       3
 #define CS_RECOVERY   4
 #define CS_NOPERM     5 /* Insufficient permissions to communicate with the device */
+#define CS_SIDELOAD   6
 
 extern int HOST;
 extern int SHELL_EXIT_NOTIFY_FD;
diff --git a/adb/commandline.c b/adb/commandline.c
index ffc120f..5b2aa88 100644
--- a/adb/commandline.c
+++ b/adb/commandline.c
@@ -367,6 +367,83 @@
     }
 }
 
+int adb_download_buffer(const char *service, const void* data, int sz,
+                        unsigned progress)
+{
+    char buf[4096];
+    unsigned total;
+    int fd;
+    const unsigned char *ptr;
+
+    sprintf(buf,"%s:%d", service, sz);
+    fd = adb_connect(buf);
+    if(fd < 0) {
+        fprintf(stderr,"error: %s\n", adb_error());
+        return -1;
+    }
+
+    int opt = CHUNK_SIZE;
+    opt = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
+
+    total = sz;
+    ptr = data;
+
+    if(progress) {
+        char *x = strrchr(service, ':');
+        if(x) service = x + 1;
+    }
+
+    while(sz > 0) {
+        unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz;
+        if(writex(fd, ptr, xfer)) {
+            adb_status(fd);
+            fprintf(stderr,"* failed to write data '%s' *\n", adb_error());
+            return -1;
+        }
+        sz -= xfer;
+        ptr += xfer;
+        if(progress) {
+            printf("sending: '%s' %4d%%    \r", service, (int)(100LL - ((100LL * sz) / (total))));
+            fflush(stdout);
+        }
+    }
+    if(progress) {
+        printf("\n");
+    }
+
+    if(readx(fd, buf, 4)){
+        fprintf(stderr,"* error reading response *\n");
+        adb_close(fd);
+        return -1;
+    }
+    if(memcmp(buf, "OKAY", 4)) {
+        buf[4] = 0;
+        fprintf(stderr,"* error response '%s' *\n", buf);
+        adb_close(fd);
+        return -1;
+    }
+
+    adb_close(fd);
+    return 0;
+}
+
+
+int adb_download(const char *service, const char *fn, unsigned progress)
+{
+    void *data;
+    unsigned sz;
+
+    data = load_file(fn, &sz);
+    if(data == 0) {
+        fprintf(stderr,"* cannot read '%s' *\n", service);
+        return -1;
+    }
+
+    int status = adb_download_buffer(service, data, sz, progress);
+    free(data);
+    return status;
+}
+
 static void status_window(transport_type ttype, const char* serial)
 {
     char command[4096];
@@ -561,6 +638,10 @@
 
     free(quoted_log_tags);
 
+    if (!strcmp(argv[0],"longcat")) {
+        strncat(buf, " -v long", sizeof(buf)-1);
+    }
+
     argc -= 1;
     argv += 1;
     while(argc-- > 0) {
@@ -644,6 +725,7 @@
         return -1;
     }
 
+    printf("Now unlock your device and confirm the backup operation.\n");
     copy_to_file(fd, outFd);
 
     adb_close(fd);
@@ -671,6 +753,7 @@
         return -1;
     }
 
+    printf("Now unlock your device and confirm the restore operation.\n");
     copy_to_file(tarFd, fd);
 
     adb_close(fd);
@@ -1057,6 +1140,15 @@
         return 0;
     }
 
+    if(!strcmp(argv[0], "sideload")) {
+        if(argc != 2) return usage();
+        if(adb_download("sideload", argv[1], 1)) {
+            return 1;
+        } else {
+            return 0;
+        }
+    }
+
     if(!strcmp(argv[0], "remount") || !strcmp(argv[0], "reboot")
             || !strcmp(argv[0], "reboot-bootloader")
             || !strcmp(argv[0], "tcpip") || !strcmp(argv[0], "usb")
@@ -1225,7 +1317,7 @@
         return 0;
     }
 
-    if(!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat")) {
+    if(!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
         return logcat(ttype, serial, argc, argv);
     }
 
diff --git a/adb/transport.c b/adb/transport.c
index 83a349a..2f7bd27 100644
--- a/adb/transport.c
+++ b/adb/transport.c
@@ -831,6 +831,7 @@
     case CS_DEVICE: return "device";
     case CS_HOST: return "host";
     case CS_RECOVERY: return "recovery";
+    case CS_SIDELOAD: return "sideload";
     case CS_NOPERM: return "no permissions";
     default: return "unknown";
     }
diff --git a/adb/transport_local.c b/adb/transport_local.c
index d985ee3..105c502 100644
--- a/adb/transport_local.c
+++ b/adb/transport_local.c
@@ -318,7 +318,7 @@
             /* Running inside the device: use TCP socket as the transport. */
             func = server_socket_thread;
         }
-#endif !ADB_HOST
+#endif // !ADB_HOST
     }
 
     D("transport: local %s init\n", HOST ? "client" : "server");
diff --git a/debuggerd/Android.mk b/debuggerd/Android.mk
index 6cfe79b..f127363 100644
--- a/debuggerd/Android.mk
+++ b/debuggerd/Android.mk
@@ -5,12 +5,9 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= debuggerd.c utility.c getevent.c $(TARGET_ARCH)/machine.c $(TARGET_ARCH)/unwind.c symbol_table.c
-ifeq ($(TARGET_ARCH),arm)
-LOCAL_SRC_FILES += $(TARGET_ARCH)/pr-support.c
-endif
+LOCAL_SRC_FILES:= debuggerd.c utility.c getevent.c $(TARGET_ARCH)/machine.c
 
-LOCAL_CFLAGS := -Wall
+LOCAL_CFLAGS := -Wall -Werror -std=gnu99
 LOCAL_MODULE := debuggerd
 
 ifeq ($(ARCH_ARM_HAVE_VFP),true)
@@ -20,7 +17,7 @@
 LOCAL_CFLAGS += -DWITH_VFP_D32
 endif # ARCH_ARM_HAVE_VFP_D32
 
-LOCAL_STATIC_LIBRARIES := libcutils libc
+LOCAL_SHARED_LIBRARIES := libcutils libc libcorkscrew
 
 include $(BUILD_EXECUTABLE)
 
diff --git a/debuggerd/arm/machine.c b/debuggerd/arm/machine.c
index d5efb79..ca45c9b 100644
--- a/debuggerd/arm/machine.c
+++ b/debuggerd/arm/machine.c
@@ -34,10 +34,11 @@
 #include <linux/input.h>
 #include <linux/user.h>
 
-#include "utility.h"
+#include "../utility.h"
+#include "../machine.h"
 
 /* enable to dump memory pointed to by every register */
-#define DUMP_MEM_FOR_ALL_REGS 0
+#define DUMP_MEMORY_FOR_ALL_REGISTERS 1
 
 #ifdef WITH_VFP
 #ifdef WITH_VFP_D32
@@ -47,172 +48,22 @@
 #endif
 #endif
 
-/* Main entry point to get the backtrace from the crashing process */
-extern int unwind_backtrace_with_ptrace(int tfd, pid_t pid, mapinfo *map,
-                                        unsigned int sp_list[],
-                                        int *frame0_pc_sane,
-                                        bool at_fault);
-
 /*
- * If this isn't clearly a null pointer dereference, dump the
- * /proc/maps entries near the fault address.
- *
- * This only makes sense to do on the thread that crashed.
+ * If configured to do so, dump memory around *all* registers
+ * for the crashing thread.
  */
-static void show_nearby_maps(int tfd, int pid, mapinfo *map)
-{
-    siginfo_t si;
-
-    memset(&si, 0, sizeof(si));
-    if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si)) {
-        _LOG(tfd, false, "cannot get siginfo for %d: %s\n",
-            pid, strerror(errno));
+static void dump_memory_and_code(int tfd, pid_t tid, bool at_fault) {
+    struct pt_regs regs;
+    if(ptrace(PTRACE_GETREGS, tid, 0, &regs)) {
         return;
     }
-    if (!signal_has_address(si.si_signo))
-        return;
 
-    uintptr_t addr = (uintptr_t) si.si_addr;
-    addr &= ~0xfff;     /* round to 4K page boundary */
-    if (addr == 0)      /* null-pointer deref */
-        return;
+    if (at_fault && DUMP_MEMORY_FOR_ALL_REGISTERS) {
+        static const char REG_NAMES[] = "r0r1r2r3r4r5r6r7r8r9slfpipsp";
 
-    _LOG(tfd, false, "\nmemory map around addr %08x:\n", si.si_addr);
-
-    /*
-     * Search for a match, or for a hole where the match would be.  The list
-     * is backward from the file content, so it starts at high addresses.
-     */
-    bool found = false;
-    mapinfo *next = NULL;
-    mapinfo *prev = NULL;
-    while (map != NULL) {
-        if (addr >= map->start && addr < map->end) {
-            found = true;
-            next = map->next;
-            break;
-        } else if (addr >= map->end) {
-            /* map would be between "prev" and this entry */
-            next = map;
-            map = NULL;
-            break;
-        }
-
-        prev = map;
-        map = map->next;
-    }
-
-    /*
-     * Show "next" then "match" then "prev" so that the addresses appear in
-     * ascending order (like /proc/pid/maps).
-     */
-    if (next != NULL) {
-        _LOG(tfd, false, "%08x-%08x %s\n", next->start, next->end, next->name);
-    } else {
-        _LOG(tfd, false, "(no map below)\n");
-    }
-    if (map != NULL) {
-        _LOG(tfd, false, "%08x-%08x %s\n", map->start, map->end, map->name);
-    } else {
-        _LOG(tfd, false, "(no map for address)\n");
-    }
-    if (prev != NULL) {
-        _LOG(tfd, false, "%08x-%08x %s\n", prev->start, prev->end, prev->name);
-    } else {
-        _LOG(tfd, false, "(no map above)\n");
-    }
-}
-
-/*
- * Dumps a few bytes of memory, starting a bit before and ending a bit
- * after the specified address.
- */
-static void dump_memory(int tfd, int pid, uintptr_t addr,
-    bool only_in_tombstone)
-{
-    char code_buffer[64];       /* actual 8+1+((8+1)*4) + 1 == 45 */
-    char ascii_buffer[32];      /* actual 16 + 1 == 17 */
-    uintptr_t p, end;
-
-    p = addr & ~3;
-    p -= 32;
-    if (p > addr) {
-        /* catch underflow */
-        p = 0;
-    }
-    end = p + 80;
-    /* catch overflow; 'end - p' has to be multiples of 16 */
-    while (end < p)
-        end -= 16;
-
-    /* Dump the code around PC as:
-     *  addr     contents                             ascii
-     *  00008d34 ef000000 e8bd0090 e1b00000 512fff1e  ............../Q
-     *  00008d44 ea00b1f9 e92d0090 e3a070fc ef000000  ......-..p......
-     */
-    while (p < end) {
-        char* asc_out = ascii_buffer;
-
-        sprintf(code_buffer, "%08x ", p);
-
-        int i;
-        for (i = 0; i < 4; i++) {
-            /*
-             * If we see (data == -1 && errno != 0), we know that the ptrace
-             * call failed, probably because we're dumping memory in an
-             * unmapped or inaccessible page.  I don't know if there's
-             * value in making that explicit in the output -- it likely
-             * just complicates parsing and clarifies nothing for the
-             * enlightened reader.
-             */
-            long data = ptrace(PTRACE_PEEKTEXT, pid, (void*)p, NULL);
-            sprintf(code_buffer + strlen(code_buffer), "%08lx ", data);
-
-            int j;
-            for (j = 0; j < 4; j++) {
-                /*
-                 * Our isprint() allows high-ASCII characters that display
-                 * differently (often badly) in different viewers, so we
-                 * just use a simpler test.
-                 */
-                char val = (data >> (j*8)) & 0xff;
-                if (val >= 0x20 && val < 0x7f) {
-                    *asc_out++ = val;
-                } else {
-                    *asc_out++ = '.';
-                }
-            }
-            p += 4;
-        }
-        *asc_out = '\0';
-        _LOG(tfd, only_in_tombstone, "%s %s\n", code_buffer, ascii_buffer);
-    }
-
-}
-
-void dump_stack_and_code(int tfd, int pid, mapinfo *map,
-                         int unwind_depth, unsigned int sp_list[],
-                         bool at_fault)
-{
-    struct pt_regs r;
-    int sp_depth;
-    bool only_in_tombstone = !at_fault;
-
-    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) return;
-
-    if (DUMP_MEM_FOR_ALL_REGS && at_fault) {
-        /*
-         * If configured to do so, dump memory around *all* registers
-         * for the crashing thread.
-         *
-         * TODO: remove duplicates.
-         */
-        static const char REG_NAMES[] = "R0R1R2R3R4R5R6R7R8R9SLFPIPSPLRPC";
-
-        int reg;
-        for (reg = 0; reg < 16; reg++) {
+        for (int reg = 0; reg < 14; reg++) {
             /* this may not be a valid way to access, but it'll do for now */
-            uintptr_t addr = r.uregs[reg];
+            uintptr_t addr = regs.uregs[reg];
 
             /*
              * Don't bother if it looks like a small int or ~= null, or if
@@ -222,152 +73,65 @@
                 continue;
             }
 
-            _LOG(tfd, only_in_tombstone, "\nmem near %.2s:\n",
-                &REG_NAMES[reg*2]);
-            dump_memory(tfd, pid, addr, false);
-        }
-    } else {
-        unsigned int pc, lr;
-        pc = r.ARM_pc;
-        lr = r.ARM_lr;
-
-        _LOG(tfd, only_in_tombstone, "\ncode around pc:\n");
-        dump_memory(tfd, pid, (uintptr_t) pc, only_in_tombstone);
-
-        if (lr != pc) {
-            _LOG(tfd, only_in_tombstone, "\ncode around lr:\n");
-            dump_memory(tfd, pid, (uintptr_t) lr, only_in_tombstone);
+            _LOG(tfd, false, "\nmemory near %.2s:\n", &REG_NAMES[reg * 2]);
+            dump_memory(tfd, tid, addr, at_fault);
         }
     }
 
-    if (at_fault) {
-        show_nearby_maps(tfd, pid, map);
-    }
+    _LOG(tfd, !at_fault, "\ncode around pc:\n");
+    dump_memory(tfd, tid, (uintptr_t)regs.ARM_pc, at_fault);
 
-    unsigned int p, end;
-    unsigned int sp = r.ARM_sp;
-
-    p = sp - 64;
-    if (p > sp)
-        p = 0;
-    p &= ~3;
-    if (unwind_depth != 0) {
-        if (unwind_depth < STACK_CONTENT_DEPTH) {
-            end = sp_list[unwind_depth-1];
-        }
-        else {
-            end = sp_list[STACK_CONTENT_DEPTH-1];
-        }
-    }
-    else {
-        end = p + 256;
-        /* 'end - p' has to be multiples of 4 */
-        if (end < p)
-            end = ~7;
-    }
-
-    _LOG(tfd, only_in_tombstone, "\nstack:\n");
-
-    /* If the crash is due to PC == 0, there will be two frames that
-     * have identical SP value.
-     */
-    if (sp_list[0] == sp_list[1]) {
-        sp_depth = 1;
-    }
-    else {
-        sp_depth = 0;
-    }
-
-    while (p <= end) {
-         char *prompt;
-         char level[16];
-         long data = ptrace(PTRACE_PEEKTEXT, pid, (void*)p, NULL);
-         if (p == sp_list[sp_depth]) {
-             sprintf(level, "#%02d", sp_depth++);
-             prompt = level;
-         }
-         else {
-             prompt = "   ";
-         }
-
-         /* Print the stack content in the log for the first 3 frames. For the
-          * rest only print them in the tombstone file.
-          */
-         _LOG(tfd, (sp_depth > 2) || only_in_tombstone,
-              "%s %08x  %08x  %s\n", prompt, p, data,
-              map_to_name(map, data, ""));
-         p += 4;
-    }
-    /* print another 64-byte of stack data after the last frame */
-
-    end = p+64;
-    /* 'end - p' has to be multiples of 4 */
-    if (end < p)
-        end = ~7;
-
-    while (p <= end) {
-         long data = ptrace(PTRACE_PEEKTEXT, pid, (void*)p, NULL);
-         _LOG(tfd, (sp_depth > 2) || only_in_tombstone,
-              "    %08x  %08x  %s\n", p, data,
-              map_to_name(map, data, ""));
-         p += 4;
+    if (regs.ARM_pc != regs.ARM_lr) {
+        _LOG(tfd, !at_fault, "\ncode around lr:\n");
+        dump_memory(tfd, tid, (uintptr_t)regs.ARM_lr, at_fault);
     }
 }
 
-void dump_pc_and_lr(int tfd, int pid, mapinfo *map, int unwound_level,
-                    bool at_fault)
-{
-    struct pt_regs r;
-
-    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) {
-        _LOG(tfd, !at_fault, "tid %d not responding!\n", pid);
-        return;
-    }
-
-    if (unwound_level == 0) {
-        _LOG(tfd, !at_fault, "         #%02d  pc %08x  %s\n", 0, r.ARM_pc,
-             map_to_name(map, r.ARM_pc, "<unknown>"));
-    }
-    _LOG(tfd, !at_fault, "         #%02d  lr %08x  %s\n", 1, r.ARM_lr,
-            map_to_name(map, r.ARM_lr, "<unknown>"));
-}
-
-void dump_registers(int tfd, int pid, bool at_fault)
+void dump_registers(const ptrace_context_t* context __attribute((unused)),
+        int tfd, pid_t tid, bool at_fault)
 {
     struct pt_regs r;
     bool only_in_tombstone = !at_fault;
 
-    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) {
-        _LOG(tfd, only_in_tombstone,
-             "cannot get registers: %s\n", strerror(errno));
+    if(ptrace(PTRACE_GETREGS, tid, 0, &r)) {
+        _LOG(tfd, only_in_tombstone, "cannot get registers: %s\n", strerror(errno));
         return;
     }
 
-    _LOG(tfd, only_in_tombstone, " r0 %08x  r1 %08x  r2 %08x  r3 %08x\n",
-         r.ARM_r0, r.ARM_r1, r.ARM_r2, r.ARM_r3);
-    _LOG(tfd, only_in_tombstone, " r4 %08x  r5 %08x  r6 %08x  r7 %08x\n",
-         r.ARM_r4, r.ARM_r5, r.ARM_r6, r.ARM_r7);
-    _LOG(tfd, only_in_tombstone, " r8 %08x  r9 %08x  10 %08x  fp %08x\n",
-         r.ARM_r8, r.ARM_r9, r.ARM_r10, r.ARM_fp);
-    _LOG(tfd, only_in_tombstone,
-         " ip %08x  sp %08x  lr %08x  pc %08x  cpsr %08x\n",
-         r.ARM_ip, r.ARM_sp, r.ARM_lr, r.ARM_pc, r.ARM_cpsr);
+    _LOG(tfd, only_in_tombstone, "    r0 %08x  r1 %08x  r2 %08x  r3 %08x\n",
+            (uint32_t)r.ARM_r0, (uint32_t)r.ARM_r1, (uint32_t)r.ARM_r2, (uint32_t)r.ARM_r3);
+    _LOG(tfd, only_in_tombstone, "    r4 %08x  r5 %08x  r6 %08x  r7 %08x\n",
+            (uint32_t)r.ARM_r4, (uint32_t)r.ARM_r5, (uint32_t)r.ARM_r6, (uint32_t)r.ARM_r7);
+    _LOG(tfd, only_in_tombstone, "    r8 %08x  r9 %08x  sl %08x  fp %08x\n",
+            (uint32_t)r.ARM_r8, (uint32_t)r.ARM_r9, (uint32_t)r.ARM_r10, (uint32_t)r.ARM_fp);
+    _LOG(tfd, only_in_tombstone, "    ip %08x  sp %08x  lr %08x  pc %08x  cpsr %08x\n",
+            (uint32_t)r.ARM_ip, (uint32_t)r.ARM_sp, (uint32_t)r.ARM_lr,
+            (uint32_t)r.ARM_pc, (uint32_t)r.ARM_cpsr);
 
 #ifdef WITH_VFP
     struct user_vfp vfp_regs;
     int i;
 
-    if(ptrace(PTRACE_GETVFPREGS, pid, 0, &vfp_regs)) {
-        _LOG(tfd, only_in_tombstone,
-             "cannot get registers: %s\n", strerror(errno));
+    if(ptrace(PTRACE_GETVFPREGS, tid, 0, &vfp_regs)) {
+        _LOG(tfd, only_in_tombstone, "cannot get registers: %s\n", strerror(errno));
         return;
     }
 
     for (i = 0; i < NUM_VFP_REGS; i += 2) {
-        _LOG(tfd, only_in_tombstone,
-             " d%-2d %016llx  d%-2d %016llx\n",
-              i, vfp_regs.fpregs[i], i+1, vfp_regs.fpregs[i+1]);
+        _LOG(tfd, only_in_tombstone, "    d%-2d %016llx  d%-2d %016llx\n",
+                i, vfp_regs.fpregs[i], i+1, vfp_regs.fpregs[i+1]);
     }
-    _LOG(tfd, only_in_tombstone, " scr %08lx\n\n", vfp_regs.fpscr);
+    _LOG(tfd, only_in_tombstone, "    scr %08lx\n", vfp_regs.fpscr);
 #endif
 }
+
+void dump_thread(const ptrace_context_t* context, int tfd, pid_t tid, bool at_fault) {
+    dump_registers(context, tfd, tid, at_fault);
+
+    dump_backtrace_and_stack(context, tfd, tid, at_fault);
+
+    if (at_fault) {
+        dump_memory_and_code(tfd, tid, at_fault);
+        dump_nearby_maps(context, tfd, tid);
+    }
+}
diff --git a/debuggerd/arm/pr-support.c b/debuggerd/arm/pr-support.c
deleted file mode 100644
index 358d9b7..0000000
--- a/debuggerd/arm/pr-support.c
+++ /dev/null
@@ -1,345 +0,0 @@
-/* ARM EABI compliant unwinding routines
-   Copyright (C) 2004, 2005 Free Software Foundation, Inc.
-   Contributed by Paul Brook
- 
-   This file is free software; you can redistribute it and/or modify it
-   under the terms of the GNU General Public License as published by the
-   Free Software Foundation; either version 2, or (at your option) any
-   later version.
-
-   In addition to the permissions in the GNU General Public License, the
-   Free Software Foundation gives you unlimited permission to link the
-   compiled version of this file into combinations with other programs,
-   and to distribute those combinations without any restriction coming
-   from the use of this file.  (The General Public License restrictions
-   do apply in other respects; for example, they cover modification of
-   the file, and distribution when not linked into a combine
-   executable.)
-
-   This file is distributed in the hope that it will be useful, but
-   WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   General Public License for more details.
-
-   You should have received a copy of the GNU General Public License
-   along with this program; see the file COPYING.  If not, write to
-   the Free Software Foundation, 51 Franklin Street, Fifth Floor,
-   Boston, MA 02110-1301, USA.  */
-
-/****************************************************************************
- * The functions here are derived from gcc/config/arm/pr-support.c from the 
- * 4.3.x release. The main changes here involve the use of ptrace to retrieve
- * memory/processor states from a remote process.
- ****************************************************************************/
-
-#include <sys/types.h>
-#include <unwind.h>
-
-#include "utility.h"
-
-/* We add a prototype for abort here to avoid creating a dependency on
-   target headers.  */
-extern void abort (void);
-
-/* Derived from _Unwind_VRS_Pop to use ptrace */
-extern _Unwind_VRS_Result 
-unwind_VRS_Pop_with_ptrace (_Unwind_Context *context, 
-                            _Unwind_VRS_RegClass regclass, 
-                            _uw discriminator, 
-                            _Unwind_VRS_DataRepresentation representation, 
-                            pid_t pid);
-
-typedef struct _ZSt9type_info type_info; /* This names C++ type_info type */
-
-/* Misc constants.  */
-#define R_IP    12
-#define R_SP    13
-#define R_LR    14
-#define R_PC    15
-
-#define uint32_highbit (((_uw) 1) << 31)
-
-void __attribute__((weak)) __cxa_call_unexpected(_Unwind_Control_Block *ucbp);
-
-/* Unwind descriptors.  */
-
-typedef struct
-{
-  _uw16 length;
-  _uw16 offset;
-} EHT16;
-
-typedef struct
-{
-  _uw length;
-  _uw offset;
-} EHT32;
-
-/* Personality routine helper functions.  */
-
-#define CODE_FINISH (0xb0)
-
-/* Derived from next_unwind_byte to use ptrace */
-/* Return the next byte of unwinding information, or CODE_FINISH if there is
-   no data remaining.  */
-static inline _uw8
-next_unwind_byte_with_ptrace (__gnu_unwind_state * uws, pid_t pid)
-{
-  _uw8 b;
-
-  if (uws->bytes_left == 0)
-    {
-      /* Load another word */
-      if (uws->words_left == 0)
-	return CODE_FINISH; /* Nothing left.  */
-      uws->words_left--;
-      uws->data = get_remote_word(pid, uws->next);
-      uws->next++;
-      uws->bytes_left = 3;
-    }
-  else
-    uws->bytes_left--;
-
-  /* Extract the most significant byte.  */
-  b = (uws->data >> 24) & 0xff;
-  uws->data <<= 8;
-  return b;
-}
-
-/* Execute the unwinding instructions described by UWS.  */
-_Unwind_Reason_Code
-unwind_execute_with_ptrace(_Unwind_Context * context, __gnu_unwind_state * uws,
-                           pid_t pid)
-{
-  _uw op;
-  int set_pc;
-  _uw reg;
-
-  set_pc = 0;
-  for (;;)
-    {
-      op = next_unwind_byte_with_ptrace (uws, pid);
-      if (op == CODE_FINISH)
-	{
-	  /* If we haven't already set pc then copy it from lr.  */
-	  if (!set_pc)
-	    {
-	      _Unwind_VRS_Get (context, _UVRSC_CORE, R_LR, _UVRSD_UINT32,
-			       &reg);
-	      _Unwind_VRS_Set (context, _UVRSC_CORE, R_PC, _UVRSD_UINT32,
-			       &reg);
-	      set_pc = 1;
-	    }
-	  /* Drop out of the loop.  */
-	  break;
-	}
-      if ((op & 0x80) == 0)
-	{
-	  /* vsp = vsp +- (imm6 << 2 + 4).  */
-	  _uw offset;
-
-	  offset = ((op & 0x3f) << 2) + 4;
-	  _Unwind_VRS_Get (context, _UVRSC_CORE, R_SP, _UVRSD_UINT32, &reg);
-	  if (op & 0x40)
-	    reg -= offset;
-	  else
-	    reg += offset;
-	  _Unwind_VRS_Set (context, _UVRSC_CORE, R_SP, _UVRSD_UINT32, &reg);
-	  continue;
-	}
-      
-      if ((op & 0xf0) == 0x80)
-	{
-	  op = (op << 8) | next_unwind_byte_with_ptrace (uws, pid);
-	  if (op == 0x8000)
-	    {
-	      /* Refuse to unwind.  */
-	      return _URC_FAILURE;
-	    }
-	  /* Pop r4-r15 under mask.  */
-	  op = (op << 4) & 0xfff0;
-	  if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_CORE, op, _UVRSD_UINT32, 
-                                      pid)
-	      != _UVRSR_OK)
-	    return _URC_FAILURE;
-	  if (op & (1 << R_PC))
-	    set_pc = 1;
-	  continue;
-	}
-      if ((op & 0xf0) == 0x90)
-	{
-	  op &= 0xf;
-	  if (op == 13 || op == 15)
-	    /* Reserved.  */
-	    return _URC_FAILURE;
-	  /* vsp = r[nnnn].  */
-	  _Unwind_VRS_Get (context, _UVRSC_CORE, op, _UVRSD_UINT32, &reg);
-	  _Unwind_VRS_Set (context, _UVRSC_CORE, R_SP, _UVRSD_UINT32, &reg);
-	  continue;
-	}
-      if ((op & 0xf0) == 0xa0)
-	{
-	  /* Pop r4-r[4+nnn], [lr].  */
-	  _uw mask;
-	  
-	  mask = (0xff0 >> (7 - (op & 7))) & 0xff0;
-	  if (op & 8)
-	    mask |= (1 << R_LR);
-	  if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_CORE, mask, _UVRSD_UINT32,
-                                      pid)
-	      != _UVRSR_OK)
-	    return _URC_FAILURE;
-	  continue;
-	}
-      if ((op & 0xf0) == 0xb0)
-	{
-	  /* op == 0xb0 already handled.  */
-	  if (op == 0xb1)
-	    {
-	      op = next_unwind_byte_with_ptrace (uws, pid);
-	      if (op == 0 || ((op & 0xf0) != 0))
-		/* Spare.  */
-		return _URC_FAILURE;
-	      /* Pop r0-r4 under mask.  */
-	      if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_CORE, op, 
-                                          _UVRSD_UINT32, pid)
-		  != _UVRSR_OK)
-		return _URC_FAILURE;
-	      continue;
-	    }
-	  if (op == 0xb2)
-	    {
-	      /* vsp = vsp + 0x204 + (uleb128 << 2).  */
-	      int shift;
-
-	      _Unwind_VRS_Get (context, _UVRSC_CORE, R_SP, _UVRSD_UINT32,
-			       &reg);
-	      op = next_unwind_byte_with_ptrace (uws, pid);
-	      shift = 2;
-	      while (op & 0x80)
-		{
-		  reg += ((op & 0x7f) << shift);
-		  shift += 7;
-		  op = next_unwind_byte_with_ptrace (uws, pid);
-		}
-	      reg += ((op & 0x7f) << shift) + 0x204;
-	      _Unwind_VRS_Set (context, _UVRSC_CORE, R_SP, _UVRSD_UINT32,
-			       &reg);
-	      continue;
-	    }
-	  if (op == 0xb3)
-	    {
-	      /* Pop VFP registers with fldmx.  */
-	      op = next_unwind_byte_with_ptrace (uws, pid);
-	      op = ((op & 0xf0) << 12) | ((op & 0xf) + 1);
-	      if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_VFP, op, _UVRSD_VFPX, 
-                                          pid)
-		  != _UVRSR_OK)
-		return _URC_FAILURE;
-	      continue;
-	    }
-	  if ((op & 0xfc) == 0xb4)
-	    {
-	      /* Pop FPA E[4]-E[4+nn].  */
-	      op = 0x40000 | ((op & 3) + 1);
-	      if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_FPA, op, _UVRSD_FPAX, 
-                                          pid)
-		  != _UVRSR_OK)
-		return _URC_FAILURE;
-	      continue;
-	    }
-	  /* op & 0xf8 == 0xb8.  */
-	  /* Pop VFP D[8]-D[8+nnn] with fldmx.  */
-	  op = 0x80000 | ((op & 7) + 1);
-	  if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_VFP, op, _UVRSD_VFPX, pid)
-	      != _UVRSR_OK)
-	    return _URC_FAILURE;
-	  continue;
-	}
-      if ((op & 0xf0) == 0xc0)
-	{
-	  if (op == 0xc6)
-	    {
-	      /* Pop iWMMXt D registers.  */
-	      op = next_unwind_byte_with_ptrace (uws, pid);
-	      op = ((op & 0xf0) << 12) | ((op & 0xf) + 1);
-	      if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_WMMXD, op, 
-                                          _UVRSD_UINT64, pid)
-		  != _UVRSR_OK)
-		return _URC_FAILURE;
-	      continue;
-	    }
-	  if (op == 0xc7)
-	    {
-	      op = next_unwind_byte_with_ptrace (uws, pid);
-	      if (op == 0 || (op & 0xf0) != 0)
-		/* Spare.  */
-		return _URC_FAILURE;
-	      /* Pop iWMMXt wCGR{3,2,1,0} under mask.  */
-	      if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_WMMXC, op, 
-                                          _UVRSD_UINT32, pid)
-		  != _UVRSR_OK)
-		return _URC_FAILURE;
-	      continue;
-	    }
-	  if ((op & 0xf8) == 0xc0)
-	    {
-	      /* Pop iWMMXt wR[10]-wR[10+nnn].  */
-	      op = 0xa0000 | ((op & 0xf) + 1);
-	      if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_WMMXD, op, 
-                                          _UVRSD_UINT64, pid)
-		  != _UVRSR_OK)
-		return _URC_FAILURE;
-	      continue;
-	    }
-	  if (op == 0xc8)
-	    {
-#ifndef __VFP_FP__
- 	      /* Pop FPA registers.  */
- 	      op = next_unwind_byte_with_ptrace (uws, pid);
-	      op = ((op & 0xf0) << 12) | ((op & 0xf) + 1);
- 	      if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_FPA, op, _UVRSD_FPAX,
-                                          pid)
- 		  != _UVRSR_OK)
- 		return _URC_FAILURE;
- 	      continue;
-#else
-              /* Pop VFPv3 registers D[16+ssss]-D[16+ssss+cccc] with vldm.  */
-              op = next_unwind_byte_with_ptrace (uws, pid);
-              op = (((op & 0xf0) + 16) << 12) | ((op & 0xf) + 1);
-              if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_VFP, op, 
-                                              _UVRSD_DOUBLE, pid)
-                  != _UVRSR_OK)
-                return _URC_FAILURE;
-              continue;
-#endif
-	    }
-	  if (op == 0xc9)
-	    {
-	      /* Pop VFP registers with fldmd.  */
-	      op = next_unwind_byte_with_ptrace (uws, pid);
-	      op = ((op & 0xf0) << 12) | ((op & 0xf) + 1);
-	      if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_VFP, op, 
-                                          _UVRSD_DOUBLE, pid)
-		  != _UVRSR_OK)
-		return _URC_FAILURE;
-	      continue;
-	    }
-	  /* Spare.  */
-	  return _URC_FAILURE;
-	}
-      if ((op & 0xf8) == 0xd0)
-	{
-	  /* Pop VFP D[8]-D[8+nnn] with fldmd.  */
-	  op = 0x80000 | ((op & 7) + 1);
-	  if (unwind_VRS_Pop_with_ptrace (context, _UVRSC_VFP, op, _UVRSD_DOUBLE, 
-                                      pid)
-	      != _UVRSR_OK)
-	    return _URC_FAILURE;
-	  continue;
-	}
-      /* Spare.  */
-      return _URC_FAILURE;
-    }
-  return _URC_OK;
-}
diff --git a/debuggerd/arm/unwind.c b/debuggerd/arm/unwind.c
deleted file mode 100644
index d9600b7..0000000
--- a/debuggerd/arm/unwind.c
+++ /dev/null
@@ -1,667 +0,0 @@
-/* ARM EABI compliant unwinding routines.
-   Copyright (C) 2004, 2005 Free Software Foundation, Inc.
-   Contributed by Paul Brook
-
-   This file is free software; you can redistribute it and/or modify it
-   under the terms of the GNU General Public License as published by the
-   Free Software Foundation; either version 2, or (at your option) any
-   later version.
-
-   In addition to the permissions in the GNU General Public License, the
-   Free Software Foundation gives you unlimited permission to link the
-   compiled version of this file into combinations with other programs,
-   and to distribute those combinations without any restriction coming
-   from the use of this file.  (The General Public License restrictions
-   do apply in other respects; for example, they cover modification of
-   the file, and distribution when not linked into a combine
-   executable.)
-
-   This file is distributed in the hope that it will be useful, but
-   WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   General Public License for more details.
-
-   You should have received a copy of the GNU General Public License
-   along with this program; see the file COPYING.  If not, write to
-   the Free Software Foundation, 51 Franklin Street, Fifth Floor,
-   Boston, MA 02110-1301, USA.  */
-
-/****************************************************************************
- * The functions here are derived from gcc/config/arm/unwind-arm.c from the 
- * 4.3.x release. The main changes here involve the use of ptrace to retrieve
- * memory/processor states from a remote process.
- ****************************************************************************/
-
-#include <cutils/logd.h>
-#include <sys/ptrace.h>
-#include <unwind.h>
-#include "utility.h"
-
-#include "symbol_table.h"
-
-typedef struct _ZSt9type_info type_info; /* This names C++ type_info type */
-
-void __attribute__((weak)) __cxa_call_unexpected(_Unwind_Control_Block *ucbp);
-bool __attribute__((weak)) __cxa_begin_cleanup(_Unwind_Control_Block *ucbp);
-bool __attribute__((weak)) __cxa_type_match(_Unwind_Control_Block *ucbp,
-                        const type_info *rttip,
-                        bool is_reference,
-                        void **matched_object);
-
-/* Misc constants.  */
-#define R_IP	12
-#define R_SP	13
-#define R_LR	14
-#define R_PC	15
-
-#define EXIDX_CANTUNWIND 1
-#define uint32_highbit (((_uw) 1) << 31)
-
-#define UCB_FORCED_STOP_FN(ucbp) ((ucbp)->unwinder_cache.reserved1)
-#define UCB_PR_ADDR(ucbp) ((ucbp)->unwinder_cache.reserved2)
-#define UCB_SAVED_CALLSITE_ADDR(ucbp) ((ucbp)->unwinder_cache.reserved3)
-#define UCB_FORCED_STOP_ARG(ucbp) ((ucbp)->unwinder_cache.reserved4)
-
-struct core_regs
-{
-  _uw r[16];
-};
-
-/* We use normal integer types here to avoid the compiler generating
-   coprocessor instructions.  */
-struct vfp_regs
-{
-  _uw64 d[16];
-  _uw pad;
-};
-
-struct vfpv3_regs
-{
-  /* Always populated via VSTM, so no need for the "pad" field from
-     vfp_regs (which is used to store the format word for FSTMX).  */
-  _uw64 d[16];
-};
-
-struct fpa_reg
-{
-  _uw w[3];
-};
-
-struct fpa_regs
-{
-  struct fpa_reg f[8];
-};
-
-struct wmmxd_regs
-{
-  _uw64 wd[16];
-};
-
-struct wmmxc_regs
-{
-  _uw wc[4];
-};
-
-/* Unwind descriptors.  */
-
-typedef struct
-{
-  _uw16 length;
-  _uw16 offset;
-} EHT16;
-
-typedef struct
-{
-  _uw length;
-  _uw offset;
-} EHT32;
-
-/* The ABI specifies that the unwind routines may only use core registers,
-   except when actually manipulating coprocessor state.  This allows
-   us to write one implementation that works on all platforms by
-   demand-saving coprocessor registers.
-
-   During unwinding we hold the coprocessor state in the actual hardware
-   registers and allocate demand-save areas for use during phase1
-   unwinding.  */
-
-typedef struct
-{
-  /* The first fields must be the same as a phase2_vrs.  */
-  _uw demand_save_flags;
-  struct core_regs core;
-  _uw prev_sp; /* Only valid during forced unwinding.  */
-  struct vfp_regs vfp;
-  struct vfpv3_regs vfp_regs_16_to_31;
-  struct fpa_regs fpa;
-  struct wmmxd_regs wmmxd;
-  struct wmmxc_regs wmmxc;
-} phase1_vrs;
-
-/* This must match the structure created by the assembly wrappers.  */
-typedef struct
-{
-  _uw demand_save_flags;
-  struct core_regs core;
-} phase2_vrs;
-
-
-/* An exception index table entry.  */
-
-typedef struct __EIT_entry
-{
-  _uw fnoffset;
-  _uw content;
-} __EIT_entry;
-
-/* Derived version to use ptrace */
-typedef _Unwind_Reason_Code (*personality_routine_with_ptrace)
-           (_Unwind_State,
-			_Unwind_Control_Block *,
-			_Unwind_Context *,
-            pid_t);
-
-/* Derived version to use ptrace */
-/* ABI defined personality routines.  */
-static _Unwind_Reason_Code unwind_cpp_pr0_with_ptrace (_Unwind_State,
-    _Unwind_Control_Block *, _Unwind_Context *, pid_t);
-static _Unwind_Reason_Code unwind_cpp_pr1_with_ptrace (_Unwind_State,
-    _Unwind_Control_Block *, _Unwind_Context *, pid_t);
-static _Unwind_Reason_Code unwind_cpp_pr2_with_ptrace (_Unwind_State,
-    _Unwind_Control_Block *, _Unwind_Context *, pid_t);
-
-/* Execute the unwinding instructions described by UWS.  */
-extern _Unwind_Reason_Code
-unwind_execute_with_ptrace(_Unwind_Context * context, __gnu_unwind_state * uws,
-                           pid_t pid);
-
-/* Derived version to use ptrace. Only handles core registers. Disregards
- * FP and others. 
- */
-/* ABI defined function to pop registers off the stack.  */
-
-_Unwind_VRS_Result unwind_VRS_Pop_with_ptrace (_Unwind_Context *context,
-				    _Unwind_VRS_RegClass regclass,
-				    _uw discriminator,
-				    _Unwind_VRS_DataRepresentation representation,
-                    pid_t pid)
-{
-  phase1_vrs *vrs = (phase1_vrs *) context;
-
-  switch (regclass)
-    {
-    case _UVRSC_CORE:
-      {
-	_uw *ptr;
-	_uw mask;
-	int i;
-
-	if (representation != _UVRSD_UINT32)
-	  return _UVRSR_FAILED;
-
-	mask = discriminator & 0xffff;
-	ptr = (_uw *) vrs->core.r[R_SP];
-	/* Pop the requested registers.  */
-	for (i = 0; i < 16; i++)
-	  {
-	    if (mask & (1 << i)) {
-	      vrs->core.r[i] = get_remote_word(pid, ptr);
-          ptr++;
-        }
-	  }
-	/* Writeback the stack pointer value if it wasn't restored.  */
-	if ((mask & (1 << R_SP)) == 0)
-	  vrs->core.r[R_SP] = (_uw) ptr;
-      }
-      return _UVRSR_OK;
-
-    default:
-      return _UVRSR_FAILED;
-    }
-}
-
-/* Core unwinding functions.  */
-
-/* Calculate the address encoded by a 31-bit self-relative offset at address
-   P.  */
-static inline _uw
-selfrel_offset31 (const _uw *p, pid_t pid)
-{
-  _uw offset = get_remote_word(pid, (void*)p);
-
-  //offset = *p;
-  /* Sign extend to 32 bits.  */
-  if (offset & (1 << 30))
-    offset |= 1u << 31;
-  else
-    offset &= ~(1u << 31);
-
-  return offset + (_uw) p;
-}
-
-
-/* Perform a binary search for RETURN_ADDRESS in TABLE.  The table contains
-   NREC entries.  */
-
-static const __EIT_entry *
-search_EIT_table (const __EIT_entry * table, int nrec, _uw return_address,
-                  pid_t pid)
-{
-  _uw next_fn;
-  _uw this_fn;
-  int n, left, right;
-
-  if (nrec == 0)
-    return (__EIT_entry *) 0;
-
-  left = 0;
-  right = nrec - 1;
-
-  while (1)
-    {
-      n = (left + right) / 2;
-      this_fn = selfrel_offset31 (&table[n].fnoffset, pid);
-      if (n != nrec - 1)
-	next_fn = selfrel_offset31 (&table[n + 1].fnoffset, pid) - 1;
-      else
-	next_fn = (_uw)0 - 1;
-
-      if (return_address < this_fn)
-	{
-	  if (n == left)
-	    return (__EIT_entry *) 0;
-	  right = n - 1;
-	}
-      else if (return_address <= next_fn)
-	return &table[n];
-      else
-	left = n + 1;
-    }
-}
-
-/* Find the exception index table eintry for the given address. */
-static const __EIT_entry*
-get_eitp(_uw return_address, pid_t pid, mapinfo *map, mapinfo **containing_map)
-{
-  const __EIT_entry *eitp = NULL;
-  int nrec;
-  mapinfo *mi;
-  
-  /* The return address is the address of the instruction following the
-     call instruction (plus one in thumb mode).  If this was the last
-     instruction in the function the address will lie in the following
-     function.  Subtract 2 from the address so that it points within the call
-     instruction itself.  */
-  if (return_address >= 2)
-      return_address -= 2;
-
-  for (mi = map; mi != NULL; mi = mi->next) {
-    if (return_address >= mi->start && return_address <= mi->end) break;
-  }
-
-  if (mi) {
-    if (containing_map) *containing_map = mi;
-    eitp = (__EIT_entry *) mi->exidx_start;
-    nrec = (mi->exidx_end - mi->exidx_start)/sizeof(__EIT_entry);
-    eitp = search_EIT_table (eitp, nrec, return_address, pid);
-  }
-  return eitp;
-}
-
-/* Find the exception index table eintry for the given address.
-   Fill in the relevant fields of the UCB.
-   Returns _URC_FAILURE if an error occurred, _URC_OK on success.  */
-
-static _Unwind_Reason_Code
-get_eit_entry (_Unwind_Control_Block *ucbp, _uw return_address, pid_t pid, 
-               mapinfo *map, mapinfo **containing_map)
-{
-  const __EIT_entry *eitp;
-  
-  eitp = get_eitp(return_address, pid, map, containing_map);
-
-  if (!eitp)
-    {
-      UCB_PR_ADDR (ucbp) = 0;
-      return _URC_FAILURE;
-    }
-  ucbp->pr_cache.fnstart = selfrel_offset31 (&eitp->fnoffset, pid);
-
-  _uw eitp_content = get_remote_word(pid, (void *)&eitp->content);
-
-  /* Can this frame be unwound at all?  */
-  if (eitp_content == EXIDX_CANTUNWIND)
-    {
-      UCB_PR_ADDR (ucbp) = 0;
-      return _URC_END_OF_STACK;
-    }
-
-  /* Obtain the address of the "real" __EHT_Header word.  */
-
-  if (eitp_content & uint32_highbit)
-    {
-      /* It is immediate data.  */
-      ucbp->pr_cache.ehtp = (_Unwind_EHT_Header *)&eitp->content;
-      ucbp->pr_cache.additional = 1;
-    }
-  else
-    {
-      /* The low 31 bits of the content field are a self-relative
-	 offset to an _Unwind_EHT_Entry structure.  */
-      ucbp->pr_cache.ehtp =
-	(_Unwind_EHT_Header *) selfrel_offset31 (&eitp->content, pid);
-      ucbp->pr_cache.additional = 0;
-    }
-
-  /* Discover the personality routine address.  */
-  if (get_remote_word(pid, ucbp->pr_cache.ehtp) & (1u << 31))
-    {
-      /* One of the predefined standard routines.  */
-      _uw idx = (get_remote_word(pid, ucbp->pr_cache.ehtp) >> 24) & 0xf;
-      if (idx == 0)
-	UCB_PR_ADDR (ucbp) = (_uw) &unwind_cpp_pr0_with_ptrace;
-      else if (idx == 1)
-	UCB_PR_ADDR (ucbp) = (_uw) &unwind_cpp_pr1_with_ptrace;
-      else if (idx == 2)
-	UCB_PR_ADDR (ucbp) = (_uw) &unwind_cpp_pr2_with_ptrace;
-      else
-	{ /* Failed */
-	  UCB_PR_ADDR (ucbp) = 0;
-	  return _URC_FAILURE;
-	}
-    } 
-  else
-    {
-      /* Execute region offset to PR */
-      UCB_PR_ADDR (ucbp) = selfrel_offset31 (ucbp->pr_cache.ehtp, pid);
-      /* Since we are unwinding the stack from a different process, it is
-       * impossible to execute the personality routine in debuggerd. Punt here.
-       */
-	  return _URC_FAILURE;
-    }
-  return _URC_OK;
-}
-
-/* Print out the current call level, pc, and module name in the crash log */
-static _Unwind_Reason_Code log_function(_Unwind_Context *context, pid_t pid, 
-                                        int tfd,
-                                        int stack_level,
-                                        mapinfo *map,
-                                        unsigned int sp_list[],
-                                        bool at_fault)
-{
-    _uw pc;
-    _uw rel_pc; 
-    phase2_vrs *vrs = (phase2_vrs*) context;
-    const mapinfo *mi;
-    bool only_in_tombstone = !at_fault;
-    const struct symbol* sym = 0;
-
-    if (stack_level < STACK_CONTENT_DEPTH) {
-        sp_list[stack_level] = vrs->core.r[R_SP];
-    }
-    pc = vrs->core.r[R_PC];
-
-    // Top level frame
-    if (stack_level == 0) {
-        pc &= ~1;
-    }
-    // For deeper framers, rollback pc by one instruction
-    else {
-        pc = vrs->core.r[R_PC];
-        /* Thumb mode - need to check whether the bl(x) has long offset or not.
-         * Examples:
-         *
-         * arm blx in the middle of thumb:
-         * 187ae:       2300            movs    r3, #0
-         * 187b0:       f7fe ee1c       blx     173ec
-         * 187b4:       2c00            cmp     r4, #0
-         *
-         * arm bl in the middle of thumb:
-         * 187d8:       1c20            adds    r0, r4, #0
-         * 187da:       f136 fd15       bl      14f208
-         * 187de:       2800            cmp     r0, #0
-         *
-         * pure thumb:
-         * 18894:       189b            adds    r3, r3, r2
-         * 18896:       4798            blx     r3
-         * 18898:       b001            add     sp, #4
-         */
-        if (pc & 1) {
-            _uw prev_word;
-            pc = (pc & ~1);
-            prev_word = get_remote_word(pid, (char *) pc-4);
-            // Long offset 
-            if ((prev_word & 0xf0000000) == 0xf0000000 && 
-                (prev_word & 0x0000e000) == 0x0000e000) {
-                pc -= 4;
-            }
-            else {
-                pc -= 2;
-            }
-        }
-        else { 
-            pc -= 4;
-        }
-    }
-
-    /* We used to print the absolute PC in the back trace, and mask out the top
-     * 3 bits to guesstimate the offset in the .so file. This is not working for
-     * non-prelinked libraries since the starting offset may not be aligned on 
-     * 1MB boundaries, and the library may be larger than 1MB. So for .so 
-     * addresses we print the relative offset in back trace.
-     */
-    mi = pc_to_mapinfo(map, pc, &rel_pc);
-
-    /* See if we can determine what symbol this stack frame resides in */
-    if (mi != 0 && mi->symbols != 0) {
-        sym = symbol_table_lookup(mi->symbols, rel_pc);
-    }
-
-    if (sym) {
-        _LOG(tfd, only_in_tombstone,
-            "         #%02d  pc %08x  %s (%s)\n", stack_level, rel_pc,
-            mi ? mi->name : "", sym->name);
-    } else {
-        _LOG(tfd, only_in_tombstone,
-            "         #%02d  pc %08x  %s\n", stack_level, rel_pc,
-            mi ? mi->name : "");
-    }
-
-    return _URC_NO_REASON;
-}
-
-/* Derived from __gnu_Unwind_Backtrace to use ptrace */
-/* Perform stack backtrace through unwind data. Return the level of stack it
- * unwinds.
- */
-int unwind_backtrace_with_ptrace(int tfd, pid_t pid, mapinfo *map, 
-                                 unsigned int sp_list[], int *frame0_pc_sane,
-                                 bool at_fault)
-{
-    phase1_vrs saved_vrs;
-    _Unwind_Reason_Code code = _URC_OK;
-    struct pt_regs r;
-    int i;
-    int stack_level = 0;
-
-    _Unwind_Control_Block ucb;
-    _Unwind_Control_Block *ucbp = &ucb;
-
-    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) return 0;
-
-    for (i = 0; i < 16; i++) {
-        saved_vrs.core.r[i] = r.uregs[i];
-        /*
-        _LOG(tfd, "r[%d] = 0x%x\n", i, saved_vrs.core.r[i]);
-        */
-    }
-
-    /* Set demand-save flags.  */
-    saved_vrs.demand_save_flags = ~(_uw) 0;
-
-    /* 
-     * If the app crashes because of calling the weeds, we cannot pass the PC 
-     * to the usual unwinding code as the EXIDX mapping will fail. 
-     * Instead, we simply print out the 0 as the top frame, and resume the 
-     * unwinding process with the value stored in LR.
-     */
-    if (get_eitp(saved_vrs.core.r[R_PC], pid, map, NULL) == NULL) { 
-        *frame0_pc_sane = 0;
-        log_function ((_Unwind_Context *) &saved_vrs, pid, tfd, stack_level, 
-                      map, sp_list, at_fault);
-        saved_vrs.core.r[R_PC] = saved_vrs.core.r[R_LR];
-        stack_level++;
-    }
-
-    do {
-        mapinfo *this_map = NULL;
-        /* Find the entry for this routine.  */
-        if (get_eit_entry(ucbp, saved_vrs.core.r[R_PC], pid, map, &this_map)
-            != _URC_OK) {
-            /* Uncomment the code below to study why the unwinder failed */
-#if 0
-            /* Shed more debugging info for stack unwinder improvement */
-            if (this_map) {
-                _LOG(tfd, 1, 
-                     "Relative PC=%#x from %s not contained in EXIDX\n", 
-                     saved_vrs.core.r[R_PC] - this_map->start, this_map->name);
-            }
-            _LOG(tfd, 1, "PC=%#x SP=%#x\n", 
-                 saved_vrs.core.r[R_PC], saved_vrs.core.r[R_SP]);
-#endif
-            code = _URC_FAILURE;
-            break;
-        }
-
-        /* The dwarf unwinder assumes the context structure holds things
-        like the function and LSDA pointers.  The ARM implementation
-        caches these in the exception header (UCB).  To avoid
-        rewriting everything we make the virtual IP register point at
-        the UCB.  */
-        _Unwind_SetGR((_Unwind_Context *)&saved_vrs, 12, (_Unwind_Ptr) ucbp);
-
-        /* Call log function.  */
-        if (log_function ((_Unwind_Context *) &saved_vrs, pid, tfd, stack_level,
-                          map, sp_list, at_fault) != _URC_NO_REASON) {
-            code = _URC_FAILURE;
-            break;
-        }
-        stack_level++;
-
-        /* Call the pr to decide what to do.  */
-        code = ((personality_routine_with_ptrace) UCB_PR_ADDR (ucbp))(
-                _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND, ucbp, 
-                (void *) &saved_vrs, pid);
-    /* 
-     * In theory the unwinding process will stop when the end of stack is
-     * reached or there is no unwinding information for the code address.
-     * To add another level of guarantee that the unwinding process
-     * will terminate we will stop it when the STACK_CONTENT_DEPTH is reached.
-     */
-    } while (code != _URC_END_OF_STACK && code != _URC_FAILURE && 
-             stack_level < STACK_CONTENT_DEPTH);
-    return stack_level;
-}
-
-
-/* Derived version to use ptrace */
-/* Common implementation for ARM ABI defined personality routines.
-   ID is the index of the personality routine, other arguments are as defined
-   by __aeabi_unwind_cpp_pr{0,1,2}.  */
-
-static _Unwind_Reason_Code
-unwind_pr_common_with_ptrace (_Unwind_State state,
-			_Unwind_Control_Block *ucbp,
-			_Unwind_Context *context,
-			int id,
-            pid_t pid)
-{
-  __gnu_unwind_state uws;
-  _uw *data;
-  int phase2_call_unexpected_after_unwind = 0;
-
-  state &= _US_ACTION_MASK;
-
-  data = (_uw *) ucbp->pr_cache.ehtp;
-  uws.data = get_remote_word(pid, data);
-  data++;
-  uws.next = data;
-  if (id == 0)
-    {
-      uws.data <<= 8;
-      uws.words_left = 0;
-      uws.bytes_left = 3;
-    }
-  else
-    {
-      uws.words_left = (uws.data >> 16) & 0xff;
-      uws.data <<= 16;
-      uws.bytes_left = 2;
-      data += uws.words_left;
-    }
-
-  /* Restore the saved pointer.  */
-  if (state == _US_UNWIND_FRAME_RESUME)
-    data = (_uw *) ucbp->cleanup_cache.bitpattern[0];
-
-  if ((ucbp->pr_cache.additional & 1) == 0)
-    {
-      /* Process descriptors.  */
-      while (get_remote_word(pid, data)) {
-      /**********************************************************************
-       * The original code here seems to deal with exceptions that are not
-       * applicable in our toolchain, thus there is no way to test it for now.
-       * Instead of leaving it here and causing potential instability in
-       * debuggerd, we'd better punt here and leave the stack unwound.
-       * In the future when we discover cases where the stack should be unwound
-       * further but is not, we can revisit the code here.
-       **********************************************************************/
-        return _URC_FAILURE;
-	  }
-	  /* Finished processing this descriptor.  */
-    }
-
-  if (unwind_execute_with_ptrace (context, &uws, pid) != _URC_OK)
-    return _URC_FAILURE;
-
-  if (phase2_call_unexpected_after_unwind)
-    {
-      /* Enter __cxa_unexpected as if called from the call site.  */
-      _Unwind_SetGR (context, R_LR, _Unwind_GetGR (context, R_PC));
-      _Unwind_SetGR (context, R_PC, (_uw) &__cxa_call_unexpected);
-      return _URC_INSTALL_CONTEXT;
-    }
-
-  return _URC_CONTINUE_UNWIND;
-}
-
-
-/* ABI defined personality routine entry points.  */
-
-static _Unwind_Reason_Code
-unwind_cpp_pr0_with_ptrace (_Unwind_State state,
-			_Unwind_Control_Block *ucbp,
-			_Unwind_Context *context,
-            pid_t pid)
-{
-  return unwind_pr_common_with_ptrace (state, ucbp, context, 0, pid);
-}
-
-static _Unwind_Reason_Code
-unwind_cpp_pr1_with_ptrace (_Unwind_State state,
-			_Unwind_Control_Block *ucbp,
-			_Unwind_Context *context,
-            pid_t pid)
-{
-  return unwind_pr_common_with_ptrace (state, ucbp, context, 1, pid);
-}
-
-static _Unwind_Reason_Code
-unwind_cpp_pr2_with_ptrace (_Unwind_State state,
-			_Unwind_Control_Block *ucbp,
-			_Unwind_Context *context,
-            pid_t pid)
-{
-  return unwind_pr_common_with_ptrace (state, ucbp, context, 2, pid);
-}
diff --git a/debuggerd/debuggerd.c b/debuggerd/debuggerd.c
index 2acf26d..0f05bfd 100644
--- a/debuggerd/debuggerd.c
+++ b/debuggerd/debuggerd.c
@@ -28,83 +28,26 @@
 #include <sys/wait.h>
 #include <sys/exec_elf.h>
 #include <sys/stat.h>
+#include <sys/poll.h>
 
 #include <cutils/sockets.h>
 #include <cutils/logd.h>
 #include <cutils/logger.h>
 #include <cutils/properties.h>
 
+#include <corkscrew/backtrace.h>
+
 #include <linux/input.h>
 
 #include <private/android_filesystem_config.h>
 
-#include "debuggerd.h"
+#include "getevent.h"
+#include "machine.h"
 #include "utility.h"
 
 #define ANDROID_LOG_INFO 4
 
-void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...)
-    __attribute__ ((format(printf, 3, 4)));
-
-/* Log information onto the tombstone */
-void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...)
-{
-    char buf[512];
-
-    va_list ap;
-    va_start(ap, fmt);
-
-    if (tfd >= 0) {
-        int len;
-        vsnprintf(buf, sizeof(buf), fmt, ap);
-        len = strlen(buf);
-        if(tfd >= 0) write(tfd, buf, len);
-    }
-
-    if (!in_tombstone_only)
-        __android_log_vprint(ANDROID_LOG_INFO, "DEBUG", fmt, ap);
-    va_end(ap);
-}
-
-// 6f000000-6f01e000 rwxp 00000000 00:0c 16389419   /system/lib/libcomposer.so
-// 012345678901234567890123456789012345678901234567890123456789
-// 0         1         2         3         4         5
-
-mapinfo *parse_maps_line(char *line)
-{
-    mapinfo *mi;
-    int len = strlen(line);
-
-    if (len < 1) return 0;      /* not expected */
-    line[--len] = 0;
-
-    if (len < 50) {
-        mi = malloc(sizeof(mapinfo) + 1);
-    } else {
-        mi = malloc(sizeof(mapinfo) + (len - 47));
-    }
-    if (mi == 0) return 0;
-
-    mi->isExecutable = (line[20] == 'x');
-
-    mi->start = strtoul(line, 0, 16);
-    mi->end = strtoul(line + 9, 0, 16);
-    /* To be filled in parse_elf_info if the mapped section starts with
-     * elf_header
-     */
-    mi->exidx_start = mi->exidx_end = 0;
-    mi->symbols = 0;
-    mi->next = 0;
-    if (len < 50) {
-        mi->name[0] = '\0';
-    } else {
-        strcpy(mi->name, line + 49);
-    }
-
-    return mi;
-}
-
-void dump_build_info(int tfd)
+static void dump_build_info(int tfd)
 {
     char fingerprint[PROPERTY_VALUE_MAX];
 
@@ -113,7 +56,7 @@
     _LOG(tfd, false, "Build fingerprint: '%s'\n", fingerprint);
 }
 
-const char *get_signame(int sig)
+static const char *get_signame(int sig)
 {
     switch(sig) {
     case SIGILL:     return "SIGILL";
@@ -122,11 +65,12 @@
     case SIGFPE:     return "SIGFPE";
     case SIGSEGV:    return "SIGSEGV";
     case SIGSTKFLT:  return "SIGSTKFLT";
+    case SIGSTOP:    return "SIGSTOP";
     default:         return "?";
     }
 }
 
-const char *get_sigcode(int signo, int code)
+static const char *get_sigcode(int signo, int code)
 {
     switch (signo) {
     case SIGILL:
@@ -170,12 +114,12 @@
     return "?";
 }
 
-void dump_fault_addr(int tfd, int pid, int sig)
+static void dump_fault_addr(int tfd, pid_t tid, int sig)
 {
     siginfo_t si;
 
     memset(&si, 0, sizeof(si));
-    if(ptrace(PTRACE_GETSIGINFO, pid, 0, &si)){
+    if(ptrace(PTRACE_GETSIGINFO, tid, 0, &si)){
         _LOG(tfd, false, "cannot get siginfo: %s\n", strerror(errno));
     } else if (signal_has_address(sig)) {
         _LOG(tfd, false, "signal %d (%s), code %d (%s), fault addr %08x\n",
@@ -188,7 +132,7 @@
     }
 }
 
-void dump_crash_banner(int tfd, unsigned pid, unsigned tid, int sig)
+static void dump_crash_banner(int tfd, pid_t pid, pid_t tid, int sig)
 {
     char data[1024];
     char *x = 0;
@@ -202,225 +146,62 @@
     }
 
     _LOG(tfd, false,
-         "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
+            "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
     dump_build_info(tfd);
     _LOG(tfd, false, "pid: %d, tid: %d  >>> %s <<<\n",
          pid, tid, x ? x : "UNKNOWN");
 
-    if(sig) dump_fault_addr(tfd, tid, sig);
-}
-
-static void parse_elf_info(mapinfo *milist, pid_t pid)
-{
-    mapinfo *mi;
-    for (mi = milist; mi != NULL; mi = mi->next) {
-        if (!mi->isExecutable)
-            continue;
-
-        Elf32_Ehdr ehdr;
-
-        memset(&ehdr, 0, sizeof(Elf32_Ehdr));
-        /* Read in sizeof(Elf32_Ehdr) worth of data from the beginning of
-         * mapped section.
-         */
-        get_remote_struct(pid, (void *) (mi->start), &ehdr,
-                          sizeof(Elf32_Ehdr));
-        /* Check if it has the matching magic words */
-        if (IS_ELF(ehdr)) {
-            Elf32_Phdr phdr;
-            Elf32_Phdr *ptr;
-            int i;
-
-            ptr = (Elf32_Phdr *) (mi->start + ehdr.e_phoff);
-            for (i = 0; i < ehdr.e_phnum; i++) {
-                /* Parse the program header */
-                get_remote_struct(pid, (char *) (ptr+i), &phdr,
-                                  sizeof(Elf32_Phdr));
-#ifdef __arm__
-                /* Found a EXIDX segment? */
-                if (phdr.p_type == PT_ARM_EXIDX) {
-                    mi->exidx_start = mi->start + phdr.p_offset;
-                    mi->exidx_end = mi->exidx_start + phdr.p_filesz;
-                    break;
-                }
-#endif
-            }
-
-            /* Try to load symbols from this file */
-            mi->symbols = symbol_table_create(mi->name);
-        }
+    if(sig) {
+        dump_fault_addr(tfd, tid, sig);
     }
 }
 
-void dump_crash_report(int tfd, unsigned pid, unsigned tid, bool at_fault)
-{
-    char data[1024];
-    FILE *fp;
-    mapinfo *milist = 0;
-    unsigned int sp_list[STACK_CONTENT_DEPTH];
-    int stack_depth;
-#ifdef __arm__
-    int frame0_pc_sane = 1;
-#endif
-
-    if (!at_fault) {
-        _LOG(tfd, true,
-         "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
-        _LOG(tfd, true, "pid: %d, tid: %d\n", pid, tid);
-    }
-
-    dump_registers(tfd, tid, at_fault);
-
-    /* Clear stack pointer records */
-    memset(sp_list, 0, sizeof(sp_list));
-
-    sprintf(data, "/proc/%d/maps", pid);
-    fp = fopen(data, "r");
-    if(fp) {
-        while(fgets(data, 1024, fp)) {
-            mapinfo *mi = parse_maps_line(data);
-            if(mi) {
-                mi->next = milist;
-                milist = mi;
-            }
-        }
-        fclose(fp);
-    }
-
-    parse_elf_info(milist, tid);
-
-#if __arm__
-    /* If stack unwinder fails, use the default solution to dump the stack
-     * content.
-     */
-    stack_depth = unwind_backtrace_with_ptrace(tfd, tid, milist, sp_list,
-                                               &frame0_pc_sane, at_fault);
-
-    /* The stack unwinder should at least unwind two levels of stack. If less
-     * level is seen we make sure at lease pc and lr are dumped.
-     */
-    if (stack_depth < 2) {
-        dump_pc_and_lr(tfd, tid, milist, stack_depth, at_fault);
-    }
-
-    dump_stack_and_code(tfd, tid, milist, stack_depth, sp_list, at_fault);
-#elif __i386__
-    /* If stack unwinder fails, use the default solution to dump the stack
-    * content.
-    */
-    stack_depth = unwind_backtrace_with_ptrace_x86(tfd, tid, milist,at_fault);
-#else
-#error "Unsupported architecture"
-#endif
-
-    while(milist) {
-        mapinfo *next = milist->next;
-        symbol_table_free(milist->symbols);
-        free(milist);
-        milist = next;
-    }
-}
-
-#define MAX_TOMBSTONES	10
-
-#define typecheck(x,y) {    \
-    typeof(x) __dummy1;     \
-    typeof(y) __dummy2;     \
-    (void)(&__dummy1 == &__dummy2); }
-
-#define TOMBSTONE_DIR	"/data/tombstones"
-
-/*
- * find_and_open_tombstone - find an available tombstone slot, if any, of the
- * form tombstone_XX where XX is 00 to MAX_TOMBSTONES-1, inclusive. If no
- * file is available, we reuse the least-recently-modified file.
- */
-static int find_and_open_tombstone(void)
-{
-    unsigned long mtime = ULONG_MAX;
-    struct stat sb;
-    char path[128];
-    int fd, i, oldest = 0;
-
-    /*
-     * XXX: Our stat.st_mtime isn't time_t. If it changes, as it probably ought
-     * to, our logic breaks. This check will generate a warning if that happens.
-     */
-    typecheck(mtime, sb.st_mtime);
-
-    /*
-     * In a single wolf-like pass, find an available slot and, in case none
-     * exist, find and record the least-recently-modified file.
-     */
-    for (i = 0; i < MAX_TOMBSTONES; i++) {
-        snprintf(path, sizeof(path), TOMBSTONE_DIR"/tombstone_%02d", i);
-
-        if (!stat(path, &sb)) {
-            if (sb.st_mtime < mtime) {
-                oldest = i;
-                mtime = sb.st_mtime;
-            }
-            continue;
-        }
-        if (errno != ENOENT)
-            continue;
-
-        fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0600);
-        if (fd < 0)
-            continue;	/* raced ? */
-
-        fchown(fd, AID_SYSTEM, AID_SYSTEM);
-        return fd;
-    }
-
-    /* we didn't find an available file, so we clobber the oldest one */
-    snprintf(path, sizeof(path), TOMBSTONE_DIR"/tombstone_%02d", oldest);
-    fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
-    fchown(fd, AID_SYSTEM, AID_SYSTEM);
-
-    return fd;
-}
-
 /* Return true if some thread is not detached cleanly */
-static bool dump_sibling_thread_report(int tfd, unsigned pid, unsigned tid)
-{
-    char task_path[1024];
+static bool dump_sibling_thread_report(const ptrace_context_t* context,
+        int tfd, pid_t pid, pid_t tid) {
+    char task_path[64];
+    snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
 
-    sprintf(task_path, "/proc/%d/task", pid);
-    DIR *d;
-    struct dirent *de;
-    int need_cleanup = 0;
-
-    d = opendir(task_path);
+    DIR* d = opendir(task_path);
     /* Bail early if cannot open the task directory */
     if (d == NULL) {
         XLOG("Cannot open /proc/%d/task\n", pid);
         return false;
     }
+
+    bool detach_failed = false;
+    struct dirent *de;
     while ((de = readdir(d)) != NULL) {
-        unsigned new_tid;
+        pid_t new_tid;
         /* Ignore "." and ".." */
-        if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
+        if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
             continue;
+        }
+
         new_tid = atoi(de->d_name);
         /* The main thread at fault has been handled individually */
-        if (new_tid == tid)
+        if (new_tid == tid) {
             continue;
+        }
 
         /* Skip this thread if cannot ptrace it */
-        if (ptrace(PTRACE_ATTACH, new_tid, 0, 0) < 0)
+        if (ptrace(PTRACE_ATTACH, new_tid, 0, 0) < 0) {
             continue;
+        }
 
-        dump_crash_report(tfd, pid, new_tid, false);
+        _LOG(tfd, true, "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
+        _LOG(tfd, true, "pid: %d, tid: %d\n", pid, new_tid);
+
+        dump_thread(context, tfd, new_tid, false);
 
         if (ptrace(PTRACE_DETACH, new_tid, 0, 0) != 0) {
-            XLOG("detach of tid %d failed: %s\n", new_tid, strerror(errno));
-            need_cleanup = 1;
+            LOG("ptrace detach from %d failed: %s\n", new_tid, strerror(errno));
+            detach_failed = true;
         }
     }
-    closedir(d);
 
-    return need_cleanup != 0;
+    closedir(d);
+    return detach_failed;
 }
 
 /*
@@ -429,7 +210,7 @@
  *
  * If "tailOnly" is set, we only print the last few lines.
  */
-static void dump_log_file(int tfd, unsigned pid, const char* filename,
+static void dump_log_file(int tfd, pid_t pid, const char* filename,
     bool tailOnly)
 {
     bool first = true;
@@ -561,52 +342,129 @@
  * Dumps the logs generated by the specified pid to the tombstone, from both
  * "system" and "main" log devices.  Ideally we'd interleave the output.
  */
-static void dump_logs(int tfd, unsigned pid, bool tailOnly)
+static void dump_logs(int tfd, pid_t pid, bool tailOnly)
 {
     dump_log_file(tfd, pid, "/dev/log/system", tailOnly);
     dump_log_file(tfd, pid, "/dev/log/main", tailOnly);
 }
 
-/* Return true if some thread is not detached cleanly */
-static bool engrave_tombstone(unsigned pid, unsigned tid, int debug_uid,
-                              int signal)
+/*
+ * Dumps all information about the specified pid to the tombstone.
+ */
+static bool dump_crash(int tfd, pid_t pid, pid_t tid, int signal,
+        bool dump_sibling_threads)
 {
-    int fd;
-    bool need_cleanup = false;
-
     /* don't copy log messages to tombstone unless this is a dev device */
     char value[PROPERTY_VALUE_MAX];
     property_get("ro.debuggable", value, "0");
     bool wantLogs = (value[0] == '1');
 
+    dump_crash_banner(tfd, pid, tid, signal);
+
+    ptrace_context_t* context = load_ptrace_context(tid);
+
+    dump_thread(context, tfd, tid, true);
+
+    if (wantLogs) {
+        dump_logs(tfd, pid, true);
+    }
+
+    bool detach_failed = false;
+    if (dump_sibling_threads) {
+        detach_failed = dump_sibling_thread_report(context, tfd, pid, tid);
+    }
+
+    free_ptrace_context(context);
+
+    if (wantLogs) {
+        dump_logs(tfd, pid, false);
+    }
+    return detach_failed;
+}
+
+#define MAX_TOMBSTONES	10
+
+#define typecheck(x,y) {    \
+    typeof(x) __dummy1;     \
+    typeof(y) __dummy2;     \
+    (void)(&__dummy1 == &__dummy2); }
+
+#define TOMBSTONE_DIR	"/data/tombstones"
+
+/*
+ * find_and_open_tombstone - find an available tombstone slot, if any, of the
+ * form tombstone_XX where XX is 00 to MAX_TOMBSTONES-1, inclusive. If no
+ * file is available, we reuse the least-recently-modified file.
+ *
+ * Returns the path of the tombstone file, allocated using malloc().  Caller must free() it.
+ */
+static char* find_and_open_tombstone(int* fd)
+{
+    unsigned long mtime = ULONG_MAX;
+    struct stat sb;
+
+    /*
+     * XXX: Our stat.st_mtime isn't time_t. If it changes, as it probably ought
+     * to, our logic breaks. This check will generate a warning if that happens.
+     */
+    typecheck(mtime, sb.st_mtime);
+
+    /*
+     * In a single wolf-like pass, find an available slot and, in case none
+     * exist, find and record the least-recently-modified file.
+     */
+    char path[128];
+    int oldest = 0;
+    for (int i = 0; i < MAX_TOMBSTONES; i++) {
+        snprintf(path, sizeof(path), TOMBSTONE_DIR"/tombstone_%02d", i);
+
+        if (!stat(path, &sb)) {
+            if (sb.st_mtime < mtime) {
+                oldest = i;
+                mtime = sb.st_mtime;
+            }
+            continue;
+        }
+        if (errno != ENOENT)
+            continue;
+
+        *fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0600);
+        if (*fd < 0)
+            continue;	/* raced ? */
+
+        fchown(*fd, AID_SYSTEM, AID_SYSTEM);
+        return strdup(path);
+    }
+
+    /* we didn't find an available file, so we clobber the oldest one */
+    snprintf(path, sizeof(path), TOMBSTONE_DIR"/tombstone_%02d", oldest);
+    *fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
+    if (*fd < 0) {
+        LOG("failed to open tombstone file '%s': %s\n", path, strerror(errno));
+        return NULL;
+    }
+    fchown(*fd, AID_SYSTEM, AID_SYSTEM);
+    return strdup(path);
+}
+
+/* Return true if some thread is not detached cleanly */
+static char* engrave_tombstone(pid_t pid, pid_t tid, int signal, bool dump_sibling_threads,
+        bool* detach_failed)
+{
     mkdir(TOMBSTONE_DIR, 0755);
     chown(TOMBSTONE_DIR, AID_SYSTEM, AID_SYSTEM);
 
-    fd = find_and_open_tombstone();
-    if (fd < 0)
-        return need_cleanup;
-
-    dump_crash_banner(fd, pid, tid, signal);
-    dump_crash_report(fd, pid, tid, true);
-
-    if (wantLogs) {
-        dump_logs(fd, pid, true);
+    int fd;
+    char* path = find_and_open_tombstone(&fd);
+    if (!path) {
+        *detach_failed = false;
+        return NULL;
     }
 
-    /*
-     * If the user has requested to attach gdb, don't collect the per-thread
-     * information as it increases the chance to lose track of the process.
-     */
-    if ((signed)pid > debug_uid) {
-        need_cleanup = dump_sibling_thread_report(fd, pid, tid);
-    }
-
-    if (wantLogs) {
-        dump_logs(fd, pid, false);
-    }
+    *detach_failed = dump_crash(fd, pid, tid, signal, dump_sibling_threads);
 
     close(fd);
-    return need_cleanup;
+    return path;
 }
 
 static int
@@ -654,25 +512,21 @@
     write_string("/sys/class/leds/left/cadence", "0,0");
 }
 
-extern int init_getevent();
-extern void uninit_getevent();
-extern int get_event(struct input_event* event, int timeout);
-
-static void wait_for_user_action(unsigned tid, struct ucred* cr)
-{
-    (void)tid;
+static void wait_for_user_action(pid_t pid) {
     /* First log a helpful message */
     LOG(    "********************************************************\n"
             "* Process %d has been suspended while crashing.  To\n"
-            "* attach gdbserver for a gdb connection on port 5039:\n"
+            "* attach gdbserver for a gdb connection on port 5039\n"
+            "* and start gdbclient:\n"
             "*\n"
-            "*     adb shell gdbserver :5039 --attach %d &\n"
+            "*     gdbclient app_process :5039 %d\n"
             "*\n"
-            "* Press HOME key to let the process continue crashing.\n"
+            "* Wait for gdb to start, then press HOME or VOLUME DOWN key\n"
+            "* to let the process continue crashing.\n"
             "********************************************************\n",
-            cr->pid, cr->pid);
+            pid, pid);
 
-    /* wait for HOME key (TODO: something useful for devices w/o HOME key) */
+    /* wait for HOME or VOLUME DOWN key */
     if (init_getevent() == 0) {
         int ms = 1200 / 10;
         int dit = 1;
@@ -685,15 +539,18 @@
         };
         size_t s = 0;
         struct input_event e;
-        int home = 0;
+        bool done = false;
         init_debug_led();
         enable_debug_led();
         do {
             int timeout = abs((int)(codes[s])) * ms;
             int res = get_event(&e, timeout);
             if (res == 0) {
-                if (e.type==EV_KEY && e.code==KEY_HOME && e.value==0)
-                    home = 1;
+                if (e.type == EV_KEY
+                        && (e.code == KEY_HOME || e.code == KEY_VOLUMEDOWN)
+                        && e.value == 0) {
+                    done = true;
+                }
             } else if (res == 1) {
                 if (++s >= sizeof(codes)/sizeof(*codes))
                     s = 0;
@@ -703,202 +560,294 @@
                     disable_debug_led();
                 }
             }
-        } while (!home);
+        } while (!done);
         uninit_getevent();
     }
 
     /* don't forget to turn debug led off */
     disable_debug_led();
+    LOG("debuggerd resuming process %d", pid);
+}
 
-    /* close filedescriptor */
-    LOG("debuggerd resuming process %d", cr->pid);
- }
+static int get_process_info(pid_t tid, pid_t* out_pid, uid_t* out_uid, uid_t* out_gid) {
+    char path[64];
+    snprintf(path, sizeof(path), "/proc/%d/status", tid);
 
-static void handle_crashing_process(int fd)
-{
-    char buf[64];
-    struct stat s;
-    unsigned tid;
+    FILE* fp = fopen(path, "r");
+    if (!fp) {
+        return -1;
+    }
+
+    int fields = 0;
+    char line[1024];
+    while (fgets(line, sizeof(line), fp)) {
+        size_t len = strlen(line);
+        if (len > 6 && !memcmp(line, "Tgid:\t", 6)) {
+            *out_pid = atoi(line + 6);
+            fields |= 1;
+        } else if (len > 5 && !memcmp(line, "Uid:\t", 5)) {
+            *out_uid = atoi(line + 5);
+            fields |= 2;
+        } else if (len > 5 && !memcmp(line, "Gid:\t", 5)) {
+            *out_gid = atoi(line + 5);
+            fields |= 4;
+        }
+    }
+    fclose(fp);
+    return fields == 7 ? 0 : -1;
+}
+
+static int wait_for_signal(pid_t tid, int* total_sleep_time_usec) {
+    const int sleep_time_usec = 200000;         /* 0.2 seconds */
+    const int max_total_sleep_usec = 3000000;   /* 3 seconds */
+    for (;;) {
+        int status;
+        pid_t n = waitpid(tid, &status, __WALL | WNOHANG);
+        if (n < 0) {
+            if(errno == EAGAIN) continue;
+            LOG("waitpid failed: %s\n", strerror(errno));
+            return -1;
+        } else if (n > 0) {
+            XLOG("waitpid: n=%d status=%08x\n", n, status);
+            if (WIFSTOPPED(status)) {
+                return WSTOPSIG(status);
+            } else {
+                LOG("unexpected waitpid response: n=%d, status=%08x\n", n, status);
+                return -1;
+            }
+        }
+
+        if (*total_sleep_time_usec > max_total_sleep_usec) {
+            LOG("timed out waiting for tid=%d to die\n", tid);
+            return -1;
+        }
+
+        /* not ready yet */
+        XLOG("not ready yet\n");
+        usleep(sleep_time_usec);
+        *total_sleep_time_usec += sleep_time_usec;
+    }
+}
+
+enum {
+    REQUEST_TYPE_CRASH,
+    REQUEST_TYPE_DUMP,
+};
+
+typedef struct {
+    int type;
+    pid_t pid, tid;
+    uid_t uid, gid;
+} request_t;
+
+static int read_request(int fd, request_t* out_request) {
     struct ucred cr;
-    int n, len, status;
-    int tid_attach_status = -1;
-    unsigned retry = 30;
-    bool need_cleanup = false;
-
-    char value[PROPERTY_VALUE_MAX];
-    property_get("debug.db.uid", value, "-1");
-    int debug_uid = atoi(value);
-
-    XLOG("handle_crashing_process(%d)\n", fd);
-
-    len = sizeof(cr);
-    n = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
-    if(n != 0) {
+    int len = sizeof(cr);
+    int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
+    if (status != 0) {
         LOG("cannot get credentials\n");
-        goto done;
+        return -1;
     }
 
     XLOG("reading tid\n");
     fcntl(fd, F_SETFL, O_NONBLOCK);
-    while((n = read(fd, &tid, sizeof(unsigned))) != sizeof(unsigned)) {
-        if(errno == EINTR) continue;
-        if(errno == EWOULDBLOCK) {
-            if(retry-- > 0) {
-                usleep(100 * 1000);
-                continue;
-            }
-            LOG("timed out reading tid\n");
-            goto done;
-        }
-        LOG("read failure? %s\n", strerror(errno));
-        goto done;
+
+    struct pollfd pollfds[1];
+    pollfds[0].fd = fd;
+    pollfds[0].events = POLLIN;
+    pollfds[0].revents = 0;
+    status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000));
+    if (status != 1) {
+        LOG("timed out reading tid\n");
+        return -1;
     }
 
-    snprintf(buf, sizeof buf, "/proc/%d/task/%d", cr.pid, tid);
+    status = TEMP_FAILURE_RETRY(read(fd, &out_request->tid, sizeof(pid_t)));
+    if (status < 0) {
+        LOG("read failure? %s\n", strerror(errno));
+        return -1;
+    }
+    if (status != sizeof(pid_t)) {
+        LOG("invalid crash request of size %d\n", status);
+        return -1;
+    }
+
+    if (out_request->tid < 0 && cr.uid == 0) {
+        /* Root can ask us to attach to any process and dump it explicitly. */
+        out_request->type = REQUEST_TYPE_DUMP;
+        out_request->tid = -out_request->tid;
+        status = get_process_info(out_request->tid, &out_request->pid,
+                &out_request->uid, &out_request->gid);
+        if (status < 0) {
+            LOG("tid %d does not exist. ignoring explicit dump request\n",
+                    out_request->tid);
+            return -1;
+        }
+        return 0;
+    }
+
+    /* Ensure that the tid reported by the crashing process is valid. */
+    out_request->type = REQUEST_TYPE_CRASH;
+    out_request->pid = cr.pid;
+    out_request->uid = cr.uid;
+    out_request->gid = cr.gid;
+
+    char buf[64];
+    struct stat s;
+    snprintf(buf, sizeof buf, "/proc/%d/task/%d", out_request->pid, out_request->tid);
     if(stat(buf, &s)) {
         LOG("tid %d does not exist in pid %d. ignoring debug request\n",
-            tid, cr.pid);
-        close(fd);
-        return;
+                out_request->tid, out_request->pid);
+        return -1;
     }
-
-    XLOG("BOOM: pid=%d uid=%d gid=%d tid=%d\n", cr.pid, cr.uid, cr.gid, tid);
-
-    /* Note that at this point, the target thread's signal handler
-     * is blocked in a read() call. This gives us the time to PTRACE_ATTACH
-     * to it before it has a chance to really fault.
-     *
-     * The PTRACE_ATTACH sends a SIGSTOP to the target process, but it
-     * won't necessarily have stopped by the time ptrace() returns.  (We
-     * currently assume it does.)  We write to the file descriptor to
-     * ensure that it can run as soon as we call PTRACE_CONT below.
-     * See details in bionic/libc/linker/debugger.c, in function
-     * debugger_signal_handler().
-     */
-    tid_attach_status = ptrace(PTRACE_ATTACH, tid, 0, 0);
-    int ptrace_error = errno;
-
-    if (TEMP_FAILURE_RETRY(write(fd, &tid, 1)) != 1) {
-        XLOG("failed responding to client: %s\n",
-            strerror(errno));
-        goto done;
-    }
-
-    if(tid_attach_status < 0) {
-        LOG("ptrace attach failed: %s\n", strerror(ptrace_error));
-        goto done;
-    }
-
-    close(fd);
-    fd = -1;
-
-    const int sleep_time_usec = 200000;         /* 0.2 seconds */
-    const int max_total_sleep_usec = 3000000;   /* 3 seconds */
-    int loop_limit = max_total_sleep_usec / sleep_time_usec;
-    for(;;) {
-        if (loop_limit-- == 0) {
-            LOG("timed out waiting for pid=%d tid=%d uid=%d to die\n",
-                cr.pid, tid, cr.uid);
-            goto done;
-        }
-        n = waitpid(tid, &status, __WALL | WNOHANG);
-
-        if (n == 0) {
-            /* not ready yet */
-            XLOG("not ready yet\n");
-            usleep(sleep_time_usec);
-            continue;
-        }
-
-        if(n < 0) {
-            if(errno == EAGAIN) continue;
-            LOG("waitpid failed: %s\n", strerror(errno));
-            goto done;
-        }
-
-        XLOG("waitpid: n=%d status=%08x\n", n, status);
-
-        if(WIFSTOPPED(status)){
-            n = WSTOPSIG(status);
-            switch(n) {
-            case SIGSTOP:
-                XLOG("stopped -- continuing\n");
-                n = ptrace(PTRACE_CONT, tid, 0, 0);
-                if(n) {
-                    LOG("ptrace failed: %s\n", strerror(errno));
-                    goto done;
-                }
-                continue;
-
-            case SIGILL:
-            case SIGABRT:
-            case SIGBUS:
-            case SIGFPE:
-            case SIGSEGV:
-            case SIGSTKFLT: {
-                XLOG("stopped -- fatal signal\n");
-                need_cleanup = engrave_tombstone(cr.pid, tid, debug_uid, n);
-                kill(tid, SIGSTOP);
-                goto done;
-            }
-
-            default:
-                XLOG("stopped -- unexpected signal\n");
-                goto done;
-            }
-        } else {
-            XLOG("unexpected waitpid response\n");
-            goto done;
-        }
-    }
-
-done:
-    XLOG("detaching\n");
-
-    /* stop the process so we can debug */
-    kill(cr.pid, SIGSTOP);
-
-    /*
-     * If a thread has been attached by ptrace, make sure it is detached
-     * successfully otherwise we will get a zombie.
-     */
-    if (tid_attach_status == 0) {
-        int detach_status;
-        /* detach so we can attach gdbserver */
-        detach_status = ptrace(PTRACE_DETACH, tid, 0, 0);
-        need_cleanup |= (detach_status != 0);
-    }
-
-    /*
-     * if debug.db.uid is set, its value indicates if we should wait
-     * for user action for the crashing process.
-     * in this case, we log a message and turn the debug LED on
-     * waiting for a gdb connection (for instance)
-     */
-
-    if ((signed)cr.uid <= debug_uid) {
-        wait_for_user_action(tid, &cr);
-    }
-
-    /*
-     * Resume stopped process (so it can crash in peace).  If we didn't
-     * successfully detach, we're still the parent, and the actual parent
-     * won't receive a death notification via wait(2).  At this point
-     * there's not much we can do about that.
-     */
-    kill(cr.pid, SIGCONT);
-
-    if (need_cleanup) {
-        LOG("debuggerd committing suicide to free the zombie!\n");
-        kill(getpid(), SIGKILL);
-    }
-
-    if(fd != -1) close(fd);
+    return 0;
 }
 
+static bool should_attach_gdb(request_t* request) {
+    if (request->type == REQUEST_TYPE_CRASH) {
+        char value[PROPERTY_VALUE_MAX];
+        property_get("debug.db.uid", value, "-1");
+        int debug_uid = atoi(value);
+        return debug_uid >= 0 && request->uid <= (uid_t)debug_uid;
+    }
+    return false;
+}
 
-int main()
-{
+static void handle_request(int fd) {
+    XLOG("handle_request(%d)\n", fd);
+
+    request_t request;
+    int status = read_request(fd, &request);
+    if (!status) {
+        XLOG("BOOM: pid=%d uid=%d gid=%d tid=%d\n", pid, uid, gid, tid);
+
+        /* At this point, the thread that made the request is blocked in
+         * a read() call.  If the thread has crashed, then this gives us
+         * time to PTRACE_ATTACH to it before it has a chance to really fault.
+         *
+         * The PTRACE_ATTACH sends a SIGSTOP to the target process, but it
+         * won't necessarily have stopped by the time ptrace() returns.  (We
+         * currently assume it does.)  We write to the file descriptor to
+         * ensure that it can run as soon as we call PTRACE_CONT below.
+         * See details in bionic/libc/linker/debugger.c, in function
+         * debugger_signal_handler().
+         */
+        if (ptrace(PTRACE_ATTACH, request.tid, 0, 0)) {
+            LOG("ptrace attach failed: %s\n", strerror(errno));
+        } else {
+            bool detach_failed = false;
+            bool attach_gdb = should_attach_gdb(&request);
+            char response = 0;
+            if (TEMP_FAILURE_RETRY(write(fd, &response, 1)) != 1) {
+                LOG("failed responding to client: %s\n", strerror(errno));
+            } else {
+                char* tombstone_path = NULL;
+
+                if (request.type != REQUEST_TYPE_DUMP) {
+                    close(fd);
+                    fd = -1;
+                }
+
+                int total_sleep_time_usec = 0;
+                for (;;) {
+                    int signal = wait_for_signal(request.tid, &total_sleep_time_usec);
+                    if (signal < 0) {
+                        break;
+                    }
+
+                    switch (signal) {
+                    case SIGSTOP:
+                        if (request.type == REQUEST_TYPE_DUMP) {
+                            XLOG("stopped -- dumping\n");
+                            tombstone_path = engrave_tombstone(request.pid, request.tid,
+                                    signal, true, &detach_failed);
+                        } else {
+                            XLOG("stopped -- continuing\n");
+                            status = ptrace(PTRACE_CONT, request.tid, 0, 0);
+                            if (status) {
+                                LOG("ptrace continue failed: %s\n", strerror(errno));
+                            }
+                            continue; /* loop again */
+                        }
+                        break;
+
+                    case SIGILL:
+                    case SIGABRT:
+                    case SIGBUS:
+                    case SIGFPE:
+                    case SIGSEGV:
+                    case SIGSTKFLT: {
+                        XLOG("stopped -- fatal signal\n");
+                        /* don't dump sibling threads when attaching to GDB because it
+                         * makes the process less reliable, apparently... */
+                        tombstone_path = engrave_tombstone(request.pid, request.tid,
+                                signal, !attach_gdb, &detach_failed);
+                        break;
+                    }
+
+                    default:
+                        XLOG("stopped -- unexpected signal\n");
+                        LOG("process stopped due to unexpected signal %d\n", signal);
+                        break;
+                    }
+                    break;
+                }
+
+                if (request.type == REQUEST_TYPE_DUMP) {
+                    if (tombstone_path) {
+                        write(fd, tombstone_path, strlen(tombstone_path));
+                    }
+                    close(fd);
+                    fd = -1;
+                }
+                free(tombstone_path);
+            }
+
+            XLOG("detaching\n");
+            if (attach_gdb) {
+                /* stop the process so we can debug */
+                kill(request.pid, SIGSTOP);
+
+                /* detach so we can attach gdbserver */
+                if (ptrace(PTRACE_DETACH, request.tid, 0, 0)) {
+                    LOG("ptrace detach from %d failed: %s\n", request.tid, strerror(errno));
+                    detach_failed = true;
+                }
+
+                /*
+                 * if debug.db.uid is set, its value indicates if we should wait
+                 * for user action for the crashing process.
+                 * in this case, we log a message and turn the debug LED on
+                 * waiting for a gdb connection (for instance)
+                 */
+                wait_for_user_action(request.pid);
+            } else {
+                /* just detach */
+                if (ptrace(PTRACE_DETACH, request.tid, 0, 0)) {
+                    LOG("ptrace detach from %d failed: %s\n", request.tid, strerror(errno));
+                    detach_failed = true;
+                }
+            }
+
+            /* resume stopped process (so it can crash in peace). */
+            kill(request.pid, SIGCONT);
+
+            /* If we didn't successfully detach, we're still the parent, and the
+             * actual parent won't receive a death notification via wait(2).  At this point
+             * there's not much we can do about that. */
+            if (detach_failed) {
+                LOG("debuggerd committing suicide to free the zombie!\n");
+                kill(getpid(), SIGKILL);
+            }
+        }
+
+    }
+    if (fd >= 0) {
+        close(fd);
+    }
+}
+
+static int do_server() {
     int s;
     struct sigaction act;
     int logsocket = -1;
@@ -931,7 +880,7 @@
 
     s = socket_local_server("android:debuggerd",
             ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
-    if(s < 0) return -1;
+    if(s < 0) return 1;
     fcntl(s, F_SETFD, FD_CLOEXEC);
 
     LOG("debuggerd: " __DATE__ " " __TIME__ "\n");
@@ -951,7 +900,52 @@
 
         fcntl(fd, F_SETFD, FD_CLOEXEC);
 
-        handle_crashing_process(fd);
+        handle_request(fd);
     }
     return 0;
 }
+
+static int do_explicit_dump(pid_t tid) {
+    fprintf(stdout, "Sending request to dump task %d.\n", tid);
+
+    int fd = socket_local_client("android:debuggerd",
+            ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
+    if (fd < 0) {
+        fputs("Error opening local socket to debuggerd.\n", stderr);
+        return 1;
+    }
+
+    pid_t request = -tid;
+    write(fd, &request, sizeof(pid_t));
+    if (read(fd, &request, 1) != 1) {
+        /* did not get expected reply, debuggerd must have closed the socket */
+        fputs("Error sending request.  Did not receive reply from debuggerd.\n", stderr);
+    } else {
+        char tombstone_path[PATH_MAX];
+        ssize_t n = read(fd, &tombstone_path, sizeof(tombstone_path) - 1);
+        if (n <= 0) {
+            fputs("Error dumping process.  Check log for details.\n", stderr);
+        } else {
+            tombstone_path[n] = '\0';
+            fprintf(stderr, "Tombstone written to: %s\n", tombstone_path);
+        }
+    }
+
+    close(fd);
+    return 0;
+}
+
+int main(int argc, char** argv) {
+    if (argc == 2) {
+        pid_t tid = atoi(argv[1]);
+        if (!tid) {
+            fputs("Usage: [<tid>]\n"
+                    "\n"
+                    "If tid specified, sends a request to debuggerd to dump that task.\n"
+                    "Otherwise, starts the debuggerd server.\n", stderr);
+            return 1;
+        }
+        return do_explicit_dump(tid);
+    }
+    return do_server();
+}
diff --git a/debuggerd/debuggerd.h b/debuggerd/debuggerd.h
deleted file mode 100644
index e3cdc7c..0000000
--- a/debuggerd/debuggerd.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* system/debuggerd/debuggerd.h
-**
-** Copyright 2006, 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 <cutils/logd.h>
-#include <sys/ptrace.h>
-#include <unwind.h>
-#include "utility.h"
-#include "symbol_table.h"
-
-
-/* Main entry point to get the backtrace from the crashing process */
-extern int unwind_backtrace_with_ptrace(int tfd, pid_t pid, mapinfo *map,
-                                        unsigned int sp_list[],
-                                        int *frame0_pc_sane,
-                                        bool at_fault);
-
-extern void dump_registers(int tfd, int pid, bool at_fault);
-
-extern int unwind_backtrace_with_ptrace_x86(int tfd, pid_t pid, mapinfo *map, bool at_fault);
-
-void dump_pc_and_lr(int tfd, int pid, mapinfo *map, int unwound_level, bool at_fault);
-
-void dump_stack_and_code(int tfd, int pid, mapinfo *map,
-                         int unwind_depth, unsigned int sp_list[],
-                         bool at_fault);
diff --git a/debuggerd/getevent.h b/debuggerd/getevent.h
new file mode 100644
index 0000000..426139d
--- /dev/null
+++ b/debuggerd/getevent.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2011 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 _DEBUGGERD_GETEVENT_H
+#define _DEBUGGERD_GETEVENT_H
+
+int init_getevent();
+void uninit_getevent();
+int get_event(struct input_event* event, int timeout);
+
+#endif // _DEBUGGERD_GETEVENT_H
diff --git a/debuggerd/machine.h b/debuggerd/machine.h
new file mode 100644
index 0000000..6049b69
--- /dev/null
+++ b/debuggerd/machine.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2011 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 _DEBUGGERD_MACHINE_H
+#define _DEBUGGERD_MACHINE_H
+
+#include <corkscrew/backtrace.h>
+#include <sys/types.h>
+
+void dump_thread(const ptrace_context_t* context, int tfd, pid_t tid, bool at_fault);
+
+#endif // _DEBUGGERD_MACHINE_H
diff --git a/debuggerd/symbol_table.c b/debuggerd/symbol_table.c
deleted file mode 100644
index 23572a3..0000000
--- a/debuggerd/symbol_table.c
+++ /dev/null
@@ -1,240 +0,0 @@
-#include <stdlib.h>
-#include <fcntl.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/mman.h>
-
-#include "symbol_table.h"
-#include "utility.h"
-
-#include <linux/elf.h>
-
-// Compare func for qsort
-static int qcompar(const void *a, const void *b)
-{
-    return ((struct symbol*)a)->addr - ((struct symbol*)b)->addr;
-}
-
-// Compare func for bsearch
-static int bcompar(const void *addr, const void *element)
-{
-    struct symbol *symbol = (struct symbol*)element;
-
-    if((unsigned int)addr < symbol->addr) {
-        return -1;
-    }
-
-    if((unsigned int)addr - symbol->addr >= symbol->size) {
-        return 1;
-    }
-
-    return 0;
-}
-
-/*
- *  Create a symbol table from a given file
- *
- *  Parameters:
- *      filename - Filename to process
- *
- *  Returns:
- *      A newly-allocated SymbolTable structure, or NULL if error.
- *      Free symbol table with symbol_table_free()
- */
-struct symbol_table *symbol_table_create(const char *filename)
-{
-    struct symbol_table *table = NULL;
-
-    // Open the file, and map it into memory
-    struct stat sb;
-    int length;
-    char *base;
-
-    XLOG2("Creating symbol table for %s\n", filename);
-    int fd = open(filename, O_RDONLY);
-
-    if(fd < 0) {
-        goto out;
-    }
-
-    fstat(fd, &sb);
-    length = sb.st_size;
-
-    base = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
-
-    if(!base) {
-        goto out_close;
-    }
-
-    // Parse the file header
-    Elf32_Ehdr *hdr = (Elf32_Ehdr*)base;
-    Elf32_Shdr *shdr = (Elf32_Shdr*)(base + hdr->e_shoff);
-
-    // Search for the dynamic symbols section
-    int sym_idx = -1;
-    int dynsym_idx = -1;
-    int i;
-
-    for(i = 0; i < hdr->e_shnum; i++) {
-        if(shdr[i].sh_type == SHT_SYMTAB ) {
-            sym_idx = i;
-        }
-        if(shdr[i].sh_type == SHT_DYNSYM ) {
-            dynsym_idx = i;
-        }
-    }
-    if ((dynsym_idx == -1) && (sym_idx == -1)) {
-        goto out_unmap;
-    }
-
-    table = malloc(sizeof(struct symbol_table));
-    if(!table) {
-        goto out_unmap;
-    }
-    table->name = strdup(filename);
-    table->num_symbols = 0;
-
-    Elf32_Sym *dynsyms = NULL;
-    Elf32_Sym *syms = NULL;
-    int dynnumsyms = 0;
-    int numsyms = 0;
-    char *dynstr = NULL;
-    char *str = NULL;
-
-    if (dynsym_idx != -1) {
-        dynsyms = (Elf32_Sym*)(base + shdr[dynsym_idx].sh_offset);
-        dynnumsyms = shdr[dynsym_idx].sh_size / shdr[dynsym_idx].sh_entsize;
-        int dynstr_idx = shdr[dynsym_idx].sh_link;
-        dynstr = base + shdr[dynstr_idx].sh_offset;
-    }
-
-    if (sym_idx != -1) {
-        syms = (Elf32_Sym*)(base + shdr[sym_idx].sh_offset);
-        numsyms = shdr[sym_idx].sh_size / shdr[sym_idx].sh_entsize;
-        int str_idx = shdr[sym_idx].sh_link;
-        str = base + shdr[str_idx].sh_offset;
-    }
-
-    int symbol_count = 0;
-    int dynsymbol_count = 0;
-
-    if (dynsym_idx != -1) {
-        // Iterate through the dynamic symbol table, and count how many symbols
-        // are actually defined
-        for(i = 0; i < dynnumsyms; i++) {
-            if(dynsyms[i].st_shndx != SHN_UNDEF) {
-                dynsymbol_count++;
-            }
-        }
-        XLOG2("Dynamic Symbol count: %d\n", dynsymbol_count);
-    }
-
-    if (sym_idx != -1) {
-        // Iterate through the symbol table, and count how many symbols
-        // are actually defined
-        for(i = 0; i < numsyms; i++) {
-            if((syms[i].st_shndx != SHN_UNDEF) &&
-                (strlen(str+syms[i].st_name)) &&
-                (syms[i].st_value != 0) && (syms[i].st_size != 0)) {
-                symbol_count++;
-            }
-        }
-        XLOG2("Symbol count: %d\n", symbol_count);
-    }
-
-    // Now, create an entry in our symbol table structure for each symbol...
-    table->num_symbols += symbol_count + dynsymbol_count;
-    table->symbols = malloc(table->num_symbols * sizeof(struct symbol));
-    if(!table->symbols) {
-        free(table);
-        table = NULL;
-        goto out_unmap;
-    }
-
-
-    int j = 0;
-    if (dynsym_idx != -1) {
-        // ...and populate them
-        for(i = 0; i < dynnumsyms; i++) {
-            if(dynsyms[i].st_shndx != SHN_UNDEF) {
-                table->symbols[j].name = strdup(dynstr + dynsyms[i].st_name);
-                table->symbols[j].addr = dynsyms[i].st_value;
-                table->symbols[j].size = dynsyms[i].st_size;
-                XLOG2("name: %s, addr: %x, size: %x\n",
-                    table->symbols[j].name, table->symbols[j].addr, table->symbols[j].size);
-                j++;
-            }
-        }
-    }
-
-    if (sym_idx != -1) {
-        // ...and populate them
-        for(i = 0; i < numsyms; i++) {
-            if((syms[i].st_shndx != SHN_UNDEF) &&
-                (strlen(str+syms[i].st_name)) &&
-                (syms[i].st_value != 0) && (syms[i].st_size != 0)) {
-                table->symbols[j].name = strdup(str + syms[i].st_name);
-                table->symbols[j].addr = syms[i].st_value;
-                table->symbols[j].size = syms[i].st_size;
-                XLOG2("name: %s, addr: %x, size: %x\n",
-                    table->symbols[j].name, table->symbols[j].addr, table->symbols[j].size);
-                j++;
-            }
-        }
-    }
-
-    // Sort the symbol table entries, so they can be bsearched later
-    qsort(table->symbols, table->num_symbols, sizeof(struct symbol), qcompar);
-
-out_unmap:
-    munmap(base, length);
-
-out_close:
-    close(fd);
-
-out:
-    return table;
-}
-
-/*
- * Free a symbol table
- *
- * Parameters:
- *     table - Table to free
- */
-void symbol_table_free(struct symbol_table *table)
-{
-    int i;
-
-    if(!table) {
-        return;
-    }
-
-    for(i=0; i<table->num_symbols; i++) {
-        free(table->symbols[i].name);
-    }
-
-    free(table->symbols);
-    free(table);
-}
-
-/*
- * Search for an address in the symbol table
- *
- * Parameters:
- *      table - Table to search in
- *      addr - Address to search for.
- *
- * Returns:
- *      A pointer to the Symbol structure corresponding to the
- *      symbol which contains this address, or NULL if no symbol
- *      contains it.
- */
-const struct symbol *symbol_table_lookup(struct symbol_table *table, unsigned int addr)
-{
-    if(!table) {
-        return NULL;
-    }
-
-    return bsearch((void*)addr, table->symbols, table->num_symbols, sizeof(struct symbol), bcompar);
-}
diff --git a/debuggerd/symbol_table.h b/debuggerd/symbol_table.h
deleted file mode 100644
index 7f41f91..0000000
--- a/debuggerd/symbol_table.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef SYMBOL_TABLE_H
-#define SYMBOL_TABLE_H
-
-struct symbol {
-    unsigned int addr;
-    unsigned int size;
-    char *name;
-};
-
-struct symbol_table {
-    struct symbol *symbols;
-    int num_symbols;
-    char *name;
-};
-
-struct symbol_table *symbol_table_create(const char *filename);
-void symbol_table_free(struct symbol_table *table);
-const struct symbol *symbol_table_lookup(struct symbol_table *table, unsigned int addr);
-
-#endif
diff --git a/debuggerd/utility.c b/debuggerd/utility.c
index 409209c..2ccf947 100644
--- a/debuggerd/utility.c
+++ b/debuggerd/utility.c
@@ -15,81 +15,37 @@
 ** limitations under the License.
 */
 
-#include <sys/ptrace.h>
-#include <sys/exec_elf.h>
 #include <signal.h>
-#include <assert.h>
 #include <string.h>
+#include <cutils/logd.h>
+#include <sys/ptrace.h>
 #include <errno.h>
+#include <corkscrew/demangle.h>
 
 #include "utility.h"
 
-/* Get a word from pid using ptrace. The result is the return value. */
-int get_remote_word(int pid, void *src)
-{
-    return ptrace(PTRACE_PEEKTEXT, pid, src, NULL);
-}
+#define STACK_DEPTH 32
+#define STACK_WORDS 16
 
+void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...) {
+    char buf[512];
 
-/* Handy routine to read aggregated data from pid using ptrace. The read 
- * values are written to the dest locations directly. 
- */
-void get_remote_struct(int pid, void *src, void *dst, size_t size)
-{
-    unsigned int i;
+    va_list ap;
+    va_start(ap, fmt);
 
-    for (i = 0; i+4 <= size; i+=4) {
-        *(int *)((char *)dst+i) = ptrace(PTRACE_PEEKTEXT, pid, (char *)src+i, NULL);
+    if (tfd >= 0) {
+        int len;
+        vsnprintf(buf, sizeof(buf), fmt, ap);
+        len = strlen(buf);
+        if(tfd >= 0) write(tfd, buf, len);
     }
 
-    if (i < size) {
-        int val;
-
-        assert((size - i) < 4);
-        val = ptrace(PTRACE_PEEKTEXT, pid, (char *)src+i, NULL);
-        while (i < size) {
-            ((unsigned char *)dst)[i] = val & 0xff;
-            i++;
-            val >>= 8;
-        }
-    }
+    if (!in_tombstone_only)
+        __android_log_vprint(ANDROID_LOG_INFO, "DEBUG", fmt, ap);
+    va_end(ap);
 }
 
-/* Map a pc address to the name of the containing ELF file */
-const char *map_to_name(mapinfo *mi, unsigned pc, const char* def)
-{
-    while(mi) {
-        if((pc >= mi->start) && (pc < mi->end)){
-            return mi->name;
-        }
-        mi = mi->next;
-    }
-    return def;
-}
-
-/* Find the containing map info for the pc */
-const mapinfo *pc_to_mapinfo(mapinfo *mi, unsigned pc, unsigned *rel_pc)
-{
-    *rel_pc = pc;
-    while(mi) {
-        if((pc >= mi->start) && (pc < mi->end)){
-            // Only calculate the relative offset for shared libraries
-            if (strstr(mi->name, ".so")) {
-                *rel_pc -= mi->start;
-            }
-            return mi;
-        }
-        mi = mi->next;
-    }
-    return NULL;
-}
-
-/*
- * Returns true if the specified signal has an associated address (i.e. it
- * sets siginfo_t.si_addr).
- */
-bool signal_has_address(int sig)
-{
+bool signal_has_address(int sig) {
     switch (sig) {
         case SIGILL:
         case SIGFPE:
@@ -100,3 +56,254 @@
             return false;
     }
 }
+
+static void dump_backtrace(const ptrace_context_t* context __attribute((unused)),
+        int tfd, pid_t tid __attribute((unused)), bool at_fault,
+        const backtrace_frame_t* backtrace, size_t frames) {
+    _LOG(tfd, !at_fault, "\nbacktrace:\n");
+
+    backtrace_symbol_t backtrace_symbols[STACK_DEPTH];
+    get_backtrace_symbols_ptrace(context, backtrace, frames, backtrace_symbols);
+    for (size_t i = 0; i < frames; i++) {
+        char line[MAX_BACKTRACE_LINE_LENGTH];
+        format_backtrace_line(i, &backtrace[i], &backtrace_symbols[i],
+                line, MAX_BACKTRACE_LINE_LENGTH);
+        _LOG(tfd, !at_fault, "    %s\n", line);
+    }
+    free_backtrace_symbols(backtrace_symbols, frames);
+}
+
+static void dump_stack_segment(const ptrace_context_t* context, int tfd, pid_t tid,
+        bool only_in_tombstone, uintptr_t* sp, size_t words, int label) {
+    for (size_t i = 0; i < words; i++) {
+        uint32_t stack_content;
+        if (!try_get_word_ptrace(tid, *sp, &stack_content)) {
+            break;
+        }
+
+        const map_info_t* mi;
+        const symbol_t* symbol;
+        find_symbol_ptrace(context, stack_content, &mi, &symbol);
+
+        if (symbol) {
+            char* demangled_name = demangle_symbol_name(symbol->name);
+            const char* symbol_name = demangled_name ? demangled_name : symbol->name;
+            uint32_t offset = stack_content - (mi->start + symbol->start);
+            if (!i && label >= 0) {
+                if (offset) {
+                    _LOG(tfd, only_in_tombstone, "    #%02d  %08x  %08x  %s (%s+%u)\n",
+                            label, *sp, stack_content, mi ? mi->name : "", symbol_name, offset);
+                } else {
+                    _LOG(tfd, only_in_tombstone, "    #%02d  %08x  %08x  %s (%s)\n",
+                            label, *sp, stack_content, mi ? mi->name : "", symbol_name);
+                }
+            } else {
+                if (offset) {
+                    _LOG(tfd, only_in_tombstone, "         %08x  %08x  %s (%s+%u)\n",
+                            *sp, stack_content, mi ? mi->name : "", symbol_name, offset);
+                } else {
+                    _LOG(tfd, only_in_tombstone, "         %08x  %08x  %s (%s)\n",
+                            *sp, stack_content, mi ? mi->name : "", symbol_name);
+                }
+            }
+            free(demangled_name);
+        } else {
+            if (!i && label >= 0) {
+                _LOG(tfd, only_in_tombstone, "    #%02d  %08x  %08x  %s\n",
+                        label, *sp, stack_content, mi ? mi->name : "");
+            } else {
+                _LOG(tfd, only_in_tombstone, "         %08x  %08x  %s\n",
+                        *sp, stack_content, mi ? mi->name : "");
+            }
+        }
+
+        *sp += sizeof(uint32_t);
+    }
+}
+
+static void dump_stack(const ptrace_context_t* context, int tfd, pid_t tid, bool at_fault,
+        const backtrace_frame_t* backtrace, size_t frames) {
+    bool have_first = false;
+    size_t first, last;
+    for (size_t i = 0; i < frames; i++) {
+        if (backtrace[i].stack_top) {
+            if (!have_first) {
+                have_first = true;
+                first = i;
+            }
+            last = i;
+        }
+    }
+    if (!have_first) {
+        return;
+    }
+
+    _LOG(tfd, !at_fault, "\nstack:\n");
+
+    // Dump a few words before the first frame.
+    bool only_in_tombstone = !at_fault;
+    uintptr_t sp = backtrace[first].stack_top - STACK_WORDS * sizeof(uint32_t);
+    dump_stack_segment(context, tfd, tid, only_in_tombstone, &sp, STACK_WORDS, -1);
+
+    // Dump a few words from all successive frames.
+    // Only log the first 3 frames, put the rest in the tombstone.
+    for (size_t i = first; i <= last; i++) {
+        const backtrace_frame_t* frame = &backtrace[i];
+        if (sp != frame->stack_top) {
+            _LOG(tfd, only_in_tombstone, "         ........  ........\n");
+            sp = frame->stack_top;
+        }
+        if (i - first == 3) {
+            only_in_tombstone = true;
+        }
+        if (i == last) {
+            dump_stack_segment(context, tfd, tid, only_in_tombstone, &sp, STACK_WORDS, i);
+            if (sp < frame->stack_top + frame->stack_size) {
+                _LOG(tfd, only_in_tombstone, "         ........  ........\n");
+            }
+        } else {
+            size_t words = frame->stack_size / sizeof(uint32_t);
+            if (words == 0) {
+                words = 1;
+            } else if (words > STACK_WORDS) {
+                words = STACK_WORDS;
+            }
+            dump_stack_segment(context, tfd, tid, only_in_tombstone, &sp, words, i);
+        }
+    }
+}
+
+void dump_backtrace_and_stack(const ptrace_context_t* context, int tfd, pid_t tid,
+        bool at_fault) {
+    backtrace_frame_t backtrace[STACK_DEPTH];
+    ssize_t frames = unwind_backtrace_ptrace(tid, context, backtrace, 0, STACK_DEPTH);
+    if (frames > 0) {
+        dump_backtrace(context, tfd, tid, at_fault, backtrace, frames);
+        dump_stack(context, tfd, tid, at_fault, backtrace, frames);
+    }
+}
+
+void dump_memory(int tfd, pid_t tid, uintptr_t addr, bool at_fault) {
+    char code_buffer[64];       /* actual 8+1+((8+1)*4) + 1 == 45 */
+    char ascii_buffer[32];      /* actual 16 + 1 == 17 */
+    uintptr_t p, end;
+
+    p = addr & ~3;
+    p -= 32;
+    if (p > addr) {
+        /* catch underflow */
+        p = 0;
+    }
+    end = p + 80;
+    /* catch overflow; 'end - p' has to be multiples of 16 */
+    while (end < p)
+        end -= 16;
+
+    /* Dump the code around PC as:
+     *  addr     contents                             ascii
+     *  00008d34 ef000000 e8bd0090 e1b00000 512fff1e  ............../Q
+     *  00008d44 ea00b1f9 e92d0090 e3a070fc ef000000  ......-..p......
+     */
+    while (p < end) {
+        char* asc_out = ascii_buffer;
+
+        sprintf(code_buffer, "%08x ", p);
+
+        int i;
+        for (i = 0; i < 4; i++) {
+            /*
+             * If we see (data == -1 && errno != 0), we know that the ptrace
+             * call failed, probably because we're dumping memory in an
+             * unmapped or inaccessible page.  I don't know if there's
+             * value in making that explicit in the output -- it likely
+             * just complicates parsing and clarifies nothing for the
+             * enlightened reader.
+             */
+            long data = ptrace(PTRACE_PEEKTEXT, tid, (void*)p, NULL);
+            sprintf(code_buffer + strlen(code_buffer), "%08lx ", data);
+
+            int j;
+            for (j = 0; j < 4; j++) {
+                /*
+                 * Our isprint() allows high-ASCII characters that display
+                 * differently (often badly) in different viewers, so we
+                 * just use a simpler test.
+                 */
+                char val = (data >> (j*8)) & 0xff;
+                if (val >= 0x20 && val < 0x7f) {
+                    *asc_out++ = val;
+                } else {
+                    *asc_out++ = '.';
+                }
+            }
+            p += 4;
+        }
+        *asc_out = '\0';
+        _LOG(tfd, !at_fault, "    %s %s\n", code_buffer, ascii_buffer);
+    }
+}
+
+void dump_nearby_maps(const ptrace_context_t* context, int tfd, pid_t tid) {
+    siginfo_t si;
+    memset(&si, 0, sizeof(si));
+    if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si)) {
+        _LOG(tfd, false, "cannot get siginfo for %d: %s\n",
+                tid, strerror(errno));
+        return;
+    }
+    if (!signal_has_address(si.si_signo)) {
+        return;
+    }
+
+    uintptr_t addr = (uintptr_t) si.si_addr;
+    addr &= ~0xfff;     /* round to 4K page boundary */
+    if (addr == 0) {    /* null-pointer deref */
+        return;
+    }
+
+    _LOG(tfd, false, "\nmemory map around fault addr %08x:\n", (int)si.si_addr);
+
+    /*
+     * Search for a match, or for a hole where the match would be.  The list
+     * is backward from the file content, so it starts at high addresses.
+     */
+    bool found = false;
+    map_info_t* map = context->map_info_list;
+    map_info_t *next = NULL;
+    map_info_t *prev = NULL;
+    while (map != NULL) {
+        if (addr >= map->start && addr < map->end) {
+            found = true;
+            next = map->next;
+            break;
+        } else if (addr >= map->end) {
+            /* map would be between "prev" and this entry */
+            next = map;
+            map = NULL;
+            break;
+        }
+
+        prev = map;
+        map = map->next;
+    }
+
+    /*
+     * Show "next" then "match" then "prev" so that the addresses appear in
+     * ascending order (like /proc/pid/maps).
+     */
+    if (next != NULL) {
+        _LOG(tfd, false, "    %08x-%08x %s\n", next->start, next->end, next->name);
+    } else {
+        _LOG(tfd, false, "    (no map below)\n");
+    }
+    if (map != NULL) {
+        _LOG(tfd, false, "    %08x-%08x %s\n", map->start, map->end, map->name);
+    } else {
+        _LOG(tfd, false, "    (no map for address)\n");
+    }
+    if (prev != NULL) {
+        _LOG(tfd, false, "    %08x-%08x %s\n", prev->start, prev->end, prev->name);
+    } else {
+        _LOG(tfd, false, "    (no map above)\n");
+    }
+}
diff --git a/debuggerd/utility.h b/debuggerd/utility.h
index 4a935d2..39f91cb 100644
--- a/debuggerd/utility.h
+++ b/debuggerd/utility.h
@@ -15,50 +15,17 @@
 ** limitations under the License.
 */
 
-#ifndef __utility_h
-#define __utility_h
+#ifndef _DEBUGGERD_UTILITY_H
+#define _DEBUGGERD_UTILITY_H
 
 #include <stddef.h>
 #include <stdbool.h>
+#include <sys/types.h>
+#include <corkscrew/backtrace.h>
 
-#include "symbol_table.h"
-
-#ifndef PT_ARM_EXIDX
-#define PT_ARM_EXIDX    0x70000001      /* .ARM.exidx segment */
-#endif
-
-#define STACK_CONTENT_DEPTH 32
-
-typedef struct mapinfo {
-    struct mapinfo *next;
-    unsigned start;
-    unsigned end;
-    unsigned exidx_start;
-    unsigned exidx_end;
-    struct symbol_table *symbols;
-    bool isExecutable;
-    char name[];
-} mapinfo;
-
-/* Get a word from pid using ptrace. The result is the return value. */
-extern int get_remote_word(int pid, void *src);
-
-/* Handy routine to read aggregated data from pid using ptrace. The read 
- * values are written to the dest locations directly. 
- */
-extern void get_remote_struct(int pid, void *src, void *dst, size_t size);
-
-/* Find the containing map for the pc */
-const mapinfo *pc_to_mapinfo (mapinfo *mi, unsigned pc, unsigned *rel_pc);
-
-/* Map a pc address to the name of the containing ELF file */
-const char *map_to_name(mapinfo *mi, unsigned pc, const char* def);
-
-/* Log information onto the tombstone */
-extern void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...);
-
-/* Determine whether si_addr is valid for this signal */
-bool signal_has_address(int sig);
+/* Log information onto the tombstone. */
+void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...)
+        __attribute__ ((format(printf, 3, 4)));
 
 #define LOG(fmt...) _LOG(-1, 0, fmt)
 
@@ -76,4 +43,30 @@
 #define XLOG2(fmt...) do {} while(0)
 #endif
 
-#endif
+/*
+ * Returns true if the specified signal has an associated address.
+ * (i.e. it sets siginfo_t.si_addr).
+ */
+bool signal_has_address(int sig);
+
+/*
+ * Dumps the backtrace and contents of the stack.
+ */
+void dump_backtrace_and_stack(const ptrace_context_t* context, int tfd, pid_t tid, bool at_fault);
+
+/*
+ * Dumps a few bytes of memory, starting a bit before and ending a bit
+ * after the specified address.
+ */
+void dump_memory(int tfd, pid_t tid, uintptr_t addr, bool at_fault);
+
+/*
+ * If this isn't clearly a null pointer dereference, dump the
+ * /proc/maps entries near the fault address.
+ *
+ * This only makes sense to do on the thread that crashed.
+ */
+void dump_nearby_maps(const ptrace_context_t* context, int tfd, pid_t tid);
+
+
+#endif // _DEBUGGERD_UTILITY_H
diff --git a/debuggerd/x86/machine.c b/debuggerd/x86/machine.c
index 9d418cf..2729c7e 100644
--- a/debuggerd/x86/machine.c
+++ b/debuggerd/x86/machine.c
@@ -31,31 +31,43 @@
 #include <cutils/sockets.h>
 #include <cutils/properties.h>
 
+#include <corkscrew/backtrace.h>
+#include <corkscrew/ptrace.h>
+
 #include <linux/input.h>
 
+#include "../machine.h"
 #include "../utility.h"
-#include "x86_utility.h"
 
-void dump_registers(int tfd, int pid, bool at_fault)
-{
+static void dump_registers(const ptrace_context_t* context __attribute((unused)),
+        int tfd, pid_t tid, bool at_fault) {
     struct pt_regs_x86 r;
     bool only_in_tombstone = !at_fault;
 
-    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) {
-        _LOG(tfd, only_in_tombstone,
-             "cannot get registers: %s\n", strerror(errno));
+    if(ptrace(PTRACE_GETREGS, tid, 0, &r)) {
+        _LOG(tfd, only_in_tombstone, "cannot get registers: %s\n", strerror(errno));
         return;
     }
-//if there is no stack, no print just like arm
+    //if there is no stack, no print just like arm
     if(!r.ebp)
         return;
-    _LOG(tfd, only_in_tombstone, " eax %08x  ebx %08x  ecx %08x  edx %08x\n",
+    _LOG(tfd, only_in_tombstone, "    eax %08x  ebx %08x  ecx %08x  edx %08x\n",
          r.eax, r.ebx, r.ecx, r.edx);
-    _LOG(tfd, only_in_tombstone, " esi %08x  edi %08x\n",
+    _LOG(tfd, only_in_tombstone, "    esi %08x  edi %08x\n",
          r.esi, r.edi);
-    _LOG(tfd, only_in_tombstone, " xcs %08x  xds %08x  xes %08x  xfs %08x xss %08x\n",
+    _LOG(tfd, only_in_tombstone, "    xcs %08x  xds %08x  xes %08x  xfs %08x  xss %08x\n",
          r.xcs, r.xds, r.xes, r.xfs, r.xss);
-    _LOG(tfd, only_in_tombstone,
-         " eip %08x  ebp %08x  esp %08x  flags %08x\n",
+    _LOG(tfd, only_in_tombstone, "    eip %08x  ebp %08x  esp %08x  flags %08x\n",
          r.eip, r.ebp, r.esp, r.eflags);
 }
+
+void dump_thread(const ptrace_context_t* context, int tfd, pid_t tid, bool at_fault) {
+    dump_registers(context, tfd, tid, at_fault);
+
+    dump_backtrace_and_stack(context, tfd, tid, at_fault);
+
+    if (at_fault) {
+        dump_nearby_maps(context, tfd, tid);
+    }
+}
+
diff --git a/debuggerd/x86/unwind.c b/debuggerd/x86/unwind.c
deleted file mode 100644
index 0a7f04c..0000000
--- a/debuggerd/x86/unwind.c
+++ /dev/null
@@ -1,86 +0,0 @@
-#include <cutils/logd.h>
-#include <sys/ptrace.h>
-#include "../utility.h"
-#include "x86_utility.h"
-
-
-int unwind_backtrace_with_ptrace_x86(int tfd, pid_t pid, mapinfo *map,
-                                 bool at_fault)
-{
-    struct pt_regs_x86 r;
-    unsigned int stack_level = 0;
-    unsigned int stack_depth = 0;
-    unsigned int rel_pc;
-    unsigned int stack_ptr;
-    unsigned int stack_content;
-
-    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) return 0;
-    unsigned int eip = (unsigned int)r.eip;
-    unsigned int ebp = (unsigned int)r.ebp;
-    unsigned int cur_sp = (unsigned int)r.esp;
-    const mapinfo *mi;
-    const struct symbol* sym = 0;
-
-
-//ebp==0, it indicates that the stack is poped to the bottom or there is no stack at all.
-    while (ebp) {
-        mi = pc_to_mapinfo(map, eip, &rel_pc);
-
-        /* See if we can determine what symbol this stack frame resides in */
-        if (mi != 0 && mi->symbols != 0) {
-            sym = symbol_table_lookup(mi->symbols, rel_pc);
-        }
-        if (sym) {
-            _LOG(tfd, !at_fault, "    #%02d  eip: %08x  %s (%s)\n",
-                 stack_level, eip, mi ? mi->name : "", sym->name);
-        } else {
-            _LOG(tfd, !at_fault, "    #%02d  eip: %08x  %s\n",
-                 stack_level, eip, mi ? mi->name : "");
-        }
-
-        stack_level++;
-        if (stack_level >= STACK_DEPTH || eip == 0)
-            break;
-        eip = ptrace(PTRACE_PEEKTEXT, pid, (void*)(ebp + 4), NULL);
-        ebp = ptrace(PTRACE_PEEKTEXT, pid, (void*)ebp, NULL);
-    }
-    ebp = (unsigned int)r.ebp;
-    stack_depth = stack_level;
-    stack_level = 0;
-    if (ebp)
-        _LOG(tfd, !at_fault, "stack: \n");
-    while (ebp) {
-        stack_ptr = cur_sp;
-        while((int)(ebp - stack_ptr) >= 0) {
-            stack_content = ptrace(PTRACE_PEEKTEXT, pid, (void*)stack_ptr, NULL);
-            mi = pc_to_mapinfo(map, stack_content, &rel_pc);
-
-            /* See if we can determine what symbol this stack frame resides in */
-            if (mi != 0 && mi->symbols != 0) {
-                sym = symbol_table_lookup(mi->symbols, rel_pc);
-            }
-            if (sym) {
-                _LOG(tfd, !at_fault, "    #%02d  %08x  %08x  %s (%s)\n",
-                     stack_level, stack_ptr, stack_content, mi ? mi->name : "", sym->name);
-            } else {
-                _LOG(tfd, !at_fault, "    #%02d  %08x  %08x  %s\n",
-                     stack_level, stack_ptr, stack_content, mi ? mi->name : "");
-            }
-
-            stack_ptr = stack_ptr + 4;
-            //the stack frame may be very deep.
-            if((int)(stack_ptr - cur_sp) >= STACK_FRAME_DEPTH) {
-                _LOG(tfd, !at_fault, "    ......  ......  \n");
-                break;
-            }
-        }
-        cur_sp = ebp + 4;
-        stack_level++;
-        if (stack_level >= STACK_DEPTH || stack_level >= stack_depth)
-            break;
-        ebp = ptrace(PTRACE_PEEKTEXT, pid, (void*)ebp, NULL);
-    }
-
-    return stack_depth;
-}
-
diff --git a/debuggerd/x86/x86_utility.h b/debuggerd/x86/x86_utility.h
deleted file mode 100644
index ac6a885..0000000
--- a/debuggerd/x86/x86_utility.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
-**
-** Copyright 2006, 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.
-*/
-
-#define STACK_DEPTH 8
-#define STACK_FRAME_DEPTH 64
-
-typedef struct pt_regs_x86 {
-    long ebx;
-    long ecx;
-    long edx;
-    long esi;
-    long edi;
-    long ebp;
-    long eax;
-    int  xds;
-    int  xes;
-    int  xfs;
-    int  xgs;
-    long orig_eax;
-    long eip;
-    int  xcs;
-    long eflags;
-    long esp;
-    int  xss;
-}pt_regs_x86;
-
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index 3c5538f..8c130ff 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -16,8 +16,9 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/../mkbootimg
-LOCAL_SRC_FILES := protocol.c engine.c bootimg.c fastboot.c 
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/../mkbootimg \
+  $(LOCAL_PATH)/../../extras/ext4_utils
+LOCAL_SRC_FILES := protocol.c engine.c bootimg.c fastboot.c
 LOCAL_MODULE := fastboot
 
 ifeq ($(HOST_OS),linux)
@@ -47,7 +48,7 @@
   LOCAL_C_INCLUDES += development/host/windows/usb/api
 endif
 
-LOCAL_STATIC_LIBRARIES := $(EXTRA_STATIC_LIBS) libzipfile libunz
+LOCAL_STATIC_LIBRARIES := $(EXTRA_STATIC_LIBS) libzipfile libunz libext4_utils libz
 
 include $(BUILD_HOST_EXECUTABLE)
 $(call dist-for-goals,dist_files,$(LOCAL_BUILT_MODULE))
diff --git a/fastboot/engine.c b/fastboot/engine.c
index 6d94035..0e6594c 100644
--- a/fastboot/engine.c
+++ b/fastboot/engine.c
@@ -26,13 +26,29 @@
  * SUCH DAMAGE.
  */
 
+#include "fastboot.h"
+#include "make_ext4fs.h"
+#include "ext4_utils.h"
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdarg.h>
+#include <stdbool.h>
 #include <string.h>
+#include <sys/stat.h>
 #include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
 
-#include "fastboot.h"
+#ifdef USE_MINGW
+#include <fcntl.h>
+#else
+#include <sys/mman.h>
+#endif
+
+extern struct fs_info info;
+
+#define ARRAY_SIZE(x)           (sizeof(x)/sizeof(x[0]))
 
 double now()
 {
@@ -60,15 +76,18 @@
 #define OP_COMMAND    2
 #define OP_QUERY      3
 #define OP_NOTICE     4
+#define OP_FORMAT     5
 
 typedef struct Action Action;
 
+#define CMD_SIZE 64
+
 struct Action 
 {
     unsigned op;
     Action *next;
 
-    char cmd[64];    
+    char cmd[CMD_SIZE];
     const char *prod;
     void *data;
     unsigned size;
@@ -82,6 +101,35 @@
 static Action *action_list = 0;
 static Action *action_last = 0;
 
+
+struct image_data {
+    long long partition_size;
+    long long image_size; // real size of image file
+    void *buffer;
+};
+
+void generate_ext4_image(struct image_data *image);
+void cleanup_image(struct image_data *image);
+
+struct generator {
+    char *fs_type;
+
+    /* generate image and return it as image->buffer.
+     * size of the buffer returned as image->image_size.
+     *
+     * image->partition_size specifies what is the size of the
+     * file partition we generate image for.
+     */
+    void (*generate)(struct image_data *image);
+
+    /* it cleans the buffer allocated during image creation.
+     * this function probably does free() or munmap().
+     */
+    void (*cleanup)(struct image_data *image);
+} generators[] = {
+    { "ext4", generate_ext4_image, cleanup_image }
+};
+
 static int cb_default(Action *a, int status, char *resp)
 {
     if (status) {
@@ -133,6 +181,162 @@
     a->msg = mkmsg("erasing '%s'", ptn);
 }
 
+/* Loads file content into buffer. Returns NULL on error. */
+static void *load_buffer(int fd, off_t size)
+{
+    void *buffer;
+
+#ifdef USE_MINGW
+    ssize_t count = 0;
+
+    // mmap is more efficient but mingw does not support it.
+    // In this case we read whole image into memory buffer.
+    buffer = malloc(size);
+    if (!buffer) {
+        perror("malloc");
+        return NULL;
+    }
+
+    lseek(fd, 0, SEEK_SET);
+    while(count < size) {
+        ssize_t actually_read = read(fd, (char*)buffer+count, size-count);
+
+        if (actually_read == 0) {
+            break;
+        }
+        if (actually_read < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+            perror("read");
+            free(buffer);
+            return NULL;
+        }
+
+        count += actually_read;
+    }
+#else
+    buffer = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
+    if (buffer == MAP_FAILED) {
+        perror("mmap");
+        return NULL;
+    }
+#endif
+
+    return buffer;
+}
+
+void cleanup_image(struct image_data *image)
+{
+#ifdef USE_MINGW
+    free(image->buffer);
+#else
+    munmap(image->buffer, image->image_size);
+#endif
+}
+
+void generate_ext4_image(struct image_data *image)
+{
+    int fd;
+    struct stat st;
+
+#ifdef USE_MINGW
+    /* Ideally we should use tmpfile() here, the same as with unix version.
+     * But unfortunately it is not portable as it is not clear whether this
+     * function opens file in TEXT or BINARY mode.
+     *
+     * There are also some reports it is buggy:
+     *    http://pdplab.it.uom.gr/teaching/gcc_manuals/gnulib.html#tmpfile
+     *    http://www.mega-nerd.com/erikd/Blog/Windiots/tmpfile.html
+     */
+    char *filename = tempnam(getenv("TEMP"), "fastboot-format.img");
+    fd = open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0644);
+    unlink(filename);
+#else
+    fd = fileno(tmpfile());
+#endif
+    reset_ext4fs_info();
+    info.len = image->partition_size;
+    make_ext4fs_internal(fd, NULL, NULL, 0, 0, 1, 0, 0, 0);
+
+    fstat(fd, &st);
+    image->image_size = st.st_size;
+    image->buffer = load_buffer(fd, st.st_size);
+
+    close(fd);
+}
+
+int fb_format(Action *a, usb_handle *usb)
+{
+    const char *partition = a->cmd;
+    char response[FB_RESPONSE_SZ+1];
+    int status = 0;
+    struct image_data image;
+    struct generator *generator = NULL;
+    int fd;
+    unsigned i;
+    char cmd[CMD_SIZE];
+
+    response[FB_RESPONSE_SZ] = '\0';
+    snprintf(cmd, sizeof(cmd), "getvar:partition-type:%s", partition);
+    status = fb_command_response(usb, cmd, response);
+    if (status) {
+        fprintf(stderr,"FAILED (%s)\n", fb_get_error());
+        return status;
+    }
+
+    for (i = 0; i < ARRAY_SIZE(generators); i++) {
+        if (!strncmp(generators[i].fs_type, response, FB_RESPONSE_SZ)) {
+            generator = &generators[i];
+            break;
+        }
+    }
+    if (!generator) {
+        fprintf(stderr,"Formatting is not supported for filesystem with type '%s'.\n",
+                response);
+        return -1;
+    }
+
+    response[FB_RESPONSE_SZ] = '\0';
+    snprintf(cmd, sizeof(cmd), "getvar:partition-size:%s", partition);
+    status = fb_command_response(usb, cmd, response);
+    if (status) {
+        fprintf(stderr,"FAILED (%s)\n", fb_get_error());
+        return status;
+    }
+    image.partition_size = strtoll(response, (char **)NULL, 16);
+
+    generator->generate(&image);
+    if (!image.buffer) {
+        fprintf(stderr,"Cannot generate image.\n");
+        return -1;
+    }
+
+    // Following piece of code is similar to fb_queue_flash() but executes
+    // actions directly without queuing
+    fprintf(stderr, "sending '%s' (%lli KB)...\n", partition, image.image_size/1024);
+    status = fb_download_data(usb, image.buffer, image.image_size);
+    if (status) goto cleanup;
+
+    fprintf(stderr, "writing '%s'...\n", partition);
+    snprintf(cmd, sizeof(cmd), "flash:%s", partition);
+    status = fb_command(usb, cmd);
+    if (status) goto cleanup;
+
+cleanup:
+    generator->cleanup(&image);
+
+    return status;
+}
+
+void fb_queue_format(const char *partition)
+{
+    Action *a;
+
+    a = queue_action(OP_FORMAT, partition);
+    a->msg = mkmsg("formatting '%s' partition", partition);
+}
+
 void fb_queue_flash(const char *ptn, void *data, unsigned sz)
 {
     Action *a;
@@ -340,6 +544,10 @@
             if (status) break;
         } else if (a->op == OP_NOTICE) {
             fprintf(stderr,"%s\n",(char*)a->data);
+        } else if (a->op == OP_FORMAT) {
+            status = fb_format(a, usb);
+            status = a->func(a, status, status ? fb_get_error() : "");
+            if (status) break;
         } else {
             die("bogus action");
         }
diff --git a/fastboot/fastboot.c b/fastboot/fastboot.c
index 8610ca1..af61f88 100644
--- a/fastboot/fastboot.c
+++ b/fastboot/fastboot.c
@@ -88,6 +88,8 @@
         fn = "system.img";
     } else if(!strcmp(item,"userdata")) {
         fn = "userdata.img";
+    } else if(!strcmp(item,"cache")) {
+        fn = "cache.img";
     } else if(!strcmp(item,"info")) {
         fn = "android-info.txt";
     } else {
@@ -224,6 +226,7 @@
             "  flashall                                 flash boot + recovery + system\n"
             "  flash <partition> [ <filename> ]         write a file to a flash partition\n"
             "  erase <partition>                        erase a flash partition\n"
+            "  format <partition>                       format a flash partition \n"
             "  getvar <variable>                        display a bootloader variable\n"
             "  boot <kernel> [ <ramdisk> ]              download and boot kernel\n"
             "  flash:raw boot <kernel> [ <ramdisk> ]    create bootimage and flash it\n"
@@ -635,6 +638,10 @@
             require(2);
             fb_queue_erase(argv[1]);
             skip(2);
+        } else if(!strcmp(*argv, "format")) {
+            require(2);
+            fb_queue_format(argv[1]);
+            skip(2);
         } else if(!strcmp(*argv, "signature")) {
             require(2);
             data = load_file(argv[1], &sz);
diff --git a/fastboot/fastboot.h b/fastboot/fastboot.h
index 9e043fe..c2f97a2 100644
--- a/fastboot/fastboot.h
+++ b/fastboot/fastboot.h
@@ -43,6 +43,7 @@
 /* engine.c - high level command queue engine */
 void fb_queue_flash(const char *ptn, void *data, unsigned sz);;
 void fb_queue_erase(const char *ptn);
+void fb_queue_format(const char *ptn);
 void fb_queue_require(const char *prod, const char *var, int invert,
         unsigned nvalues, const char **value);
 void fb_queue_display(const char *var, const char *prettyname);
diff --git a/include/arch/darwin-x86/AndroidConfig.h b/include/arch/darwin-x86/AndroidConfig.h
index c8ccc7e..f79f364 100644
--- a/include/arch/darwin-x86/AndroidConfig.h
+++ b/include/arch/darwin-x86/AndroidConfig.h
@@ -109,7 +109,7 @@
 /*
  * Define this if we have localtime_r().
  */
-#define HAVE_LOCALTIME_R
+#define HAVE_LOCALTIME_R 1
 
 /*
  * Define this if we have gethostbyname_r().
diff --git a/include/arch/freebsd-x86/AndroidConfig.h b/include/arch/freebsd-x86/AndroidConfig.h
index d828bd5..a8176f4 100644
--- a/include/arch/freebsd-x86/AndroidConfig.h
+++ b/include/arch/freebsd-x86/AndroidConfig.h
@@ -114,7 +114,7 @@
 /*
  * Define this if we have localtime_r().
  */
-#define HAVE_LOCALTIME_R
+#define HAVE_LOCALTIME_R 1
 
 /*
  * Define this if we have gethostbyname_r().
diff --git a/include/arch/linux-arm/AndroidConfig.h b/include/arch/linux-arm/AndroidConfig.h
index cae112b..e1ce0e0 100644
--- a/include/arch/linux-arm/AndroidConfig.h
+++ b/include/arch/linux-arm/AndroidConfig.h
@@ -122,7 +122,7 @@
 /*
  * Define this if we have localtime_r().
  */
-/* #define HAVE_LOCALTIME_R */
+/* #define HAVE_LOCALTIME_R 1 */
 
 /*
  * Define this if we have gethostbyname_r().
diff --git a/include/arch/linux-ppc/AndroidConfig.h b/include/arch/linux-ppc/AndroidConfig.h
index 00706dc..b9719e6 100644
--- a/include/arch/linux-ppc/AndroidConfig.h
+++ b/include/arch/linux-ppc/AndroidConfig.h
@@ -109,7 +109,7 @@
 /*
  * Define this if we have localtime_r().
  */
-#define HAVE_LOCALTIME_R
+#define HAVE_LOCALTIME_R 1
 
 /*
  * Define this if we have gethostbyname_r().
diff --git a/include/arch/linux-sh/AndroidConfig.h b/include/arch/linux-sh/AndroidConfig.h
index 5562eae..a040b98 100644
--- a/include/arch/linux-sh/AndroidConfig.h
+++ b/include/arch/linux-sh/AndroidConfig.h
@@ -122,7 +122,7 @@
 /*
  * Define this if we have localtime_r().
  */
-/* #define HAVE_LOCALTIME_R */
+/* #define HAVE_LOCALTIME_R 1 */
 
 /*
  * Define this if we have gethostbyname_r().
diff --git a/include/arch/linux-x86/AndroidConfig.h b/include/arch/linux-x86/AndroidConfig.h
index 7dcaa98..82e538c 100644
--- a/include/arch/linux-x86/AndroidConfig.h
+++ b/include/arch/linux-x86/AndroidConfig.h
@@ -109,7 +109,7 @@
 /*
  * Define this if we have localtime_r().
  */
-#define HAVE_LOCALTIME_R
+#define HAVE_LOCALTIME_R 1
 
 /*
  * Define this if we have gethostbyname_r().
diff --git a/include/arch/target_linux-x86/AndroidConfig.h b/include/arch/target_linux-x86/AndroidConfig.h
index 05dd220..9efb81a 100644
--- a/include/arch/target_linux-x86/AndroidConfig.h
+++ b/include/arch/target_linux-x86/AndroidConfig.h
@@ -108,7 +108,7 @@
 /*
  * Define this if we have localtime_r().
  */
-/* #define HAVE_LOCALTIME_R */
+/* #define HAVE_LOCALTIME_R 1 */
 
 /*
  * Define this if we have gethostbyname_r().
diff --git a/include/arch/windows/AndroidConfig.h b/include/arch/windows/AndroidConfig.h
index ad890b4..445e754 100644
--- a/include/arch/windows/AndroidConfig.h
+++ b/include/arch/windows/AndroidConfig.h
@@ -125,7 +125,7 @@
 /*
  * Define this if we have localtime_r().
  */
-/* #define HAVE_LOCALTIME_R */
+/* #define HAVE_LOCALTIME_R 1 */
 
 /*
  * Define this if we have gethostbyname_r().
diff --git a/include/corkscrew/backtrace.h b/include/corkscrew/backtrace.h
new file mode 100644
index 0000000..556ad04
--- /dev/null
+++ b/include/corkscrew/backtrace.h
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/* A stack unwinder. */
+
+#ifndef _CORKSCREW_BACKTRACE_H
+#define _CORKSCREW_BACKTRACE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <sys/types.h>
+#include <corkscrew/ptrace.h>
+#include <corkscrew/map_info.h>
+#include <corkscrew/symbol_table.h>
+
+/*
+ * Describes a single frame of a backtrace.
+ */
+typedef struct {
+    uintptr_t absolute_pc;     /* absolute PC offset */
+    uintptr_t stack_top;       /* top of stack for this frame */
+    size_t stack_size;         /* size of this stack frame */
+} backtrace_frame_t;
+
+/*
+ * Describes the symbols associated with a backtrace frame.
+ */
+typedef struct {
+    uintptr_t relative_pc;       /* relative frame PC offset from the start of the library,
+                                    or the absolute PC if the library is unknown */
+    uintptr_t relative_symbol_addr; /* relative offset of the symbol from the start of the
+                                    library or 0 if the library is unknown */
+    char* map_name;              /* executable or library name, or NULL if unknown */
+    char* symbol_name;           /* symbol name, or NULL if unknown */
+    char* demangled_name;        /* demangled symbol name, or NULL if unknown */
+} backtrace_symbol_t;
+
+/*
+ * Unwinds the call stack for the current thread of execution.
+ * Populates the backtrace array with the program counters from the call stack.
+ * Returns the number of frames collected, or -1 if an error occurred.
+ */
+ssize_t unwind_backtrace(backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth);
+
+/*
+ * Unwinds the call stack for a thread within this process.
+ * Populates the backtrace array with the program counters from the call stack.
+ * Returns the number of frames collected, or -1 if an error occurred.
+ *
+ * The task is briefly suspended while the backtrace is being collected.
+ */
+ssize_t unwind_backtrace_thread(pid_t tid, backtrace_frame_t* backtrace,
+        size_t ignore_depth, size_t max_depth);
+
+/*
+ * Unwinds the call stack of a task within a remote process using ptrace().
+ * Populates the backtrace array with the program counters from the call stack.
+ * Returns the number of frames collected, or -1 if an error occurred.
+ */
+ssize_t unwind_backtrace_ptrace(pid_t tid, const ptrace_context_t* context,
+        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth);
+
+/*
+ * Gets the symbols for each frame of a backtrace.
+ * The symbols array must be big enough to hold one symbol record per frame.
+ * The symbols must later be freed using free_backtrace_symbols.
+ */
+void get_backtrace_symbols(const backtrace_frame_t* backtrace, size_t frames,
+        backtrace_symbol_t* backtrace_symbols);
+
+/*
+ * Gets the symbols for each frame of a backtrace from a remote process.
+ * The symbols array must be big enough to hold one symbol record per frame.
+ * The symbols must later be freed using free_backtrace_symbols.
+ */
+void get_backtrace_symbols_ptrace(const ptrace_context_t* context,
+        const backtrace_frame_t* backtrace, size_t frames,
+        backtrace_symbol_t* backtrace_symbols);
+
+/*
+ * Frees the storage associated with backtrace symbols.
+ */
+void free_backtrace_symbols(backtrace_symbol_t* backtrace_symbols, size_t frames);
+
+enum {
+    // A hint for how big to make the line buffer for format_backtrace_line
+    MAX_BACKTRACE_LINE_LENGTH = 800,
+};
+
+/**
+ * Formats a line from a backtrace as a zero-terminated string into the specified buffer.
+ */
+void format_backtrace_line(unsigned frameNumber, const backtrace_frame_t* frame,
+        const backtrace_symbol_t* symbol, char* buffer, size_t bufferSize);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CORKSCREW_BACKTRACE_H
diff --git a/include/corkscrew/demangle.h b/include/corkscrew/demangle.h
new file mode 100644
index 0000000..04b0225
--- /dev/null
+++ b/include/corkscrew/demangle.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/* C++ symbol name demangling. */
+
+#ifndef _CORKSCREW_DEMANGLE_H
+#define _CORKSCREW_DEMANGLE_H
+
+#include <sys/types.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Demangles a C++ symbol name.
+ * If name is NULL or if the name cannot be demangled, returns NULL.
+ * Otherwise, returns a newly allocated string that contains the demangled name.
+ *
+ * The caller must free the returned string using free().
+ */
+char* demangle_symbol_name(const char* name);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CORKSCREW_DEMANGLE_H
diff --git a/include/corkscrew/map_info.h b/include/corkscrew/map_info.h
new file mode 100644
index 0000000..c5cd8f8
--- /dev/null
+++ b/include/corkscrew/map_info.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/* Process memory map. */
+
+#ifndef _CORKSCREW_MAP_INFO_H
+#define _CORKSCREW_MAP_INFO_H
+
+#include <sys/types.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct map_info {
+    struct map_info* next;
+    uintptr_t start;
+    uintptr_t end;
+    bool is_readable;
+    bool is_executable;
+    void* data; // arbitrary data associated with the map by the user, initially NULL
+    char name[];
+} map_info_t;
+
+/* Loads memory map from /proc/<tid>/maps. */
+map_info_t* load_map_info_list(pid_t tid);
+
+/* Frees memory map. */
+void free_map_info_list(map_info_t* milist);
+
+/* Finds the memory map that contains the specified address. */
+const map_info_t* find_map_info(const map_info_t* milist, uintptr_t addr);
+
+/* Returns true if the addr is in an readable map. */
+bool is_readable_map(const map_info_t* milist, uintptr_t addr);
+
+/* Returns true if the addr is in an executable map. */
+bool is_executable_map(const map_info_t* milist, uintptr_t addr);
+
+/* Acquires a reference to the memory map for this process.
+ * The result is cached and refreshed automatically.
+ * Make sure to release the map info when done. */
+map_info_t* acquire_my_map_info_list();
+
+/* Releases a reference to the map info for this process that was
+ * previous acquired using acquire_my_map_info_list(). */
+void release_my_map_info_list(map_info_t* milist);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CORKSCREW_MAP_INFO_H
diff --git a/include/corkscrew/ptrace.h b/include/corkscrew/ptrace.h
new file mode 100644
index 0000000..172e348
--- /dev/null
+++ b/include/corkscrew/ptrace.h
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/* Useful ptrace() utility functions. */
+
+#ifndef _CORKSCREW_PTRACE_H
+#define _CORKSCREW_PTRACE_H
+
+#include <corkscrew/map_info.h>
+#include <corkscrew/symbol_table.h>
+
+#include <sys/types.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Stores information about a process that is used for several different
+ * ptrace() based operations. */
+typedef struct {
+    map_info_t* map_info_list;
+} ptrace_context_t;
+
+/* Describes how to access memory from a process. */
+typedef struct {
+    pid_t tid;
+    const map_info_t* map_info_list;
+} memory_t;
+
+#if __i386__
+/* ptrace() register context. */
+typedef struct pt_regs_x86 {
+    uint32_t ebx;
+    uint32_t ecx;
+    uint32_t edx;
+    uint32_t esi;
+    uint32_t edi;
+    uint32_t ebp;
+    uint32_t eax;
+    uint32_t xds;
+    uint32_t xes;
+    uint32_t xfs;
+    uint32_t xgs;
+    uint32_t orig_eax;
+    uint32_t eip;
+    uint32_t xcs;
+    uint32_t eflags;
+    uint32_t esp;
+    uint32_t xss;
+} pt_regs_x86_t;
+#endif
+
+/*
+ * Initializes a memory structure for accessing memory from this process.
+ */
+void init_memory(memory_t* memory, const map_info_t* map_info_list);
+
+/*
+ * Initializes a memory structure for accessing memory from another process
+ * using ptrace().
+ */
+void init_memory_ptrace(memory_t* memory, pid_t tid);
+
+/*
+ * Reads a word of memory safely.
+ * If the memory is local, ensures that the address is readable before dereferencing it.
+ * Returns false and a value of 0xffffffff if the word could not be read.
+ */
+bool try_get_word(const memory_t* memory, uintptr_t ptr, uint32_t* out_value);
+
+/*
+ * Reads a word of memory safely using ptrace().
+ * Returns false and a value of 0xffffffff if the word could not be read.
+ */
+bool try_get_word_ptrace(pid_t tid, uintptr_t ptr, uint32_t* out_value);
+
+/*
+ * Loads information needed for examining a remote process using ptrace().
+ * The caller must already have successfully attached to the process
+ * using ptrace().
+ *
+ * The context can be used for any threads belonging to that process
+ * assuming ptrace() is attached to them before performing the actual
+ * unwinding.  The context can continue to be used to decode backtraces
+ * even after ptrace() has been detached from the process.
+ */
+ptrace_context_t* load_ptrace_context(pid_t pid);
+
+/*
+ * Frees a ptrace context.
+ */
+void free_ptrace_context(ptrace_context_t* context);
+
+/*
+ * Finds a symbol using ptrace.
+ * Returns the containing map and information about the symbol, or
+ * NULL if one or the other is not available.
+ */
+void find_symbol_ptrace(const ptrace_context_t* context,
+        uintptr_t addr, const map_info_t** out_map_info, const symbol_t** out_symbol);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CORKSCREW_PTRACE_H
diff --git a/include/corkscrew/symbol_table.h b/include/corkscrew/symbol_table.h
new file mode 100644
index 0000000..020c8b8
--- /dev/null
+++ b/include/corkscrew/symbol_table.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2011 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 _CORKSCREW_SYMBOL_TABLE_H
+#define _CORKSCREW_SYMBOL_TABLE_H
+
+#include <sys/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+    uintptr_t start;
+    uintptr_t end;
+    char* name;
+} symbol_t;
+
+typedef struct {
+    symbol_t* symbols;
+    size_t num_symbols;
+} symbol_table_t;
+
+/*
+ * Loads a symbol table from a given file.
+ * Returns NULL on error.
+ */
+symbol_table_t* load_symbol_table(const char* filename);
+
+/*
+ * Frees a symbol table.
+ */
+void free_symbol_table(symbol_table_t* table);
+
+/*
+ * Finds a symbol associated with an address in the symbol table.
+ * Returns NULL if not found.
+ */
+const symbol_t* find_symbol(const symbol_table_t* table, uintptr_t addr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CORKSCREW_SYMBOL_TABLE_H
diff --git a/include/cutils/log.h b/include/cutils/log.h
index 2997a0c..878952e 100644
--- a/include/cutils/log.h
+++ b/include/cutils/log.h
@@ -79,10 +79,6 @@
 #else
 #define ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
 #endif
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGV
-#define LOGV ALOGV
-#endif
 #endif
 
 #define CONDITION(cond)     (__builtin_expect((cond)!=0, 0))
@@ -96,10 +92,6 @@
     ? ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
 #endif
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGV_IF
-#define LOGV_IF ALOGV_IF
-#endif
 #endif
 
 /*
@@ -107,10 +99,6 @@
  */
 #ifndef ALOGD
 #define ALOGD(...) ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__))
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGD
-#define LOGD ALOGD
-#endif
 #endif
 
 #ifndef ALOGD_IF
@@ -118,10 +106,6 @@
     ( (CONDITION(cond)) \
     ? ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGD_IF
-#define LOGD_IF ALOGD_IF
-#endif
 #endif
 
 /*
@@ -129,10 +113,6 @@
  */
 #ifndef ALOGI
 #define ALOGI(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGI
-#define LOGI ALOGI
-#endif
 #endif
 
 #ifndef ALOGI_IF
@@ -140,10 +120,6 @@
     ( (CONDITION(cond)) \
     ? ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGI_IF
-#define LOGI_IF ALOGI_IF
-#endif
 #endif
 
 /*
@@ -151,10 +127,6 @@
  */
 #ifndef ALOGW
 #define ALOGW(...) ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__))
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGW
-#define LOGW ALOGW
-#endif
 #endif
 
 #ifndef ALOGW_IF
@@ -162,10 +134,6 @@
     ( (CONDITION(cond)) \
     ? ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGW_IF
-#define LOGW_IF ALOGW_IF
-#endif
 #endif
 
 /*
@@ -173,10 +141,6 @@
  */
 #ifndef ALOGE
 #define ALOGE(...) ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGE
-#define LOGE ALOGE
-#endif
 #endif
 
 #ifndef ALOGE_IF
@@ -184,10 +148,6 @@
     ( (CONDITION(cond)) \
     ? ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
-// Temporary measure for code still using old LOG macros.
-#ifndef LOGE_IF
-#define LOGE_IF ALOGE_IF
-#endif
 #endif
 
 // ---------------------------------------------------------------------
@@ -202,10 +162,6 @@
 #else
 #define IF_ALOGV() IF_ALOG(LOG_VERBOSE, LOG_TAG)
 #endif
-// Temporary measure for code still using old LOG macros.
-#ifndef IF_LOGV
-#define IF_LOGV IF_ALOGV
-#endif
 #endif
 
 /*
@@ -214,10 +170,6 @@
  */
 #ifndef IF_ALOGD
 #define IF_ALOGD() IF_ALOG(LOG_DEBUG, LOG_TAG)
-// Temporary measure for code still using old LOG macros.
-#ifndef IF_LOGD
-#define IF_LOGD IF_ALOGD
-#endif
 #endif
 
 /*
@@ -226,10 +178,6 @@
  */
 #ifndef IF_ALOGI
 #define IF_ALOGI() IF_ALOG(LOG_INFO, LOG_TAG)
-// Temporary measure for code still using old LOG macros.
-#ifndef IF_LOGI
-#define IF_LOGI IF_ALOGI
-#endif
 #endif
 
 /*
@@ -238,10 +186,6 @@
  */
 #ifndef IF_ALOGW
 #define IF_ALOGW() IF_ALOG(LOG_WARN, LOG_TAG)
-// Temporary measure for code still using old LOG macros.
-#ifndef IF_LOGW
-#define IF_LOGW IF_ALOGW
-#endif
 #endif
 
 /*
@@ -250,10 +194,6 @@
  */
 #ifndef IF_ALOGE
 #define IF_ALOGE() IF_ALOG(LOG_ERROR, LOG_TAG)
-// Temporary measure for code still using old LOG macros.
-#ifndef IF_LOGE
-#define IF_LOGE IF_ALOGE
-#endif
 #endif
 
 
@@ -392,10 +332,6 @@
 #ifndef ALOG_ASSERT
 #define ALOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ## __VA_ARGS__)
 //#define ALOG_ASSERT(cond) LOG_FATAL_IF(!(cond), "Assertion failed: " #cond)
-// Temporary measure for code still using old LOG macros.
-#ifndef LOG_ASSERT
-#define LOG_ASSERT ALOG_ASSERT
-#endif
 #endif
 
 // ---------------------------------------------------------------------
@@ -411,10 +347,6 @@
 #ifndef ALOG
 #define ALOG(priority, tag, ...) \
     LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
-// Temporary measure for code still using old LOG macros.
-#ifndef LOG
-#define LOG ALOG
-#endif
 #endif
 
 /*
@@ -439,10 +371,6 @@
 #ifndef IF_ALOG
 #define IF_ALOG(priority, tag) \
     if (android_testLog(ANDROID_##priority, tag))
-// Temporary measure for code still using old LOG macros.
-#ifndef IF_LOG
-#define IF_LOG IF_ALOG
-#endif
 #endif
 
 // ---------------------------------------------------------------------
diff --git a/include/cutils/tztime.h b/include/cutils/tztime.h
index cf103ca..36ac25d 100644
--- a/include/cutils/tztime.h
+++ b/include/cutils/tztime.h
@@ -26,8 +26,14 @@
 time_t mktime_tz(struct tm * const tmp, char const * tz);
 void localtime_tz(const time_t * const timep, struct tm * tmp, const char* tz);
 
-#ifndef HAVE_ANDROID_OS
-/* the following is defined in <time.h> in Bionic */
+#ifdef HAVE_ANDROID_OS
+
+/* the following is defined in the Bionic C library on Android, but the
+ * declarations are only available through a platform-private header
+ */
+#include <bionic_time.h>
+
+#else /* !HAVE_ANDROID_OS */
 
 struct strftime_locale {
     const char *mon[12];    /* short names */
diff --git a/include/ion/ion.h b/include/ion/ion.h
new file mode 100644
index 0000000..879eab3
--- /dev/null
+++ b/include/ion/ion.h
@@ -0,0 +1,32 @@
+/*
+ *  ion.c
+ *
+ * Memory Allocator functions for ion
+ *
+ *   Copyright 2011 Google, Inc
+ *
+ *  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 <linux/ion.h>
+
+int ion_open();
+int ion_close(int fd);
+int ion_alloc(int fd, size_t len, size_t align, unsigned int flags,
+              struct ion_handle **handle);
+int ion_free(int fd, struct ion_handle *handle);
+int ion_map(int fd, struct ion_handle *handle, size_t length, int prot,
+            int flags, off_t offset, unsigned char **ptr, int *map_fd);
+int ion_share(int fd, struct ion_handle *handle, int *share_fd);
+int ion_import(int fd, int share_fd, struct ion_handle **handle);
+
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index ce1e55d..0344b5c 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -79,7 +79,12 @@
 #define AID_MISC          9998  /* access to misc storage */
 #define AID_NOBODY        9999
 
-#define AID_APP          10000 /* first app user */
+#define AID_APP          10000  /* first app user */
+
+#define AID_ISOLATED_START 99000 /* start of uids for fully isolated sandboxed processes */
+#define AID_ISOLATED_END   99999 /* end of uids for fully isolated sandboxed processes */
+
+#define AID_USER        100000  /* offset for uid ranges for each user */
 
 #if !defined(EXCLUDE_FS_CONFIG_STRUCTURES)
 struct android_id_info {
diff --git a/include/system/audio.h b/include/system/audio.h
index 52ba5e7..0f19101 100644
--- a/include/system/audio.h
+++ b/include/system/audio.h
@@ -382,7 +382,7 @@
         return false;
 }
 
-static inline bool audio_is_valid_format(uint32_t format)
+static inline bool audio_is_valid_format(audio_format_t format)
 {
     switch (format & AUDIO_FORMAT_MAIN_MASK) {
     case AUDIO_FORMAT_PCM:
@@ -403,12 +403,12 @@
     }
 }
 
-static inline bool audio_is_linear_pcm(uint32_t format)
+static inline bool audio_is_linear_pcm(audio_format_t format)
 {
     return ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM);
 }
 
-static inline size_t audio_bytes_per_sample(uint32_t format)
+static inline size_t audio_bytes_per_sample(audio_format_t format)
 {
     size_t size = 0;
 
diff --git a/include/system/camera.h b/include/system/camera.h
index cdfa256..62167cf 100644
--- a/include/system/camera.h
+++ b/include/system/camera.h
@@ -85,6 +85,9 @@
     // request FRAME and METADATA. Or the apps can request only FRAME or only
     // METADATA.
     CAMERA_MSG_PREVIEW_METADATA = 0x0400, // dataCallback
+    // Notify on autofocus start and stop. This is useful in continuous
+    // autofocus - FOCUS_MODE_CONTINUOUS_VIDEO and FOCUS_MODE_CONTINUOUS_PICTURE.
+    CAMERA_MSG_FOCUS_MOVE = 0x0800,       // notifyCallback
     CAMERA_MSG_ALL_MSGS = 0xFFFF
 };
 
@@ -142,6 +145,12 @@
      * Stop the face detection.
      */
     CAMERA_CMD_STOP_FACE_DETECTION = 7,
+
+    /**
+     * Enable/disable focus move callback (CAMERA_MSG_FOCUS_MOVE). Passing
+     * arg1 = 0 will disable, while passing arg1 = 1 will enable the callback.
+     */
+    CAMERA_CMD_ENABLE_FOCUS_MOVE_MSG = 8,
 };
 
 /** camera fatal errors */
diff --git a/include/system/window.h b/include/system/window.h
index 1cc4a0a..9602445 100644
--- a/include/system/window.h
+++ b/include/system/window.h
@@ -18,6 +18,7 @@
 #define SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H
 
 #include <stdint.h>
+#include <string.h>
 #include <sys/cdefs.h>
 #include <system/graphics.h>
 #include <cutils/native_handle.h>
diff --git a/init/Android.mk b/init/Android.mk
index e9fd884..b456e43 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -22,6 +22,10 @@
 LOCAL_CFLAGS    += -DBOOTCHART=1
 endif
 
+ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
+LOCAL_CFLAGS += -DALLOW_LOCAL_PROP_OVERRIDE=1
+endif
+
 LOCAL_MODULE:= init
 
 LOCAL_FORCE_STATIC_EXECUTABLE := true
diff --git a/init/property_service.c b/init/property_service.c
index 059db97..0e3c25b 100644
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -338,21 +338,6 @@
     return 0;
 }
 
-static int property_list(void (*propfn)(const char *key, const char *value, void *cookie),
-                  void *cookie)
-{
-    char name[PROP_NAME_MAX];
-    char value[PROP_VALUE_MAX];
-    const prop_info *pi;
-    unsigned n;
-
-    for(n = 0; (pi = __system_property_find_nth(n)); n++) {
-        __system_property_read(pi, name, value);
-        propfn(name, value, cookie);
-    }
-    return 0;
-}
-
 void handle_property_set_fd()
 {
     prop_msg msg;
@@ -527,7 +512,9 @@
  */
 void load_persist_props(void)
 {
+#ifdef ALLOW_LOCAL_PROP_OVERRIDE
     load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE);
+#endif /* ALLOW_LOCAL_PROP_OVERRIDE */
     /* Read persistent properties after all default values have been loaded. */
     load_persistent_properties();
 }
@@ -538,7 +525,9 @@
 
     load_properties_from_file(PROP_PATH_SYSTEM_BUILD);
     load_properties_from_file(PROP_PATH_SYSTEM_DEFAULT);
+#ifdef ALLOW_LOCAL_PROP_OVERRIDE
     load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE);
+#endif /* ALLOW_LOCAL_PROP_OVERRIDE */
     /* Read persistent properties after all default values have been loaded. */
     load_persistent_properties();
 
diff --git a/init/util.c b/init/util.c
index 3a4b10b..7d79f39 100755
--- a/init/util.c
+++ b/init/util.c
@@ -151,11 +151,23 @@
     char *data;
     int sz;
     int fd;
+    struct stat sb;
 
     data = 0;
     fd = open(fn, O_RDONLY);
     if(fd < 0) return 0;
 
+    // for security reasons, disallow world-writable
+    // or group-writable files
+    if (fstat(fd, &sb) < 0) {
+        ERROR("fstat failed for '%s'\n", fn);
+        goto oops;
+    }
+    if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
+        ERROR("skipping insecure file '%s'\n", fn);
+        goto oops;
+    }
+
     sz = lseek(fd, 0, SEEK_END);
     if(sz < 0) goto oops;
 
diff --git a/libcorkscrew/Android.mk b/libcorkscrew/Android.mk
new file mode 100644
index 0000000..433f93c
--- /dev/null
+++ b/libcorkscrew/Android.mk
@@ -0,0 +1,46 @@
+# Copyright (C) 2011 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+	backtrace.c \
+	backtrace-helper.c \
+	demangle.c \
+	map_info.c \
+	ptrace.c \
+	symbol_table.c
+
+ifeq ($(TARGET_ARCH),arm)
+LOCAL_SRC_FILES += \
+	arch-arm/backtrace-arm.c \
+	arch-arm/ptrace-arm.c
+LOCAL_CFLAGS += -DCORKSCREW_HAVE_ARCH
+endif
+ifeq ($(TARGET_ARCH),x86)
+LOCAL_SRC_FILES += \
+	arch-x86/backtrace-x86.c \
+	arch-x86/ptrace-x86.c
+LOCAL_CFLAGS += -DCORKSCREW_HAVE_ARCH
+endif
+
+LOCAL_SHARED_LIBRARIES += libdl libcutils libgccdemangle
+
+LOCAL_CFLAGS += -std=gnu99 -Werror
+LOCAL_MODULE := libcorkscrew
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/libcorkscrew/MODULE_LICENSE_APACHE2 b/libcorkscrew/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/libcorkscrew/MODULE_LICENSE_APACHE2
diff --git a/libcorkscrew/NOTICE b/libcorkscrew/NOTICE
new file mode 100644
index 0000000..becc120
--- /dev/null
+++ b/libcorkscrew/NOTICE
@@ -0,0 +1,190 @@
+
+   Copyright (c) 2011, 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.
+
+   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.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
diff --git a/libcorkscrew/arch-arm/backtrace-arm.c b/libcorkscrew/arch-arm/backtrace-arm.c
new file mode 100644
index 0000000..5b91164
--- /dev/null
+++ b/libcorkscrew/arch-arm/backtrace-arm.c
@@ -0,0 +1,589 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/*
+ * Backtracing functions for ARM.
+ *
+ * This implementation uses the exception unwinding tables provided by
+ * the compiler to unwind call frames.  Refer to the ARM Exception Handling ABI
+ * documentation (EHABI) for more details about what's going on here.
+ *
+ * An ELF binary may contain an EXIDX section that provides an index to
+ * the exception handling table of each function, sorted by program
+ * counter address.
+ *
+ * This implementation also supports unwinding other processes via ptrace().
+ * In that case, the EXIDX section is found by reading the ELF section table
+ * structures using ptrace().
+ *
+ * Because the tables are used for exception handling, it can happen that
+ * a given function will not have an exception handling table.  In particular,
+ * exceptions are assumed to only ever be thrown at call sites.  Therefore,
+ * by definition leaf functions will not have exception handling tables.
+ * This may make unwinding impossible in some cases although we can still get
+ * some idea of the call stack by examining the PC and LR registers.
+ *
+ * As we are only interested in backtrace information, we do not need
+ * to perform all of the work of unwinding such as restoring register
+ * state and running cleanup functions.  Unwinding is performed virtually on
+ * an abstract machine context consisting of just the ARM core registers.
+ * Furthermore, we do not run generic "personality functions" because
+ * we may not be in a position to execute arbitrary code, especially if
+ * we are running in a signal handler or using ptrace()!
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include "../backtrace-arch.h"
+#include "../backtrace-helper.h"
+#include "../ptrace-arch.h"
+#include <corkscrew/ptrace.h>
+
+#include <stdlib.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <limits.h>
+#include <errno.h>
+#include <sys/ptrace.h>
+#include <sys/exec_elf.h>
+#include <cutils/log.h>
+
+/* Machine context at the time a signal was raised. */
+typedef struct ucontext {
+    uint32_t uc_flags;
+    struct ucontext* uc_link;
+    stack_t uc_stack;
+    struct sigcontext {
+        uint32_t trap_no;
+        uint32_t error_code;
+        uint32_t oldmask;
+        uint32_t gregs[16];
+        uint32_t arm_cpsr;
+        uint32_t fault_address;
+    } uc_mcontext;
+    uint32_t uc_sigmask;
+} ucontext_t;
+
+/* Unwind state. */
+typedef struct {
+    uint32_t gregs[16];
+} unwind_state_t;
+
+static const int R_SP = 13;
+static const int R_LR = 14;
+static const int R_PC = 15;
+
+/* Special EXIDX value that indicates that a frame cannot be unwound. */
+static const uint32_t EXIDX_CANTUNWIND = 1;
+
+/* Get the EXIDX section start and size for the module that contains a
+ * given program counter address.
+ *
+ * When the executable is statically linked, the EXIDX section can be
+ * accessed by querying the values of the __exidx_start and __exidx_end
+ * symbols.
+ *
+ * When the executable is dynamically linked, the linker exports a function
+ * called dl_unwind_find_exidx that obtains the EXIDX section for a given
+ * absolute program counter address.
+ *
+ * Bionic exports a helpful function called __gnu_Unwind_Find_exidx that
+ * handles both cases, so we use that here.
+ */
+typedef long unsigned int* _Unwind_Ptr;
+extern _Unwind_Ptr __gnu_Unwind_Find_exidx(_Unwind_Ptr pc, int *pcount);
+
+static uintptr_t find_exidx(uintptr_t pc, size_t* out_exidx_size) {
+    int count;
+    uintptr_t start = (uintptr_t)__gnu_Unwind_Find_exidx((_Unwind_Ptr)pc, &count);
+    *out_exidx_size = count;
+    return start;
+}
+
+/* Transforms a 31-bit place-relative offset to an absolute address.
+ * We assume the most significant bit is clear. */
+static uintptr_t prel_to_absolute(uintptr_t place, uint32_t prel_offset) {
+    return place + (((int32_t)(prel_offset << 1)) >> 1);
+}
+
+static uintptr_t get_exception_handler(const memory_t* memory,
+        const map_info_t* map_info_list, uintptr_t pc) {
+    if (!pc) {
+        ALOGV("get_exception_handler: pc is zero, no handler");
+        return 0;
+    }
+
+    uintptr_t exidx_start;
+    size_t exidx_size;
+    const map_info_t* mi;
+    if (memory->tid < 0) {
+        mi = NULL;
+        exidx_start = find_exidx(pc, &exidx_size);
+    } else {
+        mi = find_map_info(map_info_list, pc);
+        if (mi && mi->data) {
+            const map_info_data_t* data = (const map_info_data_t*)mi->data;
+            exidx_start = data->exidx_start;
+            exidx_size = data->exidx_size;
+        } else {
+            exidx_start = 0;
+            exidx_size = 0;
+        }
+    }
+
+    uintptr_t handler = 0;
+    int32_t handler_index = -1;
+    if (exidx_start) {
+        uint32_t low = 0;
+        uint32_t high = exidx_size;
+        while (low < high) {
+            uint32_t index = (low + high) / 2;
+            uintptr_t entry = exidx_start + index * 8;
+            uint32_t entry_prel_pc;
+            ALOGV("XXX low=%u, high=%u, index=%u", low, high, index);
+            if (!try_get_word(memory, entry, &entry_prel_pc)) {
+                break;
+            }
+            uintptr_t entry_pc = prel_to_absolute(entry, entry_prel_pc);
+            ALOGV("XXX entry_pc=0x%08x", entry_pc);
+            if (pc < entry_pc) {
+                high = index;
+                continue;
+            }
+            if (index + 1 < exidx_size) {
+                uintptr_t next_entry = entry + 8;
+                uint32_t next_entry_prel_pc;
+                if (!try_get_word(memory, next_entry, &next_entry_prel_pc)) {
+                    break;
+                }
+                uintptr_t next_entry_pc = prel_to_absolute(next_entry, next_entry_prel_pc);
+                ALOGV("XXX next_entry_pc=0x%08x", next_entry_pc);
+                if (pc >= next_entry_pc) {
+                    low = index + 1;
+                    continue;
+                }
+            }
+
+            uintptr_t entry_handler_ptr = entry + 4;
+            uint32_t entry_handler;
+            if (!try_get_word(memory, entry_handler_ptr, &entry_handler)) {
+                break;
+            }
+            if (entry_handler & (1L << 31)) {
+                handler = entry_handler_ptr; // in-place handler data
+            } else if (entry_handler != EXIDX_CANTUNWIND) {
+                handler = prel_to_absolute(entry_handler_ptr, entry_handler);
+            }
+            handler_index = index;
+            break;
+        }
+    }
+    if (mi) {
+        ALOGV("get_exception_handler: pc=0x%08x, module='%s', module_start=0x%08x, "
+                "exidx_start=0x%08x, exidx_size=%d, handler=0x%08x, handler_index=%d",
+                pc, mi->name, mi->start, exidx_start, exidx_size, handler, handler_index);
+    } else {
+        ALOGV("get_exception_handler: pc=0x%08x, "
+                "exidx_start=0x%08x, exidx_size=%d, handler=0x%08x, handler_index=%d",
+                pc, exidx_start, exidx_size, handler, handler_index);
+    }
+    return handler;
+}
+
+typedef struct {
+    uintptr_t ptr;
+    uint32_t word;
+} byte_stream_t;
+
+static bool try_next_byte(const memory_t* memory, byte_stream_t* stream, uint8_t* out_value) {
+    uint8_t result;
+    switch (stream->ptr & 3) {
+    case 0:
+        if (!try_get_word(memory, stream->ptr, &stream->word)) {
+            *out_value = 0;
+            return false;
+        }
+        *out_value = stream->word >> 24;
+        break;
+
+    case 1:
+        *out_value = stream->word >> 16;
+        break;
+
+    case 2:
+        *out_value = stream->word >> 8;
+        break;
+
+    default:
+        *out_value = stream->word;
+        break;
+    }
+
+    ALOGV("next_byte: ptr=0x%08x, value=0x%02x", stream->ptr, *out_value);
+    stream->ptr += 1;
+    return true;
+}
+
+static void set_reg(unwind_state_t* state, uint32_t reg, uint32_t value) {
+    ALOGV("set_reg: reg=%d, value=0x%08x", reg, value);
+    state->gregs[reg] = value;
+}
+
+static bool try_pop_registers(const memory_t* memory, unwind_state_t* state, uint32_t mask) {
+    uint32_t sp = state->gregs[R_SP];
+    bool sp_updated = false;
+    for (int i = 0; i < 16; i++) {
+        if (mask & (1 << i)) {
+            uint32_t value;
+            if (!try_get_word(memory, sp, &value)) {
+                return false;
+            }
+            if (i == R_SP) {
+                sp_updated = true;
+            }
+            set_reg(state, i, value);
+            sp += 4;
+        }
+    }
+    if (!sp_updated) {
+        set_reg(state, R_SP, sp);
+    }
+    return true;
+}
+
+/* Executes a built-in personality routine as defined in the EHABI.
+ * Returns true if unwinding should continue.
+ *
+ * The data for the built-in personality routines consists of a sequence
+ * of unwinding instructions, followed by a sequence of scope descriptors,
+ * each of which has a length and offset encoded using 16-bit or 32-bit
+ * values.
+ *
+ * We only care about the unwinding instructions.  They specify the
+ * operations of an abstract machine whose purpose is to transform the
+ * virtual register state (including the stack pointer) such that
+ * the call frame is unwound and the PC register points to the call site.
+ */
+static bool execute_personality_routine(const memory_t* memory,
+        unwind_state_t* state, byte_stream_t* stream, int pr_index) {
+    size_t size;
+    switch (pr_index) {
+    case 0: // Personality routine #0, short frame, descriptors have 16-bit scope.
+        size = 3;
+        break;
+    case 1: // Personality routine #1, long frame, descriptors have 16-bit scope.
+    case 2: { // Personality routine #2, long frame, descriptors have 32-bit scope.
+        uint8_t size_byte;
+        if (!try_next_byte(memory, stream, &size_byte)) {
+            return false;
+        }
+        size = (uint32_t)size_byte * sizeof(uint32_t) + 2;
+        break;
+    }
+    default: // Unknown personality routine.  Stop here.
+        return false;
+    }
+
+    bool pc_was_set = false;
+    while (size--) {
+        uint8_t op;
+        if (!try_next_byte(memory, stream, &op)) {
+            return false;
+        }
+        if ((op & 0xc0) == 0x00) {
+            // "vsp = vsp + (xxxxxx << 2) + 4"
+            set_reg(state, R_SP, state->gregs[R_SP] + ((op & 0x3f) << 2) + 4);
+        } else if ((op & 0xc0) == 0x40) {
+            // "vsp = vsp - (xxxxxx << 2) - 4"
+            set_reg(state, R_SP, state->gregs[R_SP] - ((op & 0x3f) << 2) - 4);
+        } else if ((op & 0xf0) == 0x80) {
+            uint8_t op2;
+            if (!(size--) || !try_next_byte(memory, stream, &op2)) {
+                return false;
+            }
+            uint32_t mask = (((uint32_t)op & 0x0f) << 12) | ((uint32_t)op2 << 4);
+            if (mask) {
+                // "Pop up to 12 integer registers under masks {r15-r12}, {r11-r4}"
+                if (!try_pop_registers(memory, state, mask)) {
+                    return false;
+                }
+                if (mask & (1 << R_PC)) {
+                    pc_was_set = true;
+                }
+            } else {
+                // "Refuse to unwind"
+                return false;
+            }
+        } else if ((op & 0xf0) == 0x90) {
+            if (op != 0x9d && op != 0x9f) {
+                // "Set vsp = r[nnnn]"
+                set_reg(state, R_SP, state->gregs[op & 0x0f]);
+            } else {
+                // "Reserved as prefix for ARM register to register moves"
+                // "Reserved as prefix for Intel Wireless MMX register to register moves"
+                return false;
+            }
+        } else if ((op & 0xf8) == 0xa0) {
+            // "Pop r4-r[4+nnn]"
+            uint32_t mask = (0x0ff0 >> (7 - (op & 0x07))) & 0x0ff0;
+            if (!try_pop_registers(memory, state, mask)) {
+                return false;
+            }
+        } else if ((op & 0xf8) == 0xa8) {
+            // "Pop r4-r[4+nnn], r14"
+            uint32_t mask = ((0x0ff0 >> (7 - (op & 0x07))) & 0x0ff0) | 0x4000;
+            if (!try_pop_registers(memory, state, mask)) {
+                return false;
+            }
+        } else if (op == 0xb0) {
+            // "Finish"
+            break;
+        } else if (op == 0xb1) {
+            uint8_t op2;
+            if (!(size--) || !try_next_byte(memory, stream, &op2)) {
+                return false;
+            }
+            if (op2 != 0x00 && (op2 & 0xf0) == 0x00) {
+                // "Pop integer registers under mask {r3, r2, r1, r0}"
+                if (!try_pop_registers(memory, state, op2)) {
+                    return false;
+                }
+            } else {
+                // "Spare"
+                return false;
+            }
+        } else if (op == 0xb2) {
+            // "vsp = vsp + 0x204 + (uleb128 << 2)"
+            uint32_t value = 0;
+            uint32_t shift = 0;
+            uint8_t op2;
+            do {
+                if (!(size--) || !try_next_byte(memory, stream, &op2)) {
+                    return false;
+                }
+                value |= (op2 & 0x7f) << shift;
+                shift += 7;
+            } while (op2 & 0x80);
+            set_reg(state, R_SP, state->gregs[R_SP] + (value << 2) + 0x204);
+        } else if (op == 0xb3) {
+            // "Pop VFP double-precision registers D[ssss]-D[ssss+cccc] saved (as if) by FSTMFDX"
+            uint8_t op2;
+            if (!(size--) || !try_next_byte(memory, stream, &op2)) {
+                return false;
+            }
+            set_reg(state, R_SP, state->gregs[R_SP] + (uint32_t)(op2 & 0x0f) * 8 + 12);
+        } else if ((op & 0xf8) == 0xb8) {
+            // "Pop VFP double-precision registers D[8]-D[8+nnn] saved (as if) by FSTMFDX"
+            set_reg(state, R_SP, state->gregs[R_SP] + (uint32_t)(op & 0x07) * 8 + 12);
+        } else if ((op & 0xf8) == 0xc0) {
+            // "Intel Wireless MMX pop wR[10]-wR[10+nnn]"
+            set_reg(state, R_SP, state->gregs[R_SP] + (uint32_t)(op & 0x07) * 8 + 8);
+        } else if (op == 0xc6) {
+            // "Intel Wireless MMX pop wR[ssss]-wR[ssss+cccc]"
+            uint8_t op2;
+            if (!(size--) || !try_next_byte(memory, stream, &op2)) {
+                return false;
+            }
+            set_reg(state, R_SP, state->gregs[R_SP] + (uint32_t)(op2 & 0x0f) * 8 + 8);
+        } else if (op == 0xc7) {
+            uint8_t op2;
+            if (!(size--) || !try_next_byte(memory, stream, &op2)) {
+                return false;
+            }
+            if (op2 != 0x00 && (op2 & 0xf0) == 0x00) {
+                // "Intel Wireless MMX pop wCGR registers under mask {wCGR3,2,1,0}"
+                set_reg(state, R_SP, state->gregs[R_SP] + __builtin_popcount(op2) * 4);
+            } else {
+                // "Spare"
+                return false;
+            }
+        } else if (op == 0xc8) {
+            // "Pop VFP double precision registers D[16+ssss]-D[16+ssss+cccc]
+            // saved (as if) by FSTMFD"
+            uint8_t op2;
+            if (!(size--) || !try_next_byte(memory, stream, &op2)) {
+                return false;
+            }
+            set_reg(state, R_SP, state->gregs[R_SP] + (uint32_t)(op2 & 0x0f) * 8 + 8);
+        } else if (op == 0xc9) {
+            // "Pop VFP double precision registers D[ssss]-D[ssss+cccc] saved (as if) by FSTMFDD"
+            uint8_t op2;
+            if (!(size--) || !try_next_byte(memory, stream, &op2)) {
+                return false;
+            }
+            set_reg(state, R_SP, state->gregs[R_SP] + (uint32_t)(op2 & 0x0f) * 8 + 8);
+        } else if ((op == 0xf8) == 0xd0) {
+            // "Pop VFP double-precision registers D[8]-D[8+nnn] saved (as if) by FSTMFDD"
+            set_reg(state, R_SP, state->gregs[R_SP] + (uint32_t)(op & 0x07) * 8 + 8);
+        } else {
+            // "Spare"
+            return false;
+        }
+    }
+    if (!pc_was_set) {
+        set_reg(state, R_PC, state->gregs[R_LR]);
+    }
+    return true;
+}
+
+static bool try_get_half_word(const memory_t* memory, uint32_t pc, uint16_t* out_value) {
+    uint32_t word;
+    if (try_get_word(memory, pc & ~2, &word)) {
+        *out_value = pc & 2 ? word >> 16 : word & 0xffff;
+        return true;
+    }
+    return false;
+}
+
+uintptr_t rewind_pc_arch(const memory_t* memory, uintptr_t pc) {
+    if (pc & 1) {
+        /* Thumb mode - need to check whether the bl(x) has long offset or not.
+         * Examples:
+         *
+         * arm blx in the middle of thumb:
+         * 187ae:       2300            movs    r3, #0
+         * 187b0:       f7fe ee1c       blx     173ec
+         * 187b4:       2c00            cmp     r4, #0
+         *
+         * arm bl in the middle of thumb:
+         * 187d8:       1c20            adds    r0, r4, #0
+         * 187da:       f136 fd15       bl      14f208
+         * 187de:       2800            cmp     r0, #0
+         *
+         * pure thumb:
+         * 18894:       189b            adds    r3, r3, r2
+         * 18896:       4798            blx     r3
+         * 18898:       b001            add     sp, #4
+         */
+        uint16_t prev1, prev2;
+        if (try_get_half_word(memory, pc - 5, &prev1)
+            && ((prev1 & 0xf000) == 0xf000)
+            && try_get_half_word(memory, pc - 3, &prev2)
+            && ((prev2 & 0xe000) == 0xe000)) {
+            pc -= 4; // long offset
+        } else {
+            pc -= 2;
+        }
+    } else {
+        /* ARM mode, all instructions are 32bit.  Yay! */
+        pc -= 4;
+    }
+    return pc;
+}
+
+static ssize_t unwind_backtrace_common(const memory_t* memory,
+        const map_info_t* map_info_list,
+        unwind_state_t* state, backtrace_frame_t* backtrace,
+        size_t ignore_depth, size_t max_depth) {
+    size_t ignored_frames = 0;
+    size_t returned_frames = 0;
+
+    for (size_t index = 0; returned_frames < max_depth; index++) {
+        uintptr_t pc = index ? rewind_pc_arch(memory, state->gregs[R_PC])
+                : state->gregs[R_PC];
+        backtrace_frame_t* frame = add_backtrace_entry(pc,
+                backtrace, ignore_depth, max_depth, &ignored_frames, &returned_frames);
+        if (frame) {
+            frame->stack_top = state->gregs[R_SP];
+        }
+
+        uintptr_t handler = get_exception_handler(memory, map_info_list, pc);
+        if (!handler) {
+            // If there is no handler for the PC and this is the first frame,
+            // then the program may have branched to an invalid address.
+            // Try starting from the LR instead, otherwise stop unwinding.
+            if (index == 0 && state->gregs[R_LR]
+                    && state->gregs[R_LR] != state->gregs[R_PC]) {
+                set_reg(state, R_PC, state->gregs[R_LR]);
+                continue;
+            } else {
+                break;
+            }
+        }
+
+        byte_stream_t stream;
+        stream.ptr = handler;
+        uint8_t pr;
+        if (!try_next_byte(memory, &stream, &pr)) {
+            break;
+        }
+        if ((pr & 0xf0) != 0x80) {
+            // The first word is a place-relative pointer to a generic personality
+            // routine function.  We don't support invoking such functions, so stop here.
+            break;
+        }
+
+        // The first byte indicates the personality routine to execute.
+        // Following bytes provide instructions to the personality routine.
+        if (!execute_personality_routine(memory, state, &stream, pr & 0x0f)) {
+            break;
+        }
+        if (frame && state->gregs[R_SP] > frame->stack_top) {
+            frame->stack_size = state->gregs[R_SP] - frame->stack_top;
+        }
+        if (!state->gregs[R_PC]) {
+            break;
+        }
+    }
+
+    // Ran out of frames that we could unwind using handlers.
+    // Add a final entry for the LR if it looks sane and call it good.
+    if (returned_frames < max_depth
+            && state->gregs[R_LR]
+            && state->gregs[R_LR] != state->gregs[R_PC]
+            && is_executable_map(map_info_list, state->gregs[R_LR])) {
+        // We don't know where the stack for this extra frame starts so we
+        // don't return any stack information for it.
+        add_backtrace_entry(rewind_pc_arch(memory, state->gregs[R_LR]),
+                backtrace, ignore_depth, max_depth, &ignored_frames, &returned_frames);
+    }
+    return returned_frames;
+}
+
+ssize_t unwind_backtrace_signal_arch(siginfo_t* siginfo, void* sigcontext,
+        const map_info_t* map_info_list,
+        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
+    const ucontext_t* uc = (const ucontext_t*)sigcontext;
+
+    unwind_state_t state;
+    for (int i = 0; i < 16; i++) {
+        state.gregs[i] = uc->uc_mcontext.gregs[i];
+    }
+
+    memory_t memory;
+    init_memory(&memory, map_info_list);
+    return unwind_backtrace_common(&memory, map_info_list, &state,
+            backtrace, ignore_depth, max_depth);
+}
+
+ssize_t unwind_backtrace_ptrace_arch(pid_t tid, const ptrace_context_t* context,
+        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
+    struct pt_regs regs;
+    if (ptrace(PTRACE_GETREGS, tid, 0, &regs)) {
+        return -1;
+    }
+
+    unwind_state_t state;
+    for (int i = 0; i < 16; i++) {
+        state.gregs[i] = regs.uregs[i];
+    }
+
+    memory_t memory;
+    init_memory_ptrace(&memory, tid);
+    return unwind_backtrace_common(&memory, context->map_info_list, &state,
+            backtrace, ignore_depth, max_depth);
+}
diff --git a/libcorkscrew/arch-arm/ptrace-arm.c b/libcorkscrew/arch-arm/ptrace-arm.c
new file mode 100644
index 0000000..868230c
--- /dev/null
+++ b/libcorkscrew/arch-arm/ptrace-arm.c
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include "../ptrace-arch.h"
+
+#include <sys/exec_elf.h>
+#include <cutils/log.h>
+
+#ifndef PT_ARM_EXIDX
+#define PT_ARM_EXIDX 0x70000001
+#endif
+
+static void load_exidx_header(pid_t pid, map_info_t* mi,
+        uintptr_t* out_exidx_start, size_t* out_exidx_size) {
+    uint32_t elf_phoff;
+    uint32_t elf_phentsize_phnum;
+    if (try_get_word_ptrace(pid, mi->start + offsetof(Elf32_Ehdr, e_phoff), &elf_phoff)
+            && try_get_word_ptrace(pid, mi->start + offsetof(Elf32_Ehdr, e_phnum),
+                    &elf_phentsize_phnum)) {
+        uint32_t elf_phentsize = elf_phentsize_phnum >> 16;
+        uint32_t elf_phnum = elf_phentsize_phnum & 0xffff;
+        for (uint32_t i = 0; i < elf_phnum; i++) {
+            uintptr_t elf_phdr = mi->start + elf_phoff + i * elf_phentsize;
+            uint32_t elf_phdr_type;
+            if (!try_get_word_ptrace(pid, elf_phdr + offsetof(Elf32_Phdr, p_type), &elf_phdr_type)) {
+                break;
+            }
+            if (elf_phdr_type == PT_ARM_EXIDX) {
+                uint32_t elf_phdr_offset;
+                uint32_t elf_phdr_filesz;
+                if (!try_get_word_ptrace(pid, elf_phdr + offsetof(Elf32_Phdr, p_offset),
+                        &elf_phdr_offset)
+                        || !try_get_word_ptrace(pid, elf_phdr + offsetof(Elf32_Phdr, p_filesz),
+                                &elf_phdr_filesz)) {
+                    break;
+                }
+                *out_exidx_start = mi->start + elf_phdr_offset;
+                *out_exidx_size = elf_phdr_filesz / 8;
+                ALOGV("Parsed EXIDX header info for %s: start=0x%08x, size=%d", mi->name,
+                        *out_exidx_start, *out_exidx_size);
+                return;
+            }
+        }
+    }
+    *out_exidx_start = 0;
+    *out_exidx_size = 0;
+}
+
+void load_ptrace_map_info_data_arch(pid_t pid, map_info_t* mi, map_info_data_t* data) {
+    load_exidx_header(pid, mi, &data->exidx_start, &data->exidx_size);
+}
+
+void free_ptrace_map_info_data_arch(map_info_t* mi, map_info_data_t* data) {
+}
diff --git a/libcorkscrew/arch-x86/backtrace-x86.c b/libcorkscrew/arch-x86/backtrace-x86.c
new file mode 100644
index 0000000..24fadcb
--- /dev/null
+++ b/libcorkscrew/arch-x86/backtrace-x86.c
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/*
+ * Backtracing functions for x86.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include "../backtrace-arch.h"
+#include "../backtrace-helper.h"
+#include <corkscrew/ptrace.h>
+
+#include <stdlib.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <limits.h>
+#include <errno.h>
+#include <sys/ptrace.h>
+#include <sys/exec_elf.h>
+#include <cutils/log.h>
+
+/* Machine context at the time a signal was raised. */
+typedef struct ucontext {
+    uint32_t uc_flags;
+    struct ucontext* uc_link;
+    stack_t uc_stack;
+    struct sigcontext {
+        uint32_t gs;
+        uint32_t fs;
+        uint32_t es;
+        uint32_t ds;
+        uint32_t edi;
+        uint32_t esi;
+        uint32_t ebp;
+        uint32_t esp;
+        uint32_t ebx;
+        uint32_t edx;
+        uint32_t ecx;
+        uint32_t eax;
+        uint32_t trapno;
+        uint32_t err;
+        uint32_t eip;
+        uint32_t cs;
+        uint32_t efl;
+        uint32_t uesp;
+        uint32_t ss;
+        void* fpregs;
+        uint32_t oldmask;
+        uint32_t cr2;
+    } uc_mcontext;
+    uint32_t uc_sigmask;
+} ucontext_t;
+
+/* Unwind state. */
+typedef struct {
+    uint32_t ebp;
+    uint32_t eip;
+    uint32_t esp;
+} unwind_state_t;
+
+uintptr_t rewind_pc_arch(const memory_t* memory, uintptr_t pc) {
+    // TODO: Implement for x86.
+    return pc;
+}
+
+static ssize_t unwind_backtrace_common(const memory_t* memory,
+        const map_info_t* map_info_list,
+        unwind_state_t* state, backtrace_frame_t* backtrace,
+        size_t ignore_depth, size_t max_depth) {
+    size_t ignored_frames = 0;
+    size_t returned_frames = 0;
+
+    for (size_t index = 0; state->ebp && returned_frames < max_depth; index++) {
+        backtrace_frame_t* frame = add_backtrace_entry(
+                index ? rewind_pc_arch(memory, state->eip) : state->eip,
+                backtrace, ignore_depth, max_depth,
+                &ignored_frames, &returned_frames);
+        uint32_t next_esp = state->ebp + 8;
+        if (frame) {
+            frame->stack_top = state->esp;
+            if (state->esp < next_esp) {
+                frame->stack_size = next_esp - state->esp;
+            }
+        }
+        state->esp = next_esp;
+        if (!try_get_word(memory, state->ebp + 4, &state->eip)
+                || !try_get_word(memory, state->ebp, &state->ebp)
+                || !state->eip) {
+            break;
+        }
+    }
+
+    return returned_frames;
+}
+
+ssize_t unwind_backtrace_signal_arch(siginfo_t* siginfo, void* sigcontext,
+        const map_info_t* map_info_list,
+        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
+    const ucontext_t* uc = (const ucontext_t*)sigcontext;
+
+    unwind_state_t state;
+    state.ebp = uc->uc_mcontext.ebp;
+    state.eip = uc->uc_mcontext.eip;
+    state.esp = uc->uc_mcontext.esp;
+
+    memory_t memory;
+    init_memory(&memory, map_info_list);
+    return unwind_backtrace_common(&memory, map_info_list,
+            &state, backtrace, ignore_depth, max_depth);
+}
+
+ssize_t unwind_backtrace_ptrace_arch(pid_t tid, const ptrace_context_t* context,
+        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
+    pt_regs_x86_t regs;
+    if (ptrace(PTRACE_GETREGS, tid, 0, &regs)) {
+        return -1;
+    }
+
+    unwind_state_t state;
+    state.ebp = regs.ebp;
+    state.eip = regs.eip;
+    state.esp = regs.esp;
+
+    memory_t memory;
+    init_memory_ptrace(&memory, tid);
+    return unwind_backtrace_common(&memory, context->map_info_list,
+            &state, backtrace, ignore_depth, max_depth);
+}
diff --git a/libcorkscrew/arch-x86/ptrace-x86.c b/libcorkscrew/arch-x86/ptrace-x86.c
new file mode 100644
index 0000000..f0ea110
--- /dev/null
+++ b/libcorkscrew/arch-x86/ptrace-x86.c
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include "../ptrace-arch.h"
+
+#include <cutils/log.h>
+
+void load_ptrace_map_info_data_arch(pid_t pid, map_info_t* mi, map_info_data_t* data) {
+}
+
+void free_ptrace_map_info_data_arch(map_info_t* mi, map_info_data_t* data) {
+}
diff --git a/libcorkscrew/backtrace-arch.h b/libcorkscrew/backtrace-arch.h
new file mode 100644
index 0000000..a46f80b
--- /dev/null
+++ b/libcorkscrew/backtrace-arch.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/* Architecture dependent functions. */
+
+#ifndef _CORKSCREW_BACKTRACE_ARCH_H
+#define _CORKSCREW_BACKTRACE_ARCH_H
+
+#include "ptrace-arch.h"
+#include <corkscrew/backtrace.h>
+
+#include <signal.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Rewind the program counter by one instruction. */
+uintptr_t rewind_pc_arch(const memory_t* memory, uintptr_t pc);
+
+ssize_t unwind_backtrace_signal_arch(siginfo_t* siginfo, void* sigcontext,
+        const map_info_t* map_info_list,
+        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth);
+
+ssize_t unwind_backtrace_ptrace_arch(pid_t tid, const ptrace_context_t* context,
+        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CORKSCREW_BACKTRACE_ARCH_H
diff --git a/libcorkscrew/backtrace-helper.c b/libcorkscrew/backtrace-helper.c
new file mode 100644
index 0000000..bf9d3f3
--- /dev/null
+++ b/libcorkscrew/backtrace-helper.c
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include "backtrace-helper.h"
+
+#include <cutils/log.h>
+
+backtrace_frame_t* add_backtrace_entry(uintptr_t pc, backtrace_frame_t* backtrace,
+        size_t ignore_depth, size_t max_depth,
+        size_t* ignored_frames, size_t* returned_frames) {
+    if (*ignored_frames < ignore_depth) {
+        *ignored_frames += 1;
+        return NULL;
+    }
+    if (*returned_frames >= max_depth) {
+        return NULL;
+    }
+    backtrace_frame_t* frame = &backtrace[*returned_frames];
+    frame->absolute_pc = pc;
+    frame->stack_top = 0;
+    frame->stack_size = 0;
+    *returned_frames += 1;
+    return frame;
+}
diff --git a/libcorkscrew/backtrace-helper.h b/libcorkscrew/backtrace-helper.h
new file mode 100644
index 0000000..4d8a874
--- /dev/null
+++ b/libcorkscrew/backtrace-helper.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/* Backtrace helper functions. */
+
+#ifndef _CORKSCREW_BACKTRACE_HELPER_H
+#define _CORKSCREW_BACKTRACE_HELPER_H
+
+#include <corkscrew/backtrace.h>
+#include <sys/types.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Add a program counter to a backtrace if it will fit.
+ * Returns the newly added frame, or NULL if none.
+ */
+backtrace_frame_t* add_backtrace_entry(uintptr_t pc,
+        backtrace_frame_t* backtrace,
+        size_t ignore_depth, size_t max_depth,
+        size_t* ignored_frames, size_t* returned_frames);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CORKSCREW_BACKTRACE_HELPER_H
diff --git a/libcorkscrew/backtrace.c b/libcorkscrew/backtrace.c
new file mode 100644
index 0000000..fa21574
--- /dev/null
+++ b/libcorkscrew/backtrace.c
@@ -0,0 +1,305 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include "backtrace-arch.h"
+#include "backtrace-helper.h"
+#include "ptrace-arch.h"
+#include <corkscrew/map_info.h>
+#include <corkscrew/symbol_table.h>
+#include <corkscrew/ptrace.h>
+#include <corkscrew/demangle.h>
+
+#include <unistd.h>
+#include <signal.h>
+#include <pthread.h>
+#include <unwind.h>
+#include <sys/exec_elf.h>
+#include <cutils/log.h>
+#include <cutils/atomic.h>
+
+#if HAVE_DLADDR
+#include <dlfcn.h>
+#endif
+
+typedef struct {
+    backtrace_frame_t* backtrace;
+    size_t ignore_depth;
+    size_t max_depth;
+    size_t ignored_frames;
+    size_t returned_frames;
+    memory_t memory;
+} backtrace_state_t;
+
+static _Unwind_Reason_Code unwind_backtrace_callback(struct _Unwind_Context* context, void* arg) {
+    backtrace_state_t* state = (backtrace_state_t*)arg;
+    uintptr_t pc = _Unwind_GetIP(context);
+    if (pc) {
+        // TODO: Get information about the stack layout from the _Unwind_Context.
+        //       This will require a new architecture-specific function to query
+        //       the appropriate registers.  Current callers of unwind_backtrace
+        //       don't need this information, so we won't bother collecting it just yet.
+        add_backtrace_entry(rewind_pc_arch(&state->memory, pc), state->backtrace,
+                state->ignore_depth, state->max_depth,
+                &state->ignored_frames, &state->returned_frames);
+    }
+    return state->returned_frames < state->max_depth ? _URC_NO_REASON : _URC_END_OF_STACK;
+}
+
+ssize_t unwind_backtrace(backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
+    ALOGV("Unwinding current thread %d.", gettid());
+
+    map_info_t* milist = acquire_my_map_info_list();
+
+    backtrace_state_t state;
+    state.backtrace = backtrace;
+    state.ignore_depth = ignore_depth;
+    state.max_depth = max_depth;
+    state.ignored_frames = 0;
+    state.returned_frames = 0;
+    init_memory(&state.memory, milist);
+
+    _Unwind_Reason_Code rc =_Unwind_Backtrace(unwind_backtrace_callback, &state);
+
+    release_my_map_info_list(milist);
+
+    if (state.returned_frames) {
+        return state.returned_frames;
+    }
+    return rc == _URC_END_OF_STACK ? 0 : -1;
+}
+
+#ifdef CORKSCREW_HAVE_ARCH
+static const int32_t STATE_DUMPING = -1;
+static const int32_t STATE_DONE = -2;
+static const int32_t STATE_CANCEL = -3;
+
+static pthread_mutex_t g_unwind_signal_mutex = PTHREAD_MUTEX_INITIALIZER;
+static volatile struct {
+    int32_t tid_state;
+    const map_info_t* map_info_list;
+    backtrace_frame_t* backtrace;
+    size_t ignore_depth;
+    size_t max_depth;
+    size_t returned_frames;
+} g_unwind_signal_state;
+
+static void unwind_backtrace_thread_signal_handler(int n, siginfo_t* siginfo, void* sigcontext) {
+    if (!android_atomic_acquire_cas(gettid(), STATE_DUMPING, &g_unwind_signal_state.tid_state)) {
+        g_unwind_signal_state.returned_frames = unwind_backtrace_signal_arch(
+                siginfo, sigcontext,
+                g_unwind_signal_state.map_info_list,
+                g_unwind_signal_state.backtrace,
+                g_unwind_signal_state.ignore_depth,
+                g_unwind_signal_state.max_depth);
+        android_atomic_release_store(STATE_DONE, &g_unwind_signal_state.tid_state);
+    } else {
+        ALOGV("Received spurious SIGURG on thread %d that was intended for thread %d.",
+                gettid(), android_atomic_acquire_load(&g_unwind_signal_state.tid_state));
+    }
+}
+#endif
+
+extern int tgkill(int tgid, int tid, int sig);
+
+ssize_t unwind_backtrace_thread(pid_t tid, backtrace_frame_t* backtrace,
+        size_t ignore_depth, size_t max_depth) {
+    if (tid == gettid()) {
+        return unwind_backtrace(backtrace, ignore_depth + 1, max_depth);
+    }
+
+    ALOGV("Unwinding thread %d from thread %d.", tid, gettid());
+
+#ifdef CORKSCREW_HAVE_ARCH
+    struct sigaction act;
+    struct sigaction oact;
+    memset(&act, 0, sizeof(act));
+    act.sa_sigaction = unwind_backtrace_thread_signal_handler;
+    act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
+    sigemptyset(&act.sa_mask);
+
+    pthread_mutex_lock(&g_unwind_signal_mutex);
+    map_info_t* milist = acquire_my_map_info_list();
+
+    ssize_t frames = -1;
+    if (!sigaction(SIGURG, &act, &oact)) {
+        g_unwind_signal_state.map_info_list = milist;
+        g_unwind_signal_state.backtrace = backtrace;
+        g_unwind_signal_state.ignore_depth = ignore_depth;
+        g_unwind_signal_state.max_depth = max_depth;
+        g_unwind_signal_state.returned_frames = 0;
+        android_atomic_release_store(tid, &g_unwind_signal_state.tid_state);
+
+        // Signal the specific thread that we want to dump.
+        int32_t tid_state = tid;
+        if (tgkill(getpid(), tid, SIGURG)) {
+            ALOGV("Failed to send SIGURG to thread %d.", tid);
+        } else {
+            // Wait for the other thread to start dumping the stack, or time out.
+            int wait_millis = 250;
+            for (;;) {
+                tid_state = android_atomic_acquire_load(&g_unwind_signal_state.tid_state);
+                if (tid_state != tid) {
+                    break;
+                }
+                if (wait_millis--) {
+                    ALOGV("Waiting for thread %d to start dumping the stack...", tid);
+                    usleep(1000);
+                } else {
+                    ALOGV("Timed out waiting for thread %d to start dumping the stack.", tid);
+                    break;
+                }
+            }
+        }
+
+        // Try to cancel the dump if it has not started yet.
+        if (tid_state == tid) {
+            if (!android_atomic_acquire_cas(tid, STATE_CANCEL, &g_unwind_signal_state.tid_state)) {
+                ALOGV("Canceled thread %d stack dump.", tid);
+                tid_state = STATE_CANCEL;
+            } else {
+                tid_state = android_atomic_acquire_load(&g_unwind_signal_state.tid_state);
+            }
+        }
+
+        // Wait indefinitely for the dump to finish or be canceled.
+        // We cannot apply a timeout here because the other thread is accessing state that
+        // is owned by this thread, such as milist.  It should not take very
+        // long to take the dump once started.
+        while (tid_state == STATE_DUMPING) {
+            ALOGV("Waiting for thread %d to finish dumping the stack...", tid);
+            usleep(1000);
+            tid_state = android_atomic_acquire_load(&g_unwind_signal_state.tid_state);
+        }
+
+        if (tid_state == STATE_DONE) {
+            frames = g_unwind_signal_state.returned_frames;
+        }
+
+        sigaction(SIGURG, &oact, NULL);
+    }
+
+    release_my_map_info_list(milist);
+    pthread_mutex_unlock(&g_unwind_signal_mutex);
+    return frames;
+#else
+    return -1;
+#endif
+}
+
+ssize_t unwind_backtrace_ptrace(pid_t tid, const ptrace_context_t* context,
+        backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth) {
+#ifdef CORKSCREW_HAVE_ARCH
+    return unwind_backtrace_ptrace_arch(tid, context, backtrace, ignore_depth, max_depth);
+#else
+    return -1;
+#endif
+}
+
+static void init_backtrace_symbol(backtrace_symbol_t* symbol, uintptr_t pc) {
+    symbol->relative_pc = pc;
+    symbol->relative_symbol_addr = 0;
+    symbol->map_name = NULL;
+    symbol->symbol_name = NULL;
+    symbol->demangled_name = NULL;
+}
+
+void get_backtrace_symbols(const backtrace_frame_t* backtrace, size_t frames,
+        backtrace_symbol_t* backtrace_symbols) {
+    map_info_t* milist = acquire_my_map_info_list();
+    for (size_t i = 0; i < frames; i++) {
+        const backtrace_frame_t* frame = &backtrace[i];
+        backtrace_symbol_t* symbol = &backtrace_symbols[i];
+        init_backtrace_symbol(symbol, frame->absolute_pc);
+
+        const map_info_t* mi = find_map_info(milist, frame->absolute_pc);
+        if (mi) {
+            symbol->relative_pc = frame->absolute_pc - mi->start;
+            if (mi->name[0]) {
+                symbol->map_name = strdup(mi->name);
+            }
+#if HAVE_DLADDR
+            Dl_info info;
+            if (dladdr((const void*)frame->absolute_pc, &info) && info.dli_sname) {
+                symbol->relative_symbol_addr = (uintptr_t)info.dli_saddr
+                        - (uintptr_t)info.dli_fbase;
+                symbol->symbol_name = strdup(info.dli_sname);
+                symbol->demangled_name = demangle_symbol_name(symbol->symbol_name);
+            }
+#endif
+        }
+    }
+    release_my_map_info_list(milist);
+}
+
+void get_backtrace_symbols_ptrace(const ptrace_context_t* context,
+        const backtrace_frame_t* backtrace, size_t frames,
+        backtrace_symbol_t* backtrace_symbols) {
+    for (size_t i = 0; i < frames; i++) {
+        const backtrace_frame_t* frame = &backtrace[i];
+        backtrace_symbol_t* symbol = &backtrace_symbols[i];
+        init_backtrace_symbol(symbol, frame->absolute_pc);
+
+        const map_info_t* mi;
+        const symbol_t* s;
+        find_symbol_ptrace(context, frame->absolute_pc, &mi, &s);
+        if (mi) {
+            symbol->relative_pc = frame->absolute_pc - mi->start;
+            if (mi->name[0]) {
+                symbol->map_name = strdup(mi->name);
+            }
+        }
+        if (s) {
+            symbol->relative_symbol_addr = s->start;
+            symbol->symbol_name = strdup(s->name);
+            symbol->demangled_name = demangle_symbol_name(symbol->symbol_name);
+        }
+    }
+}
+
+void free_backtrace_symbols(backtrace_symbol_t* backtrace_symbols, size_t frames) {
+    for (size_t i = 0; i < frames; i++) {
+        backtrace_symbol_t* symbol = &backtrace_symbols[i];
+        free(symbol->map_name);
+        free(symbol->symbol_name);
+        free(symbol->demangled_name);
+        init_backtrace_symbol(symbol, 0);
+    }
+}
+
+void format_backtrace_line(unsigned frameNumber, const backtrace_frame_t* frame,
+        const backtrace_symbol_t* symbol, char* buffer, size_t bufferSize) {
+    const char* mapName = symbol->map_name ? symbol->map_name : "<unknown>";
+    const char* symbolName = symbol->demangled_name ? symbol->demangled_name : symbol->symbol_name;
+    size_t fieldWidth = (bufferSize - 80) / 2;
+    if (symbolName) {
+        uint32_t pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
+        if (pc_offset) {
+            snprintf(buffer, bufferSize, "#%02d  pc %08x  %.*s (%.*s+%u)",
+                    frameNumber, symbol->relative_pc, fieldWidth, mapName,
+                    fieldWidth, symbolName, pc_offset);
+        } else {
+            snprintf(buffer, bufferSize, "#%02d  pc %08x  %.*s (%.*s)",
+                    frameNumber, symbol->relative_pc, fieldWidth, mapName,
+                    fieldWidth, symbolName);
+        }
+    } else {
+        snprintf(buffer, bufferSize, "#%02d  pc %08x  %.*s",
+                frameNumber, symbol->relative_pc, fieldWidth, mapName);
+    }
+}
diff --git a/libcorkscrew/demangle.c b/libcorkscrew/demangle.c
new file mode 100644
index 0000000..54247cb
--- /dev/null
+++ b/libcorkscrew/demangle.c
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include <corkscrew/demangle.h>
+
+#include <cutils/log.h>
+
+extern char *__cxa_demangle (const char *mangled, char *buf, size_t *len,
+                             int *status);
+
+char* demangle_symbol_name(const char* name) {
+    // __cxa_demangle handles NULL by returning NULL
+    return __cxa_demangle(name, 0, 0, 0);
+}
diff --git a/libcorkscrew/map_info.c b/libcorkscrew/map_info.c
new file mode 100644
index 0000000..f33378f
--- /dev/null
+++ b/libcorkscrew/map_info.c
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include <corkscrew/map_info.h>
+
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <cutils/log.h>
+#include <sys/time.h>
+
+// 6f000000-6f01e000 rwxp 00000000 00:0c 16389419   /system/lib/libcomposer.so\n
+// 012345678901234567890123456789012345678901234567890123456789
+// 0         1         2         3         4         5
+static map_info_t* parse_maps_line(const char* line)
+{
+    unsigned long int start;
+    unsigned long int end;
+    char permissions[5];
+    int name_pos;
+    if (sscanf(line, "%lx-%lx %4s %*x %*x:%*x %*d%n", &start, &end,
+            permissions, &name_pos) != 3) {
+        return NULL;
+    }
+
+    while (isspace(line[name_pos])) {
+        name_pos += 1;
+    }
+    const char* name = line + name_pos;
+    size_t name_len = strlen(name);
+    if (name_len && name[name_len - 1] == '\n') {
+        name_len -= 1;
+    }
+
+    map_info_t* mi = calloc(1, sizeof(map_info_t) + name_len + 1);
+    if (mi) {
+        mi->start = start;
+        mi->end = end;
+        mi->is_readable = strlen(permissions) == 4 && permissions[0] == 'r';
+        mi->is_executable = strlen(permissions) == 4 && permissions[2] == 'x';
+        mi->data = NULL;
+        memcpy(mi->name, name, name_len);
+        mi->name[name_len] = '\0';
+        ALOGV("Parsed map: start=0x%08x, end=0x%08x, "
+                "is_readable=%d, is_executable=%d, name=%s",
+                mi->start, mi->end, mi->is_readable, mi->is_executable, mi->name);
+    }
+    return mi;
+}
+
+map_info_t* load_map_info_list(pid_t tid) {
+    char path[PATH_MAX];
+    char line[1024];
+    FILE* fp;
+    map_info_t* milist = NULL;
+
+    snprintf(path, PATH_MAX, "/proc/%d/maps", tid);
+    fp = fopen(path, "r");
+    if (fp) {
+        while(fgets(line, sizeof(line), fp)) {
+            map_info_t* mi = parse_maps_line(line);
+            if (mi) {
+                mi->next = milist;
+                milist = mi;
+            }
+        }
+        fclose(fp);
+    }
+    return milist;
+}
+
+void free_map_info_list(map_info_t* milist) {
+    while (milist) {
+        map_info_t* next = milist->next;
+        free(milist);
+        milist = next;
+    }
+}
+
+const map_info_t* find_map_info(const map_info_t* milist, uintptr_t addr) {
+    const map_info_t* mi = milist;
+    while (mi && !(addr >= mi->start && addr < mi->end)) {
+        mi = mi->next;
+    }
+    return mi;
+}
+
+bool is_readable_map(const map_info_t* milist, uintptr_t addr) {
+    const map_info_t* mi = find_map_info(milist, addr);
+    return mi && mi->is_readable;
+}
+
+bool is_executable_map(const map_info_t* milist, uintptr_t addr) {
+    const map_info_t* mi = find_map_info(milist, addr);
+    return mi && mi->is_executable;
+}
+
+static pthread_mutex_t g_my_map_info_list_mutex = PTHREAD_MUTEX_INITIALIZER;
+static map_info_t* g_my_map_info_list = NULL;
+
+static const int64_t MAX_CACHE_AGE = 5 * 1000 * 1000000LL;
+
+typedef struct {
+    uint32_t refs;
+    int64_t timestamp;
+} my_map_info_data_t;
+
+static int64_t now() {
+    struct timespec t;
+    t.tv_sec = t.tv_nsec = 0;
+    clock_gettime(CLOCK_MONOTONIC, &t);
+    return t.tv_sec * 1000000000LL + t.tv_nsec;
+}
+
+static void dec_ref(map_info_t* milist, my_map_info_data_t* data) {
+    if (!--data->refs) {
+        ALOGV("Freed my_map_info_list %p.", milist);
+        free(data);
+        free_map_info_list(milist);
+    }
+}
+
+map_info_t* acquire_my_map_info_list() {
+    pthread_mutex_lock(&g_my_map_info_list_mutex);
+
+    int64_t time = now();
+    if (g_my_map_info_list) {
+        my_map_info_data_t* data = (my_map_info_data_t*)g_my_map_info_list->data;
+        int64_t age = time - data->timestamp;
+        if (age >= MAX_CACHE_AGE) {
+            ALOGV("Invalidated my_map_info_list %p, age=%lld.", g_my_map_info_list, age);
+            dec_ref(g_my_map_info_list, data);
+            g_my_map_info_list = NULL;
+        } else {
+            ALOGV("Reusing my_map_info_list %p, age=%lld.", g_my_map_info_list, age);
+        }
+    }
+
+    if (!g_my_map_info_list) {
+        my_map_info_data_t* data = (my_map_info_data_t*)malloc(sizeof(my_map_info_data_t));
+        g_my_map_info_list = load_map_info_list(getpid());
+        if (g_my_map_info_list) {
+            ALOGV("Loaded my_map_info_list %p.", g_my_map_info_list);
+            g_my_map_info_list->data = data;
+            data->refs = 1;
+            data->timestamp = time;
+        } else {
+            free(data);
+        }
+    }
+
+    map_info_t* milist = g_my_map_info_list;
+    if (milist) {
+        my_map_info_data_t* data = (my_map_info_data_t*)g_my_map_info_list->data;
+        data->refs += 1;
+    }
+
+    pthread_mutex_unlock(&g_my_map_info_list_mutex);
+    return milist;
+}
+
+void release_my_map_info_list(map_info_t* milist) {
+    if (milist) {
+        pthread_mutex_lock(&g_my_map_info_list_mutex);
+
+        my_map_info_data_t* data = (my_map_info_data_t*)milist->data;
+        dec_ref(milist, data);
+
+        pthread_mutex_unlock(&g_my_map_info_list_mutex);
+    }
+}
diff --git a/libcorkscrew/ptrace-arch.h b/libcorkscrew/ptrace-arch.h
new file mode 100644
index 0000000..c02df52
--- /dev/null
+++ b/libcorkscrew/ptrace-arch.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/* Architecture dependent functions. */
+
+#ifndef _CORKSCREW_PTRACE_ARCH_H
+#define _CORKSCREW_PTRACE_ARCH_H
+
+#include <corkscrew/ptrace.h>
+#include <corkscrew/map_info.h>
+#include <corkscrew/symbol_table.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Custom extra data we stuff into map_info_t structures as part
+ * of our ptrace_context_t. */
+typedef struct {
+#ifdef __arm__
+    uintptr_t exidx_start;
+    size_t exidx_size;
+#endif
+    symbol_table_t* symbol_table;
+} map_info_data_t;
+
+void load_ptrace_map_info_data_arch(pid_t pid, map_info_t* mi, map_info_data_t* data);
+void free_ptrace_map_info_data_arch(map_info_t* mi, map_info_data_t* data);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CORKSCREW_PTRACE_ARCH_H
diff --git a/libcorkscrew/ptrace.c b/libcorkscrew/ptrace.c
new file mode 100644
index 0000000..cbea8ca
--- /dev/null
+++ b/libcorkscrew/ptrace.c
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include "ptrace-arch.h"
+#include <corkscrew/ptrace.h>
+
+#include <errno.h>
+#include <sys/ptrace.h>
+#include <cutils/log.h>
+
+static const uint32_t ELF_MAGIC = 0x464C457f; // "ELF\0177"
+
+#ifndef PAGE_SIZE
+#define PAGE_SIZE 4096
+#endif
+
+#ifndef PAGE_MASK
+#define PAGE_MASK (~(PAGE_SIZE - 1))
+#endif
+
+void init_memory(memory_t* memory, const map_info_t* map_info_list) {
+    memory->tid = -1;
+    memory->map_info_list = map_info_list;
+}
+
+void init_memory_ptrace(memory_t* memory, pid_t tid) {
+    memory->tid = tid;
+    memory->map_info_list = NULL;
+}
+
+bool try_get_word(const memory_t* memory, uintptr_t ptr, uint32_t* out_value) {
+    ALOGV("try_get_word: reading word at 0x%08x", ptr);
+    if (ptr & 3) {
+        ALOGV("try_get_word: invalid pointer 0x%08x", ptr);
+        *out_value = 0xffffffffL;
+        return false;
+    }
+    if (memory->tid < 0) {
+        if (!is_readable_map(memory->map_info_list, ptr)) {
+            ALOGV("try_get_word: pointer 0x%08x not in a readable map", ptr);
+            *out_value = 0xffffffffL;
+            return false;
+        }
+        *out_value = *(uint32_t*)ptr;
+        return true;
+    } else {
+        // ptrace() returns -1 and sets errno when the operation fails.
+        // To disambiguate -1 from a valid result, we clear errno beforehand.
+        errno = 0;
+        *out_value = ptrace(PTRACE_PEEKTEXT, memory->tid, (void*)ptr, NULL);
+        if (*out_value == 0xffffffffL && errno) {
+            ALOGV("try_get_word: invalid pointer 0x%08x reading from tid %d, "
+                    "ptrace() errno=%d", ptr, memory->tid, errno);
+            return false;
+        }
+        return true;
+    }
+}
+
+bool try_get_word_ptrace(pid_t tid, uintptr_t ptr, uint32_t* out_value) {
+    memory_t memory;
+    init_memory_ptrace(&memory, tid);
+    return try_get_word(&memory, ptr, out_value);
+}
+
+static void load_ptrace_map_info_data(pid_t pid, map_info_t* mi) {
+    if (mi->is_executable && mi->is_readable) {
+        uint32_t elf_magic;
+        if (try_get_word_ptrace(pid, mi->start, &elf_magic) && elf_magic == ELF_MAGIC) {
+            map_info_data_t* data = (map_info_data_t*)calloc(1, sizeof(map_info_data_t));
+            if (data) {
+                mi->data = data;
+                if (mi->name[0]) {
+                    data->symbol_table = load_symbol_table(mi->name);
+                }
+#ifdef CORKSCREW_HAVE_ARCH
+                load_ptrace_map_info_data_arch(pid, mi, data);
+#endif
+            }
+        }
+    }
+}
+
+ptrace_context_t* load_ptrace_context(pid_t pid) {
+    ptrace_context_t* context =
+            (ptrace_context_t*)calloc(1, sizeof(ptrace_context_t));
+    if (context) {
+        context->map_info_list = load_map_info_list(pid);
+        for (map_info_t* mi = context->map_info_list; mi; mi = mi->next) {
+            load_ptrace_map_info_data(pid, mi);
+        }
+    }
+    return context;
+}
+
+static void free_ptrace_map_info_data(map_info_t* mi) {
+    map_info_data_t* data = (map_info_data_t*)mi->data;
+    if (data) {
+        if (data->symbol_table) {
+            free_symbol_table(data->symbol_table);
+        }
+#ifdef CORKSCREW_HAVE_ARCH
+        free_ptrace_map_info_data_arch(mi, data);
+#endif
+        free(data);
+        mi->data = NULL;
+    }
+}
+
+void free_ptrace_context(ptrace_context_t* context) {
+    for (map_info_t* mi = context->map_info_list; mi; mi = mi->next) {
+        free_ptrace_map_info_data(mi);
+    }
+    free_map_info_list(context->map_info_list);
+}
+
+void find_symbol_ptrace(const ptrace_context_t* context,
+        uintptr_t addr, const map_info_t** out_map_info, const symbol_t** out_symbol) {
+    const map_info_t* mi = find_map_info(context->map_info_list, addr);
+    const symbol_t* symbol = NULL;
+    if (mi) {
+        const map_info_data_t* data = (const map_info_data_t*)mi->data;
+        if (data && data->symbol_table) {
+            symbol = find_symbol(data->symbol_table, addr - mi->start);
+        }
+    }
+    *out_map_info = mi;
+    *out_symbol = symbol;
+}
diff --git a/libcorkscrew/symbol_table.c b/libcorkscrew/symbol_table.c
new file mode 100644
index 0000000..1b97180
--- /dev/null
+++ b/libcorkscrew/symbol_table.c
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
+
+#include <corkscrew/symbol_table.h>
+
+#include <stdlib.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+#include <sys/exec_elf.h>
+#include <cutils/log.h>
+
+// Compare function for qsort
+static int qcompar(const void *a, const void *b) {
+    const symbol_t* asym = (const symbol_t*)a;
+    const symbol_t* bsym = (const symbol_t*)b;
+    if (asym->start > bsym->start) return 1;
+    if (asym->start < bsym->start) return -1;
+    return 0;
+}
+
+// Compare function for bsearch
+static int bcompar(const void *key, const void *element) {
+    uintptr_t addr = *(const uintptr_t*)key;
+    const symbol_t* symbol = (const symbol_t*)element;
+    if (addr < symbol->start) return -1;
+    if (addr >= symbol->end) return 1;
+    return 0;
+}
+
+symbol_table_t* load_symbol_table(const char *filename) {
+    symbol_table_t* table = NULL;
+    ALOGV("Loading symbol table from '%s'.", filename);
+
+    int fd = open(filename, O_RDONLY);
+    if (fd < 0) {
+        goto out;
+    }
+
+    struct stat sb;
+    if (fstat(fd, &sb)) {
+        goto out_close;
+    }
+
+    size_t length = sb.st_size;
+    char* base = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
+    if (base == MAP_FAILED) {
+        goto out_close;
+    }
+
+    // Parse the file header
+    Elf32_Ehdr *hdr = (Elf32_Ehdr*)base;
+    if (!IS_ELF(*hdr)) {
+        goto out_close;
+    }
+    Elf32_Shdr *shdr = (Elf32_Shdr*)(base + hdr->e_shoff);
+
+    // Search for the dynamic symbols section
+    int sym_idx = -1;
+    int dynsym_idx = -1;
+    for (Elf32_Half i = 0; i < hdr->e_shnum; i++) {
+        if (shdr[i].sh_type == SHT_SYMTAB) {
+            sym_idx = i;
+        }
+        if (shdr[i].sh_type == SHT_DYNSYM) {
+            dynsym_idx = i;
+        }
+    }
+    if (dynsym_idx == -1 && sym_idx == -1) {
+        goto out_unmap;
+    }
+
+    table = malloc(sizeof(symbol_table_t));
+    if(!table) {
+        goto out_unmap;
+    }
+    table->num_symbols = 0;
+
+    Elf32_Sym *dynsyms = NULL;
+    int dynnumsyms = 0;
+    char *dynstr = NULL;
+    if (dynsym_idx != -1) {
+        dynsyms = (Elf32_Sym*)(base + shdr[dynsym_idx].sh_offset);
+        dynnumsyms = shdr[dynsym_idx].sh_size / shdr[dynsym_idx].sh_entsize;
+        int dynstr_idx = shdr[dynsym_idx].sh_link;
+        dynstr = base + shdr[dynstr_idx].sh_offset;
+    }
+
+    Elf32_Sym *syms = NULL;
+    int numsyms = 0;
+    char *str = NULL;
+    if (sym_idx != -1) {
+        syms = (Elf32_Sym*)(base + shdr[sym_idx].sh_offset);
+        numsyms = shdr[sym_idx].sh_size / shdr[sym_idx].sh_entsize;
+        int str_idx = shdr[sym_idx].sh_link;
+        str = base + shdr[str_idx].sh_offset;
+    }
+
+    int dynsymbol_count = 0;
+    if (dynsym_idx != -1) {
+        // Iterate through the dynamic symbol table, and count how many symbols
+        // are actually defined
+        for (int i = 0; i < dynnumsyms; i++) {
+            if (dynsyms[i].st_shndx != SHN_UNDEF) {
+                dynsymbol_count++;
+            }
+        }
+    }
+
+    size_t symbol_count = 0;
+    if (sym_idx != -1) {
+        // Iterate through the symbol table, and count how many symbols
+        // are actually defined
+        for (int i = 0; i < numsyms; i++) {
+            if (syms[i].st_shndx != SHN_UNDEF
+                    && str[syms[i].st_name]
+                    && syms[i].st_value
+                    && syms[i].st_size) {
+                symbol_count++;
+            }
+        }
+    }
+
+    // Now, create an entry in our symbol table structure for each symbol...
+    table->num_symbols += symbol_count + dynsymbol_count;
+    table->symbols = malloc(table->num_symbols * sizeof(symbol_t));
+    if (!table->symbols) {
+        free(table);
+        table = NULL;
+        goto out_unmap;
+    }
+
+    size_t symbol_index = 0;
+    if (dynsym_idx != -1) {
+        // ...and populate them
+        for (int i = 0; i < dynnumsyms; i++) {
+            if (dynsyms[i].st_shndx != SHN_UNDEF) {
+                table->symbols[symbol_index].name = strdup(dynstr + dynsyms[i].st_name);
+                table->symbols[symbol_index].start = dynsyms[i].st_value;
+                table->symbols[symbol_index].end = dynsyms[i].st_value + dynsyms[i].st_size;
+                ALOGV("  [%d] '%s' 0x%08x-0x%08x (DYNAMIC)",
+                        symbol_index, table->symbols[symbol_index].name,
+                        table->symbols[symbol_index].start, table->symbols[symbol_index].end);
+                symbol_index += 1;
+            }
+        }
+    }
+
+    if (sym_idx != -1) {
+        // ...and populate them
+        for (int i = 0; i < numsyms; i++) {
+            if (syms[i].st_shndx != SHN_UNDEF
+                    && str[syms[i].st_name]
+                    && syms[i].st_value
+                    && syms[i].st_size) {
+                table->symbols[symbol_index].name = strdup(str + syms[i].st_name);
+                table->symbols[symbol_index].start = syms[i].st_value;
+                table->symbols[symbol_index].end = syms[i].st_value + syms[i].st_size;
+                ALOGV("  [%d] '%s' 0x%08x-0x%08x",
+                        symbol_index, table->symbols[symbol_index].name,
+                        table->symbols[symbol_index].start, table->symbols[symbol_index].end);
+                symbol_index += 1;
+            }
+        }
+    }
+
+    // Sort the symbol table entries, so they can be bsearched later
+    qsort(table->symbols, table->num_symbols, sizeof(symbol_t), qcompar);
+
+out_unmap:
+    munmap(base, length);
+
+out_close:
+    close(fd);
+
+out:
+    return table;
+}
+
+void free_symbol_table(symbol_table_t* table) {
+    if (table) {
+        for (size_t i = 0; i < table->num_symbols; i++) {
+            free(table->symbols[i].name);
+        }
+        free(table->symbols);
+        free(table);
+    }
+}
+
+const symbol_t* find_symbol(const symbol_table_t* table, uintptr_t addr) {
+    if (!table) return NULL;
+    return (const symbol_t*)bsearch(&addr, table->symbols, table->num_symbols,
+            sizeof(symbol_t), bcompar);
+}
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index effaae0..dcf859b 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -96,6 +96,12 @@
 
 # Shared and static library for target
 # ========================================================
+
+# This is needed in LOCAL_C_INCLUDES to access the C library's private
+# header named <bionic_time.h>
+#
+libcutils_c_includes := bionic/libc/private
+
 include $(CLEAR_VARS)
 LOCAL_MODULE := libcutils
 LOCAL_SRC_FILES := $(commonSources) ashmem-dev.c mq.c android_reboot.c partition_utils.c uevent.c qtaguid.c klog.c
@@ -115,7 +121,7 @@
 endif # !sh
 endif # !arm
 
-LOCAL_C_INCLUDES := $(KERNEL_HEADERS)
+LOCAL_C_INCLUDES := $(libcutils_c_includes) $(KERNEL_HEADERS)
 LOCAL_STATIC_LIBRARIES := liblog
 LOCAL_CFLAGS += $(targetSmpFlag)
 include $(BUILD_STATIC_LIBRARY)
@@ -125,6 +131,7 @@
 LOCAL_WHOLE_STATIC_LIBRARIES := libcutils
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_CFLAGS += $(targetSmpFlag)
+LOCAL_C_INCLUDES := $(libcutils_c_includes)
 include $(BUILD_SHARED_LIBRARY)
 
 include $(CLEAR_VARS)
diff --git a/libdiskconfig/Android.mk b/libdiskconfig/Android.mk
index 9decbb9..b5d83fa 100644
--- a/libdiskconfig/Android.mk
+++ b/libdiskconfig/Android.mk
@@ -19,7 +19,6 @@
 LOCAL_SRC_FILES := $(commonSources)
 LOCAL_MODULE := libdiskconfig_host
 LOCAL_MODULE_TAGS := optional
-LOCAL_SYSTEM_SHARED_LIBRARIES := libcutils
 LOCAL_CFLAGS := -O2 -g -W -Wall -Werror -D_LARGEFILE64_SOURCE
 include $(BUILD_HOST_STATIC_LIBRARY)
 endif # HOST_OS == linux
diff --git a/libion/Android.mk b/libion/Android.mk
new file mode 100644
index 0000000..6abac3c
--- /dev/null
+++ b/libion/Android.mk
@@ -0,0 +1,15 @@
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := ion.c
+LOCAL_MODULE := libion
+LOCAL_MODULE_TAGS := optional
+LOCAL_SHARED_LIBRARIES := liblog
+include $(BUILD_HEAPTRACKED_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := ion.c ion_test.c
+LOCAL_MODULE := iontest
+LOCAL_MODULE_TAGS := optional tests
+LOCAL_SHARED_LIBRARIES := liblog
+include $(BUILD_HEAPTRACKED_EXECUTABLE)
diff --git a/libion/ion.c b/libion/ion.c
new file mode 100644
index 0000000..dbeac23
--- /dev/null
+++ b/libion/ion.c
@@ -0,0 +1,134 @@
+/*
+ *  ion.c
+ *
+ * Memory Allocator functions for ion
+ *
+ *   Copyright 2011 Google, Inc
+ *
+ *  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.
+ */
+#define LOG_TAG "ion"
+
+#include <cutils/log.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/types.h>
+
+#include <linux/ion.h>
+#include <ion/ion.h>
+
+int ion_open()
+{
+        int fd = open("/dev/ion", O_RDWR);
+        if (fd < 0)
+                ALOGE("open /dev/ion failed!\n");
+        return fd;
+}
+
+int ion_close(int fd)
+{
+        return close(fd);
+}
+
+static int ion_ioctl(int fd, int req, void *arg)
+{
+        int ret = ioctl(fd, req, arg);
+        if (ret < 0) {
+                ALOGE("ioctl %x failed with code %d: %s\n", req,
+                       ret, strerror(errno));
+                return -errno;
+        }
+        return ret;
+}
+
+int ion_alloc(int fd, size_t len, size_t align, unsigned int flags,
+              struct ion_handle **handle)
+{
+        int ret;
+        struct ion_allocation_data data = {
+                .len = len,
+                .align = align,
+                .flags = flags,
+        };
+
+        ret = ion_ioctl(fd, ION_IOC_ALLOC, &data);
+        if (ret < 0)
+                return ret;
+        *handle = data.handle;
+        return ret;
+}
+
+int ion_free(int fd, struct ion_handle *handle)
+{
+        struct ion_handle_data data = {
+                .handle = handle,
+        };
+        return ion_ioctl(fd, ION_IOC_FREE, &data);
+}
+
+int ion_map(int fd, struct ion_handle *handle, size_t length, int prot,
+            int flags, off_t offset, unsigned char **ptr, int *map_fd)
+{
+        struct ion_fd_data data = {
+                .handle = handle,
+        };
+
+        int ret = ion_ioctl(fd, ION_IOC_MAP, &data);
+        if (ret < 0)
+                return ret;
+        *map_fd = data.fd;
+        if (*map_fd < 0) {
+                ALOGE("map ioctl returned negative fd\n");
+                return -EINVAL;
+        }
+        *ptr = mmap(NULL, length, prot, flags, *map_fd, offset);
+        if (*ptr == MAP_FAILED) {
+                ALOGE("mmap failed: %s\n", strerror(errno));
+                return -errno;
+        }
+        return ret;
+}
+
+int ion_share(int fd, struct ion_handle *handle, int *share_fd)
+{
+        int map_fd;
+        struct ion_fd_data data = {
+                .handle = handle,
+        };
+
+        int ret = ion_ioctl(fd, ION_IOC_SHARE, &data);
+        if (ret < 0)
+                return ret;
+        *share_fd = data.fd;
+        if (*share_fd < 0) {
+                ALOGE("share ioctl returned negative fd\n");
+                return -EINVAL;
+        }
+        return ret;
+}
+
+int ion_import(int fd, int share_fd, struct ion_handle **handle)
+{
+        struct ion_fd_data data = {
+                .fd = share_fd,
+        };
+
+        int ret = ion_ioctl(fd, ION_IOC_IMPORT, &data);
+        if (ret < 0)
+                return ret;
+        *handle = data.handle;
+        return ret;
+}
diff --git a/libion/ion_test.c b/libion/ion_test.c
new file mode 100644
index 0000000..3f2d7cc
--- /dev/null
+++ b/libion/ion_test.c
@@ -0,0 +1,282 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <sys/mman.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <ion/ion.h>
+#include <linux/ion.h>
+#include <linux/omap_ion.h>
+
+size_t len = 1024*1024, align = 0;
+int prot = PROT_READ | PROT_WRITE;
+int map_flags = MAP_SHARED;
+int alloc_flags = 0;
+int test = -1;
+size_t width = 1024*1024, height = 1024*1024;
+size_t stride;
+
+int _ion_alloc_test(int *fd, struct ion_handle **handle)
+{
+	int ret;
+
+	*fd = ion_open();
+	if (*fd < 0)
+		return *fd;
+
+	ret = ion_alloc(*fd, len, align, alloc_flags, handle);
+
+	if (ret)
+		printf("%s failed: %s\n", __func__, strerror(ret));
+	return ret;
+}
+
+void ion_alloc_test()
+{
+	int fd, ret;
+	struct ion_handle *handle;
+
+	if(_ion_alloc_test(&fd, &handle))
+			return;
+
+	ret = ion_free(fd, handle);
+	if (ret) {
+		printf("%s failed: %s %p\n", __func__, strerror(ret), handle);
+		return;
+	}
+	ion_close(fd);
+	printf("ion alloc test: passed\n");
+}
+
+void ion_map_test()
+{
+	int fd, map_fd, ret;
+	size_t i;
+	struct ion_handle *handle;
+	unsigned char *ptr;
+
+	if(_ion_alloc_test(&fd, &handle))
+		return;
+
+	ret = ion_map(fd, handle, len, prot, map_flags, 0, &ptr, &map_fd);
+	if (ret)
+		return;
+
+	for (i = 0; i < len; i++) {
+		ptr[i] = (unsigned char)i;
+	}
+	for (i = 0; i < len; i++)
+		if (ptr[i] != (unsigned char)i)
+			printf("%s failed wrote %d read %d from mapped "
+			       "memory\n", __func__, i, ptr[i]);
+	/* clean up properly */
+	ret = ion_free(fd, handle);
+	ion_close(fd);
+	munmap(ptr, len);
+	close(map_fd);
+
+	_ion_alloc_test(&fd, &handle);
+	close(fd);
+
+#if 0
+	munmap(ptr, len);
+	close(map_fd);
+	ion_close(fd);
+
+	_ion_alloc_test(len, align, flags, &fd, &handle);
+	close(map_fd);
+	ret = ion_map(fd, handle, len, prot, flags, 0, &ptr, &map_fd);
+	/* don't clean up */
+#endif
+}
+
+void ion_share_test()
+
+{
+	struct ion_handle *handle;
+	int sd[2];
+	int num_fd = 1;
+	struct iovec count_vec = {
+		.iov_base = &num_fd,
+		.iov_len = sizeof num_fd,
+	};
+	char buf[CMSG_SPACE(sizeof(int))];
+	socketpair(AF_UNIX, SOCK_STREAM, 0, sd);
+	if (fork()) {
+		struct msghdr msg = {
+			.msg_control = buf,
+			.msg_controllen = sizeof buf,
+			.msg_iov = &count_vec,
+			.msg_iovlen = 1,
+		};
+
+		struct cmsghdr *cmsg;
+		int fd, share_fd, ret;
+		char *ptr;
+		/* parent */
+		if(_ion_alloc_test(&fd, &handle))
+			return;
+		ret = ion_share(fd, handle, &share_fd);
+		if (ret)
+			printf("share failed %s\n", strerror(errno));
+		ptr = mmap(NULL, len, prot, map_flags, share_fd, 0);
+		if (ptr == MAP_FAILED) {
+			return;
+		}
+		strcpy(ptr, "master");
+		cmsg = CMSG_FIRSTHDR(&msg);
+		cmsg->cmsg_level = SOL_SOCKET;
+		cmsg->cmsg_type = SCM_RIGHTS;
+		cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+		*(int *)CMSG_DATA(cmsg) = share_fd;
+		/* send the fd */
+		printf("master? [%10s] should be [master]\n", ptr);
+		printf("master sending msg 1\n");
+		sendmsg(sd[0], &msg, 0);
+		if (recvmsg(sd[0], &msg, 0) < 0)
+			perror("master recv msg 2");
+		printf("master? [%10s] should be [child]\n", ptr);
+
+		/* send ping */
+		sendmsg(sd[0], &msg, 0);
+		printf("master->master? [%10s]\n", ptr);
+		if (recvmsg(sd[0], &msg, 0) < 0)
+			perror("master recv 1");
+	} else {
+		struct msghdr msg;
+		struct cmsghdr *cmsg;
+		char* ptr;
+		int fd, recv_fd;
+		char* child_buf[100];
+		/* child */
+		struct iovec count_vec = {
+			.iov_base = child_buf,
+			.iov_len = sizeof child_buf,
+		};
+
+		struct msghdr child_msg = {
+			.msg_control = buf,
+			.msg_controllen = sizeof buf,
+			.msg_iov = &count_vec,
+			.msg_iovlen = 1,
+		};
+
+		if (recvmsg(sd[1], &child_msg, 0) < 0)
+			perror("child recv msg 1");
+		cmsg = CMSG_FIRSTHDR(&child_msg);
+		if (cmsg == NULL) {
+			printf("no cmsg rcvd in child");
+			return;
+		}
+		recv_fd = *(int*)CMSG_DATA(cmsg);
+		if (recv_fd < 0) {
+			printf("could not get recv_fd from socket");
+			return;
+		}
+		printf("child %d\n", recv_fd);
+		fd = ion_open();
+		ptr = mmap(NULL, len, prot, map_flags, recv_fd, 0);
+		if (ptr == MAP_FAILED) {
+			return;
+		}
+		printf("child? [%10s] should be [master]\n", ptr);
+		strcpy(ptr, "child");
+		printf("child sending msg 2\n");
+		sendmsg(sd[1], &child_msg, 0);
+	}
+}
+
+int main(int argc, char* argv[]) {
+	int c;
+	enum tests {
+		ALLOC_TEST = 0, MAP_TEST, SHARE_TEST,
+	};
+
+	while (1) {
+		static struct option opts[] = {
+			{"alloc", no_argument, 0, 'a'},
+			{"alloc_flags", required_argument, 0, 'f'},
+			{"map", no_argument, 0, 'm'},
+			{"share", no_argument, 0, 's'},
+			{"len", required_argument, 0, 'l'},
+			{"align", required_argument, 0, 'g'},
+			{"map_flags", required_argument, 0, 'z'},
+			{"prot", required_argument, 0, 'p'},
+			{"width", required_argument, 0, 'w'},
+			{"height", required_argument, 0, 'h'},
+		};
+		int i = 0;
+		c = getopt_long(argc, argv, "af:h:l:mr:stw:", opts, &i);
+		if (c == -1)
+			break;
+
+		switch (c) {
+		case 'l':
+			len = atol(optarg);
+			break;
+		case 'g':
+			align = atol(optarg);
+			break;
+		case 'z':
+			map_flags = 0;
+			map_flags |= strstr(optarg, "PROT_EXEC") ?
+				PROT_EXEC : 0;
+			map_flags |= strstr(optarg, "PROT_READ") ?
+				PROT_READ: 0;
+			map_flags |= strstr(optarg, "PROT_WRITE") ?
+				PROT_WRITE: 0;
+			map_flags |= strstr(optarg, "PROT_NONE") ?
+				PROT_NONE: 0;
+			break;
+		case 'p':
+			prot = 0;
+			prot |= strstr(optarg, "MAP_PRIVATE") ?
+				MAP_PRIVATE	 : 0;
+			prot |= strstr(optarg, "MAP_SHARED") ?
+				MAP_PRIVATE	 : 0;
+			break;
+		case 'f':
+			alloc_flags = atol(optarg);
+			break;
+		case 'a':
+			test = ALLOC_TEST;
+			break;
+		case 'm':
+			test = MAP_TEST;
+			break;
+		case 's':
+			test = SHARE_TEST;
+			break;
+		case 'w':
+			width = atol(optarg);
+			break;
+		case 'h':
+			height = atol(optarg);
+			break;
+		}
+	}
+	printf("test %d, len %u, width %u, height %u align %u, "
+		   "map_flags %d, prot %d, alloc_flags %d\n", test, len, width,
+		   height, align, map_flags, prot, alloc_flags);
+	switch (test) {
+		case ALLOC_TEST:
+			ion_alloc_test();
+			break;
+		case MAP_TEST:
+			ion_map_test();
+			break;
+		case SHARE_TEST:
+			ion_share_test();
+			break;
+		default:
+			printf("must specify a test (alloc, map, share)\n");
+	}
+	return 0;
+}
diff --git a/libnetutils/dhcp_utils.c b/libnetutils/dhcp_utils.c
old mode 100755
new mode 100644
index 1e08eb6..d18931b
--- a/libnetutils/dhcp_utils.c
+++ b/libnetutils/dhcp_utils.c
@@ -145,6 +145,11 @@
 /*
  * Start the dhcp client daemon, and wait for it to finish
  * configuring the interface.
+ *
+ * The device init.rc file needs a corresponding entry for this work.
+ *
+ * Example:
+ * service dhcpcd_<interface> /system/bin/dhcpcd -ABKL
  */
 int dhcp_do_request(const char *interface,
                     char *ipaddr,
@@ -287,8 +292,11 @@
 }
 
 /**
- * Run WiMAX dhcp renew service.
- * "wimax_renew" service shoud be included in init.rc.
+ * The device init.rc file needs a corresponding entry.
+ *
+ * Example:
+ * service iprenew_<interface> /system/bin/dhcpcd -n
+ *
  */
 int dhcp_do_request_renew(const char *interface,
                     in_addr_t *ipaddr,
diff --git a/libsysutils/Android.mk b/libsysutils/Android.mk
index cccf484..57cc313 100644
--- a/libsysutils/Android.mk
+++ b/libsysutils/Android.mk
@@ -12,6 +12,7 @@
                   src/FrameworkCommand.cpp    \
                   src/SocketClient.cpp        \
                   src/ServiceManager.cpp      \
+                  EventLogTags.logtags
 
 LOCAL_MODULE:= libsysutils
 
diff --git a/libsysutils/EventLogTags.logtags b/libsysutils/EventLogTags.logtags
new file mode 100644
index 0000000..27785f0
--- /dev/null
+++ b/libsysutils/EventLogTags.logtags
@@ -0,0 +1,4 @@
+# See system/core/logcat/event.logtags for a description of the format of this file.
+
+# FrameworkListener dispatchCommand overflow
+78001 dispatchCommand_overflow
diff --git a/libsysutils/src/FrameworkListener.cpp b/libsysutils/src/FrameworkListener.cpp
index 3416ceb..90be754 100644
--- a/libsysutils/src/FrameworkListener.cpp
+++ b/libsysutils/src/FrameworkListener.cpp
@@ -159,6 +159,7 @@
     return;
 
 overflow:
+    LOG_EVENT_INT(78001, cli->getUid());
     cli->sendMsg(500, "Command too long", false);
     goto out;
 }
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index ae56c41..b71ce86 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -253,7 +253,7 @@
     int max = 0;
     int ret;
     int queued_lines = 0;
-    bool sleep = true;
+    bool sleep = false;
 
     int result;
     fd_set readset;
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 290e375..7299513 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -70,6 +70,9 @@
     write /proc/sys/kernel/sched_compat_yield 1
     write /proc/sys/kernel/sched_child_runs_first 0
     write /proc/sys/kernel/randomize_va_space 2
+    write /proc/sys/kernel/kptr_restrict 2
+    write /proc/sys/kernel/dmesg_restrict 1
+    write /proc/sys/vm/mmap_min_addr 32768
 
 # Create cgroup mount points for process groups
     mkdir /dev/cpuctl
@@ -414,7 +417,7 @@
 
 service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
     class main
-    socket zygote stream 666
+    socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
     onrestart restart media
diff --git a/run-as/Android.mk b/run-as/Android.mk
index 326f5af..043cc3a 100644
--- a/run-as/Android.mk
+++ b/run-as/Android.mk
@@ -5,8 +5,4 @@
 
 LOCAL_MODULE:= run-as
 
-LOCAL_FORCE_STATIC_EXECUTABLE := true
-
-LOCAL_STATIC_LIBRARIES := libc
-
 include $(BUILD_EXECUTABLE)
diff --git a/run-as/package.c b/run-as/package.c
index ca08436..143d647 100644
--- a/run-as/package.c
+++ b/run-as/package.c
@@ -18,6 +18,7 @@
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/stat.h>
+#include <sys/mman.h>
 #include <private/android_filesystem_config.h>
 #include "package.h"
 
@@ -43,9 +44,6 @@
 /* The file containing the list of installed packages on the system */
 #define PACKAGES_LIST_FILE  "/data/system/packages.list"
 
-/* This should be large enough to hold the content of the package database file */
-#define PACKAGES_LIST_BUFFER_SIZE  65536
-
 /* Copy 'srclen' string bytes from 'src' into buffer 'dst' of size 'dstlen'
  * This function always zero-terminate the destination buffer unless
  * 'dstlen' is 0, even in case of overflow.
@@ -67,40 +65,73 @@
     *dst = '\0'; /* zero-terminate result */
 }
 
-/* Read up to 'buffsize' bytes into 'buff' from the file
- * named 'filename'. Return byte length on success, or -1
- * on error.
+/* Open 'filename' and map it into our address-space.
+ * Returns buffer address, or NULL on error
+ * On exit, *filesize will be set to the file's size, or 0 on error
  */
-static int
-read_file(const char* filename, char* buff, size_t buffsize)
+static void*
+map_file(const char* filename, size_t* filesize)
 {
-    int  fd, len, old_errno;
+    int  fd, ret, old_errno;
+    struct stat  st;
+    size_t  length = 0;
+    void*   address = NULL;
 
-    /* check the input buffer size */
-    if (buffsize >= INT_MAX) {
-        errno = EINVAL;
-        return -1;
-    }
+    *filesize = 0;
 
     /* open the file for reading */
-    do {
-        fd = open(filename, O_RDONLY);
-    } while (fd < 0 && errno == EINTR);
-
+    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
     if (fd < 0)
-        return -1;
+        return NULL;
 
-    /* read the content */
-    do {
-        len = read(fd, buff, buffsize);
-    } while (len < 0 && errno == EINTR);
+    /* get its size */
+    ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
+    if (ret < 0)
+        goto EXIT;
 
+    /* Ensure that the file is owned by the system user */
+    if ((st.st_uid != AID_SYSTEM) || (st.st_gid != AID_SYSTEM)) {
+        goto EXIT;
+    }
+
+    /* Ensure that the file has sane permissions */
+    if ((st.st_mode & S_IWOTH) != 0) {
+        goto EXIT;
+    }
+
+    /* Ensure that the size is not ridiculously large */
+    length = (size_t)st.st_size;
+    if ((off_t)length != st.st_size) {
+        errno = ENOMEM;
+        goto EXIT;
+    }
+
+    /* Memory-map the file now */
+    address = TEMP_FAILURE_RETRY(mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0));
+    if (address == MAP_FAILED) {
+        address = NULL;
+        goto EXIT;
+    }
+
+    /* We're good, return size */
+    *filesize = length;
+
+EXIT:
     /* close the file, preserve old errno for better diagnostics */
     old_errno = errno;
     close(fd);
     errno = old_errno;
 
-    return len;
+    return address;
+}
+
+/* unmap the file, but preserve errno */
+static void
+unmap_file(void*  address, size_t  size)
+{
+    int old_errno = errno;
+    TEMP_FAILURE_RETRY(munmap(address, size));
+    errno = old_errno;
 }
 
 /* Check that a given directory:
@@ -371,18 +402,18 @@
 int
 get_package_info(const char* pkgName, PackageInfo *info)
 {
-    static char  buffer[PACKAGES_LIST_BUFFER_SIZE];
-    int          buffer_len;
+    char*        buffer;
+    size_t       buffer_len;
     const char*  p;
     const char*  buffer_end;
-    int          result;
+    int          result = -1;
 
     info->uid          = 0;
     info->isDebuggable = 0;
     info->dataDir[0]   = '\0';
 
-    buffer_len = read_file(PACKAGES_LIST_FILE, buffer, sizeof buffer);
-    if (buffer_len < 0)
+    buffer = map_file(PACKAGES_LIST_FILE, &buffer_len);
+    if (buffer == NULL)
         return -1;
 
     p          = buffer;
@@ -455,7 +486,8 @@
         string_copy(info->dataDir, sizeof info->dataDir, p, q - p);
 
         /* Ignore the rest */
-        return 0;
+        result = 0;
+        goto EXIT;
 
     NEXT_LINE:
         p = next;
@@ -463,9 +495,14 @@
 
     /* the package is unknown */
     errno = ENOENT;
-    return -1;
+    result = -1;
+    goto EXIT;
 
 BAD_FORMAT:
     errno = EINVAL;
-    return -1;
+    result = -1;
+
+EXIT:
+    unmap_file(buffer, buffer_len);
+    return result;
 }
diff --git a/run-as/run-as.c b/run-as/run-as.c
index d2a44e1..20e1530 100644
--- a/run-as/run-as.c
+++ b/run-as/run-as.c
@@ -41,9 +41,9 @@
  *
  *  - This program should only run for the 'root' or 'shell' users
  *
- *  - Statically link against the C library, and avoid anything that
- *    is more complex than simple system calls until the uid/gid has
- *    been dropped to that of a normal user or you are sure to exit.
+ *  - Avoid anything that is more complex than simple system calls
+ *    until the uid/gid has been dropped to that of a normal user
+ *    or you are sure to exit.
  *
  *    This avoids depending on environment variables, system properties
  *    and other external factors that may affect the C library in
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index 9daeed3..be95e7c 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -55,7 +55,8 @@
 	nandread \
 	ionice \
 	touch \
-	lsof
+	lsof \
+	md5
 
 ifeq ($(HAVE_SELINUX),true)
 
@@ -83,6 +84,8 @@
 
 LOCAL_SHARED_LIBRARIES := libcutils libc libusbhost
 
+LOCAL_C_INCLUDES := bionic/libc/bionic
+
 ifeq ($(HAVE_SELINUX),true)
 
 LOCAL_CFLAGS += -DHAVE_SELINUX
diff --git a/toolbox/getevent.c b/toolbox/getevent.c
index 352f6f9..5f5e16b 100644
--- a/toolbox/getevent.c
+++ b/toolbox/getevent.c
@@ -643,7 +643,7 @@
                         return 1;
                     }
                     if(get_time) {
-                        printf("%ld-%ld: ", event.time.tv_sec, event.time.tv_usec);
+                        printf("[%8ld.%06ld] ", event.time.tv_sec, event.time.tv_usec);
                     }
                     if(print_device)
                         printf("%s: ", device_names[i]);
diff --git a/toolbox/hd.c b/toolbox/hd.c
index da31245..0d2f96a 100644
--- a/toolbox/hd.c
+++ b/toolbox/hd.c
@@ -68,6 +68,8 @@
 			if(count > 0 && base + count - filepos < read_len)
 				read_len = base + count - filepos;
 	        res = read(fd, &buf, read_len);
+			if(res == 0)
+				break;
 			for(i = 0; i < res; i++) {
 				if((i & 15) == 0) {
 					printf("%08x: ", filepos + i);
@@ -80,7 +82,7 @@
 					lsum = 0;
 				}
 			}
-			if(res <= 0) {
+			if(res < 0) {
 				printf("Read error on %s, offset %d len %d, %s\n", argv[optind], filepos, read_len, strerror(errno));
 				return 1;
 			}
diff --git a/toolbox/lsof.c b/toolbox/lsof.c
index 4e2f77a..376a642 100644
--- a/toolbox/lsof.c
+++ b/toolbox/lsof.c
@@ -178,8 +178,7 @@
     if (!stat(info.path, &pidstat)) {
         pw = getpwuid(pidstat.st_uid);
         if (pw) {
-            strncpy(info.user, pw->pw_name, USER_DISPLAY_MAX - 1);
-            info.user[USER_DISPLAY_MAX - 1] = '\0';
+            strlcpy(info.user, pw->pw_name, sizeof(info.user));
         } else {
             snprintf(info.user, USER_DISPLAY_MAX, "%d", (int)pidstat.st_uid);
         }
@@ -194,18 +193,20 @@
         fprintf(stderr, "Couldn't read %s\n", info.path);
         return;
     }
+
     char cmdline[PATH_MAX];
-    if (read(fd, cmdline, sizeof(cmdline)) < 0) {
+    int numRead = read(fd, cmdline, sizeof(cmdline) - 1);
+    close(fd);
+
+    if (numRead < 0) {
         fprintf(stderr, "Error reading cmdline: %s: %s\n", info.path, strerror(errno));
-        close(fd);
         return;
     }
-    close(fd);
-    info.path[info.parent_length] = '\0';
+
+    cmdline[numRead] = '\0';
 
     // We only want the basename of the cmdline
-    strncpy(info.cmdline, basename(cmdline), sizeof(info.cmdline));
-    info.cmdline[sizeof(info.cmdline)-1] = '\0';
+    strlcpy(info.cmdline, basename(cmdline), sizeof(info.cmdline));
 
     // Read each of these symlinks
     print_type("cwd", &info);
diff --git a/toolbox/md5.c b/toolbox/md5.c
new file mode 100644
index 0000000..2fb8b05
--- /dev/null
+++ b/toolbox/md5.c
@@ -0,0 +1,77 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <md5.h>
+
+/* When this was written, bionic's md5.h did not define this. */
+#ifndef MD5_DIGEST_LENGTH
+#define MD5_DIGEST_LENGTH 16
+#endif
+
+static int usage()
+{
+    fprintf(stderr,"md5 file ...\n");
+    return -1;
+}
+
+static int do_md5(const char *path)
+{
+    unsigned int i;
+    int fd;
+    MD5_CTX md5_ctx;
+    unsigned char md5[MD5_DIGEST_LENGTH];
+
+    fd = open(path, O_RDONLY);
+    if (fd < 0) {
+        fprintf(stderr,"could not open %s, %s\n", path, strerror(errno));
+        return -1;
+    }
+
+    /* Note that bionic's MD5_* functions return void. */
+    MD5_Init(&md5_ctx);
+
+    while (1) {
+        char buf[4096];
+        ssize_t rlen;
+        rlen = read(fd, buf, sizeof(buf));
+        if (rlen == 0)
+            break;
+        else if (rlen < 0) {
+            (void)close(fd);
+            fprintf(stderr,"could not read %s, %s\n", path, strerror(errno));
+            return -1;
+        }
+        MD5_Update(&md5_ctx, buf, rlen);
+    }
+    if (close(fd)) {
+        fprintf(stderr,"could not close %s, %s\n", path, strerror(errno));
+        return -1;
+    }
+
+    MD5_Final(md5, &md5_ctx);
+
+    for (i = 0; i < (int)sizeof(md5); i++)
+        printf("%02x", md5[i]);
+    printf("  %s\n", path);
+
+    return 0;
+}
+
+int md5_main(int argc, char *argv[])
+{
+    int i, ret = 0;
+
+    if (argc < 2)
+        return usage();
+
+    /* loop over the file args */
+    for (i = 1; i < argc; i++) {
+        if (do_md5(argv[i]))
+            ret = 1;
+    }
+
+    return ret;
+}