am a9b84a7e: Add ALOG version of LOG_ASSERT

* commit 'a9b84a7e0b3ecb389a62bc6abb8c2fea3a4a30a6':
  Add ALOG version of LOG_ASSERT
diff --git a/adb/adb.c b/adb/adb.c
index e35c334..6dbd562 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;
 }
 
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 4431ba7..d985ee3 100644
--- a/adb/transport_local.c
+++ b/adb/transport_local.c
@@ -185,6 +185,117 @@
     return 0;
 }
 
+/* This is relevant only for ADB daemon running inside the emulator. */
+#if !ADB_HOST
+/*
+ * Redefine open and write for qemu_pipe.h that contains inlined references
+ * to those routines. We will redifine them back after qemu_pipe.h inclusion.
+ */
+#undef open
+#undef write
+#define open    adb_open
+#define write   adb_write
+#include <hardware/qemu_pipe.h>
+#undef open
+#undef write
+#define open    ___xxx_open
+#define write   ___xxx_write
+
+/* A worker thread that monitors host connections, and registers a transport for
+ * every new host connection. This thread replaces server_socket_thread on
+ * condition that adbd daemon runs inside the emulator, and emulator uses QEMUD
+ * pipe to communicate with adbd daemon inside the guest. This is done in order
+ * to provide more robust communication channel between ADB host and guest. The
+ * main issue with server_socket_thread approach is that it runs on top of TCP,
+ * and thus is sensitive to network disruptions. For instance, the
+ * ConnectionManager may decide to reset all network connections, in which case
+ * the connection between ADB host and guest will be lost. To make ADB traffic
+ * independent from the network, we use here 'adb' QEMUD service to transfer data
+ * between the host, and the guest. See external/qemu/android/adb-*.* that
+ * implements the emulator's side of the protocol. Another advantage of using
+ * QEMUD approach is that ADB will be up much sooner, since it doesn't depend
+ * anymore on network being set up.
+ * The guest side of the protocol contains the following phases:
+ * - Connect with adb QEMUD service. In this phase a handle to 'adb' QEMUD service
+ *   is opened, and it becomes clear whether or not emulator supports that
+ *   protocol.
+ * - Wait for the ADB host to create connection with the guest. This is done by
+ *   sending an 'accept' request to the adb QEMUD service, and waiting on
+ *   response.
+ * - When new ADB host connection is accepted, the connection with adb QEMUD
+ *   service is registered as the transport, and a 'start' request is sent to the
+ *   adb QEMUD service, indicating that the guest is ready to receive messages.
+ *   Note that the guest will ignore messages sent down from the emulator before
+ *   the transport registration is completed. That's why we need to send the
+ *   'start' request after the transport is registered.
+ */
+static void *qemu_socket_thread(void * arg)
+{
+/* 'accept' request to the adb QEMUD service. */
+static const char _accept_req[] = "accept";
+/* 'start' request to the adb QEMUD service. */
+static const char _start_req[]  = "start";
+/* 'ok' reply from the adb QEMUD service. */
+static const char _ok_resp[]    = "ok";
+
+    const int port = (int)arg;
+    int res, fd;
+    char tmp[256];
+    char con_name[32];
+
+    D("transport: qemu_socket_thread() starting\n");
+
+    /* adb QEMUD service connection request. */
+    snprintf(con_name, sizeof(con_name), "qemud:adb:%d", port);
+
+    /* Connect to the adb QEMUD service. */
+    fd = qemu_pipe_open(con_name);
+    if (fd < 0) {
+        /* This could be an older version of the emulator, that doesn't
+         * implement adb QEMUD service. Fall back to the old TCP way. */
+        adb_thread_t thr;
+        D("adb service is not available. Falling back to TCP socket.\n");
+        adb_thread_create(&thr, server_socket_thread, arg);
+        return 0;
+    }
+
+    for(;;) {
+        /*
+         * Wait till the host creates a new connection.
+         */
+
+        /* Send the 'accept' request. */
+        res = adb_write(fd, _accept_req, strlen(_accept_req));
+        if (res == strlen(_accept_req)) {
+            /* Wait for the response. In the response we expect 'ok' on success,
+             * or 'ko' on failure. */
+            res = adb_read(fd, tmp, sizeof(tmp));
+            if (res != 2 || memcmp(tmp, _ok_resp, 2)) {
+                D("Accepting ADB host connection has failed.\n");
+                adb_close(fd);
+            } else {
+                /* Host is connected. Register the transport, and start the
+                 * exchange. */
+                register_socket_transport(fd, "host", port, 1);
+                adb_write(fd, _start_req, strlen(_start_req));
+            }
+
+            /* Prepare for accepting of the next ADB host connection. */
+            fd = qemu_pipe_open(con_name);
+            if (fd < 0) {
+                D("adb service become unavailable.\n");
+                return 0;
+            }
+        } else {
+            D("Unable to send the '%s' request to ADB service.\n", _accept_req);
+            return 0;
+        }
+    }
+    D("transport: qemu_socket_thread() exiting\n");
+    return 0;
+}
+#endif  // !ADB_HOST
+
 void local_init(int port)
 {
     adb_thread_t thr;
@@ -193,7 +304,21 @@
     if(HOST) {
         func = client_socket_thread;
     } else {
+#if ADB_HOST
         func = server_socket_thread;
+#else
+        /* For the adbd daemon in the system image we need to distinguish
+         * between the device, and the emulator. */
+        char is_qemu[PROPERTY_VALUE_MAX];
+        property_get("ro.kernel.qemu", is_qemu, "");
+        if (!strcmp(is_qemu, "1")) {
+            /* Running inside the emulator: use QEMUD pipe as the transport. */
+            func = qemu_socket_thread;
+        } else {
+            /* Running inside the device: use TCP socket as the transport. */
+            func = server_socket_thread;
+        }
+#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/fastboot.c b/fastboot/fastboot.c
index 4a2de20..0639f3b 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 {
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 139226f..5123901 100644
--- a/include/cutils/log.h
+++ b/include/cutils/log.h
@@ -47,7 +47,7 @@
 // ---------------------------------------------------------------------
 
 /*
- * Normally we strip LOGV (VERBOSE messages) from release builds.
+ * Normally we strip ALOGV (VERBOSE messages) from release builds.
  * You can modify this (for example with "#define LOG_NDEBUG 0"
  * at the top of your source file) to change that behavior.
  */
@@ -73,91 +73,81 @@
 /*
  * Simplified macro to send a verbose log message using the current LOG_TAG.
  */
-#ifndef LOGV
+#ifndef ALOGV
 #if LOG_NDEBUG
-#define LOGV(...)   ((void)0)
+#define ALOGV(...)   ((void)0)
 #else
-#define LOGV(...) ((void)LOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
+#define ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
 #endif
-#define ALOGV LOGV
 #endif
 
 #define CONDITION(cond)     (__builtin_expect((cond)!=0, 0))
 
-#ifndef LOGV_IF
+#ifndef ALOGV_IF
 #if LOG_NDEBUG
-#define LOGV_IF(cond, ...)   ((void)0)
+#define ALOGV_IF(cond, ...)   ((void)0)
 #else
-#define LOGV_IF(cond, ...) \
+#define ALOGV_IF(cond, ...) \
     ( (CONDITION(cond)) \
-    ? ((void)LOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
+    ? ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
 #endif
-#define ALOGV_IF LOGV_IF
 #endif
 
 /*
  * Simplified macro to send a debug log message using the current LOG_TAG.
  */
-#ifndef LOGD
-#define LOGD(...) ((void)LOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__))
-#define ALOGD LOGD
+#ifndef ALOGD
+#define ALOGD(...) ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__))
 #endif
 
-#ifndef LOGD_IF
-#define LOGD_IF(cond, ...) \
+#ifndef ALOGD_IF
+#define ALOGD_IF(cond, ...) \
     ( (CONDITION(cond)) \
-    ? ((void)LOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
+    ? ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
-#define ALOGD_IF LOGD_IF
 #endif
 
 /*
  * Simplified macro to send an info log message using the current LOG_TAG.
  */
-#ifndef LOGI
-#define LOGI(...) ((void)LOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
-#define ALOGI LOGI
+#ifndef ALOGI
+#define ALOGI(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
 #endif
 
-#ifndef LOGI_IF
-#define LOGI_IF(cond, ...) \
+#ifndef ALOGI_IF
+#define ALOGI_IF(cond, ...) \
     ( (CONDITION(cond)) \
-    ? ((void)LOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \
+    ? ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
-#define ALOGI_IF LOGI_IF
 #endif
 
 /*
  * Simplified macro to send a warning log message using the current LOG_TAG.
  */
-#ifndef LOGW
-#define LOGW(...) ((void)LOG(LOG_WARN, LOG_TAG, __VA_ARGS__))
-#define ALOGW LOGW
+#ifndef ALOGW
+#define ALOGW(...) ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__))
 #endif
 
-#ifndef LOGW_IF
-#define LOGW_IF(cond, ...) \
+#ifndef ALOGW_IF
+#define ALOGW_IF(cond, ...) \
     ( (CONDITION(cond)) \
-    ? ((void)LOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \
+    ? ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
-#define ALOGW_IF LOGW_IF
 #endif
 
 /*
  * Simplified macro to send an error log message using the current LOG_TAG.
  */
-#ifndef LOGE
-#define LOGE(...) ((void)LOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
-#define ALOGE LOGE
+#ifndef ALOGE
+#define ALOGE(...) ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
 #endif
 
-#ifndef LOGE_IF
-#define LOGE_IF(cond, ...) \
+#ifndef ALOGE_IF
+#define ALOGE_IF(cond, ...) \
     ( (CONDITION(cond)) \
-    ? ((void)LOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
+    ? ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
     : (void)0 )
-#define ALOGE_IF LOGE_IF
 #endif
 
 // ---------------------------------------------------------------------
@@ -166,49 +156,44 @@
  * Conditional based on whether the current LOG_TAG is enabled at
  * verbose priority.
  */
-#ifndef IF_LOGV
+#ifndef IF_ALOGV
 #if LOG_NDEBUG
-#define IF_LOGV() if (false)
+#define IF_ALOGV() if (false)
 #else
-#define IF_LOGV() IF_LOG(LOG_VERBOSE, LOG_TAG)
+#define IF_ALOGV() IF_ALOG(LOG_VERBOSE, LOG_TAG)
 #endif
-#define IF_ALOGV IF_LOGV
 #endif
 
 /*
  * Conditional based on whether the current LOG_TAG is enabled at
  * debug priority.
  */
-#ifndef IF_LOGD
-#define IF_LOGD() IF_LOG(LOG_DEBUG, LOG_TAG)
-#define IF_ALOGD IF_LOGD
+#ifndef IF_ALOGD
+#define IF_ALOGD() IF_ALOG(LOG_DEBUG, LOG_TAG)
 #endif
 
 /*
  * Conditional based on whether the current LOG_TAG is enabled at
  * info priority.
  */
-#ifndef IF_LOGI
-#define IF_LOGI() IF_LOG(LOG_INFO, LOG_TAG)
-#define IF_ALOGI IF_LOGI
+#ifndef IF_ALOGI
+#define IF_ALOGI() IF_ALOG(LOG_INFO, LOG_TAG)
 #endif
 
 /*
  * Conditional based on whether the current LOG_TAG is enabled at
  * warn priority.
  */
-#ifndef IF_LOGW
-#define IF_LOGW() IF_LOG(LOG_WARN, LOG_TAG)
-#define IF_ALOGW IF_LOGW
+#ifndef IF_ALOGW
+#define IF_ALOGW() IF_ALOG(LOG_WARN, LOG_TAG)
 #endif
 
 /*
  * Conditional based on whether the current LOG_TAG is enabled at
  * error priority.
  */
-#ifndef IF_LOGE
-#define IF_LOGE() IF_LOG(LOG_ERROR, LOG_TAG)
-#define IF_ALOGE IF_LOGE
+#ifndef IF_ALOGE
+#define IF_ALOGE() IF_ALOG(LOG_ERROR, LOG_TAG)
 #endif
 
 
@@ -356,12 +341,12 @@
  * Basic log message macro.
  *
  * Example:
- *  LOG(LOG_WARN, NULL, "Failed with error %d", errno);
+ *  ALOG(LOG_WARN, NULL, "Failed with error %d", errno);
  *
  * The second argument may be NULL or "" to indicate the "global" tag.
  */
-#ifndef LOG
-#define LOG(priority, tag, ...) \
+#ifndef ALOG
+#define ALOG(priority, tag, ...) \
     LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
 #endif
 
@@ -384,8 +369,8 @@
 /*
  * Conditional given a desired logging priority and tag.
  */
-#ifndef IF_LOG
-#define IF_LOG(priority, tag) \
+#ifndef IF_ALOG
+#define IF_ALOG(priority, tag) \
     if (android_testLog(ANDROID_##priority, tag))
 #endif
 
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/init/builtins.c b/init/builtins.c
index eccda3f..3781dcd 100644
--- a/init/builtins.c
+++ b/init/builtins.c
@@ -31,6 +31,7 @@
 #include <sys/resource.h>
 #include <linux/loop.h>
 #include <cutils/partition_utils.h>
+#include <sys/system_properties.h>
 
 #include "init.h"
 #include "keywords.h"
@@ -448,22 +449,15 @@
 {
     const char *name = args[1];
     const char *value = args[2];
+    char prop_val[PROP_VALUE_MAX];
+    int ret;
 
-    if (value[0] == '$') {
-        /* Use the value of a system property if value starts with '$' */
-        value++;
-        if (value[0] != '$') {
-            value = property_get(value);
-            if (!value) {
-                ERROR("property %s has no value for assigning to %s\n", value, name);
-                return -EINVAL;
-            }
-        } /* else fall through to support double '$' prefix for setting properties
-           * to string literals that start with '$'
-           */
+    ret = expand_props(prop_val, value, sizeof(prop_val));
+    if (ret) {
+        ERROR("cannot expand '%s' while assigning to '%s'\n", value, name);
+        return -EINVAL;
     }
-
-    property_set(name, value);
+    property_set(name, prop_val);
     return 0;
 }
 
@@ -547,21 +541,15 @@
 {
     const char *path = args[1];
     const char *value = args[2];
-    if (value[0] == '$') {
-        /* Write the value of a system property if value starts with '$' */
-        value++;
-        if (value[0] != '$') {
-            value = property_get(value);
-            if (!value) {
-                ERROR("property %s has no value for writing to %s\n", value, path);
-                return -EINVAL;
-            }
-        } /* else fall through to support double '$' prefix for writing
-           * string literals that start with '$'
-           */
-    }
+    char prop_val[PROP_VALUE_MAX];
+    int ret;
 
-    return write_file(path, value);
+    ret = expand_props(prop_val, value, sizeof(prop_val));
+    if (ret) {
+        ERROR("cannot expand '%s' while writing to '%s'\n", value, path);
+        return -EINVAL;
+    }
+    return write_file(path, prop_val);
 }
 
 int do_copy(int nargs, char **args)
diff --git a/init/init.c b/init/init.c
index d10ca47..c3be93d 100755
--- a/init/init.c
+++ b/init/init.c
@@ -59,11 +59,7 @@
 #endif
 
 static char console[32];
-static char serialno[32];
 static char bootmode[32];
-static char baseband[32];
-static char carrier[32];
-static char bootloader[32];
 static char hardware[32];
 static unsigned revision = 0;
 static char qemu[32];
@@ -420,45 +416,6 @@
     }
 }
 
-static void import_kernel_nv(char *name, int in_qemu)
-{
-    char *value = strchr(name, '=');
-
-    if (value == 0) return;
-    *value++ = 0;
-    if (*name == 0) return;
-
-    if (!in_qemu)
-    {
-        /* on a real device, white-list the kernel options */
-        if (!strcmp(name,"qemu")) {
-            strlcpy(qemu, value, sizeof(qemu));
-        } else if (!strcmp(name,"androidboot.console")) {
-            strlcpy(console, value, sizeof(console));
-        } else if (!strcmp(name,"androidboot.mode")) {
-            strlcpy(bootmode, value, sizeof(bootmode));
-        } else if (!strcmp(name,"androidboot.serialno")) {
-            strlcpy(serialno, value, sizeof(serialno));
-        } else if (!strcmp(name,"androidboot.baseband")) {
-            strlcpy(baseband, value, sizeof(baseband));
-        } else if (!strcmp(name,"androidboot.carrier")) {
-            strlcpy(carrier, value, sizeof(carrier));
-        } else if (!strcmp(name,"androidboot.bootloader")) {
-            strlcpy(bootloader, value, sizeof(bootloader));
-        } else if (!strcmp(name,"androidboot.hardware")) {
-            strlcpy(hardware, value, sizeof(hardware));
-        }
-    } else {
-        /* in the emulator, export any kernel option with the
-         * ro.kernel. prefix */
-        char  buff[32];
-        int   len = snprintf( buff, sizeof(buff), "ro.kernel.%s", name );
-        if (len < (int)sizeof(buff)) {
-            property_set( buff, value );
-        }
-    }
-}
-
 static struct command *get_first_command(struct action *act)
 {
     struct listnode *node;
@@ -518,17 +475,6 @@
     return ret;
 }
 
-static int property_init_action(int nargs, char **args)
-{
-    bool load_defaults = true;
-
-    INFO("property init\n");
-    if (!strcmp(bootmode, "charger"))
-        load_defaults = false;
-    property_init(load_defaults);
-    return 0;
-}
-
 static int keychord_init_action(int nargs, char **args)
 {
     keychord_init();
@@ -576,30 +522,104 @@
     return 0;
 }
 
-static int set_init_properties_action(int nargs, char **args)
+static void import_kernel_nv(char *name, int for_emulator)
+{
+    char *value = strchr(name, '=');
+    int name_len = strlen(name);
+
+    if (value == 0) return;
+    *value++ = 0;
+    if (name_len == 0) return;
+
+    if (for_emulator) {
+        /* in the emulator, export any kernel option with the
+         * ro.kernel. prefix */
+        char buff[PROP_NAME_MAX];
+        int len = snprintf( buff, sizeof(buff), "ro.kernel.%s", name );
+
+        if (len < (int)sizeof(buff))
+            property_set( buff, value );
+        return;
+    }
+
+    if (!strcmp(name,"qemu")) {
+        strlcpy(qemu, value, sizeof(qemu));
+    } else if (!strncmp(name, "androidboot.", 12) && name_len > 12) {
+        const char *boot_prop_name = name + 12;
+        char prop[PROP_NAME_MAX];
+        int cnt;
+
+        cnt = snprintf(prop, sizeof(prop), "ro.boot.%s", boot_prop_name);
+        if (cnt < PROP_NAME_MAX)
+            property_set(prop, value);
+    }
+}
+
+static void export_kernel_boot_props(void)
 {
     char tmp[PROP_VALUE_MAX];
+    const char *pval;
+    unsigned i;
+    struct {
+        const char *src_prop;
+        const char *dest_prop;
+        const char *def_val;
+    } prop_map[] = {
+        { "ro.boot.serialno", "ro.serialno", "", },
+        { "ro.boot.mode", "ro.bootmode", "unknown", },
+        { "ro.boot.baseband", "ro.baseband", "unknown", },
+        { "ro.boot.carrier", "ro.carrier", "unknown", },
+        { "ro.boot.bootloader", "ro.bootloader", "unknown", },
+    };
 
-    if (qemu[0])
-        import_kernel_cmdline(1, import_kernel_nv);
+    for (i = 0; i < ARRAY_SIZE(prop_map); i++) {
+        pval = property_get(prop_map[i].src_prop);
+        property_set(prop_map[i].dest_prop, pval ?: prop_map[i].def_val);
+    }
 
+    pval = property_get("ro.boot.console");
+    if (pval)
+        strlcpy(console, pval, sizeof(console));
+
+    /* save a copy for init's usage during boot */
+    strlcpy(bootmode, property_get("ro.bootmode"), sizeof(bootmode));
+
+    /* if this was given on kernel command line, override what we read
+     * before (e.g. from /proc/cpuinfo), if anything */
+    pval = property_get("ro.boot.hardware");
+    if (pval)
+        strlcpy(hardware, pval, sizeof(hardware));
+    property_set("ro.hardware", hardware);
+
+    snprintf(tmp, PROP_VALUE_MAX, "%d", revision);
+    property_set("ro.revision", tmp);
+
+    /* TODO: these are obsolete. We should delete them */
     if (!strcmp(bootmode,"factory"))
         property_set("ro.factorytest", "1");
     else if (!strcmp(bootmode,"factory2"))
         property_set("ro.factorytest", "2");
     else
         property_set("ro.factorytest", "0");
+}
 
-    property_set("ro.serialno", serialno[0] ? serialno : "");
-    property_set("ro.bootmode", bootmode[0] ? bootmode : "unknown");
-    property_set("ro.baseband", baseband[0] ? baseband : "unknown");
-    property_set("ro.carrier", carrier[0] ? carrier : "unknown");
-    property_set("ro.bootloader", bootloader[0] ? bootloader : "unknown");
+static void process_kernel_cmdline(void)
+{
+    /* don't expose the raw commandline to nonpriv processes */
+    chmod("/proc/cmdline", 0440);
 
-    property_set("ro.hardware", hardware);
-    snprintf(tmp, PROP_VALUE_MAX, "%d", revision);
-    property_set("ro.revision", tmp);
-    return 0;
+    /* first pass does the common stuff, and finds if we are in qemu.
+     * second pass is only necessary for qemu to export all kernel params
+     * as props.
+     */
+    import_kernel_cmdline(0, import_kernel_nv);
+    if (qemu[0])
+        import_kernel_cmdline(1, import_kernel_nv);
+
+    /* now propogate the info given on command line to internal variables
+     * used by init as well as the current required properties
+     */
+    export_kernel_boot_props();
 }
 
 static int property_service_init_action(int nargs, char **args)
@@ -668,6 +688,7 @@
     int property_set_fd_init = 0;
     int signal_fd_init = 0;
     int keychord_fd_init = 0;
+    bool is_charger = false;
 
     if (!strcmp(basename(argv[0]), "ueventd"))
         return ueventd_main(argc, argv);
@@ -701,31 +722,32 @@
          */
     open_devnull_stdio();
     klog_init();
+    property_init();
+
+    get_hardware_name(hardware, &revision);
+
+    process_kernel_cmdline();
+
+    is_charger = !strcmp(bootmode, "charger");
+
+    INFO("property init\n");
+    if (!is_charger)
+        property_load_boot_defaults();
 
     INFO("reading config file\n");
     init_parse_config_file("/init.rc");
 
-    /* pull the kernel commandline and ramdisk properties file in */
-    import_kernel_cmdline(0, import_kernel_nv);
-    /* don't expose the raw commandline to nonpriv processes */
-    chmod("/proc/cmdline", 0440);
-    get_hardware_name(hardware, &revision);
-    snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);
-    init_parse_config_file(tmp);
-
     action_for_each_trigger("early-init", action_add_queue_tail);
 
     queue_builtin_action(wait_for_coldboot_done_action, "wait_for_coldboot_done");
-    queue_builtin_action(property_init_action, "property_init");
     queue_builtin_action(keychord_init_action, "keychord_init");
     queue_builtin_action(console_init_action, "console_init");
-    queue_builtin_action(set_init_properties_action, "set_init_properties");
 
     /* execute all the boot actions to get us started */
     action_for_each_trigger("init", action_add_queue_tail);
 
     /* skip mounting filesystems in charger mode */
-    if (strcmp(bootmode, "charger") != 0) {
+    if (!is_charger) {
         action_for_each_trigger("early-fs", action_add_queue_tail);
         action_for_each_trigger("fs", action_add_queue_tail);
         action_for_each_trigger("post-fs", action_add_queue_tail);
@@ -736,7 +758,7 @@
     queue_builtin_action(signal_init_action, "signal_init");
     queue_builtin_action(check_startup_action, "check_startup");
 
-    if (!strcmp(bootmode, "charger")) {
+    if (is_charger) {
         action_for_each_trigger("charger", action_add_queue_tail);
     } else {
         action_for_each_trigger("early-boot", action_add_queue_tail);
diff --git a/init/init_parser.c b/init/init_parser.c
index 13c94eb..d255db9 100644
--- a/init/init_parser.c
+++ b/init/init_parser.c
@@ -40,6 +40,11 @@
 static list_declare(action_list);
 static list_declare(action_queue);
 
+struct import {
+    struct listnode list;
+    const char *filename;
+};
+
 static void *parse_service(struct parse_state *state, int nargs, char **args);
 static void parse_line_service(struct parse_state *state, int nargs, char **args);
 
@@ -159,6 +164,149 @@
 {
 }
 
+static int push_chars(char **dst, int *len, const char *chars, int cnt)
+{
+    if (cnt > *len)
+        return -1;
+
+    memcpy(*dst, chars, cnt);
+    *dst += cnt;
+    *len -= cnt;
+
+    return 0;
+}
+
+int expand_props(char *dst, const char *src, int dst_size)
+{
+    int cnt = 0;
+    char *dst_ptr = dst;
+    const char *src_ptr = src;
+    int src_len;
+    int idx = 0;
+    int ret = 0;
+    int left = dst_size - 1;
+
+    if (!src || !dst || dst_size == 0)
+        return -1;
+
+    src_len = strlen(src);
+
+    /* - variables can either be $x.y or ${x.y}, in case they are only part
+     *   of the string.
+     * - will accept $$ as a literal $.
+     * - no nested property expansion, i.e. ${foo.${bar}} is not supported,
+     *   bad things will happen
+     */
+    while (*src_ptr && left > 0) {
+        char *c;
+        char prop[PROP_NAME_MAX + 1];
+        const char *prop_val;
+        int prop_len = 0;
+
+        c = strchr(src_ptr, '$');
+        if (!c) {
+            while (left-- > 0 && *src_ptr)
+                *(dst_ptr++) = *(src_ptr++);
+            break;
+        }
+
+        memset(prop, 0, sizeof(prop));
+
+        ret = push_chars(&dst_ptr, &left, src_ptr, c - src_ptr);
+        if (ret < 0)
+            goto err_nospace;
+        c++;
+
+        if (*c == '$') {
+            *(dst_ptr++) = *(c++);
+            src_ptr = c;
+            left--;
+            continue;
+        } else if (*c == '\0') {
+            break;
+        }
+
+        if (*c == '{') {
+            c++;
+            while (*c && *c != '}' && prop_len < PROP_NAME_MAX)
+                prop[prop_len++] = *(c++);
+            if (*c != '}') {
+                /* failed to find closing brace, abort. */
+                if (prop_len == PROP_NAME_MAX)
+                    ERROR("prop name too long during expansion of '%s'\n",
+                          src);
+                else if (*c == '\0')
+                    ERROR("unexpected end of string in '%s', looking for }\n",
+                          src);
+                goto err;
+            }
+            prop[prop_len] = '\0';
+            c++;
+        } else if (*c) {
+            while (*c && prop_len < PROP_NAME_MAX)
+                prop[prop_len++] = *(c++);
+            if (prop_len == PROP_NAME_MAX && *c != '\0') {
+                ERROR("prop name too long in '%s'\n", src);
+                goto err;
+            }
+            prop[prop_len] = '\0';
+            ERROR("using deprecated syntax for specifying property '%s', use ${name} instead\n",
+                  prop);
+        }
+
+        if (prop_len == 0) {
+            ERROR("invalid zero-length prop name in '%s'\n", src);
+            goto err;
+        }
+
+        prop_val = property_get(prop);
+        if (!prop_val) {
+            ERROR("property '%s' doesn't exist while expanding '%s'\n",
+                  prop, src);
+            goto err;
+        }
+
+        ret = push_chars(&dst_ptr, &left, prop_val, strlen(prop_val));
+        if (ret < 0)
+            goto err_nospace;
+        src_ptr = c;
+        continue;
+    }
+
+    *dst_ptr = '\0';
+    return 0;
+
+err_nospace:
+    ERROR("destination buffer overflow while expanding '%s'\n", src);
+err:
+    return -1;
+}
+
+void parse_import(struct parse_state *state, int nargs, char **args)
+{
+    struct listnode *import_list = state->priv;
+    struct import *import;
+    char conf_file[PATH_MAX];
+    int ret;
+
+    if (nargs != 2) {
+        ERROR("single argument needed for import\n");
+        return;
+    }
+
+    ret = expand_props(conf_file, args[1], sizeof(conf_file));
+    if (ret) {
+        ERROR("error while handling import on line '%d' in '%s'\n",
+              state->line, state->filename);
+        return;
+    }
+
+    import = calloc(1, sizeof(struct import));
+    import->filename = strdup(conf_file);
+    list_add_tail(import_list, &import->list);
+    INFO("found import '%s', adding to import list", import->filename);
+}
+
 void parse_new_section(struct parse_state *state, int kw,
                        int nargs, char **args)
 {
@@ -180,13 +328,8 @@
         }
         break;
     case K_import:
-        if (nargs != 2) {
-            ERROR("single argument needed for import\n");
-        } else {
-            int ret = init_parse_config_file(args[1]);
-            if (ret)
-                ERROR("could not import file %s\n", args[1]);
-        }
+        parse_import(state, nargs, args);
+        break;
     }
     state->parse_line = parse_line_no_op;
 }
@@ -194,6 +337,8 @@
 static void parse_config(const char *fn, char *s)
 {
     struct parse_state state;
+    struct listnode import_list;
+    struct listnode *node;
     char *args[INIT_PARSER_MAXARGS];
     int nargs;
 
@@ -203,11 +348,15 @@
     state.ptr = s;
     state.nexttoken = 0;
     state.parse_line = parse_line_no_op;
+
+    list_init(&import_list);
+    state.priv = &import_list;
+
     for (;;) {
         switch (next_token(&state)) {
         case T_EOF:
             state.parse_line(&state, 0, 0);
-            return;
+            goto parser_done;
         case T_NEWLINE:
             state.line++;
             if (nargs) {
@@ -228,6 +377,18 @@
             break;
         }
     }
+
+parser_done:
+    list_for_each(node, &import_list) {
+         struct import *import = node_to_item(node, struct import, list);
+         int ret;
+
+         INFO("importing '%s'", import->filename);
+         ret = init_parse_config_file(import->filename);
+         if (ret)
+             ERROR("could not import file '%s' from '%s'\n",
+                   import->filename, fn);
+    }
 }
 
 int init_parse_config_file(const char *fn)
diff --git a/init/init_parser.h b/init/init_parser.h
index ff13b04..b078cad 100644
--- a/init/init_parser.h
+++ b/init/init_parser.h
@@ -31,5 +31,6 @@
 void queue_builtin_action(int (*func)(int nargs, char **args), char *name);
 
 int init_parse_config_file(const char *fn);
+int expand_props(char *dst, const char *src, int len);
 
 #endif
diff --git a/init/parser.h b/init/parser.h
index be93758..0a5802a 100644
--- a/init/parser.h
+++ b/init/parser.h
@@ -30,6 +30,7 @@
     void *context;
     void (*parse_line)(struct parse_state *state, int nargs, char **args);
     const char *filename;
+    void *priv;
 };
 
 int lookup_keyword(const char *s);
diff --git a/init/property_service.c b/init/property_service.c
index 6733437..d06df31 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;
@@ -505,11 +490,14 @@
     persistent_properties_loaded = 1;
 }
 
-void property_init(bool load_defaults)
+void property_init(void)
 {
     init_property_area();
-    if (load_defaults)
-        load_properties_from_file(PROP_PATH_RAMDISK_DEFAULT);
+}
+
+void property_load_boot_defaults(void)
+{
+    load_properties_from_file(PROP_PATH_RAMDISK_DEFAULT);
 }
 
 int properties_inited(void)
diff --git a/init/property_service.h b/init/property_service.h
index 37c2788..b9d1bf6 100644
--- a/init/property_service.h
+++ b/init/property_service.h
@@ -20,7 +20,8 @@
 #include <stdbool.h>
 
 extern void handle_property_set_fd(void);
-extern void property_init(bool load_defaults);
+extern void property_init(void);
+extern void property_load_boot_defaults(void);
 extern void load_persist_props(void);
 extern void start_property_service(void);
 void get_property_workspace(int *fd, int *sz);
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/buffer.c b/libcutils/buffer.c
index f34b8f8..af99bd7 100644
--- a/libcutils/buffer.c
+++ b/libcutils/buffer.c
@@ -104,9 +104,9 @@
     if (bytesWritten >= 0) {
         buffer->remaining -= bytesWritten;
 
-        LOGD("Buffer bytes written: %d", (int) bytesWritten);
-        LOGD("Buffer size: %d", (int) buffer->size);
-        LOGD("Buffer remaining: %d", (int) buffer->remaining);        
+        ALOGD("Buffer bytes written: %d", (int) bytesWritten);
+        ALOGD("Buffer size: %d", (int) buffer->size);
+        ALOGD("Buffer remaining: %d", (int) buffer->remaining);
 
         return buffer->remaining;
     }
diff --git a/libcutils/loghack.h b/libcutils/loghack.h
index 2bfffe4..750cab0 100644
--- a/libcutils/loghack.h
+++ b/libcutils/loghack.h
@@ -25,14 +25,14 @@
 #include <cutils/log.h>
 #else
 #include <stdio.h>
-#define LOG(level, ...) \
+#define ALOG(level, ...) \
         ((void)printf("cutils:" level "/" LOG_TAG ": " __VA_ARGS__))
-#define LOGV(...)   LOG("V", __VA_ARGS__)
-#define LOGD(...)   LOG("D", __VA_ARGS__)
-#define LOGI(...)   LOG("I", __VA_ARGS__)
-#define LOGW(...)   LOG("W", __VA_ARGS__)
-#define LOGE(...)   LOG("E", __VA_ARGS__)
-#define LOG_ALWAYS_FATAL(...)   do { LOGE(__VA_ARGS__); exit(1); } while (0)
+#define ALOGV(...)   ALOG("V", __VA_ARGS__)
+#define ALOGD(...)   ALOG("D", __VA_ARGS__)
+#define ALOGI(...)   ALOG("I", __VA_ARGS__)
+#define ALOGW(...)   ALOG("W", __VA_ARGS__)
+#define ALOGE(...)   ALOG("E", __VA_ARGS__)
+#define LOG_ALWAYS_FATAL(...)   do { ALOGE(__VA_ARGS__); exit(1); } while (0)
 #endif
 
 #endif // _CUTILS_LOGHACK_H
diff --git a/libcutils/mq.c b/libcutils/mq.c
index 3b65f1f..6f6740e 100644
--- a/libcutils/mq.c
+++ b/libcutils/mq.c
@@ -222,7 +222,7 @@
 static void closeWithWarning(int fd) {
     int result = close(fd);
     if (result == -1) {
-        LOGW("close() error: %s", strerror(errno));
+        ALOGW("close() error: %s", strerror(errno));
     }
 }
 
@@ -263,7 +263,7 @@
 
 /** Frees a simple, i.e. header-only, outgoing packet. */
 static void outgoingPacketFree(OutgoingPacket* packet) {
-    LOGD("Freeing outgoing packet.");
+    ALOGD("Freeing outgoing packet.");
 	free(packet);
 }
 
@@ -374,10 +374,10 @@
  */
 static void peerProxyKill(PeerProxy* peerProxy, bool errnoIsSet) {
     if (errnoIsSet) {
-        LOGI("Peer %d died. errno: %s", peerProxy->credentials.pid, 
+        ALOGI("Peer %d died. errno: %s", peerProxy->credentials.pid, 
                 strerror(errno));
     } else {
-        LOGI("Peer %d died.", peerProxy->credentials.pid);
+        ALOGI("Peer %d died.", peerProxy->credentials.pid);
     }
     
     // If we lost the master, we're up a creek. We can't let this happen.
@@ -433,12 +433,12 @@
 static void peerProxyHandleError(PeerProxy* peerProxy, char* functionName) {
     if (errno == EINTR) {
         // Log interruptions but otherwise ignore them.
-        LOGW("%s() interrupted.", functionName);
+        ALOGW("%s() interrupted.", functionName);
     } else if (errno == EAGAIN) {
-    	LOGD("EWOULDBLOCK");
+        ALOGD("EWOULDBLOCK");
         // Ignore.
     } else {
-        LOGW("Error returned by %s().", functionName);
+        ALOGW("Error returned by %s().", functionName);
         peerProxyKill(peerProxy, true);
     }
 }
@@ -461,7 +461,7 @@
 static void peerProxyWriteBytes(PeerProxy* peerProxy) {	
 	Buffer* buffer = peerProxy->currentPacket->bytes;
 	if (peerProxyWriteFromBuffer(peerProxy, buffer)) {
-        LOGD("Bytes written.");
+        ALOGD("Bytes written.");
         peerProxyNextPacket(peerProxy);
     }    
 }
@@ -527,10 +527,10 @@
     Buffer* outgoingHeader = &peerProxy->outgoingHeader;
     bool headerWritten = bufferWriteComplete(outgoingHeader);
     if (!headerWritten) {
-        LOGD("Writing header...");
+        ALOGD("Writing header...");
         headerWritten = peerProxyWriteFromBuffer(peerProxy, outgoingHeader);
         if (headerWritten) {
-            LOGD("Header written.");
+            ALOGD("Header written.");
         }
     }    
 
@@ -559,7 +559,7 @@
  * Sets up a peer proxy's fd before we try to select() it.
  */
 static void peerProxyBeforeSelect(SelectableFd* fd) {
-    LOGD("Before select...");
+    ALOGD("Before select...");
 
     PeerProxy* peerProxy = (PeerProxy*) fd->data;
   
@@ -568,7 +568,7 @@
     peerUnlock(peerProxy->peer);
     
     if (hasPackets) {
-        LOGD("Packets found. Setting onWritable().");
+        ALOGD("Packets found. Setting onWritable().");
             
         fd->onWritable = &peerProxyWrite;
     } else {
@@ -579,11 +579,11 @@
 
 /** Prepare to read bytes from the peer. */
 static void peerProxyExpectBytes(PeerProxy* peerProxy, Header* header) {
-	LOGD("Expecting %d bytes.", header->size);
-	
-	peerProxy->inputState = READING_BYTES;
+    ALOGD("Expecting %d bytes.", header->size);
+
+    peerProxy->inputState = READING_BYTES;
     if (bufferPrepareForRead(peerProxy->inputBuffer, header->size) == -1) {
-        LOGW("Couldn't allocate memory for incoming data. Size: %u",
+        ALOGW("Couldn't allocate memory for incoming data. Size: %u",
                 (unsigned int) header->size);    
         
         // TODO: Ignore the packet and log a warning?
@@ -670,7 +670,7 @@
     // TODO: Restructure things so we don't need this check.
     // Verify that this really is the master.
     if (!masterProxy->master) {
-        LOGW("Non-master process %d tried to send us a connection.", 
+        ALOGW("Non-master process %d tried to send us a connection.", 
             masterProxy->credentials.pid);
         // Kill off the evil peer.
         peerProxyKill(masterProxy, false);
@@ -686,7 +686,7 @@
     peerLock(localPeer);
     PeerProxy* peerProxy = peerProxyGetOrCreate(localPeer, pid, false);
     if (peerProxy == NULL) {
-        LOGW("Peer proxy creation failed: %s", strerror(errno));
+        ALOGW("Peer proxy creation failed: %s", strerror(errno));
     } else {
         // Fill in full credentials.
         peerProxy->credentials = header->credentials;
@@ -746,7 +746,7 @@
     if (size < 0) {
         if (errno == EINTR) {
             // Log interruptions but otherwise ignore them.
-            LOGW("recvmsg() interrupted.");
+            ALOGW("recvmsg() interrupted.");
             return;
         } else if (errno == EAGAIN) {
             // Keep waiting for the connection.
@@ -777,14 +777,14 @@
     // The peer proxy this connection is for.
     PeerProxy* peerProxy = masterProxy->connecting;
     if (peerProxy == NULL) {
-        LOGW("Received connection for unknown peer.");
+        ALOGW("Received connection for unknown peer.");
         closeWithWarning(incomingFd);
     } else {
         Peer* peer = masterProxy->peer;
         
         SelectableFd* selectableFd = selectorAdd(peer->selector, incomingFd);
         if (selectableFd == NULL) {
-            LOGW("Error adding fd to selector for %d.",
+            ALOGW("Error adding fd to selector for %d.",
                     peerProxy->credentials.pid);
             closeWithWarning(incomingFd);
             peerProxyKill(peerProxy, false);
@@ -811,7 +811,7 @@
     int sockets[2];
     int result = socketpair(AF_LOCAL, SOCK_STREAM, 0, sockets);
     if (result == -1) {
-        LOGW("socketpair() error: %s", strerror(errno));
+        ALOGW("socketpair() error: %s", strerror(errno));
         // TODO: Send CONNECTION_FAILED packets to peers.
         return;
     }
@@ -821,7 +821,7 @@
     if (packetA == NULL || packetB == NULL) {
         free(packetA);
         free(packetB);
-        LOGW("malloc() error. Failed to tell process %d that process %d is"
+        ALOGW("malloc() error. Failed to tell process %d that process %d is"
                 " dead.", peerA->credentials.pid, peerB->credentials.pid);
         return;
     }
@@ -852,7 +852,7 @@
         Credentials credentials) {
     OutgoingPacket* packet = calloc(1, sizeof(OutgoingPacket));
     if (packet == NULL) {
-        LOGW("malloc() error. Failed to tell process %d that process %d is"
+        ALOGW("malloc() error. Failed to tell process %d that process %d is"
                 " dead.", peerProxy->credentials.pid, credentials.pid);
         return;
     }
@@ -902,10 +902,10 @@
     peerUnlock(peer);
 
     if (peerProxy != NULL) {
-        LOGI("Couldn't connect to %d.", pid);
+        ALOGI("Couldn't connect to %d.", pid);
         peerProxyKill(peerProxy, false);
     } else {
-        LOGW("Peer proxy for %d not found. This shouldn't happen.", pid);
+        ALOGW("Peer proxy for %d not found. This shouldn't happen.", pid);
     }
     
     peerProxyExpectHeader(masterProxy);
@@ -929,7 +929,7 @@
             peerProxyExpectBytes(peerProxy, header);
             break;
         default:
-            LOGW("Invalid packet type from %d: %d", peerProxy->credentials.pid, 
+            ALOGW("Invalid packet type from %d: %d", peerProxy->credentials.pid, 
                     header->type);
             peerProxyKill(peerProxy, false);
     }
@@ -947,7 +947,7 @@
         return false;
     } else if (size == 0) {
         // EOF.
-    	LOGI("EOF");
+    	ALOGI("EOF");
         peerProxyKill(peerProxy, false);
         return false;
     } else if (bufferReadComplete(in)) {
@@ -963,23 +963,23 @@
  * Reads input from a peer process.
  */
 static void peerProxyRead(SelectableFd* fd) {
-    LOGD("Reading...");
+    ALOGD("Reading...");
     PeerProxy* peerProxy = (PeerProxy*) fd->data;
     int state = peerProxy->inputState;
     Buffer* in = peerProxy->inputBuffer;
     switch (state) {
         case READING_HEADER:
             if (peerProxyBufferInput(peerProxy)) {
-                LOGD("Header read.");
+                ALOGD("Header read.");
                 // We've read the complete header.
                 Header* header = (Header*) in->data;
                 peerProxyHandleHeader(peerProxy, header);
             }
             break;
         case READING_BYTES:
-            LOGD("Reading bytes...");
+            ALOGD("Reading bytes...");
             if (peerProxyBufferInput(peerProxy)) {
-                LOGD("Bytes read.");
+                ALOGD("Bytes read.");
                 // We have the complete packet. Notify bytes listener.
                 peerProxy->peer->onBytes(peerProxy->credentials,
                     in->data, in->size);
@@ -1026,11 +1026,11 @@
     // Accept connection.
     int socket = accept(listenerFd->fd, NULL, NULL);
     if (socket == -1) {
-        LOGW("accept() error: %s", strerror(errno));
+        ALOGW("accept() error: %s", strerror(errno));
         return;
     }
     
-    LOGD("Accepted connection as fd %d.", socket);
+    ALOGD("Accepted connection as fd %d.", socket);
     
     // Get credentials.
     Credentials credentials;
@@ -1040,7 +1040,7 @@
                 &ucredentials, &credentialsSize);
     // We might want to verify credentialsSize.
     if (result == -1) {
-        LOGW("getsockopt() error: %s", strerror(errno));
+        ALOGW("getsockopt() error: %s", strerror(errno));
         closeWithWarning(socket);
         return;
     }
@@ -1050,7 +1050,7 @@
     credentials.uid = ucredentials.uid;
     credentials.gid = ucredentials.gid;
     
-    LOGI("Accepted connection from process %d.", credentials.pid);
+    ALOGI("Accepted connection from process %d.", credentials.pid);
    
     Peer* masterPeer = (Peer*) listenerFd->data;
     
@@ -1061,7 +1061,7 @@
         = hashmapGet(masterPeer->peerProxies, &credentials.pid);
     if (peerProxy != NULL) {
         peerUnlock(masterPeer);
-        LOGW("Alread connected to process %d.", credentials.pid);
+        ALOGW("Alread connected to process %d.", credentials.pid);
         closeWithWarning(socket);
         return;
     }
@@ -1070,7 +1070,7 @@
     SelectableFd* socketFd = selectorAdd(masterPeer->selector, socket);
     if (socketFd == NULL) {
         peerUnlock(masterPeer);
-        LOGW("malloc() failed.");
+        ALOGW("malloc() failed.");
         closeWithWarning(socket);
         return;
     }
@@ -1079,7 +1079,7 @@
     peerProxy = peerProxyCreate(masterPeer, credentials);
     peerUnlock(masterPeer);
     if (peerProxy == NULL) {
-        LOGW("malloc() failed.");
+        ALOGW("malloc() failed.");
         socketFd->remove = true;
         closeWithWarning(socket);
     }
@@ -1118,7 +1118,7 @@
 
 /** Frees a packet of bytes. */
 static void outgoingPacketFreeBytes(OutgoingPacket* packet) {
-    LOGD("Freeing outgoing packet.");
+    ALOGD("Freeing outgoing packet.");
     bufferFree(packet->bytes);
     free(packet);
 }
@@ -1270,7 +1270,7 @@
         LOG_ALWAYS_FATAL("bind() error: %s", strerror(errno));
     }
 
-    LOGD("Listener socket: %d",  listenerSocket);   
+    ALOGD("Listener socket: %d",  listenerSocket);
     
     // Queue up to 16 connections.
     result = listen(listenerSocket, 16);
diff --git a/libcutils/properties.c b/libcutils/properties.c
index 98f356b..f732ec0 100644
--- a/libcutils/properties.c
+++ b/libcutils/properties.c
@@ -99,7 +99,7 @@
     
     sock = socket(AF_UNIX, SOCK_STREAM, 0);
     if (sock < 0) {
-        LOGW("UNIX domain socket create failed (errno=%d)\n", errno);
+        ALOGW("UNIX domain socket create failed (errno=%d)\n", errno);
         return -1;
     }
 
@@ -110,7 +110,7 @@
     if (cc < 0) {
         // ENOENT means socket file doesn't exist
         // ECONNREFUSED means socket exists but nobody is listening
-        //LOGW("AF_UNIX connect failed for '%s': %s\n",
+        //ALOGW("AF_UNIX connect failed for '%s': %s\n",
         //    fileName, strerror(errno));
         close(sock);
         return -1;
@@ -128,9 +128,9 @@
 
     gPropFd = connectToServer(SYSTEM_PROPERTY_PIPE_NAME);
     if (gPropFd < 0) {
-        //LOGW("not connected to system property server\n");
+        //ALOGW("not connected to system property server\n");
     } else {
-        //LOGV("Connected to system property server\n");
+        //ALOGV("Connected to system property server\n");
     }
 }
 
@@ -140,7 +140,7 @@
     char recvBuf[1+PROPERTY_VALUE_MAX];
     int len = -1;
 
-    //LOGV("PROPERTY GET [%s]\n", key);
+    //ALOGV("PROPERTY GET [%s]\n", key);
 
     pthread_once(&gInitOnce, init);
     if (gPropFd < 0) {
@@ -189,12 +189,12 @@
         strcpy(value, recvBuf+1);
         len = strlen(value);
     } else {
-        LOGE("Got strange response to property_get request (%d)\n",
+        ALOGE("Got strange response to property_get request (%d)\n",
             recvBuf[0]);
         assert(0);
         return -1;
     }
-    //LOGV("PROP [found=%d def='%s'] (%d) [%s]: [%s]\n",
+    //ALOGV("PROP [found=%d def='%s'] (%d) [%s]: [%s]\n",
     //    recvBuf[0], default_value, len, key, value);
 
     return len;
@@ -207,7 +207,7 @@
     char recvBuf[1];
     int result = -1;
 
-    //LOGV("PROPERTY SET [%s]: [%s]\n", key, value);
+    //ALOGV("PROPERTY SET [%s]: [%s]\n", key, value);
 
     pthread_once(&gInitOnce, init);
     if (gPropFd < 0)
@@ -241,7 +241,7 @@
 int property_list(void (*propfn)(const char *key, const char *value, void *cookie), 
                   void *cookie)
 {
-    //LOGV("PROPERTY LIST\n");
+    //ALOGV("PROPERTY LIST\n");
     pthread_once(&gInitOnce, init);
     if (gPropFd < 0)
         return -1;
diff --git a/libcutils/qtaguid.c b/libcutils/qtaguid.c
index 994ad32..1c57774 100644
--- a/libcutils/qtaguid.c
+++ b/libcutils/qtaguid.c
@@ -60,7 +60,7 @@
 static int write_ctrl(const char *cmd) {
     int fd, res, savedErrno;
 
-    LOGV("write_ctrl(%s)", cmd);
+    ALOGV("write_ctrl(%s)", cmd);
 
     fd = TEMP_FAILURE_RETRY(open(CTRL_PROCPATH, O_WRONLY));
     if (fd < 0) {
@@ -74,7 +74,7 @@
         savedErrno = 0;
     }
     if (res < 0) {
-        LOGI("Failed write_ctrl(%s) res=%d errno=%d", cmd, res, savedErrno);
+        ALOGI("Failed write_ctrl(%s) res=%d errno=%d", cmd, res, savedErrno);
     }
     close(fd);
     return -savedErrno;
@@ -107,11 +107,11 @@
 
     snprintf(lineBuf, sizeof(lineBuf), "t %d %llu %d", sockfd, kTag, uid);
 
-    LOGV("Tagging socket %d with tag %llx{%u,0} for uid %d", sockfd, kTag, tag, uid);
+    ALOGV("Tagging socket %d with tag %llx{%u,0} for uid %d", sockfd, kTag, tag, uid);
 
     res = write_ctrl(lineBuf);
     if (res < 0) {
-        LOGI("Tagging socket %d with tag %llx(%d) for uid %d failed errno=%d",
+        ALOGI("Tagging socket %d with tag %llx(%d) for uid %d failed errno=%d",
              sockfd, kTag, tag, uid, res);
     }
 
@@ -122,12 +122,12 @@
     char lineBuf[CTRL_MAX_INPUT_LEN];
     int res;
 
-    LOGV("Untagging socket %d", sockfd);
+    ALOGV("Untagging socket %d", sockfd);
 
     snprintf(lineBuf, sizeof(lineBuf), "u %d", sockfd);
     res = write_ctrl(lineBuf);
     if (res < 0) {
-        LOGI("Untagging socket %d failed errno=%d", sockfd, res);
+        ALOGI("Untagging socket %d failed errno=%d", sockfd, res);
     }
 
     return res;
@@ -137,7 +137,7 @@
     char lineBuf[CTRL_MAX_INPUT_LEN];
     int res;
 
-    LOGV("Setting counters to set %d for uid %d", counterSetNum, uid);
+    ALOGV("Setting counters to set %d for uid %d", counterSetNum, uid);
 
     snprintf(lineBuf, sizeof(lineBuf), "s %d %d", counterSetNum, uid);
     res = write_ctrl(lineBuf);
@@ -149,14 +149,14 @@
     int fd, cnt = 0, res = 0;
     uint64_t kTag = (uint64_t)tag << 32;
 
-    LOGV("Deleting tag data with tag %llx{%d,0} for uid %d", kTag, tag, uid);
+    ALOGV("Deleting tag data with tag %llx{%d,0} for uid %d", kTag, tag, uid);
 
     pthread_once(&resTrackInitDone, qtaguid_resTrack);
 
     snprintf(lineBuf, sizeof(lineBuf), "d %llu %d", kTag, uid);
     res = write_ctrl(lineBuf);
     if (res < 0) {
-        LOGI("Deleteing tag data with tag %llx/%d for uid %d failed with cnt=%d errno=%d",
+        ALOGI("Deleteing tag data with tag %llx/%d for uid %d failed with cnt=%d errno=%d",
              kTag, tag, uid, cnt, errno);
     }
 
diff --git a/libcutils/record_stream.c b/libcutils/record_stream.c
index 274423b..6994904 100644
--- a/libcutils/record_stream.c
+++ b/libcutils/record_stream.c
@@ -144,7 +144,7 @@
         && p_rs->read_end == p_rs->buffer_end
     ) {
         // this should never happen
-        //LOGE("max record length exceeded\n");
+        //ALOGE("max record length exceeded\n");
         assert (0);
         errno = EFBIG;
         return -1;
diff --git a/libcutils/selector.c b/libcutils/selector.c
index 9436393..3776bbb 100644
--- a/libcutils/selector.c
+++ b/libcutils/selector.c
@@ -48,7 +48,7 @@
     static char garbage[64];
     if (read(wakeupFd->fd, garbage, sizeof(garbage)) < 0) {
         if (errno == EINTR) {
-            LOGI("read() interrupted.");    
+            ALOGI("read() interrupted.");    
         } else {
             LOG_ALWAYS_FATAL("This should never happen: %s", strerror(errno));
         }
@@ -77,7 +77,7 @@
     static char garbage[1];
     if (write(selector->wakeupPipe[1], garbage, sizeof(garbage)) < 0) {
         if (errno == EINTR) {
-            LOGI("read() interrupted.");    
+            ALOGI("read() interrupted.");    
         } else {
             LOG_ALWAYS_FATAL("This should never happen: %s", strerror(errno));
         }
@@ -96,7 +96,7 @@
         LOG_ALWAYS_FATAL("pipe() error: %s", strerror(errno));
     }
     
-    LOGD("Wakeup fd: %d", selector->wakeupPipe[0]);
+    ALOGD("Wakeup fd: %d", selector->wakeupPipe[0]);
     
     SelectableFd* wakeupFd = selectorAdd(selector, selector->wakeupPipe[0]);
     if (wakeupFd == NULL) {
@@ -169,11 +169,11 @@
             
             bool inSet = false;
             if (maybeAdd(selectableFd, selectableFd->onExcept, exceptFds)) {
-            	LOGD("Selecting fd %d for writing...", selectableFd->fd);
+                ALOGD("Selecting fd %d for writing...", selectableFd->fd);
                 inSet = true;
             }
             if (maybeAdd(selectableFd, selectableFd->onReadable, readFds)) {
-            	LOGD("Selecting fd %d for reading...", selectableFd->fd);
+                ALOGD("Selecting fd %d for reading...", selectableFd->fd);
                 inSet = true;
             }
             if (maybeAdd(selectableFd, selectableFd->onWritable, writeFds)) {
@@ -200,9 +200,9 @@
  */
 static inline void maybeInvoke(SelectableFd* selectableFd,
         void (*callback)(SelectableFd*), fd_set* fdSet) {
-	if (callback != NULL && !selectableFd->remove && 
+    if (callback != NULL && !selectableFd->remove && 
             FD_ISSET(selectableFd->fd, fdSet)) {
-		LOGD("Selected fd %d.", selectableFd->fd);
+        ALOGD("Selected fd %d.", selectableFd->fd);
         callback(selectableFd);
     }
 }
@@ -238,20 +238,20 @@
         
         prepareForSelect(selector);
 
-        LOGD("Entering select().");
+        ALOGD("Entering select().");
         
         // Select file descriptors.
         int result = select(selector->maxFd + 1, &selector->readFds, 
                 &selector->writeFds, &selector->exceptFds, NULL);
         
-        LOGD("Exiting select().");
+        ALOGD("Exiting select().");
         
         setInSelect(selector, false);
         
         if (result == -1) {
             // Abort on everything except EINTR.
             if (errno == EINTR) {
-                LOGI("select() interrupted.");    
+                ALOGI("select() interrupted.");    
             } else {
                 LOG_ALWAYS_FATAL("select() error: %s", 
                         strerror(errno));
diff --git a/libcutils/sockets.c b/libcutils/sockets.c
index 101a382..b5a1b3d 100644
--- a/libcutils/sockets.c
+++ b/libcutils/sockets.c
@@ -30,12 +30,12 @@
     int n = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
 
     if (n != 0) {
-        LOGE("could not get socket credentials: %s\n", strerror(errno));
+        ALOGE("could not get socket credentials: %s\n", strerror(errno));
         return false;
     }
 
     if ((cr.uid != AID_ROOT) && (cr.uid != AID_SHELL)) {
-        LOGE("untrusted userid on other end of socket: userid %d\n", cr.uid);
+        ALOGE("untrusted userid on other end of socket: userid %d\n", cr.uid);
         return false;
     }
 #endif
diff --git a/libcutils/str_parms.c b/libcutils/str_parms.c
index dfa1f73..14fecec 100644
--- a/libcutils/str_parms.c
+++ b/libcutils/str_parms.c
@@ -103,7 +103,7 @@
     if (!str)
         goto err_strdup;
 
-    LOGV("%s: source string == '%s'\n", __func__, _string);
+    ALOGV("%s: source string == '%s'\n", __func__, _string);
 
     kvpair = strtok_r(str, ";", &tmpstr);
     while (kvpair && *kvpair) {
@@ -137,7 +137,7 @@
     }
 
     if (!items)
-        LOGV("%s: no items found in string\n", __func__);
+        ALOGV("%s: no items found in string\n", __func__);
 
     free(str);
 
@@ -281,7 +281,7 @@
 
 static bool dump_entry(void *key, void *value, void *context)
 {
-    LOGI("key: '%s' value: '%s'\n", (char *)key, (char *)value);
+    ALOGI("key: '%s' value: '%s'\n", (char *)key, (char *)value);
     return true;
 }
 
@@ -301,7 +301,7 @@
     str_parms_dump(str_parms);
     out_str = str_parms_to_str(str_parms);
     str_parms_destroy(str_parms);
-    LOGI("%s: '%s' stringified is '%s'", __func__, str, out_str);
+    ALOGI("%s: '%s' stringified is '%s'", __func__, str, out_str);
     free(out_str);
 }
 
diff --git a/libcutils/zygote.c b/libcutils/zygote.c
index aa060c0..75ce3ba 100644
--- a/libcutils/zygote.c
+++ b/libcutils/zygote.c
@@ -46,7 +46,7 @@
 {
 #ifndef HAVE_ANDROID_OS
     // not supported on simulator targets
-    //LOGE("zygote_* not supported on simulator targets");
+    //ALOGE("zygote_* not supported on simulator targets");
     return -1;
 #else /* HAVE_ANDROID_OS */
     uint32_t pid;
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/libdiskconfig/config_mbr.c b/libdiskconfig/config_mbr.c
index 825ba60..703484c 100644
--- a/libdiskconfig/config_mbr.c
+++ b/libdiskconfig/config_mbr.c
@@ -47,7 +47,7 @@
     pentry->start_lba = start;
     pentry->len_lba = len;
 
-    LOGI("Configuring pentry. status=0x%x type=0x%x start_lba=%u len_lba=%u",
+    ALOGI("Configuring pentry. status=0x%x type=0x%x start_lba=%u len_lba=%u",
          pentry->status, pentry->type, pentry->start_lba, pentry->len_lba);
 }
 
@@ -62,7 +62,7 @@
     lba = (lba + (uint64_t)sect_size - 1) & ~((uint64_t)sect_size - 1);
     lba /= (uint64_t)sect_size;
     if (lba >= 0xffffffffULL)
-        LOGE("Error converting kb -> lba. 32bit overflow, expect weirdness");
+        ALOGE("Error converting kb -> lba. 32bit overflow, expect weirdness");
     return (uint32_t)(lba & 0xffffffffULL);
 }
 
@@ -75,12 +75,12 @@
     struct pc_partition *pentry;
 
     if (pnum >= PC_NUM_BOOT_RECORD_PARTS) {
-        LOGE("Maximum number of primary partition exceeded.");
+        ALOGE("Maximum number of primary partition exceeded.");
         return NULL;
     }
 
     if (!(item = alloc_wl(sizeof(struct pc_partition)))) {
-        LOGE("Unable to allocate memory for partition entry.");
+        ALOGE("Unable to allocate memory for partition entry.");
         return NULL;
     }
 
@@ -146,7 +146,7 @@
     uint32_t len; /* in lba units */
 
     if (!(item = alloc_wl(sizeof(struct pc_boot_record)))) {
-        LOGE("Unable to allocate memory for EBR.");
+        ALOGE("Unable to allocate memory for EBR.");
         return NULL;
     }
 
@@ -163,7 +163,7 @@
         len = kb_to_lba(pinfo->len_kb, dinfo->sect_size);
     else {
         if (pnext) {
-            LOGE("Only the last partition can be specified to fill the disk "
+            ALOGE("Only the last partition can be specified to fill the disk "
                  "(name = '%s')", pinfo->name);
             goto fail;
         }
@@ -233,7 +233,7 @@
                 if ((temp_wr = mk_pri_pentry(dinfo, NULL, cnt, &cur_lba)))
                     wlist_add(&wr_list, temp_wr);
                 else {
-                    LOGE("Cannot create primary extended partition.");
+                    ALOGE("Cannot create primary extended partition.");
                     goto fail;
                 }
             }
@@ -259,7 +259,7 @@
         if (temp_wr)
             wlist_add(&wr_list, temp_wr);
         else {
-            LOGE("Cannot create partition %d (%s).", cnt, pinfo->name);
+            ALOGE("Cannot create partition %d (%s).", cnt, pinfo->name);
             goto fail;
         }
     }
@@ -270,7 +270,7 @@
         cur_lba = 0;
         memset(&blank, 0, sizeof(struct part_info));
         if (!(temp_wr = mk_pri_pentry(dinfo, &blank, cnt, &cur_lba))) {
-            LOGE("Cannot create blank partition %d.", cnt);
+            ALOGE("Cannot create blank partition %d.", cnt);
             goto fail;
         }
         wlist_add(&wr_list, temp_wr);
@@ -279,7 +279,7 @@
     return wr_list;
 
 nospace:
-    LOGE("Not enough space to add parttion '%s'.", pinfo->name);
+    ALOGE("Not enough space to add parttion '%s'.", pinfo->name);
 
 fail:
     wlist_free(wr_list);
@@ -310,13 +310,13 @@
         num++;
 
     if (!(dev_name = malloc(MAX_NAME_LEN))) {
-        LOGE("Cannot allocate memory.");
+        ALOGE("Cannot allocate memory.");
         return NULL;
     }
 
     num = snprintf(dev_name, MAX_NAME_LEN, "%s%d", dinfo->device, num);
     if (num >= MAX_NAME_LEN) {
-        LOGE("Device name is too long?!");
+        ALOGE("Device name is too long?!");
         free(dev_name);
         return NULL;
     }
diff --git a/libdiskconfig/diskconfig.c b/libdiskconfig/diskconfig.c
index 4dd8c52..d5425de 100644
--- a/libdiskconfig/diskconfig.c
+++ b/libdiskconfig/diskconfig.c
@@ -45,7 +45,7 @@
     tmp[sizeof(tmp)-1] = '\0';
     len_str = strlen(tmp);
     if (!len_str) {
-        LOGE("Invalid disk length specified.");
+        ALOGE("Invalid disk length specified.");
         return 1;
     }
 
@@ -64,13 +64,13 @@
 
     *plen = strtoull(tmp, NULL, 0);
     if (!*plen) {
-        LOGE("Invalid length specified: %s", str);
+        ALOGE("Invalid length specified: %s", str);
         return 1;
     }
 
     if (*plen == (uint64_t)-1) {
         if (multiple > 1) {
-            LOGE("Size modifier illegal when len is -1");
+            ALOGE("Size modifier illegal when len is -1");
             return 1;
         }
     } else {
@@ -80,7 +80,7 @@
         *plen *= multiple;
 
         if (*plen > 0xffffffffULL) {
-            LOGE("Length specified is too large!: %llu KB", *plen);
+            ALOGE("Length specified is too large!: %llu KB", *plen);
             return 1;
         }
     }
@@ -108,7 +108,7 @@
             pinfo->flags |= PART_ACTIVE_FLAG;
 
         if (!(tmp = config_str(partnode, "type", NULL))) {
-            LOGE("Partition type required: %s", pinfo->name);
+            ALOGE("Partition type required: %s", pinfo->name);
             return 1;
         }
 
@@ -118,7 +118,7 @@
         } else if (!strcmp(tmp, "fat32")) {
             pinfo->type = PC_PART_TYPE_FAT32;
         } else {
-            LOGE("Unsupported partition type found: %s", tmp);
+            ALOGE("Unsupported partition type found: %s", tmp);
             return 1;
         }
 
@@ -146,13 +146,13 @@
     const char *tmp;
 
     if (!(dinfo = malloc(sizeof(struct disk_info)))) {
-        LOGE("Could not malloc disk_info");
+        ALOGE("Could not malloc disk_info");
         return NULL;
     }
     memset(dinfo, 0, sizeof(struct disk_info));
 
     if (!(dinfo->part_lst = malloc(MAX_NUM_PARTS * sizeof(struct part_info)))) {
-        LOGE("Could not malloc part_lst");
+        ALOGE("Could not malloc part_lst");
         goto fail;
     }
     memset(dinfo->part_lst, 0,
@@ -160,33 +160,33 @@
 
     config_load_file(root, fn);
     if (root->first_child == NULL) {
-        LOGE("Could not read config file %s", fn);
+        ALOGE("Could not read config file %s", fn);
         goto fail;
     }
 
     if (!(devroot = config_find(root, "device"))) {
-        LOGE("Could not find device section in config file '%s'", fn);
+        ALOGE("Could not find device section in config file '%s'", fn);
         goto fail;
     }
 
 
     if (!(tmp = config_str(devroot, "path", path_override))) {
-        LOGE("device path is requried");
+        ALOGE("device path is requried");
         goto fail;
     }
     dinfo->device = strdup(tmp);
 
     /* find the partition scheme */
     if (!(tmp = config_str(devroot, "scheme", NULL))) {
-        LOGE("partition scheme is required");
+        ALOGE("partition scheme is required");
         goto fail;
     } else if (!strcmp(tmp, "mbr")) {
         dinfo->scheme = PART_SCHEME_MBR;
     } else if (!strcmp(tmp, "gpt")) {
-        LOGE("'gpt' partition scheme not supported yet.");
+        ALOGE("'gpt' partition scheme not supported yet.");
         goto fail;
     } else {
-        LOGE("Unknown partition scheme specified: %s", tmp);
+        ALOGE("Unknown partition scheme specified: %s", tmp);
         goto fail;
     }
 
@@ -194,30 +194,30 @@
     tmp = config_str(devroot, "sector_size", "512");
     dinfo->sect_size = strtol(tmp, NULL, 0);
     if (!dinfo->sect_size) {
-        LOGE("Invalid sector size: %s", tmp);
+        ALOGE("Invalid sector size: %s", tmp);
         goto fail;
     }
 
     /* first lba where the partitions will start on disk */
     if (!(tmp = config_str(devroot, "start_lba", NULL))) {
-        LOGE("start_lba must be provided");
+        ALOGE("start_lba must be provided");
         goto fail;
     }
 
     if (!(dinfo->skip_lba = strtol(tmp, NULL, 0))) {
-        LOGE("Invalid starting LBA (or zero): %s", tmp);
+        ALOGE("Invalid starting LBA (or zero): %s", tmp);
         goto fail;
     }
 
     /* Number of LBAs on disk */
     if (!(tmp = config_str(devroot, "num_lba", NULL))) {
-        LOGE("num_lba is required");
+        ALOGE("num_lba is required");
         goto fail;
     }
     dinfo->num_lba = strtoul(tmp, NULL, 0);
 
     if (!(partnode = config_find(devroot, "partitions"))) {
-        LOGE("Device must specify partition list");
+        ALOGE("Device must specify partition list");
         goto fail;
     }
 
@@ -244,12 +244,12 @@
     sync();
 
     if (fstat(fd, &stat)) {
-       LOGE("Cannot stat, errno=%d.", errno);
+       ALOGE("Cannot stat, errno=%d.", errno);
        return -1;
     }
 
     if (S_ISBLK(stat.st_mode) && ((rv = ioctl(fd, BLKRRPART, NULL)) < 0)) {
-        LOGE("Could not re-read partition table. REBOOT!. (errno=%d)", errno);
+        ALOGE("Could not re-read partition table. REBOOT!. (errno=%d)", errno);
         return -1;
     }
 
@@ -281,12 +281,12 @@
         return -1;
 
     if ((fd = open(dinfo->device, O_RDWR)) < 0) {
-        LOGE("Cannot open device '%s' (errno=%d)", dinfo->device, errno);
+        ALOGE("Cannot open device '%s' (errno=%d)", dinfo->device, errno);
         return -1;
     }
 
     if (fstat(fd, &stat)) {
-        LOGE("Cannot stat file '%s', errno=%d.", dinfo->device, errno);
+        ALOGE("Cannot stat file '%s', errno=%d.", dinfo->device, errno);
         goto fail;
     }
 
@@ -299,19 +299,19 @@
     if (S_ISBLK(stat.st_mode)) {
         /* get the sector size and make sure we agree */
         if (ioctl(fd, BLKSSZGET, &sect_sz) < 0) {
-            LOGE("Cannot get sector size (errno=%d)", errno);
+            ALOGE("Cannot get sector size (errno=%d)", errno);
             goto fail;
         }
 
         if (!sect_sz || sect_sz != dinfo->sect_size) {
-            LOGE("Device sector size is zero or sector sizes do not match!");
+            ALOGE("Device sector size is zero or sector sizes do not match!");
             goto fail;
         }
 
         /* allow the user override the "disk size" if they provided num_lba */
         if (!dinfo->num_lba) {
             if (ioctl(fd, BLKGETSIZE64, &disk_size) < 0) {
-                LOGE("Could not get block device size (errno=%d)", errno);
+                ALOGE("Could not get block device size (errno=%d)", errno);
                 goto fail;
             }
             /* XXX: we assume that the disk has < 2^32 sectors :-) */
@@ -319,9 +319,9 @@
         } else
             disk_size = (uint64_t)dinfo->num_lba * (uint64_t)dinfo->sect_size;
     } else if (S_ISREG(stat.st_mode)) {
-        LOGI("Requesting operation on a regular file, not block device.");
+        ALOGI("Requesting operation on a regular file, not block device.");
         if (!dinfo->sect_size) {
-            LOGE("Sector size for regular file images cannot be zero");
+            ALOGE("Sector size for regular file images cannot be zero");
             goto fail;
         }
         if (dinfo->num_lba)
@@ -331,12 +331,12 @@
             disk_size = (uint64_t)stat.st_size;
         }
     } else {
-        LOGE("Device does not refer to a regular file or a block device!");
+        ALOGE("Device does not refer to a regular file or a block device!");
         goto fail;
     }
 
 #if 1
-    LOGV("Device/file %s: size=%llu bytes, num_lba=%u, sect_size=%d",
+    ALOGV("Device/file %s: size=%llu bytes, num_lba=%u, sect_size=%d",
          dinfo->device, disk_size, dinfo->num_lba, dinfo->sect_size);
 #endif
 
@@ -350,12 +350,12 @@
         if (part->len_kb != (uint32_t)-1) {
             total_size += part->len_kb * 1024;
         } else if (part->len_kb == 0) {
-            LOGE("Zero-size partition '%s' is invalid.", part->name);
+            ALOGE("Zero-size partition '%s' is invalid.", part->name);
             goto fail;
         } else {
             /* the partition requests the rest of the disk. */
             if (cnt + 1 != dinfo->num_parts) {
-                LOGE("Only the last partition in the list can request to fill "
+                ALOGE("Only the last partition in the list can request to fill "
                      "the rest of disk.");
                 goto fail;
             }
@@ -363,7 +363,7 @@
 
         if ((part->type != PC_PART_TYPE_LINUX) &&
             (part->type != PC_PART_TYPE_FAT32)) {
-            LOGE("Unknown partition type (0x%x) encountered for partition "
+            ALOGE("Unknown partition type (0x%x) encountered for partition "
                  "'%s'\n", part->type, part->name);
             goto fail;
         }
@@ -371,7 +371,7 @@
 
     /* only matters for disks, not files */
     if (S_ISBLK(stat.st_mode) && total_size > disk_size) {
-        LOGE("Total requested size of partitions (%llu) is greater than disk "
+        ALOGE("Total requested size of partitions (%llu) is greater than disk "
              "size (%llu).", total_size, disk_size);
         goto fail;
     }
@@ -399,7 +399,7 @@
         case PART_SCHEME_GPT:
             /* not supported yet */
         default:
-            LOGE("Uknown partition scheme.");
+            ALOGE("Uknown partition scheme.");
             break;
     }
 
@@ -438,7 +438,7 @@
     int rv;
 
     if (validate_and_config(dinfo, &fd, &wr_lst) != 0) {
-        LOGE("Configuration is invalid.");
+        ALOGE("Configuration is invalid.");
         goto fail;
     }
 
@@ -523,10 +523,10 @@
         case PART_SCHEME_MBR:
             return find_mbr_part(dinfo, name);
         case PART_SCHEME_GPT:
-            LOGE("GPT is presently not supported");
+            ALOGE("GPT is presently not supported");
             break;
         default:
-            LOGE("Unknown partition table scheme");
+            ALOGE("Unknown partition table scheme");
             break;
     }
 
diff --git a/libdiskconfig/diskutils.c b/libdiskconfig/diskutils.c
index 22767c0..e325735 100644
--- a/libdiskconfig/diskutils.c
+++ b/libdiskconfig/diskutils.c
@@ -40,20 +40,20 @@
     int done = 0;
     uint64_t total = 0;
 
-    LOGI("Writing RAW image '%s' to '%s' (offset=%llu)", src, dst, offset);
+    ALOGI("Writing RAW image '%s' to '%s' (offset=%llu)", src, dst, offset);
     if ((src_fd = open(src, O_RDONLY)) < 0) {
-        LOGE("Could not open %s for reading (errno=%d).", src, errno);
+        ALOGE("Could not open %s for reading (errno=%d).", src, errno);
         goto fail;
     }
 
     if (!test) {
         if ((dst_fd = open(dst, O_RDWR)) < 0) {
-            LOGE("Could not open '%s' for read/write (errno=%d).", dst, errno);
+            ALOGE("Could not open '%s' for read/write (errno=%d).", dst, errno);
             goto fail;
         }
 
         if (lseek64(dst_fd, offset, SEEK_SET) != offset) {
-            LOGE("Could not seek to offset %lld in %s.", offset, dst);
+            ALOGE("Could not seek to offset %lld in %s.", offset, dst);
             goto fail;
         }
     }
@@ -63,7 +63,7 @@
             /* XXX: Should we not even bother with EINTR? */
             if (errno == EINTR)
                 continue;
-            LOGE("Error (%d) while reading from '%s'", errno, src);
+            ALOGE("Error (%d) while reading from '%s'", errno, src);
             goto fail;
         }
 
@@ -84,7 +84,7 @@
                 /* XXX: Should we not even bother with EINTR? */
                 if (errno == EINTR)
                     continue;
-                LOGE("Error (%d) while writing to '%s'", errno, dst);
+                ALOGE("Error (%d) while writing to '%s'", errno, dst);
                 goto fail;
             }
             if (!tmp)
@@ -94,14 +94,14 @@
     }
 
     if (!done) {
-        LOGE("Exited read/write loop without setting flag! WTF?!");
+        ALOGE("Exited read/write loop without setting flag! WTF?!");
         goto fail;
     }
 
     if (dst_fd >= 0)
         fsync(dst_fd);
 
-    LOGI("Wrote %llu bytes to %s @ %lld", total, dst, offset);
+    ALOGI("Wrote %llu bytes to %s @ %lld", total, dst, offset);
 
     close(src_fd);
     if (dst_fd >= 0)
diff --git a/libdiskconfig/dump_diskconfig.c b/libdiskconfig/dump_diskconfig.c
index fff19f5..75256f6 100644
--- a/libdiskconfig/dump_diskconfig.c
+++ b/libdiskconfig/dump_diskconfig.c
@@ -28,7 +28,7 @@
     struct disk_info *dinfo;
 
     if (argc < 2) {
-        LOGE("usage: %s <conf file>", argv[0]);
+        ALOGE("usage: %s <conf file>", argv[0]);
         return 1;
     }
 
diff --git a/libdiskconfig/write_lst.c b/libdiskconfig/write_lst.c
index 12b7cd7..826ef7a 100644
--- a/libdiskconfig/write_lst.c
+++ b/libdiskconfig/write_lst.c
@@ -32,7 +32,7 @@
     struct write_list *item;
 
     if (!(item = malloc(sizeof(struct write_list) + data_len))) {
-        LOGE("Unable to allocate memory.");
+        ALOGE("Unable to allocate memory.");
         return NULL;
     }
 
@@ -71,18 +71,18 @@
 {
     for(; lst; lst = lst->next) {
         if (lseek64(fd, lst->offset, SEEK_SET) != (loff_t)lst->offset) {
-            LOGE("Cannot seek to the specified position (%lld).", lst->offset);
+            ALOGE("Cannot seek to the specified position (%lld).", lst->offset);
             goto fail;
         }
 
         if (!test) {
             if (write(fd, lst->data, lst->len) != (int)lst->len) {
-                LOGE("Failed writing %u bytes at position %lld.", lst->len,
+                ALOGE("Failed writing %u bytes at position %lld.", lst->len,
                      lst->offset);
                 goto fail;
             }
         } else
-            LOGI("Would write %d bytes @ offset %lld.", lst->len, lst->offset);
+            ALOGI("Would write %d bytes @ offset %lld.", lst->len, lst->offset);
     }
 
     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/libnetutils/dhcpclient.c b/libnetutils/dhcpclient.c
index 4f2d1c1..b38e258 100644
--- a/libnetutils/dhcpclient.c
+++ b/libnetutils/dhcpclient.c
@@ -70,7 +70,7 @@
     vsnprintf(errmsg, sizeof(errmsg), fmt, ap);
     va_end(ap);
 
-    LOGD("%s", errmsg);
+    ALOGD("%s", errmsg);
 }
 
 const char *dhcp_lasterror()
@@ -151,14 +151,14 @@
 void dump_dhcp_info(dhcp_info *info)
 {
     char addr[20], gway[20], mask[20];
-    LOGD("--- dhcp %s (%d) ---",
+    ALOGD("--- dhcp %s (%d) ---",
             dhcp_type_to_name(info->type), info->type);
     strcpy(addr, ipaddr(info->ipaddr));
     strcpy(gway, ipaddr(info->gateway));
-    LOGD("ip %s gw %s prefixLength %d", addr, gway, info->prefixLength);
-    if (info->dns1) LOGD("dns1: %s", ipaddr(info->dns1));
-    if (info->dns2) LOGD("dns2: %s", ipaddr(info->dns2));
-    LOGD("server %s, lease %d seconds",
+    ALOGD("ip %s gw %s prefixLength %d", addr, gway, info->prefixLength);
+    if (info->dns1) ALOGD("dns1: %s", ipaddr(info->dns1));
+    if (info->dns2) ALOGD("dns2: %s", ipaddr(info->dns2));
+    ALOGD("server %s, lease %d seconds",
             ipaddr(info->serveraddr), info->lease);
 }
 
@@ -250,9 +250,9 @@
     const char *name;
     char buf[2048];
 
-    LOGD("===== DHCP message:");
+    ALOGD("===== DHCP message:");
     if (len < DHCP_MSG_FIXED_SIZE) {
-        LOGD("Invalid length %d, should be %d", len, DHCP_MSG_FIXED_SIZE);
+        ALOGD("Invalid length %d, should be %d", len, DHCP_MSG_FIXED_SIZE);
         return;
     }
 
@@ -264,18 +264,18 @@
         name = "BOOTREPLY";
     else
         name = "????";
-    LOGD("op = %s (%d), htype = %d, hlen = %d, hops = %d",
+    ALOGD("op = %s (%d), htype = %d, hlen = %d, hops = %d",
            name, msg->op, msg->htype, msg->hlen, msg->hops);
-    LOGD("xid = 0x%08x secs = %d, flags = 0x%04x optlen = %d",
+    ALOGD("xid = 0x%08x secs = %d, flags = 0x%04x optlen = %d",
            ntohl(msg->xid), ntohs(msg->secs), ntohs(msg->flags), len);
-    LOGD("ciaddr = %s", ipaddr(msg->ciaddr));
-    LOGD("yiaddr = %s", ipaddr(msg->yiaddr));
-    LOGD("siaddr = %s", ipaddr(msg->siaddr));
-    LOGD("giaddr = %s", ipaddr(msg->giaddr));
+    ALOGD("ciaddr = %s", ipaddr(msg->ciaddr));
+    ALOGD("yiaddr = %s", ipaddr(msg->yiaddr));
+    ALOGD("siaddr = %s", ipaddr(msg->siaddr));
+    ALOGD("giaddr = %s", ipaddr(msg->giaddr));
 
     c = msg->hlen > 16 ? 16 : msg->hlen;
     hex2str(buf, msg->chaddr, c);
-    LOGD("chaddr = {%s}", buf);
+    ALOGD("chaddr = {%s}", buf);
 
     for (n = 0; n < 64; n++) {
         if ((msg->sname[n] < ' ') || (msg->sname[n] > 127)) {
@@ -293,8 +293,8 @@
     }
     msg->file[127] = 0;
 
-    LOGD("sname = '%s'", msg->sname);
-    LOGD("file = '%s'", msg->file);
+    ALOGD("sname = '%s'", msg->sname);
+    ALOGD("file = '%s'", msg->file);
 
     if (len < 4) return;
     len -= 4;
@@ -327,7 +327,7 @@
             name = dhcp_type_to_name(x[2]);
         else
             name = NULL;
-        LOGD("op %d len %d {%s} %s", x[0], optsz, buf, name == NULL ? "" : name);
+        ALOGD("op %d len %d {%s} %s", x[0], optsz, buf, name == NULL ? "" : name);
         len -= optsz;
         x = x + optsz + 2;
     }
@@ -347,28 +347,28 @@
 static int is_valid_reply(dhcp_msg *msg, dhcp_msg *reply, int sz)
 {
     if (sz < DHCP_MSG_FIXED_SIZE) {
-        if (verbose) LOGD("netcfg: Wrong size %d != %d\n", sz, DHCP_MSG_FIXED_SIZE);
+        if (verbose) ALOGD("netcfg: Wrong size %d != %d\n", sz, DHCP_MSG_FIXED_SIZE);
         return 0;
     }
     if (reply->op != OP_BOOTREPLY) {
-        if (verbose) LOGD("netcfg: Wrong Op %d != %d\n", reply->op, OP_BOOTREPLY);
+        if (verbose) ALOGD("netcfg: Wrong Op %d != %d\n", reply->op, OP_BOOTREPLY);
         return 0;
     }
     if (reply->xid != msg->xid) {
-        if (verbose) LOGD("netcfg: Wrong Xid 0x%x != 0x%x\n", ntohl(reply->xid),
+        if (verbose) ALOGD("netcfg: Wrong Xid 0x%x != 0x%x\n", ntohl(reply->xid),
                           ntohl(msg->xid));
         return 0;
     }
     if (reply->htype != msg->htype) {
-        if (verbose) LOGD("netcfg: Wrong Htype %d != %d\n", reply->htype, msg->htype);
+        if (verbose) ALOGD("netcfg: Wrong Htype %d != %d\n", reply->htype, msg->htype);
         return 0;
     }
     if (reply->hlen != msg->hlen) {
-        if (verbose) LOGD("netcfg: Wrong Hlen %d != %d\n", reply->hlen, msg->hlen);
+        if (verbose) ALOGD("netcfg: Wrong Hlen %d != %d\n", reply->hlen, msg->hlen);
         return 0;
     }
     if (memcmp(msg->chaddr, reply->chaddr, msg->hlen)) {
-        if (verbose) LOGD("netcfg: Wrong chaddr %x != %x\n", *(reply->chaddr),*(msg->chaddr));
+        if (verbose) ALOGD("netcfg: Wrong chaddr %x != %x\n", *(reply->chaddr),*(msg->chaddr));
         return 0;
     }
     return 1;
@@ -469,7 +469,7 @@
         r = receive_packet(s, &reply);
         if (r < 0) {
             if (errno != 0) {
-                LOGD("receive_packet failed (%d): %s", r, strerror(errno));
+                ALOGD("receive_packet failed (%d): %s", r, strerror(errno));
                 if (errno == ENETDOWN || errno == ENXIO) {
                     return -1;
                 }
diff --git a/libnetutils/ifc_utils.c b/libnetutils/ifc_utils.c
index 0a2f760..186b98c 100644
--- a/libnetutils/ifc_utils.c
+++ b/libnetutils/ifc_utils.c
@@ -46,8 +46,8 @@
 #else
 #include <stdio.h>
 #include <string.h>
-#define LOGD printf
-#define LOGW printf
+#define ALOGD printf
+#define ALOGW printf
 #endif
 
 static int ifc_ctl_sock = -1;
@@ -382,7 +382,7 @@
 
         ret = ifc_del_address(ifname, addrstr, prefixlen);
         if (ret) {
-            LOGE("Deleting address %s/%d on %s: %s", addrstr, prefixlen, ifname,
+            ALOGE("Deleting address %s/%d on %s: %s", addrstr, prefixlen, ifname,
                  strerror(-ret));
             lasterror = ret;
         }
@@ -686,7 +686,7 @@
         init_sockaddr_in(&rt.rt_genmask, mask);
         addr.s_addr = dest;
         if (ioctl(ifc_ctl_sock, SIOCDELRT, &rt) < 0) {
-            LOGD("failed to remove route for %s to %s: %s",
+            ALOGD("failed to remove route for %s to %s: %s",
                  ifname, inet_ntoa(addr), strerror(errno));
         }
     }
@@ -752,7 +752,7 @@
     ifc_init();
     addr.s_addr = gateway;
     if ((result = ifc_create_default_route(ifname, gateway)) < 0) {
-        LOGD("failed to add %s as default route for %s: %s",
+        ALOGD("failed to add %s as default route for %s: %s",
              inet_ntoa(addr), ifname, strerror(errno));
     }
     ifc_close();
@@ -773,7 +773,7 @@
     rt.rt_flags = RTF_UP|RTF_GATEWAY;
     init_sockaddr_in(&rt.rt_dst, 0);
     if ((result = ioctl(ifc_ctl_sock, SIOCDELRT, &rt)) < 0) {
-        LOGD("failed to remove default route for %s: %s", ifname, strerror(errno));
+        ALOGD("failed to remove default route for %s: %s", ifname, strerror(errno));
     }
     ifc_close();
     return result;
diff --git a/libnetutils/packet.c b/libnetutils/packet.c
index 9388345..3ec83fe 100644
--- a/libnetutils/packet.c
+++ b/libnetutils/packet.c
@@ -31,8 +31,8 @@
 #else
 #include <stdio.h>
 #include <string.h>
-#define LOGD printf
-#define LOGW printf
+#define ALOGD printf
+#define ALOGW printf
 #endif
 
 #include "dhcpmsg.h"
@@ -179,23 +179,23 @@
     is_valid = 0;
     if (nread < (int)(sizeof(struct iphdr) + sizeof(struct udphdr))) {
 #if VERBOSE
-        LOGD("Packet is too small (%d) to be a UDP datagram", nread);
+        ALOGD("Packet is too small (%d) to be a UDP datagram", nread);
 #endif
     } else if (packet.ip.version != IPVERSION || packet.ip.ihl != (sizeof(packet.ip) >> 2)) {
 #if VERBOSE
-        LOGD("Not a valid IP packet");
+        ALOGD("Not a valid IP packet");
 #endif
     } else if (nread < ntohs(packet.ip.tot_len)) {
 #if VERBOSE
-        LOGD("Packet was truncated (read %d, needed %d)", nread, ntohs(packet.ip.tot_len));
+        ALOGD("Packet was truncated (read %d, needed %d)", nread, ntohs(packet.ip.tot_len));
 #endif
     } else if (packet.ip.protocol != IPPROTO_UDP) {
 #if VERBOSE
-        LOGD("IP protocol (%d) is not UDP", packet.ip.protocol);
+        ALOGD("IP protocol (%d) is not UDP", packet.ip.protocol);
 #endif
     } else if (packet.udp.dest != htons(PORT_BOOTP_CLIENT)) {
 #if VERBOSE
-        LOGD("UDP dest port (%d) is not DHCP client", ntohs(packet.udp.dest));
+        ALOGD("UDP dest port (%d) is not DHCP client", ntohs(packet.udp.dest));
 #endif
     } else {
         is_valid = 1;
@@ -209,7 +209,7 @@
     /* validate IP header checksum */
     sum = finish_sum(checksum(&packet.ip, sizeof(packet.ip), 0));
     if (sum != 0) {
-        LOGW("IP header checksum failure (0x%x)", packet.ip.check);
+        ALOGW("IP header checksum failure (0x%x)", packet.ip.check);
         return -1;
     }
     /*
@@ -231,7 +231,7 @@
     sum = finish_sum(checksum(&packet, nread, 0));
     packet.udp.check = temp;
     if (temp != sum) {
-        LOGW("UDP header checksum failure (0x%x should be 0x%x)", sum, temp);
+        ALOGW("UDP header checksum failure (0x%x should be 0x%x)", sum, temp);
         return -1;
     }
     memcpy(msg, &packet.dhcp, dhcp_size);
diff --git a/libpixelflinger/codeflinger/ARMAssembler.cpp b/libpixelflinger/codeflinger/ARMAssembler.cpp
index 4726a08..0dc5037 100644
--- a/libpixelflinger/codeflinger/ARMAssembler.cpp
+++ b/libpixelflinger/codeflinger/ARMAssembler.cpp
@@ -177,7 +177,7 @@
     // the instruction cache is flushed by CodeCache
     const int64_t duration = ggl_system_time() - mDuration;
     const char * const format = "generated %s (%d ins) at [%p:%p] in %lld ns\n";
-    LOGI(format, name, int(pc()-base()), base(), pc(), duration);
+    ALOGI(format, name, int(pc()-base()), base(), pc(), duration);
 
 #if defined(WITH_LIB_HARDWARE)
     if (__builtin_expect(mQemuTracing, 0)) {
diff --git a/libpixelflinger/codeflinger/CodeCache.cpp b/libpixelflinger/codeflinger/CodeCache.cpp
index 125c3ce..a713feb 100644
--- a/libpixelflinger/codeflinger/CodeCache.cpp
+++ b/libpixelflinger/codeflinger/CodeCache.cpp
@@ -159,7 +159,7 @@
         const long base = long(assembly->base());
         const long curr = base + long(assembly->size());
         err = cacheflush(base, curr, 0);
-        LOGE_IF(err, "__ARM_NR_cacheflush error %s\n",
+        ALOGE_IF(err, "__ARM_NR_cacheflush error %s\n",
                 strerror(errno));
 #endif
     }
diff --git a/libpixelflinger/codeflinger/GGLAssembler.cpp b/libpixelflinger/codeflinger/GGLAssembler.cpp
index 1cd189c..f1d81b2 100644
--- a/libpixelflinger/codeflinger/GGLAssembler.cpp
+++ b/libpixelflinger/codeflinger/GGLAssembler.cpp
@@ -82,7 +82,7 @@
             needs.p, needs.n, needs.t[0], needs.t[1], per_fragment_ops);
 
     if (err) {
-        LOGE("Error while generating ""%s""\n", name);
+        ALOGE("Error while generating ""%s""\n", name);
         disassemble(name);
         return -1;
     }
@@ -1095,7 +1095,7 @@
     }
     // this is not an error anymore because, we'll try again with
     // a lower optimization level.
-    //LOGE_IF(i >= nbreg, "pixelflinger ran out of registers\n");
+    //ALOGE_IF(i >= nbreg, "pixelflinger ran out of registers\n");
     if (i >= nbreg) {
         mStatus |= OUT_OF_REGISTERS;
         // we return SP so we can more easily debug things
diff --git a/libpixelflinger/codeflinger/blending.cpp b/libpixelflinger/codeflinger/blending.cpp
index 083042c..c90eaa0 100644
--- a/libpixelflinger/codeflinger/blending.cpp
+++ b/libpixelflinger/codeflinger/blending.cpp
@@ -536,7 +536,7 @@
         }
     }
 
-    LOGE_IF(ms>=32, "mul_factor overflow vs=%d, fs=%d", vs, fs);
+    ALOGE_IF(ms>=32, "mul_factor overflow vs=%d, fs=%d", vs, fs);
 
     int vreg = v.reg;
     int freg = f.reg;
@@ -574,7 +574,7 @@
     int as = a.h;
     int ms = vs+fs;
 
-    LOGE_IF(ms>=32, "mul_factor_add overflow vs=%d, fs=%d, as=%d", vs, fs, as);
+    ALOGE_IF(ms>=32, "mul_factor_add overflow vs=%d, fs=%d, as=%d", vs, fs, as);
 
     integer_t add(a.reg, a.h, a.flags);
 
diff --git a/libpixelflinger/codeflinger/load_store.cpp b/libpixelflinger/codeflinger/load_store.cpp
index ed20a00..62aa05c 100644
--- a/libpixelflinger/codeflinger/load_store.cpp
+++ b/libpixelflinger/codeflinger/load_store.cpp
@@ -257,7 +257,7 @@
     int dbits = dh - dl;
     int dithering = 0;
     
-    LOGE_IF(sbits<dbits, "sbits (%d) < dbits (%d) in downshift", sbits, dbits);
+    ALOGE_IF(sbits<dbits, "sbits (%d) < dbits (%d) in downshift", sbits, dbits);
 
     if (sbits>dbits) {
         // see if we need to dither
diff --git a/libpixelflinger/codeflinger/texturing.cpp b/libpixelflinger/codeflinger/texturing.cpp
index 7f6f8da..8464fbd 100644
--- a/libpixelflinger/codeflinger/texturing.cpp
+++ b/libpixelflinger/codeflinger/texturing.cpp
@@ -778,7 +778,7 @@
             break;
         default:
             // unsupported format, do something sensical...
-            LOGE("Unsupported 16-bits texture format (%d)", tmu.format_idx);
+            ALOGE("Unsupported 16-bits texture format (%d)", tmu.format_idx);
             LDRH(AL, texel.reg, txPtr.reg);
             return;
     }
diff --git a/libpixelflinger/scanline.cpp b/libpixelflinger/scanline.cpp
index a37b47e..93440f5 100644
--- a/libpixelflinger/scanline.cpp
+++ b/libpixelflinger/scanline.cpp
@@ -351,7 +351,7 @@
     }
 
 #if DEBUG_NEEDS
-    LOGI("Needs: n=0x%08x p=0x%08x t0=0x%08x t1=0x%08x",
+    ALOGI("Needs: n=0x%08x p=0x%08x t0=0x%08x t1=0x%08x",
          c->state.needs.n, c->state.needs.p,
          c->state.needs.t[0], c->state.needs.t[1]);
 #endif
@@ -381,7 +381,7 @@
             err = gCodeCache.cache(a->key(), a);
         }
         if (ggl_unlikely(err)) {
-            LOGE("error generating or caching assembly. Reverting to NOP.");
+            ALOGE("error generating or caching assembly. Reverting to NOP.");
             c->scanline = scanline_noop;
             c->init_y = init_y_noop;
             c->step_y = step_y__nop;
@@ -395,12 +395,12 @@
         c->scanline_as->decStrong(c);
     }
 
-    //LOGI("using generated pixel-pipeline");
+    //ALOGI("using generated pixel-pipeline");
     c->scanline_as = assembly.get();
     c->scanline_as->incStrong(c); //  hold on to assembly
     c->scanline = (void(*)(context_t* c))assembly->base();
 #else
-//    LOGW("using generic (slow) pixel-pipeline");
+//    ALOGW("using generic (slow) pixel-pipeline");
     c->scanline = scanline;
 #endif
 }
@@ -1761,7 +1761,7 @@
     // woooops, shoud never happen,
     // fail gracefully (don't display anything)
     init_y_noop(c, y0);
-    LOGE("color-buffer has an invalid format!");
+    ALOGE("color-buffer has an invalid format!");
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libpixelflinger/tinyutils/VectorImpl.cpp b/libpixelflinger/tinyutils/VectorImpl.cpp
index a049706..be3d270 100644
--- a/libpixelflinger/tinyutils/VectorImpl.cpp
+++ b/libpixelflinger/tinyutils/VectorImpl.cpp
@@ -272,7 +272,7 @@
 
 void* VectorImpl::_grow(size_t where, size_t amount)
 {
-//    LOGV("_grow(this=%p, where=%d, amount=%d) count=%d, capacity=%d",
+//    ALOGV("_grow(this=%p, where=%d, amount=%d) count=%d, capacity=%d",
 //        this, (int)where, (int)amount, (int)mCount, (int)capacity());
 
     if (where > mCount)
@@ -281,7 +281,7 @@
     const size_t new_size = mCount + amount;
     if (capacity() < new_size) {
         const size_t new_capacity = max(kMinVectorCapacity, ((new_size*3)+1)/2);
-//        LOGV("grow vector %p, new_capacity=%d", this, (int)new_capacity);
+//        ALOGV("grow vector %p, new_capacity=%d", this, (int)new_capacity);
         if ((mStorage) &&
             (mCount==where) &&
             (mFlags & HAS_TRIVIAL_COPY) &&
@@ -325,7 +325,7 @@
     if (!mStorage)
         return;
 
-//    LOGV("_shrink(this=%p, where=%d, amount=%d) count=%d, capacity=%d",
+//    ALOGV("_shrink(this=%p, where=%d, amount=%d) count=%d, capacity=%d",
 //        this, (int)where, (int)amount, (int)mCount, (int)capacity());
 
     if (where >= mCount)
@@ -334,7 +334,7 @@
     const size_t new_size = mCount - amount;
     if (new_size*3 < capacity()) {
         const size_t new_capacity = max(kMinVectorCapacity, new_size*2);
-//        LOGV("shrink vector %p, new_capacity=%d", this, (int)new_capacity);
+//        ALOGV("shrink vector %p, new_capacity=%d", this, (int)new_capacity);
         if ((where == mCount-amount) &&
             (mFlags & HAS_TRIVIAL_COPY) &&
             (mFlags & HAS_TRIVIAL_DTOR))
diff --git a/libpixelflinger/trap.cpp b/libpixelflinger/trap.cpp
index 30b633f..80efeff 100644
--- a/libpixelflinger/trap.cpp
+++ b/libpixelflinger/trap.cpp
@@ -94,15 +94,15 @@
 static void
 triangle_dump_points( const GGLcoord*  v0,
                       const GGLcoord*  v1,
-				 	  const GGLcoord*  v2 )
+                      const GGLcoord*  v2 )
 {
     float tri = 1.0f / TRI_ONE;
-  LOGD(     "  P0=(%.3f, %.3f)  [%08x, %08x]\n"
-            "  P1=(%.3f, %.3f)  [%08x, %08x]\n"
-            "  P2=(%.3f, %.3f)  [%08x, %08x]\n",
-		v0[0]*tri, v0[1]*tri, v0[0], v0[1],
-		v1[0]*tri, v1[1]*tri, v1[0], v1[1],
-		v2[0]*tri, v2[1]*tri, v2[0], v2[1] );
+    ALOGD("  P0=(%.3f, %.3f)  [%08x, %08x]\n"
+          "  P1=(%.3f, %.3f)  [%08x, %08x]\n"
+          "  P2=(%.3f, %.3f)  [%08x, %08x]\n",
+          v0[0]*tri, v0[1]*tri, v0[0], v0[1],
+          v1[0]*tri, v1[1]*tri, v1[0], v1[1],
+          v2[0]*tri, v2[1]*tri, v2[0], v2[1] );
 }
 
 // ----------------------------------------------------------------------------
@@ -639,7 +639,7 @@
 static void
 edge_dump( Edge*  edge )
 {
-  LOGI( "  top=%d (%.3f)  bot=%d (%.3f)  x=%d (%.3f)  ix=%d (%.3f)",
+  ALOGI( "  top=%d (%.3f)  bot=%d (%.3f)  x=%d (%.3f)  ix=%d (%.3f)",
         edge->y_top, edge->y_top/float(TRI_ONE),
 		edge->y_bot, edge->y_bot/float(TRI_ONE),
 		edge->x, edge->x/float(FIXED_ONE),
@@ -650,7 +650,7 @@
 triangle_dump_edges( Edge*  edges,
                      int            count )
 { 
-    LOGI( "%d edge%s:\n", count, count == 1 ? "" : "s" );
+    ALOGI( "%d edge%s:\n", count, count == 1 ? "" : "s" );
 	for ( ; count > 0; count--, edges++ )
 	  edge_dump( edges );
 }
@@ -835,7 +835,7 @@
     float tri  = 1.0f / TRI_ONE;
     float iter = 1.0f / (1<<TRI_ITERATORS_BITS);
     float fix  = 1.0f / FIXED_ONE;
-    LOGD(   "x=%08x (%.3f), "
+    ALOGD(   "x=%08x (%.3f), "
             "x_incr=%08x (%.3f), y_incr=%08x (%.3f), "
             "y_top=%08x (%.3f), y_bot=%08x (%.3f) ",
         x, x*fix,
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/libusbhost/usbhost.c b/libusbhost/usbhost.c
index b1c967d..5d261cd 100644
--- a/libusbhost/usbhost.c
+++ b/libusbhost/usbhost.c
@@ -20,7 +20,7 @@
 #ifdef USE_LIBLOG
 #define LOG_TAG "usbhost"
 #include "utils/Log.h"
-#define D LOGD
+#define D ALOGD
 #else
 #define D printf
 #endif
diff --git a/logwrapper/logwrapper.c b/logwrapper/logwrapper.c
index bdf53e8..6a80560 100644
--- a/logwrapper/logwrapper.c
+++ b/logwrapper/logwrapper.c
@@ -28,7 +28,7 @@
 
 void fatal(const char *msg) {
     fprintf(stderr, "%s", msg);
-    LOG(LOG_ERROR, "logwrapper", "%s", msg);
+    ALOG(LOG_ERROR, "logwrapper", "%s", msg);
     exit(-1);
 }
 
@@ -60,7 +60,7 @@
                 buffer[b] = '\0';
             } else if (buffer[b] == '\n') {
                 buffer[b] = '\0';
-                LOG(LOG_INFO, tag, "%s", &buffer[a]);
+                ALOG(LOG_INFO, tag, "%s", &buffer[a]);
                 a = b + 1;
             }
         }
@@ -68,7 +68,7 @@
         if (a == 0 && b == sizeof(buffer) - 1) {
             // buffer is full, flush
             buffer[b] = '\0';
-            LOG(LOG_INFO, tag, "%s", &buffer[a]);
+            ALOG(LOG_INFO, tag, "%s", &buffer[a]);
             b = 0;
         } else if (a != b) {
             // Keep left-overs
@@ -84,21 +84,21 @@
     // Flush remaining data
     if (a != b) {
         buffer[b] = '\0';
-	LOG(LOG_INFO, tag, "%s", &buffer[a]);
+        ALOG(LOG_INFO, tag, "%s", &buffer[a]);
     }
     status = 0xAAAA;
     if (wait(&status) != -1) {  // Wait for child
         if (WIFEXITED(status))
-            LOG(LOG_INFO, "logwrapper", "%s terminated by exit(%d)", tag,
+            ALOG(LOG_INFO, "logwrapper", "%s terminated by exit(%d)", tag,
                     WEXITSTATUS(status));
         else if (WIFSIGNALED(status))
-            LOG(LOG_INFO, "logwrapper", "%s terminated by signal %d", tag,
+            ALOG(LOG_INFO, "logwrapper", "%s terminated by signal %d", tag,
                     WTERMSIG(status));
         else if (WIFSTOPPED(status))
-            LOG(LOG_INFO, "logwrapper", "%s stopped by signal %d", tag,
+            ALOG(LOG_INFO, "logwrapper", "%s stopped by signal %d", tag,
                     WSTOPSIG(status));
     } else
-        LOG(LOG_INFO, "logwrapper", "%s wait() failed: %s (%d)", tag,
+        ALOG(LOG_INFO, "logwrapper", "%s wait() failed: %s (%d)", tag,
                 strerror(errno), errno);
     if (seg_fault_on_exit)
         *(int *)status = 0;  // causes SIGSEGV with fault_address = status
@@ -111,7 +111,7 @@
     argv_child[argc] = NULL;
 
     if (execvp(argv_child[0], argv_child)) {
-        LOG(LOG_ERROR, "logwrapper",
+        ALOG(LOG_ERROR, "logwrapper",
             "executing %s failed: %s\n", argv_child[0], strerror(errno));
         exit(-1);
     }
diff --git a/nexus/CommandListener.cpp b/nexus/CommandListener.cpp
index 5973ff5..7c934a7 100644
--- a/nexus/CommandListener.cpp
+++ b/nexus/CommandListener.cpp
@@ -213,12 +213,12 @@
         if (!NetworkManager::Instance()->getPropMngr()->get((*it),
                                                             p_v,
                                                             sizeof(p_v))) {
-            LOGW("Failed to get %s (%s)", (*it), strerror(errno));
+            ALOGW("Failed to get %s (%s)", (*it), strerror(errno));
         }
 
         char *buf;
         if (asprintf(&buf, "%s %s", (*it), p_v) < 0) {
-            LOGE("Failed to allocate memory");
+            ALOGE("Failed to allocate memory");
             free((*it));
             continue;
         }
diff --git a/nexus/Controller.cpp b/nexus/Controller.cpp
index f6a2436..dae8783 100644
--- a/nexus/Controller.cpp
+++ b/nexus/Controller.cpp
@@ -86,7 +86,7 @@
     }
 
     if (rc != 0) {
-        LOGW("Unable to unload kernel driver '%s' (%s)", modtag,
+        ALOGW("Unable to unload kernel driver '%s' (%s)", modtag,
              strerror(errno));
     }
     return rc;
@@ -96,7 +96,7 @@
     FILE *fp = fopen("/proc/modules", "r");
 
     if (!fp) {
-        LOGE("Unable to open /proc/modules (%s)", strerror(errno));
+        ALOGE("Unable to open /proc/modules (%s)", strerror(errno));
         return false;
     }
 
@@ -105,7 +105,7 @@
         char *endTag = strchr(line, ' ');
 
         if (!endTag) {
-            LOGW("Unable to find tag for line '%s'", line);
+            ALOGW("Unable to find tag for line '%s'", line);
             continue;
         }
         if (!strncmp(line, modtag, (endTag - line))) {
diff --git a/nexus/DhcpClient.cpp b/nexus/DhcpClient.cpp
index 713059d..81fdf47 100644
--- a/nexus/DhcpClient.cpp
+++ b/nexus/DhcpClient.cpp
@@ -53,7 +53,7 @@
 }
 
 int DhcpClient::start(Controller *c) {
-    LOGD("Starting DHCP service (arp probe = %d)", mDoArpProbe);
+    ALOGD("Starting DHCP service (arp probe = %d)", mDoArpProbe);
     char svc[PROPERTY_VALUE_MAX];
     snprintf(svc,
              sizeof(svc),
@@ -72,7 +72,7 @@
 
     sockaddr_in addr;
     if ((mListenerSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
-        LOGE("Failed to create DHCP listener socket");
+        ALOGE("Failed to create DHCP listener socket");
         pthread_mutex_unlock(&mLock);
         return -1;
     }
@@ -82,7 +82,7 @@
     addr.sin_port = htons(DhcpClient::STATUS_MONITOR_PORT);
 
     if (bind(mListenerSocket, (struct sockaddr *) &addr, sizeof(addr))) {
-        LOGE("Failed to bind DHCP listener socket");
+        ALOGE("Failed to bind DHCP listener socket");
         close(mListenerSocket);
         mListenerSocket = -1;
         pthread_mutex_unlock(&mLock);
@@ -90,14 +90,14 @@
     }
 
     if (mServiceManager->start(svc)) {
-        LOGE("Failed to start dhcp service");
+        ALOGE("Failed to start dhcp service");
         pthread_mutex_unlock(&mLock);
         return -1;
     }
 
     mListener = new DhcpListener(mController, mListenerSocket, mHandlers);
     if (mListener->startListener()) {
-        LOGE("Failed to start listener");
+        ALOGE("Failed to start listener");
 #if 0
         mServiceManager->stop("dhcpcd");
         return -1;
@@ -126,7 +126,7 @@
     close(mListenerSocket);
 
     if (mServiceManager->stop("dhcpcd")) {
-        LOGW("Failed to stop DHCP service (%s)", strerror(errno));
+        ALOGW("Failed to stop DHCP service (%s)", strerror(errno));
         // XXX: Kill it the hard way.. but its gotta go!
     }
 
diff --git a/nexus/DhcpEvent.cpp b/nexus/DhcpEvent.cpp
index 58893f4..2f1ce6f 100644
--- a/nexus/DhcpEvent.cpp
+++ b/nexus/DhcpEvent.cpp
@@ -50,7 +50,7 @@
     else if (!strcasecmp(buffer, "TIMEOUT"))
         return DhcpEvent::TIMEOUT;
     else {
-        LOGW("Bad event '%s'", buffer);
+        ALOGW("Bad event '%s'", buffer);
         return -1;
     }
 }
diff --git a/nexus/DhcpListener.cpp b/nexus/DhcpListener.cpp
index afa68eb..16c369b 100644
--- a/nexus/DhcpListener.cpp
+++ b/nexus/DhcpListener.cpp
@@ -42,7 +42,7 @@
     int rc;
 
     if ((rc = read(cli->getSocket(), buffer, sizeof(buffer))) < 0) {
-        LOGW("Error reading dhcp status msg (%s)", strerror(errno));
+        ALOGW("Error reading dhcp status msg (%s)", strerror(errno));
         return true;
     }
 
@@ -53,7 +53,7 @@
 
         for (i = 0; i < 2; i++) {
             if (!(tmp = strsep(&next, ":"))) {
-                LOGW("Error parsing state '%s'", buffer);
+                ALOGW("Error parsing state '%s'", buffer);
                 return true;
             }
         }
@@ -65,22 +65,22 @@
 	struct in_addr ipaddr, netmask, gateway, broadcast, dns1, dns2;
 
         if (!inet_aton(strsep(&next, ":"), &ipaddr)) {
-            LOGW("Malformatted IP specified");
+            ALOGW("Malformatted IP specified");
         }
         if (!inet_aton(strsep(&next, ":"), &netmask)) {
-            LOGW("Malformatted netmask specified");
+            ALOGW("Malformatted netmask specified");
         }
         if (!inet_aton(strsep(&next, ":"), &broadcast)) {
-            LOGW("Malformatted broadcast specified");
+            ALOGW("Malformatted broadcast specified");
         }
         if (!inet_aton(strsep(&next, ":"), &gateway)) {
-            LOGW("Malformatted gateway specified");
+            ALOGW("Malformatted gateway specified");
         }
         if (!inet_aton(strsep(&next, ":"), &dns1)) {
-            LOGW("Malformatted dns1 specified");
+            ALOGW("Malformatted dns1 specified");
         }
         if (!inet_aton(strsep(&next, ":"), &dns2)) {
-            LOGW("Malformatted dns2 specified");
+            ALOGW("Malformatted dns2 specified");
         }
         mHandlers->onDhcpLeaseUpdated(mController, &ipaddr, &netmask,
                                       &broadcast, &gateway, &dns1, &dns2);
@@ -92,7 +92,7 @@
 
         for (i = 0; i < 2; i++) {
             if (!(tmp = strsep(&next, ":"))) {
-                LOGW("Error parsing event '%s'", buffer);
+                ALOGW("Error parsing event '%s'", buffer);
                 return true;
             }
         }
@@ -101,7 +101,7 @@
         mHandlers->onDhcpEvent(mController, ev);
   
     } else {
-        LOGW("Unknown DHCP monitor msg '%s'", buffer);
+        ALOGW("Unknown DHCP monitor msg '%s'", buffer);
     }
 
     return true;
diff --git a/nexus/DhcpState.cpp b/nexus/DhcpState.cpp
index c9d5135..b86c186 100644
--- a/nexus/DhcpState.cpp
+++ b/nexus/DhcpState.cpp
@@ -74,7 +74,7 @@
     else if (!strcasecmp(buffer, "ANNOUNCING"))
         return DhcpState::ANNOUNCING;
     else {
-        LOGW("Bad state '%s'", buffer);
+        ALOGW("Bad state '%s'", buffer);
         return -1;
     }
 }
diff --git a/nexus/NetworkManager.cpp b/nexus/NetworkManager.cpp
index e0df409..d4285bf 100644
--- a/nexus/NetworkManager.cpp
+++ b/nexus/NetworkManager.cpp
@@ -49,7 +49,7 @@
 
 int NetworkManager::run() {
     if (startControllers()) {
-        LOGW("Unable to start all controllers (%s)", strerror(errno));
+        ALOGW("Unable to start all controllers (%s)", strerror(errno));
     }
     return 0;
 }
@@ -107,29 +107,29 @@
 }
 
 void NetworkManager::onInterfaceConnected(Controller *c) {
-    LOGD("Controller %s interface %s connected", c->getName(), c->getBoundInterface());
+    ALOGD("Controller %s interface %s connected", c->getName(), c->getBoundInterface());
 
     if (mDhcp->start(c)) {
-        LOGE("Failed to start DHCP (%s)", strerror(errno));
+        ALOGE("Failed to start DHCP (%s)", strerror(errno));
         return;
     }
 }
 
 void NetworkManager::onInterfaceDisconnected(Controller *c) {
-    LOGD("Controller %s interface %s disconnected", c->getName(),
+    ALOGD("Controller %s interface %s disconnected", c->getName(),
          c->getBoundInterface());
 
     mDhcp->stop();
 }
 
 void NetworkManager::onControllerSuspending(Controller *c) {
-    LOGD("Controller %s interface %s suspending", c->getName(),
+    ALOGD("Controller %s interface %s suspending", c->getName(),
          c->getBoundInterface());
     mDhcp->stop();
 }
 
 void NetworkManager::onControllerResumed(Controller *c) {
-    LOGD("Controller %s interface %s resumed", c->getName(),
+    ALOGD("Controller %s interface %s resumed", c->getName(),
          c->getBoundInterface());
 }
 
@@ -137,7 +137,7 @@
     char tmp[255];
     char tmp2[255];
 
-    LOGD("onDhcpStateChanged(%s -> %s)",
+    ALOGD("onDhcpStateChanged(%s -> %s)",
          DhcpState::toString(mLastDhcpState, tmp, sizeof(tmp)),
          DhcpState::toString(state, tmp2, sizeof(tmp2)));
 
@@ -169,7 +169,7 @@
 
 void NetworkManager::onDhcpEvent(Controller *c, int evt) {
     char tmp[64];
-    LOGD("onDhcpEvent(%s)", DhcpEvent::toString(evt, tmp, sizeof(tmp)));
+    ALOGD("onDhcpEvent(%s)", DhcpEvent::toString(evt, tmp, sizeof(tmp)));
 }
 
 void NetworkManager::onDhcpLeaseUpdated(Controller *c, struct in_addr *addr,
diff --git a/nexus/OpenVpnController.cpp b/nexus/OpenVpnController.cpp
index f1ea510..6b6d892 100644
--- a/nexus/OpenVpnController.cpp
+++ b/nexus/OpenVpnController.cpp
@@ -53,7 +53,7 @@
     char tmp[64];
 
     if (!mPropMngr->get("vpn.gateway", tmp, sizeof(tmp))) {
-        LOGE("Error reading property 'vpn.gateway' (%s)", strerror(errno));
+        ALOGE("Error reading property 'vpn.gateway' (%s)", strerror(errno));
         return -1;
     }
     snprintf(svc, sizeof(svc), "openvpn:--remote %s 1194", tmp);
diff --git a/nexus/Property.cpp b/nexus/Property.cpp
index d02769d..6cfa955 100644
--- a/nexus/Property.cpp
+++ b/nexus/Property.cpp
@@ -30,7 +30,7 @@
           mName(name), mReadOnly(readOnly), mType(type),
           mNumElements(numElements) {
     if (index(name, '.')) {
-        LOGW("Property name %s violates namespace rules", name);
+        ALOGW("Property name %s violates namespace rules", name);
     }
 }
 
@@ -38,22 +38,22 @@
                 Property(name, ro, Property::Type_STRING, elements) {
 }
 int StringProperty::set(int idx, int value) {
-    LOGE("Integer 'set' called on string property!");
+    ALOGE("Integer 'set' called on string property!");
     errno = EINVAL;
     return -1;
 }
 int StringProperty::set(int idx, struct in_addr *value) {
-    LOGE("IpAddr 'set' called on string property!");
+    ALOGE("IpAddr 'set' called on string property!");
     errno = EINVAL;
     return -1;
 }
 int StringProperty::get(int idx, int *buffer) {
-    LOGE("Integer 'get' called on string property!");
+    ALOGE("Integer 'get' called on string property!");
     errno = EINVAL;
     return -1;
 }
 int StringProperty::get(int idx, struct in_addr *buffer) {
-    LOGE("IpAddr 'get' called on string property!");
+    ALOGE("IpAddr 'get' called on string property!");
     errno = EINVAL;
     return -1;
 }
@@ -67,7 +67,7 @@
 
 int StringPropertyHelper::set(int idx, const char *value) {
     if (idx != 0) {
-        LOGW("Attempt to use array index on StringPropertyHelper::set");
+        ALOGW("Attempt to use array index on StringPropertyHelper::set");
         errno = EINVAL;
         return -1;
     }
@@ -77,7 +77,7 @@
 
 int StringPropertyHelper::get(int idx, char *buffer, size_t max) {
     if (idx != 0) {
-        LOGW("Attempt to use array index on StringPropertyHelper::get");
+        ALOGW("Attempt to use array index on StringPropertyHelper::get");
         errno = EINVAL;
         return -1;
     }
@@ -90,22 +90,22 @@
 }
 
 int IntegerProperty::set(int idx, const char *value) {
-    LOGE("String 'set' called on integer property!");
+    ALOGE("String 'set' called on integer property!");
     errno = EINVAL;
     return -1;
 }
 int IntegerProperty::set(int idx, struct in_addr *value) {
-    LOGE("IpAddr 'set' called on integer property!");
+    ALOGE("IpAddr 'set' called on integer property!");
     errno = EINVAL;
     return -1;
 }
 int IntegerProperty::get(int idx, char *buffer, size_t max) {
-    LOGE("String 'get' called on integer property!");
+    ALOGE("String 'get' called on integer property!");
     errno = EINVAL;
     return -1;
 }
 int IntegerProperty::get(int idx, struct in_addr *buffer) {
-    LOGE("IpAddr 'get' called on integer property!");
+    ALOGE("IpAddr 'get' called on integer property!");
     errno = EINVAL;
     return -1;
 }
@@ -118,7 +118,7 @@
 
 int IntegerPropertyHelper::set(int idx, int value) {
     if (idx != 0) {
-        LOGW("Attempt to use array index on IntegerPropertyHelper::set");
+        ALOGW("Attempt to use array index on IntegerPropertyHelper::set");
         errno = EINVAL;
         return -1;
     }
@@ -128,7 +128,7 @@
 
 int IntegerPropertyHelper::get(int idx, int *buffer) {
     if (idx != 0) {
-        LOGW("Attempt to use array index on IntegerPropertyHelper::get");
+        ALOGW("Attempt to use array index on IntegerPropertyHelper::get");
         errno = EINVAL;
         return -1;
     }
@@ -141,22 +141,22 @@
 }
 
 int IPV4AddressProperty::set(int idx, const char *value) {
-    LOGE("String 'set' called on ipv4 property!");
+    ALOGE("String 'set' called on ipv4 property!");
     errno = EINVAL;
     return -1;
 }
 int IPV4AddressProperty::set(int idx, int value) {
-    LOGE("Integer 'set' called on ipv4 property!");
+    ALOGE("Integer 'set' called on ipv4 property!");
     errno = EINVAL;
     return -1;
 }
 int IPV4AddressProperty::get(int idx, char *buffer, size_t max) {
-    LOGE("String 'get' called on ipv4 property!");
+    ALOGE("String 'get' called on ipv4 property!");
     errno = EINVAL;
     return -1;
 }
 int IPV4AddressProperty::get(int idx, int *buffer) {
-    LOGE("Integer 'get' called on ipv4 property!");
+    ALOGE("Integer 'get' called on ipv4 property!");
     errno = EINVAL;
     return -1;
 }
@@ -169,7 +169,7 @@
 
 int IPV4AddressPropertyHelper::set(int idx, struct in_addr *value) {
     if (idx != 0) {
-        LOGW("Attempt to use array index on IPV4AddressPropertyHelper::set");
+        ALOGW("Attempt to use array index on IPV4AddressPropertyHelper::set");
         errno = EINVAL;
         return -1;
     }
@@ -179,7 +179,7 @@
 
 int IPV4AddressPropertyHelper::get(int idx, struct in_addr *buffer) {
     if (idx != 0) {
-        LOGW("Attempt to use array index on IPV4AddressPropertyHelper::get");
+        ALOGW("Attempt to use array index on IPV4AddressPropertyHelper::get");
         errno = EINVAL;
         return -1;
     }
diff --git a/nexus/PropertyManager.cpp b/nexus/PropertyManager.cpp
index 704b223..41cdb41 100644
--- a/nexus/PropertyManager.cpp
+++ b/nexus/PropertyManager.cpp
@@ -66,10 +66,10 @@
 int PropertyManager::attachProperty(const char *ns_name, Property *p) {
     PropertyNamespace *ns;
 
-    LOGD("Attaching property %s to namespace %s", p->getName(), ns_name);
+    ALOGD("Attaching property %s to namespace %s", p->getName(), ns_name);
     pthread_mutex_lock(&mLock);
     if (!(ns = lookupNamespace_UNLOCKED(ns_name))) {
-        LOGD("Creating namespace %s", ns_name);
+        ALOGD("Creating namespace %s", ns_name);
         ns = new PropertyNamespace(ns_name);
         mNamespaces->push_back(ns);
     }
@@ -77,7 +77,7 @@
     if (lookupProperty_UNLOCKED(ns, p->getName())) {
         errno = EADDRINUSE;
         pthread_mutex_unlock(&mLock);
-        LOGE("Failed to register property %s.%s (%s)",
+        ALOGE("Failed to register property %s.%s (%s)",
             ns_name, p->getName(), strerror(errno));
         return -1;
     }
@@ -90,11 +90,11 @@
 int PropertyManager::detachProperty(const char *ns_name, Property *p) {
     PropertyNamespace *ns;
 
-    LOGD("Detaching property %s from namespace %s", p->getName(), ns_name);
+    ALOGD("Detaching property %s from namespace %s", p->getName(), ns_name);
     pthread_mutex_lock(&mLock);
     if (!(ns = lookupNamespace_UNLOCKED(ns_name))) {
         pthread_mutex_unlock(&mLock);
-        LOGE("Namespace '%s' not found", ns_name);
+        ALOGE("Namespace '%s' not found", ns_name);
         return -1;
     }
 
@@ -110,7 +110,7 @@
         }
     }
 
-    LOGE("Property %s.%s not found", ns_name, p->getName());
+    ALOGE("Property %s.%s not found", ns_name, p->getName());
     pthread_mutex_unlock(&mLock);
     errno = ENOENT;
     return -1;
@@ -130,7 +130,7 @@
         errno = 0;
         tmp = strtol(value, (char **) NULL, 10);
         if (errno) {
-            LOGE("Failed to convert '%s' to int", value);
+            ALOGE("Failed to convert '%s' to int", value);
             errno = EINVAL;
             return -1;
         }
@@ -138,13 +138,13 @@
     } else if (p->getType() == Property::Type_IPV4) {
         struct in_addr tmp;
         if (!inet_aton(value, &tmp)) {
-            LOGE("Failed to convert '%s' to ipv4", value);
+            ALOGE("Failed to convert '%s' to ipv4", value);
             errno = EINVAL;
             return -1;
         }
         return p->set(idx, &tmp);
     } else {
-        LOGE("Property '%s' has an unknown type (%d)", p->getName(),
+        ALOGE("Property '%s' has an unknown type (%d)", p->getName(),
              p->getType());
         errno = EINVAL;
         return -1;
@@ -157,7 +157,7 @@
 
     if (p->getType() == Property::Type_STRING) {
         if (p->get(idx, buffer, max)) {
-            LOGW("String property %s get failed (%s)", p->getName(),
+            ALOGW("String property %s get failed (%s)", p->getName(),
                  strerror(errno));
             return -1;
         }
@@ -165,7 +165,7 @@
     else if (p->getType() == Property::Type_INTEGER) {
         int tmp;
         if (p->get(idx, &tmp)) {
-            LOGW("Integer property %s get failed (%s)", p->getName(),
+            ALOGW("Integer property %s get failed (%s)", p->getName(),
                  strerror(errno));
             return -1;
         }
@@ -173,13 +173,13 @@
     } else if (p->getType() == Property::Type_IPV4) {
         struct in_addr tmp;
         if (p->get(idx, &tmp)) {
-            LOGW("IPV4 property %s get failed (%s)", p->getName(),
+            ALOGW("IPV4 property %s get failed (%s)", p->getName(),
                  strerror(errno));
             return -1;
         }
         strncpy(buffer, inet_ntoa(tmp), max);
     } else {
-        LOGE("Property '%s' has an unknown type (%d)", p->getName(),
+        ALOGE("Property '%s' has an unknown type (%d)", p->getName(),
              p->getType());
         errno = EINVAL;
         return -1;
@@ -193,7 +193,7 @@
 
 int PropertyManager::set(const char *name, const char *value) {
 
-    LOGD("set %s = '%s'", name, value);
+    ALOGD("set %s = '%s'", name, value);
     pthread_mutex_lock(&mLock);
     PropertyNamespaceCollection::iterator ns_it;
     for (ns_it = mNamespaces->begin(); ns_it != mNamespaces->end(); ++ns_it) {
@@ -215,7 +215,7 @@
         }
     }
 
-    LOGE("Property %s not found", name);
+    ALOGE("Property %s not found", name);
     pthread_mutex_unlock(&mLock);
     errno = ENOENT;
     return -1;
@@ -246,7 +246,7 @@
         }
     }
 
-    LOGE("Property %s not found", name);
+    ALOGE("Property %s not found", name);
     pthread_mutex_unlock(&mLock);
     errno = ENOENT;
     return NULL;
diff --git a/nexus/ScanResult.cpp b/nexus/ScanResult.cpp
index e9a286c..72cb164 100644
--- a/nexus/ScanResult.cpp
+++ b/nexus/ScanResult.cpp
@@ -74,7 +74,7 @@
 
     return;
  out_bad:
-    LOGW("Malformatted scan result (%s)", rawResult);
+    ALOGW("Malformatted scan result (%s)", rawResult);
 }
 
 ScanResult::~ScanResult() {
diff --git a/nexus/Supplicant.cpp b/nexus/Supplicant.cpp
index 6aa36e8..b604698 100644
--- a/nexus/Supplicant.cpp
+++ b/nexus/Supplicant.cpp
@@ -64,22 +64,22 @@
 int Supplicant::start() {
 
     if (setupConfig()) {
-        LOGW("Unable to setup supplicant.conf");
+        ALOGW("Unable to setup supplicant.conf");
     }
 
     if (mServiceManager->start(SUPPLICANT_SERVICE_NAME)) {
-        LOGE("Error starting supplicant (%s)", strerror(errno));
+        ALOGE("Error starting supplicant (%s)", strerror(errno));
         return -1;
     }
 
     wpa_ctrl_cleanup();
     if (connectToSupplicant()) {
-        LOGE("Error connecting to supplicant (%s)\n", strerror(errno));
+        ALOGE("Error connecting to supplicant (%s)\n", strerror(errno));
         return -1;
     }
     
     if (retrieveInterfaceName()) {
-        LOGE("Error retrieving interface name (%s)\n", strerror(errno));
+        ALOGE("Error retrieving interface name (%s)\n", strerror(errno));
         return -1;
     }
 
@@ -89,12 +89,12 @@
 int Supplicant::stop() {
 
     if (mListener->stopListener()) {
-        LOGW("Unable to stop supplicant listener (%s)", strerror(errno));
+        ALOGW("Unable to stop supplicant listener (%s)", strerror(errno));
         return -1;
     }
 
     if (mServiceManager->stop(SUPPLICANT_SERVICE_NAME)) {
-        LOGW("Error stopping supplicant (%s)", strerror(errno));
+        ALOGW("Error stopping supplicant (%s)", strerror(errno));
     }
 
     if (mCtrl) {
@@ -120,7 +120,7 @@
         return -1;
     }
 
-//    LOGD("sendCommand(): -> '%s'", cmd);
+//    ALOGD("sendCommand(): -> '%s'", cmd);
 
     int rc;
     memset(reply, 0, *reply_len);
@@ -133,7 +133,7 @@
         return -1;
     }
 
- //   LOGD("sendCommand(): <- '%s'", reply);
+ //   ALOGD("sendCommand(): <- '%s'", reply);
     return 0;
 }
 SupplicantStatus *Supplicant::getStatus() {
@@ -178,7 +178,7 @@
     char *linep_next = NULL;
 
     if (!strtok_r(reply, "\n", &linep_next)) {
-        LOGW("Malformatted network list\n");
+        ALOGW("Malformatted network list\n");
         free(reply);
         errno = EIO;
         return -1;
@@ -199,7 +199,7 @@
         if ((merge_wn = this->lookupNetwork_UNLOCKED(new_wn->getNetworkId()))) {
             num_refreshed++;
             if (merge_wn->refresh()) {
-                LOGW("Error refreshing network %d (%s)",
+                ALOGW("Error refreshing network %d (%s)",
                      merge_wn->getNetworkId(), strerror(errno));
                 }
             delete new_wn;
@@ -210,7 +210,7 @@
             new_wn->attachProperties(pm, new_ns);
             mNetworks->push_back(new_wn);
             if (new_wn->refresh()) {
-                LOGW("Unable to refresh network id %d (%s)",
+                ALOGW("Unable to refresh network id %d (%s)",
                     new_wn->getNetworkId(), strerror(errno));
             }
         }
@@ -233,7 +233,7 @@
     }
 
 
-    LOGD("Networks added %d, refreshed %d, removed %d\n", 
+    ALOGD("Networks added %d, refreshed %d, removed %d\n",
          num_added, num_refreshed, num_removed);
     pthread_mutex_unlock(&mNetworksLock);
 
@@ -243,11 +243,11 @@
 
 int Supplicant::connectToSupplicant() {
     if (!isStarted())
-        LOGW("Supplicant service not running");
+        ALOGW("Supplicant service not running");
 
     mCtrl = wpa_ctrl_open("tiwlan0"); // XXX:
     if (mCtrl == NULL) {
-        LOGE("Unable to open connection to supplicant on \"%s\": %s",
+        ALOGE("Unable to open connection to supplicant on \"%s\": %s",
              "tiwlan0", strerror(errno));
         return -1;
     }
@@ -267,7 +267,7 @@
     mListener = new SupplicantListener(mHandlers, mMonitor);
 
     if (mListener->startListener()) {
-        LOGE("Error - unable to start supplicant listener");
+        ALOGE("Error - unable to start supplicant listener");
         stop();
         return -1;
     }
@@ -280,7 +280,7 @@
 
     if (sendCommand((active ? "DRIVER SCAN-ACTIVE" : "DRIVER SCAN-PASSIVE"),
                      reply, &len)) {
-        LOGW("triggerScan(%d): Error setting scan mode (%s)", active,
+        ALOGW("triggerScan(%d): Error setting scan mode (%s)", active,
              strerror(errno));
         return -1;
     }
@@ -292,7 +292,7 @@
     size_t len = sizeof(reply);
 
     if (sendCommand("SCAN", reply, &len)) {
-        LOGW("triggerScan(): Error initiating scan");
+        ALOGW("triggerScan(): Error initiating scan");
         return -1;
     }
     return 0;
@@ -303,7 +303,7 @@
     size_t len = sizeof(reply);
 
     if (sendCommand("DRIVER RSSI", reply, &len)) {
-        LOGW("Failed to get RSSI (%s)", strerror(errno));
+        ALOGW("Failed to get RSSI (%s)", strerror(errno));
         return -1;
     }
 
@@ -311,7 +311,7 @@
     char *s;
     for (int i = 0; i < 3; i++) {
         if (!(s = strsep(&next, " "))) {
-            LOGE("Error parsing RSSI");
+            ALOGE("Error parsing RSSI");
             errno = EIO;
             return -1;
         }
@@ -325,7 +325,7 @@
     size_t len = sizeof(reply);
 
     if (sendCommand("DRIVER LINKSPEED", reply, &len)) {
-        LOGW("Failed to get LINKSPEED (%s)", strerror(errno));
+        ALOGW("Failed to get LINKSPEED (%s)", strerror(errno));
         return -1;
     }
 
@@ -333,13 +333,13 @@
     char *s;
 
     if (!(s = strsep(&next, " "))) {
-        LOGE("Error parsing LINKSPEED");
+        ALOGE("Error parsing LINKSPEED");
         errno = EIO;
         return -1;
     }
 
     if (!(s = strsep(&next, " "))) {
-        LOGE("Error parsing LINKSPEED");
+        ALOGE("Error parsing LINKSPEED");
         errno = EIO;
         return -1;
     }
@@ -350,10 +350,10 @@
     char reply[64];
     size_t len = sizeof(reply);
 
-    LOGD("stopDriver()");
+    ALOGD("stopDriver()");
 
     if (sendCommand("DRIVER STOP", reply, &len)) {
-        LOGW("Failed to stop driver (%s)", strerror(errno));
+        ALOGW("Failed to stop driver (%s)", strerror(errno));
         return -1;
     }
     return 0;
@@ -363,9 +363,9 @@
     char reply[64];
     size_t len = sizeof(reply);
 
-    LOGD("startDriver()");
+    ALOGD("startDriver()");
     if (sendCommand("DRIVER START", reply, &len)) {
-        LOGW("Failed to start driver (%s)", strerror(errno));
+        ALOGW("Failed to start driver (%s)", strerror(errno));
         return -1;
     }
     return 0;
@@ -452,26 +452,26 @@
     if (access(SUPP_CONFIG_FILE, R_OK|W_OK) == 0) {
         return 0;
     } else if (errno != ENOENT) {
-        LOGE("Cannot access \"%s\": %s", SUPP_CONFIG_FILE, strerror(errno));
+        ALOGE("Cannot access \"%s\": %s", SUPP_CONFIG_FILE, strerror(errno));
         return -1;
     }
 
     srcfd = open(SUPP_CONFIG_TEMPLATE, O_RDONLY);
     if (srcfd < 0) {
-        LOGE("Cannot open \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
+        ALOGE("Cannot open \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
         return -1;
     }
 
     destfd = open(SUPP_CONFIG_FILE, O_CREAT|O_WRONLY, 0660);
     if (destfd < 0) {
         close(srcfd);
-        LOGE("Cannot create \"%s\": %s", SUPP_CONFIG_FILE, strerror(errno));
+        ALOGE("Cannot create \"%s\": %s", SUPP_CONFIG_FILE, strerror(errno));
         return -1;
     }
 
     while ((nread = read(srcfd, buf, sizeof(buf))) != 0) {
         if (nread < 0) {
-            LOGE("Error reading \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
+            ALOGE("Error reading \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
             close(srcfd);
             close(destfd);
             unlink(SUPP_CONFIG_FILE);
@@ -484,7 +484,7 @@
     close(srcfd);
 
     if (chown(SUPP_CONFIG_FILE, AID_SYSTEM, AID_WIFI) < 0) {
-        LOGE("Error changing group ownership of %s to %d: %s",
+        ALOGE("Error changing group ownership of %s to %d: %s",
              SUPP_CONFIG_FILE, AID_WIFI, strerror(errno));
         unlink(SUPP_CONFIG_FILE);
         return -1;
@@ -496,7 +496,7 @@
     char reply[255];
     size_t len = sizeof(reply) -1;
 
-    LOGD("netid %d, var '%s' = '%s'", networkId, var, val);
+    ALOGD("netid %d, var '%s' = '%s'", networkId, var, val);
     char *tmp;
     asprintf(&tmp, "SET_NETWORK %d %s %s", networkId, var, val);
     if (sendCommand(tmp, reply, &len)) {
@@ -507,7 +507,7 @@
 
     len = sizeof(reply) -1;
     if (sendCommand("SAVE_CONFIG", reply, &len)) {
-        LOGE("Error saving config after %s = %s", var, val);
+        ALOGE("Error saving config after %s = %s", var, val);
         return -1;
     }
     return 0;
@@ -621,7 +621,7 @@
 int Supplicant::setApScanMode(int mode) {
     char req[64];
 
-//    LOGD("setApScanMode(%d)", mode);
+//    ALOGD("setApScanMode(%d)", mode);
     sprintf(req, "AP_SCAN %d", mode);
 
     char reply[16];
diff --git a/nexus/SupplicantAssociatingEvent.cpp b/nexus/SupplicantAssociatingEvent.cpp
index c6e9fe3..8fe502e 100644
--- a/nexus/SupplicantAssociatingEvent.cpp
+++ b/nexus/SupplicantAssociatingEvent.cpp
@@ -46,7 +46,7 @@
         //                           p
         char *q = index(p, '\'');
         if (!q) {
-            LOGE("Unable to decode SSID (p = {%s})\n", p);
+            ALOGE("Unable to decode SSID (p = {%s})\n", p);
             return;
         }
         mSsid = (char *) malloc((q - p) +1);
@@ -59,7 +59,7 @@
         //                                         ^
         //                                         p
         if (!(q = index(p, ' '))) {
-            LOGE("Unable to decode frequency\n");
+            ALOGE("Unable to decode frequency\n");
             return;
         }
         *q = '\0';
@@ -73,7 +73,7 @@
 
         char *q = index(p, '\'');
         if (!q) {
-            LOGE("Unable to decode SSID (p = {%s})\n", p);
+            ALOGE("Unable to decode SSID (p = {%s})\n", p);
             return;
         }
         mSsid = (char *) malloc((q - p) +1);
diff --git a/nexus/SupplicantConnectedEvent.cpp b/nexus/SupplicantConnectedEvent.cpp
index e58bab2..107c766 100644
--- a/nexus/SupplicantConnectedEvent.cpp
+++ b/nexus/SupplicantConnectedEvent.cpp
@@ -42,9 +42,9 @@
             else
                 mReassociated = true;
         } else
-            LOGE("Unable to decode re-assocation");
+            ALOGE("Unable to decode re-assocation");
     } else
-        LOGE("Unable to decode event");
+        ALOGE("Unable to decode event");
 }
 
 SupplicantConnectedEvent::SupplicantConnectedEvent(const char *bssid, 
diff --git a/nexus/SupplicantEventFactory.cpp b/nexus/SupplicantEventFactory.cpp
index 8695aca..f91db15 100644
--- a/nexus/SupplicantEventFactory.cpp
+++ b/nexus/SupplicantEventFactory.cpp
@@ -57,9 +57,9 @@
             level = atoi(tmp);
             event += (match - event) + 1;
         } else
-            LOGW("Unclosed level brace in event");
+            ALOGW("Unclosed level brace in event");
     } else
-        LOGW("No level specified in event");
+        ALOGW("No level specified in event");
 
     /*
      * <N>CTRL-EVENT-XXX
diff --git a/nexus/SupplicantListener.cpp b/nexus/SupplicantListener.cpp
index b91fc02..421d84d 100644
--- a/nexus/SupplicantListener.cpp
+++ b/nexus/SupplicantListener.cpp
@@ -48,13 +48,13 @@
     size_t nread = buflen - 1;
 
     if ((rc = wpa_ctrl_recv(mMonitor, buf, &nread))) {
-        LOGE("wpa_ctrl_recv failed (%s)", strerror(errno));
+        ALOGE("wpa_ctrl_recv failed (%s)", strerror(errno));
         return false;
     }
 
     buf[nread] = '\0';
     if (!rc && !nread) {
-        LOGD("Received EOF on supplicant socket\n");
+        ALOGD("Received EOF on supplicant socket\n");
         strncpy(buf, WPA_EVENT_TERMINATING " - signal 0 received", buflen-1);
         buf[buflen-1] = '\0';
         return false;
@@ -63,7 +63,7 @@
     SupplicantEvent *evt = mFactory->createEvent(buf, nread);
 
     if (!evt) {
-        LOGW("Dropping unknown supplicant event '%s'", buf);
+        ALOGW("Dropping unknown supplicant event '%s'", buf);
         return true;
     }
 
@@ -83,7 +83,7 @@
     else if (evt->getType() == SupplicantEvent::EVENT_DISCONNECTED)
         mHandlers->onDisconnectedEvent((SupplicantDisconnectedEvent *) evt);
     else
-        LOGW("Whoops - no handler available for event '%s'\n", buf);
+        ALOGW("Whoops - no handler available for event '%s'\n", buf);
 #if 0
     else if (evt->getType() == SupplicantEvent::EVENT_TERMINATING)
         mHandlers->onTerminatingEvent(evt);
diff --git a/nexus/SupplicantStateChangeEvent.cpp b/nexus/SupplicantStateChangeEvent.cpp
index cf0b9da..fd9233a 100644
--- a/nexus/SupplicantStateChangeEvent.cpp
+++ b/nexus/SupplicantStateChangeEvent.cpp
@@ -28,7 +28,7 @@
     // XXX: move this stuff into a static creation method
     char *p = index(event, ' ');
     if (!p) {
-        LOGW("Bad event '%s'\n", event);
+        ALOGW("Bad event '%s'\n", event);
         return;
     }
 
diff --git a/nexus/SupplicantStatus.cpp b/nexus/SupplicantStatus.cpp
index b3c560a..8f28abe 100644
--- a/nexus/SupplicantStatus.cpp
+++ b/nexus/SupplicantStatus.cpp
@@ -81,9 +81,9 @@
             else if (!strcmp(value, "IDLE"))
                 state = SupplicantState::IDLE;
             else 
-                LOGE("Unknown supplicant state '%s'", value);
+                ALOGE("Unknown supplicant state '%s'", value);
         } else
-            LOGD("Ignoring unsupported status token '%s'", token);
+            ALOGD("Ignoring unsupported status token '%s'", token);
     }
 
     return new SupplicantStatus(state, id, bssid, ssid);
diff --git a/nexus/TiwlanEventListener.cpp b/nexus/TiwlanEventListener.cpp
index 15e6930..fde3a44 100644
--- a/nexus/TiwlanEventListener.cpp
+++ b/nexus/TiwlanEventListener.cpp
@@ -33,25 +33,25 @@
     struct ipc_ev_data *data;
 
     if (!(data = (struct ipc_ev_data *) malloc(sizeof(struct ipc_ev_data)))) {
-        LOGE("Failed to allocate packet (out of memory)");
+        ALOGE("Failed to allocate packet (out of memory)");
         return true;
     }
 
     if (recv(cli->getSocket(), data, sizeof(struct ipc_ev_data), 0) < 0) {
-       LOGE("recv failed (%s)", strerror(errno));
+       ALOGE("recv failed (%s)", strerror(errno));
        goto out;
     }
 
     if (data->event_type == IPC_EVENT_LINK_SPEED) {
         uint32_t *spd = (uint32_t *) data->buffer;
         *spd /= 2;
-//        LOGD("Link speed = %u MB/s", *spd);
+//        ALOGD("Link speed = %u MB/s", *spd);
     } else if (data->event_type == IPC_EVENT_LOW_SNR) {
-        LOGW("Low signal/noise ratio");
+        ALOGW("Low signal/noise ratio");
     } else if (data->event_type == IPC_EVENT_LOW_RSSI) {
-        LOGW("Low RSSI");
+        ALOGW("Low RSSI");
     } else {
-//        LOGD("Dropping unhandled driver event %d", data->event_type);
+//        ALOGD("Dropping unhandled driver event %d", data->event_type);
     }
 
     // TODO: Tell WifiController about the event
diff --git a/nexus/TiwlanWifiController.cpp b/nexus/TiwlanWifiController.cpp
index 016c790..76b6a2e 100644
--- a/nexus/TiwlanWifiController.cpp
+++ b/nexus/TiwlanWifiController.cpp
@@ -75,23 +75,23 @@
     while (count-- > 0) {
         if (property_get(DRIVER_PROP_NAME, driver_status, NULL)) {
             if (!strcmp(driver_status, "ok")) {
-                LOGD("Firmware loaded OK");
+                ALOGD("Firmware loaded OK");
 
                 if (startDriverEventListener()) {
-                    LOGW("Failed to start driver event listener (%s)",
+                    ALOGW("Failed to start driver event listener (%s)",
                          strerror(errno));
                 }
 
                 return 0;
             } else if (!strcmp(DRIVER_PROP_NAME, "failed")) {
-                LOGE("Firmware load failed");
+                ALOGE("Firmware load failed");
                 return -1;
             }
         }
         usleep(200000);
     }
     property_set(DRIVER_PROP_NAME, "timeout");
-    LOGE("Firmware load timed out");
+    ALOGE("Firmware load timed out");
     return -1;
 }
 
@@ -99,13 +99,13 @@
     struct sockaddr_in addr;
 
     if (mListenerSock != -1) {
-        LOGE("Listener already started!");
+        ALOGE("Listener already started!");
         errno = EBUSY;
         return -1;
     }
 
     if ((mListenerSock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
-        LOGE("socket failed (%s)", strerror(errno));
+        ALOGE("socket failed (%s)", strerror(errno));
         return -1;
     }
 
@@ -117,14 +117,14 @@
     if (bind(mListenerSock,
              (struct sockaddr *) &addr,
              sizeof(addr)) < 0) {
-        LOGE("bind failed (%s)", strerror(errno));
+        ALOGE("bind failed (%s)", strerror(errno));
         goto out_err;
     }
 
     mEventListener = new TiwlanEventListener(mListenerSock);
 
     if (mEventListener->startListener()) {
-        LOGE("Error starting driver listener (%s)", strerror(errno));
+        ALOGE("Error starting driver listener (%s)", strerror(errno));
         goto out_err;
     }
     return 0;
diff --git a/nexus/WifiController.cpp b/nexus/WifiController.cpp
index c218c30..cedd013 100644
--- a/nexus/WifiController.cpp
+++ b/nexus/WifiController.cpp
@@ -108,50 +108,50 @@
 int WifiController::enable() {
 
     if (!isPoweredUp()) {
-        LOGI("Powering up");
+        ALOGI("Powering up");
         sendStatusBroadcast("Powering up WiFi hardware");
         if (powerUp()) {
-            LOGE("Powerup failed (%s)", strerror(errno));
+            ALOGE("Powerup failed (%s)", strerror(errno));
             return -1;
         }
     }
 
     if (mModuleName[0] != '\0' && !isKernelModuleLoaded(mModuleName)) {
-        LOGI("Loading driver");
+        ALOGI("Loading driver");
         sendStatusBroadcast("Loading WiFi driver");
         if (loadKernelModule(mModulePath, mModuleArgs)) {
-            LOGE("Kernel module load failed (%s)", strerror(errno));
+            ALOGE("Kernel module load failed (%s)", strerror(errno));
             goto out_powerdown;
         }
     }
 
     if (!isFirmwareLoaded()) {
-        LOGI("Loading firmware");
+        ALOGI("Loading firmware");
         sendStatusBroadcast("Loading WiFI firmware");
         if (loadFirmware()) {
-            LOGE("Firmware load failed (%s)", strerror(errno));
+            ALOGE("Firmware load failed (%s)", strerror(errno));
             goto out_powerdown;
         }
     }
 
     if (!mSupplicant->isStarted()) {
-        LOGI("Starting WPA Supplicant");
+        ALOGI("Starting WPA Supplicant");
         sendStatusBroadcast("Starting WPA Supplicant");
         if (mSupplicant->start()) {
-            LOGE("Supplicant start failed (%s)", strerror(errno));
+            ALOGE("Supplicant start failed (%s)", strerror(errno));
             goto out_unloadmodule;
         }
     }
 
     if (Controller::bindInterface(mSupplicant->getInterfaceName())) {
-        LOGE("Error binding interface (%s)", strerror(errno));
+        ALOGE("Error binding interface (%s)", strerror(errno));
         goto out_unloadmodule;
     }
 
     if (mSupplicant->refreshNetworkList())
-        LOGW("Error getting list of networks (%s)", strerror(errno));
+        ALOGW("Error getting list of networks (%s)", strerror(errno));
 
-    LOGW("TODO: Set # of allowed regulatory channels!");
+    ALOGW("TODO: Set # of allowed regulatory channels!");
 
     mPropMngr->attachProperty("wifi", mDynamicProperties.propSupplicantState);
     mPropMngr->attachProperty("wifi", mDynamicProperties.propActiveScan);
@@ -167,19 +167,19 @@
     mPropMngr->attachProperty("wifi", mDynamicProperties.propNetCount);
     mPropMngr->attachProperty("wifi", mDynamicProperties.propTriggerScan);
 
-    LOGI("Enabled successfully");
+    ALOGI("Enabled successfully");
     return 0;
 
 out_unloadmodule:
     if (mModuleName[0] != '\0' && !isKernelModuleLoaded(mModuleName)) {
         if (unloadKernelModule(mModuleName)) {
-            LOGE("Unable to unload module after failure!");
+            ALOGE("Unable to unload module after failure!");
         }
     }
 
 out_powerdown:
     if (powerDown()) {
-        LOGE("Unable to powerdown after failure!");
+        ALOGE("Unable to powerdown after failure!");
     }
     return -1;
 }
@@ -195,7 +195,7 @@
 
     pthread_mutex_lock(&mLock);
     if (suspend == mSuspended) {
-        LOGW("Suspended state already = %d", suspend);
+        ALOGW("Suspended state already = %d", suspend);
         pthread_mutex_unlock(&mLock);
         return 0;
     }
@@ -204,29 +204,29 @@
         mHandlers->onControllerSuspending(this);
 
         char tmp[80];
-        LOGD("Suspending from supplicant state %s",
+        ALOGD("Suspending from supplicant state %s",
              SupplicantState::toString(mSupplicantState,
                                        tmp,
                                        sizeof(tmp)));
 
         if (mSupplicantState != SupplicantState::IDLE) {
-            LOGD("Forcing Supplicant disconnect");
+            ALOGD("Forcing Supplicant disconnect");
             if (mSupplicant->disconnect()) {
-                LOGW("Error disconnecting (%s)", strerror(errno));
+                ALOGW("Error disconnecting (%s)", strerror(errno));
             }
         }
 
-        LOGD("Stopping Supplicant driver");
+        ALOGD("Stopping Supplicant driver");
         if (mSupplicant->stopDriver()) {
-            LOGE("Error stopping driver (%s)", strerror(errno));
+            ALOGE("Error stopping driver (%s)", strerror(errno));
             pthread_mutex_unlock(&mLock);
             return -1;
         }
     } else {
-        LOGD("Resuming");
+        ALOGD("Resuming");
 
         if (mSupplicant->startDriver()) {
-            LOGE("Error resuming driver (%s)", strerror(errno));
+            ALOGE("Error resuming driver (%s)", strerror(errno));
             pthread_mutex_unlock(&mLock);
             return -1;
         }
@@ -241,7 +241,7 @@
 
     mSuspended = suspend;
     pthread_mutex_unlock(&mLock);
-    LOGD("Suspend / Resume completed");
+    ALOGD("Suspend / Resume completed");
     return 0;
 }
 
@@ -269,16 +269,16 @@
     if (mSupplicant->isStarted()) {
         sendStatusBroadcast("Stopping WPA Supplicant");
         if (mSupplicant->stop()) {
-            LOGE("Supplicant stop failed (%s)", strerror(errno));
+            ALOGE("Supplicant stop failed (%s)", strerror(errno));
             return -1;
         }
     } else
-        LOGW("disable(): Supplicant not running?");
+        ALOGW("disable(): Supplicant not running?");
 
     if (mModuleName[0] != '\0' && isKernelModuleLoaded(mModuleName)) {
         sendStatusBroadcast("Unloading WiFi driver");
         if (unloadKernelModule(mModuleName)) {
-            LOGE("Unable to unload module (%s)", strerror(errno));
+            ALOGE("Unable to unload module (%s)", strerror(errno));
             return -1;
         }
     }
@@ -286,7 +286,7 @@
     if (isPoweredUp()) {
         sendStatusBroadcast("Powering down WiFi hardware");
         if (powerDown()) {
-            LOGE("Powerdown failed (%s)", strerror(errno));
+            ALOGE("Powerdown failed (%s)", strerror(errno));
             return -1;
         }
     }
@@ -426,38 +426,38 @@
 }
 
 void WifiController::onAssociatingEvent(SupplicantAssociatingEvent *evt) {
-    LOGD("onAssociatingEvent(%s, %s, %d)",
+    ALOGD("onAssociatingEvent(%s, %s, %d)",
          (evt->getBssid() ? evt->getBssid() : "n/a"),
          (evt->getSsid() ? evt->getSsid() : "n/a"),
          evt->getFreq());
 }
 
 void WifiController::onAssociatedEvent(SupplicantAssociatedEvent *evt) {
-    LOGD("onAssociatedEvent(%s)", evt->getBssid());
+    ALOGD("onAssociatedEvent(%s)", evt->getBssid());
 }
 
 void WifiController::onConnectedEvent(SupplicantConnectedEvent *evt) {
-    LOGD("onConnectedEvent(%s, %d)", evt->getBssid(), evt->getReassociated());
+    ALOGD("onConnectedEvent(%s, %d)", evt->getBssid(), evt->getReassociated());
     SupplicantStatus *ss = mSupplicant->getStatus();
     WifiNetwork *wn;
 
     if (ss->getWpaState() != SupplicantState::COMPLETED) {
         char tmp[32];
 
-        LOGW("onConnected() with SupplicantState = %s!",
+        ALOGW("onConnected() with SupplicantState = %s!",
              SupplicantState::toString(ss->getWpaState(), tmp,
              sizeof(tmp)));
         return;
     }
 
     if (ss->getId() == -1) {
-        LOGW("onConnected() with id = -1!");
+        ALOGW("onConnected() with id = -1!");
         return;
     }
     
     mCurrentlyConnectedNetworkId = ss->getId();
     if (!(wn = mSupplicant->lookupNetwork(ss->getId()))) {
-        LOGW("Error looking up connected network id %d (%s)",
+        ALOGW("Error looking up connected network id %d (%s)",
              ss->getId(), strerror(errno));
         return;
     }
@@ -470,7 +470,7 @@
     char *reply;
 
     if (!(reply = (char *) malloc(4096))) {
-        LOGE("Out of memory");
+        ALOGE("Out of memory");
         return;
     }
 
@@ -481,7 +481,7 @@
     size_t len = 4096;
 
     if (mSupplicant->sendCommand("SCAN_RESULTS", reply, &len)) {
-        LOGW("onScanResultsEvent: Error getting scan results (%s)",
+        ALOGW("onScanResultsEvent: Error getting scan results (%s)",
              strerror(errno));
         free(reply);
         return;
@@ -530,7 +530,7 @@
     if (evt->getState() == mSupplicantState)
         return;
 
-    LOGD("onStateChangeEvent(%s -> %s)", 
+    ALOGD("onStateChangeEvent(%s -> %s)",
          SupplicantState::toString(mSupplicantState, tmp, sizeof(tmp)),
          SupplicantState::toString(evt->getState(), tmp2, sizeof(tmp2)));
 
@@ -559,7 +559,7 @@
 }
 
 void WifiController::onConnectionTimeoutEvent(SupplicantConnectionTimeoutEvent *evt) {
-    LOGD("onConnectionTimeoutEvent(%s)", evt->getBssid());
+    ALOGD("onConnectionTimeoutEvent(%s)", evt->getBssid());
 }
 
 void WifiController::onDisconnectedEvent(SupplicantDisconnectedEvent *evt) {
@@ -569,39 +569,39 @@
 
 #if 0
 void WifiController::onTerminatingEvent(SupplicantEvent *evt) {
-    LOGD("onTerminatingEvent(%s)", evt->getEvent());
+    ALOGD("onTerminatingEvent(%s)", evt->getEvent());
 }
 
 void WifiController::onPasswordChangedEvent(SupplicantEvent *evt) {
-    LOGD("onPasswordChangedEvent(%s)", evt->getEvent());
+    ALOGD("onPasswordChangedEvent(%s)", evt->getEvent());
 }
 
 void WifiController::onEapNotificationEvent(SupplicantEvent *evt) {
-    LOGD("onEapNotificationEvent(%s)", evt->getEvent());
+    ALOGD("onEapNotificationEvent(%s)", evt->getEvent());
 }
 
 void WifiController::onEapStartedEvent(SupplicantEvent *evt) {
-    LOGD("onEapStartedEvent(%s)", evt->getEvent());
+    ALOGD("onEapStartedEvent(%s)", evt->getEvent());
 }
 
 void WifiController::onEapMethodEvent(SupplicantEvent *evt) {
-    LOGD("onEapMethodEvent(%s)", evt->getEvent());
+    ALOGD("onEapMethodEvent(%s)", evt->getEvent());
 }
 
 void WifiController::onEapSuccessEvent(SupplicantEvent *evt) {
-    LOGD("onEapSuccessEvent(%s)", evt->getEvent());
+    ALOGD("onEapSuccessEvent(%s)", evt->getEvent());
 }
 
 void WifiController::onEapFailureEvent(SupplicantEvent *evt) {
-    LOGD("onEapFailureEvent(%s)", evt->getEvent());
+    ALOGD("onEapFailureEvent(%s)", evt->getEvent());
 }
 
 void WifiController::onLinkSpeedEvent(SupplicantEvent *evt) {
-    LOGD("onLinkSpeedEvent(%s)", evt->getEvent());
+    ALOGD("onLinkSpeedEvent(%s)", evt->getEvent());
 }
 
 void WifiController::onDriverStateEvent(SupplicantEvent *evt) {
-    LOGD("onDriverStateEvent(%s)", evt->getEvent());
+    ALOGD("onDriverStateEvent(%s)", evt->getEvent());
 }
 #endif
 
@@ -609,7 +609,7 @@
     pthread_mutex_lock(&mLock);
     int rssi;
     if (mSupplicant->getRssi(&rssi)) {
-        LOGE("Failed to get rssi (%s)", strerror(errno));
+        ALOGE("Failed to get rssi (%s)", strerror(errno));
         pthread_mutex_unlock(&mLock);
         return;
     }
diff --git a/nexus/WifiNetwork.cpp b/nexus/WifiNetwork.cpp
index 6a0f684..0197b64 100644
--- a/nexus/WifiNetwork.cpp
+++ b/nexus/WifiNetwork.cpp
@@ -43,15 +43,15 @@
     char *flags;
 
     if (!(id = strsep(&next, "\t")))
-        LOGE("Failed to extract network id");
+        ALOGE("Failed to extract network id");
     if (!(ssid = strsep(&next, "\t")))
-        LOGE("Failed to extract ssid");
+        ALOGE("Failed to extract ssid");
     if (!(bssid = strsep(&next, "\t")))
-        LOGE("Failed to extract bssid");
+        ALOGE("Failed to extract bssid");
     if (!(flags = strsep(&next, "\t")))
-        LOGE("Failed to extract flags");
+        ALOGE("Failed to extract flags");
 
-   // LOGD("id '%s', ssid '%s', bssid '%s', flags '%s'", id, ssid, bssid,
+   // ALOGD("id '%s', ssid '%s', bssid '%s', flags '%s'", id, ssid, bssid,
    //      flags ? flags :"null");
 
     if (id)
@@ -77,7 +77,7 @@
         if (!strcmp(flags, "[DISABLED]"))
             mEnabled = false;
         else
-            LOGW("Unsupported flags '%s'", flags);
+            ALOGW("Unsupported flags '%s'", flags);
     }
 
     free(tmp);
@@ -215,7 +215,7 @@
     len = sizeof(buffer);
     if (mSuppl->getNetworkVar(mNetid, "key_mgmt", buffer, len)) {
         if (WifiNetwork::parseKeyManagementMask(buffer, &mask)) {
-            LOGE("Error parsing key_mgmt (%s)", strerror(errno));
+            ALOGE("Error parsing key_mgmt (%s)", strerror(errno));
         } else {
            mKeyManagement = mask;
         }
@@ -224,7 +224,7 @@
     len = sizeof(buffer);
     if (mSuppl->getNetworkVar(mNetid, "proto", buffer, len)) {
         if (WifiNetwork::parseProtocolsMask(buffer, &mask)) {
-            LOGE("Error parsing proto (%s)", strerror(errno));
+            ALOGE("Error parsing proto (%s)", strerror(errno));
         } else {
            mProtocols = mask;
         }
@@ -233,7 +233,7 @@
     len = sizeof(buffer);
     if (mSuppl->getNetworkVar(mNetid, "auth_alg", buffer, len)) {
         if (WifiNetwork::parseAuthAlgorithmsMask(buffer, &mask)) {
-            LOGE("Error parsing auth_alg (%s)", strerror(errno));
+            ALOGE("Error parsing auth_alg (%s)", strerror(errno));
         } else {
            mAuthAlgorithms = mask;
         }
@@ -242,7 +242,7 @@
     len = sizeof(buffer);
     if (mSuppl->getNetworkVar(mNetid, "pairwise", buffer, len)) {
         if (WifiNetwork::parsePairwiseCiphersMask(buffer, &mask)) {
-            LOGE("Error parsing pairwise (%s)", strerror(errno));
+            ALOGE("Error parsing pairwise (%s)", strerror(errno));
         } else {
            mPairwiseCiphers = mask;
         }
@@ -251,7 +251,7 @@
     len = sizeof(buffer);
     if (mSuppl->getNetworkVar(mNetid, "group", buffer, len)) {
         if (WifiNetwork::parseGroupCiphersMask(buffer, &mask)) {
-            LOGE("Error parsing group (%s)", strerror(errno));
+            ALOGE("Error parsing group (%s)", strerror(errno));
         } else {
            mGroupCiphers = mask;
         }
@@ -259,7 +259,7 @@
 
     return 0;
 out_err:
-    LOGE("Refresh failed (%s)",strerror(errno));
+    ALOGE("Refresh failed (%s)",strerror(errno));
     return -1;
 }
 
@@ -453,12 +453,12 @@
 
     if (enabled) {
         if (getPriority() == -1) {
-            LOGE("Cannot enable network when priority is not set");
+            ALOGE("Cannot enable network when priority is not set");
             errno = EAGAIN;
             return -1;
         }
         if (getKeyManagement() == KeyManagementMask::UNKNOWN) {
-            LOGE("Cannot enable network when KeyManagement is not set");
+            ALOGE("Cannot enable network when KeyManagement is not set");
             errno = EAGAIN;
             return -1;
         }
@@ -511,7 +511,7 @@
     char *v_next = v_tmp;
     char *v_token;
 
-//    LOGD("parseKeyManagementMask(%s)", buffer);
+//    ALOGD("parseKeyManagementMask(%s)", buffer);
     *mask = 0;
 
     while((v_token = strsep(&v_next, " "))) {
@@ -526,13 +526,13 @@
             else if (!strcasecmp(v_token, "IEEE8021X"))
                 *mask |= KeyManagementMask::IEEE8021X;
             else {
-                LOGW("Invalid KeyManagementMask value '%s'", v_token);
+                ALOGW("Invalid KeyManagementMask value '%s'", v_token);
                 errno = EINVAL;
                 free(v_tmp);
                 return -1;
             }
         } else {
-            LOGW("KeyManagementMask value '%s' when NONE", v_token);
+            ALOGW("KeyManagementMask value '%s' when NONE", v_token);
             errno = EINVAL;
             free(v_tmp);
             return -1;
@@ -548,7 +548,7 @@
     char *v_next = v_tmp;
     char *v_token;
 
-//    LOGD("parseProtocolsMask(%s)", buffer);
+//    ALOGD("parseProtocolsMask(%s)", buffer);
     *mask = 0;
     while((v_token = strsep(&v_next, " "))) {
         if (!strcasecmp(v_token, "WPA"))
@@ -556,7 +556,7 @@
         else if (!strcasecmp(v_token, "RSN"))
             *mask |= SecurityProtocolMask::RSN;
         else {
-            LOGW("Invalid ProtocolsMask value '%s'", v_token);
+            ALOGW("Invalid ProtocolsMask value '%s'", v_token);
             errno = EINVAL;
             free(v_tmp);
             return -1;
@@ -573,7 +573,7 @@
     char *v_next = v_tmp;
     char *v_token;
 
-//    LOGD("parseAuthAlgorithmsMask(%s)", buffer);
+//    ALOGD("parseAuthAlgorithmsMask(%s)", buffer);
 
     *mask = 0;
     if (buffer[0] == '\0')
@@ -587,7 +587,7 @@
         else if (!strcasecmp(v_token, "LEAP"))
             *mask |= AuthenticationAlgorithmMask::LEAP;
         else {
-            LOGW("Invalid AuthAlgorithmsMask value '%s'", v_token);
+            ALOGW("Invalid AuthAlgorithmsMask value '%s'", v_token);
             errno = EINVAL;
             free(v_tmp);
             return -1;
@@ -603,7 +603,7 @@
     char *v_next = v_tmp;
     char *v_token;
 
-//    LOGD("parsePairwiseCiphersMask(%s)", buffer);
+//    ALOGD("parsePairwiseCiphersMask(%s)", buffer);
 
     *mask = 0;
     while((v_token = strsep(&v_next, " "))) {
@@ -616,13 +616,13 @@
             else if (!strcasecmp(v_token, "CCMP"))
                 *mask |= PairwiseCiphersMask::CCMP;
         else {
-                LOGW("PairwiseCiphersMask value '%s' when NONE", v_token);
+                ALOGW("PairwiseCiphersMask value '%s' when NONE", v_token);
                 errno = EINVAL;
                 free(v_tmp);
                 return -1;
             }
         } else {
-            LOGW("Invalid PairwiseCiphersMask value '%s'", v_token);
+            ALOGW("Invalid PairwiseCiphersMask value '%s'", v_token);
             errno = EINVAL;
             free(v_tmp);
             return -1;
@@ -638,7 +638,7 @@
     char *v_next = v_tmp;
     char *v_token;
 
-//    LOGD("parseGroupCiphersMask(%s)", buffer);
+//    ALOGD("parseGroupCiphersMask(%s)", buffer);
 
     *mask = 0;
     while((v_token = strsep(&v_next, " "))) {
@@ -651,7 +651,7 @@
         else if (!strcasecmp(v_token, "CCMP"))
             *mask |= GroupCiphersMask::CCMP;
         else {
-            LOGW("Invalid GroupCiphersMask value '%s'", v_token);
+            ALOGW("Invalid GroupCiphersMask value '%s'", v_token);
             errno = EINVAL;
             free(v_tmp);
             return -1;
diff --git a/nexus/WifiScanner.cpp b/nexus/WifiScanner.cpp
index bdfa497..4c956ac 100644
--- a/nexus/WifiScanner.cpp
+++ b/nexus/WifiScanner.cpp
@@ -58,13 +58,13 @@
     char c = 0;
 
     if (write(mCtrlPipe[1], &c, 1) != 1) {
-        LOGE("Error writing to control pipe (%s)", strerror(errno));
+        ALOGE("Error writing to control pipe (%s)", strerror(errno));
         return -1;
     }
 
     void *ret;
     if (pthread_join(mThread, &ret)) {
-        LOGE("Error joining to scanner thread (%s)", strerror(errno));
+        ALOGE("Error joining to scanner thread (%s)", strerror(errno));
         return -1;
     }
 
@@ -74,7 +74,7 @@
 }
 
 void WifiScanner::run() {
-    LOGD("Starting wifi scanner (active = %d)", mActive);
+    ALOGD("Starting wifi scanner (active = %d)", mActive);
 
     while(1) {
         fd_set read_fds;
@@ -88,16 +88,16 @@
         FD_SET(mCtrlPipe[0], &read_fds);
 
         if (mSuppl->triggerScan(mActive)) {
-            LOGW("Error triggering scan (%s)", strerror(errno));
+            ALOGW("Error triggering scan (%s)", strerror(errno));
         }
 
         if ((rc = select(mCtrlPipe[0] + 1, &read_fds, NULL, NULL, &to)) < 0) {
-            LOGE("select failed (%s) - sleeping for one scanner period", strerror(errno));
+            ALOGE("select failed (%s) - sleeping for one scanner period", strerror(errno));
             sleep(mPeriod);
             continue;
         } else if (!rc) {
         } else if (FD_ISSET(mCtrlPipe[0], &read_fds))
             break;
     } // while
-    LOGD("Stopping wifi scanner");
+    ALOGD("Stopping wifi scanner");
 }
diff --git a/nexus/WifiStatusPoller.cpp b/nexus/WifiStatusPoller.cpp
index cf71733..015af5d 100644
--- a/nexus/WifiStatusPoller.cpp
+++ b/nexus/WifiStatusPoller.cpp
@@ -50,13 +50,13 @@
     char c = 0;
 
     if (write(mCtrlPipe[1], &c, 1) != 1) {
-        LOGE("Error writing to control pipe (%s)", strerror(errno));
+        ALOGE("Error writing to control pipe (%s)", strerror(errno));
         return -1;
     }
 
     void *ret;
     if (pthread_join(mThread, &ret)) {
-        LOGE("Error joining to listener thread (%s)", strerror(errno));
+        ALOGE("Error joining to listener thread (%s)", strerror(errno));
         return -1;
     }
     close(mCtrlPipe[0]);
@@ -68,10 +68,10 @@
     WifiStatusPoller *me = reinterpret_cast<WifiStatusPoller *>(obj);
 
     me->mStarted = true;
-    LOGD("Starting");
+    ALOGD("Starting");
     me->run();
     me->mStarted = false;
-    LOGD("Stopping");
+    ALOGD("Stopping");
     pthread_exit(NULL);
     return NULL;
 }
@@ -92,7 +92,7 @@
         max = mCtrlPipe[0];
 
         if ((rc = select(max + 1, &read_fds, NULL, NULL, &to)) < 0) {
-            LOGE("select failed (%s)", strerror(errno));
+            ALOGE("select failed (%s)", strerror(errno));
             sleep(1);
             continue;
         } else if (!rc) {
diff --git a/nexus/main.cpp b/nexus/main.cpp
index 936d33f..7d2af02 100644
--- a/nexus/main.cpp
+++ b/nexus/main.cpp
@@ -28,13 +28,13 @@
 #include "TiwlanWifiController.h"
 
 int main() {
-    LOGI("Nexus version 0.1 firing up");
+    ALOGI("Nexus version 0.1 firing up");
 
     CommandListener *cl = new CommandListener();
 
     NetworkManager *nm;
     if (!(nm = NetworkManager::Instance())) {
-        LOGE("Unable to create NetworkManager");
+        ALOGE("Unable to create NetworkManager");
         exit (-1);
     };
 
@@ -47,12 +47,12 @@
 
 
     if (NetworkManager::Instance()->run()) {
-        LOGE("Unable to Run NetworkManager (%s)", strerror(errno));
+        ALOGE("Unable to Run NetworkManager (%s)", strerror(errno));
         exit (1);
     }
 
     if (cl->startListener()) {
-        LOGE("Unable to start CommandListener (%s)", strerror(errno));
+        ALOGE("Unable to start CommandListener (%s)", strerror(errno));
         exit (1);
     }
 
@@ -62,6 +62,6 @@
         sleep(1000);
     }
 
-    LOGI("Nexus exiting");
+    ALOGI("Nexus exiting");
     exit(0);
 }
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 145f642..21f54d3 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -1,3 +1,5 @@
+import /init.${ro.hardware}.rc
+
 on early-init
     # Set init and its forked children's oom_adj.
     write /proc/1/oom_adj -16
@@ -68,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
@@ -298,7 +303,7 @@
     stop adbd
     write /sys/class/android_usb/android0/enable 0
     write /sys/class/android_usb/android0/bDeviceClass 0
-    setprop sys.usb.state $sys.usb.config
+    setprop sys.usb.state ${sys.usb.config}
 
 # adb only USB configuration
 # This should only be used during device bringup
@@ -307,34 +312,34 @@
     write /sys/class/android_usb/android0/enable 0
     write /sys/class/android_usb/android0/idVendor 18d1
     write /sys/class/android_usb/android0/idProduct D002
-    write /sys/class/android_usb/android0/functions $sys.usb.config
+    write /sys/class/android_usb/android0/functions ${sys.usb.config}
     write /sys/class/android_usb/android0/enable 1
     start adbd
-    setprop sys.usb.state $sys.usb.config
+    setprop sys.usb.state ${sys.usb.config}
 
 # USB accessory configuration
 on property:sys.usb.config=accessory
     write /sys/class/android_usb/android0/enable 0
     write /sys/class/android_usb/android0/idVendor 18d1
     write /sys/class/android_usb/android0/idProduct 2d00
-    write /sys/class/android_usb/android0/functions $sys.usb.config
+    write /sys/class/android_usb/android0/functions ${sys.usb.config}
     write /sys/class/android_usb/android0/enable 1
-    setprop sys.usb.state $sys.usb.config
+    setprop sys.usb.state ${sys.usb.config}
 
 # USB accessory configuration, with adb
 on property:sys.usb.config=accessory,adb
     write /sys/class/android_usb/android0/enable 0
     write /sys/class/android_usb/android0/idVendor 18d1
     write /sys/class/android_usb/android0/idProduct 2d01
-    write /sys/class/android_usb/android0/functions $sys.usb.config
+    write /sys/class/android_usb/android0/functions ${sys.usb.config}
     write /sys/class/android_usb/android0/enable 1
     start adbd
-    setprop sys.usb.state $sys.usb.config
+    setprop sys.usb.state ${sys.usb.config}
 
 # Used to set USB configuration at boot and to switch the configuration
 # when changing the default configuration
 on property:persist.sys.usb.config=*
-    setprop sys.usb.config $persist.sys.usb.config
+    setprop sys.usb.config ${persist.sys.usb.config}
 
 ## Daemon processes to be run by init.
 ##
diff --git a/run-as/package.c b/run-as/package.c
index ca08436..8f11646 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,63 @@
     *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 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 +392,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 +476,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 +485,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/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/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);