am 866b1bd5: fastboot: Make the format of "devices -l" match adb\'s

* commit '866b1bd5051db4f22b634df1f8a06bc1c9aa2e26':
  fastboot: Make the format of "devices -l" match adb's
diff --git a/adb/Android.mk b/adb/Android.mk
index 7744d2b..1a25106 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -95,16 +95,6 @@
 # adbd device daemon
 # =========================================================
 
-BUILD_ADBD := true
-
-# build adbd for the Linux simulator build
-# so we can use it to test the adb USB gadget driver on x86
-#ifeq ($(HOST_OS),linux)
-#    BUILD_ADBD := true
-#endif
-
-
-ifeq ($(BUILD_ADBD),true)
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := \
@@ -127,10 +117,8 @@
 LOCAL_CFLAGS := -O2 -g -DADB_HOST=0 -Wall -Wno-unused-parameter
 LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE
 
-# TODO: This should probably be board specific, whether or not the kernel has
-# the gadget driver; rather than relying on the architecture type.
-ifeq ($(TARGET_ARCH),arm)
-LOCAL_CFLAGS += -DANDROID_GADGET=1
+ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
+LOCAL_CFLAGS += -DALLOW_ADBD_ROOT=1
 endif
 
 LOCAL_MODULE := adbd
@@ -142,8 +130,6 @@
 LOCAL_STATIC_LIBRARIES := libcutils libc
 include $(BUILD_EXECUTABLE)
 
-endif
-
 
 # adb host tool for device-as-host
 # =========================================================
diff --git a/adb/adb.c b/adb/adb.c
index ed8d230..9cb67ab 100644
--- a/adb/adb.c
+++ b/adb/adb.c
@@ -136,6 +136,58 @@
     }
 }
 
+#if !ADB_HOST
+/*
+ * Implements ADB tracing inside the emulator.
+ */
+
+#include <stdarg.h>
+
+/*
+ * 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 handle to adb-debug qemud service in the emulator. */
+int   adb_debug_qemu = -1;
+
+/* Initializes connection with the adb-debug qemud service in the emulator. */
+static int adb_qemu_trace_init(void)
+{
+    char con_name[32];
+
+    if (adb_debug_qemu >= 0) {
+        return 0;
+    }
+
+    /* adb debugging QEMUD service connection request. */
+    snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
+    adb_debug_qemu = qemu_pipe_open(con_name);
+    return (adb_debug_qemu >= 0) ? 0 : -1;
+}
+
+void adb_qemu_trace(const char* fmt, ...)
+{
+    va_list args;
+    va_start(args, fmt);
+    char msg[1024];
+
+    if (adb_debug_qemu >= 0) {
+        vsnprintf(msg, sizeof(msg), fmt, args);
+        adb_write(adb_debug_qemu, msg, strlen(msg));
+    }
+}
+#endif  /* !ADB_HOST */
 
 apacket *get_apacket(void)
 {
@@ -360,6 +412,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;
 }
 
@@ -896,12 +955,47 @@
   snprintf(target_str, target_size, "tcp:%d", server_port);
 }
 
+#if !ADB_HOST
+static int should_drop_privileges() {
+#ifndef ALLOW_ADBD_ROOT
+    return 1;
+#else /* ALLOW_ADBD_ROOT */
+    int secure = 0;
+    char value[PROPERTY_VALUE_MAX];
+
+   /* run adbd in secure mode if ro.secure is set and
+    ** we are not in the emulator
+    */
+    property_get("ro.kernel.qemu", value, "");
+    if (strcmp(value, "1") != 0) {
+        property_get("ro.secure", value, "1");
+        if (strcmp(value, "1") == 0) {
+            // don't run as root if ro.secure is set...
+            secure = 1;
+
+            // ... except we allow running as root in userdebug builds if the
+            // service.adb.root property has been set by the "adb root" command
+            property_get("ro.debuggable", value, "");
+            if (strcmp(value, "1") == 0) {
+                property_get("service.adb.root", value, "");
+                if (strcmp(value, "1") == 0) {
+                    secure = 0;
+                }
+            }
+        }
+    }
+    return secure;
+#endif /* ALLOW_ADBD_ROOT */
+}
+#endif /* !ADB_HOST */
+
 int adb_main(int is_daemon, int server_port)
 {
 #if !ADB_HOST
-    int secure = 0;
     int port;
     char value[PROPERTY_VALUE_MAX];
+
+    umask(000);
 #endif
 
     atexit(adb_cleanup);
@@ -927,31 +1021,10 @@
         exit(1);
     }
 #else
-    /* run adbd in secure mode if ro.secure is set and
-    ** we are not in the emulator
-    */
-    property_get("ro.kernel.qemu", value, "");
-    if (strcmp(value, "1") != 0) {
-        property_get("ro.secure", value, "1");
-        if (strcmp(value, "1") == 0) {
-            // don't run as root if ro.secure is set...
-            secure = 1;
-
-            // ... except we allow running as root in userdebug builds if the
-            // service.adb.root property has been set by the "adb root" command
-            property_get("ro.debuggable", value, "");
-            if (strcmp(value, "1") == 0) {
-                property_get("service.adb.root", value, "");
-                if (strcmp(value, "1") == 0) {
-                    secure = 0;
-                }
-            }
-        }
-    }
 
     /* don't listen on a port (default 5037) if running in secure mode */
     /* don't run as root if we are running in secure mode */
-    if (secure) {
+    if (should_drop_privileges()) {
         struct __user_cap_header_struct header;
         struct __user_cap_data_struct cap;
 
@@ -966,13 +1039,14 @@
         ** AID_INET to diagnose network issues (netcfg, ping)
         ** AID_GRAPHICS to access the frame buffer
         ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
+        ** AID_SDCARD_R to allow reading from the SD card
         ** AID_SDCARD_RW to allow writing to the SD card
         ** AID_MOUNT to allow unmounting the SD card before rebooting
         ** AID_NET_BW_STATS to read out qtaguid statistics
         */
         gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
-                           AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_RW, AID_MOUNT,
-                           AID_NET_BW_STATS };
+                           AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
+                           AID_MOUNT, AID_NET_BW_STATS };
         if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
             exit(1);
         }
@@ -1001,29 +1075,24 @@
         }
     }
 
-    int usb = 0;
-    if (access("/dev/android_adb", F_OK) == 0) {
-        // listen on USB
-        usb_init();
-        usb = 1;
-    }
-
-    // If one of these properties is set, also listen on that port
-    // If one of the properties isn't set and we couldn't listen on usb,
-    // listen on the default port.
+        /* for the device, start the usb transport if the
+        ** android usb device exists and the "service.adb.tcp.port" and
+        ** "persist.adb.tcp.port" properties are not set.
+        ** Otherwise start the network transport.
+        */
     property_get("service.adb.tcp.port", value, "");
-    if (!value[0]) {
+    if (!value[0])
         property_get("persist.adb.tcp.port", value, "");
-    }
     if (sscanf(value, "%d", &port) == 1 && port > 0) {
-        printf("using port=%d\n", port);
         // listen on TCP port specified by service.adb.tcp.port property
         local_init(port);
-    } else if (!usb) {
+    } else if (access("/dev/android_adb", F_OK) == 0) {
+        // listen on USB
+        usb_init();
+    } else {
         // listen on default port
         local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
     }
-
     D("adb_main(): pre init_jdwp()\n");
     init_jdwp();
     D("adb_main(): post init_jdwp()\n");
@@ -1357,6 +1426,9 @@
     D("Handling commandline()\n");
     return adb_commandline(argc - 1, argv + 1);
 #else
+    /* If adbd runs inside the emulator this will enable adb tracing via
+     * adb-debug qemud service in the emulator. */
+    adb_qemu_trace_init();
     if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
         adb_device_banner = "recovery";
         recovery_mode = 1;
diff --git a/adb/adb.h b/adb/adb.h
index 300882c..622674a 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -86,6 +86,11 @@
         */
     int    closing;
 
+        /* flag: quit adbd when both ends close the
+        ** local service socket
+        */
+    int    exit_on_close;
+
         /* the asocket we are connected to
         */
 
@@ -348,6 +353,21 @@
 
 #if ADB_TRACE
 
+#if !ADB_HOST
+/*
+ * When running inside the emulator, guest's adbd can connect to 'adb-debug'
+ * qemud service that can display adb trace messages (on condition that emulator
+ * has been started with '-debug adb' option).
+ */
+
+/* Delivers a trace message to the emulator via QEMU pipe. */
+void adb_qemu_trace(const char* fmt, ...);
+/* Macro to use to send ADB trace messages to the emulator. */
+#define DQ(...)    adb_qemu_trace(__VA_ARGS__)
+#else
+#define DQ(...) ((void)0)
+#endif  /* !ADB_HOST */
+
   extern int     adb_trace_mask;
   extern unsigned char    adb_trace_output_count;
   void    adb_trace_init(void);
@@ -437,6 +457,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 22c878b..10b2332 100644
--- a/adb/commandline.c
+++ b/adb/commandline.c
@@ -121,10 +121,12 @@
         "                                   dev:<character device name>\n"
         "                                   jdwp:<process pid> (remote only)\n"
         "  adb jdwp                     - list PIDs of processes hosting a JDWP transport\n"
-        "  adb install [-l] [-r] [-s] <file> - push this package file to the device and install it\n"
+        "  adb install [-l] [-r] [-s] [--algo <algorithm name> --key <hex-encoded key> --iv <hex-encoded iv>] <file>\n"
+        "                               - push this package file to the device and install it\n"
         "                                 ('-l' means forward-lock the app)\n"
         "                                 ('-r' means reinstall the app, keeping its data)\n"
         "                                 ('-s' means install on SD card instead of internal storage)\n"
+        "                                 ('--algo', '--key', and '--iv' mean the file is encrypted already)\n"
         "  adb uninstall [-k] <package> - remove this app package from the device\n"
         "                                 ('-k' means keep the data and cache directories)\n"
         "  adb bugreport                - return all information from the device\n"
@@ -369,6 +371,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];
@@ -563,6 +642,10 @@
 
     free(quoted_log_tags);
 
+    if (!strcmp(argv[0],"longcat")) {
+        strncat(buf, " -v long", sizeof(buf)-1);
+    }
+
     argc -= 1;
     argv += 1;
     while(argc-- > 0) {
@@ -646,6 +729,7 @@
         return -1;
     }
 
+    printf("Now unlock your device and confirm the backup operation.\n");
     copy_to_file(fd, outFd);
 
     adb_close(fd);
@@ -673,6 +757,7 @@
         return -1;
     }
 
+    printf("Now unlock your device and confirm the restore operation.\n");
     copy_to_file(tarFd, fd);
 
     adb_close(fd);
@@ -1068,6 +1153,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")
@@ -1237,7 +1331,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);
     }
 
@@ -1452,6 +1546,7 @@
     int file_arg = -1;
     int err;
     int i;
+    int verify_apk = 1;
 
     for (i = 1; i < argc; i++) {
         if (*argv[i] != '-') {
@@ -1462,6 +1557,15 @@
             i++;
         } else if (!strcmp(argv[i], "-s")) {
             where = SD_DEST;
+        } else if (!strcmp(argv[i], "--algo")) {
+            verify_apk = 0;
+            i++;
+        } else if (!strcmp(argv[i], "--iv")) {
+            verify_apk = 0;
+            i++;
+        } else if (!strcmp(argv[i], "--key")) {
+            verify_apk = 0;
+            i++;
         }
     }
 
@@ -1493,9 +1597,9 @@
         }
     }
 
-    err = do_sync_push(apk_file, apk_dest, 1 /* verify APK */);
+    err = do_sync_push(apk_file, apk_dest, verify_apk);
     if (err) {
-        return err;
+        goto cleanup_apk;
     } else {
         argv[file_arg] = apk_dest; /* destination name, not source location */
     }
@@ -1511,11 +1615,11 @@
 
     pm_command(transport, serial, argc, argv);
 
+cleanup_apk:
     if (verification_file != NULL) {
         delete_file(transport, serial, verification_dest);
     }
 
-cleanup_apk:
     delete_file(transport, serial, apk_dest);
 
     return err;
diff --git a/adb/services.c b/adb/services.c
index 6940be8..495a083 100644
--- a/adb/services.c
+++ b/adb/services.c
@@ -125,12 +125,10 @@
             return;
         }
 
+        property_set("service.adb.root", "1");
         snprintf(buf, sizeof(buf), "restarting adbd as root\n");
         writex(fd, buf, strlen(buf));
         adb_close(fd);
-
-        // This will cause a property trigger in init.rc to restart us
-        property_set("service.adb.root", "1");
     }
 }
 
@@ -152,10 +150,6 @@
     snprintf(buf, sizeof(buf), "restarting in TCP mode port: %d\n", port);
     writex(fd, buf, strlen(buf));
     adb_close(fd);
-
-    // quit, and init will restart us in TCP mode
-    sleep(1);
-    exit(1);
 }
 
 void restart_usb_service(int fd, void *cookie)
@@ -166,10 +160,6 @@
     snprintf(buf, sizeof(buf), "restarting in USB mode\n");
     writex(fd, buf, strlen(buf));
     adb_close(fd);
-
-    // quit, and init will restart us in USB mode
-    sleep(1);
-    exit(1);
 }
 
 void reboot_service(int fd, void *arg)
@@ -369,7 +359,6 @@
                 break;
             }
          }
-        usleep(100000);  // poll every 0.1 sec
     }
     D("shell exited fd=%d of pid=%d err=%d\n", fd, pid, errno);
     if (SHELL_EXIT_NOTIFY_FD >=0) {
diff --git a/adb/sockets.c b/adb/sockets.c
index 830cf26..b77c38c 100644
--- a/adb/sockets.c
+++ b/adb/sockets.c
@@ -199,6 +199,8 @@
 static void local_socket_destroy(asocket  *s)
 {
     apacket *p, *n;
+    int exit_on_close = s->exit_on_close;
+
     D("LS(%d): destroying fde.fd=%d\n", s->id, s->fde.fd);
 
         /* IMPORTANT: the remove closes the fd
@@ -214,6 +216,11 @@
     }
     remove_socket(s);
     free(s);
+
+    if (exit_on_close) {
+        D("local_socket_destroy: exiting\n");
+        exit(1);
+    }
 }
 
 
@@ -418,6 +425,16 @@
 
     s = create_local_socket(fd);
     D("LS(%d): bound to '%s' via %d\n", s->id, name, fd);
+
+#if !ADB_HOST
+    if ((!strcmp(name, "root:") && getuid() != 0)
+        || !strcmp(name, "usb:")
+        || !strcmp(name, "tcpip:")) {
+        D("LS(%d): enabling exit_on_close\n", s->id);
+        s->exit_on_close = 1;
+    }
+#endif
+
     return s;
 }
 
diff --git a/adb/transport.c b/adb/transport.c
index c88b90f..9fd6cc2 100644
--- a/adb/transport.c
+++ b/adb/transport.c
@@ -886,6 +886,7 @@
     case CS_DEVICE: return "device";
     case CS_HOST: return "host";
     case CS_RECOVERY: return "recovery";
+    case CS_SIDELOAD: return "sideload";
     case CS_NOPERM: return "no permissions";
     default: return "unknown";
     }
diff --git a/adb/transport_local.c b/adb/transport_local.c
index d985ee3..105c502 100644
--- a/adb/transport_local.c
+++ b/adb/transport_local.c
@@ -318,7 +318,7 @@
             /* Running inside the device: use TCP socket as the transport. */
             func = server_socket_thread;
         }
-#endif !ADB_HOST
+#endif // !ADB_HOST
     }
 
     D("transport: local %s init\n", HOST ? "client" : "server");
diff --git a/adb/usb_vendors.c b/adb/usb_vendors.c
index d213dd9..b988115 100644
--- a/adb/usb_vendors.c
+++ b/adb/usb_vendors.c
@@ -37,6 +37,8 @@
 
 // Google's USB Vendor ID
 #define VENDOR_ID_GOOGLE        0x18d1
+// Intel's USB Vendor ID
+#define VENDOR_ID_INTEL         0x8087
 // HTC's USB Vendor ID
 #define VENDOR_ID_HTC           0x0bb4
 // Samsung's USB Vendor ID
@@ -115,18 +117,21 @@
 #define VENDOR_ID_FUJITSU       0x04C5
 // Lumigon's USB Vendor ID
 #define VENDOR_ID_LUMIGON       0x25E3
-//Intel's USB Vendor ID
-#define VENDOR_ID_INTEL         0x8087
 // Quanta's USB Vendor ID
 #define VENDOR_ID_QUANTA        0x0408
 // INQ Mobile's USB Vendor ID
 #define VENDOR_ID_INQ_MOBILE    0x2314
 // Sony's USB Vendor ID
 #define VENDOR_ID_SONY          0x054C
+// Lab126's USB Vendor ID
+#define VENDOR_ID_LAB126        0x1949
+// Yulong Coolpad's USB Vendor ID
+#define VENDOR_ID_YULONG_COOLPAD 0x1EBF
 
 /** built-in vendor list */
 int builtInVendorIds[] = {
     VENDOR_ID_GOOGLE,
+    VENDOR_ID_INTEL,
     VENDOR_ID_HTC,
     VENDOR_ID_SAMSUNG,
     VENDOR_ID_MOTOROLA,
@@ -166,10 +171,11 @@
     VENDOR_ID_POSITIVO,
     VENDOR_ID_FUJITSU,
     VENDOR_ID_LUMIGON,
-    VENDOR_ID_INTEL,
     VENDOR_ID_QUANTA,
     VENDOR_ID_INQ_MOBILE,
     VENDOR_ID_SONY,
+    VENDOR_ID_LAB126,
+    VENDOR_ID_YULONG_COOLPAD,
 };
 
 #define BUILT_IN_VENDOR_COUNT    (sizeof(builtInVendorIds)/sizeof(builtInVendorIds[0]))
diff --git a/adb/usb_windows.c b/adb/usb_windows.c
index a2fbb79..4936b77 100644
--- a/adb/usb_windows.c
+++ b/adb/usb_windows.c
@@ -255,7 +255,7 @@
 }
 
 int usb_write(usb_handle* handle, const void* data, int len) {
-  unsigned long time_out = 500 + len * 8;
+  unsigned long time_out = 5000;
   unsigned long written = 0;
   int ret;
 
@@ -300,7 +300,7 @@
 }
 
 int usb_read(usb_handle *handle, void* data, int len) {
-  unsigned long time_out = 500 + len * 8;
+  unsigned long time_out = 0;
   unsigned long read = 0;
   int ret;
 
@@ -322,7 +322,7 @@
 
         if (len == 0)
           return 0;
-      } else if (saved_errno != ERROR_SEM_TIMEOUT) {
+      } else {
         // assume ERROR_INVALID_HANDLE indicates we are disconnected
         if (saved_errno == ERROR_INVALID_HANDLE)
           usb_kick(handle);
diff --git a/cpio/mkbootfs.c b/cpio/mkbootfs.c
index f672336..323a09d 100644
--- a/cpio/mkbootfs.c
+++ b/cpio/mkbootfs.c
@@ -3,6 +3,7 @@
 #include <stdlib.h>
 #include <unistd.h>
 #include <string.h>
+#include <ctype.h>
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -34,12 +35,51 @@
     exit(1);
 }
 
+struct fs_config_entry {
+    char* name;
+    int uid, gid, mode;
+};
+
+static struct fs_config_entry* canned_config = NULL;
+
+/* Each line in the canned file should be a path plus three ints (uid,
+ * gid, mode). */
+#ifdef PATH_MAX
+#define CANNED_LINE_LENGTH  (PATH_MAX+100)
+#else
+#define CANNED_LINE_LENGTH  (1024)
+#endif
+
 static int verbose = 0;
 static int total_size = 0;
 
 static void fix_stat(const char *path, struct stat *s)
 {
-    fs_config(path, S_ISDIR(s->st_mode), &s->st_uid, &s->st_gid, &s->st_mode);
+    if (canned_config) {
+        // Use the list of file uid/gid/modes loaded from the file
+        // given with -f.
+
+        struct fs_config_entry* empty_path_config = NULL;
+        struct fs_config_entry* p;
+        for (p = canned_config; p->name; ++p) {
+            if (!p->name[0]) {
+                empty_path_config = p;
+            }
+            if (strcmp(p->name, path) == 0) {
+                s->st_uid = p->uid;
+                s->st_gid = p->gid;
+                s->st_mode = p->mode | (s->st_mode & ~07777);
+                return;
+            }
+        }
+        s->st_uid = empty_path_config->uid;
+        s->st_gid = empty_path_config->gid;
+        s->st_mode = empty_path_config->mode | (s->st_mode & ~07777);
+    } else {
+        // Use the compiled-in fs_config() function.
+
+        fs_config(path, S_ISDIR(s->st_mode), &s->st_uid, &s->st_gid, &s->st_mode);
+    }
 }
 
 static void _eject(struct stat *s, char *out, int olen, char *data, unsigned datasize)
@@ -79,7 +119,7 @@
 
     total_size += 6 + 8*13 + olen + 1;
 
-    if(strlen(out) != olen) die("ACK!");
+    if(strlen(out) != (unsigned int)olen) die("ACK!");
 
     while(total_size & 3) {
         total_size++;
@@ -235,11 +275,61 @@
     _archive_dir(in, out, strlen(in), strlen(out));
 }
 
+static void read_canned_config(char* filename)
+{
+    int allocated = 8;
+    int used = 0;
+
+    canned_config =
+        (struct fs_config_entry*)malloc(allocated * sizeof(struct fs_config_entry));
+
+    char line[CANNED_LINE_LENGTH];
+    FILE* f = fopen(filename, "r");
+    if (f == NULL) die("failed to open canned file");
+
+    while (fgets(line, CANNED_LINE_LENGTH, f) != NULL) {
+        if (!line[0]) break;
+        if (used >= allocated) {
+            allocated *= 2;
+            canned_config = (struct fs_config_entry*)realloc(
+                canned_config, allocated * sizeof(struct fs_config_entry));
+        }
+
+        struct fs_config_entry* cc = canned_config + used;
+
+        if (isspace(line[0])) {
+            cc->name = strdup("");
+            cc->uid = atoi(strtok(line, " \n"));
+        } else {
+            cc->name = strdup(strtok(line, " \n"));
+            cc->uid = atoi(strtok(NULL, " \n"));
+        }
+        cc->gid = atoi(strtok(NULL, " \n"));
+        cc->mode = strtol(strtok(NULL, " \n"), NULL, 8);
+        ++used;
+    }
+    if (used >= allocated) {
+        ++allocated;
+        canned_config = (struct fs_config_entry*)realloc(
+            canned_config, allocated * sizeof(struct fs_config_entry));
+    }
+    canned_config[used].name = NULL;
+
+    fclose(f);
+}
+
+
 int main(int argc, char *argv[])
 {
     argc--;
     argv++;
 
+    if (argc > 1 && strcmp(argv[0], "-f") == 0) {
+        read_canned_config(argv[1]);
+        argc -= 2;
+        argv += 2;
+    }
+
     if(argc == 0) die("no directories to process?!");
 
     while(argc-- > 0){
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..662683a 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";
@@ -121,12 +64,14 @@
     case SIGBUS:     return "SIGBUS";
     case SIGFPE:     return "SIGFPE";
     case SIGSEGV:    return "SIGSEGV";
+    case SIGPIPE:    return "SIGPIPE";
     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 +115,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 +133,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 +147,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 +211,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 +343,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 +513,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 +540,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 +561,303 @@
                     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",
+            request.pid, request.uid, request.gid, request.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 SIGPIPE:
+                    case SIGSTKFLT: {
+                        XLOG("stopped -- fatal signal\n");
+                        /*
+                         * Send a SIGSTOP to the process to make all of
+                         * the non-signaled threads stop moving.  Without
+                         * this we get a lot of "ptrace detach failed:
+                         * No such process".
+                         */
+                        kill(request.pid, SIGSTOP);
+                        /* 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;
@@ -912,8 +871,8 @@
     signal(SIGBUS, SIG_DFL);
     signal(SIGFPE, SIG_DFL);
     signal(SIGSEGV, SIG_DFL);
-    signal(SIGSTKFLT, SIG_DFL);
     signal(SIGPIPE, SIG_DFL);
+    signal(SIGSTKFLT, SIG_DFL);
 
     logsocket = socket_local_client("logd",
             ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_DGRAM);
@@ -931,7 +890,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 +910,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/nexus/NexusCommand.cpp b/debuggerd/getevent.h
similarity index 69%
rename from nexus/NexusCommand.cpp
rename to debuggerd/getevent.h
index 541eeeb..426139d 100644
--- a/nexus/NexusCommand.cpp
+++ b/debuggerd/getevent.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,8 +14,11 @@
  * limitations under the License.
  */
 
-#include "NexusCommand.h"
+#ifndef _DEBUGGERD_GETEVENT_H
+#define _DEBUGGERD_GETEVENT_H
 
-NexusCommand::NexusCommand(const char *cmd) :
-              FrameworkCommand(cmd)  {
-}
+int init_getevent();
+void uninit_getevent();
+int get_event(struct input_event* event, int timeout);
+
+#endif // _DEBUGGERD_GETEVENT_H
diff --git a/nexus/NexusCommand.h b/debuggerd/machine.h
similarity index 66%
rename from nexus/NexusCommand.h
rename to debuggerd/machine.h
index a7f944a..6049b69 100644
--- a/nexus/NexusCommand.h
+++ b/debuggerd/machine.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,15 +14,12 @@
  * limitations under the License.
  */
 
-#ifndef _NEXUS_COMMAND_H
-#define _NEXUS_COMMAND_H
+#ifndef _DEBUGGERD_MACHINE_H
+#define _DEBUGGERD_MACHINE_H
 
-#include <sysutils/FrameworkCommand.h>
+#include <corkscrew/backtrace.h>
+#include <sys/types.h>
 
-class NexusCommand : public FrameworkCommand {
-public:
-    NexusCommand(const char *cmd);
-    virtual ~NexusCommand() {}
-};
+void dump_thread(const ptrace_context_t* context, int tfd, pid_t tid, bool at_fault);
 
-#endif
+#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..8eb52ba 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,252 @@
             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.
+     */
+    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) {
+            next = map->next;
+            break;
+        } else if (addr >= map->end) {
+            /* map would be between "prev" and this entry */
+            next = map;
+            map = NULL;
+            break;
+        }
+
+        prev = map;
+        map = map->next;
+    }
+
+    /*
+     * Show "next" then "match" then "prev" so that the addresses appear in
+     * ascending order (like /proc/pid/maps).
+     */
+    if (next != NULL) {
+        _LOG(tfd, false, "    %08x-%08x %s\n", next->start, next->end, next->name);
+    } else {
+        _LOG(tfd, false, "    (no map below)\n");
+    }
+    if (map != NULL) {
+        _LOG(tfd, false, "    %08x-%08x %s\n", map->start, map->end, map->name);
+    } else {
+        _LOG(tfd, false, "    (no map for address)\n");
+    }
+    if (prev != NULL) {
+        _LOG(tfd, false, "    %08x-%08x %s\n", prev->start, prev->end, prev->name);
+    } else {
+        _LOG(tfd, false, "    (no map above)\n");
+    }
+}
diff --git a/debuggerd/utility.h b/debuggerd/utility.h
index 4a935d2..39f91cb 100644
--- a/debuggerd/utility.h
+++ b/debuggerd/utility.h
@@ -15,50 +15,17 @@
 ** limitations under the License.
 */
 
-#ifndef __utility_h
-#define __utility_h
+#ifndef _DEBUGGERD_UTILITY_H
+#define _DEBUGGERD_UTILITY_H
 
 #include <stddef.h>
 #include <stdbool.h>
+#include <sys/types.h>
+#include <corkscrew/backtrace.h>
 
-#include "symbol_table.h"
-
-#ifndef PT_ARM_EXIDX
-#define PT_ARM_EXIDX    0x70000001      /* .ARM.exidx segment */
-#endif
-
-#define STACK_CONTENT_DEPTH 32
-
-typedef struct mapinfo {
-    struct mapinfo *next;
-    unsigned start;
-    unsigned end;
-    unsigned exidx_start;
-    unsigned exidx_end;
-    struct symbol_table *symbols;
-    bool isExecutable;
-    char name[];
-} mapinfo;
-
-/* Get a word from pid using ptrace. The result is the return value. */
-extern int get_remote_word(int pid, void *src);
-
-/* Handy routine to read aggregated data from pid using ptrace. The read 
- * values are written to the dest locations directly. 
- */
-extern void get_remote_struct(int pid, void *src, void *dst, size_t size);
-
-/* Find the containing map for the pc */
-const mapinfo *pc_to_mapinfo (mapinfo *mi, unsigned pc, unsigned *rel_pc);
-
-/* Map a pc address to the name of the containing ELF file */
-const char *map_to_name(mapinfo *mi, unsigned pc, const char* def);
-
-/* Log information onto the tombstone */
-extern void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...);
-
-/* Determine whether si_addr is valid for this signal */
-bool signal_has_address(int sig);
+/* Log information onto the tombstone. */
+void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...)
+        __attribute__ ((format(printf, 3, 4)));
 
 #define LOG(fmt...) _LOG(-1, 0, fmt)
 
@@ -76,4 +43,30 @@
 #define XLOG2(fmt...) do {} while(0)
 #endif
 
-#endif
+/*
+ * Returns true if the specified signal has an associated address.
+ * (i.e. it sets siginfo_t.si_addr).
+ */
+bool signal_has_address(int sig);
+
+/*
+ * Dumps the backtrace and contents of the stack.
+ */
+void dump_backtrace_and_stack(const ptrace_context_t* context, int tfd, pid_t tid, bool at_fault);
+
+/*
+ * Dumps a few bytes of memory, starting a bit before and ending a bit
+ * after the specified address.
+ */
+void dump_memory(int tfd, pid_t tid, uintptr_t addr, bool at_fault);
+
+/*
+ * If this isn't clearly a null pointer dereference, dump the
+ * /proc/maps entries near the fault address.
+ *
+ * This only makes sense to do on the thread that crashed.
+ */
+void dump_nearby_maps(const ptrace_context_t* context, int tfd, pid_t tid);
+
+
+#endif // _DEBUGGERD_UTILITY_H
diff --git a/debuggerd/x86/machine.c b/debuggerd/x86/machine.c
index 9d418cf..2729c7e 100644
--- a/debuggerd/x86/machine.c
+++ b/debuggerd/x86/machine.c
@@ -31,31 +31,43 @@
 #include <cutils/sockets.h>
 #include <cutils/properties.h>
 
+#include <corkscrew/backtrace.h>
+#include <corkscrew/ptrace.h>
+
 #include <linux/input.h>
 
+#include "../machine.h"
 #include "../utility.h"
-#include "x86_utility.h"
 
-void dump_registers(int tfd, int pid, bool at_fault)
-{
+static void dump_registers(const ptrace_context_t* context __attribute((unused)),
+        int tfd, pid_t tid, bool at_fault) {
     struct pt_regs_x86 r;
     bool only_in_tombstone = !at_fault;
 
-    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) {
-        _LOG(tfd, only_in_tombstone,
-             "cannot get registers: %s\n", strerror(errno));
+    if(ptrace(PTRACE_GETREGS, tid, 0, &r)) {
+        _LOG(tfd, only_in_tombstone, "cannot get registers: %s\n", strerror(errno));
         return;
     }
-//if there is no stack, no print just like arm
+    //if there is no stack, no print just like arm
     if(!r.ebp)
         return;
-    _LOG(tfd, only_in_tombstone, " eax %08x  ebx %08x  ecx %08x  edx %08x\n",
+    _LOG(tfd, only_in_tombstone, "    eax %08x  ebx %08x  ecx %08x  edx %08x\n",
          r.eax, r.ebx, r.ecx, r.edx);
-    _LOG(tfd, only_in_tombstone, " esi %08x  edi %08x\n",
+    _LOG(tfd, only_in_tombstone, "    esi %08x  edi %08x\n",
          r.esi, r.edi);
-    _LOG(tfd, only_in_tombstone, " xcs %08x  xds %08x  xes %08x  xfs %08x xss %08x\n",
+    _LOG(tfd, only_in_tombstone, "    xcs %08x  xds %08x  xes %08x  xfs %08x  xss %08x\n",
          r.xcs, r.xds, r.xes, r.xfs, r.xss);
-    _LOG(tfd, only_in_tombstone,
-         " eip %08x  ebp %08x  esp %08x  flags %08x\n",
+    _LOG(tfd, only_in_tombstone, "    eip %08x  ebp %08x  esp %08x  flags %08x\n",
          r.eip, r.ebp, r.esp, r.eflags);
 }
+
+void dump_thread(const ptrace_context_t* context, int tfd, pid_t tid, bool at_fault) {
+    dump_registers(context, tfd, tid, at_fault);
+
+    dump_backtrace_and_stack(context, tfd, tid, at_fault);
+
+    if (at_fault) {
+        dump_nearby_maps(context, tfd, tid);
+    }
+}
+
diff --git a/debuggerd/x86/unwind.c b/debuggerd/x86/unwind.c
deleted file mode 100644
index 0a7f04c..0000000
--- a/debuggerd/x86/unwind.c
+++ /dev/null
@@ -1,86 +0,0 @@
-#include <cutils/logd.h>
-#include <sys/ptrace.h>
-#include "../utility.h"
-#include "x86_utility.h"
-
-
-int unwind_backtrace_with_ptrace_x86(int tfd, pid_t pid, mapinfo *map,
-                                 bool at_fault)
-{
-    struct pt_regs_x86 r;
-    unsigned int stack_level = 0;
-    unsigned int stack_depth = 0;
-    unsigned int rel_pc;
-    unsigned int stack_ptr;
-    unsigned int stack_content;
-
-    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) return 0;
-    unsigned int eip = (unsigned int)r.eip;
-    unsigned int ebp = (unsigned int)r.ebp;
-    unsigned int cur_sp = (unsigned int)r.esp;
-    const mapinfo *mi;
-    const struct symbol* sym = 0;
-
-
-//ebp==0, it indicates that the stack is poped to the bottom or there is no stack at all.
-    while (ebp) {
-        mi = pc_to_mapinfo(map, eip, &rel_pc);
-
-        /* See if we can determine what symbol this stack frame resides in */
-        if (mi != 0 && mi->symbols != 0) {
-            sym = symbol_table_lookup(mi->symbols, rel_pc);
-        }
-        if (sym) {
-            _LOG(tfd, !at_fault, "    #%02d  eip: %08x  %s (%s)\n",
-                 stack_level, eip, mi ? mi->name : "", sym->name);
-        } else {
-            _LOG(tfd, !at_fault, "    #%02d  eip: %08x  %s\n",
-                 stack_level, eip, mi ? mi->name : "");
-        }
-
-        stack_level++;
-        if (stack_level >= STACK_DEPTH || eip == 0)
-            break;
-        eip = ptrace(PTRACE_PEEKTEXT, pid, (void*)(ebp + 4), NULL);
-        ebp = ptrace(PTRACE_PEEKTEXT, pid, (void*)ebp, NULL);
-    }
-    ebp = (unsigned int)r.ebp;
-    stack_depth = stack_level;
-    stack_level = 0;
-    if (ebp)
-        _LOG(tfd, !at_fault, "stack: \n");
-    while (ebp) {
-        stack_ptr = cur_sp;
-        while((int)(ebp - stack_ptr) >= 0) {
-            stack_content = ptrace(PTRACE_PEEKTEXT, pid, (void*)stack_ptr, NULL);
-            mi = pc_to_mapinfo(map, stack_content, &rel_pc);
-
-            /* See if we can determine what symbol this stack frame resides in */
-            if (mi != 0 && mi->symbols != 0) {
-                sym = symbol_table_lookup(mi->symbols, rel_pc);
-            }
-            if (sym) {
-                _LOG(tfd, !at_fault, "    #%02d  %08x  %08x  %s (%s)\n",
-                     stack_level, stack_ptr, stack_content, mi ? mi->name : "", sym->name);
-            } else {
-                _LOG(tfd, !at_fault, "    #%02d  %08x  %08x  %s\n",
-                     stack_level, stack_ptr, stack_content, mi ? mi->name : "");
-            }
-
-            stack_ptr = stack_ptr + 4;
-            //the stack frame may be very deep.
-            if((int)(stack_ptr - cur_sp) >= STACK_FRAME_DEPTH) {
-                _LOG(tfd, !at_fault, "    ......  ......  \n");
-                break;
-            }
-        }
-        cur_sp = ebp + 4;
-        stack_level++;
-        if (stack_level >= STACK_DEPTH || stack_level >= stack_depth)
-            break;
-        ebp = ptrace(PTRACE_PEEKTEXT, pid, (void*)ebp, NULL);
-    }
-
-    return stack_depth;
-}
-
diff --git a/debuggerd/x86/x86_utility.h b/debuggerd/x86/x86_utility.h
deleted file mode 100644
index ac6a885..0000000
--- a/debuggerd/x86/x86_utility.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
-**
-** Copyright 2006, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define STACK_DEPTH 8
-#define STACK_FRAME_DEPTH 64
-
-typedef struct pt_regs_x86 {
-    long ebx;
-    long ecx;
-    long edx;
-    long esi;
-    long edi;
-    long ebp;
-    long eax;
-    int  xds;
-    int  xes;
-    int  xfs;
-    int  xgs;
-    long orig_eax;
-    long eip;
-    int  xcs;
-    long eflags;
-    long esp;
-    int  xss;
-}pt_regs_x86;
-
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index 8c130ff..089b9bb 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -50,6 +50,12 @@
 
 LOCAL_STATIC_LIBRARIES := $(EXTRA_STATIC_LIBS) libzipfile libunz libext4_utils libz
 
+ifneq ($(HOST_OS),windows)
+ifeq ($(HAVE_SELINUX), true)
+LOCAL_STATIC_LIBRARIES += libselinux
+endif # HAVE_SELINUX
+endif # HOST_OS != windows
+
 include $(BUILD_HOST_EXECUTABLE)
 $(call dist-for-goals,dist_files,$(LOCAL_BUILT_MODULE))
 
diff --git a/fastboot/bootimg.c b/fastboot/bootimg.c
index e5aea4e..9e0e45c 100644
--- a/fastboot/bootimg.c
+++ b/fastboot/bootimg.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -48,23 +48,23 @@
     unsigned second_actual;
     unsigned page_mask;
     boot_img_hdr *hdr;
-    
+
     page_mask = page_size - 1;
-    
+
     kernel_actual = (kernel_size + page_mask) & (~page_mask);
     ramdisk_actual = (ramdisk_size + page_mask) & (~page_mask);
     second_actual = (second_size + page_mask) & (~page_mask);
-    
+
     *bootimg_size = page_size + kernel_actual + ramdisk_actual + second_actual;
-    
+
     hdr = calloc(*bootimg_size, 1);
-    
+
     if(hdr == 0) {
         return hdr;
     }
 
     memcpy(hdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);
-    
+
     hdr->kernel_size =  kernel_size;
     hdr->ramdisk_size = ramdisk_size;
     hdr->second_size =  second_size;
@@ -74,9 +74,9 @@
     hdr->tags_addr =    base + 0x00000100;
     hdr->page_size =    page_size;
 
-    memcpy(hdr->magic + page_size, 
+    memcpy(hdr->magic + page_size,
            kernel, kernel_size);
-    memcpy(hdr->magic + page_size + kernel_actual, 
+    memcpy(hdr->magic + page_size + kernel_actual,
            ramdisk, ramdisk_size);
     memcpy(hdr->magic + page_size + kernel_actual + ramdisk_actual,
            second, second_size);
diff --git a/fastboot/engine.c b/fastboot/engine.c
index 89cff3f..f5215cf 100644
--- a/fastboot/engine.c
+++ b/fastboot/engine.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -35,12 +35,17 @@
 #include <stdarg.h>
 #include <stdbool.h>
 #include <string.h>
-#include <sys/mman.h>
 #include <sys/stat.h>
 #include <sys/time.h>
 #include <sys/types.h>
 #include <unistd.h>
 
+#ifdef USE_MINGW
+#include <fcntl.h>
+#else
+#include <sys/mman.h>
+#endif
+
 extern struct fs_info info;
 
 #define ARRAY_SIZE(x)           (sizeof(x)/sizeof(x[0]))
@@ -61,7 +66,7 @@
     va_start(ap, fmt);
     vsprintf(buf, fmt, ap);
     va_end(ap);
-    
+
     s = strdup(buf);
     if (s == 0) die("out of memory");
     return s;
@@ -77,7 +82,7 @@
 
 #define CMD_SIZE 64
 
-struct Action 
+struct Action
 {
     unsigned op;
     Action *next;
@@ -104,7 +109,7 @@
 };
 
 void generate_ext4_image(struct image_data *image);
-void munmap_image(struct image_data *image);
+void cleanup_image(struct image_data *image);
 
 struct generator {
     char *fs_type;
@@ -122,7 +127,7 @@
      */
     void (*cleanup)(struct image_data *image);
 } generators[] = {
-    { "ext4", generate_ext4_image, munmap_image }
+    { "ext4", generate_ext4_image, cleanup_image }
 };
 
 static int cb_default(Action *a, int status, char *resp)
@@ -176,9 +181,58 @@
     a->msg = mkmsg("erasing '%s'", ptn);
 }
 
-void munmap_image(struct image_data *image)
+/* Loads file content into buffer. Returns NULL on error. */
+static void *load_buffer(int fd, off_t size)
 {
+    void *buffer;
+
+#ifdef USE_MINGW
+    ssize_t count = 0;
+
+    // mmap is more efficient but mingw does not support it.
+    // In this case we read whole image into memory buffer.
+    buffer = malloc(size);
+    if (!buffer) {
+        perror("malloc");
+        return NULL;
+    }
+
+    lseek(fd, 0, SEEK_SET);
+    while(count < size) {
+        ssize_t actually_read = read(fd, (char*)buffer+count, size-count);
+
+        if (actually_read == 0) {
+            break;
+        }
+        if (actually_read < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+            perror("read");
+            free(buffer);
+            return NULL;
+        }
+
+        count += actually_read;
+    }
+#else
+    buffer = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
+    if (buffer == MAP_FAILED) {
+        perror("mmap");
+        return NULL;
+    }
+#endif
+
+    return buffer;
+}
+
+void cleanup_image(struct image_data *image)
+{
+#ifdef USE_MINGW
+    free(image->buffer);
+#else
     munmap(image->buffer, image->image_size);
+#endif
 }
 
 void generate_ext4_image(struct image_data *image)
@@ -186,20 +240,29 @@
     int fd;
     struct stat st;
 
+#ifdef USE_MINGW
+    /* Ideally we should use tmpfile() here, the same as with unix version.
+     * But unfortunately it is not portable as it is not clear whether this
+     * function opens file in TEXT or BINARY mode.
+     *
+     * There are also some reports it is buggy:
+     *    http://pdplab.it.uom.gr/teaching/gcc_manuals/gnulib.html#tmpfile
+     *    http://www.mega-nerd.com/erikd/Blog/Windiots/tmpfile.html
+     */
+    char *filename = tempnam(getenv("TEMP"), "fastboot-format.img");
+    fd = open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0644);
+    unlink(filename);
+#else
     fd = fileno(tmpfile());
+#endif
     /* reset ext4fs info so we can be called multiple times */
     reset_ext4fs_info();
     info.len = image->partition_size;
-    make_ext4fs_internal(fd, NULL, NULL, 0, 0, 1, 0, 0, 0);
+    make_ext4fs_internal(fd, NULL, NULL, NULL, 0, 1, 0, 0, 0, NULL);
 
     fstat(fd, &st);
     image->image_size = st.st_size;
-
-    image->buffer = mmap(NULL, image->image_size, PROT_READ, MAP_PRIVATE, fd, 0);
-    if (image->buffer == MAP_FAILED) {
-        perror("mmap");
-        image->buffer = NULL;
-    }
+    image->buffer = load_buffer(fd, st.st_size);
 
     close(fd);
 }
@@ -207,7 +270,6 @@
 int fb_format(Action *a, usb_handle *usb, int skip_if_not_supported)
 {
     const char *partition = a->cmd;
-    char query[256];
     char response[FB_RESPONSE_SZ+1];
     int status = 0;
     struct image_data image;
@@ -217,8 +279,8 @@
     char cmd[CMD_SIZE];
 
     response[FB_RESPONSE_SZ] = '\0';
-    snprintf(query, sizeof(query), "getvar:partition-type:%s", partition);
-    status = fb_command_response(usb, query, response);
+    snprintf(cmd, sizeof(cmd), "getvar:partition-type:%s", partition);
+    status = fb_command_response(usb, cmd, response);
     if (status) {
         if (skip_if_not_supported) {
             fprintf(stderr,
@@ -251,8 +313,8 @@
     }
 
     response[FB_RESPONSE_SZ] = '\0';
-    snprintf(query, sizeof(query), "getvar:partition-size:%s", partition);
-    status = fb_command_response(usb, query, response);
+    snprintf(cmd, sizeof(cmd), "getvar:partition-size:%s", partition);
+    status = fb_command_response(usb, cmd, response);
     if (status) {
         if (skip_if_not_supported) {
             fprintf(stderr,
@@ -278,7 +340,7 @@
     if (status) goto cleanup;
 
     fprintf(stderr, "writing '%s'...\n", partition);
-    snprintf(cmd, CMD_SIZE, "flash:%s", partition);
+    snprintf(cmd, sizeof(cmd), "flash:%s", partition);
     status = fb_command(usb, cmd);
     if (status) goto cleanup;
 
diff --git a/fastboot/fastboot.c b/fastboot/fastboot.c
index 6e42436..c44f937 100644
--- a/fastboot/fastboot.c
+++ b/fastboot/fastboot.c
@@ -89,6 +89,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 {
@@ -151,6 +153,7 @@
 {
     if(!(vendor_id && (info->dev_vendor == vendor_id)) &&
        (info->dev_vendor != 0x18d1) &&  // Google
+       (info->dev_vendor != 0x8087) &&  // Intel
        (info->dev_vendor != 0x0451) &&
        (info->dev_vendor != 0x0502) &&
        (info->dev_vendor != 0x0fce) &&  // Sony Ericsson
@@ -159,6 +162,7 @@
        (info->dev_vendor != 0x0955) &&  // Nvidia
        (info->dev_vendor != 0x413c) &&  // DELL
        (info->dev_vendor != 0x2314) &&  // INQ Mobile
+       (info->dev_vendor != 0x0b05) &&  // Asus
        (info->dev_vendor != 0x0bb4))    // HTC
             return -1;
     if(info->ifc_class != 0xff) return -1;
diff --git a/fastboot/fastboot.h b/fastboot/fastboot.h
index 6d036f8..90d8a6a 100644
--- a/fastboot/fastboot.h
+++ b/fastboot/fastboot.h
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
diff --git a/fastboot/protocol.c b/fastboot/protocol.c
index 3948363..e871113 100644
--- a/fastboot/protocol.c
+++ b/fastboot/protocol.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -40,7 +40,7 @@
     return ERROR;
 }
 
-static int check_response(usb_handle *usb, unsigned size, 
+static int check_response(usb_handle *usb, unsigned size,
                           unsigned data_okay, char *response)
 {
     unsigned char status[65];
@@ -106,7 +106,7 @@
 {
     int cmdsize = strlen(cmd);
     int r;
-    
+
     if(response) {
         response[0] = 0;
     }
@@ -145,7 +145,7 @@
             return -1;
         }
     }
-    
+
     r = check_response(usb, 0, 0, 0);
     if(r < 0) {
         return -1;
@@ -168,10 +168,10 @@
 {
     char cmd[64];
     int r;
-    
+
     sprintf(cmd, "download:%08x", size);
     r = _command_send(usb, cmd, data, size, 0);
-    
+
     if(r < 0) {
         return -1;
     } else {
diff --git a/fastboot/usb.h b/fastboot/usb.h
index 7a7d55b..d504ee2 100644
--- a/fastboot/usb.h
+++ b/fastboot/usb.h
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -42,20 +42,20 @@
     unsigned char dev_class;
     unsigned char dev_subclass;
     unsigned char dev_protocol;
-    
+
     unsigned char ifc_class;
     unsigned char ifc_subclass;
     unsigned char ifc_protocol;
 
     unsigned char has_bulk_in;
     unsigned char has_bulk_out;
-    
+
     unsigned char writable;
 
     char serial_number[256];
     char device_path[256];
 };
-  
+
 typedef int (*ifc_match_func)(usb_ifc_info *ifc);
 
 usb_handle *usb_open(ifc_match_func callback);
diff --git a/fastboot/usb_linux.c b/fastboot/usb_linux.c
index 19be51e..b7a9ca3 100644
--- a/fastboot/usb_linux.c
+++ b/fastboot/usb_linux.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -67,7 +67,7 @@
  */
 #define MAX_USBFS_BULK_SIZE (16 * 1024)
 
-struct usb_handle 
+struct usb_handle
 {
     char fname[64];
     int desc;
@@ -86,12 +86,12 @@
 static int check(void *_desc, int len, unsigned type, int size)
 {
     unsigned char *desc = _desc;
-    
+
     if(len < size) return -1;
     if(desc[0] < size) return -1;
     if(desc[0] > len) return -1;
     if(desc[1] != type) return -1;
-    
+
     return 0;
 }
 
@@ -104,7 +104,7 @@
     struct usb_interface_descriptor *ifc;
     struct usb_endpoint_descriptor *ept;
     struct usb_ifc_info info;
-    
+
     int in, out;
     unsigned i;
     unsigned e;
@@ -117,35 +117,38 @@
     dev = (void*) ptr;
     len -= dev->bLength;
     ptr += dev->bLength;
-    
+
     if(check(ptr, len, USB_DT_CONFIG, USB_DT_CONFIG_SIZE))
         return -1;
     cfg = (void*) ptr;
     len -= cfg->bLength;
     ptr += cfg->bLength;
-    
+
     info.dev_vendor = dev->idVendor;
     info.dev_product = dev->idProduct;
     info.dev_class = dev->bDeviceClass;
     info.dev_subclass = dev->bDeviceSubClass;
     info.dev_protocol = dev->bDeviceProtocol;
     info.writable = writable;
-    
+
     // read device serial number (if there is one)
     info.serial_number[0] = 0;
     if (dev->iSerialNumber) {
         struct usbdevfs_ctrltransfer  ctrl;
-        __u16 buffer[128];
+        // Keep it short enough because some bootloaders are borked if the URB len is > 255
+        // 128 is too big by 1.
+        __u16 buffer[127];
 
         memset(buffer, 0, sizeof(buffer));
 
         ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
         ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
         ctrl.wValue = (USB_DT_STRING << 8) | dev->iSerialNumber;
-        ctrl.wIndex = 0;
+        //language ID (en-us) for serial number string
+        ctrl.wIndex = 0x0409;
         ctrl.wLength = sizeof(buffer);
         ctrl.data = buffer;
-	ctrl.timeout = 50;
+        ctrl.timeout = 50;
 
         result = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
         if (result > 0) {
@@ -200,23 +203,23 @@
         ifc = (void*) ptr;
         len -= ifc->bLength;
         ptr += ifc->bLength;
-        
+
         in = -1;
         out = -1;
         info.ifc_class = ifc->bInterfaceClass;
         info.ifc_subclass = ifc->bInterfaceSubClass;
         info.ifc_protocol = ifc->bInterfaceProtocol;
-        
+
         for(e = 0; e < ifc->bNumEndpoints; e++) {
             if(check(ptr, len, USB_DT_ENDPOINT, USB_DT_ENDPOINT_SIZE))
                 return -1;
             ept = (void*) ptr;
             len -= ept->bLength;
             ptr += ept->bLength;
-    
+
             if((ept->bmAttributes & 0x03) != 0x02)
                 continue;
-            
+
             if(ept->bEndpointAddress & 0x80) {
                 in = ept->bEndpointAddress;
             } else {
@@ -226,7 +229,7 @@
 
         info.has_bulk_in = (in != -1);
         info.has_bulk_out = (out != -1);
-        
+
         if(callback(&info) == 0) {
             *ept_in_id = in;
             *ept_out_id = out;
@@ -244,25 +247,25 @@
     char busname[64], devname[64];
     char desc[1024];
     int n, in, out, ifc;
-    
+
     DIR *busdir, *devdir;
     struct dirent *de;
     int fd;
     int writable;
-    
+
     busdir = opendir(base);
     if(busdir == 0) return 0;
 
     while((de = readdir(busdir)) && (usb == 0)) {
         if(badname(de->d_name)) continue;
-        
+
         sprintf(busname, "%s/%s", base, de->d_name);
         devdir = opendir(busname);
         if(devdir == 0) continue;
-        
+
 //        DBG("[ scanning %s ]\n", busname);
         while((de = readdir(devdir)) && (usb == 0)) {
-            
+
             if(badname(de->d_name)) continue;
             sprintf(devname, "%s/%s", busname, de->d_name);
 
@@ -278,7 +281,7 @@
             }
 
             n = read(fd, desc, sizeof(desc));
-            
+
             if(filter_usb_device(fd, desc, n, writable, callback,
                                  &in, &out, &ifc) == 0) {
                 usb = calloc(1, sizeof(usb_handle));
@@ -315,13 +318,13 @@
     if(h->ep_out == 0) {
         return -1;
     }
-    
+
     if(len == 0) {
         bulk.ep = h->ep_out;
         bulk.len = 0;
         bulk.data = data;
         bulk.timeout = 0;
-        
+
         n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
         if(n != 0) {
             fprintf(stderr,"ERROR: n = %d, errno = %d (%s)\n",
@@ -330,16 +333,16 @@
         }
         return 0;
     }
-    
+
     while(len > 0) {
         int xfer;
         xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
-        
+
         bulk.ep = h->ep_out;
         bulk.len = xfer;
         bulk.data = data;
         bulk.timeout = 0;
-        
+
         n = ioctl(h->desc, USBDEVFS_BULK, &bulk);
         if(n != xfer) {
             DBG("ERROR: n = %d, errno = %d (%s)\n",
@@ -365,10 +368,10 @@
     if(h->ep_in == 0) {
         return -1;
     }
-    
+
     while(len > 0) {
         int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
-        
+
         bulk.ep = h->ep_in;
         bulk.len = xfer;
         bulk.data = data;
@@ -391,12 +394,12 @@
         count += n;
         len -= n;
         data += n;
-        
+
         if(n < xfer) {
             break;
         }
     }
-    
+
     return count;
 }
 
@@ -415,7 +418,7 @@
 int usb_close(usb_handle *h)
 {
     int fd;
-    
+
     fd = h->desc;
     h->desc = -1;
     if(fd >= 0) {
diff --git a/fastboot/usb_osx.c b/fastboot/usb_osx.c
index 605c8e2..1548ba8 100644
--- a/fastboot/usb_osx.c
+++ b/fastboot/usb_osx.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -55,7 +55,7 @@
     int success;
     ifc_match_func callback;
     usb_ifc_info info;
-    
+
     UInt8 bulkIn;
     UInt8 bulkOut;
     IOUSBInterfaceInterface190 **interface;
@@ -132,7 +132,7 @@
             // continue so we can try the next interface
             continue;
         }
-        
+
         /*
          * Now open the interface. This will cause the pipes
          * associated with the endpoints in the interface descriptor
@@ -149,7 +149,7 @@
          * use the interface. Maybe something needs to be done about
          * this situation.
          */
-        
+
         kr = (*interface)->USBInterfaceOpen(interface);
 
         if (kr != 0) {
@@ -158,7 +158,7 @@
             // continue so we can try the next interface
             continue;
         }
-        
+
         // Get the number of endpoints associated with this interface.
         kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
 
@@ -242,10 +242,10 @@
                     ERR("could not clear output pipe; result %x, ignoring....\n", kr);
                 }
             }
-            
+
             return 0;
         }
-        
+
 next_interface:
         (*interface)->USBInterfaceClose(interface);
         (*interface)->Release(interface);
@@ -285,7 +285,7 @@
         goto error;
     }
 
-    /* 
+    /*
      * We don't need the intermediate interface after the device interface
      * is created.
      */
@@ -339,14 +339,15 @@
         req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
         req.bRequest = kUSBRqGetDescriptor;
         req.wValue = (kUSBStringDesc << 8) | serialIndex;
-        req.wIndex = 0;
+        //language ID (en-us) for serial number string
+        req.wIndex = 0x0409;
         req.pData = buffer;
         req.wLength = sizeof(buffer);
         kr = (*dev)->DeviceRequest(dev, &req);
 
         if (kr == kIOReturnSuccess && req.wLenDone > 0) {
             int i, count;
-            
+
             // skip first word, and copy the rest to the serial string, changing shorts to bytes.
             count = (req.wLenDone - 1) / 2;
             for (i = 0; i < count; i++)
@@ -371,8 +372,8 @@
     if (dev != NULL) {
         (*dev)->Release(dev);
     }
-    
-    return -1;    
+
+    return -1;
 }
 
 
@@ -406,7 +407,7 @@
         ERR("Could not create iterator.");
         return -1;
     }
-    
+
     for (;;) {
         if (! IOIteratorIsValid(iterator)) {
             /*
@@ -416,7 +417,7 @@
             IOIteratorReset(iterator);
             continue;
         }
-                
+
         io_service_t device = IOIteratorNext(iterator);
 
         if (device == 0) {
diff --git a/fastboot/usb_windows.c b/fastboot/usb_windows.c
index 10317bf..7aa36b2 100644
--- a/fastboot/usb_windows.c
+++ b/fastboot/usb_windows.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -51,13 +51,13 @@
 struct usb_handle {
     /// Handle to USB interface
     ADBAPIHANDLE  adb_interface;
-    
+
     /// Handle to USB read pipe (endpoint)
     ADBAPIHANDLE  adb_read_pipe;
-    
+
     /// Handle to USB write pipe (endpoint)
     ADBAPIHANDLE  adb_write_pipe;
-    
+
     /// Interface name
     char*         interface_name;
 };
@@ -303,7 +303,7 @@
     info.ifc_subclass = interf_desc.bInterfaceSubClass;
     info.ifc_protocol = interf_desc.bInterfaceProtocol;
     info.writable = 1;
-    
+
     // read serial number (if there is one)
     unsigned long serial_number_len = sizeof(info.serial_number);
     if (!AdbGetSerialNumber(handle->adb_interface, info.serial_number,
diff --git a/fastboot/usbtest.c b/fastboot/usbtest.c
index e34d7e6..b8fb9e2 100644
--- a/fastboot/usbtest.c
+++ b/fastboot/usbtest.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -38,11 +38,11 @@
 static unsigned arg_size = 4096;
 static unsigned arg_count = 4096;
 
-long long NOW(void) 
+long long NOW(void)
 {
     struct timeval tv;
     gettimeofday(&tv, 0);
-    
+
     return (((long long) tv.tv_sec) * ((long long) 1000000)) +
         (((long long) tv.tv_usec));
 }
@@ -110,7 +110,7 @@
     int i;
     unsigned char buf[4096];
     long long t0, t1;
-    
+
     t0 = NOW();
     for(i = 0; i < arg_count; i++) {
         if(usb_read(usb, buf, arg_size) != arg_size) {
@@ -123,7 +123,7 @@
     return 0;
 }
 
-struct 
+struct
 {
     const char *cmd;
     ifc_match_func match;
@@ -179,12 +179,12 @@
 {
     usb_handle *usb;
     int i;
-    
+
     if(argc < 2)
         return usage();
 
     if(argc > 2) {
-        if(process_args(argc - 2, argv + 2)) 
+        if(process_args(argc - 2, argv + 2))
             return -1;
     }
 
diff --git a/fastboot/util_linux.c b/fastboot/util_linux.c
index 912e16f..91c3776 100644
--- a/fastboot/util_linux.c
+++ b/fastboot/util_linux.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
@@ -38,7 +38,7 @@
 {
     char proc[64];
     char *x;
-    
+
     sprintf(proc, "/proc/%d/exe", getpid());
     int err = readlink(proc, path, PATH_MAX - 1);
 
diff --git a/fastboot/util_osx.c b/fastboot/util_osx.c
index b43e316..26b832a 100644
--- a/fastboot/util_osx.c
+++ b/fastboot/util_osx.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
diff --git a/fastboot/util_windows.c b/fastboot/util_windows.c
index 37077a4..c3d545c 100644
--- a/fastboot/util_windows.c
+++ b/fastboot/util_windows.c
@@ -9,7 +9,7 @@
  *    notice, this list of conditions and the following disclaimer.
  *  * Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,7 +19,7 @@
  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
diff --git a/fs_mgr/Android.mk b/fs_mgr/Android.mk
new file mode 100644
index 0000000..7c66f6a
--- /dev/null
+++ b/fs_mgr/Android.mk
@@ -0,0 +1,33 @@
+# Copyright 2011 The Android Open Source Project
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= fs_mgr.c
+
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+
+LOCAL_MODULE:= libfs_mgr
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+
+include $(BUILD_STATIC_LIBRARY)
+
+
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= fs_mgr_main.c
+
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+
+LOCAL_MODULE:= fs_mgr
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_FORCE_STATIC_EXECUTABLE := true
+LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)/sbin
+LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_UNSTRIPPED)
+
+LOCAL_STATIC_LIBRARIES := libfs_mgr libcutils libc
+
+include $(BUILD_EXECUTABLE)
+
diff --git a/fs_mgr/fs_mgr.c b/fs_mgr/fs_mgr.c
new file mode 100644
index 0000000..0361ab8
--- /dev/null
+++ b/fs_mgr/fs_mgr.c
@@ -0,0 +1,611 @@
+/*
+ * Copyright (C) 2012 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.
+ */
+
+/* TO DO:
+ *   1. Re-direct fsck output to the kernel log?
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <ctype.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <libgen.h>
+#include <time.h>
+
+#include <private/android_filesystem_config.h>
+#include <cutils/partition_utils.h>
+#include <cutils/properties.h>
+
+#include "fs_mgr_priv.h"
+
+#define KEY_LOC_PROP   "ro.crypto.keyfile.userdata"
+#define KEY_IN_FOOTER  "footer"
+
+#define E2FSCK_BIN      "/system/bin/e2fsck"
+
+struct flag_list {
+    const char *name;
+    unsigned flag;
+};
+
+static struct flag_list mount_flags[] = {
+    { "noatime",    MS_NOATIME },
+    { "noexec",     MS_NOEXEC },
+    { "nosuid",     MS_NOSUID },
+    { "nodev",      MS_NODEV },
+    { "nodiratime", MS_NODIRATIME },
+    { "ro",         MS_RDONLY },
+    { "rw",         0 },
+    { "remount",    MS_REMOUNT },
+    { "defaults",   0 },
+    { 0,            0 },
+};
+
+static struct flag_list fs_mgr_flags[] = {
+    { "wait",        MF_WAIT },
+    { "check",       MF_CHECK },
+    { "encryptable=",MF_CRYPT },
+    { "defaults",    0 },
+    { 0,             0 },
+};
+
+/*
+ * gettime() - returns the time in seconds of the system's monotonic clock or
+ * zero on error.
+ */
+static time_t gettime(void)
+{
+    struct timespec ts;
+    int ret;
+
+    ret = clock_gettime(CLOCK_MONOTONIC, &ts);
+    if (ret < 0) {
+        ERROR("clock_gettime(CLOCK_MONOTONIC) failed: %s\n", strerror(errno));
+        return 0;
+    }
+
+    return ts.tv_sec;
+}
+
+static int wait_for_file(const char *filename, int timeout)
+{
+    struct stat info;
+    time_t timeout_time = gettime() + timeout;
+    int ret = -1;
+
+    while (gettime() < timeout_time && ((ret = stat(filename, &info)) < 0))
+        usleep(10000);
+
+    return ret;
+}
+
+static int parse_flags(char *flags, struct flag_list *fl, char **key_loc,
+                       char *fs_options, int fs_options_len)
+{
+    int f = 0;
+    int i;
+    char *p;
+    char *savep;
+
+    /* initialize key_loc to null, if we find an MF_CRYPT flag,
+     * then we'll set key_loc to the proper value */
+    if (key_loc) {
+        *key_loc = NULL;
+    }
+    /* initialize fs_options to the null string */
+    if (fs_options && (fs_options_len > 0)) {
+        fs_options[0] = '\0';
+    }
+
+    p = strtok_r(flags, ",", &savep);
+    while (p) {
+        /* Look for the flag "p" in the flag list "fl"
+         * If not found, the loop exits with fl[i].name being null.
+         */
+        for (i = 0; fl[i].name; i++) {
+            if (!strncmp(p, fl[i].name, strlen(fl[i].name))) {
+                f |= fl[i].flag;
+                if ((fl[i].flag == MF_CRYPT) && key_loc) {
+                    /* The encryptable flag is followed by an = and the
+                     * location of the keys.  Get it and return it.
+                     */
+                    *key_loc = strdup(strchr(p, '=') + 1);
+                }
+                break;
+            }
+        }
+
+        if (!fl[i].name) {
+            if (fs_options) {
+                /* It's not a known flag, so it must be a filesystem specific
+                 * option.  Add it to fs_options if it was passed in.
+                 */
+                strlcat(fs_options, p, fs_options_len);
+                strlcat(fs_options, ",", fs_options_len);
+            } else {
+                /* fs_options was not passed in, so if the flag is unknown
+                 * it's an error.
+                 */
+                ERROR("Warning: unknown flag %s\n", p);
+            }
+        }
+        p = strtok_r(NULL, ",", &savep);
+    }
+
+out:
+    if (fs_options && fs_options[0]) {
+        /* remove the last trailing comma from the list of options */
+        fs_options[strlen(fs_options) - 1] = '\0';
+    }
+
+    return f;
+}
+
+/* Read a line of text till the next newline character.
+ * If no newline is found before the buffer is full, continue reading till a new line is seen,
+ * then return an empty buffer.  This effectively ignores lines that are too long.
+ * On EOF, return null.
+ */
+static char *getline(char *buf, int size, FILE *file)
+{
+    int cnt = 0;
+    int eof = 0;
+    int eol = 0;
+    int c;
+
+    if (size < 1) {
+        return NULL;
+    }
+
+    while (cnt < (size - 1)) {
+        c = getc(file);
+        if (c == EOF) {
+            eof = 1;
+            break;
+        }
+
+        *(buf + cnt) = c;
+        cnt++;
+
+        if (c == '\n') {
+            eol = 1;
+            break;
+        }
+    }
+
+    /* Null terminate what we've read */
+    *(buf + cnt) = '\0';
+
+    if (eof) {
+        if (cnt) {
+            return buf;
+        } else {
+            return NULL;
+        }
+    } else if (eol) {
+        return buf;
+    } else {
+        /* The line is too long.  Read till a newline or EOF.
+         * If EOF, return null, if newline, return an empty buffer.
+         */
+        while(1) {
+            c = getc(file);
+            if (c == EOF) {
+                return NULL;
+            } else if (c == '\n') {
+                *buf = '\0';
+                return buf;
+            }
+        }
+    }
+}
+
+static struct fstab_rec *read_fstab(char *fstab_path)
+{
+    FILE *fstab_file;
+    int cnt, entries;
+    int len;
+    char line[256];
+    const char *delim = " \t";
+    char *save_ptr, *p;
+    struct fstab_rec *fstab;
+    char *key_loc;
+#define FS_OPTIONS_LEN 1024
+    char tmp_fs_options[FS_OPTIONS_LEN];
+
+    fstab_file = fopen(fstab_path, "r");
+    if (!fstab_file) {
+        ERROR("Cannot open file %s\n", fstab_path);
+        return 0;
+    }
+
+    entries = 0;
+    while (getline(line, sizeof(line), fstab_file)) {
+        /* if the last character is a newline, shorten the string by 1 byte */
+        len = strlen(line);
+        if (line[len - 1] == '\n') {
+            line[len - 1] = '\0';
+        }
+        /* Skip any leading whitespace */
+        p = line;
+        while (isspace(*p)) {
+            p++;
+        }
+        /* ignore comments or empty lines */
+        if (*p == '#' || *p == '\0')
+            continue;
+        entries++;
+    }
+
+    if (!entries) {
+        ERROR("No entries found in fstab\n");
+        return 0;
+    }
+
+    fstab = calloc(entries + 1, sizeof(struct fstab_rec));
+
+    fseek(fstab_file, 0, SEEK_SET);
+
+    cnt = 0;
+    while (getline(line, sizeof(line), fstab_file)) {
+        /* if the last character is a newline, shorten the string by 1 byte */
+        len = strlen(line);
+        if (line[len - 1] == '\n') {
+            line[len - 1] = '\0';
+        }
+
+        /* Skip any leading whitespace */
+        p = line;
+        while (isspace(*p)) {
+            p++;
+        }
+        /* ignore comments or empty lines */
+        if (*p == '#' || *p == '\0')
+            continue;
+
+        /* If a non-comment entry is greater than the size we allocated, give an
+         * error and quit.  This can happen in the unlikely case the file changes
+         * between the two reads.
+         */
+        if (cnt >= entries) {
+            ERROR("Tried to process more entries than counted\n");
+            break;
+        }
+
+        if (!(p = strtok_r(line, delim, &save_ptr))) {
+            ERROR("Error parsing mount source\n");
+            return 0;
+        }
+        fstab[cnt].blk_dev = strdup(p);
+
+        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
+            ERROR("Error parsing mnt_point\n");
+            return 0;
+        }
+        fstab[cnt].mnt_point = strdup(p);
+
+        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
+            ERROR("Error parsing fs_type\n");
+            return 0;
+        }
+        fstab[cnt].type = strdup(p);
+
+        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
+            ERROR("Error parsing mount_flags\n");
+            return 0;
+        }
+        tmp_fs_options[0] = '\0';
+        fstab[cnt].flags = parse_flags(p, mount_flags, 0, tmp_fs_options, FS_OPTIONS_LEN);
+
+        /* fs_options are optional */
+        if (tmp_fs_options[0]) {
+            fstab[cnt].fs_options = strdup(tmp_fs_options);
+        } else {
+            fstab[cnt].fs_options = NULL;
+        }
+
+        if (!(p = strtok_r(NULL, delim, &save_ptr))) {
+            ERROR("Error parsing fs_mgr_options\n");
+            return 0;
+        }
+        fstab[cnt].fs_mgr_flags = parse_flags(p, fs_mgr_flags, &key_loc, 0, 0);
+        fstab[cnt].key_loc = key_loc;
+
+        cnt++;
+    }
+    fclose(fstab_file);
+
+    return fstab;
+}
+
+static void free_fstab(struct fstab_rec *fstab)
+{
+    int i = 0;
+
+    while (fstab[i].blk_dev) {
+        /* Free the pointers return by strdup(3) */
+        free(fstab[i].blk_dev);
+        free(fstab[i].mnt_point);
+        free(fstab[i].type);
+        free(fstab[i].fs_options);
+        free(fstab[i].key_loc);
+
+        i++;
+    }
+
+    /* Free the actual fstab array created by calloc(3) */
+    free(fstab);
+}
+
+static void check_fs(char *blk_dev, char *type)
+{
+    pid_t pid;
+    int status;
+
+    /* Check for the types of filesystems we know how to check */
+    if (!strcmp(type, "ext2") || !strcmp(type, "ext3") || !strcmp(type, "ext4")) {
+        INFO("Running %s on %s\n", E2FSCK_BIN, blk_dev);
+        pid = fork();
+        if (pid > 0) {
+            /* Parent, wait for the child to return */
+            waitpid(pid, &status, 0);
+        } else if (pid == 0) {
+            /* child, run checker */
+            execlp(E2FSCK_BIN, E2FSCK_BIN, "-y", blk_dev, (char *)NULL);
+
+            /* Only gets here on error */
+            ERROR("Cannot run fs_mgr binary %s\n", E2FSCK_BIN);
+        } else {
+            /* No need to check for error in fork, we can't really handle it now */
+            ERROR("Fork failed trying to run %s\n", E2FSCK_BIN);
+        }
+    }
+
+    return;
+}
+
+static void remove_trailing_slashes(char *n)
+{
+    int len;
+
+    len = strlen(n) - 1;
+    while ((*(n + len) == '/') && len) {
+      *(n + len) = '\0';
+      len--;
+    }
+}
+
+static int fs_match(char *in1, char *in2)
+{
+    char *n1;
+    char *n2;
+    int ret;
+
+    n1 = strdup(in1);
+    n2 = strdup(in2);
+
+    remove_trailing_slashes(n1);
+    remove_trailing_slashes(n2);
+
+    ret = !strcmp(n1, n2);
+
+    free(n1);
+    free(n2);
+
+    return ret;
+}
+
+int fs_mgr_mount_all(char *fstab_file)
+{
+    int i = 0;
+    int encrypted = 0;
+    int ret = -1;
+    int mret;
+    struct fstab_rec *fstab = 0;
+
+    if (!(fstab = read_fstab(fstab_file))) {
+        return ret;
+    }
+
+    for (i = 0; fstab[i].blk_dev; i++) {
+        if (fstab[i].fs_mgr_flags & MF_WAIT) {
+            wait_for_file(fstab[i].blk_dev, WAIT_TIMEOUT);
+        }
+
+        if (fstab[i].fs_mgr_flags & MF_CHECK) {
+            check_fs(fstab[i].blk_dev, fstab[i].type);
+        }
+
+        mret = mount(fstab[i].blk_dev, fstab[i].mnt_point, fstab[i].type,
+                     fstab[i].flags, fstab[i].fs_options);
+        if (!mret) {
+            /* Success!  Go get the next one */
+            continue;
+        }
+
+        /* mount(2) returned an error, check if it's encrypted and deal with it */
+        if ((fstab[i].fs_mgr_flags & MF_CRYPT) && !partition_wiped(fstab[i].blk_dev)) {
+            /* Need to mount a tmpfs at this mountpoint for now, and set
+             * properties that vold will query later for decrypting
+             */
+            if (mount("tmpfs", fstab[i].mnt_point, "tmpfs",
+                  MS_NOATIME | MS_NOSUID | MS_NODEV, CRYPTO_TMPFS_OPTIONS) < 0) {
+                ERROR("Cannot mount tmpfs filesystem for encrypted fs at %s\n",
+                        fstab[i].mnt_point);
+                goto out;
+            }
+            encrypted = 1;
+        } else {
+            ERROR("Cannot mount filesystem on %s at %s\n",
+                    fstab[i].blk_dev, fstab[i].mnt_point);
+            goto out;
+        }
+    }
+
+    if (encrypted) {
+        ret = 1;
+    } else {
+        ret = 0;
+    }
+
+out:
+    free_fstab(fstab);
+    return ret;
+}
+
+/* If tmp_mnt_point is non-null, mount the filesystem there.  This is for the
+ * tmp mount we do to check the user password
+ */
+int fs_mgr_do_mount(char *fstab_file, char *n_name, char *n_blk_dev, char *tmp_mnt_point)
+{
+    int i = 0;
+    int ret = -1;
+    struct fstab_rec *fstab = 0;
+    char *m;
+
+    if (!(fstab = read_fstab(fstab_file))) {
+        return ret;
+    }
+
+    for (i = 0; fstab[i].blk_dev; i++) {
+        if (!fs_match(fstab[i].mnt_point, n_name)) {
+            continue;
+        }
+
+        /* We found our match */
+        /* First check the filesystem if requested */
+        if (fstab[i].fs_mgr_flags & MF_WAIT) {
+            wait_for_file(fstab[i].blk_dev, WAIT_TIMEOUT);
+        }
+
+        if (fstab[i].fs_mgr_flags & MF_CHECK) {
+            check_fs(fstab[i].blk_dev, fstab[i].type);
+        }
+
+        /* Now mount it where requested */
+        if (tmp_mnt_point) {
+            m = tmp_mnt_point;
+        } else {
+            m = fstab[i].mnt_point;
+        }
+        if (mount(n_blk_dev, m, fstab[i].type,
+                  fstab[i].flags, fstab[i].fs_options)) {
+            ERROR("Cannot mount filesystem on %s at %s\n",
+                    n_blk_dev, m);
+            goto out;
+        } else {
+            ret = 0;
+            goto out;
+        }
+    }
+
+    /* We didn't find a match, say so and return an error */
+    ERROR("Cannot find mount point %s in fstab\n", fstab[i].mnt_point);
+
+out:
+    free_fstab(fstab);
+    return ret;
+}
+
+/*
+ * mount a tmpfs filesystem at the given point.
+ * return 0 on success, non-zero on failure.
+ */
+int fs_mgr_do_tmpfs_mount(char *n_name)
+{
+    int ret;
+
+    ret = mount("tmpfs", n_name, "tmpfs",
+                MS_NOATIME | MS_NOSUID | MS_NODEV, CRYPTO_TMPFS_OPTIONS);
+    if (ret < 0) {
+        ERROR("Cannot mount tmpfs filesystem at %s\n", n_name);
+        return -1;
+    }
+
+    /* Success */
+    return 0;
+}
+
+int fs_mgr_unmount_all(char *fstab_file)
+{
+    int i = 0;
+    int ret = 0;
+    struct fstab_rec *fstab = 0;
+
+    if (!(fstab = read_fstab(fstab_file))) {
+        return -1;
+    }
+
+    while (fstab[i].blk_dev) {
+        if (umount(fstab[i].mnt_point)) {
+            ERROR("Cannot unmount filesystem at %s\n", fstab[i].mnt_point);
+            ret = -1;
+        }
+        i++;
+    }
+
+    free_fstab(fstab);
+    return ret;
+}
+/*
+ * key_loc must be at least PROPERTY_VALUE_MAX bytes long
+ *
+ * real_blk_dev must be at least PROPERTY_VALUE_MAX bytes long
+ */
+int fs_mgr_get_crypt_info(char *fstab_file, char *key_loc, char *real_blk_dev, int size)
+{
+    int i = 0;
+    struct fstab_rec *fstab = 0;
+
+    if (!(fstab = read_fstab(fstab_file))) {
+        return -1;
+    }
+    /* Initialize return values to null strings */
+    if (key_loc) {
+        *key_loc = '\0';
+    }
+    if (real_blk_dev) {
+        *real_blk_dev = '\0';
+    }
+
+    /* Look for the encryptable partition to find the data */
+    for (i = 0; fstab[i].blk_dev; i++) {
+        if (!(fstab[i].fs_mgr_flags & MF_CRYPT)) {
+            continue;
+        }
+
+        /* We found a match */
+        if (key_loc) {
+            strlcpy(key_loc, fstab[i].key_loc, size);
+        }
+        if (real_blk_dev) {
+            strlcpy(real_blk_dev, fstab[i].blk_dev, size);
+        }
+        break;
+    }
+
+    free_fstab(fstab);
+    return 0;
+}
+
diff --git a/fs_mgr/fs_mgr_main.c b/fs_mgr/fs_mgr_main.c
new file mode 100644
index 0000000..81febf1
--- /dev/null
+++ b/fs_mgr/fs_mgr_main.c
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2012 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 <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <libgen.h>
+#include "fs_mgr_priv.h"
+
+char *me = "";
+
+static void usage(void)
+{
+    ERROR("%s: usage: %s <-a | -n mnt_point blk_dev | -u> <fstab_file>\n", me, me);
+    exit(1);
+}
+
+/* Parse the command line.  If an error is encountered, print an error message
+ * and exit the program, do not return to the caller.
+ * Return the number of argv[] entries consumed.
+ */
+static void parse_options(int argc, char *argv[], int *a_flag, int *u_flag, int *n_flag,
+                     char **n_name, char **n_blk_dev)
+{
+    me = basename(strdup(argv[0]));
+
+    if (argc <= 1) {
+        usage();
+    }
+
+    if (!strcmp(argv[1], "-a")) {
+        if (argc != 3) {
+            usage();
+        }
+        *a_flag = 1;
+    }
+    if (!strcmp(argv[1], "-n")) {
+        if (argc != 5) {
+            usage();
+        }
+        *n_flag = 1;
+        *n_name = argv[2];
+        *n_blk_dev = argv[3];
+    }
+    if (!strcmp(argv[1], "-u")) {
+        if (argc != 3) {
+            usage();
+        }
+        *u_flag = 1;
+    }
+
+    /* If no flag is specified, it's an error */
+    if (!(*a_flag | *n_flag | *u_flag)) {
+        usage();
+    }
+
+    /* If more than one flag is specified, it's an error */
+    if ((*a_flag + *n_flag + *u_flag) > 1) {
+        usage();
+    }
+
+    return;
+}
+
+int main(int argc, char *argv[])
+{
+    int a_flag=0;
+    int u_flag=0;
+    int n_flag=0;
+    char *n_name;
+    char *n_blk_dev;
+    char *fstab;
+
+    klog_init();
+    klog_set_level(6);
+
+    parse_options(argc, argv, &a_flag, &u_flag, &n_flag, &n_name, &n_blk_dev);
+
+    /* The name of the fstab file is last, after the option */
+    fstab = argv[argc - 1];
+
+    if (a_flag) {
+        return fs_mgr_mount_all(fstab);
+    } else if (n_flag) {
+        return fs_mgr_do_mount(fstab, n_name, n_blk_dev, 0);
+    } else if (u_flag) {
+        return fs_mgr_unmount_all(fstab);
+    } else {
+        ERROR("%s: Internal error, unknown option\n", me);
+        exit(1);
+    }
+
+    /* Should not get here */
+    exit(1);
+}
+
diff --git a/fs_mgr/fs_mgr_priv.h b/fs_mgr/fs_mgr_priv.h
new file mode 100644
index 0000000..175fdab
--- /dev/null
+++ b/fs_mgr/fs_mgr_priv.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2012 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 __CORE_FS_MGR_PRIV_H
+#define __CORE_FS_MGR_PRIV_H
+
+#include <cutils/klog.h>
+#include <fs_mgr.h>
+
+#define INFO(x...)    KLOG_INFO("fs_mgr", x)
+#define ERROR(x...)   KLOG_ERROR("fs_mgr", x)
+
+#define CRYPTO_TMPFS_OPTIONS "size=128m,mode=0771,uid=1000,gid=1000"
+
+struct fstab_rec {
+    char *blk_dev;
+    char *mnt_point;
+    char *type;
+    unsigned long flags;
+    char *fs_options;
+    int fs_mgr_flags;
+    char *key_loc;
+};
+
+#define WAIT_TIMEOUT 5
+
+/* fstab has the following format:
+ *
+ * Any line starting with a # is a comment and ignored
+ *
+ * Any blank line is ignored
+ *
+ * All other lines must be in this format:
+ *   <source>  <mount_point> <fs_type> <mount_flags> <fs_options> <fs_mgr_options>
+ *
+ *   <mount_flags> is a comma separated list of flags that can be passed to the
+ *                 mount command.  The list includes noatime, nosuid, nodev, nodiratime,
+ *                 ro, rw, remount, defaults.
+ *
+ *   <fs_options> is a comma separated list of options accepted by the filesystem being
+ *                mounted.  It is passed directly to mount without being parsed
+ *
+ *   <fs_mgr_options> is a comma separated list of flags that control the operation of
+ *                     the fs_mgr program.  The list includes "wait", which will wait till
+ *                     the <source> file exists, and "check", which requests that the fs_mgr 
+ *                     run an fscheck program on the <source> before mounting the filesystem.
+ *                     If check is specifed on a read-only filesystem, it is ignored.
+ *                     Also, "encryptable" means that filesystem can be encrypted.
+ *                     The "encryptable" flag _MUST_ be followed by a : and a string which
+ *                     is the location of the encryption keys.  I can either be a path
+ *                     to a file or partition which contains the keys, or the word "footer"
+ *                     which means the keys are in the last 16 Kbytes of the partition
+ *                     containing the filesystem.
+ *
+ * When the fs_mgr is requested to mount all filesystems, it will first mount all the
+ * filesystems that do _NOT_ specify check (including filesystems that are read-only and
+ * specify check, because check is ignored in that case) and then it will check and mount
+ * filesystem marked with check.
+ *
+ */
+
+#define MF_WAIT      0x1
+#define MF_CHECK     0x2
+#define MF_CRYPT     0x4
+
+#endif /* __CORE_FS_MGR_PRIV_H */
+
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
new file mode 100644
index 0000000..76abb83
--- /dev/null
+++ b/fs_mgr/include/fs_mgr.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2012 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 __CORE_FS_MGR_H
+#define __CORE_FS_MGR_H
+
+int fs_mgr_mount_all(char *fstab_file);
+int fs_mgr_do_mount(char *fstab_file, char *n_name, char *n_blk_dev, char *tmp_mnt_point);
+int fs_mgr_do_tmpfs_mount(char *n_name);
+int fs_mgr_unmount_all(char *fstab_file);
+int fs_mgr_get_crypt_info(char *fstab_file, char *key_loc, char *real_blk_dev, int size);
+
+#endif /* __CORE_FS_MGR_H */
+
diff --git a/include/arch/darwin-x86/AndroidConfig.h b/include/arch/darwin-x86/AndroidConfig.h
index c8ccc7e..9da01c5 100644
--- a/include/arch/darwin-x86/AndroidConfig.h
+++ b/include/arch/darwin-x86/AndroidConfig.h
@@ -109,7 +109,7 @@
 /*
  * Define this if we have localtime_r().
  */
-#define HAVE_LOCALTIME_R
+#define HAVE_LOCALTIME_R 1
 
 /*
  * Define this if we have gethostbyname_r().
@@ -175,7 +175,7 @@
  * with a memory address.  If not defined, stack crawls will not have symbolic
  * information.
  */
-#define HAVE_DLADDR 0
+#define HAVE_DLADDR 1
 
 /*
  * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
@@ -305,4 +305,14 @@
  */
 #define HAVE_PRINTF_ZD 1
 
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
+ */
+#define HAVE_BSD_QSORT_R 1
+
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
+ */
+#define HAVE_GNU_QSORT_R 0
+
 #endif /*_ANDROID_CONFIG_H*/
diff --git a/include/arch/freebsd-x86/AndroidConfig.h b/include/arch/freebsd-x86/AndroidConfig.h
index d828bd5..4bc5559 100644
--- a/include/arch/freebsd-x86/AndroidConfig.h
+++ b/include/arch/freebsd-x86/AndroidConfig.h
@@ -114,7 +114,7 @@
 /*
  * Define this if we have localtime_r().
  */
-#define HAVE_LOCALTIME_R
+#define HAVE_LOCALTIME_R 1
 
 /*
  * Define this if we have gethostbyname_r().
@@ -363,4 +363,14 @@
  */
 #define HAVE_PRINTF_ZD 1
 
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
+ */
+#define HAVE_BSD_QSORT_R 1
+
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
+ */
+#define HAVE_GNU_QSORT_R 0
+
 #endif /*_ANDROID_CONFIG_H*/
diff --git a/include/arch/linux-arm/AndroidConfig.h b/include/arch/linux-arm/AndroidConfig.h
index cae112b..233752b 100644
--- a/include/arch/linux-arm/AndroidConfig.h
+++ b/include/arch/linux-arm/AndroidConfig.h
@@ -96,7 +96,7 @@
 /*
  * Define this if you have <termio.h>
  */
-#define  HAVE_TERMIO_H
+#define  HAVE_TERMIO_H 1
 
 /*
  * Define this if you have <sys/sendfile.h>
@@ -111,7 +111,7 @@
 /*
  * Define this if you have sys/uio.h
  */
-#define  HAVE_SYS_UIO_H
+#define  HAVE_SYS_UIO_H 1
 
 /*
  * Define this if your platforms implements symbolic links
@@ -122,7 +122,7 @@
 /*
  * Define this if we have localtime_r().
  */
-/* #define HAVE_LOCALTIME_R */
+/* #define HAVE_LOCALTIME_R 1 */
 
 /*
  * Define this if we have gethostbyname_r().
@@ -361,4 +361,14 @@
  */
 #define HAVE_PRINTF_ZD 1
 
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
+ */
+#define HAVE_BSD_QSORT_R 0
+
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
+ */
+#define HAVE_GNU_QSORT_R 0
+
 #endif /* _ANDROID_CONFIG_H */
diff --git a/include/arch/linux-ppc/AndroidConfig.h b/include/arch/linux-ppc/AndroidConfig.h
index 00706dc..ae2569b 100644
--- a/include/arch/linux-ppc/AndroidConfig.h
+++ b/include/arch/linux-ppc/AndroidConfig.h
@@ -83,7 +83,7 @@
 /*
  * Define this if you have <termio.h>
  */
-#define  HAVE_TERMIO_H
+#define  HAVE_TERMIO_H 1
 
 /*
  * Define this if you have <sys/sendfile.h>
@@ -98,7 +98,7 @@
 /*
  * Define this if you have sys/uio.h
  */
-#define  HAVE_SYS_UIO_H
+#define  HAVE_SYS_UIO_H 1
 
 /*
  * Define this if your platforms implements symbolic links
@@ -109,7 +109,7 @@
 /*
  * Define this if we have localtime_r().
  */
-#define HAVE_LOCALTIME_R
+#define HAVE_LOCALTIME_R 1
 
 /*
  * Define this if we have gethostbyname_r().
@@ -323,4 +323,14 @@
  */
 #define HAVE_PREAD 1
 
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
+ */
+#define HAVE_BSD_QSORT_R 0
+
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
+ */
+#define HAVE_GNU_QSORT_R 1
+
 #endif /*_ANDROID_CONFIG_H*/
diff --git a/include/arch/linux-sh/AndroidConfig.h b/include/arch/linux-sh/AndroidConfig.h
index 5562eae..818b628 100644
--- a/include/arch/linux-sh/AndroidConfig.h
+++ b/include/arch/linux-sh/AndroidConfig.h
@@ -96,7 +96,7 @@
 /*
  * Define this if you have <termio.h>
  */
-#define  HAVE_TERMIO_H
+#define  HAVE_TERMIO_H 1
 
 /*
  * Define this if you have <sys/sendfile.h>
@@ -111,7 +111,7 @@
 /*
  * Define this if you have sys/uio.h
  */
-#define  HAVE_SYS_UIO_H
+#define  HAVE_SYS_UIO_H 1
 
 /*
  * Define this if your platforms implements symbolic links
@@ -122,7 +122,7 @@
 /*
  * Define this if we have localtime_r().
  */
-/* #define HAVE_LOCALTIME_R */
+/* #define HAVE_LOCALTIME_R 1 */
 
 /*
  * Define this if we have gethostbyname_r().
@@ -366,4 +366,14 @@
  */
 #define HAVE_PRINTF_ZD 1
 
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
+ */
+#define HAVE_BSD_QSORT_R 0
+
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
+ */
+#define HAVE_GNU_QSORT_R 0
+
 #endif /* _ANDROID_CONFIG_H */
diff --git a/include/arch/linux-x86/AndroidConfig.h b/include/arch/linux-x86/AndroidConfig.h
index 7dcaa98..431a54b 100644
--- a/include/arch/linux-x86/AndroidConfig.h
+++ b/include/arch/linux-x86/AndroidConfig.h
@@ -83,7 +83,7 @@
 /*
  * Define this if you have <termio.h>
  */
-#define  HAVE_TERMIO_H
+#define  HAVE_TERMIO_H 1
 
 /*
  * Define this if you have <sys/sendfile.h>
@@ -98,7 +98,7 @@
 /*
  * Define this if you have sys/uio.h
  */
-#define  HAVE_SYS_UIO_H
+#define  HAVE_SYS_UIO_H 1
 
 /*
  * Define this if your platforms implements symbolic links
@@ -109,7 +109,7 @@
 /*
  * Define this if we have localtime_r().
  */
-#define HAVE_LOCALTIME_R
+#define HAVE_LOCALTIME_R 1
 
 /*
  * Define this if we have gethostbyname_r().
@@ -333,4 +333,18 @@
  */
 #define HAVE_PRINTF_ZD 1
 
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
+ */
+#define HAVE_BSD_QSORT_R 0
+
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
+ */
+#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8)
+#define HAVE_GNU_QSORT_R 1
+#else
+#define HAVE_GNU_QSORT_R 0
+#endif
+
 #endif /*_ANDROID_CONFIG_H*/
diff --git a/include/arch/target_linux-x86/AndroidConfig.h b/include/arch/target_linux-x86/AndroidConfig.h
index 05dd220..ab53892 100644
--- a/include/arch/target_linux-x86/AndroidConfig.h
+++ b/include/arch/target_linux-x86/AndroidConfig.h
@@ -108,7 +108,7 @@
 /*
  * Define this if we have localtime_r().
  */
-/* #define HAVE_LOCALTIME_R */
+/* #define HAVE_LOCALTIME_R 1 */
 
 /*
  * Define this if we have gethostbyname_r().
@@ -350,4 +350,14 @@
  */
 #define HAVE_PRINTF_ZD 1
 
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
+ */
+#define HAVE_BSD_QSORT_R 0
+
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
+ */
+#define HAVE_GNU_QSORT_R 0
+
 #endif /* _ANDROID_CONFIG_H */
diff --git a/include/arch/windows/AndroidConfig.h b/include/arch/windows/AndroidConfig.h
index ad890b4..0274da5 100644
--- a/include/arch/windows/AndroidConfig.h
+++ b/include/arch/windows/AndroidConfig.h
@@ -125,7 +125,7 @@
 /*
  * Define this if we have localtime_r().
  */
-/* #define HAVE_LOCALTIME_R */
+/* #define HAVE_LOCALTIME_R 1 */
 
 /*
  * Define this if we have gethostbyname_r().
@@ -338,4 +338,14 @@
  */
 /* #define HAVE_PRINTF_ZD 1 */
 
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
+ */
+#define HAVE_BSD_QSORT_R 0
+
+/*
+ * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
+ */
+#define HAVE_GNU_QSORT_R 0
+
 #endif /*_ANDROID_CONFIG_H*/
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..ea1d35f
--- /dev/null
+++ b/include/corkscrew/map_info.h
@@ -0,0 +1,68 @@
+/*
+ * 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>
+#include <stdint.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..0040c22
--- /dev/null
+++ b/include/corkscrew/ptrace.h
@@ -0,0 +1,121 @@
+/*
+ * 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>
+#include <stdint.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..4998750
--- /dev/null
+++ b/include/corkscrew/symbol_table.h
@@ -0,0 +1,59 @@
+/*
+ * 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 <stdint.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/list.h b/include/cutils/list.h
index eb5a3c8..3881fc9 100644
--- a/include/cutils/list.h
+++ b/include/cutils/list.h
@@ -19,6 +19,10 @@
 
 #include <stddef.h>
 
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
 struct listnode
 {
     struct listnode *next;
@@ -48,4 +52,8 @@
 #define list_head(list) ((list)->next)
 #define list_tail(list) ((list)->prev)
 
+#ifdef __cplusplus
+};
+#endif /* __cplusplus */
+
 #endif
diff --git a/include/cutils/log.h b/include/cutils/log.h
index 42d7382..878952e 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,23 +73,23 @@
 /*
  * 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
 #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
 #endif
@@ -97,56 +97,56 @@
 /*
  * 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__))
+#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 )
 #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__))
+#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 )
 #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__))
+#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 )
 #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__))
+#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 )
 #endif
 
@@ -156,11 +156,11 @@
  * 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
 #endif
 
@@ -168,32 +168,32 @@
  * 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)
+#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)
+#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)
+#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)
+#ifndef IF_ALOGE
+#define IF_ALOGE() IF_ALOG(LOG_ERROR, LOG_TAG)
 #endif
 
 
@@ -329,9 +329,9 @@
  * Assertion that generates a log message when the assertion fails.
  * Stripped out of release builds.  Uses the current LOG_TAG.
  */
-#ifndef LOG_ASSERT
-#define LOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ## __VA_ARGS__)
-//#define LOG_ASSERT(cond) LOG_FATAL_IF(!(cond), "Assertion failed: " #cond)
+#ifndef ALOG_ASSERT
+#define ALOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ## __VA_ARGS__)
+//#define ALOG_ASSERT(cond) LOG_FATAL_IF(!(cond), "Assertion failed: " #cond)
 #endif
 
 // ---------------------------------------------------------------------
@@ -340,12 +340,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
 
@@ -368,8 +368,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
 
@@ -424,7 +424,7 @@
     __android_log_vprint(prio, tag, fmt)
 
 /* XXX Macros to work around syntax errors in places where format string
- * arg is not passed to LOG_ASSERT, LOG_ALWAYS_FATAL or LOG_ALWAYS_FATAL_IF
+ * arg is not passed to ALOG_ASSERT, LOG_ALWAYS_FATAL or LOG_ALWAYS_FATAL_IF
  * (happens only in debug builds).
  */
 
diff --git a/include/cutils/logger.h b/include/cutils/logger.h
index b60f7ad..04f3fb0 100644
--- a/include/cutils/logger.h
+++ b/include/cutils/logger.h
@@ -12,6 +12,11 @@
 
 #include <stdint.h>
 
+/*
+ * The userspace structure for version 1 of the logger_entry ABI.
+ * This structure is returned to userspace by the kernel logger
+ * driver unless an upgrade to a newer ABI version is requested.
+ */
 struct logger_entry {
     uint16_t    len;    /* length of the payload */
     uint16_t    __pad;  /* no matter what, we get 2 bytes of padding */
@@ -22,14 +27,41 @@
     char        msg[0]; /* the entry's payload */
 };
 
+/*
+ * The userspace structure for version 2 of the logger_entry ABI.
+ * This structure is returned to userspace if ioctl(LOGGER_SET_VERSION)
+ * is called with version==2
+ */
+struct logger_entry_v2 {
+    uint16_t    len;       /* length of the payload */
+    uint16_t    hdr_size;  /* sizeof(struct logger_entry_v2) */
+    int32_t     pid;       /* generating process's pid */
+    int32_t     tid;       /* generating process's tid */
+    int32_t     sec;       /* seconds since Epoch */
+    int32_t     nsec;      /* nanoseconds */
+    uint32_t    euid;      /* effective UID of logger */
+    char        msg[0];    /* the entry's payload */
+};
+
 #define LOGGER_LOG_MAIN		"log/main"
 #define LOGGER_LOG_RADIO	"log/radio"
 #define LOGGER_LOG_EVENTS	"log/events"
 #define LOGGER_LOG_SYSTEM	"log/system"
 
-#define LOGGER_ENTRY_MAX_LEN		(4*1024)
-#define LOGGER_ENTRY_MAX_PAYLOAD	\
-	(LOGGER_ENTRY_MAX_LEN - sizeof(struct logger_entry))
+/*
+ * The maximum size of the log entry payload that can be
+ * written to the kernel logger driver. An attempt to write
+ * more than this amount to /dev/log/* will result in a
+ * truncated log entry.
+ */
+#define LOGGER_ENTRY_MAX_PAYLOAD	4076
+
+/*
+ * The maximum size of a log entry which can be read from the
+ * kernel logger driver. An attempt to read less than this amount
+ * may result in read() returning EINVAL.
+ */
+#define LOGGER_ENTRY_MAX_LEN		(5*1024)
 
 #ifdef HAVE_IOCTL
 
@@ -41,6 +73,8 @@
 #define LOGGER_GET_LOG_LEN		_IO(__LOGGERIO, 2) /* used log len */
 #define LOGGER_GET_NEXT_ENTRY_LEN	_IO(__LOGGERIO, 3) /* next entry len */
 #define LOGGER_FLUSH_LOG		_IO(__LOGGERIO, 4) /* flush log */
+#define LOGGER_GET_VERSION		_IO(__LOGGERIO, 5) /* abi version */
+#define LOGGER_SET_VERSION		_IO(__LOGGERIO, 6) /* abi version */
 
 #endif // HAVE_IOCTL
 
diff --git a/include/cutils/logprint.h b/include/cutils/logprint.h
index 769c8a7..2b1e1c5 100644
--- a/include/cutils/logprint.h
+++ b/include/cutils/logprint.h
@@ -44,8 +44,8 @@
     time_t tv_sec;
     long tv_nsec;
     android_LogPriority priority;
-    pid_t pid;
-    pthread_t tid;
+    int32_t pid;
+    int32_t tid;
     const char * tag;
     size_t messageLen;
     const char * message;
diff --git a/include/cutils/qsort_r_compat.h b/include/cutils/qsort_r_compat.h
new file mode 100644
index 0000000..479a1ab
--- /dev/null
+++ b/include/cutils/qsort_r_compat.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2012 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.
+ */
+
+/*
+ * Provides a portable version of qsort_r, called qsort_r_compat, which is a
+ * reentrant variant of qsort that passes a user data pointer to its comparator.
+ * This implementation follows the BSD parameter convention.
+ */
+
+#ifndef _LIBS_CUTILS_QSORT_R_COMPAT_H
+#define _LIBS_CUTILS_QSORT_R_COMPAT_H
+
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
+        int (*compar)(void*, const void* , const void* ));
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _LIBS_CUTILS_QSORT_R_COMPAT_H
diff --git a/include/cutils/sched_policy.h b/include/cutils/sched_policy.h
index eaf3993..ba84ce3 100644
--- a/include/cutils/sched_policy.h
+++ b/include/cutils/sched_policy.h
@@ -21,14 +21,39 @@
 extern "C" {
 #endif
 
+/* Keep in sync with THREAD_GROUP_* in frameworks/base/core/java/android/os/Process.java */
 typedef enum {
+    SP_DEFAULT    = -1,
     SP_BACKGROUND = 0,
     SP_FOREGROUND = 1,
+    SP_SYSTEM     = 2,  // can't be used with set_sched_policy()
+    SP_AUDIO_APP  = 3,
+    SP_AUDIO_SYS  = 4,
+    SP_CNT,
+    SP_MAX        = SP_CNT - 1,
+    SP_SYSTEM_DEFAULT = SP_FOREGROUND,
 } SchedPolicy;
 
+/* Assign thread tid to the cgroup associated with the specified policy.
+ * If the thread is a thread group leader, that is it's gettid() == getpid(),
+ * then the other threads in the same thread group are _not_ affected.
+ * On platforms which support gettid(), zero tid means current thread.
+ * Return value: 0 for success, or -errno for error.
+ */
 extern int set_sched_policy(int tid, SchedPolicy policy);
+
+/* Return the policy associated with the cgroup of thread tid via policy pointer.
+ * On platforms which support gettid(), zero tid means current thread.
+ * Return value: 0 for success, or -1 for error and set errno.
+ */
 extern int get_sched_policy(int tid, SchedPolicy *policy);
 
+/* Return a displayable string corresponding to policy.
+ * Return value: non-NULL NUL-terminated name of unspecified length;
+ * the caller is responsible for displaying the useful part of the string.
+ */
+extern const char *get_sched_policy_name(SchedPolicy policy);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/cutils/tztime.h b/include/cutils/tztime.h
index cf103ca..36ac25d 100644
--- a/include/cutils/tztime.h
+++ b/include/cutils/tztime.h
@@ -26,8 +26,14 @@
 time_t mktime_tz(struct tm * const tmp, char const * tz);
 void localtime_tz(const time_t * const timep, struct tm * tmp, const char* tz);
 
-#ifndef HAVE_ANDROID_OS
-/* the following is defined in <time.h> in Bionic */
+#ifdef HAVE_ANDROID_OS
+
+/* the following is defined in the Bionic C library on Android, but the
+ * declarations are only available through a platform-private header
+ */
+#include <bionic_time.h>
+
+#else /* !HAVE_ANDROID_OS */
 
 struct strftime_locale {
     const char *mon[12];    /* short names */
diff --git a/include/cutils/uevent.h b/include/cutils/uevent.h
index 4ebc300..4cca7e5 100644
--- a/include/cutils/uevent.h
+++ b/include/cutils/uevent.h
@@ -26,6 +26,7 @@
 
 int uevent_open_socket(int buf_sz, bool passcred);
 ssize_t uevent_kernel_multicast_recv(int socket, void *buffer, size_t length);
+ssize_t uevent_kernel_multicast_uid_recv(int socket, void *buffer, size_t length, uid_t *uid);
 
 #ifdef __cplusplus
 }
diff --git a/include/ion/ion.h b/include/ion/ion.h
new file mode 100644
index 0000000..cafead5
--- /dev/null
+++ b/include/ion/ion.h
@@ -0,0 +1,40 @@
+/*
+ *  ion.c
+ *
+ * Memory Allocator functions for ion
+ *
+ *   Copyright 2011 Google, Inc
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#ifndef __SYS_CORE_ION_H
+#define __SYS_CORE_ION_H
+
+#include <linux/ion.h>
+
+__BEGIN_DECLS
+
+int ion_open();
+int ion_close(int fd);
+int ion_alloc(int fd, size_t len, size_t align, unsigned int flags,
+              struct ion_handle **handle);
+int ion_free(int fd, struct ion_handle *handle);
+int ion_map(int fd, struct ion_handle *handle, size_t length, int prot,
+            int flags, off_t offset, unsigned char **ptr, int *map_fd);
+int ion_share(int fd, struct ion_handle *handle, int *share_fd);
+int ion_import(int fd, int share_fd, struct ion_handle **handle);
+
+__END_DECLS
+
+#endif /* __SYS_CORE_ION_H */
diff --git a/include/netutils/dhcp.h b/include/netutils/dhcp.h
index bd16240..d25e58f 100644
--- a/include/netutils/dhcp.h
+++ b/include/netutils/dhcp.h
@@ -30,7 +30,8 @@
                           char *dns1,
                           char *dns2,
                           char *server,
-                          uint32_t  *lease);
+                          uint32_t *lease,
+                          char *vendorInfo);
 extern int dhcp_stop(const char *ifname);
 extern int dhcp_release_lease(const char *ifname);
 extern char *dhcp_get_errmsg();
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index ce1e55d..6521cbe 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -53,7 +53,7 @@
 #define AID_KEYSTORE      1017  /* keystore subsystem */
 #define AID_USB           1018  /* USB devices */
 #define AID_DRM           1019  /* DRM server */
-#define AID_AVAILABLE     1020  /* available for use */
+#define AID_MDNSR         1020  /* MulticastDNSResponder (service discovery) */
 #define AID_GPS           1021  /* GPS daemon */
 #define AID_UNUSED1       1022  /* deprecated, DO NOT USE */
 #define AID_MEDIA_RW      1023  /* internal media storage write access */
@@ -61,6 +61,7 @@
 #define AID_UNUSED2       1025  /* deprecated, DO NOT USE */
 #define AID_DRMRPC        1026  /* group for drm rpc */
 #define AID_NFC           1027  /* nfc subsystem */
+#define AID_SDCARD_R      1028  /* external storage read access */
 
 #define AID_SHELL         2000  /* adb and debug shell user */
 #define AID_CACHE         2001  /* cache access */
@@ -79,7 +80,12 @@
 #define AID_MISC          9998  /* access to misc storage */
 #define AID_NOBODY        9999
 
-#define AID_APP          10000 /* first app user */
+#define AID_APP          10000  /* first app user */
+
+#define AID_ISOLATED_START 99000 /* start of uids for fully isolated sandboxed processes */
+#define AID_ISOLATED_END   99999 /* end of uids for fully isolated sandboxed processes */
+
+#define AID_USER        100000  /* offset for uid ranges for each user */
 
 #if !defined(EXCLUDE_FS_CONFIG_STRUCTURES)
 struct android_id_info {
@@ -105,7 +111,7 @@
     { "install",   AID_INSTALL, },
     { "media",     AID_MEDIA, },
     { "drm",       AID_DRM, },
-    { "available", AID_AVAILABLE, },
+    { "mdnsr",     AID_MDNSR, },
     { "nfc",       AID_NFC, },
     { "drmrpc",    AID_DRMRPC, },
     { "shell",     AID_SHELL, },
@@ -113,6 +119,7 @@
     { "diag",      AID_DIAG, },
     { "net_bt_admin", AID_NET_BT_ADMIN, },
     { "net_bt",    AID_NET_BT, },
+    { "sdcard_r",  AID_SDCARD_R, },
     { "sdcard_rw", AID_SDCARD_RW, },
     { "media_rw",  AID_MEDIA_RW, },
     { "vpn",       AID_VPN, },
@@ -131,7 +138,7 @@
 
 #define android_id_count \
     (sizeof(android_ids) / sizeof(android_ids[0]))
-    
+
 struct fs_path_config {
     unsigned mode;
     unsigned uid;
@@ -217,6 +224,8 @@
     { 00755, AID_ROOT,      AID_ROOT,      "bin/*" },
     { 00750, AID_ROOT,      AID_SHELL,     "init*" },
     { 00750, AID_ROOT,      AID_SHELL,     "charger*" },
+    { 00750, AID_ROOT,      AID_SHELL,     "sbin/fs_mgr" },
+    { 00640, AID_ROOT,      AID_SHELL,     "fstab.*" },
     { 00644, AID_ROOT,      AID_ROOT,       0 },
 };
 
@@ -225,7 +234,7 @@
 {
     struct fs_path_config *pc;
     int plen;
-    
+
     pc = dir ? android_dirs : android_files;
     plen = strlen(path);
     for(; pc->prefix; pc++){
@@ -245,9 +254,9 @@
     *uid = pc->uid;
     *gid = pc->gid;
     *mode = (*mode & (~07777)) | pc->mode;
-    
+
 #if 0
-    fprintf(stderr,"< '%s' '%s' %d %d %o >\n", 
+    fprintf(stderr,"< '%s' '%s' %d %d %o >\n",
             path, pc->prefix ? pc->prefix : "", *uid, *gid, *mode);
 #endif
 }
diff --git a/include/sync/sync.h b/include/sync/sync.h
new file mode 100644
index 0000000..6aa5f2d
--- /dev/null
+++ b/include/sync/sync.h
@@ -0,0 +1,45 @@
+/*
+ *  sync.h
+ *
+ *   Copyright 2012 Google, Inc
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#ifndef __SYS_CORE_SYNC_H
+#define __SYS_CORE_SYNC_H
+
+#include <linux/sync.h>
+#include <linux/sw_sync.h>
+
+__BEGIN_DECLS
+
+/* timeout in msecs */
+int sync_wait(int fd, unsigned int timeout);
+int sync_merge(const char *name, int fd1, int fd2);
+struct sync_fence_info_data *sync_fence_info(int fd);
+struct sync_pt_info *sync_pt_info(struct sync_fence_info_data *info,
+                                  struct sync_pt_info *itr);
+void sync_fence_info_free(struct sync_fence_info_data *info);
+
+/* sw_sync is mainly inteded for testing and should not be complied into
+ * production kernels
+ */
+
+int sw_sync_timeline_create(void);
+int sw_sync_timeline_inc(int fd, unsigned count);
+int sw_sync_fence_create(int fd, const char *name, unsigned value);
+
+__END_DECLS
+
+#endif /* __SYS_CORE_SYNC_H */
diff --git a/include/system/audio.h b/include/system/audio.h
index 52ba5e7..3807317 100644
--- a/include/system/audio.h
+++ b/include/system/audio.h
@@ -250,7 +250,9 @@
                                AUDIO_CHANNEL_IN_Z_AXIS |
                                AUDIO_CHANNEL_IN_VOICE_UPLINK |
                                AUDIO_CHANNEL_IN_VOICE_DNLINK),
-} audio_channels_t;
+};
+
+typedef uint32_t audio_channel_mask_t;
 
 typedef enum {
     AUDIO_MODE_INVALID          = -2,
@@ -288,6 +290,8 @@
     AUDIO_DEVICE_OUT_AUX_DIGITAL               = 0x400,
     AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET         = 0x800,
     AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET         = 0x1000,
+    AUDIO_DEVICE_OUT_USB_ACCESSORY             = 0x2000,
+    AUDIO_DEVICE_OUT_USB_DEVICE                = 0x4000,
     AUDIO_DEVICE_OUT_DEFAULT                   = 0x8000,
     AUDIO_DEVICE_OUT_ALL      = (AUDIO_DEVICE_OUT_EARPIECE |
                                  AUDIO_DEVICE_OUT_SPEAKER |
@@ -302,6 +306,8 @@
                                  AUDIO_DEVICE_OUT_AUX_DIGITAL |
                                  AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET |
                                  AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET |
+                                 AUDIO_DEVICE_OUT_USB_ACCESSORY |
+                                 AUDIO_DEVICE_OUT_USB_DEVICE |
                                  AUDIO_DEVICE_OUT_DEFAULT),
     AUDIO_DEVICE_OUT_ALL_A2DP = (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
                                  AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
@@ -309,6 +315,8 @@
     AUDIO_DEVICE_OUT_ALL_SCO  = (AUDIO_DEVICE_OUT_BLUETOOTH_SCO |
                                  AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
                                  AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
+    AUDIO_DEVICE_OUT_ALL_USB  = (AUDIO_DEVICE_OUT_USB_ACCESSORY |
+                                 AUDIO_DEVICE_OUT_USB_DEVICE),
 
     /* input devices */
     AUDIO_DEVICE_IN_COMMUNICATION         = 0x10000,
@@ -333,6 +341,29 @@
     AUDIO_DEVICE_IN_ALL_SCO = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
 } audio_devices_t;
 
+/* the audio output flags serve two purposes:
+ * - when an AudioTrack is created they indicate a "wish" to be connected to an
+ * output stream with attributes corresponding to the specified flags
+ * - when present in an output profile descriptor listed for a particular audio
+ * hardware module, they indicate that an output stream can be opened that
+ * supports the attributes indicated by the flags.
+ * the audio policy manager will try to match the flags in the request
+ * (when getOuput() is called) to an available output stream.
+ */
+typedef enum {
+    AUDIO_OUTPUT_FLAG_NONE = 0x0,       // no attributes
+    AUDIO_OUTPUT_FLAG_DIRECT = 0x1,     // this output directly connects a track
+                                        // to one output stream: no software mixer
+    AUDIO_OUTPUT_FLAG_PRIMARY = 0x2,    // this output is the primary output of
+                                        // the device. It is unique and must be
+                                        // present. It is opened by default and
+                                        // receives routing, audio mode and volume
+                                        // controls related to voice calls.
+    AUDIO_OUTPUT_FLAG_FAST = 0x4,       // output supports "fast tracks",
+                                        // defined elsewhere
+    AUDIO_OUTPUT_FLAG_DEEP_BUFFER = 0x8 // use deep audio buffers
+} audio_output_flags_t;
+
 static inline bool audio_is_output_device(audio_devices_t device)
 {
     if ((popcount(device) == 1) && ((device & ~AUDIO_DEVICE_OUT_ALL) == 0))
@@ -366,6 +397,14 @@
         return false;
 }
 
+static inline bool audio_is_usb_device(audio_devices_t device)
+{
+    if ((popcount(device) == 1) && (device & AUDIO_DEVICE_OUT_ALL_USB))
+        return true;
+    else
+        return false;
+}
+
 static inline bool audio_is_input_channel(uint32_t channel)
 {
     if ((channel & ~AUDIO_CHANNEL_IN_ALL) == 0)
@@ -382,7 +421,52 @@
         return false;
 }
 
-static inline bool audio_is_valid_format(uint32_t format)
+/* Derive an output channel mask from a channel count.
+ * This is to be used when the content channel mask is unknown. The 1, 2, 4, 5, 6, 7 and 8 channel
+ * cases are mapped to the standard game/home-theater layouts, but note that 4 is mapped to quad,
+ * and not stereo + FC + mono surround. A channel count of 3 is arbitrarily mapped to stereo + FC
+ * for continuity with stereo.
+ * Returns the matching channel mask, or 0 if the number of channels exceeds that of the
+ * configurations for which a default channel mask is defined.
+ */
+static inline audio_channel_mask_t audio_channel_out_mask_from_count(uint32_t channel_count)
+{
+    switch(channel_count) {
+    case 1:
+        return AUDIO_CHANNEL_OUT_MONO;
+    case 2:
+        return AUDIO_CHANNEL_OUT_STEREO;
+    case 3:
+        return (AUDIO_CHANNEL_OUT_STEREO | AUDIO_CHANNEL_OUT_FRONT_CENTER);
+    case 4: // 4.0
+        return AUDIO_CHANNEL_OUT_QUAD;
+    case 5: // 5.0
+        return (AUDIO_CHANNEL_OUT_QUAD | AUDIO_CHANNEL_OUT_FRONT_CENTER);
+    case 6: // 5.1
+        return AUDIO_CHANNEL_OUT_5POINT1;
+    case 7: // 6.1
+        return (AUDIO_CHANNEL_OUT_5POINT1 | AUDIO_CHANNEL_OUT_BACK_CENTER);
+    case 8:
+        return AUDIO_CHANNEL_OUT_7POINT1;
+    default:
+        return 0;
+    }
+}
+
+/* Similar to above, but for input.  Currently handles only mono and stereo. */
+static inline audio_channel_mask_t audio_channel_in_mask_from_count(uint32_t channel_count)
+{
+    switch (channel_count) {
+    case 1:
+        return AUDIO_CHANNEL_IN_MONO;
+    case 2:
+        return AUDIO_CHANNEL_IN_STEREO;
+    default:
+        return 0;
+    }
+}
+
+static inline bool audio_is_valid_format(audio_format_t format)
 {
     switch (format & AUDIO_FORMAT_MAIN_MASK) {
     case AUDIO_FORMAT_PCM:
@@ -403,28 +487,28 @@
     }
 }
 
-static inline bool audio_is_linear_pcm(uint32_t format)
+static inline bool audio_is_linear_pcm(audio_format_t format)
 {
     return ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM);
 }
 
-static inline size_t audio_bytes_per_sample(uint32_t format)
+static inline size_t audio_bytes_per_sample(audio_format_t format)
 {
     size_t size = 0;
 
     switch (format) {
-        case AUDIO_FORMAT_PCM_32_BIT:
-        case AUDIO_FORMAT_PCM_8_24_BIT:
-            size = sizeof(int32_t);
-            break;
-        case AUDIO_FORMAT_PCM_16_BIT:
-            size = sizeof(int16_t);
-            break;
-        case AUDIO_FORMAT_PCM_8_BIT:
-            size = sizeof(uint8_t);
-            break;
-        default:
-            break;
+    case AUDIO_FORMAT_PCM_32_BIT:
+    case AUDIO_FORMAT_PCM_8_24_BIT:
+        size = sizeof(int32_t);
+        break;
+    case AUDIO_FORMAT_PCM_16_BIT:
+        size = sizeof(int16_t);
+        break;
+    case AUDIO_FORMAT_PCM_8_BIT:
+        size = sizeof(uint8_t);
+        break;
+    default:
+        break;
     }
     return size;
 }
diff --git a/include/system/audio_policy.h b/include/system/audio_policy.h
index 1e0af7d..91b8e9c 100644
--- a/include/system/audio_policy.h
+++ b/include/system/audio_policy.h
@@ -30,14 +30,6 @@
  * frameworks/base/include/media/AudioSystem.h
  */
 
-/* request to open a direct output with get_output() (by opposition to
- * sharing an output with other AudioTracks)
- */
-typedef enum {
-    AUDIO_POLICY_OUTPUT_FLAG_INDIRECT = 0x0,
-    AUDIO_POLICY_OUTPUT_FLAG_DIRECT = 0x1
-} audio_policy_output_flags_t;
-
 /* device categories used for audio_policy->set_force_use() */
 typedef enum {
     AUDIO_POLICY_FORCE_NONE,
@@ -50,6 +42,7 @@
     AUDIO_POLICY_FORCE_BT_DESK_DOCK,
     AUDIO_POLICY_FORCE_ANALOG_DOCK,
     AUDIO_POLICY_FORCE_DIGITAL_DOCK,
+    AUDIO_POLICY_FORCE_NO_BT_A2DP, /* A2DP sink is not preferred to speaker or wired HS */
 
     AUDIO_POLICY_FORCE_CFG_CNT,
     AUDIO_POLICY_FORCE_CFG_MAX = AUDIO_POLICY_FORCE_CFG_CNT - 1,
diff --git a/include/system/camera.h b/include/system/camera.h
index cdfa256..e4cacc5 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
 };
 
@@ -134,7 +137,8 @@
      * KEY_FOCUS_AREAS and KEY_METERING_AREAS have no effect.
      *
      * arg1 is the face detection type. It can be CAMERA_FACE_DETECTION_HW or
-     * CAMERA_FACE_DETECTION_SW.
+     * CAMERA_FACE_DETECTION_SW. If the type of face detection requested is not
+     * supported, the HAL must return BAD_VALUE.
      */
     CAMERA_CMD_START_FACE_DETECTION = 6,
 
@@ -142,11 +146,36 @@
      * 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,
+
+    /**
+     * Ping camera service to see if camera hardware is released.
+     *
+     * When any camera method returns error, the client can use ping command
+     * to see if the camera has been taken away by other clients. If the result
+     * is NO_ERROR, it means the camera hardware is not released. If the result
+     * is not NO_ERROR, the camera has been released and the existing client
+     * can silently finish itself or show a dialog.
+     */
+    CAMERA_CMD_PING = 9,
 };
 
 /** camera fatal errors */
 enum {
     CAMERA_ERROR_UNKNOWN = 1,
+    /**
+     * Camera was released because another client has connected to the camera.
+     * The original client should call Camera::disconnect immediately after
+     * getting this notification. Otherwise, the camera will be released by
+     * camera service in a short time. The client should not call any method
+     * (except disconnect and sending CAMERA_CMD_PING) after getting this.
+     */
+    CAMERA_ERROR_RELEASED = 2,
     CAMERA_ERROR_SERVER_DIED = 100
 };
 
diff --git a/include/system/graphics.h b/include/system/graphics.h
index 729e92c..24e2bfb 100644
--- a/include/system/graphics.h
+++ b/include/system/graphics.h
@@ -78,7 +78,8 @@
      * - a vertical stride equal to the height
      *
      *   y_size = stride * height
-     *   c_size = ALIGN(stride/2, 16) * height/2
+     *   c_stride = ALIGN(stride/2, 16)
+     *   c_size = c_stride * height/2
      *   size = y_size + c_size * 2
      *   cr_offset = y_size
      *   cb_offset = y_size + c_size
@@ -86,7 +87,27 @@
      */
     HAL_PIXEL_FORMAT_YV12   = 0x32315659, // YCrCb 4:2:0 Planar
 
-
+    /*
+     * Android RAW sensor format:
+     *
+     * This format is exposed outside of the HAL to applications.
+     *
+     * RAW_SENSOR is a single-channel 16-bit format, typically representing raw
+     * Bayer-pattern images from an image sensor, with minimal processing.
+     *
+     * The exact pixel layout of the data in the buffer is sensor-dependent, and
+     * needs to be queried from the camera device.
+     *
+     * Generally, not all 16 bits are used; more common values are 10 or 12
+     * bits. All parameters to interpret the raw data (black and white points,
+     * color space, etc) must be queried from the camera device.
+     *
+     * This format assumes
+     * - an even width
+     * - an even height
+     * - a horizontal stride multiple of 16 pixels (32 bytes).
+     */
+    HAL_PIXEL_FORMAT_RAW_SENSOR = 0x20,
 
     /* Legacy formats (deprecated), used by ImageFormat.java */
     HAL_PIXEL_FORMAT_YCbCr_422_SP       = 0x10, // NV16
diff --git a/include/system/window.h b/include/system/window.h
index 1cc4a0a..8e00bcd 100644
--- a/include/system/window.h
+++ b/include/system/window.h
@@ -18,6 +18,7 @@
 #define SYSTEM_CORE_INCLUDE_ANDROID_WINDOW_H
 
 #include <stdint.h>
+#include <string.h>
 #include <sys/cdefs.h>
 #include <system/graphics.h>
 #include <cutils/native_handle.h>
@@ -156,9 +157,10 @@
 
 
     /*
-     * Default width and height of the ANativeWindow, these are the dimensions
-     * of the window irrespective of the NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS
-     * call.
+     * Default width and height of ANativeWindow buffers, these are the
+     * dimensions of the window buffers irrespective of the
+     * NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS call and match the native window
+     * size unless overridden by NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS.
      */
     NATIVE_WINDOW_DEFAULT_WIDTH = 6,
     NATIVE_WINDOW_DEFAULT_HEIGHT = 7,
@@ -211,25 +213,42 @@
      *
      */
     NATIVE_WINDOW_TRANSFORM_HINT = 8,
+
+    /*
+     * Boolean that indicates whether the consumer is running more than
+     * one buffer behind the producer.
+     */
+    NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND = 9
 };
 
-/* valid operations for the (*perform)() hook */
+/* Valid operations for the (*perform)() hook.
+ *
+ * Values marked as 'deprecated' are supported, but have been superceded by
+ * other functionality.
+ *
+ * Values marked as 'private' should be considered private to the framework.
+ * HAL implementation code with access to an ANativeWindow should not use these,
+ * as it may not interact properly with the framework's use of the
+ * ANativeWindow.
+ */
 enum {
     NATIVE_WINDOW_SET_USAGE                 =  0,
     NATIVE_WINDOW_CONNECT                   =  1,   /* deprecated */
     NATIVE_WINDOW_DISCONNECT                =  2,   /* deprecated */
-    NATIVE_WINDOW_SET_CROP                  =  3,
+    NATIVE_WINDOW_SET_CROP                  =  3,   /* private */
     NATIVE_WINDOW_SET_BUFFER_COUNT          =  4,
     NATIVE_WINDOW_SET_BUFFERS_GEOMETRY      =  5,   /* deprecated */
     NATIVE_WINDOW_SET_BUFFERS_TRANSFORM     =  6,
     NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP     =  7,
     NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS    =  8,
     NATIVE_WINDOW_SET_BUFFERS_FORMAT        =  9,
-    NATIVE_WINDOW_SET_SCALING_MODE          = 10,
+    NATIVE_WINDOW_SET_SCALING_MODE          = 10,   /* private */
     NATIVE_WINDOW_LOCK                      = 11,   /* private */
     NATIVE_WINDOW_UNLOCK_AND_POST           = 12,   /* private */
     NATIVE_WINDOW_API_CONNECT               = 13,   /* private */
     NATIVE_WINDOW_API_DISCONNECT            = 14,   /* private */
+    NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS = 15, /* private */
+    NATIVE_WINDOW_SET_POST_TRANSFORM_CROP   = 16,   /* private */
 };
 
 /* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */
@@ -275,6 +294,15 @@
     NATIVE_WINDOW_SCALING_MODE_FREEZE           = 0,
     /* the buffer is scaled in both dimensions to match the window size */
     NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW  = 1,
+    /* the buffer is scaled uniformly such that the smaller dimension
+     * of the buffer matches the window size (cropping in the process)
+     */
+    NATIVE_WINDOW_SCALING_MODE_SCALE_CROP       = 2,
+    /* the window is clipped to the size of the buffer's crop rectangle; pixels
+     * outside the crop rectangle are treated as if they are completely
+     * transparent.
+     */
+    NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP    = 3,
 };
 
 /* values returned by the NATIVE_WINDOW_CONCRETE_TYPE query */
@@ -404,18 +432,20 @@
      *     NATIVE_WINDOW_SET_USAGE
      *     NATIVE_WINDOW_CONNECT               (deprecated)
      *     NATIVE_WINDOW_DISCONNECT            (deprecated)
-     *     NATIVE_WINDOW_SET_CROP
+     *     NATIVE_WINDOW_SET_CROP              (private)
      *     NATIVE_WINDOW_SET_BUFFER_COUNT
      *     NATIVE_WINDOW_SET_BUFFERS_GEOMETRY  (deprecated)
      *     NATIVE_WINDOW_SET_BUFFERS_TRANSFORM
      *     NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP
      *     NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS
      *     NATIVE_WINDOW_SET_BUFFERS_FORMAT
-     *     NATIVE_WINDOW_SET_SCALING_MODE
+     *     NATIVE_WINDOW_SET_SCALING_MODE       (private)
      *     NATIVE_WINDOW_LOCK                   (private)
      *     NATIVE_WINDOW_UNLOCK_AND_POST        (private)
      *     NATIVE_WINDOW_API_CONNECT            (private)
      *     NATIVE_WINDOW_API_DISCONNECT         (private)
+     *     NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS (private)
+     *     NATIVE_WINDOW_SET_POST_TRANSFORM_CROP (private)
      *
      */
 
@@ -479,14 +509,16 @@
 /*
  * native_window_set_crop(..., crop)
  * Sets which region of the next queued buffers needs to be considered.
- * A buffer's crop region is scaled to match the surface's size.
+ * Depending on the scaling mode, a buffer's crop region is scaled and/or
+ * cropped to match the surface's size.  This function sets the crop in
+ * pre-transformed buffer pixel coordinates.
  *
  * The specified crop region applies to all buffers queued after it is called.
  *
- * if 'crop' is NULL, subsequently queued buffers won't be cropped.
+ * If 'crop' is NULL, subsequently queued buffers won't be cropped.
  *
- * An error is returned if for instance the crop region is invalid,
- * out of the buffer's bound or if the window is invalid.
+ * An error is returned if for instance the crop region is invalid, out of the
+ * buffer's bound or if the window is invalid.
  */
 static inline int native_window_set_crop(
         struct ANativeWindow* window,
@@ -496,6 +528,41 @@
 }
 
 /*
+ * native_window_set_post_transform_crop(..., crop)
+ * Sets which region of the next queued buffers needs to be considered.
+ * Depending on the scaling mode, a buffer's crop region is scaled and/or
+ * cropped to match the surface's size.  This function sets the crop in
+ * post-transformed pixel coordinates.
+ *
+ * The specified crop region applies to all buffers queued after it is called.
+ *
+ * If 'crop' is NULL, subsequently queued buffers won't be cropped.
+ *
+ * An error is returned if for instance the crop region is invalid, out of the
+ * buffer's bound or if the window is invalid.
+ */
+static inline int native_window_set_post_transform_crop(
+        struct ANativeWindow* window,
+        android_native_rect_t const * crop)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_POST_TRANSFORM_CROP, crop);
+}
+
+/*
+ * native_window_set_active_rect(..., active_rect)
+ *
+ * This function is deprectated and will be removed soon.  For now it simply
+ * sets the post-transform crop for compatibility while multi-project commits
+ * get checked.
+ */
+static inline int native_window_set_active_rect(
+        struct ANativeWindow* window,
+        android_native_rect_t const * active_rect)
+{
+    return native_window_set_post_transform_crop(window, active_rect);
+}
+
+/*
  * native_window_set_buffer_count(..., count)
  * Sets the number of buffers associated with this native window.
  */
@@ -526,7 +593,7 @@
 /*
  * native_window_set_buffers_dimensions(..., int w, int h)
  * All buffers dequeued after this call will have the dimensions specified.
- * In particular, all buffers will have a fixed-size, independent form the
+ * In particular, all buffers will have a fixed-size, independent from the
  * native-window size. They will be scaled according to the scaling mode
  * (see native_window_set_scaling_mode) upon window composition.
  *
@@ -545,6 +612,31 @@
 }
 
 /*
+ * native_window_set_buffers_user_dimensions(..., int w, int h)
+ *
+ * Sets the user buffer size for the window, which overrides the
+ * window's size.  All buffers dequeued after this call will have the
+ * dimensions specified unless overridden by
+ * native_window_set_buffers_dimensions.  All buffers will have a
+ * fixed-size, independent from the native-window size. They will be
+ * scaled according to the scaling mode (see
+ * native_window_set_scaling_mode) upon window composition.
+ *
+ * If w and h are 0, the normal behavior is restored. That is, the
+ * default buffer size will match the windows's size.
+ *
+ * Calling this function will reset the window crop to a NULL value, which
+ * disables cropping of the buffers.
+ */
+static inline int native_window_set_buffers_user_dimensions(
+        struct ANativeWindow* window,
+        int w, int h)
+{
+    return window->perform(window, NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS,
+            w, h);
+}
+
+/*
  * native_window_set_buffers_format(..., int format)
  * All buffers dequeued after this call will have the format specified.
  *
@@ -601,7 +693,6 @@
             mode);
 }
 
-
 /*
  * native_window_api_connect(..., int api)
  * connects an API to this window. only one API can be connected at a time.
diff --git a/include/sysutils/FrameworkClient.h b/include/sysutils/FrameworkClient.h
index 0ef0753..4a3f0de 100644
--- a/include/sysutils/FrameworkClient.h
+++ b/include/sysutils/FrameworkClient.h
@@ -1,7 +1,7 @@
 #ifndef _FRAMEWORK_CLIENT_H
 #define _FRAMEWORK_CLIENT_H
 
-#include "../../../frameworks/base/include/utils/List.h"
+#include "List.h"
 
 #include <pthread.h>
 
@@ -17,5 +17,5 @@
     int sendMsg(const char *msg, const char *data);
 };
 
-typedef android::List<FrameworkClient *> FrameworkClientCollection;
+typedef android::sysutils::List<FrameworkClient *> FrameworkClientCollection;
 #endif
diff --git a/include/sysutils/FrameworkCommand.h b/include/sysutils/FrameworkCommand.h
index 6c1fca6..3e6264b 100644
--- a/include/sysutils/FrameworkCommand.h
+++ b/include/sysutils/FrameworkCommand.h
@@ -16,7 +16,7 @@
 #ifndef __FRAMEWORK_CMD_HANDLER_H
 #define __FRAMEWORK_CMD_HANDLER_H
 
-#include "../../../frameworks/base/include/utils/List.h"
+#include "List.h"
 
 class SocketClient;
 
@@ -34,5 +34,5 @@
     const char *getCommand() { return mCommand; }
 };
 
-typedef android::List<FrameworkCommand *> FrameworkCommandCollection;
+typedef android::sysutils::List<FrameworkCommand *> FrameworkCommandCollection;
 #endif
diff --git a/include/sysutils/FrameworkListener.h b/include/sysutils/FrameworkListener.h
index 142f50c..756bacf 100644
--- a/include/sysutils/FrameworkListener.h
+++ b/include/sysutils/FrameworkListener.h
@@ -24,11 +24,17 @@
 class FrameworkListener : public SocketListener {
 public:
     static const int CMD_ARGS_MAX = 16;
+
+    /* 1 out of errorRate will be dropped */
+    int errorRate;
 private:
+    int mCommandCount;
+    bool mWithSeq;
     FrameworkCommandCollection *mCommands;
 
 public:
     FrameworkListener(const char *socketName);
+    FrameworkListener(const char *socketName, bool withSeq);
     virtual ~FrameworkListener() {}
 
 protected:
@@ -37,5 +43,6 @@
 
 private:
     void dispatchCommand(SocketClient *c, char *data);
+    void init(const char *socketName, bool withSeq);
 };
 #endif
diff --git a/include/sysutils/List.h b/include/sysutils/List.h
new file mode 100644
index 0000000..31f7b37
--- /dev/null
+++ b/include/sysutils/List.h
@@ -0,0 +1,334 @@
+/*
+ * Copyright (C) 2005 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.
+ */
+
+//
+// Templated list class.  Normally we'd use STL, but we don't have that.
+// This class mimics STL's interfaces.
+//
+// Objects are copied into the list with the '=' operator or with copy-
+// construction, so if the compiler's auto-generated versions won't work for
+// you, define your own.
+//
+// The only class you want to use from here is "List".
+//
+#ifndef _SYSUTILS_LIST_H
+#define _SYSUTILS_LIST_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+namespace android {
+namespace sysutils {
+
+/*
+ * Doubly-linked list.  Instantiate with "List<MyClass> myList".
+ *
+ * Objects added to the list are copied using the assignment operator,
+ * so this must be defined.
+ */
+template<typename T> 
+class List 
+{
+protected:
+    /*
+     * One element in the list.
+     */
+    class _Node {
+    public:
+        explicit _Node(const T& val) : mVal(val) {}
+        ~_Node() {}
+        inline T& getRef() { return mVal; }
+        inline const T& getRef() const { return mVal; }
+        inline _Node* getPrev() const { return mpPrev; }
+        inline _Node* getNext() const { return mpNext; }
+        inline void setVal(const T& val) { mVal = val; }
+        inline void setPrev(_Node* ptr) { mpPrev = ptr; }
+        inline void setNext(_Node* ptr) { mpNext = ptr; }
+    private:
+        friend class List;
+        friend class _ListIterator;
+        T           mVal;
+        _Node*      mpPrev;
+        _Node*      mpNext;
+    };
+
+    /*
+     * Iterator for walking through the list.
+     */
+    
+    template <typename TYPE>
+    struct CONST_ITERATOR {
+        typedef _Node const * NodePtr;
+        typedef const TYPE Type;
+    };
+    
+    template <typename TYPE>
+    struct NON_CONST_ITERATOR {
+        typedef _Node* NodePtr;
+        typedef TYPE Type;
+    };
+    
+    template<
+        typename U,
+        template <class> class Constness
+    > 
+    class _ListIterator {
+        typedef _ListIterator<U, Constness>     _Iter;
+        typedef typename Constness<U>::NodePtr  _NodePtr;
+        typedef typename Constness<U>::Type     _Type;
+
+        explicit _ListIterator(_NodePtr ptr) : mpNode(ptr) {}
+
+    public:
+        _ListIterator() {}
+        _ListIterator(const _Iter& rhs) : mpNode(rhs.mpNode) {}
+        ~_ListIterator() {}
+        
+        // this will handle conversions from iterator to const_iterator
+        // (and also all convertible iterators)
+        // Here, in this implementation, the iterators can be converted
+        // if the nodes can be converted
+        template<typename V> explicit 
+        _ListIterator(const V& rhs) : mpNode(rhs.mpNode) {}
+        
+
+        /*
+         * Dereference operator.  Used to get at the juicy insides.
+         */
+        _Type& operator*() const { return mpNode->getRef(); }
+        _Type* operator->() const { return &(mpNode->getRef()); }
+
+        /*
+         * Iterator comparison.
+         */
+        inline bool operator==(const _Iter& right) const { 
+            return mpNode == right.mpNode; }
+        
+        inline bool operator!=(const _Iter& right) const { 
+            return mpNode != right.mpNode; }
+
+        /*
+         * handle comparisons between iterator and const_iterator
+         */
+        template<typename OTHER>
+        inline bool operator==(const OTHER& right) const { 
+            return mpNode == right.mpNode; }
+        
+        template<typename OTHER>
+        inline bool operator!=(const OTHER& right) const { 
+            return mpNode != right.mpNode; }
+
+        /*
+         * Incr/decr, used to move through the list.
+         */
+        inline _Iter& operator++() {     // pre-increment
+            mpNode = mpNode->getNext();
+            return *this;
+        }
+        const _Iter operator++(int) {    // post-increment
+            _Iter tmp(*this);
+            mpNode = mpNode->getNext();
+            return tmp;
+        }
+        inline _Iter& operator--() {     // pre-increment
+            mpNode = mpNode->getPrev();
+            return *this;
+        }
+        const _Iter operator--(int) {   // post-increment
+            _Iter tmp(*this);
+            mpNode = mpNode->getPrev();
+            return tmp;
+        }
+
+        inline _NodePtr getNode() const { return mpNode; }
+
+        _NodePtr mpNode;    /* should be private, but older gcc fails */
+    private:
+        friend class List;
+    };
+
+public:
+    List() {
+        prep();
+    }
+    List(const List<T>& src) {      // copy-constructor
+        prep();
+        insert(begin(), src.begin(), src.end());
+    }
+    virtual ~List() {
+        clear();
+        delete[] (unsigned char*) mpMiddle;
+    }
+
+    typedef _ListIterator<T, NON_CONST_ITERATOR> iterator;
+    typedef _ListIterator<T, CONST_ITERATOR> const_iterator;
+
+    List<T>& operator=(const List<T>& right);
+
+    /* returns true if the list is empty */
+    inline bool empty() const { return mpMiddle->getNext() == mpMiddle; }
+
+    /* return #of elements in list */
+    size_t size() const {
+        return size_t(distance(begin(), end()));
+    }
+
+    /*
+     * Return the first element or one past the last element.  The
+     * _Node* we're returning is converted to an "iterator" by a
+     * constructor in _ListIterator.
+     */
+    inline iterator begin() { 
+        return iterator(mpMiddle->getNext()); 
+    }
+    inline const_iterator begin() const { 
+        return const_iterator(const_cast<_Node const*>(mpMiddle->getNext())); 
+    }
+    inline iterator end() { 
+        return iterator(mpMiddle); 
+    }
+    inline const_iterator end() const { 
+        return const_iterator(const_cast<_Node const*>(mpMiddle)); 
+    }
+
+    /* add the object to the head or tail of the list */
+    void push_front(const T& val) { insert(begin(), val); }
+    void push_back(const T& val) { insert(end(), val); }
+
+    /* insert before the current node; returns iterator at new node */
+    iterator insert(iterator posn, const T& val) 
+    {
+        _Node* newNode = new _Node(val);        // alloc & copy-construct
+        newNode->setNext(posn.getNode());
+        newNode->setPrev(posn.getNode()->getPrev());
+        posn.getNode()->getPrev()->setNext(newNode);
+        posn.getNode()->setPrev(newNode);
+        return iterator(newNode);
+    }
+
+    /* insert a range of elements before the current node */
+    void insert(iterator posn, const_iterator first, const_iterator last) {
+        for ( ; first != last; ++first)
+            insert(posn, *first);
+    }
+
+    /* remove one entry; returns iterator at next node */
+    iterator erase(iterator posn) {
+        _Node* pNext = posn.getNode()->getNext();
+        _Node* pPrev = posn.getNode()->getPrev();
+        pPrev->setNext(pNext);
+        pNext->setPrev(pPrev);
+        delete posn.getNode();
+        return iterator(pNext);
+    }
+
+    /* remove a range of elements */
+    iterator erase(iterator first, iterator last) {
+        while (first != last)
+            erase(first++);     // don't erase than incr later!
+        return iterator(last);
+    }
+
+    /* remove all contents of the list */
+    void clear() {
+        _Node* pCurrent = mpMiddle->getNext();
+        _Node* pNext;
+
+        while (pCurrent != mpMiddle) {
+            pNext = pCurrent->getNext();
+            delete pCurrent;
+            pCurrent = pNext;
+        }
+        mpMiddle->setPrev(mpMiddle);
+        mpMiddle->setNext(mpMiddle);
+    }
+
+    /*
+     * Measure the distance between two iterators.  On exist, "first"
+     * will be equal to "last".  The iterators must refer to the same
+     * list.
+     *
+     * FIXME: This is actually a generic iterator function. It should be a 
+     * template function at the top-level with specializations for things like
+     * vector<>, which can just do pointer math). Here we limit it to
+     * _ListIterator of the same type but different constness.
+     */
+    template<
+        typename U,
+        template <class> class CL,
+        template <class> class CR
+    > 
+    ptrdiff_t distance(
+            _ListIterator<U, CL> first, _ListIterator<U, CR> last) const 
+    {
+        ptrdiff_t count = 0;
+        while (first != last) {
+            ++first;
+            ++count;
+        }
+        return count;
+    }
+
+private:
+    /*
+     * I want a _Node but don't need it to hold valid data.  More
+     * to the point, I don't want T's constructor to fire, since it
+     * might have side-effects or require arguments.  So, we do this
+     * slightly uncouth storage alloc.
+     */
+    void prep() {
+        mpMiddle = (_Node*) new unsigned char[sizeof(_Node)];
+        mpMiddle->setPrev(mpMiddle);
+        mpMiddle->setNext(mpMiddle);
+    }
+
+    /*
+     * This node plays the role of "pointer to head" and "pointer to tail".
+     * It sits in the middle of a circular list of nodes.  The iterator
+     * runs around the circle until it encounters this one.
+     */
+    _Node*      mpMiddle;
+};
+
+/*
+ * Assignment operator.
+ *
+ * The simplest way to do this would be to clear out the target list and
+ * fill it with the source.  However, we can speed things along by
+ * re-using existing elements.
+ */
+template<class T>
+List<T>& List<T>::operator=(const List<T>& right)
+{
+    if (this == &right)
+        return *this;       // self-assignment
+    iterator firstDst = begin();
+    iterator lastDst = end();
+    const_iterator firstSrc = right.begin();
+    const_iterator lastSrc = right.end();
+    while (firstSrc != lastSrc && firstDst != lastDst)
+        *firstDst++ = *firstSrc++;
+    if (firstSrc == lastSrc)        // ran out of elements in source?
+        erase(firstDst, lastDst);   // yes, erase any extras
+    else
+        insert(lastDst, firstSrc, lastSrc);     // copy remaining over
+    return *this;
+}
+
+}; // namespace sysutils
+}; // namespace android
+
+#endif // _SYSUTILS_LIST_H
diff --git a/include/sysutils/SocketClient.h b/include/sysutils/SocketClient.h
index 7d2b1d6..85b58ef 100644
--- a/include/sysutils/SocketClient.h
+++ b/include/sysutils/SocketClient.h
@@ -1,9 +1,10 @@
 #ifndef _SOCKET_CLIENT_H
 #define _SOCKET_CLIENT_H
 
-#include "../../../frameworks/base/include/utils/List.h"
+#include "List.h"
 
 #include <pthread.h>
+#include <cutils/atomic.h>
 #include <sys/types.h>
 
 class SocketClient {
@@ -24,18 +25,34 @@
     pthread_mutex_t mRefCountMutex;
     int mRefCount;
 
+    int mCmdNum;
+
+    bool mUseCmdNum;
+
 public:
     SocketClient(int sock, bool owned);
+    SocketClient(int sock, bool owned, bool useCmdNum);
     virtual ~SocketClient();
 
     int getSocket() { return mSocket; }
     pid_t getPid() const { return mPid; }
     uid_t getUid() const { return mUid; }
     gid_t getGid() const { return mGid; }
+    void setCmdNum(int cmdNum) { android_atomic_release_store(cmdNum, &mCmdNum); }
+    int getCmdNum() { return mCmdNum; }
 
     // Send null-terminated C strings:
     int sendMsg(int code, const char *msg, bool addErrno);
-    int sendMsg(const char *msg);
+    int sendMsg(int code, const char *msg, bool addErrno, bool useCmdNum);
+
+    // Provides a mechanism to send a response code to the client.
+    // Sends the code and a null character.
+    int sendCode(int code);
+
+    // Provides a mechanism to send binary data to client.
+    // Sends the code and a null character, followed by 4 bytes of
+    // big-endian length, and the data.
+    int sendBinaryMsg(int code, const void *data, int len);
 
     // Sending binary data:
     int sendData(const void *data, int len);
@@ -46,7 +63,21 @@
     // decRef() when it's done with the client.
     void incRef();
     bool decRef(); // returns true at 0 (but note: SocketClient already deleted)
+
+    // return a new string in quotes with '\\' and '\"' escaped for "my arg" transmissions
+    static char *quoteArg(const char *arg);
+
+private:
+    // Send null-terminated C strings
+    int sendMsg(const char *msg);
+    void init(int socket, bool owned, bool useCmdNum);
+
+    // Sending binary data. The caller should use make sure this is protected
+    // from multiple threads entering simultaneously.
+    // returns 0 if successful, -1 if there is a 0 byte write and -2 if any other
+    // error occurred (use errno to get the error)
+    int sendDataLocked(const void *data, int len);
 };
 
-typedef android::List<SocketClient *> SocketClientCollection;
+typedef android::sysutils::List<SocketClient *> SocketClientCollection;
 #endif
diff --git a/include/sysutils/SocketListener.h b/include/sysutils/SocketListener.h
index 6592b01..8f56230 100644
--- a/include/sysutils/SocketListener.h
+++ b/include/sysutils/SocketListener.h
@@ -21,16 +21,18 @@
 #include <sysutils/SocketClient.h>
 
 class SocketListener {
-    int                     mSock;
+    bool                    mListen;
     const char              *mSocketName;
+    int                     mSock;
     SocketClientCollection  *mClients;
     pthread_mutex_t         mClientsLock;
-    bool                    mListen;
     int                     mCtrlPipe[2];
     pthread_t               mThread;
+    bool                    mUseCmdNum;
 
 public:
     SocketListener(const char *socketName, bool listen);
+    SocketListener(const char *socketName, bool listen, bool useCmdNum);
     SocketListener(int socketFd, bool listen);
 
     virtual ~SocketListener();
@@ -38,7 +40,6 @@
     int stopListener();
 
     void sendBroadcast(int code, const char *msg, bool addErrno);
-    void sendBroadcast(const char *msg);
 
 protected:
     virtual bool onDataAvailable(SocketClient *c) = 0;
@@ -46,5 +47,6 @@
 private:
     static void *threadStart(void *obj);
     void runListener();
+    void init(const char *socketName, int socketFd, bool listen, bool useCmdNum);
 };
 #endif
diff --git a/init/Android.mk b/init/Android.mk
index 162c226..7dae9df 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -22,13 +22,23 @@
 LOCAL_CFLAGS    += -DBOOTCHART=1
 endif
 
+ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
+LOCAL_CFLAGS += -DALLOW_LOCAL_PROP_OVERRIDE=1
+endif
+
 LOCAL_MODULE:= init
 
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
 LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_UNSTRIPPED)
 
-LOCAL_STATIC_LIBRARIES := libcutils libc
+LOCAL_STATIC_LIBRARIES := libfs_mgr libcutils libc
+
+ifeq ($(HAVE_SELINUX),true)
+LOCAL_STATIC_LIBRARIES += libselinux
+LOCAL_C_INCLUDES += external/libselinux/include
+LOCAL_CFLAGS += -DHAVE_SELINUX
+endif
 
 include $(BUILD_EXECUTABLE)
 
diff --git a/init/builtins.c b/init/builtins.c
index eccda3f..ac9585e 100644
--- a/init/builtins.c
+++ b/init/builtins.c
@@ -29,8 +29,16 @@
 #include <stdlib.h>
 #include <sys/mount.h>
 #include <sys/resource.h>
+#include <sys/wait.h>
 #include <linux/loop.h>
 #include <cutils/partition_utils.h>
+#include <sys/system_properties.h>
+#include <fs_mgr.h>
+
+#ifdef HAVE_SELINUX
+#include <selinux/selinux.h>
+#include <selinux/label.h>
+#endif
 
 #include "init.h"
 #include "keywords.h"
@@ -69,6 +77,63 @@
     }
 }
 
+static int _open(const char *path)
+{
+    int fd;
+
+    fd = open(path, O_RDONLY | O_NOFOLLOW);
+    if (fd < 0)
+        fd = open(path, O_WRONLY | O_NOFOLLOW);
+
+    return fd;
+}
+
+static int _chown(const char *path, unsigned int uid, unsigned int gid)
+{
+    int fd;
+    int ret;
+
+    fd = _open(path);
+    if (fd < 0) {
+        return -1;
+    }
+
+    ret = fchown(fd, uid, gid);
+    if (ret < 0) {
+        int errno_copy = errno;
+        close(fd);
+        errno = errno_copy;
+        return -1;
+    }
+
+    close(fd);
+
+    return 0;
+}
+
+static int _chmod(const char *path, mode_t mode)
+{
+    int fd;
+    int ret;
+
+    fd = _open(path);
+    if (fd < 0) {
+        return -1;
+    }
+
+    ret = fchmod(fd, mode);
+    if (ret < 0) {
+        int errno_copy = errno;
+        close(fd);
+        errno = errno_copy;
+        return -1;
+    }
+
+    close(fd);
+
+    return 0;
+}
+
 static int insmod(const char *filename, char *options)
 {
     void *module;
@@ -240,7 +305,7 @@
     ret = mkdir(args[1], mode);
     /* chmod in case the directory already exists */
     if (ret == -1 && errno == EEXIST) {
-        ret = chmod(args[1], mode);
+        ret = _chmod(args[1], mode);
     }
     if (ret == -1) {
         return -errno;
@@ -254,7 +319,7 @@
             gid = decode_uid(args[4]);
         }
 
-        if (chown(args[1], uid, gid)) {
+        if (_chown(args[1], uid, gid) < 0) {
             return -errno;
         }
     }
@@ -267,6 +332,7 @@
     unsigned flag;
 } mount_flags[] = {
     { "noatime",    MS_NOATIME },
+    { "noexec",     MS_NOEXEC },
     { "nosuid",     MS_NOSUID },
     { "nodev",      MS_NODEV },
     { "nodiratime", MS_NODIRATIME },
@@ -369,72 +435,93 @@
         if (wait)
             wait_for_file(source, COMMAND_RETRY_TIMEOUT);
         if (mount(source, target, system, flags, options) < 0) {
-            /* If this fails, it may be an encrypted filesystem
-             * or it could just be wiped.  If wiped, that will be
-             * handled later in the boot process.
-             * We only support encrypting /data.  Check
-             * if we're trying to mount it, and if so,
-             * assume it's encrypted, mount a tmpfs instead.
-             * Then save the orig mount parms in properties
-             * for vold to query when it mounts the real
-             * encrypted /data.
-             */
-            if (!strcmp(target, DATA_MNT_POINT) && !partition_wiped(source)) {
-                const char *tmpfs_options;
-
-                tmpfs_options = property_get("ro.crypto.tmpfs_options");
-
-                if (mount("tmpfs", target, "tmpfs", MS_NOATIME | MS_NOSUID | MS_NODEV,
-                    tmpfs_options) < 0) {
-                    return -1;
-                }
-
-                /* Set the property that triggers the framework to do a minimal
-                 * startup and ask the user for a password
-                 */
-                property_set("ro.crypto.state", "encrypted");
-                property_set("vold.decrypt", "1");
-            } else {
-                return -1;
-            }
+            return -1;
         }
 
-        if (!strcmp(target, DATA_MNT_POINT)) {
-            char fs_flags[32];
-
-            /* Save the original mount options */
-            property_set("ro.crypto.fs_type", system);
-            property_set("ro.crypto.fs_real_blkdev", source);
-            property_set("ro.crypto.fs_mnt_point", target);
-            if (options) {
-                property_set("ro.crypto.fs_options", options);
-            }
-            snprintf(fs_flags, sizeof(fs_flags), "0x%8.8x", flags);
-            property_set("ro.crypto.fs_flags", fs_flags);
-        }
     }
 
 exit_success:
-    /* If not running encrypted, then set the property saying we are
-     * unencrypted, and also trigger the action for a nonencrypted system.
-     */
-    if (!strcmp(target, DATA_MNT_POINT)) {
-        const char *prop;
-
-        prop = property_get("ro.crypto.state");
-        if (! prop) {
-            prop = "notset";
-        }
-        if (strcmp(prop, "encrypted")) {
-            property_set("ro.crypto.state", "unencrypted");
-            action_for_each_trigger("nonencrypted", action_add_queue_tail);
-        }
-    }
-
     return 0;
 
 }
 
+int do_mount_all(int nargs, char **args)
+{
+    pid_t pid;
+    int ret = -1;
+    int child_ret = -1;
+    int status;
+    const char *prop;
+
+    if (nargs != 2) {
+        return -1;
+    }
+
+    /*
+     * Call fs_mgr_mount_all() to mount all filesystems.  We fork(2) and
+     * do the call in the child to provide protection to the main init
+     * process if anything goes wrong (crash or memory leak), and wait for
+     * the child to finish in the parent.
+     */
+    pid = fork();
+    if (pid > 0) {
+        /* Parent.  Wait for the child to return */
+        waitpid(pid, &status, 0);
+        if (WIFEXITED(status)) {
+            ret = WEXITSTATUS(status);
+        } else {
+            ret = -1;
+        }
+    } else if (pid == 0) {
+        /* child, call fs_mgr_mount_all() */
+        klog_set_level(6);  /* So we can see what fs_mgr_mount_all() does */
+        child_ret = fs_mgr_mount_all(args[1]);
+        if (child_ret == -1) {
+            ERROR("fs_mgr_mount_all returned an error\n");
+        }
+        exit(child_ret);
+    } else {
+        /* fork failed, return an error */
+        return -1;
+    }
+
+    /* ret is 1 if the device is encrypted, 0 if not, and -1 on error */
+    if (ret == 1) {
+        property_set("ro.crypto.state", "encrypted");
+        property_set("vold.decrypt", "1");
+    } else if (ret == 0) {
+        property_set("ro.crypto.state", "unencrypted");
+        /* If fs_mgr determined this is an unencrypted device, then trigger
+         * that action.
+         */
+        action_for_each_trigger("nonencrypted", action_add_queue_tail);
+    }
+
+    return ret;
+}
+
+int do_setcon(int nargs, char **args) {
+#ifdef HAVE_SELINUX
+    if (is_selinux_enabled() <= 0)
+        return 0;
+    if (setcon(args[1]) < 0) {
+        return -errno;
+    }
+#endif
+    return 0;
+}
+
+int do_setenforce(int nargs, char **args) {
+#ifdef HAVE_SELINUX
+    if (is_selinux_enabled() <= 0)
+        return 0;
+    if (security_setenforce(atoi(args[1])) < 0) {
+        return -errno;
+    }
+#endif
+    return 0;
+}
+
 int do_setkey(int nargs, char **args)
 {
     struct kbentry kbe;
@@ -448,22 +535,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 +627,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)
@@ -629,10 +703,10 @@
 int do_chown(int nargs, char **args) {
     /* GID is optional. */
     if (nargs == 3) {
-        if (chown(args[2], decode_uid(args[1]), -1) < 0)
+        if (_chown(args[2], decode_uid(args[1]), -1) < 0)
             return -errno;
     } else if (nargs == 4) {
-        if (chown(args[3], decode_uid(args[1]), decode_uid(args[2])))
+        if (_chown(args[3], decode_uid(args[1]), decode_uid(args[2])) < 0)
             return -errno;
     } else {
         return -1;
@@ -655,12 +729,70 @@
 
 int do_chmod(int nargs, char **args) {
     mode_t mode = get_mode(args[1]);
-    if (chmod(args[2], mode) < 0) {
+    if (_chmod(args[2], mode) < 0) {
         return -errno;
     }
     return 0;
 }
 
+int do_restorecon(int nargs, char **args) {
+#ifdef HAVE_SELINUX
+    char *secontext = NULL;
+    struct stat sb;
+    int i;
+
+    if (is_selinux_enabled() <= 0 || !sehandle)
+        return 0;
+
+    for (i = 1; i < nargs; i++) {
+        if (lstat(args[i], &sb) < 0)
+            return -errno;
+        if (selabel_lookup(sehandle, &secontext, args[i], sb.st_mode) < 0)
+            return -errno;
+        if (lsetfilecon(args[i], secontext) < 0) {
+            freecon(secontext);
+            return -errno;
+        }
+        freecon(secontext);
+    }
+#endif
+    return 0;
+}
+
+int do_setsebool(int nargs, char **args) {
+#ifdef HAVE_SELINUX
+    SELboolean *b = alloca(nargs * sizeof(SELboolean));
+    char *v;
+    int i;
+
+    if (is_selinux_enabled() <= 0)
+        return 0;
+
+    for (i = 1; i < nargs; i++) {
+        char *name = args[i];
+        v = strchr(name, '=');
+        if (!v) {
+            ERROR("setsebool: argument %s had no =\n", name);
+            return -EINVAL;
+        }
+        *v++ = 0;
+        b[i-1].name = name;
+        if (!strcmp(v, "1") || !strcasecmp(v, "true") || !strcasecmp(v, "on"))
+            b[i-1].value = 1;
+        else if (!strcmp(v, "0") || !strcasecmp(v, "false") || !strcasecmp(v, "off"))
+            b[i-1].value = 0;
+        else {
+            ERROR("setsebool: invalid value %s\n", v);
+            return -EINVAL;
+        }
+    }
+
+    if (security_set_boolean_list(nargs - 1, b, 0) < 0)
+        return -errno;
+#endif
+    return 0;
+}
+
 int do_loglevel(int nargs, char **args) {
     if (nargs == 2) {
         klog_set_level(atoi(args[1]));
diff --git a/init/devices.c b/init/devices.c
index a2f84aa..125f981 100644
--- a/init/devices.c
+++ b/init/devices.c
@@ -29,6 +29,12 @@
 #include <sys/socket.h>
 #include <sys/un.h>
 #include <linux/netlink.h>
+
+#ifdef HAVE_SELINUX
+#include <selinux/selinux.h>
+#include <selinux/label.h>
+#endif
+
 #include <private/android_filesystem_config.h>
 #include <sys/time.h>
 #include <asm/page.h>
@@ -45,6 +51,10 @@
 #define FIRMWARE_DIR1   "/etc/firmware"
 #define FIRMWARE_DIR2   "/vendor/firmware"
 
+#ifdef HAVE_SELINUX
+static struct selabel_handle *sehandle;
+#endif
+
 static int device_fd = -1;
 
 struct uevent {
@@ -53,6 +63,7 @@
     const char *subsystem;
     const char *firmware;
     const char *partition_name;
+    const char *device_name;
     int partition_num;
     int major;
     int minor;
@@ -180,8 +191,17 @@
     unsigned gid;
     mode_t mode;
     dev_t dev;
+#ifdef HAVE_SELINUX
+    char *secontext = NULL;
+#endif
 
     mode = get_device_perm(path, &uid, &gid) | (block ? S_IFBLK : S_IFCHR);
+#ifdef HAVE_SELINUX
+    if (sehandle) {
+        selabel_lookup(sehandle, &secontext, path, mode);
+        setfscreatecon(secontext);
+    }
+#endif
     dev = makedev(major, minor);
     /* Temporarily change egid to avoid race condition setting the gid of the
      * device node. Unforunately changing the euid would prevent creation of
@@ -192,8 +212,40 @@
     mknod(path, mode, dev);
     chown(path, uid, -1);
     setegid(AID_ROOT);
+#ifdef HAVE_SELINUX
+    if (secontext) {
+        freecon(secontext);
+        setfscreatecon(NULL);
+    }
+#endif
 }
 
+
+static int make_dir(const char *path, mode_t mode)
+{
+    int rc;
+
+#ifdef HAVE_SELINUX
+    char *secontext = NULL;
+
+    if (sehandle) {
+        selabel_lookup(sehandle, &secontext, path, mode);
+        setfscreatecon(secontext);
+    }
+#endif
+
+    rc = mkdir(path, mode);
+
+#ifdef HAVE_SELINUX
+    if (secontext) {
+        freecon(secontext);
+        setfscreatecon(NULL);
+    }
+#endif
+    return rc;
+}
+
+
 static void add_platform_device(const char *name)
 {
     int name_len = strlen(name);
@@ -284,6 +336,7 @@
     uevent->minor = -1;
     uevent->partition_name = NULL;
     uevent->partition_num = -1;
+    uevent->device_name = NULL;
 
         /* currently ignoring SEQNUM */
     while(*msg) {
@@ -311,9 +364,12 @@
         } else if(!strncmp(msg, "PARTNAME=", 9)) {
             msg += 9;
             uevent->partition_name = msg;
+        } else if(!strncmp(msg, "DEVNAME=", 8)) {
+            msg += 8;
+            uevent->device_name = msg;
         }
 
-            /* advance to after the next \0 */
+        /* advance to after the next \0 */
         while(*msg++)
             ;
     }
@@ -506,7 +562,7 @@
         return;
 
     snprintf(devpath, sizeof(devpath), "%s%s", base, name);
-    mkdir(base, 0755);
+    make_dir(base, 0755);
 
     if (!strncmp(uevent->path, "/devices/platform/", 18))
         links = parse_platform_block_device(uevent);
@@ -528,47 +584,68 @@
 
     if (!strncmp(uevent->subsystem, "usb", 3)) {
          if (!strcmp(uevent->subsystem, "usb")) {
-             /* This imitates the file system that would be created
-              * if we were using devfs instead.
-              * Minors are broken up into groups of 128, starting at "001"
-              */
-             int bus_id = uevent->minor / 128 + 1;
-             int device_id = uevent->minor % 128 + 1;
-             /* build directories */
-             mkdir("/dev/bus", 0755);
-             mkdir("/dev/bus/usb", 0755);
-             snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d", bus_id);
-             mkdir(devpath, 0755);
-             snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d/%03d", bus_id, device_id);
+            if (uevent->device_name) {
+                /*
+                 * create device node provided by kernel if present
+                 * see drivers/base/core.c
+                 */
+                char *p = devpath;
+                snprintf(devpath, sizeof(devpath), "/dev/%s", uevent->device_name);
+                /* skip leading /dev/ */
+                p += 5;
+                /* build directories */
+                while (*p) {
+                    if (*p == '/') {
+                        *p = 0;
+                        make_dir(devpath, 0755);
+                        *p = '/';
+                    }
+                    p++;
+                }
+             }
+             else {
+                 /* This imitates the file system that would be created
+                  * if we were using devfs instead.
+                  * Minors are broken up into groups of 128, starting at "001"
+                  */
+                 int bus_id = uevent->minor / 128 + 1;
+                 int device_id = uevent->minor % 128 + 1;
+                 /* build directories */
+                 make_dir("/dev/bus", 0755);
+                 make_dir("/dev/bus/usb", 0755);
+                 snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d", bus_id);
+                 make_dir(devpath, 0755);
+                 snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d/%03d", bus_id, device_id);
+             }
          } else {
              /* ignore other USB events */
              return;
          }
      } else if (!strncmp(uevent->subsystem, "graphics", 8)) {
          base = "/dev/graphics/";
-         mkdir(base, 0755);
+         make_dir(base, 0755);
      } else if (!strncmp(uevent->subsystem, "oncrpc", 6)) {
          base = "/dev/oncrpc/";
-         mkdir(base, 0755);
+         make_dir(base, 0755);
      } else if (!strncmp(uevent->subsystem, "adsp", 4)) {
          base = "/dev/adsp/";
-         mkdir(base, 0755);
+         make_dir(base, 0755);
      } else if (!strncmp(uevent->subsystem, "msm_camera", 10)) {
          base = "/dev/msm_camera/";
-         mkdir(base, 0755);
+         make_dir(base, 0755);
      } else if(!strncmp(uevent->subsystem, "input", 5)) {
          base = "/dev/input/";
-         mkdir(base, 0755);
+         make_dir(base, 0755);
      } else if(!strncmp(uevent->subsystem, "mtd", 3)) {
          base = "/dev/mtd/";
-         mkdir(base, 0755);
+         make_dir(base, 0755);
      } else if(!strncmp(uevent->subsystem, "sound", 5)) {
          base = "/dev/snd/";
-         mkdir(base, 0755);
+         make_dir(base, 0755);
      } else if(!strncmp(uevent->subsystem, "misc", 4) &&
                  !strncmp(name, "log_", 4)) {
          base = "/dev/log/";
-         mkdir(base, 0755);
+         make_dir(base, 0755);
          name += 4;
      } else
          base = "/dev/";
@@ -819,7 +896,14 @@
     suseconds_t t0, t1;
     struct stat info;
     int fd;
+#ifdef HAVE_SELINUX
+    struct selinux_opt seopts[] = {
+        { SELABEL_OPT_PATH, "/file_contexts" }
+    };
 
+    if (is_selinux_enabled() > 0)
+        sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);
+#endif
     /* is 64K enough? udev uses 16MB! */
     device_fd = uevent_open_socket(64*1024, true);
     if(device_fd < 0)
diff --git a/init/init.c b/init/init.c
index 68e9f49..4f57144 100755
--- a/init/init.c
+++ b/init/init.c
@@ -31,6 +31,13 @@
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/un.h>
+
+#ifdef HAVE_SELINUX
+#include <sys/mman.h>
+#include <selinux/selinux.h>
+#include <selinux/label.h>
+#endif
+
 #include <libgen.h>
 
 #include <cutils/list.h>
@@ -52,6 +59,10 @@
 #include "util.h"
 #include "ueventd.h"
 
+#ifdef HAVE_SELINUX
+struct selabel_handle *sehandle;
+#endif
+
 static int property_triggers_enabled = 0;
 
 #if BOOTCHART
@@ -59,15 +70,16 @@
 #endif
 
 static char console[32];
-static char serialno[PROP_VALUE_MAX];
-static char bootmode[PROP_VALUE_MAX];
-static char baseband[PROP_VALUE_MAX];
-static char carrier[PROP_VALUE_MAX];
-static char bootloader[PROP_VALUE_MAX];
-static char hardware[PROP_VALUE_MAX];
+static char bootmode[32];
+static char hardware[32];
 static unsigned revision = 0;
 static char qemu[32];
 
+#ifdef HAVE_SELINUX
+static int selinux_enabled = 1;
+static int selinux_enforcing = 0;
+#endif
+
 static struct action *cur_action = NULL;
 static struct command *cur_command = NULL;
 static struct listnode *command_queue = NULL;
@@ -122,6 +134,7 @@
     if ((fd = open(console_name, O_RDWR)) < 0) {
         fd = open("/dev/null", O_RDWR);
     }
+    ioctl(fd, TIOCSCTTY, 0);
     dup2(fd, 0);
     dup2(fd, 1);
     dup2(fd, 2);
@@ -149,7 +162,10 @@
     pid_t pid;
     int needs_console;
     int n;
-
+#ifdef HAVE_SELINUX
+    char *scon = NULL;
+    int rc;
+#endif
         /* starting a service removes it from the disabled or reset
          * state and immediately takes it out of the restarting
          * state if it was in there
@@ -186,6 +202,34 @@
         return;
     }
 
+#ifdef HAVE_SELINUX
+    if (is_selinux_enabled() > 0) {
+        char *mycon = NULL, *fcon = NULL;
+
+        INFO("computing context for service '%s'\n", svc->args[0]);
+        rc = getcon(&mycon);
+        if (rc < 0) {
+            ERROR("could not get context while starting '%s'\n", svc->name);
+            return;
+        }
+
+        rc = getfilecon(svc->args[0], &fcon);
+        if (rc < 0) {
+            ERROR("could not get context while starting '%s'\n", svc->name);
+            freecon(mycon);
+            return;
+        }
+
+        rc = security_compute_create(mycon, fcon, string_to_security_class("process"), &scon);
+        freecon(mycon);
+        freecon(fcon);
+        if (rc < 0) {
+            ERROR("could not get context while starting '%s'\n", svc->name);
+            return;
+        }
+    }
+#endif
+
     NOTICE("starting '%s'\n", svc->name);
 
     pid = fork();
@@ -196,6 +240,7 @@
         char tmp[32];
         int fd, sz;
 
+        umask(077);
         if (properties_inited()) {
             get_property_workspace(&fd, &sz);
             sprintf(tmp, "%d,%d", dup(fd), sz);
@@ -205,6 +250,10 @@
         for (ei = svc->envvars; ei; ei = ei->next)
             add_environment(ei->name, ei->value);
 
+#ifdef HAVE_SELINUX
+        setsockcreatecon(scon);
+#endif
+
         for (si = svc->sockets; si; si = si->next) {
             int socket_type = (
                     !strcmp(si->type, "stream") ? SOCK_STREAM :
@@ -216,6 +265,12 @@
             }
         }
 
+#ifdef HAVE_SELINUX
+        freecon(scon);
+        scon = NULL;
+        setsockcreatecon(NULL);
+#endif
+
         if (svc->ioprio_class != IoSchedClass_NONE) {
             if (android_set_ioprio(getpid(), svc->ioprio_class, svc->ioprio_pri)) {
                 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
@@ -261,6 +316,15 @@
             }
         }
 
+#ifdef HAVE_SELINUX
+        if (svc->seclabel) {
+            if (is_selinux_enabled() > 0 && setexeccon(svc->seclabel) < 0) {
+                ERROR("cannot setexeccon('%s'): %s\n", svc->seclabel, strerror(errno));
+                _exit(127);
+            }
+        }
+#endif
+
         if (!dynamic_args) {
             if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
                 ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
@@ -286,6 +350,10 @@
         _exit(127);
     }
 
+#ifdef HAVE_SELINUX
+    freecon(scon);
+#endif
+
     if (pid < 0) {
         ERROR("failed to start '%s'\n", svc->name);
         svc->pid = 0;
@@ -420,45 +488,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 +547,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 +594,111 @@
     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;
+
+#ifdef HAVE_SELINUX
+    if (!strcmp(name,"enforcing")) {
+        selinux_enforcing = atoi(value);
+    } else if (!strcmp(name,"selinux")) {
+        selinux_enabled = atoi(value);
+    }
+#endif
+
+    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.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)
@@ -658,6 +757,97 @@
 }
 #endif
 
+#ifdef HAVE_SELINUX
+void selinux_load_policy(void)
+{
+    const char path_prefix[] = "/sepolicy";
+    struct selinux_opt seopts[] = {
+        { SELABEL_OPT_PATH, "/file_contexts" }
+    };
+    char path[PATH_MAX];
+    int fd, rc, vers;
+    struct stat sb;
+    void *map;
+
+    sehandle = NULL;
+    if (!selinux_enabled) {
+        INFO("SELinux:  Disabled by command line option\n");
+        return;
+    }
+
+    mkdir(SELINUXMNT, 0755);
+    if (mount("selinuxfs", SELINUXMNT, "selinuxfs", 0, NULL)) {
+        if (errno == ENODEV) {
+            /* SELinux not enabled in kernel */
+            return;
+        }
+        ERROR("SELinux:  Could not mount selinuxfs:  %s\n",
+              strerror(errno));
+        return;
+    }
+    set_selinuxmnt(SELINUXMNT);
+
+    vers = security_policyvers();
+    if (vers <= 0) {
+        ERROR("SELinux:  Unable to read policy version\n");
+        return;
+    }
+    INFO("SELinux:  Maximum supported policy version:  %d\n", vers);
+
+    snprintf(path, sizeof(path), "%s.%d",
+             path_prefix, vers);
+    fd = open(path, O_RDONLY);
+    while (fd < 0 && errno == ENOENT && --vers) {
+        snprintf(path, sizeof(path), "%s.%d",
+                 path_prefix, vers);
+        fd = open(path, O_RDONLY);
+    }
+    if (fd < 0) {
+        ERROR("SELinux:  Could not open %s:  %s\n",
+              path, strerror(errno));
+        return;
+    }
+    if (fstat(fd, &sb) < 0) {
+        ERROR("SELinux:  Could not stat %s:  %s\n",
+              path, strerror(errno));
+        return;
+    }
+    map = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
+    if (map == MAP_FAILED) {
+        ERROR("SELinux:  Could not map %s:  %s\n",
+              path, strerror(errno));
+        return;
+    }
+
+    rc = security_load_policy(map, sb.st_size);
+    if (rc < 0) {
+        ERROR("SELinux:  Could not load policy:  %s\n",
+              strerror(errno));
+        return;
+    }
+
+    rc = security_setenforce(selinux_enforcing);
+    if (rc < 0) {
+        ERROR("SELinux:  Could not set enforcing mode to %s:  %s\n",
+              selinux_enforcing ? "enforcing" : "permissive", strerror(errno));
+        return;
+    }
+
+    munmap(map, sb.st_size);
+    close(fd);
+    INFO("SELinux: Loaded policy from %s\n", path);
+
+    sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);
+    if (!sehandle) {
+        ERROR("SELinux:  Could not load file_contexts:  %s\n",
+              strerror(errno));
+        return;
+    }
+    INFO("SELinux: Loaded file contexts from %s\n", seopts[0].value);
+    return;
+}
+#endif
+
 int main(int argc, char **argv)
 {
     int fd_count = 0;
@@ -668,6 +858,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 +892,37 @@
          */
     open_devnull_stdio();
     klog_init();
+    property_init();
+
+    get_hardware_name(hardware, &revision);
+
+    process_kernel_cmdline();
+
+#ifdef HAVE_SELINUX
+    INFO("loading selinux policy\n");
+    selinux_load_policy();
+#endif
+
+    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 +933,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);
@@ -744,7 +941,7 @@
     }
 
         /* run all property triggers based on current state of the properties */
-    queue_builtin_action(queue_property_triggers_action, "queue_propety_triggers");
+    queue_builtin_action(queue_property_triggers_action, "queue_property_triggers");
 
 
 #if BOOTCHART
diff --git a/init/init.h b/init/init.h
index a91d9d4..58bbbfe 100644
--- a/init/init.h
+++ b/init/init.h
@@ -95,6 +95,10 @@
     gid_t supp_gids[NR_SVC_SUPP_GIDS];
     size_t nr_supp_gids;
 
+#ifdef HAVE_SELINUX
+    char *seclabel;
+#endif
+
     struct socketinfo *sockets;
     struct svcenvinfo *envvars;
 
@@ -132,4 +136,8 @@
 
 int load_565rle_image( char *file_name );
 
+#ifdef HAVE_SELINUX
+extern struct selabel_handle *sehandle;
+#endif
+
 #endif	/* _INIT_INIT_H */
diff --git a/init/init_parser.c b/init/init_parser.c
index 13c94eb..5393e52 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);
 
@@ -117,6 +122,7 @@
         break;
     case 'm':
         if (!strcmp(s, "kdir")) return K_mkdir;
+        if (!strcmp(s, "ount_all")) return K_mount_all;
         if (!strcmp(s, "ount")) return K_mount;
         break;
     case 'o':
@@ -126,15 +132,20 @@
         break;
     case 'r':
         if (!strcmp(s, "estart")) return K_restart;
+        if (!strcmp(s, "estorecon")) return K_restorecon;
         if (!strcmp(s, "mdir")) return K_rmdir;
         if (!strcmp(s, "m")) return K_rm;
         break;
     case 's':
+        if (!strcmp(s, "eclabel")) return K_seclabel;
         if (!strcmp(s, "ervice")) return K_service;
+        if (!strcmp(s, "etcon")) return K_setcon;
+        if (!strcmp(s, "etenforce")) return K_setenforce;
         if (!strcmp(s, "etenv")) return K_setenv;
         if (!strcmp(s, "etkey")) return K_setkey;
         if (!strcmp(s, "etprop")) return K_setprop;
         if (!strcmp(s, "etrlimit")) return K_setrlimit;
+        if (!strcmp(s, "etsebool")) return K_setsebool;
         if (!strcmp(s, "ocket")) return K_socket;
         if (!strcmp(s, "tart")) return K_start;
         if (!strcmp(s, "top")) return K_stop;
@@ -159,6 +170,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 +334,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 +343,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 +354,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 +383,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)
@@ -631,6 +798,16 @@
             svc->uid = decode_uid(args[1]);
         }
         break;
+    case K_seclabel:
+#ifdef HAVE_SELINUX
+        if (nargs != 2) {
+            parse_error(state, "seclabel option requires a label string\n");
+        } else {
+            svc->seclabel = args[1];
+        }
+#endif
+        break;
+
     default:
         parse_error(state, "invalid option '%s'\n", args[0]);
     }
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/keywords.h b/init/keywords.h
index 3e3733f..97d4950 100644
--- a/init/keywords.h
+++ b/init/keywords.h
@@ -12,13 +12,18 @@
 int do_ifup(int nargs, char **args);
 int do_insmod(int nargs, char **args);
 int do_mkdir(int nargs, char **args);
+int do_mount_all(int nargs, char **args);
 int do_mount(int nargs, char **args);
 int do_restart(int nargs, char **args);
+int do_restorecon(int nargs, char **args);
 int do_rm(int nargs, char **args);
 int do_rmdir(int nargs, char **args);
+int do_setcon(int nargs, char **args);
+int do_setenforce(int nargs, char **args);
 int do_setkey(int nargs, char **args);
 int do_setprop(int nargs, char **args);
 int do_setrlimit(int nargs, char **args);
+int do_setsebool(int nargs, char **args);
 int do_start(int nargs, char **args);
 int do_stop(int nargs, char **args);
 int do_trigger(int nargs, char **args);
@@ -56,18 +61,24 @@
     KEYWORD(import,      SECTION, 1, 0)
     KEYWORD(keycodes,    OPTION,  0, 0)
     KEYWORD(mkdir,       COMMAND, 1, do_mkdir)
+    KEYWORD(mount_all,   COMMAND, 1, do_mount_all)
     KEYWORD(mount,       COMMAND, 3, do_mount)
     KEYWORD(on,          SECTION, 0, 0)
     KEYWORD(oneshot,     OPTION,  0, 0)
     KEYWORD(onrestart,   OPTION,  0, 0)
     KEYWORD(restart,     COMMAND, 1, do_restart)
+    KEYWORD(restorecon,  COMMAND, 1, do_restorecon)
     KEYWORD(rm,          COMMAND, 1, do_rm)
     KEYWORD(rmdir,       COMMAND, 1, do_rmdir)
+    KEYWORD(seclabel,    OPTION,  0, 0)
     KEYWORD(service,     SECTION, 0, 0)
+    KEYWORD(setcon,      COMMAND, 1, do_setcon)
+    KEYWORD(setenforce,  COMMAND, 1, do_setenforce)
     KEYWORD(setenv,      OPTION,  2, 0)
     KEYWORD(setkey,      COMMAND, 0, do_setkey)
     KEYWORD(setprop,     COMMAND, 2, do_setprop)
     KEYWORD(setrlimit,   COMMAND, 3, do_setrlimit)
+    KEYWORD(setsebool,   COMMAND, 1, do_setsebool)
     KEYWORD(socket,      OPTION,  0, 0)
     KEYWORD(start,       COMMAND, 1, do_start)
     KEYWORD(stop,        COMMAND, 1, do_stop)
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..79914cd 100644
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -78,6 +78,7 @@
     { "wlan.",            AID_SYSTEM,   0 },
     { "dhcp.",            AID_SYSTEM,   0 },
     { "dhcp.",            AID_DHCP,     0 },
+    { "debug.",           AID_SYSTEM,   0 },
     { "debug.",           AID_SHELL,    0 },
     { "log.",             AID_SHELL,    0 },
     { "service.adb.root", AID_SHELL,    0 },
@@ -338,21 +339,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 +491,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)
@@ -524,7 +513,9 @@
  */
 void load_persist_props(void)
 {
+#ifdef ALLOW_LOCAL_PROP_OVERRIDE
     load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE);
+#endif /* ALLOW_LOCAL_PROP_OVERRIDE */
     /* Read persistent properties after all default values have been loaded. */
     load_persistent_properties();
 }
@@ -535,7 +526,9 @@
 
     load_properties_from_file(PROP_PATH_SYSTEM_BUILD);
     load_properties_from_file(PROP_PATH_SYSTEM_DEFAULT);
+#ifdef ALLOW_LOCAL_PROP_OVERRIDE
     load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE);
+#endif /* ALLOW_LOCAL_PROP_OVERRIDE */
     /* Read persistent properties after all default values have been loaded. */
     load_persistent_properties();
 
diff --git a/init/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/init/ueventd.c b/init/ueventd.c
index ecf3b9b..a89e067 100644
--- a/init/ueventd.c
+++ b/init/ueventd.c
@@ -53,11 +53,18 @@
     int nr;
     char tmp[32];
 
-        /* Prevent fire-and-forget children from becoming zombies.
-         * If we should need to wait() for some children in the future
-         * (as opposed to none right now), double-forking here instead
-         * of ignoring SIGCHLD may be the better solution.
-         */
+    /*
+     * init sets the umask to 077 for forked processes. We need to
+     * create files with exact permissions, without modification by
+     * the umask.
+     */
+    umask(000);
+
+    /* Prevent fire-and-forget children from becoming zombies.
+     * If we should need to wait() for some children in the future
+     * (as opposed to none right now), double-forking here instead
+     * of ignoring SIGCHLD may be the better solution.
+     */
     signal(SIGCHLD, SIG_IGN);
 
     open_devnull_stdio();
diff --git a/init/util.c b/init/util.c
index 13c9ca2..7d79f39 100755
--- a/init/util.c
+++ b/init/util.c
@@ -23,6 +23,10 @@
 #include <errno.h>
 #include <time.h>
 
+#ifdef HAVE_SELINUX
+#include <selinux/label.h>
+#endif
+
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <sys/socket.h>
@@ -33,6 +37,7 @@
 
 #include <private/android_filesystem_config.h>
 
+#include "init.h"
 #include "log.h"
 #include "util.h"
 
@@ -84,6 +89,9 @@
 {
     struct sockaddr_un addr;
     int fd, ret;
+#ifdef HAVE_SELINUX
+    char *secon;
+#endif
 
     fd = socket(PF_UNIX, type, 0);
     if (fd < 0) {
@@ -102,12 +110,26 @@
         goto out_close;
     }
 
+#ifdef HAVE_SELINUX
+    secon = NULL;
+    if (sehandle) {
+        ret = selabel_lookup(sehandle, &secon, addr.sun_path, S_IFSOCK);
+        if (ret == 0)
+            setfscreatecon(secon);
+    }
+#endif
+
     ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
     if (ret) {
         ERROR("Failed to bind socket '%s': %s\n", name, strerror(errno));
         goto out_unlink;
     }
 
+#ifdef HAVE_SELINUX
+    setfscreatecon(NULL);
+    freecon(secon);
+#endif
+
     chown(addr.sun_path, uid, gid);
     chmod(addr.sun_path, perm);
 
@@ -129,11 +151,23 @@
     char *data;
     int sz;
     int fd;
+    struct stat sb;
 
     data = 0;
     fd = open(fn, O_RDONLY);
     if(fd < 0) return 0;
 
+    // for security reasons, disallow world-writable
+    // or group-writable files
+    if (fstat(fd, &sb) < 0) {
+        ERROR("fstat failed for '%s'\n", fn);
+        goto oops;
+    }
+    if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
+        ERROR("skipping insecure file '%s'\n", fn);
+        goto oops;
+    }
+
     sz = lseek(fd, 0, SEEK_END);
     if(sz < 0) goto oops;
 
diff --git a/libcorkscrew/Android.mk b/libcorkscrew/Android.mk
new file mode 100644
index 0000000..9019986
--- /dev/null
+++ b/libcorkscrew/Android.mk
@@ -0,0 +1,87 @@
+# 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)
+
+generic_src_files := \
+	backtrace.c \
+	backtrace-helper.c \
+	demangle.c \
+	map_info.c \
+	ptrace.c \
+	symbol_table.c
+
+arm_src_files := \
+	arch-arm/backtrace-arm.c \
+	arch-arm/ptrace-arm.c
+
+x86_src_files := \
+	arch-x86/backtrace-x86.c \
+	arch-x86/ptrace-x86.c
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(generic_src_files)
+
+ifeq ($(TARGET_ARCH),arm)
+LOCAL_SRC_FILES += $(arm_src_files)
+LOCAL_CFLAGS += -DCORKSCREW_HAVE_ARCH
+endif
+ifeq ($(TARGET_ARCH),x86)
+LOCAL_SRC_FILES += $(x86_src_files)
+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)
+
+# Build test.
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := test.c
+LOCAL_CFLAGS += -std=gnu99 -Werror -fno-inline-small-functions
+LOCAL_SHARED_LIBRARIES := libcorkscrew
+LOCAL_MODULE := libcorkscrew_test
+LOCAL_MODULE_TAGS := optional
+include $(BUILD_EXECUTABLE)
+
+
+ifeq ($(HOST_OS)-$(HOST_ARCH),linux-x86)
+
+# Build libcorkscrew.
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES += $(generic_src_files) $(x86_src_files)
+LOCAL_CFLAGS += -DCORKSCREW_HAVE_ARCH
+LOCAL_SHARED_LIBRARIES += libgccdemangle
+LOCAL_STATIC_LIBRARIES += libcutils
+LOCAL_LDLIBS += -ldl -lrt
+LOCAL_CFLAGS += -std=gnu99 -Werror
+LOCAL_MODULE := libcorkscrew
+LOCAL_MODULE_TAGS := optional
+include $(BUILD_HOST_SHARED_LIBRARY)
+
+# Build test.
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := test.c
+LOCAL_CFLAGS += -std=gnu99 -Werror -fno-inline-small-functions
+LOCAL_SHARED_LIBRARIES := libcorkscrew
+LOCAL_MODULE := libcorkscrew_test
+LOCAL_MODULE_TAGS := optional
+include $(BUILD_HOST_EXECUTABLE)
+
+endif # linux-x86
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..01d9ed5
--- /dev/null
+++ b/libcorkscrew/arch-x86/backtrace-x86.c
@@ -0,0 +1,131 @@
+/*
+ * 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 <cutils/log.h>
+
+#if defined(__BIONIC__)
+
+// Bionic offers the Linux kernel headers.
+#include <asm/sigcontext.h>
+#include <asm/ucontext.h>
+typedef struct ucontext ucontext_t;
+
+#else
+
+// glibc has its own renaming of the Linux kernel's structures.
+#define __USE_GNU // For REG_EBP, REG_ESP, and REG_EIP.
+#include <ucontext.h>
+
+#endif
+
+/* 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;
+#if defined(__BIONIC__)
+    state.ebp = uc->uc_mcontext.ebp;
+    state.esp = uc->uc_mcontext.esp;
+    state.eip = uc->uc_mcontext.eip;
+#else
+    state.ebp = uc->uc_mcontext.gregs[REG_EBP];
+    state.esp = uc->uc_mcontext.gregs[REG_ESP];
+    state.eip = uc->uc_mcontext.gregs[REG_EIP];
+#endif
+
+    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/nexus/SupplicantEvent.cpp b/libcorkscrew/arch-x86/ptrace-x86.c
similarity index 65%
rename from nexus/SupplicantEvent.cpp
rename to libcorkscrew/arch-x86/ptrace-x86.c
index faf7b45..f0ea110 100644
--- a/nexus/SupplicantEvent.cpp
+++ b/libcorkscrew/arch-x86/ptrace-x86.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,16 +14,15 @@
  * limitations under the License.
  */
 
-#include <stdlib.h>
+#define LOG_TAG "Corkscrew"
+//#define LOG_NDEBUG 0
 
-#define LOG_TAG "SupplicantEvent"
+#include "../ptrace-arch.h"
+
 #include <cutils/log.h>
 
-#include "SupplicantEvent.h"
+void load_ptrace_map_info_data_arch(pid_t pid, map_info_t* mi, map_info_data_t* data) {
+}
 
-#include "libwpa_client/wpa_ctrl.h"
-
-SupplicantEvent::SupplicantEvent(int type, int level) {
-    mType = type;
-    mLevel = level;
+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..eec53a2
--- /dev/null
+++ b/libcorkscrew/backtrace.c
@@ -0,0 +1,328 @@
+/*
+ * 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 <stdlib.h>
+#include <string.h>
+#include <pthread.h>
+#include <unwind.h>
+#include <cutils/log.h>
+#include <cutils/atomic.h>
+#include <elf.h>
+
+#if HAVE_DLADDR
+#define __USE_GNU // For dladdr(3) in glibc.
+#include <dlfcn.h>
+#endif
+
+#if defined(__BIONIC__)
+
+// Bionic implements and exports gettid but only implements tgkill.
+extern int tgkill(int tgid, int tid, int sig);
+
+#else
+
+// glibc doesn't implement or export either gettid or tgkill.
+
+#include <unistd.h>
+#include <sys/syscall.h>
+
+static pid_t gettid() {
+  return syscall(__NR_gettid);
+}
+
+static int tgkill(int tgid, int tid, int sig) {
+  return syscall(__NR_tgkill, tgid, tid, sig);
+}
+
+#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
+
+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..3c52854
--- /dev/null
+++ b/libcorkscrew/map_info.c
@@ -0,0 +1,191 @@
+/*
+ * 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 <stdlib.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..6496d5e
--- /dev/null
+++ b/libcorkscrew/ptrace.c
@@ -0,0 +1,146 @@
+/*
+ * 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 <stdlib.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..29e4a79
--- /dev/null
+++ b/libcorkscrew/symbol_table.c
@@ -0,0 +1,219 @@
+/*
+ * 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 <stdbool.h>
+#include <stdlib.h>
+#include <elf.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+#include <cutils/log.h>
+
+static bool is_elf(Elf32_Ehdr* e) {
+    return (e->e_ident[EI_MAG0] == ELFMAG0 &&
+            e->e_ident[EI_MAG1] == ELFMAG1 &&
+            e->e_ident[EI_MAG2] == ELFMAG2 &&
+            e->e_ident[EI_MAG3] == ELFMAG3);
+}
+
+// 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/libcorkscrew/test.c b/libcorkscrew/test.c
new file mode 100644
index 0000000..af34c03
--- /dev/null
+++ b/libcorkscrew/test.c
@@ -0,0 +1,64 @@
+#include <corkscrew/backtrace.h>
+#include <corkscrew/symbol_table.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+void do_backtrace() {
+  const size_t MAX_DEPTH = 32;
+  backtrace_frame_t* frames = (backtrace_frame_t*) malloc(sizeof(backtrace_frame_t) * MAX_DEPTH);
+  ssize_t frame_count = unwind_backtrace(frames, 0, MAX_DEPTH);
+  fprintf(stderr, "frame_count=%d\n", (int) frame_count);
+
+  backtrace_symbol_t* backtrace_symbols = (backtrace_symbol_t*) malloc(sizeof(backtrace_symbol_t) * frame_count);
+  get_backtrace_symbols(frames, frame_count, backtrace_symbols);
+
+  for (size_t i = 0; i < (size_t) frame_count; ++i) {
+    char line[MAX_BACKTRACE_LINE_LENGTH];
+    format_backtrace_line(i, &frames[i], &backtrace_symbols[i],
+                          line, MAX_BACKTRACE_LINE_LENGTH);
+    if (backtrace_symbols[i].symbol_name != NULL) {
+      // get_backtrace_symbols found the symbol's name with dladdr(3).
+      fprintf(stderr, "  %s\n", line);
+    } else {
+      // We don't have a symbol. Maybe this is a static symbol, and
+      // we can look it up?
+      symbol_table_t* symbols = NULL;
+      if (backtrace_symbols[i].map_name != NULL) {
+        symbols = load_symbol_table(backtrace_symbols[i].map_name);
+      }
+      const symbol_t* symbol = NULL;
+      if (symbols != NULL) {
+        symbol = find_symbol(symbols, frames[i].absolute_pc);
+      }
+      if (symbol != NULL) {
+        uintptr_t offset = frames[i].absolute_pc - symbol->start;
+        fprintf(stderr, "  %s (%s%+d)\n", line, symbol->name, offset);
+      } else {
+        fprintf(stderr, "  %s (\?\?\?)\n", line);
+      }
+      free_symbol_table(symbols);
+    }
+  }
+
+  free_backtrace_symbols(backtrace_symbols, frame_count);
+  free(backtrace_symbols);
+  free(frames);
+}
+
+__attribute__ ((noinline)) void g() {
+  fprintf(stderr, "g()\n");
+  do_backtrace();
+}
+
+__attribute__ ((noinline)) int f(int i) {
+  fprintf(stderr, "f(%i)\n", i);
+  if (i == 0) {
+    g();
+    return 0;
+  }
+  return f(i - 1);
+}
+
+int main() {
+  return f(5);
+}
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index effaae0..0d49165 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -46,6 +46,7 @@
 	record_stream.c \
 	process_name.c \
 	properties.c \
+	qsort_r_compat.c \
 	threads.c \
 	sched_policy.c \
 	iosched_policy.c \
@@ -94,8 +95,25 @@
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 
+# Static library for host, 64-bit
+# ========================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := lib64cutils
+LOCAL_SRC_FILES := $(commonSources) $(commonHostSources) dlmalloc_stubs.c
+LOCAL_LDLIBS := -lpthread
+LOCAL_STATIC_LIBRARIES := lib64log
+LOCAL_CFLAGS += $(hostSmpFlag) -m64
+include $(BUILD_HOST_STATIC_LIBRARY)
+
+
 # Shared and static library for target
 # ========================================================
+
+# This is needed in LOCAL_C_INCLUDES to access the C library's private
+# header named <bionic_time.h>
+#
+libcutils_c_includes := bionic/libc/private
+
 include $(CLEAR_VARS)
 LOCAL_MODULE := libcutils
 LOCAL_SRC_FILES := $(commonSources) ashmem-dev.c mq.c android_reboot.c partition_utils.c uevent.c qtaguid.c klog.c
@@ -115,7 +133,7 @@
 endif # !sh
 endif # !arm
 
-LOCAL_C_INCLUDES := $(KERNEL_HEADERS)
+LOCAL_C_INCLUDES := $(libcutils_c_includes) $(KERNEL_HEADERS)
 LOCAL_STATIC_LIBRARIES := liblog
 LOCAL_CFLAGS += $(targetSmpFlag)
 include $(BUILD_STATIC_LIBRARY)
@@ -125,6 +143,7 @@
 LOCAL_WHOLE_STATIC_LIBRARIES := libcutils
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_CFLAGS += $(targetSmpFlag)
+LOCAL_C_INCLUDES := $(libcutils_c_includes)
 include $(BUILD_SHARED_LIBRARY)
 
 include $(CLEAR_VARS)
diff --git a/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/process_name.c b/libcutils/process_name.c
index b235429..bda9d08 100644
--- a/libcutils/process_name.c
+++ b/libcutils/process_name.c
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <stdlib.h>
 #include <string.h>
 #include <cutils/process_name.h>
 #include <cutils/properties.h>
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/qsort_r_compat.c b/libcutils/qsort_r_compat.c
new file mode 100644
index 0000000..8971cb5
--- /dev/null
+++ b/libcutils/qsort_r_compat.c
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2012 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 <stdlib.h>
+#include <cutils/qsort_r_compat.h>
+
+#if HAVE_BSD_QSORT_R
+
+/*
+ * BSD qsort_r parameter order is as we have defined here.
+ */
+
+void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
+        int (*compar)(void*, const void* , const void*)) {
+    qsort_r(base, nel, width, thunk, compar);
+}
+
+#elif HAVE_GNU_QSORT_R
+
+/*
+ * GNU qsort_r parameter order places the thunk parameter last.
+ */
+
+struct compar_data {
+    void* thunk;
+    int (*compar)(void*, const void* , const void*);
+};
+
+static int compar_wrapper(const void* a, const void* b, void* data) {
+    struct compar_data* compar_data = (struct compar_data*)data;
+    return compar_data->compar(compar_data->thunk, a, b);
+}
+
+void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
+        int (*compar)(void*, const void* , const void*)) {
+    struct compar_data compar_data;
+    compar_data.thunk = thunk;
+    compar_data.compar = compar;
+    qsort_r(base, nel, width, compar_wrapper, &compar_data);
+}
+
+#else
+
+/*
+ * Emulate qsort_r using thread local storage to access the thunk data.
+ */
+
+#include <cutils/threads.h>
+
+static thread_store_t compar_data_key = THREAD_STORE_INITIALIZER;
+
+struct compar_data {
+    void* thunk;
+    int (*compar)(void*, const void* , const void*);
+};
+
+static int compar_wrapper(const void* a, const void* b) {
+    struct compar_data* compar_data = (struct compar_data*)thread_store_get(&compar_data_key);
+    return compar_data->compar(compar_data->thunk, a, b);
+}
+
+void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
+        int (*compar)(void*, const void* , const void*)) {
+    struct compar_data compar_data;
+    compar_data.thunk = thunk;
+    compar_data.compar = compar;
+    thread_store_set(&compar_data_key, &compar_data, NULL);
+    qsort(base, nel, width, compar_wrapper);
+}
+
+#endif
diff --git a/libcutils/qtaguid.c b/libcutils/qtaguid.c
index 994ad32..5bb8176 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;
@@ -99,19 +99,17 @@
 int qtaguid_tagSocket(int sockfd, int tag, uid_t uid) {
     char lineBuf[CTRL_MAX_INPUT_LEN];
     int res;
-    /* Doing java-land a favor, enforcing "long" */
-    uint64_t kTag = ((uint64_t)tag << 32) & ~(1LLU<<63);
-
+    uint64_t kTag = ((uint64_t)tag << 32);
 
     pthread_once(&resTrackInitDone, qtaguid_resTrack);
 
     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 +120,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 +135,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 +147,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/sched_policy.c b/libcutils/sched_policy.c
index f9c111e..d20d217 100644
--- a/libcutils/sched_policy.c
+++ b/libcutils/sched_policy.c
@@ -16,24 +16,31 @@
 ** limitations under the License.
 */
 
+#define LOG_TAG "SchedPolicy"
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <string.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <cutils/sched_policy.h>
+#include <cutils/log.h>
 
-#define LOG_TAG "SchedPolicy"
-#include "cutils/log.h"
+/* Re-map SP_DEFAULT to the system default policy, and leave other values unchanged.
+ * Call this any place a SchedPolicy is used as an input parameter.
+ * Returns the possibly re-mapped policy.
+ */
+static inline SchedPolicy _policy(SchedPolicy p)
+{
+   return p == SP_DEFAULT ? SP_SYSTEM_DEFAULT : p;
+}
 
-#ifdef HAVE_SCHED_H
-#ifdef HAVE_PTHREADS
+#if defined(HAVE_ANDROID_OS) && defined(HAVE_SCHED_H) && defined(HAVE_PTHREADS)
 
 #include <sched.h>
 #include <pthread.h>
 
-#include <cutils/sched_policy.h>
-
 #ifndef SCHED_NORMAL
   #define SCHED_NORMAL 0
 #endif
@@ -44,28 +51,45 @@
 
 #define POLICY_DEBUG 0
 
+#define CAN_SET_SP_SYSTEM 0 // non-zero means to implement set_sched_policy(tid, SP_SYSTEM)
+
 static pthread_once_t the_once = PTHREAD_ONCE_INIT;
 
 static int __sys_supports_schedgroups = -1;
 
 // File descriptors open to /dev/cpuctl/../tasks, setup by initialize, or -1 on error.
-static int normal_cgroup_fd = -1;
 static int bg_cgroup_fd = -1;
+static int fg_cgroup_fd = -1;
+#if CAN_SET_SP_SYSTEM
+static int system_cgroup_fd = -1;
+#endif
 
 /* Add tid to the scheduling group defined by the policy */
 static int add_tid_to_cgroup(int tid, SchedPolicy policy)
 {
     int fd;
 
-    if (policy == SP_BACKGROUND) {
+    switch (policy) {
+    case SP_BACKGROUND:
         fd = bg_cgroup_fd;
-    } else {
-        fd = normal_cgroup_fd;
+        break;
+    case SP_FOREGROUND:
+    case SP_AUDIO_APP:
+    case SP_AUDIO_SYS:
+        fd = fg_cgroup_fd;
+        break;
+#if CAN_SET_SP_SYSTEM
+    case SP_SYSTEM:
+        fd = system_cgroup_fd;
+        break;
+#endif
+    default:
+        fd = -1;
+        break;
     }
 
     if (fd < 0) {
-        SLOGE("add_tid_to_cgroup failed; background=%d\n",
-              policy == SP_BACKGROUND ? 1 : 0);
+        SLOGE("add_tid_to_cgroup failed; policy=%d\n", policy);
         return -1;
     }
 
@@ -86,8 +110,8 @@
          */
         if (errno == ESRCH)
                 return 0;
-        SLOGW("add_tid_to_cgroup failed to write '%s' (%s); background=%d\n",
-              ptr, strerror(errno), policy == SP_BACKGROUND ? 1 : 0);
+        SLOGW("add_tid_to_cgroup failed to write '%s' (%s); policy=%d\n",
+              ptr, strerror(errno), policy);
         return -1;
     }
 
@@ -99,14 +123,22 @@
     if (!access("/dev/cpuctl/tasks", F_OK)) {
         __sys_supports_schedgroups = 1;
 
+#if CAN_SET_SP_SYSTEM
         filename = "/dev/cpuctl/tasks";
-        normal_cgroup_fd = open(filename, O_WRONLY);
-        if (normal_cgroup_fd < 0) {
+        system_cgroup_fd = open(filename, O_WRONLY | O_CLOEXEC);
+        if (system_cgroup_fd < 0) {
+            SLOGV("open of %s failed: %s\n", filename, strerror(errno));
+        }
+#endif
+
+        filename = "/dev/cpuctl/apps/tasks";
+        fg_cgroup_fd = open(filename, O_WRONLY | O_CLOEXEC);
+        if (fg_cgroup_fd < 0) {
             SLOGE("open of %s failed: %s\n", filename, strerror(errno));
         }
 
-        filename = "/dev/cpuctl/bg_non_interactive/tasks";
-        bg_cgroup_fd = open(filename, O_WRONLY);
+        filename = "/dev/cpuctl/apps/bg_non_interactive/tasks";
+        bg_cgroup_fd = open(filename, O_WRONLY | O_CLOEXEC);
         if (bg_cgroup_fd < 0) {
             SLOGE("open of %s failed: %s\n", filename, strerror(errno));
         }
@@ -189,6 +221,11 @@
 
 int get_sched_policy(int tid, SchedPolicy *policy)
 {
+#ifdef HAVE_GETTID
+    if (tid == 0) {
+        tid = gettid();
+    }
+#endif
     pthread_once(&the_once, __initialize);
 
     if (__sys_supports_schedgroups) {
@@ -196,9 +233,11 @@
         if (getSchedulerGroup(tid, grpBuf, sizeof(grpBuf)) < 0)
             return -1;
         if (grpBuf[0] == '\0') {
-            *policy = SP_FOREGROUND;
-        } else if (!strcmp(grpBuf, "bg_non_interactive")) {
+            *policy = SP_SYSTEM;
+        } else if (!strcmp(grpBuf, "apps/bg_non_interactive")) {
             *policy = SP_BACKGROUND;
+        } else if (!strcmp(grpBuf, "apps")) {
+            *policy = SP_FOREGROUND;
         } else {
             errno = ERANGE;
             return -1;
@@ -221,6 +260,12 @@
 
 int set_sched_policy(int tid, SchedPolicy policy)
 {
+#ifdef HAVE_GETTID
+    if (tid == 0) {
+        tid = gettid();
+    }
+#endif
+    policy = _policy(policy);
     pthread_once(&the_once, __initialize);
 
 #if POLICY_DEBUG
@@ -246,12 +291,21 @@
 
         strncpy(thread_name, p, (q-p));
     }
-    if (policy == SP_BACKGROUND) {
+    switch (policy) {
+    case SP_BACKGROUND:
         SLOGD("vvv tid %d (%s)", tid, thread_name);
-    } else if (policy == SP_FOREGROUND) {
+        break;
+    case SP_FOREGROUND:
+    case SP_AUDIO_APP:
+    case SP_AUDIO_SYS:
         SLOGD("^^^ tid %d (%s)", tid, thread_name);
-    } else {
+        break;
+    case SP_SYSTEM:
+        SLOGD("/// tid %d (%s)", tid, thread_name);
+        break;
+    default:
         SLOGD("??? tid %d (%s)", tid, thread_name);
+        break;
     }
 #endif
 
@@ -273,5 +327,36 @@
     return 0;
 }
 
-#endif /* HAVE_PTHREADS */
-#endif /* HAVE_SCHED_H */
+#else
+
+/* Stubs for non-Android targets. */
+
+int set_sched_policy(int tid, SchedPolicy policy)
+{
+    return 0;
+}
+
+int get_sched_policy(int tid, SchedPolicy *policy)
+{
+    *policy = SP_SYSTEM_DEFAULT;
+    return 0;
+}
+
+#endif
+
+const char *get_sched_policy_name(SchedPolicy policy)
+{
+    policy = _policy(policy);
+    static const char * const strings[SP_CNT] = {
+       [SP_BACKGROUND] = "bg",
+       [SP_FOREGROUND] = "fg",
+       [SP_SYSTEM]     = "  ",
+       [SP_AUDIO_APP]  = "aa",
+       [SP_AUDIO_SYS]  = "as",
+    };
+    if ((policy < SP_CNT) && (strings[policy] != NULL))
+        return strings[policy];
+    else
+        return "error";
+}
+
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..9e1d2dc 100644
--- a/libcutils/str_parms.c
+++ b/libcutils/str_parms.c
@@ -70,19 +70,57 @@
     return NULL;
 }
 
+struct remove_ctxt {
+    struct str_parms *str_parms;
+    const char *key;
+};
+
 static bool remove_pair(void *key, void *value, void *context)
 {
-    struct str_parms *str_parms = context;
+    struct remove_ctxt *ctxt = context;
+    bool should_continue;
 
-    hashmapRemove(str_parms->map, key);
+    /*
+     * - if key is not supplied, then we are removing all entries,
+     *   so remove key and continue (i.e. return true)
+     * - if key is supplied and matches, then remove it and don't
+     *   continue (return false). Otherwise, return true and keep searching
+     *   for key.
+     *
+     */
+    if (!ctxt->key) {
+        should_continue = true;
+        goto do_remove;
+    } else if (!strcmp(ctxt->key, key)) {
+        should_continue = false;
+        goto do_remove;
+    }
+
+    return true;
+
+do_remove:
+    hashmapRemove(ctxt->str_parms->map, key);
     free(key);
     free(value);
-    return true;
+    return should_continue;
+}
+
+void str_parms_del(struct str_parms *str_parms, const char *key)
+{
+    struct remove_ctxt ctxt = {
+        .str_parms = str_parms,
+        .key = key,
+    };
+    hashmapForEach(str_parms->map, remove_pair, &ctxt);
 }
 
 void str_parms_destroy(struct str_parms *str_parms)
 {
-    hashmapForEach(str_parms->map, remove_pair, str_parms);
+    struct remove_ctxt ctxt = {
+        .str_parms = str_parms,
+    };
+
+    hashmapForEach(str_parms->map, remove_pair, &ctxt);
     hashmapFree(str_parms->map);
     free(str_parms);
 }
@@ -103,7 +141,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) {
@@ -128,8 +166,10 @@
 
         /* if we replaced a value, free it */
         old_val = hashmapPut(str_parms->map, key, value);
-        if (old_val)
+        if (old_val) {
             free(old_val);
+            free(key);
+        }
 
         items++;
 next_pair:
@@ -137,7 +177,7 @@
     }
 
     if (!items)
-        LOGV("%s: no items found in string\n", __func__);
+        ALOGV("%s: no items found in string\n", __func__);
 
     free(str);
 
@@ -149,24 +189,23 @@
     return NULL;
 }
 
-void str_parms_del(struct str_parms *str_parms, const char *key)
-{
-    hashmapRemove(str_parms->map, (void *)key);
-}
-
 int str_parms_add_str(struct str_parms *str_parms, const char *key,
                       const char *value)
 {
     void *old_val;
-    char *tmp;
+    void *tmp_key;
+    void *tmp_val;
 
-    tmp = strdup(value);
-    old_val = hashmapPut(str_parms->map, (void *)key, tmp);
+    tmp_key = strdup(key);
+    tmp_val = strdup(value);
+    old_val = hashmapPut(str_parms->map, tmp_key, tmp_val);
 
     if (old_val) {
         free(old_val);
+        free(tmp_key);
     } else if (errno == ENOMEM) {
-        free(tmp);
+        free(tmp_key);
+        free(tmp_val);
         return -ENOMEM;
     }
     return 0;
@@ -281,7 +320,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;
 }
 
@@ -298,10 +337,13 @@
     int ret;
 
     str_parms = str_parms_create_str(str);
+    str_parms_add_str(str_parms, "dude", "woah");
+    str_parms_add_str(str_parms, "dude", "woah");
+    str_parms_del(str_parms, "dude");
     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);
 }
 
@@ -323,6 +365,7 @@
     test_str_parms_str("foo=bar;baz=");
     test_str_parms_str("foo=bar;baz=bat");
     test_str_parms_str("foo=bar;baz=bat;");
+    test_str_parms_str("foo=bar;baz=bat;foo=bar");
 
     return 0;
 }
diff --git a/libcutils/tzstrftime.c b/libcutils/tzstrftime.c
index e37d79a..e4f54df 100644
--- a/libcutils/tzstrftime.c
+++ b/libcutils/tzstrftime.c
@@ -8,6 +8,7 @@
 #endif /* !defined NOID */
 #endif /* !defined lint */
 
+#include <stdio.h>
 #include <time.h>
 #include <tzfile.h>
 #include <limits.h>
diff --git a/libcutils/uevent.c b/libcutils/uevent.c
index 4add29c..97a81e3 100644
--- a/libcutils/uevent.c
+++ b/libcutils/uevent.c
@@ -29,7 +29,24 @@
 /**
  * Like recv(), but checks that messages actually originate from the kernel.
  */
-ssize_t uevent_kernel_multicast_recv(int socket, void *buffer, size_t length) {
+ssize_t uevent_kernel_multicast_recv(int socket, void *buffer, size_t length)
+{
+    uid_t user = -1;
+    return uevent_kernel_multicast_uid_recv(socket, buffer, length, &user);
+}
+
+/**
+ * Like the above, but passes a uid_t in by reference. In the event that this
+ * fails due to a bad uid check, the uid_t will be set to the uid of the
+ * socket's peer.
+ *
+ * If this method rejects a netlink message from outside the kernel, it
+ * returns -1, sets errno to EIO, and sets "user" to the UID associated with the
+ * message. If the peer UID cannot be determined, "user" is set to -1."
+ */
+ssize_t uevent_kernel_multicast_uid_recv(int socket, void *buffer,
+                                         size_t length, uid_t *user)
+{
     struct iovec iov = { buffer, length };
     struct sockaddr_nl addr;
     char control[CMSG_SPACE(sizeof(struct ucred))];
@@ -43,16 +60,12 @@
         0,
     };
 
+    *user = -1;
     ssize_t n = recvmsg(socket, &hdr, 0);
     if (n <= 0) {
         return n;
     }
 
-    if (addr.nl_groups == 0 || addr.nl_pid != 0) {
-        /* ignoring non-kernel or unicast netlink message */
-        goto out;
-    }
-
     struct cmsghdr *cmsg = CMSG_FIRSTHDR(&hdr);
     if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
         /* ignoring netlink message with no sender credentials */
@@ -60,11 +73,17 @@
     }
 
     struct ucred *cred = (struct ucred *)CMSG_DATA(cmsg);
+    *user = cred->uid;
     if (cred->uid != 0) {
         /* ignoring netlink message from non-root user */
         goto out;
     }
 
+    if (addr.nl_groups == 0 || addr.nl_pid != 0) {
+        /* ignoring non-kernel or unicast netlink message */
+        goto out;
+    }
+
     return n;
 
 out:
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/libion/Android.mk b/libion/Android.mk
new file mode 100644
index 0000000..5121fee
--- /dev/null
+++ b/libion/Android.mk
@@ -0,0 +1,15 @@
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := ion.c
+LOCAL_MODULE := libion
+LOCAL_MODULE_TAGS := optional
+LOCAL_SHARED_LIBRARIES := liblog
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := ion.c ion_test.c
+LOCAL_MODULE := iontest
+LOCAL_MODULE_TAGS := optional tests
+LOCAL_SHARED_LIBRARIES := liblog
+include $(BUILD_EXECUTABLE)
diff --git a/libion/ion.c b/libion/ion.c
new file mode 100644
index 0000000..dbeac23
--- /dev/null
+++ b/libion/ion.c
@@ -0,0 +1,134 @@
+/*
+ *  ion.c
+ *
+ * Memory Allocator functions for ion
+ *
+ *   Copyright 2011 Google, Inc
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+#define LOG_TAG "ion"
+
+#include <cutils/log.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/types.h>
+
+#include <linux/ion.h>
+#include <ion/ion.h>
+
+int ion_open()
+{
+        int fd = open("/dev/ion", O_RDWR);
+        if (fd < 0)
+                ALOGE("open /dev/ion failed!\n");
+        return fd;
+}
+
+int ion_close(int fd)
+{
+        return close(fd);
+}
+
+static int ion_ioctl(int fd, int req, void *arg)
+{
+        int ret = ioctl(fd, req, arg);
+        if (ret < 0) {
+                ALOGE("ioctl %x failed with code %d: %s\n", req,
+                       ret, strerror(errno));
+                return -errno;
+        }
+        return ret;
+}
+
+int ion_alloc(int fd, size_t len, size_t align, unsigned int flags,
+              struct ion_handle **handle)
+{
+        int ret;
+        struct ion_allocation_data data = {
+                .len = len,
+                .align = align,
+                .flags = flags,
+        };
+
+        ret = ion_ioctl(fd, ION_IOC_ALLOC, &data);
+        if (ret < 0)
+                return ret;
+        *handle = data.handle;
+        return ret;
+}
+
+int ion_free(int fd, struct ion_handle *handle)
+{
+        struct ion_handle_data data = {
+                .handle = handle,
+        };
+        return ion_ioctl(fd, ION_IOC_FREE, &data);
+}
+
+int ion_map(int fd, struct ion_handle *handle, size_t length, int prot,
+            int flags, off_t offset, unsigned char **ptr, int *map_fd)
+{
+        struct ion_fd_data data = {
+                .handle = handle,
+        };
+
+        int ret = ion_ioctl(fd, ION_IOC_MAP, &data);
+        if (ret < 0)
+                return ret;
+        *map_fd = data.fd;
+        if (*map_fd < 0) {
+                ALOGE("map ioctl returned negative fd\n");
+                return -EINVAL;
+        }
+        *ptr = mmap(NULL, length, prot, flags, *map_fd, offset);
+        if (*ptr == MAP_FAILED) {
+                ALOGE("mmap failed: %s\n", strerror(errno));
+                return -errno;
+        }
+        return ret;
+}
+
+int ion_share(int fd, struct ion_handle *handle, int *share_fd)
+{
+        int map_fd;
+        struct ion_fd_data data = {
+                .handle = handle,
+        };
+
+        int ret = ion_ioctl(fd, ION_IOC_SHARE, &data);
+        if (ret < 0)
+                return ret;
+        *share_fd = data.fd;
+        if (*share_fd < 0) {
+                ALOGE("share ioctl returned negative fd\n");
+                return -EINVAL;
+        }
+        return ret;
+}
+
+int ion_import(int fd, int share_fd, struct ion_handle **handle)
+{
+        struct ion_fd_data data = {
+                .fd = share_fd,
+        };
+
+        int ret = ion_ioctl(fd, ION_IOC_IMPORT, &data);
+        if (ret < 0)
+                return ret;
+        *handle = data.handle;
+        return ret;
+}
diff --git a/libion/ion_test.c b/libion/ion_test.c
new file mode 100644
index 0000000..3f2d7cc
--- /dev/null
+++ b/libion/ion_test.c
@@ -0,0 +1,282 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <sys/mman.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <ion/ion.h>
+#include <linux/ion.h>
+#include <linux/omap_ion.h>
+
+size_t len = 1024*1024, align = 0;
+int prot = PROT_READ | PROT_WRITE;
+int map_flags = MAP_SHARED;
+int alloc_flags = 0;
+int test = -1;
+size_t width = 1024*1024, height = 1024*1024;
+size_t stride;
+
+int _ion_alloc_test(int *fd, struct ion_handle **handle)
+{
+	int ret;
+
+	*fd = ion_open();
+	if (*fd < 0)
+		return *fd;
+
+	ret = ion_alloc(*fd, len, align, alloc_flags, handle);
+
+	if (ret)
+		printf("%s failed: %s\n", __func__, strerror(ret));
+	return ret;
+}
+
+void ion_alloc_test()
+{
+	int fd, ret;
+	struct ion_handle *handle;
+
+	if(_ion_alloc_test(&fd, &handle))
+			return;
+
+	ret = ion_free(fd, handle);
+	if (ret) {
+		printf("%s failed: %s %p\n", __func__, strerror(ret), handle);
+		return;
+	}
+	ion_close(fd);
+	printf("ion alloc test: passed\n");
+}
+
+void ion_map_test()
+{
+	int fd, map_fd, ret;
+	size_t i;
+	struct ion_handle *handle;
+	unsigned char *ptr;
+
+	if(_ion_alloc_test(&fd, &handle))
+		return;
+
+	ret = ion_map(fd, handle, len, prot, map_flags, 0, &ptr, &map_fd);
+	if (ret)
+		return;
+
+	for (i = 0; i < len; i++) {
+		ptr[i] = (unsigned char)i;
+	}
+	for (i = 0; i < len; i++)
+		if (ptr[i] != (unsigned char)i)
+			printf("%s failed wrote %d read %d from mapped "
+			       "memory\n", __func__, i, ptr[i]);
+	/* clean up properly */
+	ret = ion_free(fd, handle);
+	ion_close(fd);
+	munmap(ptr, len);
+	close(map_fd);
+
+	_ion_alloc_test(&fd, &handle);
+	close(fd);
+
+#if 0
+	munmap(ptr, len);
+	close(map_fd);
+	ion_close(fd);
+
+	_ion_alloc_test(len, align, flags, &fd, &handle);
+	close(map_fd);
+	ret = ion_map(fd, handle, len, prot, flags, 0, &ptr, &map_fd);
+	/* don't clean up */
+#endif
+}
+
+void ion_share_test()
+
+{
+	struct ion_handle *handle;
+	int sd[2];
+	int num_fd = 1;
+	struct iovec count_vec = {
+		.iov_base = &num_fd,
+		.iov_len = sizeof num_fd,
+	};
+	char buf[CMSG_SPACE(sizeof(int))];
+	socketpair(AF_UNIX, SOCK_STREAM, 0, sd);
+	if (fork()) {
+		struct msghdr msg = {
+			.msg_control = buf,
+			.msg_controllen = sizeof buf,
+			.msg_iov = &count_vec,
+			.msg_iovlen = 1,
+		};
+
+		struct cmsghdr *cmsg;
+		int fd, share_fd, ret;
+		char *ptr;
+		/* parent */
+		if(_ion_alloc_test(&fd, &handle))
+			return;
+		ret = ion_share(fd, handle, &share_fd);
+		if (ret)
+			printf("share failed %s\n", strerror(errno));
+		ptr = mmap(NULL, len, prot, map_flags, share_fd, 0);
+		if (ptr == MAP_FAILED) {
+			return;
+		}
+		strcpy(ptr, "master");
+		cmsg = CMSG_FIRSTHDR(&msg);
+		cmsg->cmsg_level = SOL_SOCKET;
+		cmsg->cmsg_type = SCM_RIGHTS;
+		cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+		*(int *)CMSG_DATA(cmsg) = share_fd;
+		/* send the fd */
+		printf("master? [%10s] should be [master]\n", ptr);
+		printf("master sending msg 1\n");
+		sendmsg(sd[0], &msg, 0);
+		if (recvmsg(sd[0], &msg, 0) < 0)
+			perror("master recv msg 2");
+		printf("master? [%10s] should be [child]\n", ptr);
+
+		/* send ping */
+		sendmsg(sd[0], &msg, 0);
+		printf("master->master? [%10s]\n", ptr);
+		if (recvmsg(sd[0], &msg, 0) < 0)
+			perror("master recv 1");
+	} else {
+		struct msghdr msg;
+		struct cmsghdr *cmsg;
+		char* ptr;
+		int fd, recv_fd;
+		char* child_buf[100];
+		/* child */
+		struct iovec count_vec = {
+			.iov_base = child_buf,
+			.iov_len = sizeof child_buf,
+		};
+
+		struct msghdr child_msg = {
+			.msg_control = buf,
+			.msg_controllen = sizeof buf,
+			.msg_iov = &count_vec,
+			.msg_iovlen = 1,
+		};
+
+		if (recvmsg(sd[1], &child_msg, 0) < 0)
+			perror("child recv msg 1");
+		cmsg = CMSG_FIRSTHDR(&child_msg);
+		if (cmsg == NULL) {
+			printf("no cmsg rcvd in child");
+			return;
+		}
+		recv_fd = *(int*)CMSG_DATA(cmsg);
+		if (recv_fd < 0) {
+			printf("could not get recv_fd from socket");
+			return;
+		}
+		printf("child %d\n", recv_fd);
+		fd = ion_open();
+		ptr = mmap(NULL, len, prot, map_flags, recv_fd, 0);
+		if (ptr == MAP_FAILED) {
+			return;
+		}
+		printf("child? [%10s] should be [master]\n", ptr);
+		strcpy(ptr, "child");
+		printf("child sending msg 2\n");
+		sendmsg(sd[1], &child_msg, 0);
+	}
+}
+
+int main(int argc, char* argv[]) {
+	int c;
+	enum tests {
+		ALLOC_TEST = 0, MAP_TEST, SHARE_TEST,
+	};
+
+	while (1) {
+		static struct option opts[] = {
+			{"alloc", no_argument, 0, 'a'},
+			{"alloc_flags", required_argument, 0, 'f'},
+			{"map", no_argument, 0, 'm'},
+			{"share", no_argument, 0, 's'},
+			{"len", required_argument, 0, 'l'},
+			{"align", required_argument, 0, 'g'},
+			{"map_flags", required_argument, 0, 'z'},
+			{"prot", required_argument, 0, 'p'},
+			{"width", required_argument, 0, 'w'},
+			{"height", required_argument, 0, 'h'},
+		};
+		int i = 0;
+		c = getopt_long(argc, argv, "af:h:l:mr:stw:", opts, &i);
+		if (c == -1)
+			break;
+
+		switch (c) {
+		case 'l':
+			len = atol(optarg);
+			break;
+		case 'g':
+			align = atol(optarg);
+			break;
+		case 'z':
+			map_flags = 0;
+			map_flags |= strstr(optarg, "PROT_EXEC") ?
+				PROT_EXEC : 0;
+			map_flags |= strstr(optarg, "PROT_READ") ?
+				PROT_READ: 0;
+			map_flags |= strstr(optarg, "PROT_WRITE") ?
+				PROT_WRITE: 0;
+			map_flags |= strstr(optarg, "PROT_NONE") ?
+				PROT_NONE: 0;
+			break;
+		case 'p':
+			prot = 0;
+			prot |= strstr(optarg, "MAP_PRIVATE") ?
+				MAP_PRIVATE	 : 0;
+			prot |= strstr(optarg, "MAP_SHARED") ?
+				MAP_PRIVATE	 : 0;
+			break;
+		case 'f':
+			alloc_flags = atol(optarg);
+			break;
+		case 'a':
+			test = ALLOC_TEST;
+			break;
+		case 'm':
+			test = MAP_TEST;
+			break;
+		case 's':
+			test = SHARE_TEST;
+			break;
+		case 'w':
+			width = atol(optarg);
+			break;
+		case 'h':
+			height = atol(optarg);
+			break;
+		}
+	}
+	printf("test %d, len %u, width %u, height %u align %u, "
+		   "map_flags %d, prot %d, alloc_flags %d\n", test, len, width,
+		   height, align, map_flags, prot, alloc_flags);
+	switch (test) {
+		case ALLOC_TEST:
+			ion_alloc_test();
+			break;
+		case MAP_TEST:
+			ion_map_test();
+			break;
+		case SHARE_TEST:
+			ion_share_test();
+			break;
+		default:
+			printf("must specify a test (alloc, map, share)\n");
+	}
+	return 0;
+}
diff --git a/liblog/Android.mk b/liblog/Android.mk
index bd4fed4..be5cec2 100644
--- a/liblog/Android.mk
+++ b/liblog/Android.mk
@@ -40,7 +40,8 @@
 
 liblog_host_sources := $(liblog_sources) fake_log_device.c
 
-# Static library for host
+
+# Shared and static library for host
 # ========================================================
 LOCAL_MODULE := liblog
 LOCAL_SRC_FILES := $(liblog_host_sources)
@@ -48,6 +49,22 @@
 LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1
 include $(BUILD_HOST_STATIC_LIBRARY)
 
+include $(CLEAR_VARS)
+LOCAL_MODULE := liblog
+LOCAL_WHOLE_STATIC_LIBRARIES := liblog
+include $(BUILD_HOST_SHARED_LIBRARY)
+
+
+# Static library for host, 64-bit
+# ========================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := lib64log
+LOCAL_SRC_FILES := $(liblog_host_sources)
+LOCAL_LDLIBS := -lpthread
+LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1 -m64
+include $(BUILD_HOST_STATIC_LIBRARY)
+
+
 # Shared and static library for target
 # ========================================================
 include $(CLEAR_VARS)
diff --git a/liblog/fake_log_device.c b/liblog/fake_log_device.c
index f8b7254..df43299 100644
--- a/liblog/fake_log_device.c
+++ b/liblog/fake_log_device.c
@@ -398,7 +398,7 @@
         break;
     case FORMAT_THREAD:
         prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "%c(%5d:%p) ", priChar, pid, (void*)tid);
+            "%c(%5d:%5d) ", priChar, pid, tid);
         strcpy(suffixBuf, "\n"); suffixLen = 1;
         break;
     case FORMAT_RAW:
@@ -417,8 +417,8 @@
         break;
     case FORMAT_LONG:
         prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-            "[ %s %5d:%p %c/%-8s ]\n",
-            timeBuf, pid, (void*)tid, priChar, tag);
+            "[ %s %5d:%5d %c/%-8s ]\n",
+            timeBuf, pid, tid, priChar, tag);
         strcpy(suffixBuf, "\n\n"); suffixLen = 2;
         break;
     default:
diff --git a/liblog/logprint.c b/liblog/logprint.c
index 8366c94..6fac84b 100644
--- a/liblog/logprint.c
+++ b/liblog/logprint.c
@@ -673,7 +673,7 @@
 
     if (inCount != 0) {
         fprintf(stderr,
-            "Warning: leftover binary log data (%d bytes)\n", inCount);
+            "Warning: leftover binary log data (%zu bytes)\n", inCount);
     }
 
     /*
@@ -753,7 +753,7 @@
             break;
         case FORMAT_THREAD:
             prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-                "%c(%5d:%p) ", priChar, entry->pid, (void*)entry->tid);
+                "%c(%5d:%5d) ", priChar, entry->pid, entry->tid);
             strcpy(suffixBuf, "\n");
             suffixLen = 1;
             break;
@@ -773,15 +773,15 @@
         case FORMAT_THREADTIME:
             prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
                 "%s.%03ld %5d %5d %c %-8s: ", timeBuf, entry->tv_nsec / 1000000,
-                (int)entry->pid, (int)entry->tid, priChar, entry->tag);
+                entry->pid, entry->tid, priChar, entry->tag);
             strcpy(suffixBuf, "\n");
             suffixLen = 1;
             break;
         case FORMAT_LONG:
             prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-                "[ %s.%03ld %5d:%p %c/%-8s ]\n",
+                "[ %s.%03ld %5d:%5d %c/%-8s ]\n",
                 timeBuf, entry->tv_nsec / 1000000, entry->pid,
-                (void*)entry->tid, priChar, entry->tag);
+                entry->tid, priChar, entry->tag);
             strcpy(suffixBuf, "\n\n");
             suffixLen = 2;
             prefixSuffixIsHeaderFooter = 1;
diff --git a/libnetutils/dhcp_utils.c b/libnetutils/dhcp_utils.c
old mode 100755
new mode 100644
index 1e08eb6..903a1db
--- a/libnetutils/dhcp_utils.c
+++ b/libnetutils/dhcp_utils.c
@@ -33,8 +33,28 @@
                                   /* when polling for property values */
 static const char DAEMON_NAME_RENEW[]  = "iprenew";
 static char errmsg[100];
-/* interface suffix on dhcpcd */
-#define MAX_DAEMON_SUFFIX 25
+/* interface length for dhcpcd daemon start (dhcpcd_<interface> as defined in init.rc file)
+ * or for filling up system properties dhcpcd.<interface>.ipaddress, dhcpcd.<interface>.dns1
+ * and other properties on a successful bind
+ */
+#define MAX_INTERFACE_LENGTH 25
+
+/*
+ * P2p interface names increase sequentially p2p-p2p0-1, p2p-p2p0-2.. after
+ * group formation. This does not work well with system properties which can quickly
+ * exhaust or for specifiying a dhcp start target in init which requires
+ * interface to be pre-defined in init.rc file.
+ *
+ * This function returns a common string p2p for all p2p interfaces.
+ */
+void get_p2p_interface_replacement(const char *interface, char *p2p_interface) {
+    /* Use p2p for any interface starting with p2p. */
+    if (strncmp(interface, "p2p",3) == 0) {
+        strncpy(p2p_interface, "p2p", MAX_INTERFACE_LENGTH);
+    } else {
+        strncpy(p2p_interface, interface, MAX_INTERFACE_LENGTH);
+    }
+}
 
 /*
  * Wait for a system property to be assigned a specified value.
@@ -70,18 +90,23 @@
                      char *dns1,
                      char *dns2,
                      char *server,
-                     uint32_t  *lease)
+                     uint32_t *lease,
+                     char *vendorInfo)
 {
     char prop_name[PROPERTY_KEY_MAX];
     char prop_value[PROPERTY_VALUE_MAX];
+    /* Interface name after converting p2p0-p2p0-X to p2p to reuse system properties */
+    char p2p_interface[MAX_INTERFACE_LENGTH];
 
-    snprintf(prop_name, sizeof(prop_name), "%s.%s.ipaddress", DHCP_PROP_NAME_PREFIX, interface);
+    get_p2p_interface_replacement(interface, p2p_interface);
+
+    snprintf(prop_name, sizeof(prop_name), "%s.%s.ipaddress", DHCP_PROP_NAME_PREFIX, p2p_interface);
     property_get(prop_name, ipaddr, NULL);
 
-    snprintf(prop_name, sizeof(prop_name), "%s.%s.gateway", DHCP_PROP_NAME_PREFIX, interface);
+    snprintf(prop_name, sizeof(prop_name), "%s.%s.gateway", DHCP_PROP_NAME_PREFIX, p2p_interface);
     property_get(prop_name, gateway, NULL);
 
-    snprintf(prop_name, sizeof(prop_name), "%s.%s.server", DHCP_PROP_NAME_PREFIX, interface);
+    snprintf(prop_name, sizeof(prop_name), "%s.%s.server", DHCP_PROP_NAME_PREFIX, p2p_interface);
     property_get(prop_name, server, NULL);
 
     //TODO: Handle IPv6 when we change system property usage
@@ -90,7 +115,7 @@
         strncpy(gateway, server, PROPERTY_VALUE_MAX);
     }
 
-    snprintf(prop_name, sizeof(prop_name), "%s.%s.mask", DHCP_PROP_NAME_PREFIX, interface);
+    snprintf(prop_name, sizeof(prop_name), "%s.%s.mask", DHCP_PROP_NAME_PREFIX, p2p_interface);
     if (property_get(prop_name, prop_value, NULL)) {
         int p;
         // this conversion is v4 only, but this dhcp client is v4 only anyway
@@ -112,16 +137,21 @@
         }
         *prefixLength = p;
     }
-    snprintf(prop_name, sizeof(prop_name), "%s.%s.dns1", DHCP_PROP_NAME_PREFIX, interface);
+    snprintf(prop_name, sizeof(prop_name), "%s.%s.dns1", DHCP_PROP_NAME_PREFIX, p2p_interface);
     property_get(prop_name, dns1, NULL);
 
-    snprintf(prop_name, sizeof(prop_name), "%s.%s.dns2", DHCP_PROP_NAME_PREFIX, interface);
+    snprintf(prop_name, sizeof(prop_name), "%s.%s.dns2", DHCP_PROP_NAME_PREFIX, p2p_interface);
     property_get(prop_name, dns2, NULL);
 
-    snprintf(prop_name, sizeof(prop_name), "%s.%s.leasetime", DHCP_PROP_NAME_PREFIX, interface);
+    snprintf(prop_name, sizeof(prop_name), "%s.%s.leasetime", DHCP_PROP_NAME_PREFIX, p2p_interface);
     if (property_get(prop_name, prop_value, NULL)) {
         *lease = atol(prop_value);
     }
+
+    snprintf(prop_name, sizeof(prop_name), "%s.%s.vendorInfo", DHCP_PROP_NAME_PREFIX,
+            p2p_interface);
+    property_get(prop_name, vendorInfo, NULL);
+
     return 0;
 }
 
@@ -133,18 +163,14 @@
     return inet_ntoa(in_addr);
 }
 
-void get_daemon_suffix(const char *interface, char *daemon_suffix) {
-    /* Use p2p suffix for any p2p interface. */
-    if (strncmp(interface, "p2p",3) == 0) {
-        sprintf(daemon_suffix, "p2p");
-    } else {
-        snprintf(daemon_suffix, MAX_DAEMON_SUFFIX, "%s", interface);
-    }
-}
-
 /*
  * 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,
@@ -153,7 +179,8 @@
                     char *dns1,
                     char *dns2,
                     char *server,
-                    uint32_t  *lease)
+                    uint32_t *lease,
+                    char *vendorInfo)
 {
     char result_prop_name[PROPERTY_KEY_MAX];
     char daemon_prop_name[PROPERTY_KEY_MAX];
@@ -161,27 +188,28 @@
     char daemon_cmd[PROPERTY_VALUE_MAX * 2];
     const char *ctrl_prop = "ctl.start";
     const char *desired_status = "running";
-    char daemon_suffix[MAX_DAEMON_SUFFIX];
+    /* Interface name after converting p2p0-p2p0-X to p2p to reuse system properties */
+    char p2p_interface[MAX_INTERFACE_LENGTH];
 
-    get_daemon_suffix(interface, daemon_suffix);
+    get_p2p_interface_replacement(interface, p2p_interface);
 
     snprintf(result_prop_name, sizeof(result_prop_name), "%s.%s.result",
             DHCP_PROP_NAME_PREFIX,
-            interface);
+            p2p_interface);
 
     snprintf(daemon_prop_name, sizeof(daemon_prop_name), "%s_%s",
             DAEMON_PROP_NAME,
-            daemon_suffix);
+            p2p_interface);
 
     /* Erase any previous setting of the dhcp result property */
     property_set(result_prop_name, "");
 
     /* Start the daemon and wait until it's ready */
     if (property_get(HOSTNAME_PROP_NAME, prop_value, NULL) && (prop_value[0] != '\0'))
-        snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s:-h %s %s", DAEMON_NAME, daemon_suffix,
+        snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s:-h %s %s", DAEMON_NAME, p2p_interface,
                  prop_value, interface);
     else
-        snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s:%s", DAEMON_NAME, daemon_suffix, interface);
+        snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s:%s", DAEMON_NAME, p2p_interface, interface);
     memset(prop_value, '\0', PROPERTY_VALUE_MAX);
     property_set(ctrl_prop, daemon_cmd);
     if (wait_for_property(daemon_prop_name, desired_status, 10) < 0) {
@@ -202,8 +230,8 @@
     }
     if (strcmp(prop_value, "ok") == 0) {
         char dns_prop_name[PROPERTY_KEY_MAX];
-        if (fill_ip_info(interface, ipaddr, gateway, prefixLength, dns1, dns2, server, lease)
-                == -1) {
+        if (fill_ip_info(interface, ipaddr, gateway, prefixLength,
+                dns1, dns2, server, lease, vendorInfo) == -1) {
             return -1;
         }
 
@@ -231,19 +259,19 @@
     const char *ctrl_prop = "ctl.stop";
     const char *desired_status = "stopped";
 
-    char daemon_suffix[MAX_DAEMON_SUFFIX];
+    char p2p_interface[MAX_INTERFACE_LENGTH];
 
-    get_daemon_suffix(interface, daemon_suffix);
+    get_p2p_interface_replacement(interface, p2p_interface);
 
     snprintf(result_prop_name, sizeof(result_prop_name), "%s.%s.result",
             DHCP_PROP_NAME_PREFIX,
-            interface);
+            p2p_interface);
 
     snprintf(daemon_prop_name, sizeof(daemon_prop_name), "%s_%s",
             DAEMON_PROP_NAME,
-            daemon_suffix);
+            p2p_interface);
 
-    snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s", DAEMON_NAME, daemon_suffix);
+    snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s", DAEMON_NAME, p2p_interface);
 
     /* Stop the daemon and wait until it's reported to be stopped */
     property_set(ctrl_prop, daemon_cmd);
@@ -264,15 +292,15 @@
     const char *ctrl_prop = "ctl.stop";
     const char *desired_status = "stopped";
 
-    char daemon_suffix[MAX_DAEMON_SUFFIX];
+    char p2p_interface[MAX_INTERFACE_LENGTH];
 
-    get_daemon_suffix(interface, daemon_suffix);
+    get_p2p_interface_replacement(interface, p2p_interface);
 
     snprintf(daemon_prop_name, sizeof(daemon_prop_name), "%s_%s",
             DAEMON_PROP_NAME,
-            daemon_suffix);
+            p2p_interface);
 
-    snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s", DAEMON_NAME, daemon_suffix);
+    snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s", DAEMON_NAME, p2p_interface);
 
     /* Stop the daemon and wait until it's reported to be stopped */
     property_set(ctrl_prop, daemon_cmd);
@@ -287,37 +315,41 @@
 }
 
 /**
- * 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,
-                    in_addr_t *gateway,
+                    char *ipaddr,
+                    char *gateway,
                     uint32_t *prefixLength,
-                    in_addr_t *dns1,
-                    in_addr_t *dns2,
-                    in_addr_t *server,
-                    uint32_t  *lease)
+                    char *dns1,
+                    char *dns2,
+                    char *server,
+                    uint32_t *lease,
+                    char *vendorInfo)
 {
     char result_prop_name[PROPERTY_KEY_MAX];
     char prop_value[PROPERTY_VALUE_MAX] = {'\0'};
     char daemon_cmd[PROPERTY_VALUE_MAX * 2];
     const char *ctrl_prop = "ctl.start";
 
-    char daemon_suffix[MAX_DAEMON_SUFFIX];
+    char p2p_interface[MAX_INTERFACE_LENGTH];
 
-    get_daemon_suffix(interface, daemon_suffix);
+    get_p2p_interface_replacement(interface, p2p_interface);
 
     snprintf(result_prop_name, sizeof(result_prop_name), "%s.%s.result",
             DHCP_PROP_NAME_PREFIX,
-            interface);
+            p2p_interface);
 
     /* Erase any previous setting of the dhcp result property */
     property_set(result_prop_name, "");
 
     /* Start the renew daemon and wait until it's ready */
     snprintf(daemon_cmd, sizeof(daemon_cmd), "%s_%s:%s", DAEMON_NAME_RENEW,
-            daemon_suffix, interface);
+            p2p_interface, interface);
     memset(prop_value, '\0', PROPERTY_VALUE_MAX);
     property_set(ctrl_prop, daemon_cmd);
 
@@ -333,7 +365,8 @@
         return -1;
     }
     if (strcmp(prop_value, "ok") == 0) {
-        fill_ip_info(interface, ipaddr, gateway, prefixLength, dns1, dns2, server, lease);
+        fill_ip_info(interface, ipaddr, gateway, prefixLength,
+                dns1, dns2, server, lease, vendorInfo);
         return 0;
     } else {
         snprintf(errmsg, sizeof(errmsg), "DHCP Renew result was %s", prop_value);
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/fixed.cpp b/libpixelflinger/fixed.cpp
index 5b92062..5094537 100644
--- a/libpixelflinger/fixed.cpp
+++ b/libpixelflinger/fixed.cpp
@@ -62,7 +62,8 @@
     int shift;
     x = gglRecipQNormalized(x, &shift);
     shift += 16-q;
-    x += 1L << (shift-1);   // rounding
+    if (shift > 0)
+        x += 1L << (shift-1);   // rounding
     x >>= shift;
     return x;
 }    
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..05c4945 100644
--- a/libpixelflinger/tinyutils/VectorImpl.cpp
+++ b/libpixelflinger/tinyutils/VectorImpl.cpp
@@ -57,7 +57,7 @@
 
 VectorImpl::~VectorImpl()
 {
-    LOG_ASSERT(!mCount,
+    ALOG_ASSERT(!mCount,
         "[%p] "
         "subclasses of VectorImpl must call finish_vector()"
         " in their destructor. Leaking %d bytes.",
@@ -67,7 +67,7 @@
 
 VectorImpl& VectorImpl::operator = (const VectorImpl& rhs)
 {
-    LOG_ASSERT(mItemSize == rhs.mItemSize,
+    ALOG_ASSERT(mItemSize == rhs.mItemSize,
         "Vector<> have different types (this=%p, rhs=%p)", this, &rhs);
     if (this != &rhs) {
         release_storage();
@@ -176,7 +176,7 @@
 
 ssize_t VectorImpl::replaceAt(const void* prototype, size_t index)
 {
-    LOG_ASSERT(index<size(),
+    ALOG_ASSERT(index<size(),
         "[%p] replace: index=%d, size=%d", this, (int)index, (int)size());
 
     void* item = editItemLocation(index);
@@ -193,7 +193,7 @@
 
 ssize_t VectorImpl::removeItemsAt(size_t index, size_t count)
 {
-    LOG_ASSERT((index+count)<=size(),
+    ALOG_ASSERT((index+count)<=size(),
         "[%p] remove: index=%d, count=%d, size=%d",
                this, (int)index, (int)count, (int)size());
 
@@ -217,7 +217,7 @@
 
 void* VectorImpl::editItemLocation(size_t index)
 {
-    LOG_ASSERT(index<capacity(),
+    ALOG_ASSERT(index<capacity(),
         "[%p] itemLocation: index=%d, capacity=%d, count=%d",
         this, (int)index, (int)capacity(), (int)mCount);
             
@@ -229,7 +229,7 @@
 
 const void* VectorImpl::itemLocation(size_t index) const
 {
-    LOG_ASSERT(index<capacity(),
+    ALOG_ASSERT(index<capacity(),
         "[%p] editItemLocation: index=%d, capacity=%d, count=%d",
         this, (int)index, (int)capacity(), (int)mCount);
 
@@ -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/libsuspend/Android.mk b/libsuspend/Android.mk
new file mode 100644
index 0000000..45cb701
--- /dev/null
+++ b/libsuspend/Android.mk
@@ -0,0 +1,23 @@
+# Copyright 2012 The Android Open Source Project
+
+LOCAL_PATH:= $(call my-dir)
+
+libsuspend_src_files := \
+	autosuspend.c \
+	autosuspend_autosleep.c \
+	autosuspend_earlysuspend.c \
+	autosuspend_wakeup_count.c \
+
+libsuspend_libraries := \
+	liblog libcutils
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(libsuspend_src_files)
+LOCAL_MODULE := libsuspend
+LOCAL_MODULE_TAGS := optional
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/include
+LOCAL_SHARED_LIBRARIES := $(libsuspend_libraries)
+#LOCAL_CFLAGS += -DLOG_NDEBUG=0
+include $(BUILD_SHARED_LIBRARY)
diff --git a/libsuspend/autosuspend.c b/libsuspend/autosuspend.c
new file mode 100644
index 0000000..7d1d973
--- /dev/null
+++ b/libsuspend/autosuspend.c
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2012 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 <stdbool.h>
+
+#define LOG_TAG "libsuspend"
+#include <cutils/log.h>
+
+#include <suspend/autosuspend.h>
+
+#include "autosuspend_ops.h"
+
+static struct autosuspend_ops *autosuspend_ops;
+static bool autosuspend_enabled;
+static bool autosuspend_inited;
+
+static int autosuspend_init(void)
+{
+    if (autosuspend_inited) {
+        return 0;
+    }
+
+    autosuspend_inited = true;
+
+    autosuspend_ops = autosuspend_earlysuspend_init();
+    if (autosuspend_ops) {
+        goto out;
+    }
+
+    autosuspend_ops = autosuspend_autosleep_init();
+    if (autosuspend_ops) {
+        goto out;
+    }
+
+    autosuspend_ops = autosuspend_wakeup_count_init();
+    if (autosuspend_ops) {
+        goto out;
+    }
+
+    if (!autosuspend_ops) {
+        ALOGE("failed to initialize autosuspend\n");
+        return -1;
+    }
+
+out:
+    ALOGV("autosuspend initialized\n");
+    return 0;
+}
+
+int autosuspend_enable(void)
+{
+    int ret;
+
+    ret = autosuspend_init();
+    if (ret) {
+        return ret;
+    }
+
+    ALOGV("autosuspend_enable\n");
+
+    if (autosuspend_enabled) {
+        return 0;
+    }
+
+    ret = autosuspend_ops->enable();
+    if (ret) {
+        return ret;
+    }
+
+    autosuspend_enabled = true;
+    return 0;
+}
+
+int autosuspend_disable(void)
+{
+    int ret;
+
+    ret = autosuspend_init();
+    if (ret) {
+        return ret;
+    }
+
+    ALOGV("autosuspend_disable\n");
+
+    if (!autosuspend_enabled) {
+        return 0;
+    }
+
+    ret = autosuspend_ops->disable();
+    if (ret) {
+        return ret;
+    }
+
+    autosuspend_enabled = false;
+    return 0;
+}
diff --git a/libsuspend/autosuspend_autosleep.c b/libsuspend/autosuspend_autosleep.c
new file mode 100644
index 0000000..dd0dfef
--- /dev/null
+++ b/libsuspend/autosuspend_autosleep.c
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stddef.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#define LOG_TAG "libsuspend"
+#include <cutils/log.h>
+
+#include "autosuspend_ops.h"
+
+#define SYS_POWER_AUTOSLEEP "/sys/power/autosleep"
+
+static int autosleep_fd;
+static const char *sleep_state = "mem";
+static const char *on_state = "off";
+
+static int autosuspend_autosleep_enable(void)
+{
+    char buf[80];
+    int ret;
+
+    ALOGV("autosuspend_autosleep_enable\n");
+
+    ret = write(autosleep_fd, sleep_state, strlen(sleep_state));
+    if (ret < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error writing to %s: %s\n", SYS_POWER_AUTOSLEEP, buf);
+        goto err;
+    }
+
+    ALOGV("autosuspend_autosleep_enable done\n");
+
+    return 0;
+
+err:
+    return ret;
+}
+
+static int autosuspend_autosleep_disable(void)
+{
+    char buf[80];
+    int ret;
+
+    ALOGV("autosuspend_autosleep_disable\n");
+
+    ret = write(autosleep_fd, on_state, strlen(on_state));
+    if (ret < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error writing to %s: %s\n", SYS_POWER_AUTOSLEEP, buf);
+        goto err;
+    }
+
+    ALOGV("autosuspend_autosleep_disable done\n");
+
+    return 0;
+
+err:
+    return ret;
+}
+
+struct autosuspend_ops autosuspend_autosleep_ops = {
+        .enable = autosuspend_autosleep_enable,
+        .disable = autosuspend_autosleep_disable,
+};
+
+struct autosuspend_ops *autosuspend_autosleep_init(void)
+{
+    int ret;
+    char buf[80];
+
+    autosleep_fd = open(SYS_POWER_AUTOSLEEP, O_WRONLY);
+    if (autosleep_fd < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error opening %s: %s\n", SYS_POWER_AUTOSLEEP, buf);
+        return NULL;
+    }
+
+    ALOGI("Selected autosleep\n");
+    return &autosuspend_autosleep_ops;
+}
diff --git a/libsuspend/autosuspend_earlysuspend.c b/libsuspend/autosuspend_earlysuspend.c
new file mode 100644
index 0000000..2c2aa36
--- /dev/null
+++ b/libsuspend/autosuspend_earlysuspend.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stddef.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define LOG_TAG "libsuspend"
+#include <cutils/log.h>
+
+#include "autosuspend_ops.h"
+
+#define EARLYSUSPEND_SYS_POWER_STATE "/sys/power/state"
+#define EARLYSUSPEND_WAIT_FOR_FB_SLEEP "/sys/power/wait_for_fb_sleep"
+#define EARLYSUSPEND_WAIT_FOR_FB_WAKE "/sys/power/wait_for_fb_wake"
+
+
+static int sPowerStatefd;
+static const char *pwr_state_mem = "mem";
+static const char *pwr_state_on = "on";
+
+static int autosuspend_earlysuspend_enable(void)
+{
+    char buf[80];
+    int ret;
+
+    ALOGV("autosuspend_earlysuspend_enable\n");
+
+    ret = write(sPowerStatefd, pwr_state_mem, strlen(pwr_state_mem));
+    if (ret < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error writing to %s: %s\n", EARLYSUSPEND_SYS_POWER_STATE, buf);
+        goto err;
+    }
+
+    ALOGV("autosuspend_earlysuspend_enable done\n");
+
+    return 0;
+
+err:
+    return ret;
+}
+
+static int autosuspend_earlysuspend_disable(void)
+{
+    char buf[80];
+    int ret;
+
+    ALOGV("autosuspend_earlysuspend_disable\n");
+
+    ret = write(sPowerStatefd, pwr_state_on, strlen(pwr_state_on));
+    if (ret < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error writing to %s: %s\n", EARLYSUSPEND_SYS_POWER_STATE, buf);
+        goto err;
+    }
+
+    ALOGV("autosuspend_earlysuspend_disable done\n");
+
+    return 0;
+
+err:
+    return ret;
+}
+
+struct autosuspend_ops autosuspend_earlysuspend_ops = {
+        .enable = autosuspend_earlysuspend_enable,
+        .disable = autosuspend_earlysuspend_disable,
+};
+
+struct autosuspend_ops *autosuspend_earlysuspend_init(void)
+{
+    char buf[80];
+    int ret;
+
+    ret = access(EARLYSUSPEND_WAIT_FOR_FB_SLEEP, F_OK);
+    if (ret < 0) {
+        return NULL;
+    }
+
+    ret = access(EARLYSUSPEND_WAIT_FOR_FB_WAKE, F_OK);
+    if (ret < 0) {
+        return NULL;
+    }
+
+    sPowerStatefd = open(EARLYSUSPEND_SYS_POWER_STATE, O_RDWR);
+
+    if (sPowerStatefd < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error opening %s: %s\n", EARLYSUSPEND_SYS_POWER_STATE, buf);
+        return NULL;
+    }
+
+    ALOGI("Selected early suspend\n");
+    return &autosuspend_earlysuspend_ops;
+}
diff --git a/libsuspend/autosuspend_ops.h b/libsuspend/autosuspend_ops.h
new file mode 100644
index 0000000..698e25b
--- /dev/null
+++ b/libsuspend/autosuspend_ops.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2012 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 _LIBSUSPEND_AUTOSUSPEND_OPS_H_
+#define _LIBSUSPEND_AUTOSUSPEND_OPS_H_
+
+struct autosuspend_ops {
+    int (*enable)(void);
+    int (*disable)(void);
+};
+
+struct autosuspend_ops *autosuspend_autosleep_init(void);
+struct autosuspend_ops *autosuspend_earlysuspend_init(void);
+struct autosuspend_ops *autosuspend_wakeup_count_init(void);
+
+#endif
diff --git a/libsuspend/autosuspend_wakeup_count.c b/libsuspend/autosuspend_wakeup_count.c
new file mode 100644
index 0000000..b038e20
--- /dev/null
+++ b/libsuspend/autosuspend_wakeup_count.c
@@ -0,0 +1,182 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <semaphore.h>
+#include <stddef.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#define LOG_TAG "libsuspend"
+#include <cutils/log.h>
+
+#include "autosuspend_ops.h"
+
+#define SYS_POWER_STATE "/sys/power/state"
+#define SYS_POWER_WAKEUP_COUNT "/sys/power/wakeup_count"
+
+static int state_fd;
+static int wakeup_count_fd;
+static pthread_t suspend_thread;
+static sem_t suspend_lockout;
+static const char *sleep_state = "mem";
+
+static void *suspend_thread_func(void *arg)
+{
+    char buf[80];
+    char wakeup_count[20];
+    int wakeup_count_len;
+    int ret;
+
+    while (1) {
+        usleep(100000);
+        ALOGV("%s: read wakeup_count\n", __func__);
+        lseek(wakeup_count_fd, 0, SEEK_SET);
+        wakeup_count_len = read(wakeup_count_fd, wakeup_count, sizeof(wakeup_count));
+        if (wakeup_count_len < 0) {
+            strerror_r(errno, buf, sizeof(buf));
+            ALOGE("Error reading from %s: %s\n", SYS_POWER_WAKEUP_COUNT, buf);
+            wakeup_count_len = 0;
+            continue;
+        }
+        if (!wakeup_count_len) {
+            ALOGE("Empty wakeup count\n");
+            continue;
+        }
+
+        ALOGV("%s: wait\n", __func__);
+        ret = sem_wait(&suspend_lockout);
+        if (ret < 0) {
+            strerror_r(errno, buf, sizeof(buf));
+            ALOGE("Error waiting on semaphore: %s\n", buf);
+            continue;
+        }
+
+        ALOGV("%s: write %*s to wakeup_count\n", __func__, wakeup_count_len, wakeup_count);
+        ret = write(wakeup_count_fd, wakeup_count, wakeup_count_len);
+        if (ret < 0) {
+            strerror_r(errno, buf, sizeof(buf));
+            ALOGE("Error writing to %s: %s\n", SYS_POWER_WAKEUP_COUNT, buf);
+        } else {
+            ALOGV("%s: write %s to %s\n", __func__, sleep_state, SYS_POWER_STATE);
+            ret = write(state_fd, sleep_state, strlen(sleep_state));
+            if (ret < 0) {
+                strerror_r(errno, buf, sizeof(buf));
+                ALOGE("Error writing to %s: %s\n", SYS_POWER_STATE, buf);
+            }
+        }
+
+        ALOGV("%s: release sem\n", __func__);
+        ret = sem_post(&suspend_lockout);
+        if (ret < 0) {
+            strerror_r(errno, buf, sizeof(buf));
+            ALOGE("Error releasing semaphore: %s\n", buf);
+        }
+    }
+    return NULL;
+}
+
+static int autosuspend_wakeup_count_enable(void)
+{
+    char buf[80];
+    int ret;
+
+    ALOGV("autosuspend_wakeup_count_enable\n");
+
+    ret = sem_post(&suspend_lockout);
+
+    if (ret < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error changing semaphore: %s\n", buf);
+    }
+
+    ALOGV("autosuspend_wakeup_count_enable done\n");
+
+    return ret;
+}
+
+static int autosuspend_wakeup_count_disable(void)
+{
+    char buf[80];
+    int ret;
+
+    ALOGV("autosuspend_wakeup_count_disable\n");
+
+    ret = sem_wait(&suspend_lockout);
+
+    if (ret < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error changing semaphore: %s\n", buf);
+    }
+
+    ALOGV("autosuspend_wakeup_count_disable done\n");
+
+    return ret;
+}
+
+struct autosuspend_ops autosuspend_wakeup_count_ops = {
+        .enable = autosuspend_wakeup_count_enable,
+        .disable = autosuspend_wakeup_count_disable,
+};
+
+struct autosuspend_ops *autosuspend_wakeup_count_init(void)
+{
+    int ret;
+    char buf[80];
+
+    state_fd = open(SYS_POWER_STATE, O_RDWR);
+    if (state_fd < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error opening %s: %s\n", SYS_POWER_STATE, buf);
+        goto err_open_state;
+    }
+
+    wakeup_count_fd = open(SYS_POWER_WAKEUP_COUNT, O_RDWR);
+    if (wakeup_count_fd < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error opening %s: %s\n", SYS_POWER_WAKEUP_COUNT, buf);
+        goto err_open_wakeup_count;
+    }
+
+    ret = sem_init(&suspend_lockout, 0, 0);
+    if (ret < 0) {
+        strerror_r(errno, buf, sizeof(buf));
+        ALOGE("Error creating semaphore: %s\n", buf);
+        goto err_sem_init;
+    }
+    ret = pthread_create(&suspend_thread, NULL, suspend_thread_func, NULL);
+    if (ret) {
+        strerror_r(ret, buf, sizeof(buf));
+        ALOGE("Error creating thread: %s\n", buf);
+        goto err_pthread_create;
+    }
+
+    ALOGI("Selected wakeup count\n");
+    return &autosuspend_wakeup_count_ops;
+
+err_pthread_create:
+    sem_destroy(&suspend_lockout);
+err_sem_init:
+    close(wakeup_count_fd);
+err_open_wakeup_count:
+    close(state_fd);
+err_open_state:
+    return NULL;
+}
diff --git a/libsuspend/include/suspend/autosuspend.h b/libsuspend/include/suspend/autosuspend.h
new file mode 100644
index 0000000..f56fc6a
--- /dev/null
+++ b/libsuspend/include/suspend/autosuspend.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2012 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 _LIBSUSPEND_AUTOSUSPEND_H_
+#define _LIBSUSPEND_AUTOSUSPEND_H_
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+
+/*
+ * autosuspend_enable
+ *
+ * Turn on autosuspend in the kernel, allowing it to enter suspend if no
+ * wakelocks/wakeup_sources are held.
+ *
+ *
+ *
+ * Returns 0 on success, -1 if autosuspend was not enabled.
+ */
+int autosuspend_enable(void);
+
+/*
+ * autosuspend_disable
+ *
+ * Turn off autosuspend in the kernel, preventing suspend and synchronizing
+ * with any in-progress resume.
+ *
+ * Returns 0 on success, -1 if autosuspend was not disabled.
+ */
+int autosuspend_disable(void);
+
+__END_DECLS
+
+#endif
diff --git a/libsync/Android.mk b/libsync/Android.mk
new file mode 100644
index 0000000..73de069
--- /dev/null
+++ b/libsync/Android.mk
@@ -0,0 +1,15 @@
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := sync.c
+LOCAL_MODULE := libsync
+LOCAL_MODULE_TAGS := optional
+LOCAL_SHARED_LIBRARIES := liblog
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := sync.c sync_test.c
+LOCAL_MODULE := sync_test
+LOCAL_MODULE_TAGS := optional tests
+LOCAL_SHARED_LIBRARIES := liblog
+include $(BUILD_EXECUTABLE)
diff --git a/libsync/sync.c b/libsync/sync.c
new file mode 100644
index 0000000..311da14
--- /dev/null
+++ b/libsync/sync.c
@@ -0,0 +1,115 @@
+/*
+ *  sync.c
+ *
+ *   Copyright 2012 Google, Inc
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#include <fcntl.h>
+#include <stdint.h>
+#include <string.h>
+
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <sync/sync.h>
+
+int sync_wait(int fd, unsigned int timeout)
+{
+    __u32 to = timeout;
+
+    return ioctl(fd, SYNC_IOC_WAIT, &to);
+}
+
+int sync_merge(const char *name, int fd1, int fd2)
+{
+    struct sync_merge_data data;
+    int err;
+
+    data.fd2 = fd2;
+    strlcpy(data.name, name, sizeof(data.name));
+
+    err = ioctl(fd1, SYNC_IOC_MERGE, &data);
+    if (err < 0)
+        return err;
+
+    return data.fence;
+}
+
+struct sync_fence_info_data *sync_fence_info(int fd)
+{
+    struct sync_fence_info_data *info;
+    int err;
+
+    info = malloc(4096);
+    if (info == NULL)
+        return NULL;
+
+    info->len = 4096;
+    err = ioctl(fd, SYNC_IOC_FENCE_INFO, info);
+    if (err < 0) {
+        free(info);
+        return NULL;
+    }
+
+    return info;
+}
+
+struct sync_pt_info *sync_pt_info(struct sync_fence_info_data *info,
+                                  struct sync_pt_info *itr)
+{
+    if (itr == NULL)
+        itr = (struct sync_pt_info *) info->pt_info;
+    else
+        itr = (struct sync_pt_info *) ((__u8 *)itr + itr->len);
+
+    if ((__u8 *)itr - (__u8 *)info >= (int)info->len)
+        return NULL;
+
+    return itr;
+}
+
+void sync_fence_info_free(struct sync_fence_info_data *info)
+{
+    free(info);
+}
+
+
+int sw_sync_timeline_create(void)
+{
+    return open("/dev/sw_sync", O_RDWR);
+}
+
+int sw_sync_timeline_inc(int fd, unsigned count)
+{
+    __u32 arg = count;
+
+    return ioctl(fd, SW_SYNC_IOC_INC, &arg);
+}
+
+int sw_sync_fence_create(int fd, const char *name, unsigned value)
+{
+    struct sw_sync_create_fence_data data;
+    int err;
+
+    data.value = value;
+    strlcpy(data.name, name, sizeof(data.name));
+
+    err = ioctl(fd, SW_SYNC_IOC_CREATE_FENCE, &data);
+    if (err < 0)
+        return err;
+
+    return data.fence;
+}
diff --git a/libsync/sync_test.c b/libsync/sync_test.c
new file mode 100644
index 0000000..a75f671
--- /dev/null
+++ b/libsync/sync_test.c
@@ -0,0 +1,146 @@
+/*
+ *  sync_test.c
+ *
+ *   Copyright 2012 Google, Inc
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#include <errno.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <sync/sync.h>
+
+pthread_mutex_t printf_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+struct sync_thread_data {
+    int thread_no;
+    int fd[2];
+};
+
+void *sync_thread(void *data)
+{
+    struct sync_thread_data *sync_data = data;
+    struct sync_fence_info_data *info;
+    int err;
+    int i;
+
+    for (i = 0; i < 2; i++) {
+        err = sync_wait(sync_data->fd[i], 10000);
+
+        pthread_mutex_lock(&printf_mutex);
+        if (err < 0) {
+            printf("thread %d wait %d failed: %s\n", sync_data->thread_no,
+                   i, strerror(errno));
+        } else {
+            printf("thread %d wait %d done\n", sync_data->thread_no, i);
+        }
+        info = sync_fence_info(sync_data->fd[i]);
+        if (info) {
+            struct sync_pt_info *pt_info = NULL;
+            printf("  fence %s %d\n", info->name, info->status);
+
+            while ((pt_info = sync_pt_info(info, pt_info))) {
+                int ts_sec = pt_info->timestamp_ns / 1000000000LL;
+                int ts_usec = (pt_info->timestamp_ns % 1000000000LL) / 1000LL;
+                printf("    pt %s %s %d %d.%06d", pt_info->obj_name,
+                       pt_info->driver_name, pt_info->status,
+                       ts_sec, ts_usec);
+                if (!strcmp(pt_info->driver_name, "sw_sync"))
+                    printf(" val=%d\n", *(uint32_t *)pt_info->driver_data);
+                else
+                    printf("\n");
+            }
+            sync_fence_info_free(info);
+        }
+        pthread_mutex_unlock(&printf_mutex);
+    }
+
+    return NULL;
+}
+
+int main(int argc, char *argv[])
+{
+    struct sync_thread_data sync_data[4];
+    pthread_t threads[4];
+    int sync_timeline_fd;
+    int i, j;
+    char str[256];
+
+    sync_timeline_fd = sw_sync_timeline_create();
+    if (sync_timeline_fd < 0) {
+        perror("can't create sw_sync_timeline:");
+        return 1;
+    }
+
+    for (i = 0; i < 3; i++) {
+        sync_data[i].thread_no = i;
+
+        for (j = 0; j < 2; j++) {
+            unsigned val = i + j * 3 + 1;
+            sprintf(str, "test_fence%d-%d", i, j);
+            int fd = sw_sync_fence_create(sync_timeline_fd, str, val);
+            if (fd < 0) {
+                printf("can't create sync pt %d: %s", val, strerror(errno));
+                return 1;
+            }
+            sync_data[i].fd[j] = fd;
+            printf("sync_data[%d].fd[%d] = %d;\n", i, j, fd);
+
+        }
+    }
+
+    sync_data[3].thread_no = 3;
+    for (j = 0; j < 2; j++) {
+        sprintf(str, "merged_fence%d", j);
+        sync_data[3].fd[j] = sync_merge(str, sync_data[0].fd[j], sync_data[1].fd[j]);
+        if (sync_data[3].fd[j] < 0) {
+            printf("can't merge sync pts %d and %d: %s\n",
+                   sync_data[0].fd[j], sync_data[1].fd[j], strerror(errno));
+            return 1;
+        }
+    }
+
+    for (i = 0; i < 4; i++)
+        pthread_create(&threads[i], NULL, sync_thread, &sync_data[i]);
+
+
+    for (i = 0; i < 3; i++) {
+        int err;
+        printf("press enter to inc to %d\n", i+1);
+        fgets(str, sizeof(str), stdin);
+        err = sw_sync_timeline_inc(sync_timeline_fd, 1);
+        if (err < 0) {
+            perror("can't increment sync obj:");
+            return 1;
+        }
+    }
+
+    printf("press enter to close sync_timeline\n");
+    fgets(str, sizeof(str), stdin);
+
+    close(sync_timeline_fd);
+
+    printf("press enter to end test\n");
+    fgets(str, sizeof(str), stdin);
+
+    for (i = 0; i < 3; i++) {
+        void *val;
+        pthread_join(threads[i], &val);
+    }
+
+    return 0;
+}
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..7aa5cad
--- /dev/null
+++ b/libsysutils/EventLogTags.logtags
@@ -0,0 +1,5 @@
+# See system/core/logcat/event.logtags for a description of the format of this file.
+
+# FrameworkListener dispatchCommand overflow
+78001 dispatchCommand_overflow
+65537 netlink_failure (uid|1)
diff --git a/libsysutils/src/FrameworkListener.cpp b/libsysutils/src/FrameworkListener.cpp
index 3416ceb..6731cf1 100644
--- a/libsysutils/src/FrameworkListener.cpp
+++ b/libsysutils/src/FrameworkListener.cpp
@@ -25,9 +25,21 @@
 #include <sysutils/FrameworkCommand.h>
 #include <sysutils/SocketClient.h>
 
+FrameworkListener::FrameworkListener(const char *socketName, bool withSeq) :
+                            SocketListener(socketName, true, withSeq) {
+    init(socketName, withSeq);
+}
+
 FrameworkListener::FrameworkListener(const char *socketName) :
-                            SocketListener(socketName, true) {
+                            SocketListener(socketName, true, false) {
+    init(socketName, false);
+}
+
+void FrameworkListener::init(const char *socketName, bool withSeq) {
     mCommands = new FrameworkCommandCollection();
+    errorRate = 0;
+    mCommandCount = 0;
+    mWithSeq = withSeq;
 }
 
 bool FrameworkListener::onDataAvailable(SocketClient *c) {
@@ -69,6 +81,7 @@
     bool esc = false;
     bool quote = false;
     int k;
+    bool haveCmdNum = !mWithSeq;
 
     memset(argv, 0, sizeof(argv));
     memset(tmp, 0, sizeof(tmp));
@@ -115,9 +128,20 @@
         *q = *p++;
         if (!quote && *q == ' ') {
             *q = '\0';
-            if (argc >= CMD_ARGS_MAX)
-                goto overflow;
-            argv[argc++] = strdup(tmp);
+            if (!haveCmdNum) {
+                char *endptr;
+                int cmdNum = (int)strtol(tmp, &endptr, 0);
+                if (endptr == NULL || *endptr != '\0') {
+                    cli->sendMsg(500, "Invalid sequence number", false);
+                    goto out;
+                }
+                cli->setCmdNum(cmdNum);
+                haveCmdNum = true;
+            } else {
+                if (argc >= CMD_ARGS_MAX)
+                    goto overflow;
+                argv[argc++] = strdup(tmp);
+            }
             memset(tmp, 0, sizeof(tmp));
             q = tmp;
             continue;
@@ -140,6 +164,12 @@
         goto out;
     }
 
+    if (errorRate && (++mCommandCount % errorRate == 0)) {
+        /* ignore this command - let the timeout handler handle it */
+        SLOGE("Faking a timeout");
+        goto out;
+    }
+
     for (i = mCommands->begin(); i != mCommands->end(); ++i) {
         FrameworkCommand *c = *i;
 
@@ -159,6 +189,7 @@
     return;
 
 overflow:
+    LOG_EVENT_INT(78001, cli->getUid());
     cli->sendMsg(500, "Command too long", false);
     goto out;
 }
diff --git a/libsysutils/src/NetlinkListener.cpp b/libsysutils/src/NetlinkListener.cpp
index e67b5c6..9c447ca 100644
--- a/libsysutils/src/NetlinkListener.cpp
+++ b/libsysutils/src/NetlinkListener.cpp
@@ -45,9 +45,13 @@
 {
     int socket = cli->getSocket();
     ssize_t count;
+    uid_t uid = -1;
 
-    count = TEMP_FAILURE_RETRY(uevent_kernel_multicast_recv(socket, mBuffer, sizeof(mBuffer)));
+    count = TEMP_FAILURE_RETRY(uevent_kernel_multicast_uid_recv(
+                                       socket, mBuffer, sizeof(mBuffer), &uid));
     if (count < 0) {
+        if (uid > 0)
+            LOG_EVENT_INT(65537, uid);
         SLOGE("recvmsg failed (%s)", strerror(errno));
         return false;
     }
diff --git a/libsysutils/src/SocketClient.cpp b/libsysutils/src/SocketClient.cpp
index 722dcb2..3d4984d 100644
--- a/libsysutils/src/SocketClient.cpp
+++ b/libsysutils/src/SocketClient.cpp
@@ -4,22 +4,32 @@
 #include <sys/types.h>
 #include <pthread.h>
 #include <string.h>
+#include <arpa/inet.h>
 
 #define LOG_TAG "SocketClient"
 #include <cutils/log.h>
 
 #include <sysutils/SocketClient.h>
 
-SocketClient::SocketClient(int socket, bool owned)
-        : mSocket(socket)
-        , mSocketOwned(owned)
-        , mPid(-1)
-        , mUid(-1)
-        , mGid(-1)
-        , mRefCount(1)
-{
+SocketClient::SocketClient(int socket, bool owned) {
+    init(socket, owned, false);
+}
+
+SocketClient::SocketClient(int socket, bool owned, bool useCmdNum) {
+    init(socket, owned, useCmdNum);
+}
+
+void SocketClient::init(int socket, bool owned, bool useCmdNum) {
+    mSocket = socket;
+    mSocketOwned = owned;
+    mUseCmdNum = useCmdNum;
     pthread_mutex_init(&mWriteMutex, NULL);
     pthread_mutex_init(&mRefCountMutex, NULL);
+    mPid = -1;
+    mUid = -1;
+    mGid = -1;
+    mRefCount = 1;
+    mCmdNum = 0;
 
     struct ucred creds;
     socklen_t szCreds = sizeof(creds);
@@ -41,34 +51,86 @@
 }
 
 int SocketClient::sendMsg(int code, const char *msg, bool addErrno) {
-    char *buf;
-    const char* arg;
-    const char* fmt;
-    char tmp[1];
-    int  len;
-
-    if (addErrno) {
-        fmt = "%.3d %s (%s)";
-        arg = strerror(errno);
-    } else {
-        fmt = "%.3d %s";
-        arg = NULL;
-    }
-    /* Measure length of required buffer */
-    len = snprintf(tmp, sizeof tmp, fmt, code, msg, arg);
-    /* Allocate in the stack, then write to it */
-    buf = (char*)alloca(len+1);
-    snprintf(buf, len+1, fmt, code, msg, arg);
-    /* Send the zero-terminated message */
-    return sendMsg(buf);
+    return sendMsg(code, msg, addErrno, mUseCmdNum);
 }
 
-int SocketClient::sendMsg(const char *msg) {
-    if (mSocket < 0) {
-        errno = EHOSTUNREACH;
-        return -1;
-    }
+int SocketClient::sendMsg(int code, const char *msg, bool addErrno, bool useCmdNum) {
+    char *buf;
+    int ret = 0;
 
+    if (addErrno) {
+        if (useCmdNum) {
+            ret = asprintf(&buf, "%d %d %s (%s)", code, getCmdNum(), msg, strerror(errno));
+        } else {
+            ret = asprintf(&buf, "%d %s (%s)", code, msg, strerror(errno));
+        }
+    } else {
+        if (useCmdNum) {
+            ret = asprintf(&buf, "%d %d %s", code, getCmdNum(), msg);
+        } else {
+            ret = asprintf(&buf, "%d %s", code, msg);
+        }
+    }
+    /* Send the zero-terminated message */
+    if (ret != -1) {
+        ret = sendMsg(buf);
+        free(buf);
+    }
+    return ret;
+}
+
+/** send 3-digit code, null, binary-length, binary data */
+int SocketClient::sendBinaryMsg(int code, const void *data, int len) {
+
+    /* 4 bytes for the code & null + 4 bytes for the len */
+    char buf[8];
+    /* Write the code */
+    snprintf(buf, 4, "%.3d", code);
+    /* Write the len */
+    uint32_t tmp = htonl(len);
+    memcpy(buf + 4, &tmp, sizeof(uint32_t));
+
+    pthread_mutex_lock(&mWriteMutex);
+    int result = sendDataLocked(buf, sizeof(buf));
+    if (result == 0 && len > 0) {
+        result = sendDataLocked(data, len);
+    }
+    pthread_mutex_unlock(&mWriteMutex);
+
+    return result;
+}
+
+// Sends the code (c-string null-terminated).
+int SocketClient::sendCode(int code) {
+    char buf[4];
+    snprintf(buf, sizeof(buf), "%.3d", code);
+    return sendData(buf, sizeof(buf));
+}
+
+char *SocketClient::quoteArg(const char *arg) {
+    int len = strlen(arg);
+    char *result = (char *)malloc(len * 2 + 3);
+    char *current = result;
+    const char *end = arg + len;
+
+    *(current++) = '"';
+    while (arg < end) {
+        switch (*arg) {
+        case '\\':
+        case '"':
+            *(current++) = '\\'; // fallthrough
+        default:
+            *(current++) = *(arg++);
+        }
+    }
+    *(current++) = '"';
+    *(current++) = '\0';
+    result = (char *)realloc(result, current-result);
+    return result;
+}
+
+
+int SocketClient::sendMsg(const char *msg) {
     // Send the message including null character
     if (sendData(msg, strlen(msg) + 1) != 0) {
         SLOGW("Unable to send msg '%s'", msg);
@@ -77,18 +139,31 @@
     return 0;
 }
 
-int SocketClient::sendData(const void* data, int len) {
+int SocketClient::sendData(const void *data, int len) {
+
+    pthread_mutex_lock(&mWriteMutex);
+    int rc = sendDataLocked(data, len);
+    pthread_mutex_unlock(&mWriteMutex);
+
+    return rc;
+}
+
+int SocketClient::sendDataLocked(const void *data, int len) {
     int rc = 0;
     const char *p = (const char*) data;
     int brtw = len;
 
+    if (mSocket < 0) {
+        errno = EHOSTUNREACH;
+        return -1;
+    }
+
     if (len == 0) {
         return 0;
     }
 
-    pthread_mutex_lock(&mWriteMutex);
     while (brtw > 0) {
-        rc = write(mSocket, p, brtw);
+        rc = send(mSocket, p, brtw, MSG_NOSIGNAL);
         if (rc > 0) {
             p += rc;
             brtw -= rc;
@@ -98,7 +173,6 @@
         if (rc < 0 && errno == EINTR)
             continue;
 
-        pthread_mutex_unlock(&mWriteMutex);
         if (rc == 0) {
             SLOGW("0 length write :(");
             errno = EIO;
@@ -107,7 +181,6 @@
         }
         return -1;
     }
-    pthread_mutex_unlock(&mWriteMutex);
     return 0;
 }
 
diff --git a/libsysutils/src/SocketListener.cpp b/libsysutils/src/SocketListener.cpp
index 3f871ea..0361641 100644
--- a/libsysutils/src/SocketListener.cpp
+++ b/libsysutils/src/SocketListener.cpp
@@ -29,18 +29,25 @@
 #include <sysutils/SocketListener.h>
 #include <sysutils/SocketClient.h>
 
+#define LOG_NDEBUG 0
+
 SocketListener::SocketListener(const char *socketName, bool listen) {
-    mListen = listen;
-    mSocketName = socketName;
-    mSock = -1;
-    pthread_mutex_init(&mClientsLock, NULL);
-    mClients = new SocketClientCollection();
+    init(socketName, -1, listen, false);
 }
 
 SocketListener::SocketListener(int socketFd, bool listen) {
+    init(NULL, socketFd, listen, false);
+}
+
+SocketListener::SocketListener(const char *socketName, bool listen, bool useCmdNum) {
+    init(socketName, -1, listen, useCmdNum);
+}
+
+void SocketListener::init(const char *socketName, int socketFd, bool listen, bool useCmdNum) {
     mListen = listen;
-    mSocketName = NULL;
+    mSocketName = socketName;
     mSock = socketFd;
+    mUseCmdNum = useCmdNum;
     pthread_mutex_init(&mClientsLock, NULL);
     mClients = new SocketClientCollection();
 }
@@ -73,13 +80,14 @@
                  mSocketName, strerror(errno));
             return -1;
         }
+        SLOGV("got mSock = %d for %s", mSock, mSocketName);
     }
 
     if (mListen && listen(mSock, 4) < 0) {
         SLOGE("Unable to listen on socket (%s)", strerror(errno));
         return -1;
     } else if (!mListen)
-        mClients->push_back(new SocketClient(mSock, false));
+        mClients->push_back(new SocketClient(mSock, false, mUseCmdNum));
 
     if (pipe(mCtrlPipe)) {
         SLOGE("pipe failed (%s)", strerror(errno));
@@ -164,11 +172,11 @@
                 max = fd;
         }
         pthread_mutex_unlock(&mClientsLock);
-
+        SLOGV("mListen=%d, max=%d, mSocketName=%s", mListen, max, mSocketName);
         if ((rc = select(max + 1, &read_fds, NULL, NULL, NULL)) < 0) {
             if (errno == EINTR)
                 continue;
-            SLOGE("select failed (%s)", strerror(errno));
+            SLOGE("select failed (%s) mListen=%d, max=%d", strerror(errno), mListen, max);
             sleep(1);
             continue;
         } else if (!rc)
@@ -184,6 +192,7 @@
             do {
                 alen = sizeof(addr);
                 c = accept(mSock, &addr, &alen);
+                SLOGV("%s got %d from accept", mSocketName, c);
             } while (c < 0 && errno == EINTR);
             if (c < 0) {
                 SLOGE("accept failed (%s)", strerror(errno));
@@ -191,7 +200,7 @@
                 continue;
             }
             pthread_mutex_lock(&mClientsLock);
-            mClients->push_back(new SocketClient(c, true));
+            mClients->push_back(new SocketClient(c, true, mUseCmdNum));
             pthread_mutex_unlock(&mClientsLock);
         }
 
@@ -217,6 +226,7 @@
              * connection-based, remove and destroy it */
             if (!onDataAvailable(c) && mListen) {
                 /* Remove the client from our array */
+                SLOGV("going to zap %d for %s", c->getSocket(), mSocketName);
                 pthread_mutex_lock(&mClientsLock);
                 for (it = mClients->begin(); it != mClients->end(); ++it) {
                     if (*it == c) {
@@ -238,19 +248,8 @@
     SocketClientCollection::iterator i;
 
     for (i = mClients->begin(); i != mClients->end(); ++i) {
-        if ((*i)->sendMsg(code, msg, addErrno)) {
-            SLOGW("Error sending broadcast (%s)", strerror(errno));
-        }
-    }
-    pthread_mutex_unlock(&mClientsLock);
-}
-
-void SocketListener::sendBroadcast(const char *msg) {
-    pthread_mutex_lock(&mClientsLock);
-    SocketClientCollection::iterator i;
-
-    for (i = mClients->begin(); i != mClients->end(); ++i) {
-        if ((*i)->sendMsg(msg)) {
+        // broadcasts are unsolicited and should not include a cmd number
+        if ((*i)->sendMsg(code, msg, addErrno, false)) {
             SLOGW("Error sending broadcast (%s)", strerror(errno));
         }
     }
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/logcat/logcat.cpp b/logcat/logcat.cpp
index ae56c41..b71ce86 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -253,7 +253,7 @@
     int max = 0;
     int ret;
     int queued_lines = 0;
-    bool sleep = true;
+    bool sleep = false;
 
     int result;
     fd_set readset;
diff --git a/logwrapper/logwrapper.c b/logwrapper/logwrapper.c
index bdf53e8..dd777c0 100644
--- a/logwrapper/logwrapper.c
+++ b/logwrapper/logwrapper.c
@@ -22,25 +22,26 @@
 #include <unistd.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <libgen.h>
 
 #include "private/android_filesystem_config.h"
 #include "cutils/log.h"
 
 void fatal(const char *msg) {
     fprintf(stderr, "%s", msg);
-    LOG(LOG_ERROR, "logwrapper", "%s", msg);
+    ALOG(LOG_ERROR, "logwrapper", "%s", msg);
     exit(-1);
 }
 
 void usage() {
     fatal(
-        "Usage: logwrapper [-x] BINARY [ARGS ...]\n"
+        "Usage: logwrapper [-d] BINARY [ARGS ...]\n"
         "\n"
         "Forks and executes BINARY ARGS, redirecting stdout and stderr to\n"
         "the Android logging system. Tag is set to BINARY, priority is\n"
         "always LOG_INFO.\n"
         "\n"
-        "-x: Causes logwrapper to SIGSEGV when BINARY terminates\n"
+        "-d: Causes logwrapper to SIGSEGV when BINARY terminates\n"
         "    fault address is set to the status of wait()\n");
 }
 
@@ -51,6 +52,10 @@
     int a = 0;  // start index of unprocessed data
     int b = 0;  // end index of unprocessed data
     int sz;
+
+    char *btag = basename(tag);
+    if (!btag) btag = (char*) tag;
+
     while ((sz = read(parent_read, &buffer[b], sizeof(buffer) - 1 - b)) > 0) {
 
         sz += b;
@@ -60,7 +65,7 @@
                 buffer[b] = '\0';
             } else if (buffer[b] == '\n') {
                 buffer[b] = '\0';
-                LOG(LOG_INFO, tag, "%s", &buffer[a]);
+                ALOG(LOG_INFO, btag, "%s", &buffer[a]);
                 a = b + 1;
             }
         }
@@ -68,7 +73,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, btag, "%s", &buffer[a]);
             b = 0;
         } else if (a != b) {
             // Keep left-overs
@@ -84,21 +89,21 @@
     // Flush remaining data
     if (a != b) {
         buffer[b] = '\0';
-	LOG(LOG_INFO, tag, "%s", &buffer[a]);
+        ALOG(LOG_INFO, btag, "%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,
+        if (WIFEXITED(status) && WEXITSTATUS(status))
+            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 +116,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/Android.mk b/nexus/Android.mk
deleted file mode 100644
index f9f7110..0000000
--- a/nexus/Android.mk
+++ /dev/null
@@ -1,66 +0,0 @@
-BUILD_NEXUS := false
-ifeq ($(BUILD_NEXUS),true)
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:=                                      \
-                  main.cpp                             \
-                  NexusCommand.cpp                     \
-                  CommandListener.cpp                  \
-                  Property.cpp                         \
-                  PropertyManager.cpp                  \
-                  InterfaceConfig.cpp                  \
-                  NetworkManager.cpp                   \
-                  Controller.cpp                       \
-                  WifiController.cpp                   \
-                  TiwlanWifiController.cpp             \
-                  TiwlanEventListener.cpp              \
-                  WifiNetwork.cpp                      \
-                  WifiStatusPoller.cpp                 \
-                  ScanResult.cpp                       \
-                  Supplicant.cpp                       \
-                  SupplicantEvent.cpp                  \
-                  SupplicantListener.cpp               \
-                  SupplicantState.cpp                  \
-                  SupplicantEventFactory.cpp           \
-                  SupplicantConnectedEvent.cpp         \
-                  SupplicantAssociatingEvent.cpp       \
-                  SupplicantAssociatedEvent.cpp        \
-                  SupplicantStateChangeEvent.cpp       \
-                  SupplicantScanResultsEvent.cpp       \
-                  SupplicantConnectionTimeoutEvent.cpp \
-                  SupplicantDisconnectedEvent.cpp      \
-                  SupplicantStatus.cpp                 \
-                  OpenVpnController.cpp                \
-                  VpnController.cpp                    \
-                  LoopController.cpp                   \
-                  DhcpClient.cpp DhcpListener.cpp      \
-                  DhcpState.cpp DhcpEvent.cpp          \
-
-LOCAL_MODULE:= nexus
-
-LOCAL_C_INCLUDES := $(KERNEL_HEADERS) -I../../../frameworks/base/include/
-
-LOCAL_CFLAGS := 
-
-LOCAL_SHARED_LIBRARIES := libsysutils libwpa_client
-
-include $(BUILD_EXECUTABLE)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES:=          \
-                  nexctl.c \
-
-LOCAL_MODULE:= nexctl
-
-LOCAL_C_INCLUDES := $(KERNEL_HEADERS)
-
-LOCAL_CFLAGS := 
-
-LOCAL_SHARED_LIBRARIES := libcutils
-
-include $(BUILD_EXECUTABLE)
-
-endif # ifeq ($(BUILD_NEXUS),true)
diff --git a/nexus/CommandListener.cpp b/nexus/CommandListener.cpp
deleted file mode 100644
index 5973ff5..0000000
--- a/nexus/CommandListener.cpp
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <errno.h>
-
-#define LOG_TAG "CommandListener"
-#include <cutils/log.h>
-
-#include <sysutils/SocketClient.h>
-
-#include "CommandListener.h"
-#include "Controller.h"
-#include "Property.h"
-#include "NetworkManager.h"
-#include "WifiController.h"
-#include "VpnController.h"
-#include "ResponseCode.h"
-
-CommandListener::CommandListener() :
-                 FrameworkListener("nexus") {
-    registerCmd(new WifiScanResultsCmd());
-    registerCmd(new WifiListNetworksCmd());
-    registerCmd(new WifiCreateNetworkCmd());
-    registerCmd(new WifiRemoveNetworkCmd());
-
-    registerCmd(new GetCmd());
-    registerCmd(new SetCmd());
-    registerCmd(new ListCmd());
-}
-
-/* -------------
- * Wifi Commands
- * ------------ */
-
-CommandListener::WifiCreateNetworkCmd::WifiCreateNetworkCmd() :
-                 NexusCommand("wifi_create_network") {
-}
-
-int CommandListener::WifiCreateNetworkCmd::runCommand(SocketClient *cli,
-                                                      int argc, char **argv) {
-    NetworkManager *nm = NetworkManager::Instance();
-    WifiController *wc = (WifiController *) nm->findController("WIFI");
-    WifiNetwork *wn;
-
-    if (!(wn = wc->createNetwork()))
-        cli->sendMsg(ResponseCode::OperationFailed, "Failed to create network", true);
-    else {
-        char tmp[128];
-        sprintf(tmp, "Created network id %d.", wn->getNetworkId());
-        cli->sendMsg(ResponseCode::CommandOkay, tmp, false);
-    }
-    return 0;
-}
-
-CommandListener::WifiRemoveNetworkCmd::WifiRemoveNetworkCmd() :
-                 NexusCommand("wifi_remove_network") {
-}
-
-int CommandListener::WifiRemoveNetworkCmd::runCommand(SocketClient *cli,
-                                                      int argc, char **argv) {
-    NetworkManager *nm = NetworkManager::Instance();
-    WifiController *wc = (WifiController *) nm->findController("WIFI");
-
-    if (wc->removeNetwork(atoi(argv[1])))
-        cli->sendMsg(ResponseCode::OperationFailed, "Failed to remove network", true);
-    else {
-        cli->sendMsg(ResponseCode::CommandOkay, "Network removed.", false);
-    }
-    return 0;
-}
-
-CommandListener::WifiScanResultsCmd::WifiScanResultsCmd() :
-                 NexusCommand("wifi_scan_results") {
-}
-
-int CommandListener::WifiScanResultsCmd::runCommand(SocketClient *cli,
-                                                    int argc, char **argv) {
-    NetworkManager *nm = NetworkManager::Instance();
-    WifiController *wc = (WifiController *) nm->findController("WIFI");
-
-    ScanResultCollection *src = wc->createScanResults();
-    ScanResultCollection::iterator it;
-    char buffer[256];
-
-    for(it = src->begin(); it != src->end(); ++it) {
-        sprintf(buffer, "%s %u %d %s %s",
-                (*it)->getBssid(), (*it)->getFreq(), (*it)->getLevel(),
-                (*it)->getFlags(), (*it)->getSsid());
-        cli->sendMsg(ResponseCode::WifiScanResult, buffer, false);
-        delete (*it);
-        it = src->erase(it);
-    }
-
-    delete src;
-    cli->sendMsg(ResponseCode::CommandOkay, "Scan results complete.", false);
-    return 0;
-}
-
-CommandListener::WifiListNetworksCmd::WifiListNetworksCmd() :
-                 NexusCommand("wifi_list_networks") {
-}
-
-int CommandListener::WifiListNetworksCmd::runCommand(SocketClient *cli,
-                                                     int argc, char **argv) {
-    NetworkManager *nm = NetworkManager::Instance();
-    WifiController *wc = (WifiController *) nm->findController("WIFI");
-
-    WifiNetworkCollection *src = wc->createNetworkList();
-    WifiNetworkCollection::iterator it;
-    char buffer[256];
-
-    for(it = src->begin(); it != src->end(); ++it) {
-        sprintf(buffer, "%d:%s", (*it)->getNetworkId(), (*it)->getSsid());
-        cli->sendMsg(ResponseCode::WifiNetworkList, buffer, false);
-        delete (*it);
-    }
-
-    delete src;
-    cli->sendMsg(ResponseCode::CommandOkay, "Network listing complete.", false);
-    return 0;
-}
-
-/* ------------
- * Vpn Commands
- * ------------ */
-
-/* ----------------
- * Generic Commands
- * ---------------- */
-CommandListener::GetCmd::GetCmd() :
-                 NexusCommand("get") {
-}
-
-int CommandListener::GetCmd::runCommand(SocketClient *cli, int argc, char **argv) {
-    char val[Property::ValueMaxSize];
-
-    if (!NetworkManager::Instance()->getPropMngr()->get(argv[1],
-                                                        val,
-                                                        sizeof(val))) {
-        goto out_inval;
-    }
-
-    char *tmp;
-    asprintf(&tmp, "%s %s", argv[1], val);
-    cli->sendMsg(ResponseCode::PropertyRead, tmp, false);
-    free(tmp);
-
-    cli->sendMsg(ResponseCode::CommandOkay, "Property read.", false);
-    return 0;
-out_inval:
-    errno = EINVAL;
-    cli->sendMsg(ResponseCode::CommandParameterError, "Failed to read property.", true);
-    return 0;
-}
-
-CommandListener::SetCmd::SetCmd() :
-                 NexusCommand("set") {
-}
-
-int CommandListener::SetCmd::runCommand(SocketClient *cli, int argc,
-                                        char **argv) {
-    if (NetworkManager::Instance()->getPropMngr()->set(argv[1], argv[2]))
-        goto out_inval;
-
-    cli->sendMsg(ResponseCode::CommandOkay, "Property set.", false);
-    return 0;
-
-out_inval:
-    errno = EINVAL;
-    cli->sendMsg(ResponseCode::CommandParameterError, "Failed to set property.", true);
-    return 0;
-}
-
-CommandListener::ListCmd::ListCmd() :
-                 NexusCommand("list") {
-}
-
-int CommandListener::ListCmd::runCommand(SocketClient *cli, int argc, char **argv) {
-    android::List<char *> *pc;
-    char *prefix = NULL;
-
-    if (argc > 1)
-        prefix = argv[1];
-
-    if (!(pc = NetworkManager::Instance()->getPropMngr()->createPropertyList(prefix))) {
-        errno = ENODATA;
-        cli->sendMsg(ResponseCode::CommandParameterError, "Failed to list properties.", true);
-        return 0;
-    }
-
-    android::List<char *>::iterator it;
-
-    for (it = pc->begin(); it != pc->end(); ++it) {
-        char p_v[Property::ValueMaxSize];
-
-        if (!NetworkManager::Instance()->getPropMngr()->get((*it),
-                                                            p_v,
-                                                            sizeof(p_v))) {
-            LOGW("Failed to get %s (%s)", (*it), strerror(errno));
-        }
-
-        char *buf;
-        if (asprintf(&buf, "%s %s", (*it), p_v) < 0) {
-            LOGE("Failed to allocate memory");
-            free((*it));
-            continue;
-        }
-        cli->sendMsg(ResponseCode::PropertyList, buf, false);
-        free(buf);
-
-        free((*it));
-    }
-
-    delete pc;
-
-    cli->sendMsg(ResponseCode::CommandOkay, "Properties list complete.", false);
-    return 0;
-}
diff --git a/nexus/CommandListener.h b/nexus/CommandListener.h
deleted file mode 100644
index 30c6dc0..0000000
--- a/nexus/CommandListener.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _COMMANDLISTENER_H__
-#define _COMMANDLISTENER_H__
-
-#include <sysutils/FrameworkListener.h>
-#include "NexusCommand.h"
-
-class CommandListener : public FrameworkListener {
-public:
-    CommandListener();
-    virtual ~CommandListener() {}
-
-private:
-
-    class WifiScanCmd : public NexusCommand {
-    public:
-        WifiScanCmd();
-        virtual ~WifiScanCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
-
-    class WifiScanResultsCmd : public NexusCommand {
-    public:
-        WifiScanResultsCmd();
-        virtual ~WifiScanResultsCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
-
-    class WifiCreateNetworkCmd : public NexusCommand {
-    public:
-        WifiCreateNetworkCmd();
-        virtual ~WifiCreateNetworkCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
-
-    class WifiRemoveNetworkCmd : public NexusCommand {
-    public:
-        WifiRemoveNetworkCmd();
-        virtual ~WifiRemoveNetworkCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
-
-    class WifiListNetworksCmd : public NexusCommand {
-    public:
-        WifiListNetworksCmd();
-        virtual ~WifiListNetworksCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
-
-    class SetCmd : public NexusCommand {
-    public:
-        SetCmd();
-        virtual ~SetCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
-
-    class GetCmd : public NexusCommand {
-    public:
-        GetCmd();
-        virtual ~GetCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
-
-    class ListCmd : public NexusCommand {
-    public:
-        ListCmd();
-        virtual ~ListCmd() {}
-        int runCommand(SocketClient *c, int argc, char ** argv);
-    };
-};
-
-#endif
diff --git a/nexus/Controller.cpp b/nexus/Controller.cpp
deleted file mode 100644
index f6a2436..0000000
--- a/nexus/Controller.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <malloc.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#define LOG_TAG "Controller"
-
-#include <cutils/log.h>
-
-#include "Controller.h"
-#include "InterfaceConfig.h"
-
-extern "C" int init_module(void *, unsigned int, const char *);
-extern "C" int delete_module(const char *, unsigned int);
-
-Controller::Controller(const char *name, PropertyManager *propMngr,
-                       IControllerHandler *handlers) {
-    mPropMngr = propMngr;
-    mName = strdup(name);
-    mHandlers = handlers;
-    mBoundInterface = NULL;
-}
-
-Controller::~Controller() {
-    if (mBoundInterface)
-        free(mBoundInterface);
-    if (mName)
-        free(mName);
-}
-
-int Controller::start() {
-    return 0;
-}
-
-int Controller::stop() {
-    return 0;
-}
-
-int Controller::loadKernelModule(char *modpath, const char *args) {
-    void *module;
-    unsigned int size;
-
-    module = loadFile(modpath, &size);
-    if (!module) {
-        errno = -EIO;
-        return -1;
-    }
-
-    int rc = init_module(module, size, args);
-    free (module);
-    return rc;
-}
-
-int Controller::unloadKernelModule(const char *modtag) {
-    int rc = -1;
-    int retries = 10;
-
-    while (retries--) {
-        rc = delete_module(modtag, O_NONBLOCK | O_EXCL);
-        if (rc < 0 && errno == EAGAIN)
-            usleep(1000*500);
-        else
-            break;
-    }
-
-    if (rc != 0) {
-        LOGW("Unable to unload kernel driver '%s' (%s)", modtag,
-             strerror(errno));
-    }
-    return rc;
-}
-
-bool Controller::isKernelModuleLoaded(const char *modtag) {
-    FILE *fp = fopen("/proc/modules", "r");
-
-    if (!fp) {
-        LOGE("Unable to open /proc/modules (%s)", strerror(errno));
-        return false;
-    }
-
-    char line[255];
-    while(fgets(line, sizeof(line), fp)) {
-        char *endTag = strchr(line, ' ');
-
-        if (!endTag) {
-            LOGW("Unable to find tag for line '%s'", line);
-            continue;
-        }
-        if (!strncmp(line, modtag, (endTag - line))) {
-            fclose(fp);
-            return true;
-        }
-    }
-
-    fclose(fp);
-    return false;
-}
-
-void *Controller::loadFile(char *filename, unsigned int *_size)
-{
-	int ret, fd;
-	struct stat sb;
-	ssize_t size;
-	void *buffer = NULL;
-
-	/* open the file */
-	fd = open(filename, O_RDONLY);
-	if (fd < 0)
-		return NULL;
-
-	/* find out how big it is */
-	if (fstat(fd, &sb) < 0)
-		goto bail;
-	size = sb.st_size;
-
-	/* allocate memory for it to be read into */
-	buffer = malloc(size);
-	if (!buffer)
-		goto bail;
-
-	/* slurp it into our buffer */
-	ret = read(fd, buffer, size);
-	if (ret != size)
-		goto bail;
-
-	/* let the caller know how big it is */
-	*_size = size;
-
-bail:
-	close(fd);
-	return buffer;
-}
-
-int Controller::bindInterface(const char *ifname) {
-    mBoundInterface = strdup(ifname);
-    return 0;
-}
-
-int Controller::unbindInterface(const char *ifname) {
-    free(mBoundInterface);
-    mBoundInterface = NULL;
-    return 0;
-}
diff --git a/nexus/Controller.h b/nexus/Controller.h
deleted file mode 100644
index e7e17c5..0000000
--- a/nexus/Controller.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _CONTROLLER_H
-#define _CONTROLLER_H
-
-#include <unistd.h>
-#include <sys/types.h>
-
-#include <utils/List.h>
-
-class PropertyManager;
-class IControllerHandler;
-
-#include "PropertyManager.h"
-
-class Controller {
-    /*
-     * Name of this controller - WIFI/VPN/USBNET/BTNET/BTDUN/LOOP/etc
-     */
-    char *mName;
-
-    /*
-     * Name of the system ethernet interface which this controller is
-     * bound to.
-     */
-    char *mBoundInterface;
-
-protected:
-    PropertyManager *mPropMngr;
-    IControllerHandler *mHandlers;
-    
-public:
-    Controller(const char *name, PropertyManager *propMngr,
-               IControllerHandler *handlers);
-    virtual ~Controller();
-
-    virtual int start();
-    virtual int stop();
-
-    const char *getName() { return mName; }
-    const char *getBoundInterface() { return mBoundInterface; }
-    
-protected:
-    int loadKernelModule(char *modpath, const char *args);
-    bool isKernelModuleLoaded(const char *modtag);
-    int unloadKernelModule(const char *modtag);
-    int bindInterface(const char *ifname);
-    int unbindInterface(const char *ifname);
-
-private:
-    void *loadFile(char *filename, unsigned int *_size);
-};
-
-typedef android::List<Controller *> ControllerCollection;
-#endif
diff --git a/nexus/DhcpClient.cpp b/nexus/DhcpClient.cpp
deleted file mode 100644
index 713059d..0000000
--- a/nexus/DhcpClient.cpp
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#include <pthread.h>
-
-#define LOG_TAG "DhcpClient"
-#include <cutils/log.h>
-#include <cutils/properties.h>
-
-#include <sysutils/ServiceManager.h>
-
-#include <netutils/ifc.h>
-#include <netutils/dhcp.h>
-
-#include "DhcpClient.h"
-#include "DhcpState.h"
-#include "DhcpListener.h"
-#include "IDhcpEventHandlers.h"
-#include "Controller.h"
-
-DhcpClient::DhcpClient(IDhcpEventHandlers *handlers) :
-            mState(DhcpState::INIT), mHandlers(handlers) {
-    mServiceManager = new ServiceManager();
-    mListener = NULL;
-    mListenerSocket = NULL;
-    mController = NULL;
-    mDoArpProbe = false;
-    pthread_mutex_init(&mLock, NULL);
-}
-
-DhcpClient::~DhcpClient() {
-    delete mServiceManager;
-    if (mListener)
-        delete mListener;
-}
-
-int DhcpClient::start(Controller *c) {
-    LOGD("Starting DHCP service (arp probe = %d)", mDoArpProbe);
-    char svc[PROPERTY_VALUE_MAX];
-    snprintf(svc,
-             sizeof(svc),
-             "dhcpcd:%s%s",
-             (!mDoArpProbe ? "-A " : ""),
-             c->getBoundInterface());
-
-    pthread_mutex_lock(&mLock);
-
-    if (mController) {
-        pthread_mutex_unlock(&mLock);
-        errno = EBUSY;
-        return -1;
-    }
-    mController = c;
-
-    sockaddr_in addr;
-    if ((mListenerSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
-        LOGE("Failed to create DHCP listener socket");
-        pthread_mutex_unlock(&mLock);
-        return -1;
-    }
-    memset(&addr, 0, sizeof(addr));
-    addr.sin_family = AF_INET;
-    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
-    addr.sin_port = htons(DhcpClient::STATUS_MONITOR_PORT);
-
-    if (bind(mListenerSocket, (struct sockaddr *) &addr, sizeof(addr))) {
-        LOGE("Failed to bind DHCP listener socket");
-        close(mListenerSocket);
-        mListenerSocket = -1;
-        pthread_mutex_unlock(&mLock);
-        return -1;
-    }
-
-    if (mServiceManager->start(svc)) {
-        LOGE("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");
-#if 0
-        mServiceManager->stop("dhcpcd");
-        return -1;
-#endif
-        delete mListener;
-        mListener = NULL;
-        pthread_mutex_unlock(&mLock);
-    }
-
-    pthread_mutex_unlock(&mLock);
-    return 0;
-}
-
-int DhcpClient::stop() {
-    pthread_mutex_lock(&mLock);
-    if (!mController) {
-        pthread_mutex_unlock(&mLock);
-        return 0;
-    }
-
-    if (mListener) {
-        mListener->stopListener();
-        delete mListener;
-        mListener = NULL;
-    }
-    close(mListenerSocket);
-
-    if (mServiceManager->stop("dhcpcd")) {
-        LOGW("Failed to stop DHCP service (%s)", strerror(errno));
-        // XXX: Kill it the hard way.. but its gotta go!
-    }
-
-    mController = NULL;
-    pthread_mutex_unlock(&mLock);
-    return 0;
-}
-
-void DhcpClient::setDoArpProbe(bool probe) {
-    mDoArpProbe = probe;
-}
diff --git a/nexus/DhcpClient.h b/nexus/DhcpClient.h
deleted file mode 100644
index 42bfda0..0000000
--- a/nexus/DhcpClient.h
+++ /dev/null
@@ -1,54 +0,0 @@
-
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _DhcpClient_H
-#define _DhcpClient_H
-
-#include <pthread.h>
-
-class IDhcpEventHandlers;
-class ServiceManager;
-class DhcpListener;
-class Controller;
-
-class DhcpClient {
-public:
-    static const int STATUS_MONITOR_PORT = 6666;
-
-private:
-    int                mState;
-    IDhcpEventHandlers *mHandlers;
-    ServiceManager     *mServiceManager;
-    DhcpListener       *mListener;
-    int                mListenerSocket;
-    pthread_mutex_t    mLock;
-    Controller         *mController;
-    bool               mDoArpProbe;
-
-public:
-    DhcpClient(IDhcpEventHandlers *handlers);
-    virtual ~DhcpClient();
-
-    int getState() { return mState; }
-    bool getDoArpProbe() { return mDoArpProbe; }
-    void setDoArpProbe(bool probe);
-
-    int start(Controller *c);
-    int stop();
-};
-
-#endif
diff --git a/nexus/DhcpEvent.cpp b/nexus/DhcpEvent.cpp
deleted file mode 100644
index 58893f4..0000000
--- a/nexus/DhcpEvent.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-
-#define LOG_TAG "DhcpEvent"
-#include <cutils/log.h>
-
-#include "DhcpEvent.h"
-
-char *DhcpEvent::toString(int val, char *buffer, int max) {
-    if (val == DhcpEvent::UNKNOWN)
-        strncpy(buffer, "UNKNOWN", max);
-    else if (val == DhcpEvent::STOP)
-        strncpy(buffer, "STOP", max);
-    else if (val == DhcpEvent::RENEW)
-        strncpy(buffer, "RENEW", max);
-    else if (val == DhcpEvent::RELEASE)
-        strncpy(buffer, "RELEASE", max);
-    else if (val == DhcpEvent::TIMEOUT)
-        strncpy(buffer, "TIMEOUT", max);
-    else
-        strncpy(buffer, "(internal error)", max);
-
-    return buffer;
-}
-
-int DhcpEvent::parseString(const char *buffer) {
-    if (!strcasecmp(buffer, "UNKNOWN"))
-        return DhcpEvent::UNKNOWN;
-    else if (!strcasecmp(buffer, "STOP"))
-        return DhcpEvent::STOP;
-    else if (!strcasecmp(buffer, "RENEW"))
-        return DhcpEvent::RENEW;
-    else if (!strcasecmp(buffer, "RELEASE"))
-        return DhcpEvent::RELEASE;
-    else if (!strcasecmp(buffer, "TIMEOUT"))
-        return DhcpEvent::TIMEOUT;
-    else {
-        LOGW("Bad event '%s'", buffer);
-        return -1;
-    }
-}
diff --git a/nexus/DhcpEvent.h b/nexus/DhcpEvent.h
deleted file mode 100644
index f77834d..0000000
--- a/nexus/DhcpEvent.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _DHCP_EVENT_H
-#define _DHCP_EVENT_H
-
-class DhcpEvent {
-public:
-    static const int UNKNOWN = 0;
-    static const int STOP    = 1;
-    static const int RENEW   = 2;
-    static const int RELEASE = 3;
-    static const int TIMEOUT = 4;
-
-    static char *toString(int val, char *buffer, int max);
-
-    static int parseString(const char *buffer);
-};
-
-#endif
diff --git a/nexus/DhcpListener.cpp b/nexus/DhcpListener.cpp
deleted file mode 100644
index afa68eb..0000000
--- a/nexus/DhcpListener.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-#define LOG_TAG "DhcpListener"
-#include <cutils/log.h>
-
-#include <DhcpListener.h>
-#include "IDhcpEventHandlers.h"
-#include "DhcpState.h"
-#include "DhcpEvent.h"
-#include "Controller.h"
-
-DhcpListener::DhcpListener(Controller *c, int socket, IDhcpEventHandlers *handlers) :
-              SocketListener(socket, false) {
-    mHandlers = handlers;
-    mController = c;
-}
-
-DhcpListener::~DhcpListener() {
-}
-
-bool DhcpListener::onDataAvailable(SocketClient *cli) {
-    char buffer[255];
-    int rc;
-
-    if ((rc = read(cli->getSocket(), buffer, sizeof(buffer))) < 0) {
-        LOGW("Error reading dhcp status msg (%s)", strerror(errno));
-        return true;
-    }
-
-    if (!strncmp(buffer, "STATE:", 6)) {
-        char *next = buffer;
-        char *tmp;
-        int i;
-
-        for (i = 0; i < 2; i++) {
-            if (!(tmp = strsep(&next, ":"))) {
-                LOGW("Error parsing state '%s'", buffer);
-                return true;
-            }
-        }
-
-        int st = DhcpState::parseString(tmp);
-        mHandlers->onDhcpStateChanged(mController, st);
-    } else if (!strncmp(buffer, "ADDRINFO:", 9)) {
-        char *next = buffer + 9;
-	struct in_addr ipaddr, netmask, gateway, broadcast, dns1, dns2;
-
-        if (!inet_aton(strsep(&next, ":"), &ipaddr)) {
-            LOGW("Malformatted IP specified");
-        }
-        if (!inet_aton(strsep(&next, ":"), &netmask)) {
-            LOGW("Malformatted netmask specified");
-        }
-        if (!inet_aton(strsep(&next, ":"), &broadcast)) {
-            LOGW("Malformatted broadcast specified");
-        }
-        if (!inet_aton(strsep(&next, ":"), &gateway)) {
-            LOGW("Malformatted gateway specified");
-        }
-        if (!inet_aton(strsep(&next, ":"), &dns1)) {
-            LOGW("Malformatted dns1 specified");
-        }
-        if (!inet_aton(strsep(&next, ":"), &dns2)) {
-            LOGW("Malformatted dns2 specified");
-        }
-        mHandlers->onDhcpLeaseUpdated(mController, &ipaddr, &netmask,
-                                      &broadcast, &gateway, &dns1, &dns2);
- 
-    } else if (!strncmp(buffer, "EVENT:", 6)) {
-        char *next = buffer;
-        char *tmp;
-        int i;
-
-        for (i = 0; i < 2; i++) {
-            if (!(tmp = strsep(&next, ":"))) {
-                LOGW("Error parsing event '%s'", buffer);
-                return true;
-            }
-        }
-
-        int ev = DhcpEvent::parseString(tmp);
-        mHandlers->onDhcpEvent(mController, ev);
-  
-    } else {
-        LOGW("Unknown DHCP monitor msg '%s'", buffer);
-    }
-
-    return true;
-}
diff --git a/nexus/DhcpListener.h b/nexus/DhcpListener.h
deleted file mode 100644
index ca6fe37..0000000
--- a/nexus/DhcpListener.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _DhcpListener_H
-#define _DhcpListener_H
-
-#include <sysutils/SocketListener.h>
-
-class IDhcpEventHandlers;
-class Controller;
-
-class DhcpListener : public SocketListener {
-    IDhcpEventHandlers *mHandlers;
-    Controller         *mController;
-
-public:
-
-    DhcpListener(Controller *c, int socket, IDhcpEventHandlers *handlers);
-    virtual ~DhcpListener();
-
-private:
-    bool onDataAvailable(SocketClient *cli);
-};
-
-#endif
diff --git a/nexus/DhcpState.cpp b/nexus/DhcpState.cpp
deleted file mode 100644
index c9d5135..0000000
--- a/nexus/DhcpState.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-
-#define LOG_TAG "DhcpState"
-#include <cutils/log.h>
-
-#include "DhcpState.h"
-
-char *DhcpState::toString(int val, char *buffer, int max) {
-    if (val == DhcpState::INIT)
-        strncpy(buffer, "INIT", max);
-    else if (val == DhcpState::DISCOVERING)
-        strncpy(buffer, "DISCOVERING", max);
-    else if (val == DhcpState::REQUESTING)
-        strncpy(buffer, "REQUESTING", max);
-    else if (val == DhcpState::BOUND)
-        strncpy(buffer, "BOUND", max);
-    else if (val == DhcpState::RENEWING)
-        strncpy(buffer, "RENEWING", max);
-    else if (val == DhcpState::REBINDING)
-        strncpy(buffer, "REBINDING", max);
-    else if (val == DhcpState::REBOOT)
-        strncpy(buffer, "REBOOT", max);
-    else if (val == DhcpState::RENEW_REQUESTED)
-        strncpy(buffer, "RENEW_REQUESTED", max);
-    else if (val == DhcpState::INIT_IPV4LL)
-        strncpy(buffer, "INIT_IPV4LL", max);
-    else if (val == DhcpState::PROBING)
-        strncpy(buffer, "PROBING", max);
-    else if (val == DhcpState::ANNOUNCING)
-        strncpy(buffer, "ANNOUNCING", max);
-    else
-        strncpy(buffer, "(internal error)", max);
-
-    return buffer;
-}
-
-int DhcpState::parseString(const char *buffer) {
-    if (!strcasecmp(buffer, "INIT"))
-        return DhcpState::INIT;
-    else if (!strcasecmp(buffer, "DISCOVERING"))
-        return DhcpState::DISCOVERING;
-    else if (!strcasecmp(buffer, "REQUESTING"))
-        return DhcpState::REQUESTING;
-    else if (!strcasecmp(buffer, "BOUND"))
-        return DhcpState::BOUND;
-    else if (!strcasecmp(buffer, "RENEWING"))
-        return DhcpState::RENEWING;
-    else if (!strcasecmp(buffer, "REBINDING"))
-        return DhcpState::REBINDING;
-    else if (!strcasecmp(buffer, "REBOOT"))
-        return DhcpState::REBOOT;
-    else if (!strcasecmp(buffer, "RENEW_REQUESTED"))
-        return DhcpState::INIT_IPV4LL;
-    else if (!strcasecmp(buffer, "INIT_IPV4LL"))
-        return DhcpState::INIT_IPV4LL;
-    else if (!strcasecmp(buffer, "PROBING"))
-        return DhcpState::PROBING;
-    else if (!strcasecmp(buffer, "ANNOUNCING"))
-        return DhcpState::ANNOUNCING;
-    else {
-        LOGW("Bad state '%s'", buffer);
-        return -1;
-    }
-}
diff --git a/nexus/DhcpState.h b/nexus/DhcpState.h
deleted file mode 100644
index 041c5d2..0000000
--- a/nexus/DhcpState.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _DHCP_STATE_H
-#define _DHCP_STATE_H
-
-class DhcpState {
-public:
-    static const int INIT            = 0;
-    static const int DISCOVERING     = 1;
-    static const int REQUESTING      = 2;
-    static const int BOUND           = 3;
-    static const int RENEWING        = 4;
-    static const int REBINDING       = 5;
-    static const int REBOOT          = 6;
-    static const int RENEW_REQUESTED = 7;
-    static const int INIT_IPV4LL     = 8;
-    static const int PROBING         = 9;
-    static const int ANNOUNCING      = 10;
-
-    static char *toString(int val, char *buffer, int max);
-
-    static int parseString(const char *buffer);
-};
-
-#endif
diff --git a/nexus/IControllerHandler.h b/nexus/IControllerHandler.h
deleted file mode 100644
index 3151587..0000000
--- a/nexus/IControllerHandler.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ICONTROLLER_HANDLER_H
-#define _ICONTROLLER_HANDLER_H
-
-class Controller;
-class InterfaceConfig;
-
-class IControllerHandler {
-public:
-    virtual ~IControllerHandler() {}
-    virtual void onInterfaceConnected(Controller *c) = 0;
-    virtual void onInterfaceDisconnected(Controller *c) = 0;
-    virtual void onControllerSuspending(Controller *c) = 0;
-    virtual void onControllerResumed(Controller *c) = 0;
-};
-
-#endif
-
diff --git a/nexus/IDhcpEventHandlers.h b/nexus/IDhcpEventHandlers.h
deleted file mode 100644
index 2568f09..0000000
--- a/nexus/IDhcpEventHandlers.h
+++ /dev/null
@@ -1,33 +0,0 @@
-
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _IDhcpEventHandlers_H
-#define _IDhcpEventHandlers_H
-
-class IDhcpEventHandlers {
-public:
-    virtual ~IDhcpEventHandlers() {}
-    virtual void onDhcpStateChanged(Controller *c, int state) = 0;
-    virtual void onDhcpEvent(Controller *c, int event) = 0;
-    virtual void onDhcpLeaseUpdated(Controller *c,
-                                    struct in_addr *addr, struct in_addr *net,
-                                    struct in_addr *brd,
-                                    struct in_addr *gw, struct in_addr *dns1,
-                                    struct in_addr *dns2) = 0;
-};
-
-#endif
diff --git a/nexus/ISupplicantEventHandler.h b/nexus/ISupplicantEventHandler.h
deleted file mode 100644
index 1a3aa07..0000000
--- a/nexus/ISupplicantEventHandler.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ISUPPLICANT_EVENT_HANDLER_H
-#define _ISUPPLICANT_EVENT_HANDLER_H
-
-class SupplicantAssociatingEvent;
-class SupplicantAssociatedEvent;
-class SupplicantConnectedEvent;
-class SupplicantScanResultsEvent;
-class SupplicantStateChangeEvent;
-class SupplicantConnectionTimeoutEvent;
-class SupplicantDisconnectedEvent;
-
-class ISupplicantEventHandler {
-public:
-    virtual ~ISupplicantEventHandler(){}
-    virtual void onAssociatingEvent(SupplicantAssociatingEvent *evt) = 0;
-    virtual void onAssociatedEvent(SupplicantAssociatedEvent *evt) = 0;
-    virtual void onConnectedEvent(SupplicantConnectedEvent *evt) = 0;
-    virtual void onScanResultsEvent(SupplicantScanResultsEvent *evt) = 0;
-    virtual void onStateChangeEvent(SupplicantStateChangeEvent *evt) = 0;
-    virtual void onConnectionTimeoutEvent(SupplicantConnectionTimeoutEvent *evt) = 0;
-    virtual void onDisconnectedEvent(SupplicantDisconnectedEvent *evt) = 0;
-#if 0
-    virtual void onTerminatingEvent(SupplicantEvent *evt) = 0;
-    virtual void onPasswordChangedEvent(SupplicantEvent *evt) = 0;
-    virtual void onEapNotificationEvent(SupplicantEvent *evt) = 0;
-    virtual void onEapStartedEvent(SupplicantEvent *evt) = 0;
-    virtual void onEapMethodEvent(SupplicantEvent *evt) = 0;
-    virtual void onEapSuccessEvent(SupplicantEvent *evt) = 0;
-    virtual void onEapFailureEvent(SupplicantEvent *evt) = 0;
-    virtual void onLinkSpeedEvent(SupplicantEvent *evt) = 0;
-    virtual void onDriverStateEvent(SupplicantEvent *evt) = 0;
-#endif
-};
-
-#endif
-
diff --git a/nexus/IWifiStatusPollerHandler.h b/nexus/IWifiStatusPollerHandler.h
deleted file mode 100644
index 9b94945..0000000
--- a/nexus/IWifiStatusPollerHandler.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _IWIFISTATUSPOLLER_HANDLER_H
-#define _IWIFISTATUSPOLLER_HANDLER_H
-
-class IWifiStatusPollerHandler {
-public:
-    virtual ~IWifiStatusPollerHandler() {}
-    virtual void onStatusPollInterval() = 0;
-};
-
-#endif
diff --git a/nexus/InterfaceConfig.cpp b/nexus/InterfaceConfig.cpp
deleted file mode 100644
index 832cbca..0000000
--- a/nexus/InterfaceConfig.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <string.h>
-
-#define LOG_TAG "InterfaceConfig"
-#include <cutils/log.h>
-
-#include "InterfaceConfig.h"
-#include "NetworkManager.h"
-
-InterfaceConfig::InterfaceConfig(bool propertiesReadOnly) {
-    mStaticProperties.propIp = new IPV4AddressPropertyHelper("Addr", propertiesReadOnly, &mIp);
-    mStaticProperties.propNetmask = new IPV4AddressPropertyHelper("Netmask", propertiesReadOnly, &mNetmask);
-    mStaticProperties.propGateway = new IPV4AddressPropertyHelper("Gateway", propertiesReadOnly, &mGateway);
-    mStaticProperties.propBroadcast = new IPV4AddressPropertyHelper("Broadcast", propertiesReadOnly, &mBroadcast);
-    mStaticProperties.propDns = new InterfaceDnsProperty(this, propertiesReadOnly);
-}
-
-InterfaceConfig::~InterfaceConfig() {
-    delete mStaticProperties.propIp;
-    delete mStaticProperties.propNetmask;
-    delete mStaticProperties.propGateway;
-    delete mStaticProperties.propBroadcast;
-    delete mStaticProperties.propDns;
-}
-
-void InterfaceConfig::setIp(struct in_addr *addr) {
-    memcpy(&mIp, addr, sizeof(struct in_addr));
-}
-
-void InterfaceConfig::setNetmask(struct in_addr *addr) {
-    memcpy(&mNetmask, addr, sizeof(struct in_addr));
-}
-
-void InterfaceConfig::setGateway(struct in_addr *addr) {
-    memcpy(&mGateway, addr, sizeof(struct in_addr));
-}
-
-void InterfaceConfig::setBroadcast(struct in_addr *addr) {
-    memcpy(&mBroadcast, addr, sizeof(struct in_addr));
-}
-
-void InterfaceConfig::setDns(int idx, struct in_addr *addr) {
-    memcpy(&mDns[idx], addr, sizeof(struct in_addr));
-}
-
-int InterfaceConfig::attachProperties(PropertyManager *pm, const char *nsName) {
-    pm->attachProperty(nsName, mStaticProperties.propIp);
-    pm->attachProperty(nsName, mStaticProperties.propNetmask);
-    pm->attachProperty(nsName, mStaticProperties.propGateway);
-    pm->attachProperty(nsName, mStaticProperties.propBroadcast);
-    pm->attachProperty(nsName, mStaticProperties.propDns);
-    return 0;
-}
-
-int InterfaceConfig::detachProperties(PropertyManager *pm, const char *nsName) {
-    pm->detachProperty(nsName, mStaticProperties.propIp);
-    pm->detachProperty(nsName, mStaticProperties.propNetmask);
-    pm->detachProperty(nsName, mStaticProperties.propGateway);
-    pm->detachProperty(nsName, mStaticProperties.propBroadcast);
-    pm->detachProperty(nsName, mStaticProperties.propDns);
-    return 0;
-}
-
-InterfaceConfig::InterfaceDnsProperty::InterfaceDnsProperty(InterfaceConfig *c,
-                                                            bool ro) :
-                 IPV4AddressProperty("Dns", ro, 2) {
-    mCfg = c;
-}
-
-int InterfaceConfig::InterfaceDnsProperty::set(int idx, struct in_addr *value) {
-    memcpy(&mCfg->mDns[idx], value, sizeof(struct in_addr));
-    return 0;
-}
-int InterfaceConfig::InterfaceDnsProperty::get(int idx, struct in_addr *buf) {
-    memcpy(buf, &mCfg->mDns[idx], sizeof(struct in_addr));
-    return 0;
-}
-
diff --git a/nexus/InterfaceConfig.h b/nexus/InterfaceConfig.h
deleted file mode 100644
index 3fc7390..0000000
--- a/nexus/InterfaceConfig.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _INTERFACE_CONFIG_H
-#define _INTERFACE_CONFIG_H
-
-#include <unistd.h>
-#include <sys/types.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-#include "Property.h"
-class PropertyManager;
-
-class InterfaceConfig {
-    class InterfaceDnsProperty;
-    friend class InterfaceConfig::InterfaceDnsProperty;
-
-    struct {
-        IPV4AddressPropertyHelper *propIp;
-        IPV4AddressPropertyHelper *propNetmask;
-        IPV4AddressPropertyHelper *propGateway;
-        IPV4AddressPropertyHelper *propBroadcast;
-        InterfaceDnsProperty      *propDns;
-    } mStaticProperties;
-
-    struct in_addr mIp;
-    struct in_addr mNetmask;
-    struct in_addr mGateway;
-    struct in_addr mBroadcast;
-    struct in_addr mDns[2];
-
-public:
-    InterfaceConfig(bool propertiesReadOnly);
-    virtual ~InterfaceConfig();
-    
-    int set(const char *name, const char *value);
-    const char *get(const char *name, char *buffer, size_t maxsize);
-
-    const struct in_addr &getIp() const { return mIp; }
-    const struct in_addr &getNetmask() const { return mNetmask; }
-    const struct in_addr &getGateway() const { return mGateway; }
-    const struct in_addr &getBroadcast() const { return mBroadcast; }
-    const struct in_addr &getDns(int idx) const { return mDns[idx]; }
-
-    void setIp(struct in_addr *addr);
-    void setNetmask(struct in_addr *addr);
-    void setGateway(struct in_addr *addr);
-    void setBroadcast(struct in_addr *addr);
-    void setDns(int idx, struct in_addr *addr);
-
-    int attachProperties(PropertyManager *pm, const char *nsName);
-    int detachProperties(PropertyManager *pm, const char *nsName);
-
-private:
-
-    class InterfaceDnsProperty : public IPV4AddressProperty {
-        InterfaceConfig *mCfg;
-    public:
-        InterfaceDnsProperty(InterfaceConfig *cfg, bool ro);
-        int set(int idx, struct in_addr *value);
-        int get(int idx, struct in_addr *buffer);
-    };
-};
-
-
-#endif
diff --git a/nexus/LoopController.cpp b/nexus/LoopController.cpp
deleted file mode 100644
index f8e01d7..0000000
--- a/nexus/LoopController.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-
-#include "LoopController.h"
-#include "PropertyManager.h"
-
-LoopController::LoopController(PropertyManager *propmngr,
-                               IControllerHandler *handlers) :
-                Controller("loop", propmngr, handlers) {
-}
diff --git a/nexus/LoopController.h b/nexus/LoopController.h
deleted file mode 100644
index 53d16f1..0000000
--- a/nexus/LoopController.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _LOOP_CONTROLLER_H
-#define _LOOP_CONTROLLER_H
-
-#include "Controller.h"
-
-class ControllerHandler;
-
-class LoopController : public Controller {
-public:
-    LoopController(PropertyManager *propmngr, IControllerHandler *h);
-    virtual ~LoopController() {}
-
-    int set(const char *name, const char *value);
-    const char *get(const char *name, char *buffer, size_t maxsize);
-};
-
-#endif
diff --git a/nexus/NetworkManager.cpp b/nexus/NetworkManager.cpp
deleted file mode 100644
index e0df409..0000000
--- a/nexus/NetworkManager.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <errno.h>
-
-#define LOG_TAG "Nexus"
-
-#include <cutils/log.h>
-
-#include "NetworkManager.h"
-#include "InterfaceConfig.h"
-#include "DhcpClient.h"
-#include "DhcpState.h"
-#include "DhcpEvent.h"
-#include "ResponseCode.h"
-
-NetworkManager *NetworkManager::sInstance = NULL;
-
-NetworkManager *NetworkManager::Instance() {
-    if (!sInstance)
-        sInstance = new NetworkManager(new PropertyManager());
-    return sInstance;
-}
-
-NetworkManager::NetworkManager(PropertyManager *propMngr) {
-    mBroadcaster = NULL;
-    mControllerBindings = new ControllerBindingCollection();
-    mPropMngr = propMngr;
-    mLastDhcpState = DhcpState::INIT;
-    mDhcp = new DhcpClient(this);
-}
-
-NetworkManager::~NetworkManager() {
-}
-
-int NetworkManager::run() {
-    if (startControllers()) {
-        LOGW("Unable to start all controllers (%s)", strerror(errno));
-    }
-    return 0;
-}
-
-int NetworkManager::attachController(Controller *c) {
-    ControllerBinding *cb = new ControllerBinding(c);
-    mControllerBindings->push_back(cb);
-    return 0;
-}
-
-int NetworkManager::startControllers() {
-    int rc = 0;
-    ControllerBindingCollection::iterator it;
-
-    for (it = mControllerBindings->begin(); it != mControllerBindings->end(); ++it) {
-        int irc = (*it)->getController()->start();
-        if (irc && !rc)
-            rc = irc;
-    }
-    return rc;
-}
-
-int NetworkManager::stopControllers() {
-    int rc = 0;
-    ControllerBindingCollection::iterator it;
-
-    for (it = mControllerBindings->begin(); it != mControllerBindings->end(); ++it) {
-        int irc = (*it)->getController()->stop();
-        if (irc && !rc)
-            rc = irc;
-    }
-    return rc;
-}
-
-NetworkManager::ControllerBinding *NetworkManager::lookupBinding(Controller *c) {
-    ControllerBindingCollection::iterator it;
-
-    for (it = mControllerBindings->begin(); it != mControllerBindings->end(); ++it) {
-        if ((*it)->getController() == c)
-            return (*it);
-    }
-    errno = ENOENT;
-    return NULL;
-}
-
-Controller *NetworkManager::findController(const char *name) {
-    ControllerBindingCollection::iterator it;
-
-    for (it = mControllerBindings->begin(); it != mControllerBindings->end(); ++it) {
-        if (!strcasecmp((*it)->getController()->getName(), name))
-            return (*it)->getController();
-    }
-    errno = ENOENT;
-    return NULL;
-}
-
-void NetworkManager::onInterfaceConnected(Controller *c) {
-    LOGD("Controller %s interface %s connected", c->getName(), c->getBoundInterface());
-
-    if (mDhcp->start(c)) {
-        LOGE("Failed to start DHCP (%s)", strerror(errno));
-        return;
-    }
-}
-
-void NetworkManager::onInterfaceDisconnected(Controller *c) {
-    LOGD("Controller %s interface %s disconnected", c->getName(),
-         c->getBoundInterface());
-
-    mDhcp->stop();
-}
-
-void NetworkManager::onControllerSuspending(Controller *c) {
-    LOGD("Controller %s interface %s suspending", c->getName(),
-         c->getBoundInterface());
-    mDhcp->stop();
-}
-
-void NetworkManager::onControllerResumed(Controller *c) {
-    LOGD("Controller %s interface %s resumed", c->getName(),
-         c->getBoundInterface());
-}
-
-void NetworkManager::onDhcpStateChanged(Controller *c, int state) {
-    char tmp[255];
-    char tmp2[255];
-
-    LOGD("onDhcpStateChanged(%s -> %s)",
-         DhcpState::toString(mLastDhcpState, tmp, sizeof(tmp)),
-         DhcpState::toString(state, tmp2, sizeof(tmp2)));
-
-    switch(state) {
-        case DhcpState::BOUND:
-            // Refresh the 'net.xxx' for the controller
-            break;
-        case DhcpState::RENEWING:
-            break;
-        default:
-            break;
-    }
-
-    char *tmp3;
-    asprintf(&tmp3,
-             "DHCP state changed from %d (%s) -> %d (%s)", 
-             mLastDhcpState,
-             DhcpState::toString(mLastDhcpState, tmp, sizeof(tmp)),
-             state,
-             DhcpState::toString(state, tmp2, sizeof(tmp2)));
-
-    getBroadcaster()->sendBroadcast(ResponseCode::DhcpStateChange,
-                                    tmp3,
-                                    false);
-    free(tmp3);
-                          
-    mLastDhcpState = state;
-}
-
-void NetworkManager::onDhcpEvent(Controller *c, int evt) {
-    char tmp[64];
-    LOGD("onDhcpEvent(%s)", DhcpEvent::toString(evt, tmp, sizeof(tmp)));
-}
-
-void NetworkManager::onDhcpLeaseUpdated(Controller *c, struct in_addr *addr,
-                                        struct in_addr *net,
-                                        struct in_addr *brd,
-                                        struct in_addr *gw,
-                                        struct in_addr *dns1,
-                                        struct in_addr *dns2) {
-    ControllerBinding *bind = lookupBinding(c);
-
-    if (!bind->getCurrentCfg())
-        bind->setCurrentCfg(new InterfaceConfig(true));
-
-    bind->getCurrentCfg()->setIp(addr);
-    bind->getCurrentCfg()->setNetmask(net);
-    bind->getCurrentCfg()->setGateway(gw);
-    bind->getCurrentCfg()->setBroadcast(brd);
-    bind->getCurrentCfg()->setDns(0, dns1);
-    bind->getCurrentCfg()->setDns(1, dns2);
-}
-
-NetworkManager::ControllerBinding::ControllerBinding(Controller *c) :
-                mController(c) {
-}
-
-void NetworkManager::ControllerBinding::setCurrentCfg(InterfaceConfig *c) {
-    mCurrentCfg = c;
-}
-
-void NetworkManager::ControllerBinding::setBoundCfg(InterfaceConfig *c) {
-    mBoundCfg = c;
-}
-
diff --git a/nexus/NetworkManager.h b/nexus/NetworkManager.h
deleted file mode 100644
index 93702ce..0000000
--- a/nexus/NetworkManager.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _NETWORKMANAGER_H
-#define _NETWORKMANAGER_H
-
-#include <utils/List.h>
-#include <sysutils/SocketListener.h>
-
-#include "Controller.h"
-#include "PropertyManager.h"
-#include "IControllerHandler.h"
-#include "IDhcpEventHandlers.h"
-
-class InterfaceConfig;
-class DhcpClient;
-
-class NetworkManager : public IControllerHandler, public IDhcpEventHandlers {
-    static NetworkManager *sInstance;
-
-    class ControllerBinding {
-        Controller      *mController;
-        InterfaceConfig *mCurrentCfg;
-        InterfaceConfig *mBoundCfg;
-
-    public:
-        ControllerBinding(Controller *c);
-        virtual ~ControllerBinding() {}
-
-        InterfaceConfig *getCurrentCfg() { return mCurrentCfg; }
-        InterfaceConfig *getBoundCfg() { return mCurrentCfg; }
-        Controller *getController() { return mController; }
-
-        void setCurrentCfg(InterfaceConfig *cfg);
-        void setBoundCfg(InterfaceConfig *cfg);
-    };
-
-    typedef android::List<ControllerBinding *> ControllerBindingCollection;
-
-private:
-    ControllerBindingCollection *mControllerBindings;
-    SocketListener              *mBroadcaster;
-    PropertyManager             *mPropMngr;
-    DhcpClient                  *mDhcp;
-    int                         mLastDhcpState;
-
-public:
-    virtual ~NetworkManager();
-
-    int run();
-
-    int attachController(Controller *controller);
-
-    Controller *findController(const char *name);
-
-    void setBroadcaster(SocketListener *sl) { mBroadcaster = sl; }
-    SocketListener *getBroadcaster() { return mBroadcaster; }
-    PropertyManager *getPropMngr() { return mPropMngr; }
-
-    static NetworkManager *Instance();
-
-private:
-    int startControllers();
-    int stopControllers();
-
-    NetworkManager(PropertyManager *propMngr);
-    ControllerBinding *lookupBinding(Controller *c);
-
-    void onInterfaceConnected(Controller *c);
-    void onInterfaceDisconnected(Controller *c);
-    void onControllerSuspending(Controller *c);
-    void onControllerResumed(Controller *c);
-
-    void onDhcpStateChanged(Controller *c, int state);
-    void onDhcpEvent(Controller *c, int event);
-    void onDhcpLeaseUpdated(Controller *c,
-                            struct in_addr *addr, struct in_addr *net,
-                            struct in_addr *brd,
-                            struct in_addr *gw, struct in_addr *dns1,
-                            struct in_addr *dns2);
-};
-#endif
diff --git a/nexus/OpenVpnController.cpp b/nexus/OpenVpnController.cpp
deleted file mode 100644
index f1ea510..0000000
--- a/nexus/OpenVpnController.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-#define LOG_TAG "OpenVpnController"
-#include <cutils/log.h>
-#include <cutils/properties.h>
-
-#include <sysutils/ServiceManager.h>
-
-#include "OpenVpnController.h"
-#include "PropertyManager.h"
-
-#define DAEMON_PROP_NAME "vpn.openvpn.status"
-#define DAEMON_CONFIG_FILE "/data/misc/openvpn/openvpn.conf"
-
-OpenVpnController::OpenVpnController(PropertyManager *propmngr,
-                                     IControllerHandler *handlers) :
-                   VpnController(propmngr, handlers) {
-    mServiceManager = new ServiceManager();
-}
-
-OpenVpnController::~OpenVpnController() {
-    delete mServiceManager;
-}
-
-int OpenVpnController::start() {
-    return VpnController::start();
-}
-
-int OpenVpnController::stop() {
-    return VpnController::stop();
-}
-
-int OpenVpnController::enable() {
-    char svc[PROPERTY_VALUE_MAX];
-    char tmp[64];
-
-    if (!mPropMngr->get("vpn.gateway", tmp, sizeof(tmp))) {
-        LOGE("Error reading property 'vpn.gateway' (%s)", strerror(errno));
-        return -1;
-    }
-    snprintf(svc, sizeof(svc), "openvpn:--remote %s 1194", tmp);
-
-    if (mServiceManager->start(svc))
-        return -1;
-
-    return 0;
-}
-
-int OpenVpnController::disable() {
-    if (mServiceManager->stop("openvpn"))
-        return -1;
-    return 0;
-}
diff --git a/nexus/OpenVpnController.h b/nexus/OpenVpnController.h
deleted file mode 100644
index 529aab5..0000000
--- a/nexus/OpenVpnController.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _OPEN_VPN_CONTROLLER_H
-#define _OPEN_VPN_CONTROLLER_H
-
-#include "PropertyManager.h"
-#include "VpnController.h"
-
-class ServiceManager;
-class IControllerHandler;
-
-class OpenVpnController : public VpnController {
-private:
-    ServiceManager *mServiceManager;
-
-public:
-    OpenVpnController(PropertyManager *propmngr, IControllerHandler *handlers);
-    virtual ~OpenVpnController();
-
-    int start();
-    int stop();
-
-private:
-    int enable();
-    int disable();
-};
-
-#endif
diff --git a/nexus/Property.cpp b/nexus/Property.cpp
deleted file mode 100644
index d02769d..0000000
--- a/nexus/Property.cpp
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <errno.h>
-#include <strings.h>
-#include <netinet/in.h>
-
-#define LOG_TAG "Property"
-
-#include <cutils/log.h>
-
-#include "Property.h"
-
-Property::Property(const char *name, bool readOnly,
-                   int type, int numElements) :
-          mName(name), mReadOnly(readOnly), mType(type),
-          mNumElements(numElements) {
-    if (index(name, '.')) {
-        LOGW("Property name %s violates namespace rules", name);
-    }
-}
-
-StringProperty::StringProperty(const char *name, bool ro, int elements) :
-                Property(name, ro, Property::Type_STRING, elements) {
-}
-int StringProperty::set(int idx, int value) {
-    LOGE("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!");
-    errno = EINVAL;
-    return -1;
-}
-int StringProperty::get(int idx, int *buffer) {
-    LOGE("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!");
-    errno = EINVAL;
-    return -1;
-}
-
-StringPropertyHelper::StringPropertyHelper(const char *name, bool ro,
-                                           char *buffer, size_t max) :
-                      StringProperty(name, ro, 1) {
-    mBuffer = buffer;
-    mMax = max;
-}
-
-int StringPropertyHelper::set(int idx, const char *value) {
-    if (idx != 0) {
-        LOGW("Attempt to use array index on StringPropertyHelper::set");
-        errno = EINVAL;
-        return -1;
-    }
-    strncpy(mBuffer, value, mMax);
-    return 0;
-}
-
-int StringPropertyHelper::get(int idx, char *buffer, size_t max) {
-    if (idx != 0) {
-        LOGW("Attempt to use array index on StringPropertyHelper::get");
-        errno = EINVAL;
-        return -1;
-    }
-    strncpy(buffer, mBuffer, max);
-    return 0;
-}
- 
-IntegerProperty::IntegerProperty(const char *name, bool ro, int elements) :
-                Property(name, ro, Property::Type_INTEGER, elements) {
-}
-
-int IntegerProperty::set(int idx, const char *value) {
-    LOGE("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!");
-    errno = EINVAL;
-    return -1;
-}
-int IntegerProperty::get(int idx, char *buffer, size_t max) {
-    LOGE("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!");
-    errno = EINVAL;
-    return -1;
-}
-
-IntegerPropertyHelper::IntegerPropertyHelper(const char *name, bool ro,
-                                             int *buffer) :
-                       IntegerProperty(name, ro, 1) {
-    mBuffer = buffer;
-}
-
-int IntegerPropertyHelper::set(int idx, int value) {
-    if (idx != 0) {
-        LOGW("Attempt to use array index on IntegerPropertyHelper::set");
-        errno = EINVAL;
-        return -1;
-    }
-    *mBuffer = value;
-    return 0;
-}
-
-int IntegerPropertyHelper::get(int idx, int *buffer) {
-    if (idx != 0) {
-        LOGW("Attempt to use array index on IntegerPropertyHelper::get");
-        errno = EINVAL;
-        return -1;
-    }
-    *buffer = *mBuffer;
-    return 0;
-}
-
-IPV4AddressProperty::IPV4AddressProperty(const char *name, bool ro, int elements) :
-                Property(name, ro, Property::Type_IPV4, elements) {
-}
-
-int IPV4AddressProperty::set(int idx, const char *value) {
-    LOGE("String 'set' called on ipv4 property!");
-    errno = EINVAL;
-    return -1;
-}
-int IPV4AddressProperty::set(int idx, int value) {
-    LOGE("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!");
-    errno = EINVAL;
-    return -1;
-}
-int IPV4AddressProperty::get(int idx, int *buffer) {
-    LOGE("Integer 'get' called on ipv4 property!");
-    errno = EINVAL;
-    return -1;
-}
-
-IPV4AddressPropertyHelper::IPV4AddressPropertyHelper(const char *name, bool ro,
-                                                     struct in_addr *buffer) :
-                       IPV4AddressProperty(name, ro, 1) {
-    mBuffer = buffer;
-}
-
-int IPV4AddressPropertyHelper::set(int idx, struct in_addr *value) {
-    if (idx != 0) {
-        LOGW("Attempt to use array index on IPV4AddressPropertyHelper::set");
-        errno = EINVAL;
-        return -1;
-    }
-    memcpy(mBuffer, value, sizeof(struct in_addr));
-    return 0;
-}
-
-int IPV4AddressPropertyHelper::get(int idx, struct in_addr *buffer) {
-    if (idx != 0) {
-        LOGW("Attempt to use array index on IPV4AddressPropertyHelper::get");
-        errno = EINVAL;
-        return -1;
-    }
-    memcpy(buffer, mBuffer, sizeof(struct in_addr));
-    return 0;
-}
-
-PropertyNamespace::PropertyNamespace(const char *name) {
-    mName = strdup(name);
-    mProperties = new PropertyCollection();
-}
-
-PropertyNamespace::~PropertyNamespace() {
-    PropertyCollection::iterator it;
-    for (it = mProperties->begin(); it != mProperties->end();) {
-        delete (*it);
-        it = mProperties->erase(it);
-    }
-    delete mProperties;
-    free(mName);
-}
diff --git a/nexus/Property.h b/nexus/Property.h
deleted file mode 100644
index ceea2d3..0000000
--- a/nexus/Property.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _PROPERTY_H
-#define _PROPERTY_H
-
-#include <netinet/in.h>
-#include <utils/List.h>
-
-class Property {
-    const char *mName;
-    bool       mReadOnly;
-    int        mType;
-    int        mNumElements;
-
-public:
-    static const int NameMaxSize   = 128;
-    static const int ValueMaxSize  = 255;
-
-    static const int Type_STRING  = 1;
-    static const int Type_INTEGER = 2;
-    static const int Type_IPV4    = 3;
-
-    Property(const char *name, bool ro, int type, int elements);
-    virtual ~Property() {}
-
-    virtual int set(int idx, const char *value) = 0;
-    virtual int set(int idx, int value) = 0;
-    virtual int set(int idx, struct in_addr *value) = 0;
-
-    virtual int get(int idx, char *buffer, size_t max) = 0;
-    virtual int get(int idx, int *buffer) = 0;
-    virtual int get(int idx, struct in_addr *buffer) = 0;
-
-    int getType() { return mType; }
-    bool getReadOnly() { return mReadOnly; }
-    int getNumElements() { return mNumElements; }
-    const char *getName() { return mName; }
-};
-
-class StringProperty : public Property {
-public:
-    StringProperty(const char *name, bool ro, int elements);
-    virtual ~StringProperty() {}
- 
-    virtual int set(int idx, const char *value) = 0;
-    int set(int idx, int value);
-    int set(int idx, struct in_addr *value);
-
-    virtual int get(int idx, char *buffer, size_t max) = 0;
-    int get(int idx, int *buffer);
-    int get(int idx, struct in_addr *buffer);
-};
-
-class StringPropertyHelper : public StringProperty {
-    char *mBuffer;
-    size_t mMax;
-public:
-    StringPropertyHelper(const char *name, bool ro,
-                         char *buffer, size_t max);
-    int set(int idx, const char *value);
-    int get(int idx, char *buffer, size_t max);
-};
-
-class IntegerProperty : public Property {
-public:
-    IntegerProperty(const char *name, bool ro, int elements);
-    virtual ~IntegerProperty() {}
- 
-    int set(int idx, const char *value);
-    virtual int set(int idx, int value) = 0;
-    int set(int idx, struct in_addr *value);
-
-    int get(int idx, char *buffer, size_t max);
-    virtual int get(int idx, int *buffer) = 0;
-    int get(int idx, struct in_addr *buffer);
-};
-
-class IntegerPropertyHelper : public IntegerProperty {
-    int *mBuffer;
-public:
-    IntegerPropertyHelper(const char *name, bool ro, int *buffer);
-    int set(int idx, int value);
-    int get(int idx, int *buffer);
-};
-
-class IPV4AddressProperty : public Property {
-public:
-    IPV4AddressProperty(const char *name, bool ro, int elements);
-    virtual ~IPV4AddressProperty() {}
- 
-    int set(int idx, const char *value);
-    int set(int idx, int value);
-    virtual int set(int idx, struct in_addr *value) = 0;
-
-    int get(int idx, char *buffer, size_t max);
-    int get(int idx, int *buffer);
-    virtual int get(int idx, struct in_addr *buffer) = 0;
-};
-
-class IPV4AddressPropertyHelper : public IPV4AddressProperty {
-    struct in_addr *mBuffer;
-public:
-    IPV4AddressPropertyHelper(const char *name, bool ro, struct in_addr *buf);
-    int set(int idx, struct in_addr *value);
-    int get(int idx, struct in_addr *buffer);
-};
-
-typedef android::List<Property *> PropertyCollection;
-
-class PropertyNamespace {
-    char         *mName;
-    PropertyCollection *mProperties;
-
-public:
-    PropertyNamespace(const char *name);
-    virtual ~PropertyNamespace();
-
-    const char *getName() { return mName; }
-    PropertyCollection *getProperties() { return mProperties; }
-};
-
-typedef android::List<PropertyNamespace *> PropertyNamespaceCollection;
-#endif
diff --git a/nexus/PropertyManager.cpp b/nexus/PropertyManager.cpp
deleted file mode 100644
index 704b223..0000000
--- a/nexus/PropertyManager.cpp
+++ /dev/null
@@ -1,280 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-#define LOG_TAG "PropertyManager"
-
-#include <cutils/log.h>
-
-#include "PropertyManager.h"
-
-PropertyManager::PropertyManager() {
-    mNamespaces = new PropertyNamespaceCollection();
-    pthread_mutex_init(&mLock, NULL);
-}
-
-PropertyManager::~PropertyManager() {
-    PropertyNamespaceCollection::iterator it;
-
-    for (it = mNamespaces->begin(); it != mNamespaces->end();) {
-        delete (*it);
-        it = mNamespaces->erase(it);
-    }
-    delete mNamespaces;
-}
-
-PropertyNamespace *PropertyManager::lookupNamespace_UNLOCKED(const char *ns) {
-    PropertyNamespaceCollection::iterator ns_it;
-
-    for (ns_it = mNamespaces->begin(); ns_it != mNamespaces->end(); ++ns_it) {
-        if (!strcasecmp(ns, (*ns_it)->getName()))
-            return (*ns_it);
-    }
-    errno = ENOENT;
-    return NULL;
-}
-
-Property *PropertyManager::lookupProperty_UNLOCKED(PropertyNamespace *ns, const char *name) {
-    PropertyCollection::iterator it;
-
-    for (it = ns->getProperties()->begin();
-         it != ns->getProperties()->end(); ++it) {
-        if (!strcasecmp(name, (*it)->getName()))
-            return (*it);
-    }
-    errno = ENOENT;
-    return NULL;
-}
-
-int PropertyManager::attachProperty(const char *ns_name, Property *p) {
-    PropertyNamespace *ns;
-
-    LOGD("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);
-        ns = new PropertyNamespace(ns_name);
-        mNamespaces->push_back(ns);
-    }
-
-    if (lookupProperty_UNLOCKED(ns, p->getName())) {
-        errno = EADDRINUSE;
-        pthread_mutex_unlock(&mLock);
-        LOGE("Failed to register property %s.%s (%s)",
-            ns_name, p->getName(), strerror(errno));
-        return -1;
-    }
-
-    ns->getProperties()->push_back(p);
-    pthread_mutex_unlock(&mLock);
-    return 0;
-}
-
-int PropertyManager::detachProperty(const char *ns_name, Property *p) {
-    PropertyNamespace *ns;
-
-    LOGD("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);
-        return -1;
-    }
-
-    PropertyCollection::iterator it;
-
-    for (it = ns->getProperties()->begin();
-         it != ns->getProperties()->end(); ++it) {
-        if (!strcasecmp(p->getName(), (*it)->getName())) {
-            delete ((*it));
-            ns->getProperties()->erase(it);
-            pthread_mutex_unlock(&mLock);
-            return 0;
-        }
-    }
-
-    LOGE("Property %s.%s not found", ns_name, p->getName());
-    pthread_mutex_unlock(&mLock);
-    errno = ENOENT;
-    return -1;
-}
-
-int PropertyManager::doSet(Property *p, int idx, const char *value) {
-
-    if (p->getReadOnly()) {
-        errno = EROFS;
-        return -1;
-    }
-
-    if (p->getType() == Property::Type_STRING) {
-        return p->set(idx, value);
-    } else if (p->getType() == Property::Type_INTEGER) {
-        int tmp;
-        errno = 0;
-        tmp = strtol(value, (char **) NULL, 10);
-        if (errno) {
-            LOGE("Failed to convert '%s' to int", value);
-            errno = EINVAL;
-            return -1;
-        }
-        return p->set(idx, tmp);
-    } else if (p->getType() == Property::Type_IPV4) {
-        struct in_addr tmp;
-        if (!inet_aton(value, &tmp)) {
-            LOGE("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(),
-             p->getType());
-        errno = EINVAL;
-        return -1;
-    }
-    errno = ENOENT;
-    return -1;
-}
-
-int PropertyManager::doGet(Property *p, int idx, char *buffer, size_t max) {
-
-    if (p->getType() == Property::Type_STRING) {
-        if (p->get(idx, buffer, max)) {
-            LOGW("String property %s get failed (%s)", p->getName(),
-                 strerror(errno));
-            return -1;
-        }
-    }
-    else if (p->getType() == Property::Type_INTEGER) {
-        int tmp;
-        if (p->get(idx, &tmp)) {
-            LOGW("Integer property %s get failed (%s)", p->getName(),
-                 strerror(errno));
-            return -1;
-        }
-        snprintf(buffer, max, "%d", tmp);
-    } 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(),
-                 strerror(errno));
-            return -1;
-        }
-        strncpy(buffer, inet_ntoa(tmp), max);
-    } else {
-        LOGE("Property '%s' has an unknown type (%d)", p->getName(),
-             p->getType());
-        errno = EINVAL;
-        return -1;
-    }
-    return 0;
-}
-
-/*
- * IPropertyManager methods
- */
-
-int PropertyManager::set(const char *name, const char *value) {
-
-    LOGD("set %s = '%s'", name, value);
-    pthread_mutex_lock(&mLock);
-    PropertyNamespaceCollection::iterator ns_it;
-    for (ns_it = mNamespaces->begin(); ns_it != mNamespaces->end(); ++ns_it) {
-        PropertyCollection::iterator p_it;
-        for (p_it = (*ns_it)->getProperties()->begin();
-             p_it != (*ns_it)->getProperties()->end(); ++p_it) {
-            for (int i = 0; i < (*p_it)->getNumElements(); i++) {
-                char fqn[255];
-                char tmp[8];
-                sprintf(tmp, "_%d", i);
-                snprintf(fqn, sizeof(fqn), "%s.%s%s",
-                         (*ns_it)->getName(), (*p_it)->getName(),
-                         ((*p_it)->getNumElements() > 1 ? tmp : ""));
-                if (!strcasecmp(name, fqn)) {
-                    pthread_mutex_unlock(&mLock);
-                    return doSet((*p_it), i, value);
-                }
-            }
-        }
-    }
-
-    LOGE("Property %s not found", name);
-    pthread_mutex_unlock(&mLock);
-    errno = ENOENT;
-    return -1;
-}
-
-const char *PropertyManager::get(const char *name, char *buffer, size_t max) {
-    pthread_mutex_lock(&mLock);
-    PropertyNamespaceCollection::iterator ns_it;
-    for (ns_it = mNamespaces->begin(); ns_it != mNamespaces->end(); ++ns_it) {
-        PropertyCollection::iterator p_it;
-        for (p_it = (*ns_it)->getProperties()->begin();
-             p_it != (*ns_it)->getProperties()->end(); ++p_it) {
-
-            for (int i = 0; i < (*p_it)->getNumElements(); i++) {
-                char fqn[255];
-                char tmp[8];
-                sprintf(tmp, "_%d", i);
-                snprintf(fqn, sizeof(fqn), "%s.%s%s",
-                         (*ns_it)->getName(), (*p_it)->getName(),
-                         ((*p_it)->getNumElements() > 1 ? tmp : ""));
-                if (!strcasecmp(name, fqn)) {
-                    pthread_mutex_unlock(&mLock);
-                    if (doGet((*p_it), i, buffer, max))
-                        return NULL;
-                    return buffer;
-                }
-            }
-        }
-    }
-
-    LOGE("Property %s not found", name);
-    pthread_mutex_unlock(&mLock);
-    errno = ENOENT;
-    return NULL;
-}
-
-android::List<char *> *PropertyManager::createPropertyList(const char *prefix) {
-    android::List<char *> *c = new android::List<char *>();
-
-    pthread_mutex_lock(&mLock);
-    PropertyNamespaceCollection::iterator ns_it;
-    for (ns_it = mNamespaces->begin(); ns_it != mNamespaces->end(); ++ns_it) {
-        PropertyCollection::iterator p_it;
-        for (p_it = (*ns_it)->getProperties()->begin();
-             p_it != (*ns_it)->getProperties()->end(); ++p_it) {
-            for (int i = 0; i < (*p_it)->getNumElements(); i++) {
-                char fqn[255];
-                char tmp[8];
-                sprintf(tmp, "_%d", i);
-                snprintf(fqn, sizeof(fqn), "%s.%s%s",
-                         (*ns_it)->getName(), (*p_it)->getName(),
-                         ((*p_it)->getNumElements() > 1 ? tmp : ""));
-                if (!prefix ||
-                    (prefix && !strncasecmp(fqn, prefix, strlen(prefix)))) {
-                    c->push_back(strdup(fqn));
-                }
-            }
-        }
-    }
-    pthread_mutex_unlock(&mLock);
-    return c;
-}
diff --git a/nexus/PropertyManager.h b/nexus/PropertyManager.h
deleted file mode 100644
index af56a9c..0000000
--- a/nexus/PropertyManager.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _PROPERTY_MANAGER_H
-#define _PROPERTY_MANAGER_H
-
-#include <errno.h>
-#include <pthread.h>
-
-#include <utils/List.h>
-
-#include "Property.h"
-
-class PropertyManager {
-    PropertyNamespaceCollection *mNamespaces;
-    pthread_mutex_t    mLock;
-
-public:
-    PropertyManager();
-    virtual ~PropertyManager();
-    int attachProperty(const char *ns, Property *p);
-    int detachProperty(const char *ns, Property *p);
-
-    android::List<char *> *createPropertyList(const char *prefix);
-
-    int set(const char *name, const char *value);
-    const char *get(const char *name, char *buffer, size_t max);
-
-private:
-    PropertyNamespace *lookupNamespace_UNLOCKED(const char *ns);
-    Property *lookupProperty_UNLOCKED(PropertyNamespace *ns, const char *name);
-    int doSet(Property *p, int idx, const char *value);
-    int doGet(Property *p, int idx, char *buffer, size_t max);
-};
-
-#endif
diff --git a/nexus/ResponseCode.h b/nexus/ResponseCode.h
deleted file mode 100644
index 4b6cac8..0000000
--- a/nexus/ResponseCode.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _RESPONSECODE_H
-#define _RESPONSECODE_H
-
-class ResponseCode {
-public:
-    // 100 series - Requestion action was initiated; expect another reply
-    // before proceeding with a new command.
-    static const int ActionInitiated = 100;
-
-    static const int WifiScanResult = 125;
-    static const int WifiNetworkList = 126;
-
-    static const int PropertyRead = 127;
-    static const int PropertySet = 128;
-    static const int PropertyList = 129;
-
-    // 200 series - Requested action has been successfully completed
-    static const int CommandOkay = 200;
-
-    // 400 series - The command was accepted but the requested action
-    // did not take place.
-    static const int OperationFailed = 400;
-
-    // 500 series - The command was not accepted and the requested
-    // action did not take place.
-    static const int CommandSyntaxError = 500;
-    static const int CommandParameterError = 501;
-
-    // 600 series - Unsolicited broadcasts
-    static const int UnsolicitedInformational = 600;
-    static const int DhcpStateChange = 605;
-    static const int SupplicantStateChange = 610;
-    static const int ScanResultsReady = 615;
-    static const int LinkSpeedChange = 620;
-    static const int RssiChange = 625;
-};
-#endif
diff --git a/nexus/ScanResult.cpp b/nexus/ScanResult.cpp
deleted file mode 100644
index e9a286c..0000000
--- a/nexus/ScanResult.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <ctype.h>
-
-#define LOG_TAG "ScanResult"
-#include <cutils/log.h>
-
-#include "ScanResult.h"
-
-ScanResult::ScanResult() {
-}
-
-ScanResult::ScanResult(char *rawResult) {
-    char *p = rawResult, *q = rawResult;
-    char tmp[255];
-
-    // BSSID
-    for (q = p; *q != '\t'; ++q);
-    strncpy(tmp, p, (q - p));
-    tmp[q-p] = '\0';
-    mBssid = strdup(tmp);
-    ++q;
-
-    // FREQ
-    for (p = q; *q != '\t'; ++q);
-    strncpy(tmp, p, (q - p));
-    tmp[q-p] = '\0';
-    mFreq = atoi(tmp);
-    ++q;
-
-    // LEVEL
-    for (p = q; *q != '\t'; ++q);
-    strncpy(tmp, p, (q - p));
-    tmp[q-p] = '\0';
-    mLevel = atoi(tmp);
-    ++q;
-
-    // FLAGS
-    for (p = q; *q != '\t'; ++q);
-    strncpy(tmp, p, (q - p));
-    tmp[q-p] = '\0';
-    mFlags = strdup(tmp);
-    ++q;
-
-    // XXX: For some reason Supplicant sometimes sends a double-tab here.
-    // haven't had time to dig into it ...
-    if (*q == '\t')
-        q++;
-
-    for (p = q; *q != '\t'; ++q) {
-        if (*q == '\0')
-            break;
-    }
-
-    strncpy(tmp, p, (q - p));
-    tmp[q-p] = '\0';
-    mSsid = strdup(tmp);
-    ++q;
-
-    return;
- out_bad:
-    LOGW("Malformatted scan result (%s)", rawResult);
-}
-
-ScanResult::~ScanResult() {
-    if (mBssid)
-        free(mBssid);
-    if (mFlags)
-        free(mFlags);
-    if (mSsid)
-        free(mSsid);
-}
-
-ScanResult *ScanResult::clone() {
-    ScanResult *r = new ScanResult();
-
-    r->mBssid = strdup(mBssid);
-    r->mFreq = mFreq;
-    r->mLevel = mLevel;
-    r->mFlags = strdup(mFlags);
-    r->mSsid = strdup(mSsid);
-
-    return r;
-}
diff --git a/nexus/ScanResult.h b/nexus/ScanResult.h
deleted file mode 100644
index 68ad0f0..0000000
--- a/nexus/ScanResult.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SCAN_RESULT_H
-#define _SCAN_RESULT_H
-
-#include <sys/types.h>
-
-#include <utils/List.h>
-
-class ScanResult {
-    char     *mBssid;
-    uint32_t mFreq;
-    int      mLevel;
-    char     *mFlags;
-    char     *mSsid;
-
-private:
-    ScanResult();
-
-public:
-    ScanResult(char *rawResult);
-    virtual ~ScanResult();
-
-    ScanResult *clone();
-
-    const char *getBssid() { return mBssid; }
-    uint32_t getFreq() { return mFreq; }
-    int getLevel() { return mLevel; }
-    const char *getFlags() { return mFlags; }
-    const char *getSsid() { return mSsid; }
-};
-
-typedef android::List<ScanResult *> ScanResultCollection;
-
-#endif
diff --git a/nexus/Supplicant.cpp b/nexus/Supplicant.cpp
deleted file mode 100644
index 6aa36e8..0000000
--- a/nexus/Supplicant.cpp
+++ /dev/null
@@ -1,677 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <sys/types.h>
-#include <fcntl.h>
-#include <errno.h>
-
-#define LOG_TAG "Supplicant"
-#include <cutils/log.h>
-#include <cutils/properties.h>
-
-#include "private/android_filesystem_config.h"
-
-#include <sysutils/ServiceManager.h>
-
-#include "Supplicant.h"
-#include "SupplicantListener.h"
-#include "NetworkManager.h"
-#include "WifiController.h"
-#include "SupplicantStatus.h"
-
-#include "libwpa_client/wpa_ctrl.h"
-
-#define IFACE_DIR        "/data/system/wpa_supplicant"
-#define DRIVER_PROP_NAME "wlan.driver.status"
-#define SUPPLICANT_SERVICE_NAME  "wpa_supplicant"
-#define SUPP_CONFIG_TEMPLATE "/system/etc/wifi/wpa_supplicant.conf"
-#define SUPP_CONFIG_FILE "/data/misc/wifi/wpa_supplicant.conf"
-
-Supplicant::Supplicant(WifiController *wc, ISupplicantEventHandler *handlers) {
-    mHandlers = handlers;
-    mController = wc;
-    mInterfaceName = NULL;
-    mCtrl = NULL;
-    mMonitor = NULL;
-    mListener = NULL;
-   
-    mServiceManager = new ServiceManager();
-
-    mNetworks = new WifiNetworkCollection();
-    pthread_mutex_init(&mNetworksLock, NULL);
-}
-
-Supplicant::~Supplicant() {
-    delete mServiceManager;
-    if (mInterfaceName)
-        free(mInterfaceName);
-}
-
-int Supplicant::start() {
-
-    if (setupConfig()) {
-        LOGW("Unable to setup supplicant.conf");
-    }
-
-    if (mServiceManager->start(SUPPLICANT_SERVICE_NAME)) {
-        LOGE("Error starting supplicant (%s)", strerror(errno));
-        return -1;
-    }
-
-    wpa_ctrl_cleanup();
-    if (connectToSupplicant()) {
-        LOGE("Error connecting to supplicant (%s)\n", strerror(errno));
-        return -1;
-    }
-    
-    if (retrieveInterfaceName()) {
-        LOGE("Error retrieving interface name (%s)\n", strerror(errno));
-        return -1;
-    }
-
-    return 0;
-}
-
-int Supplicant::stop() {
-
-    if (mListener->stopListener()) {
-        LOGW("Unable to stop supplicant listener (%s)", strerror(errno));
-        return -1;
-    }
-
-    if (mServiceManager->stop(SUPPLICANT_SERVICE_NAME)) {
-        LOGW("Error stopping supplicant (%s)", strerror(errno));
-    }
-
-    if (mCtrl) {
-        wpa_ctrl_close(mCtrl);
-        mCtrl = NULL;
-    }
-    if (mMonitor) {
-        wpa_ctrl_close(mMonitor);
-        mMonitor = NULL;
-    }
-
-    return 0;
-}
-
-bool Supplicant::isStarted() {
-    return mServiceManager->isRunning(SUPPLICANT_SERVICE_NAME);
-}
-
-int Supplicant::sendCommand(const char *cmd, char *reply, size_t *reply_len) {
-
-    if (!mCtrl) {
-        errno = ENOTCONN;
-        return -1;
-    }
-
-//    LOGD("sendCommand(): -> '%s'", cmd);
-
-    int rc;
-    memset(reply, 0, *reply_len);
-    if ((rc = wpa_ctrl_request(mCtrl, cmd, strlen(cmd), reply, reply_len, NULL)) == -2)  {
-        errno = ETIMEDOUT;
-        return -1;
-    } else if (rc < 0 || !strncmp(reply, "FAIL", 4)) {
-        strcpy(reply, "FAIL");
-        errno = EIO;
-        return -1;
-    }
-
- //   LOGD("sendCommand(): <- '%s'", reply);
-    return 0;
-}
-SupplicantStatus *Supplicant::getStatus() {
-    char *reply;
-    size_t len = 4096;
-
-    if (!(reply = (char *) malloc(len))) {
-        errno = ENOMEM;
-        return NULL;
-    }
-
-    if (sendCommand("STATUS", reply, &len)) {
-        free(reply);
-        return NULL;
-    }
-
-    SupplicantStatus *ss = SupplicantStatus::createStatus(reply, len);
-  
-    free (reply);
-    return ss;
-}
-
-/*
- * Retrieves the list of networks from Supplicant
- * and merge them into our current list
- */
-int Supplicant::refreshNetworkList() {
-    char *reply;
-    size_t len = 4096;
-
-    if (!(reply = (char *) malloc(len))) {
-        errno = ENOMEM;
-        return -1;
-    }
-
-    if (sendCommand("LIST_NETWORKS", reply, &len)) {
-        free(reply);
-        return -1;
-    }
-
-    char *linep;
-    char *linep_next = NULL;
-
-    if (!strtok_r(reply, "\n", &linep_next)) {
-        LOGW("Malformatted network list\n");
-        free(reply);
-        errno = EIO;
-        return -1;
-    }
-
-    PropertyManager *pm = NetworkManager::Instance()->getPropMngr();
-    pthread_mutex_lock(&mNetworksLock);
-
-    int num_added = 0;
-    int num_refreshed = 0;
-    int num_removed = 0;
-    while((linep = strtok_r(NULL, "\n", &linep_next))) {
-        // TODO: Move the decode into a static method so we
-        // don't create new_wn when we don't have to.
-        WifiNetwork *new_wn = new WifiNetwork(mController, this, linep);
-        WifiNetwork *merge_wn;
-
-        if ((merge_wn = this->lookupNetwork_UNLOCKED(new_wn->getNetworkId()))) {
-            num_refreshed++;
-            if (merge_wn->refresh()) {
-                LOGW("Error refreshing network %d (%s)",
-                     merge_wn->getNetworkId(), strerror(errno));
-                }
-            delete new_wn;
-        } else {
-            num_added++;
-            char new_ns[20];
-            snprintf(new_ns, sizeof(new_ns), "wifi.net.%d", new_wn->getNetworkId());
-            new_wn->attachProperties(pm, new_ns);
-            mNetworks->push_back(new_wn);
-            if (new_wn->refresh()) {
-                LOGW("Unable to refresh network id %d (%s)",
-                    new_wn->getNetworkId(), strerror(errno));
-            }
-        }
-    }
-
-    if (!mNetworks->empty()) {
-        // TODO: Add support for detecting removed networks
-        WifiNetworkCollection::iterator i;
-
-        for (i = mNetworks->begin(); i != mNetworks->end(); ++i) {
-            if (0) {
-                num_removed++;
-                char del_ns[20];
-                snprintf(del_ns, sizeof(del_ns), "wifi.net.%d", (*i)->getNetworkId());
-                (*i)->detachProperties(pm, del_ns);
-                delete (*i);
-                i = mNetworks->erase(i);
-            }
-        }
-    }
-
-
-    LOGD("Networks added %d, refreshed %d, removed %d\n", 
-         num_added, num_refreshed, num_removed);
-    pthread_mutex_unlock(&mNetworksLock);
-
-    free(reply);
-    return 0;
-}
-
-int Supplicant::connectToSupplicant() {
-    if (!isStarted())
-        LOGW("Supplicant service not running");
-
-    mCtrl = wpa_ctrl_open("tiwlan0"); // XXX:
-    if (mCtrl == NULL) {
-        LOGE("Unable to open connection to supplicant on \"%s\": %s",
-             "tiwlan0", strerror(errno));
-        return -1;
-    }
-    mMonitor = wpa_ctrl_open("tiwlan0");
-    if (mMonitor == NULL) {
-        wpa_ctrl_close(mCtrl);
-        mCtrl = NULL;
-        return -1;
-    }
-    if (wpa_ctrl_attach(mMonitor) != 0) {
-        wpa_ctrl_close(mMonitor);
-        wpa_ctrl_close(mCtrl);
-        mCtrl = mMonitor = NULL;
-        return -1;
-    }
-
-    mListener = new SupplicantListener(mHandlers, mMonitor);
-
-    if (mListener->startListener()) {
-        LOGE("Error - unable to start supplicant listener");
-        stop();
-        return -1;
-    }
-    return 0;
-}
-
-int Supplicant::setScanMode(bool active) {
-    char reply[255];
-    size_t len = sizeof(reply);
-
-    if (sendCommand((active ? "DRIVER SCAN-ACTIVE" : "DRIVER SCAN-PASSIVE"),
-                     reply, &len)) {
-        LOGW("triggerScan(%d): Error setting scan mode (%s)", active,
-             strerror(errno));
-        return -1;
-    }
-    return 0;
-}
-
-int Supplicant::triggerScan() {
-    char reply[255];
-    size_t len = sizeof(reply);
-
-    if (sendCommand("SCAN", reply, &len)) {
-        LOGW("triggerScan(): Error initiating scan");
-        return -1;
-    }
-    return 0;
-}
-
-int Supplicant::getRssi(int *buffer) {
-    char reply[64];
-    size_t len = sizeof(reply);
-
-    if (sendCommand("DRIVER RSSI", reply, &len)) {
-        LOGW("Failed to get RSSI (%s)", strerror(errno));
-        return -1;
-    }
-
-    char *next = reply;
-    char *s;
-    for (int i = 0; i < 3; i++) {
-        if (!(s = strsep(&next, " "))) {
-            LOGE("Error parsing RSSI");
-            errno = EIO;
-            return -1;
-        }
-    }
-    *buffer = atoi(s);
-    return 0;
-}
-
-int Supplicant::getLinkSpeed() {
-    char reply[64];
-    size_t len = sizeof(reply);
-
-    if (sendCommand("DRIVER LINKSPEED", reply, &len)) {
-        LOGW("Failed to get LINKSPEED (%s)", strerror(errno));
-        return -1;
-    }
-
-    char *next = reply;
-    char *s;
-
-    if (!(s = strsep(&next, " "))) {
-        LOGE("Error parsing LINKSPEED");
-        errno = EIO;
-        return -1;
-    }
-
-    if (!(s = strsep(&next, " "))) {
-        LOGE("Error parsing LINKSPEED");
-        errno = EIO;
-        return -1;
-    }
-    return atoi(s);
-}
-
-int Supplicant::stopDriver() {
-    char reply[64];
-    size_t len = sizeof(reply);
-
-    LOGD("stopDriver()");
-
-    if (sendCommand("DRIVER STOP", reply, &len)) {
-        LOGW("Failed to stop driver (%s)", strerror(errno));
-        return -1;
-    }
-    return 0;
-}
-
-int Supplicant::startDriver() {
-    char reply[64];
-    size_t len = sizeof(reply);
-
-    LOGD("startDriver()");
-    if (sendCommand("DRIVER START", reply, &len)) {
-        LOGW("Failed to start driver (%s)", strerror(errno));
-        return -1;
-    }
-    return 0;
-}
-
-WifiNetwork *Supplicant::createNetwork() {
-    char reply[255];
-    size_t len = sizeof(reply) -1;
-
-    if (sendCommand("ADD_NETWORK", reply, &len))
-        return NULL;
-
-    if (reply[strlen(reply) -1] == '\n')
-        reply[strlen(reply) -1] = '\0';
-
-    WifiNetwork *wn = new WifiNetwork(mController, this, atoi(reply));
-    PropertyManager *pm = NetworkManager::Instance()->getPropMngr();
-    pthread_mutex_lock(&mNetworksLock);
-    char new_ns[20];
-    snprintf(new_ns, sizeof(new_ns), "wifi.net.%d", wn->getNetworkId());
-    wn->attachProperties(pm, new_ns);
-    mNetworks->push_back(wn);
-    pthread_mutex_unlock(&mNetworksLock);
-    return wn;
-}
-
-int Supplicant::removeNetwork(WifiNetwork *wn) {
-    char req[64];
-
-    sprintf(req, "REMOVE_NETWORK %d", wn->getNetworkId());
-    char reply[32];
-    size_t len = sizeof(reply) -1;
-
-    if (sendCommand(req, reply, &len))
-        return -1;
-
-    pthread_mutex_lock(&mNetworksLock);
-    WifiNetworkCollection::iterator it;
-    for (it = mNetworks->begin(); it != mNetworks->end(); ++it) {
-        if ((*it) == wn) {
-            mNetworks->erase(it);
-            break;
-        }
-    }
-    pthread_mutex_unlock(&mNetworksLock);
-    return 0;
-}
-
-WifiNetwork *Supplicant::lookupNetwork(int networkId) {
-    pthread_mutex_lock(&mNetworksLock);
-    WifiNetwork *wn = lookupNetwork_UNLOCKED(networkId);
-    pthread_mutex_unlock(&mNetworksLock);
-    return wn;
-}
-
-WifiNetwork *Supplicant::lookupNetwork_UNLOCKED(int networkId) {
-    WifiNetworkCollection::iterator it;
-    for (it = mNetworks->begin(); it != mNetworks->end(); ++it) {
-        if ((*it)->getNetworkId() == networkId) {
-            return *it;
-        }
-    }
-    errno = ENOENT;
-    return NULL;
-}
-
-WifiNetworkCollection *Supplicant::createNetworkList() {
-    WifiNetworkCollection *d = new WifiNetworkCollection();
-    WifiNetworkCollection::iterator i;
-
-    pthread_mutex_lock(&mNetworksLock);
-    for (i = mNetworks->begin(); i != mNetworks->end(); ++i)
-        d->push_back((*i)->clone());
-
-    pthread_mutex_unlock(&mNetworksLock);
-    return d;
-}
-
-int Supplicant::setupConfig() {
-    char buf[2048];
-    int srcfd, destfd;
-    int nread;
-
-    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));
-        return -1;
-    }
-
-    srcfd = open(SUPP_CONFIG_TEMPLATE, O_RDONLY);
-    if (srcfd < 0) {
-        LOGE("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));
-        return -1;
-    }
-
-    while ((nread = read(srcfd, buf, sizeof(buf))) != 0) {
-        if (nread < 0) {
-            LOGE("Error reading \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
-            close(srcfd);
-            close(destfd);
-            unlink(SUPP_CONFIG_FILE);
-            return -1;
-        }
-        write(destfd, buf, nread);
-    }
-
-    close(destfd);
-    close(srcfd);
-
-    if (chown(SUPP_CONFIG_FILE, AID_SYSTEM, AID_WIFI) < 0) {
-        LOGE("Error changing group ownership of %s to %d: %s",
-             SUPP_CONFIG_FILE, AID_WIFI, strerror(errno));
-        unlink(SUPP_CONFIG_FILE);
-        return -1;
-    }
-    return 0;
-}
-
-int Supplicant::setNetworkVar(int networkId, const char *var, const char *val) {
-    char reply[255];
-    size_t len = sizeof(reply) -1;
-
-    LOGD("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)) {
-        free(tmp);
-        return -1;
-    }
-    free(tmp);
-
-    len = sizeof(reply) -1;
-    if (sendCommand("SAVE_CONFIG", reply, &len)) {
-        LOGE("Error saving config after %s = %s", var, val);
-        return -1;
-    }
-    return 0;
-}
-
-const char *Supplicant::getNetworkVar(int networkId, const char *var,
-                                      char *buffer, size_t max) {
-    size_t len = max - 1;
-    char *tmp;
-
-    asprintf(&tmp, "GET_NETWORK %d %s", networkId, var);
-    if (sendCommand(tmp, buffer, &len)) {
-        free(tmp);
-        return NULL;
-    }
-    free(tmp);
-    return buffer;
-}
-
-int Supplicant::enableNetwork(int networkId, bool enabled) {
-    char req[64];
-
-    if (enabled)
-        sprintf(req, "ENABLE_NETWORK %d", networkId);
-    else
-        sprintf(req, "DISABLE_NETWORK %d", networkId);
-
-    char reply[16];
-    size_t len = sizeof(reply) -1;
-
-    if (sendCommand(req, reply, &len))
-        return -1;
-    return 0;
-}
-
-int Supplicant::enablePacketFilter() {
-    char req[128];
-    char reply[16];
-    size_t len;
-    int i;
-    
-    for (i = 0; i <=3; i++) {
-        snprintf(req, sizeof(req), "DRIVER RXFILTER-ADD %d", i);
-        len = sizeof(reply);
-        if (sendCommand(req, reply, &len))
-            return -1;
-    }
-
-    len = sizeof(reply);
-    if (sendCommand("DRIVER RXFILTER-START", reply, &len))
-        return -1;
-    return 0;
-}
-  
-int Supplicant::disablePacketFilter() {
-    char req[128];
-    char reply[16];
-    size_t len;
-    int i;
-    
-    len = sizeof(reply);
-    if (sendCommand("DRIVER RXFILTER-STOP", reply, &len))
-        return -1;
-
-    for (i = 3; i >=0; i--) {
-        snprintf(req, sizeof(req), "DRIVER RXFILTER-REMOVE %d", i);
-        len = sizeof(reply);
-        if (sendCommand(req, reply, &len))
-            return -1;
-    }
-    return 0;
-}
-
-int Supplicant::enableBluetoothCoexistenceScan() {
-    char req[128];
-    char reply[16];
-    size_t len;
-    int i;
-    
-    len = sizeof(reply);
-    if (sendCommand("DRIVER BTCOEXSCAN-START", reply, &len))
-        return -1;
-    return 0;
-}
-
-int Supplicant::disableBluetoothCoexistenceScan() {
-    char req[128];
-    char reply[16];
-    size_t len;
-    int i;
-    
-    len = sizeof(reply);
-    if (sendCommand("DRIVER BTCOEXSCAN-STOP", reply, &len))
-        return -1;
-    return 0;
-}
-
-int Supplicant::setBluetoothCoexistenceMode(int mode) {
-    char req[64];
-
-    sprintf(req, "DRIVER BTCOEXMODE %d", mode);
-
-    char reply[16];
-    size_t len = sizeof(reply) -1;
-
-    if (sendCommand(req, reply, &len))
-        return -1;
-    return 0;
-}
-
-int Supplicant::setApScanMode(int mode) {
-    char req[64];
-
-//    LOGD("setApScanMode(%d)", mode);
-    sprintf(req, "AP_SCAN %d", mode);
-
-    char reply[16];
-    size_t len = sizeof(reply) -1;
-
-    if (sendCommand(req, reply, &len))
-        return -1;
-    return 0;
-}
-
-
-int Supplicant::retrieveInterfaceName() {
-    char reply[255];
-    size_t len = sizeof(reply) -1;
-
-    if (sendCommand("INTERFACES", reply, &len))
-        return -1;
-
-    reply[strlen(reply)-1] = '\0';
-    mInterfaceName = strdup(reply);
-    return 0;
-}
-
-int Supplicant::reconnect() {
-    char req[128];
-    char reply[16];
-    size_t len;
-    int i;
-    
-    len = sizeof(reply);
-    if (sendCommand("RECONNECT", reply, &len))
-        return -1;
-    return 0;
-}
-
-int Supplicant::disconnect() {
-    char req[128];
-    char reply[16];
-    size_t len;
-    int i;
-    
-    len = sizeof(reply);
-    if (sendCommand("DISCONNECT", reply, &len))
-        return -1;
-    return 0;
-}
-
-int Supplicant::getNetworkCount() {
-    pthread_mutex_lock(&mNetworksLock);
-    int cnt = mNetworks->size();
-    pthread_mutex_unlock(&mNetworksLock);
-    return cnt;
-}
diff --git a/nexus/Supplicant.h b/nexus/Supplicant.h
deleted file mode 100644
index 3900f4f..0000000
--- a/nexus/Supplicant.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SUPPLICANT_H
-#define _SUPPLICANT_H
-
-struct wpa_ctrl;
-class SupplicantListener;
-class ServiceManager;
-class Controller;
-class WifiController;
-class SupplicantStatus;
-
-#include <pthread.h>
-
-#include "WifiNetwork.h"
-#include "ISupplicantEventHandler.h"
-
-class Supplicant {
-    struct wpa_ctrl      *mCtrl;
-    struct wpa_ctrl      *mMonitor;
-    SupplicantListener   *mListener;
-    ServiceManager       *mServiceManager;
-    WifiController       *mController;
-    char                 *mInterfaceName;
-
-    WifiNetworkCollection   *mNetworks;
-    pthread_mutex_t         mNetworksLock;
-    ISupplicantEventHandler *mHandlers;
- 
-public:
-    Supplicant(WifiController *wc, ISupplicantEventHandler *handlers);
-    virtual ~Supplicant();
-
-    int start();
-    int stop();
-    bool isStarted();
-
-    int setScanMode(bool active);
-    int triggerScan();
-
-    WifiNetwork *createNetwork();
-    WifiNetwork *lookupNetwork(int networkId);
-    int removeNetwork(WifiNetwork *net);
-    WifiNetworkCollection *createNetworkList();
-    int refreshNetworkList();
-
-    int setNetworkVar(int networkId, const char *var, const char *value);
-    const char *getNetworkVar(int networkid, const char *var, char *buffer,
-                              size_t max);
-    int enableNetwork(int networkId, bool enabled);
-
-    int disconnect();
-    int reconnect();
-    int reassociate();
-    int setApScanMode(int mode);
-    int enablePacketFilter();
-    int disablePacketFilter();
-    int setBluetoothCoexistenceMode(int mode);
-    int enableBluetoothCoexistenceScan();
-    int disableBluetoothCoexistenceScan();
-    int stopDriver();
-    int startDriver();
-    int getRssi(int *buffer);
-    int getLinkSpeed();
-    int getNetworkCount();
-
-    SupplicantStatus *getStatus();
-
-    Controller *getController() { return (Controller *) mController; }
-    const char *getInterfaceName() { return mInterfaceName; }
-
-    int sendCommand(const char *cmd, char *reply, size_t *reply_len);
-
-private:
-    int connectToSupplicant();
-    int setupConfig();
-    int retrieveInterfaceName();
-    WifiNetwork *lookupNetwork_UNLOCKED(int networkId);
-};
-
-#endif
diff --git a/nexus/SupplicantAssociatedEvent.cpp b/nexus/SupplicantAssociatedEvent.cpp
deleted file mode 100644
index e40411e..0000000
--- a/nexus/SupplicantAssociatedEvent.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-
-#define LOG_TAG "SupplicantAssociatedEvent"
-#include <cutils/log.h>
-
-#include "SupplicantAssociatedEvent.h"
-
-SupplicantAssociatedEvent::SupplicantAssociatedEvent(int level, char *event,
-                                                     size_t len) :
-                           SupplicantEvent(SupplicantEvent::EVENT_ASSOCIATED,
-                                           level) {
-    char *p = event;
-
-    // "00:13:46:40:40:aa"
-    mBssid = (char *) malloc(18);
-    strncpy(mBssid, p, 17);
-    mBssid[17] = '\0';
-}
-
-SupplicantAssociatedEvent::~SupplicantAssociatedEvent() {
-    if (mBssid)
-        free(mBssid);
-}
-
diff --git a/nexus/SupplicantAssociatedEvent.h b/nexus/SupplicantAssociatedEvent.h
deleted file mode 100644
index aa33c59..0000000
--- a/nexus/SupplicantAssociatedEvent.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantAssociatedEvent_H
-#define _SupplicantAssociatedEvent_H
-
-#include "SupplicantEvent.h"
-
-class SupplicantAssociatedEvent : public SupplicantEvent {
-    char *mBssid;
-    char *mSsid;
-    int  mFreq;
-
-public:
-    SupplicantAssociatedEvent(int level, char *event, size_t len);
-    virtual ~SupplicantAssociatedEvent();
-
-    const char *getBssid() { return mBssid; }
-};
-
-#endif
diff --git a/nexus/SupplicantAssociatingEvent.cpp b/nexus/SupplicantAssociatingEvent.cpp
deleted file mode 100644
index c6e9fe3..0000000
--- a/nexus/SupplicantAssociatingEvent.cpp
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-
-#define LOG_TAG "SupplicantAssociatingEvent"
-#include <cutils/log.h>
-
-#include "SupplicantAssociatingEvent.h"
-
-SupplicantAssociatingEvent::SupplicantAssociatingEvent(int level, char *event,
-                                                     size_t len) :
-                           SupplicantEvent(SupplicantEvent::EVENT_ASSOCIATING,
-                                           level) {
-    char *p = event;
-
-    mBssid = NULL;
-    mSsid = NULL;
-    mFreq = -1;
-
-    // SSID 'default' 
-    // OR
-    // "00:13:46:40:40:aa (SSID='default' freq=2437 MHz)"
-
-    if (strncmp(event, "SSID", 4)) {
-        mBssid = (char *) malloc(18);
-        strncpy(mBssid, p, 17);
-        mBssid[17] = '\0';
-        p += 25;
-
-        // "00:13:46:40:40:aa (SSID='default' freq=2437 MHz)"
-        //                           ^
-        //                           p
-        char *q = index(p, '\'');
-        if (!q) {
-            LOGE("Unable to decode SSID (p = {%s})\n", p);
-            return;
-        }
-        mSsid = (char *) malloc((q - p) +1);
-        strncpy(mSsid, p, q-p);
-        mSsid[q-p] = '\0';
-
-        p = q + 7;
-    
-        // "00:13:46:40:40:aa (SSID='default' freq=2437 MHz)"
-        //                                         ^
-        //                                         p
-        if (!(q = index(p, ' '))) {
-            LOGE("Unable to decode frequency\n");
-            return;
-        }
-        *q = '\0';
-        mFreq = atoi(p);
-    } else {
-        p+= 6;
-
-        // SSID 'default' 
-        //       ^
-        //       p
-
-        char *q = index(p, '\'');
-        if (!q) {
-            LOGE("Unable to decode SSID (p = {%s})\n", p);
-            return;
-        }
-        mSsid = (char *) malloc((q - p) +1);
-        strncpy(mSsid, p, q-p);
-        mSsid[q-p] = '\0';
-    }
-}
-
-SupplicantAssociatingEvent::SupplicantAssociatingEvent(const char *bssid, 
-                                                     const char *ssid,
-                                                     int freq) :
-                           SupplicantEvent(SupplicantEvent::EVENT_ASSOCIATING, -1) {
-    mBssid = strdup(bssid);
-    mSsid= strdup(ssid);
-    mFreq = freq;
-}
-
-SupplicantAssociatingEvent::~SupplicantAssociatingEvent() {
-    if (mBssid)
-        free(mBssid);
-    if (mSsid)
-        free(mSsid);
-}
-
diff --git a/nexus/SupplicantAssociatingEvent.h b/nexus/SupplicantAssociatingEvent.h
deleted file mode 100644
index d3a4d5c..0000000
--- a/nexus/SupplicantAssociatingEvent.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantAssociatingEvent_H
-#define _SupplicantAssociatingEvent_H
-
-#include "SupplicantEvent.h"
-
-class SupplicantAssociatingEvent : public SupplicantEvent {
-    char *mBssid;
-    char *mSsid;
-    int  mFreq;
-
-public:
-    SupplicantAssociatingEvent(int level, char *event, size_t len);
-    SupplicantAssociatingEvent(const char *bssid, const char *ssid, int freq);
-    virtual ~SupplicantAssociatingEvent();
-
-    const char *getBssid() { return mBssid; }
-    const char *getSsid() { return mSsid; }
-    int getFreq() { return mFreq;}
-};
-
-#endif
diff --git a/nexus/SupplicantConnectedEvent.cpp b/nexus/SupplicantConnectedEvent.cpp
deleted file mode 100644
index e58bab2..0000000
--- a/nexus/SupplicantConnectedEvent.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "SupplicantConnectedEvent"
-#include <cutils/log.h>
-
-#include "SupplicantConnectedEvent.h"
-
-SupplicantConnectedEvent::SupplicantConnectedEvent(int level, char *event,
-                                                   size_t len) :
-                          SupplicantEvent(SupplicantEvent::EVENT_CONNECTED,
-                                          level) {
-    char *p;
-
-    //  "- Connection to 00:13:46:40:40:aa completed (auth) [id=1 id_str=], 89"
-    
-    if ((p = index(event + 2, ' ')) && (++p = index(p, ' '))) {
-        mBssid = (char *) malloc(18);
-        strncpy(mBssid, ++p, 17);
-        mBssid[17] = '\0';
-
-        //  "- Connection to 00:13:46:40:40:aa completed (auth) [id=1 id_str=], 89"
-        //                   ^
-        //                   p
-        
-        if ((p = index(p, ' ')) && ((++p = index(p, ' ')))) {
-            if (!strncmp(++p, "(auth)", 6))
-                mReassociated = false;
-            else
-                mReassociated = true;
-        } else
-            LOGE("Unable to decode re-assocation");
-    } else
-        LOGE("Unable to decode event");
-}
-
-SupplicantConnectedEvent::SupplicantConnectedEvent(const char *bssid, 
-                                                   bool reassocated) :
-                          SupplicantEvent(SupplicantEvent::EVENT_CONNECTED, -1) {
-    mBssid = strdup(bssid);
-    mReassociated = reassocated;
-}
-
-SupplicantConnectedEvent::~SupplicantConnectedEvent() {
-    if (mBssid)
-        free(mBssid);
-}
-
diff --git a/nexus/SupplicantConnectedEvent.h b/nexus/SupplicantConnectedEvent.h
deleted file mode 100644
index 03e9842..0000000
--- a/nexus/SupplicantConnectedEvent.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantConnectedEvent_H
-#define _SupplicantConnectedEvent_H
-
-#include "SupplicantEvent.h"
-
-class SupplicantConnectedEvent : public SupplicantEvent {
-private:
-    char *mBssid;
-    bool mReassociated;
-
-public:
-    SupplicantConnectedEvent(int level, char *event, size_t len);
-    SupplicantConnectedEvent(const char *bssid, bool reassicated);
-    virtual ~SupplicantConnectedEvent();
-
-    const char *getBssid() { return mBssid; }
-    bool getReassociated() { return mReassociated; }
-};
-
-#endif
diff --git a/nexus/SupplicantConnectionTimeoutEvent.cpp b/nexus/SupplicantConnectionTimeoutEvent.cpp
deleted file mode 100644
index 8b8a7d7..0000000
--- a/nexus/SupplicantConnectionTimeoutEvent.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "SupplicantConnectionTimeoutEvent"
-#include <cutils/log.h>
-
-#include "SupplicantConnectionTimeoutEvent.h"
-
-SupplicantConnectionTimeoutEvent::SupplicantConnectionTimeoutEvent(int level, char *event,
-                                                   size_t len) :
-                          SupplicantEvent(SupplicantEvent::EVENT_CONNECTIONTIMEOUT,
-                                          level) {
-    // 00:13:46:40:40:aa timed out.'
-    mBssid = (char *) malloc(18);
-    strncpy(mBssid, event, 17);
-    mBssid[17] = '\0';
-}
-
-SupplicantConnectionTimeoutEvent::~SupplicantConnectionTimeoutEvent() {
-    if (mBssid)
-        free(mBssid);
-}
-
diff --git a/nexus/SupplicantConnectionTimeoutEvent.h b/nexus/SupplicantConnectionTimeoutEvent.h
deleted file mode 100644
index 0d2606d..0000000
--- a/nexus/SupplicantConnectionTimeoutEvent.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantConnectionTimeoutEvent_H
-#define _SupplicantConnectionTimeoutEvent_H
-
-#include "SupplicantEvent.h"
-
-class SupplicantConnectionTimeoutEvent : public SupplicantEvent {
-private:
-    char *mBssid;
-    bool mReassociated;
-
-public:
-    SupplicantConnectionTimeoutEvent(int level, char *event, size_t len);
-    virtual ~SupplicantConnectionTimeoutEvent();
-
-    const char *getBssid() { return mBssid; }
-};
-
-#endif
diff --git a/nexus/SupplicantDisconnectedEvent.cpp b/nexus/SupplicantDisconnectedEvent.cpp
deleted file mode 100644
index 11e499d..0000000
--- a/nexus/SupplicantDisconnectedEvent.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "SupplicantDisconnectedEvent"
-#include <cutils/log.h>
-
-#include "SupplicantDisconnectedEvent.h"
-
-SupplicantDisconnectedEvent::SupplicantDisconnectedEvent(int level, char *event,
-                                                       size_t len) :
-                            SupplicantEvent(SupplicantEvent::EVENT_DISCONNECTED,
-                                            level) {
-}
-
-SupplicantDisconnectedEvent::SupplicantDisconnectedEvent() :
-                            SupplicantEvent(SupplicantEvent::EVENT_DISCONNECTED, -1) {
-}
-
-SupplicantDisconnectedEvent::~SupplicantDisconnectedEvent() {
-}
diff --git a/nexus/SupplicantDisconnectedEvent.h b/nexus/SupplicantDisconnectedEvent.h
deleted file mode 100644
index c09ec62..0000000
--- a/nexus/SupplicantDisconnectedEvent.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantDisconnectedEvent_H
-#define _SupplicantDisconnectedEvent_H
-
-#include "SupplicantEvent.h"
-
-class SupplicantDisconnectedEvent : public SupplicantEvent {
-
-public:
-    SupplicantDisconnectedEvent(int level, char *event, size_t len);
-    SupplicantDisconnectedEvent();
-    virtual ~SupplicantDisconnectedEvent();
-};
-
-#endif
diff --git a/nexus/SupplicantEvent.h b/nexus/SupplicantEvent.h
deleted file mode 100644
index 9d7cbd9..0000000
--- a/nexus/SupplicantEvent.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SUPPLICANT_EVENT_H
-#define _SUPPLICANT_EVENT_H
-
-#include <sys/types.h>
-
-class SupplicantEvent {
-private:
-    int mType;
-    int mLevel;
-
-public:
-    static const int EVENT_UNKNOWN           = 0;
-    static const int EVENT_CONNECTED         = 1;
-    static const int EVENT_DISCONNECTED      = 2;
-    static const int EVENT_TERMINATING       = 3;
-    static const int EVENT_PASSWORD_CHANGED  = 4;
-    static const int EVENT_EAP_NOTIFICATION  = 5;
-    static const int EVENT_EAP_STARTED       = 6;
-    static const int EVENT_EAP_METHOD        = 7;
-    static const int EVENT_EAP_SUCCESS       = 8;
-    static const int EVENT_EAP_FAILURE       = 9;
-    static const int EVENT_SCAN_RESULTS      = 10;
-    static const int EVENT_STATE_CHANGE      = 11;
-    static const int EVENT_LINK_SPEED        = 12;
-    static const int EVENT_DRIVER_STATE      = 13;
-    static const int EVENT_ASSOCIATING       = 14;
-    static const int EVENT_ASSOCIATED        = 15;
-    static const int EVENT_CONNECTIONTIMEOUT = 16;
-
-public:
-    SupplicantEvent(int type, int level);
-    virtual ~SupplicantEvent() {}
-
-    int getType() { return mType; }
-    int getLevel() { return mLevel; }
-};
-
-#endif
diff --git a/nexus/SupplicantEventFactory.cpp b/nexus/SupplicantEventFactory.cpp
deleted file mode 100644
index 8695aca..0000000
--- a/nexus/SupplicantEventFactory.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-
-#define LOG_TAG "SupplicantEventFactory"
-#include <cutils/log.h>
-
-#include "SupplicantEvent.h"
-#include "SupplicantEventFactory.h"
-#include "SupplicantAssociatingEvent.h"
-#include "SupplicantAssociatedEvent.h"
-#include "SupplicantConnectedEvent.h"
-#include "SupplicantStateChangeEvent.h"
-#include "SupplicantScanResultsEvent.h"
-#include "SupplicantConnectionTimeoutEvent.h"
-#include "SupplicantDisconnectedEvent.h"
-#if 0
-#include "SupplicantTerminatingEvent.h"
-#include "SupplicantPasswordChangedEvent.h"
-#include "SupplicantEapNotificationEvent.h"
-#include "SupplicantEapStartedEvent.h"
-#include "SupplicantEapMethodEvent.h"
-#include "SupplicantEapSuccessEvent.h"
-#include "SupplicantEapFailureEvent.h"
-#include "SupplicantLinkSpeedEvent.h"
-#include "SupplicantDriverStateEvent.h"
-#endif
-
-#include "libwpa_client/wpa_ctrl.h"
-
-SupplicantEventFactory::SupplicantEventFactory() {
-}
-
-SupplicantEvent *SupplicantEventFactory::createEvent(char *event, size_t len) {
-    int level = 0;
-
-    if (event[0] == '<') {
-        char *match = strchr(event, '>');
-        if (match) {
-            char tmp[16];
-
-            strncpy(tmp, &event[1], (match - event));
-            level = atoi(tmp);
-            event += (match - event) + 1;
-        } else
-            LOGW("Unclosed level brace in event");
-    } else
-        LOGW("No level specified in event");
-
-    /*
-     * <N>CTRL-EVENT-XXX
-     *    ^
-     *    +---- event
-     */
-
-    if (!strncmp(event, "Authentication with ", 20)) {
-        if (!strcmp(event + strlen(event) - strlen(" timed out."),
-                    " timed out.")) {
-            return new SupplicantConnectionTimeoutEvent(level,
-                                                        event + 20,
-                                                        len);
-        } else
-            return NULL;
-        
-    } else if (!strncmp(event, "Associated with ", 16))
-        return new SupplicantAssociatedEvent(level, event + 16, len);
-    else if (!strncmp(event, "Trying to associate with ", 25))
-        return new SupplicantAssociatingEvent(level, event + 25, len);
-    else if (!strncmp(event, WPA_EVENT_CONNECTED, strlen(WPA_EVENT_CONNECTED))) {
-        return new SupplicantConnectedEvent(level,
-                                            event + strlen(WPA_EVENT_CONNECTED),
-                                            len);
-    } else if (!strncmp(event, WPA_EVENT_SCAN_RESULTS, strlen(WPA_EVENT_SCAN_RESULTS))) {
-        return new SupplicantScanResultsEvent(level,
-                                              event + strlen(WPA_EVENT_SCAN_RESULTS),
-                                              len);
-    } else if (!strncmp(event, WPA_EVENT_STATE_CHANGE, strlen(WPA_EVENT_STATE_CHANGE))) {
-        return new SupplicantStateChangeEvent(level,
-                                              event + strlen(WPA_EVENT_STATE_CHANGE),
-                                              len);
-    }
-    else if (!strncmp(event, WPA_EVENT_DISCONNECTED, strlen(WPA_EVENT_DISCONNECTED)))
-        return new SupplicantDisconnectedEvent(level, event, len);
-#if 0
-    else if (!strncmp(event, WPA_EVENT_TERMINATING, strlen(WPA_EVENT_TERMINATING)))
-        return new SupplicantTerminatingEvent(event, len);
-    else if (!strncmp(event, WPA_EVENT_PASSWORD_CHANGED, strlen(WPA_EVENT_PASSWORD_CHANGED)))
-        return new SupplicantPasswordChangedEvent(event, len);
-    else if (!strncmp(event, WPA_EVENT_EAP_NOTIFICATION, strlen(WPA_EVENT_EAP_NOTIFICATION)))
-        return new SupplicantEapNotificationEvent(event, len);
-    else if (!strncmp(event, WPA_EVENT_EAP_STARTED, strlen(WPA_EVENT_EAP_STARTED)))
-        return new SupplicantEapStartedEvent(event, len);
-    else if (!strncmp(event, WPA_EVENT_EAP_METHOD, strlen(WPA_EVENT_EAP_METHOD)))
-        return new SupplicantEapMethodEvent(event, len);
-    else if (!strncmp(event, WPA_EVENT_EAP_SUCCESS, strlen(WPA_EVENT_EAP_SUCCESS)))
-        return new SupplicantEapSuccessEvent(event, len);
-    else if (!strncmp(event, WPA_EVENT_EAP_FAILURE, strlen(WPA_EVENT_EAP_FAILURE)))
-        return new SupplicantEapFailureEvent(event, len);
-    else if (!strncmp(event, WPA_EVENT_LINK_SPEED, strlen(WPA_EVENT_LINK_SPEED)))
-        return new SupplicantLinkSpeedEvent(event, len);
-    else if (!strncmp(event, WPA_EVENT_DRIVER_STATE, strlen(WPA_EVENT_DRIVER_STATE)))
-         return new SupplicantDriverStateEvent(event, len);
-#endif
-    return NULL;
-}
diff --git a/nexus/SupplicantEventFactory.h b/nexus/SupplicantEventFactory.h
deleted file mode 100644
index 22e5707..0000000
--- a/nexus/SupplicantEventFactory.h
+++ /dev/null
@@ -1,31 +0,0 @@
-
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantEventFactory_H
-#define _SupplicantEventFactory_H
-
-class SupplicantEvent;
-
-class SupplicantEventFactory {
-public:
-    SupplicantEventFactory();
-    virtual ~SupplicantEventFactory() {}
-
-    SupplicantEvent *createEvent(char *event, size_t len);
-};
-
-#endif
diff --git a/nexus/SupplicantListener.cpp b/nexus/SupplicantListener.cpp
deleted file mode 100644
index b91fc02..0000000
--- a/nexus/SupplicantListener.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <sys/types.h>
-#include <pthread.h>
-
-#define LOG_TAG "SupplicantListener"
-#include <cutils/log.h>
-
-#include "libwpa_client/wpa_ctrl.h"
-
-#include "SupplicantListener.h"
-#include "ISupplicantEventHandler.h"
-#include "SupplicantEventFactory.h"
-#include "SupplicantEvent.h"
-#include "SupplicantAssociatingEvent.h"
-#include "SupplicantAssociatedEvent.h"
-#include "SupplicantConnectedEvent.h"
-#include "SupplicantScanResultsEvent.h"
-#include "SupplicantStateChangeEvent.h"
-
-SupplicantListener::SupplicantListener(ISupplicantEventHandler *handlers, 
-                                       struct wpa_ctrl *monitor) :
-                    SocketListener(wpa_ctrl_get_fd(monitor), false) {
-    mHandlers = handlers;
-    mMonitor = monitor;
-    mFactory = new SupplicantEventFactory();
-}
-
-bool SupplicantListener::onDataAvailable(SocketClient *cli) {
-    char buf[255];
-    size_t buflen = sizeof(buf);
-    int rc;
-    size_t nread = buflen - 1;
-
-    if ((rc = wpa_ctrl_recv(mMonitor, buf, &nread))) {
-        LOGE("wpa_ctrl_recv failed (%s)", strerror(errno));
-        return false;
-    }
-
-    buf[nread] = '\0';
-    if (!rc && !nread) {
-        LOGD("Received EOF on supplicant socket\n");
-        strncpy(buf, WPA_EVENT_TERMINATING " - signal 0 received", buflen-1);
-        buf[buflen-1] = '\0';
-        return false;
-    }
-
-    SupplicantEvent *evt = mFactory->createEvent(buf, nread);
-
-    if (!evt) {
-        LOGW("Dropping unknown supplicant event '%s'", buf);
-        return true;
-    }
-
-    // Call the appropriate handler
-    if (evt->getType() == SupplicantEvent::EVENT_ASSOCIATING)
-        mHandlers->onAssociatingEvent((SupplicantAssociatingEvent *) evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_ASSOCIATED)
-        mHandlers->onAssociatedEvent((SupplicantAssociatedEvent *) evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_CONNECTED)
-        mHandlers->onConnectedEvent((SupplicantConnectedEvent *) evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_SCAN_RESULTS)
-        mHandlers->onScanResultsEvent((SupplicantScanResultsEvent *) evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_STATE_CHANGE)
-        mHandlers->onStateChangeEvent((SupplicantStateChangeEvent *) evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_CONNECTIONTIMEOUT)
-        mHandlers->onConnectionTimeoutEvent((SupplicantConnectionTimeoutEvent *) evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_DISCONNECTED)
-        mHandlers->onDisconnectedEvent((SupplicantDisconnectedEvent *) evt);
-    else
-        LOGW("Whoops - no handler available for event '%s'\n", buf);
-#if 0
-    else if (evt->getType() == SupplicantEvent::EVENT_TERMINATING)
-        mHandlers->onTerminatingEvent(evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_PASSWORD_CHANGED)
-        mHandlers->onPasswordChangedEvent(evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_EAP_NOTIFICATION)
-        mHandlers->onEapNotificationEvent(evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_EAP_STARTED)
-        mHandlers->onEapStartedEvent(evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_EAP_SUCCESS)
-        mHandlers->onEapSuccessEvent(evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_EAP_FAILURE)
-        mHandlers->onEapFailureEvent(evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_LINK_SPEED)
-        mHandlers->onLinkSpeedEvent(evt);
-    else if (evt->getType() == SupplicantEvent::EVENT_DRIVER_STATE)
-        mHandlers->onDriverStateEvent(evt);
-#endif
-
-    delete evt;
-
-    return true;
-}
diff --git a/nexus/SupplicantListener.h b/nexus/SupplicantListener.h
deleted file mode 100644
index a1da773..0000000
--- a/nexus/SupplicantListener.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SUPPLICANTLISTENER_H__
-#define _SUPPLICANTLISTENER_H__
-
-#include <sysutils/SocketListener.h>
-
-struct wpa_ctrl;
-class Supplicant;
-class SocketClient;
-class ISupplicantEventHandler;
-class SupplicantEventFactory;
-
-class SupplicantListener: public SocketListener {
-    struct wpa_ctrl         *mMonitor;
-    ISupplicantEventHandler *mHandlers;
-    SupplicantEventFactory  *mFactory;
-    
-public:
-    SupplicantListener(ISupplicantEventHandler *handlers,
-                       struct wpa_ctrl *monitor);
-    virtual ~SupplicantListener() {}
-
-    struct wpa_ctrl *getMonitor() { return mMonitor; }
-
-protected:
-    virtual bool onDataAvailable(SocketClient *c);
-};
-
-#endif
diff --git a/nexus/SupplicantScanResultsEvent.cpp b/nexus/SupplicantScanResultsEvent.cpp
deleted file mode 100644
index c53adad..0000000
--- a/nexus/SupplicantScanResultsEvent.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "SupplicantScanResultsEvent"
-#include <cutils/log.h>
-
-#include "SupplicantScanResultsEvent.h"
-
-SupplicantScanResultsEvent::SupplicantScanResultsEvent(int level, char *event,
-                                                       size_t len) :
-                            SupplicantEvent(SupplicantEvent::EVENT_SCAN_RESULTS,
-                                            level) {
-}
-
-SupplicantScanResultsEvent::SupplicantScanResultsEvent() :
-                            SupplicantEvent(SupplicantEvent::EVENT_SCAN_RESULTS, -1) {
-}
-
-SupplicantScanResultsEvent::~SupplicantScanResultsEvent() {
-}
-
diff --git a/nexus/SupplicantScanResultsEvent.h b/nexus/SupplicantScanResultsEvent.h
deleted file mode 100644
index 5f82041..0000000
--- a/nexus/SupplicantScanResultsEvent.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantScanResultsEvent_H
-#define _SupplicantScanResultsEvent_H
-
-#include "SupplicantEvent.h"
-
-class SupplicantScanResultsEvent : public SupplicantEvent {
-
-public:
-    SupplicantScanResultsEvent(int level, char *event, size_t len);
-    SupplicantScanResultsEvent();
-    virtual ~SupplicantScanResultsEvent();
-};
-
-#endif
diff --git a/nexus/SupplicantState.cpp b/nexus/SupplicantState.cpp
deleted file mode 100644
index 2815430..0000000
--- a/nexus/SupplicantState.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-
-#define LOG_TAG "SupplicantState"
-#include <cutils/log.h>
-
-#include "SupplicantState.h"
-
-char *SupplicantState::toString(int val, char *buffer, int max) {
-    if (val == SupplicantState::UNKNOWN)
-        strncpy(buffer, "UNKNOWN", max);
-    else if (val == SupplicantState::DISCONNECTED)
-        strncpy(buffer, "DISCONNECTED", max);
-    else if (val == SupplicantState::INACTIVE)
-        strncpy(buffer, "INACTIVE", max);
-    else if (val == SupplicantState::SCANNING)
-        strncpy(buffer, "SCANNING", max);
-    else if (val == SupplicantState::ASSOCIATING)
-        strncpy(buffer, "ASSOCIATING", max);
-    else if (val == SupplicantState::ASSOCIATED)
-        strncpy(buffer, "ASSOCIATED", max);
-    else if (val == SupplicantState::FOURWAY_HANDSHAKE)
-        strncpy(buffer, "FOURWAY_HANDSHAKE", max);
-    else if (val == SupplicantState::GROUP_HANDSHAKE)
-        strncpy(buffer, "GROUP_HANDSHAKE", max);
-    else if (val == SupplicantState::COMPLETED)
-        strncpy(buffer, "COMPLETED", max);
-    else if (val == SupplicantState::IDLE)
-        strncpy(buffer, "IDLE", max);
-    else
-        strncpy(buffer, "(internal error)", max);
-
-    return buffer;
-}
diff --git a/nexus/SupplicantState.h b/nexus/SupplicantState.h
deleted file mode 100644
index 6882f0c..0000000
--- a/nexus/SupplicantState.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SUPPLICANT_STATE_H
-#define _SUPPLICANT_STATE_H
-
-class SupplicantState {
-public:
-    static const int UNKNOWN           = -1;
-    static const int DISCONNECTED      = 0;
-    static const int INACTIVE          = 1;
-    static const int SCANNING          = 2;
-    static const int ASSOCIATING       = 3;
-    static const int ASSOCIATED        = 4;
-    static const int FOURWAY_HANDSHAKE = 5;
-    static const int GROUP_HANDSHAKE   = 6;
-    static const int COMPLETED         = 7;
-    static const int IDLE              = 8;
-
-    static char *toString(int val, char *buffer, int max);
-};
-
-#endif
diff --git a/nexus/SupplicantStateChangeEvent.cpp b/nexus/SupplicantStateChangeEvent.cpp
deleted file mode 100644
index cf0b9da..0000000
--- a/nexus/SupplicantStateChangeEvent.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-
-#define LOG_TAG "SupplicantStateChangeEvent"
-#include <cutils/log.h>
-
-#include "SupplicantStateChangeEvent.h"
-
-SupplicantStateChangeEvent::SupplicantStateChangeEvent(int level, char *event,
-                                                       size_t len) :
-                            SupplicantEvent(SupplicantEvent::EVENT_STATE_CHANGE,
-                                            level) {
-    // XXX: move this stuff into a static creation method
-    char *p = index(event, ' ');
-    if (!p) {
-        LOGW("Bad event '%s'\n", event);
-        return;
-    }
-
-    mState = atoi(p + strlen("state=") + 1);
-}
-
-SupplicantStateChangeEvent::SupplicantStateChangeEvent(int state) :
-                            SupplicantEvent(SupplicantEvent::EVENT_STATE_CHANGE, -1) {
-    mState = state;
-}
-
-SupplicantStateChangeEvent::~SupplicantStateChangeEvent() {
-}
-
diff --git a/nexus/SupplicantStateChangeEvent.h b/nexus/SupplicantStateChangeEvent.h
deleted file mode 100644
index 77bff65..0000000
--- a/nexus/SupplicantStateChangeEvent.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantStateChangeEvent_H
-#define _SupplicantStateChangeEvent_H
-
-#include "SupplicantEvent.h"
-
-class SupplicantStateChangeEvent : public SupplicantEvent {
-private:
-    int mState;
-
-public:
-    SupplicantStateChangeEvent(int level, char *event, size_t len);
-    SupplicantStateChangeEvent(int state);
-    virtual ~SupplicantStateChangeEvent();
-
-    int getState() { return mState; }
-};
-
-#endif
diff --git a/nexus/SupplicantStatus.cpp b/nexus/SupplicantStatus.cpp
deleted file mode 100644
index b3c560a..0000000
--- a/nexus/SupplicantStatus.cpp
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <string.h>
-
-#define LOG_TAG "SupplicantStatus"
-#include <cutils/log.h>
-
-#include "SupplicantStatus.h"
-#include "SupplicantState.h"
-
-SupplicantStatus::SupplicantStatus() {
-    mWpaState = SupplicantState::UNKNOWN;
-    mId = -1;
-    mBssid = NULL;
-    mSsid = NULL;
-}
-
-SupplicantStatus::SupplicantStatus(int state, int id, char *bssid, char *ssid) :
-                  mWpaState(state), mId(id), mBssid(bssid), mSsid(ssid) {
-
-LOGD("state %d, id %d, bssid %p, ssid %p\n", mWpaState, mId, mBssid, mSsid);
-}
-
-SupplicantStatus::~SupplicantStatus() {
-    if (mBssid)
-        free(mBssid);
-    if (mSsid)
-        free(mSsid);
-}
-
-SupplicantStatus *SupplicantStatus::createStatus(char *data, int len) {
-    char *bssid = NULL;
-    char *ssid = NULL;
-    int id = -1;
-    int state = SupplicantState::UNKNOWN;
-
-    char *next = data;
-    char *line;
-    while((line = strsep(&next, "\n"))) {
-        char *line_next =  line;
-        char *token = strsep(&line_next, "=");
-        char *value = strsep(&line_next, "=");
-        if (!strcmp(token, "bssid"))
-            bssid = strdup(value);
-        else if (!strcmp(token, "ssid"))
-            ssid = strdup(value);
-        else if (!strcmp(token, "id"))
-            id = atoi(value);
-        else if (!strcmp(token, "wpa_state")) {
-            if (!strcmp(value, "DISCONNECTED"))
-                state = SupplicantState::DISCONNECTED;
-            else if (!strcmp(value, "INACTIVE"))
-                state = SupplicantState::INACTIVE;
-            else if (!strcmp(value, "SCANNING"))
-                state = SupplicantState::SCANNING;
-            else if (!strcmp(value, "ASSOCIATING"))
-                state = SupplicantState::ASSOCIATING;
-            else if (!strcmp(value, "ASSOCIATED"))
-                state = SupplicantState::ASSOCIATED;
-            else if (!strcmp(value, "FOURWAY_HANDSHAKE"))
-                state = SupplicantState::FOURWAY_HANDSHAKE;
-            else if (!strcmp(value, "GROUP_HANDSHAKE"))
-                state = SupplicantState::GROUP_HANDSHAKE;
-            else if (!strcmp(value, "COMPLETED"))
-                state = SupplicantState::COMPLETED;
-            else if (!strcmp(value, "IDLE"))
-                state = SupplicantState::IDLE;
-            else 
-                LOGE("Unknown supplicant state '%s'", value);
-        } else
-            LOGD("Ignoring unsupported status token '%s'", token);
-    }
-
-    return new SupplicantStatus(state, id, bssid, ssid);
-    
-}
diff --git a/nexus/SupplicantStatus.h b/nexus/SupplicantStatus.h
deleted file mode 100644
index ef01841..0000000
--- a/nexus/SupplicantStatus.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _SupplicantStatus_H
-#define _SupplicantStatus_H
-
-class SupplicantStatus {
-private:
-    int mWpaState;
-    int mId;
-    char *mBssid;
-    char *mSsid;
-
-private:
-    SupplicantStatus();
-    SupplicantStatus(int state, int id, char *bssid, char *ssid);
-
-public:
-    virtual ~SupplicantStatus();
-    static SupplicantStatus *createStatus(char *data, int len);
-
-    int getWpaState() { return mWpaState; }
-    int getId() { return mId; }
-    const char *getBssid() { return mBssid; }
-    const char *getSsid() { return mSsid; }
-   
-};
-
-#endif
diff --git a/nexus/TiwlanEventListener.cpp b/nexus/TiwlanEventListener.cpp
deleted file mode 100644
index 15e6930..0000000
--- a/nexus/TiwlanEventListener.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <pthread.h>
-#include <sys/types.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#define LOG_TAG "TiwlanEventListener"
-#include <cutils/log.h>
-
-#include "TiwlanEventListener.h"
-
-TiwlanEventListener::TiwlanEventListener(int socket) :
-                     SocketListener(socket, false) {
-}
-
-bool TiwlanEventListener::onDataAvailable(SocketClient *cli) {
-    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)");
-        return true;
-    }
-
-    if (recv(cli->getSocket(), data, sizeof(struct ipc_ev_data), 0) < 0) {
-       LOGE("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);
-    } else if (data->event_type == IPC_EVENT_LOW_SNR) {
-        LOGW("Low signal/noise ratio");
-    } else if (data->event_type == IPC_EVENT_LOW_RSSI) {
-        LOGW("Low RSSI");
-    } else {
-//        LOGD("Dropping unhandled driver event %d", data->event_type);
-    }
-
-    // TODO: Tell WifiController about the event
-out:
-    free(data);
-    return true;
-}
diff --git a/nexus/TiwlanEventListener.h b/nexus/TiwlanEventListener.h
deleted file mode 100644
index 052d6b1..0000000
--- a/nexus/TiwlanEventListener.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _TIWLAN_EVENT_LISTENER_H__
-#define _TIWLAN_EVENT_LISTENER_H__
-
-#include <sysutils/SocketListener.h>
-
-struct wpa_ctrl;
-class SocketClient;
-class ITiwlanEventHandler;
-class TiwlanEventFactory;
-
-class TiwlanEventListener: public SocketListener {
-    
-public:
-    TiwlanEventListener(int sock);
-    virtual ~TiwlanEventListener() {}
-
-protected:
-    virtual bool onDataAvailable(SocketClient *c);
-};
-
-// TODO: Move all this crap into a factory
-#define TI_DRIVER_MSG_PORT 9001
-
-#define IPC_EVENT_LINK_SPEED  2
-#define IPC_EVENT_LOW_SNR     13
-#define IPC_EVENT_LOW_RSSI    14
-
-struct ipc_ev_data {
-    uint32_t event_type;
-    void     *event_id;
-    uint32_t process_id;
-    uint32_t delivery_type;
-    uint32_t user_param;
-    void     *event_callback;
-    uint32_t bufferSize;
-    uint8_t  buffer[2048];
-};
-
-#endif
diff --git a/nexus/TiwlanWifiController.cpp b/nexus/TiwlanWifiController.cpp
deleted file mode 100644
index 016c790..0000000
--- a/nexus/TiwlanWifiController.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <arpa/inet.h>
-
-#include <cutils/properties.h>
-#define LOG_TAG "TiwlanWifiController"
-#include <cutils/log.h>
-
-#include "PropertyManager.h"
-#include "TiwlanWifiController.h"
-#include "TiwlanEventListener.h"
-
-#define DRIVER_PROP_NAME "wlan.driver.status"
-
-extern "C" int sched_yield(void);
-
-TiwlanWifiController::TiwlanWifiController(PropertyManager *propmngr,
-                                           IControllerHandler *handlers,
-                                           char *modpath, char *modname,
-                                           char *modargs) :
-                      WifiController(propmngr, handlers, modpath, modname,
-                                     modargs) {
-    mEventListener = NULL;
-    mListenerSock = -1;
-}
-
-int TiwlanWifiController::powerUp() {
-    return 0; // Powerup is currently done when the driver is loaded
-}
-
-int TiwlanWifiController::powerDown() {
-    if (mEventListener) {
-        delete mEventListener;
-        shutdown(mListenerSock, SHUT_RDWR);
-        close(mListenerSock);
-        mListenerSock = -1;
-        mEventListener = NULL;
-    }
-   
-    return 0; // Powerdown is currently done when the driver is unloaded
-}
-
-bool TiwlanWifiController::isPoweredUp() {
-    return isKernelModuleLoaded(getModuleName());
-}
-
-int TiwlanWifiController::loadFirmware() {
-    char driver_status[PROPERTY_VALUE_MAX];
-    int count = 100;
-
-    property_set("ctl.start", "wlan_loader");
-    sched_yield();
-
-    // Wait for driver to be ready
-    while (count-- > 0) {
-        if (property_get(DRIVER_PROP_NAME, driver_status, NULL)) {
-            if (!strcmp(driver_status, "ok")) {
-                LOGD("Firmware loaded OK");
-
-                if (startDriverEventListener()) {
-                    LOGW("Failed to start driver event listener (%s)",
-                         strerror(errno));
-                }
-
-                return 0;
-            } else if (!strcmp(DRIVER_PROP_NAME, "failed")) {
-                LOGE("Firmware load failed");
-                return -1;
-            }
-        }
-        usleep(200000);
-    }
-    property_set(DRIVER_PROP_NAME, "timeout");
-    LOGE("Firmware load timed out");
-    return -1;
-}
-
-int TiwlanWifiController::startDriverEventListener() {
-    struct sockaddr_in addr;
-
-    if (mListenerSock != -1) {
-        LOGE("Listener already started!");
-        errno = EBUSY;
-        return -1;
-    }
-
-    if ((mListenerSock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
-        LOGE("socket failed (%s)", strerror(errno));
-        return -1;
-    }
-
-    memset(&addr, 0, sizeof(addr));
-    addr.sin_family = AF_INET;
-    addr.sin_addr.s_addr = htonl(INADDR_ANY);
-    addr.sin_port = htons(TI_DRIVER_MSG_PORT);
-
-    if (bind(mListenerSock,
-             (struct sockaddr *) &addr,
-             sizeof(addr)) < 0) {
-        LOGE("bind failed (%s)", strerror(errno));
-        goto out_err;
-    }
-
-    mEventListener = new TiwlanEventListener(mListenerSock);
-
-    if (mEventListener->startListener()) {
-        LOGE("Error starting driver listener (%s)", strerror(errno));
-        goto out_err;
-    }
-    return 0;
-out_err:
-    if (mEventListener) {
-        delete mEventListener;
-        mEventListener = NULL;
-    }
-    if (mListenerSock != -1) {
-        shutdown(mListenerSock, SHUT_RDWR);
-        close(mListenerSock);
-        mListenerSock = -1;
-    }
-    return -1;
-}
-
-bool TiwlanWifiController::isFirmwareLoaded() {
-    // Always load the firmware
-    return false;
-}
diff --git a/nexus/TiwlanWifiController.h b/nexus/TiwlanWifiController.h
deleted file mode 100644
index 583be71..0000000
--- a/nexus/TiwlanWifiController.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _TIWLAN_WIFI_CONTROLLER_H
-#define _TIWLAN_WIFI_CONTROLLER_H
-
-#include "PropertyManager.h"
-#include "WifiController.h"
-
-class IControllerHandler;
-class TiwlanEventListener;
-
-class TiwlanWifiController : public WifiController {
-    int                 mListenerSock;
-    TiwlanEventListener *mEventListener;
-
-public:
-    TiwlanWifiController(PropertyManager *propmngr, IControllerHandler *handlers, char *modpath, char *modname, char *modargs);
-    virtual ~TiwlanWifiController() {}
-
-    virtual int powerUp();
-    virtual int powerDown();
-    virtual bool isPoweredUp();
-    virtual int loadFirmware();
-    virtual bool isFirmwareLoaded();
-
-private:
-    int startDriverEventListener();
-};
-#endif
diff --git a/nexus/VpnController.cpp b/nexus/VpnController.cpp
deleted file mode 100644
index 015710f..0000000
--- a/nexus/VpnController.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-#include "PropertyManager.h"
-#include "VpnController.h"
-
-VpnController::VpnController(PropertyManager *propmngr,
-                             IControllerHandler *handlers) :
-               Controller("vpn", propmngr, handlers) {
-    mEnabled = false;
-
-    mStaticProperties.propEnabled = new VpnEnabledProperty(this);
-    mDynamicProperties.propGateway = new IPV4AddressPropertyHelper("Gateway",
-                                                                   false,
-                                                                   &mGateway);
-}
-
-int VpnController::start() {
-    mPropMngr->attachProperty("vpn", mStaticProperties.propEnabled);
-    return 0;
-}
-
-int VpnController::stop() {
-    mPropMngr->detachProperty("vpn", mStaticProperties.propEnabled);
-    return 0;
-}
-
-VpnController::VpnIntegerProperty::VpnIntegerProperty(VpnController *c,
-                                                      const char *name,
-                                                      bool ro,
-                                                      int elements) :
-                IntegerProperty(name, ro, elements) {
-    mVc = c;
-}
-
-VpnController::VpnStringProperty::VpnStringProperty(VpnController *c,
-                                                    const char *name,
-                                                    bool ro, int elements) :
-                StringProperty(name, ro, elements) {
-    mVc = c;
-}
-
-VpnController::VpnIPV4AddressProperty::VpnIPV4AddressProperty(VpnController *c,
-                                                              const char *name,
-                                                              bool ro, int elements) :
-                IPV4AddressProperty(name, ro, elements) {
-    mVc = c;
-}
-
-VpnController::VpnEnabledProperty::VpnEnabledProperty(VpnController *c) :
-                VpnIntegerProperty(c, "Enabled", false, 1) {
-}
-int VpnController::VpnEnabledProperty::get(int idx, int *buffer) {
-    *buffer = mVc->mEnabled;
-    return 0;
-}
-int VpnController::VpnEnabledProperty::set(int idx, int value) {
-    int rc;
-    if (!value) {
-        mVc->mPropMngr->detachProperty("vpn", mVc->mDynamicProperties.propGateway);
-        rc = mVc->disable();
-    } else {
-        rc = mVc->enable();
-        if (!rc) {
-            mVc->mPropMngr->attachProperty("vpn", mVc->mDynamicProperties.propGateway);
-        }
-    }
-    if (!rc)
-        mVc->mEnabled = value;
-    return rc;
-}
diff --git a/nexus/VpnController.h b/nexus/VpnController.h
deleted file mode 100644
index 4bd86b5..0000000
--- a/nexus/VpnController.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _VPN_CONTROLLER_H
-#define _VPN_CONTROLLER_H
-
-#include <netinet/in.h>
-
-#include "Controller.h"
-
-class IControllerHandler;
-
-class VpnController : public Controller {
-    class VpnIntegerProperty : public IntegerProperty {
-    protected:
-        VpnController *mVc;
-    public:
-        VpnIntegerProperty(VpnController *c, const char *name, bool ro,
-                            int elements);
-        virtual ~VpnIntegerProperty() {}
-        virtual int set(int idx, int value) = 0;
-        virtual int get(int idx, int *buffer) = 0;
-    };
-    friend class VpnController::VpnIntegerProperty;
-
-    class VpnStringProperty : public StringProperty {
-    protected:
-        VpnController *mVc;
-    public:
-        VpnStringProperty(VpnController *c, const char *name, bool ro,
-                            int elements);
-        virtual ~VpnStringProperty() {}
-        virtual int set(int idx, const char *value) = 0;
-        virtual int get(int idx, char *buffer, size_t max) = 0;
-    };
-    friend class VpnController::VpnStringProperty;
-
-    class VpnIPV4AddressProperty : public IPV4AddressProperty {
-    protected:
-        VpnController *mVc;
-    public:
-        VpnIPV4AddressProperty(VpnController *c, const char *name, bool ro,
-                          int elements);
-        virtual ~VpnIPV4AddressProperty() {}
-        virtual int set(int idx, struct in_addr *value) = 0;
-        virtual int get(int idx, struct in_addr *buffer) = 0;
-    };
-    friend class VpnController::VpnIPV4AddressProperty;
-
-    class VpnEnabledProperty : public VpnIntegerProperty {
-    public:
-        VpnEnabledProperty(VpnController *c);
-        virtual ~VpnEnabledProperty() {};
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    bool           mEnabled;
-    /*
-     * Gateway of the VPN server to connect to
-     */
-    struct in_addr mGateway;
-
-    struct {
-        VpnEnabledProperty *propEnabled;
-    } mStaticProperties;
-
-    struct {
-        IPV4AddressPropertyHelper *propGateway;
-    } mDynamicProperties;
-
-public:
-    VpnController(PropertyManager *propmngr, IControllerHandler *handlers);
-    virtual ~VpnController() {}
-
-    virtual int start();
-    virtual int stop();
-
-protected:
-    virtual int enable() = 0;
-    virtual int disable() = 0;
-};
-
-#endif
diff --git a/nexus/WifiController.cpp b/nexus/WifiController.cpp
deleted file mode 100644
index c218c30..0000000
--- a/nexus/WifiController.cpp
+++ /dev/null
@@ -1,819 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-
-#define LOG_TAG "WifiController"
-#include <cutils/log.h>
-
-#include "Supplicant.h"
-#include "WifiController.h"
-#include "NetworkManager.h"
-#include "ResponseCode.h"
-#include "WifiNetwork.h"
-#include "ISupplicantEventHandler.h"
-#include "SupplicantState.h"
-#include "SupplicantStatus.h"
-#include "SupplicantAssociatingEvent.h"
-#include "SupplicantAssociatedEvent.h"
-#include "SupplicantConnectedEvent.h"
-#include "SupplicantScanResultsEvent.h"
-#include "SupplicantStateChangeEvent.h"
-#include "SupplicantConnectionTimeoutEvent.h"
-#include "SupplicantDisconnectedEvent.h"
-#include "WifiStatusPoller.h"
-
-WifiController::WifiController(PropertyManager *mPropMngr,
-                               IControllerHandler *handlers,
-                               char *modpath, char *modname, char *modargs) :
-                Controller("wifi", mPropMngr, handlers) {
-    strncpy(mModulePath, modpath, sizeof(mModulePath));
-    strncpy(mModuleName, modname, sizeof(mModuleName));
-    strncpy(mModuleArgs, modargs, sizeof(mModuleArgs));
-
-    mLatestScanResults = new ScanResultCollection();
-    pthread_mutex_init(&mLatestScanResultsLock, NULL);
-
-    pthread_mutex_init(&mLock, NULL);
-
-    mSupplicant = new Supplicant(this, this);
-    mActiveScan = false;
-    mEnabled = false;
-    mScanOnly = false;
-    mPacketFilter = false;
-    mBluetoothCoexScan = false;
-    mBluetoothCoexMode = 0;
-    mCurrentlyConnectedNetworkId = -1;
-    mStatusPoller = new WifiStatusPoller(this);
-    mRssiEventThreshold = 5;
-    mLastLinkSpeed = 0;
-
-    mSupplicantState = SupplicantState::UNKNOWN;
-
-    mStaticProperties.propEnabled = new WifiEnabledProperty(this);
-    mStaticProperties.propScanOnly = new WifiScanOnlyProperty(this);
-    mStaticProperties.propAllowedChannels = new WifiAllowedChannelsProperty(this);
-
-    mStaticProperties.propRssiEventThreshold =
-            new IntegerPropertyHelper("RssiEventThreshold", false, &mRssiEventThreshold);
-
-    mDynamicProperties.propSupplicantState = new WifiSupplicantStateProperty(this);
-    mDynamicProperties.propActiveScan = new WifiActiveScanProperty(this);
-    mDynamicProperties.propInterface = new WifiInterfaceProperty(this);
-    mDynamicProperties.propSearching = new WifiSearchingProperty(this);
-    mDynamicProperties.propPacketFilter = new WifiPacketFilterProperty(this);
-    mDynamicProperties.propBluetoothCoexScan = new WifiBluetoothCoexScanProperty(this);
-    mDynamicProperties.propBluetoothCoexMode = new WifiBluetoothCoexModeProperty(this);
-    mDynamicProperties.propCurrentNetwork = new WifiCurrentNetworkProperty(this);
-
-    mDynamicProperties.propRssi = new IntegerPropertyHelper("Rssi", true, &mLastRssi);
-    mDynamicProperties.propLinkSpeed = new IntegerPropertyHelper("LinkSpeed", true, &mLastLinkSpeed);
-
-    mDynamicProperties.propSuspended = new WifiSuspendedProperty(this);
-    mDynamicProperties.propNetCount = new WifiNetCountProperty(this);
-    mDynamicProperties.propTriggerScan = new WifiTriggerScanProperty(this);
-}
-
-int WifiController::start() {
-    mPropMngr->attachProperty("wifi", mStaticProperties.propEnabled);
-    mPropMngr->attachProperty("wifi", mStaticProperties.propScanOnly);
-    mPropMngr->attachProperty("wifi", mStaticProperties.propAllowedChannels);
-    mPropMngr->attachProperty("wifi", mStaticProperties.propRssiEventThreshold);
-    return 0;
-}
-
-int WifiController::stop() {
-    mPropMngr->detachProperty("wifi", mStaticProperties.propEnabled);
-    mPropMngr->detachProperty("wifi", mStaticProperties.propScanOnly);
-    mPropMngr->detachProperty("wifi", mStaticProperties.propAllowedChannels);
-    mPropMngr->detachProperty("wifi", mStaticProperties.propRssiEventThreshold);
-    return 0;
-}
-
-int WifiController::enable() {
-
-    if (!isPoweredUp()) {
-        LOGI("Powering up");
-        sendStatusBroadcast("Powering up WiFi hardware");
-        if (powerUp()) {
-            LOGE("Powerup failed (%s)", strerror(errno));
-            return -1;
-        }
-    }
-
-    if (mModuleName[0] != '\0' && !isKernelModuleLoaded(mModuleName)) {
-        LOGI("Loading driver");
-        sendStatusBroadcast("Loading WiFi driver");
-        if (loadKernelModule(mModulePath, mModuleArgs)) {
-            LOGE("Kernel module load failed (%s)", strerror(errno));
-            goto out_powerdown;
-        }
-    }
-
-    if (!isFirmwareLoaded()) {
-        LOGI("Loading firmware");
-        sendStatusBroadcast("Loading WiFI firmware");
-        if (loadFirmware()) {
-            LOGE("Firmware load failed (%s)", strerror(errno));
-            goto out_powerdown;
-        }
-    }
-
-    if (!mSupplicant->isStarted()) {
-        LOGI("Starting WPA Supplicant");
-        sendStatusBroadcast("Starting WPA Supplicant");
-        if (mSupplicant->start()) {
-            LOGE("Supplicant start failed (%s)", strerror(errno));
-            goto out_unloadmodule;
-        }
-    }
-
-    if (Controller::bindInterface(mSupplicant->getInterfaceName())) {
-        LOGE("Error binding interface (%s)", strerror(errno));
-        goto out_unloadmodule;
-    }
-
-    if (mSupplicant->refreshNetworkList())
-        LOGW("Error getting list of networks (%s)", strerror(errno));
-
-    LOGW("TODO: Set # of allowed regulatory channels!");
-
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propSupplicantState);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propActiveScan);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propInterface);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propSearching);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propPacketFilter);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propBluetoothCoexScan);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propBluetoothCoexMode);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propCurrentNetwork);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propRssi);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propLinkSpeed);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propSuspended);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propNetCount);
-    mPropMngr->attachProperty("wifi", mDynamicProperties.propTriggerScan);
-
-    LOGI("Enabled successfully");
-    return 0;
-
-out_unloadmodule:
-    if (mModuleName[0] != '\0' && !isKernelModuleLoaded(mModuleName)) {
-        if (unloadKernelModule(mModuleName)) {
-            LOGE("Unable to unload module after failure!");
-        }
-    }
-
-out_powerdown:
-    if (powerDown()) {
-        LOGE("Unable to powerdown after failure!");
-    }
-    return -1;
-}
-
-bool WifiController::getSuspended() {
-    pthread_mutex_lock(&mLock);
-    bool r = mSuspended;
-    pthread_mutex_unlock(&mLock);
-    return r;
-}
-
-int WifiController::setSuspend(bool suspend) {
-
-    pthread_mutex_lock(&mLock);
-    if (suspend == mSuspended) {
-        LOGW("Suspended state already = %d", suspend);
-        pthread_mutex_unlock(&mLock);
-        return 0;
-    }
-
-    if (suspend) {
-        mHandlers->onControllerSuspending(this);
-
-        char tmp[80];
-        LOGD("Suspending from supplicant state %s",
-             SupplicantState::toString(mSupplicantState,
-                                       tmp,
-                                       sizeof(tmp)));
-
-        if (mSupplicantState != SupplicantState::IDLE) {
-            LOGD("Forcing Supplicant disconnect");
-            if (mSupplicant->disconnect()) {
-                LOGW("Error disconnecting (%s)", strerror(errno));
-            }
-        }
-
-        LOGD("Stopping Supplicant driver");
-        if (mSupplicant->stopDriver()) {
-            LOGE("Error stopping driver (%s)", strerror(errno));
-            pthread_mutex_unlock(&mLock);
-            return -1;
-        }
-    } else {
-        LOGD("Resuming");
-
-        if (mSupplicant->startDriver()) {
-            LOGE("Error resuming driver (%s)", strerror(errno));
-            pthread_mutex_unlock(&mLock);
-            return -1;
-        }
-        // XXX: set regulatory max channels 
-        if (mScanOnly)
-            mSupplicant->triggerScan();
-        else
-            mSupplicant->reconnect();
-
-        mHandlers->onControllerResumed(this);
-    }
-
-    mSuspended = suspend;
-    pthread_mutex_unlock(&mLock);
-    LOGD("Suspend / Resume completed");
-    return 0;
-}
-
-void WifiController::sendStatusBroadcast(const char *msg) {
-    NetworkManager::Instance()->
-                    getBroadcaster()->
-                    sendBroadcast(ResponseCode::UnsolicitedInformational, msg, false);
-}
-
-int WifiController::disable() {
-
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propSupplicantState);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propActiveScan);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propInterface);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propSearching);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propPacketFilter);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propBluetoothCoexScan);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propBluetoothCoexMode);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propCurrentNetwork);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propRssi);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propLinkSpeed);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propSuspended);
-    mPropMngr->detachProperty("wifi", mDynamicProperties.propNetCount);
-
-    if (mSupplicant->isStarted()) {
-        sendStatusBroadcast("Stopping WPA Supplicant");
-        if (mSupplicant->stop()) {
-            LOGE("Supplicant stop failed (%s)", strerror(errno));
-            return -1;
-        }
-    } else
-        LOGW("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));
-            return -1;
-        }
-    }
-
-    if (isPoweredUp()) {
-        sendStatusBroadcast("Powering down WiFi hardware");
-        if (powerDown()) {
-            LOGE("Powerdown failed (%s)", strerror(errno));
-            return -1;
-        }
-    }
-    return 0;
-}
-
-int WifiController::loadFirmware() {
-    return 0;
-}
-
-int WifiController::triggerScan() {
-    pthread_mutex_lock(&mLock);
-    if (verifyNotSuspended()) {
-        pthread_mutex_unlock(&mLock);
-        return -1;
-    }
-
-    switch (mSupplicantState) {
-        case SupplicantState::DISCONNECTED:
-        case SupplicantState::INACTIVE:
-        case SupplicantState::SCANNING:
-        case SupplicantState::IDLE:
-            break;
-        default:
-            // Switch to scan only mode
-            mSupplicant->setApScanMode(2);
-            break;
-    }
-
-    int rc = mSupplicant->triggerScan();
-    pthread_mutex_unlock(&mLock);
-    return rc;
-}
-
-int WifiController::setActiveScan(bool active) {
-    pthread_mutex_lock(&mLock);
-    if (mActiveScan == active) {
-        pthread_mutex_unlock(&mLock);
-        return 0;
-    }
-    mActiveScan = active;
-
-    int rc = mSupplicant->setScanMode(active);
-    pthread_mutex_unlock(&mLock);
-    return rc;
-}
-
-WifiNetwork *WifiController::createNetwork() {
-    pthread_mutex_lock(&mLock);
-    WifiNetwork *wn = mSupplicant->createNetwork();
-    pthread_mutex_unlock(&mLock);
-    return wn;
-}
-
-int WifiController::removeNetwork(int networkId) {
-    pthread_mutex_lock(&mLock);
-    WifiNetwork *wn = mSupplicant->lookupNetwork(networkId);
-
-    if (!wn) {
-        pthread_mutex_unlock(&mLock);
-        return -1;
-    }
-    int rc = mSupplicant->removeNetwork(wn);
-    pthread_mutex_unlock(&mLock);
-    return rc;
-}
-
-ScanResultCollection *WifiController::createScanResults() {
-    ScanResultCollection *d = new ScanResultCollection();
-    ScanResultCollection::iterator i;
-
-    pthread_mutex_lock(&mLatestScanResultsLock);
-    for (i = mLatestScanResults->begin(); i != mLatestScanResults->end(); ++i)
-        d->push_back((*i)->clone());
-
-    pthread_mutex_unlock(&mLatestScanResultsLock);
-    return d;
-}
-
-WifiNetworkCollection *WifiController::createNetworkList() {
-    return mSupplicant->createNetworkList();
-}
-
-int WifiController::setPacketFilter(bool enable) {
-    int rc;
-
-    pthread_mutex_lock(&mLock);
-    if (enable)
-        rc = mSupplicant->enablePacketFilter();
-    else
-        rc = mSupplicant->disablePacketFilter();
-
-    if (!rc)
-        mPacketFilter = enable;
-    pthread_mutex_unlock(&mLock);
-    return rc;
-}
-
-int WifiController::setBluetoothCoexistenceScan(bool enable) {
-    int rc;
-
-    pthread_mutex_lock(&mLock);
-
-    if (enable)
-        rc = mSupplicant->enableBluetoothCoexistenceScan();
-    else
-        rc = mSupplicant->disableBluetoothCoexistenceScan();
-
-    if (!rc)
-        mBluetoothCoexScan = enable;
-    pthread_mutex_unlock(&mLock);
-    return rc;
-}
-
-int WifiController::setScanOnly(bool scanOnly) {
-    pthread_mutex_lock(&mLock);
-    int rc = mSupplicant->setApScanMode((scanOnly ? 2 : 1));
-    if (!rc)
-        mScanOnly = scanOnly;
-    if (!mSuspended) {
-        if (scanOnly)
-            mSupplicant->disconnect();
-        else
-            mSupplicant->reconnect();
-    }
-    pthread_mutex_unlock(&mLock);
-    return rc;
-}
-
-int WifiController::setBluetoothCoexistenceMode(int mode) {
-    pthread_mutex_lock(&mLock);
-    int rc = mSupplicant->setBluetoothCoexistenceMode(mode);
-    if (!rc)
-        mBluetoothCoexMode = mode;
-    pthread_mutex_unlock(&mLock);
-    return rc;
-}
-
-void WifiController::onAssociatingEvent(SupplicantAssociatingEvent *evt) {
-    LOGD("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());
-}
-
-void WifiController::onConnectedEvent(SupplicantConnectedEvent *evt) {
-    LOGD("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!",
-             SupplicantState::toString(ss->getWpaState(), tmp,
-             sizeof(tmp)));
-        return;
-    }
-
-    if (ss->getId() == -1) {
-        LOGW("onConnected() with id = -1!");
-        return;
-    }
-    
-    mCurrentlyConnectedNetworkId = ss->getId();
-    if (!(wn = mSupplicant->lookupNetwork(ss->getId()))) {
-        LOGW("Error looking up connected network id %d (%s)",
-             ss->getId(), strerror(errno));
-        return;
-    }
-  
-    delete ss;
-    mHandlers->onInterfaceConnected(this);
-}
-
-void WifiController::onScanResultsEvent(SupplicantScanResultsEvent *evt) {
-    char *reply;
-
-    if (!(reply = (char *) malloc(4096))) {
-        LOGE("Out of memory");
-        return;
-    }
-
-    mNumScanResultsSinceLastStateChange++;
-    if (mNumScanResultsSinceLastStateChange >= 3)
-        mIsSupplicantSearching = false;
-
-    size_t len = 4096;
-
-    if (mSupplicant->sendCommand("SCAN_RESULTS", reply, &len)) {
-        LOGW("onScanResultsEvent: Error getting scan results (%s)",
-             strerror(errno));
-        free(reply);
-        return;
-    }
-
-    pthread_mutex_lock(&mLatestScanResultsLock);
-    if (!mLatestScanResults->empty()) {
-        ScanResultCollection::iterator i;
-
-        for (i = mLatestScanResults->begin();
-             i !=mLatestScanResults->end(); ++i) {
-            delete *i;
-        }
-        mLatestScanResults->clear();
-    }
-
-    char *linep;
-    char *linep_next = NULL;
-
-    if (!strtok_r(reply, "\n", &linep_next)) {
-        free(reply);
-        pthread_mutex_unlock(&mLatestScanResultsLock);
-        return;
-    }
-
-    while((linep = strtok_r(NULL, "\n", &linep_next)))
-        mLatestScanResults->push_back(new ScanResult(linep));
-
-    // Switch handling of scan results back to normal mode
-    mSupplicant->setApScanMode(1);
-
-    char *tmp;
-    asprintf(&tmp, "Scan results ready (%d)", mLatestScanResults->size());
-    NetworkManager::Instance()->getBroadcaster()->
-                                sendBroadcast(ResponseCode::ScanResultsReady,
-                                              tmp, false);
-    free(tmp);
-    pthread_mutex_unlock(&mLatestScanResultsLock);
-    free(reply);
-}
-
-void WifiController::onStateChangeEvent(SupplicantStateChangeEvent *evt) {
-    char tmp[32];
-    char tmp2[32];
-    
-    if (evt->getState() == mSupplicantState)
-        return;
-
-    LOGD("onStateChangeEvent(%s -> %s)", 
-         SupplicantState::toString(mSupplicantState, tmp, sizeof(tmp)),
-         SupplicantState::toString(evt->getState(), tmp2, sizeof(tmp2)));
-
-    if (evt->getState() != SupplicantState::SCANNING) {
-        mIsSupplicantSearching = true;
-        mNumScanResultsSinceLastStateChange = 0;
-    }
-
-    char *tmp3;
-    asprintf(&tmp3,
-             "Supplicant state changed from %d (%s) -> %d (%s)",
-             mSupplicantState, tmp, evt->getState(), tmp2);
-
-    mSupplicantState = evt->getState();
-
-    if (mSupplicantState == SupplicantState::COMPLETED) {
-        mStatusPoller->start();
-    } else if (mStatusPoller->isStarted()) {
-        mStatusPoller->stop();
-    }
-
-    NetworkManager::Instance()->getBroadcaster()->
-                                sendBroadcast(ResponseCode::SupplicantStateChange,
-                                              tmp3, false);
-    free(tmp3);
-}
-
-void WifiController::onConnectionTimeoutEvent(SupplicantConnectionTimeoutEvent *evt) {
-    LOGD("onConnectionTimeoutEvent(%s)", evt->getBssid());
-}
-
-void WifiController::onDisconnectedEvent(SupplicantDisconnectedEvent *evt) {
-    mCurrentlyConnectedNetworkId = -1;
-    mHandlers->onInterfaceDisconnected(this);
-}
-
-#if 0
-void WifiController::onTerminatingEvent(SupplicantEvent *evt) {
-    LOGD("onTerminatingEvent(%s)", evt->getEvent());
-}
-
-void WifiController::onPasswordChangedEvent(SupplicantEvent *evt) {
-    LOGD("onPasswordChangedEvent(%s)", evt->getEvent());
-}
-
-void WifiController::onEapNotificationEvent(SupplicantEvent *evt) {
-    LOGD("onEapNotificationEvent(%s)", evt->getEvent());
-}
-
-void WifiController::onEapStartedEvent(SupplicantEvent *evt) {
-    LOGD("onEapStartedEvent(%s)", evt->getEvent());
-}
-
-void WifiController::onEapMethodEvent(SupplicantEvent *evt) {
-    LOGD("onEapMethodEvent(%s)", evt->getEvent());
-}
-
-void WifiController::onEapSuccessEvent(SupplicantEvent *evt) {
-    LOGD("onEapSuccessEvent(%s)", evt->getEvent());
-}
-
-void WifiController::onEapFailureEvent(SupplicantEvent *evt) {
-    LOGD("onEapFailureEvent(%s)", evt->getEvent());
-}
-
-void WifiController::onLinkSpeedEvent(SupplicantEvent *evt) {
-    LOGD("onLinkSpeedEvent(%s)", evt->getEvent());
-}
-
-void WifiController::onDriverStateEvent(SupplicantEvent *evt) {
-    LOGD("onDriverStateEvent(%s)", evt->getEvent());
-}
-#endif
-
-void WifiController::onStatusPollInterval() {
-    pthread_mutex_lock(&mLock);
-    int rssi;
-    if (mSupplicant->getRssi(&rssi)) {
-        LOGE("Failed to get rssi (%s)", strerror(errno));
-        pthread_mutex_unlock(&mLock);
-        return;
-    }
-
-    if (abs(mLastRssi - rssi) > mRssiEventThreshold) {
-        char *tmp3;
-        asprintf(&tmp3, "RSSI changed from %d -> %d",
-                 mLastRssi, rssi);
-        mLastRssi = rssi;
-        NetworkManager::Instance()->getBroadcaster()->
-                               sendBroadcast(ResponseCode::RssiChange,
-                                             tmp3, false);
-        free(tmp3);
-    }
-
-    int linkspeed = mSupplicant->getLinkSpeed();
-    if (linkspeed != mLastLinkSpeed) {
-        char *tmp3;
-        asprintf(&tmp3, "Link speed changed from %d -> %d",
-                 mLastLinkSpeed, linkspeed);
-        mLastLinkSpeed = linkspeed;
-        NetworkManager::Instance()->getBroadcaster()->
-                               sendBroadcast(ResponseCode::LinkSpeedChange,
-                                             tmp3, false);
-        free(tmp3);
-        
-    }
-    pthread_mutex_unlock(&mLock);
-}
-
-int WifiController::verifyNotSuspended() {
-    if (mSuspended) {
-        errno = ESHUTDOWN;
-        return -1;
-    }
-    return 0;
-}
-
-/*
- * Property inner classes
- */
-
-WifiController::WifiIntegerProperty::WifiIntegerProperty(WifiController *c, 
-                                                         const char *name,
-                                                         bool ro,
-                                                         int elements) :
-                IntegerProperty(name, ro, elements) {
-    mWc = c;
-}
-
-WifiController::WifiStringProperty::WifiStringProperty(WifiController *c, 
-                                                       const char *name,
-                                                       bool ro, int elements) :
-                StringProperty(name, ro, elements) {
-    mWc = c;
-}
-
-WifiController::WifiEnabledProperty::WifiEnabledProperty(WifiController *c) :
-                WifiIntegerProperty(c, "Enabled", false, 1) {
-}
-
-int WifiController::WifiEnabledProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mEnabled;
-    return 0;
-}
-int WifiController::WifiEnabledProperty::set(int idx, int value) {
-    int rc = (value ? mWc->enable() : mWc->disable());
-    if (!rc)
-        mWc->mEnabled = value;
-    return rc;
-}
-
-WifiController::WifiScanOnlyProperty::WifiScanOnlyProperty(WifiController *c) :
-                WifiIntegerProperty(c, "ScanOnly", false, 1) {
-}
-int WifiController::WifiScanOnlyProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mScanOnly;
-    return 0;
-}
-int WifiController::WifiScanOnlyProperty::set(int idx, int value) {
-    return mWc->setScanOnly(value == 1);
-}
-
-WifiController::WifiAllowedChannelsProperty::WifiAllowedChannelsProperty(WifiController *c) :
-                WifiIntegerProperty(c, "AllowedChannels", false, 1) {
-}
-int WifiController::WifiAllowedChannelsProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mNumAllowedChannels;
-    return 0;
-}
-int WifiController::WifiAllowedChannelsProperty::set(int idx, int value) {
-    // XXX: IMPL
-    errno = ENOSYS;
-    return -1;
-}
-
-WifiController::WifiSupplicantStateProperty::WifiSupplicantStateProperty(WifiController *c) :
-                WifiStringProperty(c, "SupplicantState", true, 1) {
-}
-int WifiController::WifiSupplicantStateProperty::get(int idx, char *buffer, size_t max) {
-    if (!SupplicantState::toString(mWc->mSupplicantState, buffer, max))
-        return -1;
-    return 0;
-}
-
-WifiController::WifiActiveScanProperty::WifiActiveScanProperty(WifiController *c) :
-                WifiIntegerProperty(c, "ActiveScan", false, 1) {
-}
-int WifiController::WifiActiveScanProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mActiveScan;
-    return 0;
-}
-int WifiController::WifiActiveScanProperty::set(int idx, int value) {
-    return mWc->setActiveScan(value);
-}
-
-WifiController::WifiInterfaceProperty::WifiInterfaceProperty(WifiController *c) :
-                WifiStringProperty(c, "Interface", true, 1) {
-}
-int WifiController::WifiInterfaceProperty::get(int idx, char *buffer, size_t max) {
-    strncpy(buffer, (mWc->getBoundInterface() ? mWc->getBoundInterface() : "none"), max);
-    return 0;
-}
-
-WifiController::WifiSearchingProperty::WifiSearchingProperty(WifiController *c) :
-                WifiIntegerProperty(c, "Searching", true, 1) {
-}
-int WifiController::WifiSearchingProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mIsSupplicantSearching;
-    return 0;
-}
-
-WifiController::WifiPacketFilterProperty::WifiPacketFilterProperty(WifiController *c) :
-                WifiIntegerProperty(c, "PacketFilter", false, 1) {
-}
-int WifiController::WifiPacketFilterProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mPacketFilter;
-    return 0;
-}
-int WifiController::WifiPacketFilterProperty::set(int idx, int value) {
-    return mWc->setPacketFilter(value);
-}
-
-WifiController::WifiBluetoothCoexScanProperty::WifiBluetoothCoexScanProperty(WifiController *c) :
-                WifiIntegerProperty(c, "BluetoothCoexScan", false, 1) {
-}
-int WifiController::WifiBluetoothCoexScanProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mBluetoothCoexScan;
-    return 0;
-}
-int WifiController::WifiBluetoothCoexScanProperty::set(int idx, int value) {
-    return mWc->setBluetoothCoexistenceScan(value == 1);
-}
-
-WifiController::WifiBluetoothCoexModeProperty::WifiBluetoothCoexModeProperty(WifiController *c) :
-                WifiIntegerProperty(c, "BluetoothCoexMode", false, 1) {
-}
-int WifiController::WifiBluetoothCoexModeProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mBluetoothCoexMode;
-    return 0;
-}
-int WifiController::WifiBluetoothCoexModeProperty::set(int idx, int value) {
-    return mWc->setBluetoothCoexistenceMode(value);
-}
-
-WifiController::WifiCurrentNetworkProperty::WifiCurrentNetworkProperty(WifiController *c) :
-                WifiIntegerProperty(c, "CurrentlyConnectedNetworkId", true, 1) {
-}
-int WifiController::WifiCurrentNetworkProperty::get(int idx, int *buffer) {
-    *buffer = mWc->mCurrentlyConnectedNetworkId;
-    return 0;
-}
-
-WifiController::WifiSuspendedProperty::WifiSuspendedProperty(WifiController *c) :
-                WifiIntegerProperty(c, "Suspended", false, 1) {
-}
-int WifiController::WifiSuspendedProperty::get(int idx, int *buffer) {
-    *buffer = mWc->getSuspended();
-    return 0;
-}
-int WifiController::WifiSuspendedProperty::set(int idx, int value) {
-    return mWc->setSuspend(value == 1);
-}
-
-WifiController::WifiNetCountProperty::WifiNetCountProperty(WifiController *c) :
-                WifiIntegerProperty(c, "NetCount", true, 1) {
-}
-int WifiController::WifiNetCountProperty::get(int idx, int *buffer) {
-    pthread_mutex_lock(&mWc->mLock);
-    *buffer = mWc->mSupplicant->getNetworkCount();
-    pthread_mutex_unlock(&mWc->mLock);
-    return 0;
-}
-
-WifiController::WifiTriggerScanProperty::WifiTriggerScanProperty(WifiController *c) :
-                WifiIntegerProperty(c, "TriggerScan", false, 1) {
-}
-int WifiController::WifiTriggerScanProperty::get(int idx, int *buffer) {
-    // XXX: Need action type
-    *buffer = 0;
-    return 0;
-}
-
-int WifiController::WifiTriggerScanProperty::set(int idx, int value) {
-    return mWc->triggerScan();
-}
-
diff --git a/nexus/WifiController.h b/nexus/WifiController.h
deleted file mode 100644
index b1524f6..0000000
--- a/nexus/WifiController.h
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _WIFI_CONTROLLER_H
-#define _WIFI_CONTROLLER_H
-
-#include <sys/types.h>
-
-#include "Controller.h"
-#include "ScanResult.h"
-#include "WifiNetwork.h"
-#include "ISupplicantEventHandler.h"
-#include "IWifiStatusPollerHandler.h"
-
-class NetInterface;
-class Supplicant;
-class SupplicantAssociatingEvent;
-class SupplicantAssociatedEvent;
-class SupplicantConnectedEvent;
-class SupplicantScanResultsEvent;
-class SupplicantStateChangeEvent;
-class SupplicantDisconnectedEvent;
-class WifiStatusPoller;
-
-class WifiController : public Controller,
-                       public ISupplicantEventHandler,
-                       public IWifiStatusPollerHandler {
-
-    class WifiIntegerProperty : public IntegerProperty {
-    protected:
-        WifiController *mWc;
-    public:
-        WifiIntegerProperty(WifiController *c, const char *name, bool ro, 
-                            int elements);
-        virtual ~WifiIntegerProperty() {}
-        virtual int set(int idx, int value) = 0;
-        virtual int get(int idx, int *buffer) = 0;
-    };
-    friend class WifiController::WifiIntegerProperty;
-
-    class WifiStringProperty : public StringProperty {
-    protected:
-        WifiController *mWc;
-    public:
-        WifiStringProperty(WifiController *c, const char *name, bool ro, 
-                            int elements);
-        virtual ~WifiStringProperty() {}
-        virtual int set(int idx, const char *value) = 0;
-        virtual int get(int idx, char *buffer, size_t max) = 0;
-    };
-    friend class WifiController::WifiStringProperty;
-
-    class WifiEnabledProperty : public WifiIntegerProperty {
-    public:
-        WifiEnabledProperty(WifiController *c);
-        virtual ~WifiEnabledProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiScanOnlyProperty : public WifiIntegerProperty {
-    public:
-        WifiScanOnlyProperty(WifiController *c);
-        virtual ~WifiScanOnlyProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiAllowedChannelsProperty : public WifiIntegerProperty {
-    public:
-        WifiAllowedChannelsProperty(WifiController *c);
-        virtual ~WifiAllowedChannelsProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiActiveScanProperty : public WifiIntegerProperty {
-    public:
-        WifiActiveScanProperty(WifiController *c);
-        virtual ~WifiActiveScanProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiSearchingProperty : public WifiIntegerProperty {
-    public:
-        WifiSearchingProperty(WifiController *c);
-        virtual ~WifiSearchingProperty() {}
-        int set(int idx, int value) { return -1; }
-        int get(int idx, int *buffer);
-    };
-
-    class WifiPacketFilterProperty : public WifiIntegerProperty {
-    public:
-        WifiPacketFilterProperty(WifiController *c);
-        virtual ~WifiPacketFilterProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiBluetoothCoexScanProperty : public WifiIntegerProperty {
-    public:
-        WifiBluetoothCoexScanProperty(WifiController *c);
-        virtual ~WifiBluetoothCoexScanProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiBluetoothCoexModeProperty : public WifiIntegerProperty {
-    public:
-        WifiBluetoothCoexModeProperty(WifiController *c);
-        virtual ~WifiBluetoothCoexModeProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiCurrentNetworkProperty : public WifiIntegerProperty {
-    public:
-        WifiCurrentNetworkProperty(WifiController *c);
-        virtual ~WifiCurrentNetworkProperty() {}
-        int set(int idx, int value) { return -1; }
-        int get(int idx, int *buffer);
-    };
-
-    class WifiSuspendedProperty : public WifiIntegerProperty {
-    public:
-        WifiSuspendedProperty(WifiController *c);
-        virtual ~WifiSuspendedProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiNetCountProperty : public WifiIntegerProperty {
-    public:
-        WifiNetCountProperty(WifiController *c);
-        virtual ~WifiNetCountProperty() {}
-        int set(int idx, int value) { return -1; }
-        int get(int idx, int *buffer);
-    };
-
-    class WifiTriggerScanProperty : public WifiIntegerProperty {
-    public:
-        WifiTriggerScanProperty(WifiController *c);
-        virtual ~WifiTriggerScanProperty() {}
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiSupplicantStateProperty : public WifiStringProperty {
-    public:
-        WifiSupplicantStateProperty(WifiController *c);
-        virtual ~WifiSupplicantStateProperty() {}
-        int set(int idx, const char *value) { return -1; }
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiInterfaceProperty : public WifiStringProperty {
-    public:
-        WifiInterfaceProperty(WifiController *c);
-        virtual ~WifiInterfaceProperty() {}
-        int set(int idx, const char *value) { return -1; }
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    Supplicant *mSupplicant;
-    char        mModulePath[255];
-    char        mModuleName[64];
-    char        mModuleArgs[255];
-
-    int         mSupplicantState;
-    bool        mActiveScan;
-    bool        mScanOnly;
-    bool        mPacketFilter;
-    bool        mBluetoothCoexScan;
-    int         mBluetoothCoexMode;
-    int         mCurrentlyConnectedNetworkId;
-    bool        mSuspended;
-    int         mLastRssi;
-    int         mRssiEventThreshold;
-    int         mLastLinkSpeed;
-    int         mNumAllowedChannels;
-
-    ScanResultCollection *mLatestScanResults;
-    pthread_mutex_t      mLatestScanResultsLock;
-    pthread_mutex_t      mLock;
-    WifiStatusPoller     *mStatusPoller;
-
-    struct {
-        WifiEnabledProperty         *propEnabled;
-        WifiScanOnlyProperty        *propScanOnly;
-        WifiAllowedChannelsProperty *propAllowedChannels;
-        IntegerPropertyHelper       *propRssiEventThreshold;
-    } mStaticProperties;
-
-    struct {
-        WifiActiveScanProperty        *propActiveScan;
-        WifiSearchingProperty         *propSearching;
-        WifiPacketFilterProperty      *propPacketFilter;
-        WifiBluetoothCoexScanProperty *propBluetoothCoexScan;
-        WifiBluetoothCoexModeProperty *propBluetoothCoexMode;
-        WifiCurrentNetworkProperty    *propCurrentNetwork;
-        IntegerPropertyHelper         *propRssi;
-        IntegerPropertyHelper         *propLinkSpeed;
-        WifiSuspendedProperty         *propSuspended;
-        WifiNetCountProperty          *propNetCount;
-        WifiSupplicantStateProperty   *propSupplicantState;
-        WifiInterfaceProperty         *propInterface;
-        WifiTriggerScanProperty       *propTriggerScan;
-    } mDynamicProperties;
-
-    // True if supplicant is currently searching for a network
-    bool mIsSupplicantSearching;
-    int  mNumScanResultsSinceLastStateChange;
-
-    bool        mEnabled;
-
-public:
-    WifiController(PropertyManager *propmngr, IControllerHandler *handlers, char *modpath, char *modname, char *modargs);
-    virtual ~WifiController() {}
-
-    int start();
-    int stop();
-
-    WifiNetwork *createNetwork();
-    int removeNetwork(int networkId);
-    WifiNetworkCollection *createNetworkList();
-
-    ScanResultCollection *createScanResults();
-
-    char *getModulePath() { return mModulePath; }
-    char *getModuleName() { return mModuleName; }
-    char *getModuleArgs() { return mModuleArgs; }
-
-    Supplicant *getSupplicant() { return mSupplicant; }
-
-protected:
-    // Move this crap into a 'driver'
-    virtual int powerUp() = 0;
-    virtual int powerDown() = 0;
-    virtual int loadFirmware();
-
-    virtual bool isFirmwareLoaded() = 0;
-    virtual bool isPoweredUp() = 0;
-
-private:
-    void sendStatusBroadcast(const char *msg);
-    int setActiveScan(bool active);
-    int triggerScan();
-    int enable();
-    int disable();
-    int setSuspend(bool suspend);
-    bool getSuspended();
-    int setBluetoothCoexistenceScan(bool enable);
-    int setBluetoothCoexistenceMode(int mode);
-    int setPacketFilter(bool enable);
-    int setScanOnly(bool scanOnly);
-
-    // ISupplicantEventHandler methods
-    void onAssociatingEvent(SupplicantAssociatingEvent *evt);
-    void onAssociatedEvent(SupplicantAssociatedEvent *evt);
-    void onConnectedEvent(SupplicantConnectedEvent *evt);
-    void onScanResultsEvent(SupplicantScanResultsEvent *evt);
-    void onStateChangeEvent(SupplicantStateChangeEvent *evt);
-    void onConnectionTimeoutEvent(SupplicantConnectionTimeoutEvent *evt);
-    void onDisconnectedEvent(SupplicantDisconnectedEvent *evt);
-#if 0
-    virtual void onTerminatingEvent(SupplicantEvent *evt);
-    virtual void onPasswordChangedEvent(SupplicantEvent *evt);
-    virtual void onEapNotificationEvent(SupplicantEvent *evt);
-    virtual void onEapStartedEvent(SupplicantEvent *evt);
-    virtual void onEapMethodEvent(SupplicantEvent *evt);
-    virtual void onEapSuccessEvent(SupplicantEvent *evt);
-    virtual void onEapFailureEvent(SupplicantEvent *evt);
-    virtual void onLinkSpeedEvent(SupplicantEvent *evt);
-    virtual void onDriverStateEvent(SupplicantEvent *evt);
-#endif
-
-    void onStatusPollInterval();
-
-    int verifyNotSuspended();
-};
-
-#endif
diff --git a/nexus/WifiNetwork.cpp b/nexus/WifiNetwork.cpp
deleted file mode 100644
index 6a0f684..0000000
--- a/nexus/WifiNetwork.cpp
+++ /dev/null
@@ -1,970 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <string.h>
-#include <stdlib.h>
-#include <sys/types.h>
-
-#define LOG_TAG "WifiNetwork"
-#include <cutils/log.h>
-
-#include "NetworkManager.h"
-#include "WifiNetwork.h"
-#include "Supplicant.h"
-#include "WifiController.h"
-
-WifiNetwork::WifiNetwork() {
-   // This is private to restrict copy constructors
-}
-
-WifiNetwork::WifiNetwork(WifiController *c, Supplicant *suppl, const char *data) {
-    mController = c;
-    mSuppl = suppl;
-
-    char *tmp = strdup(data);
-    char *next = tmp;
-    char *id;
-    char *ssid;
-    char *bssid;
-    char *flags;
-
-    if (!(id = strsep(&next, "\t")))
-        LOGE("Failed to extract network id");
-    if (!(ssid = strsep(&next, "\t")))
-        LOGE("Failed to extract ssid");
-    if (!(bssid = strsep(&next, "\t")))
-        LOGE("Failed to extract bssid");
-    if (!(flags = strsep(&next, "\t")))
-        LOGE("Failed to extract flags");
-
-   // LOGD("id '%s', ssid '%s', bssid '%s', flags '%s'", id, ssid, bssid,
-   //      flags ? flags :"null");
-
-    if (id)
-        mNetid = atoi(id);
-    if (ssid)
-        mSsid = strdup(ssid);
-    if (bssid)
-        mBssid = strdup(bssid);
-
-    mPsk = NULL;
-    memset(mWepKeys, 0, sizeof(mWepKeys));
-    mDefaultKeyIndex = -1;
-    mPriority = -1;
-    mHiddenSsid = NULL;
-    mKeyManagement = KeyManagementMask::UNKNOWN;
-    mProtocols = 0;
-    mAuthAlgorithms = 0;
-    mPairwiseCiphers = 0;
-    mGroupCiphers = 0;
-    mEnabled = true;
-
-    if (flags && flags[0] != '\0') {
-        if (!strcmp(flags, "[DISABLED]"))
-            mEnabled = false;
-        else
-            LOGW("Unsupported flags '%s'", flags);
-    }
-
-    free(tmp);
-    createProperties();
-}
-
-WifiNetwork::WifiNetwork(WifiController *c, Supplicant *suppl, int networkId) {
-    mController = c;
-    mSuppl = suppl;
-    mNetid = networkId;
-    mSsid = NULL;
-    mBssid = NULL;
-    mPsk = NULL;
-    memset(mWepKeys, 0, sizeof(mWepKeys));
-    mDefaultKeyIndex = -1;
-    mPriority = -1;
-    mHiddenSsid = NULL;
-    mKeyManagement = 0;
-    mProtocols = 0;
-    mAuthAlgorithms = 0;
-    mPairwiseCiphers = 0;
-    mGroupCiphers = 0;
-    mEnabled = false;
-    createProperties();
-}
-
-WifiNetwork *WifiNetwork::clone() {
-    WifiNetwork *r = new WifiNetwork();
-
-    r->mSuppl = mSuppl;
-    r->mNetid = mNetid;
-
-    if (mSsid)
-        r->mSsid = strdup(mSsid);
-    if (mBssid)
-        r->mBssid = strdup(mBssid);
-    if (mPsk)
-        r->mPsk = strdup(mPsk);
-
-    r->mController = mController;
-    memcpy(r->mWepKeys, mWepKeys, sizeof(mWepKeys));
-    r->mDefaultKeyIndex = mDefaultKeyIndex;
-    r->mPriority = mPriority;
-    if (mHiddenSsid)
-        r->mHiddenSsid = strdup(mHiddenSsid);
-    r->mKeyManagement = mKeyManagement;
-    r->mProtocols = mProtocols;
-    r->mAuthAlgorithms = mAuthAlgorithms;
-    r->mPairwiseCiphers = mPairwiseCiphers;
-    r->mGroupCiphers = mGroupCiphers;
-    return r;
-}
-
-void WifiNetwork::createProperties() {
-    asprintf(&mPropNamespace, "wifi.net.%d", mNetid);
-
-    mStaticProperties.propEnabled = new WifiNetworkEnabledProperty(this);
-    mStaticProperties.propSsid = new WifiNetworkSsidProperty(this);
-    mStaticProperties.propBssid = new WifiNetworkBssidProperty(this);
-    mStaticProperties.propPsk = new WifiNetworkPskProperty(this);
-    mStaticProperties.propWepKey = new WifiNetworkWepKeyProperty(this);
-    mStaticProperties.propDefKeyIdx = new WifiNetworkDefaultKeyIndexProperty(this);
-    mStaticProperties.propPriority = new WifiNetworkPriorityProperty(this);
-    mStaticProperties.propKeyManagement = new WifiNetworkKeyManagementProperty(this);
-    mStaticProperties.propProtocols = new WifiNetworkProtocolsProperty(this);
-    mStaticProperties.propAuthAlgorithms = new WifiNetworkAuthAlgorithmsProperty(this);
-    mStaticProperties.propPairwiseCiphers = new WifiNetworkPairwiseCiphersProperty(this);
-    mStaticProperties.propGroupCiphers = new WifiNetworkGroupCiphersProperty(this);
-    mStaticProperties.propHiddenSsid = new WifiNetworkHiddenSsidProperty(this);
-}
-
-WifiNetwork::~WifiNetwork() {
-    if (mPropNamespace)
-        free(mPropNamespace);
-    if (mSsid)
-        free(mSsid);
-    if (mBssid)
-        free(mBssid);
-    if (mPsk)
-        free(mPsk);
-    for (int i = 0; i < 4; i++) {
-        if (mWepKeys[i])
-            free(mWepKeys[i]);
-    }
-
-    if (mHiddenSsid)
-        free(mHiddenSsid);
-
-    delete mStaticProperties.propEnabled;
-    delete mStaticProperties.propSsid;
-    delete mStaticProperties.propBssid;
-    delete mStaticProperties.propPsk;
-    delete mStaticProperties.propWepKey;
-    delete mStaticProperties.propDefKeyIdx;
-    delete mStaticProperties.propPriority;
-    delete mStaticProperties.propKeyManagement;
-    delete mStaticProperties.propProtocols;
-    delete mStaticProperties.propAuthAlgorithms;
-    delete mStaticProperties.propPairwiseCiphers;
-    delete mStaticProperties.propGroupCiphers;
-    delete mStaticProperties.propHiddenSsid;
-}
-
-int WifiNetwork::refresh() {
-    char buffer[255];
-    size_t len;
-    uint32_t mask;
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "psk", buffer, len))
-        mPsk = strdup(buffer);
-
-    for (int i = 0; i < 4; i++) {
-        char *name;
-
-        asprintf(&name, "wep_key%d", i);
-        len = sizeof(buffer);
-        if (mSuppl->getNetworkVar(mNetid, name, buffer, len))
-            mWepKeys[i] = strdup(buffer);
-        free(name);
-    }
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "wep_tx_keyidx", buffer, len))
-        mDefaultKeyIndex = atoi(buffer);
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "priority", buffer, len))
-        mPriority = atoi(buffer);
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "scan_ssid", buffer, len))
-        mHiddenSsid = strdup(buffer);
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "key_mgmt", buffer, len)) {
-        if (WifiNetwork::parseKeyManagementMask(buffer, &mask)) {
-            LOGE("Error parsing key_mgmt (%s)", strerror(errno));
-        } else {
-           mKeyManagement = mask;
-        }
-    }
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "proto", buffer, len)) {
-        if (WifiNetwork::parseProtocolsMask(buffer, &mask)) {
-            LOGE("Error parsing proto (%s)", strerror(errno));
-        } else {
-           mProtocols = mask;
-        }
-    }
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "auth_alg", buffer, len)) {
-        if (WifiNetwork::parseAuthAlgorithmsMask(buffer, &mask)) {
-            LOGE("Error parsing auth_alg (%s)", strerror(errno));
-        } else {
-           mAuthAlgorithms = mask;
-        }
-    }
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "pairwise", buffer, len)) {
-        if (WifiNetwork::parsePairwiseCiphersMask(buffer, &mask)) {
-            LOGE("Error parsing pairwise (%s)", strerror(errno));
-        } else {
-           mPairwiseCiphers = mask;
-        }
-    }
-
-    len = sizeof(buffer);
-    if (mSuppl->getNetworkVar(mNetid, "group", buffer, len)) {
-        if (WifiNetwork::parseGroupCiphersMask(buffer, &mask)) {
-            LOGE("Error parsing group (%s)", strerror(errno));
-        } else {
-           mGroupCiphers = mask;
-        }
-    }
-
-    return 0;
-out_err:
-    LOGE("Refresh failed (%s)",strerror(errno));
-    return -1;
-}
-
-int WifiNetwork::setSsid(const char *ssid) {
-    char tmp[255];
-    snprintf(tmp, sizeof(tmp), "\"%s\"", ssid);
-    if (mSuppl->setNetworkVar(mNetid, "ssid", tmp))
-        return -1;
-    if (mSsid)
-        free(mSsid);
-    mSsid = strdup(ssid);
-    return 0;
-}
-
-int WifiNetwork::setBssid(const char *bssid) {
-    if (mSuppl->setNetworkVar(mNetid, "bssid", bssid))
-        return -1;
-    if (mBssid)
-        free(mBssid);
-    mBssid = strdup(bssid);
-    return 0;
-}
-
-int WifiNetwork::setPsk(const char *psk) {
-    char tmp[255];
-    snprintf(tmp, sizeof(tmp), "\"%s\"", psk);
-    if (mSuppl->setNetworkVar(mNetid, "psk", tmp))
-        return -1;
-
-    if (mPsk)
-        free(mPsk);
-    mPsk = strdup(psk);
-    return 0;
-}
-
-int WifiNetwork::setWepKey(int idx, const char *key) {
-    char *name;
-
-    asprintf(&name, "wep_key%d", idx);
-    int rc = mSuppl->setNetworkVar(mNetid, name, key);
-    free(name);
-
-    if (rc)
-        return -1;
-
-    if (mWepKeys[idx])
-        free(mWepKeys[idx]);
-    mWepKeys[idx] = strdup(key);
-    return 0;
-}
-
-int WifiNetwork::setDefaultKeyIndex(int idx) {
-    char val[16];
-    sprintf(val, "%d", idx);
-    if (mSuppl->setNetworkVar(mNetid, "wep_tx_keyidx", val))
-        return -1;
-
-    mDefaultKeyIndex = idx;
-    return 0;
-}
-
-int WifiNetwork::setPriority(int priority) {
-    char val[16];
-    sprintf(val, "%d", priority);
-    if (mSuppl->setNetworkVar(mNetid, "priority", val))
-        return -1;
-
-    mPriority = priority;
-    return 0;
-}
-
-int WifiNetwork::setHiddenSsid(const char *ssid) {
-    if (mSuppl->setNetworkVar(mNetid, "scan_ssid", ssid))
-        return -1;
-
-    if (mHiddenSsid)
-        free(mHiddenSsid);
-    mHiddenSsid = strdup(ssid);
-    return 0;
-}
-
-int WifiNetwork::setKeyManagement(uint32_t mask) {
-    char accum[64] = {'\0'};
-
-    if (mask == KeyManagementMask::NONE)
-        strcpy(accum, "NONE");
-    else {
-        if (mask & KeyManagementMask::WPA_PSK) 
-            strcat(accum, "WPA-PSK");
-        if (mask & KeyManagementMask::WPA_EAP) {
-            if (accum[0] != '\0')
-                strcat(accum, " ");
-            strcat(accum, "WPA-EAP");
-        }
-        if (mask & KeyManagementMask::IEEE8021X) {
-            if (accum[0] != '\0')
-                strcat(accum, " ");
-            strcat(accum, "IEEE8021X");
-        }
-    }
-
-    if (mSuppl->setNetworkVar(mNetid, "key_mgmt", accum))
-        return -1;
-    mKeyManagement = mask;
-    return 0;
-}
-
-int WifiNetwork::setProtocols(uint32_t mask) {
-    char accum[64];
-
-    accum[0] = '\0';
-
-    if (mask & SecurityProtocolMask::WPA)
-        strcpy(accum, "WPA ");
-
-    if (mask & SecurityProtocolMask::RSN)
-        strcat(accum, "RSN");
-
-    if (mSuppl->setNetworkVar(mNetid, "proto", accum))
-        return -1;
-    mProtocols = mask;
-    return 0;
-}
-
-int WifiNetwork::setAuthAlgorithms(uint32_t mask) {
-    char accum[64];
-
-    accum[0] = '\0';
-
-    if (mask == 0)
-        strcpy(accum, "");
-
-    if (mask & AuthenticationAlgorithmMask::OPEN)
-        strcpy(accum, "OPEN ");
-
-    if (mask & AuthenticationAlgorithmMask::SHARED)
-        strcat(accum, "SHARED ");
-
-    if (mask & AuthenticationAlgorithmMask::LEAP)
-        strcat(accum, "LEAP ");
-
-    if (mSuppl->setNetworkVar(mNetid, "auth_alg", accum))
-        return -1;
-
-    mAuthAlgorithms = mask;
-    return 0;
-}
-
-int WifiNetwork::setPairwiseCiphers(uint32_t mask) {
-    char accum[64];
-
-    accum[0] = '\0';
-
-    if (mask == PairwiseCiphersMask::NONE)
-        strcpy(accum, "NONE");
-    else {
-        if (mask & PairwiseCiphersMask::TKIP)
-            strcat(accum, "TKIP ");
-        if (mask & PairwiseCiphersMask::CCMP)
-            strcat(accum, "CCMP ");
-    }
-
-    if (mSuppl->setNetworkVar(mNetid, "pairwise", accum))
-        return -1;
-
-    mPairwiseCiphers = mask;
-    return 0;
-}
-
-int WifiNetwork::setGroupCiphers(uint32_t mask) {
-    char accum[64];
-
-    accum[0] = '\0';
-
-    if (mask & GroupCiphersMask::WEP40)
-        strcat(accum, "WEP40 ");
-    if (mask & GroupCiphersMask::WEP104)
-        strcat(accum, "WEP104 ");
-    if (mask & GroupCiphersMask::TKIP)
-        strcat(accum, "TKIP ");
-    if (mask & GroupCiphersMask::CCMP)
-        strcat(accum, "CCMP ");
-
-    if (mSuppl->setNetworkVar(mNetid, "group", accum))
-        return -1;
-    mGroupCiphers = mask;
-    return 0;
-}
-
-int WifiNetwork::setEnabled(bool enabled) {
-
-    if (enabled) {
-        if (getPriority() == -1) {
-            LOGE("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");
-            errno = EAGAIN;
-            return -1;
-        }
-    }
-
-    if (mSuppl->enableNetwork(mNetid, enabled))
-        return -1;
-
-    mEnabled = enabled;
-    return 0;
-}
-
-int WifiNetwork::attachProperties(PropertyManager *pm, const char *nsName) {
-    pm->attachProperty(nsName, mStaticProperties.propSsid);
-    pm->attachProperty(nsName, mStaticProperties.propBssid);
-    pm->attachProperty(nsName, mStaticProperties.propPsk);
-    pm->attachProperty(nsName, mStaticProperties.propWepKey);
-    pm->attachProperty(nsName, mStaticProperties.propDefKeyIdx);
-    pm->attachProperty(nsName, mStaticProperties.propPriority);
-    pm->attachProperty(nsName, mStaticProperties.propKeyManagement);
-    pm->attachProperty(nsName, mStaticProperties.propProtocols);
-    pm->attachProperty(nsName, mStaticProperties.propAuthAlgorithms);
-    pm->attachProperty(nsName, mStaticProperties.propPairwiseCiphers);
-    pm->attachProperty(nsName, mStaticProperties.propGroupCiphers);
-    pm->attachProperty(nsName, mStaticProperties.propHiddenSsid);
-    pm->attachProperty(nsName, mStaticProperties.propEnabled);
-    return 0;
-}
-
-int WifiNetwork::detachProperties(PropertyManager *pm, const char *nsName) {
-    pm->detachProperty(nsName, mStaticProperties.propEnabled);
-    pm->detachProperty(nsName, mStaticProperties.propSsid);
-    pm->detachProperty(nsName, mStaticProperties.propBssid);
-    pm->detachProperty(nsName, mStaticProperties.propPsk);
-    pm->detachProperty(nsName, mStaticProperties.propWepKey);
-    pm->detachProperty(nsName, mStaticProperties.propDefKeyIdx);
-    pm->detachProperty(nsName, mStaticProperties.propPriority);
-    pm->detachProperty(nsName, mStaticProperties.propKeyManagement);
-    pm->detachProperty(nsName, mStaticProperties.propProtocols);
-    pm->detachProperty(nsName, mStaticProperties.propAuthAlgorithms);
-    pm->detachProperty(nsName, mStaticProperties.propPairwiseCiphers);
-    pm->detachProperty(nsName, mStaticProperties.propGroupCiphers);
-    pm->detachProperty(nsName, mStaticProperties.propHiddenSsid);
-    return 0;
-}
-
-int WifiNetwork::parseKeyManagementMask(const char *buffer, uint32_t *mask) {
-    bool none = false;
-    char *v_tmp = strdup(buffer);
-    char *v_next = v_tmp;
-    char *v_token;
-
-//    LOGD("parseKeyManagementMask(%s)", buffer);
-    *mask = 0;
-
-    while((v_token = strsep(&v_next, " "))) {
-        if (!strcasecmp(v_token, "NONE")) {
-            *mask = KeyManagementMask::NONE;
-            none = true;
-        } else if (!none) {
-            if (!strcasecmp(v_token, "WPA-PSK"))
-                *mask |= KeyManagementMask::WPA_PSK;
-            else if (!strcasecmp(v_token, "WPA-EAP"))
-                *mask |= KeyManagementMask::WPA_EAP;
-            else if (!strcasecmp(v_token, "IEEE8021X"))
-                *mask |= KeyManagementMask::IEEE8021X;
-            else {
-                LOGW("Invalid KeyManagementMask value '%s'", v_token);
-                errno = EINVAL;
-                free(v_tmp);
-                return -1;
-            }
-        } else {
-            LOGW("KeyManagementMask value '%s' when NONE", v_token);
-            errno = EINVAL;
-            free(v_tmp);
-            return -1;
-        }
-    }
-    free(v_tmp);
-    return 0;
-}
-
-int WifiNetwork::parseProtocolsMask(const char *buffer, uint32_t *mask) {
-    bool none = false;
-    char *v_tmp = strdup(buffer);
-    char *v_next = v_tmp;
-    char *v_token;
-
-//    LOGD("parseProtocolsMask(%s)", buffer);
-    *mask = 0;
-    while((v_token = strsep(&v_next, " "))) {
-        if (!strcasecmp(v_token, "WPA"))
-            *mask |= SecurityProtocolMask::WPA;
-        else if (!strcasecmp(v_token, "RSN"))
-            *mask |= SecurityProtocolMask::RSN;
-        else {
-            LOGW("Invalid ProtocolsMask value '%s'", v_token);
-            errno = EINVAL;
-            free(v_tmp);
-            return -1;
-        }
-    }
-
-    free(v_tmp);
-    return 0;
-}
-
-int WifiNetwork::parseAuthAlgorithmsMask(const char *buffer, uint32_t *mask) {
-    bool none = false;
-    char *v_tmp = strdup(buffer);
-    char *v_next = v_tmp;
-    char *v_token;
-
-//    LOGD("parseAuthAlgorithmsMask(%s)", buffer);
-
-    *mask = 0;
-    if (buffer[0] == '\0')
-        return 0;
-
-    while((v_token = strsep(&v_next, " "))) {
-        if (!strcasecmp(v_token, "OPEN"))
-            *mask |= AuthenticationAlgorithmMask::OPEN;
-        else if (!strcasecmp(v_token, "SHARED"))
-            *mask |= AuthenticationAlgorithmMask::SHARED;
-        else if (!strcasecmp(v_token, "LEAP"))
-            *mask |= AuthenticationAlgorithmMask::LEAP;
-        else {
-            LOGW("Invalid AuthAlgorithmsMask value '%s'", v_token);
-            errno = EINVAL;
-            free(v_tmp);
-            return -1;
-        }
-    }
-    free(v_tmp);
-    return 0;
-}
-
-int WifiNetwork::parsePairwiseCiphersMask(const char *buffer, uint32_t *mask) {
-    bool none = false;
-    char *v_tmp = strdup(buffer);
-    char *v_next = v_tmp;
-    char *v_token;
-
-//    LOGD("parsePairwiseCiphersMask(%s)", buffer);
-
-    *mask = 0;
-    while((v_token = strsep(&v_next, " "))) {
-        if (!strcasecmp(v_token, "NONE")) {
-            *mask = PairwiseCiphersMask::NONE;
-            none = true;
-        } else if (!none) {
-            if (!strcasecmp(v_token, "TKIP"))
-                *mask |= PairwiseCiphersMask::TKIP;
-            else if (!strcasecmp(v_token, "CCMP"))
-                *mask |= PairwiseCiphersMask::CCMP;
-        else {
-                LOGW("PairwiseCiphersMask value '%s' when NONE", v_token);
-                errno = EINVAL;
-                free(v_tmp);
-                return -1;
-            }
-        } else {
-            LOGW("Invalid PairwiseCiphersMask value '%s'", v_token);
-            errno = EINVAL;
-            free(v_tmp);
-            return -1;
-        }
-    }
-    free(v_tmp);
-    return 0;
-}
-
-int WifiNetwork::parseGroupCiphersMask(const char *buffer, uint32_t *mask) {
-    bool none = false;
-    char *v_tmp = strdup(buffer);
-    char *v_next = v_tmp;
-    char *v_token;
-
-//    LOGD("parseGroupCiphersMask(%s)", buffer);
-
-    *mask = 0;
-    while((v_token = strsep(&v_next, " "))) {
-        if (!strcasecmp(v_token, "WEP40"))
-            *mask |= GroupCiphersMask::WEP40;
-        else if (!strcasecmp(v_token, "WEP104"))
-            *mask |= GroupCiphersMask::WEP104;
-        else if (!strcasecmp(v_token, "TKIP"))
-            *mask |= GroupCiphersMask::TKIP;
-        else if (!strcasecmp(v_token, "CCMP"))
-            *mask |= GroupCiphersMask::CCMP;
-        else {
-            LOGW("Invalid GroupCiphersMask value '%s'", v_token);
-            errno = EINVAL;
-            free(v_tmp);
-            return -1;
-        }
-    }
-    free(v_tmp);
-    return 0;
-}
-
-WifiNetwork::WifiNetworkIntegerProperty::WifiNetworkIntegerProperty(WifiNetwork *wn,
-                                                      const char *name,
-                                                      bool ro,
-                                                      int elements) :
-             IntegerProperty(name, ro, elements) {
-    mWn = wn;
-}
-
-WifiNetwork::WifiNetworkStringProperty::WifiNetworkStringProperty(WifiNetwork *wn,
-                                                                  const char *name,
-                                                              bool ro, int elements) :
-             StringProperty(name, ro, elements) {
-    mWn = wn;
-}
-
-WifiNetwork::WifiNetworkEnabledProperty::WifiNetworkEnabledProperty(WifiNetwork *wn) :
-                WifiNetworkIntegerProperty(wn, "Enabled", false, 1) {
-}
-
-int WifiNetwork::WifiNetworkEnabledProperty::get(int idx, int *buffer) {
-    *buffer = mWn->mEnabled;
-    return 0;
-}
-int WifiNetwork::WifiNetworkEnabledProperty::set(int idx, int value) {
-    return mWn->setEnabled(value == 1);
-}
-
-WifiNetwork::WifiNetworkSsidProperty::WifiNetworkSsidProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "Ssid", false, 1) {
-}
-
-int WifiNetwork::WifiNetworkSsidProperty::get(int idx, char *buffer, size_t max) {
-    strncpy(buffer,
-            mWn->getSsid() ? mWn->getSsid() : "none",
-            max);
-    return 0;
-}
-int WifiNetwork::WifiNetworkSsidProperty::set(int idx, const char *value) {
-    return mWn->setSsid(value);
-}
-
-WifiNetwork::WifiNetworkBssidProperty::WifiNetworkBssidProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "Bssid", false, 1) {
-}
-int WifiNetwork::WifiNetworkBssidProperty::get(int idx, char *buffer, size_t max) {
-    strncpy(buffer,
-            mWn->getBssid() ? mWn->getBssid() : "none",
-            max);
-    return 0;
-}
-int WifiNetwork::WifiNetworkBssidProperty::set(int idx, const char *value) {
-    return mWn->setBssid(value);
-}
-
-WifiNetwork::WifiNetworkPskProperty::WifiNetworkPskProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "Psk", false, 1) {
-}
-int WifiNetwork::WifiNetworkPskProperty::get(int idx, char *buffer, size_t max) {
-    strncpy(buffer,
-            mWn->getPsk() ? mWn->getPsk() : "none",
-            max);
-    return 0;
-}
-int WifiNetwork::WifiNetworkPskProperty::set(int idx, const char *value) {
-    return mWn->setPsk(value);
-}
-
-WifiNetwork::WifiNetworkWepKeyProperty::WifiNetworkWepKeyProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "WepKey", false, 4) {
-}
-
-int WifiNetwork::WifiNetworkWepKeyProperty::get(int idx, char *buffer, size_t max) {
-    const char *key = mWn->getWepKey(idx);
-
-    strncpy(buffer, (key ? key : "none"), max);
-    return 0;
-}
-int WifiNetwork::WifiNetworkWepKeyProperty::set(int idx, const char *value) {
-    return mWn->setWepKey(idx, value);
-}
-
-WifiNetwork::WifiNetworkDefaultKeyIndexProperty::WifiNetworkDefaultKeyIndexProperty(WifiNetwork *wn) :
-                WifiNetworkIntegerProperty(wn, "DefaultKeyIndex", false,  1) {
-}
-int WifiNetwork::WifiNetworkDefaultKeyIndexProperty::get(int idx, int *buffer) {
-    *buffer = mWn->getDefaultKeyIndex();
-    return 0;
-}
-int WifiNetwork::WifiNetworkDefaultKeyIndexProperty::set(int idx, int value) {
-    return mWn->setDefaultKeyIndex(value);
-}
-
-WifiNetwork::WifiNetworkPriorityProperty::WifiNetworkPriorityProperty(WifiNetwork *wn) :
-                WifiNetworkIntegerProperty(wn, "Priority", false, 1) {
-}
-int WifiNetwork::WifiNetworkPriorityProperty::get(int idx, int *buffer) {
-    *buffer = mWn->getPriority();
-    return 0;
-}
-int WifiNetwork::WifiNetworkPriorityProperty::set(int idx, int value) {
-    return mWn->setPriority(value);
-}
-
-WifiNetwork::WifiNetworkKeyManagementProperty::WifiNetworkKeyManagementProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "KeyManagement", false, 1) {
-}
-int WifiNetwork::WifiNetworkKeyManagementProperty::get(int idx, char *buffer, size_t max) {
-
-    if (mWn->getKeyManagement() == KeyManagementMask::NONE)
-        strncpy(buffer, "NONE", max);
-    else {
-        char tmp[80] = { '\0' };
-
-        if (mWn->getKeyManagement() & KeyManagementMask::WPA_PSK)
-            strcat(tmp, "WPA-PSK");
-        if (mWn->getKeyManagement() & KeyManagementMask::WPA_EAP) {
-            if (tmp[0] != '\0')
-                strcat(tmp, " ");
-            strcat(tmp, "WPA-EAP");
-        }
-        if (mWn->getKeyManagement() & KeyManagementMask::IEEE8021X) {
-            if (tmp[0] != '\0')
-                strcat(tmp, " ");
-            strcat(tmp, "IEEE8021X");
-        }
-        if (tmp[0] == '\0') {
-            strncpy(buffer, "(internal error)", max);
-            errno = ENOENT;
-            return -1;
-        }
-        if (tmp[strlen(tmp)] == ' ')
-            tmp[strlen(tmp)] = '\0';
-
-        strncpy(buffer, tmp, max);
-    }
-    return 0;
-}
-int WifiNetwork::WifiNetworkKeyManagementProperty::set(int idx, const char *value) {
-    uint32_t mask;
-    if (mWn->parseKeyManagementMask(value, &mask))
-        return -1;
-    return mWn->setKeyManagement(mask);
-}
-
-WifiNetwork::WifiNetworkProtocolsProperty::WifiNetworkProtocolsProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "Protocols", false, 1) {
-}
-int WifiNetwork::WifiNetworkProtocolsProperty::get(int idx, char *buffer, size_t max) {
-    char tmp[80] = { '\0' };
-
-    if (mWn->getProtocols() & SecurityProtocolMask::WPA)
-        strcat(tmp, "WPA");
-    if (mWn->getProtocols() & SecurityProtocolMask::RSN) {
-        if (tmp[0] != '\0')
-            strcat(tmp, " ");
-        strcat(tmp, "RSN");
-    }
-
-    if (tmp[0] == '\0') {
-        strncpy(buffer, "(internal error)", max);
-        errno = ENOENT;
-        return NULL;
-    }
-    if (tmp[strlen(tmp)] == ' ')
-        tmp[strlen(tmp)] = '\0';
-
-    strncpy(buffer, tmp, max);
-    return 0;
-}
-int WifiNetwork::WifiNetworkProtocolsProperty::set(int idx, const char *value) {
-    uint32_t mask;
-    if (mWn->parseProtocolsMask(value, &mask))
-        return -1;
-    return mWn->setProtocols(mask);
-}
-
-WifiNetwork::WifiNetworkAuthAlgorithmsProperty::WifiNetworkAuthAlgorithmsProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "AuthAlgorithms", false, 1) {
-}
-int WifiNetwork::WifiNetworkAuthAlgorithmsProperty::get(int idx, char *buffer, size_t max) {
-    char tmp[80] = { '\0' };
-
-    if (mWn->getAuthAlgorithms() == 0) {
-        strncpy(buffer, "NONE", max);
-        return 0;
-    }
-
-    if (mWn->getAuthAlgorithms() & AuthenticationAlgorithmMask::OPEN)
-        strcat(tmp, "OPEN");
-    if (mWn->getAuthAlgorithms() & AuthenticationAlgorithmMask::SHARED) {
-        if (tmp[0] != '\0')
-            strcat(tmp, " ");
-        strcat(tmp, "SHARED");
-    }
-    if (mWn->getAuthAlgorithms() & AuthenticationAlgorithmMask::LEAP) {
-        if (tmp[0] != '\0')
-            strcat(tmp, " ");
-        strcat(tmp, "LEAP");
-    }
-
-    if (tmp[0] == '\0') {
-        strncpy(buffer, "(internal error)", max);
-        errno = ENOENT;
-        return NULL;
-    }
-    if (tmp[strlen(tmp)] == ' ')
-        tmp[strlen(tmp)] = '\0';
-
-    strncpy(buffer, tmp, max);
-    return 0;
-}
-int WifiNetwork::WifiNetworkAuthAlgorithmsProperty::set(int idx, const char *value) {
-    uint32_t mask;
-    if (mWn->parseAuthAlgorithmsMask(value, &mask))
-        return -1;
-    return mWn->setAuthAlgorithms(mask);
-}
-
-WifiNetwork::WifiNetworkPairwiseCiphersProperty::WifiNetworkPairwiseCiphersProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "PairwiseCiphers", false, 1) {
-}
-int WifiNetwork::WifiNetworkPairwiseCiphersProperty::get(int idx, char *buffer, size_t max) {
-    if (mWn->getPairwiseCiphers() == PairwiseCiphersMask::NONE)
-        strncpy(buffer, "NONE", max);
-    else {
-        char tmp[80] = { '\0' };
-
-        if (mWn->getPairwiseCiphers() & PairwiseCiphersMask::TKIP)
-            strcat(tmp, "TKIP");
-        if (mWn->getPairwiseCiphers() & PairwiseCiphersMask::CCMP) {
-            if (tmp[0] != '\0')
-                strcat(tmp, " ");
-            strcat(tmp, "CCMP");
-        }
-        if (tmp[0] == '\0') {
-            strncpy(buffer, "(internal error)", max);
-            errno = ENOENT;
-            return NULL;
-        }
-        if (tmp[strlen(tmp)] == ' ')
-            tmp[strlen(tmp)] = '\0';
-
-        strncpy(buffer, tmp, max);
-    }
-    return 0;
-}
-int WifiNetwork::WifiNetworkPairwiseCiphersProperty::set(int idx, const char *value) {
-    uint32_t mask;
-    if (mWn->parsePairwiseCiphersMask(value, &mask))
-        return -1;
-    return mWn->setPairwiseCiphers(mask);
-}
-
-WifiNetwork::WifiNetworkGroupCiphersProperty::WifiNetworkGroupCiphersProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "GroupCiphers", false, 1) {
-}
-int WifiNetwork::WifiNetworkGroupCiphersProperty::get(int idx, char *buffer, size_t max) {
-   char tmp[80] = { '\0' };
-
-    if (mWn->getGroupCiphers() & GroupCiphersMask::WEP40)
-        strcat(tmp, "WEP40");
-    if (mWn->getGroupCiphers() & GroupCiphersMask::WEP104) {
-        if (tmp[0] != '\0')
-            strcat(tmp, " ");
-        strcat(tmp, "WEP104");
-    }
-    if (mWn->getGroupCiphers() & GroupCiphersMask::TKIP) {
-        if (tmp[0] != '\0')
-            strcat(tmp, " ");
-        strcat(tmp, "TKIP");
-    }
-    if (mWn->getGroupCiphers() & GroupCiphersMask::CCMP) {
-        if (tmp[0] != '\0')
-            strcat(tmp, " ");
-        strcat(tmp, "CCMP");
-    }
-
-    if (tmp[0] == '\0') {
-        strncpy(buffer, "(internal error)", max);
-        errno = ENOENT;
-        return -1;
-    }
-    if (tmp[strlen(tmp)] == ' ')
-        tmp[strlen(tmp)] = '\0';
-
-    strncpy(buffer, tmp, max);
-    return 0;
-}
-int WifiNetwork::WifiNetworkGroupCiphersProperty::set(int idx, const char *value) {
-    uint32_t mask;
-    if (mWn->parseGroupCiphersMask(value, &mask))
-        return -1;
-    return mWn->setGroupCiphers(mask);
-}
-
-WifiNetwork::WifiNetworkHiddenSsidProperty::WifiNetworkHiddenSsidProperty(WifiNetwork *wn) :
-                WifiNetworkStringProperty(wn, "HiddenSsid", false, 1) {
-}
-int WifiNetwork::WifiNetworkHiddenSsidProperty::get(int idx, char *buffer, size_t max) {
-    const char *scan_ssid = mWn->getHiddenSsid();
-    
-    strncpy(buffer, (scan_ssid ? scan_ssid : "none"), max);
-    return 0;
-}
-int WifiNetwork::WifiNetworkHiddenSsidProperty::set(int idx, const char *value) {
-    return mWn->setHiddenSsid(value);
-}
diff --git a/nexus/WifiNetwork.h b/nexus/WifiNetwork.h
deleted file mode 100644
index 15ec647..0000000
--- a/nexus/WifiNetwork.h
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _WIFI_NETWORK_H
-#define _WIFI_NETWORK_H
-
-#include <sys/types.h>
-
-#include <utils/List.h>
-
-#include "Property.h"
-
-class PropertyManager;
-
-class KeyManagementMask {
-public:
-    static const uint32_t UNKNOWN   = 0;
-    static const uint32_t NONE      = 0x01;
-    static const uint32_t WPA_PSK   = 0x02;
-    static const uint32_t WPA_EAP   = 0x04;
-    static const uint32_t IEEE8021X = 0x08;
-    static const uint32_t ALL       = WPA_PSK | WPA_EAP | IEEE8021X;
-};
-
-class SecurityProtocolMask {
-public:
-    static const uint32_t WPA = 0x01;
-    static const uint32_t RSN = 0x02;
-};
-
-class AuthenticationAlgorithmMask {
-public:
-    static const uint32_t OPEN   = 0x01;
-    static const uint32_t SHARED = 0x02;
-    static const uint32_t LEAP   = 0x04;
-};
-
-class PairwiseCiphersMask {
-public:
-    static const uint32_t NONE = 0x00;
-    static const uint32_t TKIP = 0x01;
-    static const uint32_t CCMP = 0x02;
-};
-
-class GroupCiphersMask {
-public:
-    static const uint32_t WEP40  = 0x01;
-    static const uint32_t WEP104 = 0x02;
-    static const uint32_t TKIP   = 0x04;
-    static const uint32_t CCMP   = 0x08;
-};
-
-class Supplicant;
-class Controller;
-class WifiController;
-
-class WifiNetwork {
-    class WifiNetworkIntegerProperty : public IntegerProperty {
-    protected:
-        WifiNetwork *mWn;
-    public:
-        WifiNetworkIntegerProperty(WifiNetwork *wn, const char *name, bool ro,
-                                   int elements);
-        virtual ~WifiNetworkIntegerProperty() {}
-        virtual int set(int idx, int value) = 0;
-        virtual int get(int idx, int *buffer) = 0;
-    };
-    friend class WifiNetwork::WifiNetworkIntegerProperty;
-
-    class WifiNetworkStringProperty : public StringProperty {
-    protected:
-        WifiNetwork *mWn;
-    public:
-        WifiNetworkStringProperty(WifiNetwork *wn, const char *name, bool ro,
-                                 int elements);
-        virtual ~WifiNetworkStringProperty() {}
-        virtual int set(int idx, const char *value) = 0;
-        virtual int get(int idx, char *buffer, size_t max) = 0;
-    };
-    friend class WifiNetwork::WifiNetworkStringProperty;
-
-    class WifiNetworkEnabledProperty : public WifiNetworkIntegerProperty {
-    public:
-        WifiNetworkEnabledProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkEnabledProperty() {};
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiNetworkPriorityProperty : public WifiNetworkIntegerProperty {
-    public:
-        WifiNetworkPriorityProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkPriorityProperty() {};
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiNetworkDefaultKeyIndexProperty : public WifiNetworkIntegerProperty {
-    public:
-        WifiNetworkDefaultKeyIndexProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkDefaultKeyIndexProperty() {};
-        int set(int idx, int value);
-        int get(int idx, int *buffer);
-    };
-
-    class WifiNetworkSsidProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkSsidProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkSsidProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkBssidProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkBssidProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkBssidProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkPskProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkPskProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkPskProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkKeyManagementProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkKeyManagementProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkKeyManagementProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkAuthAlgorithmsProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkAuthAlgorithmsProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkAuthAlgorithmsProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkProtocolsProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkProtocolsProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkProtocolsProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkWepKeyProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkWepKeyProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkWepKeyProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkPairwiseCiphersProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkPairwiseCiphersProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkPairwiseCiphersProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkGroupCiphersProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkGroupCiphersProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkGroupCiphersProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-    class WifiNetworkHiddenSsidProperty : public WifiNetworkStringProperty {
-    public:
-        WifiNetworkHiddenSsidProperty(WifiNetwork *wn);
-        virtual ~WifiNetworkHiddenSsidProperty() {};
-        int set(int idx, const char *value);
-        int get(int idx, char *buffer, size_t max);
-    };
-
-private:
-    Supplicant *mSuppl;
-    WifiController *mController;
-
-    /*
-     * Unique network id - normally provided by supplicant
-     */
-    int mNetid;
-
-    /*
-     * The networks' SSID. Can either be an ASCII string,
-     * which must be enclosed in double quotation marks
-     * (ie: "MyNetwork"), or a string of hex digits which
-     * are not enclosed in quotes (ie: 01ab7893)
-     */
-    char *mSsid;
-
-    /*
-     * When set, this entry should only be used
-     * when associating with the AP having the specified
-     * BSSID. The value is a string in the format of an
-     * Ethernet MAC address
-     */
-    char *mBssid;
-
-    /*
-     *  Pre-shared key for use with WPA-PSK
-     */
-    char *mPsk;
-
-    /*
-     * Up to four WEP keys. Either in ASCII string enclosed in
-     * double quotes, or a string of hex digits
-     */
-    char *mWepKeys[4];
-
-    /*
-     * Default WEP key index, ranging from 0 -> NUM_WEP_KEYS -1
-     */
-    int mDefaultKeyIndex;
-
-    /*
-     * Priority determines the preference given to a network by 
-     * supplicant when choosing an access point with which
-     * to associate
-     */
-    int mPriority;
-
-    /*
-     * This is a network that does not broadcast it's SSID, so an
-     * SSID-specific probe request must be used for scans.
-     */
-    char *mHiddenSsid;
-
-    /*
-     * The set of key management protocols supported by this configuration.
-     */
-    uint32_t mKeyManagement;
-
-    /*
-     * The set of security protocols supported by this configuration.
-     */
-    uint32_t mProtocols;
-
-    /*
-     * The set of authentication protocols supported by this configuration.
-     */
-    uint32_t mAuthAlgorithms;
-
-    /*
-     * The set of pairwise ciphers for WPA supported by this configuration.
-     */
-    uint32_t mPairwiseCiphers;
-
-    /*
-     * The set of group ciphers for WPA supported by this configuration.
-     */
-    uint32_t mGroupCiphers;
-
-    /*
-     * Set if this Network is enabled
-     */
-    bool mEnabled;
-
-    char *mPropNamespace;
-    struct {
-        WifiNetworkEnabledProperty               *propEnabled;
-        WifiNetworkSsidProperty                  *propSsid;
-        WifiNetworkBssidProperty                 *propBssid;
-        WifiNetworkPskProperty                   *propPsk;
-        WifiNetworkWepKeyProperty                *propWepKey;
-        WifiNetworkDefaultKeyIndexProperty       *propDefKeyIdx;
-        WifiNetworkPriorityProperty              *propPriority;
-        WifiNetworkKeyManagementProperty  *propKeyManagement;
-        WifiNetworkProtocolsProperty      *propProtocols;
-        WifiNetworkAuthAlgorithmsProperty *propAuthAlgorithms;
-        WifiNetworkPairwiseCiphersProperty       *propPairwiseCiphers;
-        WifiNetworkGroupCiphersProperty          *propGroupCiphers;
-        WifiNetworkHiddenSsidProperty            *propHiddenSsid;
-    } mStaticProperties;
-private:
-    WifiNetwork();
-
-public:
-    WifiNetwork(WifiController *c, Supplicant *suppl, int networkId);
-    WifiNetwork(WifiController *c, Supplicant *suppl, const char *data);
-
-    virtual ~WifiNetwork();
-
-    WifiNetwork *clone();
-    int attachProperties(PropertyManager *pm, const char *nsName);
-    int detachProperties(PropertyManager *pm, const char *nsName);
-
-    int getNetworkId() { return mNetid; }
-    const char *getSsid() { return mSsid; }
-    const char *getBssid() { return mBssid; }
-    const char *getPsk() { return mPsk; }
-    const char *getWepKey(int idx) { return mWepKeys[idx]; }
-    int getDefaultKeyIndex() { return mDefaultKeyIndex; }
-    int getPriority() { return mPriority; }
-    const char *getHiddenSsid() { return mHiddenSsid; }
-    uint32_t getKeyManagement() { return mKeyManagement; }
-    uint32_t getProtocols() { return mProtocols; }
-    uint32_t getAuthAlgorithms() { return mAuthAlgorithms; }
-    uint32_t getPairwiseCiphers() { return mPairwiseCiphers; }
-    uint32_t getGroupCiphers() { return mGroupCiphers; }
-    bool getEnabled() { return mEnabled; }
-    Controller *getController() { return (Controller *) mController; }
-
-    int setEnabled(bool enabled);
-    int setSsid(const char *ssid);
-    int setBssid(const char *bssid);
-    int setPsk(const char *psk);
-    int setWepKey(int idx, const char *key);
-    int setDefaultKeyIndex(int idx);
-    int setPriority(int pri);
-    int setHiddenSsid(const char *ssid);
-    int setKeyManagement(uint32_t mask);
-    int setProtocols(uint32_t mask);
-    int setAuthAlgorithms(uint32_t mask);
-    int setPairwiseCiphers(uint32_t mask);
-    int setGroupCiphers(uint32_t mask);
-
-    // XXX:Should this really be exposed?.. meh
-    int refresh();
-
-private:
-    int parseKeyManagementMask(const char *buffer, uint32_t *mask);
-    int parseProtocolsMask(const char *buffer, uint32_t *mask);
-    int parseAuthAlgorithmsMask(const char *buffer, uint32_t *mask);
-    int parsePairwiseCiphersMask(const char *buffer, uint32_t *mask);
-    int parseGroupCiphersMask(const char *buffer, uint32_t *mask);
-    void createProperties();
-};
-
-typedef android::List<WifiNetwork *> WifiNetworkCollection;
-
-#endif
diff --git a/nexus/WifiScanner.cpp b/nexus/WifiScanner.cpp
deleted file mode 100644
index bdfa497..0000000
--- a/nexus/WifiScanner.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <errno.h>
-#include <pthread.h>
-
-#define LOG_TAG "WifiScanner"
-#include <cutils/log.h>
-
-#include "WifiScanner.h"
-#include "Supplicant.h"
-
-extern "C" int pthread_cancel(pthread_t thread);
-
-WifiScanner::WifiScanner(Supplicant *suppl, int period) {
-    mSuppl = suppl;
-    mPeriod = period;
-    mActive = false;
-}
-
-int WifiScanner::start(bool active) {
-    mActive = active;
-
-    if(pipe(mCtrlPipe))
-        return -1;
-
-    if (pthread_create(&mThread, NULL, WifiScanner::threadStart, this))
-        return -1;
-    return 0;
-}
-
-void *WifiScanner::threadStart(void *obj) {
-    WifiScanner *me = reinterpret_cast<WifiScanner *>(obj);
-    me->run();
-    pthread_exit(NULL);
-    return NULL;
-}
-
-int WifiScanner::stop() {
-    char c = 0;
-
-    if (write(mCtrlPipe[1], &c, 1) != 1) {
-        LOGE("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));
-        return -1;
-    }
-
-    close(mCtrlPipe[0]);
-    close(mCtrlPipe[1]);
-    return 0;
-}
-
-void WifiScanner::run() {
-    LOGD("Starting wifi scanner (active = %d)", mActive);
-
-    while(1) {
-        fd_set read_fds;
-        struct timeval to;
-        int rc = 0;
-
-        to.tv_usec = 0;
-        to.tv_sec = mPeriod;
-
-        FD_ZERO(&read_fds);
-        FD_SET(mCtrlPipe[0], &read_fds);
-
-        if (mSuppl->triggerScan(mActive)) {
-            LOGW("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));
-            sleep(mPeriod);
-            continue;
-        } else if (!rc) {
-        } else if (FD_ISSET(mCtrlPipe[0], &read_fds))
-            break;
-    } // while
-    LOGD("Stopping wifi scanner");
-}
diff --git a/nexus/WifiScanner.h b/nexus/WifiScanner.h
deleted file mode 100644
index 92822e9..0000000
--- a/nexus/WifiScanner.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _WIFISCANNER_H
-#define _WIFISCANNER_H
-
-#include <pthread.h>
-
-class Supplicant;
-
-class WifiScanner {
-    pthread_t  mThread;
-    int        mCtrlPipe[2];
-    Supplicant *mSuppl;
-    int        mPeriod;
-    bool       mActive;
-    
-
-public:
-    WifiScanner(Supplicant *suppl, int period);
-    virtual ~WifiScanner() {}
-
-    int getPeriod() { return mPeriod; }
-
-    int start(bool active);
-    int stop();
-
-private:
-    static void *threadStart(void *obj);
-
-    void run();
-};
-
-#endif
diff --git a/nexus/WifiStatusPoller.cpp b/nexus/WifiStatusPoller.cpp
deleted file mode 100644
index cf71733..0000000
--- a/nexus/WifiStatusPoller.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <stdio.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <sys/un.h>
-
-#define LOG_TAG "WifiStatusPoller"
-#include <cutils/log.h>
-
-#include "WifiStatusPoller.h"
-#include "IWifiStatusPollerHandler.h"
-
-
-WifiStatusPoller::WifiStatusPoller(IWifiStatusPollerHandler *handler) :
-                  mHandlers(handler) {
-    mPollingInterval = 5;
-    mStarted = false;
-}
-
-int WifiStatusPoller::start() {
-
-    if (pipe(mCtrlPipe))
-        return -1;
-
-    if (pthread_create(&mThread, NULL, WifiStatusPoller::threadStart, this))
-        return -1;
-
-    return 0;
-}
-
-int WifiStatusPoller::stop() {
-    char c = 0;
-
-    if (write(mCtrlPipe[1], &c, 1) != 1) {
-        LOGE("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));
-        return -1;
-    }
-    close(mCtrlPipe[0]);
-    close(mCtrlPipe[1]);
-    return 0;
-}
-
-void *WifiStatusPoller::threadStart(void *obj) {
-    WifiStatusPoller *me = reinterpret_cast<WifiStatusPoller *>(obj);
-
-    me->mStarted = true;
-    LOGD("Starting");
-    me->run();
-    me->mStarted = false;
-    LOGD("Stopping");
-    pthread_exit(NULL);
-    return NULL;
-}
-
-void WifiStatusPoller::run() {
-
-    while(1) {
-        struct timeval to;
-        fd_set read_fds;
-        int rc = 0;
-        int max = 0;
-
-        FD_ZERO(&read_fds);
-        to.tv_usec = 0;
-        to.tv_sec = mPollingInterval;
-
-        FD_SET(mCtrlPipe[0], &read_fds);
-        max = mCtrlPipe[0];
-
-        if ((rc = select(max + 1, &read_fds, NULL, NULL, &to)) < 0) {
-            LOGE("select failed (%s)", strerror(errno));
-            sleep(1);
-            continue;
-        } else if (!rc) {
-            mHandlers->onStatusPollInterval();
-        }
-        if (FD_ISSET(mCtrlPipe[0], &read_fds))
-            break;
-    }
-}
diff --git a/nexus/WifiStatusPoller.h b/nexus/WifiStatusPoller.h
deleted file mode 100644
index 202bbbf..0000000
--- a/nexus/WifiStatusPoller.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _WIFI_STATUS_POLLER_H
-#define _WIFI_STATUS_POLLER_H
-
-#include <pthread.h>
-
-class IWifiStatusPollerHandler;
-
-class WifiStatusPoller {
-    pthread_t                mThread;
-    int                      mCtrlPipe[2];
-    int                      mPollingInterval;
-    IWifiStatusPollerHandler *mHandlers;
-    bool                     mStarted;
-
-public:
-    WifiStatusPoller(IWifiStatusPollerHandler *handler);
-    virtual ~WifiStatusPoller() {}
-
-    int start();
-    int stop();
-    bool isStarted() { return mStarted; }
-
-    void setPollingInterval(int interval);
-    int getPollingInterval() { return mPollingInterval; }
-    
-private:
-    static void *threadStart(void *obj);
-    void run();
-};
-
-#endif
diff --git a/nexus/main.cpp b/nexus/main.cpp
deleted file mode 100644
index 936d33f..0000000
--- a/nexus/main.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <errno.h>
-
-#define LOG_TAG "Nexus"
-
-#include "cutils/log.h"
-#include "NetworkManager.h"
-#include "CommandListener.h"
-
-#include "LoopController.h"
-#include "OpenVpnController.h"
-#include "TiwlanWifiController.h"
-
-int main() {
-    LOGI("Nexus version 0.1 firing up");
-
-    CommandListener *cl = new CommandListener();
-
-    NetworkManager *nm;
-    if (!(nm = NetworkManager::Instance())) {
-        LOGE("Unable to create NetworkManager");
-        exit (-1);
-    };
-
-    nm->setBroadcaster((SocketListener *) cl);
-
-    nm->attachController(new LoopController(nm->getPropMngr(), nm));
-    nm->attachController(new TiwlanWifiController(nm->getPropMngr(), nm, "/system/lib/modules/wlan.ko", "wlan", ""));
-//    nm->attachController(new AndroidL2TPVpnController(nm->getPropMngr(), nm));
-    nm->attachController(new OpenVpnController(nm->getPropMngr(), nm));
-
-
-    if (NetworkManager::Instance()->run()) {
-        LOGE("Unable to Run NetworkManager (%s)", strerror(errno));
-        exit (1);
-    }
-
-    if (cl->startListener()) {
-        LOGE("Unable to start CommandListener (%s)", strerror(errno));
-        exit (1);
-    }
-
-    // XXX: we'll use the main thread for the NetworkManager eventually
-
-    while(1) {
-        sleep(1000);
-    }
-
-    LOGI("Nexus exiting");
-    exit(0);
-}
diff --git a/nexus/nexctl.c b/nexus/nexctl.c
deleted file mode 100644
index 8e1d90c..0000000
--- a/nexus/nexctl.c
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <string.h>
-#include <signal.h>
-#include <errno.h>
-#include <fcntl.h>
-
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <sys/un.h>
-
-#include <cutils/sockets.h>
-#include <private/android_filesystem_config.h>
-
-static void usage(char *progname);
-static int do_monitor(int sock, int stop_after_cmd);
-static int do_cmd(int sock, int argc, char **argv);
-
-int main(int argc, char **argv) {
-    int sock;
-
-    if (argc < 2)
-        usage(argv[0]);
-
-    if ((sock = socket_local_client("nexus",
-                                     ANDROID_SOCKET_NAMESPACE_RESERVED,
-                                     SOCK_STREAM)) < 0) {
-        fprintf(stderr, "Error connecting (%s)\n", strerror(errno));
-        exit(4);
-    }
-
-    if (!strcmp(argv[1], "monitor"))
-        exit(do_monitor(sock, 0));
-    exit(do_cmd(sock, argc, argv));
-}
-
-static int do_cmd(int sock, int argc, char **argv) {
-    char final_cmd[255] = { '\0' };
-    int i;
-
-    for (i = 1; i < argc; i++) {
-        char *cmp;
-
-        if (!index(argv[i], ' '))
-            asprintf(&cmp, "%s%s", argv[i], (i == (argc -1)) ? "" : " ");
-        else
-            asprintf(&cmp, "\"%s\"%s", argv[i], (i == (argc -1)) ? "" : " ");
-
-        strcat(final_cmd, cmp);
-        free(cmp);
-    }
-
-    if (write(sock, final_cmd, strlen(final_cmd) + 1) < 0) {
-        perror("write");
-        return errno;
-    }
-
-    return do_monitor(sock, 1);
-}
-
-static int do_monitor(int sock, int stop_after_cmd) {
-    char *buffer = malloc(4096);
-
-    if (!stop_after_cmd)
-        printf("[Connected to Nexus]\n");
-
-    while(1) {
-        fd_set read_fds;
-        struct timeval to;
-        int rc = 0;
-
-        to.tv_sec = 10;
-        to.tv_usec = 0;
-
-        FD_ZERO(&read_fds);
-        FD_SET(sock, &read_fds);
-
-        if ((rc = select(sock +1, &read_fds, NULL, NULL, &to)) < 0) {
-            fprintf(stderr, "Error in select (%s)\n", strerror(errno));
-            free(buffer);
-            return errno;
-        } else if (!rc) {
-            continue;
-            fprintf(stderr, "[TIMEOUT]\n");
-            return ETIMEDOUT;
-        } else if (FD_ISSET(sock, &read_fds)) {
-            memset(buffer, 0, 4096);
-            if ((rc = read(sock, buffer, 4096)) <= 0) {
-                if (rc == 0)
-                    fprintf(stderr, "Lost connection to Nexus - did it crash?\n");
-                else
-                    fprintf(stderr, "Error reading data (%s)\n", strerror(errno));
-                free(buffer);
-                if (rc == 0)
-                    return ECONNRESET;
-                return errno;
-            }
-            
-            int offset = 0;
-            int i = 0;
-
-            for (i = 0; i < rc; i++) {
-                if (buffer[i] == '\0') {
-                    int code;
-                    char tmp[4];
-
-                    strncpy(tmp, buffer + offset, 3);
-                    tmp[3] = '\0';
-                    code = atoi(tmp);
-
-                    printf("%s\n", buffer + offset);
-                    if (stop_after_cmd) {
-                        if (code >= 200 && code < 600)
-                            return 0;
-                    }
-                    offset = i + 1;
-                }
-            }
-        }
-    }
-    free(buffer);
-    return 0;
-}
-
-static void usage(char *progname) {
-    fprintf(stderr, "Usage: %s <monitor>|<cmd> [arg1] [arg2...]\n", progname);
-    exit(1);
-}
-
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index 1a9e06f..e62c3ea 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -50,6 +50,8 @@
 ALL_PREBUILT += $(file)
 $(INSTALLED_RAMDISK_TARGET): $(file)
 
+# init.usb.rc is handled by build/target/product/core.rc
+
 # Just like /system/etc/init.goldfish.sh, the /init.godlfish.rc is here
 # to allow -user builds to properly run the dex pre-optimization pass in
 # the emulator.
diff --git a/rootdir/init.rc b/rootdir/init.rc
index a9541e7..2305572 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -1,3 +1,12 @@
+# Copyright (C) 2012 The Android Open Source Project
+#
+# IMPORTANT: Do not create world writable files or directories.
+# This is a common source of Android security bugs.
+#
+
+import /init.${ro.hardware}.rc
+import /init.usb.rc
+
 on early-init
     # Set init and its forked children's oom_adj.
     write /proc/1/oom_adj -16
@@ -22,7 +31,7 @@
     export ANDROID_DATA /data
     export ASEC_MOUNTPOINT /mnt/asec
     export LOOP_MOUNTPOINT /mnt/obb
-    export BOOTCLASSPATH /system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar:/system/framework/filterfw.jar
+    export BOOTCLASSPATH /system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar
 
 # Backward compatibility
     symlink /system/etc /etc
@@ -68,25 +77,36 @@
     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
+    write /proc/sys/kernel/sched_rt_runtime_us 950000
+    write /proc/sys/kernel/sched_rt_period_us 1000000
 
 # Create cgroup mount points for process groups
     mkdir /dev/cpuctl
     mount cgroup none /dev/cpuctl cpu
     chown system system /dev/cpuctl
     chown system system /dev/cpuctl/tasks
-    chmod 0777 /dev/cpuctl/tasks
+    chmod 0660 /dev/cpuctl/tasks
     write /dev/cpuctl/cpu.shares 1024
+    write /dev/cpuctl/cpu.rt_runtime_us 950000
+    write /dev/cpuctl/cpu.rt_period_us 1000000
 
-    mkdir /dev/cpuctl/fg_boost
-    chown system system /dev/cpuctl/fg_boost/tasks
-    chmod 0777 /dev/cpuctl/fg_boost/tasks
-    write /dev/cpuctl/fg_boost/cpu.shares 1024
+    mkdir /dev/cpuctl/apps
+    chown system system /dev/cpuctl/apps/tasks
+    chmod 0666 /dev/cpuctl/apps/tasks
+    write /dev/cpuctl/apps/cpu.shares 1024
+    write /dev/cpuctl/apps/cpu.rt_runtime_us 800000
+    write /dev/cpuctl/apps/cpu.rt_period_us 1000000
 
-    mkdir /dev/cpuctl/bg_non_interactive
-    chown system system /dev/cpuctl/bg_non_interactive/tasks
-    chmod 0777 /dev/cpuctl/bg_non_interactive/tasks
+    mkdir /dev/cpuctl/apps/bg_non_interactive
+    chown system system /dev/cpuctl/apps/bg_non_interactive/tasks
+    chmod 0666 /dev/cpuctl/apps/bg_non_interactive/tasks
     # 5.0 %
-    write /dev/cpuctl/bg_non_interactive/cpu.shares 52
+    write /dev/cpuctl/apps/bg_non_interactive/cpu.shares 52
+    write /dev/cpuctl/apps/bg_non_interactive/cpu.rt_runtime_us 700000
+    write /dev/cpuctl/apps/bg_non_interactive/cpu.rt_period_us 1000000
 
 # Allow everybody to read the xt_qtaguid resource tracking misc dev.
 # This is needed by any process that uses socket tagging.
@@ -158,9 +178,13 @@
     mkdir /data/misc/wifi 0770 wifi wifi
     chmod 0660 /data/misc/wifi/wpa_supplicant.conf
     mkdir /data/local 0751 root root
+
+    # For security reasons, /data/local/tmp should always be empty.
+    # Do not place files or directories in /data/local/tmp
     mkdir /data/local/tmp 0771 shell shell
     mkdir /data/data 0771 system system
     mkdir /data/app-private 0771 system system
+    mkdir /data/app-asec 0700 root root
     mkdir /data/app 0771 system system
     mkdir /data/property 0700 root root
     mkdir /data/ssh 0750 root shell
@@ -187,11 +211,6 @@
     # Set indication (checked by vold) that we have finished this action
     #setprop vold.post_fs_data_done 1
 
-    chown system system /sys/class/android_usb/android0/f_mass_storage/lun/file
-    chmod 0660 /sys/class/android_usb/android0/f_mass_storage/lun/file
-    chown system system /sys/class/android_usb/android0/f_rndis/ethaddr
-    chmod 0660 /sys/class/android_usb/android0/f_rndis/ethaddr
-
 on boot
 # basic network init
     ifup lo
@@ -203,7 +222,7 @@
 
 # Memory management.  Basic kernel parameters, and allow the high
 # level system server to be able to adjust the kernel OOM driver
-# paramters to match how it is managing things.
+# parameters to match how it is managing things.
     write /proc/sys/vm/overcommit_memory 1
     write /proc/sys/vm/min_free_order_shift 4
     chown root system /sys/module/lowmemorykiller/parameters/adj
@@ -221,12 +240,34 @@
     chown radio system /sys/android_power/acquire_full_wake_lock
     chown radio system /sys/android_power/acquire_partial_wake_lock
     chown radio system /sys/android_power/release_wake_lock
-    chown radio system /sys/power/state
+    chown system system /sys/power/state
+    chown system system /sys/power/wakeup_count
     chown radio system /sys/power/wake_lock
     chown radio system /sys/power/wake_unlock
     chmod 0660 /sys/power/state
     chmod 0660 /sys/power/wake_lock
     chmod 0660 /sys/power/wake_unlock
+
+    chown system system /sys/devices/system/cpu/cpufreq/interactive/timer_rate
+    chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/timer_rate
+    chown system system /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
+    chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
+    chown system system /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
+    chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
+    chown system system /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
+    chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
+    chown system system /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
+    chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
+    chown system system /sys/devices/system/cpu/cpufreq/interactive/boost
+    chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/boost
+    chown system system /sys/devices/system/cpu/cpufreq/interactive/boostpulse
+    chown system system /sys/devices/system/cpu/cpufreq/interactive/input_boost
+    chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/input_boost
+
+    # Assume SMP uses shared cpufreq policy for all CPUs
+    chown system system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
+    chmod 0660 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
+
     chown system system /sys/class/timed_output/vibrator/enable
     chown system system /sys/class/leds/keyboard-backlight/brightness
     chown system system /sys/class/leds/lcd-backlight/brightness
@@ -296,49 +337,6 @@
     class_reset late_start
     class_reset main
 
-# Used to disable USB when switching states
-on property:sys.usb.config=none
-    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
-
-# adb only USB configuration
-# This should only be used during device bringup
-# and as a fallback if the USB manager fails to set a standard configuration
-on property:sys.usb.config=adb
-    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/enable 1
-    start adbd
-    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/enable 1
-    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/enable 1
-    start adbd
-    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
-
 ## Daemon processes to be run by init.
 ##
 service ueventd /sbin/ueventd
@@ -355,6 +353,10 @@
 on property:ro.debuggable=1
     start console
 
+# Allow writing to the kernel trace log.  Enabling tracing still requires root.
+on property:ro.debuggable=1
+    chmod 0222 /sys/kernel/debug/tracing/trace_marker
+
 # adbd is controlled via property triggers in init.<platform>.usb.rc
 service adbd /sbin/adbd
     class core
@@ -364,18 +366,6 @@
 on property:ro.kernel.qemu=1
     start adbd
 
-# This property trigger has added to imitiate the previous behavior of "adb root".
-# The adb gadget driver used to reset the USB bus when the adbd daemon exited,
-# and the host side adb relied on this behavior to force it to reconnect with the
-# new adbd instance after init relaunches it. So now we force the USB bus to reset
-# here when adbd sets the service.adb.root property to 1.  We also restart adbd here
-# rather than waiting for init to notice its death and restarting it so the timing
-# of USB resetting and adb restarting more closely matches the previous behavior.
-on property:service.adb.root=1
-    write /sys/class/android_usb/android0/enable 0
-    restart adbd
-    write /sys/class/android_usb/android0/enable 1
-
 service servicemanager /system/bin/servicemanager
     class core
     user system
@@ -395,6 +385,7 @@
     class main
     socket netd stream 0660 root system
     socket dnsproxyd stream 0660 root inet
+    socket mdns stream 0660 root system
 
 service debuggerd /system/bin/debuggerd
     class main
@@ -414,7 +405,7 @@
 
 service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
     class main
-    socket zygote stream 666
+    socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
     onrestart restart media
@@ -423,7 +414,7 @@
 service drm /system/bin/drmserver
     class main
     user drm
-    group system inet drmrpc
+    group drm system inet drmrpc sdcard_r
 
 service media /system/bin/mediaserver
     class main
@@ -480,7 +471,7 @@
 service keystore /system/bin/keystore /data/misc/keystore
     class main
     user keystore
-    group keystore
+    group keystore drmrpc
     socket keystore stream 666
 
 service dumpstate /system/bin/dumpstate -s
@@ -491,3 +482,13 @@
 
 service sshd /system/bin/start-ssh
     class main
+    disabled
+
+service mdnsd /system/bin/mdnsd
+    class main
+    user mdnsr
+    group inet net_raw
+    socket mdnsd stream 0660 mdnsr inet
+    disabled
+    oneshot
+
diff --git a/rootdir/init.usb.rc b/rootdir/init.usb.rc
new file mode 100644
index 0000000..15467cc
--- /dev/null
+++ b/rootdir/init.usb.rc
@@ -0,0 +1,91 @@
+# Copyright (C) 2012 The Android Open Source Project
+#
+# USB configuration common for all android devices
+#
+
+on post-fs-data
+    chown system system /sys/class/android_usb/android0/f_mass_storage/lun/file
+    chmod 0660 /sys/class/android_usb/android0/f_mass_storage/lun/file
+    chown system system /sys/class/android_usb/android0/f_rndis/ethaddr
+    chmod 0660 /sys/class/android_usb/android0/f_rndis/ethaddr
+
+# Used to disable USB when switching states
+on property:sys.usb.config=none
+    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}
+
+# adb only USB configuration
+# This should only be used during device bringup
+# and as a fallback if the USB manager fails to set a standard configuration
+on property:sys.usb.config=adb
+    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/enable 1
+    start adbd
+    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/enable 1
+    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/enable 1
+    start adbd
+    setprop sys.usb.state ${sys.usb.config}
+
+# audio accessory configuration
+on property:sys.usb.config=audio_source
+    write /sys/class/android_usb/android0/enable 0
+    write /sys/class/android_usb/android0/idVendor 18d1
+    write /sys/class/android_usb/android0/idProduct 2d02
+    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}
+
+# audio accessory configuration, with adb
+on property:sys.usb.config=audio_source,adb
+    write /sys/class/android_usb/android0/enable 0
+    write /sys/class/android_usb/android0/idVendor 18d1
+    write /sys/class/android_usb/android0/idProduct 2d03
+    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}
+
+# USB and audio accessory configuration
+on property:sys.usb.config=accessory,audio_source
+    write /sys/class/android_usb/android0/enable 0
+    write /sys/class/android_usb/android0/idVendor 18d1
+    write /sys/class/android_usb/android0/idProduct 2d04
+    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}
+
+# USB and audio accessory configuration, with adb
+on property:sys.usb.config=accessory,audio_source,adb
+    write /sys/class/android_usb/android0/enable 0
+    write /sys/class/android_usb/android0/idVendor 18d1
+    write /sys/class/android_usb/android0/idProduct 2d05
+    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}
+
+# 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}
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index 438cf0a..07624c4 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -8,8 +8,9 @@
 /dev/ashmem               0666   root       root
 /dev/binder               0666   root       root
 
-# logger should be world writable (for logging) but not readable
-/dev/log/*                0662   root       log
+# Anyone can read the logs, but if they're not in the "logs"
+# group, then they'll only see log entries for their UID.
+/dev/log/*                0666   root       log
 
 # the msm hw3d client device node is world writable/readable.
 /dev/msm_hw3dc            0666   root       root
diff --git a/run-as/Android.mk b/run-as/Android.mk
index 326f5af..043cc3a 100644
--- a/run-as/Android.mk
+++ b/run-as/Android.mk
@@ -5,8 +5,4 @@
 
 LOCAL_MODULE:= run-as
 
-LOCAL_FORCE_STATIC_EXECUTABLE := true
-
-LOCAL_STATIC_LIBRARIES := libc
-
 include $(BUILD_EXECUTABLE)
diff --git a/run-as/package.c b/run-as/package.c
index ca08436..143d647 100644
--- a/run-as/package.c
+++ b/run-as/package.c
@@ -18,6 +18,7 @@
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/stat.h>
+#include <sys/mman.h>
 #include <private/android_filesystem_config.h>
 #include "package.h"
 
@@ -43,9 +44,6 @@
 /* The file containing the list of installed packages on the system */
 #define PACKAGES_LIST_FILE  "/data/system/packages.list"
 
-/* This should be large enough to hold the content of the package database file */
-#define PACKAGES_LIST_BUFFER_SIZE  65536
-
 /* Copy 'srclen' string bytes from 'src' into buffer 'dst' of size 'dstlen'
  * This function always zero-terminate the destination buffer unless
  * 'dstlen' is 0, even in case of overflow.
@@ -67,40 +65,73 @@
     *dst = '\0'; /* zero-terminate result */
 }
 
-/* Read up to 'buffsize' bytes into 'buff' from the file
- * named 'filename'. Return byte length on success, or -1
- * on error.
+/* Open 'filename' and map it into our address-space.
+ * Returns buffer address, or NULL on error
+ * On exit, *filesize will be set to the file's size, or 0 on error
  */
-static int
-read_file(const char* filename, char* buff, size_t buffsize)
+static void*
+map_file(const char* filename, size_t* filesize)
 {
-    int  fd, len, old_errno;
+    int  fd, ret, old_errno;
+    struct stat  st;
+    size_t  length = 0;
+    void*   address = NULL;
 
-    /* check the input buffer size */
-    if (buffsize >= INT_MAX) {
-        errno = EINVAL;
-        return -1;
-    }
+    *filesize = 0;
 
     /* open the file for reading */
-    do {
-        fd = open(filename, O_RDONLY);
-    } while (fd < 0 && errno == EINTR);
-
+    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
     if (fd < 0)
-        return -1;
+        return NULL;
 
-    /* read the content */
-    do {
-        len = read(fd, buff, buffsize);
-    } while (len < 0 && errno == EINTR);
+    /* get its size */
+    ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
+    if (ret < 0)
+        goto EXIT;
 
+    /* Ensure that the file is owned by the system user */
+    if ((st.st_uid != AID_SYSTEM) || (st.st_gid != AID_SYSTEM)) {
+        goto EXIT;
+    }
+
+    /* Ensure that the file has sane permissions */
+    if ((st.st_mode & S_IWOTH) != 0) {
+        goto EXIT;
+    }
+
+    /* Ensure that the size is not ridiculously large */
+    length = (size_t)st.st_size;
+    if ((off_t)length != st.st_size) {
+        errno = ENOMEM;
+        goto EXIT;
+    }
+
+    /* Memory-map the file now */
+    address = TEMP_FAILURE_RETRY(mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0));
+    if (address == MAP_FAILED) {
+        address = NULL;
+        goto EXIT;
+    }
+
+    /* We're good, return size */
+    *filesize = length;
+
+EXIT:
     /* close the file, preserve old errno for better diagnostics */
     old_errno = errno;
     close(fd);
     errno = old_errno;
 
-    return len;
+    return address;
+}
+
+/* unmap the file, but preserve errno */
+static void
+unmap_file(void*  address, size_t  size)
+{
+    int old_errno = errno;
+    TEMP_FAILURE_RETRY(munmap(address, size));
+    errno = old_errno;
 }
 
 /* Check that a given directory:
@@ -371,18 +402,18 @@
 int
 get_package_info(const char* pkgName, PackageInfo *info)
 {
-    static char  buffer[PACKAGES_LIST_BUFFER_SIZE];
-    int          buffer_len;
+    char*        buffer;
+    size_t       buffer_len;
     const char*  p;
     const char*  buffer_end;
-    int          result;
+    int          result = -1;
 
     info->uid          = 0;
     info->isDebuggable = 0;
     info->dataDir[0]   = '\0';
 
-    buffer_len = read_file(PACKAGES_LIST_FILE, buffer, sizeof buffer);
-    if (buffer_len < 0)
+    buffer = map_file(PACKAGES_LIST_FILE, &buffer_len);
+    if (buffer == NULL)
         return -1;
 
     p          = buffer;
@@ -455,7 +486,8 @@
         string_copy(info->dataDir, sizeof info->dataDir, p, q - p);
 
         /* Ignore the rest */
-        return 0;
+        result = 0;
+        goto EXIT;
 
     NEXT_LINE:
         p = next;
@@ -463,9 +495,14 @@
 
     /* the package is unknown */
     errno = ENOENT;
-    return -1;
+    result = -1;
+    goto EXIT;
 
 BAD_FORMAT:
     errno = EINVAL;
-    return -1;
+    result = -1;
+
+EXIT:
+    unmap_file(buffer, buffer_len);
+    return result;
 }
diff --git a/run-as/run-as.c b/run-as/run-as.c
index d2a44e1..20e1530 100644
--- a/run-as/run-as.c
+++ b/run-as/run-as.c
@@ -41,9 +41,9 @@
  *
  *  - This program should only run for the 'root' or 'shell' users
  *
- *  - Statically link against the C library, and avoid anything that
- *    is more complex than simple system calls until the uid/gid has
- *    been dropped to that of a normal user or you are sure to exit.
+ *  - Avoid anything that is more complex than simple system calls
+ *    until the uid/gid has been dropped to that of a normal user
+ *    or you are sure to exit.
  *
  *    This avoids depending on environment variables, system properties
  *    and other external factors that may affect the C library in
diff --git a/sdcard/Android.mk b/sdcard/Android.mk
index c430ac8..fb04d6d 100644
--- a/sdcard/Android.mk
+++ b/sdcard/Android.mk
@@ -4,6 +4,7 @@
 
 LOCAL_SRC_FILES:= sdcard.c
 LOCAL_MODULE:= sdcard
+LOCAL_CFLAGS := -Wall -Wno-unused-parameter
 
 LOCAL_SHARED_LIBRARIES := libc
 
diff --git a/sdcard/sdcard.c b/sdcard/sdcard.c
index 689cd2a..316588c 100644
--- a/sdcard/sdcard.c
+++ b/sdcard/sdcard.c
@@ -25,7 +25,9 @@
 #include <sys/statfs.h>
 #include <sys/uio.h>
 #include <dirent.h>
+#include <limits.h>
 #include <ctype.h>
+#include <pthread.h>
 
 #include <private/android_filesystem_config.h>
 
@@ -43,7 +45,7 @@
  * usage:  sdcard <path> <uid> <gid>
  *
  * It must be run as root, but will change to uid/gid as soon as it
- * mounts a filesystem on /mnt/sdcard.  It will refuse to run if uid or
+ * mounts a filesystem on /storage/sdcard.  It will refuse to run if uid or
  * gid are zero.
  *
  *
@@ -70,30 +72,44 @@
 
 #define FUSE_UNKNOWN_INO 0xffffffff
 
-#define MOUNT_POINT "/mnt/sdcard"
+#define MOUNT_POINT "/storage/sdcard0"
+
+/* Maximum number of bytes to write in one request. */
+#define MAX_WRITE (256 * 1024)
+
+/* Maximum number of bytes to read in one request. */
+#define MAX_READ (128 * 1024)
+
+/* Largest possible request.
+ * The request size is bounded by the maximum size of a FUSE_WRITE request because it has
+ * the largest possible data payload. */
+#define MAX_REQUEST_SIZE (sizeof(struct fuse_in_header) + sizeof(struct fuse_write_in) + MAX_WRITE)
+
+/* Default number of threads. */
+#define DEFAULT_NUM_THREADS 2
+
+/* Pseudo-error constant used to indicate that no fuse status is needed
+ * or that a reply has already been written. */
+#define NO_STATUS 1
 
 struct handle {
-    struct node *node;
     int fd;
 };
 
 struct dirhandle {
-    struct node *node;
     DIR *d;
 };
 
 struct node {
+    __u32 refcount;
     __u64 nid;
     __u64 gen;
 
     struct node *next;          /* per-dir sibling list */
     struct node *child;         /* first contained file by this dir */
-    struct node *all;           /* global node list */
     struct node *parent;        /* containing directory */
 
-    __u32 refcount;
-    __u32 namelen;
-
+    size_t namelen;
     char *name;
     /* If non-null, this is the real name of the file in the underlying storage.
      * This may differ from the field "name" only by case.
@@ -103,98 +119,166 @@
     char *actual_name;
 };
 
+/* Global data structure shared by all fuse handlers. */
 struct fuse {
+    pthread_mutex_t lock;
+
     __u64 next_generation;
-    __u64 next_node_id;
-
     int fd;
-
-    struct node *all;
-
     struct node root;
-    char rootpath[1024];
+    char rootpath[PATH_MAX];
 };
 
-static unsigned uid = -1;
-static unsigned gid = -1;
+/* Private data used by a single fuse handler. */
+struct fuse_handler {
+    struct fuse* fuse;
+    int token;
 
-#define PATH_BUFFER_SIZE 1024
+    /* To save memory, we never use the contents of the request buffer and the read
+     * buffer at the same time.  This allows us to share the underlying storage. */
+    union {
+        __u8 request_buffer[MAX_REQUEST_SIZE];
+        __u8 read_buffer[MAX_READ];
+    };
+};
 
-#define NO_CASE_SENSITIVE_MATCH 0
-#define CASE_SENSITIVE_MATCH 1
-
-/*
- * Get the real-life absolute path to a node.
- *   node: start at this node
- *   buf: storage for returned string
- *   name: append this string to path if set
- */
-char *do_node_get_path(struct node *node, char *buf, const char *name, int match_case_insensitive)
+static inline void *id_to_ptr(__u64 nid)
 {
-    struct node *in_node = node;
-    const char *in_name = name;
-    char *out = buf + PATH_BUFFER_SIZE - 1;
-    int len;
-    out[0] = 0;
+    return (void *) (uintptr_t) nid;
+}
 
-    if (name) {
-        len = strlen(name);
-        goto start;
-    }
+static inline __u64 ptr_to_id(void *ptr)
+{
+    return (__u64) (uintptr_t) ptr;
+}
 
-    while (node) {
-        name = (node->actual_name ? node->actual_name : node->name);
-        len = node->namelen;
-        node = node->parent;
-    start:
-        if ((len + 1) > (out - buf))
-            return 0;
-        out -= len;
-        memcpy(out, name, len);
-        /* avoid double slash at beginning of path */
-        if (out[0] != '/') {
-            out --;
-            out[0] = '/';
+static void acquire_node_locked(struct node* node)
+{
+    node->refcount++;
+    TRACE("ACQUIRE %p (%s) rc=%d\n", node, node->name, node->refcount);
+}
+
+static void remove_node_from_parent_locked(struct node* node);
+
+static void release_node_locked(struct node* node)
+{
+    TRACE("RELEASE %p (%s) rc=%d\n", node, node->name, node->refcount);
+    if (node->refcount > 0) {
+        node->refcount--;
+        if (!node->refcount) {
+            TRACE("DESTROY %p (%s)\n", node, node->name);
+            remove_node_from_parent_locked(node);
+
+                /* TODO: remove debugging - poison memory */
+            memset(node->name, 0xef, node->namelen);
+            free(node->name);
+            free(node->actual_name);
+            memset(node, 0xfc, sizeof(*node));
+            free(node);
         }
+    } else {
+        ERROR("Zero refcnt %p\n", node);
+    }
+}
+
+static void add_node_to_parent_locked(struct node *node, struct node *parent) {
+    node->parent = parent;
+    node->next = parent->child;
+    parent->child = node;
+    acquire_node_locked(parent);
+}
+
+static void remove_node_from_parent_locked(struct node* node)
+{
+    if (node->parent) {
+        if (node->parent->child == node) {
+            node->parent->child = node->parent->child->next;
+        } else {
+            struct node *node2;
+            node2 = node->parent->child;
+            while (node2->next != node)
+                node2 = node2->next;
+            node2->next = node->next;
+        }
+        release_node_locked(node->parent);
+        node->parent = NULL;
+        node->next = NULL;
+    }
+}
+
+/* Gets the absolute path to a node into the provided buffer.
+ *
+ * Populates 'buf' with the path and returns the length of the path on success,
+ * or returns -1 if the path is too long for the provided buffer.
+ */
+static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize)
+{
+    size_t namelen = node->namelen;
+    if (bufsize < namelen + 1) {
+        return -1;
     }
 
-    /* If we are searching for a file within node (rather than computing node's path)
-     * and fail, then we need to look for a case insensitive match.
-     */
-    if (in_name && match_case_insensitive && access(out, F_OK) != 0) {
-        char *path, buffer[PATH_BUFFER_SIZE];
-        DIR* dir;
+    ssize_t pathlen = 0;
+    if (node->parent) {
+        pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 2);
+        if (pathlen < 0) {
+            return -1;
+        }
+        buf[pathlen++] = '/';
+    }
+
+    const char* name = node->actual_name ? node->actual_name : node->name;
+    memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
+    return pathlen + namelen;
+}
+
+/* Finds the absolute path of a file within a given directory.
+ * Performs a case-insensitive search for the file and sets the buffer to the path
+ * of the first matching file.  If 'search' is zero or if no match is found, sets
+ * the buffer to the path that the file would have, assuming the name were case-sensitive.
+ *
+ * Populates 'buf' with the path and returns the actual name (within 'buf') on success,
+ * or returns NULL if the path is too long for the provided buffer.
+ */
+static char* find_file_within(const char* path, const char* name,
+        char* buf, size_t bufsize, int search)
+{
+    size_t pathlen = strlen(path);
+    size_t namelen = strlen(name);
+    size_t childlen = pathlen + namelen + 1;
+    char* actual;
+
+    if (bufsize <= childlen) {
+        return NULL;
+    }
+
+    memcpy(buf, path, pathlen);
+    buf[pathlen] = '/';
+    actual = buf + pathlen + 1;
+    memcpy(actual, name, namelen + 1);
+
+    if (search && access(buf, F_OK)) {
         struct dirent* entry;
-        path = do_node_get_path(in_node, buffer, NULL, NO_CASE_SENSITIVE_MATCH);
-        dir = opendir(path);
+        DIR* dir = opendir(path);
         if (!dir) {
             ERROR("opendir %s failed: %s", path, strerror(errno));
-            return out;
+            return actual;
         }
-
         while ((entry = readdir(dir))) {
-            if (!strcasecmp(entry->d_name, in_name)) {
-                /* we have a match - replace the name */
-                len = strlen(in_name);
-                memcpy(buf + PATH_BUFFER_SIZE - len - 1, entry->d_name, len);
+            if (!strcasecmp(entry->d_name, name)) {
+                /* we have a match - replace the name, don't need to copy the null again */
+                memcpy(actual, entry->d_name, namelen);
                 break;
             }
         }
         closedir(dir);
     }
-
-   return out;
+    return actual;
 }
 
-char *node_get_path(struct node *node, char *buf, const char *name)
+static void attr_from_stat(struct fuse_attr *attr, const struct stat *s, __u64 nid)
 {
-    /* We look for case insensitive matches by default */
-    return do_node_get_path(node, buf, name, CASE_SENSITIVE_MATCH);
-}
-
-void attr_from_stat(struct fuse_attr *attr, struct stat *s)
-{
-    attr->ino = s->st_ino;
+    attr->ino = nid;
     attr->size = s->st_size;
     attr->blocks = s->st_blocks;
     attr->atime = s->st_atime;
@@ -221,129 +305,81 @@
     attr->gid = AID_SDCARD_RW;
 }
 
-int node_get_attr(struct node *node, struct fuse_attr *attr)
-{
-    int res;
-    struct stat s;
-    char *path, buffer[PATH_BUFFER_SIZE];
-
-    path = node_get_path(node, buffer, 0);
-    res = lstat(path, &s);
-    if (res < 0) {
-        ERROR("lstat('%s') errno %d\n", path, errno);
-        return -1;
-    }
-
-    attr_from_stat(attr, &s);    
-    attr->ino = node->nid;
-
-    return 0;
-}
-
-static void add_node_to_parent(struct node *node, struct node *parent) {
-    node->parent = parent;
-    node->next = parent->child;
-    parent->child = node;
-    parent->refcount++;
-}
-
-/* Check to see if our parent directory already has a file with a name
- * that differs only by case.  If we find one, store it in the actual_name
- * field so node_get_path will map it to this file in the underlying storage.
- */
-static void node_find_actual_name(struct node *node)
-{
-    char *path, buffer[PATH_BUFFER_SIZE];
-    const char *node_name = node->name;
-    DIR* dir;
-    struct dirent* entry;
-
-    if (!node->parent) return;
-
-    path = node_get_path(node->parent, buffer, 0);
-    dir = opendir(path);
-    if (!dir) {
-        ERROR("opendir %s failed: %s", path, strerror(errno));
-        return;
-    }
-
-    while ((entry = readdir(dir))) {
-        const char *test_name = entry->d_name;
-        if (strcmp(test_name, node_name) && !strcasecmp(test_name, node_name)) {
-            /* we have a match - differs but only by case */
-            node->actual_name = strdup(test_name);
-            if (!node->actual_name) {
-                ERROR("strdup failed - out of memory\n");
-                exit(1);
-            }
-            break;
-        }
-    }
-    closedir(dir);
-}
-
-struct node *node_create(struct node *parent, const char *name, __u64 nid, __u64 gen)
+struct node *create_node_locked(struct fuse* fuse,
+        struct node *parent, const char *name, const char* actual_name)
 {
     struct node *node;
-    int namelen = strlen(name);
+    size_t namelen = strlen(name);
 
     node = calloc(1, sizeof(struct node));
-    if (node == 0) {
-        return 0;
+    if (!node) {
+        return NULL;
     }
     node->name = malloc(namelen + 1);
-    if (node->name == 0) {
+    if (!node->name) {
         free(node);
-        return 0;
+        return NULL;
     }
-
-    node->nid = nid;
-    node->gen = gen;
-    add_node_to_parent(node, parent);
     memcpy(node->name, name, namelen + 1);
+    if (strcmp(name, actual_name)) {
+        node->actual_name = malloc(namelen + 1);
+        if (!node->actual_name) {
+            free(node->name);
+            free(node);
+            return NULL;
+        }
+        memcpy(node->actual_name, actual_name, namelen + 1);
+    }
     node->namelen = namelen;
-    node_find_actual_name(node);
+    node->nid = ptr_to_id(node);
+    node->gen = fuse->next_generation++;
+    acquire_node_locked(node);
+    add_node_to_parent_locked(node, parent);
     return node;
 }
 
-static char *rename_node(struct node *node, const char *name)
+static int rename_node_locked(struct node *node, const char *name,
+        const char* actual_name)
 {
-    node->namelen = strlen(name);
-    char *newname = realloc(node->name, node->namelen + 1);
-    if (newname == 0)
-        return 0;
-    node->name = newname;
-    memcpy(node->name, name, node->namelen + 1);
-    node_find_actual_name(node);
-    return node->name;
+    size_t namelen = strlen(name);
+    int need_actual_name = strcmp(name, actual_name);
+
+    /* make the storage bigger without actually changing the name
+     * in case an error occurs part way */
+    if (namelen > node->namelen) {
+        char* new_name = realloc(node->name, namelen + 1);
+        if (!new_name) {
+            return -ENOMEM;
+        }
+        node->name = new_name;
+        if (need_actual_name && node->actual_name) {
+            char* new_actual_name = realloc(node->actual_name, namelen + 1);
+            if (!new_actual_name) {
+                return -ENOMEM;
+            }
+            node->actual_name = new_actual_name;
+        }
+    }
+
+    /* update the name, taking care to allocate storage before overwriting the old name */
+    if (need_actual_name) {
+        if (!node->actual_name) {
+            node->actual_name = malloc(namelen + 1);
+            if (!node->actual_name) {
+                return -ENOMEM;
+            }
+        }
+        memcpy(node->actual_name, actual_name, namelen + 1);
+    } else {
+        free(node->actual_name);
+        node->actual_name = NULL;
+    }
+    memcpy(node->name, name, namelen + 1);
+    node->namelen = namelen;
+    return 0;
 }
 
-void fuse_init(struct fuse *fuse, int fd, const char *path)
-{
-    fuse->fd = fd;
-    fuse->next_node_id = 2;
-    fuse->next_generation = 0;
-
-    fuse->all = &fuse->root;
-
-    memset(&fuse->root, 0, sizeof(fuse->root));
-    fuse->root.nid = FUSE_ROOT_ID; /* 1 */
-    fuse->root.refcount = 2;
-    rename_node(&fuse->root, path);
-}
-
-static inline void *id_to_ptr(__u64 nid)
-{
-    return (void *) nid;
-}
-
-static inline __u64 ptr_to_id(void *ptr)
-{
-    return (__u64) ptr;
-}
-
-
-struct node *lookup_by_inode(struct fuse *fuse, __u64 nid)
+static struct node *lookup_node_by_id_locked(struct fuse *fuse, __u64 nid)
 {
     if (nid == FUSE_ROOT_ID) {
         return &fuse->root;
@@ -352,9 +388,23 @@
     }
 }
 
-struct node *lookup_child_by_name(struct node *node, const char *name)
+static struct node* lookup_node_and_path_by_id_locked(struct fuse* fuse, __u64 nid,
+        char* buf, size_t bufsize)
+{
+    struct node* node = lookup_node_by_id_locked(fuse, nid);
+    if (node && get_node_path_locked(node, buf, bufsize) < 0) {
+        node = NULL;
+    }
+    return node;
+}
+
+static struct node *lookup_child_by_name_locked(struct node *node, const char *name)
 {
     for (node = node->child; node; node = node->next) {
+        /* use exact string comparison, nodes that differ by case
+         * must be considered distinct even if they refer to the same
+         * underlying file as otherwise operations such as "mv x x"
+         * will not work because the source and target nodes are the same. */
         if (!strcmp(name, node->name)) {
             return node;
         }
@@ -362,123 +412,43 @@
     return 0;
 }
 
-struct node *lookup_child_by_inode(struct node *node, __u64 nid)
+static struct node* acquire_or_create_child_locked(
+        struct fuse* fuse, struct node* parent,
+        const char* name, const char* actual_name)
 {
-    for (node = node->child; node; node = node->next) {
-        if (node->nid == nid) {
-            return node;
-        }
-    }
-    return 0;
-}
-
-static void dec_refcount(struct node *node) {
-    if (node->refcount > 0) {
-        node->refcount--;
-        TRACE("dec_refcount %p(%s) -> %d\n", node, node->name, node->refcount);
+    struct node* child = lookup_child_by_name_locked(parent, name);
+    if (child) {
+        acquire_node_locked(child);
     } else {
-        ERROR("Zero refcnt %p\n", node);
+        child = create_node_locked(fuse, parent, name, actual_name);
     }
- }
-
-static struct node *remove_child(struct node *parent, __u64 nid)
-{
-    struct node *prev = 0;
-    struct node *node;
-
-    for (node = parent->child; node; node = node->next) {
-        if (node->nid == nid) {
-            if (prev) {
-                prev->next = node->next;
-            } else {
-                parent->child = node->next;
-            }
-            node->next = 0;
-            node->parent = 0;
-            dec_refcount(parent);
-            return node;
-        }
-        prev = node;
-    }
-    return 0;
+    return child;
 }
 
-struct node *node_lookup(struct fuse *fuse, struct node *parent, const char *name,
-                         struct fuse_attr *attr)
+static void fuse_init(struct fuse *fuse, int fd, const char *path)
 {
-    int res;
-    struct stat s;
-    char *path, buffer[PATH_BUFFER_SIZE];
-    struct node *node;
+    pthread_mutex_init(&fuse->lock, NULL);
 
-    path = node_get_path(parent, buffer, name);
-        /* XXX error? */
+    fuse->fd = fd;
+    fuse->next_generation = 0;
 
-    res = lstat(path, &s);
-    if (res < 0)
-        return 0;
-    
-    node = lookup_child_by_name(parent, name);
-    if (!node) {
-        node = node_create(parent, name, fuse->next_node_id++, fuse->next_generation++);
-        if (!node)
-            return 0;
-        node->nid = ptr_to_id(node);
-        node->all = fuse->all;
-        fuse->all = node;
-    }
-
-    attr_from_stat(attr, &s);
-    attr->ino = node->nid;
-
-    return node;
+    memset(&fuse->root, 0, sizeof(fuse->root));
+    fuse->root.nid = FUSE_ROOT_ID; /* 1 */
+    fuse->root.refcount = 2;
+    fuse->root.namelen = strlen(path);
+    fuse->root.name = strdup(path);
 }
 
-void node_release(struct node *node)
-{
-    TRACE("RELEASE %p (%s) rc=%d\n", node, node->name, node->refcount);
-    dec_refcount(node);
-    if (node->refcount == 0) {
-        if (node->parent->child == node) {
-            node->parent->child = node->parent->child->next;
-        } else {
-            struct node *node2;
-
-            node2 = node->parent->child;
-            while (node2->next != node)
-                node2 = node2->next;
-            node2->next = node->next;            
-        }
-
-        TRACE("DESTROY %p (%s)\n", node, node->name);
-
-        node_release(node->parent);
-
-        node->parent = 0;
-        node->next = 0;
-
-            /* TODO: remove debugging - poison memory */
-        memset(node->name, 0xef, node->namelen);
-        free(node->name);
-        free(node->actual_name);
-        memset(node, 0xfc, sizeof(*node));
-        free(node);
-    }
-}
-
-void fuse_status(struct fuse *fuse, __u64 unique, int err)
+static void fuse_status(struct fuse *fuse, __u64 unique, int err)
 {
     struct fuse_out_header hdr;
     hdr.len = sizeof(hdr);
     hdr.error = err;
     hdr.unique = unique;
-    if (err) {
-//        ERROR("*** %d ***\n", err);
-    }
     write(fuse->fd, &hdr, sizeof(hdr));
 }
 
-void fuse_reply(struct fuse *fuse, __u64 unique, void *data, int len)
+static void fuse_reply(struct fuse *fuse, __u64 unique, void *data, int len)
 {
     struct fuse_out_header hdr;
     struct iovec vec[2];
@@ -499,481 +469,856 @@
     }
 }
 
-void lookup_entry(struct fuse *fuse, struct node *node,
-                  const char *name, __u64 unique)
+static int fuse_reply_entry(struct fuse* fuse, __u64 unique,
+        struct node* parent, const char* name, const char* actual_name,
+        const char* path)
 {
+    struct node* node;
     struct fuse_entry_out out;
-    
-    memset(&out, 0, sizeof(out));
+    struct stat s;
 
-    node = node_lookup(fuse, node, name, &out.attr);
-    if (!node) {
-        fuse_status(fuse, unique, -ENOENT);
-        return;
+    if (lstat(path, &s) < 0) {
+        return -errno;
     }
-    
-    node->refcount++;
-//    fprintf(stderr,"ACQUIRE %p (%s) rc=%d\n", node, node->name, node->refcount);
+
+    pthread_mutex_lock(&fuse->lock);
+    node = acquire_or_create_child_locked(fuse, parent, name, actual_name);
+    if (!node) {
+        pthread_mutex_unlock(&fuse->lock);
+        return -ENOMEM;
+    }
+    memset(&out, 0, sizeof(out));
+    attr_from_stat(&out.attr, &s, node->nid);
+    out.attr_valid = 10;
+    out.entry_valid = 10;
     out.nodeid = node->nid;
     out.generation = node->gen;
-    out.entry_valid = 10;
-    out.attr_valid = 10;
-    
+    pthread_mutex_unlock(&fuse->lock);
     fuse_reply(fuse, unique, &out, sizeof(out));
+    return NO_STATUS;
 }
 
-void handle_fuse_request(struct fuse *fuse, struct fuse_in_header *hdr, void *data, unsigned len)
+static int fuse_reply_attr(struct fuse* fuse, __u64 unique, __u64 nid,
+        const char* path)
 {
-    struct node *node;
+    struct fuse_attr_out out;
+    struct stat s;
 
-    if ((len < sizeof(*hdr)) || (hdr->len != len)) {
-        ERROR("malformed header\n");
-        return;
+    if (lstat(path, &s) < 0) {
+        return -errno;
     }
+    memset(&out, 0, sizeof(out));
+    attr_from_stat(&out.attr, &s, nid);
+    out.attr_valid = 10;
+    fuse_reply(fuse, unique, &out, sizeof(out));
+    return NO_STATUS;
+}
 
-    len -= hdr->len;
+static int handle_lookup(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const char* name)
+{
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+    const char* actual_name;
 
-    if (hdr->nodeid) {
-        node = lookup_by_inode(fuse, hdr->nodeid);
-        if (!node) {
-            fuse_status(fuse, hdr->unique, -ENOENT);
-            return;
+    pthread_mutex_lock(&fuse->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    TRACE("[%d] LOOKUP %s @ %llx (%s)\n", handler->token, name, hdr->nodeid,
+        parent_node ? parent_node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1))) {
+        return -ENOENT;
+    }
+    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
+}
+
+static int handle_forget(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const struct fuse_forget_in *req)
+{
+    struct node* node;
+
+    pthread_mutex_lock(&fuse->lock);
+    node = lookup_node_by_id_locked(fuse, hdr->nodeid);
+    TRACE("[%d] FORGET #%lld @ %llx (%s)\n", handler->token, req->nlookup,
+            hdr->nodeid, node ? node->name : "?");
+    if (node) {
+        __u64 n = req->nlookup;
+        while (n--) {
+            release_node_locked(node);
         }
-    } else {
-        node = 0;
+    }
+    pthread_mutex_unlock(&fuse->lock);
+    return NO_STATUS; /* no reply */
+}
+
+static int handle_getattr(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const struct fuse_getattr_in *req)
+{
+    struct node* node;
+    char path[PATH_MAX];
+
+    pthread_mutex_lock(&fuse->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
+    TRACE("[%d] GETATTR flags=%x fh=%llx @ %llx (%s)\n", handler->token,
+            req->getattr_flags, req->fh, hdr->nodeid, node ? node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!node) {
+        return -ENOENT;
+    }
+    return fuse_reply_attr(fuse, hdr->unique, hdr->nodeid, path);
+}
+
+static int handle_setattr(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const struct fuse_setattr_in *req)
+{
+    struct node* node;
+    char path[PATH_MAX];
+    struct timespec times[2];
+
+    pthread_mutex_lock(&fuse->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
+    TRACE("[%d] SETATTR fh=%llx valid=%x @ %llx (%s)\n", handler->token,
+            req->fh, req->valid, hdr->nodeid, node ? node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!node) {
+        return -ENOENT;
     }
 
+    /* XXX: incomplete implementation on purpose.
+     * chmod/chown should NEVER be implemented.*/
+
+    if ((req->valid & FATTR_SIZE) && truncate(path, req->size) < 0) {
+        return -errno;
+    }
+
+    /* Handle changing atime and mtime.  If FATTR_ATIME_and FATTR_ATIME_NOW
+     * are both set, then set it to the current time.  Else, set it to the
+     * time specified in the request.  Same goes for mtime.  Use utimensat(2)
+     * as it allows ATIME and MTIME to be changed independently, and has
+     * nanosecond resolution which fuse also has.
+     */
+    if (req->valid & (FATTR_ATIME | FATTR_MTIME)) {
+        times[0].tv_nsec = UTIME_OMIT;
+        times[1].tv_nsec = UTIME_OMIT;
+        if (req->valid & FATTR_ATIME) {
+            if (req->valid & FATTR_ATIME_NOW) {
+              times[0].tv_nsec = UTIME_NOW;
+            } else {
+              times[0].tv_sec = req->atime;
+              times[0].tv_nsec = req->atimensec;
+            }
+        }
+        if (req->valid & FATTR_MTIME) {
+            if (req->valid & FATTR_MTIME_NOW) {
+              times[1].tv_nsec = UTIME_NOW;
+            } else {
+              times[1].tv_sec = req->mtime;
+              times[1].tv_nsec = req->mtimensec;
+            }
+        }
+        TRACE("[%d] Calling utimensat on %s with atime %ld, mtime=%ld\n",
+                handler->token, path, times[0].tv_sec, times[1].tv_sec);
+        if (utimensat(-1, path, times, 0) < 0) {
+            return -errno;
+        }
+    }
+    return fuse_reply_attr(fuse, hdr->unique, hdr->nodeid, path);
+}
+
+static int handle_mknod(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_mknod_in* req, const char* name)
+{
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+    const char* actual_name;
+
+    pthread_mutex_lock(&fuse->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    TRACE("[%d] MKNOD %s 0%o @ %llx (%s)\n", handler->token,
+            name, req->mode, hdr->nodeid, parent_node ? parent_node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1))) {
+        return -ENOENT;
+    }
+    __u32 mode = (req->mode & (~0777)) | 0664;
+    if (mknod(child_path, mode, req->rdev) < 0) {
+        return -errno;
+    }
+    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
+}
+
+static int handle_mkdir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_mkdir_in* req, const char* name)
+{
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+    const char* actual_name;
+
+    pthread_mutex_lock(&fuse->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    TRACE("[%d] MKDIR %s 0%o @ %llx (%s)\n", handler->token,
+            name, req->mode, hdr->nodeid, parent_node ? parent_node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1))) {
+        return -ENOENT;
+    }
+    __u32 mode = (req->mode & (~0777)) | 0775;
+    if (mkdir(child_path, mode) < 0) {
+        return -errno;
+    }
+    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
+}
+
+static int handle_unlink(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const char* name)
+{
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+
+    pthread_mutex_lock(&fuse->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    TRACE("[%d] UNLINK %s @ %llx (%s)\n", handler->token,
+            name, hdr->nodeid, parent_node ? parent_node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!parent_node || !find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1)) {
+        return -ENOENT;
+    }
+    if (unlink(child_path) < 0) {
+        return -errno;
+    }
+    return 0;
+}
+
+static int handle_rmdir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const char* name)
+{
+    struct node* parent_node;
+    char parent_path[PATH_MAX];
+    char child_path[PATH_MAX];
+
+    pthread_mutex_lock(&fuse->lock);
+    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            parent_path, sizeof(parent_path));
+    TRACE("[%d] RMDIR %s @ %llx (%s)\n", handler->token,
+            name, hdr->nodeid, parent_node ? parent_node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!parent_node || !find_file_within(parent_path, name,
+            child_path, sizeof(child_path), 1)) {
+        return -ENOENT;
+    }
+    if (rmdir(child_path) < 0) {
+        return -errno;
+    }
+    return 0;
+}
+
+static int handle_rename(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_rename_in* req,
+        const char* old_name, const char* new_name)
+{
+    struct node* old_parent_node;
+    struct node* new_parent_node;
+    struct node* child_node;
+    char old_parent_path[PATH_MAX];
+    char new_parent_path[PATH_MAX];
+    char old_child_path[PATH_MAX];
+    char new_child_path[PATH_MAX];
+    const char* new_actual_name;
+    int res;
+
+    pthread_mutex_lock(&fuse->lock);
+    old_parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
+            old_parent_path, sizeof(old_parent_path));
+    new_parent_node = lookup_node_and_path_by_id_locked(fuse, req->newdir,
+            new_parent_path, sizeof(new_parent_path));
+    TRACE("[%d] RENAME %s->%s @ %llx (%s) -> %llx (%s)\n", handler->token,
+            old_name, new_name,
+            hdr->nodeid, old_parent_node ? old_parent_node->name : "?",
+            req->newdir, new_parent_node ? new_parent_node->name : "?");
+    if (!old_parent_node || !new_parent_node) {
+        res = -ENOENT;
+        goto lookup_error;
+    }
+    child_node = lookup_child_by_name_locked(old_parent_node, old_name);
+    if (!child_node || get_node_path_locked(child_node,
+            old_child_path, sizeof(old_child_path)) < 0) {
+        res = -ENOENT;
+        goto lookup_error;
+    }
+    acquire_node_locked(child_node);
+    pthread_mutex_unlock(&fuse->lock);
+
+    /* Special case for renaming a file where destination is same path
+     * differing only by case.  In this case we don't want to look for a case
+     * insensitive match.  This allows commands like "mv foo FOO" to work as expected.
+     */
+    int search = old_parent_node != new_parent_node
+            || strcasecmp(old_name, new_name);
+    if (!(new_actual_name = find_file_within(new_parent_path, new_name,
+            new_child_path, sizeof(new_child_path), search))) {
+        res = -ENOENT;
+        goto io_error;
+    }
+
+    TRACE("[%d] RENAME %s->%s\n", handler->token, old_child_path, new_child_path);
+    res = rename(old_child_path, new_child_path);
+    if (res < 0) {
+        res = -errno;
+        goto io_error;
+    }
+
+    pthread_mutex_lock(&fuse->lock);
+    res = rename_node_locked(child_node, new_name, new_actual_name);
+    if (!res) {
+        remove_node_from_parent_locked(child_node);
+        add_node_to_parent_locked(child_node, new_parent_node);
+    }
+    goto done;
+
+io_error:
+    pthread_mutex_lock(&fuse->lock);
+done:
+    release_node_locked(child_node);
+lookup_error:
+    pthread_mutex_unlock(&fuse->lock);
+    return res;
+}
+
+static int handle_open(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
+{
+    struct node* node;
+    char path[PATH_MAX];
+    struct fuse_open_out out;
+    struct handle *h;
+
+    pthread_mutex_lock(&fuse->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
+    TRACE("[%d] OPEN 0%o @ %llx (%s)\n", handler->token,
+            req->flags, hdr->nodeid, node ? node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!node) {
+        return -ENOENT;
+    }
+    h = malloc(sizeof(*h));
+    if (!h) {
+        return -ENOMEM;
+    }
+    TRACE("[%d] OPEN %s\n", handler->token, path);
+    h->fd = open(path, req->flags);
+    if (h->fd < 0) {
+        free(h);
+        return -errno;
+    }
+    out.fh = ptr_to_id(h);
+    out.open_flags = 0;
+    out.padding = 0;
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_read(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
+{
+    struct handle *h = id_to_ptr(req->fh);
+    __u64 unique = hdr->unique;
+    __u32 size = req->size;
+    __u64 offset = req->offset;
+    int res;
+
+    /* Don't access any other fields of hdr or req beyond this point, the read buffer
+     * overlaps the request buffer and will clobber data in the request.  This
+     * saves us 128KB per request handler thread at the cost of this scary comment. */
+
+    TRACE("[%d] READ %p(%d) %u@%llu\n", handler->token,
+            h, h->fd, size, offset);
+    if (size > sizeof(handler->read_buffer)) {
+        return -EINVAL;
+    }
+    res = pread64(h->fd, handler->read_buffer, size, offset);
+    if (res < 0) {
+        return -errno;
+    }
+    fuse_reply(fuse, unique, handler->read_buffer, res);
+    return NO_STATUS;
+}
+
+static int handle_write(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_write_in* req,
+        const void* buffer)
+{
+    struct fuse_write_out out;
+    struct handle *h = id_to_ptr(req->fh);
+    int res;
+
+    TRACE("[%d] WRITE %p(%d) %u@%llu\n", handler->token,
+            h, h->fd, req->size, req->offset);
+    res = pwrite64(h->fd, buffer, req->size, req->offset);
+    if (res < 0) {
+        return -errno;
+    }
+    out.size = res;
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_statfs(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr)
+{
+    char path[PATH_MAX];
+    struct statfs stat;
+    struct fuse_statfs_out out;
+    int res;
+
+    pthread_mutex_lock(&fuse->lock);
+    TRACE("[%d] STATFS\n", handler->token);
+    res = get_node_path_locked(&fuse->root, path, sizeof(path));
+    pthread_mutex_unlock(&fuse->lock);
+    if (res < 0) {
+        return -ENOENT;
+    }
+    if (statfs(fuse->root.name, &stat) < 0) {
+        return -errno;
+    }
+    memset(&out, 0, sizeof(out));
+    out.st.blocks = stat.f_blocks;
+    out.st.bfree = stat.f_bfree;
+    out.st.bavail = stat.f_bavail;
+    out.st.files = stat.f_files;
+    out.st.ffree = stat.f_ffree;
+    out.st.bsize = stat.f_bsize;
+    out.st.namelen = stat.f_namelen;
+    out.st.frsize = stat.f_frsize;
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_release(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
+{
+    struct handle *h = id_to_ptr(req->fh);
+
+    TRACE("[%d] RELEASE %p(%d)\n", handler->token, h, h->fd);
+    close(h->fd);
+    free(h);
+    return 0;
+}
+
+static int handle_fsync(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_fsync_in* req)
+{
+    int is_data_sync = req->fsync_flags & 1;
+    struct handle *h = id_to_ptr(req->fh);
+    int res;
+
+    TRACE("[%d] FSYNC %p(%d) is_data_sync=%d\n", handler->token,
+            h, h->fd, is_data_sync);
+    res = is_data_sync ? fdatasync(h->fd) : fsync(h->fd);
+    if (res < 0) {
+        return -errno;
+    }
+    return 0;
+}
+
+static int handle_flush(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr)
+{
+    TRACE("[%d] FLUSH\n", handler->token);
+    return 0;
+}
+
+static int handle_opendir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
+{
+    struct node* node;
+    char path[PATH_MAX];
+    struct fuse_open_out out;
+    struct dirhandle *h;
+
+    pthread_mutex_lock(&fuse->lock);
+    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
+    TRACE("[%d] OPENDIR @ %llx (%s)\n", handler->token,
+            hdr->nodeid, node ? node->name : "?");
+    pthread_mutex_unlock(&fuse->lock);
+
+    if (!node) {
+        return -ENOENT;
+    }
+    h = malloc(sizeof(*h));
+    if (!h) {
+        return -ENOMEM;
+    }
+    TRACE("[%d] OPENDIR %s\n", handler->token, path);
+    h->d = opendir(path);
+    if (!h->d) {
+        free(h);
+        return -errno;
+    }
+    out.fh = ptr_to_id(h);
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_readdir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
+{
+    char buffer[8192];
+    struct fuse_dirent *fde = (struct fuse_dirent*) buffer;
+    struct dirent *de;
+    struct dirhandle *h = id_to_ptr(req->fh);
+
+    TRACE("[%d] READDIR %p\n", handler->token, h);
+    if (req->offset == 0) {
+        /* rewinddir() might have been called above us, so rewind here too */
+        TRACE("[%d] calling rewinddir()\n", handler->token);
+        rewinddir(h->d);
+    }
+    de = readdir(h->d);
+    if (!de) {
+        return 0;
+    }
+    fde->ino = FUSE_UNKNOWN_INO;
+    /* increment the offset so we can detect when rewinddir() seeks back to the beginning */
+    fde->off = req->offset + 1;
+    fde->type = de->d_type;
+    fde->namelen = strlen(de->d_name);
+    memcpy(fde->name, de->d_name, fde->namelen + 1);
+    fuse_reply(fuse, hdr->unique, fde,
+            FUSE_DIRENT_ALIGN(sizeof(struct fuse_dirent) + fde->namelen));
+    return NO_STATUS;
+}
+
+static int handle_releasedir(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
+{
+    struct dirhandle *h = id_to_ptr(req->fh);
+
+    TRACE("[%d] RELEASEDIR %p\n", handler->token, h);
+    closedir(h->d);
+    free(h);
+    return 0;
+}
+
+static int handle_init(struct fuse* fuse, struct fuse_handler* handler,
+        const struct fuse_in_header* hdr, const struct fuse_init_in* req)
+{
+    struct fuse_init_out out;
+
+    TRACE("[%d] INIT ver=%d.%d maxread=%d flags=%x\n",
+            handler->token, req->major, req->minor, req->max_readahead, req->flags);
+    out.major = FUSE_KERNEL_VERSION;
+    out.minor = FUSE_KERNEL_MINOR_VERSION;
+    out.max_readahead = req->max_readahead;
+    out.flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
+    out.max_background = 32;
+    out.congestion_threshold = 32;
+    out.max_write = MAX_WRITE;
+    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
+    return NO_STATUS;
+}
+
+static int handle_fuse_request(struct fuse *fuse, struct fuse_handler* handler,
+        const struct fuse_in_header *hdr, const void *data, size_t data_len)
+{
     switch (hdr->opcode) {
     case FUSE_LOOKUP: { /* bytez[] -> entry_out */
-        TRACE("LOOKUP %llx %s\n", hdr->nodeid, (char*) data);
-        lookup_entry(fuse, node, (char*) data, hdr->unique);
-        return;
+        const char* name = data;
+        return handle_lookup(fuse, handler, hdr, name);
     }
+
     case FUSE_FORGET: {
-        struct fuse_forget_in *req = data;
-        TRACE("FORGET %llx (%s) #%lld\n", hdr->nodeid, node->name, req->nlookup);
-            /* no reply */
-        while (req->nlookup--)
-            node_release(node);
-        return;
+        const struct fuse_forget_in *req = data;
+        return handle_forget(fuse, handler, hdr, req);
     }
+
     case FUSE_GETATTR: { /* getattr_in -> attr_out */
-        struct fuse_getattr_in *req = data;
-        struct fuse_attr_out out;
-
-        TRACE("GETATTR flags=%x fh=%llx\n", req->getattr_flags, req->fh);
-
-        memset(&out, 0, sizeof(out));
-        node_get_attr(node, &out.attr);
-        out.attr_valid = 10;
-
-        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-        return;
+        const struct fuse_getattr_in *req = data;
+        return handle_getattr(fuse, handler, hdr, req);
     }
+
     case FUSE_SETATTR: { /* setattr_in -> attr_out */
-        struct fuse_setattr_in *req = data;
-        struct fuse_attr_out out;
-        char *path, buffer[PATH_BUFFER_SIZE];
-        int res = 0;
-        struct timespec times[2];
-
-        TRACE("SETATTR fh=%llx id=%llx valid=%x\n",
-              req->fh, hdr->nodeid, req->valid);
-
-        /* XXX: incomplete implementation on purpose.   chmod/chown
-         * should NEVER be implemented.*/
-
-        path = node_get_path(node, buffer, 0);
-        if (req->valid & FATTR_SIZE)
-            res = truncate(path, req->size);
-        if (res)
-            goto getout;
-
-        /* Handle changing atime and mtime.  If FATTR_ATIME_and FATTR_ATIME_NOW
-         * are both set, then set it to the current time.  Else, set it to the
-         * time specified in the request.  Same goes for mtime.  Use utimensat(2)
-         * as it allows ATIME and MTIME to be changed independently, and has
-         * nanosecond resolution which fuse also has.
-         */
-        if (req->valid & (FATTR_ATIME | FATTR_MTIME)) {
-            times[0].tv_nsec = UTIME_OMIT;
-            times[1].tv_nsec = UTIME_OMIT;
-            if (req->valid & FATTR_ATIME) {
-                if (req->valid & FATTR_ATIME_NOW) {
-                  times[0].tv_nsec = UTIME_NOW;
-                } else {
-                  times[0].tv_sec = req->atime;
-                  times[0].tv_nsec = req->atimensec;
-                }
-            }
-            if (req->valid & FATTR_MTIME) {
-                if (req->valid & FATTR_MTIME_NOW) {
-                  times[1].tv_nsec = UTIME_NOW;
-                } else {
-                  times[1].tv_sec = req->mtime;
-                  times[1].tv_nsec = req->mtimensec;
-                }
-            }
-            TRACE("Calling utimensat on %s with atime %ld, mtime=%ld\n", path, times[0].tv_sec, times[1].tv_sec);
-            res = utimensat(-1, path, times, 0);
-        }
-
-        getout:
-        memset(&out, 0, sizeof(out));
-        node_get_attr(node, &out.attr);
-        out.attr_valid = 10;
-
-        if (res)
-            fuse_status(fuse, hdr->unique, -errno);
-        else
-            fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-        return;
+        const struct fuse_setattr_in *req = data;
+        return handle_setattr(fuse, handler, hdr, req);
     }
+
 //    case FUSE_READLINK:
 //    case FUSE_SYMLINK:
     case FUSE_MKNOD: { /* mknod_in, bytez[] -> entry_out */
-        struct fuse_mknod_in *req = data;
-        char *path, buffer[PATH_BUFFER_SIZE];
-        char *name = ((char*) data) + sizeof(*req);
-        int res;
-
-        TRACE("MKNOD %s @ %llx\n", name, hdr->nodeid);
-        path = node_get_path(node, buffer, name);
-
-        req->mode = (req->mode & (~0777)) | 0664;
-        res = mknod(path, req->mode, req->rdev); /* XXX perm?*/
-        if (res < 0) {
-            fuse_status(fuse, hdr->unique, -errno);
-        } else {
-            lookup_entry(fuse, node, name, hdr->unique);
-        }
-        return;
+        const struct fuse_mknod_in *req = data;
+        const char *name = ((const char*) data) + sizeof(*req);
+        return handle_mknod(fuse, handler, hdr, req, name);
     }
+
     case FUSE_MKDIR: { /* mkdir_in, bytez[] -> entry_out */
-        struct fuse_mkdir_in *req = data;
-        struct fuse_entry_out out;
-        char *path, buffer[PATH_BUFFER_SIZE];
-        char *name = ((char*) data) + sizeof(*req);
-        int res;
-
-        TRACE("MKDIR %s @ %llx 0%o\n", name, hdr->nodeid, req->mode);
-        path = node_get_path(node, buffer, name);
-
-        req->mode = (req->mode & (~0777)) | 0775;
-        res = mkdir(path, req->mode);
-        if (res < 0) {
-            fuse_status(fuse, hdr->unique, -errno);
-        } else {
-            lookup_entry(fuse, node, name, hdr->unique);
-        }
-        return;
+        const struct fuse_mkdir_in *req = data;
+        const char *name = ((const char*) data) + sizeof(*req);
+        return handle_mkdir(fuse, handler, hdr, req, name);
     }
+
     case FUSE_UNLINK: { /* bytez[] -> */
-        char *path, buffer[PATH_BUFFER_SIZE];
-        int res;
-        TRACE("UNLINK %s @ %llx\n", (char*) data, hdr->nodeid);
-        path = node_get_path(node, buffer, (char*) data);
-        res = unlink(path);
-        fuse_status(fuse, hdr->unique, res ? -errno : 0);
-        return;
+        const char* name = data;
+        return handle_unlink(fuse, handler, hdr, name);
     }
+
     case FUSE_RMDIR: { /* bytez[] -> */
-        char *path, buffer[PATH_BUFFER_SIZE];
-        int res;
-        TRACE("RMDIR %s @ %llx\n", (char*) data, hdr->nodeid);
-        path = node_get_path(node, buffer, (char*) data);
-        res = rmdir(path);
-        fuse_status(fuse, hdr->unique, res ? -errno : 0);
-        return;
+        const char* name = data;
+        return handle_rmdir(fuse, handler, hdr, name);
     }
+
     case FUSE_RENAME: { /* rename_in, oldname, newname ->  */
-        struct fuse_rename_in *req = data;
-        char *oldname = ((char*) data) + sizeof(*req);
-        char *newname = oldname + strlen(oldname) + 1;
-        char *oldpath, oldbuffer[PATH_BUFFER_SIZE];
-        char *newpath, newbuffer[PATH_BUFFER_SIZE];
-        struct node *target;
-        struct node *newparent;
-        int res;
-
-        TRACE("RENAME %s->%s @ %llx\n", oldname, newname, hdr->nodeid);
-
-        target = lookup_child_by_name(node, oldname);
-        if (!target) {
-            fuse_status(fuse, hdr->unique, -ENOENT);
-            return;
-        }
-        oldpath = node_get_path(node, oldbuffer, oldname);
-
-        newparent = lookup_by_inode(fuse, req->newdir);
-        if (!newparent) {
-            fuse_status(fuse, hdr->unique, -ENOENT);
-            return;
-        }
-        if (newparent == node) {
-            /* Special case for renaming a file where destination
-             * is same path differing only by case.
-             * In this case we don't want to look for a case insensitive match.
-             * This allows commands like "mv foo FOO" to work as expected.
-             */
-            newpath = do_node_get_path(newparent, newbuffer, newname, NO_CASE_SENSITIVE_MATCH);
-        } else {
-            newpath = node_get_path(newparent, newbuffer, newname);
-        }
-
-        if (!remove_child(node, target->nid)) {
-            ERROR("RENAME remove_child not found");
-            fuse_status(fuse, hdr->unique, -ENOENT);
-            return;
-        }
-        if (!rename_node(target, newname)) {
-            fuse_status(fuse, hdr->unique, -ENOMEM);
-            return;
-        }
-        add_node_to_parent(target, newparent);
-
-        res = rename(oldpath, newpath);
-        TRACE("RENAME result %d\n", res);
-
-        fuse_status(fuse, hdr->unique, res ? -errno : 0);
-        return;
+        const struct fuse_rename_in *req = data;
+        const char *old_name = ((const char*) data) + sizeof(*req);
+        const char *new_name = old_name + strlen(old_name) + 1;
+        return handle_rename(fuse, handler, hdr, req, old_name, new_name);
     }
-//    case FUSE_LINK:        
+
+//    case FUSE_LINK:
     case FUSE_OPEN: { /* open_in -> open_out */
-        struct fuse_open_in *req = data;
-        struct fuse_open_out out;
-        char *path, buffer[PATH_BUFFER_SIZE];
-        struct handle *h;
-
-        h = malloc(sizeof(*h));
-        if (!h) {
-            fuse_status(fuse, hdr->unique, -ENOMEM);
-            return;
-        }
-
-        path = node_get_path(node, buffer, 0);
-        TRACE("OPEN %llx '%s' 0%o fh=%p\n", hdr->nodeid, path, req->flags, h);
-        h->fd = open(path, req->flags);
-        if (h->fd < 0) {
-            ERROR("ERROR\n");
-            fuse_status(fuse, hdr->unique, -errno);
-            free(h);
-            return;
-        }
-        out.fh = ptr_to_id(h);
-        out.open_flags = 0;
-        out.padding = 0;
-        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-        return;
+        const struct fuse_open_in *req = data;
+        return handle_open(fuse, handler, hdr, req);
     }
+
     case FUSE_READ: { /* read_in -> byte[] */
-        char buffer[128 * 1024];
-        struct fuse_read_in *req = data;
-        struct handle *h = id_to_ptr(req->fh);
-        int res;
-        TRACE("READ %p(%d) %u@%llu\n", h, h->fd, req->size, req->offset);
-        if (req->size > sizeof(buffer)) {
-            fuse_status(fuse, hdr->unique, -EINVAL);
-            return;
-        }
-        res = pread64(h->fd, buffer, req->size, req->offset);
-        if (res < 0) {
-            fuse_status(fuse, hdr->unique, -errno);
-            return;
-        }
-        fuse_reply(fuse, hdr->unique, buffer, res);
-        return;
+        const struct fuse_read_in *req = data;
+        return handle_read(fuse, handler, hdr, req);
     }
+
     case FUSE_WRITE: { /* write_in, byte[write_in.size] -> write_out */
-        struct fuse_write_in *req = data;
-        struct fuse_write_out out;
-        struct handle *h = id_to_ptr(req->fh);
-        int res;
-        TRACE("WRITE %p(%d) %u@%llu\n", h, h->fd, req->size, req->offset);
-        res = pwrite64(h->fd, ((char*) data) + sizeof(*req), req->size, req->offset);
-        if (res < 0) {
-            fuse_status(fuse, hdr->unique, -errno);
-            return;
-        }
-        out.size = res;
-        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-        goto oops;
+        const struct fuse_write_in *req = data;
+        const void* buffer = (const __u8*)data + sizeof(*req);
+        return handle_write(fuse, handler, hdr, req, buffer);
     }
+
     case FUSE_STATFS: { /* getattr_in -> attr_out */
-        struct statfs stat;
-        struct fuse_statfs_out out;
-        int res;
-
-        TRACE("STATFS\n");
-
-        if (statfs(fuse->root.name, &stat)) {
-            fuse_status(fuse, hdr->unique, -errno);
-            return;
-        }
-
-        memset(&out, 0, sizeof(out));
-        out.st.blocks = stat.f_blocks;
-        out.st.bfree = stat.f_bfree;
-        out.st.bavail = stat.f_bavail;
-        out.st.files = stat.f_files;
-        out.st.ffree = stat.f_ffree;
-        out.st.bsize = stat.f_bsize;
-        out.st.namelen = stat.f_namelen;
-        out.st.frsize = stat.f_frsize;
-        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-        return;
+        return handle_statfs(fuse, handler, hdr);
     }
+
     case FUSE_RELEASE: { /* release_in -> */
-        struct fuse_release_in *req = data;
-        struct handle *h = id_to_ptr(req->fh);
-        TRACE("RELEASE %p(%d)\n", h, h->fd);
-        close(h->fd);
-        free(h);
-        fuse_status(fuse, hdr->unique, 0);
-        return;
+        const struct fuse_release_in *req = data;
+        return handle_release(fuse, handler, hdr, req);
     }
-//    case FUSE_FSYNC:
+
+    case FUSE_FSYNC: {
+        const struct fuse_fsync_in *req = data;
+        return handle_fsync(fuse, handler, hdr, req);
+    }
+
 //    case FUSE_SETXATTR:
 //    case FUSE_GETXATTR:
 //    case FUSE_LISTXATTR:
 //    case FUSE_REMOVEXATTR:
-    case FUSE_FLUSH:
-        fuse_status(fuse, hdr->unique, 0);
-        return;
+    case FUSE_FLUSH: {
+        return handle_flush(fuse, handler, hdr);
+    }
+
     case FUSE_OPENDIR: { /* open_in -> open_out */
-        struct fuse_open_in *req = data;
-        struct fuse_open_out out;
-        char *path, buffer[PATH_BUFFER_SIZE];
-        struct dirhandle *h;
-
-        h = malloc(sizeof(*h));
-        if (!h) {
-            fuse_status(fuse, hdr->unique, -ENOMEM);
-            return;
-        }
-
-        path = node_get_path(node, buffer, 0);
-        TRACE("OPENDIR %llx '%s'\n", hdr->nodeid, path);
-        h->d = opendir(path);
-        if (h->d == 0) {
-            ERROR("ERROR\n");
-            fuse_status(fuse, hdr->unique, -errno);
-            free(h);
-            return;
-        }
-        out.fh = ptr_to_id(h);
-        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-        return;
+        const struct fuse_open_in *req = data;
+        return handle_opendir(fuse, handler, hdr, req);
     }
+
     case FUSE_READDIR: {
-        struct fuse_read_in *req = data;
-        char buffer[8192];
-        struct fuse_dirent *fde = (struct fuse_dirent*) buffer;
-        struct dirent *de;
-        struct dirhandle *h = id_to_ptr(req->fh);
-        TRACE("READDIR %p\n", h);
-        if (req->offset == 0) {
-            /* rewinddir() might have been called above us, so rewind here too */
-            TRACE("calling rewinddir()\n");
-            rewinddir(h->d);
-        }
-        de = readdir(h->d);
-        if (!de) {
-            fuse_status(fuse, hdr->unique, 0);
-            return;
-        }
-        fde->ino = FUSE_UNKNOWN_INO;
-        /* increment the offset so we can detect when rewinddir() seeks back to the beginning */
-        fde->off = req->offset + 1;
-        fde->type = de->d_type;
-        fde->namelen = strlen(de->d_name);
-        memcpy(fde->name, de->d_name, fde->namelen + 1);
-        fuse_reply(fuse, hdr->unique, fde,
-                   FUSE_DIRENT_ALIGN(sizeof(struct fuse_dirent) + fde->namelen));
-        return;
+        const struct fuse_read_in *req = data;
+        return handle_readdir(fuse, handler, hdr, req);
     }
+
     case FUSE_RELEASEDIR: { /* release_in -> */
-        struct fuse_release_in *req = data;
-        struct dirhandle *h = id_to_ptr(req->fh);
-        TRACE("RELEASEDIR %p\n",h);
-        closedir(h->d);
-        free(h);
-        fuse_status(fuse, hdr->unique, 0);
-        return;
+        const struct fuse_release_in *req = data;
+        return handle_releasedir(fuse, handler, hdr, req);
     }
+
 //    case FUSE_FSYNCDIR:
     case FUSE_INIT: { /* init_in -> init_out */
-        struct fuse_init_in *req = data;
-        struct fuse_init_out out;
-        
-        TRACE("INIT ver=%d.%d maxread=%d flags=%x\n",
-                req->major, req->minor, req->max_readahead, req->flags);
-
-        out.major = FUSE_KERNEL_VERSION;
-        out.minor = FUSE_KERNEL_MINOR_VERSION;
-        out.max_readahead = req->max_readahead;
-        out.flags = FUSE_ATOMIC_O_TRUNC;
-        out.max_background = 32;
-        out.congestion_threshold = 32;
-        out.max_write = 256 * 1024;
-
-        fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-        return;
+        const struct fuse_init_in *req = data;
+        return handle_init(fuse, handler, hdr, req);
     }
+
     default: {
-        struct fuse_out_header h;
-        ERROR("NOTIMPL op=%d uniq=%llx nid=%llx\n",
-                hdr->opcode, hdr->unique, hdr->nodeid);
-
-        oops:
-        h.len = sizeof(h);
-        h.error = -ENOSYS;
-        h.unique = hdr->unique;
-        write(fuse->fd, &h, sizeof(h));
-        break;
+        TRACE("[%d] NOTIMPL op=%d uniq=%llx nid=%llx\n",
+                handler->token, hdr->opcode, hdr->unique, hdr->nodeid);
+        return -ENOSYS;
     }
-    }   
+    }
 }
 
-void handle_fuse_requests(struct fuse *fuse)
+static void handle_fuse_requests(struct fuse_handler* handler)
 {
-    unsigned char req[256 * 1024 + 128];
-    int len;
-    
+    struct fuse* fuse = handler->fuse;
     for (;;) {
-        len = read(fuse->fd, req, 8192);
+        ssize_t len = read(fuse->fd,
+                handler->request_buffer, sizeof(handler->request_buffer));
         if (len < 0) {
-            if (errno == EINTR)
-                continue;
-            ERROR("handle_fuse_requests: errno=%d\n", errno);
-            return;
+            if (errno != EINTR) {
+                ERROR("[%d] handle_fuse_requests: errno=%d\n", handler->token, errno);
+            }
+            continue;
         }
-        handle_fuse_request(fuse, (void*) req, (void*) (req + sizeof(struct fuse_in_header)), len);
+
+        if ((size_t)len < sizeof(struct fuse_in_header)) {
+            ERROR("[%d] request too short: len=%zu\n", handler->token, (size_t)len);
+            continue;
+        }
+
+        const struct fuse_in_header *hdr = (void*)handler->request_buffer;
+        if (hdr->len != (size_t)len) {
+            ERROR("[%d] malformed header: len=%zu, hdr->len=%u\n",
+                    handler->token, (size_t)len, hdr->len);
+            continue;
+        }
+
+        const void *data = handler->request_buffer + sizeof(struct fuse_in_header);
+        size_t data_len = len - sizeof(struct fuse_in_header);
+        __u64 unique = hdr->unique;
+        int res = handle_fuse_request(fuse, handler, hdr, data, data_len);
+
+        /* We do not access the request again after this point because the underlying
+         * buffer storage may have been reused while processing the request. */
+
+        if (res != NO_STATUS) {
+            if (res) {
+                TRACE("[%d] ERROR %d\n", handler->token, res);
+            }
+            fuse_status(fuse, unique, res);
+        }
     }
 }
 
+static void* start_handler(void* data)
+{
+    struct fuse_handler* handler = data;
+    handle_fuse_requests(handler);
+    return NULL;
+}
+
+static int ignite_fuse(struct fuse* fuse, int num_threads)
+{
+    struct fuse_handler* handlers;
+    int i;
+
+    handlers = malloc(num_threads * sizeof(struct fuse_handler));
+    if (!handlers) {
+        ERROR("cannot allocate storage for threads");
+        return -ENOMEM;
+    }
+
+    for (i = 0; i < num_threads; i++) {
+        handlers[i].fuse = fuse;
+        handlers[i].token = i;
+    }
+
+    for (i = 1; i < num_threads; i++) {
+        pthread_t thread;
+        int res = pthread_create(&thread, NULL, start_handler, &handlers[i]);
+        if (res) {
+            ERROR("failed to start thread #%d, error=%d", i, res);
+            goto quit;
+        }
+    }
+    handle_fuse_requests(&handlers[0]);
+    ERROR("terminated prematurely");
+
+    /* don't bother killing all of the other threads or freeing anything,
+     * should never get here anyhow */
+quit:
+    exit(1);
+}
+
 static int usage()
 {
-    ERROR("usage: sdcard [-l -f] <path> <uid> <gid>\n\n\t-l force file names to lower case when creating new files\n\t-f fix up file system before starting (repairs bad file name case and group ownership)\n");
-    return -1;
+    ERROR("usage: sdcard [-t<threads>] <path> <uid> <gid>\n"
+            "    -t<threads>: specify number of threads to use, default -t%d\n"
+            "\n", DEFAULT_NUM_THREADS);
+    return 1;
+}
+
+static int run(const char* path, uid_t uid, gid_t gid, int num_threads)
+{
+    int fd;
+    char opts[256];
+    int res;
+    struct fuse fuse;
+
+    /* cleanup from previous instance, if necessary */
+    umount2(MOUNT_POINT, 2);
+
+    fd = open("/dev/fuse", O_RDWR);
+    if (fd < 0){
+        ERROR("cannot open fuse device (error %d)\n", errno);
+        return -1;
+    }
+
+    snprintf(opts, sizeof(opts),
+            "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
+            fd, uid, gid);
+
+    res = mount("/dev/fuse", MOUNT_POINT, "fuse", MS_NOSUID | MS_NODEV, opts);
+    if (res < 0) {
+        ERROR("cannot mount fuse filesystem (error %d)\n", errno);
+        goto error;
+    }
+
+    res = setgid(gid);
+    if (res < 0) {
+        ERROR("cannot setgid (error %d)\n", errno);
+        goto error;
+    }
+
+    res = setuid(uid);
+    if (res < 0) {
+        ERROR("cannot setuid (error %d)\n", errno);
+        goto error;
+    }
+
+    fuse_init(&fuse, fd, path);
+
+    umask(0);
+    res = ignite_fuse(&fuse, num_threads);
+
+    /* we do not attempt to umount the file system here because we are no longer
+     * running as the root user */
+
+error:
+    close(fd);
+    return res;
 }
 
 int main(int argc, char **argv)
 {
-    struct fuse fuse;
-    char opts[256];
-    int fd;
     int res;
     const char *path = NULL;
+    uid_t uid = 0;
+    gid_t gid = 0;
+    int num_threads = DEFAULT_NUM_THREADS;
     int i;
 
     for (i = 1; i < argc; i++) {
         char* arg = argv[i];
-        if (!path)
+        if (!strncmp(arg, "-t", 2))
+            num_threads = strtoul(arg + 2, 0, 10);
+        else if (!path)
             path = arg;
-        else if (uid == -1)
+        else if (!uid)
             uid = strtoul(arg, 0, 10);
-        else if (gid == -1)
+        else if (!gid)
             gid = strtoul(arg, 0, 10);
         else {
             ERROR("too many arguments\n");
@@ -985,42 +1330,15 @@
         ERROR("no path specified\n");
         return usage();
     }
-    if (uid <= 0 || gid <= 0) {
+    if (!uid || !gid) {
         ERROR("uid and gid must be nonzero\n");
         return usage();
     }
-
-        /* cleanup from previous instance, if necessary */
-    umount2(MOUNT_POINT, 2);
-
-    fd = open("/dev/fuse", O_RDWR);
-    if (fd < 0){
-        ERROR("cannot open fuse device (%d)\n", errno);
-        return -1;
+    if (num_threads < 1) {
+        ERROR("number of threads must be at least 1\n");
+        return usage();
     }
 
-    sprintf(opts, "fd=%i,rootmode=40000,default_permissions,allow_other,"
-            "user_id=%d,group_id=%d", fd, uid, gid);
-    
-    res = mount("/dev/fuse", MOUNT_POINT, "fuse", MS_NOSUID | MS_NODEV, opts);
-    if (res < 0) {
-        ERROR("cannot mount fuse filesystem (%d)\n", errno);
-        return -1;
-    }
-
-    if (setgid(gid) < 0) {
-        ERROR("cannot setgid!\n");
-        return -1;
-    }
-    if (setuid(uid) < 0) {
-        ERROR("cannot setuid!\n");
-        return -1;
-    }
-
-    fuse_init(&fuse, fd, path);
-
-    umask(0);
-    handle_fuse_requests(&fuse);
-    
-    return 0;
+    res = run(path, uid, gid, num_threads);
+    return res < 0 ? 1 : 0;
 }
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index 7e20448..be95e7c 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -58,6 +58,21 @@
 	lsof \
 	md5
 
+ifeq ($(HAVE_SELINUX),true)
+
+TOOLS += \
+	getenforce \
+	setenforce \
+	chcon \
+	restorecon \
+	runcon \
+	getsebool \
+	setsebool \
+	load_policy
+
+endif
+
+
 ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
 TOOLS += r
 endif
@@ -71,6 +86,14 @@
 
 LOCAL_C_INCLUDES := bionic/libc/bionic
 
+ifeq ($(HAVE_SELINUX),true)
+
+LOCAL_CFLAGS += -DHAVE_SELINUX
+LOCAL_SHARED_LIBRARIES += libselinux
+LOCAL_C_INCLUDES += external/libselinux/include
+
+endif
+
 LOCAL_MODULE:= toolbox
 
 # Including this will define $(intermediates).
diff --git a/toolbox/chcon.c b/toolbox/chcon.c
new file mode 100644
index 0000000..d594b9b
--- /dev/null
+++ b/toolbox/chcon.c
@@ -0,0 +1,25 @@
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <selinux/selinux.h>
+
+int chcon_main(int argc, char **argv)
+{
+    int rc, i;
+
+    if (argc < 3) {
+        fprintf(stderr, "usage:  %s context path...\n", argv[0]);
+        exit(1);
+    }
+
+    for (i = 2; i < argc; i++) {
+        rc = setfilecon(argv[i], argv[1]);
+        if (rc < 0) {
+            fprintf(stderr, "%s:  Could not label %s with %s:  %s\n",
+                    argv[0], argv[i], argv[1], strerror(errno));
+            exit(2);
+        }
+    }
+    exit(0);
+}
diff --git a/toolbox/chown.c b/toolbox/chown.c
index e9d108b..92efee6 100644
--- a/toolbox/chown.c
+++ b/toolbox/chown.c
@@ -15,7 +15,7 @@
     int i;
 
     if (argc < 3) {
-        fprintf(stderr, "Usage: chown <USER>[.GROUP] <FILE1> [FILE2] ...\n");
+        fprintf(stderr, "Usage: chown <USER>[:GROUP] <FILE1> [FILE2] ...\n");
         return 10;
     }
 
@@ -24,7 +24,9 @@
     char user[32];
     char *group = NULL;
     strncpy(user, argv[1], sizeof(user));
-    if ((group = strchr(user, '.')) != NULL) {
+    if ((group = strchr(user, ':')) != NULL) {
+        *group++ = '\0';
+    } else if ((group = strchr(user, '.')) != NULL) {
         *group++ = '\0';
     }
 
@@ -62,7 +64,7 @@
 
     for (i = 2; i < argc; i++) {
         if (chown(argv[i], uid, gid) < 0) {
-            fprintf(stderr, "Unable to chmod %s: %s\n", argv[i], strerror(errno));
+            fprintf(stderr, "Unable to chown %s: %s\n", argv[i], strerror(errno));
             return 10;
         }
     }
diff --git a/toolbox/dd.c b/toolbox/dd.c
index c6af3ea..53a6206 100644
--- a/toolbox/dd.c
+++ b/toolbox/dd.c
@@ -64,7 +64,7 @@
 
 #include "dd.h"
 
-#define NO_CONV
+//#define NO_CONV
 
 //#include "extern.h"
 void block(void);
@@ -91,12 +91,9 @@
 extern u_int		files_cnt;
 extern int		progress;
 extern const u_char	*ctab;
-extern const u_char	a2e_32V[], a2e_POSIX[];
-extern const u_char	e2a_32V[], e2a_POSIX[];
-extern const u_char	a2ibm_32V[], a2ibm_POSIX[];
-extern u_char		casetab[];
 
 
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
 #define MAX(a, b) ((a) > (b) ? (a) : (b))
 
 static void dd_close(void);
@@ -243,42 +240,6 @@
 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
 
-	/*
-	 * If converting case at the same time as another conversion, build a
-	 * table that does both at once.  If just converting case, use the
-	 * built-in tables.
-	 */
-	if (ddflags & (C_LCASE|C_UCASE)) {
-#ifdef	NO_CONV
-		/* Should not get here, but just in case... */
-		fprintf(stderr, "case conv and -DNO_CONV\n");
-		exit(1);
-		/* NOTREACHED */
-#else	/* NO_CONV */
-		u_int cnt;
-
-		if (ddflags & C_ASCII || ddflags & C_EBCDIC) {
-			if (ddflags & C_LCASE) {
-				for (cnt = 0; cnt < 0377; ++cnt)
-					casetab[cnt] = tolower(ctab[cnt]);
-			} else {
-				for (cnt = 0; cnt < 0377; ++cnt)
-					casetab[cnt] = toupper(ctab[cnt]);
-			}
-		} else {
-			if (ddflags & C_LCASE) {
-				for (cnt = 0; cnt < 0377; ++cnt)
-					casetab[cnt] = tolower(cnt);
-			} else {
-				for (cnt = 0; cnt < 0377; ++cnt)
-					casetab[cnt] = toupper(cnt);
-			}
-		}
-
-		ctab = casetab;
-#endif	/* NO_CONV */
-	}
-
 	(void)gettimeofday(&st.start, NULL);	/* Statistics timestamp. */
 }
 
@@ -796,6 +757,9 @@
 void
 def_close(void)
 {
+	if (ddflags & C_FDATASYNC) {
+		fdatasync(out.fd);
+	}
 
 	/* Just update the count, everything is already in the buffer. */
 	if (in.dbcnt)
@@ -1301,21 +1265,14 @@
 	u_int set, noset;
 	const u_char *ctab;
 } clist[] = {
-	{ "ascii",	C_ASCII,	C_EBCDIC,	e2a_POSIX },
 	{ "block",	C_BLOCK,	C_UNBLOCK,	NULL },
-	{ "ebcdic",	C_EBCDIC,	C_ASCII,	a2e_POSIX },
-	{ "ibm",	C_EBCDIC,	C_ASCII,	a2ibm_POSIX },
-	{ "lcase",	C_LCASE,	C_UCASE,	NULL },
+	{ "fdatasync",	C_FDATASYNC,	0,		NULL },
 	{ "noerror",	C_NOERROR,	0,		NULL },
 	{ "notrunc",	C_NOTRUNC,	0,		NULL },
-	{ "oldascii",	C_ASCII,	C_EBCDIC,	e2a_32V },
-	{ "oldebcdic",	C_EBCDIC,	C_ASCII,	a2e_32V },
-	{ "oldibm",	C_EBCDIC,	C_ASCII,	a2ibm_32V },
 	{ "osync",	C_OSYNC,	C_BS,		NULL },
 	{ "sparse",	C_SPARSE,	0,		NULL },
 	{ "swab",	C_SWAB,		0,		NULL },
 	{ "sync",	C_SYNC,		0,		NULL },
-	{ "ucase",	C_UCASE,	C_LCASE,	NULL },
 	{ "unblock",	C_UNBLOCK,	C_BLOCK,	NULL },
 	/* If you add items to this table, be sure to add the
 	 * conversions to the C_BS check in the jcl routine above.
diff --git a/toolbox/dd.h b/toolbox/dd.h
index cca1024..89f2833 100644
--- a/toolbox/dd.h
+++ b/toolbox/dd.h
@@ -91,3 +91,4 @@
 #define	C_UNBLOCK	0x80000
 #define	C_OSYNC		0x100000
 #define	C_SPARSE	0x200000
+#define	C_FDATASYNC	0x400000
diff --git a/toolbox/getenforce.c b/toolbox/getenforce.c
new file mode 100644
index 0000000..9e7589a
--- /dev/null
+++ b/toolbox/getenforce.c
@@ -0,0 +1,30 @@
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <selinux/selinux.h>
+
+int getenforce_main(int argc, char **argv)
+{
+    int rc;
+
+    rc = is_selinux_enabled();
+    if (rc <= 0) {
+        printf("Disabled\n");
+        return 0;
+    }
+
+    rc = security_getenforce();
+    if (rc < 0) {
+        fprintf(stderr, "Could not get enforcing status:  %s\n",
+                strerror(errno));
+        return 2;
+    }
+
+    if (rc)
+        printf("Enforcing\n");
+    else
+        printf("Permissive\n");
+
+    return 0;
+}
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/getsebool.c b/toolbox/getsebool.c
new file mode 100644
index 0000000..aab5200
--- /dev/null
+++ b/toolbox/getsebool.c
@@ -0,0 +1,104 @@
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <getopt.h>
+#include <errno.h>
+#include <string.h>
+#include <selinux/selinux.h>
+
+static void usage(const char *progname)
+{
+    fprintf(stderr, "usage:  %s -a or %s boolean...\n", progname, progname);
+    exit(1);
+}
+
+int getsebool_main(int argc, char **argv)
+{
+    int i, get_all = 0, rc = 0, active, pending, len = 0, opt;
+    char **names;
+
+    while ((opt = getopt(argc, argv, "a")) > 0) {
+        switch (opt) {
+        case 'a':
+            if (argc > 2)
+                usage(argv[0]);
+            if (is_selinux_enabled() <= 0) {
+                fprintf(stderr, "%s:  SELinux is disabled\n",
+                        argv[0]);
+                return 1;
+            }
+            errno = 0;
+            rc = security_get_boolean_names(&names, &len);
+            if (rc) {
+                fprintf(stderr,
+                        "%s:  Unable to get boolean names:  %s\n",
+                        argv[0], strerror(errno));
+                return 1;
+            }
+            if (!len) {
+                printf("No booleans\n");
+                return 0;
+            }
+            get_all = 1;
+            break;
+        default:
+            usage(argv[0]);
+        }
+    }
+
+    if (is_selinux_enabled() <= 0) {
+        fprintf(stderr, "%s:  SELinux is disabled\n", argv[0]);
+        return 1;
+    }
+    if (!len) {
+        if (argc < 2)
+            usage(argv[0]);
+        len = argc - 1;
+        names = malloc(sizeof(char *) * len);
+        if (!names) {
+            fprintf(stderr, "%s:  out of memory\n", argv[0]);
+            return 2;
+        }
+        for (i = 0; i < len; i++) {
+            names[i] = strdup(argv[i + 1]);
+            if (!names[i]) {
+                fprintf(stderr, "%s:  out of memory\n",
+                        argv[0]);
+                return 2;
+            }
+        }
+    }
+
+    for (i = 0; i < len; i++) {
+        active = security_get_boolean_active(names[i]);
+        if (active < 0) {
+            if (get_all && errno == EACCES)
+                continue;
+            fprintf(stderr, "Error getting active value for %s\n",
+                    names[i]);
+            rc = -1;
+            goto out;
+        }
+        pending = security_get_boolean_pending(names[i]);
+        if (pending < 0) {
+            fprintf(stderr, "Error getting pending value for %s\n",
+                    names[i]);
+            rc = -1;
+            goto out;
+        }
+        if (pending != active) {
+            printf("%s --> %s pending: %s\n", names[i],
+                   (active ? "on" : "off"),
+                   (pending ? "on" : "off"));
+        } else {
+            printf("%s --> %s\n", names[i],
+                   (active ? "on" : "off"));
+        }
+    }
+
+out:
+    for (i = 0; i < len; i++)
+        free(names[i]);
+    free(names);
+    return rc;
+}
diff --git a/toolbox/id.c b/toolbox/id.c
index bb03cad..bc79288 100644
--- a/toolbox/id.c
+++ b/toolbox/id.c
@@ -5,6 +5,10 @@
 #include <pwd.h>
 #include <grp.h>
 
+#ifdef HAVE_SELINUX
+#include <selinux/selinux.h>
+#endif
+
 static void print_uid(uid_t uid)
 {
     struct passwd *pw = getpwuid(uid);
@@ -30,6 +34,9 @@
 {
     gid_t list[64];
     int n, max;
+#ifdef HAVE_SELINUX
+    char *secctx;
+#endif
 
     max = getgroups(64, list);
     if (max < 0) max = 0;
@@ -46,6 +53,12 @@
             print_gid(list[n]);
         }
     }
+#ifdef HAVE_SELINUX
+    if (getcon(&secctx) == 0) {
+        printf(" context=%s", secctx);
+        free(secctx);
+    }
+#endif
     printf("\n");
     return 0;
 }
diff --git a/toolbox/kill.c b/toolbox/kill.c
index 4d0e479..b79805f 100644
--- a/toolbox/kill.c
+++ b/toolbox/kill.c
@@ -5,16 +5,127 @@
 #include <sys/types.h>
 #include <signal.h>
 
+static struct {
+    unsigned int number;
+    char *name;
+} signals[] = {
+#define _SIG(name) {SIG##name, #name}
+    /* Single Unix Specification signals */
+    _SIG(ABRT),
+    _SIG(ALRM),
+    _SIG(FPE),
+    _SIG(HUP),
+    _SIG(ILL),
+    _SIG(INT),
+    _SIG(KILL),
+    _SIG(PIPE),
+    _SIG(QUIT),
+    _SIG(SEGV),
+    _SIG(TERM),
+    _SIG(USR1),
+    _SIG(USR2),
+    _SIG(CHLD),
+    _SIG(CONT),
+    _SIG(STOP),
+    _SIG(TSTP),
+    _SIG(TTIN),
+    _SIG(TTOU),
+    _SIG(BUS),
+    _SIG(POLL),
+    _SIG(PROF),
+    _SIG(SYS),
+    _SIG(TRAP),
+    _SIG(URG),
+    _SIG(VTALRM),
+    _SIG(XCPU),
+    _SIG(XFSZ),
+    /* non-SUS signals */
+    _SIG(IO),
+    _SIG(PWR),
+    _SIG(STKFLT),
+    _SIG(WINCH),
+#undef _SIG
+};
+
+/* To indicate a matching signal was not found */
+static const unsigned int SENTINEL = (unsigned int) -1;
+
+void list_signals()
+{
+    unsigned int sorted_signals[_NSIG];
+    unsigned int i;
+    unsigned int num;
+
+    memset(sorted_signals, SENTINEL, sizeof(sorted_signals));
+
+    // Sort the signals
+    for (i = 0; i < sizeof(signals)/sizeof(signals[0]); i++) {
+        sorted_signals[signals[i].number] = i;
+    }
+
+    num = 0;
+    for (i = 1; i < _NSIG; i++) {
+        unsigned int index = sorted_signals[i];
+        if (index == SENTINEL) {
+            continue;
+        }
+
+        fprintf(stderr, "%2d) SIG%-9s ", i, signals[index].name);
+
+        if ((num++ % 4) == 3) {
+            fprintf(stderr, "\n");
+        }
+    }
+
+    if ((num % 4) == 3) {
+        fprintf(stderr, "\n");
+    }
+}
+
+unsigned int name_to_signal(const char* name)
+{
+    unsigned int i;
+
+    for (i = 1; i < sizeof(signals) / sizeof(signals[0]); i++) {
+        if (!strcasecmp(name, signals[i].name)) {
+            return signals[i].number;
+        }
+    }
+
+    return SENTINEL;
+}
+
 int kill_main(int argc, char **argv)
 {
-    int sig = SIGTERM;
+    unsigned int sig = SIGTERM;
     int result = 0;
-    
+
     argc--;
     argv++;
 
-    if(argc >= 2 && argv[0][0] == '-'){
-        sig = atoi(argv[0] + 1);
+    if (argc >= 1 && argv[0][0] == '-') {
+        char *endptr;
+        size_t arg_len = strlen(argv[0]);
+        if (arg_len < 2) {
+            fprintf(stderr, "invalid argument: -\n");
+            return -1;
+        }
+
+        char* arg = argv[0] + 1;
+        if (arg_len == 2 && *arg == 'l') {
+            list_signals();
+            return 0;
+        }
+
+        sig = strtol(arg, &endptr, 10);
+        if (*endptr != '\0') {
+            sig = name_to_signal(arg);
+            if (sig == SENTINEL) {
+                fprintf(stderr, "invalid signal name: %s\n", arg);
+                return -1;
+            }
+        }
+
         argc--;
         argv++;
     }
@@ -26,10 +137,10 @@
             result = err;
             fprintf(stderr, "could not kill pid %d: %s\n", pid, strerror(errno));
         }
-            
+
         argc--;
         argv++;
     }
-    
+
     return result;
 }
diff --git a/toolbox/load_policy.c b/toolbox/load_policy.c
new file mode 100644
index 0000000..eb5aba6
--- /dev/null
+++ b/toolbox/load_policy.c
@@ -0,0 +1,49 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+#include <errno.h>
+#include <selinux/selinux.h>
+
+int load_policy_main(int argc, char **argv)
+{
+    int fd, rc, vers;
+    struct stat sb;
+    void *map;
+    const char *path;
+
+    if (argc != 2) {
+        fprintf(stderr, "usage:  %s policy-file\n", argv[0]);
+        exit(1);
+    }
+
+    path = argv[1];
+    fd = open(path, O_RDONLY);
+    if (fd < 0) {
+        fprintf(stderr, "Could not open %s:  %s\n", path, strerror(errno));
+        exit(2);
+    }
+
+    if (fstat(fd, &sb) < 0) {
+        fprintf(stderr, "Could not stat %s:  %s\n", path, strerror(errno));
+        exit(3);
+    }
+
+    map = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
+    if (map == MAP_FAILED) {
+        fprintf(stderr, "Could not mmap %s:  %s\n", path, strerror(errno));
+        exit(4);
+    }
+
+    rc = security_load_policy(map, sb.st_size);
+    if (rc < 0) {
+        fprintf(stderr, "Could not load %s:  %s\n", path, strerror(errno));
+        exit(5);
+    }
+    munmap(map, sb.st_size);
+    close(fd);
+    exit(0);
+}
diff --git a/toolbox/ls.c b/toolbox/ls.c
index bee365c..a4db99c 100644
--- a/toolbox/ls.c
+++ b/toolbox/ls.c
@@ -5,6 +5,10 @@
 #include <dirent.h>
 #include <errno.h>
 
+#ifdef HAVE_SELINUX
+#include <selinux/selinux.h>
+#endif
+
 #include <sys/stat.h>
 #include <unistd.h>
 #include <time.h>
@@ -25,6 +29,7 @@
 #define LIST_SIZE           (1 << 4)
 #define LIST_LONG_NUMERIC   (1 << 5)
 #define LIST_CLASSIFY       (1 << 6)
+#define LIST_MACLABEL       (1 << 7)
 
 // fwd
 static int listpath(const char *name, int flags);
@@ -234,9 +239,75 @@
     return 0;
 }
 
+static int listfile_maclabel(const char *path, int flags)
+{
+    struct stat s;
+    char mode[16];
+    char user[16];
+    char group[16];
+    char *maclabel = NULL;
+    const char *name;
+
+    /* name is anything after the final '/', or the whole path if none*/
+    name = strrchr(path, '/');
+    if(name == 0) {
+        name = path;
+    } else {
+        name++;
+    }
+
+    if(lstat(path, &s) < 0) {
+        return -1;
+    }
+
+#ifdef HAVE_SELINUX
+    lgetfilecon(path, &maclabel);
+#else
+    maclabel = strdup("-");
+#endif
+    if (!maclabel) {
+        return -1;
+    }
+
+    mode2str(s.st_mode, mode);
+    user2str(s.st_uid, user);
+    group2str(s.st_gid, group);
+
+    switch(s.st_mode & S_IFMT) {
+    case S_IFLNK: {
+        char linkto[256];
+        int len;
+
+        len = readlink(path, linkto, sizeof(linkto));
+        if(len < 0) return -1;
+
+        if(len > sizeof(linkto)-1) {
+            linkto[sizeof(linkto)-4] = '.';
+            linkto[sizeof(linkto)-3] = '.';
+            linkto[sizeof(linkto)-2] = '.';
+            linkto[sizeof(linkto)-1] = 0;
+        } else {
+            linkto[len] = 0;
+        }
+
+        printf("%s %-8s %-8s          %s %s -> %s\n",
+               mode, user, group, maclabel, name, linkto);
+        break;
+    }
+    default:
+        printf("%s %-8s %-8s          %s %s\n",
+               mode, user, group, maclabel, name);
+
+    }
+
+    free(maclabel);
+
+    return 0;
+}
+
 static int listfile(const char *dirname, const char *filename, int flags)
 {
-    if ((flags & (LIST_LONG | LIST_SIZE | LIST_CLASSIFY)) == 0) {
+    if ((flags & LIST_LONG | LIST_SIZE | LIST_CLASSIFY | LIST_MACLABEL) == 0) {
         printf("%s\n", filename);
         return 0;
     }
@@ -251,7 +322,9 @@
         pathname = filename;
     }
 
-    if ((flags & LIST_LONG) != 0) {
+    if ((flags & LIST_MACLABEL) != 0) {
+        return listfile_maclabel(pathname, flags);
+    } else if ((flags & LIST_LONG) != 0) {
         return listfile_long(pathname, flags);
     } else /*((flags & LIST_SIZE) != 0)*/ {
         return listfile_size(pathname, filename, flags);
@@ -386,6 +459,7 @@
                     case 's': flags |= LIST_SIZE; break;
                     case 'R': flags |= LIST_RECURSIVE; break;
                     case 'd': flags |= LIST_DIRECTORIES; break;
+                    case 'Z': flags |= LIST_MACLABEL; break;
                     case 'a': flags |= LIST_ALL; break;
                     case 'F': flags |= LIST_CLASSIFY; break;
                     default:
diff --git a/toolbox/lsof.c b/toolbox/lsof.c
index 4e2f77a..376a642 100644
--- a/toolbox/lsof.c
+++ b/toolbox/lsof.c
@@ -178,8 +178,7 @@
     if (!stat(info.path, &pidstat)) {
         pw = getpwuid(pidstat.st_uid);
         if (pw) {
-            strncpy(info.user, pw->pw_name, USER_DISPLAY_MAX - 1);
-            info.user[USER_DISPLAY_MAX - 1] = '\0';
+            strlcpy(info.user, pw->pw_name, sizeof(info.user));
         } else {
             snprintf(info.user, USER_DISPLAY_MAX, "%d", (int)pidstat.st_uid);
         }
@@ -194,18 +193,20 @@
         fprintf(stderr, "Couldn't read %s\n", info.path);
         return;
     }
+
     char cmdline[PATH_MAX];
-    if (read(fd, cmdline, sizeof(cmdline)) < 0) {
+    int numRead = read(fd, cmdline, sizeof(cmdline) - 1);
+    close(fd);
+
+    if (numRead < 0) {
         fprintf(stderr, "Error reading cmdline: %s: %s\n", info.path, strerror(errno));
-        close(fd);
         return;
     }
-    close(fd);
-    info.path[info.parent_length] = '\0';
+
+    cmdline[numRead] = '\0';
 
     // We only want the basename of the cmdline
-    strncpy(info.cmdline, basename(cmdline), sizeof(info.cmdline));
-    info.cmdline[sizeof(info.cmdline)-1] = '\0';
+    strlcpy(info.cmdline, basename(cmdline), sizeof(info.cmdline));
 
     // Read each of these symlinks
     print_type("cwd", &info);
diff --git a/toolbox/newfs_msdos.c b/toolbox/newfs_msdos.c
index ff9e844..6d78eb6 100644
--- a/toolbox/newfs_msdos.c
+++ b/toolbox/newfs_msdos.c
@@ -431,7 +431,8 @@
 		bpb.spc = 8;
 	    else if (bpb.bsec <= (1<<19)) /* 256M -> 8k */
 		bpb.spc = 16;
-	    else if (bpb.bsec <= (1<<21)) /* 1G -> 16k */
+	    else if (bpb.bsec <= (1<<22)) /* 2G -> 16k, some versions of windows
+					     require a minimum of 65527 clusters */
 		bpb.spc = 32;
 	    else
 		bpb.spc = 64;		/* otherwise 32k */
diff --git a/toolbox/powerd.c b/toolbox/powerd.c
deleted file mode 100644
index 1f29a8b..0000000
--- a/toolbox/powerd.c
+++ /dev/null
@@ -1,441 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <string.h>
-#include <errno.h>
-#include <time.h>
-#include <sys/select.h>
-#include <sys/inotify.h>
-
-#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
-
-//#include <linux/input.h> // this does not compile
-
-// from <linux/input.h>
-
-struct input_event {
-	struct timeval time;
-	__u16 type;
-	__u16 code;
-	__s32 value;
-};
-
-#define EVIOCGVERSION		_IOR('E', 0x01, int)			/* get driver version */
-#define EVIOCGID		_IOR('E', 0x02, struct input_id)	/* get device ID */
-#define EVIOCGKEYCODE		_IOR('E', 0x04, int[2])			/* get keycode */
-#define EVIOCSKEYCODE		_IOW('E', 0x04, int[2])			/* set keycode */
-
-#define EVIOCGNAME(len)		_IOC(_IOC_READ, 'E', 0x06, len)		/* get device name */
-#define EVIOCGPHYS(len)		_IOC(_IOC_READ, 'E', 0x07, len)		/* get physical location */
-#define EVIOCGUNIQ(len)		_IOC(_IOC_READ, 'E', 0x08, len)		/* get unique identifier */
-
-#define EVIOCGKEY(len)		_IOC(_IOC_READ, 'E', 0x18, len)		/* get global keystate */
-#define EVIOCGLED(len)		_IOC(_IOC_READ, 'E', 0x19, len)		/* get all LEDs */
-#define EVIOCGSND(len)		_IOC(_IOC_READ, 'E', 0x1a, len)		/* get all sounds status */
-#define EVIOCGSW(len)		_IOC(_IOC_READ, 'E', 0x1b, len)		/* get all switch states */
-
-#define EVIOCGBIT(ev,len)	_IOC(_IOC_READ, 'E', 0x20 + ev, len)	/* get event bits */
-#define EVIOCGABS(abs)		_IOR('E', 0x40 + abs, struct input_absinfo)		/* get abs value/limits */
-#define EVIOCSABS(abs)		_IOW('E', 0xc0 + abs, struct input_absinfo)		/* set abs value/limits */
-
-#define EVIOCSFF		_IOC(_IOC_WRITE, 'E', 0x80, sizeof(struct ff_effect))	/* send a force effect to a force feedback device */
-#define EVIOCRMFF		_IOW('E', 0x81, int)			/* Erase a force effect */
-#define EVIOCGEFFECTS		_IOR('E', 0x84, int)			/* Report number of effects playable at the same time */
-
-#define EVIOCGRAB		_IOW('E', 0x90, int)			/* Grab/Release device */
-
-/*
- * Event types
- */
-
-#define EV_SYN			0x00
-#define EV_KEY			0x01
-#define EV_REL			0x02
-#define EV_ABS			0x03
-#define EV_MSC			0x04
-#define EV_SW			0x05
-#define EV_LED			0x11
-#define EV_SND			0x12
-#define EV_REP			0x14
-#define EV_FF			0x15
-#define EV_PWR			0x16
-#define EV_FF_STATUS		0x17
-#define EV_MAX			0x1f
-
-#define KEY_POWER		116
-#define KEY_SLEEP		142
-#define SW_0		0x00
-
-// end <linux/input.h>
-
-struct notify_entry {
-    int id;
-    int (*handler)(struct notify_entry *entry, struct inotify_event *event);
-    const char *filename;
-};
-
-int charging_state_notify_handler(struct notify_entry *entry, struct inotify_event *event)
-{
-    static int state = -1;
-    int last_state;
-    char buf[40];
-    int read_len;
-    int fd;
-
-    last_state = state;
-    fd = open(entry->filename, O_RDONLY);
-    read_len = read(fd, buf, sizeof(buf));
-    if(read_len > 0) {
-        //printf("charging_state_notify_handler: \"%s\"\n", buf);
-        state = !(strncmp(buf, "Unknown", 7) == 0 
-                  || strncmp(buf, "Discharging", 11) == 0);
-    }
-    close(fd);
-    //printf("charging_state_notify_handler: %d -> %d\n", last_state, state);
-    return state > last_state;
-}
-
-struct notify_entry watched_files[] = {
-    {
-        .filename = "/sys/android_power/charging_state",
-        .handler = charging_state_notify_handler
-    }
-};
-
-int call_notify_handler(struct inotify_event *event)
-{
-    unsigned int start, i;
-    start = event->wd - watched_files[0].id;
-    if(start >= ARRAY_SIZE(watched_files))
-        start = 0;
-    //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
-    for(i = start; i < ARRAY_SIZE(watched_files); i++) {
-        if(event->wd == watched_files[i].id) {
-            if(watched_files[i].handler) {
-                return watched_files[i].handler(&watched_files[i], event);
-            }
-            return 1;
-        }
-    }
-    for(i = 0; i < start; i++) {
-        if(event->wd == watched_files[i].id) {
-            if(watched_files[i].handler) {
-                return watched_files[i].handler(&watched_files[i], event);
-            }
-            return 1;
-        }
-    }
-    return 0;
-}
-
-int handle_inotify_event(int nfd)
-{
-    int res;
-    int wake_up = 0;
-    struct inotify_event *event;
-    char event_buf[512];
-    int event_pos = 0;
-
-    res = read(nfd, event_buf, sizeof(event_buf));
-    if(res < (int)sizeof(*event)) {
-        if(errno == EINTR)
-            return 0;
-        fprintf(stderr, "could not get event, %s\n", strerror(errno));
-        return 0;
-    }
-    printf("got %d bytes of event information\n", res);
-    while(res >= (int)sizeof(*event)) {
-        int event_size;
-        event = (struct inotify_event *)(event_buf + event_pos);
-        wake_up |= call_notify_handler(event);
-        event_size = sizeof(*event) + event->len;
-        res -= event_size;
-        event_pos += event_size;
-    }
-    return wake_up;
-}
-
-int powerd_main(int argc, char *argv[])
-{
-    int c;
-    unsigned int i;
-    int res;
-    struct timeval tv;
-    int eventfd;
-    int notifyfd;
-    int powerfd;
-    int powerfd_is_sleep;
-    int user_activity_fd;
-    int acquire_partial_wake_lock_fd;
-    int acquire_full_wake_lock_fd;
-    int release_wake_lock_fd;
-    char *eventdev = "/dev/input/event0";
-    const char *android_sleepdev = "/sys/android_power/request_sleep";
-    const char *android_autooff_dev = "/sys/android_power/auto_off_timeout";
-    const char *android_user_activity_dev = "/sys/android_power/last_user_activity";
-    const char *android_acquire_partial_wake_lock_dev = "/sys/android_power/acquire_partial_wake_lock";
-    const char *android_acquire_full_wake_lock_dev = "/sys/android_power/acquire_full_wake_lock";
-    const char *android_release_wake_lock_dev = "/sys/android_power/release_wake_lock";
-    const char *powerdev = "/sys/power/state";
-    const char suspendstring[] = "standby";
-    const char wakelockstring[] = "powerd";
-    fd_set rfds;
-    struct input_event event;
-    struct input_event light_event;
-    struct input_event light_event2;
-    int gotkey = 1;
-    time_t idle_time = 5;
-    const char *idle_time_string = "5";
-    time_t lcd_light_time = 0;
-    time_t key_light_time = 0;
-    int verbose = 1;
-    int event_sleep = 0;
-    int got_power_key_down = 0;
-    struct timeval power_key_down_time = { 0, 0 };
-
-    light_event.type = EV_LED;
-    light_event.code = 4; // bright lcd backlight
-    light_event.value = 0; // light off -- sleep after timeout
-
-    light_event2.type = EV_LED;
-    light_event2.code = 8; // keyboard backlight
-    light_event2.value = 0; // light off -- sleep after timeout
-
-    do {
-        c = getopt(argc, argv, "e:ni:vql:k:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'e':
-            eventdev = optarg;
-            break;
-        case 'n':
-            gotkey = 0;
-            break;
-        case 'i':
-            idle_time = atoi(optarg);
-            idle_time_string = optarg;
-            break;
-        case 'v':
-            verbose = 2;
-            break;
-        case 'q':
-            verbose = 0;
-            break;
-        case 'l':
-            lcd_light_time = atoi(optarg);
-            break;
-        case 'k':
-            key_light_time = atoi(optarg);
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-    if(optind  != argc) {
-        fprintf(stderr,"%s [-e eventdev]\n", argv[0]);
-        return 1;
-    }
-
-    eventfd = open(eventdev, O_RDWR | O_NONBLOCK);
-    if(eventfd < 0) {
-        fprintf(stderr, "could not open %s, %s\n", eventdev, strerror(errno));
-        return 1;
-    }
-    if(key_light_time >= lcd_light_time) {
-        lcd_light_time = key_light_time + 1;
-        fprintf(stderr,"lcd bright backlight time must be longer than keyboard backlight time.\n"
-            "Setting lcd bright backlight time to %ld seconds\n", lcd_light_time);
-    }
-
-    user_activity_fd = open(android_user_activity_dev, O_RDWR);
-    if(user_activity_fd >= 0) {
-        int auto_off_fd = open(android_autooff_dev, O_RDWR);
-        write(auto_off_fd, idle_time_string, strlen(idle_time_string));
-        close(auto_off_fd);
-    }
-
-    powerfd = open(android_sleepdev, O_RDWR);
-    if(powerfd >= 0) {
-        powerfd_is_sleep = 1;
-        if(verbose > 0)
-            printf("Using android sleep dev: %s\n", android_sleepdev);
-    }
-    else {
-        powerfd_is_sleep = 0;
-        powerfd = open(powerdev, O_RDWR);
-        if(powerfd >= 0) {
-            if(verbose > 0)
-                printf("Using linux power dev: %s\n", powerdev);
-        }
-    }
-    if(powerfd < 0) {
-        fprintf(stderr, "could not open %s, %s\n", powerdev, strerror(errno));
-        return 1;
-    }
-
-    notifyfd = inotify_init();
-    if(notifyfd < 0) {
-        fprintf(stderr, "inotify_init failed, %s\n", strerror(errno));
-        return 1;
-    }
-    fcntl(notifyfd, F_SETFL, O_NONBLOCK | fcntl(notifyfd, F_GETFL));
-    for(i = 0; i < ARRAY_SIZE(watched_files); i++) {
-        watched_files[i].id = inotify_add_watch(notifyfd, watched_files[i].filename, IN_MODIFY);
-        printf("Watching %s, id %d\n", watched_files[i].filename, watched_files[i].id);
-    }
-
-    acquire_partial_wake_lock_fd = open(android_acquire_partial_wake_lock_dev, O_RDWR);
-    acquire_full_wake_lock_fd = open(android_acquire_full_wake_lock_dev, O_RDWR);
-    release_wake_lock_fd = open(android_release_wake_lock_dev, O_RDWR);
-
-    if(user_activity_fd >= 0) {
-        idle_time = 60*60*24; // driver handles real timeout
-    }
-    if(gotkey) {
-        tv.tv_sec = idle_time;
-        tv.tv_usec = 0;
-    }
-    else {
-        tv.tv_sec = 0;
-        tv.tv_usec = 500000;
-    }
-    
-    while(1) {
-        FD_ZERO(&rfds);
-        //FD_SET(0, &rfds);
-        FD_SET(eventfd, &rfds);
-        FD_SET(notifyfd, &rfds);
-        res = select(((notifyfd > eventfd) ? notifyfd : eventfd) + 1, &rfds, NULL, NULL, &tv);
-        if(res < 0) {
-            fprintf(stderr, "select failed, %s\n", strerror(errno));
-            return 1;
-        }
-        if(res == 0) {
-            if(light_event2.value == 1)
-                goto light2_off;
-            if(light_event.value == 1)
-                goto light_off;
-            if(user_activity_fd < 0) {
-                if(gotkey && verbose > 0)
-                    printf("Idle - sleep\n");
-                if(!gotkey && verbose > 1)
-                    printf("Reenter sleep\n");
-                goto sleep;
-            }
-            else {
-                tv.tv_sec = 60*60*24;
-                tv.tv_usec = 0;
-            }
-        }
-        if(res > 0) {
-            //if(FD_ISSET(0, &rfds)) {
-            //  printf("goto data on stdin quit\n");
-            //  return 0;
-            //}
-            if(FD_ISSET(notifyfd, &rfds)) {
-                write(acquire_partial_wake_lock_fd, wakelockstring, sizeof(wakelockstring) - 1);
-                if(handle_inotify_event(notifyfd) > 0) {
-                    write(acquire_full_wake_lock_fd, wakelockstring, sizeof(wakelockstring) - 1);
-                }
-                write(release_wake_lock_fd, wakelockstring, sizeof(wakelockstring) - 1);
-            }
-            if(FD_ISSET(eventfd, &rfds)) {
-                write(acquire_partial_wake_lock_fd, wakelockstring, sizeof(wakelockstring) - 1);
-                res = read(eventfd, &event, sizeof(event));
-                if(res < (int)sizeof(event)) {
-                    fprintf(stderr, "could not get event\n");
-                    write(release_wake_lock_fd, wakelockstring, sizeof(wakelockstring) - 1);
-                    return 1;
-                }
-                if(event.type == EV_PWR && event.code == KEY_SLEEP) {
-                    event_sleep = event.value;
-                }
-                if(event.type == EV_KEY || (event.type == EV_SW && event.code == SW_0 && event.value == 1)) {
-                    gotkey = 1;
-                    if(user_activity_fd >= 0) {
-                        char buf[32];
-                        int len;
-                        len = sprintf(buf, "%ld%06lu000", event.time.tv_sec, event.time.tv_usec);
-                        write(user_activity_fd, buf, len);
-                    }
-                    if(lcd_light_time | key_light_time) {
-                        tv.tv_sec = key_light_time;
-                        light_event.value = 1;
-                        write(eventfd, &light_event, sizeof(light_event));
-                        light_event2.value = 1;
-                        write(eventfd, &light_event2, sizeof(light_event2));
-                    }
-                    else {
-                        tv.tv_sec = idle_time;
-                    }
-                    tv.tv_usec = 0;
-                    if(verbose > 1)
-                        printf("got %s %s %d%s\n", event.type == EV_KEY ? "key" : "switch", event.value ? "down" : "up", event.code, event_sleep ? " from sleep" : "");
-                    if(event.code == KEY_POWER) {
-                        if(event.value == 0) {
-                            int tmp_got_power_key_down = got_power_key_down;
-                            got_power_key_down = 0;
-                            if(tmp_got_power_key_down) {
-                                // power key released
-                                if(verbose > 0)
-                                    printf("Power key released - sleep\n");
-                                write(release_wake_lock_fd, wakelockstring, sizeof(wakelockstring) - 1);
-                                goto sleep;
-                            }
-                        }
-                        else if(event_sleep == 0) {
-                            got_power_key_down = 1;
-                            power_key_down_time = event.time;
-                        }
-                    }
-                }
-                if(event.type == EV_SW && event.code == SW_0 && event.value == 0) {
-                    if(verbose > 0)
-                        printf("Flip closed - sleep\n");
-                    power_key_down_time = event.time;
-                    write(release_wake_lock_fd, wakelockstring, sizeof(wakelockstring) - 1);
-                    goto sleep;
-                }
-                write(release_wake_lock_fd, wakelockstring, sizeof(wakelockstring) - 1);
-            }
-        }
-        if(0) {
-light_off:
-            light_event.value = 0;
-            write(eventfd, &light_event, sizeof(light_event));
-            tv.tv_sec = idle_time - lcd_light_time;
-        }
-        if(0) {
-light2_off:
-            light_event2.value = 0;
-            write(eventfd, &light_event2, sizeof(light_event2));
-            tv.tv_sec = lcd_light_time - key_light_time;
-        }
-        if(0) {
-sleep:
-            if(light_event.value == 1) {
-                light_event.value = 0;
-                write(eventfd, &light_event, sizeof(light_event));
-                light_event2.value = 0;
-                write(eventfd, &light_event2, sizeof(light_event2));
-                tv.tv_sec = idle_time - lcd_light_time;
-            }
-            if(powerfd_is_sleep) {
-                char buf[32];
-                int len;
-                len = sprintf(buf, "%ld%06lu000", power_key_down_time.tv_sec, power_key_down_time.tv_usec);
-                write(powerfd, buf, len);
-            }
-            else
-                write(powerfd, suspendstring, sizeof(suspendstring) - 1);
-            gotkey = 0;
-            tv.tv_sec = 0;
-            tv.tv_usec = 500000;
-        }
-    }
-
-    return 0;
-}
diff --git a/toolbox/ps.c b/toolbox/ps.c
index 2aa3efb..7c35ccb 100644
--- a/toolbox/ps.c
+++ b/toolbox/ps.c
@@ -13,7 +13,6 @@
 
 #include <cutils/sched_policy.h>
 
-
 static char *nexttoksep(char **strp, char *sep)
 {
     char *p = strsep(strp,sep);
@@ -28,6 +27,7 @@
 #define SHOW_TIME 2
 #define SHOW_POLICY 4
 #define SHOW_CPU  8
+#define SHOW_MACLABEL 16
 
 static int display_flags = 0;
 
@@ -35,6 +35,7 @@
 {
     char statline[1024];
     char cmdline[1024];
+    char macline[1024];
     char user[32];
     struct stat stats;
     int fd, r;
@@ -51,9 +52,11 @@
     if(tid) {
         sprintf(statline, "/proc/%d/task/%d/stat", pid, tid);
         cmdline[0] = 0;
+        snprintf(macline, sizeof(macline), "/proc/%d/task/%d/attr/current", pid, tid);
     } else {
         sprintf(statline, "/proc/%d/stat", pid);
-        sprintf(cmdline, "/proc/%d/cmdline", pid);    
+        sprintf(cmdline, "/proc/%d/cmdline", pid);
+        snprintf(macline, sizeof(macline), "/proc/%d/attr/current", pid);
         fd = open(cmdline, O_RDONLY);
         if(fd == 0) {
             r = 0;
@@ -142,6 +145,19 @@
     }
     
     if(!namefilter || !strncmp(name, namefilter, strlen(namefilter))) {
+        if (display_flags & SHOW_MACLABEL) {
+            fd = open(macline, O_RDONLY);
+            strcpy(macline, "-");
+            if (fd >= 0) {
+                r = read(fd, macline, sizeof(macline)-1);
+                close(fd);
+                if (r > 0)
+                    macline[r] = 0;
+            }
+            printf("%-30s %-9s %-5d %-5d %s\n", macline, user, pid, ppid, cmdline[0] ? cmdline : name);
+            return 0;
+        }
+
         printf("%-9s %-5d %-5d %-6d %-5d", user, pid, ppid, vss / 1024, rss * 4);
         if (display_flags & SHOW_CPU)
             printf(" %-2d", psr);
@@ -151,14 +167,8 @@
             SchedPolicy p;
             if (get_sched_policy(pid, &p) < 0)
                 printf(" un ");
-            else {
-                if (p == SP_BACKGROUND)
-                    printf(" bg ");
-                else if (p == SP_FOREGROUND)
-                    printf(" fg ");
-                else
-                    printf(" er ");
-            }
+            else
+                printf(" %.2s ", get_sched_policy_name(p));
         }
         printf(" %08x %08x %s %s", wchan, eip, state, cmdline[0] ? cmdline : name);
         if(display_flags&SHOW_TIME)
@@ -206,6 +216,8 @@
             threads = 1;
         } else if(!strcmp(argv[1],"-x")) {
             display_flags |= SHOW_TIME;
+        } else if(!strcmp(argv[1], "-Z")) {
+            display_flags |= SHOW_MACLABEL;
         } else if(!strcmp(argv[1],"-P")) {
             display_flags |= SHOW_POLICY;
         } else if(!strcmp(argv[1],"-p")) {
@@ -221,10 +233,14 @@
         argv++;
     }
 
-    printf("USER     PID   PPID  VSIZE  RSS   %s%s %s WCHAN    PC         NAME\n",
-           (display_flags&SHOW_CPU)?"CPU ":"",
-           (display_flags&SHOW_PRIO)?"PRIO  NICE  RTPRI SCHED ":"",
-           (display_flags&SHOW_POLICY)?"PCY " : "");
+    if (display_flags & SHOW_MACLABEL) {
+        printf("LABEL                          USER     PID   PPID  NAME\n");
+    } else {
+        printf("USER     PID   PPID  VSIZE  RSS   %s%s %s WCHAN    PC         NAME\n",
+               (display_flags&SHOW_CPU)?"CPU ":"",
+               (display_flags&SHOW_PRIO)?"PRIO  NICE  RTPRI SCHED ":"",
+               (display_flags&SHOW_POLICY)?"PCY " : "");
+    }
     while((de = readdir(d)) != 0){
         if(isdigit(de->d_name[0])){
             int pid = atoi(de->d_name);
diff --git a/toolbox/restorecon.c b/toolbox/restorecon.c
new file mode 100644
index 0000000..5ef0ef1
--- /dev/null
+++ b/toolbox/restorecon.c
@@ -0,0 +1,141 @@
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fts.h>
+#include <selinux/selinux.h>
+#include <selinux/label.h>
+
+#define FCPATH "/file_contexts"
+
+static struct selabel_handle *sehandle;
+static const char *progname;
+static int nochange;
+static int verbose;
+
+static void usage(void)
+{
+    fprintf(stderr, "usage:  %s [-f file_contexts] [-nrRv] pathname...\n", progname);
+    exit(1);
+}
+
+static int restore(const char *pathname, const struct stat *sb)
+{
+    char *oldcontext, *newcontext;
+
+    if (lgetfilecon(pathname, &oldcontext) < 0) {
+        fprintf(stderr, "Could not get context of %s:  %s\n",
+                pathname, strerror(errno));
+        return -1;
+    }
+    if (selabel_lookup(sehandle, &newcontext, pathname, sb->st_mode) < 0) {
+        fprintf(stderr, "Could not lookup context for %s:  %s\n", pathname,
+                strerror(errno));
+        return -1;
+    }
+    if (strcmp(newcontext, "<<none>>") &&
+        strcmp(oldcontext, newcontext)) {
+        if (verbose)
+            printf("Relabeling %s from %s to %s.\n", pathname, oldcontext, newcontext);
+        if (!nochange) {
+            if (lsetfilecon(pathname, newcontext) < 0) {
+                fprintf(stderr, "Could not label %s with %s:  %s\n",
+                        pathname, newcontext, strerror(errno));
+                return -1;
+            }
+        }
+    }
+    freecon(oldcontext);
+    freecon(newcontext);
+    return 0;
+}
+
+int restorecon_main(int argc, char **argv)
+{
+    struct selinux_opt seopts[] = {
+        { SELABEL_OPT_PATH, FCPATH }
+    };
+    int ch, recurse = 0, ftsflags = FTS_PHYSICAL;
+
+    progname = argv[0];
+
+    do {
+        ch = getopt(argc, argv, "f:nrRv");
+        if (ch == EOF)
+            break;
+        switch (ch) {
+        case 'f':
+            seopts[0].value = optarg;
+            break;
+        case 'n':
+            nochange = 1;
+            break;
+        case 'r':
+        case 'R':
+            recurse = 1;
+            break;
+        case 'v':
+            verbose = 1;
+            break;
+        default:
+            usage();
+        }
+    } while (1);
+
+    argc -= optind;
+    argv += optind;
+    if (!argc)
+        usage();
+
+    sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);
+    if (!sehandle) {
+        fprintf(stderr, "Could not load file contexts from %s:  %s\n", seopts[0].value,
+                strerror(errno));
+        return -1;
+    }
+
+    if (recurse) {
+        FTS *fts;
+        FTSENT *ftsent;
+        fts = fts_open(argv, ftsflags, NULL);
+        if (!fts) {
+            fprintf(stderr, "Could not traverse filesystems (first was %s):  %s\n",
+                    argv[0], strerror(errno));
+            return -1;
+        }
+        while ((ftsent = fts_read(fts))) {
+            switch (ftsent->fts_info) {
+            case FTS_DP:
+                break;
+            case FTS_DNR:
+            case FTS_ERR:
+            case FTS_NS:
+                fprintf(stderr, "Could not access %s:  %s\n", ftsent->fts_path,
+                        strerror(errno));
+                fts_set(fts, ftsent, FTS_SKIP);
+                break;
+            default:
+                if (restore(ftsent->fts_path, ftsent->fts_statp) < 0)
+                    fts_set(fts, ftsent, FTS_SKIP);
+                break;
+            }
+        }
+    } else {
+        int i, rc;
+        struct stat sb;
+
+        for (i = 0; i < argc; i++) {
+            rc = lstat(argv[i], &sb);
+            if (rc < 0) {
+                fprintf(stderr, "Could not stat %s:  %s\n", argv[i],
+                        strerror(errno));
+                continue;
+            }
+            restore(argv[i], &sb);
+        }
+    }
+
+    return 0;
+}
diff --git a/toolbox/rm.c b/toolbox/rm.c
index bd66311..3a24bec 100644
--- a/toolbox/rm.c
+++ b/toolbox/rm.c
@@ -7,14 +7,17 @@
 #include <sys/stat.h>
 #include <sys/types.h>
 
+#define OPT_RECURSIVE 1
+#define OPT_FORCE     2
+
 static int usage()
 {
-    fprintf(stderr,"rm [-rR] <target>\n");
+    fprintf(stderr,"Usage: rm [-rR] [-f] <target>\n");
     return -1;
 }
 
 /* return -1 on failure, with errno set to the first error */
-static int unlink_recursive(const char* name)
+static int unlink_recursive(const char* name, int flags)
 {
     struct stat st;
     DIR *dir;
@@ -23,7 +26,7 @@
 
     /* is it a file or directory? */
     if (lstat(name, &st) < 0)
-        return -1;
+        return ((flags & OPT_FORCE) && errno == ENOENT) ? 0 : -1;
 
     /* a file, so unlink it */
     if (!S_ISDIR(st.st_mode))
@@ -41,7 +44,7 @@
         if (!strcmp(de->d_name, "..") || !strcmp(de->d_name, "."))
             continue;
         sprintf(dn, "%s/%s", name, de->d_name);
-        if (unlink_recursive(dn) < 0) {
+        if (unlink_recursive(dn, flags) < 0) {
             fail = 1;
             break;
         }
@@ -66,21 +69,45 @@
 int rm_main(int argc, char *argv[])
 {
     int ret;
-    int i = 1;
-    int recursive = 0;
+    int i, c;
+    int flags = 0;
 
     if (argc < 2)
         return usage();
 
-    /* check if recursive */
-    if (argc >=2 && (!strcmp(argv[1], "-r") || !strcmp(argv[1], "-R"))) {
-        recursive = 1;
-        i = 2;
+    /* check flags */
+    do {
+        c = getopt(argc, argv, "frR");
+        if (c == EOF)
+            break;
+        switch (c) {
+        case 'f':
+            flags |= OPT_FORCE;
+            break;
+        case 'r':
+        case 'R':
+            flags |= OPT_RECURSIVE;
+            break;
+        }
+    } while (1);
+
+    if (optind < 1 || optind >= argc) {
+        usage();
+        return -1;
     }
-    
+
     /* loop over the file/directory args */
-    for (; i < argc; i++) {
-        int ret = recursive ? unlink_recursive(argv[i]) : unlink(argv[i]);
+    for (i = optind; i < argc; i++) {
+
+        if (flags & OPT_RECURSIVE) {
+            ret = unlink_recursive(argv[i], flags);
+        } else {
+            ret = unlink(argv[i]);
+            if (errno == ENOENT && (flags & OPT_FORCE)) {
+                return 0;
+            }
+        }
+
         if (ret < 0) {
             fprintf(stderr, "rm failed for %s, %s\n", argv[i], strerror(errno));
             return -1;
diff --git a/toolbox/rmmod.c b/toolbox/rmmod.c
index 7e10c06..25257cc 100644
--- a/toolbox/rmmod.c
+++ b/toolbox/rmmod.c
@@ -25,6 +25,8 @@
 	modname = strrchr(argv[1], '/');
 	if (!modname)
 		modname = argv[1];
+	else modname++;
+
 	dot = strchr(argv[1], '.');
 	if (dot)
 		*dot = '\0';
diff --git a/toolbox/runcon.c b/toolbox/runcon.c
new file mode 100644
index 0000000..4a57bf3
--- /dev/null
+++ b/toolbox/runcon.c
@@ -0,0 +1,28 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <selinux/selinux.h>
+
+int runcon_main(int argc, char **argv)
+{
+    int rc;
+
+    if (argc < 3) {
+        fprintf(stderr, "usage:  %s context program args...\n", argv[0]);
+        exit(1);
+    }
+
+    rc = setexeccon(argv[1]);
+    if (rc < 0) {
+        fprintf(stderr, "Could not set context to %s:  %s\n", argv[1], strerror(errno));
+        exit(2);
+    }
+
+    argv += 2;
+    argc -= 2;
+    execvp(argv[0], argv);
+    fprintf(stderr, "Could not exec %s:  %s\n", argv[0], strerror(errno));
+    exit(3);
+}
diff --git a/toolbox/setenforce.c b/toolbox/setenforce.c
new file mode 100644
index 0000000..1b0ea5c
--- /dev/null
+++ b/toolbox/setenforce.c
@@ -0,0 +1,44 @@
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <string.h>
+#include <strings.h>
+#include <errno.h>
+#include <selinux/selinux.h>
+
+void usage(const char *progname)
+{
+    fprintf(stderr, "usage:  %s [ Enforcing | Permissive | 1 | 0 ]\n",
+            progname);
+    exit(1);
+}
+
+int setenforce_main(int argc, char **argv)
+{
+    int rc = 0;
+    if (argc != 2) {
+        usage(argv[0]);
+    }
+
+    if (is_selinux_enabled() <= 0) {
+        fprintf(stderr, "%s: SELinux is disabled\n", argv[0]);
+        return 1;
+    }
+    if (strlen(argv[1]) == 1 && (argv[1][0] == '0' || argv[1][0] == '1')) {
+        rc = security_setenforce(atoi(argv[1]));
+    } else {
+        if (strcasecmp(argv[1], "enforcing") == 0) {
+            rc = security_setenforce(1);
+        } else if (strcasecmp(argv[1], "permissive") == 0) {
+            rc = security_setenforce(0);
+        } else
+            usage(argv[0]);
+    }
+    if (rc < 0) {
+        fprintf(stderr, "%s:  Could not set enforcing status:  %s\n",
+                argv[0], strerror(errno));
+        return 2;
+    }
+    return 0;
+}
diff --git a/toolbox/setsebool.c b/toolbox/setsebool.c
new file mode 100644
index 0000000..4a3d87d
--- /dev/null
+++ b/toolbox/setsebool.c
@@ -0,0 +1,55 @@
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <selinux/selinux.h>
+#include <errno.h>
+
+static int do_setsebool(int nargs, char **args) {
+    SELboolean *b = alloca(nargs * sizeof(SELboolean));
+    char *v;
+    int i;
+
+    if (is_selinux_enabled() <= 0)
+        return 0;
+
+    for (i = 1; i < nargs; i++) {
+        char *name = args[i];
+        v = strchr(name, '=');
+        if (!v) {
+            fprintf(stderr, "setsebool: argument %s had no =\n", name);
+            return -1;
+        }
+        *v++ = 0;
+        b[i-1].name = name;
+        if (!strcmp(v, "1") || !strcasecmp(v, "true") || !strcasecmp(v, "on"))
+            b[i-1].value = 1;
+        else if (!strcmp(v, "0") || !strcasecmp(v, "false") || !strcasecmp(v, "off"))
+            b[i-1].value = 0;
+        else {
+            fprintf(stderr, "setsebool: invalid value %s\n", v);
+            return -1;
+        }
+    }
+
+    if (security_set_boolean_list(nargs - 1, b, 0) < 0)
+    {
+        fprintf(stderr, "setsebool: unable to set booleans: %s", strerror(errno));
+        return -1;
+    }
+
+    return 0;
+}
+
+int setsebool_main(int argc, char **argv)
+{
+    if (argc < 2) {
+        fprintf(stderr, "Usage:  %s name=value...\n", argv[0]);
+        exit(1);
+    }
+
+    return do_setsebool(argc, argv);
+}
diff --git a/toolbox/top.c b/toolbox/top.c
index 999c8e1..7642522 100644
--- a/toolbox/top.c
+++ b/toolbox/top.c
@@ -48,6 +48,7 @@
 
 #define PROC_NAME_LEN 64
 #define THREAD_NAME_LEN 32
+#define POLICY_NAME_LEN 4
 
 struct proc_info {
     struct proc_info *next;
@@ -67,7 +68,7 @@
     long rss;
     int prs;
     int num_threads;
-    char policy[32];
+    char policy[POLICY_NAME_LEN];
 };
 
 struct proc_list {
@@ -381,14 +382,10 @@
 static void read_policy(int pid, struct proc_info *proc) {
     SchedPolicy p;
     if (get_sched_policy(pid, &p) < 0)
-        strcpy(proc->policy, "unk");
+        strlcpy(proc->policy, "unk", POLICY_NAME_LEN);
     else {
-        if (p == SP_BACKGROUND)
-            strcpy(proc->policy, "bg");
-        else if (p == SP_FOREGROUND)
-            strcpy(proc->policy, "fg");
-        else
-            strcpy(proc->policy, "er");
+        strlcpy(proc->policy, get_sched_policy_name(p), POLICY_NAME_LEN);
+        proc->policy[2] = '\0';
     }
 }