am 0f86444b: Merge "sdcard : inode numbers must be fully representable as uint32_t." into lmp-mr1-dev

* commit '0f86444b3912cadb4227755f3b80d2ff74841575':
  sdcard : inode numbers must be fully representable as uint32_t.
diff --git a/README b/README
deleted file mode 100644
index 0083247..0000000
--- a/README
+++ /dev/null
@@ -1,20 +0,0 @@
-
-The system/ directory is intended for pieces of the world that are the
-core of the embedded linux platform at the heart of Android.  These
-essential bits are required for basic booting, operation, and debugging.
-
-They should not depend on libraries outside of system/... (some of them
-do currently -- they need to be updated or changed) and they should not
-be required for the simulator build.
-
-The license for all these pieces should be clean (Apache2, BSD, or MIT).
-
-Currently system/bluetooth/... and system/extra/... have some pieces
-with GPL/LGPL licensed code.
-
-Assorted Issues:
-
-- pppd depends on libutils for logging
-- pppd depends on libcrypt/libcrypto
-- init, linker, debuggerd, toolbox, usbd depend on libcutils
-- should probably rename bionic to libc
diff --git a/ThirdPartyProject.prop b/ThirdPartyProject.prop
deleted file mode 100644
index 18b0594..0000000
--- a/ThirdPartyProject.prop
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright 2010 Google Inc. All Rights Reserved.
-#Fri Jul 16 10:03:09 PDT 2010
-currentVersion=2.6.32
-version=2.6.32
-isNative=true
-feedurl=http\://kernel.org/pub/linux/kernel/v2.6/
-name=linux
-keywords=linux
-onDevice=true
-homepage=http\://kernel.org
diff --git a/adb/Android.mk b/adb/Android.mk
index b70c153..8ebcbf0 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -24,6 +24,7 @@
   USB_SRCS := usb_osx.c
   EXTRA_SRCS := get_my_path_darwin.c
   LOCAL_LDLIBS += -lpthread -framework CoreFoundation -framework IOKit -framework Carbon
+  LOCAL_CFLAGS += -Wno-sizeof-pointer-memaccess -Wno-unused-parameter
 endif
 
 ifeq ($(HOST_OS),freebsd)
@@ -62,9 +63,6 @@
 	file_sync_client.c \
 	$(EXTRA_SRCS) \
 	$(USB_SRCS) \
-	usb_vendors.c
-
-LOCAL_C_INCLUDES += external/openssl/include
 
 ifneq ($(USE_SYSDEPS_WIN32),)
   LOCAL_SRC_FILES += sysdeps_win32.c
@@ -77,11 +75,12 @@
 LOCAL_MODULE := adb
 LOCAL_MODULE_TAGS := debug
 
-LOCAL_STATIC_LIBRARIES := libzipfile libunz libcrypto_static $(EXTRA_STATIC_LIBS)
+LOCAL_STATIC_LIBRARIES := libzipfile libz libcrypto_static $(EXTRA_STATIC_LIBS)
 ifeq ($(USE_SYSDEPS_WIN32),)
 	LOCAL_STATIC_LIBRARIES += libcutils
 endif
 
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_HOST_EXECUTABLE)
 
 $(call dist-for-goals,dist_files sdk,$(LOCAL_BUILT_MODULE))
@@ -111,11 +110,16 @@
 	jdwp_service.c \
 	framebuffer_service.c \
 	remount_service.c \
-	disable_verity_service.c \
+	set_verity_enable_state_service.c \
 	usb_linux_client.c
 
-LOCAL_CFLAGS := -O2 -g -DADB_HOST=0 -Wall -Wno-unused-parameter -Werror
-LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE
+LOCAL_CFLAGS := \
+	-O2 \
+	-g \
+	-DADB_HOST=0 \
+	-D_XOPEN_SOURCE \
+	-D_GNU_SOURCE \
+	-Wall -Wno-unused-parameter -Werror -Wno-deprecated-declarations \
 
 ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
 LOCAL_CFLAGS += -DALLOW_ADBD_ROOT=1
@@ -140,6 +144,8 @@
 	libselinux \
 	libext4_utils_static
 
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
 include $(BUILD_EXECUTABLE)
 
 
@@ -162,7 +168,6 @@
 	file_sync_client.c \
 	get_my_path_linux.c \
 	usb_linux.c \
-	usb_vendors.c \
 	fdevent.c
 
 LOCAL_CFLAGS := \
@@ -174,13 +179,12 @@
 	-D_XOPEN_SOURCE \
 	-D_GNU_SOURCE
 
-LOCAL_C_INCLUDES += external/openssl/include
-
 LOCAL_MODULE := adb
 
-LOCAL_STATIC_LIBRARIES := libzipfile libunz libcutils liblog
+LOCAL_STATIC_LIBRARIES := libzipfile libz libcutils liblog
 
 LOCAL_SHARED_LIBRARIES := libcrypto
 
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_EXECUTABLE)
 endif
diff --git a/adb/adb.c b/adb/adb.c
index 10a1e0d..1834472 100644
--- a/adb/adb.c
+++ b/adb/adb.c
@@ -41,8 +41,6 @@
 #include <sys/prctl.h>
 #include <getopt.h>
 #include <selinux/selinux.h>
-#else
-#include "usb_vendors.h"
 #endif
 
 #if ADB_TRACE
@@ -329,6 +327,7 @@
 }
 #endif
 
+#if ADB_HOST
 static void send_msg_with_okay(int fd, const char* msg, size_t msglen) {
     char header[9];
     if (msglen > 0xffff)
@@ -337,6 +336,7 @@
     writex(fd, header, 8);
     writex(fd, msg, msglen);
 }
+#endif // ADB_HOST
 
 static void send_connect(atransport *t)
 {
@@ -414,6 +414,7 @@
     send_connect(t);
 }
 
+#if ADB_HOST
 static char *connection_state_name(atransport *t)
 {
     if (t == NULL) {
@@ -437,6 +438,7 @@
         return "unknown";
     }
 }
+#endif // ADB_HOST
 
 /* qual_overwrite is used to overwrite a qualifier string.  dst is a
  * pointer to a char pointer.  It is assumed that if *dst is non-NULL, it
@@ -943,7 +945,7 @@
     return INSTALL_STATUS_INTERNAL_ERROR;
 }
 
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
 static BOOL WINAPI ctrlc_handler(DWORD type)
 {
     exit(STATUS_CONTROL_C_EXIT);
@@ -958,7 +960,7 @@
 
 void start_logging(void)
 {
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
     char    temp[ MAX_PATH ];
     FILE*   fnul;
     FILE*   flog;
@@ -1066,7 +1068,7 @@
 
 int launch_server(int server_port)
 {
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
     /* we need to start the server in the background                    */
     /* we create a PIPE that will be used to wait for the server's "OK" */
     /* message since the pipe handles must be inheritable, we use a     */
@@ -1165,7 +1167,7 @@
             return -1;
         }
     }
-#elif defined(HAVE_FORKEXEC)
+#else /* !defined(_WIN32) */
     char    path[PATH_MAX];
     int     fd[2];
 
@@ -1216,12 +1218,10 @@
 
         setsid();
     }
-#else
-#error "cannot implement background server start on this platform"
-#endif
+#endif /* !defined(_WIN32) */
     return 0;
 }
-#endif
+#endif /* ADB_HOST */
 
 /* Constructs a local name of form tcp:port.
  * target_str points to the target string, it's content will be overwritten.
@@ -1303,9 +1303,9 @@
 #endif
 
     atexit(adb_cleanup);
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
     SetConsoleCtrlHandler( ctrlc_handler, TRUE );
-#elif defined(HAVE_FORKEXEC)
+#else
     // No SIGCHLD. Let the service subproc handle its children.
     signal(SIGPIPE, SIG_IGN);
 #endif
@@ -1318,7 +1318,6 @@
 #ifdef WORKAROUND_BUG6558362
     if(is_daemon) adb_set_affinity();
 #endif
-    usb_vendors_init();
     usb_init();
     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
     adb_auth_init();
@@ -1349,14 +1348,13 @@
     ** AID_LOG to read system logs (adb logcat)
     ** AID_INPUT to diagnose input issues (getevent)
     ** 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_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_R, AID_SDCARD_RW,
+    gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_NET_BT,
+                       AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
                        AID_NET_BW_STATS };
     if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
         exit(1);
@@ -1421,10 +1419,10 @@
     if (is_daemon)
     {
         // inform our parent that we are up and running.
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
         DWORD  count;
         WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
-#elif defined(HAVE_FORKEXEC)
+#else
         fprintf(stderr, "OK\n");
 #endif
         start_logging();
@@ -1554,8 +1552,6 @@
 
 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
 {
-    atransport *transport = NULL;
-
     if(!strcmp(service, "kill")) {
         fprintf(stderr,"adb server killed by remote request\n");
         fflush(stdout);
@@ -1565,6 +1561,7 @@
     }
 
 #if ADB_HOST
+    atransport *transport = NULL;
     // "transport:" is used for switching transport with a specified serial number
     // "transport-usb:" is used for switching transport to the only USB transport
     // "transport-local:" is used for switching transport to the only local transport
diff --git a/adb/adb.h b/adb/adb.h
index 44e5981..a37fd5b 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -328,8 +328,10 @@
 
 #if !ADB_HOST
 void framebuffer_service(int fd, void *cookie);
+// Allow enable-verity to write to system and vendor block devices
+int make_block_device_writable(const char* dev);
 void remount_service(int fd, void *cookie);
-void disable_verity_service(int fd, void* cookie);
+void set_verity_enabled_state_service(int fd, void* cookie);
 #endif
 
 /* packet allocator */
@@ -339,6 +341,9 @@
 int check_header(apacket *p);
 int check_data(apacket *p);
 
+// Define it if you want to dump packets.
+#define DEBUG_PACKETS 0
+
 #if !DEBUG_PACKETS
 #define print_packet(tag,p) do {} while (0)
 #endif
@@ -376,7 +381,6 @@
 int is_adb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol);
 #endif
 
-unsigned host_to_le32(unsigned n);
 int adb_commandline(int argc, char **argv);
 
 int connection_state(atransport *t);
diff --git a/adb/adb_auth_host.c b/adb/adb_auth_host.c
index dd83900..a859199 100644
--- a/adb/adb_auth_host.c
+++ b/adb/adb_auth_host.c
@@ -48,6 +48,10 @@
 #include <openssl/rsa.h>
 #include <openssl/sha.h>
 
+#if defined(OPENSSL_IS_BORINGSSL)
+#include <openssl/base64.h>
+#endif
+
 #define TRACE_TAG TRACE_AUTH
 
 #define ANDROID_PATH   ".android"
@@ -151,43 +155,67 @@
 static int write_public_keyfile(RSA *private_key, const char *private_key_path)
 {
     RSAPublicKey pkey;
-    BIO *bio, *b64, *bfile;
+    FILE *outfile = NULL;
     char path[PATH_MAX], info[MAX_PAYLOAD];
-    int ret;
+    uint8_t *encoded = NULL;
+    size_t encoded_length;
+    int ret = 0;
 
-    ret = snprintf(path, sizeof(path), "%s.pub", private_key_path);
-    if (ret >= (signed)sizeof(path))
+    if (snprintf(path, sizeof(path), "%s.pub", private_key_path) >=
+        (int)sizeof(path)) {
+        D("Path too long while writing public key\n");
         return 0;
+    }
 
-    ret = RSA_to_RSAPublicKey(private_key, &pkey);
-    if (!ret) {
+    if (!RSA_to_RSAPublicKey(private_key, &pkey)) {
         D("Failed to convert to publickey\n");
         return 0;
     }
 
-    bfile = BIO_new_file(path, "w");
-    if (!bfile) {
+    outfile = fopen(path, "w");
+    if (!outfile) {
         D("Failed to open '%s'\n", path);
         return 0;
     }
 
     D("Writing public key to '%s'\n", path);
 
-    b64 = BIO_new(BIO_f_base64());
-    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
+#if defined(OPENSSL_IS_BORINGSSL)
+    if (!EVP_EncodedLength(&encoded_length, sizeof(pkey))) {
+        D("Public key too large to base64 encode");
+        goto out;
+    }
+#else
+    /* While we switch from OpenSSL to BoringSSL we have to implement
+     * |EVP_EncodedLength| here. */
+    encoded_length = 1 + ((sizeof(pkey) + 2) / 3 * 4);
+#endif
 
-    bio = BIO_push(b64, bfile);
-    BIO_write(bio, &pkey, sizeof(pkey));
-    (void) BIO_flush(bio);
-    BIO_pop(b64);
-    BIO_free(b64);
+    encoded = malloc(encoded_length);
+    if (encoded == NULL) {
+        D("Allocation failure");
+        goto out;
+    }
 
+    encoded_length = EVP_EncodeBlock(encoded, (uint8_t*) &pkey, sizeof(pkey));
     get_user_info(info, sizeof(info));
-    BIO_write(bfile, info, strlen(info));
-    (void) BIO_flush(bfile);
-    BIO_free_all(bfile);
 
-    return 1;
+    if (fwrite(encoded, encoded_length, 1, outfile) != 1 ||
+        fwrite(info, strlen(info), 1, outfile) != 1) {
+        D("Write error while writing public key");
+        goto out;
+    }
+
+    ret = 1;
+
+ out:
+    if (outfile != NULL) {
+        fclose(outfile);
+    }
+    if (encoded != NULL) {
+        free(encoded);
+    }
+    return ret;
 }
 
 static int generate_key(const char *file)
diff --git a/adb/adb_client.c b/adb/adb_client.c
index eb1720d..ac5e15a 100644
--- a/adb/adb_client.c
+++ b/adb/adb_client.c
@@ -279,7 +279,7 @@
 
     fd = _adb_connect(service);
     if(fd == -1) {
-        D("_adb_connect error: %s\n", __adb_error);
+        D("_adb_connect error: %s", __adb_error);
     } else if(fd == -2) {
         fprintf(stderr,"** daemon still not running\n");
     }
diff --git a/adb/adb_trace.h b/adb/adb_trace.h
index 8a5d9f8..b8a2f4c 100644
--- a/adb/adb_trace.h
+++ b/adb/adb_trace.h
@@ -73,8 +73,9 @@
             if (ADB_TRACING) {                         \
                 int save_errno = errno;                \
                 adb_mutex_lock(&D_lock);               \
-                fprintf(stderr, "%s::%s():",           \
-                        __FILE__, __FUNCTION__);       \
+                fprintf(stderr, "%16s: %5d:%5lu | ",   \
+                        __FUNCTION__,                  \
+                        getpid(), adb_thread_id());    \
                 errno = save_errno;                    \
                 fprintf(stderr, __VA_ARGS__ );         \
                 fflush(stderr);                        \
@@ -96,15 +97,16 @@
         } while (0)
 #  define  DD(...)                                     \
         do {                                           \
-          int save_errno = errno;                      \
-          adb_mutex_lock(&D_lock);                     \
-          fprintf(stderr, "%s::%s():",                 \
-                  __FILE__, __FUNCTION__);             \
-          errno = save_errno;                          \
-          fprintf(stderr, __VA_ARGS__ );               \
-          fflush(stderr);                              \
-          adb_mutex_unlock(&D_lock);                   \
-          errno = save_errno;                          \
+            int save_errno = errno;                    \
+            adb_mutex_lock(&D_lock);                   \
+            fprintf(stderr, "%16s: %5d:%5lu | ",       \
+                    __FUNCTION__,                      \
+                    getpid(), adb_thread_id());        \
+            errno = save_errno;                        \
+            fprintf(stderr, __VA_ARGS__ );             \
+            fflush(stderr);                            \
+            adb_mutex_unlock(&D_lock);                 \
+            errno = save_errno;                        \
         } while (0)
 #else
 #  define  D(...)                                      \
diff --git a/adb/commandline.c b/adb/commandline.c
index 7704878..f345787 100644
--- a/adb/commandline.c
+++ b/adb/commandline.c
@@ -29,7 +29,7 @@
 
 #include "sysdeps.h"
 
-#ifdef HAVE_TERMIO_H
+#if !defined(_WIN32)
 #include <termios.h>
 #endif
 
@@ -191,6 +191,7 @@
         "  adb restore <file>           - restore device contents from the <file> backup archive\n"
         "\n"
         "  adb disable-verity           - disable dm-verity checking on USERDEBUG builds\n"
+        "  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds\n"
         "  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,\n"
         "                                 and the public key is stored in <file>.pub. Any existing files\n"
         "                                 are overwritten.\n"
@@ -239,7 +240,18 @@
     return 1;
 }
 
-#ifdef HAVE_TERMIO_H
+#if defined(_WIN32)
+
+// Windows does not have <termio.h>.
+static void stdin_raw_init(int fd) {
+
+}
+
+static void stdin_raw_restore(int fd) {
+
+}
+
+#else
 static struct termios tio_save;
 
 static void stdin_raw_init(int fd)
@@ -313,11 +325,11 @@
     long total = 0;
 
     D("copy_to_file(%d -> %d)\n", inFd, outFd);
-#ifdef HAVE_TERMIO_H
+
     if (inFd == STDIN_FILENO) {
         stdin_raw_init(STDIN_FILENO);
     }
-#endif
+
     for (;;) {
         if (inFd == STDIN_FILENO) {
             len = unix_read(inFd, buf, BUFSIZE);
@@ -344,11 +356,11 @@
         }
         total += len;
     }
-#ifdef HAVE_TERMIO_H
+
     if (inFd == STDIN_FILENO) {
         stdin_raw_restore(STDIN_FILENO);
     }
-#endif
+
     D("copy_to_file() finished after %lu bytes\n", total);
     free(buf);
 }
@@ -389,9 +401,7 @@
             case '.':
                 if(state == 2) {
                     fprintf(stderr,"\n* disconnect *\n");
-#ifdef HAVE_TERMIO_H
                     stdin_raw_restore(fdi);
-#endif
                     exit(0);
                 }
             default:
@@ -423,14 +433,10 @@
     fds[0] = fd;
     fds[1] = fdi;
 
-#ifdef HAVE_TERMIO_H
     stdin_raw_init(fdi);
-#endif
     adb_thread_create(&thr, stdin_read_thread, fds);
     read_and_dump(fd);
-#ifdef HAVE_TERMIO_H
     stdin_raw_restore(fdi);
-#endif
     return 0;
 }
 
@@ -733,7 +739,7 @@
  */
 int ppp(int argc, char **argv)
 {
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
     fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]);
     return -1;
 #else
@@ -796,7 +802,7 @@
         adb_close(fd);
         return 0;
     }
-#endif /* !HAVE_WIN32_PROC */
+#endif /* !defined(_WIN32) */
 }
 
 static int send_shellcommand(transport_type transport, char* serial, char* buf)
@@ -1162,17 +1168,17 @@
     }
 
     /* modifiers and flags */
-    while(argc > 0) {
-        if(!strcmp(argv[0],"server")) {
+    while (argc > 0) {
+        if (!strcmp(argv[0],"server")) {
             is_server = 1;
-        } else if(!strcmp(argv[0],"nodaemon")) {
+        } else if (!strcmp(argv[0],"nodaemon")) {
             no_daemon = 1;
         } else if (!strcmp(argv[0], "fork-server")) {
             /* this is a special flag used only when the ADB client launches the ADB Server */
             is_daemon = 1;
-        } else if(!strcmp(argv[0],"persist")) {
+        } else if (!strcmp(argv[0],"persist")) {
             persist = 1;
-        } else if(!strncmp(argv[0], "-p", 2)) {
+        } else if (!strncmp(argv[0], "-p", 2)) {
             const char *product = NULL;
             if (argv[0][2] == '\0') {
                 if (argc < 2) return usage();
@@ -1192,7 +1198,7 @@
             if (isdigit(argv[0][2])) {
                 serial = argv[0] + 2;
             } else {
-                if(argc < 2 || argv[0][2] != '\0') return usage();
+                if (argc < 2 || argv[0][2] != '\0') return usage();
                 serial = argv[1];
                 argc--;
                 argv++;
@@ -1203,7 +1209,7 @@
             ttype = kTransportLocal;
         } else if (!strcmp(argv[0],"-a")) {
             gListenAll = 1;
-        } else if(!strncmp(argv[0], "-H", 2)) {
+        } else if (!strncmp(argv[0], "-H", 2)) {
             const char *hostname = NULL;
             if (argv[0][2] == '\0') {
                 if (argc < 2) return usage();
@@ -1215,7 +1221,7 @@
             }
             adb_set_tcp_name(hostname);
 
-        } else if(!strncmp(argv[0], "-P", 2)) {
+        } else if (!strncmp(argv[0], "-P", 2)) {
             if (argv[0][2] == '\0') {
                 if (argc < 2) return usage();
                 server_port_str = argv[1];
@@ -1254,20 +1260,51 @@
         } else {
             r = launch_server(server_port);
         }
-        if(r) {
+        if (r) {
             fprintf(stderr,"* could not start server *\n");
         }
         return r;
     }
 
-top:
-    if(argc == 0) {
+    if (argc == 0) {
         return usage();
     }
 
-    /* adb_connect() commands */
+    /* handle wait-for-* prefix */
+    if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
+        char* service = argv[0];
+        if (!strncmp(service, "wait-for-device", strlen("wait-for-device"))) {
+            if (ttype == kTransportUsb) {
+                service = "wait-for-usb";
+            } else if (ttype == kTransportLocal) {
+                service = "wait-for-local";
+            } else {
+                service = "wait-for-any";
+            }
+        }
 
-    if(!strcmp(argv[0], "devices")) {
+        format_host_command(buf, sizeof buf, service, ttype, serial);
+
+        if (adb_command(buf)) {
+            D("failure: %s *\n",adb_error());
+            fprintf(stderr,"error: %s\n", adb_error());
+            return 1;
+        }
+
+        /* Allow a command to be run after wait-for-device,
+            * e.g. 'adb wait-for-device shell'.
+            */
+        if (argc == 1) {
+            return 0;
+        }
+
+        /* Fall through */
+        argc--;
+        argv++;
+    }
+
+    /* adb_connect() commands */
+    if (!strcmp(argv[0], "devices")) {
         char *tmp;
         char *listopt;
         if (argc < 2)
@@ -1280,7 +1317,7 @@
         }
         snprintf(buf, sizeof buf, "host:%s%s", argv[0], listopt);
         tmp = adb_query(buf);
-        if(tmp) {
+        if (tmp) {
             printf("List of devices attached \n");
             printf("%s\n", tmp);
             return 0;
@@ -1288,8 +1325,7 @@
             return 1;
         }
     }
-
-    if(!strcmp(argv[0], "connect")) {
+    else if (!strcmp(argv[0], "connect")) {
         char *tmp;
         if (argc != 2) {
             fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
@@ -1297,15 +1333,14 @@
         }
         snprintf(buf, sizeof buf, "host:connect:%s", argv[1]);
         tmp = adb_query(buf);
-        if(tmp) {
+        if (tmp) {
             printf("%s\n", tmp);
             return 0;
         } else {
             return 1;
         }
     }
-
-    if(!strcmp(argv[0], "disconnect")) {
+    else if (!strcmp(argv[0], "disconnect")) {
         char *tmp;
         if (argc > 2) {
             fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
@@ -1317,19 +1352,17 @@
             snprintf(buf, sizeof buf, "host:disconnect:");
         }
         tmp = adb_query(buf);
-        if(tmp) {
+        if (tmp) {
             printf("%s\n", tmp);
             return 0;
         } else {
             return 1;
         }
     }
-
-    if (!strcmp(argv[0], "emu")) {
+    else if (!strcmp(argv[0], "emu")) {
         return adb_send_emulator_command(argc, argv);
     }
-
-    if(!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) {
+    else if (!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) {
         int r;
         int fd;
 
@@ -1340,7 +1373,7 @@
             fflush(stdout);
         }
 
-        if(argc < 2) {
+        if (argc < 2) {
             D("starting interactive shell\n");
             r = interactive_shell();
             if (h) {
@@ -1363,7 +1396,7 @@
         for(;;) {
             D("interactive shell loop. buff=%s\n", buf);
             fd = adb_connect(buf);
-            if(fd >= 0) {
+            if (fd >= 0) {
                 D("about to read_and_dump(fd=%d)\n", fd);
                 read_and_dump(fd);
                 D("read_and_dump() done.\n");
@@ -1374,7 +1407,7 @@
                 r = -1;
             }
 
-            if(persist) {
+            if (persist) {
                 fprintf(stderr,"\n- waiting for device -\n");
                 adb_sleep_ms(1000);
                 do_cmd(ttype, serial, "wait-for-device", 0);
@@ -1388,8 +1421,7 @@
             }
         }
     }
-
-    if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
+    else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
         int exec_in = !strcmp(argv[0], "exec-in");
         int fd;
 
@@ -1418,30 +1450,31 @@
         adb_close(fd);
         return 0;
     }
-
-    if(!strcmp(argv[0], "kill-server")) {
+    else if (!strcmp(argv[0], "kill-server")) {
         int fd;
         fd = _adb_connect("host:kill");
-        if(fd == -1) {
+        if (fd == -1) {
             fprintf(stderr,"* server not running *\n");
             return 1;
         }
         return 0;
     }
-
-    if(!strcmp(argv[0], "sideload")) {
-        if(argc != 2) return usage();
+    else if (!strcmp(argv[0], "sideload")) {
+        if (argc != 2) return usage();
         if (adb_sideload_host(argv[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")
-            || !strcmp(argv[0], "root") || !strcmp(argv[0], "disable-verity")) {
+    else if (!strcmp(argv[0], "remount") ||
+             !strcmp(argv[0], "reboot") ||
+             !strcmp(argv[0], "reboot-bootloader") ||
+             !strcmp(argv[0], "tcpip") ||
+             !strcmp(argv[0], "usb") ||
+             !strcmp(argv[0], "root") ||
+             !strcmp(argv[0], "disable-verity") ||
+             !strcmp(argv[0], "enable-verity")) {
         char command[100];
         if (!strcmp(argv[0], "reboot-bootloader"))
             snprintf(command, sizeof(command), "reboot:bootloader");
@@ -1450,7 +1483,7 @@
         else
             snprintf(command, sizeof(command), "%s:", argv[0]);
         int fd = adb_connect(command);
-        if(fd >= 0) {
+        if (fd >= 0) {
             read_and_dump(fd);
             adb_close(fd);
             return 0;
@@ -1458,49 +1491,13 @@
         fprintf(stderr,"error: %s\n", adb_error());
         return 1;
     }
-
-    if(!strcmp(argv[0], "bugreport")) {
+    else if (!strcmp(argv[0], "bugreport")) {
         if (argc != 1) return usage();
         do_cmd(ttype, serial, "shell", "bugreport", 0);
         return 0;
     }
-
     /* adb_command() wrapper commands */
-
-    if(!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
-        char* service = argv[0];
-        if (!strncmp(service, "wait-for-device", strlen("wait-for-device"))) {
-            if (ttype == kTransportUsb) {
-                service = "wait-for-usb";
-            } else if (ttype == kTransportLocal) {
-                service = "wait-for-local";
-            } else {
-                service = "wait-for-any";
-            }
-        }
-
-        format_host_command(buf, sizeof buf, service, ttype, serial);
-
-        if (adb_command(buf)) {
-            D("failure: %s *\n",adb_error());
-            fprintf(stderr,"error: %s\n", adb_error());
-            return 1;
-        }
-
-        /* Allow a command to be run after wait-for-device,
-            * e.g. 'adb wait-for-device shell'.
-            */
-        if(argc > 1) {
-            argc--;
-            argv++;
-            goto top;
-        }
-        return 0;
-    }
-
-    if(!strcmp(argv[0], "forward") ||
-       !strcmp(argv[0], "reverse"))
-    {
+    else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
         char host_prefix[64];
         char reverse = (char) !strcmp(argv[0], "reverse");
         char remove = 0;
@@ -1585,21 +1582,18 @@
           snprintf(buf, sizeof buf, "%s:%s:%s;%s", host_prefix, command, argv[1], argv[2]);
         }
 
-        if(adb_command(buf)) {
+        if (adb_command(buf)) {
             fprintf(stderr,"error: %s\n", adb_error());
             return 1;
         }
         return 0;
     }
-
     /* do_sync_*() commands */
-
-    if(!strcmp(argv[0], "ls")) {
-        if(argc != 2) return usage();
+    else if (!strcmp(argv[0], "ls")) {
+        if (argc != 2) return usage();
         return do_sync_ls(argv[1]);
     }
-
-    if(!strcmp(argv[0], "push")) {
+    else if (!strcmp(argv[0], "push")) {
         int show_progress = 0;
         int copy_attrs = 0; // unused
         const char* lpath = NULL, *rpath = NULL;
@@ -1612,8 +1606,7 @@
 
         return usage();
     }
-
-    if(!strcmp(argv[0], "pull")) {
+    else if (!strcmp(argv[0], "pull")) {
         int show_progress = 0;
         int copy_attrs = 0;
         const char* rpath = NULL, *lpath = ".";
@@ -1626,28 +1619,24 @@
 
         return usage();
     }
-
-    if (!strcmp(argv[0], "install")) {
+    else if (!strcmp(argv[0], "install")) {
         if (argc < 2) return usage();
         return install_app(ttype, serial, argc, argv);
     }
-
-    if (!strcmp(argv[0], "install-multiple")) {
+    else if (!strcmp(argv[0], "install-multiple")) {
         if (argc < 2) return usage();
         return install_multiple_app(ttype, serial, argc, argv);
     }
-
-    if (!strcmp(argv[0], "uninstall")) {
+    else if (!strcmp(argv[0], "uninstall")) {
         if (argc < 2) return usage();
         return uninstall_app(ttype, serial, argc, argv);
     }
-
-    if(!strcmp(argv[0], "sync")) {
+    else if (!strcmp(argv[0], "sync")) {
         char *srcarg, *android_srcpath, *data_srcpath, *vendor_srcpath;
         int listonly = 0;
 
         int ret;
-        if(argc < 2) {
+        if (argc < 2) {
             /* No local path was specified. */
             srcarg = NULL;
         } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) {
@@ -1657,20 +1646,20 @@
             } else {
                 srcarg = NULL;
             }
-        } else if(argc == 2) {
+        } else if (argc == 2) {
             /* A local path or "android"/"data" arg was specified. */
             srcarg = argv[1];
         } else {
             return usage();
         }
         ret = find_sync_dirs(srcarg, &android_srcpath, &data_srcpath, &vendor_srcpath);
-        if(ret != 0) return usage();
+        if (ret != 0) return usage();
 
-        if(android_srcpath != NULL)
+        if (android_srcpath != NULL)
             ret = do_sync_sync(android_srcpath, "/system", listonly);
-        if(ret == 0 && vendor_srcpath != NULL)
+        if (ret == 0 && vendor_srcpath != NULL)
             ret = do_sync_sync(vendor_srcpath, "/vendor", listonly);
-        if(ret == 0 && data_srcpath != NULL)
+        if (ret == 0 && data_srcpath != NULL)
             ret = do_sync_sync(data_srcpath, "/data", listonly);
 
         free(android_srcpath);
@@ -1678,10 +1667,8 @@
         free(data_srcpath);
         return ret;
     }
-
     /* passthrough commands */
-
-    if(!strcmp(argv[0],"get-state") ||
+    else if (!strcmp(argv[0],"get-state") ||
         !strcmp(argv[0],"get-serialno") ||
         !strcmp(argv[0],"get-devpath"))
     {
@@ -1689,47 +1676,38 @@
 
         format_host_command(buf, sizeof buf, argv[0], ttype, serial);
         tmp = adb_query(buf);
-        if(tmp) {
+        if (tmp) {
             printf("%s\n", tmp);
             return 0;
         } else {
             return 1;
         }
     }
-
     /* other commands */
-
-    if(!strcmp(argv[0],"status-window")) {
+    else if (!strcmp(argv[0],"status-window")) {
         status_window(ttype, serial);
         return 0;
     }
-
-    if(!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
+    else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
         return logcat(ttype, serial, argc, argv);
     }
-
-    if(!strcmp(argv[0],"ppp")) {
+    else if (!strcmp(argv[0],"ppp")) {
         return ppp(argc, argv);
     }
-
-    if (!strcmp(argv[0], "start-server")) {
+    else if (!strcmp(argv[0], "start-server")) {
         return adb_connect("host:start-server");
     }
-
-    if (!strcmp(argv[0], "backup")) {
+    else if (!strcmp(argv[0], "backup")) {
         return backup(argc, argv);
     }
-
-    if (!strcmp(argv[0], "restore")) {
+    else if (!strcmp(argv[0], "restore")) {
         return restore(argc, argv);
     }
-
-    if (!strcmp(argv[0], "keygen")) {
+    else if (!strcmp(argv[0], "keygen")) {
         if (argc < 2) return usage();
         return adb_auth_keygen(argv[1]);
     }
-
-    if (!strcmp(argv[0], "jdwp")) {
+    else if (!strcmp(argv[0], "jdwp")) {
         int  fd = adb_connect("jdwp");
         if (fd >= 0) {
             read_and_dump(fd);
@@ -1740,14 +1718,12 @@
             return -1;
         }
     }
-
     /* "adb /?" is a common idiom under Windows */
-    if(!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
+    else if (!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
         help();
         return 0;
     }
-
-    if(!strcmp(argv[0], "version")) {
+    else if (!strcmp(argv[0], "version")) {
         version(stdout);
         return 0;
     }
diff --git a/adb/fdevent.c b/adb/fdevent.c
index 43e600c..f5ecd14 100644
--- a/adb/fdevent.c
+++ b/adb/fdevent.c
@@ -661,6 +661,8 @@
     if(adb_socketpair(s)) {
         FATAL("cannot create shell-exit socket-pair\n");
     }
+    D("socketpair: (%d,%d)", s[0], s[1]);
+
     SHELL_EXIT_NOTIFY_FD = s[0];
     fdevent *fde;
     fde = fdevent_create(s[1], fdevent_subproc_event_func, NULL);
diff --git a/adb/file_sync_client.c b/adb/file_sync_client.c
index ad59e81..ee09d5d 100644
--- a/adb/file_sync_client.c
+++ b/adb/file_sync_client.c
@@ -309,7 +309,9 @@
     return err;
 }
 
-#ifdef HAVE_SYMLINKS
+#if defined(_WIN32)
+extern int write_data_link(int fd, const char *path, syncsendbuf *sbuf) __attribute__((error("no symlinks on Windows")));
+#else
 static int write_data_link(int fd, const char *path, syncsendbuf *sbuf)
 {
     int len, ret;
@@ -364,10 +366,8 @@
         free(file_buffer);
     } else if (S_ISREG(mode))
         write_data_file(fd, lpath, sbuf, show_progress);
-#ifdef HAVE_SYMLINKS
     else if (S_ISLNK(mode))
         write_data_link(fd, lpath, sbuf);
-#endif
     else
         goto fail;
 
@@ -893,6 +893,21 @@
     return r1 ? : r2;
 }
 
+/* Return a copy of the path string with / appended if needed */
+static char *add_slash_to_path(const char *path)
+{
+    if (path[strlen(path) - 1] != '/') {
+        size_t len = strlen(path) + 2;
+        char *path_with_slash = malloc(len);
+        if (path_with_slash == NULL)
+            return NULL;
+        snprintf(path_with_slash, len, "%s/", path);
+        return path_with_slash;
+    } else {
+        return strdup(path);
+    }
+}
+
 static int copy_remote_dir_local(int fd, const char *rpath, const char *lpath,
                                  int copy_attrs)
 {
@@ -900,28 +915,32 @@
     copyinfo *ci, *next;
     int pulled = 0;
     int skipped = 0;
+    char *rpath_clean = NULL;
+    char *lpath_clean = NULL;
+    int ret = 0;
+
+    if (rpath[0] == '\0' || lpath[0] == '\0') {
+        ret = -1;
+        goto finish;
+    }
 
     /* Make sure that both directory paths end in a slash. */
-    if (rpath[0] == 0 || lpath[0] == 0) return -1;
-    if (rpath[strlen(rpath) - 1] != '/') {
-        int  tmplen = strlen(rpath) + 2;
-        char *tmp = malloc(tmplen);
-        if (tmp == 0) return -1;
-        snprintf(tmp, tmplen, "%s/", rpath);
-        rpath = tmp;
+    rpath_clean = add_slash_to_path(rpath);
+    if (!rpath_clean) {
+        ret = -1;
+        goto finish;
     }
-    if (lpath[strlen(lpath) - 1] != '/') {
-        int  tmplen = strlen(lpath) + 2;
-        char *tmp = malloc(tmplen);
-        if (tmp == 0) return -1;
-        snprintf(tmp, tmplen, "%s/", lpath);
-        lpath = tmp;
+    lpath_clean = add_slash_to_path(lpath);
+    if (!lpath_clean) {
+        ret = -1;
+        goto finish;
     }
 
-    fprintf(stderr, "pull: building file list...\n");
     /* Recursively build the list of files to copy. */
-    if (remote_build_list(fd, &filelist, rpath, lpath)) {
-        return -1;
+    fprintf(stderr, "pull: building file list...\n");
+    if (remote_build_list(fd, &filelist, rpath_clean, lpath_clean)) {
+        ret = -1;
+        goto finish;
     }
 
     for (ci = filelist; ci != 0; ci = next) {
@@ -929,11 +948,13 @@
         if (ci->flag == 0) {
             fprintf(stderr, "pull: %s -> %s\n", ci->src, ci->dst);
             if (sync_recv(fd, ci->src, ci->dst, 0 /* no show progress */)) {
-                return 1;
+                ret = -1;
+                goto finish;
             }
 
             if (copy_attrs && set_time_and_mode(ci->dst, ci->time, ci->mode)) {
-               return 1;
+                ret = -1;
+                goto finish;
             }
             pulled++;
         } else {
@@ -946,7 +967,10 @@
             pulled, (pulled == 1) ? "" : "s",
             skipped, (skipped == 1) ? "" : "s");
 
-    return 0;
+finish:
+    free(lpath_clean);
+    free(rpath_clean);
+    return ret;
 }
 
 int do_sync_pull(const char *rpath, const char *lpath, int show_progress, int copy_attrs)
diff --git a/adb/file_sync_service.c b/adb/file_sync_service.c
index 7933858..7de82b7 100644
--- a/adb/file_sync_service.c
+++ b/adb/file_sync_service.c
@@ -270,7 +270,9 @@
     return -1;
 }
 
-#ifdef HAVE_SYMLINKS
+#if defined(_WIN32)
+extern int handle_send_link(int s, char *path, char *buffer) __attribute__((error("no symlinks on Windows")));
+#else
 static int handle_send_link(int s, char *path, char *buffer)
 {
     syncmsg msg;
@@ -321,25 +323,20 @@
 
     return 0;
 }
-#endif /* HAVE_SYMLINKS */
+#endif
 
 static int do_send(int s, char *path, char *buffer)
 {
-    char *tmp;
     unsigned int mode;
-    int is_link, ret;
+    bool is_link = false;
     bool do_unlink;
 
-    tmp = strrchr(path,',');
+    char* tmp = strrchr(path,',');
     if(tmp) {
         *tmp = 0;
         errno = 0;
         mode = strtoul(tmp + 1, NULL, 0);
-#ifndef HAVE_SYMLINKS
-        is_link = 0;
-#else
         is_link = S_ISLNK((mode_t) mode);
-#endif
         mode &= 0777;
     }
     if(!tmp || errno) {
@@ -355,32 +352,26 @@
         }
     }
 
-#ifdef HAVE_SYMLINKS
-    if(is_link)
-        ret = handle_send_link(s, path, buffer);
-    else {
-#else
-    {
-#endif
-        uid_t uid = -1;
-        gid_t gid = -1;
-        uint64_t cap = 0;
-
-        /* copy user permission bits to "group" and "other" permissions */
-        mode |= ((mode >> 3) & 0070);
-        mode |= ((mode >> 3) & 0007);
-
-        tmp = path;
-        if(*tmp == '/') {
-            tmp++;
-        }
-        if (is_on_system(path) || is_on_vendor(path)) {
-            fs_config(tmp, 0, &uid, &gid, &mode, &cap);
-        }
-        ret = handle_send_file(s, path, uid, gid, mode, buffer, do_unlink);
+    if (is_link) {
+        return handle_send_link(s, path, buffer);
     }
 
-    return ret;
+    uid_t uid = -1;
+    gid_t gid = -1;
+    uint64_t cap = 0;
+
+    /* copy user permission bits to "group" and "other" permissions */
+    mode |= ((mode >> 3) & 0070);
+    mode |= ((mode >> 3) & 0007);
+
+    tmp = path;
+    if(*tmp == '/') {
+        tmp++;
+    }
+    if (is_on_system(path) || is_on_vendor(path)) {
+        fs_config(tmp, 0, &uid, &gid, &mode, &cap);
+    }
+    return handle_send_file(s, path, uid, gid, mode, buffer, do_unlink);
 }
 
 static int do_recv(int s, const char *path, char *buffer)
diff --git a/adb/file_sync_service.h b/adb/file_sync_service.h
index 5dd2e80..c3c8574 100644
--- a/adb/file_sync_service.h
+++ b/adb/file_sync_service.h
@@ -17,22 +17,10 @@
 #ifndef _FILE_SYNC_SERVICE_H_
 #define _FILE_SYNC_SERVICE_H_
 
-#ifdef HAVE_BIG_ENDIAN
-static inline unsigned __swap_uint32(unsigned x) 
-{
-    return (((x) & 0xFF000000) >> 24)
-        | (((x) & 0x00FF0000) >> 8)
-        | (((x) & 0x0000FF00) << 8)
-        | (((x) & 0x000000FF) << 24);
-}
-#define htoll(x) __swap_uint32(x)
-#define ltohl(x) __swap_uint32(x)
-#define MKID(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((a) << 24))
-#else
 #define htoll(x) (x)
 #define ltohl(x) (x)
+
 #define MKID(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
-#endif
 
 #define ID_STAT MKID('S','T','A','T')
 #define ID_LIST MKID('L','I','S','T')
diff --git a/adb/framebuffer_service.c b/adb/framebuffer_service.c
index 8cbe840..61578aa 100644
--- a/adb/framebuffer_service.c
+++ b/adb/framebuffer_service.c
@@ -76,6 +76,7 @@
         exit(1);
     }
 
+    close(fds[1]);
     fd_screencap = fds[0];
 
     /* read w, h & format */
@@ -173,10 +174,9 @@
     }
 
 done:
-    TEMP_FAILURE_RETRY(waitpid(pid, NULL, 0));
-
     close(fds[0]);
-    close(fds[1]);
+
+    TEMP_FAILURE_RETRY(waitpid(pid, NULL, 0));
 pipefail:
     close(fd);
 }
diff --git a/adb/get_my_path_darwin.c b/adb/get_my_path_darwin.c
index 5b95d15..ff1396c 100644
--- a/adb/get_my_path_darwin.c
+++ b/adb/get_my_path_darwin.c
@@ -19,12 +19,12 @@
 
 void get_my_path(char *s, size_t maxLen)
 {
-    ProcessSerialNumber psn;
-    GetCurrentProcess(&psn);
-    CFDictionaryRef dict;
-    dict = ProcessInformationCopyDictionary(&psn, 0xffffffff);
-    CFStringRef value = (CFStringRef)CFDictionaryGetValue(dict,
-                CFSTR("CFBundleExecutable"));
-    CFStringGetCString(value, s, maxLen, kCFStringEncodingUTF8);
+    CFBundleRef mainBundle = CFBundleGetMainBundle();
+    CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle);
+    CFStringRef executablePathString = CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle);
+    CFRelease(executableURL);
+
+    CFStringGetFileSystemRepresentation(executablePathString, s, maxLen);
+    CFRelease(executablePathString);
 }
 
diff --git a/adb/jdwp_service.c b/adb/jdwp_service.c
index cd62b55..3074e42 100644
--- a/adb/jdwp_service.c
+++ b/adb/jdwp_service.c
@@ -415,6 +415,7 @@
               __FUNCTION__, strerror(errno));
             return -1;
         }
+        D("socketpair: (%d,%d)", fds[0], fds[1]);
 
         proc->out_fds[ proc->out_count ] = fds[1];
         if (++proc->out_count == 1)
diff --git a/adb/remount_service.c b/adb/remount_service.c
index 36367a7..d7b0dd1 100644
--- a/adb/remount_service.c
+++ b/adb/remount_service.c
@@ -18,6 +18,7 @@
 
 #include <errno.h>
 #include <fcntl.h>
+#include <mntent.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -36,38 +37,21 @@
 /* Returns the device used to mount a directory in /proc/mounts */
 static char *find_mount(const char *dir)
 {
-    int fd;
-    int res;
-    char *token = NULL;
-    const char delims[] = "\n";
-    char buf[4096];
+    FILE* fp;
+    struct mntent* mentry;
+    char* device = NULL;
 
-    fd = unix_open("/proc/mounts", O_RDONLY | O_CLOEXEC);
-    if (fd < 0)
+    if ((fp = setmntent("/proc/mounts", "r")) == NULL) {
         return NULL;
-
-    buf[sizeof(buf) - 1] = '\0';
-    adb_read(fd, buf, sizeof(buf) - 1);
-    adb_close(fd);
-
-    token = strtok(buf, delims);
-
-    while (token) {
-        char mount_dev[256];
-        char mount_dir[256];
-        int mount_freq;
-        int mount_passno;
-
-        res = sscanf(token, "%255s %255s %*s %*s %d %d\n",
-                     mount_dev, mount_dir, &mount_freq, &mount_passno);
-        mount_dev[255] = 0;
-        mount_dir[255] = 0;
-        if (res == 4 && (strcmp(dir, mount_dir) == 0))
-            return strdup(mount_dev);
-
-        token = strtok(NULL, delims);
     }
-    return NULL;
+    while ((mentry = getmntent(fp)) != NULL) {
+        if (strcmp(dir, mentry->mnt_dir) == 0) {
+            device = strdup(mentry->mnt_fsname);
+            break;
+        }
+    }
+    endmntent(fp);
+    return device;
 }
 
 static int hasVendorPartition()
@@ -79,34 +63,50 @@
     return false;
 }
 
-/* Init mounts /system as read only, remount to enable writes. */
-static int remount(const char* dir, int* dir_ro)
+int make_block_device_writable(const char* dev)
 {
-    char *dev;
-    int fd;
+    int fd = -1;
     int OFF = 0;
-
-    if (dir_ro == 0) {
-        return 0;
-    }
-
-    dev = find_mount(dir);
+    int rc = -1;
 
     if (!dev)
-        return -1;
+        goto errout;
 
     fd = unix_open(dev, O_RDONLY | O_CLOEXEC);
     if (fd < 0)
-        return -1;
+        goto errout;
 
-    ioctl(fd, BLKROSET, &OFF);
-    adb_close(fd);
+    if (ioctl(fd, BLKROSET, &OFF)) {
+        goto errout;
+    }
 
-    *dir_ro = mount(dev, dir, "none", MS_REMOUNT, NULL);
+    rc = 0;
 
+errout:
+    if (fd >= 0) {
+        adb_close(fd);
+    }
+    return rc;
+}
+
+/* Init mounts /system as read only, remount to enable writes. */
+static int remount(const char* dir, int* dir_ro)
+{
+    char *dev = 0;
+    int rc = -1;
+
+    dev = find_mount(dir);
+
+    if (!dev || make_block_device_writable(dev)) {
+        goto errout;
+    }
+
+    rc = mount(dev, dir, "none", MS_REMOUNT, NULL);
+    *dir_ro = rc;
+
+errout:
     free(dev);
-
-    return *dir_ro;
+    return rc;
 }
 
 static void write_string(int fd, const char* str)
@@ -167,4 +167,3 @@
 
     adb_close(fd);
 }
-
diff --git a/adb/services.c b/adb/services.c
index 21b08dc..d5a4642 100644
--- a/adb/services.c
+++ b/adb/services.c
@@ -164,6 +164,7 @@
         printf("cannot create service socket pair\n");
         return -1;
     }
+    D("socketpair: (%d,%d)", s[0], s[1]);
 
     sti = malloc(sizeof(stinfo));
     if(sti == 0) fatal("cannot allocate stinfo");
@@ -202,10 +203,10 @@
 static int create_subproc_pty(const char *cmd, const char *arg0, const char *arg1, pid_t *pid)
 {
     D("create_subproc_pty(cmd=%s, arg0=%s, arg1=%s)\n", cmd, arg0, arg1);
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
     fprintf(stderr, "error: create_subproc_pty not implemented on Win32 (%s %s %s)\n", cmd, arg0, arg1);
     return -1;
-#else /* !HAVE_WIN32_PROC */
+#else
     int ptm;
 
     ptm = unix_open("/dev/ptmx", O_RDWR | O_CLOEXEC); // | O_NOCTTY);
@@ -251,23 +252,24 @@
     } else {
         return ptm;
     }
-#endif /* !HAVE_WIN32_PROC */
+#endif /* !defined(_WIN32) */
 }
 
 static int create_subproc_raw(const char *cmd, const char *arg0, const char *arg1, pid_t *pid)
 {
     D("create_subproc_raw(cmd=%s, arg0=%s, arg1=%s)\n", cmd, arg0, arg1);
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
     fprintf(stderr, "error: create_subproc_raw not implemented on Win32 (%s %s %s)\n", cmd, arg0, arg1);
     return -1;
-#else /* !HAVE_WIN32_PROC */
+#else
 
     // 0 is parent socket, 1 is child socket
     int sv[2];
-    if (unix_socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
+    if (adb_socketpair(sv) < 0) {
         printf("[ cannot create socket pair - %s ]\n", strerror(errno));
         return -1;
     }
+    D("socketpair: (%d,%d)", sv[0], sv[1]);
 
     *pid = fork();
     if (*pid < 0) {
@@ -295,7 +297,7 @@
         adb_close(sv[1]);
         return sv[0];
     }
-#endif /* !HAVE_WIN32_PROC */
+#endif /* !defined(_WIN32) */
 }
 #endif  /* !ABD_HOST */
 
@@ -470,7 +472,9 @@
             }
         }
     } else if(!strncmp(name, "disable-verity:", 15)) {
-        ret = create_service_thread(disable_verity_service, NULL);
+        ret = create_service_thread(set_verity_enabled_state_service, (void*)0);
+    } else if(!strncmp(name, "enable-verity:", 15)) {
+        ret = create_service_thread(set_verity_enabled_state_service, (void*)1);
 #endif
     }
     if (ret >= 0) {
diff --git a/adb/disable_verity_service.c b/adb/set_verity_enable_state_service.c
similarity index 71%
rename from adb/disable_verity_service.c
rename to adb/set_verity_enable_state_service.c
index ed3da52..2660ddd 100644
--- a/adb/disable_verity_service.c
+++ b/adb/set_verity_enable_state_service.c
@@ -44,6 +44,7 @@
     adb_write(fd, buffer, strnlen(buffer, sizeof(buffer)));
 }
 
+#ifdef ALLOW_ADBD_DISABLE_VERITY
 static int get_target_device_size(int fd, const char *blk_device,
                                   uint64_t *device_size)
 {
@@ -78,15 +79,23 @@
     return 0;
 }
 
-static int disable_verity(int fd, const char *block_device,
-                          const char* mount_point)
+/* Turn verity on/off */
+static int set_verity_enabled_state(int fd, const char *block_device,
+                                    const char* mount_point, bool enable)
 {
     uint32_t magic_number;
-    const uint32_t voff = VERITY_METADATA_MAGIC_DISABLE;
+    const uint32_t new_magic = enable ? VERITY_METADATA_MAGIC_NUMBER
+                                      : VERITY_METADATA_MAGIC_DISABLE;
     uint64_t device_length;
-    int device;
+    int device = -1;
     int retval = -1;
 
+    if (make_block_device_writable(block_device)) {
+        write_console(fd, "Could not make block device %s writable (%s).\n",
+                      block_device, strerror(errno));
+        goto errout;
+    }
+
     device = adb_open(block_device, O_RDWR | O_CLOEXEC);
     if (device == -1) {
         write_console(fd, "Could not open block device %s (%s).\n",
@@ -114,12 +123,18 @@
         goto errout;
     }
 
-    if (magic_number == VERITY_METADATA_MAGIC_DISABLE) {
+    if (!enable && magic_number == VERITY_METADATA_MAGIC_DISABLE) {
         write_console(fd, "Verity already disabled on %s\n", mount_point);
         goto errout;
     }
 
-    if (magic_number != VERITY_METADATA_MAGIC_NUMBER) {
+    if (enable && magic_number == VERITY_METADATA_MAGIC_NUMBER) {
+        write_console(fd, "Verity already enabled on %s\n", mount_point);
+        goto errout;
+    }
+
+    if (magic_number != VERITY_METADATA_MAGIC_NUMBER
+            && magic_number != VERITY_METADATA_MAGIC_DISABLE) {
         write_console(fd,
                       "Couldn't find verity metadata at offset %"PRIu64"!\n",
                       device_length);
@@ -132,27 +147,33 @@
         goto errout;
     }
 
-    if (adb_write(device, &voff, sizeof(voff)) != sizeof(voff)) {
-        write_console(fd, "Could not set verity disabled flag on device %s\n",
-                      block_device);
+    if (adb_write(device, &new_magic, sizeof(new_magic)) != sizeof(new_magic)) {
+        write_console(fd, "Could not set verity %s flag on device %s with error %s\n",
+                      enable ? "enabled" : "disabled",
+                      block_device,
+                      strerror(errno));
         goto errout;
     }
 
-    write_console(fd, "Verity disabled on %s\n", mount_point);
+    write_console(fd, "Verity %s on %s\n",
+                  enable ? "enabled" : "disabled",
+                  mount_point);
     retval = 0;
 errout:
     if (device != -1)
         adb_close(device);
     return retval;
 }
+#endif
 
-void disable_verity_service(int fd, void* cookie)
+void set_verity_enabled_state_service(int fd, void* cookie)
 {
+    bool enable = (cookie != NULL);
 #ifdef ALLOW_ADBD_DISABLE_VERITY
     char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
     char propbuf[PROPERTY_VALUE_MAX];
     int i;
-    bool any_disabled = false;
+    bool any_changed = false;
 
     property_get("ro.secure", propbuf, "0");
     if (strcmp(propbuf, "1")) {
@@ -162,7 +183,7 @@
 
     property_get("ro.debuggable", propbuf, "0");
     if (strcmp(propbuf, "1")) {
-        write_console(fd, "verity cannot be disabled - USER build\n");
+        write_console(fd, "verity cannot be disabled/enabled - USER build\n");
         goto errout;
     }
 
@@ -179,21 +200,22 @@
     /* Loop through entries looking for ones that vold manages */
     for (i = 0; i < fstab->num_entries; i++) {
         if(fs_mgr_is_verified(&fstab->recs[i])) {
-            if (!disable_verity(fd, fstab->recs[i].blk_device,
-                                fstab->recs[i].mount_point)) {
-                any_disabled = true;
+            if (!set_verity_enabled_state(fd, fstab->recs[i].blk_device,
+                                          fstab->recs[i].mount_point, enable)) {
+                any_changed = true;
             }
        }
     }
 
-    if (any_disabled) {
+    if (any_changed) {
         write_console(fd,
                       "Now reboot your device for settings to take effect\n");
     }
+errout:
 #else
-    write_console(fd, "disable-verity only works for userdebug builds\n");
+    write_console(fd, "%s-verity only works for userdebug builds\n",
+                  enable ? "enable" : "disable");
 #endif
 
-errout:
     adb_close(fd);
 }
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index cc1f839..8d63d14 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -77,6 +77,11 @@
     return 0;
 }
 
+static __inline__  unsigned long adb_thread_id()
+{
+    return GetCurrentThreadId();
+}
+
 static __inline__ void  close_on_exec(int  fd)
 {
     /* nothing really */
@@ -516,6 +521,12 @@
 {
     return strtok_r(str, delim, saveptr);
 }
+
+static __inline__ unsigned long adb_thread_id()
+{
+    return (unsigned long)pthread_self();
+}
+
 #undef   strtok_r
 #define  strtok_r  ___xxx_strtok_r
 
diff --git a/adb/tests/test_adb.py b/adb/tests/test_adb.py
new file mode 100644
index 0000000..b0ae07f
--- /dev/null
+++ b/adb/tests/test_adb.py
@@ -0,0 +1,390 @@
+#!/usr/bin/env python2
+"""Simple conformance test for adb.
+
+This script will use the available adb in path and run simple
+tests that attempt to touch all accessible attached devices.
+"""
+import hashlib
+import os
+import random
+import re
+import subprocess
+import tempfile
+import unittest
+import sys
+import shlex
+
+
+def trace(cmd):
+    """Print debug message if tracing enabled."""
+    if False:
+        print >> sys.stderr, cmd
+
+
+def call(cmd_str):
+    """Run process and return output tuple (stdout, stderr, ret code)."""
+    trace(cmd_str)
+    process = subprocess.Popen(shlex.split(cmd_str),
+                               stdout=subprocess.PIPE,
+                               stderr=subprocess.PIPE)
+    stdout, stderr = process.communicate()
+    return stdout, stderr, process.returncode
+
+
+def call_combined(cmd_str):
+    """Run process and return output tuple (stdout+stderr, ret code)."""
+    trace(cmd_str)
+    process = subprocess.Popen(shlex.split(cmd_str),
+                               stdout=subprocess.PIPE,
+                               stderr=subprocess.STDOUT)
+    stdout, _ = process.communicate()
+    return stdout, process.returncode
+
+
+def call_checked(cmd_str):
+    """Run process and get stdout+stderr, raise an exception on trouble."""
+    trace(cmd_str)
+    return subprocess.check_output(shlex.split(cmd_str),
+                                   stderr=subprocess.STDOUT)
+
+
+def call_checked_list(cmd_str):
+    return call_checked(cmd_str).split('\n')
+
+
+def call_checked_list_skip(cmd_str):
+    out_list = call_checked_list(cmd_str)
+
+    def is_init_line(line):
+        if (len(line) >= 3) and (line[0] == "*") and (line[-2] == "*"):
+            return True
+        else:
+            return False
+
+    return [line for line in out_list if not is_init_line(line)]
+
+
+def get_device_list():
+    output = call_checked_list_skip("adb devices")
+    dev_list = []
+    for line in output[1:]:
+        if line.strip() == "":
+            continue
+        device, _ = line.split()
+        dev_list.append(device)
+    return dev_list
+
+
+def get_attached_device_count():
+    return len(get_device_list())
+
+
+def compute_md5(string):
+    hsh = hashlib.md5()
+    hsh.update(string)
+    return hsh.hexdigest()
+
+
+class HostFile(object):
+    def __init__(self, handle, md5):
+        self.handle = handle
+        self.md5 = md5
+        self.full_path = handle.name
+        self.base_name = os.path.basename(self.full_path)
+
+
+class DeviceFile(object):
+    def __init__(self, md5, full_path):
+        self.md5 = md5
+        self.full_path = full_path
+        self.base_name = os.path.basename(self.full_path)
+
+
+def make_random_host_files(in_dir, num_files, rand_size=True):
+    files = {}
+    min_size = 1 * (1 << 10)
+    max_size = 16 * (1 << 10)
+    fixed_size = min_size
+
+    for _ in range(num_files):
+        file_handle = tempfile.NamedTemporaryFile(dir=in_dir)
+
+        if rand_size:
+            size = random.randrange(min_size, max_size, 1024)
+        else:
+            size = fixed_size
+        rand_str = os.urandom(size)
+        file_handle.write(rand_str)
+        file_handle.flush()
+
+        md5 = compute_md5(rand_str)
+        files[file_handle.name] = HostFile(file_handle, md5)
+    return files
+
+
+def make_random_device_files(adb, in_dir, num_files, rand_size=True):
+    files = {}
+    min_size = 1 * (1 << 10)
+    max_size = 16 * (1 << 10)
+    fixed_size = min_size
+
+    for i in range(num_files):
+        if rand_size:
+            size = random.randrange(min_size, max_size, 1024)
+        else:
+            size = fixed_size
+
+        base_name = "device_tmpfile" + str(i)
+        full_path = in_dir + "/" + base_name
+
+        adb.shell("dd if=/dev/urandom of={} bs={} count=1".format(full_path,
+                                                                  size))
+        dev_md5, _ = adb.shell("md5sum {}".format(full_path)).split()
+
+        files[full_path] = DeviceFile(dev_md5, full_path)
+    return files
+
+
+class AdbWrapper(object):
+    """Convenience wrapper object for the adb command."""
+    def __init__(self, device=None, out_dir=None):
+        self.device = device
+        self.out_dir = out_dir
+        self.adb_cmd = "adb "
+        if self.device:
+            self.adb_cmd += "-s {} ".format(device)
+        if self.out_dir:
+            self.adb_cmd += "-p {} ".format(out_dir)
+
+    def shell(self, cmd):
+        return call_checked(self.adb_cmd + "shell " + cmd)
+
+    def shell_nocheck(self, cmd):
+        return call_combined(self.adb_cmd + "shell " + cmd)
+
+    def push(self, local, remote):
+        return call_checked(self.adb_cmd + "push {} {}".format(local, remote))
+
+    def pull(self, remote, local):
+        return call_checked(self.adb_cmd + "pull {} {}".format(remote, local))
+
+    def sync(self, directory=""):
+        return call_checked(self.adb_cmd + "sync {}".format(directory))
+
+    def forward(self, local, remote):
+        return call_checked(self.adb_cmd + "forward {} {}".format(local,
+                                                                  remote))
+
+    def tcpip(self, port):
+        return call_checked(self.adb_cmd + "tcpip {}".format(port))
+
+    def usb(self):
+        return call_checked(self.adb_cmd + "usb")
+
+    def forward_remove(self, local):
+        return call_checked(self.adb_cmd + "forward --remove {}".format(local))
+
+    def forward_remove_all(self):
+        return call_checked(self.adb_cmd + "forward --remove-all")
+
+    def connect(self, host):
+        return call_checked(self.adb_cmd + "connect {}".format(host))
+
+    def disconnect(self, host):
+        return call_checked(self.adb_cmd + "disconnect {}".format(host))
+
+    def reverse(self, remote, local):
+        return call_checked(self.adb_cmd + "reverse {} {}".format(remote,
+                                                                  local))
+
+    def reverse_remove_all(self):
+        return call_checked(self.adb_cmd + "reverse --remove-all")
+
+    def reverse_remove(self, remote):
+        return call_checked(
+            self.adb_cmd + "reverse --remove {}".format(remote))
+
+    def wait(self):
+        return call_checked(self.adb_cmd + "wait-for-device")
+
+
+class AdbBasic(unittest.TestCase):
+    def test_devices(self):
+        """Get uptime for each device plugged in from /proc/uptime."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            out = call_checked(
+                "adb -s {} shell cat /proc/uptime".format(device))
+            self.assertEqual(len(out.split()), 2)
+            self.assertGreater(float(out.split()[0]), 0.0)
+            self.assertGreater(float(out.split()[1]), 0.0)
+
+    def test_help(self):
+        """Make sure we get _something_ out of help."""
+        out = call_checked("adb help")
+        self.assertTrue(len(out) > 0)
+
+    def test_version(self):
+        """Get a version number out of the output of adb."""
+        out = call_checked("adb version").split()
+        version_num = False
+        for item in out:
+            if re.match(r"[\d+\.]*\d", item):
+                version_num = True
+        self.assertTrue(version_num)
+
+
+class AdbFile(unittest.TestCase):
+    SCRATCH_DIR = "/data/local/tmp"
+    DEVICE_TEMP_FILE = SCRATCH_DIR + "/adb_test_file"
+    DEVICE_TEMP_DIR = SCRATCH_DIR + "/adb_test_dir"
+
+    def test_push(self):
+        """Push a file to all attached devices."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            self.push_with_device(device)
+
+    def push_with_device(self, device):
+        """Push a randomly generated file to specified device."""
+        kbytes = 512
+        adb = AdbWrapper(device)
+        with tempfile.NamedTemporaryFile(mode="w") as tmp:
+            rand_str = os.urandom(1024 * kbytes)
+            tmp.write(rand_str)
+            tmp.flush()
+
+            host_md5 = compute_md5(rand_str)
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_FILE))
+            try:
+                adb.push(local=tmp.name, remote=AdbFile.DEVICE_TEMP_FILE)
+                dev_md5, _ = adb.shell(
+                    "md5sum {}".format(AdbFile.DEVICE_TEMP_FILE)).split()
+                self.assertEqual(host_md5, dev_md5)
+            finally:
+                adb.shell_nocheck("rm {}".format(AdbFile.DEVICE_TEMP_FILE))
+
+    # TODO: write push directory test.
+
+    def test_pull(self):
+        """Pull a file from all attached devices."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            self.pull_with_device(device)
+
+    def pull_with_device(self, device):
+        """Pull a randomly generated file from specified device."""
+        kbytes = 512
+        adb = AdbWrapper(device)
+        adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_FILE))
+        try:
+            adb.shell("dd if=/dev/urandom of={} bs=1024 count={}".format(
+                AdbFile.DEVICE_TEMP_FILE, kbytes))
+            dev_md5, _ = adb.shell(
+                "md5sum {}".format(AdbFile.DEVICE_TEMP_FILE)).split()
+
+            with tempfile.NamedTemporaryFile(mode="w") as tmp_write:
+                adb.pull(remote=AdbFile.DEVICE_TEMP_FILE, local=tmp_write.name)
+                with open(tmp_write.name) as tmp_read:
+                    host_contents = tmp_read.read()
+                    host_md5 = compute_md5(host_contents)
+                self.assertEqual(dev_md5, host_md5)
+        finally:
+            adb.shell_nocheck("rm {}".format(AdbFile.DEVICE_TEMP_FILE))
+
+    def test_pull_dir(self):
+        """Pull a directory from all attached devices."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            self.pull_dir_with_device(device)
+
+    def pull_dir_with_device(self, device):
+        """Pull a randomly generated directory of files from the device."""
+        adb = AdbWrapper(device)
+        temp_files = {}
+        host_dir = None
+        try:
+            # create temporary host directory
+            host_dir = tempfile.mkdtemp()
+
+            # create temporary dir on device
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_DIR))
+            adb.shell("mkdir -p {}".format(AdbFile.DEVICE_TEMP_DIR))
+
+            # populate device dir with random files
+            temp_files = make_random_device_files(
+                adb, in_dir=AdbFile.DEVICE_TEMP_DIR, num_files=32)
+
+            adb.pull(remote=AdbFile.DEVICE_TEMP_DIR, local=host_dir)
+
+            for device_full_path in temp_files:
+                host_path = os.path.join(
+                    host_dir, temp_files[device_full_path].base_name)
+                with open(host_path) as host_file:
+                    host_md5 = compute_md5(host_file.read())
+                    self.assertEqual(host_md5,
+                                     temp_files[device_full_path].md5)
+        finally:
+            for dev_file in temp_files.values():
+                host_path = os.path.join(host_dir, dev_file.base_name)
+                os.remove(host_path)
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_DIR))
+            if host_dir:
+                os.removedirs(host_dir)
+
+    def test_sync(self):
+        """Sync a directory with all attached devices."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            self.sync_dir_with_device(device)
+
+    def sync_dir_with_device(self, device):
+        """Sync a randomly generated directory of files to specified device."""
+        try:
+            adb = AdbWrapper(device)
+            temp_files = {}
+
+            # create temporary host directory
+            base_dir = tempfile.mkdtemp()
+
+            # create mirror device directory hierarchy within base_dir
+            full_dir_path = base_dir + AdbFile.DEVICE_TEMP_DIR
+            os.makedirs(full_dir_path)
+
+            # create 32 random files within the host mirror
+            temp_files = make_random_host_files(in_dir=full_dir_path,
+                                                num_files=32)
+
+            # clean up any trash on the device
+            adb = AdbWrapper(device, out_dir=base_dir)
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_DIR))
+
+            # issue the sync
+            adb.sync("data")
+
+            # confirm that every file on the device mirrors that on the host
+            for host_full_path in temp_files.keys():
+                device_full_path = os.path.join(
+                    AdbFile.DEVICE_TEMP_DIR,
+                    temp_files[host_full_path].base_name)
+                dev_md5, _ = adb.shell(
+                    "md5sum {}".format(device_full_path)).split()
+                self.assertEqual(temp_files[host_full_path].md5, dev_md5)
+
+        finally:
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_DIR))
+            if temp_files:
+                for tf in temp_files.values():
+                    tf.handle.close()
+            if base_dir:
+                os.removedirs(base_dir + AdbFile.DEVICE_TEMP_DIR)
+
+
+if __name__ == '__main__':
+    random.seed(0)
+    dev_count = get_attached_device_count()
+    if dev_count:
+        suite = unittest.TestLoader().loadTestsFromName(__name__)
+        unittest.TextTestRunner(verbosity=3).run(suite)
+    else:
+        print "Test suite must be run with attached devices"
diff --git a/adb/transport.c b/adb/transport.c
index f35880c..7db6a47 100644
--- a/adb/transport.c
+++ b/adb/transport.c
@@ -629,7 +629,7 @@
             fatal_errno("cannot open transport socketpair");
         }
 
-        D("transport: %s (%d,%d) starting\n", t->serial, s[0], s[1]);
+        D("transport: %s socketpair: (%d,%d) starting", t->serial, s[0], s[1]);
 
         t->transport_socket = s[0];
         t->fd = s[1];
@@ -673,6 +673,7 @@
     if(adb_socketpair(s)){
         fatal_errno("cannot open transport registration socketpair");
     }
+    D("socketpair: (%d,%d)", s[0], s[1]);
 
     transport_registration_send = s[0];
     transport_registration_recv = s[1];
diff --git a/adb/transport_local.c b/adb/transport_local.c
index 948cc15..6c4e220 100644
--- a/adb/transport_local.c
+++ b/adb/transport_local.c
@@ -28,21 +28,6 @@
 #define  TRACE_TAG  TRACE_TRANSPORT
 #include "adb.h"
 
-#ifdef HAVE_BIG_ENDIAN
-#define H4(x)	(((x) & 0xFF000000) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | (((x) & 0x000000FF) << 24)
-static inline void fix_endians(apacket *p)
-{
-    p->msg.command     = H4(p->msg.command);
-    p->msg.arg0        = H4(p->msg.arg0);
-    p->msg.arg1        = H4(p->msg.arg1);
-    p->msg.data_length = H4(p->msg.data_length);
-    p->msg.data_check  = H4(p->msg.data_check);
-    p->msg.magic       = H4(p->msg.magic);
-}
-#else
-#define fix_endians(p) do {} while (0)
-#endif
-
 #if ADB_HOST
 /* we keep a list of opened transports. The atransport struct knows to which
  * local transport it is connected. The list is used to detect when we're
@@ -62,12 +47,6 @@
         return -1;
     }
 
-    fix_endians(p);
-
-#if 0 && defined HAVE_BIG_ENDIAN
-    D("read remote packet: %04x arg0=%0x arg1=%0x data_length=%0x data_check=%0x magic=%0x\n",
-      p->msg.command, p->msg.arg0, p->msg.arg1, p->msg.data_length, p->msg.data_check, p->msg.magic);
-#endif
     if(check_header(p)) {
         D("bad header: terminated (data)\n");
         return -1;
@@ -90,12 +69,6 @@
 {
     int   length = p->msg.data_length;
 
-    fix_endians(p);
-
-#if 0 && defined HAVE_BIG_ENDIAN
-    D("write remote packet: %04x arg0=%0x arg1=%0x data_length=%0x data_check=%0x magic=%0x\n",
-      p->msg.command, p->msg.arg0, p->msg.arg1, p->msg.data_length, p->msg.data_check, p->msg.magic);
-#endif
     if(writex(t->sfd, &p->msg, sizeof(amessage) + length)) {
         D("remote local: write terminated\n");
         return -1;
diff --git a/adb/transport_usb.c b/adb/transport_usb.c
index ee6b637..1138ddd 100644
--- a/adb/transport_usb.c
+++ b/adb/transport_usb.c
@@ -23,33 +23,6 @@
 #define  TRACE_TAG  TRACE_TRANSPORT
 #include "adb.h"
 
-#if ADB_HOST
-#include "usb_vendors.h"
-#endif
-
-#ifdef HAVE_BIG_ENDIAN
-#define H4(x)	(((x) & 0xFF000000) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | (((x) & 0x000000FF) << 24)
-static inline void fix_endians(apacket *p)
-{
-    p->msg.command     = H4(p->msg.command);
-    p->msg.arg0        = H4(p->msg.arg0);
-    p->msg.arg1        = H4(p->msg.arg1);
-    p->msg.data_length = H4(p->msg.data_length);
-    p->msg.data_check  = H4(p->msg.data_check);
-    p->msg.magic       = H4(p->msg.magic);
-}
-unsigned host_to_le32(unsigned n)
-{
-    return H4(n);
-}
-#else
-#define fix_endians(p) do {} while (0)
-unsigned host_to_le32(unsigned n)
-{
-    return n;
-}
-#endif
-
 static int remote_read(apacket *p, atransport *t)
 {
     if(usb_read(t->usb, &p->msg, sizeof(amessage))){
@@ -57,8 +30,6 @@
         return -1;
     }
 
-    fix_endians(p);
-
     if(check_header(p)) {
         D("remote usb: check_header failed\n");
         return -1;
@@ -83,8 +54,6 @@
 {
     unsigned size = p->msg.data_length;
 
-    fix_endians(p);
-
     if(usb_write(t->usb, &p->msg, sizeof(amessage))) {
         D("remote usb: 1 - write terminated\n");
         return -1;
@@ -131,18 +100,6 @@
 #if ADB_HOST
 int is_adb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol)
 {
-    unsigned i;
-    for (i = 0; i < vendorIdCount; i++) {
-        if (vid == vendorIds[i]) {
-            if (usb_class == ADB_CLASS && usb_subclass == ADB_SUBCLASS &&
-                    usb_protocol == ADB_PROTOCOL) {
-                return 1;
-            }
-
-            return 0;
-        }
-    }
-
-    return 0;
+    return (usb_class == ADB_CLASS && usb_subclass == ADB_SUBCLASS && usb_protocol == ADB_PROTOCOL);
 }
 #endif
diff --git a/adb/usb_linux.c b/adb/usb_linux.c
index f16bdd0..7d13a5d 100644
--- a/adb/usb_linux.c
+++ b/adb/usb_linux.c
@@ -237,8 +237,20 @@
                             // looks like ADB...
                         ep1 = (struct usb_endpoint_descriptor *)bufptr;
                         bufptr += USB_DT_ENDPOINT_SIZE;
+                            // For USB 3.0 SuperSpeed devices, skip potential
+                            // USB 3.0 SuperSpeed Endpoint Companion descriptor
+                        if (bufptr+2 <= devdesc + desclength &&
+                            bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
+                            bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
+                            bufptr += USB_DT_SS_EP_COMP_SIZE;
+                        }
                         ep2 = (struct usb_endpoint_descriptor *)bufptr;
                         bufptr += USB_DT_ENDPOINT_SIZE;
+                        if (bufptr+2 <= devdesc + desclength &&
+                            bufptr[0] == USB_DT_SS_EP_COMP_SIZE &&
+                            bufptr[1] == USB_DT_SS_ENDPOINT_COMP) {
+                            bufptr += USB_DT_SS_EP_COMP_SIZE;
+                        }
 
                         if (bufptr > devdesc + desclength ||
                             ep1->bLength != USB_DT_ENDPOINT_SIZE ||
diff --git a/adb/usb_linux_client.c b/adb/usb_linux_client.c
index 8426e0e..fd566f4 100644
--- a/adb/usb_linux_client.c
+++ b/adb/usb_linux_client.c
@@ -33,6 +33,7 @@
 
 #define MAX_PACKET_SIZE_FS	64
 #define MAX_PACKET_SIZE_HS	512
+#define MAX_PACKET_SIZE_SS	1024
 
 #define cpu_to_le16(x)  htole16(x)
 #define cpu_to_le32(x)  htole32(x)
@@ -55,71 +56,85 @@
     int bulk_in;  /* "in" from the host's perspective => sink for adbd */
 };
 
-static const struct {
-    struct usb_functionfs_descs_head header;
-    struct {
-        struct usb_interface_descriptor intf;
-        struct usb_endpoint_descriptor_no_audio source;
-        struct usb_endpoint_descriptor_no_audio sink;
-    } __attribute__((packed)) fs_descs, hs_descs;
-} __attribute__((packed)) descriptors = {
-    .header = {
-        .magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC),
-        .length = cpu_to_le32(sizeof(descriptors)),
-        .fs_count = 3,
-        .hs_count = 3,
+struct func_desc {
+    struct usb_interface_descriptor intf;
+    struct usb_endpoint_descriptor_no_audio source;
+    struct usb_endpoint_descriptor_no_audio sink;
+} __attribute__((packed));
+
+struct desc_v1 {
+    struct usb_functionfs_descs_head_v1 {
+        __le32 magic;
+        __le32 length;
+        __le32 fs_count;
+        __le32 hs_count;
+    } __attribute__((packed)) header;
+    struct func_desc fs_descs, hs_descs;
+} __attribute__((packed));
+
+struct desc_v2 {
+    struct usb_functionfs_descs_head_v2 {
+        __le32 magic;
+        __le32 length;
+        __le32 flags;
+        __le32 fs_count;
+        __le32 hs_count;
+        __le32 ss_count;
+    } __attribute__((packed)) header;
+    struct func_desc fs_descs, hs_descs;
+} __attribute__((packed));
+
+struct func_desc fs_descriptors = {
+    .intf = {
+        .bLength = sizeof(fs_descriptors.intf),
+        .bDescriptorType = USB_DT_INTERFACE,
+        .bInterfaceNumber = 0,
+        .bNumEndpoints = 2,
+        .bInterfaceClass = ADB_CLASS,
+        .bInterfaceSubClass = ADB_SUBCLASS,
+        .bInterfaceProtocol = ADB_PROTOCOL,
+        .iInterface = 1, /* first string from the provided table */
     },
-    .fs_descs = {
-        .intf = {
-            .bLength = sizeof(descriptors.fs_descs.intf),
-            .bDescriptorType = USB_DT_INTERFACE,
-            .bInterfaceNumber = 0,
-            .bNumEndpoints = 2,
-            .bInterfaceClass = ADB_CLASS,
-            .bInterfaceSubClass = ADB_SUBCLASS,
-            .bInterfaceProtocol = ADB_PROTOCOL,
-            .iInterface = 1, /* first string from the provided table */
-        },
-        .source = {
-            .bLength = sizeof(descriptors.fs_descs.source),
-            .bDescriptorType = USB_DT_ENDPOINT,
-            .bEndpointAddress = 1 | USB_DIR_OUT,
-            .bmAttributes = USB_ENDPOINT_XFER_BULK,
-            .wMaxPacketSize = MAX_PACKET_SIZE_FS,
-        },
-        .sink = {
-            .bLength = sizeof(descriptors.fs_descs.sink),
-            .bDescriptorType = USB_DT_ENDPOINT,
-            .bEndpointAddress = 2 | USB_DIR_IN,
-            .bmAttributes = USB_ENDPOINT_XFER_BULK,
-            .wMaxPacketSize = MAX_PACKET_SIZE_FS,
-        },
+    .source = {
+        .bLength = sizeof(fs_descriptors.source),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 1 | USB_DIR_OUT,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_FS,
     },
-    .hs_descs = {
-        .intf = {
-            .bLength = sizeof(descriptors.hs_descs.intf),
-            .bDescriptorType = USB_DT_INTERFACE,
-            .bInterfaceNumber = 0,
-            .bNumEndpoints = 2,
-            .bInterfaceClass = ADB_CLASS,
-            .bInterfaceSubClass = ADB_SUBCLASS,
-            .bInterfaceProtocol = ADB_PROTOCOL,
-            .iInterface = 1, /* first string from the provided table */
-        },
-        .source = {
-            .bLength = sizeof(descriptors.hs_descs.source),
-            .bDescriptorType = USB_DT_ENDPOINT,
-            .bEndpointAddress = 1 | USB_DIR_OUT,
-            .bmAttributes = USB_ENDPOINT_XFER_BULK,
-            .wMaxPacketSize = MAX_PACKET_SIZE_HS,
-        },
-        .sink = {
-            .bLength = sizeof(descriptors.hs_descs.sink),
-            .bDescriptorType = USB_DT_ENDPOINT,
-            .bEndpointAddress = 2 | USB_DIR_IN,
-            .bmAttributes = USB_ENDPOINT_XFER_BULK,
-            .wMaxPacketSize = MAX_PACKET_SIZE_HS,
-        },
+    .sink = {
+        .bLength = sizeof(fs_descriptors.sink),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 2 | USB_DIR_IN,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_FS,
+    },
+};
+
+struct func_desc hs_descriptors = {
+    .intf = {
+        .bLength = sizeof(hs_descriptors.intf),
+        .bDescriptorType = USB_DT_INTERFACE,
+        .bInterfaceNumber = 0,
+        .bNumEndpoints = 2,
+        .bInterfaceClass = ADB_CLASS,
+        .bInterfaceSubClass = ADB_SUBCLASS,
+        .bInterfaceProtocol = ADB_PROTOCOL,
+        .iInterface = 1, /* first string from the provided table */
+    },
+    .source = {
+        .bLength = sizeof(hs_descriptors.source),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 1 | USB_DIR_OUT,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_HS,
+    },
+    .sink = {
+        .bLength = sizeof(hs_descriptors.sink),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 2 | USB_DIR_IN,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_HS,
     },
 };
 
@@ -263,6 +278,17 @@
 static void init_functionfs(struct usb_handle *h)
 {
     ssize_t ret;
+    struct desc_v1 v1_descriptor;
+    struct desc_v2 v2_descriptor;
+
+    v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2);
+    v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor));
+    v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
+    v2_descriptor.header.fs_count = 3;
+    v2_descriptor.header.hs_count = 3;
+    v2_descriptor.header.ss_count = 0;
+    v2_descriptor.fs_descs = fs_descriptors;
+    v2_descriptor.hs_descs = hs_descriptors;
 
     if (h->control < 0) { // might have already done this before
         D("OPENING %s\n", USB_FFS_ADB_EP0);
@@ -272,10 +298,20 @@
             goto err;
         }
 
-        ret = adb_write(h->control, &descriptors, sizeof(descriptors));
+        ret = adb_write(h->control, &v2_descriptor, sizeof(v2_descriptor));
         if (ret < 0) {
-            D("[ %s: write descriptors failed: errno=%d ]\n", USB_FFS_ADB_EP0, errno);
-            goto err;
+            v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC);
+            v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor));
+            v1_descriptor.header.fs_count = 3;
+            v1_descriptor.header.hs_count = 3;
+            v1_descriptor.fs_descs = fs_descriptors;
+            v1_descriptor.hs_descs = hs_descriptors;
+            D("[ %s: Switching to V1_descriptor format errno=%d ]\n", USB_FFS_ADB_EP0, errno);
+            ret = adb_write(h->control, &v1_descriptor, sizeof(v1_descriptor));
+            if (ret < 0) {
+                D("[ %s: write descriptors failed: errno=%d ]\n", USB_FFS_ADB_EP0, errno);
+                goto err;
+            }
         }
 
         ret = adb_write(h->control, &strings, sizeof(strings));
diff --git a/adb/usb_osx.c b/adb/usb_osx.c
index ca4f2af..ba157f1 100644
--- a/adb/usb_osx.c
+++ b/adb/usb_osx.c
@@ -28,12 +28,11 @@
 
 #define TRACE_TAG   TRACE_USB
 #include "adb.h"
-#include "usb_vendors.h"
 
 #define  DBG   D
 
 static IONotificationPortRef    notificationPort = 0;
-static io_iterator_t*           notificationIterators;
+static io_iterator_t            notificationIterator;
 
 struct usb_handle
 {
@@ -61,8 +60,6 @@
 {
     CFMutableDictionaryRef  matchingDict;
     CFRunLoopSourceRef      runLoopSource;
-    SInt32                  vendor, if_subclass, if_protocol;
-    unsigned                i;
 
     //* To set up asynchronous notifications, create a notification port and
     //* add its run loop event source to the program's run loop
@@ -70,47 +67,33 @@
     runLoopSource = IONotificationPortGetRunLoopSource(notificationPort);
     CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
 
-    memset(notificationIterators, 0, sizeof(notificationIterators));
+    //* Create our matching dictionary to find the Android device's
+    //* adb interface
+    //* IOServiceAddMatchingNotification consumes the reference, so we do
+    //* not need to release this
+    matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
 
-    //* loop through all supported vendors
-    for (i = 0; i < vendorIdCount; i++) {
-        //* Create our matching dictionary to find the Android device's
-        //* adb interface
-        //* IOServiceAddMatchingNotification consumes the reference, so we do
-        //* not need to release this
-        matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
-
-        if (!matchingDict) {
-            DBG("ERR: Couldn't create USB matching dictionary.\n");
-            return -1;
-        }
-
-        //* Match based on vendor id, interface subclass and protocol
-        vendor = vendorIds[i];
-        if_subclass = ADB_SUBCLASS;
-        if_protocol = ADB_PROTOCOL;
-        CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID),
-                             CFNumberCreate(kCFAllocatorDefault,
-                                            kCFNumberSInt32Type, &vendor));
-        CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceSubClass),
-                             CFNumberCreate(kCFAllocatorDefault,
-                                            kCFNumberSInt32Type, &if_subclass));
-        CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceProtocol),
-                             CFNumberCreate(kCFAllocatorDefault,
-                                            kCFNumberSInt32Type, &if_protocol));
-        IOServiceAddMatchingNotification(
-                notificationPort,
-                kIOFirstMatchNotification,
-                matchingDict,
-                AndroidInterfaceAdded,
-                NULL,
-                &notificationIterators[i]);
-
-        //* Iterate over set of matching interfaces to access already-present
-        //* devices and to arm the notification
-        AndroidInterfaceAdded(NULL, notificationIterators[i]);
+    if (!matchingDict) {
+        DBG("ERR: Couldn't create USB matching dictionary.\n");
+        return -1;
     }
 
+    //* We have to get notifications for all potential candidates and test them
+    //* at connection time because the matching rules don't allow for a
+    //* USB interface class of 0xff for class+subclass+protocol matches
+    //* See https://developer.apple.com/library/mac/qa/qa1076/_index.html
+    IOServiceAddMatchingNotification(
+            notificationPort,
+            kIOFirstMatchNotification,
+            matchingDict,
+            AndroidInterfaceAdded,
+            NULL,
+            &notificationIterator);
+
+    //* Iterate over set of matching interfaces to access already-present
+    //* devices and to arm the notification
+    AndroidInterfaceAdded(NULL, notificationIterator);
+
     return 0;
 }
 
@@ -126,6 +109,7 @@
     HRESULT                  result;
     SInt32                   score;
     UInt32                   locationId;
+    UInt8                    class, subclass, protocol;
     UInt16                   vendor;
     UInt16                   product;
     UInt8                    serialIndex;
@@ -156,6 +140,16 @@
             continue;
         }
 
+        kr = (*iface)->GetInterfaceClass(iface, &class);
+        kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
+        kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
+        if(class != ADB_CLASS || subclass != ADB_SUBCLASS || protocol != ADB_PROTOCOL) {
+            // Ignore non-ADB devices.
+            DBG("Ignoring interface with incorrect class/subclass/protocol - %d, %d, %d\n", class, subclass, protocol);
+            (*iface)->Release(iface);
+            continue;
+        }
+
         //* this gets us an ioservice, with which we will find the actual
         //* device; after getting a plugin, and querying the interface, of
         //* course.
@@ -192,12 +186,12 @@
 
         //* Now after all that, we actually have a ref to the device and
         //* the interface that matched our criteria
-
         kr = (*dev)->GetDeviceVendor(dev, &vendor);
         kr = (*dev)->GetDeviceProduct(dev, &product);
         kr = (*dev)->GetLocationID(dev, &locationId);
         if (kr == 0) {
-            snprintf(devpathBuf, sizeof(devpathBuf), "usb:%lX", locationId);
+            snprintf(devpathBuf, sizeof(devpathBuf), "usb:%" PRIu32 "X",
+	             (unsigned int)locationId);
             devpath = devpathBuf;
         }
         kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
@@ -384,8 +378,6 @@
 
 void* RunLoopThread(void* unused)
 {
-    unsigned i;
-
     InitUSB();
 
     currentRunLoop = CFRunLoopGetCurrent();
@@ -398,9 +390,7 @@
     CFRunLoopRun();
     currentRunLoop = 0;
 
-    for (i = 0; i < vendorIdCount; i++) {
-        IOObjectRelease(notificationIterators[i]);
-    }
+    IOObjectRelease(notificationIterator);
     IONotificationPortDestroy(notificationPort);
 
     DBG("RunLoopThread done\n");
@@ -415,9 +405,6 @@
     {
         adb_thread_t    tid;
 
-        notificationIterators = (io_iterator_t*)malloc(
-            vendorIdCount * sizeof(io_iterator_t));
-
         adb_mutex_init(&start_lock, NULL);
         adb_cond_init(&start_cond, NULL);
 
@@ -442,11 +429,6 @@
     close_usb_devices();
     if (currentRunLoop)
         CFRunLoopStop(currentRunLoop);
-
-    if (notificationIterators != NULL) {
-        free(notificationIterators);
-        notificationIterators = NULL;
-    }
 }
 
 int usb_write(usb_handle *handle, const void *buf, int len)
diff --git a/adb/usb_vendors.c b/adb/usb_vendors.c
deleted file mode 100755
index 19bcae4..0000000
--- a/adb/usb_vendors.c
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * Copyright (C) 2009 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 "usb_vendors.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#ifdef _WIN32
-#  ifndef WIN32_LEAN_AND_MEAN
-#    define WIN32_LEAN_AND_MEAN
-#  endif
-#  include "windows.h"
-#  include "shlobj.h"
-#else
-#  include <unistd.h>
-#  include <sys/stat.h>
-#endif
-
-#include "sysdeps.h"
-#include "adb.h"
-
-#define ANDROID_PATH            ".android"
-#define ANDROID_ADB_INI         "adb_usb.ini"
-
-#define TRACE_TAG               TRACE_USB
-
-/* Keep the list below sorted alphabetically by #define name */
-// Acer's USB Vendor ID
-#define VENDOR_ID_ACER          0x0502
-// Allwinner's USB Vendor ID
-#define VENDOR_ID_ALLWINNER     0x1F3A
-// Amlogic's USB Vendor ID
-#define VENDOR_ID_AMLOGIC       0x1b8e
-// AnyDATA's USB Vendor ID
-#define VENDOR_ID_ANYDATA       0x16D5
-// Archos's USB Vendor ID
-#define VENDOR_ID_ARCHOS        0x0E79
-// Asus's USB Vendor ID
-#define VENDOR_ID_ASUS          0x0b05
-// BYD's USB Vendor ID
-#define VENDOR_ID_BYD           0x1D91
-// Compal's USB Vendor ID
-#define VENDOR_ID_COMPAL        0x04B7
-// Compalcomm's USB Vendor ID
-#define VENDOR_ID_COMPALCOMM    0x1219
-// Dell's USB Vendor ID
-#define VENDOR_ID_DELL          0x413c
-// ECS's USB Vendor ID
-#define VENDOR_ID_ECS           0x03fc
-// EMERGING_TECH's USB Vendor ID
-#define VENDOR_ID_EMERGING_TECH 0x297F
-// Emerson's USB Vendor ID
-#define VENDOR_ID_EMERSON       0x2207
-// Foxconn's USB Vendor ID
-#define VENDOR_ID_FOXCONN       0x0489
-// Fujitsu's USB Vendor ID
-#define VENDOR_ID_FUJITSU       0x04C5
-// Funai's USB Vendor ID
-#define VENDOR_ID_FUNAI         0x0F1C
-// Garmin-Asus's USB Vendor ID
-#define VENDOR_ID_GARMIN_ASUS   0x091E
-// Gigabyte's USB Vendor ID
-#define VENDOR_ID_GIGABYTE      0x0414
-// Gigaset's USB Vendor ID
-#define VENDOR_ID_GIGASET       0x1E85
-// GIONEE's USB Vendor ID
-#define VENDOR_ID_GIONEE        0x271D
-// Google's USB Vendor ID
-#define VENDOR_ID_GOOGLE        0x18d1
-// Haier's USB Vendor ID
-#define VENDOR_ID_HAIER         0x201E
-// Harris's USB Vendor ID
-#define VENDOR_ID_HARRIS        0x19A5
-// Hisense's USB Vendor ID
-#define VENDOR_ID_HISENSE       0x109b
-// Honeywell's USB Vendor ID
-#define VENDOR_ID_HONEYWELL     0x0c2e
-// HP's USB Vendor ID
-#define VENDOR_ID_HP            0x03f0
-// HTC's USB Vendor ID
-#define VENDOR_ID_HTC           0x0bb4
-// Huawei's USB Vendor ID
-#define VENDOR_ID_HUAWEI        0x12D1
-// INQ Mobile's USB Vendor ID
-#define VENDOR_ID_INQ_MOBILE    0x2314
-// Intel's USB Vendor ID
-#define VENDOR_ID_INTEL         0x8087
-// Intermec's USB Vendor ID
-#define VENDOR_ID_INTERMEC      0x067e
-// IRiver's USB Vendor ID
-#define VENDOR_ID_IRIVER        0x2420
-// K-Touch's USB Vendor ID
-#define VENDOR_ID_K_TOUCH       0x24E3
-// KT Tech's USB Vendor ID
-#define VENDOR_ID_KT_TECH       0x2116
-// Kobo's USB Vendor ID
-#define VENDOR_ID_KOBO          0x2237
-// Kyocera's USB Vendor ID
-#define VENDOR_ID_KYOCERA       0x0482
-// Lab126's USB Vendor ID
-#define VENDOR_ID_LAB126        0x1949
-// Lenovo's USB Vendor ID
-#define VENDOR_ID_LENOVO        0x17EF
-// LenovoMobile's USB Vendor ID
-#define VENDOR_ID_LENOVOMOBILE  0x2006
-// LG's USB Vendor ID
-#define VENDOR_ID_LGE           0x1004
-// Lumigon's USB Vendor ID
-#define VENDOR_ID_LUMIGON       0x25E3
-// Motorola's USB Vendor ID
-#define VENDOR_ID_MOTOROLA      0x22b8
-// MSI's USB Vendor ID
-#define VENDOR_ID_MSI           0x0DB0
-// MTK's USB Vendor ID
-#define VENDOR_ID_MTK           0x0e8d
-// NEC's USB Vendor ID
-#define VENDOR_ID_NEC           0x0409
-// B&N Nook's USB Vendor ID
-#define VENDOR_ID_NOOK          0x2080
-// Nvidia's USB Vendor ID
-#define VENDOR_ID_NVIDIA        0x0955
-// OPPO's USB Vendor ID
-#define VENDOR_ID_OPPO          0x22D9
-// On-The-Go-Video's USB Vendor ID
-#define VENDOR_ID_OTGV          0x2257
-// OUYA's USB Vendor ID
-#define VENDOR_ID_OUYA          0x2836
-// Pantech's USB Vendor ID
-#define VENDOR_ID_PANTECH       0x10A9
-// Pegatron's USB Vendor ID
-#define VENDOR_ID_PEGATRON      0x1D4D
-// Philips's USB Vendor ID
-#define VENDOR_ID_PHILIPS       0x0471
-// Panasonic Mobile Communication's USB Vendor ID
-#define VENDOR_ID_PMC           0x04DA
-// Positivo's USB Vendor ID
-#define VENDOR_ID_POSITIVO      0x1662
-// Prestigio's USB Vendor ID
-#define VENDOR_ID_PRESTIGIO     0x29e4
-// Qisda's USB Vendor ID
-#define VENDOR_ID_QISDA         0x1D45
-// Qualcomm's USB Vendor ID
-#define VENDOR_ID_QUALCOMM      0x05c6
-// Quanta's USB Vendor ID
-#define VENDOR_ID_QUANTA        0x0408
-// Rockchip's USB Vendor ID
-#define VENDOR_ID_ROCKCHIP      0x2207
-// Samsung's USB Vendor ID
-#define VENDOR_ID_SAMSUNG       0x04e8
-// Sharp's USB Vendor ID
-#define VENDOR_ID_SHARP         0x04dd
-// SK Telesys's USB Vendor ID
-#define VENDOR_ID_SK_TELESYS    0x1F53
-// Smartisan's USB Vendor ID
-#define VENDOR_ID_SMARTISAN     0x29a9
-// Sony's USB Vendor ID
-#define VENDOR_ID_SONY          0x054C
-// Sony Ericsson's USB Vendor ID
-#define VENDOR_ID_SONY_ERICSSON 0x0FCE
-// T & A Mobile Phones' USB Vendor ID
-#define VENDOR_ID_T_AND_A       0x1BBB
-// TechFaith's USB Vendor ID
-#define VENDOR_ID_TECHFAITH     0x1d09
-// Teleepoch's USB Vendor ID
-#define VENDOR_ID_TELEEPOCH     0x2340
-// Texas Instruments's USB Vendor ID
-#define VENDOR_ID_TI            0x0451
-// Toshiba's USB Vendor ID
-#define VENDOR_ID_TOSHIBA       0x0930
-// Unowhy's USB Vendor ID
-#define VENDOR_ID_UNOWHY        0x2A49
-// Vizio's USB Vendor ID
-#define VENDOR_ID_VIZIO         0xE040
-// Wacom's USB Vendor ID
-#define VENDOR_ID_WACOM         0x0531
-// Xiaomi's USB Vendor ID
-#define VENDOR_ID_XIAOMI        0x2717
-// YotaDevices's USB Vendor ID
-#define VENDOR_ID_YOTADEVICES   0x2916
-// Yulong Coolpad's USB Vendor ID
-#define VENDOR_ID_YULONG_COOLPAD 0x1EBF
-// ZTE's USB Vendor ID
-#define VENDOR_ID_ZTE           0x19D2
-/* Keep the list above sorted alphabetically by #define name */
-
-/** built-in vendor list */
-/* Keep the list below sorted alphabetically */
-int builtInVendorIds[] = {
-    VENDOR_ID_ACER,
-    VENDOR_ID_ALLWINNER,
-    VENDOR_ID_AMLOGIC,
-    VENDOR_ID_ANYDATA,
-    VENDOR_ID_ARCHOS,
-    VENDOR_ID_ASUS,
-    VENDOR_ID_BYD,
-    VENDOR_ID_COMPAL,
-    VENDOR_ID_COMPALCOMM,
-    VENDOR_ID_DELL,
-    VENDOR_ID_ECS,
-    VENDOR_ID_EMERGING_TECH,
-    VENDOR_ID_EMERSON,
-    VENDOR_ID_FOXCONN,
-    VENDOR_ID_FUJITSU,
-    VENDOR_ID_FUNAI,
-    VENDOR_ID_GARMIN_ASUS,
-    VENDOR_ID_GIGABYTE,
-    VENDOR_ID_GIGASET,
-    VENDOR_ID_GIONEE,
-    VENDOR_ID_GOOGLE,
-    VENDOR_ID_HAIER,
-    VENDOR_ID_HARRIS,
-    VENDOR_ID_HISENSE,
-    VENDOR_ID_HONEYWELL,
-    VENDOR_ID_HP,
-    VENDOR_ID_HTC,
-    VENDOR_ID_HUAWEI,
-    VENDOR_ID_INQ_MOBILE,
-    VENDOR_ID_INTEL,
-    VENDOR_ID_INTERMEC,
-    VENDOR_ID_IRIVER,
-    VENDOR_ID_KOBO,
-    VENDOR_ID_K_TOUCH,
-    VENDOR_ID_KT_TECH,
-    VENDOR_ID_KYOCERA,
-    VENDOR_ID_LAB126,
-    VENDOR_ID_LENOVO,
-    VENDOR_ID_LENOVOMOBILE,
-    VENDOR_ID_LGE,
-    VENDOR_ID_LUMIGON,
-    VENDOR_ID_MOTOROLA,
-    VENDOR_ID_MSI,
-    VENDOR_ID_MTK,
-    VENDOR_ID_NEC,
-    VENDOR_ID_NOOK,
-    VENDOR_ID_NVIDIA,
-    VENDOR_ID_OPPO,
-    VENDOR_ID_OTGV,
-    VENDOR_ID_OUYA,
-    VENDOR_ID_PANTECH,
-    VENDOR_ID_PEGATRON,
-    VENDOR_ID_PHILIPS,
-    VENDOR_ID_PMC,
-    VENDOR_ID_POSITIVO,
-    VENDOR_ID_PRESTIGIO,
-    VENDOR_ID_QISDA,
-    VENDOR_ID_QUALCOMM,
-    VENDOR_ID_QUANTA,
-    VENDOR_ID_ROCKCHIP,
-    VENDOR_ID_SAMSUNG,
-    VENDOR_ID_SHARP,
-    VENDOR_ID_SK_TELESYS,
-    VENDOR_ID_SMARTISAN,
-    VENDOR_ID_SONY,
-    VENDOR_ID_SONY_ERICSSON,
-    VENDOR_ID_T_AND_A,
-    VENDOR_ID_TECHFAITH,
-    VENDOR_ID_TELEEPOCH,
-    VENDOR_ID_TI,
-    VENDOR_ID_TOSHIBA,
-    VENDOR_ID_UNOWHY,
-    VENDOR_ID_VIZIO,
-    VENDOR_ID_WACOM,
-    VENDOR_ID_XIAOMI,
-    VENDOR_ID_YOTADEVICES,
-    VENDOR_ID_YULONG_COOLPAD,
-    VENDOR_ID_ZTE,
-};
-/* Keep the list above sorted alphabetically */
-
-#define BUILT_IN_VENDOR_COUNT    (sizeof(builtInVendorIds)/sizeof(builtInVendorIds[0]))
-
-/* max number of supported vendor ids (built-in + 3rd party). increase as needed */
-#define VENDOR_COUNT_MAX         128
-
-int vendorIds[VENDOR_COUNT_MAX];
-unsigned vendorIdCount = 0;
-
-int get_adb_usb_ini(char* buff, size_t len);
-
-void usb_vendors_init(void)
-{
-    if (VENDOR_COUNT_MAX < BUILT_IN_VENDOR_COUNT) {
-        fprintf(stderr, "VENDOR_COUNT_MAX not big enough for built-in vendor list.\n");
-        exit(2);
-    }
-
-    /* add the built-in vendors at the beginning of the array */
-    memcpy(vendorIds, builtInVendorIds, sizeof(builtInVendorIds));
-
-    /* default array size is the number of built-in vendors */
-    vendorIdCount = BUILT_IN_VENDOR_COUNT;
-
-    if (VENDOR_COUNT_MAX == BUILT_IN_VENDOR_COUNT)
-        return;
-
-    char temp[PATH_MAX];
-    if (get_adb_usb_ini(temp, sizeof(temp)) == 0) {
-        FILE * f = fopen(temp, "rt");
-
-        if (f != NULL) {
-            /* The vendor id file is pretty basic. 1 vendor id per line.
-               Lines starting with # are comments */
-            while (fgets(temp, sizeof(temp), f) != NULL) {
-                if (temp[0] == '#')
-                    continue;
-
-                long value = strtol(temp, NULL, 0);
-                if (errno == EINVAL || errno == ERANGE || value > INT_MAX || value < 0) {
-                    fprintf(stderr, "Invalid content in %s. Quitting.\n", ANDROID_ADB_INI);
-                    exit(2);
-                }
-
-                vendorIds[vendorIdCount++] = (int)value;
-
-                /* make sure we don't go beyond the array */
-                if (vendorIdCount == VENDOR_COUNT_MAX) {
-                    break;
-                }
-            }
-            fclose(f);
-        }
-    }
-}
-
-/* Utils methods */
-
-/* builds the path to the adb vendor id file. returns 0 if success */
-int build_path(char* buff, size_t len, const char* format, const char* home)
-{
-    if (snprintf(buff, len, format, home, ANDROID_PATH, ANDROID_ADB_INI) >= (signed)len) {
-        return 1;
-    }
-
-    return 0;
-}
-
-/* fills buff with the path to the adb vendor id file. returns 0 if success */
-int get_adb_usb_ini(char* buff, size_t len)
-{
-#ifdef _WIN32
-    const char* home = getenv("ANDROID_SDK_HOME");
-    if (home != NULL) {
-        return build_path(buff, len, "%s\\%s\\%s", home);
-    } else {
-        char path[MAX_PATH];
-        SHGetFolderPath( NULL, CSIDL_PROFILE, NULL, 0, path);
-        return build_path(buff, len, "%s\\%s\\%s", path);
-    }
-#else
-    const char* home = getenv("HOME");
-    if (home == NULL)
-        home = "/tmp";
-
-    return build_path(buff, len, "%s/%s/%s", home);
-#endif
-}
diff --git a/adb/usb_vendors.h b/adb/usb_vendors.h
deleted file mode 100644
index cee23a1..0000000
--- a/adb/usb_vendors.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2009 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 __USB_VENDORS_H
-#define __USB_VENDORS_H
-
-extern int vendorIds[];
-extern unsigned  vendorIdCount;
-
-void usb_vendors_init(void);
-
-#endif
diff --git a/adf/libadf/tests/Android.mk b/adf/libadf/tests/Android.mk
new file mode 100644
index 0000000..93efafa
--- /dev/null
+++ b/adf/libadf/tests/Android.mk
@@ -0,0 +1,22 @@
+#
+# Copyright (C) 2013 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 := $(my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := adf_test.cpp
+LOCAL_MODULE := adf-unit-tests
+LOCAL_STATIC_LIBRARIES := libadf
+include $(BUILD_NATIVE_TEST)
diff --git a/adf/libadf/tests/adf_test.cpp b/adf/libadf/tests/adf_test.cpp
new file mode 100644
index 0000000..d95330d
--- /dev/null
+++ b/adf/libadf/tests/adf_test.cpp
@@ -0,0 +1,342 @@
+/*
+ * Copyright (C) 2013 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 <adf/adf.h>
+#include <gtest/gtest.h>
+#include <sys/mman.h>
+
+class AdfTest : public testing::Test {
+public:
+    AdfTest() : intf_id(0), intf(-1), eng_id(0), eng(-1) { }
+
+    virtual void SetUp() {
+        int err = adf_device_open(dev_id, O_RDWR, &dev);
+        ASSERT_GE(err, 0) << "opening ADF device " << dev_id <<
+                " failed: " << strerror(-err);
+
+        err = adf_find_simple_post_configuration(&dev, fmt8888, n_fmt8888,
+                &intf_id, &eng_id);
+        ASSERT_GE(err, 0) << "finding ADF configuration failed: " <<
+                strerror(-err);
+
+        intf = adf_interface_open(&dev, intf_id, O_RDWR);
+        ASSERT_GE(intf, 0) << "opening ADF interface " << dev_id << "." <<
+                intf_id << " failed: " << strerror(-intf);
+
+        eng = adf_overlay_engine_open(&dev, eng_id, O_RDWR);
+        ASSERT_GE(eng, 0) << "opening ADF overlay engine " << dev_id << "." <<
+                eng_id << " failed: " << strerror(-eng);
+    }
+
+    virtual void TearDown() {
+        if (eng >= 0)
+            close(eng);
+        if (intf >= 0)
+            close(intf);
+        adf_device_close(&dev);
+    }
+
+    void get8888Format(uint32_t &fmt, char fmt_str[ADF_FORMAT_STR_SIZE]) {
+        adf_overlay_engine_data data;
+        int err = adf_get_overlay_engine_data(eng, &data);
+        ASSERT_GE(err, 0) << "getting ADF overlay engine data failed: " <<
+                strerror(-err);
+
+        for (size_t i = 0; i < data.n_supported_formats; i++) {
+            for (size_t j = 0; j < n_fmt8888; j++) {
+                if (data.supported_formats[i] == fmt8888[j]) {
+                    fmt = data.supported_formats[i];
+                    adf_format_str(fmt, fmt_str);
+                    adf_free_overlay_engine_data(&data);
+                    return;
+                }
+            }
+        }
+
+        adf_free_overlay_engine_data(&data);
+        FAIL(); /* this should never happen */
+    }
+
+    void drawCheckerboard(void *buf, uint32_t w, uint32_t h, uint32_t pitch) {
+        uint8_t *buf8 = reinterpret_cast<uint8_t *>(buf);
+        for (uint32_t y = 0; y < h / 2; y++) {
+            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
+            for (uint32_t x = 0; x < w / 2; x++)
+                scanline[x] = 0xFF0000FF;
+            for (uint32_t x = w / 2; x < w; x++)
+                scanline[x] = 0xFF00FFFF;
+        }
+        for (uint32_t y = h / 2; y < h; y++) {
+            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
+            for (uint32_t x = 0; x < w / 2; x++)
+                scanline[x] = 0xFFFF00FF;
+            for (uint32_t x = w / 2; x < w; x++)
+                scanline[x] = 0xFFFFFFFF;
+        }
+    }
+
+    /* various helpers to call ADF and die on failure */
+
+    void getInterfaceData(adf_interface_data &data) {
+         int err = adf_get_interface_data(intf, &data);
+         ASSERT_GE(err, 0) << "getting ADF interface data failed: " <<
+                 strerror(-err);
+    }
+
+    void getCurrentMode(uint32_t &w, uint32_t &h) {
+        adf_interface_data data;
+        ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
+        w = data.current_mode.hdisplay;
+        h = data.current_mode.vdisplay;
+        adf_free_interface_data(&data);
+    }
+
+    void blank(uint8_t mode) {
+        int err = adf_interface_blank(intf, mode);
+        ASSERT_FALSE(err < 0 && err != -EBUSY) <<
+                "unblanking interface failed: " << strerror(-err);
+    }
+
+    void attach() {
+        int err = adf_device_attach(&dev, eng_id, intf_id);
+        ASSERT_FALSE(err < 0 && err != -EALREADY) <<
+                "attaching overlay engine " << eng_id << " to interface " <<
+                intf_id << " failed: " << strerror(-err);
+    }
+
+    void detach() {
+        int err = adf_device_detach(&dev, eng_id, intf_id);
+        ASSERT_FALSE(err < 0 && err != -EINVAL) <<
+                "detaching overlay engine " << eng_id << " from interface " <<
+                intf_id << " failed: " << strerror(-err);
+    }
+
+    void readVsyncTimestamp(uint64_t &timestamp) {
+        adf_event *event;
+        int err = adf_read_event(intf, &event);
+        ASSERT_GE(err, 0) << "reading ADF event failed: " << strerror(-err);
+
+        ASSERT_EQ(ADF_EVENT_VSYNC, event->type);
+        ASSERT_EQ(sizeof(adf_vsync_event), event->length);
+
+        adf_vsync_event *vsync_event =
+                reinterpret_cast<adf_vsync_event *>(event);
+        timestamp = vsync_event->timestamp;
+        free(event);
+    }
+
+protected:
+    adf_device dev;
+    adf_id_t intf_id;
+    int intf;
+    adf_id_t eng_id;
+    int eng;
+
+private:
+    const static adf_id_t dev_id = 0;
+    const static __u32 fmt8888[];
+    const static size_t n_fmt8888;
+};
+
+const __u32 AdfTest::fmt8888[] = {
+   DRM_FORMAT_XRGB8888,
+   DRM_FORMAT_XBGR8888,
+   DRM_FORMAT_RGBX8888,
+   DRM_FORMAT_BGRX8888,
+   DRM_FORMAT_ARGB8888,
+   DRM_FORMAT_ABGR8888,
+   DRM_FORMAT_RGBA8888,
+   DRM_FORMAT_BGRA8888
+};
+const size_t AdfTest::n_fmt8888 = sizeof(fmt8888) / sizeof(fmt8888[0]);
+
+TEST(adf, devices) {
+    adf_id_t *devs;
+    ssize_t n_devs = adf_devices(&devs);
+    free(devs);
+
+    ASSERT_GE(n_devs, 0) << "enumerating ADF devices failed: " <<
+            strerror(-n_devs);
+    ASSERT_TRUE(devs != NULL);
+}
+
+TEST_F(AdfTest, device_data) {
+    adf_device_data data;
+    int err = adf_get_device_data(&dev, &data);
+    ASSERT_GE(err, 0) << "getting ADF device data failed: " << strerror(-err);
+
+    EXPECT_LT(data.n_attachments, ADF_MAX_ATTACHMENTS);
+    EXPECT_GT(data.n_allowed_attachments, 0);
+    EXPECT_LT(data.n_allowed_attachments, ADF_MAX_ATTACHMENTS);
+    EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE);
+    adf_free_device_data(&data);
+}
+
+TEST_F(AdfTest, interface_data) {
+    adf_interface_data data;
+    ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
+
+    EXPECT_LT(data.type, ADF_INTF_TYPE_MAX);
+    EXPECT_LE(data.dpms_state, DRM_MODE_DPMS_OFF);
+    EXPECT_EQ(1, data.hotplug_detect);
+    EXPECT_GT(data.n_available_modes, 0);
+    EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE);
+    adf_free_interface_data(&data);
+}
+
+TEST_F(AdfTest, overlay_engine_data) {
+    adf_overlay_engine_data data;
+    int err = adf_get_overlay_engine_data(eng, &data);
+    ASSERT_GE(err, 0) << "getting ADF overlay engine failed: " <<
+            strerror(-err);
+
+    EXPECT_GT(data.n_supported_formats, 0);
+    EXPECT_LT(data.n_supported_formats, ADF_MAX_SUPPORTED_FORMATS);
+    EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE);
+    adf_free_overlay_engine_data(&data);
+}
+
+TEST_F(AdfTest, blank) {
+    int err = adf_interface_blank(intf, (uint8_t)-1);
+    EXPECT_EQ(-EINVAL, err) << "setting bogus DPMS mode should have failed";
+
+    err = adf_interface_blank(eng, DRM_MODE_DPMS_OFF);
+    EXPECT_EQ(-EINVAL, err) << "blanking overlay engine should have failed";
+
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_OFF));
+    err = adf_interface_blank(intf, DRM_MODE_DPMS_OFF);
+    EXPECT_EQ(-EBUSY, err) << "blanking interface twice should have failed";
+
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
+    err = adf_interface_blank(intf, DRM_MODE_DPMS_ON);
+    EXPECT_EQ(-EBUSY, err) << "unblanking interface twice should have failed";
+
+    adf_interface_data data;
+    ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
+    EXPECT_EQ(DRM_MODE_DPMS_ON, data.dpms_state);
+    adf_free_interface_data(&data);
+}
+
+TEST_F(AdfTest, event) {
+    int err = adf_set_event(intf, ADF_EVENT_TYPE_MAX, true);
+    EXPECT_EQ(-EINVAL, err) << "enabling bogus ADF event should have failed";
+
+    err = adf_set_event(intf, ADF_EVENT_TYPE_MAX, false);
+    EXPECT_EQ(-EINVAL, err) << "disabling bogus ADF event should have failed";
+
+    err = adf_set_event(intf, ADF_EVENT_VSYNC, true);
+    ASSERT_GE(err, 0) << "enabling vsync event failed: " << strerror(-err);
+
+    err = adf_set_event(intf, ADF_EVENT_VSYNC, true);
+    EXPECT_EQ(-EALREADY, err) <<
+            "enabling vsync event twice should have failed";
+
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
+
+    uint64_t timestamp1, timestamp2;
+    ASSERT_NO_FATAL_FAILURE(readVsyncTimestamp(timestamp1));
+    ASSERT_NO_FATAL_FAILURE(readVsyncTimestamp(timestamp2));
+    EXPECT_GT(timestamp2, timestamp1);
+
+    err = adf_set_event(intf, ADF_EVENT_VSYNC, false);
+    EXPECT_GE(err, 0) << "disabling vsync event failed: " << strerror(-err);
+
+    err = adf_set_event(intf, ADF_EVENT_VSYNC, false);
+    EXPECT_EQ(-EALREADY, err) <<
+            "disabling vsync event twice should have failed";
+}
+
+TEST_F(AdfTest, attach) {
+    ASSERT_NO_FATAL_FAILURE(attach());
+    int err = adf_device_attach(&dev, eng_id, intf_id);
+    EXPECT_EQ(-EALREADY, err) << "attaching overlay engine " << eng_id <<
+            " to interface " << intf_id << " twice should have failed";
+
+    ASSERT_NO_FATAL_FAILURE(detach());
+    err = adf_device_detach(&dev, eng_id, intf_id);
+    EXPECT_EQ(-EINVAL, err) << "detaching overlay engine " << eng_id <<
+            " from interface " << intf_id << " twice should have failed";
+
+    err = adf_device_attach(&dev, eng_id, ADF_MAX_INTERFACES);
+    EXPECT_EQ(-EINVAL, err) << "attaching overlay engine " << eng_id <<
+            " to bogus interface should have failed";
+
+    err = adf_device_detach(&dev, eng_id, ADF_MAX_INTERFACES);
+    EXPECT_EQ(-EINVAL, err) << "detaching overlay engine " << eng_id <<
+            " from bogus interface should have failed";
+}
+
+TEST_F(AdfTest, simple_buffer_alloc) {
+    uint32_t w = 0, h = 0;
+    ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h));
+
+    uint32_t format;
+    char format_str[ADF_FORMAT_STR_SIZE];
+    ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str));
+
+    uint32_t offset;
+    uint32_t pitch;
+    int buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset,
+            &pitch);
+    EXPECT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-buf_fd);
+    EXPECT_GE(pitch, w * 4);
+    close(buf_fd);
+
+    buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, 0xDEADBEEF, &offset,
+            &pitch);
+    /* n.b.: ADF only allows simple buffers with built-in RGB formats,
+       so this should fail even if a driver supports custom format 0xDEADBEEF */
+    EXPECT_EQ(-EINVAL, buf_fd) <<
+            "allocating buffer with bogus format should have failed";
+}
+
+TEST_F(AdfTest, simple_buffer) {
+    uint32_t w = 0, h = 0;
+    ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h));
+
+    uint32_t format = 0;
+    char format_str[ADF_FORMAT_STR_SIZE];
+    ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str));
+
+    uint32_t offset;
+    uint32_t pitch;
+    int buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset,
+            &pitch);
+    ASSERT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-buf_fd);
+    EXPECT_GE(pitch, w * 4);
+
+    void *mapped = mmap(NULL, pitch * h, PROT_WRITE, MAP_SHARED, buf_fd,
+            offset);
+    ASSERT_NE(mapped, MAP_FAILED) << "mapping " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-errno);
+    drawCheckerboard(mapped, w, h, pitch);
+    munmap(mapped, pitch * h);
+
+    ASSERT_NO_FATAL_FAILURE(attach());
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
+
+    int release_fence = adf_interface_simple_post(intf, eng_id, w, h, format,
+            buf_fd, offset, pitch, -1);
+    close(buf_fd);
+    ASSERT_GE(release_fence, 0) << "posting " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-release_fence);
+    close(release_fence);
+}
diff --git a/debuggerd/Android.mk b/debuggerd/Android.mk
index c33b263..0cf2818 100644
--- a/debuggerd/Android.mk
+++ b/debuggerd/Android.mk
@@ -28,7 +28,7 @@
     liblog \
     libselinux \
 
-include external/stlport/libstlport.mk
+LOCAL_CLANG := true
 
 LOCAL_MODULE := debuggerd
 LOCAL_MODULE_STEM_32 := debuggerd
diff --git a/debuggerd/crasher.c b/debuggerd/crasher.c
index d315ee5..af86fe9 100644
--- a/debuggerd/crasher.c
+++ b/debuggerd/crasher.c
@@ -32,16 +32,23 @@
     }
 }
 
-static int smash_stack(int i __unused) {
+static char* smash_stack_dummy_buf;
+__attribute__ ((noinline)) static void smash_stack_dummy_function(volatile int* plen) {
+  smash_stack_dummy_buf[*plen] = 0;
+}
+
+// This must be marked with "__attribute__ ((noinline))", to ensure the
+// compiler generates the proper stack guards around this function.
+// Assign local array address to global variable to force stack guards.
+// Use another noinline function to corrupt the stack.
+__attribute__ ((noinline)) static int smash_stack(volatile int* plen) {
     printf("crasher: deliberately corrupting stack...\n");
-    // Unless there's a "big enough" buffer on the stack, gcc
-    // doesn't bother inserting checks.
-    char buf[8];
-    // If we don't write something relatively unpredictable
-    // into the buffer and then do something with it, gcc
-    // optimizes everything away and just returns a constant.
-    *(int*)(&buf[7]) = (uintptr_t) &buf[0];
-    return *(int*)(&buf[0]);
+
+    char buf[128];
+    smash_stack_dummy_buf = buf;
+    // This should corrupt stack guards and make process abort.
+    smash_stack_dummy_function(plen);
+    return 0;
 }
 
 static void* global = 0; // So GCC doesn't optimize the tail recursion out of overflow_stack.
@@ -59,7 +66,7 @@
     for(;;) {
         usleep(250*1000);
         write(2, &c, 1);
-        if(c == 'C') *((unsigned*) 0) = 42;
+        if(c == 'C') *((volatile unsigned*) 0) = 42;
     }
     return NULL;
 }
@@ -125,7 +132,8 @@
     } else if (!strcmp(arg, "SIGSEGV-non-null")) {
         sigsegv_non_null();
     } else if (!strcmp(arg, "smash-stack")) {
-        return smash_stack(42);
+        volatile int len = 128;
+        return smash_stack(&len);
     } else if (!strcmp(arg, "stack-overflow")) {
         overflow_stack(NULL);
     } else if (!strcmp(arg, "nostack")) {
diff --git a/debuggerd/debuggerd.cpp b/debuggerd/debuggerd.cpp
index 06c16f8..318b224 100644
--- a/debuggerd/debuggerd.cpp
+++ b/debuggerd/debuggerd.cpp
@@ -30,6 +30,8 @@
 #include <sys/stat.h>
 #include <sys/poll.h>
 
+#include <selinux/android.h>
+
 #include <log/logger.h>
 
 #include <cutils/sockets.h>
@@ -124,6 +126,53 @@
   return fields == 7 ? 0 : -1;
 }
 
+static int selinux_enabled;
+
+/*
+ * Corresponds with debugger_action_t enum type in
+ * include/cutils/debugger.h.
+ */
+static const char *debuggerd_perms[] = {
+  NULL, /* crash is only used on self, no check applied */
+  "dump_tombstone",
+  "dump_backtrace"
+};
+
+static bool selinux_action_allowed(int s, pid_t tid, debugger_action_t action)
+{
+  char *scon = NULL, *tcon = NULL;
+  const char *tclass = "debuggerd";
+  const char *perm;
+  bool allowed = false;
+
+  if (selinux_enabled <= 0)
+    return true;
+
+  if (action <= 0 || action >= (sizeof(debuggerd_perms)/sizeof(debuggerd_perms[0]))) {
+    ALOGE("SELinux:  No permission defined for debugger action %d", action);
+    return false;
+  }
+
+  perm = debuggerd_perms[action];
+
+  if (getpeercon(s, &scon) < 0) {
+    ALOGE("Cannot get peer context from socket\n");
+    goto out;
+  }
+
+  if (getpidcon(tid, &tcon) < 0) {
+    ALOGE("Cannot get context for tid %d\n", tid);
+    goto out;
+  }
+
+  allowed = (selinux_check_access(scon, tcon, tclass, perm, NULL) == 0);
+
+out:
+   freecon(scon);
+   freecon(tcon);
+   return allowed;
+}
+
 static int read_request(int fd, debugger_request_t* out_request) {
   ucred cr;
   socklen_t len = sizeof(cr);
@@ -186,6 +235,9 @@
       ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid);
       return -1;
     }
+
+    if (!selinux_action_allowed(fd, out_request->tid, out_request->action))
+      return -1;
   } else {
     // No one else is allowed to dump arbitrary processes.
     return -1;
@@ -430,7 +482,11 @@
 }
 
 int main(int argc, char** argv) {
+  union selinux_callback cb;
   if (argc == 1) {
+    selinux_enabled = is_selinux_enabled();
+    cb.func_log = selinux_log_callback;
+    selinux_set_callback(SELINUX_CB_LOG, cb);
     return do_server();
   }
 
diff --git a/debuggerd/tombstone.cpp b/debuggerd/tombstone.cpp
index 0c1b80f..38e9d17 100644
--- a/debuggerd/tombstone.cpp
+++ b/debuggerd/tombstone.cpp
@@ -16,6 +16,7 @@
 
 #define LOG_TAG "DEBUG"
 
+#include <arpa/inet.h>
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
diff --git a/debuggerd/utility.cpp b/debuggerd/utility.cpp
index 2baf9de..e10feff 100644
--- a/debuggerd/utility.cpp
+++ b/debuggerd/utility.cpp
@@ -131,12 +131,6 @@
   return -1;
 }
 
-#if defined (__mips__)
-#define DUMP_MEMORY_AS_ASCII 1
-#else
-#define DUMP_MEMORY_AS_ASCII 0
-#endif
-
 void dump_memory(log_t* log, pid_t tid, uintptr_t addr) {
     char code_buffer[64];
     char ascii_buffer[32];
@@ -183,7 +177,6 @@
                                static_cast<uintptr_t>(data));
             }
 
-#if DUMP_MEMORY_AS_ASCII
             for (size_t j = 0; j < sizeof(long); j++) {
                 /*
                  * Our isprint() allows high-ASCII characters that display
@@ -197,7 +190,6 @@
                     *asc_out++ = '.';
                 }
             }
-#endif
             p += sizeof(long);
         }
         *asc_out = '\0';
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index e11691f..aa5b14a 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -32,6 +32,7 @@
   LOCAL_SRC_FILES += usb_osx.c util_osx.c
   LOCAL_LDLIBS += -lpthread -framework CoreFoundation -framework IOKit \
 	-framework Carbon
+  LOCAL_CFLAGS += -Wno-unused-parameter
 endif
 
 ifeq ($(HOST_OS),windows)
@@ -52,7 +53,6 @@
 LOCAL_STATIC_LIBRARIES := \
     $(EXTRA_STATIC_LIBS) \
     libzipfile \
-    libunz \
     libext4_utils_host \
     libsparse_host \
     libz
diff --git a/fastboot/fastboot.c b/fastboot/fastboot.c
index 43d05aa..959d3ad 100644
--- a/fastboot/fastboot.c
+++ b/fastboot/fastboot.c
@@ -244,7 +244,7 @@
         // output compatible with "adb devices"
         if (!long_listing) {
             printf("%s\tfastboot\n", serial);
-        } else if (!info->device_path) {
+        } else if (strcmp("", info->device_path) == 0) {
             printf("%-22s fastboot\n", serial);
         } else {
             printf("%-22s fastboot %s\n", serial, info->device_path);
@@ -988,6 +988,7 @@
     unsigned sz;
     int status;
     int c;
+    int longindex;
 
     const struct option longopts[] = {
         {"base", required_argument, 0, 'b'},
@@ -996,13 +997,14 @@
         {"ramdisk_offset", required_argument, 0, 'r'},
         {"tags_offset", required_argument, 0, 't'},
         {"help", 0, 0, 'h'},
+        {"unbuffered", 0, 0, 0},
         {0, 0, 0, 0}
     };
 
     serial = getenv("ANDROID_SERIAL");
 
     while (1) {
-        c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, NULL);
+        c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, &longindex);
         if (c < 0) {
             break;
         }
@@ -1063,6 +1065,12 @@
             break;
         case '?':
             return 1;
+        case 0:
+            if (strcmp("unbuffered", longopts[longindex].name) == 0) {
+                setvbuf(stdout, NULL, _IONBF, 0);
+                setvbuf(stderr, NULL, _IONBF, 0);
+            }
+            break;
         default:
             abort();
         }
diff --git a/fastboot/fastboot_protocol.txt b/fastboot/fastboot_protocol.txt
index 2248992..37b1959 100644
--- a/fastboot/fastboot_protocol.txt
+++ b/fastboot/fastboot_protocol.txt
@@ -12,8 +12,8 @@
 ------------------
 
 * Two bulk endpoints (in, out) are required
-* Max packet size must be 64 bytes for full-speed and 512 bytes for 
-  high-speed USB
+* Max packet size must be 64 bytes for full-speed, 512 bytes for
+  high-speed and 1024 bytes for Super Speed USB.
 * The protocol is entirely host-driven and synchronous (unlike the
   multi-channel, bi-directional, asynchronous ADB protocol)
 
diff --git a/fastboot/protocol.c b/fastboot/protocol.c
index 84e9837..10a84c1 100644
--- a/fastboot/protocol.c
+++ b/fastboot/protocol.c
@@ -216,7 +216,7 @@
     }
 }
 
-#define USB_BUF_SIZE 512
+#define USB_BUF_SIZE 1024
 static char usb_buf[USB_BUF_SIZE];
 static int usb_buf_len;
 
diff --git a/fastboot/usb_linux.c b/fastboot/usb_linux.c
index fabbd51..022f364 100644
--- a/fastboot/usb_linux.c
+++ b/fastboot/usb_linux.c
@@ -223,6 +223,13 @@
             } else {
                 out = ept->bEndpointAddress;
             }
+
+            // For USB 3.0 devices skip the SS Endpoint Companion descriptor
+            if (check((struct usb_descriptor_hdr *)ptr, len,
+                      USB_DT_SS_ENDPOINT_COMP, USB_DT_SS_EP_COMP_SIZE) == 0) {
+                len -= USB_DT_SS_EP_COMP_SIZE;
+                ptr += USB_DT_SS_EP_COMP_SIZE;
+            }
         }
 
         info.has_bulk_in = (in != -1);
diff --git a/fastboot/usb_osx.c b/fastboot/usb_osx.c
index 0f55e0d..0b6c515 100644
--- a/fastboot/usb_osx.c
+++ b/fastboot/usb_osx.c
@@ -328,7 +328,8 @@
         ERR("GetLocationId");
         goto error;
     }
-    snprintf(handle->info.device_path, sizeof(handle->info.device_path), "usb:%lX", locationId);
+    snprintf(handle->info.device_path, sizeof(handle->info.device_path),
+             "usb:%" PRIu32 "X", (unsigned int)locationId);
 
     kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
 
diff --git a/fastboot/util_osx.c b/fastboot/util_osx.c
index 26b832a..e718562 100644
--- a/fastboot/util_osx.c
+++ b/fastboot/util_osx.c
@@ -31,14 +31,15 @@
 
 void get_my_path(char s[PATH_MAX])
 {
-    char *x;
-    ProcessSerialNumber psn;
-    GetCurrentProcess(&psn);
-    CFDictionaryRef dict;
-    dict = ProcessInformationCopyDictionary(&psn, 0xffffffff);
-    CFStringRef value = (CFStringRef)CFDictionaryGetValue(dict,
-                CFSTR("CFBundleExecutable"));
-    CFStringGetCString(value, s, PATH_MAX - 1, kCFStringEncodingUTF8);
+    CFBundleRef mainBundle = CFBundleGetMainBundle();
+    CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle);
+    CFStringRef executablePathString = CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle);
+    CFRelease(executableURL);
+
+    CFStringGetFileSystemRepresentation(executablePathString, s, PATH_MAX-1);
+    CFRelease(executablePathString);
+
+	char *x;
     x = strrchr(s, '/');
     if(x) x[1] = 0;
 }
diff --git a/fastbootd/Android.mk b/fastbootd/Android.mk
index 6aa7400..1e69e7a 100644
--- a/fastbootd/Android.mk
+++ b/fastbootd/Android.mk
@@ -16,12 +16,6 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_C_INCLUDES := \
-    external/openssl/include \
-    external/mdnsresponder/mDNSShared \
-    $(LOCAL_PATH)/include \
-    external/zlib/ \
-
 LOCAL_SRC_FILES := \
     config.c \
     commands.c \
@@ -42,7 +36,7 @@
 
 LOCAL_MODULE := fastbootd
 LOCAL_MODULE_TAGS := optional
-LOCAL_CFLAGS := -Wall -Werror -Wno-unused-parameter -DFLASH_CERT
+LOCAL_CFLAGS := -Wall -Werror -Wno-unused-parameter -Wno-deprecated-declarations -DFLASH_CERT
 LOCAL_LDFLAGS := -ldl
 
 LOCAL_STATIC_LIBRARIES := \
@@ -60,8 +54,6 @@
 include $(BUILD_EXECUTABLE)
 
 include $(CLEAR_VARS)
-LOCAL_C_INCLUDES := \
-    external/zlib/
 
 LOCAL_SRC_FILES := \
     commands/partitions.c \
diff --git a/fastbootd/commands.c b/fastbootd/commands.c
index 98b7866..9be96dc 100644
--- a/fastbootd/commands.c
+++ b/fastbootd/commands.c
@@ -173,7 +173,7 @@
         return;
     }
 
-    if (path == NULL) {
+    if (!path[0]) {
         fastboot_fail(phandle, "Couldn't find partition");
         return;
     }
diff --git a/fastbootd/commands/partitions.c b/fastbootd/commands/partitions.c
index 74232e6..3b27959 100644
--- a/fastbootd/commands/partitions.c
+++ b/fastbootd/commands/partitions.c
@@ -31,6 +31,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <errno.h>
 #include <fcntl.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
@@ -547,7 +548,8 @@
 int GPT_parse_entry(char *string, struct GPT_entry_raw *entry)
 {
     char *ptr = string;
-    char *key, *value;
+    char *key = NULL;
+    char *value = NULL;
 
     while ((ptr = get_key_value(ptr, &key, &value)) != NULL) {
         if (add_key_value(key, value, entry)) {
diff --git a/fastbootd/commands/virtual_partitions.c b/fastbootd/commands/virtual_partitions.c
index 813f485..9da4020 100644
--- a/fastbootd/commands/virtual_partitions.c
+++ b/fastbootd/commands/virtual_partitions.c
@@ -30,6 +30,9 @@
  */
 
 #include "commands/virtual_partitions.h"
+
+#include <string.h>
+
 #include "debug.h"
 
 static struct virtual_partition *partitions = NULL;
diff --git a/fastbootd/config.c b/fastbootd/config.c
index fe6da69..012a197 100644
--- a/fastbootd/config.c
+++ b/fastbootd/config.c
@@ -29,6 +29,7 @@
  * SUCH DAMAGE.
  */
 
+#include <errno.h>
 #include <fcntl.h>
 #include <string.h>
 #include <unistd.h>
diff --git a/fastbootd/transport.c b/fastbootd/transport.c
index 9a16fd7..232c999 100644
--- a/fastbootd/transport.c
+++ b/fastbootd/transport.c
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <errno.h>
 #include <pthread.h>
 #include <stddef.h>
 #include <stdio.h>
diff --git a/fastbootd/usb_linux_client.c b/fastbootd/usb_linux_client.c
index 64420e9..beaafc3 100644
--- a/fastbootd/usb_linux_client.c
+++ b/fastbootd/usb_linux_client.c
@@ -15,6 +15,7 @@
  */
 
 #include <endian.h>
+#include <errno.h>
 #include <fcntl.h>
 #include <pthread.h>
 #include <stdio.h>
@@ -69,71 +70,85 @@
     struct transport_handle handle;
 };
 
-static const struct {
-    struct usb_functionfs_descs_head header;
-    struct {
-        struct usb_interface_descriptor intf;
-        struct usb_endpoint_descriptor_no_audio source;
-        struct usb_endpoint_descriptor_no_audio sink;
-    } __attribute__((packed)) fs_descs, hs_descs;
-} __attribute__((packed)) descriptors = {
-    .header = {
-        .magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC),
-        .length = cpu_to_le32(sizeof(descriptors)),
-        .fs_count = 3,
-        .hs_count = 3,
+struct func_desc {
+    struct usb_interface_descriptor intf;
+    struct usb_endpoint_descriptor_no_audio source;
+    struct usb_endpoint_descriptor_no_audio sink;
+} __attribute__((packed));
+
+struct desc_v1 {
+    struct usb_functionfs_descs_head_v1 {
+        __le32 magic;
+        __le32 length;
+        __le32 fs_count;
+        __le32 hs_count;
+    } __attribute__((packed)) header;
+    struct func_desc fs_descs, hs_descs;
+} __attribute__((packed));
+
+struct desc_v2 {
+    struct usb_functionfs_descs_head_v2 {
+        __le32 magic;
+        __le32 length;
+        __le32 flags;
+        __le32 fs_count;
+        __le32 hs_count;
+        __le32 ss_count;
+    } __attribute__((packed)) header;
+    struct func_desc fs_descs, hs_descs;
+} __attribute__((packed));
+
+struct func_desc fs_descriptors = {
+    .intf = {
+        .bLength = sizeof(fs_descriptors.intf),
+        .bDescriptorType = USB_DT_INTERFACE,
+        .bInterfaceNumber = 0,
+        .bNumEndpoints = 2,
+        .bInterfaceClass = FASTBOOT_CLASS,
+        .bInterfaceSubClass = FASTBOOT_SUBCLASS,
+        .bInterfaceProtocol = FASTBOOT_PROTOCOL,
+        .iInterface = 1, /* first string from the provided table */
     },
-    .fs_descs = {
-        .intf = {
-            .bLength = sizeof(descriptors.fs_descs.intf),
-            .bDescriptorType = USB_DT_INTERFACE,
-            .bInterfaceNumber = 0,
-            .bNumEndpoints = 2,
-            .bInterfaceClass = FASTBOOT_CLASS,
-            .bInterfaceSubClass = FASTBOOT_SUBCLASS,
-            .bInterfaceProtocol = FASTBOOT_PROTOCOL,
-            .iInterface = 1, /* first string from the provided table */
-        },
-        .source = {
-            .bLength = sizeof(descriptors.fs_descs.source),
-            .bDescriptorType = USB_DT_ENDPOINT,
-            .bEndpointAddress = 1 | USB_DIR_OUT,
-            .bmAttributes = USB_ENDPOINT_XFER_BULK,
-            .wMaxPacketSize = MAX_PACKET_SIZE_FS,
-        },
-        .sink = {
-            .bLength = sizeof(descriptors.fs_descs.sink),
-            .bDescriptorType = USB_DT_ENDPOINT,
-            .bEndpointAddress = 2 | USB_DIR_IN,
-            .bmAttributes = USB_ENDPOINT_XFER_BULK,
-            .wMaxPacketSize = MAX_PACKET_SIZE_FS,
-        },
+    .source = {
+        .bLength = sizeof(fs_descriptors.source),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 1 | USB_DIR_OUT,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_FS,
     },
-    .hs_descs = {
-        .intf = {
-            .bLength = sizeof(descriptors.hs_descs.intf),
-            .bDescriptorType = USB_DT_INTERFACE,
-            .bInterfaceNumber = 0,
-            .bNumEndpoints = 2,
-            .bInterfaceClass = FASTBOOT_CLASS,
-            .bInterfaceSubClass = FASTBOOT_SUBCLASS,
-            .bInterfaceProtocol = FASTBOOT_PROTOCOL,
-            .iInterface = 1, /* first string from the provided table */
-        },
-        .source = {
-            .bLength = sizeof(descriptors.hs_descs.source),
-            .bDescriptorType = USB_DT_ENDPOINT,
-            .bEndpointAddress = 1 | USB_DIR_OUT,
-            .bmAttributes = USB_ENDPOINT_XFER_BULK,
-            .wMaxPacketSize = MAX_PACKET_SIZE_HS,
-        },
-        .sink = {
-            .bLength = sizeof(descriptors.hs_descs.sink),
-            .bDescriptorType = USB_DT_ENDPOINT,
-            .bEndpointAddress = 2 | USB_DIR_IN,
-            .bmAttributes = USB_ENDPOINT_XFER_BULK,
-            .wMaxPacketSize = MAX_PACKET_SIZE_HS,
-        },
+    .sink = {
+        .bLength = sizeof(fs_descriptors.sink),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 2 | USB_DIR_IN,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_FS,
+    },
+};
+
+struct func_desc hs_descriptors = {
+    .intf = {
+        .bLength = sizeof(hs_descriptors.intf),
+        .bDescriptorType = USB_DT_INTERFACE,
+        .bInterfaceNumber = 0,
+        .bNumEndpoints = 2,
+        .bInterfaceClass = FASTBOOT_CLASS,
+        .bInterfaceSubClass = FASTBOOT_SUBCLASS,
+        .bInterfaceProtocol = FASTBOOT_PROTOCOL,
+        .iInterface = 1, /* first string from the provided table */
+    },
+    .source = {
+        .bLength = sizeof(hs_descriptors.source),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 1 | USB_DIR_OUT,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_HS,
+    },
+    .sink = {
+        .bLength = sizeof(hs_descriptors.sink),
+        .bDescriptorType = USB_DT_ENDPOINT,
+        .bEndpointAddress = 2 | USB_DIR_IN,
+        .bmAttributes = USB_ENDPOINT_XFER_BULK,
+        .wMaxPacketSize = MAX_PACKET_SIZE_HS,
     },
 };
 
@@ -161,6 +176,17 @@
 static int init_functionfs(struct usb_transport *usb_transport)
 {
     ssize_t ret;
+    struct desc_v1 v1_descriptor;
+    struct desc_v2 v2_descriptor;
+
+    v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2);
+    v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor));
+    v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
+    v2_descriptor.header.fs_count = 3;
+    v2_descriptor.header.hs_count = 3;
+    v2_descriptor.header.ss_count = 0;
+    v2_descriptor.fs_descs = fs_descriptors;
+    v2_descriptor.hs_descs = hs_descriptors;
 
     D(VERBOSE, "OPENING %s", USB_FFS_FASTBOOT_EP0);
     usb_transport->control = open(USB_FFS_FASTBOOT_EP0, O_RDWR);
@@ -169,10 +195,20 @@
         goto err;
     }
 
-    ret = write(usb_transport->control, &descriptors, sizeof(descriptors));
+    ret = write(usb_transport->control, &v2_descriptor, sizeof(v2_descriptor));
     if (ret < 0) {
-        D(ERR, "[ %s: write descriptors failed: errno=%d ]", USB_FFS_FASTBOOT_EP0, errno);
-        goto err;
+        v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC);
+        v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor));
+        v1_descriptor.header.fs_count = 3;
+        v1_descriptor.header.hs_count = 3;
+        v1_descriptor.fs_descs = fs_descriptors;
+        v1_descriptor.hs_descs = hs_descriptors;
+        D(ERR, "[ %s: Switching to V1_descriptor format errno=%d ]\n", USB_FFS_FASTBOOT_EP0, errno);
+        ret = write(usb_transport->control, &v1_descriptor, sizeof(v1_descriptor));
+        if (ret < 0) {
+            D(ERR, "[ %s: write descriptors failed: errno=%d ]", USB_FFS_FASTBOOT_EP0, errno);
+            goto err;
+        }
     }
 
     ret = write(usb_transport->control, &strings, sizeof(strings));
diff --git a/fastbootd/utils.c b/fastbootd/utils.c
index bef2463..a9ab47e 100644
--- a/fastbootd/utils.c
+++ b/fastbootd/utils.c
@@ -28,6 +28,7 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
+#include <errno.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
diff --git a/fastbootd/utils.h b/fastbootd/utils.h
index 3d98699..2f89582 100644
--- a/fastbootd/utils.h
+++ b/fastbootd/utils.h
@@ -29,7 +29,7 @@
  * SUCH DAMAGE.
  */
 
-#ifndef _FASTBOOT_UTLIS_H
+#ifndef _FASTBOOT_UTILS_H
 #define _FASTBOOT_UTILS_H
 
 #include <stdio.h>
diff --git a/fastbootd/vendor_trigger_default.c b/fastbootd/vendor_trigger_default.c
index 3627024..0bcc99b 100644
--- a/fastbootd/vendor_trigger_default.c
+++ b/fastbootd/vendor_trigger_default.c
@@ -52,7 +52,7 @@
     return 0;
 }
 
-int trigger_oem_cmd(const char *arg, const char **response) {
+int trigger_oem_cmd(const char *arg, const char **response __unused) {
     KLOG_DEBUG("fastbootd", "%s: %s", __func__, arg);
     return 0;
 }
diff --git a/fs_mgr/fs_mgr_verity.c b/fs_mgr/fs_mgr_verity.c
index a82db4e..f02781c 100644
--- a/fs_mgr/fs_mgr_verity.c
+++ b/fs_mgr/fs_mgr_verity.c
@@ -120,7 +120,9 @@
 {
     int data_device;
     struct ext4_super_block sb;
-    struct fs_info info = {0};
+    struct fs_info info;
+
+    info.len = 0;  /* Only len is set to 0 to ask the device for real size. */
 
     data_device = TEMP_FAILURE_RETRY(open(blk_device, O_RDONLY | O_CLOEXEC));
     if (data_device == -1) {
@@ -376,7 +378,7 @@
 
 int fs_mgr_setup_verity(struct fstab_rec *fstab) {
 
-    int retval = FS_MGR_SETUP_VERITY_FAIL;
+    int retval = -1;
     int fd = -1;
 
     char *verity_blk_name = 0;
@@ -407,8 +409,6 @@
         goto out;
     }
 
-    retval = FS_MGR_SETUP_VERITY_FAIL;
-
     // get the device mapper fd
     if ((fd = open("/dev/device-mapper", O_RDWR)) < 0) {
         ERROR("Error opening device mapper (%s)", strerror(errno));
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index 9388ed0..7ea8250 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -389,7 +389,6 @@
             if (!strcmp(name, ".") || !strcmp(name, ".."))
                 continue;
 
-            char buf[20];
             // Look for "type" file in each subdirectory
             path.clear();
             path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH, name);
diff --git a/healthd/BatteryPropertiesRegistrar.cpp b/healthd/BatteryPropertiesRegistrar.cpp
index 74bcbfd..09667a1 100644
--- a/healthd/BatteryPropertiesRegistrar.cpp
+++ b/healthd/BatteryPropertiesRegistrar.cpp
@@ -48,13 +48,13 @@
         Mutex::Autolock _l(mRegistrationLock);
         // check whether this is a duplicate
         for (size_t i = 0; i < mListeners.size(); i++) {
-            if (mListeners[i]->asBinder() == listener->asBinder()) {
+            if (IInterface::asBinder(mListeners[i]) == IInterface::asBinder(listener)) {
                 return;
             }
         }
 
         mListeners.add(listener);
-        listener->asBinder()->linkToDeath(this);
+        IInterface::asBinder(listener)->linkToDeath(this);
     }
     healthd_battery_update();
 }
@@ -64,8 +64,8 @@
         return;
     Mutex::Autolock _l(mRegistrationLock);
     for (size_t i = 0; i < mListeners.size(); i++) {
-        if (mListeners[i]->asBinder() == listener->asBinder()) {
-            mListeners[i]->asBinder()->unlinkToDeath(this);
+        if (IInterface::asBinder(mListeners[i]) == IInterface::asBinder(listener)) {
+            IInterface::asBinder(mListeners[i])->unlinkToDeath(this);
             mListeners.removeAt(i);
             break;
         }
@@ -93,7 +93,7 @@
     Mutex::Autolock _l(mRegistrationLock);
 
     for (size_t i = 0; i < mListeners.size(); i++) {
-        if (mListeners[i]->asBinder() == who) {
+        if (IInterface::asBinder(mListeners[i]) == who) {
             mListeners.removeAt(i);
             break;
         }
diff --git a/healthd/healthd.cpp b/healthd/healthd.cpp
index f4171bd..1fee855 100644
--- a/healthd/healthd.cpp
+++ b/healthd/healthd.cpp
@@ -65,7 +65,6 @@
 #define MAX_EPOLL_EVENTS 40
 static int uevent_fd;
 static int wakealarm_fd;
-static int binder_fd;
 
 // -1 for no epoll timeout
 static int awake_poll_interval = -1;
diff --git a/healthd/healthd_mode_charger.cpp b/healthd/healthd_mode_charger.cpp
index 5039649..9ed5944 100644
--- a/healthd/healthd_mode_charger.cpp
+++ b/healthd/healthd_mode_charger.cpp
@@ -344,7 +344,6 @@
 static void update_screen_state(struct charger *charger, int64_t now)
 {
     struct animation *batt_anim = charger->batt_anim;
-    int cur_frame;
     int disp_time;
 
     if (!batt_anim->run || now < charger->next_screen_transition)
@@ -387,7 +386,6 @@
 
     /* animation starting, set up the animation */
     if (batt_anim->cur_frame == 0) {
-        int ret;
 
         LOGV("[%" PRId64 "] animation starting\n", now);
         if (batt_prop && batt_prop->batteryLevel >= 0 && batt_anim->num_frames != 0) {
@@ -510,7 +508,6 @@
 static void process_key(struct charger *charger, int code, int64_t now)
 {
     struct key_state *key = &charger->keys[code];
-    int64_t next_key_check;
 
     if (code == KEY_POWER) {
         if (key->down) {
@@ -583,7 +580,6 @@
 {
     struct charger *charger = &charger_state;
     int64_t now = curr_time_ms();
-    int ret;
 
     handle_input_state(charger, now);
     handle_power_supply_state(charger, now);
@@ -618,8 +614,6 @@
     int64_t now = curr_time_ms();
     int64_t next_event = INT64_MAX;
     int64_t timeout;
-    struct input_event ev;
-    int ret;
 
     LOGV("[%" PRId64 "] next screen: %" PRId64 " next key: %" PRId64 " next pwr: %" PRId64 "\n", now,
          charger->next_screen_transition, charger->next_key_check,
diff --git a/include/cutils/aref.h b/include/cutils/aref.h
index 460ac02..3bd36ea 100644
--- a/include/cutils/aref.h
+++ b/include/cutils/aref.h
@@ -20,11 +20,7 @@
 #include <stddef.h>
 #include <sys/cdefs.h>
 
-#ifdef ANDROID_SMP
-#include <cutils/atomic-inline.h>
-#else
 #include <cutils/atomic.h>
-#endif
 
 __BEGIN_DECLS
 
diff --git a/include/cutils/atomic-arm.h b/include/cutils/atomic-arm.h
deleted file mode 100644
index 6b031b6..0000000
--- a/include/cutils/atomic-arm.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (C) 2010 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 ANDROID_CUTILS_ATOMIC_ARM_H
-#define ANDROID_CUTILS_ATOMIC_ARM_H
-
-#include <stdint.h>
-
-#ifndef ANDROID_ATOMIC_INLINE
-#define ANDROID_ATOMIC_INLINE inline __attribute__((always_inline))
-#endif
-
-extern ANDROID_ATOMIC_INLINE void android_compiler_barrier()
-{
-    __asm__ __volatile__ ("" : : : "memory");
-}
-
-extern ANDROID_ATOMIC_INLINE void android_memory_barrier()
-{
-#if ANDROID_SMP == 0
-    android_compiler_barrier();
-#else
-    __asm__ __volatile__ ("dmb" : : : "memory");
-#endif
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_acquire_load(volatile const int32_t *ptr)
-{
-    int32_t value = *ptr;
-    android_memory_barrier();
-    return value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_release_load(volatile const int32_t *ptr)
-{
-    android_memory_barrier();
-    return *ptr;
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_atomic_acquire_store(int32_t value, volatile int32_t *ptr)
-{
-    *ptr = value;
-    android_memory_barrier();
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_atomic_release_store(int32_t value, volatile int32_t *ptr)
-{
-    android_memory_barrier();
-    *ptr = value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_cas(int32_t old_value, int32_t new_value,
-                       volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    do {
-        __asm__ __volatile__ ("ldrex %0, [%3]\n"
-                              "mov %1, #0\n"
-                              "teq %0, %4\n"
-#ifdef __thumb2__
-                              "it eq\n"
-#endif
-                              "strexeq %1, %5, [%3]"
-                              : "=&r" (prev), "=&r" (status), "+m"(*ptr)
-                              : "r" (ptr), "Ir" (old_value), "r" (new_value)
-                              : "cc");
-    } while (__builtin_expect(status != 0, 0));
-    return prev != old_value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_acquire_cas(int32_t old_value, int32_t new_value,
-                               volatile int32_t *ptr)
-{
-    int status = android_atomic_cas(old_value, new_value, ptr);
-    android_memory_barrier();
-    return status;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_release_cas(int32_t old_value, int32_t new_value,
-                               volatile int32_t *ptr)
-{
-    android_memory_barrier();
-    return android_atomic_cas(old_value, new_value, ptr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_add(int32_t increment, volatile int32_t *ptr)
-{
-    int32_t prev, tmp, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ ("ldrex %0, [%4]\n"
-                              "add %1, %0, %5\n"
-                              "strex %2, %1, [%4]"
-                              : "=&r" (prev), "=&r" (tmp),
-                                "=&r" (status), "+m" (*ptr)
-                              : "r" (ptr), "Ir" (increment)
-                              : "cc");
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t android_atomic_inc(volatile int32_t *addr)
-{
-    return android_atomic_add(1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t android_atomic_dec(volatile int32_t *addr)
-{
-    return android_atomic_add(-1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_and(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, tmp, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ ("ldrex %0, [%4]\n"
-                              "and %1, %0, %5\n"
-                              "strex %2, %1, [%4]"
-                              : "=&r" (prev), "=&r" (tmp),
-                                "=&r" (status), "+m" (*ptr)
-                              : "r" (ptr), "Ir" (value)
-                              : "cc");
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_or(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, tmp, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ ("ldrex %0, [%4]\n"
-                              "orr %1, %0, %5\n"
-                              "strex %2, %1, [%4]"
-                              : "=&r" (prev), "=&r" (tmp),
-                                "=&r" (status), "+m" (*ptr)
-                              : "r" (ptr), "Ir" (value)
-                              : "cc");
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-#endif /* ANDROID_CUTILS_ATOMIC_ARM_H */
diff --git a/include/cutils/atomic-arm64.h b/include/cutils/atomic-arm64.h
deleted file mode 100644
index 7ae47d7..0000000
--- a/include/cutils/atomic-arm64.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    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
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * 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
- * 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
- * SUCH DAMAGE.
- */
-
-#ifndef ANDROID_CUTILS_ATOMIC_AARCH64_H
-#define ANDROID_CUTILS_ATOMIC_AARCH64_H
-
-#include <stdint.h>
-
-#ifndef ANDROID_ATOMIC_INLINE
-#define ANDROID_ATOMIC_INLINE inline __attribute__((always_inline))
-#endif
-
-/*
-   TODOAArch64: Revisit the below functions and check for potential
-   optimizations using assembly code or otherwise.
-*/
-
-extern ANDROID_ATOMIC_INLINE
-void android_compiler_barrier(void)
-{
-    __asm__ __volatile__ ("" : : : "memory");
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_memory_barrier(void)
-{
-    __asm__ __volatile__ ("dmb ish" : : : "memory");
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_acquire_load(volatile const int32_t *ptr)
-{
-    int32_t value = *ptr;
-    android_memory_barrier();
-    return value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_release_load(volatile const int32_t *ptr)
-{
-    android_memory_barrier();
-    return *ptr;
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_atomic_acquire_store(int32_t value, volatile int32_t *ptr)
-{
-    *ptr = value;
-    android_memory_barrier();
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_atomic_release_store(int32_t value, volatile int32_t *ptr)
-{
-    android_memory_barrier();
-    *ptr = value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_cas(int32_t old_value, int32_t new_value,
-                       volatile int32_t *ptr)
-{
-    return __sync_val_compare_and_swap(ptr, old_value, new_value) != old_value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_acquire_cas(int32_t old_value, int32_t new_value,
-                               volatile int32_t *ptr)
-{
-    int status = android_atomic_cas(old_value, new_value, ptr);
-    android_memory_barrier();
-    return status;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_release_cas(int32_t old_value, int32_t new_value,
-                               volatile int32_t *ptr)
-{
-    android_memory_barrier();
-    return android_atomic_cas(old_value, new_value, ptr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_add(int32_t increment, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        prev = *ptr;
-        status = android_atomic_cas(prev, prev + increment, ptr);
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_inc(volatile int32_t *addr)
-{
-    return android_atomic_add(1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_dec(volatile int32_t *addr)
-{
-    return android_atomic_add(-1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_and(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        prev = *ptr;
-        status = android_atomic_cas(prev, prev & value, ptr);
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_or(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        prev = *ptr;
-        status = android_atomic_cas(prev, prev | value, ptr);
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-#endif /* ANDROID_CUTILS_ATOMIC_AARCH64_H */
diff --git a/include/cutils/atomic-inline.h b/include/cutils/atomic-inline.h
deleted file mode 100644
index a31e913..0000000
--- a/include/cutils/atomic-inline.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2010 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 ANDROID_CUTILS_ATOMIC_INLINE_H
-#define ANDROID_CUTILS_ATOMIC_INLINE_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Inline declarations and macros for some special-purpose atomic
- * operations.  These are intended for rare circumstances where a
- * memory barrier needs to be issued inline rather than as a function
- * call.
- *
- * Most code should not use these.
- *
- * Anything that does include this file must set ANDROID_SMP to either
- * 0 or 1, indicating compilation for UP or SMP, respectively.
- *
- * Macros defined in this header:
- *
- * void ANDROID_MEMBAR_FULL(void)
- *   Full memory barrier.  Provides a compiler reordering barrier, and
- *   on SMP systems emits an appropriate instruction.
- */
-
-#if !defined(ANDROID_SMP)
-# error "Must define ANDROID_SMP before including atomic-inline.h"
-#endif
-
-#if defined(__aarch64__)
-#include <cutils/atomic-arm64.h>
-#elif defined(__arm__)
-#include <cutils/atomic-arm.h>
-#elif defined(__i386__)
-#include <cutils/atomic-x86.h>
-#elif defined(__x86_64__)
-#include <cutils/atomic-x86_64.h>
-#elif defined(__mips64)
-#include <cutils/atomic-mips64.h>
-#elif defined(__mips__)
-#include <cutils/atomic-mips.h>
-#else
-#error atomic operations are unsupported
-#endif
-
-#if ANDROID_SMP == 0
-#define ANDROID_MEMBAR_FULL android_compiler_barrier
-#else
-#define ANDROID_MEMBAR_FULL android_memory_barrier
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* ANDROID_CUTILS_ATOMIC_INLINE_H */
diff --git a/include/cutils/atomic-mips.h b/include/cutils/atomic-mips.h
deleted file mode 100644
index 5d4f097..0000000
--- a/include/cutils/atomic-mips.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2010 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 ANDROID_CUTILS_ATOMIC_MIPS_H
-#define ANDROID_CUTILS_ATOMIC_MIPS_H
-
-#include <stdint.h>
-
-#ifndef ANDROID_ATOMIC_INLINE
-#define ANDROID_ATOMIC_INLINE inline __attribute__((always_inline))
-#endif
-
-extern ANDROID_ATOMIC_INLINE void android_compiler_barrier(void)
-{
-    __asm__ __volatile__ ("" : : : "memory");
-}
-
-#if ANDROID_SMP == 0
-extern ANDROID_ATOMIC_INLINE void android_memory_barrier(void)
-{
-    android_compiler_barrier();
-}
-#else
-extern ANDROID_ATOMIC_INLINE void android_memory_barrier(void)
-{
-    __asm__ __volatile__ ("sync" : : : "memory");
-}
-#endif
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_acquire_load(volatile const int32_t *ptr)
-{
-    int32_t value = *ptr;
-    android_memory_barrier();
-    return value;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_release_load(volatile const int32_t *ptr)
-{
-    android_memory_barrier();
-    return *ptr;
-}
-
-extern ANDROID_ATOMIC_INLINE void
-android_atomic_acquire_store(int32_t value, volatile int32_t *ptr)
-{
-    *ptr = value;
-    android_memory_barrier();
-}
-
-extern ANDROID_ATOMIC_INLINE void
-android_atomic_release_store(int32_t value, volatile int32_t *ptr)
-{
-    android_memory_barrier();
-    *ptr = value;
-}
-
-extern ANDROID_ATOMIC_INLINE int
-android_atomic_cas(int32_t old_value, int32_t new_value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    do {
-        __asm__ __volatile__ (
-            "    ll     %[prev], (%[ptr])\n"
-            "    li     %[status], 1\n"
-            "    bne    %[prev], %[old], 9f\n"
-            "    move   %[status], %[new_value]\n"
-            "    sc     %[status], (%[ptr])\n"
-            "9:\n"
-            : [prev] "=&r" (prev), [status] "=&r" (status)
-            : [ptr] "r" (ptr), [old] "r" (old_value), [new_value] "r" (new_value)
-            );
-    } while (__builtin_expect(status == 0, 0));
-    return prev != old_value;
-}
-
-extern ANDROID_ATOMIC_INLINE int
-android_atomic_acquire_cas(int32_t old_value,
-                           int32_t new_value,
-                           volatile int32_t *ptr)
-{
-    int status = android_atomic_cas(old_value, new_value, ptr);
-    android_memory_barrier();
-    return status;
-}
-
-extern ANDROID_ATOMIC_INLINE int
-android_atomic_release_cas(int32_t old_value,
-                           int32_t new_value,
-                           volatile int32_t *ptr)
-{
-    android_memory_barrier();
-    return android_atomic_cas(old_value, new_value, ptr);
-}
-
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_add(int32_t increment, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ (
-        "    ll    %[prev], (%[ptr])\n"
-        "    addu  %[status], %[prev], %[inc]\n"
-        "    sc    %[status], (%[ptr])\n"
-        :  [status] "=&r" (status), [prev] "=&r" (prev)
-        :  [ptr] "r" (ptr), [inc] "Ir" (increment)
-        );
-    } while (__builtin_expect(status == 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_inc(volatile int32_t *addr)
-{
-    return android_atomic_add(1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_dec(volatile int32_t *addr)
-{
-    return android_atomic_add(-1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_and(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ (
-        "    ll    %[prev], (%[ptr])\n"
-        "    and   %[status], %[prev], %[value]\n"
-        "    sc    %[status], (%[ptr])\n"
-        : [prev] "=&r" (prev), [status] "=&r" (status)
-        : [ptr] "r" (ptr), [value] "Ir" (value)
-            );
-    } while (__builtin_expect(status == 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_or(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ (
-        "    ll    %[prev], (%[ptr])\n"
-        "    or    %[status], %[prev], %[value]\n"
-        "    sc    %[status], (%[ptr])\n"
-        : [prev] "=&r" (prev), [status] "=&r" (status)
-        : [ptr] "r" (ptr), [value] "Ir" (value)
-            );
-    } while (__builtin_expect(status == 0, 0));
-    return prev;
-}
-
-#endif /* ANDROID_CUTILS_ATOMIC_MIPS_H */
diff --git a/include/cutils/atomic-mips64.h b/include/cutils/atomic-mips64.h
deleted file mode 100644
index 9d8f65e..0000000
--- a/include/cutils/atomic-mips64.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2010 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 ANDROID_CUTILS_ATOMIC_MIPS64_H
-#define ANDROID_CUTILS_ATOMIC_MIPS64_H
-
-#include <stdint.h>
-
-#ifndef ANDROID_ATOMIC_INLINE
-#define ANDROID_ATOMIC_INLINE inline __attribute__((always_inline))
-#endif
-
-extern ANDROID_ATOMIC_INLINE void android_compiler_barrier(void)
-{
-    __asm__ __volatile__ ("" : : : "memory");
-}
-
-extern ANDROID_ATOMIC_INLINE void android_memory_barrier(void)
-{
-    __asm__ __volatile__ ("sync" : : : "memory");
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_acquire_load(volatile const int32_t *ptr)
-{
-    int32_t value = *ptr;
-    android_memory_barrier();
-    return value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_release_load(volatile const int32_t *ptr)
-{
-    android_memory_barrier();
-    return *ptr;
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_atomic_acquire_store(int32_t value, volatile int32_t *ptr)
-{
-    *ptr = value;
-    android_memory_barrier();
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_atomic_release_store(int32_t value, volatile int32_t *ptr)
-{
-    android_memory_barrier();
-    *ptr = value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_cas(int32_t old_value, int32_t new_value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    do {
-        __asm__ __volatile__ (
-            "    ll     %[prev], (%[ptr])\n"
-            "    li     %[status], 1\n"
-            "    bne    %[prev], %[old], 9f\n"
-            "    move   %[status], %[new_value]\n"
-            "    sc     %[status], (%[ptr])\n"
-            "9:\n"
-            : [prev] "=&r" (prev), [status] "=&r" (status)
-            : [ptr] "r" (ptr), [old] "r" (old_value), [new_value] "r" (new_value)
-            );
-    } while (__builtin_expect(status == 0, 0));
-    return prev != old_value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_acquire_cas(int32_t old_value,
-                           int32_t new_value,
-                           volatile int32_t *ptr)
-{
-    int status = android_atomic_cas(old_value, new_value, ptr);
-    android_memory_barrier();
-    return status;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_release_cas(int32_t old_value,
-                           int32_t new_value,
-                           volatile int32_t *ptr)
-{
-    android_memory_barrier();
-    return android_atomic_cas(old_value, new_value, ptr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_add(int32_t increment, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ (
-        "    ll    %[prev], (%[ptr])\n"
-        "    addu  %[status], %[prev], %[inc]\n"
-        "    sc    %[status], (%[ptr])\n"
-        :  [status] "=&r" (status), [prev] "=&r" (prev)
-        :  [ptr] "r" (ptr), [inc] "Ir" (increment)
-        );
-    } while (__builtin_expect(status == 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_inc(volatile int32_t *addr)
-{
-    return android_atomic_add(1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_dec(volatile int32_t *addr)
-{
-    return android_atomic_add(-1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_and(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ (
-        "    ll    %[prev], (%[ptr])\n"
-        "    and   %[status], %[prev], %[value]\n"
-        "    sc    %[status], (%[ptr])\n"
-        : [prev] "=&r" (prev), [status] "=&r" (status)
-        : [ptr] "r" (ptr), [value] "Ir" (value)
-            );
-    } while (__builtin_expect(status == 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_or(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    android_memory_barrier();
-    do {
-        __asm__ __volatile__ (
-        "    ll    %[prev], (%[ptr])\n"
-        "    or    %[status], %[prev], %[value]\n"
-        "    sc    %[status], (%[ptr])\n"
-        : [prev] "=&r" (prev), [status] "=&r" (status)
-        : [ptr] "r" (ptr), [value] "Ir" (value)
-            );
-    } while (__builtin_expect(status == 0, 0));
-    return prev;
-}
-
-#endif /* ANDROID_CUTILS_ATOMIC_MIPS_H */
diff --git a/include/cutils/atomic-x86.h b/include/cutils/atomic-x86.h
deleted file mode 100644
index 06bf1a3..0000000
--- a/include/cutils/atomic-x86.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2010 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 ANDROID_CUTILS_ATOMIC_X86_H
-#define ANDROID_CUTILS_ATOMIC_X86_H
-
-#include <stdint.h>
-
-#ifndef ANDROID_ATOMIC_INLINE
-#define ANDROID_ATOMIC_INLINE inline __attribute__((always_inline))
-#endif
-
-extern ANDROID_ATOMIC_INLINE void android_compiler_barrier(void)
-{
-    __asm__ __volatile__ ("" : : : "memory");
-}
-
-#if ANDROID_SMP == 0
-extern ANDROID_ATOMIC_INLINE void android_memory_barrier(void)
-{
-    android_compiler_barrier();
-}
-#else
-extern ANDROID_ATOMIC_INLINE void android_memory_barrier(void)
-{
-    __asm__ __volatile__ ("mfence" : : : "memory");
-}
-#endif
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_acquire_load(volatile const int32_t *ptr)
-{
-    int32_t value = *ptr;
-    android_compiler_barrier();
-    return value;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_release_load(volatile const int32_t *ptr)
-{
-    android_memory_barrier();
-    return *ptr;
-}
-
-extern ANDROID_ATOMIC_INLINE void
-android_atomic_acquire_store(int32_t value, volatile int32_t *ptr)
-{
-    *ptr = value;
-    android_memory_barrier();
-}
-
-extern ANDROID_ATOMIC_INLINE void
-android_atomic_release_store(int32_t value, volatile int32_t *ptr)
-{
-    android_compiler_barrier();
-    *ptr = value;
-}
-
-extern ANDROID_ATOMIC_INLINE int
-android_atomic_cas(int32_t old_value, int32_t new_value, volatile int32_t *ptr)
-{
-    int32_t prev;
-    __asm__ __volatile__ ("lock; cmpxchgl %1, %2"
-                          : "=a" (prev)
-                          : "q" (new_value), "m" (*ptr), "0" (old_value)
-                          : "memory");
-    return prev != old_value;
-}
-
-extern ANDROID_ATOMIC_INLINE int
-android_atomic_acquire_cas(int32_t old_value,
-                           int32_t new_value,
-                           volatile int32_t *ptr)
-{
-    /* Loads are not reordered with other loads. */
-    return android_atomic_cas(old_value, new_value, ptr);
-}
-
-extern ANDROID_ATOMIC_INLINE int
-android_atomic_release_cas(int32_t old_value,
-                           int32_t new_value,
-                           volatile int32_t *ptr)
-{
-    /* Stores are not reordered with other stores. */
-    return android_atomic_cas(old_value, new_value, ptr);
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_add(int32_t increment, volatile int32_t *ptr)
-{
-    __asm__ __volatile__ ("lock; xaddl %0, %1"
-                          : "+r" (increment), "+m" (*ptr)
-                          : : "memory");
-    /* increment now holds the old value of *ptr */
-    return increment;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_inc(volatile int32_t *addr)
-{
-    return android_atomic_add(1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_dec(volatile int32_t *addr)
-{
-    return android_atomic_add(-1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_and(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    do {
-        prev = *ptr;
-        status = android_atomic_cas(prev, prev & value, ptr);
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE int32_t
-android_atomic_or(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    do {
-        prev = *ptr;
-        status = android_atomic_cas(prev, prev | value, ptr);
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-#endif /* ANDROID_CUTILS_ATOMIC_X86_H */
diff --git a/include/cutils/atomic-x86_64.h b/include/cutils/atomic-x86_64.h
deleted file mode 100644
index 99cb070..0000000
--- a/include/cutils/atomic-x86_64.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    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
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * 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
- * 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
- * SUCH DAMAGE.
- */
-
-#ifndef ANDROID_CUTILS_ATOMIC_X86_64_H
-#define ANDROID_CUTILS_ATOMIC_X86_64_H
-
-#include <stdint.h>
-
-#ifndef ANDROID_ATOMIC_INLINE
-#define ANDROID_ATOMIC_INLINE inline __attribute__((always_inline))
-#endif
-
-extern ANDROID_ATOMIC_INLINE
-void android_compiler_barrier(void)
-{
-    __asm__ __volatile__ ("" : : : "memory");
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_memory_barrier(void)
-{
-    __asm__ __volatile__ ("mfence" : : : "memory");
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_acquire_load(volatile const int32_t *ptr)
-{
-    int32_t value = *ptr;
-    android_compiler_barrier();
-    return value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_release_load(volatile const int32_t *ptr)
-{
-    android_memory_barrier();
-    return *ptr;
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_atomic_acquire_store(int32_t value, volatile int32_t *ptr)
-{
-    *ptr = value;
-    android_memory_barrier();
-}
-
-extern ANDROID_ATOMIC_INLINE
-void android_atomic_release_store(int32_t value, volatile int32_t *ptr)
-{
-    android_compiler_barrier();
-    *ptr = value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_cas(int32_t old_value, int32_t new_value,
-                       volatile int32_t *ptr)
-{
-    int32_t prev;
-    __asm__ __volatile__ ("lock; cmpxchgl %1, %2"
-                          : "=a" (prev)
-                          : "q" (new_value), "m" (*ptr), "0" (old_value)
-                          : "memory");
-    return prev != old_value;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_acquire_cas(int32_t old_value, int32_t new_value,
-                               volatile int32_t *ptr)
-{
-    /* Loads are not reordered with other loads. */
-    return android_atomic_cas(old_value, new_value, ptr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int android_atomic_release_cas(int32_t old_value, int32_t new_value,
-                               volatile int32_t *ptr)
-{
-    /* Stores are not reordered with other stores. */
-    return android_atomic_cas(old_value, new_value, ptr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_add(int32_t increment, volatile int32_t *ptr)
-{
-    __asm__ __volatile__ ("lock; xaddl %0, %1"
-                          : "+r" (increment), "+m" (*ptr)
-                          : : "memory");
-    /* increment now holds the old value of *ptr */
-    return increment;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_inc(volatile int32_t *addr)
-{
-    return android_atomic_add(1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_dec(volatile int32_t *addr)
-{
-    return android_atomic_add(-1, addr);
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_and(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    do {
-        prev = *ptr;
-        status = android_atomic_cas(prev, prev & value, ptr);
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-extern ANDROID_ATOMIC_INLINE
-int32_t android_atomic_or(int32_t value, volatile int32_t *ptr)
-{
-    int32_t prev, status;
-    do {
-        prev = *ptr;
-        status = android_atomic_cas(prev, prev | value, ptr);
-    } while (__builtin_expect(status != 0, 0));
-    return prev;
-}
-
-#endif /* ANDROID_CUTILS_ATOMIC_X86_64_H */
diff --git a/include/cutils/atomic.h b/include/cutils/atomic.h
index 79409a7..ded972a 100644
--- a/include/cutils/atomic.h
+++ b/include/cutils/atomic.h
@@ -19,9 +19,10 @@
 
 #include <stdint.h>
 #include <sys/types.h>
+#include <stdatomic.h>
 
-#ifdef __cplusplus
-extern "C" {
+#ifndef ANDROID_ATOMIC_INLINE
+#define ANDROID_ATOMIC_INLINE static inline
 #endif
 
 /*
@@ -77,11 +78,41 @@
  * These have the same characteristics (e.g. what happens on overflow)
  * as the equivalent non-atomic C operations.
  */
-int32_t android_atomic_inc(volatile int32_t* addr);
-int32_t android_atomic_dec(volatile int32_t* addr);
-int32_t android_atomic_add(int32_t value, volatile int32_t* addr);
-int32_t android_atomic_and(int32_t value, volatile int32_t* addr);
-int32_t android_atomic_or(int32_t value, volatile int32_t* addr);
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_inc(volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+        /* Int32_t, if it exists, is the same as int_least32_t. */
+    return atomic_fetch_add_explicit(a, 1, memory_order_release);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_dec(volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    return atomic_fetch_sub_explicit(a, 1, memory_order_release);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_add(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    return atomic_fetch_add_explicit(a, value, memory_order_release);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_and(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    return atomic_fetch_and_explicit(a, value, memory_order_release);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_or(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    return atomic_fetch_or_explicit(a, value, memory_order_release);
+}
 
 /*
  * Perform an atomic load with "acquire" or "release" ordering.
@@ -96,29 +127,53 @@
  * this comment, you are in the vast majority, and should not be
  * using release loads or replacing them with anything other than
  * locks or default sequentially consistent atomics.
- *
- * This is only necessary if you need the memory barrier.  A 32-bit read
- * from a 32-bit aligned address is atomic on all supported platforms.
  */
-int32_t android_atomic_acquire_load(volatile const int32_t* addr);
-int32_t android_atomic_release_load(volatile const int32_t* addr);
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_acquire_load(volatile const int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    return atomic_load_explicit(a, memory_order_acquire);
+}
+
+ANDROID_ATOMIC_INLINE
+int32_t android_atomic_release_load(volatile const int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    atomic_thread_fence(memory_order_seq_cst);
+    /* Any reasonable clients of this interface would probably prefer   */
+    /* something weaker.  But some remaining clients seem to be         */
+    /* abusing this API in strange ways, e.g. by using it as a fence.   */
+    /* Thus we are conservative until we can get rid of remaining       */
+    /* clients (and this function).                                     */
+    return atomic_load_explicit(a, memory_order_relaxed);
+}
 
 /*
  * Perform an atomic store with "acquire" or "release" ordering.
  *
- * Note that the notion of a "acquire" ordering for a store does not
+ * Note that the notion of an "acquire" ordering for a store does not
  * really fit into the C11 or C++11 memory model.  The extra ordering
  * is normally observable only by code using memory_order_relaxed
  * atomics, or data races.  In the rare cases in which such ordering
  * is called for, use memory_order_relaxed atomics and a trailing
  * atomic_thread_fence (typically with memory_order_release,
  * not memory_order_acquire!) instead.
- *
- * This is only necessary if you need the memory barrier.  A 32-bit write
- * to a 32-bit aligned address is atomic on all supported platforms.
  */
-void android_atomic_acquire_store(int32_t value, volatile int32_t* addr);
-void android_atomic_release_store(int32_t value, volatile int32_t* addr);
+ANDROID_ATOMIC_INLINE
+void android_atomic_acquire_store(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    atomic_store_explicit(a, value, memory_order_relaxed);
+    atomic_thread_fence(memory_order_seq_cst);
+    /* Again overly conservative to accomodate weird clients.   */
+}
+
+ANDROID_ATOMIC_INLINE
+void android_atomic_release_store(int32_t value, volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    atomic_store_explicit(a, value, memory_order_release);
+}
 
 /*
  * Compare-and-set operation with "acquire" or "release" ordering.
@@ -132,10 +187,44 @@
  * Implementations that use the release CAS in a loop may be less efficient
  * than possible, because we re-issue the memory barrier on each iteration.
  */
+ANDROID_ATOMIC_INLINE
 int android_atomic_acquire_cas(int32_t oldvalue, int32_t newvalue,
-        volatile int32_t* addr);
+                           volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    return (int)(!atomic_compare_exchange_strong_explicit(
+                                          a, &oldvalue, newvalue,
+                                          memory_order_acquire,
+                                          memory_order_acquire));
+}
+
+ANDROID_ATOMIC_INLINE
 int android_atomic_release_cas(int32_t oldvalue, int32_t newvalue,
-        volatile int32_t* addr);
+                               volatile int32_t* addr)
+{
+    volatile atomic_int_least32_t* a = (volatile atomic_int_least32_t*)addr;
+    return (int)(!atomic_compare_exchange_strong_explicit(
+                                          a, &oldvalue, newvalue,
+                                          memory_order_release,
+                                          memory_order_relaxed));
+}
+
+/*
+ * Fence primitives.
+ */
+ANDROID_ATOMIC_INLINE
+void android_compiler_barrier(void)
+{
+    __asm__ __volatile__ ("" : : : "memory");
+    /* Could probably also be:                          */
+    /* atomic_signal_fence(memory_order_seq_cst);       */
+}
+
+ANDROID_ATOMIC_INLINE
+void android_memory_barrier(void)
+{
+    atomic_thread_fence(memory_order_seq_cst);
+}
 
 /*
  * Aliases for code using an older version of this header.  These are now
@@ -145,8 +234,4 @@
 #define android_atomic_write android_atomic_release_store
 #define android_atomic_cmpxchg android_atomic_release_cas
 
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
 #endif // ANDROID_CUTILS_ATOMIC_H
diff --git a/include/cutils/open_memstream.h b/include/cutils/open_memstream.h
index b7998be..c1a81eb 100644
--- a/include/cutils/open_memstream.h
+++ b/include/cutils/open_memstream.h
@@ -19,7 +19,7 @@
 
 #include <stdio.h>
 
-#ifndef HAVE_OPEN_MEMSTREAM
+#if defined(__APPLE__)
 
 #ifdef __cplusplus
 extern "C" {
@@ -31,6 +31,6 @@
 }
 #endif
 
-#endif /*!HAVE_OPEN_MEMSTREAM*/
+#endif /* __APPLE__ */
 
 #endif /*__CUTILS_OPEN_MEMSTREAM_H__*/
diff --git a/include/cutils/properties.h b/include/cutils/properties.h
index 798db8b..24aa224 100644
--- a/include/cutils/properties.h
+++ b/include/cutils/properties.h
@@ -126,22 +126,6 @@
 
 #endif
 
-#ifdef HAVE_SYSTEM_PROPERTY_SERVER
-/*
- * We have an external property server instead of built-in libc support.
- * Used by the simulator.
- */
-#define SYSTEM_PROPERTY_PIPE_NAME       "/tmp/android-sysprop"
-
-enum {
-    kSystemPropertyUnknown = 0,
-    kSystemPropertyGet,
-    kSystemPropertySet,
-    kSystemPropertyList
-};
-#endif /*HAVE_SYSTEM_PROPERTY_SERVER*/
-
-
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/cutils/sockets.h b/include/cutils/sockets.h
index daf43ec..c47588c 100644
--- a/include/cutils/sockets.h
+++ b/include/cutils/sockets.h
@@ -25,7 +25,7 @@
 #ifdef HAVE_WINSOCK
 #include <winsock2.h>
 typedef int  socklen_t;
-#elif HAVE_SYS_SOCKET_H
+#else
 #include <sys/socket.h>
 #endif
 
diff --git a/include/cutils/trace.h b/include/cutils/trace.h
index fd24561..59ff6c1 100644
--- a/include/cutils/trace.h
+++ b/include/cutils/trace.h
@@ -25,12 +25,8 @@
 #include <sys/types.h>
 #include <unistd.h>
 
-#include <cutils/compiler.h>
-#ifdef ANDROID_SMP
-#include <cutils/atomic-inline.h>
-#else
 #include <cutils/atomic.h>
-#endif
+#include <cutils/compiler.h>
 
 __BEGIN_DECLS
 
@@ -86,13 +82,6 @@
 
 #ifdef HAVE_ANDROID_OS
 /**
- * Maximum size of a message that can be logged to the trace buffer.
- * Note this message includes a tag, the pid, and the string given as the name.
- * Names should be kept short to get the most use of the trace buffer.
- */
-#define ATRACE_MESSAGE_LENGTH 1024
-
-/**
  * Opens the trace file for writing and reads the property for initial tags.
  * The atrace.tags.enableflags property sets the tags to trace.
  * This function should not be explicitly called, the first call to any normal
@@ -184,11 +173,8 @@
 static inline void atrace_begin(uint64_t tag, const char* name)
 {
     if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        char buf[ATRACE_MESSAGE_LENGTH];
-        size_t len;
-
-        len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "B|%d|%s", getpid(), name);
-        write(atrace_marker_fd, buf, len);
+        void atrace_begin_body(const char*);
+        atrace_begin_body(name);
     }
 }
 
@@ -218,12 +204,8 @@
         int32_t cookie)
 {
     if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        char buf[ATRACE_MESSAGE_LENGTH];
-        size_t len;
-
-        len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "S|%d|%s|%" PRId32,
-                getpid(), name, cookie);
-        write(atrace_marker_fd, buf, len);
+        void atrace_async_begin_body(const char*, int32_t);
+        atrace_async_begin_body(name, cookie);
     }
 }
 
@@ -232,20 +214,14 @@
  * This should have a corresponding ATRACE_ASYNC_BEGIN.
  */
 #define ATRACE_ASYNC_END(name, cookie) atrace_async_end(ATRACE_TAG, name, cookie)
-static inline void atrace_async_end(uint64_t tag, const char* name,
-        int32_t cookie)
+static inline void atrace_async_end(uint64_t tag, const char* name, int32_t cookie)
 {
     if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        char buf[ATRACE_MESSAGE_LENGTH];
-        size_t len;
-
-        len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "F|%d|%s|%" PRId32,
-                getpid(), name, cookie);
-        write(atrace_marker_fd, buf, len);
+        void atrace_async_end_body(const char*, int32_t);
+        atrace_async_end_body(name, cookie);
     }
 }
 
-
 /**
  * Traces an integer counter value.  name is used to identify the counter.
  * This can be used to track how a value changes over time.
@@ -254,12 +230,8 @@
 static inline void atrace_int(uint64_t tag, const char* name, int32_t value)
 {
     if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        char buf[ATRACE_MESSAGE_LENGTH];
-        size_t len;
-
-        len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "C|%d|%s|%" PRId32,
-                getpid(), name, value);
-        write(atrace_marker_fd, buf, len);
+        void atrace_int_body(const char*, int32_t);
+        atrace_int_body(name, value);
     }
 }
 
@@ -271,12 +243,8 @@
 static inline void atrace_int64(uint64_t tag, const char* name, int64_t value)
 {
     if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
-        char buf[ATRACE_MESSAGE_LENGTH];
-        size_t len;
-
-        len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "C|%d|%s|%" PRId64,
-                getpid(), name, value);
-        write(atrace_marker_fd, buf, len);
+        void atrace_int64_body(const char*, int64_t);
+        atrace_int64_body(name, value);
     }
 }
 
diff --git a/include/log/log_read.h b/include/log/log_read.h
index 946711a..1b70aff 100644
--- a/include/log/log_read.h
+++ b/include/log/log_read.h
@@ -100,6 +100,12 @@
         log_time local(*this);
         return local -= T;
     }
+    log_time operator+= (const timespec &T);
+    log_time operator+ (const timespec &T) const
+    {
+        log_time local(*this);
+        return local += T;
+    }
 
     // log_time
     bool operator== (const log_time &T) const
@@ -134,6 +140,12 @@
         log_time local(*this);
         return local -= T;
     }
+    log_time operator+= (const log_time &T);
+    log_time operator+ (const log_time &T) const
+    {
+        log_time local(*this);
+        return local += T;
+    }
 
     uint64_t nsec() const
     {
diff --git a/include/log/logprint.h b/include/log/logprint.h
index 481c96e..1e42b47 100644
--- a/include/log/logprint.h
+++ b/include/log/logprint.h
@@ -36,6 +36,7 @@
     FORMAT_TIME,
     FORMAT_THREADTIME,
     FORMAT_LONG,
+    FORMAT_COLOR,
 } AndroidLogPrintFormat;
 
 typedef struct AndroidLogFormat_t AndroidLogFormat;
diff --git a/include/log/uio.h b/include/log/uio.h
index a71f515..7059da5 100644
--- a/include/log/uio.h
+++ b/include/log/uio.h
@@ -14,20 +14,23 @@
  * limitations under the License.
  */
 
-//
-// implementation of sys/uio.h for platforms that don't have it (Win32)
-//
 #ifndef _LIBS_CUTILS_UIO_H
 #define _LIBS_CUTILS_UIO_H
 
-#ifdef HAVE_SYS_UIO_H
+#if !defined(_WIN32)
+
 #include <sys/uio.h>
+
 #else
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+//
+// Implementation of sys/uio.h for Win32.
+//
+
 #include <stddef.h>
 
 struct iovec {
@@ -42,7 +45,7 @@
 }
 #endif
 
-#endif /* !HAVE_SYS_UIO_H */
+#endif
 
 #endif /* _LIBS_UTILS_UIO_H */
 
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index 5d9c3ea..5efe2e1 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -83,6 +83,11 @@
 #define AID_CACHE         2001  /* cache access */
 #define AID_DIAG          2002  /* access to diagnostic resources */
 
+/* The range 2900-2999 is reserved for OEM, and must never be
+ * used here */
+#define AID_OEM_RESERVED_START 2900
+#define AID_OEM_RESERVED_END   2999
+
 /* The 3000 series are intended for use as supplemental group id's only.
  * They indicate special Android capabilities that the kernel is aware of. */
 #define AID_NET_BT_ADMIN  3001  /* bluetooth: create any socket */
@@ -227,7 +232,6 @@
     { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.goldfish.sh" },
     { 00440, AID_ROOT,      AID_SHELL,     0, "system/etc/init.trout.rc" },
     { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.ril" },
-    { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.testmenu" },
     { 00550, AID_DHCP,      AID_SHELL,     0, "system/etc/dhcpcd/dhcpcd-run-hooks" },
     { 00444, AID_RADIO,     AID_AUDIO,     0, "system/etc/AudioPara4.csv" },
     { 00555, AID_ROOT,      AID_ROOT,      0, "system/etc/ppp/*" },
diff --git a/include/private/pixelflinger/ggl_fixed.h b/include/private/pixelflinger/ggl_fixed.h
index d0493f3..787f620 100644
--- a/include/private/pixelflinger/ggl_fixed.h
+++ b/include/private/pixelflinger/ggl_fixed.h
@@ -190,7 +190,7 @@
         );
     return res;
 }
-#elif defined(__mips__)
+#elif defined(__mips__) && __mips_isa_rev < 6
 
 /*inline MIPS implementations*/
 inline GGLfixed gglMulx(GGLfixed a, GGLfixed b, int shift) CONST;
diff --git a/include/utils/AndroidThreads.h b/include/utils/AndroidThreads.h
index 4eee14d..3c640b6 100644
--- a/include/utils/AndroidThreads.h
+++ b/include/utils/AndroidThreads.h
@@ -73,9 +73,6 @@
 // ------------------------------------------------------------------
 // Extra functions working with raw pids.
 
-// Get pid for the current thread.
-extern pid_t androidGetTid();
-
 #ifdef HAVE_ANDROID_OS
 // Change the priority AND scheduling group of a particular thread.  The priority
 // should be one of the ANDROID_PRIORITY constants.  Returns INVALID_OPERATION
diff --git a/include/utils/Compat.h b/include/utils/Compat.h
index fb7748e..0df40a1 100644
--- a/include/utils/Compat.h
+++ b/include/utils/Compat.h
@@ -19,11 +19,9 @@
 
 #include <unistd.h>
 
-/* Compatibility definitions for non-Linux (i.e., BSD-based) hosts. */
-#ifndef HAVE_OFF64_T
-#if _FILE_OFFSET_BITS < 64
-#error "_FILE_OFFSET_BITS < 64; large files are not supported on this platform"
-#endif /* _FILE_OFFSET_BITS < 64 */
+#if defined(__APPLE__)
+
+/* Mac OS has always had a 64-bit off_t, so it doesn't have off64_t. */
 
 typedef off_t off64_t;
 
@@ -31,13 +29,11 @@
     return lseek(fd, offset, whence);
 }
 
-#ifdef HAVE_PREAD
 static inline ssize_t pread64(int fd, void* buf, size_t nbytes, off64_t offset) {
     return pread(fd, buf, nbytes, offset);
 }
-#endif
 
-#endif /* !HAVE_OFF64_T */
+#endif /* __APPLE__ */
 
 #if HAVE_PRINTF_ZD
 #  define ZD "%zd"
@@ -48,6 +44,17 @@
 #endif
 
 /*
+ * Needed for cases where something should be constexpr if possible, but not
+ * being constexpr is fine if in pre-C++11 code (such as a const static float
+ * member variable).
+ */
+#if __cplusplus >= 201103L
+#define CONSTEXPR constexpr
+#else
+#define CONSTEXPR
+#endif
+
+/*
  * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
  * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
  * not already defined, then define it here.
diff --git a/include/utils/Condition.h b/include/utils/Condition.h
index 1c99d1a..db9be59 100644
--- a/include/utils/Condition.h
+++ b/include/utils/Condition.h
@@ -113,15 +113,15 @@
     return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts);
 #else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
     struct timespec ts;
-#if defined(HAVE_POSIX_CLOCKS)
+#if defined(__linux__)
     clock_gettime(CLOCK_REALTIME, &ts);
-#else // HAVE_POSIX_CLOCKS
+#else // __APPLE__
     // we don't support the clocks here.
     struct timeval t;
     gettimeofday(&t, NULL);
     ts.tv_sec = t.tv_sec;
     ts.tv_nsec= t.tv_usec*1000;
-#endif // HAVE_POSIX_CLOCKS
+#endif
     ts.tv_sec += reltime/1000000000;
     ts.tv_nsec+= reltime%1000000000;
     if (ts.tv_nsec >= 1000000000) {
diff --git a/include/utils/Endian.h b/include/utils/Endian.h
index 19f2504..591cae0 100644
--- a/include/utils/Endian.h
+++ b/include/utils/Endian.h
@@ -20,21 +20,16 @@
 #ifndef _LIBS_UTILS_ENDIAN_H
 #define _LIBS_UTILS_ENDIAN_H
 
-#if defined(HAVE_ENDIAN_H)
-
-#include <endian.h>
-
-#else /*not HAVE_ENDIAN_H*/
+#if defined(__APPLE__) || defined(_WIN32)
 
 #define __BIG_ENDIAN 0x1000
 #define __LITTLE_ENDIAN 0x0001
+#define __BYTE_ORDER __LITTLE_ENDIAN
 
-#if defined(HAVE_LITTLE_ENDIAN)
-# define __BYTE_ORDER __LITTLE_ENDIAN
 #else
-# define __BYTE_ORDER __BIG_ENDIAN
-#endif
 
-#endif /*not HAVE_ENDIAN_H*/
+#include <endian.h>
+
+#endif
 
 #endif /*_LIBS_UTILS_ENDIAN_H*/
diff --git a/include/utils/FileMap.h b/include/utils/FileMap.h
index dfe6d51..6c0aa52 100644
--- a/include/utils/FileMap.h
+++ b/include/utils/FileMap.h
@@ -24,7 +24,11 @@
 
 #include <utils/Compat.h>
 
-#ifdef HAVE_WIN32_FILEMAP
+#if defined(__MINGW32__)
+// Ensure that we always pull in winsock2.h before windows.h
+#ifdef HAVE_WINSOCK
+#include <winsock2.h>
+#endif
 #include <windows.h>
 #endif
 
@@ -123,7 +127,7 @@
     off64_t     mDataOffset;    // offset used when map was created
     void*       mDataPtr;       // start of requested data, offset from base
     size_t      mDataLength;    // length, measured from "mDataPtr"
-#ifdef HAVE_WIN32_FILEMAP
+#if defined(__MINGW32__)
     HANDLE      mFileHandle;    // Win32 file handle
     HANDLE      mFileMapping;   // Win32 file mapping handle
 #endif
diff --git a/include/utils/Mutex.h b/include/utils/Mutex.h
index dd201c8..a3b594d 100644
--- a/include/utils/Mutex.h
+++ b/include/utils/Mutex.h
@@ -26,6 +26,7 @@
 #endif
 
 #include <utils/Errors.h>
+#include <utils/Timers.h>
 
 // ---------------------------------------------------------------------------
 namespace android {
@@ -45,7 +46,7 @@
         PRIVATE = 0,
         SHARED = 1
     };
-    
+
                 Mutex();
                 Mutex(const char* name);
                 Mutex(int type, const char* name = NULL);
@@ -58,6 +59,16 @@
     // lock if possible; returns 0 on success, error otherwise
     status_t    tryLock();
 
+#if HAVE_ANDROID_OS
+    // lock the mutex, but don't wait longer than timeoutMilliseconds.
+    // Returns 0 on success, TIMED_OUT for failure due to timeout expiration.
+    //
+    // OSX doesn't have pthread_mutex_timedlock() or equivalent. To keep
+    // capabilities consistent across host OSes, this method is only available
+    // when building Android binaries.
+    status_t    timedLock(nsecs_t timeoutMilliseconds);
+#endif
+
     // Manages the mutex automatically. It'll be locked when Autolock is
     // constructed and released when Autolock goes out of scope.
     class Autolock {
@@ -71,11 +82,11 @@
 
 private:
     friend class Condition;
-    
+
     // A mutex cannot be copied
                 Mutex(const Mutex&);
     Mutex&      operator = (const Mutex&);
-    
+
 #if defined(HAVE_PTHREADS)
     pthread_mutex_t mMutex;
 #else
@@ -117,6 +128,15 @@
 inline status_t Mutex::tryLock() {
     return -pthread_mutex_trylock(&mMutex);
 }
+#if HAVE_ANDROID_OS
+inline status_t Mutex::timedLock(nsecs_t timeoutNs) {
+    const struct timespec ts = {
+        /* .tv_sec = */ static_cast<time_t>(timeoutNs / 1000000000),
+        /* .tv_nsec = */ static_cast<long>(timeoutNs % 1000000000),
+    };
+    return -pthread_mutex_timedlock(&mMutex, &ts);
+}
+#endif
 
 #endif // HAVE_PTHREADS
 
@@ -127,7 +147,7 @@
  * When the function returns, it will go out of scope, and release the
  * mutex.
  */
- 
+
 typedef Mutex::Autolock AutoMutex;
 
 // ---------------------------------------------------------------------------
diff --git a/include/utils/RefBase.h b/include/utils/RefBase.h
index 8e15c19..eac6a78 100644
--- a/include/utils/RefBase.h
+++ b/include/utils/RefBase.h
@@ -491,7 +491,8 @@
                 TYPE::renameRefId(d[i].get(), &s[i], &d[i]);
             }
         public:
-            Renamer(sp<TYPE>* d, sp<TYPE> const* s) : s(s), d(d) { }
+            Renamer(sp<TYPE>* d, sp<TYPE> const* s) : d(d), s(s) { }
+            virtual ~Renamer() { }
         };
 
         memmove(d, s, n*sizeof(sp<TYPE>));
@@ -510,7 +511,8 @@
                 TYPE::renameRefId(d[i].get_refs(), &s[i], &d[i]);
             }
         public:
-            Renamer(wp<TYPE>* d, wp<TYPE> const* s) : s(s), d(d) { }
+            Renamer(wp<TYPE>* d, wp<TYPE> const* s) : d(d), s(s) { }
+            virtual ~Renamer() { }
         };
 
         memmove(d, s, n*sizeof(wp<TYPE>));
diff --git a/include/utils/Singleton.h b/include/utils/Singleton.h
index c60680e..ffc03cb 100644
--- a/include/utils/Singleton.h
+++ b/include/utils/Singleton.h
@@ -65,9 +65,10 @@
  */
 
 #define ANDROID_SINGLETON_STATIC_INSTANCE(TYPE)                 \
-    template<> Mutex Singleton< TYPE >::sLock(Mutex::PRIVATE);  \
-    template<> TYPE* Singleton< TYPE >::sInstance(0);           \
-    template class Singleton< TYPE >;
+    template<> ::android::Mutex  \
+        (::android::Singleton< TYPE >::sLock)(::android::Mutex::PRIVATE);  \
+    template<> TYPE* ::android::Singleton< TYPE >::sInstance(0);  \
+    template class ::android::Singleton< TYPE >;
 
 
 // ---------------------------------------------------------------------------
diff --git a/include/utils/Thread.h b/include/utils/Thread.h
index df30611..c867e95 100644
--- a/include/utils/Thread.h
+++ b/include/utils/Thread.h
@@ -71,8 +71,8 @@
             bool        isRunning() const;
 
 #ifdef HAVE_ANDROID_OS
-    // Return the thread's kernel ID, same as the thread itself calling gettid() or
-    // androidGetTid(), or -1 if the thread is not running.
+    // Return the thread's kernel ID, same as the thread itself calling gettid(),
+    // or -1 if the thread is not running.
             pid_t       getTid() const;
 #endif
 
diff --git a/include/utils/Unicode.h b/include/utils/Unicode.h
index 5b98de2..b76a5e2 100644
--- a/include/utils/Unicode.h
+++ b/include/utils/Unicode.h
@@ -22,12 +22,6 @@
 
 extern "C" {
 
-// Definitions exist in C++11
-#if defined __cplusplus && __cplusplus < 201103L
-typedef uint32_t char32_t;
-typedef uint16_t char16_t;
-#endif
-
 // Standard string functions on char16_t strings.
 int strcmp16(const char16_t *, const char16_t *);
 int strncmp16(const char16_t *s1, const char16_t *s2, size_t n);
diff --git a/include/ziparchive/zip_archive.h b/include/ziparchive/zip_archive.h
index 1877494..7da6e84 100644
--- a/include/ziparchive/zip_archive.h
+++ b/include/ziparchive/zip_archive.h
@@ -21,6 +21,7 @@
 #define LIBZIPARCHIVE_ZIPARCHIVE_H_
 
 #include <stdint.h>
+#include <string.h>
 #include <sys/types.h>
 #include <utils/Compat.h>
 
@@ -33,8 +34,16 @@
 };
 
 struct ZipEntryName {
-  const char* name;
+  const uint8_t* name;
   uint16_t name_length;
+
+  ZipEntryName() {}
+
+  /*
+   * entry_name has to be an c-style string with only ASCII characters.
+   */
+  explicit ZipEntryName(const char* entry_name)
+      : name(reinterpret_cast<const uint8_t*>(entry_name)), name_length(strlen(entry_name)) {}
 };
 
 /*
@@ -124,24 +133,24 @@
  * and length, a call to VerifyCrcAndLengths must be made after entry data
  * has been processed.
  */
-int32_t FindEntry(const ZipArchiveHandle handle, const char* entryName,
+int32_t FindEntry(const ZipArchiveHandle handle, const ZipEntryName& entryName,
                   ZipEntry* data);
 
 /*
  * Start iterating over all entries of a zip file. The order of iteration
  * is not guaranteed to be the same as the order of elements
- * in the central directory but is stable for a given zip file. |cookie|
- * must point to a writeable memory location, and will be set to the value
- * of an opaque cookie which can be used to make one or more calls to
- * Next.
+ * in the central directory but is stable for a given zip file. |cookie| will
+ * contain the value of an opaque cookie which can be used to make one or more
+ * calls to Next. All calls to StartIteration must be matched by a call to
+ * EndIteration to free any allocated memory.
  *
  * This method also accepts an optional prefix to restrict iteration to
- * entry names that start with |prefix|.
+ * entry names that start with |optional_prefix|.
  *
  * Returns 0 on success and negative values on failure.
  */
 int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr,
-                       const char* prefix);
+                       const ZipEntryName* optional_prefix);
 
 /*
  * Advance to the next element in the zipfile in iteration order.
@@ -152,6 +161,12 @@
 int32_t Next(void* cookie, ZipEntry* data, ZipEntryName *name);
 
 /*
+ * End iteration over all entries of a zip file and frees the memory allocated
+ * in StartIteration.
+ */
+void EndIteration(void* cookie);
+
+/*
  * Uncompress and write an entry to an open file identified by |fd|.
  * |entry->uncompressed_length| bytes will be written to the file at
  * its current offset, and the file will be truncated at the end of
diff --git a/init/Android.mk b/init/Android.mk
index 489dc93..8cda879 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -33,6 +33,10 @@
 
 LOCAL_MODULE:= init
 
+# Currently, init doesn't start when built with clang.
+# Needs further investigation.
+LOCAL_CLANG := false
+
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
 LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_UNSTRIPPED)
@@ -47,25 +51,9 @@
 	libmincrypt \
 	libext4_utils_static
 
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
+# Create symlinks
+LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \
+    ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \
+    ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd
 
 include $(BUILD_EXECUTABLE)
-
-# Make a symlink from /sbin/ueventd and /sbin/watchdogd to /init
-SYMLINKS := \
-	$(TARGET_ROOT_OUT)/sbin/ueventd \
-	$(TARGET_ROOT_OUT)/sbin/watchdogd
-
-$(SYMLINKS): INIT_BINARY := $(LOCAL_MODULE)
-$(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk
-	@echo "Symlink: $@ -> ../$(INIT_BINARY)"
-	@mkdir -p $(dir $@)
-	@rm -rf $@
-	$(hide) ln -sf ../$(INIT_BINARY) $@
-
-ALL_DEFAULT_INSTALLED_MODULES += $(SYMLINKS)
-
-# We need this so that the installed files could be picked up based on the
-# local module name
-ALL_MODULES.$(LOCAL_MODULE).INSTALLED := \
-    $(ALL_MODULES.$(LOCAL_MODULE).INSTALLED) $(SYMLINKS)
diff --git a/init/bootchart.c b/init/bootchart.c
index f72fcaa..a514261 100644
--- a/init/bootchart.c
+++ b/init/bootchart.c
@@ -119,6 +119,18 @@
     }
 }
 
+static long long
+get_uptime_jiffies()
+{
+    char       buff[64];
+    long long  jiffies = 0;
+
+    if (proc_read("/proc/uptime", buff, sizeof(buff)) > 0)
+        jiffies = 100LL*strtod(buff,NULL);
+
+    return jiffies;
+}
+
 static void
 log_header(void)
 {
@@ -185,22 +197,11 @@
 do_log_uptime(FileBuff  log)
 {
     char  buff[65];
-    int   fd, ret, len;
+    int   len;
 
-    fd = open("/proc/uptime",O_RDONLY);
-    if (fd >= 0) {
-        int  ret;
-        ret = unix_read(fd, buff, 64);
-        close(fd);
-        buff[64] = 0;
-        if (ret >= 0) {
-            long long  jiffies = 100LL*strtod(buff,NULL);
-            int        len;
-            snprintf(buff,sizeof(buff),"%lld\n",jiffies);
-            len = strlen(buff);
-            file_buff_write(log, buff, len);
-        }
-    }
+    snprintf(buff,sizeof(buff),"%lld\n",get_uptime_jiffies());
+    len = strlen(buff);
+    file_buff_write(log, buff, len);
 }
 
 static void
@@ -376,3 +377,9 @@
     file_buff_done(log_procs);
     acct(NULL);
 }
+
+/* called to get time (in ms) used by bootchart */
+long long  bootchart_gettime( void )
+{
+    return 10LL*get_uptime_jiffies();
+}
diff --git a/init/bootchart.h b/init/bootchart.h
index 39d2d4f..ed65e8a 100644
--- a/init/bootchart.h
+++ b/init/bootchart.h
@@ -26,6 +26,7 @@
 extern int   bootchart_init(void);
 extern int   bootchart_step(void);
 extern void  bootchart_finish(void);
+extern long long  bootchart_gettime(void);
 
 # define BOOTCHART_POLLING_MS   200   /* polling period in ms */
 # define BOOTCHART_DEFAULT_TIME_SEC    (2*60)  /* default polling time in seconds */
diff --git a/init/builtins.c b/init/builtins.c
index c192551..5d2a517 100644
--- a/init/builtins.c
+++ b/init/builtins.c
@@ -433,6 +433,7 @@
             sprintf(tmp, "/dev/block/loop%d", n);
             loop = open(tmp, mode);
             if (loop < 0) {
+                close(fd);
                 return -1;
             }
 
@@ -500,7 +501,6 @@
     int ret = -1;
     int child_ret = -1;
     int status;
-    const char *prop;
     struct fstab *fstab;
 
     if (nargs != 2) {
diff --git a/init/devices.c b/init/devices.c
index 1012fee..dde43df 100644
--- a/init/devices.c
+++ b/init/devices.c
@@ -191,7 +191,6 @@
 static mode_t get_device_perm(const char *path, const char **links,
                 unsigned *uid, unsigned *gid)
 {
-    mode_t perm;
     struct listnode *node;
     struct perm_node *perm_node;
     struct perms_ *dp;
@@ -458,7 +457,7 @@
 
     /* skip "/devices/platform/<driver>" */
     parent = strchr(uevent->path + pdev->path_len, '/');
-    if (!*parent)
+    if (!parent)
         goto err;
 
     if (!strncmp(parent, "/usb", 4)) {
@@ -497,15 +496,10 @@
     struct platform_node *pdev;
     char *slash;
     const char *type;
-    int width;
     char buf[256];
     char link_path[256];
-    int fd;
     int link_num = 0;
-    int ret;
     char *p;
-    unsigned int size;
-    struct stat info;
 
     pdev = find_platform_device(uevent->path);
     if (pdev) {
@@ -926,7 +920,6 @@
 static void handle_firmware_event(struct uevent *uevent)
 {
     pid_t pid;
-    int ret;
 
     if(strcmp(uevent->subsystem, "firmware"))
         return;
@@ -938,7 +931,9 @@
     pid = fork();
     if (!pid) {
         process_firmware_event(uevent);
-        exit(EXIT_SUCCESS);
+        _exit(EXIT_SUCCESS);
+    } else if (pid < 0) {
+        log_event_print("could not fork to process firmware event: %s\n", strerror(errno));
     }
 }
 
@@ -1043,15 +1038,18 @@
     fcntl(device_fd, F_SETFD, FD_CLOEXEC);
     fcntl(device_fd, F_SETFL, O_NONBLOCK);
 
-    if (stat(coldboot_done, &info) < 0) {
+    if (stat(COLDBOOT_DONE, &info) < 0) {
         t0 = get_usecs();
         coldboot("/sys/class");
         coldboot("/sys/block");
         coldboot("/sys/devices");
         t1 = get_usecs();
-        fd = open(coldboot_done, O_WRONLY|O_CREAT, 0000);
+        fd = open(COLDBOOT_DONE, O_WRONLY|O_CREAT, 0000);
         close(fd);
         log_event_print("coldboot %ld uS\n", ((long) (t1 - t0)));
+        // t0 & t1 are unused if the log isn't doing anything.
+        (void)t0;
+        (void)t1;
     } else {
         log_event_print("skipping coldboot, already done\n");
     }
diff --git a/init/init.c b/init/init.c
index bd1db7a..7ddab80 100644
--- a/init/init.c
+++ b/init/init.c
@@ -65,6 +65,7 @@
 
 #if BOOTCHART
 static int   bootchart_count;
+static long long bootchart_time = 0;
 #endif
 
 static char console[32];
@@ -75,7 +76,6 @@
 
 static struct action *cur_action = NULL;
 static struct command *cur_command = NULL;
-static struct listnode *command_queue = NULL;
 
 void notify_service_state(const char *name, const char *state)
 {
@@ -169,7 +169,6 @@
     struct stat s;
     pid_t pid;
     int needs_console;
-    int n;
     char *scon = NULL;
     int rc;
 
@@ -577,10 +576,10 @@
 static int wait_for_coldboot_done_action(int nargs, char **args)
 {
     int ret;
-    INFO("wait for %s\n", coldboot_done);
-    ret = wait_for_file(coldboot_done, COMMAND_RETRY_TIMEOUT);
+    INFO("wait for %s\n", COLDBOOT_DONE);
+    ret = wait_for_file(COLDBOOT_DONE, COMMAND_RETRY_TIMEOUT);
     if (ret)
-        ERROR("Timed out waiting for %s\n", coldboot_done);
+        ERROR("Timed out waiting for %s\n", COLDBOOT_DONE);
     return ret;
 }
 
@@ -859,26 +858,6 @@
 }
 #endif
 
-static const struct selinux_opt seopts_prop[] = {
-        { SELABEL_OPT_PATH, "/property_contexts" },
-        { SELABEL_OPT_PATH, "/data/security/current/property_contexts" },
-        { 0, NULL }
-};
-
-struct selabel_handle* selinux_android_prop_context_handle(void)
-{
-    int policy_index = selinux_android_use_data_policy() ? 1 : 0;
-    struct selabel_handle* sehandle = selabel_open(SELABEL_CTX_ANDROID_PROP,
-                                                   &seopts_prop[policy_index], 1);
-    if (!sehandle) {
-        ERROR("SELinux:  Could not load property_contexts:  %s\n",
-              strerror(errno));
-        return NULL;
-    }
-    INFO("SELinux: Loaded property contexts from %s\n", seopts_prop[policy_index].value);
-    return sehandle;
-}
-
 void selinux_init_all_handles(void)
 {
     sehandle = selinux_android_file_context_handle();
@@ -1002,9 +981,6 @@
 {
     int fd_count = 0;
     struct pollfd ufds[4];
-    char *tmpdev;
-    char* debuggable;
-    char tmp[32];
     int property_set_fd_init = 0;
     int signal_fd_init = 0;
     int keychord_fd_init = 0;
@@ -1147,11 +1123,29 @@
 
 #if BOOTCHART
         if (bootchart_count > 0) {
-            if (timeout < 0 || timeout > BOOTCHART_POLLING_MS)
-                timeout = BOOTCHART_POLLING_MS;
-            if (bootchart_step() < 0 || --bootchart_count == 0) {
-                bootchart_finish();
-                bootchart_count = 0;
+            long long current_time;
+            int elapsed_time, remaining_time;
+
+            current_time = bootchart_gettime();
+            elapsed_time = current_time - bootchart_time;
+
+            if (elapsed_time >= BOOTCHART_POLLING_MS) {
+                /* count missed samples */
+                while (elapsed_time >= BOOTCHART_POLLING_MS) {
+                    elapsed_time -= BOOTCHART_POLLING_MS;
+                    bootchart_count--;
+                }
+                /* count may be negative, take a sample anyway */
+                bootchart_time = current_time;
+                if (bootchart_step() < 0 || bootchart_count <= 0) {
+                    bootchart_finish();
+                    bootchart_count = 0;
+                }
+            }
+            if (bootchart_count > 0) {
+                remaining_time = BOOTCHART_POLLING_MS - elapsed_time;
+                if (timeout < 0 || timeout > remaining_time)
+                    timeout = remaining_time;
             }
         }
 #endif
diff --git a/init/init_parser.c b/init/init_parser.c
index 6466db2..2b4db8e 100644
--- a/init/init_parser.c
+++ b/init/init_parser.c
@@ -187,19 +187,14 @@
 
 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 $.
@@ -847,7 +842,6 @@
 {
     struct command *cmd;
     struct action *act = state->context;
-    int (*func)(int nargs, char **args);
     int kw, n;
 
     if (nargs == 0) {
diff --git a/init/property_service.c b/init/property_service.c
index 91ef251..55e37b9 100644
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -63,7 +63,6 @@
 
 static int init_workspace(workspace *w, size_t size)
 {
-    void *data;
     int fd = open(PROP_FILENAME, O_RDONLY | O_NOFOLLOW);
     if (fd < 0)
         return -1;
@@ -142,9 +141,6 @@
  */
 static int check_perms(const char *name, char *sctx)
 {
-    int i;
-    unsigned int app_id;
-
     if(!strncmp(name, "ro.", 3))
         name +=3;
 
@@ -261,7 +257,6 @@
     prop_msg msg;
     int s;
     int r;
-    int res;
     struct ucred cr;
     struct sockaddr_un addr;
     socklen_t addr_size = sizeof(addr);
@@ -448,10 +443,8 @@
         while ((entry = readdir(dir)) != NULL) {
             if (strncmp("persist.", entry->d_name, strlen("persist.")))
                 continue;
-#if HAVE_DIRENT_D_TYPE
             if (entry->d_type != DT_REG)
                 continue;
-#endif
             /* open the file and read the property value */
             fd = openat(dir_fd, entry->d_name, O_RDONLY | O_NOFOLLOW);
             if (fd < 0) {
@@ -541,6 +534,7 @@
     load_properties_from_file(PROP_PATH_SYSTEM_BUILD, NULL);
     load_properties_from_file(PROP_PATH_SYSTEM_DEFAULT, NULL);
     load_properties_from_file(PROP_PATH_VENDOR_BUILD, NULL);
+    load_properties_from_file(PROP_PATH_BOOTIMAGE_BUILD, NULL);
     load_properties_from_file(PROP_PATH_FACTORY, "ro.*");
 
     load_override_properties();
diff --git a/init/readme.txt b/init/readme.txt
index 26be536..750d953 100644
--- a/init/readme.txt
+++ b/init/readme.txt
@@ -123,15 +123,6 @@
    Triggers of this form occur when the property <name> is set
    to the specific value <value>.
 
-device-added-<path>
-device-removed-<path>
-   Triggers of these forms occur when a device node is added
-   or removed.
-
-service-exited-<name>
-   Triggers of this form occur when the specified service exits.
-
-
 Commands
 --------
 
@@ -211,8 +202,6 @@
 restorecon_recursive <path> [ <path> ]*
    Recursively restore the directory tree named by <path> to the
    security contexts specified in the file_contexts configuration.
-   Do NOT use this with paths leading to shell-writable or app-writable
-   directories, e.g. /data/local/tmp, /data/data or any prefix thereof.
 
 setcon <securitycontext>
    Set the current process security context to the specified string.
@@ -327,12 +316,6 @@
    user system
    group system
 
-on device-added-/dev/compass
-   start akmd
-
-on device-removed-/dev/compass
-   stop akmd
-
 service akmd /sbin/akmd
    disabled
    user akmd
diff --git a/init/util.h b/init/util.h
index 04b8129..4cfe99d 100644
--- a/init/util.h
+++ b/init/util.h
@@ -22,7 +22,7 @@
 
 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
 
-static const char *coldboot_done = "/dev/.coldboot_done";
+#define COLDBOOT_DONE "/dev/.coldboot_done"
 
 int mtd_name_to_number(const char *name);
 int create_socket(const char *name, int type, mode_t perm,
diff --git a/libbacktrace/Android.build.mk b/libbacktrace/Android.build.mk
index 2f55645..7e1cd53 100644
--- a/libbacktrace/Android.build.mk
+++ b/libbacktrace/Android.build.mk
@@ -61,18 +61,13 @@
     $($(module)_ldlibs_$(build_type)) \
 
 ifeq ($(build_type),target)
-  ifneq ($($(module)_libc++),)
-    include external/libcxx/libcxx.mk
-  else
-    include external/stlport/libstlport.mk
-  endif
-
   include $(BUILD_$(build_target))
 endif
 
 ifeq ($(build_type),host)
   # Only build if host builds are supported.
   ifeq ($(build_host),true)
+    LOCAL_CFLAGS += -Wno-extern-c-compat
     ifneq ($($(module)_libc++),)
       include external/libcxx/libcxx.mk
     endif
diff --git a/libbacktrace/Android.mk b/libbacktrace/Android.mk
index 9588dd6..ca1e4bf 100755
--- a/libbacktrace/Android.mk
+++ b/libbacktrace/Android.mk
@@ -51,9 +51,6 @@
 	UnwindMap.cpp \
 	UnwindPtrace.cpp \
 
-libbacktrace_c_includes := \
-	external/libunwind/include \
-
 libbacktrace_shared_libraries := \
 	libunwind \
 	libunwind-ptrace \
@@ -74,58 +71,9 @@
 build_target := SHARED_LIBRARY
 include $(LOCAL_PATH)/Android.build.mk
 build_type := host
+libbacktrace_multilib := both
 include $(LOCAL_PATH)/Android.build.mk
 
-# Don't build for unbundled branches
-ifeq (,$(TARGET_BUILD_APPS))
-#-------------------------------------------------------------------------
-# The libbacktrace library (libc++)
-#-------------------------------------------------------------------------
-libbacktrace_libc++_src_files := \
-	BacktraceImpl.cpp \
-	BacktraceMap.cpp \
-	BacktraceThread.cpp \
-	thread_utils.c \
-
-libbacktrace_libc++_shared_libraries_target := \
-	libcutils \
-	libgccdemangle \
-
-libbacktrace_libc++_src_files += \
-	UnwindCurrent.cpp \
-	UnwindMap.cpp \
-	UnwindPtrace.cpp \
-
-libbacktrace_libc++_c_includes := \
-	external/libunwind/include \
-
-libbacktrace_libc++_shared_libraries := \
-	libunwind \
-	libunwind-ptrace \
-
-libbacktrace_libc++_shared_libraries_host := \
-	liblog \
-
-libbacktrace_libc++_static_libraries_host := \
-	libcutils \
-
-libbacktrace_libc++_ldlibs_host := \
-	-lpthread \
-	-lrt \
-
-libbacktrace_libc++_libc++ := true
-
-module := libbacktrace_libc++
-module_tag := optional
-build_type := target
-build_target := SHARED_LIBRARY
-include $(LOCAL_PATH)/Android.build.mk
-build_type := host
-libbacktrace_libc++_multilib := both
-include $(LOCAL_PATH)/Android.build.mk
-libbacktrace_libc++_multilib :=
-endif
-
 #-------------------------------------------------------------------------
 # The libbacktrace_test library needed by backtrace_test.
 #-------------------------------------------------------------------------
@@ -194,25 +142,8 @@
 LOCAL_SRC_FILES := \
 	BacktraceMap.cpp \
 
-include $(BUILD_HOST_SHARED_LIBRARY)
-
-# Don't build for unbundled branches
-ifeq (,$(TARGET_BUILD_APPS))
-#-------------------------------------------------------------------------
-# The libbacktrace library (libc++)
-#-------------------------------------------------------------------------
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libbacktrace_libc++
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := \
-	BacktraceMap.cpp \
-
 LOCAL_MULTILIB := both
 
 include $(BUILD_HOST_SHARED_LIBRARY)
 
-endif # TARGET_BUILD_APPS
-
 endif # HOST_OS-darwin
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index b016a42..7202704 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -16,13 +16,6 @@
 LOCAL_PATH := $(my-dir)
 include $(CLEAR_VARS)
 
-ifeq ($(TARGET_CPU_SMP),true)
-    targetSmpFlag := -DANDROID_SMP=1
-else
-    targetSmpFlag := -DANDROID_SMP=0
-endif
-hostSmpFlag := -DANDROID_SMP=0
-
 commonSources := \
 	hashmap.c \
 	atomic.c.arm \
@@ -77,7 +70,6 @@
 LOCAL_MODULE := libcutils
 LOCAL_SRC_FILES := $(commonSources) $(commonHostSources) dlmalloc_stubs.c
 LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_CFLAGS += $(hostSmpFlag)
 ifneq ($(HOST_OS),windows)
 LOCAL_CFLAGS += -Werror
 endif
@@ -121,29 +113,40 @@
 LOCAL_SRC_FILES_arm += \
         arch-arm/memset32.S \
 
+# arch-arm/memset32.S does not compile with Clang.
+LOCAL_CLANG_ASFLAGS_arm += -no-integrated-as
+
 LOCAL_SRC_FILES_arm64 += \
         arch-arm64/android_memset.S \
 
+ifndef ARCH_MIPS_REV6
 LOCAL_SRC_FILES_mips += \
         arch-mips/android_memset.c \
 
+LOCAL_CFLAGS_mips += -DHAVE_MEMSET16 -DHAVE_MEMSET32
+endif
+
+# TODO: switch mips64 back to using arch-mips/android_memset.c
+LOCAL_SRC_FILES_mips64 += \
+#       arch-mips/android_memset.c \
+
 LOCAL_SRC_FILES_x86 += \
         arch-x86/android_memset16.S \
         arch-x86/android_memset32.S \
 
 LOCAL_SRC_FILES_x86_64 += \
-        arch-x86_64/android_memset16_SSE2-atom.S \
-        arch-x86_64/android_memset32_SSE2-atom.S \
+        arch-x86_64/android_memset16.S \
+        arch-x86_64/android_memset32.S \
 
 LOCAL_CFLAGS_arm += -DHAVE_MEMSET16 -DHAVE_MEMSET32
 LOCAL_CFLAGS_arm64 += -DHAVE_MEMSET16 -DHAVE_MEMSET32
-LOCAL_CFLAGS_mips += -DHAVE_MEMSET16 -DHAVE_MEMSET32
+#LOCAL_CFLAGS_mips64 += -DHAVE_MEMSET16 -DHAVE_MEMSET32
 LOCAL_CFLAGS_x86 += -DHAVE_MEMSET16 -DHAVE_MEMSET32
 LOCAL_CFLAGS_x86_64 += -DHAVE_MEMSET16 -DHAVE_MEMSET32
 
 LOCAL_C_INCLUDES := $(libcutils_c_includes)
 LOCAL_STATIC_LIBRARIES := liblog
-LOCAL_CFLAGS += $(targetSmpFlag) -Werror
+LOCAL_CFLAGS += -Werror -std=gnu90
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_STATIC_LIBRARY)
 
@@ -153,7 +156,7 @@
 # liblog symbols present in libcutils.
 LOCAL_WHOLE_STATIC_LIBRARIES := libcutils liblog
 LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_CFLAGS += $(targetSmpFlag) -Werror
+LOCAL_CFLAGS += -Werror
 LOCAL_C_INCLUDES := $(libcutils_c_includes)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_SHARED_LIBRARY)
diff --git a/libcutils/android_reboot.c b/libcutils/android_reboot.c
index 5d98295..aa86206 100644
--- a/libcutils/android_reboot.c
+++ b/libcutils/android_reboot.c
@@ -20,6 +20,7 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
+#include <mntent.h>
 #include <stdio.h>
 #include <string.h>
 
@@ -33,37 +34,21 @@
  */
 static int remount_ro_done(void)
 {
-    FILE *f;
-    char mount_dev[256];
-    char mount_dir[256];
-    char mount_type[256];
-    char mount_opts[256];
-    int mount_freq;
-    int mount_passno;
-    int match;
+    FILE* fp;
+    struct mntent* mentry;
     int found_rw_fs = 0;
 
-    f = fopen("/proc/mounts", "r");
-    if (! f) {
-        /* If we can't read /proc/mounts, just give up */
+    if ((fp = setmntent("/proc/mounts", "r")) == NULL) {
+        /* If we can't read /proc/mounts, just give up. */
         return 1;
     }
-
-    do {
-        match = fscanf(f, "%255s %255s %255s %255s %d %d\n",
-                       mount_dev, mount_dir, mount_type,
-                       mount_opts, &mount_freq, &mount_passno);
-        mount_dev[255] = 0;
-        mount_dir[255] = 0;
-        mount_type[255] = 0;
-        mount_opts[255] = 0;
-        if ((match == 6) && !strncmp(mount_dev, "/dev/block", 10) && strstr(mount_opts, "rw,")) {
+    while ((mentry = getmntent(fp)) != NULL) {
+        if (!strncmp(mentry->mnt_fsname, "/dev/block", 10) && strstr(mentry->mnt_opts, "rw,")) {
             found_rw_fs = 1;
             break;
         }
-    } while (match != EOF);
-
-    fclose(f);
+    }
+    endmntent(fp);
 
     return !found_rw_fs;
 }
diff --git a/libcutils/arch-x86/android_memset16.S b/libcutils/arch-x86/android_memset16.S
old mode 100644
new mode 100755
index f8b79bd..cb2ff14
--- a/libcutils/arch-x86/android_memset16.S
+++ b/libcutils/arch-x86/android_memset16.S
@@ -13,13 +13,707 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * Contributed by: Intel Corporation
- */
 
-# include "cache_wrapper.S"
-# undef __i686
-# define USE_AS_ANDROID
-# define sse2_memset16_atom android_memset16
-# include "sse2-memset16-atom.S"
+#include "cache.h"
 
+#ifndef MEMSET
+# define MEMSET		android_memset16
+#endif
+
+#ifndef L
+# define L(label)	.L##label
+#endif
+
+#ifndef ALIGN
+# define ALIGN(n)	.p2align n
+#endif
+
+#ifndef cfi_startproc
+# define cfi_startproc			.cfi_startproc
+#endif
+
+#ifndef cfi_endproc
+# define cfi_endproc			.cfi_endproc
+#endif
+
+#ifndef cfi_rel_offset
+# define cfi_rel_offset(reg, off)	.cfi_rel_offset reg, off
+#endif
+
+#ifndef cfi_restore
+# define cfi_restore(reg)		.cfi_restore reg
+#endif
+
+#ifndef cfi_adjust_cfa_offset
+# define cfi_adjust_cfa_offset(off)	.cfi_adjust_cfa_offset off
+#endif
+
+#ifndef ENTRY
+# define ENTRY(name)			\
+	.type name,  @function; 	\
+	.globl name;			\
+	.p2align 4;			\
+name:					\
+	cfi_startproc
+#endif
+
+#ifndef END
+# define END(name)			\
+	cfi_endproc;			\
+	.size name, .-name
+#endif
+
+#define CFI_PUSH(REG)						\
+  cfi_adjust_cfa_offset (4);					\
+  cfi_rel_offset (REG, 0)
+
+#define CFI_POP(REG)						\
+  cfi_adjust_cfa_offset (-4);					\
+  cfi_restore (REG)
+
+#define PUSH(REG)	pushl REG; CFI_PUSH (REG)
+#define POP(REG)	popl REG; CFI_POP (REG)
+
+#ifdef USE_AS_BZERO16
+# define DEST		PARMS
+# define LEN		DEST+4
+# define SETRTNVAL
+#else
+# define DEST		PARMS
+# define CHR		DEST+4
+# define LEN		CHR+4
+# define SETRTNVAL	movl DEST(%esp), %eax
+#endif
+
+#if (defined SHARED || defined __PIC__)
+# define ENTRANCE	PUSH (%ebx);
+# define RETURN_END	POP (%ebx); ret
+# define RETURN		RETURN_END; CFI_PUSH (%ebx)
+# define PARMS		8		/* Preserve EBX.  */
+# define JMPTBL(I, B)	I - B
+
+/* Load an entry in a jump table into EBX and branch to it.  TABLE is a
+   jump table with relative offsets.   */
+# define BRANCH_TO_JMPTBL_ENTRY(TABLE)				\
+    /* We first load PC into EBX.  */				\
+    call	__x86.get_pc_thunk.bx;				\
+    /* Get the address of the jump table.  */			\
+    add		$(TABLE - .), %ebx;				\
+    /* Get the entry and convert the relative offset to the	\
+       absolute address.  */					\
+    add		(%ebx,%ecx,4), %ebx;				\
+    /* We loaded the jump table and adjuested EDX. Go.  */	\
+    jmp		*%ebx
+
+	.section	.gnu.linkonce.t.__x86.get_pc_thunk.bx,"ax",@progbits
+	.globl	__x86.get_pc_thunk.bx
+	.hidden	__x86.get_pc_thunk.bx
+	ALIGN (4)
+	.type	__x86.get_pc_thunk.bx,@function
+__x86.get_pc_thunk.bx:
+	movl	(%esp), %ebx
+	ret
+#else
+# define ENTRANCE
+# define RETURN_END	ret
+# define RETURN		RETURN_END
+# define PARMS		4
+# define JMPTBL(I, B)	I
+
+/* Branch to an entry in a jump table.  TABLE is a jump table with
+   absolute offsets.  */
+# define BRANCH_TO_JMPTBL_ENTRY(TABLE)				\
+    jmp		*TABLE(,%ecx,4)
+#endif
+
+	.section .text.sse2,"ax",@progbits
+	ALIGN (4)
+ENTRY (MEMSET)
+	ENTRANCE
+
+	movl	LEN(%esp), %ecx
+	shr	$1, %ecx
+#ifdef USE_AS_BZERO16
+	xor	%eax, %eax
+#else
+	movzwl	CHR(%esp), %eax
+	mov	%eax, %edx
+	shl	$16, %eax
+	or	%edx, %eax
+#endif
+	movl	DEST(%esp), %edx
+	cmp	$32, %ecx
+	jae	L(32wordsormore)
+
+L(write_less32words):
+	lea	(%edx, %ecx, 2), %edx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_less32words))
+
+
+	.pushsection .rodata.sse2,"a",@progbits
+	ALIGN (2)
+L(table_less32words):
+	.int	JMPTBL (L(write_0words), L(table_less32words))
+	.int	JMPTBL (L(write_1words), L(table_less32words))
+	.int	JMPTBL (L(write_2words), L(table_less32words))
+	.int	JMPTBL (L(write_3words), L(table_less32words))
+	.int	JMPTBL (L(write_4words), L(table_less32words))
+	.int	JMPTBL (L(write_5words), L(table_less32words))
+	.int	JMPTBL (L(write_6words), L(table_less32words))
+	.int	JMPTBL (L(write_7words), L(table_less32words))
+	.int	JMPTBL (L(write_8words), L(table_less32words))
+	.int	JMPTBL (L(write_9words), L(table_less32words))
+	.int	JMPTBL (L(write_10words), L(table_less32words))
+	.int	JMPTBL (L(write_11words), L(table_less32words))
+	.int	JMPTBL (L(write_12words), L(table_less32words))
+	.int	JMPTBL (L(write_13words), L(table_less32words))
+	.int	JMPTBL (L(write_14words), L(table_less32words))
+	.int	JMPTBL (L(write_15words), L(table_less32words))
+	.int	JMPTBL (L(write_16words), L(table_less32words))
+	.int	JMPTBL (L(write_17words), L(table_less32words))
+	.int	JMPTBL (L(write_18words), L(table_less32words))
+	.int	JMPTBL (L(write_19words), L(table_less32words))
+	.int	JMPTBL (L(write_20words), L(table_less32words))
+	.int	JMPTBL (L(write_21words), L(table_less32words))
+	.int	JMPTBL (L(write_22words), L(table_less32words))
+	.int	JMPTBL (L(write_23words), L(table_less32words))
+	.int	JMPTBL (L(write_24words), L(table_less32words))
+	.int	JMPTBL (L(write_25words), L(table_less32words))
+	.int	JMPTBL (L(write_26words), L(table_less32words))
+	.int	JMPTBL (L(write_27words), L(table_less32words))
+	.int	JMPTBL (L(write_28words), L(table_less32words))
+	.int	JMPTBL (L(write_29words), L(table_less32words))
+	.int	JMPTBL (L(write_30words), L(table_less32words))
+	.int	JMPTBL (L(write_31words), L(table_less32words))
+	.popsection
+
+	ALIGN (4)
+L(write_28words):
+	movl	%eax, -56(%edx)
+	movl	%eax, -52(%edx)
+L(write_24words):
+	movl	%eax, -48(%edx)
+	movl	%eax, -44(%edx)
+L(write_20words):
+	movl	%eax, -40(%edx)
+	movl	%eax, -36(%edx)
+L(write_16words):
+	movl	%eax, -32(%edx)
+	movl	%eax, -28(%edx)
+L(write_12words):
+	movl	%eax, -24(%edx)
+	movl	%eax, -20(%edx)
+L(write_8words):
+	movl	%eax, -16(%edx)
+	movl	%eax, -12(%edx)
+L(write_4words):
+	movl	%eax, -8(%edx)
+	movl	%eax, -4(%edx)
+L(write_0words):
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+L(write_29words):
+	movl	%eax, -58(%edx)
+	movl	%eax, -54(%edx)
+L(write_25words):
+	movl	%eax, -50(%edx)
+	movl	%eax, -46(%edx)
+L(write_21words):
+	movl	%eax, -42(%edx)
+	movl	%eax, -38(%edx)
+L(write_17words):
+	movl	%eax, -34(%edx)
+	movl	%eax, -30(%edx)
+L(write_13words):
+	movl	%eax, -26(%edx)
+	movl	%eax, -22(%edx)
+L(write_9words):
+	movl	%eax, -18(%edx)
+	movl	%eax, -14(%edx)
+L(write_5words):
+	movl	%eax, -10(%edx)
+	movl	%eax, -6(%edx)
+L(write_1words):
+	mov	%ax, -2(%edx)
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+L(write_30words):
+	movl	%eax, -60(%edx)
+	movl	%eax, -56(%edx)
+L(write_26words):
+	movl	%eax, -52(%edx)
+	movl	%eax, -48(%edx)
+L(write_22words):
+	movl	%eax, -44(%edx)
+	movl	%eax, -40(%edx)
+L(write_18words):
+	movl	%eax, -36(%edx)
+	movl	%eax, -32(%edx)
+L(write_14words):
+	movl	%eax, -28(%edx)
+	movl	%eax, -24(%edx)
+L(write_10words):
+	movl	%eax, -20(%edx)
+	movl	%eax, -16(%edx)
+L(write_6words):
+	movl	%eax, -12(%edx)
+	movl	%eax, -8(%edx)
+L(write_2words):
+	movl	%eax, -4(%edx)
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+L(write_31words):
+	movl	%eax, -62(%edx)
+	movl	%eax, -58(%edx)
+L(write_27words):
+	movl	%eax, -54(%edx)
+	movl	%eax, -50(%edx)
+L(write_23words):
+	movl	%eax, -46(%edx)
+	movl	%eax, -42(%edx)
+L(write_19words):
+	movl	%eax, -38(%edx)
+	movl	%eax, -34(%edx)
+L(write_15words):
+	movl	%eax, -30(%edx)
+	movl	%eax, -26(%edx)
+L(write_11words):
+	movl	%eax, -22(%edx)
+	movl	%eax, -18(%edx)
+L(write_7words):
+	movl	%eax, -14(%edx)
+	movl	%eax, -10(%edx)
+L(write_3words):
+	movl	%eax, -6(%edx)
+	movw	%ax, -2(%edx)
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+
+L(32wordsormore):
+	shl	$1, %ecx
+	test	$0x01, %edx
+	jz	L(aligned2bytes)
+	mov	%eax, (%edx)
+	mov	%eax, -4(%edx, %ecx)
+	sub	$2, %ecx
+	add	$1, %edx
+	rol	$8, %eax
+L(aligned2bytes):
+#ifdef USE_AS_BZERO16
+	pxor	%xmm0, %xmm0
+#else
+	movd	%eax, %xmm0
+	pshufd	$0, %xmm0, %xmm0
+#endif
+	testl	$0xf, %edx
+	jz	L(aligned_16)
+/* ECX > 32 and EDX is not 16 byte aligned.  */
+L(not_aligned_16):
+	movdqu	%xmm0, (%edx)
+	movl	%edx, %eax
+	and	$-16, %edx
+	add	$16, %edx
+	sub	%edx, %eax
+	add	%eax, %ecx
+	movd	%xmm0, %eax
+
+	ALIGN (4)
+L(aligned_16):
+	cmp	$128, %ecx
+	jae	L(128bytesormore)
+
+L(aligned_16_less128bytes):
+	add	%ecx, %edx
+	shr	$1, %ecx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
+
+	ALIGN (4)
+L(128bytesormore):
+#ifdef SHARED_CACHE_SIZE
+	PUSH (%ebx)
+	mov	$SHARED_CACHE_SIZE, %ebx
+#else
+# if (defined SHARED || defined __PIC__)
+	call	__x86.get_pc_thunk.bx
+	add	$_GLOBAL_OFFSET_TABLE_, %ebx
+	mov	__x86_shared_cache_size@GOTOFF(%ebx), %ebx
+# else
+	PUSH (%ebx)
+	mov	__x86_shared_cache_size, %ebx
+# endif
+#endif
+	cmp	%ebx, %ecx
+	jae	L(128bytesormore_nt_start)
+
+
+#ifdef DATA_CACHE_SIZE
+	POP (%ebx)
+# define RESTORE_EBX_STATE CFI_PUSH (%ebx)
+	cmp	$DATA_CACHE_SIZE, %ecx
+#else
+# if (defined SHARED || defined __PIC__)
+#  define RESTORE_EBX_STATE
+	call	__x86.get_pc_thunk.bx
+	add	$_GLOBAL_OFFSET_TABLE_, %ebx
+	cmp	__x86_data_cache_size@GOTOFF(%ebx), %ecx
+# else
+	POP (%ebx)
+#  define RESTORE_EBX_STATE CFI_PUSH (%ebx)
+	cmp	__x86_data_cache_size, %ecx
+# endif
+#endif
+
+	jae	L(128bytes_L2_normal)
+	subl	$128, %ecx
+L(128bytesormore_normal):
+	sub	$128, %ecx
+	movdqa	%xmm0, (%edx)
+	movdqa	%xmm0, 0x10(%edx)
+	movdqa	%xmm0, 0x20(%edx)
+	movdqa	%xmm0, 0x30(%edx)
+	movdqa	%xmm0, 0x40(%edx)
+	movdqa	%xmm0, 0x50(%edx)
+	movdqa	%xmm0, 0x60(%edx)
+	movdqa	%xmm0, 0x70(%edx)
+	lea	128(%edx), %edx
+	jb	L(128bytesless_normal)
+
+
+	sub	$128, %ecx
+	movdqa	%xmm0, (%edx)
+	movdqa	%xmm0, 0x10(%edx)
+	movdqa	%xmm0, 0x20(%edx)
+	movdqa	%xmm0, 0x30(%edx)
+	movdqa	%xmm0, 0x40(%edx)
+	movdqa	%xmm0, 0x50(%edx)
+	movdqa	%xmm0, 0x60(%edx)
+	movdqa	%xmm0, 0x70(%edx)
+	lea	128(%edx), %edx
+	jae	L(128bytesormore_normal)
+
+L(128bytesless_normal):
+	lea	128(%ecx), %ecx
+	add	%ecx, %edx
+	shr	$1, %ecx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
+
+	ALIGN (4)
+L(128bytes_L2_normal):
+	prefetcht0	0x380(%edx)
+	prefetcht0	0x3c0(%edx)
+	sub	$128, %ecx
+	movdqa	%xmm0, (%edx)
+	movaps	%xmm0, 0x10(%edx)
+	movaps	%xmm0, 0x20(%edx)
+	movaps	%xmm0, 0x30(%edx)
+	movaps	%xmm0, 0x40(%edx)
+	movaps	%xmm0, 0x50(%edx)
+	movaps	%xmm0, 0x60(%edx)
+	movaps	%xmm0, 0x70(%edx)
+	add	$128, %edx
+	cmp	$128, %ecx
+	jae	L(128bytes_L2_normal)
+
+L(128bytesless_L2_normal):
+	add	%ecx, %edx
+	shr	$1, %ecx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
+
+	RESTORE_EBX_STATE
+L(128bytesormore_nt_start):
+	sub	%ebx, %ecx
+	mov	%ebx, %eax
+	and	$0x7f, %eax
+	add	%eax, %ecx
+	movd	%xmm0, %eax
+	ALIGN (4)
+L(128bytesormore_shared_cache_loop):
+	prefetcht0	0x3c0(%edx)
+	prefetcht0	0x380(%edx)
+	sub	$0x80, %ebx
+	movdqa	%xmm0, (%edx)
+	movdqa	%xmm0, 0x10(%edx)
+	movdqa	%xmm0, 0x20(%edx)
+	movdqa	%xmm0, 0x30(%edx)
+	movdqa	%xmm0, 0x40(%edx)
+	movdqa	%xmm0, 0x50(%edx)
+	movdqa	%xmm0, 0x60(%edx)
+	movdqa	%xmm0, 0x70(%edx)
+	add	$0x80, %edx
+	cmp	$0x80, %ebx
+	jae	L(128bytesormore_shared_cache_loop)
+	cmp	$0x80, %ecx
+	jb	L(shared_cache_loop_end)
+	ALIGN (4)
+L(128bytesormore_nt):
+	sub	$0x80, %ecx
+	movntdq	%xmm0, (%edx)
+	movntdq	%xmm0, 0x10(%edx)
+	movntdq	%xmm0, 0x20(%edx)
+	movntdq	%xmm0, 0x30(%edx)
+	movntdq	%xmm0, 0x40(%edx)
+	movntdq	%xmm0, 0x50(%edx)
+	movntdq	%xmm0, 0x60(%edx)
+	movntdq	%xmm0, 0x70(%edx)
+	add	$0x80, %edx
+	cmp	$0x80, %ecx
+	jae	L(128bytesormore_nt)
+	sfence
+L(shared_cache_loop_end):
+#if defined DATA_CACHE_SIZE || !(defined SHARED || defined __PIC__)
+	POP (%ebx)
+#endif
+	add	%ecx, %edx
+	shr	$1, %ecx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
+
+
+	.pushsection .rodata.sse2,"a",@progbits
+	ALIGN (2)
+L(table_16_128bytes):
+	.int	JMPTBL (L(aligned_16_0bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_2bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_4bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_6bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_8bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_10bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_12bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_14bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_16bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_18bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_20bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_22bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_24bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_26bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_28bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_30bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_32bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_34bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_36bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_38bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_40bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_42bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_44bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_46bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_48bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_50bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_52bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_54bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_56bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_58bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_60bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_62bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_64bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_66bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_68bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_70bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_72bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_74bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_76bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_78bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_80bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_82bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_84bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_86bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_88bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_90bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_92bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_94bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_96bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_98bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_100bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_102bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_104bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_106bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_108bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_110bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_112bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_114bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_116bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_118bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_120bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_122bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_124bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_126bytes), L(table_16_128bytes))
+	.popsection
+
+
+	ALIGN (4)
+L(aligned_16_112bytes):
+	movdqa	%xmm0, -112(%edx)
+L(aligned_16_96bytes):
+	movdqa	%xmm0, -96(%edx)
+L(aligned_16_80bytes):
+	movdqa	%xmm0, -80(%edx)
+L(aligned_16_64bytes):
+	movdqa	%xmm0, -64(%edx)
+L(aligned_16_48bytes):
+	movdqa	%xmm0, -48(%edx)
+L(aligned_16_32bytes):
+	movdqa	%xmm0, -32(%edx)
+L(aligned_16_16bytes):
+	movdqa	%xmm0, -16(%edx)
+L(aligned_16_0bytes):
+	SETRTNVAL
+	RETURN
+
+
+	ALIGN (4)
+L(aligned_16_114bytes):
+	movdqa	%xmm0, -114(%edx)
+L(aligned_16_98bytes):
+	movdqa	%xmm0, -98(%edx)
+L(aligned_16_82bytes):
+	movdqa	%xmm0, -82(%edx)
+L(aligned_16_66bytes):
+	movdqa	%xmm0, -66(%edx)
+L(aligned_16_50bytes):
+	movdqa	%xmm0, -50(%edx)
+L(aligned_16_34bytes):
+	movdqa	%xmm0, -34(%edx)
+L(aligned_16_18bytes):
+	movdqa	%xmm0, -18(%edx)
+L(aligned_16_2bytes):
+	movw	%ax, -2(%edx)
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+L(aligned_16_116bytes):
+	movdqa	%xmm0, -116(%edx)
+L(aligned_16_100bytes):
+	movdqa	%xmm0, -100(%edx)
+L(aligned_16_84bytes):
+	movdqa	%xmm0, -84(%edx)
+L(aligned_16_68bytes):
+	movdqa	%xmm0, -68(%edx)
+L(aligned_16_52bytes):
+	movdqa	%xmm0, -52(%edx)
+L(aligned_16_36bytes):
+	movdqa	%xmm0, -36(%edx)
+L(aligned_16_20bytes):
+	movdqa	%xmm0, -20(%edx)
+L(aligned_16_4bytes):
+	movl	%eax, -4(%edx)
+	SETRTNVAL
+	RETURN
+
+
+	ALIGN (4)
+L(aligned_16_118bytes):
+	movdqa	%xmm0, -118(%edx)
+L(aligned_16_102bytes):
+	movdqa	%xmm0, -102(%edx)
+L(aligned_16_86bytes):
+	movdqa	%xmm0, -86(%edx)
+L(aligned_16_70bytes):
+	movdqa	%xmm0, -70(%edx)
+L(aligned_16_54bytes):
+	movdqa	%xmm0, -54(%edx)
+L(aligned_16_38bytes):
+	movdqa	%xmm0, -38(%edx)
+L(aligned_16_22bytes):
+	movdqa	%xmm0, -22(%edx)
+L(aligned_16_6bytes):
+	movl	%eax, -6(%edx)
+	movw	%ax, -2(%edx)
+	SETRTNVAL
+	RETURN
+
+
+	ALIGN (4)
+L(aligned_16_120bytes):
+	movdqa	%xmm0, -120(%edx)
+L(aligned_16_104bytes):
+	movdqa	%xmm0, -104(%edx)
+L(aligned_16_88bytes):
+	movdqa	%xmm0, -88(%edx)
+L(aligned_16_72bytes):
+	movdqa	%xmm0, -72(%edx)
+L(aligned_16_56bytes):
+	movdqa	%xmm0, -56(%edx)
+L(aligned_16_40bytes):
+	movdqa	%xmm0, -40(%edx)
+L(aligned_16_24bytes):
+	movdqa	%xmm0, -24(%edx)
+L(aligned_16_8bytes):
+	movq	%xmm0, -8(%edx)
+	SETRTNVAL
+	RETURN
+
+
+	ALIGN (4)
+L(aligned_16_122bytes):
+	movdqa	%xmm0, -122(%edx)
+L(aligned_16_106bytes):
+	movdqa	%xmm0, -106(%edx)
+L(aligned_16_90bytes):
+	movdqa	%xmm0, -90(%edx)
+L(aligned_16_74bytes):
+	movdqa	%xmm0, -74(%edx)
+L(aligned_16_58bytes):
+	movdqa	%xmm0, -58(%edx)
+L(aligned_16_42bytes):
+	movdqa	%xmm0, -42(%edx)
+L(aligned_16_26bytes):
+	movdqa	%xmm0, -26(%edx)
+L(aligned_16_10bytes):
+	movq	%xmm0, -10(%edx)
+	movw	%ax, -2(%edx)
+	SETRTNVAL
+	RETURN
+
+
+	ALIGN (4)
+L(aligned_16_124bytes):
+	movdqa	%xmm0, -124(%edx)
+L(aligned_16_108bytes):
+	movdqa	%xmm0, -108(%edx)
+L(aligned_16_92bytes):
+	movdqa	%xmm0, -92(%edx)
+L(aligned_16_76bytes):
+	movdqa	%xmm0, -76(%edx)
+L(aligned_16_60bytes):
+	movdqa	%xmm0, -60(%edx)
+L(aligned_16_44bytes):
+	movdqa	%xmm0, -44(%edx)
+L(aligned_16_28bytes):
+	movdqa	%xmm0, -28(%edx)
+L(aligned_16_12bytes):
+	movq	%xmm0, -12(%edx)
+	movl	%eax, -4(%edx)
+	SETRTNVAL
+	RETURN
+
+
+	ALIGN (4)
+L(aligned_16_126bytes):
+	movdqa	%xmm0, -126(%edx)
+L(aligned_16_110bytes):
+	movdqa	%xmm0, -110(%edx)
+L(aligned_16_94bytes):
+	movdqa	%xmm0, -94(%edx)
+L(aligned_16_78bytes):
+	movdqa	%xmm0, -78(%edx)
+L(aligned_16_62bytes):
+	movdqa	%xmm0, -62(%edx)
+L(aligned_16_46bytes):
+	movdqa	%xmm0, -46(%edx)
+L(aligned_16_30bytes):
+	movdqa	%xmm0, -30(%edx)
+L(aligned_16_14bytes):
+	movq	%xmm0, -14(%edx)
+	movl	%eax, -6(%edx)
+	movw	%ax, -2(%edx)
+	SETRTNVAL
+	RETURN
+
+END (MEMSET)
diff --git a/libcutils/arch-x86/android_memset32.S b/libcutils/arch-x86/android_memset32.S
old mode 100644
new mode 100755
index 6249fce..f4326dc
--- a/libcutils/arch-x86/android_memset32.S
+++ b/libcutils/arch-x86/android_memset32.S
@@ -13,13 +13,498 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * Contributed by: Intel Corporation
- */
 
-# include "cache_wrapper.S"
-# undef __i686
-# define USE_AS_ANDROID
-# define sse2_memset32_atom android_memset32
-# include "sse2-memset32-atom.S"
+#include "cache.h"
 
+#ifndef MEMSET
+# define MEMSET 	android_memset32
+#endif
+
+#ifndef L
+# define L(label)	.L##label
+#endif
+
+#ifndef ALIGN
+# define ALIGN(n)	.p2align n
+#endif
+
+#ifndef cfi_startproc
+# define cfi_startproc			.cfi_startproc
+#endif
+
+#ifndef cfi_endproc
+# define cfi_endproc			.cfi_endproc
+#endif
+
+#ifndef cfi_rel_offset
+# define cfi_rel_offset(reg, off)	.cfi_rel_offset reg, off
+#endif
+
+#ifndef cfi_restore
+# define cfi_restore(reg)		.cfi_restore reg
+#endif
+
+#ifndef cfi_adjust_cfa_offset
+# define cfi_adjust_cfa_offset(off)	.cfi_adjust_cfa_offset off
+#endif
+
+#ifndef ENTRY
+# define ENTRY(name)			\
+	.type name,  @function; 	\
+	.globl name;			\
+	.p2align 4;			\
+name:					\
+	cfi_startproc
+#endif
+
+#ifndef END
+# define END(name)			\
+	cfi_endproc;			\
+	.size name, .-name
+#endif
+
+#define CFI_PUSH(REG)						\
+  cfi_adjust_cfa_offset (4);					\
+  cfi_rel_offset (REG, 0)
+
+#define CFI_POP(REG)						\
+  cfi_adjust_cfa_offset (-4);					\
+  cfi_restore (REG)
+
+#define PUSH(REG)	pushl REG; CFI_PUSH (REG)
+#define POP(REG)	popl REG; CFI_POP (REG)
+
+#ifdef USE_AS_BZERO32
+# define DEST		PARMS
+# define LEN		DEST+4
+# define SETRTNVAL
+#else
+# define DEST		PARMS
+# define DWDS		DEST+4
+# define LEN		DWDS+4
+# define SETRTNVAL	movl DEST(%esp), %eax
+#endif
+
+#if (defined SHARED || defined __PIC__)
+# define ENTRANCE	PUSH (%ebx);
+# define RETURN_END	POP (%ebx); ret
+# define RETURN		RETURN_END; CFI_PUSH (%ebx)
+# define PARMS		8		/* Preserve EBX.  */
+# define JMPTBL(I, B)	I - B
+
+/* Load an entry in a jump table into EBX and branch to it.  TABLE is a
+   jump table with relative offsets.   */
+# define BRANCH_TO_JMPTBL_ENTRY(TABLE)				\
+    /* We first load PC into EBX.  */				\
+    call	__x86.get_pc_thunk.bx;				\
+    /* Get the address of the jump table.  */			\
+    add		$(TABLE - .), %ebx;				\
+    /* Get the entry and convert the relative offset to the	\
+       absolute address.  */					\
+    add		(%ebx,%ecx,4), %ebx;				\
+    /* We loaded the jump table and adjuested EDX. Go.  */	\
+    jmp		*%ebx
+
+	.section	.gnu.linkonce.t.__x86.get_pc_thunk.bx,"ax",@progbits
+	.globl	__x86.get_pc_thunk.bx
+	.hidden	__x86.get_pc_thunk.bx
+	ALIGN (4)
+	.type	__x86.get_pc_thunk.bx,@function
+__x86.get_pc_thunk.bx:
+	movl	(%esp), %ebx
+	ret
+#else
+# define ENTRANCE
+# define RETURN_END	ret
+# define RETURN		RETURN_END
+# define PARMS		4
+# define JMPTBL(I, B)	I
+
+/* Branch to an entry in a jump table.  TABLE is a jump table with
+   absolute offsets.  */
+# define BRANCH_TO_JMPTBL_ENTRY(TABLE)				\
+    jmp		*TABLE(,%ecx,4)
+#endif
+
+	.section .text.sse2,"ax",@progbits
+	ALIGN (4)
+ENTRY (MEMSET)
+	ENTRANCE
+
+	movl	LEN(%esp), %ecx
+	shr     $2, %ecx
+#ifdef USE_AS_BZERO32
+	xor	%eax, %eax
+#else
+	mov	DWDS(%esp), %eax
+	mov	%eax, %edx
+#endif
+	movl	DEST(%esp), %edx
+	cmp	$16, %ecx
+	jae	L(16dbwordsormore)
+
+L(write_less16dbwords):
+	lea	(%edx, %ecx, 4), %edx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_less16dbwords))
+
+	.pushsection .rodata.sse2,"a",@progbits
+	ALIGN (2)
+L(table_less16dbwords):
+	.int	JMPTBL (L(write_0dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_1dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_2dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_3dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_4dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_5dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_6dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_7dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_8dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_9dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_10dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_11dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_12dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_13dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_14dbwords), L(table_less16dbwords))
+	.int	JMPTBL (L(write_15dbwords), L(table_less16dbwords))
+	.popsection
+
+	ALIGN (4)
+L(write_15dbwords):
+	movl	%eax, -60(%edx)
+L(write_14dbwords):
+	movl	%eax, -56(%edx)
+L(write_13dbwords):
+	movl	%eax, -52(%edx)
+L(write_12dbwords):
+	movl	%eax, -48(%edx)
+L(write_11dbwords):
+	movl	%eax, -44(%edx)
+L(write_10dbwords):
+	movl	%eax, -40(%edx)
+L(write_9dbwords):
+	movl	%eax, -36(%edx)
+L(write_8dbwords):
+	movl	%eax, -32(%edx)
+L(write_7dbwords):
+	movl	%eax, -28(%edx)
+L(write_6dbwords):
+	movl	%eax, -24(%edx)
+L(write_5dbwords):
+	movl	%eax, -20(%edx)
+L(write_4dbwords):
+	movl	%eax, -16(%edx)
+L(write_3dbwords):
+	movl	%eax, -12(%edx)
+L(write_2dbwords):
+	movl	%eax, -8(%edx)
+L(write_1dbwords):
+	movl	%eax, -4(%edx)
+L(write_0dbwords):
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+L(16dbwordsormore):
+	test	$3, %edx
+	jz	L(aligned4bytes)
+	mov	%eax, (%edx)
+	mov	%eax, -4(%edx, %ecx, 4)
+	sub	$1, %ecx
+	rol	$24, %eax
+	add	$1, %edx
+	test	$3, %edx
+	jz	L(aligned4bytes)
+	ror	$8, %eax
+	add	$1, %edx
+	test	$3, %edx
+	jz	L(aligned4bytes)
+	ror	$8, %eax
+	add	$1, %edx
+L(aligned4bytes):
+	shl	$2, %ecx
+
+#ifdef USE_AS_BZERO32
+	pxor	%xmm0, %xmm0
+#else
+	movd	%eax, %xmm0
+	pshufd	$0, %xmm0, %xmm0
+#endif
+	testl	$0xf, %edx
+	jz	L(aligned_16)
+/* ECX > 32 and EDX is not 16 byte aligned.  */
+L(not_aligned_16):
+	movdqu	%xmm0, (%edx)
+	movl	%edx, %eax
+	and	$-16, %edx
+	add	$16, %edx
+	sub	%edx, %eax
+	add	%eax, %ecx
+	movd	%xmm0, %eax
+	ALIGN (4)
+L(aligned_16):
+	cmp	$128, %ecx
+	jae	L(128bytesormore)
+
+L(aligned_16_less128bytes):
+	add	%ecx, %edx
+	shr	$2, %ecx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
+
+	ALIGN (4)
+L(128bytesormore):
+#ifdef SHARED_CACHE_SIZE
+	PUSH (%ebx)
+	mov	$SHARED_CACHE_SIZE, %ebx
+#else
+# if (defined SHARED || defined __PIC__)
+	call	__x86.get_pc_thunk.bx
+	add	$_GLOBAL_OFFSET_TABLE_, %ebx
+	mov	__x86_shared_cache_size@GOTOFF(%ebx), %ebx
+# else
+	PUSH (%ebx)
+	mov	__x86_shared_cache_size, %ebx
+# endif
+#endif
+	cmp	%ebx, %ecx
+	jae	L(128bytesormore_nt_start)
+
+#ifdef DATA_CACHE_SIZE
+	POP (%ebx)
+# define RESTORE_EBX_STATE CFI_PUSH (%ebx)
+	cmp	$DATA_CACHE_SIZE, %ecx
+#else
+# if (defined SHARED || defined __PIC__)
+#  define RESTORE_EBX_STATE
+	call	__x86.get_pc_thunk.bx
+	add	$_GLOBAL_OFFSET_TABLE_, %ebx
+	cmp	__x86_data_cache_size@GOTOFF(%ebx), %ecx
+# else
+	POP (%ebx)
+#  define RESTORE_EBX_STATE CFI_PUSH (%ebx)
+	cmp	__x86_data_cache_size, %ecx
+# endif
+#endif
+
+	jae	L(128bytes_L2_normal)
+	subl	$128, %ecx
+L(128bytesormore_normal):
+	sub	$128, %ecx
+	movdqa	%xmm0, (%edx)
+	movdqa	%xmm0, 0x10(%edx)
+	movdqa	%xmm0, 0x20(%edx)
+	movdqa	%xmm0, 0x30(%edx)
+	movdqa	%xmm0, 0x40(%edx)
+	movdqa	%xmm0, 0x50(%edx)
+	movdqa	%xmm0, 0x60(%edx)
+	movdqa	%xmm0, 0x70(%edx)
+	lea	128(%edx), %edx
+	jb	L(128bytesless_normal)
+
+
+	sub	$128, %ecx
+	movdqa	%xmm0, (%edx)
+	movdqa	%xmm0, 0x10(%edx)
+	movdqa	%xmm0, 0x20(%edx)
+	movdqa	%xmm0, 0x30(%edx)
+	movdqa	%xmm0, 0x40(%edx)
+	movdqa	%xmm0, 0x50(%edx)
+	movdqa	%xmm0, 0x60(%edx)
+	movdqa	%xmm0, 0x70(%edx)
+	lea	128(%edx), %edx
+	jae	L(128bytesormore_normal)
+
+L(128bytesless_normal):
+	lea	128(%ecx), %ecx
+	add	%ecx, %edx
+	shr	$2, %ecx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
+
+	ALIGN (4)
+L(128bytes_L2_normal):
+	prefetcht0	0x380(%edx)
+	prefetcht0	0x3c0(%edx)
+	sub	$128, %ecx
+	movdqa	%xmm0, (%edx)
+	movaps	%xmm0, 0x10(%edx)
+	movaps	%xmm0, 0x20(%edx)
+	movaps	%xmm0, 0x30(%edx)
+	movaps	%xmm0, 0x40(%edx)
+	movaps	%xmm0, 0x50(%edx)
+	movaps	%xmm0, 0x60(%edx)
+	movaps	%xmm0, 0x70(%edx)
+	add	$128, %edx
+	cmp	$128, %ecx
+	jae	L(128bytes_L2_normal)
+
+L(128bytesless_L2_normal):
+	add	%ecx, %edx
+	shr	$2, %ecx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
+
+	RESTORE_EBX_STATE
+L(128bytesormore_nt_start):
+	sub	%ebx, %ecx
+	mov	%ebx, %eax
+	and	$0x7f, %eax
+	add	%eax, %ecx
+	movd	%xmm0, %eax
+	ALIGN (4)
+L(128bytesormore_shared_cache_loop):
+	prefetcht0	0x3c0(%edx)
+	prefetcht0	0x380(%edx)
+	sub	$0x80, %ebx
+	movdqa	%xmm0, (%edx)
+	movdqa	%xmm0, 0x10(%edx)
+	movdqa	%xmm0, 0x20(%edx)
+	movdqa	%xmm0, 0x30(%edx)
+	movdqa	%xmm0, 0x40(%edx)
+	movdqa	%xmm0, 0x50(%edx)
+	movdqa	%xmm0, 0x60(%edx)
+	movdqa	%xmm0, 0x70(%edx)
+	add	$0x80, %edx
+	cmp	$0x80, %ebx
+	jae	L(128bytesormore_shared_cache_loop)
+	cmp	$0x80, %ecx
+	jb	L(shared_cache_loop_end)
+
+	ALIGN (4)
+L(128bytesormore_nt):
+	sub	$0x80, %ecx
+	movntdq	%xmm0, (%edx)
+	movntdq	%xmm0, 0x10(%edx)
+	movntdq	%xmm0, 0x20(%edx)
+	movntdq	%xmm0, 0x30(%edx)
+	movntdq	%xmm0, 0x40(%edx)
+	movntdq	%xmm0, 0x50(%edx)
+	movntdq	%xmm0, 0x60(%edx)
+	movntdq	%xmm0, 0x70(%edx)
+	add	$0x80, %edx
+	cmp	$0x80, %ecx
+	jae	L(128bytesormore_nt)
+	sfence
+L(shared_cache_loop_end):
+#if defined DATA_CACHE_SIZE || !(defined SHARED || defined __PIC__)
+	POP (%ebx)
+#endif
+	add	%ecx, %edx
+	shr	$2, %ecx
+	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
+
+	.pushsection .rodata.sse2,"a",@progbits
+	ALIGN (2)
+L(table_16_128bytes):
+	.int	JMPTBL (L(aligned_16_0bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_4bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_8bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_12bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_16bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_20bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_24bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_28bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_32bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_36bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_40bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_44bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_48bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_52bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_56bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_60bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_64bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_68bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_72bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_76bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_80bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_84bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_88bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_92bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_96bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_100bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_104bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_108bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_112bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_116bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_120bytes), L(table_16_128bytes))
+	.int	JMPTBL (L(aligned_16_124bytes), L(table_16_128bytes))
+	.popsection
+
+	ALIGN (4)
+L(aligned_16_112bytes):
+	movdqa	%xmm0, -112(%edx)
+L(aligned_16_96bytes):
+	movdqa	%xmm0, -96(%edx)
+L(aligned_16_80bytes):
+	movdqa	%xmm0, -80(%edx)
+L(aligned_16_64bytes):
+	movdqa	%xmm0, -64(%edx)
+L(aligned_16_48bytes):
+	movdqa	%xmm0, -48(%edx)
+L(aligned_16_32bytes):
+	movdqa	%xmm0, -32(%edx)
+L(aligned_16_16bytes):
+	movdqa	%xmm0, -16(%edx)
+L(aligned_16_0bytes):
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+L(aligned_16_116bytes):
+	movdqa	%xmm0, -116(%edx)
+L(aligned_16_100bytes):
+	movdqa	%xmm0, -100(%edx)
+L(aligned_16_84bytes):
+	movdqa	%xmm0, -84(%edx)
+L(aligned_16_68bytes):
+	movdqa	%xmm0, -68(%edx)
+L(aligned_16_52bytes):
+	movdqa	%xmm0, -52(%edx)
+L(aligned_16_36bytes):
+	movdqa	%xmm0, -36(%edx)
+L(aligned_16_20bytes):
+	movdqa	%xmm0, -20(%edx)
+L(aligned_16_4bytes):
+	movl	%eax, -4(%edx)
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+L(aligned_16_120bytes):
+	movdqa	%xmm0, -120(%edx)
+L(aligned_16_104bytes):
+	movdqa	%xmm0, -104(%edx)
+L(aligned_16_88bytes):
+	movdqa	%xmm0, -88(%edx)
+L(aligned_16_72bytes):
+	movdqa	%xmm0, -72(%edx)
+L(aligned_16_56bytes):
+	movdqa	%xmm0, -56(%edx)
+L(aligned_16_40bytes):
+	movdqa	%xmm0, -40(%edx)
+L(aligned_16_24bytes):
+	movdqa	%xmm0, -24(%edx)
+L(aligned_16_8bytes):
+	movq	%xmm0, -8(%edx)
+	SETRTNVAL
+	RETURN
+
+	ALIGN (4)
+L(aligned_16_124bytes):
+	movdqa	%xmm0, -124(%edx)
+L(aligned_16_108bytes):
+	movdqa	%xmm0, -108(%edx)
+L(aligned_16_92bytes):
+	movdqa	%xmm0, -92(%edx)
+L(aligned_16_76bytes):
+	movdqa	%xmm0, -76(%edx)
+L(aligned_16_60bytes):
+	movdqa	%xmm0, -60(%edx)
+L(aligned_16_44bytes):
+	movdqa	%xmm0, -44(%edx)
+L(aligned_16_28bytes):
+	movdqa	%xmm0, -28(%edx)
+L(aligned_16_12bytes):
+	movq	%xmm0, -12(%edx)
+	movl	%eax, -4(%edx)
+	SETRTNVAL
+	RETURN
+
+END (MEMSET)
diff --git a/libcutils/arch-x86/cache_wrapper.S b/libcutils/arch-x86/cache.h
similarity index 95%
rename from libcutils/arch-x86/cache_wrapper.S
rename to libcutils/arch-x86/cache.h
index 9eee25c..1c22fea 100644
--- a/libcutils/arch-x86/cache_wrapper.S
+++ b/libcutils/arch-x86/cache.h
@@ -13,9 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * Contributed by: Intel Corporation
- */
 
 #if defined(__slm__)
 /* Values are optimized for Silvermont */
diff --git a/libcutils/arch-x86/sse2-memset16-atom.S b/libcutils/arch-x86/sse2-memset16-atom.S
deleted file mode 100755
index c2a762b..0000000
--- a/libcutils/arch-x86/sse2-memset16-atom.S
+++ /dev/null
@@ -1,722 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-/*
- * Contributed by: Intel Corporation
- */
-
-#ifndef L
-# define L(label)	.L##label
-#endif
-
-#ifndef ALIGN
-# define ALIGN(n)	.p2align n
-#endif
-
-#ifndef cfi_startproc
-# define cfi_startproc			.cfi_startproc
-#endif
-
-#ifndef cfi_endproc
-# define cfi_endproc			.cfi_endproc
-#endif
-
-#ifndef cfi_rel_offset
-# define cfi_rel_offset(reg, off)	.cfi_rel_offset reg, off
-#endif
-
-#ifndef cfi_restore
-# define cfi_restore(reg)		.cfi_restore reg
-#endif
-
-#ifndef cfi_adjust_cfa_offset
-# define cfi_adjust_cfa_offset(off)	.cfi_adjust_cfa_offset off
-#endif
-
-#ifndef ENTRY
-# define ENTRY(name)			\
-	.type name,  @function; 	\
-	.globl name;			\
-	.p2align 4;			\
-name:					\
-	cfi_startproc
-#endif
-
-#ifndef END
-# define END(name)			\
-	cfi_endproc;			\
-	.size name, .-name
-#endif
-
-#define CFI_PUSH(REG)						\
-  cfi_adjust_cfa_offset (4);					\
-  cfi_rel_offset (REG, 0)
-
-#define CFI_POP(REG)						\
-  cfi_adjust_cfa_offset (-4);					\
-  cfi_restore (REG)
-
-#define PUSH(REG)	pushl REG; CFI_PUSH (REG)
-#define POP(REG)	popl REG; CFI_POP (REG)
-
-#ifdef USE_AS_BZERO16
-# define DEST		PARMS
-# define LEN		DEST+4
-#else
-# define DEST		PARMS
-# define CHR		DEST+4
-# define LEN		CHR+4
-#endif
-
-#if 1
-# define SETRTNVAL
-#else
-# define SETRTNVAL	movl DEST(%esp), %eax
-#endif
-
-#if (defined SHARED || defined __PIC__)
-# define ENTRANCE	PUSH (%ebx);
-# define RETURN_END	POP (%ebx); ret
-# define RETURN		RETURN_END; CFI_PUSH (%ebx)
-# define PARMS		8		/* Preserve EBX.  */
-# define JMPTBL(I, B)	I - B
-
-/* Load an entry in a jump table into EBX and branch to it.  TABLE is a
-   jump table with relative offsets.   */
-# define BRANCH_TO_JMPTBL_ENTRY(TABLE)				\
-    /* We first load PC into EBX.  */				\
-    call	__i686.get_pc_thunk.bx;				\
-    /* Get the address of the jump table.  */			\
-    add		$(TABLE - .), %ebx;				\
-    /* Get the entry and convert the relative offset to the	\
-       absolute address.  */					\
-    add		(%ebx,%ecx,4), %ebx;				\
-    /* We loaded the jump table and adjuested EDX. Go.  */	\
-    jmp		*%ebx
-
-	.section	.gnu.linkonce.t.__i686.get_pc_thunk.bx,"ax",@progbits
-	.globl	__i686.get_pc_thunk.bx
-	.hidden	__i686.get_pc_thunk.bx
-	ALIGN (4)
-	.type	__i686.get_pc_thunk.bx,@function
-__i686.get_pc_thunk.bx:
-	movl	(%esp), %ebx
-	ret
-#else
-# define ENTRANCE
-# define RETURN_END	ret
-# define RETURN		RETURN_END
-# define PARMS		4
-# define JMPTBL(I, B)	I
-
-/* Branch to an entry in a jump table.  TABLE is a jump table with
-   absolute offsets.  */
-# define BRANCH_TO_JMPTBL_ENTRY(TABLE)				\
-    jmp		*TABLE(,%ecx,4)
-#endif
-
-	.section .text.sse2,"ax",@progbits
-	ALIGN (4)
-ENTRY (sse2_memset16_atom)
-	ENTRANCE
-
-	movl	LEN(%esp), %ecx
-#ifdef USE_AS_ANDROID
-	shr	$1, %ecx
-#endif
-#ifdef USE_AS_BZERO16
-	xor	%eax, %eax
-#else
-	movzwl	CHR(%esp), %eax
-	mov	%eax, %edx
-	shl	$16, %eax
-	or	%edx, %eax
-#endif
-	movl	DEST(%esp), %edx
-	cmp	$32, %ecx
-	jae	L(32wordsormore)
-
-L(write_less32words):
-	lea	(%edx, %ecx, 2), %edx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_less32words))
-
-
-	.pushsection .rodata.sse2,"a",@progbits
-	ALIGN (2)
-L(table_less32words):
-	.int	JMPTBL (L(write_0words), L(table_less32words))
-	.int	JMPTBL (L(write_1words), L(table_less32words))
-	.int	JMPTBL (L(write_2words), L(table_less32words))
-	.int	JMPTBL (L(write_3words), L(table_less32words))
-	.int	JMPTBL (L(write_4words), L(table_less32words))
-	.int	JMPTBL (L(write_5words), L(table_less32words))
-	.int	JMPTBL (L(write_6words), L(table_less32words))
-	.int	JMPTBL (L(write_7words), L(table_less32words))
-	.int	JMPTBL (L(write_8words), L(table_less32words))
-	.int	JMPTBL (L(write_9words), L(table_less32words))
-	.int	JMPTBL (L(write_10words), L(table_less32words))
-	.int	JMPTBL (L(write_11words), L(table_less32words))
-	.int	JMPTBL (L(write_12words), L(table_less32words))
-	.int	JMPTBL (L(write_13words), L(table_less32words))
-	.int	JMPTBL (L(write_14words), L(table_less32words))
-	.int	JMPTBL (L(write_15words), L(table_less32words))
-	.int	JMPTBL (L(write_16words), L(table_less32words))
-	.int	JMPTBL (L(write_17words), L(table_less32words))
-	.int	JMPTBL (L(write_18words), L(table_less32words))
-	.int	JMPTBL (L(write_19words), L(table_less32words))
-	.int	JMPTBL (L(write_20words), L(table_less32words))
-	.int	JMPTBL (L(write_21words), L(table_less32words))
-	.int	JMPTBL (L(write_22words), L(table_less32words))
-	.int	JMPTBL (L(write_23words), L(table_less32words))
-	.int	JMPTBL (L(write_24words), L(table_less32words))
-	.int	JMPTBL (L(write_25words), L(table_less32words))
-	.int	JMPTBL (L(write_26words), L(table_less32words))
-	.int	JMPTBL (L(write_27words), L(table_less32words))
-	.int	JMPTBL (L(write_28words), L(table_less32words))
-	.int	JMPTBL (L(write_29words), L(table_less32words))
-	.int	JMPTBL (L(write_30words), L(table_less32words))
-	.int	JMPTBL (L(write_31words), L(table_less32words))
-	.popsection
-
-	ALIGN (4)
-L(write_28words):
-	movl	%eax, -56(%edx)
-	movl	%eax, -52(%edx)
-L(write_24words):
-	movl	%eax, -48(%edx)
-	movl	%eax, -44(%edx)
-L(write_20words):
-	movl	%eax, -40(%edx)
-	movl	%eax, -36(%edx)
-L(write_16words):
-	movl	%eax, -32(%edx)
-	movl	%eax, -28(%edx)
-L(write_12words):
-	movl	%eax, -24(%edx)
-	movl	%eax, -20(%edx)
-L(write_8words):
-	movl	%eax, -16(%edx)
-	movl	%eax, -12(%edx)
-L(write_4words):
-	movl	%eax, -8(%edx)
-	movl	%eax, -4(%edx)
-L(write_0words):
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-L(write_29words):
-	movl	%eax, -58(%edx)
-	movl	%eax, -54(%edx)
-L(write_25words):
-	movl	%eax, -50(%edx)
-	movl	%eax, -46(%edx)
-L(write_21words):
-	movl	%eax, -42(%edx)
-	movl	%eax, -38(%edx)
-L(write_17words):
-	movl	%eax, -34(%edx)
-	movl	%eax, -30(%edx)
-L(write_13words):
-	movl	%eax, -26(%edx)
-	movl	%eax, -22(%edx)
-L(write_9words):
-	movl	%eax, -18(%edx)
-	movl	%eax, -14(%edx)
-L(write_5words):
-	movl	%eax, -10(%edx)
-	movl	%eax, -6(%edx)
-L(write_1words):
-	mov	%ax, -2(%edx)
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-L(write_30words):
-	movl	%eax, -60(%edx)
-	movl	%eax, -56(%edx)
-L(write_26words):
-	movl	%eax, -52(%edx)
-	movl	%eax, -48(%edx)
-L(write_22words):
-	movl	%eax, -44(%edx)
-	movl	%eax, -40(%edx)
-L(write_18words):
-	movl	%eax, -36(%edx)
-	movl	%eax, -32(%edx)
-L(write_14words):
-	movl	%eax, -28(%edx)
-	movl	%eax, -24(%edx)
-L(write_10words):
-	movl	%eax, -20(%edx)
-	movl	%eax, -16(%edx)
-L(write_6words):
-	movl	%eax, -12(%edx)
-	movl	%eax, -8(%edx)
-L(write_2words):
-	movl	%eax, -4(%edx)
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-L(write_31words):
-	movl	%eax, -62(%edx)
-	movl	%eax, -58(%edx)
-L(write_27words):
-	movl	%eax, -54(%edx)
-	movl	%eax, -50(%edx)
-L(write_23words):
-	movl	%eax, -46(%edx)
-	movl	%eax, -42(%edx)
-L(write_19words):
-	movl	%eax, -38(%edx)
-	movl	%eax, -34(%edx)
-L(write_15words):
-	movl	%eax, -30(%edx)
-	movl	%eax, -26(%edx)
-L(write_11words):
-	movl	%eax, -22(%edx)
-	movl	%eax, -18(%edx)
-L(write_7words):
-	movl	%eax, -14(%edx)
-	movl	%eax, -10(%edx)
-L(write_3words):
-	movl	%eax, -6(%edx)
-	movw	%ax, -2(%edx)
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-
-L(32wordsormore):
-	shl	$1, %ecx
-	test	$0x01, %edx
-	jz	L(aligned2bytes)
-	mov	%eax, (%edx)
-	mov	%eax, -4(%edx, %ecx)
-	sub	$2, %ecx
-	add	$1, %edx
-	rol	$8, %eax
-L(aligned2bytes):
-#ifdef USE_AS_BZERO16
-	pxor	%xmm0, %xmm0
-#else
-	movd	%eax, %xmm0
-	pshufd	$0, %xmm0, %xmm0
-#endif
-	testl	$0xf, %edx
-	jz	L(aligned_16)
-/* ECX > 32 and EDX is not 16 byte aligned.  */
-L(not_aligned_16):
-	movdqu	%xmm0, (%edx)
-	movl	%edx, %eax
-	and	$-16, %edx
-	add	$16, %edx
-	sub	%edx, %eax
-	add	%eax, %ecx
-	movd	%xmm0, %eax
-
-	ALIGN (4)
-L(aligned_16):
-	cmp	$128, %ecx
-	jae	L(128bytesormore)
-
-L(aligned_16_less128bytes):
-	add	%ecx, %edx
-	shr	$1, %ecx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
-
-	ALIGN (4)
-L(128bytesormore):
-#ifdef SHARED_CACHE_SIZE
-	PUSH (%ebx)
-	mov	$SHARED_CACHE_SIZE, %ebx
-#else
-# if (defined SHARED || defined __PIC__)
-	call	__i686.get_pc_thunk.bx
-	add	$_GLOBAL_OFFSET_TABLE_, %ebx
-	mov	__x86_shared_cache_size@GOTOFF(%ebx), %ebx
-# else
-	PUSH (%ebx)
-	mov	__x86_shared_cache_size, %ebx
-# endif
-#endif
-	cmp	%ebx, %ecx
-	jae	L(128bytesormore_nt_start)
-
-	
-#ifdef DATA_CACHE_SIZE
-	POP (%ebx)
-# define RESTORE_EBX_STATE CFI_PUSH (%ebx)
-	cmp	$DATA_CACHE_SIZE, %ecx
-#else
-# if (defined SHARED || defined __PIC__)
-#  define RESTORE_EBX_STATE
-	call	__i686.get_pc_thunk.bx
-	add	$_GLOBAL_OFFSET_TABLE_, %ebx
-	cmp	__x86_data_cache_size@GOTOFF(%ebx), %ecx
-# else
-	POP (%ebx)
-#  define RESTORE_EBX_STATE CFI_PUSH (%ebx)
-	cmp	__x86_data_cache_size, %ecx
-# endif
-#endif
-
-	jae	L(128bytes_L2_normal)
-	subl	$128, %ecx
-L(128bytesormore_normal):
-	sub	$128, %ecx
-	movdqa	%xmm0, (%edx)
-	movdqa	%xmm0, 0x10(%edx)
-	movdqa	%xmm0, 0x20(%edx)
-	movdqa	%xmm0, 0x30(%edx)
-	movdqa	%xmm0, 0x40(%edx)
-	movdqa	%xmm0, 0x50(%edx)
-	movdqa	%xmm0, 0x60(%edx)
-	movdqa	%xmm0, 0x70(%edx)
-	lea	128(%edx), %edx
-	jb	L(128bytesless_normal)
-
-
-	sub	$128, %ecx
-	movdqa	%xmm0, (%edx)
-	movdqa	%xmm0, 0x10(%edx)
-	movdqa	%xmm0, 0x20(%edx)
-	movdqa	%xmm0, 0x30(%edx)
-	movdqa	%xmm0, 0x40(%edx)
-	movdqa	%xmm0, 0x50(%edx)
-	movdqa	%xmm0, 0x60(%edx)
-	movdqa	%xmm0, 0x70(%edx)
-	lea	128(%edx), %edx
-	jae	L(128bytesormore_normal)
-
-L(128bytesless_normal):
-	lea	128(%ecx), %ecx
-	add	%ecx, %edx
-	shr	$1, %ecx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
-
-	ALIGN (4)
-L(128bytes_L2_normal):
-	prefetcht0	0x380(%edx)
-	prefetcht0	0x3c0(%edx)
-	sub	$128, %ecx
-	movdqa	%xmm0, (%edx)
-	movaps	%xmm0, 0x10(%edx)
-	movaps	%xmm0, 0x20(%edx)
-	movaps	%xmm0, 0x30(%edx)
-	movaps	%xmm0, 0x40(%edx)
-	movaps	%xmm0, 0x50(%edx)
-	movaps	%xmm0, 0x60(%edx)
-	movaps	%xmm0, 0x70(%edx)
-	add	$128, %edx
-	cmp	$128, %ecx 	
-	jae	L(128bytes_L2_normal)
-
-L(128bytesless_L2_normal):
-	add	%ecx, %edx
-	shr	$1, %ecx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
-
-	RESTORE_EBX_STATE
-L(128bytesormore_nt_start):
-	sub	%ebx, %ecx
-	mov	%ebx, %eax
-	and	$0x7f, %eax
-	add	%eax, %ecx
-	movd	%xmm0, %eax
-	ALIGN (4)
-L(128bytesormore_shared_cache_loop):
-	prefetcht0	0x3c0(%edx)
-	prefetcht0	0x380(%edx)
-	sub	$0x80, %ebx
-	movdqa	%xmm0, (%edx)
-	movdqa	%xmm0, 0x10(%edx)
-	movdqa	%xmm0, 0x20(%edx)
-	movdqa	%xmm0, 0x30(%edx)
-	movdqa	%xmm0, 0x40(%edx)
-	movdqa	%xmm0, 0x50(%edx)
-	movdqa	%xmm0, 0x60(%edx)
-	movdqa	%xmm0, 0x70(%edx)
-	add	$0x80, %edx
-	cmp	$0x80, %ebx
-	jae	L(128bytesormore_shared_cache_loop)
-	cmp	$0x80, %ecx
-	jb	L(shared_cache_loop_end)
-	ALIGN (4)
-L(128bytesormore_nt):
-	sub	$0x80, %ecx
-	movntdq	%xmm0, (%edx)
-	movntdq	%xmm0, 0x10(%edx)
-	movntdq	%xmm0, 0x20(%edx)
-	movntdq	%xmm0, 0x30(%edx)
-	movntdq	%xmm0, 0x40(%edx)
-	movntdq	%xmm0, 0x50(%edx)
-	movntdq	%xmm0, 0x60(%edx)
-	movntdq	%xmm0, 0x70(%edx)
-	add	$0x80, %edx
-	cmp	$0x80, %ecx
-	jae	L(128bytesormore_nt)
-	sfence
-L(shared_cache_loop_end):
-#if defined DATA_CACHE_SIZE || !(defined SHARED || defined __PIC__)
-	POP (%ebx)
-#endif
-	add	%ecx, %edx
-	shr	$1, %ecx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
-
-
-	.pushsection .rodata.sse2,"a",@progbits
-	ALIGN (2)
-L(table_16_128bytes):
-	.int	JMPTBL (L(aligned_16_0bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_2bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_4bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_6bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_8bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_10bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_12bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_14bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_16bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_18bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_20bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_22bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_24bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_26bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_28bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_30bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_32bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_34bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_36bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_38bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_40bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_42bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_44bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_46bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_48bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_50bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_52bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_54bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_56bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_58bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_60bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_62bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_64bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_66bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_68bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_70bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_72bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_74bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_76bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_78bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_80bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_82bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_84bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_86bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_88bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_90bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_92bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_94bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_96bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_98bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_100bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_102bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_104bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_106bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_108bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_110bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_112bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_114bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_116bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_118bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_120bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_122bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_124bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_126bytes), L(table_16_128bytes))
-	.popsection
-
-
-	ALIGN (4)
-L(aligned_16_112bytes):
-	movdqa	%xmm0, -112(%edx)
-L(aligned_16_96bytes):
-	movdqa	%xmm0, -96(%edx)
-L(aligned_16_80bytes):
-	movdqa	%xmm0, -80(%edx)
-L(aligned_16_64bytes):
-	movdqa	%xmm0, -64(%edx)
-L(aligned_16_48bytes):
-	movdqa	%xmm0, -48(%edx)
-L(aligned_16_32bytes):
-	movdqa	%xmm0, -32(%edx)
-L(aligned_16_16bytes):
-	movdqa	%xmm0, -16(%edx)
-L(aligned_16_0bytes):
-	SETRTNVAL
-	RETURN
-
-
-	ALIGN (4)
-L(aligned_16_114bytes):
-	movdqa	%xmm0, -114(%edx)
-L(aligned_16_98bytes):
-	movdqa	%xmm0, -98(%edx)
-L(aligned_16_82bytes):
-	movdqa	%xmm0, -82(%edx)
-L(aligned_16_66bytes):
-	movdqa	%xmm0, -66(%edx)
-L(aligned_16_50bytes):
-	movdqa	%xmm0, -50(%edx)
-L(aligned_16_34bytes):
-	movdqa	%xmm0, -34(%edx)
-L(aligned_16_18bytes):
-	movdqa	%xmm0, -18(%edx)
-L(aligned_16_2bytes):
-	movw	%ax, -2(%edx)
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-L(aligned_16_116bytes):
-	movdqa	%xmm0, -116(%edx)
-L(aligned_16_100bytes):
-	movdqa	%xmm0, -100(%edx)
-L(aligned_16_84bytes):
-	movdqa	%xmm0, -84(%edx)
-L(aligned_16_68bytes):
-	movdqa	%xmm0, -68(%edx)
-L(aligned_16_52bytes):
-	movdqa	%xmm0, -52(%edx)
-L(aligned_16_36bytes):
-	movdqa	%xmm0, -36(%edx)
-L(aligned_16_20bytes):
-	movdqa	%xmm0, -20(%edx)
-L(aligned_16_4bytes):
-	movl	%eax, -4(%edx)
-	SETRTNVAL
-	RETURN
-
-
-	ALIGN (4)
-L(aligned_16_118bytes):
-	movdqa	%xmm0, -118(%edx)
-L(aligned_16_102bytes):
-	movdqa	%xmm0, -102(%edx)
-L(aligned_16_86bytes):
-	movdqa	%xmm0, -86(%edx)
-L(aligned_16_70bytes):
-	movdqa	%xmm0, -70(%edx)
-L(aligned_16_54bytes):
-	movdqa	%xmm0, -54(%edx)
-L(aligned_16_38bytes):
-	movdqa	%xmm0, -38(%edx)
-L(aligned_16_22bytes):
-	movdqa	%xmm0, -22(%edx)
-L(aligned_16_6bytes):
-	movl	%eax, -6(%edx)
-	movw	%ax, -2(%edx)
-	SETRTNVAL
-	RETURN
-
-
-	ALIGN (4)
-L(aligned_16_120bytes):
-	movdqa	%xmm0, -120(%edx)
-L(aligned_16_104bytes):
-	movdqa	%xmm0, -104(%edx)
-L(aligned_16_88bytes):
-	movdqa	%xmm0, -88(%edx)
-L(aligned_16_72bytes):
-	movdqa	%xmm0, -72(%edx)
-L(aligned_16_56bytes):
-	movdqa	%xmm0, -56(%edx)
-L(aligned_16_40bytes):
-	movdqa	%xmm0, -40(%edx)
-L(aligned_16_24bytes):
-	movdqa	%xmm0, -24(%edx)
-L(aligned_16_8bytes):
-	movq	%xmm0, -8(%edx)
-	SETRTNVAL
-	RETURN
-
-
-	ALIGN (4)
-L(aligned_16_122bytes):
-	movdqa	%xmm0, -122(%edx)
-L(aligned_16_106bytes):
-	movdqa	%xmm0, -106(%edx)
-L(aligned_16_90bytes):
-	movdqa	%xmm0, -90(%edx)
-L(aligned_16_74bytes):
-	movdqa	%xmm0, -74(%edx)
-L(aligned_16_58bytes):
-	movdqa	%xmm0, -58(%edx)
-L(aligned_16_42bytes):
-	movdqa	%xmm0, -42(%edx)
-L(aligned_16_26bytes):
-	movdqa	%xmm0, -26(%edx)
-L(aligned_16_10bytes):
-	movq	%xmm0, -10(%edx)
-	movw	%ax, -2(%edx)
-	SETRTNVAL
-	RETURN
-
-
-	ALIGN (4)
-L(aligned_16_124bytes):
-	movdqa	%xmm0, -124(%edx)
-L(aligned_16_108bytes):
-	movdqa	%xmm0, -108(%edx)
-L(aligned_16_92bytes):
-	movdqa	%xmm0, -92(%edx)
-L(aligned_16_76bytes):
-	movdqa	%xmm0, -76(%edx)
-L(aligned_16_60bytes):
-	movdqa	%xmm0, -60(%edx)
-L(aligned_16_44bytes):
-	movdqa	%xmm0, -44(%edx)
-L(aligned_16_28bytes):
-	movdqa	%xmm0, -28(%edx)
-L(aligned_16_12bytes):
-	movq	%xmm0, -12(%edx)
-	movl	%eax, -4(%edx)
-	SETRTNVAL
-	RETURN
-
-
-	ALIGN (4)
-L(aligned_16_126bytes):
-	movdqa	%xmm0, -126(%edx)
-L(aligned_16_110bytes):
-	movdqa	%xmm0, -110(%edx)
-L(aligned_16_94bytes):
-	movdqa	%xmm0, -94(%edx)
-L(aligned_16_78bytes):
-	movdqa	%xmm0, -78(%edx)
-L(aligned_16_62bytes):
-	movdqa	%xmm0, -62(%edx)
-L(aligned_16_46bytes):
-	movdqa	%xmm0, -46(%edx)
-L(aligned_16_30bytes):
-	movdqa	%xmm0, -30(%edx)
-L(aligned_16_14bytes):
-	movq	%xmm0, -14(%edx)
-	movl	%eax, -6(%edx)
-	movw	%ax, -2(%edx)
-	SETRTNVAL
-	RETURN
-
-END (sse2_memset16_atom)
diff --git a/libcutils/arch-x86/sse2-memset32-atom.S b/libcutils/arch-x86/sse2-memset32-atom.S
deleted file mode 100755
index 05eb64f..0000000
--- a/libcutils/arch-x86/sse2-memset32-atom.S
+++ /dev/null
@@ -1,513 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-/*
- * Contributed by: Intel Corporation
- */
-
-#ifndef L
-# define L(label)	.L##label
-#endif
-
-#ifndef ALIGN
-# define ALIGN(n)	.p2align n
-#endif
-
-#ifndef cfi_startproc
-# define cfi_startproc			.cfi_startproc
-#endif
-
-#ifndef cfi_endproc
-# define cfi_endproc			.cfi_endproc
-#endif
-
-#ifndef cfi_rel_offset
-# define cfi_rel_offset(reg, off)	.cfi_rel_offset reg, off
-#endif
-
-#ifndef cfi_restore
-# define cfi_restore(reg)		.cfi_restore reg
-#endif
-
-#ifndef cfi_adjust_cfa_offset
-# define cfi_adjust_cfa_offset(off)	.cfi_adjust_cfa_offset off
-#endif
-
-#ifndef ENTRY
-# define ENTRY(name)			\
-	.type name,  @function; 	\
-	.globl name;			\
-	.p2align 4;			\
-name:					\
-	cfi_startproc
-#endif
-
-#ifndef END
-# define END(name)			\
-	cfi_endproc;			\
-	.size name, .-name
-#endif
-
-#define CFI_PUSH(REG)						\
-  cfi_adjust_cfa_offset (4);					\
-  cfi_rel_offset (REG, 0)
-
-#define CFI_POP(REG)						\
-  cfi_adjust_cfa_offset (-4);					\
-  cfi_restore (REG)
-
-#define PUSH(REG)	pushl REG; CFI_PUSH (REG)
-#define POP(REG)	popl REG; CFI_POP (REG)
-
-#ifdef USE_AS_BZERO32
-# define DEST		PARMS
-# define LEN		DEST+4
-#else
-# define DEST		PARMS
-# define DWDS		DEST+4
-# define LEN		DWDS+4
-#endif
-
-#ifdef USE_AS_WMEMSET32
-# define SETRTNVAL	movl DEST(%esp), %eax
-#else
-# define SETRTNVAL
-#endif
-
-#if (defined SHARED || defined __PIC__)
-# define ENTRANCE	PUSH (%ebx);
-# define RETURN_END	POP (%ebx); ret
-# define RETURN		RETURN_END; CFI_PUSH (%ebx)
-# define PARMS		8		/* Preserve EBX.  */
-# define JMPTBL(I, B)	I - B
-
-/* Load an entry in a jump table into EBX and branch to it.  TABLE is a
-   jump table with relative offsets.   */
-# define BRANCH_TO_JMPTBL_ENTRY(TABLE)				\
-    /* We first load PC into EBX.  */				\
-    call	__i686.get_pc_thunk.bx;				\
-    /* Get the address of the jump table.  */			\
-    add		$(TABLE - .), %ebx;				\
-    /* Get the entry and convert the relative offset to the	\
-       absolute address.  */					\
-    add		(%ebx,%ecx,4), %ebx;				\
-    /* We loaded the jump table and adjuested EDX. Go.  */	\
-    jmp		*%ebx
-
-	.section	.gnu.linkonce.t.__i686.get_pc_thunk.bx,"ax",@progbits
-	.globl	__i686.get_pc_thunk.bx
-	.hidden	__i686.get_pc_thunk.bx
-	ALIGN (4)
-	.type	__i686.get_pc_thunk.bx,@function
-__i686.get_pc_thunk.bx:
-	movl	(%esp), %ebx
-	ret
-#else
-# define ENTRANCE
-# define RETURN_END	ret
-# define RETURN		RETURN_END
-# define PARMS		4
-# define JMPTBL(I, B)	I
-
-/* Branch to an entry in a jump table.  TABLE is a jump table with
-   absolute offsets.  */
-# define BRANCH_TO_JMPTBL_ENTRY(TABLE)				\
-    jmp		*TABLE(,%ecx,4)
-#endif
-
-	.section .text.sse2,"ax",@progbits
-	ALIGN (4)
-ENTRY (sse2_memset32_atom)
-	ENTRANCE
-
-	movl	LEN(%esp), %ecx
-#ifdef USE_AS_ANDROID
-	shr     $2, %ecx
-#endif
-#ifdef USE_AS_BZERO32
-	xor	%eax, %eax
-#else
-	mov	DWDS(%esp), %eax
-	mov	%eax, %edx
-#endif
-	movl	DEST(%esp), %edx
-	cmp	$16, %ecx
-	jae	L(16dbwordsormore)
-
-L(write_less16dbwords):
-	lea	(%edx, %ecx, 4), %edx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_less16dbwords))
-
-	.pushsection .rodata.sse2,"a",@progbits
-	ALIGN (2)
-L(table_less16dbwords):
-	.int	JMPTBL (L(write_0dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_1dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_2dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_3dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_4dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_5dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_6dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_7dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_8dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_9dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_10dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_11dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_12dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_13dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_14dbwords), L(table_less16dbwords))
-	.int	JMPTBL (L(write_15dbwords), L(table_less16dbwords))
-	.popsection
-
-	ALIGN (4)
-L(write_15dbwords):
-	movl	%eax, -60(%edx)
-L(write_14dbwords):
-	movl	%eax, -56(%edx)
-L(write_13dbwords):
-	movl	%eax, -52(%edx)
-L(write_12dbwords):
-	movl	%eax, -48(%edx)
-L(write_11dbwords):
-	movl	%eax, -44(%edx)
-L(write_10dbwords):
-	movl	%eax, -40(%edx)
-L(write_9dbwords):
-	movl	%eax, -36(%edx)
-L(write_8dbwords):
-	movl	%eax, -32(%edx)
-L(write_7dbwords):
-	movl	%eax, -28(%edx)
-L(write_6dbwords):
-	movl	%eax, -24(%edx)
-L(write_5dbwords):
-	movl	%eax, -20(%edx)
-L(write_4dbwords):
-	movl	%eax, -16(%edx)
-L(write_3dbwords):
-	movl	%eax, -12(%edx)
-L(write_2dbwords):
-	movl	%eax, -8(%edx)
-L(write_1dbwords):
-	movl	%eax, -4(%edx)
-L(write_0dbwords):
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-L(16dbwordsormore):
-	test	$3, %edx
-	jz	L(aligned4bytes)
-	mov	%eax, (%edx)
-	mov	%eax, -4(%edx, %ecx, 4)
-	sub	$1, %ecx
-	rol	$24, %eax
-	add	$1, %edx
-	test	$3, %edx
-	jz	L(aligned4bytes)
-	ror	$8, %eax
-	add	$1, %edx
-	test	$3, %edx
-	jz	L(aligned4bytes)
-	ror	$8, %eax
-	add	$1, %edx
-L(aligned4bytes):
-	shl	$2, %ecx
-
-#ifdef USE_AS_BZERO32
-	pxor	%xmm0, %xmm0
-#else
-	movd	%eax, %xmm0
-	pshufd	$0, %xmm0, %xmm0
-#endif
-	testl	$0xf, %edx
-	jz	L(aligned_16)
-/* ECX > 32 and EDX is not 16 byte aligned.  */
-L(not_aligned_16):
-	movdqu	%xmm0, (%edx)
-	movl	%edx, %eax
-	and	$-16, %edx
-	add	$16, %edx
-	sub	%edx, %eax
-	add	%eax, %ecx
-	movd	%xmm0, %eax
-	ALIGN (4)
-L(aligned_16):
-	cmp	$128, %ecx
-	jae	L(128bytesormore)
-
-L(aligned_16_less128bytes):
-	add	%ecx, %edx
-	shr	$2, %ecx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
-
-	ALIGN (4)
-L(128bytesormore):
-#ifdef SHARED_CACHE_SIZE
-	PUSH (%ebx)
-	mov	$SHARED_CACHE_SIZE, %ebx
-#else
-# if (defined SHARED || defined __PIC__)
-	call	__i686.get_pc_thunk.bx
-	add	$_GLOBAL_OFFSET_TABLE_, %ebx
-	mov	__x86_shared_cache_size@GOTOFF(%ebx), %ebx
-# else
-	PUSH (%ebx)
-	mov	__x86_shared_cache_size, %ebx
-# endif
-#endif
-	cmp	%ebx, %ecx
-	jae	L(128bytesormore_nt_start)
-	
-#ifdef DATA_CACHE_SIZE
-	POP (%ebx)
-# define RESTORE_EBX_STATE CFI_PUSH (%ebx)
-	cmp	$DATA_CACHE_SIZE, %ecx
-#else
-# if (defined SHARED || defined __PIC__)
-#  define RESTORE_EBX_STATE
-	call	__i686.get_pc_thunk.bx
-	add	$_GLOBAL_OFFSET_TABLE_, %ebx
-	cmp	__x86_data_cache_size@GOTOFF(%ebx), %ecx
-# else
-	POP (%ebx)
-#  define RESTORE_EBX_STATE CFI_PUSH (%ebx)
-	cmp	__x86_data_cache_size, %ecx
-# endif
-#endif
-
-	jae	L(128bytes_L2_normal)
-	subl	$128, %ecx
-L(128bytesormore_normal):
-	sub	$128, %ecx
-	movdqa	%xmm0, (%edx)
-	movdqa	%xmm0, 0x10(%edx)
-	movdqa	%xmm0, 0x20(%edx)
-	movdqa	%xmm0, 0x30(%edx)
-	movdqa	%xmm0, 0x40(%edx)
-	movdqa	%xmm0, 0x50(%edx)
-	movdqa	%xmm0, 0x60(%edx)
-	movdqa	%xmm0, 0x70(%edx)
-	lea	128(%edx), %edx
-	jb	L(128bytesless_normal)
-
-
-	sub	$128, %ecx
-	movdqa	%xmm0, (%edx)
-	movdqa	%xmm0, 0x10(%edx)
-	movdqa	%xmm0, 0x20(%edx)
-	movdqa	%xmm0, 0x30(%edx)
-	movdqa	%xmm0, 0x40(%edx)
-	movdqa	%xmm0, 0x50(%edx)
-	movdqa	%xmm0, 0x60(%edx)
-	movdqa	%xmm0, 0x70(%edx)
-	lea	128(%edx), %edx
-	jae	L(128bytesormore_normal)
-
-L(128bytesless_normal):
-	lea	128(%ecx), %ecx
-	add	%ecx, %edx
-	shr	$2, %ecx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
-
-	ALIGN (4)
-L(128bytes_L2_normal):
-	prefetcht0	0x380(%edx)
-	prefetcht0	0x3c0(%edx)
-	sub	$128, %ecx
-	movdqa	%xmm0, (%edx)
-	movaps	%xmm0, 0x10(%edx)
-	movaps	%xmm0, 0x20(%edx)
-	movaps	%xmm0, 0x30(%edx)
-	movaps	%xmm0, 0x40(%edx)
-	movaps	%xmm0, 0x50(%edx)
-	movaps	%xmm0, 0x60(%edx)
-	movaps	%xmm0, 0x70(%edx)
-	add	$128, %edx
-	cmp	$128, %ecx 	
-	jae	L(128bytes_L2_normal)
-
-L(128bytesless_L2_normal):
-	add	%ecx, %edx
-	shr	$2, %ecx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
-
-	RESTORE_EBX_STATE
-L(128bytesormore_nt_start):
-	sub	%ebx, %ecx
-	mov	%ebx, %eax
-	and	$0x7f, %eax
-	add	%eax, %ecx
-	movd	%xmm0, %eax
-	ALIGN (4)
-L(128bytesormore_shared_cache_loop):
-	prefetcht0	0x3c0(%edx)
-	prefetcht0	0x380(%edx)
-	sub	$0x80, %ebx
-	movdqa	%xmm0, (%edx)
-	movdqa	%xmm0, 0x10(%edx)
-	movdqa	%xmm0, 0x20(%edx)
-	movdqa	%xmm0, 0x30(%edx)
-	movdqa	%xmm0, 0x40(%edx)
-	movdqa	%xmm0, 0x50(%edx)
-	movdqa	%xmm0, 0x60(%edx)
-	movdqa	%xmm0, 0x70(%edx)
-	add	$0x80, %edx
-	cmp	$0x80, %ebx
-	jae	L(128bytesormore_shared_cache_loop)
-	cmp	$0x80, %ecx
-	jb	L(shared_cache_loop_end)
-
-	ALIGN (4)
-L(128bytesormore_nt):
-	sub	$0x80, %ecx
-	movntdq	%xmm0, (%edx)
-	movntdq	%xmm0, 0x10(%edx)
-	movntdq	%xmm0, 0x20(%edx)
-	movntdq	%xmm0, 0x30(%edx)
-	movntdq	%xmm0, 0x40(%edx)
-	movntdq	%xmm0, 0x50(%edx)
-	movntdq	%xmm0, 0x60(%edx)
-	movntdq	%xmm0, 0x70(%edx)
-	add	$0x80, %edx
-	cmp	$0x80, %ecx
-	jae	L(128bytesormore_nt)
-	sfence
-L(shared_cache_loop_end):
-#if defined DATA_CACHE_SIZE || !(defined SHARED || defined __PIC__)
-	POP (%ebx)
-#endif
-	add	%ecx, %edx
-	shr	$2, %ecx
-	BRANCH_TO_JMPTBL_ENTRY (L(table_16_128bytes))
-
-	.pushsection .rodata.sse2,"a",@progbits
-	ALIGN (2)
-L(table_16_128bytes):
-	.int	JMPTBL (L(aligned_16_0bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_4bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_8bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_12bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_16bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_20bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_24bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_28bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_32bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_36bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_40bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_44bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_48bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_52bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_56bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_60bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_64bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_68bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_72bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_76bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_80bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_84bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_88bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_92bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_96bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_100bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_104bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_108bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_112bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_116bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_120bytes), L(table_16_128bytes))
-	.int	JMPTBL (L(aligned_16_124bytes), L(table_16_128bytes))
-	.popsection
-
-	ALIGN (4)
-L(aligned_16_112bytes):
-	movdqa	%xmm0, -112(%edx)
-L(aligned_16_96bytes):
-	movdqa	%xmm0, -96(%edx)
-L(aligned_16_80bytes):
-	movdqa	%xmm0, -80(%edx)
-L(aligned_16_64bytes):
-	movdqa	%xmm0, -64(%edx)
-L(aligned_16_48bytes):
-	movdqa	%xmm0, -48(%edx)
-L(aligned_16_32bytes):
-	movdqa	%xmm0, -32(%edx)
-L(aligned_16_16bytes):
-	movdqa	%xmm0, -16(%edx)
-L(aligned_16_0bytes):
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-L(aligned_16_116bytes):
-	movdqa	%xmm0, -116(%edx)
-L(aligned_16_100bytes):
-	movdqa	%xmm0, -100(%edx)
-L(aligned_16_84bytes):
-	movdqa	%xmm0, -84(%edx)
-L(aligned_16_68bytes):
-	movdqa	%xmm0, -68(%edx)
-L(aligned_16_52bytes):
-	movdqa	%xmm0, -52(%edx)
-L(aligned_16_36bytes):
-	movdqa	%xmm0, -36(%edx)
-L(aligned_16_20bytes):
-	movdqa	%xmm0, -20(%edx)
-L(aligned_16_4bytes):
-	movl	%eax, -4(%edx)
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-L(aligned_16_120bytes):
-	movdqa	%xmm0, -120(%edx)
-L(aligned_16_104bytes):
-	movdqa	%xmm0, -104(%edx)
-L(aligned_16_88bytes):
-	movdqa	%xmm0, -88(%edx)
-L(aligned_16_72bytes):
-	movdqa	%xmm0, -72(%edx)
-L(aligned_16_56bytes):
-	movdqa	%xmm0, -56(%edx)
-L(aligned_16_40bytes):
-	movdqa	%xmm0, -40(%edx)
-L(aligned_16_24bytes):
-	movdqa	%xmm0, -24(%edx)
-L(aligned_16_8bytes):
-	movq	%xmm0, -8(%edx)
-	SETRTNVAL
-	RETURN
-
-	ALIGN (4)
-L(aligned_16_124bytes):
-	movdqa	%xmm0, -124(%edx)
-L(aligned_16_108bytes):
-	movdqa	%xmm0, -108(%edx)
-L(aligned_16_92bytes):
-	movdqa	%xmm0, -92(%edx)
-L(aligned_16_76bytes):
-	movdqa	%xmm0, -76(%edx)
-L(aligned_16_60bytes):
-	movdqa	%xmm0, -60(%edx)
-L(aligned_16_44bytes):
-	movdqa	%xmm0, -44(%edx)
-L(aligned_16_28bytes):
-	movdqa	%xmm0, -28(%edx)
-L(aligned_16_12bytes):
-	movq	%xmm0, -12(%edx)
-	movl	%eax, -4(%edx)
-	SETRTNVAL
-	RETURN
-
-END (sse2_memset32_atom)
diff --git a/libcutils/arch-x86_64/android_memset16_SSE2-atom.S b/libcutils/arch-x86_64/android_memset16.S
similarity index 98%
rename from libcutils/arch-x86_64/android_memset16_SSE2-atom.S
rename to libcutils/arch-x86_64/android_memset16.S
index 48a10ed..cb6d4a3 100644
--- a/libcutils/arch-x86_64/android_memset16_SSE2-atom.S
+++ b/libcutils/arch-x86_64/android_memset16.S
@@ -13,12 +13,13 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * Contributed by: Intel Corporation
- */
 
 #include "cache.h"
 
+#ifndef MEMSET
+# define MEMSET		android_memset16
+#endif
+
 #ifndef L
 # define L(label)	.L##label
 #endif
@@ -63,7 +64,7 @@
 
 	.section .text.sse2,"ax",@progbits
 	ALIGN (4)
-ENTRY (android_memset16)	// Address in rdi
+ENTRY (MEMSET)	// Address in rdi
 	shr    $1, %rdx			// Count in rdx
 	movzwl %si, %ecx
 	/* Fill the whole ECX with pattern.  */
@@ -561,4 +562,4 @@
 	movw   %cx, -2(%rdi)
 	ret
 
-END (android_memset16)
+END (MEMSET)
diff --git a/libcutils/arch-x86_64/android_memset32_SSE2-atom.S b/libcutils/arch-x86_64/android_memset32.S
similarity index 98%
rename from libcutils/arch-x86_64/android_memset32_SSE2-atom.S
rename to libcutils/arch-x86_64/android_memset32.S
index 4bdea8e..1514aa2 100644
--- a/libcutils/arch-x86_64/android_memset32_SSE2-atom.S
+++ b/libcutils/arch-x86_64/android_memset32.S
@@ -13,12 +13,13 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * Contributed by: Intel Corporation
- */
 
 #include "cache.h"
 
+#ifndef MEMSET
+# define MEMSET		android_memset32
+#endif
+
 #ifndef L
 # define L(label)	.L##label
 #endif
@@ -63,7 +64,7 @@
 
 	.section .text.sse2,"ax",@progbits
 	ALIGN (4)
-ENTRY (android_memset32)	// Address in rdi
+ENTRY (MEMSET)	// Address in rdi
 	shr    $2, %rdx			// Count in rdx
 	movl   %esi, %ecx		// Pattern in ecx
 
@@ -369,4 +370,4 @@
 	movl	%ecx, -4(%rdi)
 	ret
 
-END (android_memset32)
+END (MEMSET)
diff --git a/libcutils/arch-x86_64/cache.h b/libcutils/arch-x86_64/cache.h
index ab5dd2f..f144309 100644
--- a/libcutils/arch-x86_64/cache.h
+++ b/libcutils/arch-x86_64/cache.h
@@ -13,19 +13,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * Contributed by: Intel Corporation
- */
 
-#if defined(__slm__)
 /* Values are optimized for Silvermont */
 #define SHARED_CACHE_SIZE	(1024*1024)			/* Silvermont L2 Cache */
 #define DATA_CACHE_SIZE		(24*1024)			/* Silvermont L1 Data Cache */
-#else
-/* Values are optimized for Atom */
-#define SHARED_CACHE_SIZE	(512*1024)			/* Atom L2 Cache */
-#define DATA_CACHE_SIZE		(24*1024)			/* Atom L1 Data Cache */
-#endif
 
 #define SHARED_CACHE_SIZE_HALF	(SHARED_CACHE_SIZE / 2)
 #define DATA_CACHE_SIZE_HALF	(DATA_CACHE_SIZE / 2)
diff --git a/libcutils/atomic.c b/libcutils/atomic.c
index 1484ef8..d34aa00 100644
--- a/libcutils/atomic.c
+++ b/libcutils/atomic.c
@@ -14,6 +14,13 @@
  * limitations under the License.
  */
 
+/*
+ * Generate non-inlined versions of android_atomic functions.
+ * Nobody should be using these, but some binary blobs currently (late 2014)
+ * are.
+ * If you read this in 2015 or later, please try to delete this file.
+ */
+
 #define ANDROID_ATOMIC_INLINE
 
-#include <cutils/atomic-inline.h>
+#include <cutils/atomic.h>
diff --git a/libcutils/open_memstream.c b/libcutils/open_memstream.c
index 5b4388a..9183266 100644
--- a/libcutils/open_memstream.c
+++ b/libcutils/open_memstream.c
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef HAVE_OPEN_MEMSTREAM
+#if defined(__APPLE__)
 
 /*
  * Implementation of the POSIX open_memstream() function, which Linux has
@@ -59,8 +59,6 @@
 # define DBUG(x) ((void)0)
 #endif
 
-#ifdef HAVE_FUNOPEN
-
 /*
  * Definition of a seekable, write-only memory stream.
  */
@@ -251,12 +249,6 @@
     return fp;
 }
 
-#else /*not HAVE_FUNOPEN*/
-FILE* open_memstream(char** bufp, size_t* sizep)
-{
-    abort();
-}
-#endif /*HAVE_FUNOPEN*/
 
 
 
@@ -378,4 +370,4 @@
 
 #endif
 
-#endif /*!HAVE_OPEN_MEMSTREAM*/
+#endif /* __APPLE__ */
diff --git a/libcutils/process_name.c b/libcutils/process_name.c
index 9c3dfb8..cc931eb 100644
--- a/libcutils/process_name.c
+++ b/libcutils/process_name.c
@@ -17,7 +17,7 @@
 #include <fcntl.h>
 #include <stdlib.h>
 #include <string.h>
-#if defined(HAVE_PRCTL)
+#if defined(__linux__)
 #include <sys/prctl.h>
 #endif
 #include <sys/stat.h>
@@ -51,7 +51,7 @@
     strcpy(copy, new_name);
     process_name = (const char*) copy;
 
-#if defined(HAVE_PRCTL)
+#if defined(__linux__)
     if (len < 16) {
         prctl(PR_SET_NAME, (unsigned long) new_name, 0, 0, 0);
     } else {
diff --git a/libcutils/properties.c b/libcutils/properties.c
index b283658..1190ab7 100644
--- a/libcutils/properties.c
+++ b/libcutils/properties.c
@@ -104,7 +104,7 @@
     return (int32_t)property_get_imax(key, INT32_MIN, INT32_MAX, default_value);
 }
 
-#ifdef HAVE_LIBC_SYSTEM_PROPERTIES
+#ifdef __BIONIC__
 
 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
 #include <sys/_system_properties.h>
@@ -157,191 +157,9 @@
     return __system_property_foreach(property_list_callback, &data);
 }
 
-#elif defined(HAVE_SYSTEM_PROPERTY_SERVER)
-
-/*
- * The Linux simulator provides a "system property server" that uses IPC
- * to set/get/list properties.  The file descriptor is shared by all
- * threads in the process, so we use a mutex to ensure that requests
- * from multiple threads don't get interleaved.
- */
-#include <stdio.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <pthread.h>
-
-static pthread_once_t gInitOnce = PTHREAD_ONCE_INIT;
-static pthread_mutex_t gPropertyFdLock = PTHREAD_MUTEX_INITIALIZER;
-static int gPropFd = -1;
-
-/*
- * Connect to the properties server.
- *
- * Returns the socket descriptor on success.
- */
-static int connectToServer(const char* fileName)
-{
-    int sock = -1;
-    int cc;
-
-    struct sockaddr_un addr;
-    
-    sock = socket(AF_UNIX, SOCK_STREAM, 0);
-    if (sock < 0) {
-        ALOGW("UNIX domain socket create failed (errno=%d)\n", errno);
-        return -1;
-    }
-
-    /* connect to socket; fails if file doesn't exist */
-    strcpy(addr.sun_path, fileName);    // max 108 bytes
-    addr.sun_family = AF_UNIX;
-    cc = connect(sock, (struct sockaddr*) &addr, SUN_LEN(&addr));
-    if (cc < 0) {
-        // ENOENT means socket file doesn't exist
-        // ECONNREFUSED means socket exists but nobody is listening
-        //ALOGW("AF_UNIX connect failed for '%s': %s\n",
-        //    fileName, strerror(errno));
-        close(sock);
-        return -1;
-    }
-
-    return sock;
-}
-
-/*
- * Perform one-time initialization.
- */
-static void init(void)
-{
-    assert(gPropFd == -1);
-
-    gPropFd = connectToServer(SYSTEM_PROPERTY_PIPE_NAME);
-    if (gPropFd < 0) {
-        //ALOGW("not connected to system property server\n");
-    } else {
-        //ALOGV("Connected to system property server\n");
-    }
-}
-
-int property_get(const char *key, char *value, const char *default_value)
-{
-    char sendBuf[1+PROPERTY_KEY_MAX];
-    char recvBuf[1+PROPERTY_VALUE_MAX];
-    int len = -1;
-
-    //ALOGV("PROPERTY GET [%s]\n", key);
-
-    pthread_once(&gInitOnce, init);
-    if (gPropFd < 0) {
-        /* this mimics the behavior of the device implementation */
-        if (default_value != NULL) {
-            strcpy(value, default_value);
-            len = strlen(value);
-        }
-        return len;
-    }
-
-    if (strlen(key) >= PROPERTY_KEY_MAX) return -1;
-
-    memset(sendBuf, 0xdd, sizeof(sendBuf));    // placate valgrind
-
-    sendBuf[0] = (char) kSystemPropertyGet;
-    strcpy(sendBuf+1, key);
-
-    pthread_mutex_lock(&gPropertyFdLock);
-    if (write(gPropFd, sendBuf, sizeof(sendBuf)) != sizeof(sendBuf)) {
-        pthread_mutex_unlock(&gPropertyFdLock);
-        return -1;
-    }
-    if (read(gPropFd, recvBuf, sizeof(recvBuf)) != sizeof(recvBuf)) {
-        pthread_mutex_unlock(&gPropertyFdLock);
-        return -1;
-    }
-    pthread_mutex_unlock(&gPropertyFdLock);
-
-    /* first byte is 0 if value not defined, 1 if found */
-    if (recvBuf[0] == 0) {
-        if (default_value != NULL) {
-            strcpy(value, default_value);
-            len = strlen(value);
-        } else {
-            /*
-             * If the value isn't defined, hand back an empty string and
-             * a zero length, rather than a failure.  This seems wrong,
-             * since you can't tell the difference between "undefined" and
-             * "defined but empty", but it's what the device does.
-             */
-            value[0] = '\0';
-            len = 0;
-        }
-    } else if (recvBuf[0] == 1) {
-        strcpy(value, recvBuf+1);
-        len = strlen(value);
-    } else {
-        ALOGE("Got strange response to property_get request (%d)\n",
-            recvBuf[0]);
-        assert(0);
-        return -1;
-    }
-    //ALOGV("PROP [found=%d def='%s'] (%d) [%s]: [%s]\n",
-    //    recvBuf[0], default_value, len, key, value);
-
-    return len;
-}
-
-
-int property_set(const char *key, const char *value)
-{
-    char sendBuf[1+PROPERTY_KEY_MAX+PROPERTY_VALUE_MAX];
-    char recvBuf[1];
-    int result = -1;
-
-    //ALOGV("PROPERTY SET [%s]: [%s]\n", key, value);
-
-    pthread_once(&gInitOnce, init);
-    if (gPropFd < 0)
-        return -1;
-
-    if (strlen(key) >= PROPERTY_KEY_MAX) return -1;
-    if (strlen(value) >= PROPERTY_VALUE_MAX) return -1;
-
-    memset(sendBuf, 0xdd, sizeof(sendBuf));    // placate valgrind
-
-    sendBuf[0] = (char) kSystemPropertySet;
-    strcpy(sendBuf+1, key);
-    strcpy(sendBuf+1+PROPERTY_KEY_MAX, value);
-
-    pthread_mutex_lock(&gPropertyFdLock);
-    if (write(gPropFd, sendBuf, sizeof(sendBuf)) != sizeof(sendBuf)) {
-        pthread_mutex_unlock(&gPropertyFdLock);
-        return -1;
-    }
-    if (read(gPropFd, recvBuf, sizeof(recvBuf)) != sizeof(recvBuf)) {
-        pthread_mutex_unlock(&gPropertyFdLock);
-        return -1;
-    }
-    pthread_mutex_unlock(&gPropertyFdLock);
-
-    if (recvBuf[0] != 1)
-        return -1;
-    return 0;
-}
-
-int property_list(void (*propfn)(const char *key, const char *value, void *cookie), 
-                  void *cookie)
-{
-    //ALOGV("PROPERTY LIST\n");
-    pthread_once(&gInitOnce, init);
-    if (gPropFd < 0)
-        return -1;
-
-    return 0;
-}
-
 #else
 
-/* SUPER-cheesy place-holder implementation for Win32 */
+/* SUPER-cheesy place-holder implementation for glibc/Mac OS/Windows. */
 
 #include <cutils/threads.h>
 
diff --git a/libcutils/sched_policy.c b/libcutils/sched_policy.c
index 493511e..dfc8777 100644
--- a/libcutils/sched_policy.c
+++ b/libcutils/sched_policy.c
@@ -37,7 +37,7 @@
    return p == SP_DEFAULT ? SP_SYSTEM_DEFAULT : p;
 }
 
-#if defined(HAVE_ANDROID_OS) && defined(HAVE_SCHED_H) && defined(HAVE_PTHREADS)
+#if defined(HAVE_ANDROID_OS)
 
 #include <pthread.h>
 #include <sched.h>
@@ -203,11 +203,9 @@
 
 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) {
@@ -240,11 +238,9 @@
 
 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);
 
diff --git a/libcutils/socket_local_client.c b/libcutils/socket_local_client.c
index ddcc2da..7b42daa 100644
--- a/libcutils/socket_local_client.c
+++ b/libcutils/socket_local_client.c
@@ -52,7 +52,7 @@
 
     switch (namespaceId) {
         case ANDROID_SOCKET_NAMESPACE_ABSTRACT:
-#ifdef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE
+#if defined(__linux__)
             namelen  = strlen(name);
 
             // Test with length +1 for the *initial* '\0'.
@@ -67,7 +67,7 @@
             
             p_addr->sun_path[0] = 0;
             memcpy(p_addr->sun_path + 1, name, namelen);
-#else /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/
+#else
             /* this OS doesn't have the Linux abstract namespace */
 
             namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX);
@@ -79,7 +79,7 @@
 
             strcpy(p_addr->sun_path, FILESYSTEM_SOCKET_PREFIX);
             strcat(p_addr->sun_path, name);
-#endif /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/
+#endif
         break;
 
         case ANDROID_SOCKET_NAMESPACE_RESERVED:
diff --git a/libcutils/socket_local_server.c b/libcutils/socket_local_server.c
index 7628fe4..60eb86b 100644
--- a/libcutils/socket_local_server.c
+++ b/libcutils/socket_local_server.c
@@ -66,7 +66,7 @@
     }
 
     /* basically: if this is a filesystem path, unlink first */
-#ifndef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE
+#if !defined(__linux__)
     if (1) {
 #else
     if (namespaceId == ANDROID_SOCKET_NAMESPACE_RESERVED
diff --git a/libcutils/socket_network_client.c b/libcutils/socket_network_client.c
index 4826033..e0031ba 100644
--- a/libcutils/socket_network_client.c
+++ b/libcutils/socket_network_client.c
@@ -45,7 +45,6 @@
 {
     struct hostent *hp;
     struct sockaddr_in addr;
-    socklen_t alen;
     int s;
     int flags = 0, error = 0, ret = 0;
     fd_set rset, wset;
diff --git a/libcutils/tests/Android.mk b/libcutils/tests/Android.mk
index 8e65310..5a54698 100644
--- a/libcutils/tests/Android.mk
+++ b/libcutils/tests/Android.mk
@@ -19,6 +19,7 @@
     PropertiesTest.cpp \
 
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE := libcutils_test
 LOCAL_SRC_FILES := $(test_src_files)
 LOCAL_SHARED_LIBRARIES := \
@@ -31,18 +32,21 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 include $(BUILD_NATIVE_TEST)
 
-include $(CLEAR_VARS)
-LOCAL_MODULE := libcutils_test_static
-LOCAL_FORCE_STATIC_EXECUTABLE := true
-LOCAL_SRC_FILES := $(test_src_files)
-LOCAL_STATIC_LIBRARIES := \
-    libc \
-    libcutils \
-    liblog \
-    libstlport_static \
-    libutils \
+# The static libcutils tests cannot be built when using libc++ because there are
+# multiple symbol definition errors between libc++ and libgcc. b/18389856
+#include $(CLEAR_VARS)
+#LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+#LOCAL_MODULE := libcutils_test_static
+#LOCAL_FORCE_STATIC_EXECUTABLE := true
+#LOCAL_SRC_FILES := $(test_src_files)
+#LOCAL_STATIC_LIBRARIES := \
+#    libc \
+#    libcutils \
+#    liblog \
+#    libutils \
 
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-include $(BUILD_NATIVE_TEST)
+#LOCAL_CXX_STL := stlport_static
+#LOCAL_MULTILIB := both
+#LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+#LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+#include $(BUILD_NATIVE_TEST)
diff --git a/libcutils/trace.c b/libcutils/trace.c
index f57aac2..4396625 100644
--- a/libcutils/trace.c
+++ b/libcutils/trace.c
@@ -30,6 +30,13 @@
 #define LOG_TAG "cutils-trace"
 #include <log/log.h>
 
+/**
+ * Maximum size of a message that can be logged to the trace buffer.
+ * Note this message includes a tag, the pid, and the string given as the name.
+ * Names should be kept short to get the most use of the trace buffer.
+ */
+#define ATRACE_MESSAGE_LENGTH 1024
+
 volatile int32_t        atrace_is_ready      = 0;
 int                     atrace_marker_fd     = -1;
 uint64_t                atrace_enabled_tags  = ATRACE_TAG_NOT_READY;
@@ -183,3 +190,53 @@
 {
     pthread_once(&atrace_once_control, atrace_init_once);
 }
+
+void atrace_begin_body(const char* name)
+{
+    char buf[ATRACE_MESSAGE_LENGTH];
+    size_t len;
+
+    len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "B|%d|%s", getpid(), name);
+    write(atrace_marker_fd, buf, len);
+}
+
+
+void atrace_async_begin_body(const char* name, int32_t cookie)
+{
+    char buf[ATRACE_MESSAGE_LENGTH];
+    size_t len;
+
+    len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "S|%d|%s|%" PRId32,
+            getpid(), name, cookie);
+    write(atrace_marker_fd, buf, len);
+}
+
+void atrace_async_end_body(const char* name, int32_t cookie)
+{
+    char buf[ATRACE_MESSAGE_LENGTH];
+    size_t len;
+
+    len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "F|%d|%s|%" PRId32,
+            getpid(), name, cookie);
+    write(atrace_marker_fd, buf, len);
+}
+
+void atrace_int_body(const char* name, int32_t value)
+{
+    char buf[ATRACE_MESSAGE_LENGTH];
+    size_t len;
+
+    len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "C|%d|%s|%" PRId32,
+            getpid(), name, value);
+    write(atrace_marker_fd, buf, len);
+}
+
+void atrace_int64_body(const char* name, int64_t value)
+{
+    char buf[ATRACE_MESSAGE_LENGTH];
+    size_t len;
+
+    len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "C|%d|%s|%" PRId64,
+            getpid(), name, value);
+    write(atrace_marker_fd, buf, len);
+}
diff --git a/libion/ion.c b/libion/ion.c
index 80bdc2a..a79525d 100644
--- a/libion/ion.c
+++ b/libion/ion.c
@@ -117,7 +117,6 @@
 
 int ion_share(int fd, ion_user_handle_t handle, int *share_fd)
 {
-    int map_fd;
     int ret;
     struct ion_fd_data data = {
         .handle = handle,
diff --git a/libion/ion_test.c b/libion/ion_test.c
index 8872282..b7d5583 100644
--- a/libion/ion_test.c
+++ b/libion/ion_test.c
@@ -164,8 +164,9 @@
         printf("master->master? [%10s]\n", ptr);
         if (recvmsg(sd[0], &msg, 0) < 0)
             perror("master recv 1");
+        close(fd);
+        _exit(0);
     } else {
-        struct msghdr msg;
         struct cmsghdr *cmsg;
         char* ptr;
         int fd, recv_fd;
@@ -205,6 +206,7 @@
         strcpy(ptr, "child");
         printf("child sending msg 2\n");
         sendmsg(sd[1], &child_msg, 0);
+        close(fd);
     }
 }
 
diff --git a/libion/tests/Android.mk b/libion/tests/Android.mk
index 8dc7f9d..abf527a 100644
--- a/libion/tests/Android.mk
+++ b/libion/tests/Android.mk
@@ -21,7 +21,6 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_CFLAGS += -g -Wall -Werror -std=gnu++11 -Wno-missing-field-initializers
 LOCAL_SHARED_LIBRARIES += libion
-LOCAL_STATIC_LIBRARIES += libgtest_main
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/../kernel-headers
 LOCAL_SRC_FILES := \
 	ion_test_fixture.cpp \
diff --git a/liblog/fake_log_device.c b/liblog/fake_log_device.c
index 136792d..117e154 100644
--- a/liblog/fake_log_device.c
+++ b/liblog/fake_log_device.c
@@ -320,9 +320,9 @@
     return priorityStrings[idx];
 }
 
-#ifndef HAVE_WRITEV
+#if defined(_WIN32)
 /*
- * Some platforms like WIN32 do not have writev().
+ * WIN32 does not have writev().
  * Make up something to replace it.
  */
 static ssize_t fake_writev(int fd, const struct iovec *iov, int iovcnt) {
@@ -352,7 +352,7 @@
 static void showLog(LogState *state,
         int logPrio, const char* tag, const char* msg)
 {
-#if defined(HAVE_LOCALTIME_R)
+#if !defined(_WIN32)
     struct tm tmBuf;
 #endif
     struct tm* ptm;
@@ -377,7 +377,7 @@
      * in the time stamp.  Don't use forward slashes, parenthesis,
      * brackets, asterisks, or other special chars here.
      */
-#if defined(HAVE_LOCALTIME_R)
+#if !defined(_WIN32)
     ptm = localtime_r(&when, &tmBuf);
 #else
     ptm = localtime(&when);
diff --git a/liblog/log_read.c b/liblog/log_read.c
index ca5a1a7..2f21a5d 100644
--- a/liblog/log_read.c
+++ b/liblog/log_read.c
@@ -72,7 +72,7 @@
 
     switch (namespaceId) {
     case ANDROID_SOCKET_NAMESPACE_ABSTRACT:
-#ifdef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE
+#if defined(__linux__)
         namelen  = strlen(name);
 
         /* Test with length +1 for the *initial* '\0'. */
@@ -87,7 +87,7 @@
 
         p_addr->sun_path[0] = 0;
         memcpy(p_addr->sun_path + 1, name, namelen);
-#else /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/
+#else
         /* this OS doesn't have the Linux abstract namespace */
 
         namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX);
@@ -99,7 +99,7 @@
 
         strcpy(p_addr->sun_path, FILESYSTEM_SOCKET_PREFIX);
         strcat(p_addr->sun_path, name);
-#endif /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/
+#endif
         break;
 
     case ANDROID_SOCKET_NAMESPACE_RESERVED:
diff --git a/liblog/log_time.cpp b/liblog/log_time.cpp
index 755c2d9..50742df 100644
--- a/liblog/log_time.cpp
+++ b/liblog/log_time.cpp
@@ -39,7 +39,7 @@
 #endif
 
     struct tm *ptm;
-#if (defined(HAVE_LOCALTIME_R))
+#if !defined(_WIN32)
     struct tm tmBuf;
     ptm = localtime_r(&now, &tmBuf);
 #else
@@ -78,7 +78,7 @@
                 ++ret;
             }
             now = tv_sec;
-#if (defined(HAVE_LOCALTIME_R))
+#if !defined(_WIN32)
             ptm = localtime_r(&now, &tmBuf);
 #else
             ptm = localtime(&now);
@@ -150,6 +150,17 @@
     return *this;
 }
 
+log_time log_time::operator+= (const timespec &T) {
+    this->tv_nsec += (unsigned long int)T.tv_nsec;
+    if (this->tv_nsec >= NS_PER_SEC) {
+        this->tv_nsec -= NS_PER_SEC;
+        ++this->tv_sec;
+    }
+    this->tv_sec += T.tv_sec;
+
+    return *this;
+}
+
 log_time log_time::operator-= (const log_time &T) {
     // No concept of negative time, clamp to EPOCH
     if (*this <= T) {
@@ -166,3 +177,14 @@
 
     return *this;
 }
+
+log_time log_time::operator+= (const log_time &T) {
+    this->tv_nsec += T.tv_nsec;
+    if (this->tv_nsec >= NS_PER_SEC) {
+        this->tv_nsec -= NS_PER_SEC;
+        ++this->tv_sec;
+    }
+    this->tv_sec += T.tv_sec;
+
+    return *this;
+}
diff --git a/liblog/logprint.c b/liblog/logprint.c
index 08e830a..5987782 100644
--- a/liblog/logprint.c
+++ b/liblog/logprint.c
@@ -21,10 +21,12 @@
 #include <assert.h>
 #include <ctype.h>
 #include <errno.h>
+#include <stdbool.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/param.h>
 
 #include <log/logd.h>
 #include <log/logprint.h>
@@ -39,8 +41,23 @@
     android_LogPriority global_pri;
     FilterInfo *filters;
     AndroidLogPrintFormat format;
+    bool colored_output;
 };
 
+/*
+ *  gnome-terminal color tags
+ *    See http://misc.flogisoft.com/bash/tip_colors_and_formatting
+ *    for ideas on how to set the forground color of the text for xterm.
+ *    The color manipulation character stream is defined as:
+ *      ESC [ 3 8 ; 5 ; <color#> m
+ */
+#define ANDROID_COLOR_BLUE     75
+#define ANDROID_COLOR_DEFAULT 231
+#define ANDROID_COLOR_GREEN    40
+#define ANDROID_COLOR_ORANGE  166
+#define ANDROID_COLOR_RED     196
+#define ANDROID_COLOR_YELLOW  226
+
 static FilterInfo * filterinfo_new(const char * tag, android_LogPriority pri)
 {
     FilterInfo *p_ret;
@@ -110,6 +127,23 @@
     }
 }
 
+static int colorFromPri (android_LogPriority pri)
+{
+    switch (pri) {
+        case ANDROID_LOG_VERBOSE:       return ANDROID_COLOR_DEFAULT;
+        case ANDROID_LOG_DEBUG:         return ANDROID_COLOR_BLUE;
+        case ANDROID_LOG_INFO:          return ANDROID_COLOR_GREEN;
+        case ANDROID_LOG_WARN:          return ANDROID_COLOR_ORANGE;
+        case ANDROID_LOG_ERROR:         return ANDROID_COLOR_RED;
+        case ANDROID_LOG_FATAL:         return ANDROID_COLOR_RED;
+        case ANDROID_LOG_SILENT:        return ANDROID_COLOR_DEFAULT;
+
+        case ANDROID_LOG_DEFAULT:
+        case ANDROID_LOG_UNKNOWN:
+        default:                        return ANDROID_COLOR_DEFAULT;
+    }
+}
+
 static android_LogPriority filterPriForTag(
         AndroidLogFormat *p_format, const char *tag)
 {
@@ -149,6 +183,7 @@
 
     p_ret->global_pri = ANDROID_LOG_VERBOSE;
     p_ret->format = FORMAT_BRIEF;
+    p_ret->colored_output = false;
 
     return p_ret;
 }
@@ -174,7 +209,10 @@
 void android_log_setPrintFormat(AndroidLogFormat *p_format,
         AndroidLogPrintFormat format)
 {
-    p_format->format=format;
+    if (format == FORMAT_COLOR)
+        p_format->colored_output = true;
+    else
+        p_format->format = format;
 }
 
 /**
@@ -192,6 +230,7 @@
     else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
     else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
     else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
+    else if (strcmp(formatString, "color") == 0) format = FORMAT_COLOR;
     else format = FORMAT_OFF;
 
     return format;
@@ -305,15 +344,6 @@
     return -1;
 }
 
-static inline char * strip_end(char *str)
-{
-    char *end = str + strlen(str) - 1;
-
-    while (end >= str && isspace(*end))
-        *end-- = '\0';
-    return str;
-}
-
 /**
  * Splits a wire-format buffer into an AndroidLogEntry
  * entry allocated by caller. Pointers will point directly into buf
@@ -687,7 +717,7 @@
     const AndroidLogEntry *entry,
     size_t *p_outLength)
 {
-#if defined(HAVE_LOCALTIME_R)
+#if !defined(_WIN32)
     struct tm tmBuf;
 #endif
     struct tm* ptm;
@@ -698,6 +728,8 @@
     char * ret = NULL;
 
     priChar = filterPriToChar(entry->priority);
+    size_t prefixLen = 0, suffixLen = 0;
+    size_t len;
 
     /*
      * Get the current date/time in pretty form
@@ -708,7 +740,7 @@
      * in the time stamp.  Don't use forward slashes, parenthesis,
      * brackets, asterisks, or other special chars here.
      */
-#if defined(HAVE_LOCALTIME_R)
+#if !defined(_WIN32)
     ptm = localtime_r(&(entry->tv_sec), &tmBuf);
 #else
     ptm = localtime(&(entry->tv_sec));
@@ -719,73 +751,80 @@
     /*
      * Construct a buffer containing the log header and log message.
      */
-    size_t prefixLen, suffixLen;
+    if (p_format->colored_output) {
+        prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
+                             colorFromPri(entry->priority));
+        prefixLen = MIN(prefixLen, sizeof(prefixBuf));
+        suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
+        suffixLen = MIN(suffixLen, sizeof(suffixBuf));
+    }
 
     switch (p_format->format) {
         case FORMAT_TAG:
-            prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
+            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
                 "%c/%-8s: ", priChar, entry->tag);
-            strcpy(suffixBuf, "\n"); suffixLen = 1;
+            strcpy(suffixBuf + suffixLen, "\n");
+            ++suffixLen;
             break;
         case FORMAT_PROCESS:
-            prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
-                "%c(%5d) ", priChar, entry->pid);
-            suffixLen = snprintf(suffixBuf, sizeof(suffixBuf),
+            len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
                 "  (%s)\n", entry->tag);
+            suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
+            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
+                "%c(%5d) ", priChar, entry->pid);
             break;
         case FORMAT_THREAD:
-            prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
+            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
                 "%c(%5d:%5d) ", priChar, entry->pid, entry->tid);
-            strcpy(suffixBuf, "\n");
-            suffixLen = 1;
+            strcpy(suffixBuf + suffixLen, "\n");
+            ++suffixLen;
             break;
         case FORMAT_RAW:
-            prefixBuf[0] = 0;
-            prefixLen = 0;
-            strcpy(suffixBuf, "\n");
-            suffixLen = 1;
+            prefixBuf[prefixLen] = 0;
+            len = 0;
+            strcpy(suffixBuf + suffixLen, "\n");
+            ++suffixLen;
             break;
         case FORMAT_TIME:
-            prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
+            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
                 "%s.%03ld %c/%-8s(%5d): ", timeBuf, entry->tv_nsec / 1000000,
                 priChar, entry->tag, entry->pid);
-            strcpy(suffixBuf, "\n");
-            suffixLen = 1;
+            strcpy(suffixBuf + suffixLen, "\n");
+            ++suffixLen;
             break;
         case FORMAT_THREADTIME:
-            prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
+            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
                 "%s.%03ld %5d %5d %c %-8s: ", timeBuf, entry->tv_nsec / 1000000,
                 entry->pid, entry->tid, priChar, entry->tag);
-            strcpy(suffixBuf, "\n");
-            suffixLen = 1;
+            strcpy(suffixBuf + suffixLen, "\n");
+            ++suffixLen;
             break;
         case FORMAT_LONG:
-            prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
+            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
                 "[ %s.%03ld %5d:%5d %c/%-8s ]\n",
                 timeBuf, entry->tv_nsec / 1000000, entry->pid,
                 entry->tid, priChar, entry->tag);
-            strcpy(suffixBuf, "\n\n");
-            suffixLen = 2;
+            strcpy(suffixBuf + suffixLen, "\n\n");
+            suffixLen += 2;
             prefixSuffixIsHeaderFooter = 1;
             break;
         case FORMAT_BRIEF:
         default:
-            prefixLen = snprintf(prefixBuf, sizeof(prefixBuf),
+            len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
                 "%c/%-8s(%5d): ", priChar, entry->tag, entry->pid);
-            strcpy(suffixBuf, "\n");
-            suffixLen = 1;
+            strcpy(suffixBuf + suffixLen, "\n");
+            ++suffixLen;
             break;
     }
+
     /* snprintf has a weird return value.   It returns what would have been
      * written given a large enough buffer.  In the case that the prefix is
      * longer then our buffer(128), it messes up the calculations below
      * possibly causing heap corruption.  To avoid this we double check and
      * set the length at the maximum (size minus null byte)
      */
-    if(prefixLen >= sizeof(prefixBuf))
-        prefixLen = sizeof(prefixBuf) - 1;
-    if(suffixLen >= sizeof(suffixBuf))
-        suffixLen = sizeof(suffixBuf) - 1;
+    prefixLen += MIN(len, sizeof(prefixBuf) - prefixLen);
+    suffixLen = MIN(suffixLen, sizeof(suffixLen));
 
     /* the following code is tragically unreadable */
 
diff --git a/liblog/tests/Android.mk b/liblog/tests/Android.mk
index cd1bf33..172b186 100644
--- a/liblog/tests/Android.mk
+++ b/liblog/tests/Android.mk
@@ -43,10 +43,6 @@
 LOCAL_CFLAGS += $(benchmark_c_flags)
 LOCAL_SHARED_LIBRARIES += liblog libm
 LOCAL_SRC_FILES := $(benchmark_src_files)
-ifndef LOCAL_SDK_VERSION
-LOCAL_C_INCLUDES += bionic bionic/libstdc++/include external/stlport/stlport
-LOCAL_SHARED_LIBRARIES += libstlport
-endif
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
 include $(BUILD_EXECUTABLE)
 
@@ -71,7 +67,7 @@
 test_src_files += \
     libc_test.cpp
 
-ifndef ($(TARGET_USES_LOGD),false)
+ifneq ($(TARGET_USES_LOGD),false)
 test_c_flags += -DTARGET_USES_LOGD
 endif
 
diff --git a/liblog/tests/benchmark_main.cpp b/liblog/tests/benchmark_main.cpp
index 090394c..e5ef970 100644
--- a/liblog/tests/benchmark_main.cpp
+++ b/liblog/tests/benchmark_main.cpp
@@ -17,6 +17,7 @@
 #include <benchmark.h>
 
 #include <inttypes.h>
+#include <math.h>
 #include <regex.h>
 #include <stdio.h>
 #include <stdlib.h>
diff --git a/liblog/uio.c b/liblog/uio.c
index 24a6507..f77cc49 100644
--- a/liblog/uio.c
+++ b/liblog/uio.c
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef HAVE_SYS_UIO_H
+#if defined(_WIN32)
 
 #include <log/uio.h>
 #include <unistd.h>
@@ -73,4 +73,4 @@
     return total;
 }
 
-#endif /* !HAVE_SYS_UIO_H */
+#endif
diff --git a/libmemtrack/memtrack.c b/libmemtrack/memtrack.c
index 9a656df..5d68083 100644
--- a/libmemtrack/memtrack.c
+++ b/libmemtrack/memtrack.c
@@ -20,6 +20,7 @@
 
 #include <log/log.h>
 
+#include <errno.h>
 #include <hardware/memtrack.h>
 
 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
diff --git a/libmincrypt/Android.mk b/libmincrypt/Android.mk
index 7906986..503bcb4 100644
--- a/libmincrypt/Android.mk
+++ b/libmincrypt/Android.mk
@@ -6,6 +6,8 @@
 LOCAL_MODULE := libmincrypt
 LOCAL_SRC_FILES := dsa_sig.c p256.c p256_ec.c p256_ecdsa.c rsa.c sha.c sha256.c
 LOCAL_CFLAGS := -Wall -Werror
+# Clang's slp-vectorize phase has segmentation fault when compiling p256_ec.c.
+LOCAL_CLANG_CFLAGS += -fno-slp-vectorize
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
diff --git a/libnativebridge/tests/CompleteFlow_test.cpp b/libnativebridge/tests/CompleteFlow_test.cpp
index cf06d2c..b033792 100644
--- a/libnativebridge/tests/CompleteFlow_test.cpp
+++ b/libnativebridge/tests/CompleteFlow_test.cpp
@@ -36,6 +36,7 @@
 
     // Unload
     UnloadNativeBridge();
+
     ASSERT_FALSE(NativeBridgeAvailable());
     ASSERT_FALSE(NativeBridgeError());
 
diff --git a/libnetutils/dhcp_utils.c b/libnetutils/dhcp_utils.c
index e1df874..0f7c384 100644
--- a/libnetutils/dhcp_utils.c
+++ b/libnetutils/dhcp_utils.c
@@ -166,14 +166,6 @@
     return 0;
 }
 
-static const char *ipaddr_to_string(in_addr_t addr)
-{
-    struct in_addr in_addr;
-
-    in_addr.s_addr = addr;
-    return inet_ntoa(in_addr);
-}
-
 /*
  * Start the dhcp client daemon, and wait for it to finish
  * configuring the interface.
@@ -242,7 +234,6 @@
         return -1;
     }
     if (strcmp(prop_value, "ok") == 0) {
-        char dns_prop_name[PROPERTY_KEY_MAX];
         if (fill_ip_info(interface, ipaddr, gateway, prefixLength, dns,
                 server, lease, vendorInfo, domain, mtu) == -1) {
             return -1;
diff --git a/libnetutils/dhcpclient.c b/libnetutils/dhcpclient.c
index b58120e..700b02f 100644
--- a/libnetutils/dhcpclient.c
+++ b/libnetutils/dhcpclient.c
@@ -150,7 +150,7 @@
 
 void dump_dhcp_info(dhcp_info *info)
 {
-    char addr[20], gway[20], mask[20];
+    char addr[20], gway[20];
     ALOGD("--- dhcp %s (%d) ---",
             dhcp_type_to_name(info->type), info->type);
     strcpy(addr, ipaddr(info->ipaddr));
diff --git a/libnetutils/ifc_utils.c b/libnetutils/ifc_utils.c
index 913f51e..bfe7121 100644
--- a/libnetutils/ifc_utils.c
+++ b/libnetutils/ifc_utils.c
@@ -421,7 +421,6 @@
 
 int ifc_set_hwaddr(const char *name, const void *ptr)
 {
-    int r;
     struct ifreq ifr;
     ifc_init_ifr(name, &ifr);
 
diff --git a/libnetutils/packet.c b/libnetutils/packet.c
index 3cdefb0..a878dd3 100644
--- a/libnetutils/packet.c
+++ b/libnetutils/packet.c
@@ -41,7 +41,7 @@
 
 int open_raw_socket(const char *ifname __attribute__((unused)), uint8_t *hwaddr, int if_index)
 {
-    int s, flag;
+    int s;
     struct sockaddr_ll bindaddr;
 
     if((s = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) {
diff --git a/libpixelflinger/Android.mk b/libpixelflinger/Android.mk
index 484cf50..f1bd522 100644
--- a/libpixelflinger/Android.mk
+++ b/libpixelflinger/Android.mk
@@ -36,6 +36,7 @@
 
 ifeq ($(ARCH_ARM_HAVE_NEON),true)
 PIXELFLINGER_SRC_FILES_arm += col32cb16blend_neon.S
+PIXELFLINGER_CFLAGS_arm += -D__ARM_HAVE_NEON
 endif
 
 PIXELFLINGER_SRC_FILES_arm64 := \
@@ -44,11 +45,13 @@
 	arch-arm64/col32cb16blend.S \
 	arch-arm64/t32cb16blend.S \
 
+ifndef ARCH_MIPS_REV6
 PIXELFLINGER_SRC_FILES_mips := \
 	codeflinger/MIPSAssembler.cpp \
 	codeflinger/mips_disassem.c \
 	arch-mips/t32cb16blend.S \
 
+endif
 #
 # Shared library
 #
@@ -67,6 +70,10 @@
 LOCAL_SHARED_LIBRARIES += libhardware_legacy
 LOCAL_CFLAGS += -DWITH_LIB_HARDWARE
 endif
+# t32cb16blend.S does not compile with Clang.
+LOCAL_CLANG_ASFLAGS_arm += -no-integrated-as
+# arch-arm64/col32cb16blend.S does not compile with Clang.
+LOCAL_CLANG_ASFLAGS_arm64 += -no-integrated-as
 include $(BUILD_SHARED_LIBRARY)
 
 #
@@ -80,6 +87,10 @@
 LOCAL_SRC_FILES_arm64 := $(PIXELFLINGER_SRC_FILES_arm64)
 LOCAL_SRC_FILES_mips := $(PIXELFLINGER_SRC_FILES_mips)
 LOCAL_CFLAGS := $(PIXELFLINGER_CFLAGS)
+# t32cb16blend.S does not compile with Clang.
+LOCAL_CLANG_ASFLAGS_arm += -no-integrated-as
+# arch-arm64/col32cb16blend.S does not compile with Clang.
+LOCAL_CLANG_ASFLAGS_arm64 += -no-integrated-as
 include $(BUILD_STATIC_LIBRARY)
 
 
diff --git a/libpixelflinger/codeflinger/CodeCache.cpp b/libpixelflinger/codeflinger/CodeCache.cpp
index cfd2b37..d770302 100644
--- a/libpixelflinger/codeflinger/CodeCache.cpp
+++ b/libpixelflinger/codeflinger/CodeCache.cpp
@@ -201,8 +201,8 @@
         mCacheInUse += assemblySize;
         mWhen++;
         // synchronize caches...
-        void* base = assembly->base();
-        void* curr = (uint8_t*)base + assembly->size();
+        char* base = reinterpret_cast<char*>(assembly->base());
+        char* curr = reinterpret_cast<char*>(base + assembly->size());
         __builtin___clear_cache(base, curr);
     }
 
diff --git a/libpixelflinger/codeflinger/load_store.cpp b/libpixelflinger/codeflinger/load_store.cpp
index 0a46eaa..e5a1ae0 100644
--- a/libpixelflinger/codeflinger/load_store.cpp
+++ b/libpixelflinger/codeflinger/load_store.cpp
@@ -20,10 +20,6 @@
 #include <cutils/log.h>
 #include "GGLAssembler.h"
 
-#ifdef __ARM_ARCH__
-#include <machine/cpu-features.h>
-#endif
-
 namespace android {
 
 // ----------------------------------------------------------------------------
@@ -117,20 +113,6 @@
 #endif
     assert(h);
     
-#if __ARM_ARCH__ >= 7
-    const int mask = (1<<maskLen)-1;
-    if ((h == bits) && !l && (s != d.reg)) {
-        MOV(AL, 0, d.reg, s);                   // component = packed;
-    } else if ((h == bits) && l) {
-        MOV(AL, 0, d.reg, reg_imm(s, LSR, l));  // component = packed >> l;
-    } else if (!l && isValidImmediate(mask)) {
-        AND(AL, 0, d.reg, s, imm(mask));        // component = packed & mask;
-    } else if (!l && isValidImmediate(~mask)) {
-        BIC(AL, 0, d.reg, s, imm(~mask));       // component = packed & mask;
-    } else {
-        UBFX(AL, d.reg, s, l, maskLen);         // component = (packed & mask) >> l;
-    }
-#else
     if (h != bits) {
         const int mask = ((1<<maskLen)-1) << l;
         if (isValidImmediate(mask)) {
@@ -153,7 +135,6 @@
     if (s != d.reg) {
         MOV(AL, 0, d.reg, s);
     }
-#endif
 
     d.s = maskLen;
 }
diff --git a/libpixelflinger/codeflinger/texturing.cpp b/libpixelflinger/codeflinger/texturing.cpp
index 81950bf..29a3742 100644
--- a/libpixelflinger/codeflinger/texturing.cpp
+++ b/libpixelflinger/codeflinger/texturing.cpp
@@ -25,10 +25,6 @@
 
 #include "GGLAssembler.h"
 
-#ifdef __ARM_ARCH__
-#include <machine/cpu-features.h>
-#endif
-
 namespace android {
 
 // ---------------------------------------------------------------------------
@@ -888,106 +884,6 @@
     load(txPtr, texel, 0);
 }
 
-#if __ARM_ARCH__ >= 6
-// ARMv6 version, using UXTB16, and scheduled for Cortex-A8 pipeline
-void GGLAssembler::filter32(
-        const fragment_parts_t& parts,
-        pixel_t& texel, const texture_unit_t& tmu,
-        int U, int V, pointer_t& txPtr,
-        int FRAC_BITS)
-{
-    const int adjust = FRAC_BITS*2 - 8;
-    const int round  = 0;
-    const int prescale = 16 - adjust;
-
-    Scratch scratches(registerFile());
-    
-    int pixel= scratches.obtain();
-    int dh   = scratches.obtain();
-    int u    = scratches.obtain();
-    int k    = scratches.obtain();
-
-    int temp = scratches.obtain();
-    int dl   = scratches.obtain();
-
-    int offsetrt = scratches.obtain();
-    int offsetlb = scratches.obtain();
-
-    int pixellb = offsetlb;
-
-    // RB -> U * V
-    CONTEXT_LOAD(offsetrt, generated_vars.rt);
-    CONTEXT_LOAD(offsetlb, generated_vars.lb);
-    if(!round) {
-        MOV(AL, 0, U, reg_imm(U, LSL, prescale));
-    }
-    ADD(AL, 0, u, offsetrt, offsetlb);
-
-    LDR(AL, pixel, txPtr.reg, reg_scale_pre(u));
-    if (round) {
-        SMULBB(AL, u, U, V);
-        RSB(AL, 0, U, U, imm(1<<FRAC_BITS));
-    } else {
-        SMULWB(AL, u, U, V);
-        RSB(AL, 0, U, U, imm(1<<(FRAC_BITS+prescale)));
-    }
-    UXTB16(AL, temp, pixel, 0);
-    if (round) {
-        ADD(AL, 0, u, u, imm(1<<(adjust-1)));
-        MOV(AL, 0, u, reg_imm(u, LSR, adjust));
-    }
-    LDR(AL, pixellb, txPtr.reg, reg_scale_pre(offsetlb));
-    MUL(AL, 0, dh, temp, u);
-    UXTB16(AL, temp, pixel, 8);
-    MUL(AL, 0, dl, temp, u);
-    RSB(AL, 0, k, u, imm(0x100));
-
-    // LB -> (1-U) * V
-    if (round) {
-        SMULBB(AL, u, U, V);
-    } else {
-        SMULWB(AL, u, U, V);
-    }
-    UXTB16(AL, temp, pixellb, 0);
-    if (round) {
-        ADD(AL, 0, u, u, imm(1<<(adjust-1)));
-        MOV(AL, 0, u, reg_imm(u, LSR, adjust));
-    }
-    MLA(AL, 0, dh, temp, u, dh);    
-    UXTB16(AL, temp, pixellb, 8);
-    MLA(AL, 0, dl, temp, u, dl);
-    SUB(AL, 0, k, k, u);
-
-    // LT -> (1-U)*(1-V)
-    RSB(AL, 0, V, V, imm(1<<FRAC_BITS));
-    LDR(AL, pixel, txPtr.reg);
-    if (round) {
-        SMULBB(AL, u, U, V);
-    } else {
-        SMULWB(AL, u, U, V);
-    }
-    UXTB16(AL, temp, pixel, 0);
-    if (round) {
-        ADD(AL, 0, u, u, imm(1<<(adjust-1)));
-        MOV(AL, 0, u, reg_imm(u, LSR, adjust));
-    }
-    MLA(AL, 0, dh, temp, u, dh);    
-    UXTB16(AL, temp, pixel, 8);
-    MLA(AL, 0, dl, temp, u, dl);
-
-    // RT -> U*(1-V)            
-    LDR(AL, pixel, txPtr.reg, reg_scale_pre(offsetrt));
-    SUB(AL, 0, u, k, u);
-    UXTB16(AL, temp, pixel, 0);
-    MLA(AL, 0, dh, temp, u, dh);    
-    UXTB16(AL, temp, pixel, 8);
-    MLA(AL, 0, dl, temp, u, dl);
-
-    UXTB16(AL, dh, dh, 8);
-    UXTB16(AL, dl, dl, 8);
-    ORR(AL, 0, texel.reg, dh, reg_imm(dl, LSL, 8));
-}
-#else
 void GGLAssembler::filter32(
         const fragment_parts_t& /*parts*/,
         pixel_t& texel, const texture_unit_t& /*tmu*/,
@@ -1075,7 +971,6 @@
     AND(AL, 0, dl, dl, reg_imm(mask, LSL, 8));
     ORR(AL, 0, texel.reg, dh, dl);
 }
-#endif
 
 void GGLAssembler::build_texture_environment(
         component_t& fragment,
diff --git a/libpixelflinger/pixelflinger.cpp b/libpixelflinger/pixelflinger.cpp
index ea5bc8e..fd449b2 100644
--- a/libpixelflinger/pixelflinger.cpp
+++ b/libpixelflinger/pixelflinger.cpp
@@ -727,18 +727,10 @@
 
 int64_t ggl_system_time()
 {
-#if defined(HAVE_POSIX_CLOCKS)
     struct timespec t;
     t.tv_sec = t.tv_nsec = 0;
     clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t);
     return int64_t(t.tv_sec)*1000000000LL + t.tv_nsec;
-#else
-    // we don't support the clocks here.
-    struct timeval t;
-    t.tv_sec = t.tv_usec = 0;
-    gettimeofday(&t, NULL);
-    return int64_t(t.tv_sec)*1000000000LL + int64_t(t.tv_usec)*1000LL;
-#endif
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libpixelflinger/scanline.cpp b/libpixelflinger/scanline.cpp
index 26b9a3e..3d14531 100644
--- a/libpixelflinger/scanline.cpp
+++ b/libpixelflinger/scanline.cpp
@@ -39,7 +39,7 @@
 #include "codeflinger/ARMAssembler.h"
 #elif defined(__aarch64__)
 #include "codeflinger/Arm64Assembler.h"
-#elif defined(__mips__) && !defined(__LP64__)
+#elif defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6
 #include "codeflinger/MIPSAssembler.h"
 #endif
 //#include "codeflinger/ARMAssemblerOptimizer.h"
@@ -59,7 +59,7 @@
 #   define ANDROID_CODEGEN      ANDROID_CODEGEN_GENERATED
 #endif
 
-#if defined(__arm__) || (defined(__mips__) && !defined(__LP64__)) || defined(__aarch64__)
+#if defined(__arm__) || (defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6) || defined(__aarch64__)
 #   define ANDROID_ARM_CODEGEN  1
 #else
 #   define ANDROID_ARM_CODEGEN  0
@@ -73,7 +73,7 @@
  */
 #define DEBUG_NEEDS  0
 
-#if defined( __mips__) && !defined(__LP64__)
+#if defined( __mips__) && !defined(__LP64__) && __mips_isa_rev < 6
 #define ASSEMBLY_SCRATCH_SIZE   4096
 #elif defined(__aarch64__)
 #define ASSEMBLY_SCRATCH_SIZE   8192
@@ -134,7 +134,7 @@
 #elif defined(__aarch64__)
 extern "C" void scanline_t32cb16blend_arm64(uint16_t*, uint32_t*, size_t);
 extern "C" void scanline_col32cb16blend_arm64(uint16_t *dst, uint32_t col, size_t ct);
-#elif defined(__mips__)  && !defined(__LP64__)
+#elif defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6
 extern "C" void scanline_t32cb16blend_mips(uint16_t*, uint32_t*, size_t);
 #endif
 
@@ -286,7 +286,7 @@
 
 #if ANDROID_ARM_CODEGEN
 
-#if defined(__mips__)
+#if defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6
 static CodeCache gCodeCache(32 * 1024);
 #elif defined(__aarch64__)
 static CodeCache gCodeCache(48 * 1024);
@@ -2175,7 +2175,7 @@
 
 void scanline_t32cb16blend(context_t* c)
 {
-#if ((ANDROID_CODEGEN >= ANDROID_CODEGEN_ASM) && (defined(__arm__) || (defined(__mips__) && !defined(__LP64__)) || defined(__aarch64__)))
+#if ((ANDROID_CODEGEN >= ANDROID_CODEGEN_ASM) && (defined(__arm__) || (defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6) || defined(__aarch64__)))
     int32_t x = c->iterators.xl;
     size_t ct = c->iterators.xr - x;
     int32_t y = c->iterators.y;
diff --git a/libpixelflinger/tests/arch-arm64/assembler/Android.mk b/libpixelflinger/tests/arch-arm64/assembler/Android.mk
index eca36ef..961f323 100644
--- a/libpixelflinger/tests/arch-arm64/assembler/Android.mk
+++ b/libpixelflinger/tests/arch-arm64/assembler/Android.mk
@@ -5,6 +5,9 @@
     arm64_assembler_test.cpp\
     asm_test_jacket.S
 
+# asm_test_jacket.S does not compile with Clang.
+LOCAL_CLANG_ASFLAGS_arm64 += -no-integrated-as
+
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
     libpixelflinger
diff --git a/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp b/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp
index 456be58..5f58797 100644
--- a/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp
+++ b/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp
@@ -409,7 +409,7 @@
 {
     const long base = long(instrMem);
     const long curr = base + long(instrMemSize);
-    __builtin___clear_cache((void*)base, (void*)curr);
+    __builtin___clear_cache((char*)base, (char*)curr);
 }
 void dataOpTest(dataOpTest_t test, ARMAssemblerInterface *a64asm, uint32_t Rd = 0,
                 uint32_t Rn = 1, uint32_t Rm = 2, uint32_t Rs = 3)
@@ -493,16 +493,17 @@
         if(i == Rd) continue;
         if(regs[i] != savedRegs[i])
         {
-            printf("Test %x failed Reg(%d) tampered Expected(0x%"PRIx64"),"
-                   "Actual(0x%"PRIx64") t\n", test.id, i, savedRegs[i], regs[i]);
+            printf("Test %x failed Reg(%d) tampered Expected(0x%" PRIx64 "),"
+                   "Actual(0x%" PRIx64 ") t\n", test.id, i, savedRegs[i],
+                   regs[i]);
             return;
         }
     }
 
     if(test.checkRd == 1 && (uint64_t)regs[Rd] != test.postRdValue)
     {
-        printf("Test %x failed, Expected(%"PRIx64"), Actual(%"PRIx64")\n",
-                test.id, test.postRdValue, regs[Rd]);
+        printf("Test %x failed, Expected(%" PRIx64 "), Actual(%" PRIx64 ")\n",
+               test.id, test.postRdValue, regs[Rd]);
     }
     else if(test.checkFlag == 1 && flags[test.postFlag] == 0)
     {
@@ -610,7 +611,7 @@
         if(regs[i] != savedRegs[i])
         {
             printf("Test %x failed Reg(%d) tampered"
-                   " Expected(0x%"PRIx64"), Actual(0x%"PRIx64") t\n",
+                   " Expected(0x%" PRIx64 "), Actual(0x%" PRIx64 ") t\n",
                    test.id, i, savedRegs[i], regs[i]);
             return;
         }
@@ -619,13 +620,13 @@
     if((uint64_t)regs[Rd] != test.postRdValue)
     {
         printf("Test %x failed, "
-               "Expected in Rd(0x%"PRIx64"), Actual(0x%"PRIx64")\n",
+               "Expected in Rd(0x%" PRIx64 "), Actual(0x%" PRIx64 ")\n",
                test.id, test.postRdValue, regs[Rd]);
     }
     else if((uint64_t)regs[Rn] != (uint64_t)(&dataMem[test.postRnValue]))
     {
         printf("Test %x failed, "
-               "Expected in Rn(0x%"PRIx64"), Actual(0x%"PRIx64")\n",
+               "Expected in Rn(0x%" PRIx64 "), Actual(0x%" PRIx64 ")\n",
                test.id, test.postRnValue, regs[Rn] - (uint64_t)dataMem);
     }
     else if(test.checkMem == true)
@@ -638,7 +639,7 @@
         if(value != test.postMemValue)
         {
             printf("Test %x failed, "
-                   "Expected in Mem(0x%"PRIx64"), Actual(0x%"PRIx64")\n",
+                   "Expected in Mem(0x%" PRIx64 "), Actual(0x%" PRIx64 ")\n",
                    test.id, test.postMemValue, value);
         }
         else
@@ -697,8 +698,8 @@
                 if(regs[j] != j)
                 {
                     printf("LDM/STM Test %x failed "
-                           "Reg%d expected(0x%x) Actual(0x%"PRIx64") \n",
-                            patterns[i],j,j,regs[j]);
+                           "Reg%d expected(0x%x) Actual(0x%" PRIx64 ") \n",
+                           patterns[i], j, j, regs[j]);
                     break;
                 }
             }
diff --git a/libpixelflinger/tests/arch-arm64/col32cb16blend/Android.mk b/libpixelflinger/tests/arch-arm64/col32cb16blend/Android.mk
index 3368eb0..5d69203 100644
--- a/libpixelflinger/tests/arch-arm64/col32cb16blend/Android.mk
+++ b/libpixelflinger/tests/arch-arm64/col32cb16blend/Android.mk
@@ -5,6 +5,8 @@
     col32cb16blend_test.c \
     ../../../arch-arm64/col32cb16blend.S
 
+LOCAL_CLANG_ASFLAGS_arm64 += -no-integrated-as
+
 LOCAL_SHARED_LIBRARIES :=
 
 LOCAL_C_INCLUDES :=
diff --git a/libpixelflinger/tests/arch-arm64/t32cb16blend/Android.mk b/libpixelflinger/tests/arch-arm64/t32cb16blend/Android.mk
index 8e5ec5e..2c1379b 100644
--- a/libpixelflinger/tests/arch-arm64/t32cb16blend/Android.mk
+++ b/libpixelflinger/tests/arch-arm64/t32cb16blend/Android.mk
@@ -5,6 +5,8 @@
     t32cb16blend_test.c \
     ../../../arch-arm64/t32cb16blend.S
 
+LOCAL_CLANG_ASFLAGS_arm64 += -no-integrated-as
+
 LOCAL_SHARED_LIBRARIES :=
 
 LOCAL_C_INCLUDES :=
diff --git a/libpixelflinger/tests/codegen/codegen.cpp b/libpixelflinger/tests/codegen/codegen.cpp
index 46c1ccc..148b6f4 100644
--- a/libpixelflinger/tests/codegen/codegen.cpp
+++ b/libpixelflinger/tests/codegen/codegen.cpp
@@ -9,16 +9,18 @@
 #include "codeflinger/CodeCache.h"
 #include "codeflinger/GGLAssembler.h"
 #include "codeflinger/ARMAssembler.h"
+#if defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6
 #include "codeflinger/MIPSAssembler.h"
+#endif
 #include "codeflinger/Arm64Assembler.h"
 
-#if defined(__arm__) || defined(__mips__) || defined(__aarch64__)
+#if defined(__arm__) || (defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6) || defined(__aarch64__)
 #   define ANDROID_ARM_CODEGEN  1
 #else
 #   define ANDROID_ARM_CODEGEN  0
 #endif
 
-#if defined (__mips__)
+#if defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6
 #define ASSEMBLY_SCRATCH_SIZE   4096
 #elif defined(__aarch64__)
 #define ASSEMBLY_SCRATCH_SIZE   8192
@@ -52,7 +54,7 @@
     GGLAssembler assembler( new ARMAssembler(a) );
 #endif
 
-#if defined(__mips__) && !defined(__LP64__)
+#if defined(__mips__) && !defined(__LP64__) && __mips_isa_rev < 6
     GGLAssembler assembler( new ArmToMipsAssembler(a) );
 #endif
 
diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp
index 49f5903..a80965f 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -19,7 +19,9 @@
 
 #include <assert.h>
 #include <dirent.h>
+#include <errno.h>
 #include <fcntl.h>
+#include <inttypes.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -100,7 +102,7 @@
 
     ctx->buf_len += ret;
     ctx->buf[ctx->buf_len] = 0;
-    SLOGV("Read %d to buffer: %s", ret, ctx->buf);
+    SLOGV("Read %zd to buffer: %s", ret, ctx->buf);
 
     assert(ctx->buf_len <= sizeof(ctx->buf));
 
@@ -251,7 +253,7 @@
 {
     int processes;
     int sleep_us = 100;
-    long startTime = android::uptimeMillis();
+    int64_t startTime = android::uptimeMillis();
 
     while ((processes = killProcessGroupOnce(uid, initialPid, signal)) > 0) {
         SLOGV("killed %d processes for processgroup %d\n", processes, initialPid);
@@ -265,7 +267,7 @@
         }
     }
 
-    SLOGV("Killed process group uid %d pid %d in %ldms, %d procs remain", uid, initialPid,
+    SLOGV("Killed process group uid %d pid %d in %" PRId64 "ms, %d procs remain", uid, initialPid,
             android::uptimeMillis()-startTime, processes);
 
     if (processes == 0) {
@@ -279,12 +281,12 @@
 {
     int ret;
 
-    ret = mkdir(path, 0750);
+    ret = mkdir(path, mode);
     if (ret < 0 && errno != EEXIST) {
         return -errno;
     }
 
-    ret = chown(path, AID_SYSTEM, AID_SYSTEM);
+    ret = chown(path, uid, gid);
     if (ret < 0) {
         ret = -errno;
         rmdir(path);
diff --git a/libsparse/Android.mk b/libsparse/Android.mk
index 0abe33d..925b98b 100644
--- a/libsparse/Android.mk
+++ b/libsparse/Android.mk
@@ -16,7 +16,7 @@
 LOCAL_SRC_FILES := $(libsparse_src_files)
 LOCAL_MODULE := libsparse_host
 LOCAL_STATIC_LIBRARIES := libz
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/include external/zlib
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
 LOCAL_CFLAGS := -Werror
 include $(BUILD_HOST_STATIC_LIBRARY)
 
@@ -25,7 +25,7 @@
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
 LOCAL_SRC_FILES := $(libsparse_src_files)
 LOCAL_MODULE := libsparse
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/include external/zlib
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/include
 LOCAL_SHARED_LIBRARIES := \
     libz
 LOCAL_CFLAGS := -Werror
@@ -36,7 +36,7 @@
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
 LOCAL_SRC_FILES := $(libsparse_src_files)
 LOCAL_MODULE := libsparse_static
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/include external/zlib
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/include
 LOCAL_STATIC_LIBRARIES := libz
 LOCAL_CFLAGS := -Werror
 include $(BUILD_STATIC_LIBRARY)
diff --git a/libsuspend/autosuspend_autosleep.c b/libsuspend/autosuspend_autosleep.c
index 5451615..0d31e74 100644
--- a/libsuspend/autosuspend_autosleep.c
+++ b/libsuspend/autosuspend_autosleep.c
@@ -84,7 +84,6 @@
 
 struct autosuspend_ops *autosuspend_autosleep_init(void)
 {
-    int ret;
     char buf[80];
 
     autosleep_fd = open(SYS_POWER_AUTOSLEEP, O_WRONLY);
diff --git a/libsysutils/src/SocketClient.cpp b/libsysutils/src/SocketClient.cpp
index d3ce8f5..8358823 100644
--- a/libsysutils/src/SocketClient.cpp
+++ b/libsysutils/src/SocketClient.cpp
@@ -220,7 +220,9 @@
 
     sigaction(SIGPIPE, &old_action, &new_action);
 
-    errno = e;
+    if (e != 0) {
+        errno = e;
+    }
     return ret;
 }
 
diff --git a/libutils/Android.mk b/libutils/Android.mk
index b1dc1f8..52de910 100644
--- a/libutils/Android.mk
+++ b/libutils/Android.mk
@@ -53,13 +53,6 @@
 endif
 endif
 
-host_commonLdlibs :=
-
-ifeq ($(TARGET_OS),linux)
-host_commonLdlibs += -lrt -ldl
-endif
-
-
 # For the host
 # =====================================================
 include $(CLEAR_VARS)
@@ -67,6 +60,9 @@
 ifeq ($(HOST_OS), linux)
 LOCAL_SRC_FILES += Looper.cpp
 endif
+ifeq ($(HOST_OS),darwin)
+LOCAL_CFLAGS += -Wno-unused-parameter
+endif
 LOCAL_MODULE:= libutils
 LOCAL_STATIC_LIBRARIES := liblog
 LOCAL_CFLAGS += $(host_commonCflags)
@@ -90,10 +86,6 @@
 endif
 LOCAL_CFLAGS += -Werror
 
-LOCAL_C_INCLUDES += \
-		bionic/libc \
-		external/zlib
-
 LOCAL_STATIC_LIBRARIES := \
 	libcutils
 
@@ -102,8 +94,6 @@
         liblog \
         libdl
 
-include external/stlport/libstlport.mk
-
 LOCAL_MODULE:= libutils
 include $(BUILD_STATIC_LIBRARY)
 
@@ -119,8 +109,6 @@
         liblog
 LOCAL_CFLAGS := -Werror
 
-include external/stlport/libstlport.mk
-
 include $(BUILD_SHARED_LIBRARY)
 
 # Include subdirectory makefiles
diff --git a/libutils/FileMap.cpp b/libutils/FileMap.cpp
index f8d6bda..f49b4f9 100644
--- a/libutils/FileMap.cpp
+++ b/libutils/FileMap.cpp
@@ -23,7 +23,7 @@
 #include <utils/FileMap.h>
 #include <utils/Log.h>
 
-#if defined(HAVE_WIN32_FILEMAP) && !defined(__USE_MINGW_ANSI_STDIO)
+#if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO)
 # define PRId32 "I32d"
 # define PRIx32 "I32x"
 # define PRId64 "I64d"
@@ -33,7 +33,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 
-#ifdef HAVE_POSIX_FILEMAP
+#if !defined(__MINGW32__)
 #include <sys/mman.h>
 #endif
 
@@ -64,12 +64,7 @@
     if (mFileName != NULL) {
         free(mFileName);
     }
-#ifdef HAVE_POSIX_FILEMAP
-    if (mBasePtr && munmap(mBasePtr, mBaseLength) != 0) {
-        ALOGD("munmap(%p, %zu) failed\n", mBasePtr, mBaseLength);
-    }
-#endif
-#ifdef HAVE_WIN32_FILEMAP
+#if defined(__MINGW32__)
     if (mBasePtr && UnmapViewOfFile(mBasePtr) == 0) {
         ALOGD("UnmapViewOfFile(%p) failed, error = %" PRId32 "\n", mBasePtr,
               GetLastError() );
@@ -77,6 +72,10 @@
     if (mFileMapping != INVALID_HANDLE_VALUE) {
         CloseHandle(mFileMapping);
     }
+#else
+    if (mBasePtr && munmap(mBasePtr, mBaseLength) != 0) {
+        ALOGD("munmap(%p, %zu) failed\n", mBasePtr, mBaseLength);
+    }
 #endif
 }
 
@@ -90,7 +89,7 @@
 bool FileMap::create(const char* origFileName, int fd, off64_t offset, size_t length,
         bool readOnly)
 {
-#ifdef HAVE_WIN32_FILEMAP
+#if defined(__MINGW32__)
     int     adjust;
     off64_t adjOffset;
     size_t  adjLength;
@@ -128,8 +127,7 @@
         mFileMapping = INVALID_HANDLE_VALUE;
         return false;
     }
-#endif
-#ifdef HAVE_POSIX_FILEMAP
+#else // !defined(__MINGW32__)
     int     prot, flags, adjust;
     off64_t adjOffset;
     size_t  adjLength;
@@ -179,7 +177,7 @@
         return false;
     }
     mBasePtr = ptr;
-#endif // HAVE_POSIX_FILEMAP
+#endif // !defined(__MINGW32__)
 
     mFileName = origFileName != NULL ? strdup(origFileName) : NULL;
     mBaseLength = adjLength;
@@ -196,9 +194,9 @@
 }
 
 // Provide guidance to the system.
+#if !defined(_WIN32)
 int FileMap::advise(MapAdvice advice)
 {
-#if HAVE_MADVISE
     int cc, sysAdvice;
 
     switch (advice) {
@@ -216,7 +214,11 @@
     if (cc != 0)
         ALOGW("madvise(%d) failed: %s\n", sysAdvice, strerror(errno));
     return cc;
-#else
-    return -1;
-#endif // HAVE_MADVISE
 }
+
+#else
+int FileMap::advise(MapAdvice /* advice */)
+{
+    return -1;
+}
+#endif
diff --git a/libutils/String8.cpp b/libutils/String8.cpp
index 9092cbc..3323b82 100644
--- a/libutils/String8.cpp
+++ b/libutils/String8.cpp
@@ -424,7 +424,7 @@
             next = len;
         }
 
-        memcpy(buf + tail, buf + index + skip, next - index - skip);
+        memmove(buf + tail, buf + index + skip, next - index - skip);
         tail += next - index - skip;
         index = next;
     }
diff --git a/libutils/SystemClock.cpp b/libutils/SystemClock.cpp
index dbad581..ac3dd98 100644
--- a/libutils/SystemClock.cpp
+++ b/libutils/SystemClock.cpp
@@ -68,7 +68,7 @@
  */
 #define DEBUG_TIMESTAMP         0
 
-#if DEBUG_TIMESTAMP && defined(ARCH_ARM)
+#if DEBUG_TIMESTAMP && defined(__arm__)
 static inline void checkTimeStamps(int64_t timestamp,
                                    int64_t volatile *prevTimestampPtr,
                                    int volatile *prevMethodPtr,
diff --git a/libutils/Threads.cpp b/libutils/Threads.cpp
index b09d510..b2c6903 100644
--- a/libutils/Threads.cpp
+++ b/libutils/Threads.cpp
@@ -28,9 +28,6 @@
 # include <pthread.h>
 # include <sched.h>
 # include <sys/resource.h>
-#ifdef HAVE_ANDROID_OS
-# include <private/bionic_pthread.h>
-#endif
 #elif defined(HAVE_WIN32_THREADS)
 # include <windows.h>
 # include <stdint.h>
@@ -38,7 +35,7 @@
 # define HAVE_CREATETHREAD  // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
 #endif
 
-#if defined(HAVE_PRCTL)
+#if defined(__linux__)
 #include <sys/prctl.h>
 #endif
 
@@ -103,7 +100,7 @@
 };
 
 void androidSetThreadName(const char* name) {
-#if defined(HAVE_PRCTL)
+#if defined(__linux__)
     // Mac OS doesn't have this, and we build libutil for the host too
     int hasAt = 0;
     int hasDot = 0;
@@ -306,15 +303,6 @@
     gCreateThreadFn = func;
 }
 
-pid_t androidGetTid()
-{
-#ifdef HAVE_GETTID
-    return gettid();
-#else
-    return getpid();
-#endif
-}
-
 #ifdef HAVE_ANDROID_OS
 int androidSetThreadPriority(pid_t tid, int pri)
 {
@@ -864,7 +852,7 @@
     pid_t tid;
     if (mRunning) {
         pthread_t pthread = android_thread_id_t_to_pthread(mThread);
-        tid = __pthread_gettid(pthread);
+        tid = pthread_gettid_np(pthread);
     } else {
         ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
         tid = -1;
diff --git a/libutils/Unicode.cpp b/libutils/Unicode.cpp
index 378d2a7..fb876c9 100644
--- a/libutils/Unicode.cpp
+++ b/libutils/Unicode.cpp
@@ -24,17 +24,10 @@
 # undef  nhtos
 # undef  htons
 
-# ifdef HAVE_LITTLE_ENDIAN
-#  define ntohl(x)    ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
-#  define htonl(x)    ntohl(x)
-#  define ntohs(x)    ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
-#  define htons(x)    ntohs(x)
-# else
-#  define ntohl(x)    (x)
-#  define htonl(x)    (x)
-#  define ntohs(x)    (x)
-#  define htons(x)    (x)
-# endif
+# define ntohl(x)    ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
+# define htonl(x)    ntohl(x)
+# define ntohs(x)    ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
+# define htons(x)    ntohs(x)
 #else
 # include <netinet/in.h>
 #endif
@@ -47,8 +40,9 @@
 // Surrogates aren't valid for UTF-32 characters, so define some
 // constants that will let us screen them out.
 static const char32_t kUnicodeSurrogateHighStart  = 0x0000D800;
-static const char32_t kUnicodeSurrogateHighEnd    = 0x0000DBFF;
-static const char32_t kUnicodeSurrogateLowStart   = 0x0000DC00;
+// Unused, here for completeness:
+// static const char32_t kUnicodeSurrogateHighEnd = 0x0000DBFF;
+// static const char32_t kUnicodeSurrogateLowStart = 0x0000DC00;
 static const char32_t kUnicodeSurrogateLowEnd     = 0x0000DFFF;
 static const char32_t kUnicodeSurrogateStart      = kUnicodeSurrogateHighStart;
 static const char32_t kUnicodeSurrogateEnd        = kUnicodeSurrogateLowEnd;
diff --git a/libutils/tests/Android.mk b/libutils/tests/Android.mk
index caedaff..634f44f 100644
--- a/libutils/tests/Android.mk
+++ b/libutils/tests/Android.mk
@@ -1,9 +1,28 @@
-# Build the unit tests.
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
+#
+# Copyright (C) 2014 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.
+#
 
 # Build the unit tests.
-test_src_files := \
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
+LOCAL_MODULE := libutils_tests
+
+LOCAL_SRC_FILES := \
     BasicHashtable_test.cpp \
     BlobCache_test.cpp \
     BitSet_test.cpp \
@@ -11,24 +30,12 @@
     LruCache_test.cpp \
     String8_test.cpp \
     Unicode_test.cpp \
-    Vector_test.cpp
+    Vector_test.cpp \
 
-shared_libraries := \
+LOCAL_SHARED_LIBRARIES := \
     libz \
     liblog \
     libcutils \
     libutils \
-    libstlport
 
-static_libraries := \
-    libgtest \
-    libgtest_main
-
-$(foreach file,$(test_src_files), \
-    $(eval include $(CLEAR_VARS)) \
-    $(eval LOCAL_SHARED_LIBRARIES := $(shared_libraries)) \
-    $(eval LOCAL_STATIC_LIBRARIES := $(static_libraries)) \
-    $(eval LOCAL_SRC_FILES := $(file)) \
-    $(eval LOCAL_MODULE := $(notdir $(file:%.cpp=%))) \
-    $(eval include $(BUILD_NATIVE_TEST)) \
-)
+include $(BUILD_NATIVE_TEST)
diff --git a/libutils/tests/BasicHashtable_test.cpp b/libutils/tests/BasicHashtable_test.cpp
index a61b1e1..4b3a717 100644
--- a/libutils/tests/BasicHashtable_test.cpp
+++ b/libutils/tests/BasicHashtable_test.cpp
@@ -21,12 +21,12 @@
 #include <gtest/gtest.h>
 #include <unistd.h>
 
-namespace android {
+namespace {
 
 typedef int SimpleKey;
 typedef int SimpleValue;
-typedef key_value_pair_t<SimpleKey, SimpleValue> SimpleEntry;
-typedef BasicHashtable<SimpleKey, SimpleEntry> SimpleHashtable;
+typedef android::key_value_pair_t<SimpleKey, SimpleValue> SimpleEntry;
+typedef android::BasicHashtable<SimpleKey, SimpleEntry> SimpleHashtable;
 
 struct ComplexKey {
     int k;
@@ -56,10 +56,6 @@
 
 ssize_t ComplexKey::instanceCount = 0;
 
-template<> inline hash_t hash_type(const ComplexKey& value) {
-    return hash_type(value.k);
-}
-
 struct ComplexValue {
     int v;
 
@@ -80,9 +76,18 @@
 
 ssize_t ComplexValue::instanceCount = 0;
 
+} // namespace
+
+
+namespace android {
+
 typedef key_value_pair_t<ComplexKey, ComplexValue> ComplexEntry;
 typedef BasicHashtable<ComplexKey, ComplexEntry> ComplexHashtable;
 
+template<> inline hash_t hash_type(const ComplexKey& value) {
+    return hash_type(value.k);
+}
+
 class BasicHashtableTest : public testing::Test {
 protected:
     virtual void SetUp() {
diff --git a/libutils/tests/LruCache_test.cpp b/libutils/tests/LruCache_test.cpp
index bcbea32..6534211 100644
--- a/libutils/tests/LruCache_test.cpp
+++ b/libutils/tests/LruCache_test.cpp
@@ -20,7 +20,7 @@
 #include <cutils/log.h>
 #include <gtest/gtest.h>
 
-namespace android {
+namespace {
 
 typedef int SimpleKey;
 typedef const char* StringValue;
@@ -53,10 +53,6 @@
 
 ssize_t ComplexKey::instanceCount = 0;
 
-template<> inline hash_t hash_type(const ComplexKey& value) {
-    return hash_type(value.k);
-}
-
 struct ComplexValue {
     int v;
 
@@ -77,8 +73,17 @@
 
 ssize_t ComplexValue::instanceCount = 0;
 
+} // namespace
+
+
+namespace android {
+
 typedef LruCache<ComplexKey, ComplexValue> ComplexCache;
 
+template<> inline android::hash_t hash_type(const ComplexKey& value) {
+    return hash_type(value.k);
+}
+
 class EntryRemovedCallback : public OnEntryRemoved<SimpleKey, StringValue> {
 public:
     EntryRemovedCallback() : callbackCount(0), lastKey(-1), lastValue(NULL) { }
diff --git a/libziparchive/Android.mk b/libziparchive/Android.mk
index d23a94f..ba7b74d 100644
--- a/libziparchive/Android.mk
+++ b/libziparchive/Android.mk
@@ -14,31 +14,23 @@
 # limitations under the License.
 
 LOCAL_PATH := $(call my-dir)
+
+source_files := zip_archive.cc
+
 include $(CLEAR_VARS)
-
-source_files := \
-	zip_archive.h \
-	zip_archive.cc
-
-includes := external/zlib
-
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_CPP_EXTENSION := .cc
 LOCAL_SRC_FILES := ${source_files}
-
 LOCAL_STATIC_LIBRARIES := libz
 LOCAL_SHARED_LIBRARIES := libutils
 LOCAL_MODULE:= libziparchive
-
-LOCAL_C_INCLUDES += ${includes}
 LOCAL_CFLAGS := -Werror
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
-LOCAL_MODULE := libziparchive
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_CPP_EXTENSION := .cc
 LOCAL_SRC_FILES := ${source_files}
-LOCAL_C_INCLUDES += ${includes}
-
 LOCAL_STATIC_LIBRARIES := libz libutils
 LOCAL_MODULE:= libziparchive-host
 LOCAL_CFLAGS := -Werror
@@ -49,29 +41,37 @@
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+LOCAL_CPP_EXTENSION := .cc
+LOCAL_SRC_FILES := ${source_files}
+LOCAL_STATIC_LIBRARIES := libz libutils
+LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_MODULE:= libziparchive-host
+LOCAL_CFLAGS := -Werror
+LOCAL_MULTILIB := both
+include $(BUILD_HOST_SHARED_LIBRARY)
+
+# Tests.
+include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE := ziparchive-tests
 LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS += \
-    -DGTEST_OS_LINUX_ANDROID \
-    -DGTEST_HAS_STD_STRING \
-    -Werror
-LOCAL_SRC_FILES := zip_archive_test.cc
+LOCAL_CFLAGS := -Werror
+LOCAL_SRC_FILES := zip_archive_test.cc entry_name_utils_test.cc
 LOCAL_SHARED_LIBRARIES := liblog
-LOCAL_STATIC_LIBRARIES := libziparchive libz libgtest libgtest_main libutils
+LOCAL_STATIC_LIBRARIES := libziparchive libz libutils
 include $(BUILD_NATIVE_TEST)
 
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE := ziparchive-tests-host
 LOCAL_CPP_EXTENSION := .cc
 LOCAL_CFLAGS += \
-    -DGTEST_OS_LINUX \
-    -DGTEST_HAS_STD_STRING \
-    -Werror
-LOCAL_SRC_FILES := zip_archive_test.cc
-LOCAL_STATIC_LIBRARIES := libziparchive-host \
-	libz \
-	libgtest_host \
-	libgtest_main_host \
-	liblog \
-	libutils
+    -Werror \
+    -Wno-unnamed-type-template-args
+LOCAL_SRC_FILES := zip_archive_test.cc entry_name_utils_test.cc
+LOCAL_SHARED_LIBRARIES := libziparchive-host liblog
+LOCAL_STATIC_LIBRARIES := \
+    libz \
+    libutils
 include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libziparchive/entry_name_utils-inl.h b/libziparchive/entry_name_utils-inl.h
new file mode 100644
index 0000000..ddbc286
--- /dev/null
+++ b/libziparchive/entry_name_utils-inl.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2014 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 LIBZIPARCHIVE_ENTRY_NAME_UTILS_INL_H_
+#define LIBZIPARCHIVE_ENTRY_NAME_UTILS_INL_H_
+
+#include <stddef.h>
+#include <stdint.h>
+
+// Check if |length| bytes at |entry_name| constitute a valid entry name.
+// Entry names must be valid UTF-8 and must not contain '0'.
+inline bool IsValidEntryName(const uint8_t* entry_name, const size_t length) {
+  for (size_t i = 0; i < length; ++i) {
+    const uint8_t byte = entry_name[i];
+    if (byte == 0) {
+      return false;
+    } else if ((byte & 0x80) == 0) {
+      // Single byte sequence.
+      continue;
+    } else if ((byte & 0xc0) == 0x80 || (byte & 0xfe) == 0xfe) {
+      // Invalid sequence.
+      return false;
+    } else {
+      // 2-5 byte sequences.
+      for (uint8_t first = byte << 1; first & 0x80; first <<= 1) {
+        ++i;
+
+        // Missing continuation byte..
+        if (i == length) {
+          return false;
+        }
+
+        // Invalid continuation byte.
+        const uint8_t continuation_byte = entry_name[i];
+        if ((continuation_byte & 0xc0) != 0x80) {
+          return false;
+        }
+      }
+    }
+  }
+
+  return true;
+}
+
+
+#endif  // LIBZIPARCHIVE_ENTRY_NAME_UTILS_INL_H_
diff --git a/libziparchive/entry_name_utils_test.cc b/libziparchive/entry_name_utils_test.cc
new file mode 100644
index 0000000..20715bb
--- /dev/null
+++ b/libziparchive/entry_name_utils_test.cc
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2014 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 "entry_name_utils-inl.h"
+
+#include <gtest/gtest.h>
+
+TEST(entry_name_utils, NullChars) {
+  // 'A', 'R', '\0', 'S', 'E'
+  const uint8_t zeroes[] = { 0x41, 0x52, 0x00, 0x53, 0x45 };
+  ASSERT_FALSE(IsValidEntryName(zeroes, sizeof(zeroes)));
+
+  const uint8_t zeroes_continuation_chars[] = { 0xc2, 0xa1, 0xc2, 0x00 };
+  ASSERT_FALSE(IsValidEntryName(zeroes_continuation_chars,
+                                sizeof(zeroes_continuation_chars)));
+}
+
+TEST(entry_name_utils, InvalidSequence) {
+  // 0xfe is an invalid start byte
+  const uint8_t invalid[] = { 0x41, 0xfe };
+  ASSERT_FALSE(IsValidEntryName(invalid, sizeof(invalid)));
+
+  // 0x91 is an invalid start byte (it's a valid continuation byte).
+  const uint8_t invalid2[] = { 0x41, 0x91 };
+  ASSERT_FALSE(IsValidEntryName(invalid2, sizeof(invalid2)));
+}
+
+TEST(entry_name_utils, TruncatedContinuation) {
+  // Malayalam script with truncated bytes. There should be 2 bytes
+  // after 0xe0
+  const uint8_t truncated[] = { 0xe0, 0xb4, 0x85, 0xe0, 0xb4 };
+  ASSERT_FALSE(IsValidEntryName(truncated, sizeof(truncated)));
+
+  // 0xc2 is the start of a 2 byte sequence that we've subsequently
+  // dropped.
+  const uint8_t truncated2[] = { 0xc2, 0xc2, 0xa1 };
+  ASSERT_FALSE(IsValidEntryName(truncated2, sizeof(truncated2)));
+}
+
+TEST(entry_name_utils, BadContinuation) {
+  // 0x41 is an invalid continuation char, since it's MSBs
+  // aren't "10..." (are 01).
+  const uint8_t bad[] = { 0xc2, 0xa1, 0xc2, 0x41 };
+  ASSERT_FALSE(IsValidEntryName(bad, sizeof(bad)));
+
+  // 0x41 is an invalid continuation char, since it's MSBs
+  // aren't "10..." (are 11).
+  const uint8_t bad2[] = { 0xc2, 0xa1, 0xc2, 0xfe };
+  ASSERT_FALSE(IsValidEntryName(bad2, sizeof(bad2)));
+}
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index 87dac0e..b6fd0d2 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -33,8 +33,10 @@
 
 #include <JNIHelp.h>  // TEMP_FAILURE_RETRY may or may not be in unistd
 
+#include "entry_name_utils-inl.h"
 #include "ziparchive/zip_archive.h"
 
+
 // This is for windows. If we don't open a file in binary mode, weird
 // things will happen.
 #ifndef O_BINARY
@@ -193,7 +195,6 @@
 #undef DISALLOW_IMPLICIT_CONSTRUCTORS
 
 static const uint32_t kGPBDDFlagMask = 0x0008;         // mask value that signifies that the entry has a DD
-static const uint32_t kMaxErrorLen = 1024;
 
 // The maximum size of a central directory or a file
 // comment in bytes.
@@ -385,8 +386,10 @@
   return val;
 }
 
-static uint32_t ComputeHash(const char* str, uint16_t len) {
+static uint32_t ComputeHash(const ZipEntryName& name) {
   uint32_t hash = 0;
+  uint16_t len = name.name_length;
+  const uint8_t* str = name.name;
 
   while (len--) {
     hash = hash * 31 + *str++;
@@ -401,21 +404,21 @@
  */
 static int64_t EntryToIndex(const ZipEntryName* hash_table,
                             const uint32_t hash_table_size,
-                            const char* name, uint16_t length) {
-  const uint32_t hash = ComputeHash(name, length);
+                            const ZipEntryName& name) {
+  const uint32_t hash = ComputeHash(name);
 
   // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
   uint32_t ent = hash & (hash_table_size - 1);
   while (hash_table[ent].name != NULL) {
-    if (hash_table[ent].name_length == length &&
-        memcmp(hash_table[ent].name, name, length) == 0) {
+    if (hash_table[ent].name_length == name.name_length &&
+        memcmp(hash_table[ent].name, name.name, name.name_length) == 0) {
       return ent;
     }
 
     ent = (ent + 1) & (hash_table_size - 1);
   }
 
-  ALOGV("Zip: Unable to find entry %.*s", length, name);
+  ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
   return kEntryNotFound;
 }
 
@@ -423,8 +426,8 @@
  * Add a new entry to the hash table.
  */
 static int32_t AddToHash(ZipEntryName *hash_table, const uint64_t hash_table_size,
-                         const char* name, uint16_t length) {
-  const uint64_t hash = ComputeHash(name, length);
+                         const ZipEntryName& name) {
+  const uint64_t hash = ComputeHash(name);
   uint32_t ent = hash & (hash_table_size - 1);
 
   /*
@@ -432,17 +435,17 @@
    * Further, we guarantee that the hashtable size is not 0.
    */
   while (hash_table[ent].name != NULL) {
-    if (hash_table[ent].name_length == length &&
-        memcmp(hash_table[ent].name, name, length) == 0) {
+    if (hash_table[ent].name_length == name.name_length &&
+        memcmp(hash_table[ent].name, name.name, name.name_length) == 0) {
       // We've found a duplicate entry. We don't accept it
-      ALOGW("Zip: Found duplicate entry %.*s", length, name);
+      ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
       return kDuplicateEntry;
     }
     ent = (ent + 1) & (hash_table_size - 1);
   }
 
-  hash_table[ent].name = name;
-  hash_table[ent].name_length = length;
+  hash_table[ent].name = name.name;
+  hash_table[ent].name_length = name.name_length;
   return 0;
 }
 
@@ -638,17 +641,19 @@
     const uint16_t file_name_length = cdr->file_name_length;
     const uint16_t extra_length = cdr->extra_field_length;
     const uint16_t comment_length = cdr->comment_length;
-    const char* file_name = reinterpret_cast<const char*>(ptr + sizeof(CentralDirectoryRecord));
+    const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
 
-    /* check that file name doesn't contain \0 character */
-    if (memchr(file_name, 0, file_name_length) != NULL) {
-      ALOGW("Zip: entry name can't contain \\0 character");
+    /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
+    if (!IsValidEntryName(file_name, file_name_length)) {
       goto bail;
     }
 
     /* add the CDE filename to the hash table */
+    ZipEntryName entry_name;
+    entry_name.name = file_name;
+    entry_name.name_length = file_name_length;
     const int add_result = AddToHash(archive->hash_table,
-        archive->hash_table_size, file_name, file_name_length);
+        archive->hash_table_size, entry_name);
     if (add_result) {
       ALOGW("Zip: Error adding entry to hash table %d", add_result);
       result = add_result;
@@ -739,7 +744,7 @@
 // as a side effect of this call.
 static inline ssize_t ReadAtOffset(int fd, uint8_t* buf, size_t len,
                                    off64_t off) {
-#ifdef HAVE_PREAD
+#if !defined(_WIN32)
   return TEMP_FAILURE_RETRY(pread64(fd, buf, len, off));
 #else
   // The only supported platform that doesn't support pread at the moment
@@ -751,18 +756,17 @@
   }
 
   return TEMP_FAILURE_RETRY(read(fd, buf, len));
-#endif  // HAVE_PREAD
+#endif
 }
 
 static int32_t FindEntry(const ZipArchive* archive, const int ent,
                          ZipEntry* data) {
   const uint16_t nameLen = archive->hash_table[ent].name_length;
-  const char* name = archive->hash_table[ent].name;
 
   // Recover the start of the central directory entry from the filename
   // pointer.  The filename is the first entry past the fixed-size data,
   // so we can just subtract back from that.
-  const uint8_t* ptr = reinterpret_cast<const uint8_t*>(name);
+  const uint8_t* ptr = archive->hash_table[ent].name;
   ptr -= sizeof(CentralDirectoryRecord);
 
   // This is the base of our mmapped region, we have to sanity check that
@@ -853,7 +857,7 @@
       return kIoError;
     }
 
-    if (memcmp(name, name_buf, nameLen)) {
+    if (memcmp(archive->hash_table[ent].name, name_buf, nameLen)) {
       free(name_buf);
       return kInconsistentInformation;
     }
@@ -890,12 +894,28 @@
 
 struct IterationHandle {
   uint32_t position;
-  const char* prefix;
+  // We're not using vector here because this code is used in the Windows SDK
+  // where the STL is not available.
+  const uint8_t* prefix;
   uint16_t prefix_len;
   ZipArchive* archive;
+
+  IterationHandle() : prefix(NULL), prefix_len(0) {}
+
+  IterationHandle(const ZipEntryName& prefix_name)
+      : prefix_len(prefix_name.name_length) {
+    uint8_t* prefix_copy = new uint8_t[prefix_len];
+    memcpy(prefix_copy, prefix_name.name, prefix_len);
+    prefix = prefix_copy;
+  }
+
+  ~IterationHandle() {
+    delete[] prefix;
+  }
 };
 
-int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const char* prefix) {
+int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr,
+                       const ZipEntryName* optional_prefix) {
   ZipArchive* archive = (ZipArchive *) handle;
 
   if (archive == NULL || archive->hash_table == NULL) {
@@ -903,32 +923,32 @@
     return kInvalidHandle;
   }
 
-  IterationHandle* cookie = (IterationHandle*) malloc(sizeof(IterationHandle));
+  IterationHandle* cookie =
+      optional_prefix != NULL ? new IterationHandle(*optional_prefix) : new IterationHandle();
   cookie->position = 0;
-  cookie->prefix = prefix;
   cookie->archive = archive;
-  if (prefix != NULL) {
-    cookie->prefix_len = strlen(prefix);
-  }
 
   *cookie_ptr = cookie ;
   return 0;
 }
 
-int32_t FindEntry(const ZipArchiveHandle handle, const char* entryName,
+void EndIteration(void* cookie) {
+  delete reinterpret_cast<IterationHandle*>(cookie);
+}
+
+int32_t FindEntry(const ZipArchiveHandle handle, const ZipEntryName& entryName,
                   ZipEntry* data) {
   const ZipArchive* archive = (ZipArchive*) handle;
-  const int nameLen = strlen(entryName);
-  if (nameLen == 0 || nameLen > 65535) {
-    ALOGW("Zip: Invalid filename %s", entryName);
+  if (entryName.name_length == 0) {
+    ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
     return kInvalidEntryName;
   }
 
   const int64_t ent = EntryToIndex(archive->hash_table,
-    archive->hash_table_size, entryName, nameLen);
+    archive->hash_table_size, entryName);
 
   if (ent < 0) {
-    ALOGV("Zip: Could not find entry %.*s", nameLen, entryName);
+    ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
     return ent;
   }
 
@@ -953,7 +973,7 @@
 
   for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
     if (hash_table[i].name != NULL &&
-        (handle->prefix == NULL ||
+        (handle->prefix_len == 0 ||
          (memcmp(handle->prefix, hash_table[i].name, handle->prefix_len) == 0))) {
       handle->position = (i + 1);
       const int error = FindEntry(archive, i, data);
diff --git a/libziparchive/zip_archive_test.cc b/libziparchive/zip_archive_test.cc
index 813a87f..4775de0 100644
--- a/libziparchive/zip_archive_test.cc
+++ b/libziparchive/zip_archive_test.cc
@@ -40,6 +40,27 @@
   '\n'
 };
 
+static const uint16_t kATxtNameLength = 5;
+static const uint16_t kBTxtNameLength = 5;
+static const uint16_t kNonexistentTxtNameLength = 15;
+static const uint16_t kEmptyTxtNameLength = 9;
+
+static const uint8_t kATxtName[kATxtNameLength] = {
+  'a', '.', 't', 'x', 't'
+};
+
+static const uint8_t kBTxtName[kBTxtNameLength] = {
+  'b', '.', 't', 'x', 't'
+};
+
+static const uint8_t kNonexistentTxtName[kNonexistentTxtNameLength] = {
+  'n', 'o', 'n', 'e', 'x', 'i', 's', 't', 'e', 'n', 't', '.', 't', 'x' ,'t'
+};
+
+static const uint8_t kEmptyTxtName[kEmptyTxtNameLength] = {
+  'e', 'm', 'p', 't', 'y', '.', 't', 'x', 't'
+};
+
 static int32_t OpenArchiveWrapper(const std::string& name,
                                   ZipArchiveHandle* handle) {
   const std::string abs_path = test_data_dir + "/" + name;
@@ -108,7 +129,10 @@
   ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
 
   ZipEntry data;
-  ASSERT_EQ(0, FindEntry(handle, "a.txt", &data));
+  ZipEntryName name;
+  name.name = kATxtName;
+  name.name_length = kATxtNameLength;
+  ASSERT_EQ(0, FindEntry(handle, name, &data));
 
   // Known facts about a.txt, from zipinfo -v.
   ASSERT_EQ(63, data.offset);
@@ -118,7 +142,10 @@
   ASSERT_EQ(0x950821c5, data.crc32);
 
   // An entry that doesn't exist. Should be a negative return code.
-  ASSERT_LT(FindEntry(handle, "nonexistent.txt", &data), 0);
+  ZipEntryName absent_name;
+  absent_name.name = kNonexistentTxtName;
+  absent_name.name_length = kNonexistentTxtNameLength;
+  ASSERT_LT(FindEntry(handle, absent_name, &data), 0);
 
   CloseArchive(handle);
 }
@@ -129,7 +156,10 @@
 
   // An entry that's deflated.
   ZipEntry data;
-  ASSERT_EQ(0, FindEntry(handle, "a.txt", &data));
+  ZipEntryName a_name;
+  a_name.name = kATxtName;
+  a_name.name_length = kATxtNameLength;
+  ASSERT_EQ(0, FindEntry(handle, a_name, &data));
   const uint32_t a_size = data.uncompressed_length;
   ASSERT_EQ(a_size, sizeof(kATxtContents));
   uint8_t* buffer = new uint8_t[a_size];
@@ -138,7 +168,10 @@
   delete[] buffer;
 
   // An entry that's stored.
-  ASSERT_EQ(0, FindEntry(handle, "b.txt", &data));
+  ZipEntryName b_name;
+  b_name.name = kBTxtName;
+  b_name.name_length = kBTxtNameLength;
+  ASSERT_EQ(0, FindEntry(handle, b_name, &data));
   const uint32_t b_size = data.uncompressed_length;
   ASSERT_EQ(b_size, sizeof(kBTxtContents));
   buffer = new uint8_t[b_size];
@@ -184,7 +217,10 @@
   ASSERT_EQ(0, OpenArchiveFd(fd, "EmptyEntriesTest", &handle));
 
   ZipEntry entry;
-  ASSERT_EQ(0, FindEntry(handle, "empty.txt", &entry));
+  ZipEntryName empty_name;
+  empty_name.name = kEmptyTxtName;
+  empty_name.name_length = kEmptyTxtNameLength;
+  ASSERT_EQ(0, FindEntry(handle, empty_name, &entry));
   ASSERT_EQ(static_cast<uint32_t>(0), entry.uncompressed_length);
   uint8_t buffer[1];
   ASSERT_EQ(0, ExtractToMemory(handle, &entry, buffer, 1));
@@ -231,7 +267,10 @@
   ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
 
   ZipEntry entry;
-  ASSERT_EQ(0, FindEntry(handle, "a.txt", &entry));
+  ZipEntryName name;
+  name.name = kATxtName;
+  name.name_length = kATxtNameLength;
+  ASSERT_EQ(0, FindEntry(handle, name, &entry));
   ASSERT_EQ(0, ExtractEntryToFile(handle, &entry, fd));
 
 
diff --git a/libzipfile/Android.mk b/libzipfile/Android.mk
index 12a2229..f054e15 100644
--- a/libzipfile/Android.mk
+++ b/libzipfile/Android.mk
@@ -7,13 +7,10 @@
 	centraldir.c \
 	zipfile.c
 
-LOCAL_STATIC_LIBRARIES := \
-	libunz
+LOCAL_STATIC_LIBRARIES := libz
 
 LOCAL_MODULE:= libzipfile
 
-LOCAL_C_INCLUDES += external/zlib
-
 LOCAL_CFLAGS := -Werror
 
 LOCAL_MULTILIB := both
@@ -27,13 +24,10 @@
 	centraldir.c \
 	zipfile.c
 
-LOCAL_STATIC_LIBRARIES := \
-	libunz
+LOCAL_STATIC_LIBRARIES := libz
 
 LOCAL_MODULE:= libzipfile
 
-LOCAL_C_INCLUDES += external/zlib
-
 LOCAL_CFLAGS := -Werror
 
 include $(BUILD_STATIC_LIBRARY)
@@ -45,12 +39,10 @@
 LOCAL_SRC_FILES:= \
 	test_zipfile.c
 
-LOCAL_STATIC_LIBRARIES := libzipfile libunz
+LOCAL_STATIC_LIBRARIES := libzipfile libz
 
 LOCAL_MODULE := test_zipfile
 
-LOCAL_C_INCLUDES += external/zlib
-
 LOCAL_CFLAGS := -Werror
 
 include $(BUILD_HOST_EXECUTABLE)
diff --git a/lmkd/lmkd.c b/lmkd/lmkd.c
index a534a24..7bbc811 100644
--- a/lmkd/lmkd.c
+++ b/lmkd/lmkd.c
@@ -607,7 +607,6 @@
 static int find_and_kill_process(int other_free, int other_file, bool first)
 {
     int i;
-    int r;
     int min_score_adj = OOM_ADJUST_MAX + 1;
     int minfree = 0;
     int killed_size = 0;
@@ -643,7 +642,6 @@
 }
 
 static void mp_event(uint32_t events __unused) {
-    int i;
     int ret;
     unsigned long long evcount;
     struct sysmeminfo mi;
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 858e56c..79f2ebd 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -4,6 +4,7 @@
 #include <ctype.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <math.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdarg.h>
@@ -80,15 +81,20 @@
 
     close(g_outFD);
 
+    // Compute the maximum number of digits needed to count up to g_maxRotatedLogs in decimal.
+    // eg: g_maxRotatedLogs == 30 -> log10(30) == 1.477 -> maxRotationCountDigits == 2
+    int maxRotationCountDigits =
+            (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
+
     for (int i = g_maxRotatedLogs ; i > 0 ; i--) {
         char *file0, *file1;
 
-        asprintf(&file1, "%s.%d", g_outputFileName, i);
+        asprintf(&file1, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
 
         if (i - 1 == 0) {
             asprintf(&file0, "%s", g_outputFileName);
         } else {
-            asprintf(&file0, "%s.%d", g_outputFileName, i - 1);
+            asprintf(&file0, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i - 1);
         }
 
         err = rename (file0, file1);
@@ -219,8 +225,8 @@
                     "  -f <filename>   Log to file. Default to stdout\n"
                     "  -r [<kbytes>]   Rotate log every kbytes. (16 if unspecified). Requires -f\n"
                     "  -n <count>      Sets max number of rotated logs to <count>, default 4\n"
-                    "  -v <format>     Sets the log print format, where <format> is one of:\n\n"
-                    "                  brief process tag thread raw time threadtime long\n\n"
+                    "  -v <format>     Sets the log print format, where <format> is:\n\n"
+                    "                  brief color long process raw tag thread threadtime time\n\n"
                     "  -c              clear (flush) the entire log and exit\n"
                     "  -d              dump the log and then exit (don't block)\n"
                     "  -t <count>      print only the most recent <count> lines (implies -d)\n"
@@ -259,7 +265,7 @@
                    "\nIf not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS.\n"
                    "If no filterspec is found, filter defaults to '*:I'\n"
                    "\nIf not specified with -v, format is set from ANDROID_PRINTF_LOG\n"
-                   "or defaults to \"brief\"\n\n");
+                   "or defaults to \"threadtime\"\n\n");
 
 
 
@@ -449,36 +455,31 @@
                         delete dev;
                     }
 
-                    dev = devices = new log_device_t("main", false, 'm');
-                    android::g_devCount = 1;
-                    if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
-                        dev->next = new log_device_t("system", false, 's');
-                        if (dev->next) {
-                            dev = dev->next;
-                            android::g_devCount++;
+                    devices = dev = NULL;
+                    android::g_devCount = 0;
+                    needBinary = false;
+                    for(int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
+                        const char *name = android_log_id_to_name((log_id_t)i);
+                        log_id_t log_id = android_name_to_log_id(name);
+
+                        if (log_id != (log_id_t)i) {
+                            continue;
                         }
-                    }
-                    if (android_name_to_log_id("radio") == LOG_ID_RADIO) {
-                        dev->next = new log_device_t("radio", false, 'r');
-                        if (dev->next) {
-                            dev = dev->next;
-                            android::g_devCount++;
+
+                        bool binary = strcmp(name, "events") == 0;
+                        log_device_t* d = new log_device_t(name, binary, *name);
+
+                        if (dev) {
+                            dev->next = d;
+                            dev = d;
+                        } else {
+                            devices = dev = d;
                         }
-                    }
-                    if (android_name_to_log_id("events") == LOG_ID_EVENTS) {
-                        dev->next = new log_device_t("events", true, 'e');
-                        if (dev->next) {
-                            dev = dev->next;
-                            android::g_devCount++;
+                        android::g_devCount++;
+                        if (binary) {
                             needBinary = true;
                         }
                     }
-                    if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
-                        dev->next = new log_device_t("crash", false, 'c');
-                        if (dev->next) {
-                            android::g_devCount++;
-                        }
-                    }
                     break;
                 }
 
@@ -543,7 +544,9 @@
                     exit(-1);
                 }
 
-                hasSetLogFormat = 1;
+                if (strcmp("color", optarg)) { // exception for modifiers
+                    hasSetLogFormat = 1;
+                }
             break;
 
             case 'Q':
@@ -653,11 +656,12 @@
 
         if (logFormat != NULL) {
             err = setLogFormat(logFormat);
-
             if (err < 0) {
                 fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n",
                                     logFormat);
             }
+        } else {
+            setLogFormat("threadtime");
         }
     }
 
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index 85756d5..b358485 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -243,7 +243,7 @@
 
     FILE *fp;
     ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -b events -t 100 2>/dev/null",
+      "logcat -v brief -b events -t 100 2>/dev/null",
       "r")));
 
     char buffer[5120];
@@ -275,7 +275,7 @@
 
     // NB: crash log only available in user space
     ASSERT_TRUE(NULL != (fp = popen(
-      "logcat -b radio -b events -b system -b main -g 2>/dev/null",
+      "logcat -v brief -b radio -b events -b system -b main -g 2>/dev/null",
       "r")));
 
     char buffer[5120];
@@ -364,7 +364,7 @@
 
     ASSERT_TRUE(NULL != (fp = popen(
       "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
-      " logcat -b events 2>&1",
+      " logcat -v brief -b events 2>&1",
       "r")));
 
     char buffer[5120];
@@ -433,7 +433,7 @@
 
     ASSERT_TRUE(NULL != (fp = popen(
       "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
-      " logcat -b events -T 5 2>&1",
+      " logcat -v brief -b events -T 5 2>&1",
       "r")));
 
     char buffer[5120];
@@ -503,10 +503,14 @@
             int count = 0;
 
             while (fgets(buffer, sizeof(buffer), fp)) {
-                static const char match[] = "4 log.txt";
+                static const char match_1[] = "4 log.txt";
+                static const char match_2[] = "8 log.txt";
+                static const char match_3[] = "16 log.txt";
                 static const char total[] = "total ";
 
-                if (!strncmp(buffer, match, sizeof(match) - 1)) {
+                if (!strncmp(buffer, match_1, sizeof(match_1) - 1)
+                 || !strncmp(buffer, match_2, sizeof(match_2) - 1)
+                 || !strncmp(buffer, match_3, sizeof(match_3) - 1)) {
                     ++count;
                 } else if (strncmp(buffer, total, sizeof(total) - 1)) {
                     fprintf(stderr, "WARNING: Parse error: %s", buffer);
@@ -520,6 +524,59 @@
     EXPECT_FALSE(system(command));
 }
 
+TEST(logcat, logrotate_suffix) {
+    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    char tmp_out_dir[sizeof(tmp_out_dir_form)];
+    ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
+
+    static const char logcat_cmd[] = "logcat -b radio -b events -b system -b main"
+                                     " -d -f %s/log.txt -n 10 -r 1";
+    char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd)];
+    sprintf(command, logcat_cmd, tmp_out_dir);
+
+    int ret;
+    EXPECT_FALSE((ret = system(command)));
+    if (!ret) {
+        sprintf(command, "ls %s 2>/dev/null", tmp_out_dir);
+
+        FILE *fp;
+        EXPECT_TRUE(NULL != (fp = popen(command, "r")));
+        char buffer[5120];
+        int log_file_count = 0;
+
+        while (fgets(buffer, sizeof(buffer), fp)) {
+            static const char rotated_log_filename_prefix[] = "log.txt.";
+            static const size_t rotated_log_filename_prefix_len =
+                strlen(rotated_log_filename_prefix);
+            static const char log_filename[] = "log.txt";
+
+            if (!strncmp(buffer, rotated_log_filename_prefix, rotated_log_filename_prefix_len)) {
+              // Rotated file should have form log.txt.##
+              char* rotated_log_filename_suffix = buffer + rotated_log_filename_prefix_len;
+              char* endptr;
+              const long int suffix_value = strtol(rotated_log_filename_suffix, &endptr, 10);
+              EXPECT_EQ(rotated_log_filename_suffix + 2, endptr);
+              EXPECT_LE(suffix_value, 10);
+              EXPECT_GT(suffix_value, 0);
+              ++log_file_count;
+              continue;
+            }
+
+            if (!strncmp(buffer, log_filename, strlen(log_filename))) {
+              ++log_file_count;
+              continue;
+            }
+
+            fprintf(stderr, "ERROR: Unexpected file: %s", buffer);
+            ADD_FAILURE();
+        }
+        pclose(fp);
+        EXPECT_EQ(11, log_file_count);
+    }
+    sprintf(command, "rm -rf %s", tmp_out_dir);
+    EXPECT_FALSE(system(command));
+}
+
 static void caught_blocking_clear(int /*signum*/)
 {
     unsigned long long v = 0xDEADBEEFA55C0000ULL;
@@ -542,7 +599,7 @@
     ASSERT_TRUE(NULL != (fp = popen(
       "( trap exit HUP QUIT INT PIPE KILL ; sleep 6; echo DONE )&"
       " logcat -b events -c 2>&1 ;"
-      " logcat -b events 2>&1",
+      " logcat -v brief -b events 2>&1",
       "r")));
 
     char buffer[5120];
diff --git a/logd/LogAudit.cpp b/logd/LogAudit.cpp
index ee2f32d..c7c0249 100644
--- a/logd/LogAudit.cpp
+++ b/logd/LogAudit.cpp
@@ -19,7 +19,6 @@
 #include <limits.h>
 #include <stdarg.h>
 #include <stdlib.h>
-#include <sys/klog.h>
 #include <sys/prctl.h>
 #include <sys/uio.h>
 #include <syslog.h>
@@ -33,21 +32,23 @@
     '0' + (LOG_AUTH | (PRI)) % 10, \
     '>'
 
-LogAudit::LogAudit(LogBuffer *buf, LogReader *reader, int fdDmsg)
+LogAudit::LogAudit(LogBuffer *buf, LogReader *reader, int fdDmesg)
         : SocketListener(getLogSocket(), false)
         , logbuf(buf)
         , reader(reader)
-        , fdDmesg(-1) {
+        , fdDmesg(fdDmesg)
+        , initialized(false) {
     static const char auditd_message[] = { KMSG_PRIORITY(LOG_INFO),
         'l', 'o', 'g', 'd', '.', 'a', 'u', 'd', 'i', 't', 'd', ':',
         ' ', 's', 't', 'a', 'r', 't', '\n' };
-    write(fdDmsg, auditd_message, sizeof(auditd_message));
-    logDmesg();
-    fdDmesg = fdDmsg;
+    write(fdDmesg, auditd_message, sizeof(auditd_message));
 }
 
 bool LogAudit::onDataAvailable(SocketClient *cli) {
-    prctl(PR_SET_NAME, "logd.auditd");
+    if (!initialized) {
+        prctl(PR_SET_NAME, "logd.auditd");
+        initialized = true;
+    }
 
     struct audit_message rep;
 
@@ -60,7 +61,8 @@
         return false;
     }
 
-    logPrint("type=%d %.*s", rep.nlh.nlmsg_type, rep.nlh.nlmsg_len, rep.data);
+    logPrint("type=%d %.*s",
+        rep.nlh.nlmsg_type, rep.nlh.nlmsg_len, rep.data);
 
     return true;
 }
@@ -87,7 +89,7 @@
     }
 
     bool info = strstr(str, " permissive=1") || strstr(str, " policy loaded ");
-    if (fdDmesg >= 0) {
+    if ((fdDmesg >= 0) && initialized) {
         struct iovec iov[3];
         static const char log_info[] = { KMSG_PRIORITY(LOG_INFO) };
         static const char log_warning[] = { KMSG_PRIORITY(LOG_WARNING) };
@@ -213,34 +215,23 @@
     return rc;
 }
 
-void LogAudit::logDmesg() {
-    int len = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
-    if (len <= 0) {
-        return;
+int LogAudit::log(char *buf) {
+    char *audit = strstr(buf, " audit(");
+    if (!audit) {
+        return 0;
     }
 
-    len++;
-    char buf[len];
+    *audit = '\0';
 
-    int rc = klogctl(KLOG_READ_ALL, buf, len);
-
-    buf[len - 1] = '\0';
-
-    for(char *tok = buf; (rc >= 0) && ((tok = strtok(tok, "\r\n"))); tok = NULL) {
-        char *audit = strstr(tok, " audit(");
-        if (!audit) {
-            continue;
-        }
-
-        *audit++ = '\0';
-
-        char *type = strstr(tok, "type=");
-        if (type) {
-            rc = logPrint("%s %s", type, audit);
-        } else {
-            rc = logPrint("%s", audit);
-        }
+    int rc;
+    char *type = strstr(buf, "type=");
+    if (type) {
+        rc = logPrint("%s %s", type, audit + 1);
+    } else {
+        rc = logPrint("%s", audit + 1);
     }
+    *audit = ' ';
+    return rc;
 }
 
 int LogAudit::getLogSocket() {
diff --git a/logd/LogAudit.h b/logd/LogAudit.h
index 111030a..f977be9 100644
--- a/logd/LogAudit.h
+++ b/logd/LogAudit.h
@@ -24,16 +24,17 @@
     LogBuffer *logbuf;
     LogReader *reader;
     int fdDmesg;
+    bool initialized;
 
 public:
     LogAudit(LogBuffer *buf, LogReader *reader, int fdDmesg);
+    int log(char *buf);
 
 protected:
     virtual bool onDataAvailable(SocketClient *cli);
 
 private:
     static int getLogSocket();
-    void logDmesg();
     int logPrint(const char *fmt, ...)
         __attribute__ ((__format__ (__printf__, 2, 3)));
 };
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 8c1c344..6307bed 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -147,7 +147,8 @@
     //  NB: if end is region locked, place element at end of list
     LogBufferElementCollection::iterator it = mLogElements.end();
     LogBufferElementCollection::iterator last = it;
-    while (--it != mLogElements.begin()) {
+    while (last != mLogElements.begin()) {
+        --it;
         if ((*it)->getRealTime() <= realtime) {
             // halves the peak performance, use with caution
             if (dgramQlenStatistics) {
@@ -241,7 +242,7 @@
     LastLogTimes::iterator t = mTimes.begin();
     while(t != mTimes.end()) {
         LogTimeEntry *entry = (*t);
-        if (entry->owned_Locked()
+        if (entry->owned_Locked() && entry->isWatching(id)
                 && (!oldest || (oldest->mStart > entry->mStart))) {
             oldest = entry;
         }
@@ -353,7 +354,7 @@
                         // kick a misbehaving log reader client off the island
                         oldest->release_Locked();
                     } else {
-                        oldest->triggerSkip_Locked(pruneRows);
+                        oldest->triggerSkip_Locked(id, pruneRows);
                     }
                 }
                 break;
@@ -384,7 +385,7 @@
                         // kick a misbehaving log reader client off the island
                         oldest->release_Locked();
                     } else {
-                        oldest->triggerSkip_Locked(pruneRows);
+                        oldest->triggerSkip_Locked(id, pruneRows);
                     }
                     break;
                 }
diff --git a/logd/LogStatistics.cpp b/logd/LogStatistics.cpp
index 2a45590..6f3a088 100644
--- a/logd/LogStatistics.cpp
+++ b/logd/LogStatistics.cpp
@@ -690,8 +690,11 @@
             size_t sizesTotal = p->sizesTotal();
 
             android::String8 sz("");
-            sz.appendFormat((sizes != sizesTotal) ? "%zu/%zu" : "%zu",
-                            sizes, sizesTotal);
+            if (sizes == sizesTotal) {
+                sz.appendFormat("%zu", sizes);
+            } else {
+                sz.appendFormat("%zu/%zu", sizes, sizesTotal);
+            }
 
             android::String8 pd("");
             pd.appendFormat("%u%c", pid, p->pidGone() ? '?' : ' ');
@@ -802,12 +805,15 @@
             PidStatistics *pp = *pt;
             pid_t p = pp->getPid();
 
-            intermediate = string.format(oneline
-                                             ? ((p == PidStatistics::gone)
-                                                 ? "%d/?"
-                                                 : "%d/%d%c")
-                                             : "%d",
-                                         u, p, pp->pidGone() ? '?' : '\0');
+            if (!oneline) {
+                intermediate = string.format("%d", u);
+            } else if (p == PidStatistics::gone) {
+                intermediate = string.format("%d/?", u);
+            } else if (pp->pidGone()) {
+                intermediate = string.format("%d/%d?", u, p);
+            } else {
+                intermediate = string.format("%d/%d", u, p);
+            }
             string.appendFormat(first ? "\n%-12s" : "%-12s",
                                 intermediate.string());
             intermediate.clear();
diff --git a/logd/LogTimes.cpp b/logd/LogTimes.cpp
index ea4e8c8..5f9db8d 100644
--- a/logd/LogTimes.cpp
+++ b/logd/LogTimes.cpp
@@ -36,7 +36,6 @@
         , mReader(reader)
         , mLogMask(logMask)
         , mPid(pid)
-        , skipAhead(0)
         , mCount(0)
         , mTail(tail)
         , mIndex(0)
@@ -46,6 +45,7 @@
         , mEnd(CLOCK_MONOTONIC)
 {
         pthread_cond_init(&threadTriggeredCondition, NULL);
+        cleanSkip_Locked();
 }
 
 void LogTimeEntry::startReader_Locked(void) {
@@ -148,6 +148,8 @@
             break;
         }
 
+        me->cleanSkip_Locked();
+
         pthread_cond_wait(&me->threadTriggeredCondition, &timesLock);
     }
 
@@ -169,7 +171,7 @@
     }
 
     if ((!me->mPid || (me->mPid == element->getPid()))
-            && (me->mLogMask & (1 << element->getLogId()))) {
+            && (me->isWatching(element->getLogId()))) {
         ++me->mCount;
     }
 
@@ -184,19 +186,19 @@
 
     LogTimeEntry::lock();
 
-    if (me->skipAhead) {
-        me->skipAhead--;
+    me->mStart = element->getMonotonicTime();
+
+    if (me->skipAhead[element->getLogId()]) {
+        me->skipAhead[element->getLogId()]--;
         goto skip;
     }
 
-    me->mStart = element->getMonotonicTime();
-
     // Truncate to close race between first and second pass
     if (me->mNonBlock && me->mTail && (me->mIndex >= me->mCount)) {
         goto skip;
     }
 
-    if ((me->mLogMask & (1 << element->getLogId())) == 0) {
+    if (!me->isWatching(element->getLogId())) {
         goto skip;
     }
 
@@ -223,7 +225,7 @@
     }
 
 ok:
-    if (!me->skipAhead) {
+    if (!me->skipAhead[element->getLogId()]) {
         LogTimeEntry::unlock();
         return true;
     }
@@ -233,3 +235,9 @@
     LogTimeEntry::unlock();
     return false;
 }
+
+void LogTimeEntry::cleanSkip_Locked(void) {
+    for (log_id_t i = LOG_ID_MIN; i < LOG_ID_MAX; i = (log_id_t) (i + 1)) {
+        skipAhead[i] = 0;
+    }
+}
diff --git a/logd/LogTimes.h b/logd/LogTimes.h
index 0bfa7a2..81aedfb 100644
--- a/logd/LogTimes.h
+++ b/logd/LogTimes.h
@@ -22,6 +22,7 @@
 #include <sys/types.h>
 #include <sysutils/SocketClient.h>
 #include <utils/List.h>
+#include <log/log.h>
 
 class LogReader;
 
@@ -38,7 +39,7 @@
     static void threadStop(void *me);
     const unsigned int mLogMask;
     const pid_t mPid;
-    unsigned int skipAhead;
+    unsigned int skipAhead[LOG_ID_MAX];
     unsigned long mCount;
     unsigned long mTail;
     unsigned long mIndex;
@@ -67,7 +68,8 @@
         pthread_cond_signal(&threadTriggeredCondition);
     }
 
-    void triggerSkip_Locked(unsigned int skip) { skipAhead = skip; }
+    void triggerSkip_Locked(log_id_t id, unsigned int skip) { skipAhead[id] = skip; }
+    void cleanSkip_Locked(void);
 
     // Called after LogTimeEntry removed from list, lock implicitly held
     void release_Locked(void) {
@@ -99,7 +101,7 @@
         // No one else is holding a reference to this
         delete this;
     }
-
+    bool isWatching(log_id_t id) { return (mLogMask & (1<<id)) != 0; }
     // flushTo filter callbacks
     static bool FilterFirstPass(const LogBufferElement *element, void *me);
     static bool FilterSecondPass(const LogBufferElement *element, void *me);
diff --git a/logd/LogWhiteBlackList.cpp b/logd/LogWhiteBlackList.cpp
index e87b604..9728db1 100644
--- a/logd/LogWhiteBlackList.cpp
+++ b/logd/LogWhiteBlackList.cpp
@@ -39,10 +39,15 @@
 
 void Prune::format(char **strp) {
     if (mUid != uid_all) {
-        asprintf(strp, (mPid != pid_all) ? "%u/%u" : "%u", mUid, mPid);
-    } else {
-        // NB: mPid == pid_all can not happen if mUid == uid_all
-        asprintf(strp, (mPid != pid_all) ? "/%u" : "/", mPid);
+        if (mPid != pid_all) {
+            asprintf(strp, "%u/%u", mUid, mPid);
+        } else {
+            asprintf(strp, "%u", mUid);
+        }
+    } else if (mPid != pid_all) {
+        asprintf(strp, "/%u", mPid);
+    } else { // NB: mPid == pid_all can not happen if mUid == uid_all
+        asprintf(strp, "/");
     }
 }
 
diff --git a/logd/main.cpp b/logd/main.cpp
index 54da7e3..946a9a0 100644
--- a/logd/main.cpp
+++ b/logd/main.cpp
@@ -22,6 +22,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/capability.h>
+#include <sys/klog.h>
 #include <sys/prctl.h>
 #include <sys/stat.h>
 #include <sys/types.h>
@@ -195,6 +196,23 @@
     if (auditd) {
         // failure is an option ... messages are in dmesg (required by standard)
         LogAudit *al = new LogAudit(logBuf, reader, fdDmesg);
+
+        int len = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
+        if (len > 0) {
+            len++;
+            char buf[len];
+
+            int rc = klogctl(KLOG_READ_ALL, buf, len);
+
+            buf[len - 1] = '\0';
+
+            for(char *ptr, *tok = buf;
+                    (rc >= 0) && ((tok = strtok_r(tok, "\r\n", &ptr)));
+                    tok = NULL) {
+                rc = al->log(tok);
+            }
+        }
+
         if (al->startListener()) {
             delete al;
             close(fdDmesg);
diff --git a/logd/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index 4bea4be..96877a9 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -417,7 +417,11 @@
         if (((p - cp) > 3) && !*p && ((unsigned int)(p - cp) < len)) {
             fprintf(stderr, "\"");
             while (*cp) {
-                fprintf(stderr, (*cp != '\n') ? "%c" : "\\n", *cp);
+                if (*cp != '\n') {
+                    fprintf(stderr, "%c", *cp);
+                } else {
+                    fprintf(stderr, "\\n");
+                }
                 ++cp;
                 --len;
             }
diff --git a/rootdir/etc/hosts b/rootdir/etc/hosts
index 99848f6..649151c 100644
--- a/rootdir/etc/hosts
+++ b/rootdir/etc/hosts
@@ -1 +1,2 @@
-127.0.0.1		    localhost
+127.0.0.1       localhost
+::1             ip6-localhost
diff --git a/rootdir/etc/init.testmenu b/rootdir/etc/init.testmenu
deleted file mode 100755
index 7ae16d5..0000000
--- a/rootdir/etc/init.testmenu
+++ /dev/null
@@ -1,322 +0,0 @@
-#!/system/bin/sh
-
-atdev=/dev/omap_csmi_tty0
-pppdev=/dev/omap_csmi_tty1
-
-n1=`cat /data/phoneentry1 2>/dev/null`
-n2=`cat /data/phoneentry2 2>/dev/null`
-n3=`cat /data/phoneentry3 2>/dev/null`
-n1=${n1:-"*#06#"}
-n2=${n2:-"*#06#"}
-n3=${n3:-"*#06#"}
-phoneoutputpid=
-eventoutputpid=
-notifypid=
-notifytoggle=false
-pppdpid=
-powerdidletime=120
-
-# map phone specific keys
-setkey -k 0xe4 -v 0x23 # map #
-setkey -k 0xe3 -v 0x2a # map *
-setkey -k 231 -v 513 # map send to newline
-#setkey -k 0x67 -v 0x20b # map up to scroll back
-#setkey -k 0x6c -v 0x20a # map down to scroll forward
-setkey -k 0x73 -v 0x20b # map volume up to scroll back
-setkey -k 0x72 -v 0x20a # map volume down to scroll forward
-setkey -k 0x60 -v 0x211 # map PoC to next console
-
-# tuttle keys
-setkey -k 0x38 -v 0x703 # map leftalt to alt
-setkey -k 0x9b -v 0x703 # map mail to alt
-setkey -t 8 -k 0x9b -v 0x703 # map alt-mail to alt
-setkey -t 8 -k 0x10 -v 0x21 # map alt-q to !
-setkey -t 8 -k 0x11 -v 0x31 # map alt-w to 1
-setkey -t 8 -k 0x12 -v 0x32 # map alt-e to 2
-setkey -t 8 -k 0x13 -v 0x33 # map alt-r to 3
-setkey -t 8 -k 0x14 -v 0x2b # map alt-t to +
-setkey -t 8 -k 0x15 -v 0x28 # map alt-y to (
-setkey -t 8 -k 0x16 -v 0x29 # map alt-u to )
-setkey -t 8 -k 0x17 -v 0x2d # map alt-i to -
-setkey -t 8 -k 0x18 -v 0x5f # map alt-o to _
-setkey -t 8 -k 0x19 -v 0x22 # map alt-p to "
-setkey -t 8 -k 0x1e -v 0x23 # map alt-a to #
-setkey -t 8 -k 0x1f -v 0x34 # map alt-s to 4
-setkey -t 8 -k 0x20 -v 0x35 # map alt-d to 5
-setkey -t 8 -k 0x21 -v 0x36 # map alt-f to 6
-setkey -t 8 -k 0x22 -v 0x2f # map alt-g to /
-setkey -t 8 -k 0x23 -v 0x3f # map alt-h to ?
-setkey -t 8 -k 0x24 -v 0xa3 # map alt-j to pound
-setkey -t 8 -k 0x25 -v 0x24 # map alt-k to $
-setkey -t 8 -k 0x2c -v 0x2a # map alt-z to *
-setkey -t 8 -k 0x2d -v 0x37 # map alt-x to 7
-setkey -t 8 -k 0x2e -v 0x38 # map alt-c to 8
-setkey -t 8 -k 0x2f -v 0x39 # map alt-v to 9
-setkey -t 8 -k 0x30 -v 0x7c # map alt-b to |
-setkey -t 8 -k 0x31 -v 0x40 # map alt-n to @
-setkey -t 8 -k 0x32 -v 0x3d # map alt-m to =
-setkey -t 8 -k 0x33 -v 0x3b # map alt-, to ;
-setkey -t 8 -k 0x34 -v 0x3a # map alt-. to :
-setkey -t 8 -k 0x0f -v 0x30 # map alt-tab to 0
-setkey -t 8 -k 0x67 -v 0x20b # map alt-up to scroll back
-setkey -t 8 -k 0x6c -v 0x20a # map alt-down to scroll forward
-
-while true
-do
-	echo
-	echo "------------------------------"
-	echo " 1: init commands"
-	echo " 2: call commands"
-	echo " 3: misc phone"
-	echo " 4: phone debug output"
-	echo " 5: test data connection"
-	echo " 6: start runtime"
-	echo " 7: start runtime w/output"
-	echo " 8: stop runtime"
-	echo " 9: misc"
-	echo -n ": "
-	while true
-	do
-		c=`readtty -t 50 -f -a 1234567890#`
-		case "$c" in
-			"" ) ;;
-			* ) break;
-		esac
-	done
-	echo Got key -$c-
-	case $c in
-		"1" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Print phone output"
-				echo " 2: ATQ0V1E1+CMEE=2;+CREG=0"
-				echo " 3: AT+CFUN=1"
-				echo " 4: AT+COPS=0"
-				echo " 5: AT+CREG?"
-				echo " 6: Stop phone output"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234560#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) kill $phoneoutputpid; cat $atdev & phoneoutputpid=$! ;;
-					"2" ) echo -e "ATQ0V1E1+CMEE=2;+CREG=0\r" >$atdev;;
-					"3" ) echo -e "AT+CFUN=1\r" >$atdev;;
-					"4" ) echo -e "AT+COPS=0\r" >$atdev;;
-					"5" ) echo -e "AT+CREG?\r" >$atdev;;
-					"6" ) kill $phoneoutputpid; phoneoutputpid= ;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"2" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Dial: ATD $n1;"
-				echo " 2: Dial: ATD $n2;"
-				echo " 3: Dial: ATD $n3;"
-				echo " 4: Set number for 1"
-				echo " 5: Set number for 2"
-				echo " 6: Set number for 3"
-				echo " 7: Dial: ATD ...;"
-				echo " 8: Hang up: ATH"
-				echo " 9: Answer: ATA"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234567890#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) echo "Dialing $n1"; echo -e "ATD $n1;\r" >$atdev;;
-					"2" ) echo "Dialing $n2"; echo -e "ATD $n2;\r" >$atdev;;
-					"3" ) echo "Dialing $n3"; echo -e "ATD $n3;\r" >$atdev;;
-					"4" ) echo -n "Number: "; read n1; echo $n1 >/data/phoneentry1;;
-					"5" ) echo -n "Number: "; read n2; echo $n2 >/data/phoneentry2;;
-					"6" ) echo -n "Number: "; read n3; echo $n3 >/data/phoneentry3;;
-					"7" ) echo -n "Number: "; read n; echo "Dialing $n"; echo -e "ATD $n;\r" >$atdev;;
-					"8" ) echo -e "ATH\r" >$atdev;;
-					"9" ) echo -e "ATA\r" >$atdev;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"3" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Save FFS data"
-				echo " 2: Load user FFS data"
-				echo " 3: Load system FFS data"
-				echo " 4: Reset FFS data"
-				echo " 5: Set uplink gain"
-				echo " 6: Set echo"
-				echo " 7: cat /dev/omap_csmi_battery_t"
-				echo " 8: cat /dev/omap_csmi_htc"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 123456780#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) cat /dev/omap_csmi_ffs >/data/ffsdata;;
-					"2" ) cat /data/ffsdata >/dev/omap_csmi_ffs;;
-					"3" ) cat /system/ffsdata >/dev/omap_csmi_ffs;;
-					"4" ) echo - >/dev/omap_csmi_ffs;;
-					"5" )
-						echo -n "Gain: "; read g;
-						echo gu$g >/tmp/gain;
-						cat /tmp/gain 2>/dev/null >/dev/omap_csmi_audio_tes
-					;;
-					"6" )
-						echo -n "Echo param (hex): "; read e;
-						echo "e0x$e" >/tmp/echo;
-						cat /tmp/echo 2>/dev/null >/dev/omap_csmi_audio_tes
-					;;
-					"7" ) cat /dev/omap_csmi_battery_t;;
-					"8" ) cat /dev/omap_csmi_htc;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"4" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Toggle debug I/O"
-				echo " 2: Toggle debug Flow"
-				echo " 3: Toggle debug Interrupt"
-				echo " 4: Toggle debug Info"
-				echo " 5: Toggle GSM run state"
-				echo " 6: Clear GSM data area"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234560#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) echo -n "i" >/sys/devices/system/omap_csmi/debug;;
-					"2" ) echo -n "f" >/sys/devices/system/omap_csmi/debug;;
-					"3" ) echo -n "I" >/sys/devices/system/omap_csmi/debug;;
-					"4" ) echo -n "F" >/sys/devices/system/omap_csmi/debug;;
-					"5" ) echo -n "s" >/sys/devices/system/omap_csmi/debug;;
-					"6" ) echo -n "c" >/sys/devices/system/omap_csmi/debug;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"5" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Start pppd - userspace"
-				echo " 2: Start pppd - kernel"
-				echo " 3: Start pppd - kernel <at1"
-				echo " 4: Configure ppp data to at2"
-				echo " 5: Test with HTTP GET"
-				echo " 6: Kill pppd"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234560#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) kill $pppdpid; pppd notty < $pppdev > $pppdev & pppdpid=$!;;
-					"2" ) kill $pppdpid; pppd nodetach $pppdev & pppdpid=$!;;
-					"3" ) kill &pppdpid; pppd nodetach $pppdev connect "sh -c \"chat -v -f /etc/ppp/connect-data <$atdev >$atdev\"" & pppdpid=$!;;
-					"4" ) echo -e 'AT%DATA=2,"UART",1,,"SER","UART",0\r' >$atdev;;
-					"5" ) test-data-connection;;
-					"6" ) kill $pppdpid; pppdpid=;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"6" )
-			echo
-			echo ------------------------
-			echo Starting android runtime
-			echo ------------------------
-			start
-		;;
-		"7" )
-			echo
-			echo ------------------------
-			echo Starting android runtime
-			echo ------------------------
-			if exists /data/singleproc
-			then
-				single_process="-s"
-			else
-				single_process=""
-			fi
-			start runtime $single_process
-		;;
-		"8" )
-			stop
-		;;
-		"9" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Print events"
-				echo " 2: Stop event output"
-				if $notifytoggle
-				then
-					echo " 3: stop notify"
-				else
-					echo " 3: notify /sys/android_power"
-				fi
-				echo " 4: start powerd"
-				echo " 5: start powerd verbose"
-				echo " 6: stop powerd"
-				echo " 7: set powerd idletime ($powerdidletime)"
-				echo " 8: start multitap shell"
-				if exists /data/singleproc
-				then
-					echo " 9: enable multiprocess"
-				else
-					echo " 9: disable multiprocess"
-				fi
-				echo " c: start shell"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234567890c#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) kill $eventoutputpid; getevent & eventoutputpid=$! ;;
-					"2" ) kill $eventoutputpid; eventoutputpid= ;;
-					"3" )
-						if $notifytoggle
-						then
-							kill $notifypid
-							notifypid=
-							notifytoggle=false
-						else
-							kill $notifypid
-							notify -m 0x00000002 -c 0 -p -v 0 -w 30 /sys/android_power &
-							notifypid=$!
-							notifytoggle=true
-						fi
-					;;
-					"4" ) start powerd -i $powerdidletime ;;
-					"5" ) start powerd -i $powerdidletime -v ;;
-					"6" ) stop powerd ;;
-					"7" ) echo -n "Idle time (seconds): "; read powerdidletime ;;
-					"8" )
-						readtty -f -p -t 10 -e "[ ~" | sh -i
-					;;
-					"9" )
-						if exists /data/singleproc
-						then
-							echo "Enabling multiprocess environment."
-							rm /data/singleproc
-						else
-							echo "Disabling multiprocess environment."
-							echo >/data/singleproc "true"
-						fi
-					;;
-					"c" ) sh -i <>/dev/tty0 1>&0 2>&1 ;;
-					"0" ) break;;
-				esac
-			done
-		;;
-	esac
-done
-
diff --git a/rootdir/init.rc b/rootdir/init.rc
index cbcb842..b4bed91 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -150,6 +150,8 @@
     mount pstore pstore /sys/fs/pstore
     chown system log /sys/fs/pstore/console-ramoops
     chmod 0440 /sys/fs/pstore/console-ramoops
+    chown system log /sys/fs/pstore/pmsg-ramoops-0
+    chmod 0440 /sys/fs/pstore/pmsg-ramoops-0
 
 # Healthd can trigger a full boot from charger mode by signaling this
 # property when the power button is held.
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index 474f630..9cf9ed9 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -16,6 +16,7 @@
 # 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
+/dev/pmsg0                0222   root       log
 
 # the msm hw3d client device node is world writable/readable.
 /dev/msm_hw3dc            0666   root       root
diff --git a/sdcard/sdcard.c b/sdcard/sdcard.c
index 9cfb040..4d50bf0 100644
--- a/sdcard/sdcard.c
+++ b/sdcard/sdcard.c
@@ -29,6 +29,7 @@
 #include <string.h>
 #include <sys/inotify.h>
 #include <sys/mount.h>
+#include <sys/param.h>
 #include <sys/resource.h>
 #include <sys/stat.h>
 #include <sys/statfs.h>
@@ -414,12 +415,12 @@
     attr->ino = node->ino;
     attr->size = s->st_size;
     attr->blocks = s->st_blocks;
-    attr->atime = s->st_atime;
-    attr->mtime = s->st_mtime;
-    attr->ctime = s->st_ctime;
-    attr->atimensec = s->st_atime_nsec;
-    attr->mtimensec = s->st_mtime_nsec;
-    attr->ctimensec = s->st_ctime_nsec;
+    attr->atime = s->st_atim.tv_sec;
+    attr->mtime = s->st_mtim.tv_sec;
+    attr->ctime = s->st_ctim.tv_sec;
+    attr->atimensec = s->st_atim.tv_nsec;
+    attr->mtimensec = s->st_mtim.tv_nsec;
+    attr->ctimensec = s->st_ctim.tv_nsec;
     attr->mode = s->st_mode;
     attr->nlink = s->st_nlink;
 
@@ -936,7 +937,9 @@
     if (!node) {
         return -ENOENT;
     }
-    if (!check_caller_access_to_node(fuse, hdr, node, W_OK, has_rw)) {
+
+    if (!(req->valid & FATTR_FH) &&
+            !check_caller_access_to_node(fuse, hdr, node, W_OK, has_rw)) {
         return -EACCES;
     }
 
@@ -1301,6 +1304,7 @@
         return -errno;
     }
     out.size = res;
+    out.padding = 0;
     fuse_reply(fuse, hdr->unique, &out, sizeof(out));
     return NO_STATUS;
 }
@@ -1460,17 +1464,42 @@
         const struct fuse_in_header* hdr, const struct fuse_init_in* req)
 {
     struct fuse_init_out out;
+    size_t fuse_struct_size;
 
     TRACE("[%d] INIT ver=%d.%d maxread=%d flags=%x\n",
             handler->token, req->major, req->minor, req->max_readahead, req->flags);
+
+    /* Kernel 2.6.16 is the first stable kernel with struct fuse_init_out
+     * defined (fuse version 7.6). The structure is the same from 7.6 through
+     * 7.22. Beginning with 7.23, the structure increased in size and added
+     * new parameters.
+     */
+    if (req->major != FUSE_KERNEL_VERSION || req->minor < 6) {
+        ERROR("Fuse kernel version mismatch: Kernel version %d.%d, Expected at least %d.6",
+              req->major, req->minor, FUSE_KERNEL_VERSION);
+        return -1;
+    }
+
+    out.minor = MIN(req->minor, FUSE_KERNEL_MINOR_VERSION);
+    fuse_struct_size = sizeof(out);
+#if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
+    /* FUSE_KERNEL_VERSION >= 23. */
+
+    /* If the kernel only works on minor revs older than or equal to 22,
+     * then use the older structure size since this code only uses the 7.22
+     * version of the structure. */
+    if (req->minor <= 22) {
+        fuse_struct_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
+    }
+#endif
+
     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));
+    fuse_reply(fuse, hdr->unique, &out, fuse_struct_size);
     return NO_STATUS;
 }
 
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index 84714cf..39842b9 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -7,13 +7,10 @@
     -I$(LOCAL_PATH)/upstream-netbsd/include/ \
     -include bsd-compatibility.h \
 
+# Temporary, remove after cleanup. b/18632512
+common_cflags += -Wno-unused-variable \
+                 -Wno-unused-but-set-variable
 
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/cat/cat.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=cat_main
-LOCAL_MODULE := libtoolbox_cat
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES := upstream-netbsd/sbin/chown/chown.c
@@ -24,15 +21,6 @@
 
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES := \
-    upstream-netbsd/bin/cp/cp.c \
-    upstream-netbsd/bin/cp/utils.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=cp_main
-LOCAL_MODULE := libtoolbox_cp
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := \
     upstream-netbsd/bin/dd/args.c \
     upstream-netbsd/bin/dd/conv.c \
     upstream-netbsd/bin/dd/dd.c \
@@ -63,145 +51,52 @@
 LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
 include $(BUILD_STATIC_LIBRARY)
 
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/kill/kill.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=kill_main
-LOCAL_MODULE := libtoolbox_kill
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/ln/ln.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=ln_main
-LOCAL_MODULE := libtoolbox_ln
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/mv/mv.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=mv_main -D__SVR4
-LOCAL_MODULE := libtoolbox_mv
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/usr.bin/printenv/printenv.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=printenv_main
-LOCAL_MODULE := libtoolbox_printenv
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/rm/rm.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=rm_main
-LOCAL_MODULE := libtoolbox_rm
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/rmdir/rmdir.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=rmdir_main
-LOCAL_MODULE := libtoolbox_rmdir
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/sleep/sleep.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=sleep_main
-LOCAL_MODULE := libtoolbox_sleep
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/sync/sync.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=sync_main
-LOCAL_MODULE := libtoolbox_sync
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
 
 include $(CLEAR_VARS)
 
 BSD_TOOLS := \
-    cat \
     chown \
-    cp \
     dd \
     du \
     grep \
-    kill \
-    ln \
-    mv \
-    printenv \
-    rm \
-    rmdir \
-    sleep \
-    sync \
 
 OUR_TOOLS := \
-    chcon \
-    chmod \
-    clear \
     cmp \
-    date \
     df \
-    dmesg \
-    getenforce \
     getevent \
     getprop \
     getsebool \
-    hd \
     id \
-    ifconfig \
     iftop \
-    insmod \
     ioctl \
     ionice \
     load_policy \
     log \
     ls \
-    lsmod \
     lsof \
-    md5 \
-    mkdir \
-    mknod \
-    mkswap \
     mount \
     nandread \
-    netstat \
     newfs_msdos \
-    nohup \
-    notify \
     ps \
-    readlink \
+    prlimit \
     renice \
     restorecon \
-    prlimit \
-    rmmod \
     route \
     runcon \
     schedtop \
     sendevent \
-    setenforce \
     setprop \
     setsebool \
     smd \
     start \
     stop \
-    swapoff \
-    swapon \
     top \
     touch \
     umount \
     uptime \
-    vmstat \
     watchprops \
     wipe \
 
-ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
-OUR_TOOLS += r
-endif
-
 ALL_TOOLS = $(BSD_TOOLS) $(OUR_TOOLS)
 
 LOCAL_SRC_FILES := \
@@ -217,23 +112,18 @@
 
 LOCAL_CFLAGS += $(common_cflags)
 
-LOCAL_C_INCLUDES += external/openssl/include
-
 LOCAL_SHARED_LIBRARIES := \
-    libcrypto \
     libcutils \
     libselinux \
 
-# libusbhost is only used by lsusb, and that isn't usually included in toolbox.
-# The linker strips out all the unused library code in the normal case.
-LOCAL_STATIC_LIBRARIES := \
-    libusbhost \
-
 LOCAL_WHOLE_STATIC_LIBRARIES := $(patsubst %,libtoolbox_%,$(BSD_TOOLS))
 
 LOCAL_MODULE := toolbox
 LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
 
+# Install the symlinks.
+LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,$(ALL_TOOLS),ln -sf toolbox $(TARGET_OUT)/bin/$(t);)
+
 # Including this will define $(intermediates).
 #
 include $(BUILD_EXECUTABLE)
@@ -247,19 +137,12 @@
 $(TOOLS_H):
 	$(transform-generated-source)
 
-# Make #!/system/bin/toolbox launchers for each tool.
-#
-SYMLINKS := $(addprefix $(TARGET_OUT)/bin/,$(ALL_TOOLS))
-$(SYMLINKS): TOOLBOX_BINARY := $(LOCAL_MODULE)
-$(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk
-	@echo "Symlink: $@ -> $(TOOLBOX_BINARY)"
-	@mkdir -p $(dir $@)
-	@rm -rf $@
-	$(hide) ln -sf $(TOOLBOX_BINARY) $@
 
-ALL_DEFAULT_INSTALLED_MODULES += $(SYMLINKS)
-
-# We need this so that the installed files could be picked up based on the
-# local module name
-ALL_MODULES.$(LOCAL_MODULE).INSTALLED := \
-    $(ALL_MODULES.$(LOCAL_MODULE).INSTALLED) $(SYMLINKS)
+# We only want 'r' on userdebug and eng builds.
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := r.c
+LOCAL_CFLAGS += $(common_cflags)
+LOCAL_MODULE := r
+LOCAL_MODULE_TAGS := debug
+LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
+include $(BUILD_EXECUTABLE)
diff --git a/toolbox/alarm.c b/toolbox/alarm.c
deleted file mode 100644
index 9bd58aa..0000000
--- a/toolbox/alarm.c
+++ /dev/null
@@ -1,190 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <string.h>
-#include <errno.h>
-#include <time.h>
-#include <asm/ioctl.h>
-//#include <linux/rtc.h>
-#include <linux/android_alarm.h>
-
-int alarm_main(int argc, char *argv[])
-{
-	int c;
-    int res;
-	struct tm tm;
-	time_t t;
-	struct timespec ts;
-//	struct rtc_time rtc_time;
-	char strbuf[26];
-	int afd;
-	int nfd;
-//	struct timeval timeout = { 0, 0 };
-    int wait = 0;
-	fd_set rfds;
-	const char wake_lock_id[] = "alarm_test"; 
-	int waitalarmmask = 0;
-
-    int useutc = 0;
-	android_alarm_type_t alarmtype_low = ANDROID_ALARM_RTC_WAKEUP;
-	android_alarm_type_t alarmtype_high = ANDROID_ALARM_RTC_WAKEUP;
-	android_alarm_type_t alarmtype = 0;
-
-    do {
-        //c = getopt(argc, argv, "uw:");
-        c = getopt(argc, argv, "uwat:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'u':
-            useutc = 1;
-            break;
-		case 't':
-			alarmtype_low = alarmtype_high = strtol(optarg, NULL, 0);
-			break;
-		case 'a':
-			alarmtype_low = ANDROID_ALARM_RTC_WAKEUP;
-			alarmtype_high = ANDROID_ALARM_TYPE_COUNT - 1;
-			break;
-        case 'w':
-            //timeout.tv_sec = strtol(optarg, NULL, 0);
-            wait = 1;
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-    if(optind + 2 < argc) {
-        fprintf(stderr,"%s [-uwa] [-t type] [seconds]\n", argv[0]);
-        return 1;
-    }
-
-    afd = open("/dev/alarm", O_RDWR);
-    if(afd < 0) {
-        fprintf(stderr, "Unable to open rtc: %s\n", strerror(errno));
-        return 1;
-    }
-
-    if(optind == argc) {
-		for(alarmtype = alarmtype_low; alarmtype <= alarmtype_high; alarmtype++) {
-			waitalarmmask |= 1U << alarmtype;
-		}
-#if 0
-        res = ioctl(fd, RTC_ALM_READ, &tm);
-        if(res < 0) {
-            fprintf(stderr, "Unable to read alarm: %s\n", strerror(errno));
-			return 1;
-        }
-#endif
-#if 0
-		t = timegm(&tm);
-        if(useutc)
-            gmtime_r(&t, &tm);
-        else
-            localtime_r(&t, &tm);
-#endif
-#if 0
-        asctime_r(&tm, strbuf);
-        printf("%s", strbuf);
-#endif
-    }
-    else if(optind + 1 == argc) {
-#if 0
-        res = ioctl(fd, RTC_RD_TIME, &tm);
-        if(res < 0) {
-            fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno));
-			return 1;
-        }
-        asctime_r(&tm, strbuf);
-        printf("Now: %s", strbuf);
-        time(&tv.tv_sec);
-#endif
-#if 0
-		time(&ts.tv_sec);
-		ts.tv_nsec = 0;
-		
-        //strptime(argv[optind], NULL, &tm);
-        //tv.tv_sec = mktime(&tm);
-        //tv.tv_usec = 0;
-#endif
-		for(alarmtype = alarmtype_low; alarmtype <= alarmtype_high; alarmtype++) {
-			waitalarmmask |= 1U << alarmtype;
-		    res = ioctl(afd, ANDROID_ALARM_GET_TIME(alarmtype), &ts);
-		    if(res < 0) {
-		        fprintf(stderr, "Unable to get current time: %s\n", strerror(errno));
-				return 1;
-		    }
-		    ts.tv_sec += strtol(argv[optind], NULL, 0);
-		    //strtotimeval(argv[optind], &tv);
-			gmtime_r(&ts.tv_sec, &tm);
-		    printf("time %s -> %ld.%09ld\n", argv[optind], ts.tv_sec, ts.tv_nsec);
-		    asctime_r(&tm, strbuf);
-		    printf("Requested %s", strbuf);
-			
-		    res = ioctl(afd, ANDROID_ALARM_SET(alarmtype), &ts);
-		    if(res < 0) {
-		        fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno));
-				return 1;
-		    }
-		}
-#if 0
-        res = ioctl(fd, RTC_ALM_SET, &tm);
-        if(res < 0) {
-            fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno));
-			return 1;
-        }
-        res = ioctl(fd, RTC_AIE_ON);
-        if(res < 0) {
-            fprintf(stderr, "Unable to enable alarm: %s\n", strerror(errno));
-			return 1;
-        }
-#endif
-    }
-    else {
-        fprintf(stderr,"%s [-u] [date]\n", argv[0]);
-        return 1;
-    }
-
-	if(wait) {
-		while(waitalarmmask) {
-			printf("wait for alarm %x\n", waitalarmmask);
-			res = ioctl(afd, ANDROID_ALARM_WAIT);
-			if(res < 0) {
-				fprintf(stderr, "alarm wait failed\n");
-			}
-			printf("got alarm %x\n", res);
-			waitalarmmask &= ~res;
-			nfd = open("/sys/android_power/acquire_full_wake_lock", O_RDWR);
-			write(nfd, wake_lock_id, sizeof(wake_lock_id) - 1);
-			close(nfd);
-			//sleep(5);
-			nfd = open("/sys/android_power/release_wake_lock", O_RDWR);
-			write(nfd, wake_lock_id, sizeof(wake_lock_id) - 1);
-			close(nfd);
-		}
-		printf("done\n");
-	}
-#if 0	
-	FD_ZERO(&rfds);
-	FD_SET(fd, &rfds);
-	res = select(fd + 1, &rfds, NULL, NULL, &timeout);
-    if(res < 0) {
-        fprintf(stderr, "select failed: %s\n", strerror(errno));
-		return 1;
-    }
-	if(res > 0) {
-		int event;
-		read(fd, &event, sizeof(event));
-		fprintf(stderr, "got %x\n", event);
-	}
-	else {
-		fprintf(stderr, "timeout waiting for alarm\n");
-	}
-#endif
-
-    close(afd);
-
-    return 0;
-}
diff --git a/toolbox/bsd-compatibility.h b/toolbox/bsd-compatibility.h
index 9c6c34a..36ddca9 100644
--- a/toolbox/bsd-compatibility.h
+++ b/toolbox/bsd-compatibility.h
@@ -50,9 +50,6 @@
 
 #define S_ISWHT(x) false
 
-// TODO: should this be in bionic? (glibc does this, even though it's not quite right.)
-#define O_RSYNC O_SYNC
-
 __BEGIN_DECLS
 
 /* From NetBSD <grp.h> and <pwd.h>. */
diff --git a/toolbox/chcon.c b/toolbox/chcon.c
deleted file mode 100644
index d594b9b..0000000
--- a/toolbox/chcon.c
+++ /dev/null
@@ -1,25 +0,0 @@
-#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/chmod.c b/toolbox/chmod.c
deleted file mode 100644
index 2a524e9..0000000
--- a/toolbox/chmod.c
+++ /dev/null
@@ -1,101 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <dirent.h>
-#include <errno.h>
-#include <sys/limits.h>
-#include <sys/stat.h>
-
-#include <unistd.h>
-#include <time.h>
-
-void recurse_chmod(char* path, int mode)
-{
-    struct dirent *dp;
-    DIR *dir = opendir(path);
-    if (dir == NULL) {
-        // not a directory, carry on
-        return;
-    }
-    char *subpath = malloc(sizeof(char)*PATH_MAX);
-    int pathlen = strlen(path);
-
-    while ((dp = readdir(dir)) != NULL) {
-        if (strcmp(dp->d_name, ".") == 0 ||
-            strcmp(dp->d_name, "..") == 0) continue;
-
-        if (strlen(dp->d_name) + pathlen + 2/*NUL and slash*/ > PATH_MAX) {
-            fprintf(stderr, "Invalid path specified: too long\n");
-            exit(1);
-        }
-
-        strcpy(subpath, path);
-        strcat(subpath, "/");
-        strcat(subpath, dp->d_name);
-
-        if (chmod(subpath, mode) < 0) {
-            fprintf(stderr, "Unable to chmod %s: %s\n", subpath, strerror(errno));
-            exit(1);
-        }
-
-        recurse_chmod(subpath, mode);
-    }
-    free(subpath);
-    closedir(dir);
-}
-
-static int usage()
-{
-    fprintf(stderr, "Usage: chmod [OPTION] <MODE> <FILE>\n");
-    fprintf(stderr, "  -R, --recursive         change files and directories recursively\n");
-    fprintf(stderr, "  --help                  display this help and exit\n");
-
-    return 10;
-}
-
-int chmod_main(int argc, char **argv)
-{
-    int i;
-
-    if (argc < 3 || strcmp(argv[1], "--help") == 0) {
-        return usage();
-    }
-
-    int recursive = (strcmp(argv[1], "-R") == 0 ||
-                     strcmp(argv[1], "--recursive") == 0) ? 1 : 0;
-
-    if (recursive && argc < 4) {
-        return usage();
-    }
-
-    if (recursive) {
-        argc--;
-        argv++;
-    }
-
-    int mode = 0;
-    const char* s = argv[1];
-    while (*s) {
-        if (*s >= '0' && *s <= '7') {
-            mode = (mode<<3) | (*s-'0');
-        }
-        else {
-            fprintf(stderr, "Bad mode\n");
-            return 10;
-        }
-        s++;
-    }
-
-    for (i = 2; i < argc; i++) {
-        if (chmod(argv[i], mode) < 0) {
-            fprintf(stderr, "Unable to chmod %s: %s\n", argv[i], strerror(errno));
-            return 10;
-        }
-        if (recursive) {
-            recurse_chmod(argv[i], mode);
-        }
-    }
-    return 0;
-}
-
diff --git a/toolbox/clear.c b/toolbox/clear.c
deleted file mode 100644
index df46ad2..0000000
--- a/toolbox/clear.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2012, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    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
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * 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
- * 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
- * SUCH DAMAGE.
- */
-
-#include <stdio.h>
-
-int clear_main(int argc, char **argv) {
-    /* This prints the clear screen and move cursor to top-left corner control
-     * characters for VT100 terminals. This means it will not work on
-     * non-VT100 compliant terminals, namely Windows' cmd.exe, but should
-     * work on anything unix-y. */
-    fputs("\x1b[2J\x1b[H", stdout);
-    return 0;
-}
diff --git a/toolbox/date.c b/toolbox/date.c
deleted file mode 100644
index 70ce1d5..0000000
--- a/toolbox/date.c
+++ /dev/null
@@ -1,227 +0,0 @@
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <linux/android_alarm.h>
-#include <linux/rtc.h>
-#include <sys/ioctl.h>
-
-static int settime_alarm(struct timespec *ts) {
-    int fd, ret;
-
-    fd = open("/dev/alarm", O_RDWR);
-    if (fd < 0)
-        return fd;
-
-    ret = ioctl(fd, ANDROID_ALARM_SET_RTC, ts);
-    close(fd);
-    return ret;
-}
-
-static int settime_alarm_tm(struct tm *tm) {
-    time_t t;
-    struct timespec ts;
-
-    t = mktime(tm);
-    ts.tv_sec = t;
-    ts.tv_nsec = 0;
-    return settime_alarm(&ts);
-}
-
-static int settime_alarm_timeval(struct timeval *tv) {
-    struct timespec ts;
-
-    ts.tv_sec = tv->tv_sec;
-    ts.tv_nsec = tv->tv_usec * 1000;
-    return settime_alarm(&ts);
-}
-
-static int settime_rtc_tm(struct tm *tm) {
-    int fd, ret;
-    struct timeval tv;
-    struct rtc_time rtc;
-
-    fd = open("/dev/rtc0", O_RDWR);
-    if (fd < 0)
-        return fd;
-
-    tv.tv_sec = mktime(tm);
-    tv.tv_usec = 0;
-
-    ret = settimeofday(&tv, NULL);
-    if (ret < 0)
-        goto done;
-
-    memset(&rtc, 0, sizeof(rtc));
-    rtc.tm_sec = tm->tm_sec;
-    rtc.tm_min = tm->tm_min;
-    rtc.tm_hour = tm->tm_hour;
-    rtc.tm_mday = tm->tm_mday;
-    rtc.tm_mon = tm->tm_mon;
-    rtc.tm_year = tm->tm_year;
-    rtc.tm_wday = tm->tm_wday;
-    rtc.tm_yday = tm->tm_yday;
-    rtc.tm_isdst = tm->tm_isdst;
-
-    ret = ioctl(fd, RTC_SET_TIME, rtc);
-done:
-    close(fd);
-    return ret;
-}
-
-static int settime_rtc_timeval(struct timeval *tv) {
-    struct tm tm, *err;
-    time_t t = tv->tv_sec;
-
-    err = gmtime_r(&t, &tm);
-    if (!err)
-        return -1;
-
-    return settime_rtc_tm(&tm);
-}
-
-static void settime(char *s) {
-    struct tm tm;
-    int day = atoi(s);
-    int hour;
-
-    while (*s && *s != '.')
-        s++;
-
-    if (*s)
-        s++;
-
-    hour = atoi(s);
-
-    tm.tm_year = day / 10000 - 1900;
-    tm.tm_mon = (day % 10000) / 100 - 1;
-    tm.tm_mday = (day % 100);
-    tm.tm_hour = hour / 10000;
-    tm.tm_min = (hour % 10000) / 100;
-    tm.tm_sec = (hour % 100);
-    tm.tm_isdst = -1;
-
-    if (settime_alarm_tm(&tm) < 0)
-        settime_rtc_tm(&tm);
-}
-
-static char *parse_time(const char *str, struct timeval *ts) {
-  char *s;
-  long fs = 0; /* fractional seconds */
-
-  ts->tv_sec = strtoumax(str, &s, 10);
-
-  if (*s == '.') {
-    s++;
-    int count = 0;
-
-    /* read up to 6 digits (microseconds) */
-    while (*s && isdigit(*s)) {
-      if (++count < 7) {
-        fs = fs*10 + (*s - '0');
-      }
-      s++;
-    }
-
-    for (; count < 6; count++) {
-      fs *= 10;
-    }
-  }
-
-  ts->tv_usec = fs;
-  return s;
-}
-
-int date_main(int argc, char *argv[])
-{
-    int c;
-    int res;
-    struct tm tm;
-    time_t t;
-    struct timeval tv;
-    char strbuf[260];
-
-    int useutc = 0;
-
-    tzset();
-
-    do {
-        c = getopt(argc, argv, "us:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'u':
-            useutc = 1;
-            break;
-        case 's':
-            settime(optarg);
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-    if(optind + 2 < argc) {
-        fprintf(stderr,"%s [-u] [date]\n", argv[0]);
-        return 1;
-    }
-
-    int hasfmt = argc == optind + 1 && argv[optind][0] == '+';
-    if(optind == argc || hasfmt) {
-        time(&t);
-        if (useutc) {
-            gmtime_r(&t, &tm);
-            strftime(strbuf, sizeof(strbuf),
-                     (hasfmt ? argv[optind] + 1 : "%a %b %e %H:%M:%S GMT %Y"),
-                     &tm);
-        } else {
-            localtime_r(&t, &tm);
-            strftime(strbuf, sizeof(strbuf),
-                     (hasfmt ? argv[optind] + 1 : "%a %b %e %H:%M:%S %Z %Y"),
-                     &tm);
-        }
-        printf("%s\n", strbuf);
-    }
-    else if(optind + 1 == argc) {
-#if 0
-        struct tm *tmptr;
-        tmptr = getdate(argv[optind]);
-        if(tmptr == NULL) {
-            fprintf(stderr,"getdate_r failed\n");
-            return 1;
-        }
-        tm = *tmptr;
-#if 0
-        if(getdate_r(argv[optind], &tm) < 0) {
-            fprintf(stderr,"getdate_r failed %s\n", strerror(errno));
-            return 1;
-        }
-#endif
-#endif
-        //strptime(argv[optind], NULL, &tm);
-        //tv.tv_sec = mktime(&tm);
-        //tv.tv_usec = 0;
-        parse_time(argv[optind], &tv);
-        printf("time %s -> %lu.%lu\n", argv[optind], tv.tv_sec, tv.tv_usec);
-        res = settime_alarm_timeval(&tv);
-        if (res < 0)
-            res = settime_rtc_timeval(&tv);
-        if(res < 0) {
-            fprintf(stderr,"settimeofday failed %s\n", strerror(errno));
-            return 1;
-        }
-    }
-    else {
-        fprintf(stderr,"%s [-s 20070325.123456] [-u] [date]\n", argv[0]);
-        return 1;
-    }
-
-    return 0;
-}
diff --git a/toolbox/dmesg.c b/toolbox/dmesg.c
deleted file mode 100644
index 9c73b00..0000000
--- a/toolbox/dmesg.c
+++ /dev/null
@@ -1,58 +0,0 @@
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <errno.h>
-#include <sys/klog.h>
-#include <string.h>
-
-#define FALLBACK_KLOG_BUF_SHIFT	17	/* CONFIG_LOG_BUF_SHIFT from our kernel */
-#define FALLBACK_KLOG_BUF_LEN	(1 << FALLBACK_KLOG_BUF_SHIFT)
-
-int dmesg_main(int argc, char **argv)
-{
-    char *buffer;
-    char *p;
-    ssize_t ret;
-    int n, op, klog_buf_len;
-
-    klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
-
-    if (klog_buf_len <= 0) {
-        klog_buf_len = FALLBACK_KLOG_BUF_LEN;
-    }
-
-    buffer = (char *)malloc(klog_buf_len + 1);
-
-    if (!buffer) {
-        perror("malloc");
-        return EXIT_FAILURE;
-    }
-
-    p = buffer;
-
-    if((argc == 2) && (!strcmp(argv[1],"-c"))) {
-        op = KLOG_READ_CLEAR;
-    } else {
-        op = KLOG_READ_ALL;
-    }
-
-    n = klogctl(op, buffer, klog_buf_len);
-    if (n < 0) {
-        perror("klogctl");
-        return EXIT_FAILURE;
-    }
-    buffer[n] = '\0';
-
-    while((ret = write(STDOUT_FILENO, p, n))) {
-        if (ret == -1) {
-	    if (errno == EINTR)
-                continue;
-	    perror("write");
-	    return EXIT_FAILURE;
-	}
-	p += ret;
-	n -= ret;
-    }
-
-    return 0;
-}
diff --git a/toolbox/exists.c b/toolbox/exists.c
deleted file mode 100644
index e348668..0000000
--- a/toolbox/exists.c
+++ /dev/null
@@ -1,16 +0,0 @@
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-int exists_main(int argc, char *argv[])
-{
-    struct stat s;
-
-    if(argc < 2) return 1;
-
-    if(stat(argv[1], &s)) {
-        return 1;
-    } else {
-        return 0;
-    }
-}
diff --git a/toolbox/getenforce.c b/toolbox/getenforce.c
deleted file mode 100644
index 9e7589a..0000000
--- a/toolbox/getenforce.c
+++ /dev/null
@@ -1,30 +0,0 @@
-#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 da83ec3..c58eb5d 100644
--- a/toolbox/getevent.c
+++ b/toolbox/getevent.c
@@ -10,6 +10,7 @@
 #include <sys/poll.h>
 #include <linux/input.h>
 #include <errno.h>
+#include <unistd.h>
 
 #include "getevent.h"
 
diff --git a/toolbox/hd.c b/toolbox/hd.c
deleted file mode 100644
index 7c9998e..0000000
--- a/toolbox/hd.c
+++ /dev/null
@@ -1,97 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdint.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <errno.h>
-
-int hd_main(int argc, char *argv[])
-{
-    int c;
-    int fd;
-	unsigned char buf[4096];
-    int res;
-	int read_len;
-	int i;
-	int filepos = 0;
-	int sum;
-	int lsum;
-
-	int base = -1;
-	int count = 0;
-	int repeat = 0;
-
-    do {
-        c = getopt(argc, argv, "b:c:r:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'b':
-            base = strtol(optarg, NULL, 0);
-            break;
-        case 'c':
-            count = strtol(optarg, NULL, 0);
-            break;
-		case 'r':
-			repeat = strtol(optarg, NULL, 0);
-			break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-
-    if (optind + 1 != argc) {
-        fprintf(stderr, "Usage: %s [-b base] [-c count] [-r delay] file\n", argv[0]);
-        exit(1);
-    }
-
-    fd = open(argv[optind], O_RDONLY);
-    if(fd < 0) {
-        fprintf(stderr, "could not open %s, %s\n", argv[optind], strerror(errno));
-        return 1;
-    }
-
-	do {
-		if(base >= 0) {
-			lseek(fd, base, SEEK_SET);
-			filepos = base;
-		}
-		sum = 0;
-		lsum = 0;
-	    while(1) {
-			read_len = sizeof(buf);
-			if(count > 0 && base + count - filepos < read_len)
-				read_len = base + count - filepos;
-	        res = read(fd, &buf, read_len);
-			if(res == 0)
-				break;
-			for(i = 0; i < res; i++) {
-				if((i & 15) == 0) {
-					printf("%08x: ", filepos + i);
-				}
-				lsum += buf[i];
-				sum += buf[i];
-				printf("%02x ", buf[i]);
-				if(((i & 15) == 15) || (i == res - 1)) {
-					printf("s %x\n", lsum);
-					lsum = 0;
-				}
-			}
-			if(res < 0) {
-				printf("Read error on %s, offset %d len %d, %s\n", argv[optind], filepos, read_len, strerror(errno));
-				return 1;
-			}
-			filepos += res;
-			if(filepos == base + count)
-				break;
-	    }
-		printf("sum %x\n", sum);
-		if(repeat)
-			sleep(repeat);
-	} while(repeat);
-	return 0;
-}
diff --git a/toolbox/ifconfig.c b/toolbox/ifconfig.c
deleted file mode 100644
index b953176..0000000
--- a/toolbox/ifconfig.c
+++ /dev/null
@@ -1,157 +0,0 @@
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include <errno.h>
-#include <string.h>
-#include <ctype.h>
-
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <linux/if.h>
-#include <linux/sockios.h>
-#include <arpa/inet.h>
-
-static void die(const char *s)
-{
-    fprintf(stderr,"error: %s (%s)\n", s, strerror(errno));
-    exit(-1);
-}
-
-static void setflags(int s, struct ifreq *ifr, int set, int clr)
-{
-    if(ioctl(s, SIOCGIFFLAGS, ifr) < 0) die("SIOCGIFFLAGS");
-    ifr->ifr_flags = (ifr->ifr_flags & (~clr)) | set;
-    if(ioctl(s, SIOCSIFFLAGS, ifr) < 0) die("SIOCSIFFLAGS");
-}
-
-static inline void init_sockaddr_in(struct sockaddr_in *sin, const char *addr)
-{
-    sin->sin_family = AF_INET;
-    sin->sin_port = 0;
-    sin->sin_addr.s_addr = inet_addr(addr);
-}
-
-static void setmtu(int s, struct ifreq *ifr, const char *mtu)
-{
-    int m = atoi(mtu);
-    ifr->ifr_mtu = m;
-    if(ioctl(s, SIOCSIFMTU, ifr) < 0) die("SIOCSIFMTU");
-}
-static void setdstaddr(int s, struct ifreq *ifr, const char *addr)
-{
-    init_sockaddr_in((struct sockaddr_in *) &ifr->ifr_dstaddr, addr);
-    if(ioctl(s, SIOCSIFDSTADDR, ifr) < 0) die("SIOCSIFDSTADDR");
-}
-
-static void setnetmask(int s, struct ifreq *ifr, const char *addr)
-{
-    init_sockaddr_in((struct sockaddr_in *) &ifr->ifr_netmask, addr);
-    if(ioctl(s, SIOCSIFNETMASK, ifr) < 0) die("SIOCSIFNETMASK");
-}
-
-static void setaddr(int s, struct ifreq *ifr, const char *addr)
-{
-    init_sockaddr_in((struct sockaddr_in *) &ifr->ifr_addr, addr);
-    if(ioctl(s, SIOCSIFADDR, ifr) < 0) die("SIOCSIFADDR");
-}
-
-int ifconfig_main(int argc, char *argv[])
-{
-    struct ifreq ifr;
-    int s;
-    unsigned int flags;
-    char astring[20];
-    char mstring[20];
-    char *updown, *brdcst, *loopbk, *ppp, *running, *multi;
-
-    argc--;
-    argv++;
-
-    if(argc == 0) return 0;
-
-    memset(&ifr, 0, sizeof(struct ifreq));
-    strncpy(ifr.ifr_name, argv[0], IFNAMSIZ);
-    ifr.ifr_name[IFNAMSIZ-1] = 0;
-    argc--, argv++;
-
-    if((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-        die("cannot open control socket\n");
-    }
-
-    if (argc == 0) {
-        if (ioctl(s, SIOCGIFADDR, &ifr) < 0) {
-            perror(ifr.ifr_name);
-            return -1;
-        } else
-            strlcpy(astring,
-                   inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr),
-                   sizeof(astring));
-
-        if (ioctl(s, SIOCGIFNETMASK, &ifr) < 0) {
-            perror(ifr.ifr_name);
-            return -1;
-        } else
-            strlcpy(mstring,
-                   inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr),
-                   sizeof(mstring));
-
-        if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) {
-            perror(ifr.ifr_name);
-            return -1;
-        } else
-            flags = ifr.ifr_flags;
-
-        printf("%s: ip %s mask %s flags [", ifr.ifr_name,
-               astring,
-               mstring
-               );
-
-        updown =  (flags & IFF_UP)           ? "up" : "down";
-        brdcst =  (flags & IFF_BROADCAST)    ? " broadcast" : "";
-        loopbk =  (flags & IFF_LOOPBACK)     ? " loopback" : "";
-        ppp =     (flags & IFF_POINTOPOINT)  ? " point-to-point" : "";
-        running = (flags & IFF_RUNNING)      ? " running" : "";
-        multi =   (flags & IFF_MULTICAST)    ? " multicast" : "";
-        printf("%s%s%s%s%s%s]\n", updown, brdcst, loopbk, ppp, running, multi);
-        return 0;
-    }
-    
-    while(argc > 0) {
-        if (!strcmp(argv[0], "up")) {
-            setflags(s, &ifr, IFF_UP, 0);
-        } else if (!strcmp(argv[0], "mtu")) {
-            argc--, argv++;
-            if (!argc) {
-                errno = EINVAL;
-                die("expecting a value for parameter \"mtu\"");
-            }
-            setmtu(s, &ifr, argv[0]);
-        } else if (!strcmp(argv[0], "-pointopoint")) {
-            setflags(s, &ifr, IFF_POINTOPOINT, 1);
-        } else if (!strcmp(argv[0], "pointopoint")) {
-            argc--, argv++;
-            if (!argc) { 
-                errno = EINVAL;
-                die("expecting an IP address for parameter \"pointtopoint\"");
-            }
-            setdstaddr(s, &ifr, argv[0]);
-            setflags(s, &ifr, IFF_POINTOPOINT, 0);
-        } else if (!strcmp(argv[0], "down")) {
-            setflags(s, &ifr, 0, IFF_UP);
-        } else if (!strcmp(argv[0], "netmask")) {
-            argc--, argv++;
-            if (!argc) { 
-                errno = EINVAL;
-                die("expecting an IP address for parameter \"netmask\"");
-            }
-            setnetmask(s, &ifr, argv[0]);
-        } else if (isdigit(argv[0][0])) {
-            setaddr(s, &ifr, argv[0]);
-            setflags(s, &ifr, IFF_UP, 0);
-        }
-        argc--, argv++;
-    }
-    return 0;
-}
diff --git a/toolbox/insmod.c b/toolbox/insmod.c
deleted file mode 100644
index d252433..0000000
--- a/toolbox/insmod.c
+++ /dev/null
@@ -1,97 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <malloc.h>
-#include <errno.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-extern int init_module(void *, unsigned long, const char *);
-
-static void *read_file(const char *filename, ssize_t *_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 insmod_main(int argc, char **argv)
-{
-	void *file;
-	ssize_t size = 0;
-	char opts[1024];
-	int ret;
-
-	/* make sure we've got an argument */
-	if (argc < 2) {
-		fprintf(stderr, "usage: insmod <module.o>\n");
-		return -1;
-	}
-
-	/* read the file into memory */
-	file = read_file(argv[1], &size);
-	if (!file) {
-		fprintf(stderr, "insmod: can't open '%s'\n", argv[1]);
-		return -1;
-	}
-
-	opts[0] = '\0';
-	if (argc > 2) {
-		int i, len;
-		char *end = opts + sizeof(opts) - 1;
-		char *ptr = opts;
-
-		for (i = 2; (i < argc) && (ptr < end); i++) {
-			len = MIN(strlen(argv[i]), (size_t)(end - ptr));
-			memcpy(ptr, argv[i], len);
-			ptr += len;
-			*ptr++ = ' ';
-		}
-		*(ptr - 1) = '\0';
-	}
-
-	/* pass it to the kernel */
-	ret = init_module(file, size, opts);
-	if (ret != 0) {
-		fprintf(stderr,
-                "insmod: init_module '%s' failed (%s)\n",
-                argv[1], strerror(errno));
-	}
-
-	/* free the file buffer */
-	free(file);
-
-	return ret;
-}
-
diff --git a/toolbox/ioctl.c b/toolbox/ioctl.c
index fd90812..d1cc14a 100644
--- a/toolbox/ioctl.c
+++ b/toolbox/ioctl.c
@@ -9,6 +9,7 @@
 #include <errno.h>
 #include <pthread.h>
 #include <sys/ioctl.h>
+#include <unistd.h>
 
 int ioctl_main(int argc, char *argv[])
 {
@@ -45,7 +46,7 @@
             break;
         case 'h':
             fprintf(stderr, "%s [-l <length>] [-a <argsize>] [-rdh] <device> <ioctlnr>\n"
-                    "  -l <lenght>   Length of io buffer\n"
+                    "  -l <length>   Length of io buffer\n"
                     "  -a <argsize>  Size of each argument (1-8)\n"
                     "  -r            Open device in read only mode\n"
                     "  -d            Direct argument (no iobuffer)\n"
diff --git a/toolbox/lsmod.c b/toolbox/lsmod.c
deleted file mode 100644
index 8b55ee6..0000000
--- a/toolbox/lsmod.c
+++ /dev/null
@@ -1,10 +0,0 @@
-#include <stdio.h>
-
-extern int cat_main(int argc, char **argv);
-
-int lsmod_main(int argc, char **argv)
-{
-	char *cat_argv[] = { "cat", "/proc/modules", NULL };
-	return cat_main(2, cat_argv);
-}
-
diff --git a/toolbox/lsusb.c b/toolbox/lsusb.c
deleted file mode 100644
index 236e74b..0000000
--- a/toolbox/lsusb.c
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 2010 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 <endian.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdint.h>
-#include <string.h>
-
-#include <usbhost/usbhost.h>
-
-static int verbose = 0;
-static char str_buff[4096];
-
-static const char *get_str(struct usb_device *dev, int id)
-{
-    char *str = usb_device_get_string(dev, id);
-
-    if (id && str) {
-        strlcpy(str_buff, str, sizeof(str_buff));
-        free(str);
-    } else {
-        snprintf(str_buff, sizeof(str_buff), "%02x", id);
-    }
-
-    return str_buff;
-}
-
-
-static void lsusb_parse_device_descriptor(struct usb_device *dev,
-                                          struct usb_device_descriptor *desc)
-{
-    printf("  Device Descriptor\n");
-    printf("\tbcdUSB: %04x\n", letoh16(desc->bcdUSB));
-    printf("\tbDeviceClass: %02x\n", desc->bDeviceClass);
-    printf("\tbDeviceSubClass: %02x\n", desc->bDeviceSubClass);
-    printf("\tbDeviceProtocol: %02x\n", desc->bDeviceProtocol);
-    printf("\tbMaxPacketSize0: %02x\n", desc->bMaxPacketSize0);
-    printf("\tidVendor: %04x\n", letoh16(desc->idVendor));
-    printf("\tidProduct: %04x\n", letoh16(desc->idProduct));
-    printf("\tbcdDevice: %04x\n", letoh16(desc->bcdDevice));
-    printf("\tiManufacturer: %s\n", get_str(dev, desc->iManufacturer));
-    printf("\tiProduct: %s\n", get_str(dev, desc->iProduct));
-    printf("\tiSerialNumber: %s\n", get_str(dev,desc->iSerialNumber));
-    printf("\tbNumConfiguration: %02x\n", desc->bNumConfigurations);
-    printf("\n");
-}
-
-static void lsusb_parse_config_descriptor(struct usb_device *dev,
-                                          struct usb_config_descriptor *desc)
-{
-    printf("  Config Descriptor\n");
-    printf("\twTotalLength: %04x\n", letoh16(desc->wTotalLength));
-    printf("\tbNumInterfaces: %02x\n", desc->bNumInterfaces);
-    printf("\tbConfigurationValue: %02x\n", desc->bConfigurationValue);
-    printf("\tiConfiguration: %s\n", get_str(dev, desc->iConfiguration));
-    printf("\tbmAttributes: %02x\n", desc->bmAttributes);
-    printf("\tbMaxPower: %d mA\n", desc->bMaxPower * 2);
-    printf("\n");
-}
-
-static void lsusb_parse_interface_descriptor(struct usb_device *dev,
-                                             struct usb_interface_descriptor *desc)
-{
-    printf("  Interface Descriptor\n");
-    printf("\tbInterfaceNumber: %02x\n", desc->bInterfaceNumber);
-    printf("\tbAlternateSetting: %02x\n", desc->bAlternateSetting);
-    printf("\tbNumEndpoints: %02x\n", desc->bNumEndpoints);
-    printf("\tbInterfaceClass: %02x\n", desc->bInterfaceClass);
-    printf("\tbInterfaceSubClass: %02x\n", desc->bInterfaceSubClass);
-    printf("\tbInterfaceProtocol: %02x\n", desc->bInterfaceProtocol);
-    printf("\tiInterface: %s\n", get_str(dev, desc->iInterface));
-    printf("\n");
-}
-
-static void lsusb_parse_endpoint_descriptor(struct usb_device *dev,
-                                            struct usb_endpoint_descriptor *desc)
-{
-    printf("  Endpoint Descriptor\n");
-    printf("\tbEndpointAddress: %02x\n", desc->bEndpointAddress);
-    printf("\tbmAttributes: %02x\n", desc->bmAttributes);
-    printf("\twMaxPacketSize: %02x\n", letoh16(desc->wMaxPacketSize));
-    printf("\tbInterval: %02x\n", desc->bInterval);
-    printf("\tbRefresh: %02x\n", desc->bRefresh);
-    printf("\tbSynchAddress: %02x\n", desc->bSynchAddress);
-    printf("\n");
-}
-
-static void lsusb_dump_descriptor(struct usb_device *dev,
-                                  struct usb_descriptor_header *desc)
-{
-    int i;
-    printf("  Descriptor type %02x\n", desc->bDescriptorType);
-
-    for (i = 0; i < desc->bLength; i++ ) {
-        if ((i % 16) == 0)
-            printf("\t%02x:", i);
-        printf(" %02x", ((uint8_t *)desc)[i]);
-        if ((i % 16) == 15)
-            printf("\n");
-    }
-
-    if ((i % 16) != 0)
-        printf("\n");
-    printf("\n");
-}
-
-static void lsusb_parse_descriptor(struct usb_device *dev,
-                                   struct usb_descriptor_header *desc)
-{
-    switch (desc->bDescriptorType) {
-    case USB_DT_DEVICE:
-        lsusb_parse_device_descriptor(dev, (struct usb_device_descriptor *) desc);
-        break;
-
-    case USB_DT_CONFIG:
-        lsusb_parse_config_descriptor(dev, (struct usb_config_descriptor *) desc);
-        break;
-
-    case USB_DT_INTERFACE:
-        lsusb_parse_interface_descriptor(dev, (struct usb_interface_descriptor *) desc);
-        break;
-
-    case USB_DT_ENDPOINT:
-        lsusb_parse_endpoint_descriptor(dev, (struct usb_endpoint_descriptor *) desc);
-        break;
-
-    default:
-        lsusb_dump_descriptor(dev, desc);
-
-        break;
-    }
-}
-
-static int lsusb_device_added(const char *dev_name, void *client_data)
-{
-    struct usb_device *dev = usb_device_open(dev_name);
-
-    if (!dev) {
-        fprintf(stderr, "can't open device %s: %s\n", dev_name, strerror(errno));
-        return 0;
-    }
-
-    if (verbose) {
-        struct usb_descriptor_iter iter;
-        struct usb_descriptor_header *desc;
-
-        printf("%s:\n", dev_name);
-
-        usb_descriptor_iter_init(dev, &iter);
-
-        while ((desc = usb_descriptor_iter_next(&iter)) != NULL)
-            lsusb_parse_descriptor(dev, desc);
-
-    } else {
-        uint16_t vid, pid;
-        char *mfg_name, *product_name, *serial;
-
-        vid = usb_device_get_vendor_id(dev);
-        pid = usb_device_get_product_id(dev);
-        mfg_name = usb_device_get_manufacturer_name(dev);
-        product_name = usb_device_get_product_name(dev);
-        serial = usb_device_get_serial(dev);
-
-        printf("%s: %04x:%04x %s %s %s\n", dev_name, vid, pid,
-               mfg_name, product_name, serial);
-
-        free(mfg_name);
-        free(product_name);
-        free(serial);
-    }
-
-    usb_device_close(dev);
-
-    return 0;
-}
-
-static int lsusb_device_removed(const char *dev_name, void *client_data)
-{
-    return 0;
-}
-
-
-static int lsusb_discovery_done(void *client_data)
-{
-    return 1;
-}
-
-
-
-int lsusb_main(int argc, char **argv)
-{
-    struct usb_host_context *ctx;
-
-    if (argc == 2 && !strcmp(argv[1], "-v"))
-        verbose = 1;
-
-    ctx = usb_host_init();
-    if (!ctx) {
-        perror("usb_host_init:");
-        return 1;
-    }
-
-    usb_host_run(ctx,
-                 lsusb_device_added,
-                 lsusb_device_removed,
-                 lsusb_discovery_done,
-                 NULL);
-
-    usb_host_cleanup(ctx);
-
-    return 0;
-}
-
diff --git a/toolbox/md5.c b/toolbox/md5.c
deleted file mode 100644
index 5de4d9e..0000000
--- a/toolbox/md5.c
+++ /dev/null
@@ -1,71 +0,0 @@
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <openssl/md5.h>
-
-static int usage()
-{
-    fprintf(stderr,"md5 file ...\n");
-    return -1;
-}
-
-static int do_md5(const char *path)
-{
-    unsigned int i;
-    int fd;
-    MD5_CTX md5_ctx;
-    unsigned char md5[MD5_DIGEST_LENGTH];
-
-    fd = open(path, O_RDONLY);
-    if (fd < 0) {
-        fprintf(stderr,"could not open %s, %s\n", path, strerror(errno));
-        return -1;
-    }
-
-    MD5_Init(&md5_ctx);
-
-    while (1) {
-        char buf[4096];
-        ssize_t rlen;
-        rlen = read(fd, buf, sizeof(buf));
-        if (rlen == 0)
-            break;
-        else if (rlen < 0) {
-            (void)close(fd);
-            fprintf(stderr,"could not read %s, %s\n", path, strerror(errno));
-            return -1;
-        }
-        MD5_Update(&md5_ctx, buf, rlen);
-    }
-    if (close(fd)) {
-        fprintf(stderr,"could not close %s, %s\n", path, strerror(errno));
-        return -1;
-    }
-
-    MD5_Final(md5, &md5_ctx);
-
-    for (i = 0; i < (int)sizeof(md5); i++)
-        printf("%02x", md5[i]);
-    printf("  %s\n", path);
-
-    return 0;
-}
-
-int md5_main(int argc, char *argv[])
-{
-    int i, ret = 0;
-
-    if (argc < 2)
-        return usage();
-
-    /* loop over the file args */
-    for (i = 1; i < argc; i++) {
-        if (do_md5(argv[i]))
-            ret = 1;
-    }
-
-    return ret;
-}
diff --git a/toolbox/mkdir.c b/toolbox/mkdir.c
deleted file mode 100644
index 398d350..0000000
--- a/toolbox/mkdir.c
+++ /dev/null
@@ -1,77 +0,0 @@
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/limits.h>
-#include <sys/stat.h>
-
-static int usage()
-{
-    fprintf(stderr,"mkdir [OPTION] <target>\n");
-    fprintf(stderr,"    --help           display usage and exit\n");
-    fprintf(stderr,"    -p, --parents    create parent directories as needed\n");
-    return -1;
-}
-
-int mkdir_main(int argc, char *argv[])
-{
-    int ret;
-    if(argc < 2 || strcmp(argv[1], "--help") == 0) {
-        return usage();
-    }
-
-    int recursive = (strcmp(argv[1], "-p") == 0 ||
-                     strcmp(argv[1], "--parents") == 0) ? 1 : 0;
-
-    if(recursive && argc < 3) {
-        // -p specified without a path
-        return usage();
-    }
-
-    if(recursive) {
-        argc--;
-        argv++;
-    }
-
-    char currpath[PATH_MAX], *pathpiece;
-    struct stat st;
-
-    while(argc > 1) {
-        argc--;
-        argv++;
-        if(recursive) {
-            // reset path
-            strcpy(currpath, "");
-            // create the pieces of the path along the way
-            pathpiece = strtok(argv[0], "/");
-            if(argv[0][0] == '/') {
-                // prepend / if needed
-                strcat(currpath, "/");
-            }
-            while(pathpiece != NULL) {
-                if(strlen(currpath) + strlen(pathpiece) + 2/*NUL and slash*/ > PATH_MAX) {
-                    fprintf(stderr, "Invalid path specified: too long\n");
-                    return 1;
-                }
-                strcat(currpath, pathpiece);
-                strcat(currpath, "/");
-                if(stat(currpath, &st) != 0) {
-                    ret = mkdir(currpath, 0777);
-                    if(ret < 0) {
-                        fprintf(stderr, "mkdir failed for %s, %s\n", currpath, strerror(errno));
-                        return ret;
-                    }
-                }
-                pathpiece = strtok(NULL, "/");
-            }
-        } else {
-            ret = mkdir(argv[0], 0777);
-            if(ret < 0) {
-                fprintf(stderr, "mkdir failed for %s, %s\n", argv[0], strerror(errno));
-                return ret;
-            }
-        }
-    }
-    
-    return 0;
-}
diff --git a/toolbox/mknod.c b/toolbox/mknod.c
deleted file mode 100644
index 0fedece..0000000
--- a/toolbox/mknod.c
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2014, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    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
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * 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
- * 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
- * SUCH DAMAGE.
- */
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <sys/stat.h>
-
-static int print_usage() {
-    fprintf(stderr, "mknod <path> [b|c|u|p] <major> <minor>\n");
-    return EXIT_FAILURE;
-}
-
-int mknod_main(int argc, char **argv) {
-    char *path = NULL;
-    int major = 0;
-    int minor = 0;
-    int args = 0;
-    mode_t mode = 0660;
-
-    /* Check correct argument count is 3 or 5 */
-    if (argc != 3 && argc != 5) {
-        fprintf(stderr, "Incorrect argument count\n");
-        return print_usage();
-    }
-
-    path = argv[1];
-
-    const char node_type = *argv[2];
-    switch (node_type) {
-    case 'b':
-        mode |= S_IFBLK;
-        args = 5;
-        break;
-    case 'c':
-    case 'u':
-        mode |= S_IFCHR;
-        args = 5;
-        break;
-    case 'p':
-        mode |= S_IFIFO;
-        args = 3;
-        break;
-    default:
-        fprintf(stderr, "Invalid node type '%c'\n", node_type);
-        return print_usage();
-    }
-
-    if (argc != args) {
-        if (args == 5) {
-            fprintf(stderr, "Node type '%c' requires <major> and <minor>\n", node_type);
-        } else {
-            fprintf(stderr, "Node type '%c' does not require <major> and <minor>\n", node_type);
-        }
-        return print_usage();
-    }
-
-    if (args == 5) {
-        major = atoi(argv[3]);
-        minor = atoi(argv[4]);
-    }
-
-    if (mknod(path, mode, makedev(major, minor))) {
-        perror("Unable to create node");
-        return EXIT_FAILURE;
-    }
-    return 0;
-}
diff --git a/toolbox/mkswap.c b/toolbox/mkswap.c
deleted file mode 100644
index 0904152..0000000
--- a/toolbox/mkswap.c
+++ /dev/null
@@ -1,93 +0,0 @@
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/swap.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-/* XXX This needs to be obtained from kernel headers. See b/9336527 */
-struct linux_swap_header {
-    char            bootbits[1024]; /* Space for disklabel etc. */
-    uint32_t        version;
-    uint32_t        last_page;
-    uint32_t        nr_badpages;
-    unsigned char   sws_uuid[16];
-    unsigned char   sws_volume[16];
-    uint32_t        padding[117];
-    uint32_t        badpages[1];
-};
-
-#define MAGIC_SWAP_HEADER     "SWAPSPACE2"
-#define MAGIC_SWAP_HEADER_LEN 10
-#define MIN_PAGES             10
-
-int mkswap_main(int argc, char **argv)
-{
-    int err = 0;
-    int fd;
-    ssize_t len;
-    off_t swap_size;
-    int pagesize;
-    struct linux_swap_header sw_hdr;
-
-    if (argc != 2) {
-        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
-        return -EINVAL;
-    }
-
-    fd = open(argv[1], O_WRONLY);
-    if (fd < 0) {
-        err = errno;
-        fprintf(stderr, "Cannot open %s\n", argv[1]);
-        return err;
-    }
-
-    pagesize = getpagesize();
-    /* Determine the length of the swap file */
-    swap_size = lseek(fd, 0, SEEK_END);
-    if (swap_size < MIN_PAGES * pagesize) {
-        fprintf(stderr, "Swap file needs to be at least %dkB\n",
-            (MIN_PAGES * pagesize) >> 10);
-        err = -ENOSPC;
-        goto err;
-    }
-    if (lseek(fd, 0, SEEK_SET)) {
-        err = errno;
-        fprintf(stderr, "Can't seek to the beginning of the file\n");
-        goto err;
-    }
-
-    memset(&sw_hdr, 0, sizeof(sw_hdr));
-    sw_hdr.version = 1;
-    sw_hdr.last_page = (swap_size / pagesize) - 1;
-
-    len = write(fd, &sw_hdr, sizeof(sw_hdr));
-    if (len != sizeof(sw_hdr)) {
-        err = errno;
-        fprintf(stderr, "Failed to write swap header into %s\n", argv[1]);
-        goto err;
-    }
-
-    /* Write the magic header */
-    if (lseek(fd, pagesize - MAGIC_SWAP_HEADER_LEN, SEEK_SET) < 0) {
-        err = errno;
-        fprintf(stderr, "Failed to seek into %s\n", argv[1]);
-        goto err;
-    }
-
-    len = write(fd, MAGIC_SWAP_HEADER, MAGIC_SWAP_HEADER_LEN);
-    if (len != MAGIC_SWAP_HEADER_LEN) {
-        err = errno;
-        fprintf(stderr, "Failed to write magic swap header into %s\n", argv[1]);
-        goto err;
-    }
-
-    if (fsync(fd) < 0) {
-        err = errno;
-        fprintf(stderr, "Failed to sync %s\n", argv[1]);
-        goto err;
-    }
-err:
-    close(fd);
-    return err;
-}
diff --git a/toolbox/netstat.c b/toolbox/netstat.c
deleted file mode 100644
index 05dc640..0000000
--- a/toolbox/netstat.c
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (c) 2008, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    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
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * 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
- * 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
- * SUCH DAMAGE.
- */
-
-#include <arpa/inet.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-
-typedef union iaddr iaddr;
-typedef union iaddr6 iaddr6;
-
-union iaddr {
-    unsigned u;
-    unsigned char b[4];
-};
-
-union iaddr6 {
-    struct {
-        unsigned a;
-        unsigned b;
-        unsigned c;
-        unsigned d;
-    } u;
-    unsigned char b[16];
-};
-
-static const char *state2str(unsigned state)
-{
-    switch(state){
-    case 0x1: return "ESTABLISHED";
-    case 0x2: return "SYN_SENT";
-    case 0x3: return "SYN_RECV";
-    case 0x4: return "FIN_WAIT1";
-    case 0x5: return "FIN_WAIT2";
-    case 0x6: return "TIME_WAIT";
-    case 0x7: return "CLOSE";
-    case 0x8: return "CLOSE_WAIT";
-    case 0x9: return "LAST_ACK";
-    case 0xA: return "LISTEN";
-    case 0xB: return "CLOSING";
-    default: return "UNKNOWN";
-    }
-}
-
-/* addr + : + port + \0 */
-#define ADDR_LEN INET6_ADDRSTRLEN + 1 + 5 + 1
-
-static void addr2str(int af, const void *addr, unsigned port, char *buf)
-{
-    if (inet_ntop(af, addr, buf, ADDR_LEN) == NULL) {
-        *buf = '\0';
-        return;
-    }
-    size_t len = strlen(buf);
-    if (port) {
-        snprintf(buf+len, ADDR_LEN-len, ":%d", port);
-    } else {
-        strncat(buf+len, ":*", ADDR_LEN-len-1);
-    }
-}
-
-static void ipv4(const char *filename, const char *label) {
-    FILE *fp = fopen(filename, "r");
-    if (fp == NULL) {
-        return;
-    }
-    char buf[BUFSIZ];
-    fgets(buf, BUFSIZ, fp);
-    while (fgets(buf, BUFSIZ, fp)){
-        char lip[ADDR_LEN];
-        char rip[ADDR_LEN];
-        iaddr laddr, raddr;
-        unsigned lport, rport, state, txq, rxq, num;
-        int n = sscanf(buf, " %d: %x:%x %x:%x %x %x:%x",
-                       &num, &laddr.u, &lport, &raddr.u, &rport,
-                       &state, &txq, &rxq);
-        if (n == 8) {
-            addr2str(AF_INET, &laddr, lport, lip);
-            addr2str(AF_INET, &raddr, rport, rip);
-
-            printf("%4s  %6d %6d %-22s %-22s %s\n",
-                   label, rxq, txq, lip, rip,
-                   state2str(state));
-        }
-    }
-    fclose(fp);
-}
-
-static void ipv6(const char *filename, const char *label) {
-    FILE *fp = fopen(filename, "r");
-    if (fp == NULL) {
-        return;
-    }
-    char buf[BUFSIZ];
-    fgets(buf, BUFSIZ, fp);
-    while (fgets(buf, BUFSIZ, fp)){
-        char lip[ADDR_LEN];
-        char rip[ADDR_LEN];
-        iaddr6 laddr6, raddr6;
-        unsigned lport, rport, state, txq, rxq, num;
-        int n = sscanf(buf, " %d: %8x%8x%8x%8x:%x %8x%8x%8x%8x:%x %x %x:%x",
-                       &num, &laddr6.u.a, &laddr6.u.b, &laddr6.u.c, &laddr6.u.d, &lport,
-                       &raddr6.u.a, &raddr6.u.b, &raddr6.u.c, &raddr6.u.d, &rport,
-                       &state, &txq, &rxq);
-        if (n == 14) {
-            addr2str(AF_INET6, &laddr6, lport, lip);
-            addr2str(AF_INET6, &raddr6, rport, rip);
-
-            printf("%4s  %6d %6d %-22s %-22s %s\n",
-                   label, rxq, txq, lip, rip,
-                   state2str(state));
-        }
-    }
-    fclose(fp);
-}
-
-int netstat_main(int argc, char *argv[])
-{
-    printf("Proto Recv-Q Send-Q Local Address          Foreign Address        State\n");
-    ipv4("/proc/net/tcp",  "tcp");
-    ipv4("/proc/net/udp",  "udp");
-    ipv6("/proc/net/tcp6", "tcp6");
-    ipv6("/proc/net/udp6", "udp6");
-    return 0;
-}
diff --git a/toolbox/nohup.c b/toolbox/nohup.c
deleted file mode 100644
index 363999d..0000000
--- a/toolbox/nohup.c
+++ /dev/null
@@ -1,26 +0,0 @@
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-int nohup_main(int argc, char *argv[])
-{
-    if (argc < 2) {
-        fprintf(stderr, "Usage: %s [-n] program args...\n", argv[0]);
-        return EXIT_FAILURE;
-    }
-    signal(SIGHUP, SIG_IGN);
-    argv++;
-    if (strcmp(argv[0], "-n") == 0) {
-        argv++;
-        signal(SIGINT, SIG_IGN);
-        signal(SIGSTOP, SIG_IGN);
-        signal(SIGTTIN, SIG_IGN);
-        signal(SIGTTOU, SIG_IGN);
-        signal(SIGQUIT, SIG_IGN);
-        signal(SIGTERM, SIG_IGN);
-    }
-    execvp(argv[0], argv);
-    perror(argv[0]);
-    return EXIT_FAILURE;
-}
diff --git a/toolbox/notify.c b/toolbox/notify.c
deleted file mode 100644
index c983ed5..0000000
--- a/toolbox/notify.c
+++ /dev/null
@@ -1,145 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdint.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <sys/ioctl.h>
-#include <sys/inotify.h>
-#include <errno.h>
-
-int notify_main(int argc, char *argv[])
-{
-    int c;
-    int nfd, ffd;
-    int res;
-	char event_buf[512];
-    struct inotify_event *event;
-	int event_mask = IN_ALL_EVENTS;
-    int event_count = 1;
-	int print_files = 0;
-	int verbose = 2;
-	int width = 80;
-	char **file_names;
-	int file_count;
-	int id_offset = 0;
-	int i;
-	char *buf;
-
-    do {
-        c = getopt(argc, argv, "m:c:pv:w:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'm':
-            event_mask = strtol(optarg, NULL, 0);
-            break;
-        case 'c':
-            event_count = atoi(optarg);
-            break;
-		case 'p':
-			print_files = 1;
-			break;
-        case 'v':
-            verbose = atoi(optarg);
-            break;
-        case 'w':
-            width = atoi(optarg);
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-
-    if (argc <= optind) {
-        fprintf(stderr, "Usage: %s [-m eventmask] [-c count] [-p] [-v verbosity] path [path ...]\n", argv[0]);
-		return 1;
-    }
-
-    nfd = inotify_init();
-    if(nfd < 0) {
-        fprintf(stderr, "inotify_init failed, %s\n", strerror(errno));
-        return 1;
-    }
-	file_names = argv + optind;
-	file_count = argc - optind;
-	for(i = 0; i < file_count; i++) {
-		res = inotify_add_watch(nfd, file_names[i], event_mask);
-		if(res < 0) {
-	        fprintf(stderr, "inotify_add_watch failed for %s, %s\n", file_names[i], strerror(errno));
-			return 1;
-		}
-		if(i == 0)
-			id_offset = -res;
-		if(res + id_offset != i) {
-			fprintf(stderr, "%s got unexpected id %d instead of %d\n", file_names[i], res, i);
-			return 1;
-		}
-	}
-
-	buf = malloc(width + 2);
-    
-    while(1) {
-		int event_pos = 0;
-        res = read(nfd, event_buf, sizeof(event_buf));
-        if(res < (int)sizeof(*event)) {
-			if(errno == EINTR)
-				continue;
-            fprintf(stderr, "could not get event, %s\n", strerror(errno));
-            return 1;
-        }
-		//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);
-			if(verbose >= 2)
-		        printf("%s: %08x %08x \"%s\"\n", file_names[event->wd + id_offset], event->mask, event->cookie, event->len ? event->name : "");
-			else if(verbose >= 2)
-		        printf("%s: %08x \"%s\"\n", file_names[event->wd + id_offset], event->mask, event->len ? event->name : "");
-			else if(verbose >= 1)
-		        printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
-			if(print_files && (event->mask & IN_MODIFY)) {
-				char filename[512];
-				ssize_t read_len;
-				char *display_name;
-				int buflen;
-				strcpy(filename, file_names[event->wd + id_offset]);
-				if(event->len) {
-					strcat(filename, "/");
-					strcat(filename, event->name);
-				}
-				ffd = open(filename, O_RDONLY);
-				display_name = (verbose >= 2 || event->len == 0) ? filename : event->name;
-				buflen = width - strlen(display_name);
-				read_len = read(ffd, buf, buflen);
-				if(read_len > 0) {
-					if(read_len < buflen && buf[read_len-1] != '\n') {
-						buf[read_len] = '\n';
-						read_len++;
-					}
-					if(read_len == buflen) {
-						buf[--read_len] = '\0';
-						buf[--read_len] = '\n';
-						buf[--read_len] = '.';
-						buf[--read_len] = '.';
-						buf[--read_len] = '.';
-					}
-					else {
-						buf[read_len] = '\0';
-					}
-					printf("%s: %s", display_name, buf);
-				}
-				close(ffd);
-			}
-	        if(event_count && --event_count == 0)
-	            return 0;
-			event_size = sizeof(*event) + event->len;
-			res -= event_size;
-			event_pos += event_size;
-		}
-    }
-
-    return 0;
-}
diff --git a/toolbox/ps.c b/toolbox/ps.c
index 5458f6b..7d6dfa0 100644
--- a/toolbox/ps.c
+++ b/toolbox/ps.c
@@ -1,15 +1,13 @@
+#include <ctype.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <pwd.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <ctype.h>
-#include <fcntl.h>
-
 #include <string.h>
-
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <dirent.h>
-
-#include <pwd.h>
+#include <unistd.h>
 
 #include <cutils/sched_policy.h>
 
@@ -147,7 +145,7 @@
         strcpy(user,pw->pw_name);
     }
 
-    if(!namefilter || !strncmp(name, namefilter, strlen(namefilter))) {
+    if(!namefilter || !strncmp(cmdline[0] ? cmdline : name, namefilter, strlen(namefilter))) {
         if (display_flags & SHOW_MACLABEL) {
             fd = open(macline, O_RDONLY);
             strcpy(macline, "-");
diff --git a/toolbox/r.c b/toolbox/r.c
index 3b80db7..b96cdb2 100644
--- a/toolbox/r.c
+++ b/toolbox/r.c
@@ -5,6 +5,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/mman.h>
+#include <unistd.h>
 
 #if __LP64__
 #define strtoptr strtoull
@@ -18,7 +19,7 @@
     return -1;
 }
 
-int r_main(int argc, char *argv[])
+int main(int argc, char *argv[])
 {
     if(argc < 2) return usage();
 
diff --git a/toolbox/readlink.c b/toolbox/readlink.c
deleted file mode 100644
index d114e20..0000000
--- a/toolbox/readlink.c
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2013, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    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
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * 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
- * 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
- * SUCH DAMAGE.
- */
-
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-static int skip_newline, quiet_errors, canonicalize;
-
-static void usage(char* name) {
-    fprintf(stderr, "Usage: %s [OPTION]... FILE\n", name);
-}
-
-int readlink_main(int argc, char* argv[]) {
-    int c;
-    while ((c = getopt(argc, argv, "nfqs")) != -1) {
-        switch (c) {
-        case 'n':
-            skip_newline = 1;
-            break;
-        case 'f':
-            canonicalize = 1;
-            break;
-        case 'q':
-        case 's':
-            quiet_errors = 1;
-            break;
-        case '?':
-        default:
-            usage(argv[0]);
-            return EXIT_FAILURE;
-        }
-    }
-    int index = optind;
-    if (argc - index != 1) {
-        usage(argv[0]);
-        return EXIT_FAILURE;
-    }
-
-    char name[PATH_MAX+1];
-    if (canonicalize) {
-        if(!realpath(argv[optind], name)) {
-            if (!quiet_errors) {
-                perror("readlink");
-            }
-            return EXIT_FAILURE;
-        }
-    } else {
-        ssize_t len = readlink(argv[1], name, PATH_MAX);
-
-        if (len < 0) {
-            if (!quiet_errors) {
-                perror("readlink");
-            }
-            return EXIT_FAILURE;
-        }
-        name[len] = '\0';
-    }
-
-    fputs(name, stdout);
-    if (!skip_newline) {
-        fputs("\n", stdout);
-    }
-
-    return EXIT_SUCCESS;
-}
diff --git a/toolbox/readtty.c b/toolbox/readtty.c
deleted file mode 100644
index 2b27548..0000000
--- a/toolbox/readtty.c
+++ /dev/null
@@ -1,183 +0,0 @@
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/mman.h>
-#include <fcntl.h>
-#include <string.h>
-#include <termios.h>
-#include <unistd.h>
-
-struct {
-    char key;
-    char *chars;
-} map[] = {
-    { '1', "_ -1?!,.:;\"'<=>()_" },
-    { '2', "Cabc2ABC" },
-    { '3', "Fdef3DEF" },
-    { '4', "Ighi4GHI" },
-    { '5', "Ljkl5JKL" },
-    { '6', "Omno6MNO" },
-    { '7', "Spqrs7PQRS" },
-    { '8', "Vtuv8TUV" },
-    { '9', "Zwxyz9WXYZ" },
-    { '0', "*+&0@/#*" },
-};
-
-char next_char(char key, char current)
-{
-    int i;
-    char *next;
-    for(i = 0; i < sizeof(map) / sizeof(map[0]); i++) {
-        if(key == map[i].key) {
-            next = strchr(map[i].chars, current);
-            if(next && next[1])
-                return next[1];
-            return map[i].chars[1];
-        }
-    }
-    return key;
-}
-
-char prev_char(char key, char current)
-{
-    int i;
-    char *next;
-    for(i = 0; i < sizeof(map) / sizeof(map[0]); i++) {
-        if(key == map[i].key) {
-            next = strchr(map[i].chars+1, current);
-            if(next && next[-1])
-                return next[-1];
-            return map[i].chars[1];
-        }
-    }
-    return key;
-}
-
-int readtty_main(int argc, char *argv[])
-{
-    int c;
-    //int flags;
-    char buf[1];
-    int res;
-    struct termios ttyarg;
-    struct termios savedttyarg;
-    int nonblock = 0;
-    int timeout = 0;
-    int flush = 0;
-    int phone = 0;
-    char *accept = NULL;
-    char *rejectstring = NULL;
-    char last_char_in = 0;
-    char current_char = 0;
-    char *exit_string = NULL;
-    int exit_match = 0;
-
-    do {
-        c = getopt(argc, argv, "nt:fa:r:pe:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 't':
-            timeout = atoi(optarg);
-            break;
-        case 'n':
-            nonblock = 1;
-            break;
-        case 'f':
-            flush = 1;
-            break;
-        case 'a':
-            accept = optarg;
-            break;
-        case 'r':
-            rejectstring = optarg;
-            break;
-        case 'p':
-            phone = 1;
-            break;
-        case 'e':
-            exit_string = optarg;
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-
-    if(flush)
-        tcflush(STDIN_FILENO, TCIFLUSH);
-    ioctl(STDIN_FILENO, TCGETS , &savedttyarg) ;       /* set changed tty arguments */
-    ttyarg = savedttyarg;
-    ttyarg.c_cc[VMIN] = (timeout > 0 || nonblock) ? 0 : 1;                /* minimum of 0 chars */
-    ttyarg.c_cc[VTIME] = timeout;              /* wait max 15/10 sec */
-    ttyarg.c_iflag = BRKINT | ICRNL; 
-    ttyarg.c_lflag &= ~(ECHO | ICANON);
-    ioctl(STDIN_FILENO, TCSETS , &ttyarg);
-
-    while (1) {
-        res = read(STDIN_FILENO, buf, 1);
-        if(res <= 0) {
-            if(phone) {
-                if(current_char) {
-                    write(STDERR_FILENO, &current_char, 1);
-                    write(STDOUT_FILENO, &current_char, 1);
-                    if(exit_string && current_char == exit_string[exit_match]) {
-                        exit_match++;
-                        if(exit_string[exit_match] == '\0')
-                            break;
-                    }
-                    else
-                        exit_match = 0;
-                    current_char = 0;
-                }
-                continue;
-            }
-            break;
-        }
-        if(accept && strchr(accept, buf[0]) == NULL) {
-            if(rejectstring) {
-                write(STDOUT_FILENO, rejectstring, strlen(rejectstring));
-                break;
-            }
-            if(flush)
-                tcflush(STDIN_FILENO, TCIFLUSH);
-            continue;
-        }
-        if(phone) {
-            //if(!isprint(buf[0])) {
-            //  fprintf(stderr, "got unprintable character 0x%x\n", buf[0]);
-            //}
-            if(buf[0] == '\0') {
-                if(current_char) {
-                    current_char = prev_char(last_char_in, current_char);
-                    write(STDERR_FILENO, &current_char, 1);
-                    write(STDERR_FILENO, "\b", 1);
-                }
-                continue;
-            }
-            if(current_char && buf[0] != last_char_in) {
-                write(STDERR_FILENO, &current_char, 1);
-                write(STDOUT_FILENO, &current_char, 1);
-                if(exit_string && current_char == exit_string[exit_match]) {
-                    exit_match++;
-                    if(exit_string[exit_match] == '\0')
-                        break;
-                }
-                else
-                    exit_match = 0;
-                current_char = 0;
-            }
-            last_char_in = buf[0];
-            current_char = next_char(last_char_in, current_char);
-            write(STDERR_FILENO, &current_char, 1);
-            write(STDERR_FILENO, "\b", 1);
-            continue;
-        }
-        write(STDOUT_FILENO, buf, 1);
-        break;
-    }
-    ioctl(STDIN_FILENO, TCSETS , &savedttyarg) ;       /* set changed tty arguments */
-
-    return 0;
-}
diff --git a/toolbox/rmmod.c b/toolbox/rmmod.c
deleted file mode 100644
index c7e0d6a..0000000
--- a/toolbox/rmmod.c
+++ /dev/null
@@ -1,53 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <malloc.h>
-#include <errno.h>
-#include <asm/unistd.h>
-
-extern int delete_module(const char *, unsigned int);
-
-int rmmod_main(int argc, char **argv)
-{
-	int ret, i;
-	char *modname, *dot;
-
-	/* make sure we've got an argument */
-	if (argc < 2) {
-		fprintf(stderr, "usage: rmmod <module>\n");
-		return -1;
-	}
-
-	/* if given /foo/bar/blah.ko, make a weak attempt
-	 * to convert to "blah", just for convenience
-	 */
-	modname = strrchr(argv[1], '/');
-	if (!modname)
-		modname = argv[1];
-	else modname++;
-
-	dot = strchr(argv[1], '.');
-	if (dot)
-		*dot = '\0';
-
-	/* Replace "-" with "_". This would keep rmmod
-	 * compatible with module-init-tools version of
-	 * rmmod
-	 */
-	for (i = 0; modname[i] != '\0'; i++) {
-		if (modname[i] == '-')
-			modname[i] = '_';
-	}
-
-	/* pass it to the kernel */
-	ret = delete_module(modname, O_NONBLOCK | O_EXCL);
-	if (ret != 0) {
-		fprintf(stderr, "rmmod: delete_module '%s' failed (errno %d)\n",
-						modname, errno);
-		return -1;
-	}
-
-	return 0;
-}
-
diff --git a/toolbox/rotatefb.c b/toolbox/rotatefb.c
deleted file mode 100644
index 2ff4127..0000000
--- a/toolbox/rotatefb.c
+++ /dev/null
@@ -1,71 +0,0 @@
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/mman.h>
-#include <fcntl.h>
-#include <string.h>
-#include <termios.h>
-#include <unistd.h>
-#include <errno.h>
-#include <linux/fb.h>
-
-
-int rotatefb_main(int argc, char *argv[])
-{
-    int c;
-    char *fbdev = "/dev/graphics/fb0";
-    int rotation = 0;
-    int fd;
-    int res;
-    struct fb_var_screeninfo fbinfo;
-
-    do {
-        c = getopt(argc, argv, "d:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'd':
-            fbdev = optarg;
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-
-    if(optind + 1 != argc) {
-        fprintf(stderr, "%s: specify rotation\n", argv[0]);
-        exit(1);
-    }
-    rotation = atoi(argv[optind]);
-
-    fd = open(fbdev, O_RDWR);
-    if(fd < 0) {
-        fprintf(stderr, "cannot open %s\n", fbdev);
-        return 1;
-    }
-
-    res = ioctl(fd, FBIOGET_VSCREENINFO, &fbinfo);
-    if(res < 0) {
-        fprintf(stderr, "failed to get fbinfo: %s\n", strerror(errno));
-        return 1;
-    }
-    if((fbinfo.rotate ^ rotation) & 1) {
-        unsigned int xres = fbinfo.yres;
-        fbinfo.yres = fbinfo.xres;
-        fbinfo.xres = xres;
-        fbinfo.xres_virtual = fbinfo.xres;
-        fbinfo.yres_virtual = fbinfo.yres * 2;
-        if(fbinfo.yoffset == xres)
-            fbinfo.yoffset = fbinfo.yres;
-    }
-    fbinfo.rotate = rotation; 
-    res = ioctl(fd, FBIOPUT_VSCREENINFO, &fbinfo);
-    if(res < 0) {
-        fprintf(stderr, "failed to set fbinfo: %s\n", strerror(errno));
-        return 1;
-    }
-
-    return 0;
-}
diff --git a/toolbox/sendevent.c b/toolbox/sendevent.c
index 9b813f6..4d0ca17 100644
--- a/toolbox/sendevent.c
+++ b/toolbox/sendevent.c
@@ -1,49 +1,12 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/input.h>
+#include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <stdint.h>
-#include <fcntl.h>
 #include <sys/ioctl.h>
-//#include <linux/input.h> // this does not compile
-#include <errno.h>
-
-
-// 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 */
-
-// end <linux/input.h>
-
-
+#include <unistd.h>
 
 int sendevent_main(int argc, char *argv[])
 {
diff --git a/toolbox/setenforce.c b/toolbox/setenforce.c
deleted file mode 100644
index 444073d..0000000
--- a/toolbox/setenforce.c
+++ /dev/null
@@ -1,44 +0,0 @@
-#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>
-
-static 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/setkey.c b/toolbox/setkey.c
deleted file mode 100644
index 1ff2774..0000000
--- a/toolbox/setkey.c
+++ /dev/null
@@ -1,89 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <string.h>
-#include <linux/kd.h>
-#include <linux/vt.h>
-#include <errno.h>
-
-static void setkey_usage(char *argv[])
-{
-    fprintf(stderr, "%s [-t <table>] [-k <index>] [-v value] [-r] [-h]\n"
-            "  -t <table> Select table\n"
-            "  -k <index> Select key\n"
-            "  -v <value> Set entry\n"
-            "  -r         Read current entry\n"
-            "  -h         Print help\n", argv[0]);
-}
-
-#define TTYDEV	"/dev/tty0"
-
-int setkey_main(int argc, char *argv[])
-{
-    int fd;
-    struct kbentry kbe;
-    int did_something = 0;
-
-    kbe.kb_table = 0;
-    kbe.kb_index = -1;
-    kbe.kb_value = 0;
-
-    fd = open(TTYDEV, O_RDWR | O_SYNC);
-    if (fd < 0) {
-        fprintf(stderr, "open %s: %s\n", TTYDEV, strerror(errno));
-        return 1;
-    }
-
-    do {
-        int c, ret;
-
-        c = getopt(argc, argv, "t:k:v:hr");
-        if (c == EOF)
-            break;
-
-        switch (c) {
-        case 't':
-            kbe.kb_table = strtol(optarg, NULL, 0);
-            break;
-        case 'k':
-            kbe.kb_index = strtol(optarg, NULL, 0);
-            break;
-        case 'v':
-            kbe.kb_value = strtol(optarg, NULL, 0);
-            ret = ioctl(fd, KDSKBENT, &kbe);
-            if (ret < 0) {
-                fprintf(stderr, "KDSKBENT %d %d %d failed: %s\n",
-                        kbe.kb_table, kbe.kb_index, kbe.kb_value,
-                        strerror(errno));
-                return 1;
-            }
-            did_something = 1;
-            break;
-        case 'r':
-            ret = ioctl(fd, KDGKBENT, &kbe);
-            if (ret < 0) {
-                fprintf(stderr, "KDGKBENT %d %d  failed: %s\n",
-                        kbe.kb_table, kbe.kb_index, strerror(errno));
-                return 1;
-            }
-            printf("0x%x 0x%x 0x%x\n",
-                   kbe.kb_table, kbe.kb_index, kbe.kb_value);
-            did_something = 1;
-            break;
-        case 'h':
-            setkey_usage(argv);
-            return 1;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            return 1;
-        }
-    } while (1);
-
-    if(optind != argc || !did_something) {
-        setkey_usage(argv);
-        return 1;
-    }
-
-    return 0;
-}
diff --git a/toolbox/smd.c b/toolbox/smd.c
index 91e495c..343dea7 100644
--- a/toolbox/smd.c
+++ b/toolbox/smd.c
@@ -3,6 +3,7 @@
 #include <string.h>
 #include <fcntl.h>
 #include <errno.h>
+#include <unistd.h>
 
 int smd_main(int argc, char **argv)
 {
diff --git a/toolbox/swapoff.c b/toolbox/swapoff.c
deleted file mode 100644
index d8f6a00..0000000
--- a/toolbox/swapoff.c
+++ /dev/null
@@ -1,20 +0,0 @@
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/swap.h>
-
-int swapoff_main(int argc, char **argv)
-{
-    int err = 0;
-
-    if (argc != 2) {
-        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
-        return -EINVAL;
-    }
-
-    err = swapoff(argv[1]);
-    if (err) {
-        fprintf(stderr, "swapoff failed for %s\n", argv[1]);
-    }
-
-    return err;
-}
diff --git a/toolbox/swapon.c b/toolbox/swapon.c
deleted file mode 100644
index 150701a..0000000
--- a/toolbox/swapon.c
+++ /dev/null
@@ -1,66 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <getopt.h>
-#include <sys/swap.h>
-
-static void usage(char *name)
-{
-    fprintf(stderr, "Usage: %s [-p prio] <filename>\n"
-        "        prio must be between 0 and %d\n", name, SWAP_FLAG_PRIO_MASK);
-}
-
-static int parse_prio(char *prio_str)
-{
-    unsigned long p = strtoul(prio_str, NULL, 10);
-
-    return (p > SWAP_FLAG_PRIO_MASK)? -1 : (int)p;
-}
-
-int swapon_main(int argc, char **argv)
-{
-    int err = 0;
-    int flags = 0;
-    int prio;
-
-    opterr = 0;
-    do {
-        int c = getopt(argc, argv, "hp:");
-        if (c == -1)
-            break;
-
-        switch (c) {
-            case 'p':
-                if (optarg != NULL)
-                    prio = parse_prio(optarg);
-                else
-                    prio = -1;
-
-                if (prio < 0) {
-                    usage(argv[0]);
-                    return -EINVAL;
-                }
-                flags |= SWAP_FLAG_PREFER;
-                flags |= (prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK;
-                break;
-            case 'h':
-                usage(argv[0]);
-                return 0;
-            case '?':
-                fprintf(stderr, "unknown option: %c\n", optopt);
-                return -EINVAL;
-        }
-    } while (1);
-
-    if (optind != argc - 1) {
-        usage(argv[0]);
-        return -EINVAL;
-    }
-
-    err = swapon(argv[argc - 1], flags);
-    if (err) {
-        fprintf(stderr, "swapon failed for %s\n", argv[argc - 1]);
-    }
-
-    return err;
-}
diff --git a/toolbox/syren.c b/toolbox/syren.c
deleted file mode 100644
index 47c2460..0000000
--- a/toolbox/syren.c
+++ /dev/null
@@ -1,158 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <malloc.h>
-
-/* ioctl crap */
-#define SYREN_RD		101
-#define SYREN_WR		102
-#define SYREN_OLD_RD	108
-#define SYREN_OLD_WR	109
-
-struct syren_io_args {
-	unsigned long	page;
-	unsigned long	addr;
-	unsigned long	value;
-};
-
-typedef struct {
-	u_char			page;
-	u_char			addr;
-	const char		*name;
-} syren_reg;
-
-static syren_reg registers[] = {
-	{ 0, 0x04, "TOGBR1" },
-	{ 0, 0x05, "TOGBR2" },
-	{ 0, 0x06, "VBDCTRL" },
-	{ 1, 0x07, "VBUCTRL" },
-	{ 1, 0x08, "VBCTRL" },
-	{ 1, 0x09, "PWDNRG" },
-	{ 1, 0x0a, "VBPOP" },
-	{ 1, 0x0b, "VBCTRL2" },
-	{ 1, 0x0f, "VAUDCTRL" },
-	{ 1, 0x10, "VAUSCTRL" },
-	{ 1, 0x11, "VAUOCTRL" },
-	{ 1, 0x12, "VAUDPLL" },
-	{ 1, 0x17, "VRPCSIMR" },
-	{ 0, 0, 0 }
-};
-
-static syren_reg *find_reg(const char *name)
-{
-	int i;
-
-	for (i = 0; registers[i].name != 0; i++) {
-		if (!strcasecmp(registers[i].name, name))
-			return &registers[i];
-	}
-
-	return NULL;
-}
-
-static int usage(void)
-{
-	fprintf(stderr, "usage: syren [r/w] [REGNAME | page:addr] (value)\n");
-	return 1;
-}
-
-int
-syren_main(int argc, char **argv)
-{
-	int cmd = -1;
-	syren_reg *r;
-	struct syren_io_args sio;
-	char name[32];
-	int fd;
-
-	if (argc < 3) {
-		return usage();
-	}
-
-	switch(argv[1][0]) {
-	case 'r':
-		cmd = SYREN_RD;
-		break;
-	case 'w':
-		cmd = SYREN_WR;
-		break;
-	case 'R':
-		cmd = SYREN_OLD_RD;
-		break;
-	case 'W':
-		cmd = SYREN_OLD_WR;
-		break;
-	default:
-		return usage();
-	}
-
-	if (cmd == SYREN_WR || cmd == SYREN_OLD_WR) {
-		if (argc < 4)
-			return usage();
-		sio.value = strtoul(argv[3], 0, 0);
-	}
-
-	fd = open("/dev/eac", O_RDONLY);
-	if (fd < 0) {
-		fprintf(stderr, "can't open /dev/eac\n");
-		return 1;
-	}
-
-	if (strcasecmp(argv[2], "all") == 0) {
-		int i;
-		if (cmd != SYREN_RD && cmd != SYREN_OLD_RD) {
-			fprintf(stderr, "can only read all registers\n");
-			return 1;
-		}
-
-		for (i = 0; registers[i].name; i++) {
-			sio.page = registers[i].page;
-			sio.addr = registers[i].addr;
-			if (ioctl(fd, cmd, &sio) < 0) {
-				fprintf(stderr, "%s: error\n", registers[i].name);
-			} else {
-				fprintf(stderr, "%s: %04x\n", registers[i].name, sio.value);
-			}
-		}
-
-		close(fd);
-		return 0;
-	}
-
-	r = find_reg(argv[2]);
-	if (r == NULL) {
-		if(strlen(argv[2]) >= sizeof(name)){
-			fprintf(stderr, "REGNAME too long\n");
-			return 0;
-		}
-		strlcpy(name, argv[2], sizeof(name));
-		char *addr_str = strchr(argv[2], ':');
-		if (addr_str == NULL)
-			return usage();
-		*addr_str++ = 0;
-		sio.page = strtoul(argv[2], 0, 0);
-		sio.addr = strtoul(addr_str, 0, 0);
-	} else {
-		strlcpy(name, r->name, sizeof(name));
-		sio.page = r->page;
-		sio.addr = r->addr;
-	}
-
-	if (ioctl(fd, cmd, &sio) < 0) {
-		fprintf(stderr, "ioctl(%d) failed\n", cmd);
-		return 1;
-	}
-
-	if (cmd == SYREN_RD || cmd == SYREN_OLD_RD) {
-		printf("%s: %04x\n", name, sio.value);
-	} else {
-		printf("wrote %04x to %s\n", sio.value, name);
-	}
-
-	close(fd);
-
-	return 0;
-}
-
diff --git a/toolbox/touch.c b/toolbox/touch.c
index 52ddf2a..980f0d3 100644
--- a/toolbox/touch.c
+++ b/toolbox/touch.c
@@ -6,6 +6,7 @@
 #include <stdlib.h>
 #include <fcntl.h>
 #include <time.h>
+#include <unistd.h>
 
 static void usage(void)
 {
diff --git a/toolbox/upstream-netbsd/bin/cat/cat.c b/toolbox/upstream-netbsd/bin/cat/cat.c
deleted file mode 100644
index cca8cf5..0000000
--- a/toolbox/upstream-netbsd/bin/cat/cat.c
+++ /dev/null
@@ -1,329 +0,0 @@
-/* $NetBSD: cat.c,v 1.54 2013/12/08 08:32:13 spz Exp $	*/
-
-/*
- * Copyright (c) 1989, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Kevin Fall.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#if HAVE_NBTOOL_CONFIG_H
-#include "nbtool_config.h"
-#endif
-
-#include <sys/cdefs.h>
-#if !defined(lint)
-__COPYRIGHT(
-"@(#) Copyright (c) 1989, 1993\
- The Regents of the University of California.  All rights reserved.");
-#if 0
-static char sccsid[] = "@(#)cat.c	8.2 (Berkeley) 4/27/95";
-#else
-__RCSID("$NetBSD: cat.c,v 1.54 2013/12/08 08:32:13 spz Exp $");
-#endif
-#endif /* not lint */
-
-#include <sys/param.h>
-#include <sys/stat.h>
-
-#include <ctype.h>
-#include <err.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <locale.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-static int bflag, eflag, fflag, lflag, nflag, sflag, tflag, vflag;
-static size_t bsize;
-static int rval;
-static const char *filename;
-
-void cook_args(char *argv[]);
-void cook_buf(FILE *);
-void raw_args(char *argv[]);
-void raw_cat(int);
-
-int
-main(int argc, char *argv[])
-{
-	int ch;
-	struct flock stdout_lock;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	while ((ch = getopt(argc, argv, "B:beflnstuv")) != -1)
-		switch (ch) {
-		case 'B':
-			bsize = (size_t)strtol(optarg, NULL, 0);
-			break;
-		case 'b':
-			bflag = nflag = 1;	/* -b implies -n */
-			break;
-		case 'e':
-			eflag = vflag = 1;	/* -e implies -v */
-			break;
-		case 'f':
-			fflag = 1;
-			break;
-		case 'l':
-			lflag = 1;
-			break;
-		case 'n':
-			nflag = 1;
-			break;
-		case 's':
-			sflag = 1;
-			break;
-		case 't':
-			tflag = vflag = 1;	/* -t implies -v */
-			break;
-		case 'u':
-			setbuf(stdout, NULL);
-			break;
-		case 'v':
-			vflag = 1;
-			break;
-		default:
-		case '?':
-			(void)fprintf(stderr,
-			    "Usage: %s [-beflnstuv] [-B bsize] [-] "
-			    "[file ...]\n", getprogname());
-			return EXIT_FAILURE;
-		}
-	argv += optind;
-
-	if (lflag) {
-		stdout_lock.l_len = 0;
-		stdout_lock.l_start = 0;
-		stdout_lock.l_type = F_WRLCK;
-		stdout_lock.l_whence = SEEK_SET;
-		if (fcntl(STDOUT_FILENO, F_SETLKW, &stdout_lock) == -1)
-			err(EXIT_FAILURE, "stdout");
-	}
-
-	if (bflag || eflag || nflag || sflag || tflag || vflag)
-		cook_args(argv);
-	else
-		raw_args(argv);
-	if (fclose(stdout))
-		err(EXIT_FAILURE, "stdout");
-	return rval;
-}
-
-void
-cook_args(char **argv)
-{
-	FILE *fp;
-
-	fp = stdin;
-	filename = "stdin";
-	do {
-		if (*argv) {
-			if (!strcmp(*argv, "-"))
-				fp = stdin;
-			else if ((fp = fopen(*argv,
-			    fflag ? "rf" : "r")) == NULL) {
-				warn("%s", *argv);
-				rval = EXIT_FAILURE;
-				++argv;
-				continue;
-			}
-			filename = *argv++;
-		}
-		cook_buf(fp);
-		if (fp != stdin)
-			(void)fclose(fp);
-		else
-			clearerr(fp);
-	} while (*argv);
-}
-
-void
-cook_buf(FILE *fp)
-{
-	int ch, gobble, line, prev;
-
-	line = gobble = 0;
-	for (prev = '\n'; (ch = getc(fp)) != EOF; prev = ch) {
-		if (prev == '\n') {
-			if (ch == '\n') {
-				if (sflag) {
-					if (!gobble && nflag && !bflag)
-						(void)fprintf(stdout,
-							"%6d\t\n", ++line);
-					else if (!gobble && putchar(ch) == EOF)
-						break;
-					gobble = 1;
-					continue;
-				}
-				if (nflag) {
-					if (!bflag) {
-						(void)fprintf(stdout,
-						    "%6d\t", ++line);
-						if (ferror(stdout))
-							break;
-					} else if (eflag) {
-						(void)fprintf(stdout,
-						    "%6s\t", "");
-						if (ferror(stdout))
-							break;
-					}
-				}
-			} else if (nflag) {
-				(void)fprintf(stdout, "%6d\t", ++line);
-				if (ferror(stdout))
-					break;
-			}
-		}
-		gobble = 0;
-		if (ch == '\n') {
-			if (eflag)
-				if (putchar('$') == EOF)
-					break;
-		} else if (ch == '\t') {
-			if (tflag) {
-				if (putchar('^') == EOF || putchar('I') == EOF)
-					break;
-				continue;
-			}
-		} else if (vflag) {
-			if (!isascii(ch)) {
-				if (putchar('M') == EOF || putchar('-') == EOF)
-					break;
-				ch = toascii(ch);
-			}
-			if (iscntrl(ch)) {
-				if (putchar('^') == EOF ||
-				    putchar(ch == '\177' ? '?' :
-				    ch | 0100) == EOF)
-					break;
-				continue;
-			}
-		}
-		if (putchar(ch) == EOF)
-			break;
-	}
-	if (ferror(fp)) {
-		warn("%s", filename);
-		rval = EXIT_FAILURE;
-		clearerr(fp);
-	}
-	if (ferror(stdout))
-		err(EXIT_FAILURE, "stdout");
-}
-
-void
-raw_args(char **argv)
-{
-	int fd;
-
-	fd = fileno(stdin);
-	filename = "stdin";
-	do {
-		if (*argv) {
-			if (!strcmp(*argv, "-")) {
-				fd = fileno(stdin);
-				if (fd < 0)
-					goto skip;
-			} else if (fflag) {
-				struct stat st;
-				fd = open(*argv, O_RDONLY|O_NONBLOCK, 0);
-				if (fd < 0)
-					goto skip;
-
-				if (fstat(fd, &st) == -1) {
-					close(fd);
-					goto skip;
-				}
-				if (!S_ISREG(st.st_mode)) {
-					close(fd);
-					warnx("%s: not a regular file", *argv);
-					goto skipnomsg;
-				}
-			}
-			else if ((fd = open(*argv, O_RDONLY, 0)) < 0) {
-skip:
-				warn("%s", *argv);
-skipnomsg:
-				rval = EXIT_FAILURE;
-				++argv;
-				continue;
-			}
-			filename = *argv++;
-		} else if (fd < 0) {
-			err(EXIT_FAILURE, "stdin");
-		}
-		raw_cat(fd);
-		if (fd != fileno(stdin))
-			(void)close(fd);
-	} while (*argv);
-}
-
-void
-raw_cat(int rfd)
-{
-	static char *buf;
-	static char fb_buf[BUFSIZ];
-
-	ssize_t nr, nw, off;
-	int wfd;
-
-	wfd = fileno(stdout);
-	if (wfd < 0)
-		err(EXIT_FAILURE, "stdout");
-	if (buf == NULL) {
-		struct stat sbuf;
-
-		if (bsize == 0) {
-			if (fstat(wfd, &sbuf) == 0 && sbuf.st_blksize > 0 &&
-			    (size_t)sbuf.st_blksize > sizeof(fb_buf))
-				bsize = sbuf.st_blksize;
-		}
-		if (bsize > sizeof(fb_buf)) {
-			buf = malloc(bsize);
-			if (buf == NULL)
-				warnx("malloc, using %zu buffer", bsize);
-		}
-		if (buf == NULL) {
-			bsize = sizeof(fb_buf);
-			buf = fb_buf;
-		}
-	}
-	while ((nr = read(rfd, buf, bsize)) > 0)
-		for (off = 0; nr; nr -= nw, off += nw)
-			if ((nw = write(wfd, buf + off, (size_t)nr)) < 0)
-				err(EXIT_FAILURE, "stdout");
-	if (nr < 0) {
-		warn("%s", filename);
-		rval = EXIT_FAILURE;
-	}
-}
diff --git a/toolbox/upstream-netbsd/bin/cp/cp.c b/toolbox/upstream-netbsd/bin/cp/cp.c
deleted file mode 100644
index 4bbe1b7..0000000
--- a/toolbox/upstream-netbsd/bin/cp/cp.c
+++ /dev/null
@@ -1,548 +0,0 @@
-/* $NetBSD: cp.c,v 1.58 2012/01/04 15:58:37 christos Exp $ */
-
-/*
- * Copyright (c) 1988, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * David Hitz of Auspex Systems Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT(
-"@(#) Copyright (c) 1988, 1993, 1994\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)cp.c	8.5 (Berkeley) 4/29/95";
-#else
-__RCSID("$NetBSD: cp.c,v 1.58 2012/01/04 15:58:37 christos Exp $");
-#endif
-#endif /* not lint */
-
-/*
- * Cp copies source files to target files.
- * 
- * The global PATH_T structure "to" always contains the path to the
- * current target file.  Since fts(3) does not change directories,
- * this path can be either absolute or dot-relative.
- * 
- * The basic algorithm is to initialize "to" and use fts(3) to traverse
- * the file hierarchy rooted in the argument list.  A trivial case is the
- * case of 'cp file1 file2'.  The more interesting case is the case of
- * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
- * path (relative to the root of the traversal) is appended to dir (stored
- * in "to") to form the final target path.
- */
-
-#include <sys/param.h>
-#include <sys/stat.h>
-
-#include <assert.h>
-#include <err.h>
-#include <errno.h>
-#include <fts.h>
-#include <locale.h>
-#include <signal.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "extern.h"
-
-#define	STRIP_TRAILING_SLASH(p) {					\
-        while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
-                *--(p).p_end = '\0';					\
-}
-
-static char empty[] = "";
-PATH_T to = { .p_end = to.p_path, .target_end = empty  };
-
-uid_t myuid;
-int Hflag, Lflag, Rflag, Pflag, fflag, iflag, lflag, pflag, rflag, vflag, Nflag;
-mode_t myumask;
-sig_atomic_t pinfo;
-
-enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
-
-static int copy(char *[], enum op, int);
-
-static void
-progress(int sig __unused)
-{
-
-	pinfo++;
-}
-
-int
-main(int argc, char *argv[])
-{
-	struct stat to_stat, tmp_stat;
-	enum op type;
-	int ch, fts_options, r, have_trailing_slash;
-	char *target, **src;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	Hflag = Lflag = Pflag = Rflag = 0;
-	while ((ch = getopt(argc, argv, "HLNPRfailprv")) != -1) 
-		switch (ch) {
-		case 'H':
-			Hflag = 1;
-			Lflag = Pflag = 0;
-			break;
-		case 'L':
-			Lflag = 1;
-			Hflag = Pflag = 0;
-			break;
-		case 'N':
-			Nflag = 1;
-			break;
-		case 'P':
-			Pflag = 1;
-			Hflag = Lflag = 0;
-			break;
-		case 'R':
-			Rflag = 1;
-			break;
-		case 'a':
-			Pflag = 1;
-			pflag = 1;
-			Rflag = 1;
-			Hflag = Lflag = 0;
-			break;
-		case 'f':
-			fflag = 1;
-			iflag = 0;
-			break;
-		case 'i':
-			iflag = isatty(fileno(stdin));
-			fflag = 0;
-			break;
-		case 'l':
-			lflag = 1;
-			break;
-		case 'p':
-			pflag = 1;
-			break;
-		case 'r':
-			rflag = 1;
-			break;
-		case 'v':
-			vflag = 1;
-			break;
-		case '?':
-		default:
-			usage();
-			/* NOTREACHED */
-		}
-	argc -= optind;
-	argv += optind;
-
-	if (argc < 2)
-		usage();
-
-	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
-	if (rflag) {
-		if (Rflag) {
-			errx(EXIT_FAILURE,
-		    "the -R and -r options may not be specified together.");
-			/* NOTREACHED */
-		}
-		if (Hflag || Lflag || Pflag) {
-			errx(EXIT_FAILURE,
-	"the -H, -L, and -P options may not be specified with the -r option.");
-			/* NOTREACHED */
-		}
-		fts_options &= ~FTS_PHYSICAL;
-		fts_options |= FTS_LOGICAL;
-	}
-
-	if (Rflag) {
-		if (Hflag)
-			fts_options |= FTS_COMFOLLOW;
-		if (Lflag) {
-			fts_options &= ~FTS_PHYSICAL;
-			fts_options |= FTS_LOGICAL;
-		}
-	} else if (!Pflag) {
-		fts_options &= ~FTS_PHYSICAL;
-		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
-	}
-
-	myuid = getuid();
-
-	/* Copy the umask for explicit mode setting. */
-	myumask = umask(0);
-	(void)umask(myumask);
-
-	/* Save the target base in "to". */
-	target = argv[--argc];
-	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
-		errx(EXIT_FAILURE, "%s: name too long", target);
-	to.p_end = to.p_path + strlen(to.p_path);
-	have_trailing_slash = (to.p_end[-1] == '/');
-	if (have_trailing_slash)
-		STRIP_TRAILING_SLASH(to);
-	to.target_end = to.p_end;
-
-	/* Set end of argument list for fts(3). */
-	argv[argc] = NULL;     
-	
-	(void)signal(SIGINFO, progress);
-	
-	/*
-	 * Cp has two distinct cases:
-	 *
-	 * cp [-R] source target
-	 * cp [-R] source1 ... sourceN directory
-	 *
-	 * In both cases, source can be either a file or a directory.
-	 *
-	 * In (1), the target becomes a copy of the source. That is, if the
-	 * source is a file, the target will be a file, and likewise for
-	 * directories.
-	 *
-	 * In (2), the real target is not directory, but "directory/source".
-	 */
-	if (Pflag)
-		r = lstat(to.p_path, &to_stat);
-	else
-		r = stat(to.p_path, &to_stat);
-	if (r == -1 && errno != ENOENT) {
-		err(EXIT_FAILURE, "%s", to.p_path);
-		/* NOTREACHED */
-	}
-	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
-		/*
-		 * Case (1).  Target is not a directory.
-		 */ 
-		if (argc > 1)
-			usage();
-		/*
-		 * Need to detect the case:
-		 *	cp -R dir foo
-		 * Where dir is a directory and foo does not exist, where
-		 * we want pathname concatenations turned on but not for
-		 * the initial mkdir().
-		 */
-		if (r == -1) {
-			if (rflag || (Rflag && (Lflag || Hflag)))
-				r = stat(*argv, &tmp_stat);
-			else
-				r = lstat(*argv, &tmp_stat);
-			if (r == -1) {
-				err(EXIT_FAILURE, "%s", *argv);
-				/* NOTREACHED */
-			}
-			
-			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
-				type = DIR_TO_DNE;
-			else
-				type = FILE_TO_FILE;
-		} else
-			type = FILE_TO_FILE;
-
-		if (have_trailing_slash && type == FILE_TO_FILE) {
-			if (r == -1)
-				errx(1, "directory %s does not exist",
-				     to.p_path);
-			else
-				errx(1, "%s is not a directory", to.p_path);
-		}
-	} else {
-		/*
-		 * Case (2).  Target is a directory.
-		 */
-		type = FILE_TO_DIR;
-	}
-
-	/*
-	 * make "cp -rp src/ dst" behave like "cp -rp src dst" not
-	 * like "cp -rp src/. dst"
-	 */
-	for (src = argv; *src; src++) {
-		size_t len = strlen(*src);
-		while (len-- > 1 && (*src)[len] == '/')
-			(*src)[len] = '\0';
-	}
-
-	exit(copy(argv, type, fts_options));
-	/* NOTREACHED */
-}
-
-static int dnestack[MAXPATHLEN]; /* unlikely we'll have more nested dirs */
-static ssize_t dnesp;
-static void
-pushdne(int dne)
-{
-
-	dnestack[dnesp++] = dne;
-	assert(dnesp < MAXPATHLEN);
-}
-
-static int
-popdne(void)
-{
-	int rv;
-
-	rv = dnestack[--dnesp];
-	assert(dnesp >= 0);
-	return rv;
-}
-
-static int
-copy(char *argv[], enum op type, int fts_options)
-{
-	struct stat to_stat;
-	FTS *ftsp;
-	FTSENT *curr;
-	int base, dne, sval;
-	int this_failed, any_failed;
-	size_t nlen;
-	char *p, *target_mid;
-
-	base = 0;	/* XXX gcc -Wuninitialized (see comment below) */
-
-	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
-		err(EXIT_FAILURE, "%s", argv[0]);
-		/* NOTREACHED */
-	for (any_failed = 0; (curr = fts_read(ftsp)) != NULL;) {
-		this_failed = 0;
-		switch (curr->fts_info) {
-		case FTS_NS:
-		case FTS_DNR:
-		case FTS_ERR:
-			warnx("%s: %s", curr->fts_path,
-					strerror(curr->fts_errno));
-			this_failed = any_failed = 1;
-			continue;
-		case FTS_DC:			/* Warn, continue. */
-			warnx("%s: directory causes a cycle", curr->fts_path);
-			this_failed = any_failed = 1;
-			continue;
-		}
-
-		/*
-		 * If we are in case (2) or (3) above, we need to append the 
-                 * source name to the target name.  
-                 */
-		if (type != FILE_TO_FILE) {
-			if ((curr->fts_namelen +
-			    to.target_end - to.p_path + 1) > MAXPATHLEN) {
-				warnx("%s/%s: name too long (not copied)",
-						to.p_path, curr->fts_name);
-				this_failed = any_failed = 1;
-				continue;
-			}
-
-			/*
-			 * Need to remember the roots of traversals to create
-			 * correct pathnames.  If there's a directory being
-			 * copied to a non-existent directory, e.g.
-			 *	cp -R a/dir noexist
-			 * the resulting path name should be noexist/foo, not
-			 * noexist/dir/foo (where foo is a file in dir), which
-			 * is the case where the target exists.
-			 *
-			 * Also, check for "..".  This is for correct path
-			 * concatentation for paths ending in "..", e.g.
-			 *	cp -R .. /tmp
-			 * Paths ending in ".." are changed to ".".  This is
-			 * tricky, but seems the easiest way to fix the problem.
-			 *
-			 * XXX
-			 * Since the first level MUST be FTS_ROOTLEVEL, base
-			 * is always initialized.
-			 */
-			if (curr->fts_level == FTS_ROOTLEVEL) {
-				if (type != DIR_TO_DNE) {
-					p = strrchr(curr->fts_path, '/');
-					base = (p == NULL) ? 0 : 
-					    (int)(p - curr->fts_path + 1);
-
-					if (!strcmp(&curr->fts_path[base], 
-					    ".."))
-						base += 1;
-				} else
-					base = curr->fts_pathlen;
-			}
-
-			p = &curr->fts_path[base];
-			nlen = curr->fts_pathlen - base;
-			target_mid = to.target_end;
-			if (*p != '/' && target_mid[-1] != '/')
-				*target_mid++ = '/';
-			*target_mid = 0;
-
-			if (target_mid - to.p_path + nlen >= PATH_MAX) {
-				warnx("%s%s: name too long (not copied)",
-				    to.p_path, p);
-				this_failed = any_failed = 1;
-				continue;
-			}
-			(void)strncat(target_mid, p, nlen);
-			to.p_end = target_mid + nlen;
-			*to.p_end = 0;
-			STRIP_TRAILING_SLASH(to);
-		}
-
-		sval = Pflag ? lstat(to.p_path, &to_stat) : stat(to.p_path, &to_stat);
-		/* Not an error but need to remember it happened */
-		if (sval == -1)
-			dne = 1;
-		else {
-			if (to_stat.st_dev == curr->fts_statp->st_dev &&
-			    to_stat.st_ino == curr->fts_statp->st_ino) {
-				warnx("%s and %s are identical (not copied).",
-				    to.p_path, curr->fts_path);
-				this_failed = any_failed = 1;
-				if (S_ISDIR(curr->fts_statp->st_mode))
-					(void)fts_set(ftsp, curr, FTS_SKIP);
-				continue;
-			}
-			if (!S_ISDIR(curr->fts_statp->st_mode) &&
-			    S_ISDIR(to_stat.st_mode)) {
-		warnx("cannot overwrite directory %s with non-directory %s",
-				    to.p_path, curr->fts_path);
-				this_failed = any_failed = 1;
-				continue;
-			}
-			dne = 0;
-		}
-
-		switch (curr->fts_statp->st_mode & S_IFMT) {
-		case S_IFLNK:
-			/* Catch special case of a non dangling symlink */
-			if((fts_options & FTS_LOGICAL) ||
-			   ((fts_options & FTS_COMFOLLOW) && curr->fts_level == 0)) {
-				if (copy_file(curr, dne))
-					this_failed = any_failed = 1;
-			} else {	
-				if (copy_link(curr, !dne))
-					this_failed = any_failed = 1;
-			}
-			break;
-		case S_IFDIR:
-			if (!Rflag && !rflag) {
-				if (curr->fts_info == FTS_D)
-					warnx("%s is a directory (not copied).",
-					    curr->fts_path);
-				(void)fts_set(ftsp, curr, FTS_SKIP);
-				this_failed = any_failed = 1;
-				break;
-			}
-
-                        /*
-                         * Directories get noticed twice:
-                         *  In the first pass, create it if needed.
-                         *  In the second pass, after the children have been copied, set the permissions.
-                         */
-			if (curr->fts_info == FTS_D) /* First pass */
-			{
-				/*
-				 * If the directory doesn't exist, create the new
-				 * one with the from file mode plus owner RWX bits,
-				 * modified by the umask.  Trade-off between being
-				 * able to write the directory (if from directory is
-				 * 555) and not causing a permissions race.  If the
-				 * umask blocks owner writes, we fail..
-				 */
-				pushdne(dne);
-				if (dne) {
-					if (mkdir(to.p_path, 
-					    curr->fts_statp->st_mode | S_IRWXU) < 0)
-						err(EXIT_FAILURE, "%s",
-						    to.p_path);
-						/* NOTREACHED */
-				} else if (!S_ISDIR(to_stat.st_mode)) {
-					errno = ENOTDIR;
-					err(EXIT_FAILURE, "%s",
-						to.p_path);
-					/* NOTREACHED */
-				}
-			}
-			else if (curr->fts_info == FTS_DP) /* Second pass */
-			{
-	                        /*
-				 * If not -p and directory didn't exist, set it to be
-				 * the same as the from directory, umodified by the 
-                        	 * umask; arguably wrong, but it's been that way 
-                        	 * forever.
-				 */
-				if (pflag && setfile(curr->fts_statp, 0))
-					this_failed = any_failed = 1;
-				else if ((dne = popdne()))
-					(void)chmod(to.p_path, 
-					    curr->fts_statp->st_mode);
-			}
-			else
-			{
-				warnx("directory %s encountered when not expected.",
-				    curr->fts_path);
-				this_failed = any_failed = 1;
-				break;
-			}
-
-			break;
-		case S_IFBLK:
-		case S_IFCHR:
-			if (Rflag) {
-				if (copy_special(curr->fts_statp, !dne))
-					this_failed = any_failed = 1;
-			} else
-				if (copy_file(curr, dne))
-					this_failed = any_failed = 1;
-			break;
-		case S_IFIFO:
-			if (Rflag) {
-				if (copy_fifo(curr->fts_statp, !dne))
-					this_failed = any_failed = 1;
-			} else 
-				if (copy_file(curr, dne))
-					this_failed = any_failed = 1;
-			break;
-		default:
-			if (copy_file(curr, dne))
-				this_failed = any_failed = 1;
-			break;
-		}
-		if (vflag && !this_failed)
-			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
-	}
-	if (errno) {
-		err(EXIT_FAILURE, "fts_read");
-		/* NOTREACHED */
-	}
-	(void)fts_close(ftsp);
-	return (any_failed);
-}
diff --git a/toolbox/upstream-netbsd/bin/cp/extern.h b/toolbox/upstream-netbsd/bin/cp/extern.h
deleted file mode 100644
index e393844..0000000
--- a/toolbox/upstream-netbsd/bin/cp/extern.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/* $NetBSD: extern.h,v 1.17 2012/01/04 15:58:37 christos Exp $ */
-
-/*-
- * Copyright (c) 1991, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- *
- *	@(#)extern.h	8.2 (Berkeley) 4/1/94
- */
-
-#ifndef _EXTERN_H_
-#define _EXTERN_H_
-
-typedef struct {
-	char *p_end;			/* pointer to NULL at end of path */
-	char *target_end;		/* pointer to end of target base */
-	char p_path[MAXPATHLEN + 1];	/* pointer to the start of a path */
-} PATH_T;
-
-extern PATH_T to;
-extern uid_t myuid;
-extern int Rflag, rflag, Hflag, Lflag, Pflag, fflag, iflag, lflag, pflag, Nflag;
-extern mode_t myumask;
-extern sig_atomic_t pinfo;
-
-#include <sys/cdefs.h>
-
-__BEGIN_DECLS
-int	copy_fifo(struct stat *, int);
-int	copy_file(FTSENT *, int);
-int	copy_link(FTSENT *, int);
-int	copy_special(struct stat *, int);
-int	set_utimes(const char *, struct stat *);
-int	setfile(struct stat *, int);
-void	usage(void) __attribute__((__noreturn__));
-__END_DECLS
-
-#endif /* !_EXTERN_H_ */
diff --git a/toolbox/upstream-netbsd/bin/cp/utils.c b/toolbox/upstream-netbsd/bin/cp/utils.c
deleted file mode 100644
index d8f900a..0000000
--- a/toolbox/upstream-netbsd/bin/cp/utils.c
+++ /dev/null
@@ -1,444 +0,0 @@
-/* $NetBSD: utils.c,v 1.42 2013/12/11 06:00:11 dholland Exp $ */
-
-/*-
- * Copyright (c) 1991, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
-#else
-__RCSID("$NetBSD: utils.c,v 1.42 2013/12/11 06:00:11 dholland Exp $");
-#endif
-#endif /* not lint */
-
-#include <sys/mman.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/extattr.h>
-
-#include <err.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <fts.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "extern.h"
-
-#define	MMAP_MAX_SIZE	(8 * 1048576)
-#define	MMAP_MAX_WRITE	(64 * 1024)
-
-int
-set_utimes(const char *file, struct stat *fs)
-{
-    static struct timeval tv[2];
-
-#ifdef __ANDROID__
-    tv[0].tv_sec = fs->st_atime;
-    tv[0].tv_usec = 0;
-    tv[1].tv_sec = fs->st_mtime;
-    tv[1].tv_usec = 0;
-
-    if (utimes(file, tv)) {
-        warn("utimes: %s", file);
-        return 1;
-    }
-#else
-    TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
-    TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
-
-    if (lutimes(file, tv)) {
-	warn("lutimes: %s", file);
-	return (1);
-    }
-#endif
-    return (0);
-}
-
-struct finfo {
-	const char *from;
-	const char *to;
-	size_t size;
-};
-
-static void
-progress(const struct finfo *fi, size_t written)
-{
-	int pcent = (int)((100.0 * written) / fi->size);
-
-	pinfo = 0;
-	(void)fprintf(stderr, "%s => %s %zu/%zu bytes %d%% written\n",
-	    fi->from, fi->to, written, fi->size, pcent);
-}
-
-int
-copy_file(FTSENT *entp, int dne)
-{
-	static char buf[MAXBSIZE];
-	struct stat to_stat, *fs;
-	int ch, checkch, from_fd, rcount, rval, to_fd, tolnk, wcount;
-	char *p;
-	size_t ptotal = 0;
-	
-	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
-		warn("%s", entp->fts_path);
-		return (1);
-	}
-
-	to_fd = -1;
-	fs = entp->fts_statp;
-	tolnk = ((Rflag && !(Lflag || Hflag)) || Pflag);
-
-	/*
-	 * If the file exists and we're interactive, verify with the user.
-	 * If the file DNE, set the mode to be the from file, minus setuid
-	 * bits, modified by the umask; arguably wrong, but it makes copying
-	 * executables work right and it's been that way forever.  (The
-	 * other choice is 666 or'ed with the execute bits on the from file
-	 * modified by the umask.)
-	 */
-	if (!dne) {
-		struct stat sb;
-		int sval;
-
-		if (iflag) {
-			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
-			checkch = ch = getchar();
-			while (ch != '\n' && ch != EOF)
-				ch = getchar();
-			if (checkch != 'y' && checkch != 'Y') {
-				(void)close(from_fd);
-				return (0);
-			}
-		}
-
-		sval = tolnk ?
-			lstat(to.p_path, &sb) : stat(to.p_path, &sb);
-		if (sval == -1) {
-			warn("stat: %s", to.p_path);
-			(void)close(from_fd);
-			return (1);
-		}
-
-		if (!(tolnk && S_ISLNK(sb.st_mode)))
-			to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
-	} else
-		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
-		    fs->st_mode & ~(S_ISUID | S_ISGID));
-
-	if (to_fd == -1 && (fflag || tolnk)) {
-		/*
-		 * attempt to remove existing destination file name and
-		 * create a new file
-		 */
-		(void)unlink(to.p_path);
-		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
-			     fs->st_mode & ~(S_ISUID | S_ISGID));
-	}
-
-	if (to_fd == -1) {
-		warn("%s", to.p_path);
-		(void)close(from_fd);
-		return (1);
-	}
-
-	rval = 0;
-
-	/* if hard linking then simply close the open fds, link and return */
-	if (lflag) {
-		(void)close(from_fd);
-		(void)close(to_fd);
-		(void)unlink(to.p_path);
-		if (link(entp->fts_path, to.p_path)) {
-			warn("%s", to.p_path);
-			return (1);
-		}
-		return (0);
-	}
-
-	/*
-	 * There's no reason to do anything other than close the file
-	 * now if it's empty, so let's not bother.
-	 */
-#ifndef __ANDROID__ // Files in /proc report length 0. mmap will fail but we'll fall back to read.
-	if (fs->st_size > 0) {
-#endif
-		struct finfo fi;
-
-		fi.from = entp->fts_path;
-		fi.to = to.p_path;
-		fi.size = (size_t)fs->st_size;
-
-		/*
-		 * Mmap and write if less than 8M (the limit is so
-		 * we don't totally trash memory on big files).
-		 * This is really a minor hack, but it wins some CPU back.
-		 */
-		bool use_read;
-
-		use_read = true;
-		if (fs->st_size <= MMAP_MAX_SIZE) {
-			size_t fsize = (size_t)fs->st_size;
-			p = mmap(NULL, fsize, PROT_READ, MAP_FILE|MAP_SHARED,
-			    from_fd, (off_t)0);
-			if (p != MAP_FAILED) {
-				size_t remainder;
-
-				use_read = false;
-
-				(void) madvise(p, (size_t)fs->st_size,
-				     MADV_SEQUENTIAL);
-
-				/*
-				 * Write out the data in small chunks to
-				 * avoid locking the output file for a
-				 * long time if the reading the data from
-				 * the source is slow.
-				 */
-				remainder = fsize;
-				do {
-					ssize_t chunk;
-
-					chunk = (remainder > MMAP_MAX_WRITE) ?
-					    MMAP_MAX_WRITE : remainder;
-					if (write(to_fd, &p[fsize - remainder],
-					    chunk) != chunk) {
-						warn("%s", to.p_path);
-						rval = 1;
-						break;
-					}
-					remainder -= chunk;
-					ptotal += chunk;
-					if (pinfo)
-						progress(&fi, ptotal);
-				} while (remainder > 0);
-
-				if (munmap(p, fsize) < 0) {
-					warn("%s", entp->fts_path);
-					rval = 1;
-				}
-			}
-		}
-
-		if (use_read) {
-			while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
-				wcount = write(to_fd, buf, (size_t)rcount);
-				if (rcount != wcount || wcount == -1) {
-					warn("%s", to.p_path);
-					rval = 1;
-					break;
-				}
-				ptotal += wcount;
-				if (pinfo)
-					progress(&fi, ptotal);
-			}
-			if (rcount < 0) {
-				warn("%s", entp->fts_path);
-				rval = 1;
-			}
-		}
-#ifndef __ANDROID__
-	}
-#endif
-
-#ifndef __ANDROID__
-	if (pflag && (fcpxattr(from_fd, to_fd) != 0))
-		warn("%s: error copying extended attributes", to.p_path);
-#endif
-
-	(void)close(from_fd);
-
-	if (rval == 1) {
-		(void)close(to_fd);
-		return (1);
-	}
-
-	if (pflag && setfile(fs, to_fd))
-		rval = 1;
-	/*
-	 * If the source was setuid or setgid, lose the bits unless the
-	 * copy is owned by the same user and group.
-	 */
-#define	RETAINBITS \
-	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
-	if (!pflag && dne
-	    && fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
-		if (fstat(to_fd, &to_stat)) {
-			warn("%s", to.p_path);
-			rval = 1;
-		} else if (fs->st_gid == to_stat.st_gid &&
-		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
-			warn("%s", to.p_path);
-			rval = 1;
-		}
-	}
-	if (close(to_fd)) {
-		warn("%s", to.p_path);
-		rval = 1;
-	}
-	/* set the mod/access times now after close of the fd */
-	if (pflag && set_utimes(to.p_path, fs)) { 
-	    rval = 1;
-	}
-	return (rval);
-}
-
-int
-copy_link(FTSENT *p, int exists)
-{
-	int len;
-	char target[MAXPATHLEN];
-
-	if ((len = readlink(p->fts_path, target, sizeof(target)-1)) == -1) {
-		warn("readlink: %s", p->fts_path);
-		return (1);
-	}
-	target[len] = '\0';
-	if (exists && unlink(to.p_path)) {
-		warn("unlink: %s", to.p_path);
-		return (1);
-	}
-	if (symlink(target, to.p_path)) {
-		warn("symlink: %s", target);
-		return (1);
-	}
-	return (pflag ? setfile(p->fts_statp, 0) : 0);
-}
-
-int
-copy_fifo(struct stat *from_stat, int exists)
-{
-	if (exists && unlink(to.p_path)) {
-		warn("unlink: %s", to.p_path);
-		return (1);
-	}
-	if (mkfifo(to.p_path, from_stat->st_mode)) {
-		warn("mkfifo: %s", to.p_path);
-		return (1);
-	}
-	return (pflag ? setfile(from_stat, 0) : 0);
-}
-
-int
-copy_special(struct stat *from_stat, int exists)
-{
-	if (exists && unlink(to.p_path)) {
-		warn("unlink: %s", to.p_path);
-		return (1);
-	}
-	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
-		warn("mknod: %s", to.p_path);
-		return (1);
-	}
-	return (pflag ? setfile(from_stat, 0) : 0);
-}
-
-
-/*
- * Function: setfile
- *
- * Purpose:
- *   Set the owner/group/permissions for the "to" file to the information
- *   in the stat structure.  If fd is zero, also call set_utimes() to set
- *   the mod/access times.  If fd is non-zero, the caller must do a utimes
- *   itself after close(fd).
- */
-int
-setfile(struct stat *fs, int fd)
-{
-	int rval, islink;
-
-	rval = 0;
-	islink = S_ISLNK(fs->st_mode);
-	fs->st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
-
-	/*
-	 * Changing the ownership probably won't succeed, unless we're root
-	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
-	 * the mode; current BSD behavior is to remove all setuid bits on
-	 * chown.  If chown fails, lose setuid/setgid bits.
-	 */
-	if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
-	    lchown(to.p_path, fs->st_uid, fs->st_gid)) {
-		if (errno != EPERM) {
-			warn("chown: %s", to.p_path);
-			rval = 1;
-		}
-		fs->st_mode &= ~(S_ISUID | S_ISGID);
-	}
-#ifdef __ANDROID__
-	if (fd ? fchmod(fd, fs->st_mode) : chmod(to.p_path, fs->st_mode)) {
-#else
-	if (fd ? fchmod(fd, fs->st_mode) : lchmod(to.p_path, fs->st_mode)) {
-#endif
-		warn("chmod: %s", to.p_path);
-		rval = 1;
-	}
-
-#ifndef __ANDROID__
-	if (!islink && !Nflag) {
-		unsigned long fflags = fs->st_flags;
-		/*
-		 * XXX
-		 * NFS doesn't support chflags; ignore errors unless
-		 * there's reason to believe we're losing bits.
-		 * (Note, this still won't be right if the server
-		 * supports flags and we were trying to *remove* flags
-		 * on a file that we copied, i.e., that we didn't create.)
-		 */
-		errno = 0;
-		if ((fd ? fchflags(fd, fflags) :
-		    chflags(to.p_path, fflags)) == -1)
-			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
-				warn("chflags: %s", to.p_path);
-				rval = 1;
-			}
-	}
-#endif
-	/* if fd is non-zero, caller must call set_utimes() after close() */
-	if (fd == 0 && set_utimes(to.p_path, fs))
-	    rval = 1;
-	return (rval);
-}
-
-void
-usage(void)
-{
-	(void)fprintf(stderr,
-	    "usage: %s [-R [-H | -L | -P]] [-f | -i] [-alNpv] src target\n"
-	    "       %s [-R [-H | -L | -P]] [-f | -i] [-alNpv] src1 ... srcN directory\n",
-	    getprogname(), getprogname());
-	exit(1);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/bin/kill/kill.c b/toolbox/upstream-netbsd/bin/kill/kill.c
deleted file mode 100644
index 0592577..0000000
--- a/toolbox/upstream-netbsd/bin/kill/kill.c
+++ /dev/null
@@ -1,253 +0,0 @@
-/* $NetBSD: kill.c,v 1.27 2011/08/29 14:51:18 joerg Exp $ */
-
-/*
- * Copyright (c) 1988, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#if !defined(lint) && !defined(SHELL)
-__COPYRIGHT("@(#) Copyright (c) 1988, 1993, 1994\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)kill.c	8.4 (Berkeley) 4/28/95";
-#else
-__RCSID("$NetBSD: kill.c,v 1.27 2011/08/29 14:51:18 joerg Exp $");
-#endif
-#endif /* not lint */
-
-#include <ctype.h>
-#include <err.h>
-#include <errno.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <limits.h>
-#include <inttypes.h>
-#include <string.h>
-#include <termios.h>
-#include <unistd.h>
-#include <locale.h>
-#include <sys/ioctl.h>
-
-#ifdef SHELL            /* sh (aka ash) builtin */
-int killcmd(int, char *argv[]);
-#define main killcmd
-#include "../../bin/sh/bltin/bltin.h"
-#endif /* SHELL */ 
-
-__dead static void nosig(char *);
-static void printsignals(FILE *);
-static int signame_to_signum(char *);
-__dead static void usage(void);
-
-int
-main(int argc, char *argv[])
-{
-	int errors;
-	intmax_t numsig, pid;
-	char *ep;
-
-	setprogname(argv[0]);
-	setlocale(LC_ALL, "");
-	if (argc < 2)
-		usage();
-
-	numsig = SIGTERM;
-
-	argc--, argv++;
-	if (strcmp(*argv, "-l") == 0) {
-		argc--, argv++;
-		if (argc > 1)
-			usage();
-		if (argc == 1) {
-			if (isdigit((unsigned char)**argv) == 0)
-				usage();
-			numsig = strtoimax(*argv, &ep, 10);
-			/* check for correctly parsed number */
-			if (*ep != '\0' || numsig == INTMAX_MIN || numsig == INTMAX_MAX) {
-				errx(EXIT_FAILURE, "illegal signal number: %s",
-						*argv);
-				/* NOTREACHED */
-			}
-			if (numsig >= 128)
-				numsig -= 128;
-			/* and whether it fits into signals range */
-			if (numsig <= 0 || numsig >= NSIG)
-				nosig(*argv);
-			printf("%s\n", sys_signame[(int) numsig]);
-			exit(0);
-		}
-		printsignals(stdout);
-		exit(0);
-	}
-
-	if (!strcmp(*argv, "-s")) {
-		argc--, argv++;
-		if (argc < 1) {
-			warnx("option requires an argument -- s");
-			usage();
-		}
-		if (strcmp(*argv, "0")) {
-			if ((numsig = signame_to_signum(*argv)) < 0)
-				nosig(*argv);
-		} else
-			numsig = 0;
-		argc--, argv++;
-	} else if (**argv == '-') {
-		char *sn = *argv + 1;
-		if (isalpha((unsigned char)*sn)) {
-			if ((numsig = signame_to_signum(sn)) < 0)
-				nosig(sn);
-		} else if (isdigit((unsigned char)*sn)) {
-			numsig = strtoimax(sn, &ep, 10);
-			/* check for correctly parsed number */
-			if (*ep || numsig == INTMAX_MIN || numsig == INTMAX_MAX ) {
-				errx(EXIT_FAILURE, "illegal signal number: %s",
-						sn);
-				/* NOTREACHED */
-			}
-			/* and whether it fits into signals range */
-			if (numsig < 0 || numsig >= NSIG)
-				nosig(sn);
-		} else
-			nosig(sn);
-		argc--, argv++;
-	}
-
-	if (argc == 0)
-		usage();
-
-	for (errors = 0; argc; argc--, argv++) {
-#ifdef SHELL
-		extern int getjobpgrp(const char *);
-		if (*argv[0] == '%') {
-			pid = getjobpgrp(*argv);
-			if (pid == 0) {
-				warnx("illegal job id: %s", *argv);
-				errors = 1;
-				continue;
-			}
-		} else 
-#endif
-		{
-			pid = strtoimax(*argv, &ep, 10);
-			/* make sure the pid is a number and fits into pid_t */
-			if (!**argv || *ep || pid == INTMAX_MIN ||
-				pid == INTMAX_MAX || pid != (pid_t) pid) {
-
-				warnx("illegal process id: %s", *argv);
-				errors = 1;
-				continue;
-			}
-		}
-		if (kill((pid_t) pid, (int) numsig) == -1) {
-			warn("%s", *argv);
-			errors = 1;
-		}
-#ifdef SHELL
-		/* Wakeup the process if it was suspended, so it can
-		   exit without an explicit 'fg'. */
-		if (numsig == SIGTERM || numsig == SIGHUP)
-			kill((pid_t) pid, SIGCONT);
-#endif
-	}
-
-	exit(errors);
-	/* NOTREACHED */
-}
-
-static int
-signame_to_signum(char *sig)
-{
-	int n;
-
-	if (strncasecmp(sig, "sig", 3) == 0)
-		sig += 3;
-	for (n = 1; n < NSIG; n++) {
-		if (!strcasecmp(sys_signame[n], sig))
-			return (n);
-	}
-	return (-1);
-}
-
-static void
-nosig(char *name)
-{
-
-	warnx("unknown signal %s; valid signals:", name);
-	printsignals(stderr);
-	exit(1);
-	/* NOTREACHED */
-}
-
-static void
-printsignals(FILE *fp)
-{
-	int sig;
-	int len, nl;
-	const char *name;
-	int termwidth = 80;
-
-	if (isatty(fileno(fp))) {
-		struct winsize win;
-		if (ioctl(fileno(fp), TIOCGWINSZ, &win) == 0 && win.ws_col > 0)
-			termwidth = win.ws_col;
-	}
-
-	for (len = 0, sig = 1; sig < NSIG; sig++) {
-		name = sys_signame[sig];
-		nl = 1 + strlen(name);
-
-		if (len + nl >= termwidth) {
-			fprintf(fp, "\n");
-			len = 0;
-		} else
-			if (len != 0)
-				fprintf(fp, " ");
-		len += nl;
-		fprintf(fp, "%s", name);
-	}
-	if (len != 0)
-		fprintf(fp, "\n");
-}
-
-static void
-usage(void)
-{
-
-	fprintf(stderr, "usage: %s [-s signal_name] pid ...\n"
-	    "       %s -l [exit_status]\n"
-	    "       %s -signal_name pid ...\n"
-	    "       %s -signal_number pid ...\n",
-	    getprogname(), getprogname(), getprogname(), getprogname());
-	exit(1);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/bin/ln/ln.c b/toolbox/upstream-netbsd/bin/ln/ln.c
deleted file mode 100644
index 9127477..0000000
--- a/toolbox/upstream-netbsd/bin/ln/ln.c
+++ /dev/null
@@ -1,230 +0,0 @@
-/* $NetBSD: ln.c,v 1.35 2011/08/29 14:38:30 joerg Exp $ */
-
-/*
- * Copyright (c) 1987, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1987, 1993, 1994\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)ln.c	8.2 (Berkeley) 3/31/94";
-#else
-__RCSID("$NetBSD: ln.c,v 1.35 2011/08/29 14:38:30 joerg Exp $");
-#endif
-#endif /* not lint */
-
-#include <sys/param.h>
-#include <sys/stat.h>
-
-#include <err.h>
-#include <errno.h>
-#include <locale.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-static int	fflag;				/* Unlink existing files. */
-static int	hflag;				/* Check new name for symlink first. */
-static int	iflag;				/* Interactive mode. */
-static int	sflag;				/* Symbolic, not hard, link. */
-static int	vflag;                          /* Verbose output */
-
-					/* System link call. */
-static int (*linkf)(const char *, const char *);
-static char   linkch;
-
-static int	linkit(const char *, const char *, int);
-__dead static void	usage(void);
-
-int
-main(int argc, char *argv[])
-{
-	struct stat sb;
-	int ch, exitval;
-	char *sourcedir;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	while ((ch = getopt(argc, argv, "fhinsv")) != -1)
-		switch (ch) {
-		case 'f':
-			fflag = 1;
-			iflag = 0;
-			break;
-		case 'h':
-		case 'n':
-			hflag = 1;
-			break;
-		case 'i':
-			iflag = 1;
-			fflag = 0;
-			break;
-		case 's':
-			sflag = 1;
-			break;
-		case 'v':               
-			vflag = 1;
-			break;
-		case '?':
-		default:
-			usage();
-			/* NOTREACHED */
-		}
-
-	argv += optind;
-	argc -= optind;
-
-	if (sflag) {
-		linkf  = symlink;
-		linkch = '-';
-	} else {
-		linkf  = link;
-		linkch = '=';
-	}
-
-	switch(argc) {
-	case 0:
-		usage();
-		/* NOTREACHED */
-	case 1:				/* ln target */
-		exit(linkit(argv[0], ".", 1));
-		/* NOTREACHED */
-	case 2:				/* ln target source */
-		exit(linkit(argv[0], argv[1], 0));
-		/* NOTREACHED */
-	}
-
-					/* ln target1 target2 directory */
-	sourcedir = argv[argc - 1];
-	if (hflag && lstat(sourcedir, &sb) == 0 && S_ISLNK(sb.st_mode)) {
-		/* we were asked not to follow symlinks, but found one at
-		   the target--simulate "not a directory" error */
-		errno = ENOTDIR;
-		err(EXIT_FAILURE, "%s", sourcedir);
-		/* NOTREACHED */
-	}
-	if (stat(sourcedir, &sb)) {
-		err(EXIT_FAILURE, "%s", sourcedir);
-		/* NOTREACHED */
-	}
-	if (!S_ISDIR(sb.st_mode)) {
-		usage();
-		/* NOTREACHED */
-	}
-	for (exitval = 0; *argv != sourcedir; ++argv)
-		exitval |= linkit(*argv, sourcedir, 1);
-	exit(exitval);
-	/* NOTREACHED */
-}
-
-static int
-linkit(const char *target, const char *source, int isdir)
-{
-	struct stat sb;
-	const char *p;
-	char path[MAXPATHLEN];
-	int ch, exists, first;
-
-	if (!sflag) {
-		/* If target doesn't exist, quit now. */
-		if (stat(target, &sb)) {
-			warn("%s", target);
-			return (1);
-		}
-	}
-
-	/* If the source is a directory (and not a symlink if hflag),
-	   append the target's name. */
-	if (isdir ||
-	    (!lstat(source, &sb) && S_ISDIR(sb.st_mode)) ||
-	    (!hflag && !stat(source, &sb) && S_ISDIR(sb.st_mode))) {
-		if ((p = strrchr(target, '/')) == NULL)
-			p = target;
-		else
-			++p;
-		(void)snprintf(path, sizeof(path), "%s/%s", source, p);
-		source = path;
-	}
-
-	exists = !lstat(source, &sb);
-
-	/*
-	 * If the file exists, then unlink it forcibly if -f was specified
-	 * and interactively if -i was specified.
-	 */
-	if (fflag && exists) {
-		if (unlink(source)) {
-			warn("%s", source);
-			return (1);
-		}
-	} else if (iflag && exists) {
-		fflush(stdout);
-		(void)fprintf(stderr, "replace %s? ", source);
-
-		first = ch = getchar();
-		while (ch != '\n' && ch != EOF)
-			ch = getchar();
-		if (first != 'y' && first != 'Y') {
-			(void)fprintf(stderr, "not replaced\n");
-			return (1);
-		}
-
-		if (unlink(source)) {
-			warn("%s", source);
-			return (1);
-		}
-	}
-
-	/* Attempt the link. */
-	if ((*linkf)(target, source)) {
-		warn("%s", source);
-		return (1);
-	}
-	if (vflag)
-		(void)printf("%s %c> %s\n", source, linkch, target);
-
-	return (0);
-}
-
-static void
-usage(void)
-{
-
-	(void)fprintf(stderr,
-	    "usage:\t%s [-fhinsv] file1 file2\n\t%s [-fhinsv] file ... directory\n",
-	    getprogname(), getprogname());
-	exit(1);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/bin/mv/mv.c b/toolbox/upstream-netbsd/bin/mv/mv.c
deleted file mode 100644
index 4be6c30..0000000
--- a/toolbox/upstream-netbsd/bin/mv/mv.c
+++ /dev/null
@@ -1,396 +0,0 @@
-/* $NetBSD: mv.c,v 1.43 2011/08/29 14:46:54 joerg Exp $ */
-
-/*
- * Copyright (c) 1989, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Ken Smith of The State University of New York at Buffalo.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)mv.c	8.2 (Berkeley) 4/2/94";
-#else
-__RCSID("$NetBSD: mv.c,v 1.43 2011/08/29 14:46:54 joerg Exp $");
-#endif
-#endif /* not lint */
-
-#include <sys/param.h>
-#include <sys/time.h>
-#include <sys/wait.h>
-#include <sys/stat.h>
-#include <sys/extattr.h>
-
-#include <err.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <locale.h>
-#include <pwd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "pathnames.h"
-
-static int fflg, iflg, vflg;
-static int stdin_ok;
-
-static int	copy(char *, char *);
-static int	do_move(char *, char *);
-static int	fastcopy(char *, char *, struct stat *);
-__dead static void	usage(void);
-
-int
-main(int argc, char *argv[])
-{
-	int ch, len, rval;
-	char *p, *endp;
-	struct stat sb;
-	char path[MAXPATHLEN + 1];
-	size_t baselen;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	while ((ch = getopt(argc, argv, "ifv")) != -1)
-		switch (ch) {
-		case 'i':
-			fflg = 0;
-			iflg = 1;
-			break;
-		case 'f':
-			iflg = 0;
-			fflg = 1;
-			break;
-		case 'v':
-			vflg = 1;
-			break;
-		default:
-			usage();
-		}
-	argc -= optind;
-	argv += optind;
-
-	if (argc < 2)
-		usage();
-
-	stdin_ok = isatty(STDIN_FILENO);
-
-	/*
-	 * If the stat on the target fails or the target isn't a directory,
-	 * try the move.  More than 2 arguments is an error in this case.
-	 */
-	if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
-		if (argc > 2)
-			usage();
-		exit(do_move(argv[0], argv[1]));
-	}
-
-	/* It's a directory, move each file into it. */
-	baselen = strlcpy(path, argv[argc - 1], sizeof(path));
-	if (baselen >= sizeof(path))
-		errx(1, "%s: destination pathname too long", argv[argc - 1]);
-	endp = &path[baselen];
-	if (!baselen || *(endp - 1) != '/') {
-		*endp++ = '/';
-		++baselen;
-	}
-	for (rval = 0; --argc; ++argv) {
-		p = *argv + strlen(*argv) - 1;
-		while (*p == '/' && p != *argv)
-			*p-- = '\0';
-		if ((p = strrchr(*argv, '/')) == NULL)
-			p = *argv;
-		else
-			++p;
-
-		if ((baselen + (len = strlen(p))) >= MAXPATHLEN) {
-			warnx("%s: destination pathname too long", *argv);
-			rval = 1;
-		} else {
-			memmove(endp, p, len + 1);
-			if (do_move(*argv, path))
-				rval = 1;
-		}
-	}
-	exit(rval);
-	/* NOTREACHED */
-}
-
-static int
-do_move(char *from, char *to)
-{
-	struct stat sb;
-	char modep[15];
-
-	/*
-	 * (1)	If the destination path exists, the -f option is not specified
-	 *	and either of the following conditions are true:
-	 *
-	 *	(a) The permissions of the destination path do not permit
-	 *	    writing and the standard input is a terminal.
-	 *	(b) The -i option is specified.
-	 *
-	 *	the mv utility shall write a prompt to standard error and
-	 *	read a line from standard input.  If the response is not
-	 *	affirmative, mv shall do nothing more with the current
-	 *	source file...
-	 */
-	if (!fflg && !access(to, F_OK)) {
-		int ask = 1;
-		int ch;
-
-		if (iflg) {
-			if (access(from, F_OK)) {
-				warn("rename %s", from);
-				return (1);
-			}
-			(void)fprintf(stderr, "overwrite %s? ", to);
-		} else if (stdin_ok && access(to, W_OK) && !stat(to, &sb)) {
-			if (access(from, F_OK)) {
-				warn("rename %s", from);
-				return (1);
-			}
-			strmode(sb.st_mode, modep);
-			(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
-			    modep + 1, modep[9] == ' ' ? "" : " ",
-			    user_from_uid(sb.st_uid, 0),
-			    group_from_gid(sb.st_gid, 0), to);
-		} else
-			ask = 0;
-		if (ask) {
-			if ((ch = getchar()) != EOF && ch != '\n') {
-				int ch2;
-				while ((ch2 = getchar()) != EOF && ch2 != '\n')
-					continue;
-			}
-			if (ch != 'y' && ch != 'Y')
-				return (0);
-		}
-	}
-
-	/*
-	 * (2)	If rename() succeeds, mv shall do nothing more with the
-	 *	current source file.  If it fails for any other reason than
-	 *	EXDEV, mv shall write a diagnostic message to the standard
-	 *	error and do nothing more with the current source file.
-	 *
-	 * (3)	If the destination path exists, and it is a file of type
-	 *	directory and source_file is not a file of type directory,
-	 *	or it is a file not of type directory, and source file is
-	 *	a file of type directory, mv shall write a diagnostic
-	 *	message to standard error, and do nothing more with the
-	 *	current source file...
-	 */
-	if (!rename(from, to)) {
-		if (vflg)
-			printf("%s -> %s\n", from, to);
-		return (0);
-	}
-
-	if (errno != EXDEV) {
-		warn("rename %s to %s", from, to);
-		return (1);
-	}
-
-	/*
-	 * (4)	If the destination path exists, mv shall attempt to remove it.
-	 *	If this fails for any reason, mv shall write a diagnostic
-	 *	message to the standard error and do nothing more with the
-	 *	current source file...
-	 */
-	if (!lstat(to, &sb)) {
-		if ((S_ISDIR(sb.st_mode)) ? rmdir(to) : unlink(to)) {
-			warn("can't remove %s", to);
-			return (1);
-		}
-	}
-
-	/*
-	 * (5)	The file hierarchy rooted in source_file shall be duplicated
-	 *	as a file hierarchy rooted in the destination path...
-	 */
-	if (lstat(from, &sb)) {
-		warn("%s", from);
-		return (1);
-	}
-
-	return (S_ISREG(sb.st_mode) ?
-	    fastcopy(from, to, &sb) : copy(from, to));
-}
-
-static int
-fastcopy(char *from, char *to, struct stat *sbp)
-{
-	struct timeval tval[2];
-	static blksize_t blen;
-	static char *bp;
-	int nread, from_fd, to_fd;
-
-	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
-		warn("%s", from);
-		return (1);
-	}
-	if ((to_fd =
-	    open(to, O_CREAT | O_TRUNC | O_WRONLY, sbp->st_mode)) < 0) {
-		warn("%s", to);
-		(void)close(from_fd);
-		return (1);
-	}
-	if (!blen && !(bp = malloc(blen = sbp->st_blksize))) {
-		warn(NULL);
-		blen = 0;
-		(void)close(from_fd);
-		(void)close(to_fd);
-		return (1);
-	}
-	while ((nread = read(from_fd, bp, blen)) > 0)
-		if (write(to_fd, bp, nread) != nread) {
-			warn("%s", to);
-			goto err;
-		}
-	if (nread < 0) {
-		warn("%s", from);
-err:		if (unlink(to))
-			warn("%s: remove", to);
-		(void)close(from_fd);
-		(void)close(to_fd);
-		return (1);
-	}
-
-#ifndef __ANDROID__
-	if (fcpxattr(from_fd, to_fd) == -1)
-		warn("%s: error copying extended attributes", to);
-#endif
-
-	(void)close(from_fd);
-#ifdef BSD4_4
-	TIMESPEC_TO_TIMEVAL(&tval[0], &sbp->st_atimespec);
-	TIMESPEC_TO_TIMEVAL(&tval[1], &sbp->st_mtimespec);
-#else
-	tval[0].tv_sec = sbp->st_atime;
-	tval[1].tv_sec = sbp->st_mtime;
-	tval[0].tv_usec = 0;
-	tval[1].tv_usec = 0;
-#endif
-#ifdef __SVR4
-	if (utimes(to, tval))
-#else
-	if (futimes(to_fd, tval))
-#endif
-		warn("%s: set times", to);
-	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
-		if (errno != EPERM)
-			warn("%s: set owner/group", to);
-		sbp->st_mode &= ~(S_ISUID | S_ISGID);
-	}
-	if (fchmod(to_fd, sbp->st_mode))
-		warn("%s: set mode", to);
-#ifndef __ANDROID__
-	if (fchflags(to_fd, sbp->st_flags) && (errno != EOPNOTSUPP))
-		warn("%s: set flags (was: 0%07o)", to, sbp->st_flags);
-#endif
-
-	if (close(to_fd)) {
-		warn("%s", to);
-		return (1);
-	}
-
-	if (unlink(from)) {
-		warn("%s: remove", from);
-		return (1);
-	}
-
-	if (vflg)
-		printf("%s -> %s\n", from, to);
-
-	return (0);
-}
-
-static int
-copy(char *from, char *to)
-{
-	pid_t pid;
-	int status;
-
-	if ((pid = vfork()) == 0) {
-		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", "--", from, to, NULL);
-		warn("%s", _PATH_CP);
-		_exit(1);
-	}
-	if (waitpid(pid, &status, 0) == -1) {
-		warn("%s: waitpid", _PATH_CP);
-		return (1);
-	}
-	if (!WIFEXITED(status)) {
-		warnx("%s: did not terminate normally", _PATH_CP);
-		return (1);
-	}
-	if (WEXITSTATUS(status)) {
-		warnx("%s: terminated with %d (non-zero) status",
-		    _PATH_CP, WEXITSTATUS(status));
-		return (1);
-	}
-	if (!(pid = vfork())) {
-		execl(_PATH_RM, "mv", "-rf", "--", from, NULL);
-		warn("%s", _PATH_RM);
-		_exit(1);
-	}
-	if (waitpid(pid, &status, 0) == -1) {
-		warn("%s: waitpid", _PATH_RM);
-		return (1);
-	}
-	if (!WIFEXITED(status)) {
-		warnx("%s: did not terminate normally", _PATH_RM);
-		return (1);
-	}
-	if (WEXITSTATUS(status)) {
-		warnx("%s: terminated with %d (non-zero) status",
-		    _PATH_RM, WEXITSTATUS(status));
-		return (1);
-	}
-	return (0);
-}
-
-static void
-usage(void)
-{
-	(void)fprintf(stderr, "usage: %s [-fiv] source target\n"
-	    "       %s [-fiv] source ... directory\n", getprogname(),
-	    getprogname());
-	exit(1);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/bin/mv/pathnames.h b/toolbox/upstream-netbsd/bin/mv/pathnames.h
deleted file mode 100644
index 7838946..0000000
--- a/toolbox/upstream-netbsd/bin/mv/pathnames.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*	$NetBSD: pathnames.h,v 1.8 2004/08/19 22:26:07 christos Exp $	*/
-
-/*
- * Copyright (c) 1989, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- *
- *	@(#)pathnames.h	8.1 (Berkeley) 5/31/93
- */
-
-#ifdef __ANDROID__
-#define	_PATH_RM	"/system/bin/rm"
-#define	_PATH_CP	"/system/bin/cp"
-#else
-#ifdef RESCUEDIR
-#define	_PATH_RM	RESCUEDIR "/rm"
-#define	_PATH_CP	RESCUEDIR "/cp"
-#else
-#define	_PATH_RM	"/bin/rm"
-#define	_PATH_CP	"/bin/cp"
-#endif
-#endif
diff --git a/toolbox/upstream-netbsd/bin/rm/rm.c b/toolbox/upstream-netbsd/bin/rm/rm.c
deleted file mode 100644
index f183810..0000000
--- a/toolbox/upstream-netbsd/bin/rm/rm.c
+++ /dev/null
@@ -1,625 +0,0 @@
-/* $NetBSD: rm.c,v 1.53 2013/04/26 18:43:22 christos Exp $ */
-
-/*-
- * Copyright (c) 1990, 1993, 1994, 2003
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)rm.c	8.8 (Berkeley) 4/27/95";
-#else
-__RCSID("$NetBSD: rm.c,v 1.53 2013/04/26 18:43:22 christos Exp $");
-#endif
-#endif /* not lint */
-
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#include <err.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <fts.h>
-#include <grp.h>
-#include <locale.h>
-#include <pwd.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-static int dflag, eval, fflag, iflag, Pflag, stdin_ok, vflag, Wflag;
-static int xflag;
-static sig_atomic_t pinfo;
-
-static int	check(char *, char *, struct stat *);
-static void	checkdot(char **);
-static void	progress(int);
-static void	rm_file(char **);
-static int	rm_overwrite(char *, struct stat *);
-static void	rm_tree(char **);
-__dead static void	usage(void);
-
-/*
- * For the sake of the `-f' flag, check whether an error number indicates the
- * failure of an operation due to an non-existent file, either per se (ENOENT)
- * or because its filename argument was illegal (ENAMETOOLONG, ENOTDIR).
- */
-#define NONEXISTENT(x) \
-    ((x) == ENOENT || (x) == ENAMETOOLONG || (x) == ENOTDIR)
-
-/*
- * rm --
- *	This rm is different from historic rm's, but is expected to match
- *	POSIX 1003.2 behavior.  The most visible difference is that -f
- *	has two specific effects now, ignore non-existent files and force
- * 	file removal.
- */
-int
-main(int argc, char *argv[])
-{
-	int ch, rflag;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	Pflag = rflag = xflag = 0;
-	while ((ch = getopt(argc, argv, "dfiPRrvWx")) != -1)
-		switch (ch) {
-		case 'd':
-			dflag = 1;
-			break;
-		case 'f':
-			fflag = 1;
-			iflag = 0;
-			break;
-		case 'i':
-			fflag = 0;
-			iflag = 1;
-			break;
-		case 'P':
-			Pflag = 1;
-			break;
-		case 'R':
-		case 'r':			/* Compatibility. */
-			rflag = 1;
-			break;
-		case 'v':
-			vflag = 1;
-			break;
-		case 'x':
-			xflag = 1;
-			break;
-#ifndef __ANDROID__
-		case 'W':
-			Wflag = 1;
-			break;
-#endif
-		case '?':
-		default:
-			usage();
-		}
-	argc -= optind;
-	argv += optind;
-
-	if (argc < 1) {
-		if (fflag)
-			return 0;
-		usage();
-	}
-
-	(void)signal(SIGINFO, progress);
-
-	checkdot(argv);
-
-	if (*argv) {
-		stdin_ok = isatty(STDIN_FILENO);
-
-		if (rflag)
-			rm_tree(argv);
-		else
-			rm_file(argv);
-	}
-
-	exit(eval);
-	/* NOTREACHED */
-}
-
-static void
-rm_tree(char **argv)
-{
-	FTS *fts;
-	FTSENT *p;
-	int flags, needstat, rval;
-			
-	/*
-	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
-	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
-	 */
-	needstat = !fflag && !iflag && stdin_ok;
-
-	/*
-	 * If the -i option is specified, the user can skip on the pre-order
-	 * visit.  The fts_number field flags skipped directories.
-	 */
-#define	SKIPPED	1
-
-	flags = FTS_PHYSICAL;
-	if (!needstat)
-		flags |= FTS_NOSTAT;
-#ifndef __ANDROID__
-	if (Wflag)
-		flags |= FTS_WHITEOUT;
-#endif
-	if (xflag)
-		flags |= FTS_XDEV;
-	if ((fts = fts_open(argv, flags, NULL)) == NULL)
-		err(1, "fts_open failed");
-	while ((p = fts_read(fts)) != NULL) {
-	
-		switch (p->fts_info) {
-		case FTS_DNR:
-			if (!fflag || p->fts_errno != ENOENT) {
-				warnx("%s: %s", p->fts_path,
-						strerror(p->fts_errno));
-				eval = 1;
-			}
-			continue;
-		case FTS_ERR:
-			errx(EXIT_FAILURE, "%s: %s", p->fts_path,
-					strerror(p->fts_errno));
-			/* NOTREACHED */
-		case FTS_NS:
-			/*
-			 * FTS_NS: assume that if can't stat the file, it
-			 * can't be unlinked.
-			 */
-			if (fflag && NONEXISTENT(p->fts_errno))
-				continue;
-			if (needstat) {
-				warnx("%s: %s", p->fts_path,
-						strerror(p->fts_errno));
-				eval = 1;
-				continue;
-			}
-			break;
-		case FTS_D:
-			/* Pre-order: give user chance to skip. */
-			if (!fflag && !check(p->fts_path, p->fts_accpath,
-			    p->fts_statp)) {
-				(void)fts_set(fts, p, FTS_SKIP);
-				p->fts_number = SKIPPED;
-			}
-			continue;
-		case FTS_DP:
-			/* Post-order: see if user skipped. */
-			if (p->fts_number == SKIPPED)
-				continue;
-			break;
-		default:
-			if (!fflag &&
-			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
-				continue;
-		}
-
-		rval = 0;
-		/*
-		 * If we can't read or search the directory, may still be
-		 * able to remove it.  Don't print out the un{read,search}able
-		 * message unless the remove fails.
-		 */
-		switch (p->fts_info) {
-		case FTS_DP:
-		case FTS_DNR:
-			rval = rmdir(p->fts_accpath);
-			if (rval != 0 && fflag && errno == ENOENT)
-				continue;
-			break;
-
-#ifndef __ANDROID__
-		case FTS_W:
-			rval = undelete(p->fts_accpath);
-			if (rval != 0 && fflag && errno == ENOENT)
-				continue;
-			break;
-#endif
-
-		default:
-			if (Pflag) {
-				if (rm_overwrite(p->fts_accpath, NULL))
-					continue;
-			}
-			rval = unlink(p->fts_accpath);
-			if (rval != 0 && fflag && NONEXISTENT(errno))
-				continue;
-			break;
-		}
-		if (rval != 0) {
-			warn("%s", p->fts_path);
-			eval = 1;
-		} else if (vflag || pinfo) {
-			pinfo = 0;
-			(void)printf("%s\n", p->fts_path);
-		}
-	}
-	if (errno)
-		err(1, "fts_read");
-	fts_close(fts);
-}
-
-static void
-rm_file(char **argv)
-{
-	struct stat sb;
-	int rval;
-	char *f;
-
-	/*
-	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
-	 * to remove a directory is an error, so must always stat the file.
-	 */
-	while ((f = *argv++) != NULL) {
-		/* Assume if can't stat the file, can't unlink it. */
-		if (lstat(f, &sb)) {
-#ifndef __ANDROID__
-			if (Wflag) {
-				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
-			} else {
-#endif
-				if (!fflag || !NONEXISTENT(errno)) {
-					warn("%s", f);
-					eval = 1;
-				}
-				continue;
-#ifndef __ANDROID__
-			}
-		} else if (Wflag) {
-			warnx("%s: %s", f, strerror(EEXIST));
-			eval = 1;
-			continue;
-#endif
-		}
-
-		if (S_ISDIR(sb.st_mode) && !dflag) {
-			warnx("%s: is a directory", f);
-			eval = 1;
-			continue;
-		}
-		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
-			continue;
-#ifndef __ANDROID__
-		if (S_ISWHT(sb.st_mode))
-			rval = undelete(f);
-		else if (S_ISDIR(sb.st_mode))
-#else
-		if (S_ISDIR(sb.st_mode))
-#endif
-			rval = rmdir(f);
-		else {
-			if (Pflag) {
-				if (rm_overwrite(f, &sb))
-					continue;
-			}
-			rval = unlink(f);
-		}
-		if (rval && (!fflag || !NONEXISTENT(errno))) {
-			warn("%s", f);
-			eval = 1;
-		}
-		if (vflag && rval == 0)
-			(void)printf("%s\n", f);
-	}
-}
-
-/*
- * rm_overwrite --
- *	Overwrite the file 3 times with varying bit patterns.
- *
- * This is an expensive way to keep people from recovering files from your
- * non-snapshotted FFS filesystems using fsdb(8).  Really.  No more.  Only
- * regular files are deleted, directories (and therefore names) will remain.
- * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
- * System V file system).  In a logging file system, you'll have to have
- * kernel support.
- *
- * A note on standards:  U.S. DoD 5220.22-M "National Industrial Security
- * Program Operating Manual" ("NISPOM") is often cited as a reference
- * for clearing and sanitizing magnetic media.  In fact, a matrix of
- * "clearing" and "sanitization" methods for various media was given in
- * Chapter 8 of the original 1995 version of NISPOM.  However, that
- * matrix was *removed from the document* when Chapter 8 was rewritten
- * in Change 2 to the document in 2001.  Recently, the Defense Security
- * Service has made a revised clearing and sanitization matrix available
- * in Microsoft Word format on the DSS web site.  The standardization
- * status of this matrix is unclear.  Furthermore, one must be very
- * careful when referring to this matrix: it is intended for the "clearing"
- * prior to reuse or "sanitization" prior to disposal of *entire media*,
- * not individual files and the only non-physically-destructive method of
- * "sanitization" that is permitted for magnetic disks of any kind is
- * specifically noted to be prohibited for media that have contained
- * Top Secret data.
- *
- * It is impossible to actually conform to the exact procedure given in
- * the matrix if one is overwriting a file, not an entire disk, because
- * the procedure requires examination and comparison of the disk's defect
- * lists.  Any program that claims to securely erase *files* while 
- * conforming to the standard, then, is not correct.  We do as much of
- * what the standard requires as can actually be done when erasing a
- * file, rather than an entire disk; but that does not make us conformant.
- *
- * Furthermore, the presence of track caches, disk and controller write
- * caches, and so forth make it extremely difficult to ensure that data
- * have actually been written to the disk, particularly when one tries
- * to repeatedly overwrite the same sectors in quick succession.  We call
- * fsync(), but controllers with nonvolatile cache, as well as IDE disks
- * that just plain lie about the stable storage of data, will defeat this.
- *
- * Finally, widely respected research suggests that the given procedure
- * is nowhere near sufficient to prevent the recovery of data using special
- * forensic equipment and techniques that are well-known.  This is 
- * presumably one reason that the matrix requires physical media destruction,
- * rather than any technique of the sort attempted here, for secret data.
- *
- * Caveat Emptor.
- *
- * rm_overwrite will return 0 on success.
- */
-
-static int
-rm_overwrite(char *file, struct stat *sbp)
-{
-	struct stat sb, sb2;
-	int fd, randint;
-	char randchar;
-
-	fd = -1;
-	if (sbp == NULL) {
-		if (lstat(file, &sb))
-			goto err;
-		sbp = &sb;
-	}
-	if (!S_ISREG(sbp->st_mode))
-		return 0;
-
-	/* flags to try to defeat hidden caching by forcing seeks */
-	if ((fd = open(file, O_RDWR|O_SYNC|O_RSYNC|O_NOFOLLOW, 0)) == -1)
-		goto err;
-
-	if (fstat(fd, &sb2)) {
-		goto err;
-	}
-
-	if (sb2.st_dev != sbp->st_dev || sb2.st_ino != sbp->st_ino ||
-	    !S_ISREG(sb2.st_mode)) {
-		errno = EPERM;
-		goto err;
-	}
-
-#define RAND_BYTES	1
-#define THIS_BYTE	0
-
-#define	WRITE_PASS(mode, byte) do {					\
-	off_t len;							\
-	size_t wlen, i;							\
-	char buf[8 * 1024];						\
-									\
-	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))			\
-		goto err;						\
-									\
-	if (mode == THIS_BYTE)						\
-		memset(buf, byte, sizeof(buf));				\
-	for (len = sbp->st_size; len > 0; len -= wlen) {		\
-		if (mode == RAND_BYTES) {				\
-			for (i = 0; i < sizeof(buf); 			\
-			    i+= sizeof(u_int32_t))			\
-				*(int *)(buf + i) = arc4random();	\
-		}							\
-		wlen = len < (off_t)sizeof(buf) ? (size_t)len : sizeof(buf); \
-		if ((size_t)write(fd, buf, wlen) != wlen)		\
-			goto err;					\
-	}								\
-	sync();		/* another poke at hidden caches */		\
-} while (/* CONSTCOND */ 0)
-
-#define READ_PASS(byte) do {						\
-	off_t len;							\
-	size_t rlen;							\
-	char pattern[8 * 1024];						\
-	char buf[8 * 1024];						\
-									\
-	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))			\
-		goto err;						\
-									\
-	memset(pattern, byte, sizeof(pattern));				\
-	for(len = sbp->st_size; len > 0; len -= rlen) {			\
-		rlen = len < (off_t)sizeof(buf) ? (size_t)len : sizeof(buf); \
-		if((size_t)read(fd, buf, rlen) != rlen)			\
-			goto err;					\
-		if(memcmp(buf, pattern, rlen))				\
-			goto err;					\
-	}								\
-	sync();		/* another poke at hidden caches */		\
-} while (/* CONSTCOND */ 0)
-
-	/*
-	 * DSS sanitization matrix "clear" for magnetic disks: 
-	 * option 'c' "Overwrite all addressable locations with a single 
-	 * character."
-	 */
-	randint = arc4random();
-	randchar = *(char *)&randint;
-	WRITE_PASS(THIS_BYTE, randchar);
-
-	/*
-	 * DSS sanitization matrix "sanitize" for magnetic disks: 
-	 * option 'd', sub 2 "Overwrite all addressable locations with a
-	 * character, then its complement.  Verify "complement" character
-	 * was written successfully to all addressable locations, then
-	 * overwrite all addressable locations with random characters; or
-	 * verify third overwrite of random characters."  The rest of the
-	 * text in d-sub-2 specifies requirements for overwriting spared
-	 * sectors; we cannot conform to it when erasing only a file, thus
-	 * we do not conform to the standard.
-	 */
-
-	/* 1. "a character" */
-	WRITE_PASS(THIS_BYTE, 0xff);
-
-	/* 2. "its complement" */
-	WRITE_PASS(THIS_BYTE, 0x00);
-
-	/* 3. "Verify 'complement' character" */
-	READ_PASS(0x00);
-
-	/* 4. "overwrite all addressable locations with random characters" */
-
-	WRITE_PASS(RAND_BYTES, 0x00);
-
-	/*
-	 * As the file might be huge, and we note that this revision of
-	 * the matrix says "random characters", not "a random character"
-	 * as the original did, we do not verify the random-character
-	 * write; the "or" in the standard allows this.
-	 */
-
-	if (close(fd) == -1) {
-		fd = -1;
-		goto err;
-	}
-
-	return 0;
-
-err:	eval = 1;
-	warn("%s", file);
-	if (fd != -1)
-		close(fd);
-	return 1;
-}
-
-static int
-check(char *path, char *name, struct stat *sp)
-{
-	int ch, first;
-	char modep[15];
-
-	/* Check -i first. */
-	if (iflag)
-		(void)fprintf(stderr, "remove '%s'? ", path);
-	else {
-		/*
-		 * If it's not a symbolic link and it's unwritable and we're
-		 * talking to a terminal, ask.  Symbolic links are excluded
-		 * because their permissions are meaningless.  Check stdin_ok
-		 * first because we may not have stat'ed the file.
-		 */
-		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
-		    !(access(name, W_OK) && (errno != ETXTBSY)))
-			return (1);
-		strmode(sp->st_mode, modep);
-		if (Pflag) {
-			warnx(
-			    "%s: -P was specified but file could not"
-			    " be overwritten", path);
-			return 0;
-		}
-		(void)fprintf(stderr, "override %s%s%s:%s for '%s'? ",
-		    modep + 1, modep[9] == ' ' ? "" : " ",
-		    user_from_uid(sp->st_uid, 0),
-		    group_from_gid(sp->st_gid, 0), path);
-	}
-	(void)fflush(stderr);
-
-	first = ch = getchar();
-	while (ch != '\n' && ch != EOF)
-		ch = getchar();
-	return (first == 'y' || first == 'Y');
-}
-
-/*
- * POSIX.2 requires that if "." or ".." are specified as the basename
- * portion of an operand, a diagnostic message be written to standard
- * error and nothing more be done with such operands.
- *
- * Since POSIX.2 defines basename as the final portion of a path after
- * trailing slashes have been removed, we'll remove them here.
- */
-#define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
-static void
-checkdot(char **argv)
-{
-	char *p, **save, **t;
-	int complained;
-
-	complained = 0;
-	for (t = argv; *t;) {
-		/* strip trailing slashes */
-		p = strrchr(*t, '\0');
-		while (--p > *t && *p == '/')
-			*p = '\0';
-
-		/* extract basename */
-		if ((p = strrchr(*t, '/')) != NULL)
-			++p;
-		else
-			p = *t;
-
-		if (ISDOT(p)) {
-			if (!complained++)
-				warnx("\".\" and \"..\" may not be removed");
-			eval = 1;
-			for (save = t; (t[0] = t[1]) != NULL; ++t)
-				continue;
-			t = save;
-		} else
-			++t;
-	}
-}
-
-static void
-usage(void)
-{
-
-	(void)fprintf(stderr, "usage: %s [-f|-i] [-dPRrvWx] file ...\n",
-	    getprogname());
-	exit(1);
-	/* NOTREACHED */
-}
-
-static void
-progress(int sig __unused)
-{
-	
-	pinfo++;
-}
diff --git a/toolbox/upstream-netbsd/bin/rmdir/rmdir.c b/toolbox/upstream-netbsd/bin/rmdir/rmdir.c
deleted file mode 100644
index 03261ce..0000000
--- a/toolbox/upstream-netbsd/bin/rmdir/rmdir.c
+++ /dev/null
@@ -1,121 +0,0 @@
-/* $NetBSD: rmdir.c,v 1.26 2011/08/29 14:49:38 joerg Exp $ */
-
-/*-
- * Copyright (c) 1992, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1992, 1993, 1994\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)rmdir.c	8.3 (Berkeley) 4/2/94";
-#else
-__RCSID("$NetBSD: rmdir.c,v 1.26 2011/08/29 14:49:38 joerg Exp $");
-#endif
-#endif /* not lint */
-
-#include <sys/param.h>
-
-#include <err.h>
-#include <locale.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-static int	rm_path(char *);
-__dead static void	usage(void);
-
-int
-main(int argc, char *argv[])
-{
-	int ch, errors, pflag;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	pflag = 0;
-	while ((ch = getopt(argc, argv, "p")) != -1)
-		switch(ch) {
-		case 'p':
-			pflag = 1;
-			break;
-		case '?':
-		default:
-			usage();
-		}
-	argc -= optind;
-	argv += optind;
-
-	if (argc == 0)
-		usage();
-
-	for (errors = 0; *argv; argv++) {
-		/* We rely on the kernel to ignore trailing '/' characters. */
-		if (rmdir(*argv) < 0) {
-			warn("%s", *argv);
-			errors = 1;
-		} else if (pflag)
-			errors |= rm_path(*argv);
-	}
-
-	exit(errors);
-	/* NOTREACHED */
-}
-
-static int
-rm_path(char *path)
-{
-	char *p;
-
-	while ((p = strrchr(path, '/')) != NULL) {
-		*p = 0;
-		if (p[1] == 0)
-			/* Ignore trailing '/' on deleted name */
-			continue;
-
-		if (rmdir(path) < 0) {
-			warn("%s", path);
-			return (1);
-		}
-	}
-
-	return (0);
-}
-
-static void
-usage(void)
-{
-	(void)fprintf(stderr, "usage: %s [-p] directory ...\n", getprogname());
-	exit(1);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/bin/sleep/sleep.c b/toolbox/upstream-netbsd/bin/sleep/sleep.c
deleted file mode 100644
index 4349af4..0000000
--- a/toolbox/upstream-netbsd/bin/sleep/sleep.c
+++ /dev/null
@@ -1,159 +0,0 @@
-/* $NetBSD: sleep.c,v 1.24 2011/08/29 14:51:19 joerg Exp $ */
-
-/*
- * Copyright (c) 1988, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1988, 1993, 1994\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)sleep.c	8.3 (Berkeley) 4/2/94";
-#else
-__RCSID("$NetBSD: sleep.c,v 1.24 2011/08/29 14:51:19 joerg Exp $");
-#endif
-#endif /* not lint */
-
-#include <ctype.h>
-#include <err.h>
-#include <locale.h>
-#include <math.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-#include <unistd.h>
-
-__dead static void alarmhandle(int);
-__dead static void usage(void);
-
-static volatile sig_atomic_t report_requested;
-static void
-report_request(int signo __unused)
-{
-
-	report_requested = 1;
-}
-
-int
-main(int argc, char *argv[])
-{
-	char *arg, *temp;
-	double fval, ival, val;
-	struct timespec ntime;
-	time_t original;
-	int ch, fracflag, rv;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	(void)signal(SIGALRM, alarmhandle);
-
-	while ((ch = getopt(argc, argv, "")) != -1)
-		switch(ch) {
-		default:
-			usage();
-		}
-	argc -= optind;
-	argv += optind;
-
-	if (argc != 1)
-		usage();
-
-	/*
-	 * Okay, why not just use atof for everything? Why bother
-	 * checking if there is a fraction in use? Because the old
-	 * sleep handled the full range of integers, that's why, and a
-	 * double can't handle a large long. This is fairly useless
-	 * given how large a number a double can hold on most
-	 * machines, but now we won't ever have trouble. If you want
-	 * 1000000000.9 seconds of sleep, well, that's your
-	 * problem. Why use an isdigit() check instead of checking for
-	 * a period? Because doing it this way means locales will be
-	 * handled transparently by the atof code.
-	 */
-	fracflag = 0;
-	arg = *argv;
-	for (temp = arg; *temp != '\0'; temp++)
-		if (!isdigit((unsigned char)*temp))
-			fracflag++;
-
-	if (fracflag) {
-		val = atof(arg);
-		if (val <= 0)
-			usage();
-		ival = floor(val);
-		fval = (1000000000 * (val-ival));
-		ntime.tv_sec = ival;
-		ntime.tv_nsec = fval;
-	}
-	else {
-		ntime.tv_sec = atol(arg);
-		if (ntime.tv_sec <= 0)
-			return EXIT_SUCCESS;
-		ntime.tv_nsec = 0;
-	}
-
-	original = ntime.tv_sec;
-	signal(SIGINFO, report_request);
-	while ((rv = nanosleep(&ntime, &ntime)) != 0) {
-		if (report_requested) {
-		/* Reporting does not bother with nanoseconds. */
-			warnx("about %d second(s) left out of the original %d",
-			(int)ntime.tv_sec, (int)original);
-			report_requested = 0;
-		} else
-			break;
-	}
-
-	if (rv == -1)
-		err(EXIT_FAILURE, "nanosleep failed");
-
-	return EXIT_SUCCESS;
-	/* NOTREACHED */
-}
-
-static void
-usage(void)
-{
-	(void)fprintf(stderr, "usage: %s seconds\n", getprogname());
-	exit(EXIT_FAILURE);
-	/* NOTREACHED */
-}
-
-/* ARGSUSED */
-static void
-alarmhandle(int i)
-{
-	_exit(EXIT_SUCCESS);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/bin/sync/sync.c b/toolbox/upstream-netbsd/bin/sync/sync.c
deleted file mode 100644
index 2b9c367..0000000
--- a/toolbox/upstream-netbsd/bin/sync/sync.c
+++ /dev/null
@@ -1,59 +0,0 @@
-/* $NetBSD: sync.c,v 1.13 2008/07/20 00:52:40 lukem Exp $ */
-
-/*
- * Copyright (c) 1987, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1987, 1993\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)sync.c	8.1 (Berkeley) 5/31/93";
-#else
-__RCSID("$NetBSD: sync.c,v 1.13 2008/07/20 00:52:40 lukem Exp $");
-#endif
-#endif /* not lint */
-
-#include <stdlib.h>
-#include <unistd.h>
-
-int main(int, char *[]);
-
-/* ARGSUSED */
-int
-main(int argc, char *argv[])
-{
-	setprogname(argv[0]);
-	sync();
-	exit(0);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c b/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c
deleted file mode 100644
index e15384f..0000000
--- a/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c
+++ /dev/null
@@ -1,102 +0,0 @@
-/*	$NetBSD: printenv.c,v 1.12 2011/09/06 18:26:55 joerg Exp $	*/
-
-/*
- * Copyright (c) 1987, 1993
- *    The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. 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 distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS 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 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
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1987, 1993\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-/*static char sccsid[] = "from: @(#)printenv.c	8.2 (Berkeley) 5/4/95";*/
-__RCSID("$NetBSD: printenv.c,v 1.12 2011/09/06 18:26:55 joerg Exp $");
-#endif /* not lint */
-
-#include <sys/types.h>
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <err.h>
-
-__dead static void usage(void);
-
-/*
- * printenv
- *
- * Bill Joy, UCB
- * February, 1979
- */
-int
-main(int argc, char *argv[])
-{
-	extern char **environ;
-	char *cp, **ep;
-	size_t len;
-	int ch;
-
-	while ((ch = getopt(argc, argv, "")) != -1)
-		switch(ch) {
-		case '?':
-		default:
-			usage();
-		}
-	argc -= optind;
-	argv += optind;
-
-	if (argc == 0) {
-		for (ep = environ; *ep; ep++)
-			(void)printf("%s\n", *ep);
-		exit(0);
-	}
-	if (argc != 1)
-		usage();
-	if (strchr(*argv, '=') != NULL)
-		errx(1, "Invalid environment variable %s", *argv);
-	len = strlen(*argv);
-	for (ep = environ; *ep; ep++)
-		if (!memcmp(*ep, *argv, len)) {
-			cp = *ep + len;
-			if (!*cp || *cp == '=') {
-				(void)printf("%s\n", *cp ? cp + 1 : cp);
-				exit(0);
-			}
-		}
-	exit(1);
-}
-
-static void
-usage(void)
-{
-	(void)fprintf(stderr, "Usage: printenv [name]\n");
-	exit(1);
-}
diff --git a/toolbox/uptime.c b/toolbox/uptime.c
index 3fb4606..2dd8084 100644
--- a/toolbox/uptime.c
+++ b/toolbox/uptime.c
@@ -36,7 +36,7 @@
 #include <fcntl.h>
 #include <stdio.h>
 #include <time.h>
-
+#include <unistd.h>
 
 static void format_time(int time, char* buffer) {
     int seconds, minutes, hours, days;
diff --git a/toolbox/vmstat.c b/toolbox/vmstat.c
deleted file mode 100644
index 4086ed0..0000000
--- a/toolbox/vmstat.c
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (c) 2008, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    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 
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * 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 
- * 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
- * SUCH DAMAGE.
- */
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/param.h>
-#include <unistd.h>
-
-struct state {
-    long procs_r;
-    long procs_b;
-
-    long mem_free;
-    long mem_mapped;
-    long mem_anon;
-    long mem_slab;
-
-    long sys_in;
-    long sys_cs;
-    long sys_flt;
-
-    long cpu_us;
-    long cpu_ni;
-    long cpu_sy;
-    long cpu_id;
-    long cpu_wa;
-    long cpu_ir;
-    long cpu_si;
-};
-
-#define MAX_LINE 256
-
-char line[MAX_LINE];
-
-static void read_state(struct state *s);
-static int read_meminfo(struct state *s);
-static int read_stat(struct state *s);
-static int read_vmstat(struct state *s);
-static void print_header(void);
-static void print_line(struct state *old, struct state *new);
-static void usage(char *cmd);
-
-int vmstat_main(int argc, char *argv[]) {
-    struct state s[2];
-    int iterations, delay, header_interval;
-    int toggle, count;
-    int i;
-
-    iterations = -1;
-    delay = 1;
-    header_interval = 20;
-
-    for (i = 1; i < argc; i++) {
-        if (!strcmp(argv[i], "-n")) { 
-            if (i >= argc - 1) {
-                fprintf(stderr, "Option -n requires an argument.\n");
-                exit(EXIT_FAILURE);
-            }
-            iterations = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-d")) {
-            if (i >= argc - 1) {
-                fprintf(stderr, "Option -d requires an argument.\n");
-                exit(EXIT_FAILURE);
-            }
-            delay = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-r")) {
-            if (i >= argc - 1) {
-                fprintf(stderr, "Option -r requires an argument.\n");
-                exit(EXIT_FAILURE);
-            }
-            header_interval = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-h")) {
-            usage(argv[0]);
-            exit(EXIT_SUCCESS);
-        }
-        fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
-        usage(argv[0]);
-	exit(EXIT_FAILURE);
-    }
-
-    toggle = 0;
-    count = 0;
-
-    if (!header_interval)
-        print_header();
-    read_state(&s[1 - toggle]);
-    while ((iterations < 0) || (iterations-- > 0)) {
-        sleep(delay);
-        read_state(&s[toggle]);
-        if (header_interval) {
-            if (count == 0)
-                print_header();
-            count = (count + 1) % header_interval;
-        }
-        print_line(&s[1 - toggle], &s[toggle]);
-        toggle = 1 - toggle;
-    }
-
-    return 0;
-}
-
-static void read_state(struct state *s) {
-    int error;
-
-    error = read_meminfo(s);
-    if (error) {
-        fprintf(stderr, "vmstat: could not read /proc/meminfo: %s\n", strerror(error));
-        exit(EXIT_FAILURE);
-    }
-
-    error = read_stat(s);
-    if (error) {
-        fprintf(stderr, "vmstat: could not read /proc/stat: %s\n", strerror(error));
-        exit(EXIT_FAILURE);
-    }
-
-    error = read_vmstat(s);
-    if (error) {
-        fprintf(stderr, "vmstat: could not read /proc/vmstat: %s\n", strerror(error));
-        exit(EXIT_FAILURE);
-    }
-}
-
-static int read_meminfo(struct state *s) {
-    FILE *f;
-
-    f = fopen("/proc/meminfo", "r");
-    if (!f) return errno;
-
-    while (fgets(line, MAX_LINE, f)) {
-        sscanf(line, "MemFree: %ld kB", &s->mem_free);
-        sscanf(line, "AnonPages: %ld kB", &s->mem_anon);
-        sscanf(line, "Mapped: %ld kB", &s->mem_mapped);
-        sscanf(line, "Slab: %ld kB", &s->mem_slab);
-    }
-
-    fclose(f);
-
-    return 0;
-}
-
-static int read_stat(struct state *s) {
-    FILE *f;
-
-    f = fopen("/proc/stat", "r");
-    if (!f) return errno;
-
-    while (fgets(line, MAX_LINE, f)) {
-        if (!strncmp(line, "cpu ", 4)) {
-            sscanf(line, "cpu  %ld %ld %ld %ld %ld %ld %ld",
-                &s->cpu_us, &s->cpu_ni, &s->cpu_sy, &s->cpu_id, &s->cpu_wa,
-                &s->cpu_ir, &s->cpu_si);
-        }
-        sscanf(line, "intr %ld", &s->sys_in);
-        sscanf(line, "ctxt %ld", &s->sys_cs);
-        sscanf(line, "procs_running %ld", &s->procs_r);
-        sscanf(line, "procs_blocked %ld", &s->procs_b);
-    }
-
-    fclose(f);
-
-    return 0;
-}
-
-static int read_vmstat(struct state *s) {
-    FILE *f;
-
-    f = fopen("/proc/vmstat", "r");
-    if (!f) return errno;
-
-    while (fgets(line, MAX_LINE, f)) {
-        sscanf(line, "pgmajfault %ld", &s->sys_flt);
-    }
-
-    fclose(f);
-
-    return 0;
-}
-
-static void print_header(void) {
-    printf("%-5s  %-27s  %-14s  %-17s\n", "procs", "memory", "system", "cpu");
-    printf("%2s %2s  %6s %6s %6s %6s  %4s %4s %4s  %2s %2s %2s %2s %2s %2s\n", "r", "b", "free", "mapped", "anon", "slab", "in", "cs", "flt", "us", "ni", "sy", "id", "wa", "ir");
-}
-
-/* Jiffies to percent conversion */
-#define JP(jif) ((jif) * 100 / (HZ))
-#define NORM(var) ((var) = (((var) > 99) ? (99) : (var)))
-
-static void print_line(struct state *old, struct state *new) {
-    int us, ni, sy, id, wa, ir;
-    us = JP(new->cpu_us - old->cpu_us); NORM(us);
-    ni = JP(new->cpu_ni - old->cpu_ni); NORM(ni);
-    sy = JP(new->cpu_sy - old->cpu_sy); NORM(sy);
-    id = JP(new->cpu_id - old->cpu_id); NORM(id);
-    wa = JP(new->cpu_wa - old->cpu_wa); NORM(wa);
-    ir = JP(new->cpu_ir - old->cpu_ir); NORM(ir);
-    printf("%2ld %2ld  %6ld %6ld %6ld %6ld  %4ld %4ld %4ld  %2d %2d %2d %2d %2d %2d\n",
-        new->procs_r ? (new->procs_r - 1) : 0, new->procs_b,
-        new->mem_free, new->mem_mapped, new->mem_anon, new->mem_slab,
-        new->sys_in - old->sys_in, new->sys_cs - old->sys_cs, new->sys_flt - old->sys_flt,
-        us, ni, sy, id, wa, ir);
-}
-
-static void usage(char *cmd) {
-    fprintf(stderr, "Usage: %s [ -h ] [ -n iterations ] [ -d delay ] [ -r header_repeat ]\n"
-                    "    -n iterations     How many rows of data to print.\n"
-                    "    -d delay          How long to sleep between rows.\n"
-                    "    -r header_repeat  How many rows to print before repeating\n"
-                    "                      the header.  Zero means never repeat.\n"
-                    "    -h                Displays this help screen.\n",
-        cmd);
-}