am a5a4e9e0: sdcard: mount sdcard with the noexec option

* commit 'a5a4e9e0cad383f0c14dbe92a60b7d8150ae6b1f':
  sdcard: mount sdcard with the noexec option
diff --git a/adb/Android.mk b/adb/Android.mk
index b70c153..24cbce0 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,7 +63,6 @@
 	file_sync_client.c \
 	$(EXTRA_SRCS) \
 	$(USB_SRCS) \
-	usb_vendors.c
 
 LOCAL_C_INCLUDES += external/openssl/include
 
@@ -82,6 +82,7 @@
 	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))
@@ -114,8 +115,13 @@
 	disable_verity_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 +146,8 @@
 	libselinux \
 	libext4_utils_static
 
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
 include $(BUILD_EXECUTABLE)
 
 
@@ -162,7 +170,6 @@
 	file_sync_client.c \
 	get_my_path_linux.c \
 	usb_linux.c \
-	usb_vendors.c \
 	fdevent.c
 
 LOCAL_CFLAGS := \
@@ -182,5 +189,6 @@
 
 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..f584c57 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -376,7 +376,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/commandline.c b/adb/commandline.c
index 7704878..903b818 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
 
@@ -239,7 +239,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 +324,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 +355,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 +400,7 @@
             case '.':
                 if(state == 2) {
                     fprintf(stderr,"\n* disconnect *\n");
-#ifdef HAVE_TERMIO_H
                     stdin_raw_restore(fdi);
-#endif
                     exit(0);
                 }
             default:
@@ -423,14 +432,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 +738,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 +801,7 @@
         adb_close(fd);
         return 0;
     }
-#endif /* !HAVE_WIN32_PROC */
+#endif /* !defined(_WIN32) */
 }
 
 static int send_shellcommand(transport_type transport, char* serial, char* buf)
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/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/services.c b/adb/services.c
index 21b08dc..703aec8 100644
--- a/adb/services.c
+++ b/adb/services.c
@@ -202,10 +202,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,16 +251,16 @@
     } 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];
@@ -295,7 +295,7 @@
         adb_close(sv[1]);
         return sv[0];
     }
-#endif /* !HAVE_WIN32_PROC */
+#endif /* !defined(_WIN32) */
 }
 #endif  /* !ABD_HOST */
 
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_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..1b8b98d 100644
--- a/debuggerd/Android.mk
+++ b/debuggerd/Android.mk
@@ -28,8 +28,6 @@
     liblog \
     libselinux \
 
-include external/stlport/libstlport.mk
-
 LOCAL_MODULE := debuggerd
 LOCAL_MODULE_STEM_32 := debuggerd
 LOCAL_MODULE_STEM_64 := debuggerd64
diff --git a/debuggerd/crasher.c b/debuggerd/crasher.c
index d315ee5..d0c3912 100644
--- a/debuggerd/crasher.c
+++ b/debuggerd/crasher.c
@@ -59,7 +59,7 @@
     for(;;) {
         usleep(250*1000);
         write(2, &c, 1);
-        if(c == 'C') *((unsigned*) 0) = 42;
+        if(c == 'C') *((volatile unsigned*) 0) = 42;
     }
     return NULL;
 }
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/fastboot/Android.mk b/fastboot/Android.mk
index e11691f..f03bbea 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)
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..bccac68 100644
--- a/fastbootd/Android.mk
+++ b/fastbootd/Android.mk
@@ -42,7 +42,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 := \
diff --git a/fastbootd/commands/partitions.c b/fastbootd/commands/partitions.c
index 74232e6..f2c9da7 100644
--- a/fastbootd/commands/partitions.c
+++ b/fastbootd/commands/partitions.c
@@ -547,7 +547,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/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..51555a1 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) {
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/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/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/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/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index 5d9c3ea..b2f91a5 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 */
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/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/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/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..aaf951b 100644
--- a/include/utils/Unicode.h
+++ b/include/utils/Unicode.h
@@ -24,8 +24,8 @@
 
 // Definitions exist in C++11
 #if defined __cplusplus && __cplusplus < 201103L
-typedef uint32_t char32_t;
-typedef uint16_t char16_t;
+typedef unsigned int   char32_t;
+typedef unsigned short char16_t;
 #endif
 
 // Standard string functions on char16_t strings.
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..72c2272 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)
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..7f4daa7 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;
             }
 
diff --git a/init/devices.c b/init/devices.c
index 1012fee..a95111a 100644
--- a/init/devices.c
+++ b/init/devices.c
@@ -458,7 +458,7 @@
 
     /* skip "/devices/platform/<driver>" */
     parent = strchr(uevent->path + pdev->path_len, '/');
-    if (!*parent)
+    if (!parent)
         goto err;
 
     if (!strncmp(parent, "/usb", 4)) {
@@ -938,7 +938,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));
     }
 }
 
diff --git a/init/init.c b/init/init.c
index bd1db7a..99474e6 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];
@@ -1147,11 +1148,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/property_service.c b/init/property_service.c
index 91ef251..44658c5 100644
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -448,10 +448,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) {
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.c b/init/util.c
index 0f69e1c..e1a3ee3 100644
--- a/init/util.c
+++ b/init/util.c
@@ -329,9 +329,9 @@
     if (!s)
         return;
 
-    for (; *s; s++) {
+    while (*s) {
         s += strspn(s, accept);
-        if (*s) *s = '_';
+        if (*s) *s++ = '_';
     }
 }
 
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..f2f71f9 100755
--- a/libbacktrace/Android.mk
+++ b/libbacktrace/Android.mk
@@ -74,58 +74,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 +145,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/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/sched_policy.c b/libcutils/sched_policy.c
index 493511e..e07bbbd 100644
--- a/libcutils/sched_policy.c
+++ b/libcutils/sched_policy.c
@@ -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/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/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..b8d87bb 100644
--- a/liblog/fake_log_device.c
+++ b/liblog/fake_log_device.c
@@ -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..209a9da 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);
diff --git a/liblog/logprint.c b/liblog/logprint.c
index 08e830a..9b5a543 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;
@@ -687,7 +726,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 +737,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 +749,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 +760,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/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/libpixelflinger/Android.mk b/libpixelflinger/Android.mk
index 484cf50..da9829d 100644
--- a/libpixelflinger/Android.mk
+++ b/libpixelflinger/Android.mk
@@ -44,11 +44,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 +69,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 +86,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/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..fd96f7e 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)
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..4b09f24 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -20,6 +20,7 @@
 #include <assert.h>
 #include <dirent.h>
 #include <fcntl.h>
+#include <inttypes.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -100,7 +101,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 +252,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 +266,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 +280,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/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..e738c15 100644
--- a/libutils/Android.mk
+++ b/libutils/Android.mk
@@ -67,6 +67,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)
@@ -91,8 +94,7 @@
 LOCAL_CFLAGS += -Werror
 
 LOCAL_C_INCLUDES += \
-		bionic/libc \
-		external/zlib
+	external/zlib
 
 LOCAL_STATIC_LIBRARIES := \
 	libcutils
@@ -102,8 +104,6 @@
         liblog \
         libdl
 
-include external/stlport/libstlport.mk
-
 LOCAL_MODULE:= libutils
 include $(BUILD_STATIC_LIBRARY)
 
@@ -119,8 +119,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/Threads.cpp b/libutils/Threads.cpp
index b09d510..9bcd063 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>
@@ -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..d9334f7 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
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..9bc6e61 100644
--- a/libziparchive/Android.mk
+++ b/libziparchive/Android.mk
@@ -14,31 +14,27 @@
 # limitations under the License.
 
 LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
 
-source_files := \
-	zip_archive.h \
-	zip_archive.cc
-
+source_files := zip_archive.cc
 includes := external/zlib
 
+include $(CLEAR_VARS)
+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_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE := libziparchive
 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 +45,39 @@
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+LOCAL_MODULE := libziparchive
+LOCAL_CPP_EXTENSION := .cc
+LOCAL_SRC_FILES := ${source_files}
+LOCAL_C_INCLUDES += ${includes}
+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_CFLAGS := -Werror
 LOCAL_SRC_FILES := zip_archive_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
+    -Werror \
+    -Wno-unnamed-type-template-args
 LOCAL_SRC_FILES := zip_archive_test.cc
-LOCAL_STATIC_LIBRARIES := libziparchive-host \
-	libz \
-	libgtest_host \
-	libgtest_main_host \
-	liblog \
-	libutils
+LOCAL_SHARED_LIBRARIES := libziparchive-host liblog
+LOCAL_STATIC_LIBRARIES := \
+    libz \
+    libutils
 include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index 87dac0e..40416a0 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -385,8 +385,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 +403,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 +425,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 +434,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,7 +640,7 @@
     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) {
@@ -647,8 +649,11 @@
     }
 
     /* 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/logcat/logcat.cpp b/logcat/logcat.cpp
index 858e56c..6306f5c 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");
 
 
 
@@ -543,7 +549,9 @@
                     exit(-1);
                 }
 
-                hasSetLogFormat = 1;
+                if (strcmp("color", optarg)) { // exception for modifiers
+                    hasSetLogFormat = 1;
+                }
             break;
 
             case 'Q':
@@ -653,11 +661,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..b1412ff 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,60 @@
     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 total[] = "total ";
+            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 +600,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/LogBuffer.cpp b/logd/LogBuffer.cpp
index 8c1c344..1c74ba5 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) {
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/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/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/sdcard/sdcard.c b/sdcard/sdcard.c
index 247ddd0..2318978 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>
@@ -390,12 +391,12 @@
     attr->ino = node->nid;
     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;
 
@@ -1268,6 +1269,7 @@
         return -errno;
     }
     out.size = res;
+    out.padding = 0;
     fuse_reply(fuse, hdr->unique, &out, sizeof(out));
     return NO_STATUS;
 }
@@ -1427,17 +1429,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..c1b9f68 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -141,7 +141,6 @@
 OUR_TOOLS := \
     chcon \
     chmod \
-    clear \
     cmp \
     date \
     df \
@@ -198,10 +197,6 @@
     watchprops \
     wipe \
 
-ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
-OUR_TOOLS += r
-endif
-
 ALL_TOOLS = $(BSD_TOOLS) $(OUR_TOOLS)
 
 LOCAL_SRC_FILES := \
@@ -247,8 +242,7 @@
 $(TOOLS_H):
 	$(transform-generated-source)
 
-# Make #!/system/bin/toolbox launchers for each tool.
-#
+# Make symbolic link launchers for each tool.
 SYMLINKS := $(addprefix $(TARGET_OUT)/bin/,$(ALL_TOOLS))
 $(SYMLINKS): TOOLBOX_BINARY := $(LOCAL_MODULE)
 $(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk
@@ -263,3 +257,13 @@
 # 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/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/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/ioctl.c b/toolbox/ioctl.c
index fd90812..73539d1 100644
--- a/toolbox/ioctl.c
+++ b/toolbox/ioctl.c
@@ -45,7 +45,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/mkswap.c b/toolbox/mkswap.c
index 0904152..ad66353 100644
--- a/toolbox/mkswap.c
+++ b/toolbox/mkswap.c
@@ -1,11 +1,13 @@
+#include <fcntl.h>
+#include <linux/fs.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <unistd.h>
+#include <sys/stat.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 */
+/* This is not in a uapi header. */
 struct linux_swap_header {
     char            bootbits[1024]; /* Space for disklabel etc. */
     uint32_t        version;
@@ -23,71 +25,67 @@
 
 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;
+        return EXIT_FAILURE;
     }
 
-    fd = open(argv[1], O_WRONLY);
+    int fd = open(argv[1], O_RDWR);
     if (fd < 0) {
-        err = errno;
-        fprintf(stderr, "Cannot open %s\n", argv[1]);
-        return err;
+        fprintf(stderr, "Cannot open %s: %s\n", argv[1], strerror(errno));
+        return EXIT_FAILURE;
     }
 
-    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;
+    off64_t swap_size;
+    struct stat sb;
+    if (fstat(fd, &sb)) {
+        fprintf(stderr, "Couldn't fstat file: %s\n", strerror(errno));
+        return EXIT_FAILURE;
     }
-    if (lseek(fd, 0, SEEK_SET)) {
-        err = errno;
-        fprintf(stderr, "Can't seek to the beginning of the file\n");
-        goto err;
+    if (S_ISBLK(sb.st_mode)) {
+        if (ioctl(fd, BLKGETSIZE64, &swap_size) < 0) {
+            fprintf(stderr, "Couldn't determine block device size: %s\n", strerror(errno));
+            return EXIT_FAILURE;
+        }
+    } else {
+        swap_size = sb.st_size;
     }
 
+    int pagesize = getpagesize();
+    if (swap_size < MIN_PAGES * pagesize) {
+        fprintf(stderr, "Swap file needs to be at least %d KiB\n", (MIN_PAGES * pagesize) >> 10);
+        return EXIT_FAILURE;
+    }
+
+    struct linux_swap_header sw_hdr;
     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));
+    ssize_t 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;
+        fprintf(stderr, "Failed to write swap header into %s: %s\n", argv[1], strerror(errno));
+        return EXIT_FAILURE;
     }
 
     /* 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;
+        fprintf(stderr, "Failed to seek into %s: %s\n", argv[1], strerror(errno));
+        return EXIT_FAILURE;
     }
 
     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;
+        fprintf(stderr, "Failed to write magic swap header into %s: %s\n", argv[1], strerror(errno));
+        return EXIT_FAILURE;
     }
 
     if (fsync(fd) < 0) {
-        err = errno;
-        fprintf(stderr, "Failed to sync %s\n", argv[1]);
-        goto err;
+        fprintf(stderr, "Failed to sync %s: %s\n", argv[1], strerror(errno));
+        return EXIT_FAILURE;
     }
-err:
+
     close(fd);
-    return err;
+    return EXIT_SUCCESS;
 }
diff --git a/toolbox/notify.c b/toolbox/notify.c
index c983ed5..8ce346c 100644
--- a/toolbox/notify.c
+++ b/toolbox/notify.c
@@ -101,14 +101,17 @@
 			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];
+				char* filename = file_names[event->wd + id_offset];
+				char* alloc_buf = NULL;
 				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);
+					if(asprintf(&alloc_buf, "%s/%s", filename, event->name) < 0) {
+						fprintf(stderr, "asprintf failed, %s\n", strerror(errno));
+						return 1;
+					}
+					filename = alloc_buf;
 				}
 				ffd = open(filename, O_RDONLY);
 				display_name = (verbose >= 2 || event->len == 0) ? filename : event->name;
@@ -132,6 +135,7 @@
 					printf("%s: %s", display_name, buf);
 				}
 				close(ffd);
+				free(alloc_buf);
 			}
 	        if(event_count && --event_count == 0)
 	            return 0;
diff --git a/toolbox/ps.c b/toolbox/ps.c
index 5458f6b..4f001b8 100644
--- a/toolbox/ps.c
+++ b/toolbox/ps.c
@@ -147,7 +147,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..6183677 100644
--- a/toolbox/r.c
+++ b/toolbox/r.c
@@ -18,7 +18,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/sendevent.c b/toolbox/sendevent.c
index 9b813f6..4b5a761 100644
--- a/toolbox/sendevent.c
+++ b/toolbox/sendevent.c
@@ -1,49 +1,11 @@
+#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>
-
-
 
 int sendevent_main(int argc, char *argv[])
 {
diff --git a/toolbox/swapoff.c b/toolbox/swapoff.c
index d8f6a00..477494e 100644
--- a/toolbox/swapoff.c
+++ b/toolbox/swapoff.c
@@ -13,7 +13,7 @@
 
     err = swapoff(argv[1]);
     if (err) {
-        fprintf(stderr, "swapoff failed for %s\n", argv[1]);
+        fprintf(stderr, "swapoff failed for %s: %s\n", argv[1], strerror(errno));
     }
 
     return err;
diff --git a/toolbox/swapon.c b/toolbox/swapon.c
index 150701a..51b4ff1 100644
--- a/toolbox/swapon.c
+++ b/toolbox/swapon.c
@@ -59,7 +59,7 @@
 
     err = swapon(argv[argc - 1], flags);
     if (err) {
-        fprintf(stderr, "swapon failed for %s\n", argv[argc - 1]);
+        fprintf(stderr, "swapon failed for %s: %s\n", argv[argc - 1], strerror(errno));
     }
 
     return err;