am 43329bc1: am 8a387870: Revert "Reload policy after setting up the data partition."

* commit '43329bc1c99c0f5f3670a8aaab39e54df34819a1':
  Revert "Reload policy after setting up the data partition."
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 8611d3b..74ec29d 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -50,3 +50,4 @@
 
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/init.rc)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/init.rc)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/reboot)
diff --git a/adb/Android.mk b/adb/Android.mk
index a803978..36f595b 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -64,7 +64,6 @@
 	file_sync_client.c \
 	$(EXTRA_SRCS) \
 	$(USB_SRCS) \
-	utils.c \
 	usb_vendors.c
 
 LOCAL_C_INCLUDES += external/openssl/include
@@ -116,8 +115,7 @@
 	framebuffer_service.c \
 	remount_service.c \
 	usb_linux_client.c \
-	log_service.c \
-	utils.c
+	log_service.c
 
 LOCAL_CFLAGS := -O2 -g -DADB_HOST=0 -Wall -Wno-unused-parameter
 LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE
@@ -157,7 +155,6 @@
 	file_sync_client.c \
 	get_my_path_linux.c \
 	usb_linux.c \
-	utils.c \
 	usb_vendors.c \
 	fdevent.c
 
diff --git a/adb/SERVICES.TXT b/adb/SERVICES.TXT
index b53bc44..5966686 100644
--- a/adb/SERVICES.TXT
+++ b/adb/SERVICES.TXT
@@ -225,27 +225,6 @@
       If the adbd daemon doesn't have sufficient privileges to open
       the framebuffer device, the connection is simply closed immediately.
 
-dns:<server-name>
-    This service is an exception because it only runs within the ADB server.
-    It is used to implement USB networking, i.e. to provide a network connection
-    to the device through the host machine (note: this is the exact opposite of
-    network tethering).
-
-    It is used to perform a gethostbyname(<address>) on the host and return
-    the corresponding IP address as a 4-byte string.
-
-recover:<size>
-    This service is used to upload a recovery image to the device. <size>
-    must be a number corresponding to the size of the file. The service works
-    by:
-
-       - creating a file named /tmp/update
-       - reading 'size' bytes from the client and writing them to /tmp/update
-       - when everything is read successfully, create a file named /tmp/update.start
-
-    This service can only work when the device is in recovery mode. Otherwise,
-    the /tmp directory doesn't exist and the connection will be closed immediately.
-
 jdwp:<pid>
     Connects to the JDWP thread running in the VM of process <pid>.
 
diff --git a/adb/adb.c b/adb/adb.c
index ec74b49..187f51a 100644
--- a/adb/adb.c
+++ b/adb/adb.c
@@ -1199,7 +1199,7 @@
 #endif
     int i;
     for (i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
-        if ((i == CAP_SETUID) || (i == CAP_SETGID)) {
+        if (i == CAP_SETUID || i == CAP_SETGID) {
             // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
             continue;
         }
@@ -1301,13 +1301,6 @@
     /* don't listen on a port (default 5037) if running in secure mode */
     /* don't run as root if we are running in secure mode */
     if (should_drop_privileges()) {
-        struct __user_cap_header_struct header;
-        struct __user_cap_data_struct cap[2];
-
-        if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
-            exit(1);
-        }
-
         drop_capabilities_bounding_set_if_needed();
 
         /* add extra groups:
@@ -1337,16 +1330,6 @@
             exit(1);
         }
 
-        memset(&header, 0, sizeof(header));
-        memset(cap, 0, sizeof(cap));
-
-        /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
-        header.version = _LINUX_CAPABILITY_VERSION_3;
-        header.pid = 0;
-        cap[CAP_TO_INDEX(CAP_SYS_BOOT)].effective |= CAP_TO_MASK(CAP_SYS_BOOT);
-        cap[CAP_TO_INDEX(CAP_SYS_BOOT)].permitted |= CAP_TO_MASK(CAP_SYS_BOOT);
-        capset(&header, cap);
-
         D("Local port disabled\n");
     } else {
         char local_name[30];
@@ -1404,105 +1387,6 @@
     return 0;
 }
 
-#if ADB_HOST
-void connect_device(char* host, char* buffer, int buffer_size)
-{
-    int port, fd;
-    char* portstr = strchr(host, ':');
-    char hostbuf[100];
-    char serial[100];
-
-    strncpy(hostbuf, host, sizeof(hostbuf) - 1);
-    if (portstr) {
-        if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
-            snprintf(buffer, buffer_size, "bad host name %s", host);
-            return;
-        }
-        // zero terminate the host at the point we found the colon
-        hostbuf[portstr - host] = 0;
-        if (sscanf(portstr + 1, "%d", &port) == 0) {
-            snprintf(buffer, buffer_size, "bad port number %s", portstr);
-            return;
-        }
-    } else {
-        port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
-    }
-
-    snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
-    if (find_transport(serial)) {
-        snprintf(buffer, buffer_size, "already connected to %s", serial);
-        return;
-    }
-
-    fd = socket_network_client(hostbuf, port, SOCK_STREAM);
-    if (fd < 0) {
-        snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
-        return;
-    }
-
-    D("client: connected on remote on fd %d\n", fd);
-    close_on_exec(fd);
-    disable_tcp_nagle(fd);
-    register_socket_transport(fd, serial, port, 0);
-    snprintf(buffer, buffer_size, "connected to %s", serial);
-}
-
-void connect_emulator(char* port_spec, char* buffer, int buffer_size)
-{
-    char* port_separator = strchr(port_spec, ',');
-    if (!port_separator) {
-        snprintf(buffer, buffer_size,
-                "unable to parse '%s' as <console port>,<adb port>",
-                port_spec);
-        return;
-    }
-
-    // Zero-terminate console port and make port_separator point to 2nd port.
-    *port_separator++ = 0;
-    int console_port = strtol(port_spec, NULL, 0);
-    int adb_port = strtol(port_separator, NULL, 0);
-    if (!(console_port > 0 && adb_port > 0)) {
-        *(port_separator - 1) = ',';
-        snprintf(buffer, buffer_size,
-                "Invalid port numbers: Expected positive numbers, got '%s'",
-                port_spec);
-        return;
-    }
-
-    /* Check if the emulator is already known.
-     * Note: There's a small but harmless race condition here: An emulator not
-     * present just yet could be registered by another invocation right
-     * after doing this check here. However, local_connect protects
-     * against double-registration too. From here, a better error message
-     * can be produced. In the case of the race condition, the very specific
-     * error message won't be shown, but the data doesn't get corrupted. */
-    atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
-    if (known_emulator != NULL) {
-        snprintf(buffer, buffer_size,
-                "Emulator on port %d already registered.", adb_port);
-        return;
-    }
-
-    /* Check if more emulators can be registered. Similar unproblematic
-     * race condition as above. */
-    int candidate_slot = get_available_local_transport_index();
-    if (candidate_slot < 0) {
-        snprintf(buffer, buffer_size, "Cannot accept more emulators.");
-        return;
-    }
-
-    /* Preconditions met, try to connect to the emulator. */
-    if (!local_connect_arbitrary_ports(console_port, adb_port)) {
-        snprintf(buffer, buffer_size,
-                "Connected to emulator on ports %d,%d", console_port, adb_port);
-    } else {
-        snprintf(buffer, buffer_size,
-                "Could not connect to emulator on ports %d,%d",
-                console_port, adb_port);
-    }
-}
-#endif
-
 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
 {
     atransport *transport = NULL;
@@ -1563,21 +1447,6 @@
         }
     }
 
-    // add a new TCP transport, device or emulator
-    if (!strncmp(service, "connect:", 8)) {
-        char buffer[4096];
-        char* host = service + 8;
-        if (!strncmp(host, "emu:", 4)) {
-            connect_emulator(host + 4, buffer, sizeof(buffer));
-        } else {
-            connect_device(host, buffer, sizeof(buffer));
-        }
-        // Send response for emulator and device
-        snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
-        writex(reply_fd, buf, strlen(buf));
-        return 0;
-    }
-
     // remove TCP transport
     if (!strncmp(service, "disconnect:", 11)) {
         char buffer[4096];
diff --git a/adb/adb.h b/adb/adb.h
index a01d460..622ca70 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -128,10 +128,7 @@
         */
     void (*close)(asocket *s);
 
-        /* socket-type-specific extradata */
-    void *extra;
-
-    	/* A socket is bound to atransport */
+        /* A socket is bound to atransport */
     atransport *transport;
 };
 
@@ -292,7 +289,7 @@
 void close_usb_devices();
 
 /* cause new transports to be init'd and added to the list */
-void register_socket_transport(int s, const char *serial, int port, int local);
+int register_socket_transport(int s, const char *serial, int port, int local);
 
 /* these should only be used for the "adb disconnect" command */
 void unregister_transport(atransport *t);
diff --git a/adb/adb_auth_client.c b/adb/adb_auth_client.c
index 763b448..f8d7306 100644
--- a/adb/adb_auth_client.c
+++ b/adb/adb_auth_client.c
@@ -25,6 +25,7 @@
 #include "adb_auth.h"
 #include "fdevent.h"
 #include "mincrypt/rsa.h"
+#include "mincrypt/sha.h"
 
 #define TRACE_TAG TRACE_AUTH
 
@@ -149,7 +150,7 @@
 
     list_for_each(item, &key_list) {
         key = node_to_item(item, struct adb_public_key, node);
-        ret = RSA_verify(&key->key, sig, siglen, token);
+        ret = RSA_verify(&key->key, sig, siglen, token, SHA_DIGEST_SIZE);
         if (ret)
             break;
     }
diff --git a/adb/mutex_list.h b/adb/mutex_list.h
index 652dd73..ff72751 100644
--- a/adb/mutex_list.h
+++ b/adb/mutex_list.h
@@ -6,7 +6,6 @@
 #ifndef ADB_MUTEX
 #error ADB_MUTEX not defined when including this file
 #endif
-ADB_MUTEX(dns_lock)
 ADB_MUTEX(socket_list_lock)
 ADB_MUTEX(transport_lock)
 #if ADB_HOST
diff --git a/adb/remount_service.c b/adb/remount_service.c
index 4cb41e7..ad61284 100644
--- a/adb/remount_service.c
+++ b/adb/remount_service.c
@@ -72,6 +72,8 @@
 static int remount_system()
 {
     char *dev;
+    int fd;
+    int OFF = 0;
 
     if (system_ro == 0) {
         return 0;
@@ -82,6 +84,13 @@
     if (!dev)
         return -1;
 
+    fd = unix_open(dev, O_RDONLY);
+    if (fd < 0)
+        return -1;
+
+    ioctl(fd, BLKROSET, &OFF);
+    adb_close(fd);
+
     system_ro = mount(dev, "/system", "none", MS_REMOUNT, NULL);
 
     free(dev);
diff --git a/adb/services.c b/adb/services.c
index 54d21a8..d2d428a 100644
--- a/adb/services.c
+++ b/adb/services.c
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <stddef.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <unistd.h>
@@ -53,59 +54,7 @@
     return 0;
 }
 
-#if ADB_HOST
-ADB_MUTEX_DEFINE( dns_lock );
-
-static void dns_service(int fd, void *cookie)
-{
-    char *hostname = cookie;
-    struct hostent *hp;
-    unsigned zero = 0;
-
-    adb_mutex_lock(&dns_lock);
-    hp = gethostbyname(hostname);
-    free(cookie);
-    if(hp == 0) {
-        writex(fd, &zero, 4);
-    } else {
-        writex(fd, hp->h_addr, 4);
-    }
-    adb_mutex_unlock(&dns_lock);
-    adb_close(fd);
-}
-#else
-extern int recovery_mode;
-
-static void recover_service(int s, void *cookie)
-{
-    unsigned char buf[4096];
-    unsigned count = (unsigned) cookie;
-    int fd;
-
-    fd = adb_creat("/tmp/update", 0644);
-    if(fd < 0) {
-        adb_close(s);
-        return;
-    }
-
-    while(count > 0) {
-        unsigned xfer = (count > 4096) ? 4096 : count;
-        if(readx(s, buf, xfer)) break;
-        if(writex(fd, buf, xfer)) break;
-        count -= xfer;
-    }
-
-    if(count == 0) {
-        writex(s, "OKAY", 4);
-    } else {
-        writex(s, "FAIL", 4);
-    }
-    adb_close(fd);
-    adb_close(s);
-
-    fd = adb_creat("/tmp/update.begin", 0644);
-    adb_close(fd);
-}
+#if !ADB_HOST
 
 void restart_root_service(int fd, void *cookie)
 {
@@ -165,6 +114,7 @@
 void reboot_service(int fd, void *arg)
 {
     char buf[100];
+    char property_val[PROPERTY_VALUE_MAX];
     int pid, ret;
 
     sync();
@@ -182,51 +132,25 @@
         waitpid(pid, &ret, 0);
     }
 
-    ret = android_reboot(ANDROID_RB_RESTART2, 0, (char *) arg);
+    ret = snprintf(property_val, sizeof(property_val), "reboot,%s", (char *) arg);
+    if (ret >= (int) sizeof(property_val)) {
+        snprintf(buf, sizeof(buf), "reboot string too long. length=%d\n", ret);
+        writex(fd, buf, strlen(buf));
+        goto cleanup;
+    }
+
+    ret = property_set(ANDROID_RB_PROPERTY, property_val);
     if (ret < 0) {
-        snprintf(buf, sizeof(buf), "reboot failed: %s\n", strerror(errno));
+        snprintf(buf, sizeof(buf), "reboot failed: %d\n", ret);
         writex(fd, buf, strlen(buf));
     }
+cleanup:
     free(arg);
     adb_close(fd);
 }
 
 #endif
 
-#if 0
-static void echo_service(int fd, void *cookie)
-{
-    char buf[4096];
-    int r;
-    char *p;
-    int c;
-
-    for(;;) {
-        r = adb_read(fd, buf, 4096);
-        if(r == 0) goto done;
-        if(r < 0) {
-            if(errno == EINTR) continue;
-            else goto done;
-        }
-
-        c = r;
-        p = buf;
-        while(c > 0) {
-            r = write(fd, p, c);
-            if(r > 0) {
-                c -= r;
-                p += r;
-                continue;
-            }
-            if((r < 0) && (errno == EINTR)) continue;
-            goto done;
-        }
-    }
-done:
-    close(fd);
-}
-#endif
-
 static int create_service_thread(void (*func)(int, void *), void *cookie)
 {
     stinfo *sti;
@@ -413,9 +337,7 @@
                 disable_tcp_nagle(ret);
         } else {
 #if ADB_HOST
-            adb_mutex_lock(&dns_lock);
             ret = socket_network_client(name + 1, port, SOCK_STREAM);
-            adb_mutex_unlock(&dns_lock);
 #else
             return -1;
 #endif
@@ -434,18 +356,11 @@
         ret = socket_local_client(name + 16,
                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
 #endif
-#if ADB_HOST
-    } else if(!strncmp("dns:", name, 4)){
-        char *n = strdup(name + 4);
-        if(n == 0) return -1;
-        ret = create_service_thread(dns_service, n);
-#else /* !ADB_HOST */
+#if !ADB_HOST
     } else if(!strncmp("dev:", name, 4)) {
         ret = unix_open(name + 4, O_RDWR);
     } else if(!strncmp(name, "framebuffer:", 12)) {
         ret = create_service_thread(framebuffer_service, 0);
-    } else if(recovery_mode && !strncmp(name, "recover:", 8)) {
-        ret = create_service_thread(recover_service, (void*) atoi(name + 8));
     } else if (!strncmp(name, "jdwp:", 5)) {
         ret = create_jdwp_connection_fd(atoi(name+5));
     } else if (!strncmp(name, "log:", 4)) {
@@ -481,10 +396,6 @@
     } else if(!strncmp(name, "usb:", 4)) {
         ret = create_service_thread(restart_usb_service, NULL);
 #endif
-#if 0
-    } else if(!strncmp(name, "echo:", 5)){
-        ret = create_service_thread(echo_service, 0);
-#endif
     }
     if (ret >= 0) {
         close_on_exec(ret);
@@ -519,6 +430,124 @@
     adb_close(fd);
     D("wait_for_state is done\n");
 }
+
+static void connect_device(char* host, char* buffer, int buffer_size)
+{
+    int port, fd;
+    char* portstr = strchr(host, ':');
+    char hostbuf[100];
+    char serial[100];
+    int ret;
+
+    strncpy(hostbuf, host, sizeof(hostbuf) - 1);
+    if (portstr) {
+        if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
+            snprintf(buffer, buffer_size, "bad host name %s", host);
+            return;
+        }
+        // zero terminate the host at the point we found the colon
+        hostbuf[portstr - host] = 0;
+        if (sscanf(portstr + 1, "%d", &port) == 0) {
+            snprintf(buffer, buffer_size, "bad port number %s", portstr);
+            return;
+        }
+    } else {
+        port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
+    }
+
+    snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
+
+    fd = socket_network_client(hostbuf, port, SOCK_STREAM);
+    if (fd < 0) {
+        snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
+        return;
+    }
+
+    D("client: connected on remote on fd %d\n", fd);
+    close_on_exec(fd);
+    disable_tcp_nagle(fd);
+
+    ret = register_socket_transport(fd, serial, port, 0);
+    if (ret < 0) {
+        adb_close(fd);
+        snprintf(buffer, buffer_size, "already connected to %s", serial);
+    } else {
+        snprintf(buffer, buffer_size, "connected to %s", serial);
+    }
+}
+
+void connect_emulator(char* port_spec, char* buffer, int buffer_size)
+{
+    char* port_separator = strchr(port_spec, ',');
+    if (!port_separator) {
+        snprintf(buffer, buffer_size,
+                "unable to parse '%s' as <console port>,<adb port>",
+                port_spec);
+        return;
+    }
+
+    // Zero-terminate console port and make port_separator point to 2nd port.
+    *port_separator++ = 0;
+    int console_port = strtol(port_spec, NULL, 0);
+    int adb_port = strtol(port_separator, NULL, 0);
+    if (!(console_port > 0 && adb_port > 0)) {
+        *(port_separator - 1) = ',';
+        snprintf(buffer, buffer_size,
+                "Invalid port numbers: Expected positive numbers, got '%s'",
+                port_spec);
+        return;
+    }
+
+    /* Check if the emulator is already known.
+     * Note: There's a small but harmless race condition here: An emulator not
+     * present just yet could be registered by another invocation right
+     * after doing this check here. However, local_connect protects
+     * against double-registration too. From here, a better error message
+     * can be produced. In the case of the race condition, the very specific
+     * error message won't be shown, but the data doesn't get corrupted. */
+    atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
+    if (known_emulator != NULL) {
+        snprintf(buffer, buffer_size,
+                "Emulator on port %d already registered.", adb_port);
+        return;
+    }
+
+    /* Check if more emulators can be registered. Similar unproblematic
+     * race condition as above. */
+    int candidate_slot = get_available_local_transport_index();
+    if (candidate_slot < 0) {
+        snprintf(buffer, buffer_size, "Cannot accept more emulators.");
+        return;
+    }
+
+    /* Preconditions met, try to connect to the emulator. */
+    if (!local_connect_arbitrary_ports(console_port, adb_port)) {
+        snprintf(buffer, buffer_size,
+                "Connected to emulator on ports %d,%d", console_port, adb_port);
+    } else {
+        snprintf(buffer, buffer_size,
+                "Could not connect to emulator on ports %d,%d",
+                console_port, adb_port);
+    }
+}
+
+static void connect_service(int fd, void* cookie)
+{
+    char buf[4096];
+    char resp[4096];
+    char *host = cookie;
+
+    if (!strncmp(host, "emu:", 4)) {
+        connect_emulator(host + 4, buf, sizeof(buf));
+    } else {
+        connect_device(host, buf, sizeof(buf));
+    }
+
+    // Send response for emulator and device
+    snprintf(resp, sizeof(resp), "%04x%s",(unsigned)strlen(buf), buf);
+    writex(fd, resp, strlen(resp));
+    adb_close(fd);
+}
 #endif
 
 #if ADB_HOST
@@ -552,6 +581,10 @@
 
         int fd = create_service_thread(wait_for_state, sinfo);
         return create_local_socket(fd);
+    } else if (!strncmp(name, "connect:", 8)) {
+        const char *host = name + 8;
+        int fd = create_service_thread(connect_service, (void *)host);
+        return create_local_socket(fd);
     }
     return NULL;
 }
diff --git a/adb/sockets.c b/adb/sockets.c
index 305cb44..f17608b 100644
--- a/adb/sockets.c
+++ b/adb/sockets.c
@@ -844,7 +844,7 @@
     free(s);
 }
 
-asocket *create_smart_socket(void (*action_cb)(asocket *s, const char *act))
+static asocket *create_smart_socket(void)
 {
     D("Creating smart socket \n");
     asocket *s = calloc(1, sizeof(asocket));
@@ -852,21 +852,15 @@
     s->enqueue = smart_socket_enqueue;
     s->ready = smart_socket_ready;
     s->close = smart_socket_close;
-    s->extra = action_cb;
 
-    D("SS(%d): created %p\n", s->id, action_cb);
+    D("SS(%d)\n", s->id);
     return s;
 }
 
-void smart_socket_action(asocket *s, const char *act)
-{
-
-}
-
 void connect_to_smartsocket(asocket *s)
 {
     D("Connecting to smart socket \n");
-    asocket *ss = create_smart_socket(smart_socket_action);
+    asocket *ss = create_smart_socket();
     s->peer = ss;
     ss->peer = s;
     s->ready(s);
diff --git a/adb/transport.c b/adb/transport.c
index b4abb66..224fe55 100644
--- a/adb/transport.c
+++ b/adb/transport.c
@@ -32,6 +32,11 @@
     .prev = &transport_list,
 };
 
+static atransport pending_list = {
+    .next = &pending_list,
+    .prev = &pending_list,
+};
+
 ADB_MUTEX_DEFINE( transport_lock );
 
 #if ADB_TRACE
@@ -645,8 +650,11 @@
         }
     }
 
-        /* put us on the master device list */
     adb_mutex_lock(&transport_lock);
+    /* remove from pending list */
+    t->next->prev = t->prev;
+    t->prev->next = t->next;
+    /* put us on the master device list */
     t->next = &transport_list;
     t->prev = transport_list.prev;
     t->next->prev = t;
@@ -989,9 +997,10 @@
 }
 #endif // ADB_HOST
 
-void register_socket_transport(int s, const char *serial, int port, int local)
+int register_socket_transport(int s, const char *serial, int port, int local)
 {
     atransport *t = calloc(1, sizeof(atransport));
+    atransport *n;
     char buff[32];
 
     if (!serial) {
@@ -999,15 +1008,37 @@
         serial = buff;
     }
     D("transport: %s init'ing for socket %d, on port %d\n", serial, s, port);
-    if ( init_socket_transport(t, s, port, local) < 0 ) {
-        adb_close(s);
+    if (init_socket_transport(t, s, port, local) < 0) {
         free(t);
-        return;
+        return -1;
     }
-    if(serial) {
-        t->serial = strdup(serial);
+
+    adb_mutex_lock(&transport_lock);
+    for (n = pending_list.next; n != &pending_list; n = n->next) {
+        if (n->serial && !strcmp(serial, n->serial)) {
+            adb_mutex_unlock(&transport_lock);
+            free(t);
+            return -1;
+        }
     }
+
+    for (n = transport_list.next; n != &transport_list; n = n->next) {
+        if (n->serial && !strcmp(serial, n->serial)) {
+            adb_mutex_unlock(&transport_lock);
+            free(t);
+            return -1;
+        }
+    }
+
+    t->next = &pending_list;
+    t->prev = pending_list.prev;
+    t->next->prev = t;
+    t->prev->next = t;
+    t->serial = strdup(serial);
+    adb_mutex_unlock(&transport_lock);
+
     register_transport(t);
+    return 0;
 }
 
 #if ADB_HOST
@@ -1077,6 +1108,14 @@
     if(devpath) {
         t->devpath = strdup(devpath);
     }
+
+    adb_mutex_lock(&transport_lock);
+    t->next = &pending_list;
+    t->prev = pending_list.prev;
+    t->next->prev = t;
+    t->prev->next = t;
+    adb_mutex_unlock(&transport_lock);
+
     register_transport(t);
 }
 
diff --git a/adb/utils.c b/adb/utils.c
deleted file mode 100644
index 91518ba..0000000
--- a/adb/utils.c
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "utils.h"
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-
-char*
-buff_addc (char*  buff, char*  buffEnd, int  c)
-{
-    int  avail = buffEnd - buff;
-
-    if (avail <= 0)  /* already in overflow mode */
-        return buff;
-
-    if (avail == 1) {  /* overflowing, the last byte is reserved for zero */
-        buff[0] = 0;
-        return buff + 1;
-    }
-
-    buff[0] = (char) c;  /* add char and terminating zero */
-    buff[1] = 0;
-    return buff + 1;
-}
-
-char*
-buff_adds (char*  buff, char*  buffEnd, const char*  s)
-{
-    int  slen = strlen(s);
-
-    return buff_addb(buff, buffEnd, s, slen);
-}
-
-char*
-buff_addb (char*  buff, char*  buffEnd, const void*  data, int  len)
-{
-    int  avail = (buffEnd - buff);
-
-    if (avail <= 0 || len <= 0)  /* already overflowing */
-        return buff;
-
-    if (len > avail)
-        len = avail;
-
-    memcpy(buff, data, len);
-
-    buff += len;
-
-    /* ensure there is a terminating zero */
-    if (buff >= buffEnd) {  /* overflow */
-        buff[-1] = 0;
-    } else
-        buff[0] = 0;
-
-    return buff;
-}
-
-char*
-buff_add  (char*  buff, char*  buffEnd, const char*  format, ... )
-{
-    int      avail;
-
-    avail = (buffEnd - buff);
-
-    if (avail > 0) {
-        va_list  args;
-        int      nn;
-
-        va_start(args, format);
-        nn = vsnprintf( buff, avail, format, args);
-        va_end(args);
-
-        if (nn < 0) {
-            /* some C libraries return -1 in case of overflow,
-             * but they will also do that if the format spec is
-             * invalid. We assume ADB is not buggy enough to
-             * trigger that last case. */
-            nn = avail;
-        }
-        else if (nn > avail) {
-            nn = avail;
-        }
-
-        buff += nn;
-
-        /* ensure that there is a terminating zero */
-        if (buff >= buffEnd)
-            buff[-1] = 0;
-        else
-            buff[0] = 0;
-    }
-    return buff;
-}
diff --git a/adb/utils.h b/adb/utils.h
deleted file mode 100644
index f70ecd2..0000000
--- a/adb/utils.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef _ADB_UTILS_H
-#define _ADB_UTILS_H
-
-/* bounded buffer functions */
-
-/* all these functions are used to append data to a bounded buffer.
- *
- * after each operation, the buffer is guaranteed to be zero-terminated,
- * even in the case of an overflow. they all return the new buffer position
- * which allows one to use them in succession, only checking for overflows
- * at the end. For example:
- *
- *    BUFF_DECL(temp,p,end,1024);
- *    char*    p;
- *
- *    p = buff_addc(temp, end, '"');
- *    p = buff_adds(temp, end, string);
- *    p = buff_addc(temp, end, '"');
- *
- *    if (p >= end) {
- *        overflow detected. note that 'temp' is
- *        zero-terminated for safety. 
- *    }
- *    return strdup(temp);
- */
-
-/* tries to add a character to the buffer, in case of overflow
- * this will only write a terminating zero and return buffEnd.
- */
-char*   buff_addc (char*  buff, char*  buffEnd, int  c);
-
-/* tries to add a string to the buffer */
-char*   buff_adds (char*  buff, char*  buffEnd, const char*  s);
-
-/* tries to add a bytes to the buffer. the input can contain zero bytes,
- * but a terminating zero will always be appended at the end anyway
- */
-char*   buff_addb (char*  buff, char*  buffEnd, const void*  data, int  len);
-
-/* tries to add a formatted string to a bounded buffer */
-char*   buff_add  (char*  buff, char*  buffEnd, const char*  format, ... );
-
-/* convenience macro used to define a bounded buffer, as well as
- * a 'cursor' and 'end' variables all in one go.
- *
- * note: this doesn't place an initial terminating zero in the buffer,
- * you need to use one of the buff_ functions for this. or simply
- * do _cursor[0] = 0 manually.
- */
-#define  BUFF_DECL(_buff,_cursor,_end,_size)   \
-    char   _buff[_size], *_cursor=_buff, *_end = _cursor + (_size)
-
-#endif /* _ADB_UTILS_H */
diff --git a/fs_mgr/fs_mgr.c b/fs_mgr/fs_mgr.c
index fecc556..0848342 100644
--- a/fs_mgr/fs_mgr.c
+++ b/fs_mgr/fs_mgr.c
@@ -487,6 +487,43 @@
     }
 }
 
+/*
+ * Mark the given block device as read-only, using the BLKROSET ioctl.
+ * Return 0 on success, and -1 on error.
+ */
+static void fs_set_blk_ro(const char *blockdev)
+{
+    int fd;
+    int ON = 1;
+
+    fd = open(blockdev, O_RDONLY);
+    if (fd < 0) {
+        // should never happen
+        return;
+    }
+
+    ioctl(fd, BLKROSET, &ON);
+    close(fd);
+}
+
+/*
+ * __mount(): wrapper around the mount() system call which also
+ * sets the underlying block device to read-only if the mount is read-only.
+ * See "man 2 mount" for return values.
+ */
+static int __mount(const char *source, const char *target,
+                   const char *filesystemtype, unsigned long mountflags,
+                   const void *data)
+{
+    int ret = mount(source, target, filesystemtype, mountflags, data);
+
+    if ((ret == 0) && (mountflags & MS_RDONLY) != 0) {
+        fs_set_blk_ro(source);
+    }
+
+    return ret;
+}
+
 static int fs_match(char *in1, char *in2)
 {
     char *n1;
@@ -539,9 +576,9 @@
                      fstab->recs[i].mount_point);
         }
 
-        mret = mount(fstab->recs[i].blk_device, fstab->recs[i].mount_point,
-                     fstab->recs[i].fs_type, fstab->recs[i].flags,
-                     fstab->recs[i].fs_options);
+        mret = __mount(fstab->recs[i].blk_device, fstab->recs[i].mount_point,
+                       fstab->recs[i].fs_type, fstab->recs[i].flags,
+                       fstab->recs[i].fs_options);
         if (!mret) {
             /* Success!  Go get the next one */
             continue;
@@ -621,8 +658,8 @@
         } else {
             m = fstab->recs[i].mount_point;
         }
-        if (mount(n_blk_device, m, fstab->recs[i].fs_type,
-                  fstab->recs[i].flags, fstab->recs[i].fs_options)) {
+        if (__mount(n_blk_device, m, fstab->recs[i].fs_type,
+                    fstab->recs[i].flags, fstab->recs[i].fs_options)) {
             ERROR("Cannot mount filesystem on %s at %s\n",
                     n_blk_device, m);
             goto out;
diff --git a/include/cutils/abort_socket.h b/include/cutils/abort_socket.h
deleted file mode 100644
index fbb1112..0000000
--- a/include/cutils/abort_socket.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 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.
- */
-
-/* Helper to perform abortable blocking operations on a socket:
- *   asocket_connect()
- *   asocket_accept()
- *   asocket_read()
- *   asocket_write()
- * These calls are similar to the regular syscalls, but can be aborted with:
- *   asocket_abort()
- *
- * Calling close() on a regular POSIX socket does not abort blocked syscalls on
- * that socket in other threads.
- *
- * After calling asocket_abort() the socket cannot be reused.
- *
- * Call asocket_destory() *after* all threads have finished with the socket to
- * finish closing the socket and free the asocket structure.
- *
- * The helper is implemented by setting the socket non-blocking to initiate
- * syscalls connect(), accept(), read(), write(), then using a blocking poll()
- * on both the primary socket and a local pipe. This makes the poll() abortable
- * by writing a byte to the local pipe in asocket_abort().
- *
- * asocket_create() sets the fd to non-blocking mode. It must not be changed to
- * blocking mode.
- *
- * Using asocket will triple the number of file descriptors required per
- * socket, due to the local pipe. It may be possible to use a global pipe per
- * process rather than per socket, but we have not been able to come up with a
- * race-free implementation yet.
- *
- * All functions except asocket_init() and asocket_destroy() are thread safe.
- */
-
-#include <stdlib.h>
-#include <sys/socket.h>
-
-#ifndef __CUTILS_ABORT_SOCKET_H__
-#define __CUTILS_ABORT_SOCKET_H__
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct asocket {
-    int fd;           /* primary socket fd */
-    int abort_fd[2];  /* pipe used to abort */
-};
-
-/* Create an asocket from fd.
- * Sets the socket to non-blocking mode.
- * Returns NULL on error with errno set.
- */
-struct asocket *asocket_init(int fd);
-
-/* Blocking socket I/O with timeout.
- * Calling asocket_abort() from another thread will cause each of these
- * functions to immediately return with value -1 and errno ECANCELED.
- * timeout is in ms, use -1 to indicate no timeout. On timeout -1 is returned
- * with errno ETIMEDOUT.
- * EINTR is handled in-call.
- * Other semantics are identical to the regular syscalls.
- */
-int asocket_connect(struct asocket *s, const struct sockaddr *addr,
-        socklen_t addrlen, int timeout);
-
-int asocket_accept(struct asocket *s, struct sockaddr *addr,
-        socklen_t *addrlen, int timeout);
-
-int asocket_read(struct asocket *s, void *buf, size_t count, int timeout);
-
-int asocket_write(struct asocket *s, const void *buf, size_t count,
-        int timeout);
-
-/* Abort above calls and shutdown socket.
- * Further I/O operations on this socket will immediately fail after this call.
- * asocket_destroy() should be used to release resources once all threads
- * have returned from blocking calls on the socket.
- */
-void asocket_abort(struct asocket *s);
-
-/* Close socket and free asocket structure.
- * Must not be called until all calls on this structure have completed.
- */
-void asocket_destroy(struct asocket *s);
-
-#ifdef __cplusplus
-}
-#endif
-#endif //__CUTILS_ABORT_SOCKET__H__
diff --git a/include/cutils/android_reboot.h b/include/cutils/android_reboot.h
index 0c79be7..8c30e8e 100644
--- a/include/cutils/android_reboot.h
+++ b/include/cutils/android_reboot.h
@@ -24,9 +24,8 @@
 #define ANDROID_RB_POWEROFF 0xDEAD0002
 #define ANDROID_RB_RESTART2 0xDEAD0003
 
-/* Flags */
-#define ANDROID_RB_FLAG_NO_SYNC       0x1
-#define ANDROID_RB_FLAG_NO_REMOUNT_RO 0x2
+/* Properties */
+#define ANDROID_RB_PROPERTY "sys.powerctl"
 
 int android_reboot(int cmd, int flags, char *arg);
 
diff --git a/include/cutils/array.h b/include/cutils/array.h
deleted file mode 100644
index c97ff34..0000000
--- a/include/cutils/array.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * A pointer array which intelligently expands its capacity ad needed.
- */
-
-#ifndef __ARRAY_H
-#define __ARRAY_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdlib.h>
-
-/** An array. */
-typedef struct Array Array;
-
-/** Constructs a new array. Returns NULL if we ran out of memory. */
-Array* arrayCreate();
-
-/** Frees an array. Does not free elements themselves. */
-void arrayFree(Array* array);
-
-/** Adds a pointer. Returns 0 is successful, < 0 otherwise. */
-int arrayAdd(Array* array, void* pointer);
-
-/** Gets the pointer at the specified index. */
-void* arrayGet(Array* array, int index);
-
-/** Removes the pointer at the given index and returns it. */
-void* arrayRemove(Array* array, int index);
-
-/** Sets pointer at the given index. Returns old pointer. */
-void* arraySet(Array* array, int index, void* pointer);
-
-/** Sets the array size. Sets new pointers to NULL. Returns 0 if successful, < 0 otherwise . */
-int arraySetSize(Array* array, int size);
-
-/** Returns the size of the given array. */
-int arraySize(Array* array);
-
-/** 
- * Returns a pointer to a C-style array which will be valid until this array 
- * changes.
- */
-const void** arrayUnwrap(Array* array);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __ARRAY_H */ 
diff --git a/include/cutils/bitops.h b/include/cutils/bitops.h
index eb44236..c26dc54 100644
--- a/include/cutils/bitops.h
+++ b/include/cutils/bitops.h
@@ -75,6 +75,16 @@
     return -1;
 }
 
+static inline int bitmask_weight(unsigned int *bitmask, int num_bits)
+{
+    int i;
+    int weight = 0;
+
+    for (i = 0; i < BITS_TO_WORDS(num_bits); i++)
+        weight += __builtin_popcount(bitmask[i]);
+    return weight;
+}
+
 static inline void bitmask_set(unsigned int *bitmask, int bit)
 {
     bitmask[BIT_WORD(bit)] |= BIT_MASK(bit);
diff --git a/include/cutils/mq.h b/include/cutils/mq.h
deleted file mode 100644
index b27456d..0000000
--- a/include/cutils/mq.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2007 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.
- */
-
-/**
- * IPC messaging library.
- */
-
-#ifndef __MQ_H
-#define __MQ_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/** A message. */
-typedef struct MqMessage MqMessage;
-
-/** A destination to which messages can be sent. */
-typedef struct MqDestination MqDestination;
-
-/* Array of bytes. */
-typedef struct MqBytes MqBytes;
-
-/** 
- * Hears messages. 
- * 
- * @param destination to which the message was sent
- * @param message the message to hear
- */
-typedef void MqMessageListener(MqDestination* destination, MqMessage* message);
-
-/** 
- * Hears a destination close.
- * 
- * @param destination that closed
- */
-typedef void MqCloseListener(MqDestination* destination);
-
-/** Message functions. */
-
-/** 
- * Creates a new Message.
- * 
- * @param header as defined by user
- * @param body as defined by user
- * @param replyTo destination to which replies should be sent, NULL if none
- */
-MqMessage* mqCreateMessage(MqBytes header, MqBytes body, 
-        MqDestination* replyTo);
-
-/** Sends a message to a destination. */
-void mqSendMessage(MqMessage* message, MqDestination* destination);
-
-/** Destination functions. */
-
-/** 
- * Creates a new destination. Acquires a reference implicitly.
- *
- * @param messageListener function to call when a message is recieved
- * @param closeListener function to call when the destination closes
- * @param userData user-specific data to associate with the destination.
- *  Retrieve using mqGetDestinationUserData().
- */
-MqDestination* mqCreateDestination(MqMessageListener* messageListener, 
-        MqCloseListener* closeListener, void* userData);
-
-/**
- * Gets user data which was associated with the given destination at 
- * construction time. 
- * 
- * It is only valid to call this function in the same process that the 
- * given destination was created in.
- * This function returns a null pointer if you call it on a destination
- * created in a remote process.
- */
-void* mqGetUserData(MqDestination* destination);
-
-/**
- * Returns 1 if the destination was created in this process, or 0 if
- * the destination was created in a different process, in which case you have
- * a remote stub.
- */
-int mqIsDestinationLocal(MqDestination* destination);
-
-/**
- * Increments the destination's reference count.
- */
-void mqKeepDestination(MqDesintation* destination);
-
-/**
- * Decrements the destination's reference count. 
- */
-void mqFreeDestination(MqDestination* desintation);
-
-/** Registry API. */
-
-/**
- * Gets the destination bound to a name.
- */
-MqDestination* mqGetDestination(char* name);
-
-/**
- * Binds a destination to a name.
- */
-void mqPutDestination(char* name, MqDestination* desintation);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __MQ_H */ 
diff --git a/include/cutils/qsort_r_compat.h b/include/cutils/qsort_r_compat.h
deleted file mode 100644
index 479a1ab..0000000
--- a/include/cutils/qsort_r_compat.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Provides a portable version of qsort_r, called qsort_r_compat, which is a
- * reentrant variant of qsort that passes a user data pointer to its comparator.
- * This implementation follows the BSD parameter convention.
- */
-
-#ifndef _LIBS_CUTILS_QSORT_R_COMPAT_H
-#define _LIBS_CUTILS_QSORT_R_COMPAT_H
-
-#include <stdlib.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
-        int (*compar)(void*, const void* , const void* ));
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _LIBS_CUTILS_QSORT_R_COMPAT_H
diff --git a/include/cutils/record_stream.h b/include/cutils/record_stream.h
deleted file mode 100644
index bfac87a..0000000
--- a/include/cutils/record_stream.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * A simple utility for reading fixed records out of a stream fd
- */
-
-#ifndef _CUTILS_RECORD_STREAM_H
-#define _CUTILS_RECORD_STREAM_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-typedef struct RecordStream RecordStream;
-
-extern RecordStream *record_stream_new(int fd, size_t maxRecordLen);
-extern void record_stream_free(RecordStream *p_rs);
-
-extern int record_stream_get_next (RecordStream *p_rs, void ** p_outRecord, 
-                                    size_t *p_outRecordLen);
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif /*_CUTILS_RECORD_STREAM_H*/
-
diff --git a/include/cutils/selector.h b/include/cutils/selector.h
deleted file mode 100644
index dfc2a9d..0000000
--- a/include/cutils/selector.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2007 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.
- */
-
-/**
- * Framework for multiplexing I/O. A selector manages a set of file
- * descriptors and calls out to user-provided callback functions to read and
- * write data and handle errors.
- */
-
-#ifndef __SELECTOR_H
-#define __SELECTOR_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdbool.h>
-    
-/** 
- * Manages SelectableFds and invokes their callbacks at appropriate times. 
- */
-typedef struct Selector Selector;
-
-/** 
- * A selectable descriptor. Contains callbacks which the selector can invoke
- * before calling select(), when the descriptor is readable or writable, and 
- * when the descriptor contains out-of-band data. Simply set a callback to 
- * NULL if you're not interested in that particular event.
- *
- * A selectable descriptor can indicate that it needs to be removed from the
- * selector by setting the 'remove' flag. The selector will remove the
- * descriptor at a later time and invoke the onRemove() callback.
- * 
- * SelectableFd fields should only be modified from the selector loop.
- */
-typedef struct SelectableFd SelectableFd;
-struct SelectableFd {
-
-    /** The file descriptor itself. */
-    int fd;
-    
-    /** Pointer to user-specific data. Can be NULL. */
-    void* data;
-    
-    /** 
-     * Set this flag when you no longer wish to be selected. The selector
-     * will invoke onRemove() when the descriptor is actually removed.
-     */
-    bool remove;
-
-    /** 
-     * Invoked by the selector before calling select. You can set up other
-     * callbacks from here as necessary.
-     */
-    void (*beforeSelect)(SelectableFd* self);
-
-    /** 
-     * Invoked by the selector when the descriptor has data available. Set to
-     * NULL to indicate that you're not interested in reading.
-     */
-    void (*onReadable)(SelectableFd* self);
-
-    /** 
-     * Invoked by the selector when the descriptor can accept data. Set to
-     * NULL to indicate that you're not interested in writing.
-     */
-    void (*onWritable)(SelectableFd* self);
-
-    /** 
-     * Invoked by the selector when out-of-band (OOB) data is available. Set to
-     * NULL to indicate that you're not interested in OOB data.
-     */
-    void (*onExcept)(SelectableFd* self);
-
-    /**
-     * Invoked by the selector after the descriptor is removed from the
-     * selector but before the selector frees the SelectableFd memory.
-     */
-    void (*onRemove)(SelectableFd* self);
-
-    /**
-     * The selector which selected this fd. Set by the selector itself.
-     */
-    Selector* selector;
-};
-
-/** 
- * Creates a new selector. 
- */
-Selector* selectorCreate(void);
-
-/** 
- * Creates a new selectable fd, adds it to the given selector and returns a 
- * pointer. Outside of 'selector' and 'fd', all fields are set to 0 or NULL 
- * by default.
- * 
- * The selectable fd should only be modified from the selector loop thread.
- */
-SelectableFd* selectorAdd(Selector* selector, int fd);
-
-/**
- * Wakes up the selector even though no I/O events occurred. Use this
- * to indicate that you're ready to write to a descriptor.
- */
-void selectorWakeUp(Selector* selector);
-    
-/** 
- * Loops continuously selecting file descriptors and firing events. 
- * Does not return. 
- */
-void selectorLoop(Selector* selector);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __SELECTOR_H */ 
diff --git a/include/cutils/zygote.h b/include/cutils/zygote.h
deleted file mode 100644
index a7480d3..0000000
--- a/include/cutils/zygote.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2007 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 __CUTILS_ZYGOTE_H
-#define __CUTILS_ZYGOTE_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int zygote_run_oneshot(int sendStdio, int argc, const char **argv);
-int zygote_run(int argc, const char **argv);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __CUTILS_ZYGOTE_H */
diff --git a/include/mincrypt/hash-internal.h b/include/mincrypt/hash-internal.h
new file mode 100644
index 0000000..96806f7
--- /dev/null
+++ b/include/mincrypt/hash-internal.h
@@ -0,0 +1,40 @@
+// Copyright 2007 Google Inc. All Rights Reserved.
+// Author: mschilder@google.com (Marius Schilder)
+
+#ifndef SECURITY_UTIL_LITE_HASH_INTERNAL_H__
+#define SECURITY_UTIL_LITE_HASH_INTERNAL_H__
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif  // __cplusplus
+
+struct HASH_CTX;  // forward decl
+
+typedef struct HASH_VTAB {
+  void (* const init)(struct HASH_CTX*);
+  void (* const update)(struct HASH_CTX*, const void*, int);
+  const uint8_t* (* const final)(struct HASH_CTX*);
+  const uint8_t* (* const hash)(const void*, int, uint8_t*);
+  int size;
+} HASH_VTAB;
+
+typedef struct HASH_CTX {
+  const HASH_VTAB * f;
+  uint64_t count;
+  uint8_t buf[64];
+  uint32_t state[8];  // upto SHA2
+} HASH_CTX;
+
+#define HASH_init(ctx) (ctx)->f->init(ctx)
+#define HASH_update(ctx, data, len) (ctx)->f->update(ctx, data, len)
+#define HASH_final(ctx) (ctx)->f->final(ctx)
+#define HASH_hash(data, len, digest) (ctx)->f->hash(data, len, digest)
+#define HASH_size(ctx) (ctx)->f->size
+
+#ifdef __cplusplus
+}
+#endif  // __cplusplus
+
+#endif  // SECURITY_UTIL_LITE_HASH_INTERNAL_H__
diff --git a/include/mincrypt/rsa.h b/include/mincrypt/rsa.h
index d7429fc..cc0e800 100644
--- a/include/mincrypt/rsa.h
+++ b/include/mincrypt/rsa.h
@@ -48,7 +48,8 @@
 int RSA_verify(const RSAPublicKey *key,
                const uint8_t* signature,
                const int len,
-               const uint8_t* sha);
+               const uint8_t* hash,
+               const int hash_len);
 
 #ifdef __cplusplus
 }
diff --git a/include/mincrypt/sha.h b/include/mincrypt/sha.h
index af63e87..120ddcb 100644
--- a/include/mincrypt/sha.h
+++ b/include/mincrypt/sha.h
@@ -1,63 +1,30 @@
-/* sha.h
-**
-** Copyright 2008, The Android Open Source Project
-**
-** 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 Google Inc. ``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 Google Inc. 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.
-*/
+// Copyright 2005 Google Inc. All Rights Reserved.
+// Author: mschilder@google.com (Marius Schilder)
 
-#ifndef _EMBEDDED_SHA_H_
-#define _EMBEDDED_SHA_H_
+#ifndef SECURITY_UTIL_LITE_SHA1_H__
+#define SECURITY_UTIL_LITE_SHA1_H__
 
-#include <inttypes.h>
+#include <stdint.h>
+#include "hash-internal.h"
 
 #ifdef __cplusplus
 extern "C" {
-#endif
+#endif // __cplusplus
 
-typedef struct SHA_CTX {
-    uint64_t count;
-    uint32_t state[5];
-#if defined(HAVE_ENDIAN_H) && defined(HAVE_LITTLE_ENDIAN)
-    union {
-        uint8_t b[64];
-        uint32_t w[16];
-    } buf;
-#else
-    uint8_t buf[64];
-#endif
-} SHA_CTX;
+typedef HASH_CTX SHA_CTX;
 
 void SHA_init(SHA_CTX* ctx);
 void SHA_update(SHA_CTX* ctx, const void* data, int len);
 const uint8_t* SHA_final(SHA_CTX* ctx);
 
-/* Convenience method. Returns digest parameter value. */
-const uint8_t* SHA(const void* data, int len, uint8_t* digest);
+// Convenience method. Returns digest address.
+// NOTE: *digest needs to hold SHA_DIGEST_SIZE bytes.
+const uint8_t* SHA_hash(const void* data, int len, uint8_t* digest);
 
 #define SHA_DIGEST_SIZE 20
 
 #ifdef __cplusplus
 }
-#endif
+#endif // __cplusplus
 
-#endif
+#endif  // SECURITY_UTIL_LITE_SHA1_H__
diff --git a/include/mincrypt/sha256.h b/include/mincrypt/sha256.h
new file mode 100644
index 0000000..0f3efb7
--- /dev/null
+++ b/include/mincrypt/sha256.h
@@ -0,0 +1,29 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+// Author: mschilder@google.com (Marius Schilder)
+
+#ifndef SECURITY_UTIL_LITE_SHA256_H__
+#define SECURITY_UTIL_LITE_SHA256_H__
+
+#include <stdint.h>
+#include "hash-internal.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+typedef HASH_CTX SHA256_CTX;
+
+void SHA256_init(SHA256_CTX* ctx);
+void SHA256_update(SHA256_CTX* ctx, const void* data, int len);
+const uint8_t* SHA256_final(SHA256_CTX* ctx);
+
+// Convenience method. Returns digest address.
+const uint8_t* SHA256_hash(const void* data, int len, uint8_t* digest);
+
+#define SHA256_DIGEST_SIZE 32
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif  // SECURITY_UTIL_LITE_SHA256_H__
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index 5d363a7..4a7d377 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -229,7 +229,7 @@
     { 06755, AID_ROOT,      AID_ROOT,      0, "system/xbin/tcpdump" },
     { 04770, AID_ROOT,      AID_RADIO,     0, "system/bin/pppd-ril" },
 
-    /* the following file has enhanced capabilities and IS included in user builds. */
+    /* the following files have enhanced capabilities and ARE included in user builds. */
     { 00750, AID_ROOT,      AID_SHELL,     (1 << CAP_SETUID) | (1 << CAP_SETGID), "system/bin/run-as" },
 
     { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/*" },
diff --git a/init/builtins.c b/init/builtins.c
index 0f9f131..9ae9ba3 100644
--- a/init/builtins.c
+++ b/init/builtins.c
@@ -32,6 +32,7 @@
 #include <sys/wait.h>
 #include <linux/loop.h>
 #include <cutils/partition_utils.h>
+#include <cutils/android_reboot.h>
 #include <sys/system_properties.h>
 #include <fs_mgr.h>
 
@@ -599,6 +600,43 @@
     return 0;
 }
 
+int do_powerctl(int nargs, char **args)
+{
+    char command[PROP_VALUE_MAX];
+    int res;
+    int len = 0;
+    int cmd = 0;
+    char *reboot_target;
+
+    res = expand_props(command, args[1], sizeof(command));
+    if (res) {
+        ERROR("powerctl: cannot expand '%s'\n", args[1]);
+        return -EINVAL;
+    }
+
+    if (strncmp(command, "shutdown", 8) == 0) {
+        cmd = ANDROID_RB_POWEROFF;
+        len = 8;
+    } else if (strncmp(command, "reboot", 6) == 0) {
+        cmd = ANDROID_RB_RESTART2;
+        len = 6;
+    } else {
+        ERROR("powerctl: unrecognized command '%s'\n", command);
+        return -EINVAL;
+    }
+
+    if (command[len] == ',') {
+        reboot_target = &command[len + 1];
+    } else if (command[len] == '\0') {
+        reboot_target = "";
+    } else {
+        ERROR("powerctl: unrecognized reboot target '%s'\n", &command[len]);
+        return -EINVAL;
+    }
+
+    return android_reboot(cmd, 0, reboot_target);
+}
+
 int do_trigger(int nargs, char **args)
 {
     action_for_each_trigger(args[1], action_add_queue_tail);
diff --git a/init/init_parser.c b/init/init_parser.c
index 686640e..a1d2423 100644
--- a/init/init_parser.c
+++ b/init/init_parser.c
@@ -130,6 +130,8 @@
         if (!strcmp(s, "neshot")) return K_oneshot;
         if (!strcmp(s, "nrestart")) return K_onrestart;
         break;
+    case 'p':
+        if (!strcmp(s, "owerctl")) return K_powerctl;
     case 'r':
         if (!strcmp(s, "estart")) return K_restart;
         if (!strcmp(s, "estorecon")) return K_restorecon;
diff --git a/init/keywords.h b/init/keywords.h
index f188db5..f147506 100644
--- a/init/keywords.h
+++ b/init/keywords.h
@@ -14,6 +14,7 @@
 int do_mkdir(int nargs, char **args);
 int do_mount_all(int nargs, char **args);
 int do_mount(int nargs, char **args);
+int do_powerctl(int nargs, char **args);
 int do_restart(int nargs, char **args);
 int do_restorecon(int nargs, char **args);
 int do_rm(int nargs, char **args);
@@ -66,6 +67,7 @@
     KEYWORD(on,          SECTION, 0, 0)
     KEYWORD(oneshot,     OPTION,  0, 0)
     KEYWORD(onrestart,   OPTION,  0, 0)
+    KEYWORD(powerctl,    COMMAND, 1, do_powerctl)
     KEYWORD(restart,     COMMAND, 1, do_restart)
     KEYWORD(restorecon,  COMMAND, 1, do_restorecon)
     KEYWORD(rm,          COMMAND, 1, do_rm)
diff --git a/init/property_service.c b/init/property_service.c
old mode 100755
new mode 100644
index 0989e6d..10be3f5
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -77,6 +77,7 @@
     { "runtime.",         AID_SYSTEM,   0 },
     { "hw.",              AID_SYSTEM,   0 },
     { "sys.",             AID_SYSTEM,   0 },
+    { "sys.powerctl",     AID_SHELL,    0 },
     { "service.",         AID_SYSTEM,   0 },
     { "wlan.",            AID_SYSTEM,   0 },
     { "bluetooth.",       AID_BLUETOOTH,   0 },
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index 5037705..afbc758 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -24,11 +24,9 @@
 hostSmpFlag := -DANDROID_SMP=0
 
 commonSources := \
-	array.c \
 	hashmap.c \
 	atomic.c.arm \
 	native_handle.c \
-	buffer.c \
 	socket_inaddr_any_server.c \
 	socket_local_client.c \
 	socket_local_server.c \
@@ -43,10 +41,8 @@
 	open_memstream.c \
 	strdup16to8.c \
 	strdup8to16.c \
-	record_stream.c \
 	process_name.c \
 	properties.c \
-	qsort_r_compat.c \
 	threads.c \
 	sched_policy.c \
 	iosched_policy.c \
@@ -74,11 +70,8 @@
         uio.c
 else
     commonSources += \
-        abort_socket.c \
         fs.c \
-        selector.c \
-        multiuser.c \
-        zygote.c
+        multiuser.c
 endif
 
 
@@ -118,7 +111,6 @@
         ashmem-dev.c \
         debugger.c \
         klog.c \
-        mq.c \
         partition_utils.c \
         qtaguid.c \
         trace.c \
diff --git a/libcutils/abort_socket.c b/libcutils/abort_socket.c
deleted file mode 100644
index 6a5e5e4..0000000
--- a/libcutils/abort_socket.c
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright 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 <stdlib.h>
-#include <errno.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/socket.h>
-#include <sys/poll.h>
-
-#include "cutils/abort_socket.h"
-
-struct asocket *asocket_init(int fd) {
-    int abort_fd[2];
-    int flags;
-    struct asocket *s;
-
-    /* set primary socket to non-blocking */
-    flags = fcntl(fd, F_GETFL);
-    if (flags == -1)
-        return NULL;
-    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK))
-        return NULL;
-
-    /* create pipe with non-blocking write, so that asocket_close() cannot
-       block */
-    if (pipe(abort_fd))
-        return NULL;
-    flags = fcntl(abort_fd[1], F_GETFL);
-    if (flags == -1)
-        return NULL;
-    if (fcntl(abort_fd[1], F_SETFL, flags | O_NONBLOCK))
-        return NULL;
-
-    s = malloc(sizeof(struct asocket));
-    if (!s)
-        return NULL;
-
-    s->fd = fd;
-    s->abort_fd[0] = abort_fd[0];
-    s->abort_fd[1] = abort_fd[1];
-
-    return s;
-}
-
-int asocket_connect(struct asocket *s, const struct sockaddr *addr,
-        socklen_t addrlen, int timeout) {
-
-    int ret;
-
-    do {
-        ret = connect(s->fd, addr, addrlen);
-    } while (ret && errno == EINTR);
-
-    if (ret && errno == EINPROGRESS) {
-        /* ready to poll() */
-        socklen_t retlen;
-        struct pollfd pfd[2];
-
-        pfd[0].fd = s->fd;
-        pfd[0].events = POLLOUT;
-        pfd[0].revents = 0;
-        pfd[1].fd = s->abort_fd[0];
-        pfd[1].events = POLLIN;
-        pfd[1].revents = 0;
-
-        do {
-            ret = poll(pfd, 2, timeout);
-        } while (ret < 0 && errno == EINTR);
-
-        if (ret < 0)
-            return -1;
-        else if (ret == 0) {
-            /* timeout */
-            errno = ETIMEDOUT;
-            return -1;
-        }
-
-        if (pfd[1].revents) {
-            /* abort due to asocket_abort() */
-            errno = ECANCELED;
-            return -1;
-        }
-
-        if (pfd[0].revents) {
-            if (pfd[0].revents & POLLOUT) {
-                /* connect call complete, read return code */
-                retlen = sizeof(ret);
-                if (getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &ret, &retlen))
-                    return -1;
-                /* got connect() return code */
-                if (ret) {
-                    errno = ret;
-                }
-            } else {
-                /* some error event on this fd */
-                errno = ECONNABORTED;
-                return -1;
-            }
-        }
-    }
-
-    return ret;
-}
-
-int asocket_accept(struct asocket *s, struct sockaddr *addr,
-        socklen_t *addrlen, int timeout) {
-
-    int ret;
-    struct pollfd pfd[2];
-
-    pfd[0].fd = s->fd;
-    pfd[0].events = POLLIN;
-    pfd[0].revents = 0;
-    pfd[1].fd = s->abort_fd[0];
-    pfd[1].events = POLLIN;
-    pfd[1].revents = 0;
-
-    do {
-        ret = poll(pfd, 2, timeout);
-    } while (ret < 0 && errno == EINTR);
-
-    if (ret < 0)
-        return -1;
-    else if (ret == 0) {
-        /* timeout */
-        errno = ETIMEDOUT;
-        return -1;
-    }
-
-    if (pfd[1].revents) {
-        /* abort due to asocket_abort() */
-        errno = ECANCELED;
-        return -1;
-    }
-
-    if (pfd[0].revents) {
-        if (pfd[0].revents & POLLIN) {
-            /* ready to accept() without blocking */
-            do {
-                ret = accept(s->fd, addr, addrlen);
-            } while (ret < 0 && errno == EINTR);
-        } else {
-            /* some error event on this fd */
-            errno = ECONNABORTED;
-            return -1;
-        }
-    }
-
-    return ret;
-}
-
-int asocket_read(struct asocket *s, void *buf, size_t count, int timeout) {
-    int ret;
-    struct pollfd pfd[2];
-
-    pfd[0].fd = s->fd;
-    pfd[0].events = POLLIN;
-    pfd[0].revents = 0;
-    pfd[1].fd = s->abort_fd[0];
-    pfd[1].events = POLLIN;
-    pfd[1].revents = 0;
-
-    do {
-        ret = poll(pfd, 2, timeout);
-    } while (ret < 0 && errno == EINTR);
-
-    if (ret < 0)
-        return -1;
-    else if (ret == 0) {
-        /* timeout */
-        errno = ETIMEDOUT;
-        return -1;
-    }
-
-    if (pfd[1].revents) {
-        /* abort due to asocket_abort() */
-        errno = ECANCELED;
-        return -1;
-    }
-
-    if (pfd[0].revents) {
-        if (pfd[0].revents & POLLIN) {
-            /* ready to read() without blocking */
-            do {
-                ret = read(s->fd, buf, count);
-            } while (ret < 0 && errno == EINTR);
-        } else {
-            /* some error event on this fd */
-            errno = ECONNABORTED;
-            return -1;
-        }
-    }
-
-    return ret;
-}
-
-int asocket_write(struct asocket *s, const void *buf, size_t count,
-        int timeout) {
-    int ret;
-    struct pollfd pfd[2];
-
-    pfd[0].fd = s->fd;
-    pfd[0].events = POLLOUT;
-    pfd[0].revents = 0;
-    pfd[1].fd = s->abort_fd[0];
-    pfd[1].events = POLLIN;
-    pfd[1].revents = 0;
-
-    do {
-        ret = poll(pfd, 2, timeout);
-    } while (ret < 0 && errno == EINTR);
-
-    if (ret < 0)
-        return -1;
-    else if (ret == 0) {
-        /* timeout */
-        errno = ETIMEDOUT;
-        return -1;
-    }
-
-    if (pfd[1].revents) {
-        /* abort due to asocket_abort() */
-        errno = ECANCELED;
-        return -1;
-    }
-
-    if (pfd[0].revents) {
-        if (pfd[0].revents & POLLOUT) {
-            /* ready to write() without blocking */
-            do {
-                ret = write(s->fd, buf, count);
-            } while (ret < 0 && errno == EINTR);
-        } else {
-            /* some error event on this fd */
-            errno = ECONNABORTED;
-            return -1;
-        }
-    }
-
-    return ret;
-}
-
-void asocket_abort(struct asocket *s) {
-    int ret;
-    char buf = 0;
-
-    /* Prevent further use of fd, without yet releasing the fd */
-    shutdown(s->fd, SHUT_RDWR);
-
-    /* wake up calls blocked at poll() */
-    do {
-        ret = write(s->abort_fd[1], &buf, 1);
-    } while (ret < 0 && errno == EINTR);
-}
-
-void asocket_destroy(struct asocket *s) {
-    struct asocket s_copy = *s;
-
-    /* Clients should *not* be using these fd's after calling
-       asocket_destroy(), but in case they do, set to -1 so they cannot use a
-       stale fd */
-    s->fd = -1;
-    s->abort_fd[0] = -1;
-    s->abort_fd[1] = -1;
-
-    /* Call asocket_abort() in case there are still threads blocked on this
-       socket. Clients should not rely on this behavior - it is racy because we
-       are about to close() these sockets - clients should instead make sure
-       all threads are done with the socket before calling asocket_destory().
-     */
-    asocket_abort(&s_copy);
-
-    /* enough safety checks, close and release memory */
-    close(s_copy.abort_fd[1]);
-    close(s_copy.abort_fd[0]);
-    close(s_copy.fd);
-
-    free(s);
-}
diff --git a/libcutils/android_reboot.c b/libcutils/android_reboot.c
index 33a7358..16f82bb 100644
--- a/libcutils/android_reboot.c
+++ b/libcutils/android_reboot.c
@@ -105,11 +105,8 @@
 {
     int ret;
 
-    if (!(flags & ANDROID_RB_FLAG_NO_SYNC))
-        sync();
-
-    if (!(flags & ANDROID_RB_FLAG_NO_REMOUNT_RO))
-        remount_ro();
+    sync();
+    remount_ro();
 
     switch (cmd) {
         case ANDROID_RB_RESTART:
diff --git a/libcutils/array.c b/libcutils/array.c
deleted file mode 100644
index 55ec055..0000000
--- a/libcutils/array.c
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <cutils/array.h>
-#include <assert.h>
-#include <stdlib.h>
-#include <string.h>
-#include <limits.h>
-
-#define INITIAL_CAPACITY (4)
-#define MAX_CAPACITY     ((int)(UINT_MAX/sizeof(void*)))
-
-struct Array {
-    void** contents;
-    int size;
-    int capacity;
-};
-
-Array* arrayCreate() {
-    return calloc(1, sizeof(struct Array));
-}
-
-void arrayFree(Array* array) {
-    assert(array != NULL);
-
-    // Free internal array.
-    free(array->contents);
-
-    // Free the Array itself.
-    free(array);
-}
-
-/** Returns 0 if successful, < 0 otherwise.. */
-static int ensureCapacity(Array* array, int capacity) {
-    int oldCapacity = array->capacity;
-    if (capacity > oldCapacity) {
-        int newCapacity = (oldCapacity == 0) ? INITIAL_CAPACITY : oldCapacity;
-
-        // Ensure we're not doing something nasty
-        if (capacity > MAX_CAPACITY)
-            return -1;
-
-        // Keep doubling capacity until we surpass necessary capacity.
-        while (newCapacity < capacity) {
-            int  newCap = newCapacity*2;
-            // Handle integer overflows
-            if (newCap < newCapacity || newCap > MAX_CAPACITY) {
-                newCap = MAX_CAPACITY;
-            }
-            newCapacity = newCap;
-        }
-
-        // Should not happen, but better be safe than sorry
-        if (newCapacity < 0 || newCapacity > MAX_CAPACITY)
-            return -1;
-
-        void** newContents;
-        if (array->contents == NULL) {
-            // Allocate new array.
-            newContents = malloc(newCapacity * sizeof(void*));
-            if (newContents == NULL) {
-                return -1;
-            }
-        } else {
-            // Expand existing array.
-            newContents = realloc(array->contents, sizeof(void*) * newCapacity);
-            if (newContents == NULL) {
-                return -1;
-            }
-        }
-
-        array->capacity = newCapacity;
-        array->contents = newContents;
-    }
-
-    return 0;
-}
-
-int arrayAdd(Array* array, void* pointer) {
-    assert(array != NULL);
-    int size = array->size;
-    int result = ensureCapacity(array, size + 1);
-    if (result < 0) {
-        return result;
-    }
-    array->contents[size] = pointer;
-    array->size++;
-    return 0;
-}
-
-static inline void checkBounds(Array* array, int index) {
-    assert(array != NULL);
-    assert(index < array->size);
-    assert(index >= 0);
-}
-
-void* arrayGet(Array* array, int index) {
-    checkBounds(array, index);
-    return array->contents[index];
-}
-
-void* arrayRemove(Array* array, int index) {
-    checkBounds(array, index);
-
-    void* pointer = array->contents[index];
-    
-    int newSize = array->size - 1;
-    
-    // Shift entries left.
-    if (index != newSize) {
-        memmove(array->contents + index, array->contents + index + 1, 
-                (sizeof(void*)) * (newSize - index));
-    }
-
-    array->size = newSize;
-
-    return pointer;
-}
-
-void* arraySet(Array* array, int index, void* pointer) {
-    checkBounds(array, index);
-    void* old = array->contents[index];
-    array->contents[index] = pointer;
-    return old;
-}
-
-int arraySetSize(Array* array, int newSize) {
-    assert(array != NULL);
-    assert(newSize >= 0);
-   
-    int oldSize = array->size;
-    
-    if (newSize > oldSize) {
-        // Expand.
-        int result = ensureCapacity(array, newSize);
-        if (result < 0) {
-            return result;
-        }
-
-        // Zero out new entries.
-        memset(array->contents + sizeof(void*) * oldSize, 0,
-                sizeof(void*) * (newSize - oldSize));
-    }
-
-    array->size = newSize;
-
-    return 0;
-}
-
-int arraySize(Array* array) {
-    assert(array != NULL);
-    return array->size;
-}
-
-const void** arrayUnwrap(Array* array) {
-    return (const void**)array->contents;
-}
diff --git a/libcutils/buffer.c b/libcutils/buffer.c
deleted file mode 100644
index af99bd7..0000000
--- a/libcutils/buffer.c
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "buffer"
-
-#include <assert.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include "buffer.h"
-#include "loghack.h"
-
-Buffer* bufferCreate(size_t capacity) {
-    Buffer* buffer = malloc(sizeof(Buffer));
-    if (buffer == NULL) {
-        return NULL;
-    }
-    buffer->capacity = capacity;
-    buffer->expected = 0;
-    buffer->data = malloc(capacity);
-    if (buffer->data == NULL) {
-        free(buffer);
-        return NULL;
-    }
-    return buffer;
-}
-
-void bufferFree(Buffer* buffer) {
-    free(buffer->data);
-    free(buffer);
-}
-
-Buffer* bufferWrap(char* data, size_t capacity, size_t size) {
-    Buffer* buffer = malloc(sizeof(Buffer));
-    if (buffer == NULL) {
-        return NULL;
-    }
-
-    buffer->data = data;
-    buffer->capacity = capacity;
-    buffer->size = size;
-    buffer->expected = 0;
-    return buffer;
-}
-
-int bufferPrepareForRead(Buffer* buffer, size_t expected) {
-    if (expected > buffer->capacity) {
-        // Expand buffer.
-        char* expanded = realloc(buffer->data, expected);
-        if (expanded == NULL) {
-            errno = ENOMEM;
-            return -1;
-        }
-        buffer->capacity = expected;
-        buffer->data = expanded;
-    }
-
-    buffer->size = 0;
-    buffer->expected = expected;
-    return 0;
-}
-
-ssize_t bufferRead(Buffer* buffer, int fd) {
-    assert(buffer->size < buffer->expected);
-    
-    ssize_t bytesRead = read(fd, 
-            buffer->data + buffer->size, 
-            buffer->expected - buffer->size);
-
-    if (bytesRead > 0) {
-        buffer->size += bytesRead;
-        return buffer->size;        
-    }
-
-    return bytesRead;
-}
-
-void bufferPrepareForWrite(Buffer* buffer) {
-    buffer->remaining = buffer->size;
-}
-
-ssize_t bufferWrite(Buffer* buffer, int fd) {
-    assert(buffer->remaining > 0);
-    assert(buffer->remaining <= buffer->size);
-
-    ssize_t bytesWritten = write(fd, 
-            buffer->data + buffer->size - buffer->remaining,
-            buffer->remaining);
-
-    if (bytesWritten >= 0) {
-        buffer->remaining -= bytesWritten;
-
-        ALOGD("Buffer bytes written: %d", (int) bytesWritten);
-        ALOGD("Buffer size: %d", (int) buffer->size);
-        ALOGD("Buffer remaining: %d", (int) buffer->remaining);
-
-        return buffer->remaining;
-    }
-
-    return bytesWritten;
-}
-
diff --git a/libcutils/buffer.h b/libcutils/buffer.h
deleted file mode 100644
index d8bc108..0000000
--- a/libcutils/buffer.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2007 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.
- */
-
-/**
- * Byte buffer utilities.
- */
-
-#ifndef __BUFFER_H
-#define __BUFFER_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdlib.h>
-
-/** 
- * Byte buffer of known size. Keeps track of how much data has been read
- * into or written out of the buffer.
- */
-typedef struct {
-    /** Buffered data. */
-    char* data;
-
-    union {
-        /** For reading. # of bytes we expect. */
-        size_t expected;
-
-        /** For writing. # of bytes to write. */
-        size_t remaining;
-    };
-
-    /** Actual # of bytes in the buffer. */
-    size_t size;
-
-    /** Amount of memory allocated for this buffer. */
-    size_t capacity;
-} Buffer;
-
-/**
- * Returns true if all data has been read into the buffer.
- */
-#define bufferReadComplete(buffer) (buffer->expected == buffer->size)
-
-/**
- * Returns true if the buffer has been completely written.
- */
-#define bufferWriteComplete(buffer) (buffer->remaining == 0)
-
-/**
- * Creates a new buffer with the given initial capacity.
- */
-Buffer* bufferCreate(size_t initialCapacity);
-
-/**
- * Wraps an existing byte array.
- */
-Buffer* bufferWrap(char* data, size_t capacity, size_t size);
-
-/**
- * Frees and its data.
- */
-void bufferFree(Buffer* buffer);
-
-/**
- * Prepares buffer to read 'expected' number of bytes. Expands capacity if
- * necessary. Returns 0 if successful or -1 if an error occurs allocating
- * memory.
- */
-int bufferPrepareForRead(Buffer* buffer, size_t expected);
-
-/**
- * Reads some data into a buffer. Returns -1 in case of an error and sets 
- * errno (see read()). Returns 0 for EOF. Updates buffer->size and returns
- * the new size after a succesful read. 
- *
- * Precondition: buffer->size < buffer->expected
- */
-ssize_t bufferRead(Buffer* buffer, int fd);
-
-/**
- * Prepares a buffer to be written out.
- */
-void bufferPrepareForWrite(Buffer* buffer);
-
-/**
- * Writes data from buffer to the given fd. Returns -1 and sets errno in case
- * of an error. Updates buffer->remaining and returns the number of remaining
- * bytes to be written after a successful write. 
- *
- * Precondition: buffer->remaining > 0
- */
-ssize_t bufferWrite(Buffer* buffer, int fd);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __BUFFER_H */ 
diff --git a/libcutils/klog.c b/libcutils/klog.c
index 812af3b..d69fb10 100644
--- a/libcutils/klog.c
+++ b/libcutils/klog.c
@@ -40,6 +40,8 @@
 
     if (mknod(name, S_IFCHR | 0600, (1 << 8) | 11) == 0) {
         klog_fd = open(name, O_WRONLY);
+        if (klog_fd < 0)
+                return;
         fcntl(klog_fd, F_SETFD, FD_CLOEXEC);
         unlink(name);
     }
@@ -54,6 +56,7 @@
 
     if (level > klog_level) return;
     if (klog_fd < 0) klog_init();
+    if (klog_fd < 0) return;
 
     va_start(ap, fmt);
     vsnprintf(buf, LOG_BUF_MAX, fmt, ap);
diff --git a/libcutils/mq.c b/libcutils/mq.c
deleted file mode 100644
index 6f6740e..0000000
--- a/libcutils/mq.c
+++ /dev/null
@@ -1,1357 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "mq"
-
-#include <assert.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/un.h>
-#include <sys/uio.h>
-
-#include <cutils/array.h>
-#include <cutils/hashmap.h>
-#include <cutils/selector.h>
-
-#include "loghack.h"
-#include "buffer.h"
-
-/** Number of dead peers to remember. */
-#define PEER_HISTORY (16)
-
-typedef struct sockaddr SocketAddress;
-typedef struct sockaddr_un UnixAddress;
-
-/** 
- * Process/user/group ID. We don't use ucred directly because it's only 
- * available on Linux.
- */
-typedef struct {
-    pid_t pid;
-    uid_t uid;
-    gid_t gid;
-} Credentials;
-
-/** Listens for bytes coming from remote peers. */
-typedef void BytesListener(Credentials credentials, char* bytes, size_t size);
-
-/** Listens for the deaths of remote peers. */
-typedef void DeathListener(pid_t pid);
-
-/** Types of packets. */
-typedef enum {
-    /** Request for a connection to another peer. */
-    CONNECTION_REQUEST, 
-
-    /** A connection to another peer. */
-    CONNECTION, 
-
-    /** Reports a failed connection attempt. */
-    CONNECTION_ERROR, 
-
-    /** A generic packet of bytes. */
-    BYTES,
-} PacketType;
-
-typedef enum {
-    /** Reading a packet header. */
-    READING_HEADER,
-
-    /** Waiting for a connection from the master. */
-    ACCEPTING_CONNECTION,
-
-    /** Reading bytes. */
-    READING_BYTES,
-} InputState;
-
-/** A packet header. */
-// TODO: Use custom headers for master->peer, peer->master, peer->peer.
-typedef struct {
-    PacketType type;
-    union {
-        /** Packet size. Used for BYTES. */
-        size_t size;
-
-        /** Credentials. Used for CONNECTION and CONNECTION_REQUEST. */
-        Credentials credentials; 
-    };
-} Header;
-
-/** A packet which will be sent to a peer. */
-typedef struct OutgoingPacket OutgoingPacket;
-struct OutgoingPacket {
-    /** Packet header. */
-    Header header; 
-    
-    union {
-        /** Connection to peer. Used with CONNECTION. */
-        int socket;
-        
-        /** Buffer of bytes. Used with BYTES. */
-        Buffer* bytes;
-    };
-
-    /** Frees all resources associated with this packet. */
-    void (*free)(OutgoingPacket* packet);
-   
-    /** Optional context. */
-    void* context;
-    
-    /** Next packet in the queue. */
-    OutgoingPacket* nextPacket;
-};
-
-/** Represents a remote peer. */
-typedef struct PeerProxy PeerProxy;
-
-/** Local peer state. You typically have one peer per process. */
-typedef struct {
-    /** This peer's PID. */
-    pid_t pid;
-    
-    /** 
-     * Map from pid to peer proxy. The peer has a peer proxy for each remote
-     * peer it's connected to. 
-     *
-     * Acquire mutex before use.
-     */
-    Hashmap* peerProxies;
-
-    /** Manages I/O. */
-    Selector* selector;
-   
-    /** Used to synchronize operations with the selector thread. */
-    pthread_mutex_t mutex; 
-
-    /** Is this peer the master? */
-    bool master;
-
-    /** Peer proxy for the master. */
-    PeerProxy* masterProxy;
-    
-    /** Listens for packets from remote peers. */
-    BytesListener* onBytes;
-    
-    /** Listens for deaths of remote peers. */
-    DeathListener* onDeath;
-    
-    /** Keeps track of recently dead peers. Requires mutex. */
-    pid_t deadPeers[PEER_HISTORY];
-    size_t deadPeerCursor;
-} Peer;
-
-struct PeerProxy {
-    /** Credentials of the remote process. */
-    Credentials credentials;
-
-    /** Keeps track of data coming in from the remote peer. */
-    InputState inputState;
-    Buffer* inputBuffer;
-    PeerProxy* connecting;
-
-    /** File descriptor for this peer. */
-    SelectableFd* fd;
-
-    /** 
-     * Queue of packets to be written out to the remote peer.
-     *
-     * Requires mutex.
-     */
-    // TODO: Limit queue length.
-    OutgoingPacket* currentPacket;
-    OutgoingPacket* lastPacket;
-    
-    /** Used to write outgoing header. */
-    Buffer outgoingHeader;
-    
-    /** True if this is the master's proxy. */
-    bool master;
-
-    /** Reference back to the local peer. */
-    Peer* peer;
-
-    /**
-     * Used in master only. Maps this peer proxy to other peer proxies to
-     * which the peer has been connected to. Maps pid to PeerProxy. Helps
-     * keep track of which connections we've sent to whom.
-     */
-    Hashmap* connections;
-};
-
-/** Server socket path. */
-static const char* MASTER_PATH = "/master.peer";
-
-/** Credentials of the master peer. */
-static const Credentials MASTER_CREDENTIALS = {0, 0, 0};
-
-/** Creates a peer proxy and adds it to the peer proxy map. */
-static PeerProxy* peerProxyCreate(Peer* peer, Credentials credentials);
-
-/** Sets the non-blocking flag on a descriptor. */
-static void setNonBlocking(int fd) {
-    int flags;
-    if ((flags = fcntl(fd, F_GETFL, 0)) < 0) { 
-        LOG_ALWAYS_FATAL("fcntl() error: %s", strerror(errno));
-    } 
-    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) { 
-        LOG_ALWAYS_FATAL("fcntl() error: %s", strerror(errno));
-    } 
-}
-
-/** Closes a fd and logs a warning if the close fails. */
-static void closeWithWarning(int fd) {
-    int result = close(fd);
-    if (result == -1) {
-        ALOGW("close() error: %s", strerror(errno));
-    }
-}
-
-/** Hashes pid_t keys. */
-static int pidHash(void* key) {
-    pid_t* pid = (pid_t*) key;
-    return (int) (*pid);
-}
-
-/** Compares pid_t keys. */
-static bool pidEquals(void* keyA, void* keyB) {
-    pid_t* a = (pid_t*) keyA;
-    pid_t* b = (pid_t*) keyB;
-    return *a == *b;
-}
-
-/** Gets the master address. Not thread safe. */
-static UnixAddress* getMasterAddress() {
-    static UnixAddress masterAddress;
-    static bool initialized = false;
-    if (initialized == false) {
-        masterAddress.sun_family = AF_LOCAL;
-        strcpy(masterAddress.sun_path, MASTER_PATH); 
-        initialized = true;
-    }
-    return &masterAddress;
-}
-
-/** Gets exclusive access to the peer for this thread. */
-static void peerLock(Peer* peer) {
-    pthread_mutex_lock(&peer->mutex);
-}
-
-/** Releases exclusive access to the peer. */
-static void peerUnlock(Peer* peer) {
-    pthread_mutex_unlock(&peer->mutex);
-}
-
-/** Frees a simple, i.e. header-only, outgoing packet. */
-static void outgoingPacketFree(OutgoingPacket* packet) {
-    ALOGD("Freeing outgoing packet.");
-	free(packet);
-}
-
-/**
- * Prepare to read a new packet from the peer.
- */
-static void peerProxyExpectHeader(PeerProxy* peerProxy) {
-    peerProxy->inputState = READING_HEADER;
-    bufferPrepareForRead(peerProxy->inputBuffer, sizeof(Header));
-}
-
-/** Sets up the buffer for the outgoing header. */
-static void peerProxyPrepareOutgoingHeader(PeerProxy* peerProxy) {
-    peerProxy->outgoingHeader.data 
-        = (char*) &(peerProxy->currentPacket->header);
-    peerProxy->outgoingHeader.size = sizeof(Header);
-    bufferPrepareForWrite(&peerProxy->outgoingHeader);
-}
-
-/** Adds a packet to the end of the queue. Callers must have the mutex. */
-static void peerProxyEnqueueOutgoingPacket(PeerProxy* peerProxy,
-        OutgoingPacket* newPacket) {
-    newPacket->nextPacket = NULL; // Just in case.
-    if (peerProxy->currentPacket == NULL) {
-        // The queue is empty.
-        peerProxy->currentPacket = newPacket;
-        peerProxy->lastPacket = newPacket;
-        
-        peerProxyPrepareOutgoingHeader(peerProxy); 
-    } else {
-        peerProxy->lastPacket->nextPacket = newPacket;
-    }
-}
-
-/** Takes the peer lock and enqueues the given packet. */
-static void peerProxyLockAndEnqueueOutgoingPacket(PeerProxy* peerProxy,
-        OutgoingPacket* newPacket) {
-    Peer* peer = peerProxy->peer;
-    peerLock(peer);
-    peerProxyEnqueueOutgoingPacket(peerProxy, newPacket);
-    peerUnlock(peer);
-}
-
-/** 
- * Frees current packet and moves to the next one. Returns true if there is
- * a next packet or false if the queue is empty.
- */
-static bool peerProxyNextPacket(PeerProxy* peerProxy) {
-    Peer* peer = peerProxy->peer;
-    peerLock(peer);
-    
-    OutgoingPacket* current = peerProxy->currentPacket;
-    
-    if (current == NULL) {
-    	// The queue is already empty.
-        peerUnlock(peer);
-        return false;
-    }
-    
-    OutgoingPacket* next = current->nextPacket;
-    peerProxy->currentPacket = next;
-    current->nextPacket = NULL;
-    current->free(current);
-    if (next == NULL) {
-        // The queue is empty.
-        peerProxy->lastPacket = NULL;
-        peerUnlock(peer);
-        return false;
-    } else {
-        peerUnlock(peer);
-        peerProxyPrepareOutgoingHeader(peerProxy); 
-
-        // TODO: Start writing next packet? It would reduce the number of
-        // system calls, but we could also starve other peers.
-        return true;
-    }
-}
-
-/**
- * Checks whether a peer died recently.
- */
-static bool peerIsDead(Peer* peer, pid_t pid) {
-    size_t i;
-    for (i = 0; i < PEER_HISTORY; i++) {
-        pid_t deadPeer = peer->deadPeers[i];
-        if (deadPeer == 0) {
-            return false;
-        }
-        if (deadPeer == pid) {
-            return true;
-        }
-    }
-    return false;
-}
-
-/**
- * Cleans up connection information.
- */
-static bool peerProxyRemoveConnection(void* key, void* value, void* context) {
-    PeerProxy* deadPeer = (PeerProxy*) context;
-    PeerProxy* otherPeer = (PeerProxy*) value;
-    hashmapRemove(otherPeer->connections, &(deadPeer->credentials.pid));
-    return true;
-}
-
-/**
- * Called when the peer dies.
- */
-static void peerProxyKill(PeerProxy* peerProxy, bool errnoIsSet) {
-    if (errnoIsSet) {
-        ALOGI("Peer %d died. errno: %s", peerProxy->credentials.pid, 
-                strerror(errno));
-    } else {
-        ALOGI("Peer %d died.", peerProxy->credentials.pid);
-    }
-    
-    // If we lost the master, we're up a creek. We can't let this happen.
-    if (peerProxy->master) {    
-        LOG_ALWAYS_FATAL("Lost connection to master.");
-    }
-
-    Peer* localPeer = peerProxy->peer;
-    pid_t pid = peerProxy->credentials.pid;
-    
-    peerLock(localPeer);
-    
-    // Remember for awhile that the peer died.
-    localPeer->deadPeers[localPeer->deadPeerCursor] 
-        = peerProxy->credentials.pid;
-    localPeer->deadPeerCursor++;
-    if (localPeer->deadPeerCursor == PEER_HISTORY) {
-        localPeer->deadPeerCursor = 0;
-    }
-  
-    // Remove from peer map.
-    hashmapRemove(localPeer->peerProxies, &pid);
-    
-    // External threads can no longer get to this peer proxy, so we don't 
-    // need the lock anymore.
-    peerUnlock(localPeer);
-    
-    // Remove the fd from the selector.
-    if (peerProxy->fd != NULL) {
-        peerProxy->fd->remove = true;
-    }
-
-    // Clear outgoing packet queue.
-    while (peerProxyNextPacket(peerProxy)) {}
-
-    bufferFree(peerProxy->inputBuffer);
-
-    // This only applies to the master.
-    if (peerProxy->connections != NULL) {
-        // We can't leave these other maps pointing to freed memory.
-        hashmapForEach(peerProxy->connections, &peerProxyRemoveConnection, 
-                peerProxy);
-        hashmapFree(peerProxy->connections);
-    }
-
-    // Invoke death listener.
-    localPeer->onDeath(pid);
-
-    // Free the peer proxy itself.
-    free(peerProxy);
-}
-
-static void peerProxyHandleError(PeerProxy* peerProxy, char* functionName) {
-    if (errno == EINTR) {
-        // Log interruptions but otherwise ignore them.
-        ALOGW("%s() interrupted.", functionName);
-    } else if (errno == EAGAIN) {
-        ALOGD("EWOULDBLOCK");
-        // Ignore.
-    } else {
-        ALOGW("Error returned by %s().", functionName);
-        peerProxyKill(peerProxy, true);
-    }
-}
-
-/**
- * Buffers output sent to a peer. May be called multiple times until the entire
- * buffer is filled. Returns true when the buffer is empty.
- */
-static bool peerProxyWriteFromBuffer(PeerProxy* peerProxy, Buffer* outgoing) {
-    ssize_t size = bufferWrite(outgoing, peerProxy->fd->fd);
-    if (size < 0) {
-        peerProxyHandleError(peerProxy, "write");
-        return false;
-    } else {
-        return bufferWriteComplete(outgoing);
-    }
-}
-
-/** Writes packet bytes to peer. */
-static void peerProxyWriteBytes(PeerProxy* peerProxy) {	
-	Buffer* buffer = peerProxy->currentPacket->bytes;
-	if (peerProxyWriteFromBuffer(peerProxy, buffer)) {
-        ALOGD("Bytes written.");
-        peerProxyNextPacket(peerProxy);
-    }    
-}
-
-/** Sends a socket to the peer. */
-static void peerProxyWriteConnection(PeerProxy* peerProxy) {
-    int socket = peerProxy->currentPacket->socket;
-
-    // Why does sending and receiving fds have to be such a PITA?
-    struct msghdr msg;
-    struct iovec iov[1];
-    
-    union {
-        struct cmsghdr cm;
-        char control[CMSG_SPACE(sizeof(int))];
-    } control_un;
-   
-    struct cmsghdr *cmptr;
-    
-    msg.msg_control = control_un.control;
-    msg.msg_controllen = sizeof(control_un.control);
-    cmptr = CMSG_FIRSTHDR(&msg);
-    cmptr->cmsg_len = CMSG_LEN(sizeof(int));
-    cmptr->cmsg_level = SOL_SOCKET;
-    cmptr->cmsg_type = SCM_RIGHTS;
-   
-    // Store the socket in the message.
-    *((int *) CMSG_DATA(cmptr)) = peerProxy->currentPacket->socket;
-
-    msg.msg_name = NULL;
-    msg.msg_namelen = 0;
-    iov[0].iov_base = "";
-    iov[0].iov_len = 1;
-    msg.msg_iov = iov;
-    msg.msg_iovlen = 1;
-
-    ssize_t result = sendmsg(peerProxy->fd->fd, &msg, 0);
-    
-    if (result < 0) {
-        peerProxyHandleError(peerProxy, "sendmsg");
-    } else {
-        // Success. Queue up the next packet.
-        peerProxyNextPacket(peerProxy);
-        
-    }
-}
-
-/**
- * Writes some outgoing data.
- */
-static void peerProxyWrite(SelectableFd* fd) {
-    // TODO: Try to write header and body with one system call.
-
-    PeerProxy* peerProxy = (PeerProxy*) fd->data;
-    OutgoingPacket* current = peerProxy->currentPacket;
-    
-    if (current == NULL) {
-        // We have nothing left to write.
-        return;
-    }
-
-    // Write the header.
-    Buffer* outgoingHeader = &peerProxy->outgoingHeader;
-    bool headerWritten = bufferWriteComplete(outgoingHeader);
-    if (!headerWritten) {
-        ALOGD("Writing header...");
-        headerWritten = peerProxyWriteFromBuffer(peerProxy, outgoingHeader);
-        if (headerWritten) {
-            ALOGD("Header written.");
-        }
-    }    
-
-    // Write body.
-    if (headerWritten) {
-        PacketType type = current->header.type;
-        switch (type) {
-            case CONNECTION:
-                peerProxyWriteConnection(peerProxy);
-                break;
-            case BYTES:
-                peerProxyWriteBytes(peerProxy);
-                break;
-            case CONNECTION_REQUEST:
-            case CONNECTION_ERROR:
-                // These packets consist solely of a header.
-                peerProxyNextPacket(peerProxy);
-                break;
-            default:
-                LOG_ALWAYS_FATAL("Unknown packet type: %d", type); 
-        }
-    }
-}
-
-/**
- * Sets up a peer proxy's fd before we try to select() it.
- */
-static void peerProxyBeforeSelect(SelectableFd* fd) {
-    ALOGD("Before select...");
-
-    PeerProxy* peerProxy = (PeerProxy*) fd->data;
-  
-    peerLock(peerProxy->peer);
-    bool hasPackets = peerProxy->currentPacket != NULL;
-    peerUnlock(peerProxy->peer);
-    
-    if (hasPackets) {
-        ALOGD("Packets found. Setting onWritable().");
-            
-        fd->onWritable = &peerProxyWrite;
-    } else {
-        // We have nothing to write.
-        fd->onWritable = NULL;
-    }
-}
-
-/** Prepare to read bytes from the peer. */
-static void peerProxyExpectBytes(PeerProxy* peerProxy, Header* header) {
-    ALOGD("Expecting %d bytes.", header->size);
-
-    peerProxy->inputState = READING_BYTES;
-    if (bufferPrepareForRead(peerProxy->inputBuffer, header->size) == -1) {
-        ALOGW("Couldn't allocate memory for incoming data. Size: %u",
-                (unsigned int) header->size);    
-        
-        // TODO: Ignore the packet and log a warning?
-        peerProxyKill(peerProxy, false);
-    }
-}
-
-/**
- * Gets a peer proxy for the given ID. Creates a peer proxy if necessary.
- * Sends a connection request to the master if desired.
- *
- * Returns NULL if an error occurs. Sets errno to EHOSTDOWN if the peer died
- * or ENOMEM if memory couldn't be allocated.
- */
-static PeerProxy* peerProxyGetOrCreate(Peer* peer, pid_t pid, 
-        bool requestConnection) {
-    if (pid == peer->pid) {
-        errno = EINVAL;
-        return NULL;
-    }
-    
-    if (peerIsDead(peer, pid)) {
-        errno = EHOSTDOWN;
-        return NULL;
-    }
-    
-    PeerProxy* peerProxy = hashmapGet(peer->peerProxies, &pid);
-    if (peerProxy != NULL) {
-        return peerProxy;
-    }
-
-    // If this is the master peer, we already know about all peers.
-    if (peer->master) {
-        errno = EHOSTDOWN;
-        return NULL;
-    }
-
-    // Try to create a peer proxy.
-    Credentials credentials;
-    credentials.pid = pid;
-
-    // Fake gid and uid until we have the real thing. The real creds are
-    // filled in by masterProxyExpectConnection(). These fake creds will
-    // never be exposed to the user.
-    credentials.uid = 0;
-    credentials.gid = 0;
-
-    // Make sure we can allocate the connection request packet.
-    OutgoingPacket* packet = NULL;
-    if (requestConnection) {
-        packet = calloc(1, sizeof(OutgoingPacket));
-        if (packet == NULL) {
-            errno = ENOMEM;
-            return NULL;
-        }
-
-        packet->header.type = CONNECTION_REQUEST;
-        packet->header.credentials = credentials;
-        packet->free = &outgoingPacketFree;
-    }
-    
-    peerProxy = peerProxyCreate(peer, credentials);
-    if (peerProxy == NULL) {
-        free(packet);
-        errno = ENOMEM;
-        return NULL;
-    } else {
-        // Send a connection request to the master.
-        if (requestConnection) {
-            PeerProxy* masterProxy = peer->masterProxy;
-            peerProxyEnqueueOutgoingPacket(masterProxy, packet);
-        }
-        
-        return peerProxy;
-    }
-}
-
-/**
- * Switches the master peer proxy into a state where it's waiting for a
- * connection from the master.
- */
-static void masterProxyExpectConnection(PeerProxy* masterProxy,
-        Header* header) {
-    // TODO: Restructure things so we don't need this check.
-    // Verify that this really is the master.
-    if (!masterProxy->master) {
-        ALOGW("Non-master process %d tried to send us a connection.", 
-            masterProxy->credentials.pid);
-        // Kill off the evil peer.
-        peerProxyKill(masterProxy, false);
-        return;
-    }
-    
-    masterProxy->inputState = ACCEPTING_CONNECTION;
-    Peer* localPeer = masterProxy->peer;
-   
-    // Create a peer proxy so we have somewhere to stash the creds.
-    // See if we already have a proxy set up.
-    pid_t pid = header->credentials.pid;
-    peerLock(localPeer);
-    PeerProxy* peerProxy = peerProxyGetOrCreate(localPeer, pid, false);
-    if (peerProxy == NULL) {
-        ALOGW("Peer proxy creation failed: %s", strerror(errno));
-    } else {
-        // Fill in full credentials.
-        peerProxy->credentials = header->credentials;
-    }
-    peerUnlock(localPeer);
-    
-    // Keep track of which peer proxy we're accepting a connection for.
-    masterProxy->connecting = peerProxy;
-}
-
-/**
- * Reads input from a peer process.
- */
-static void peerProxyRead(SelectableFd* fd);
-
-/** Sets up fd callbacks. */
-static void peerProxySetFd(PeerProxy* peerProxy, SelectableFd* fd) {
-    peerProxy->fd = fd;
-    fd->data = peerProxy;
-    fd->onReadable = &peerProxyRead;
-    fd->beforeSelect = &peerProxyBeforeSelect;
-    
-    // Make the socket non-blocking.
-    setNonBlocking(fd->fd);
-}
-
-/**
- * Accepts a connection sent by the master proxy.
- */
-static void masterProxyAcceptConnection(PeerProxy* masterProxy) {
-    struct msghdr msg;
-    struct iovec iov[1];
-    ssize_t size;
-    char ignored;
-    int incomingFd;
-    
-    // TODO: Reuse code which writes the connection. Who the heck designed
-    // this API anyway?
-    union {
-        struct cmsghdr cm;
-        char control[CMSG_SPACE(sizeof(int))];
-    } control_un;
-    struct cmsghdr *cmptr;
-    msg.msg_control = control_un.control;
-    msg.msg_controllen = sizeof(control_un.control);
-
-    msg.msg_name = NULL;
-    msg.msg_namelen = 0;
-
-    // We sent 1 byte of data so we can detect EOF.
-    iov[0].iov_base = &ignored;
-    iov[0].iov_len = 1;
-    msg.msg_iov = iov;
-    msg.msg_iovlen = 1;
-
-    size = recvmsg(masterProxy->fd->fd, &msg, 0);
-    if (size < 0) {
-        if (errno == EINTR) {
-            // Log interruptions but otherwise ignore them.
-            ALOGW("recvmsg() interrupted.");
-            return;
-        } else if (errno == EAGAIN) {
-            // Keep waiting for the connection.
-            return;
-        } else {
-            LOG_ALWAYS_FATAL("Error reading connection from master: %s",
-                    strerror(errno));
-        }
-    } else if (size == 0) {
-        // EOF.
-        LOG_ALWAYS_FATAL("Received EOF from master.");
-    }
-
-    // Extract fd from message.
-    if ((cmptr = CMSG_FIRSTHDR(&msg)) != NULL 
-            && cmptr->cmsg_len == CMSG_LEN(sizeof(int))) {
-        if (cmptr->cmsg_level != SOL_SOCKET) {
-            LOG_ALWAYS_FATAL("Expected SOL_SOCKET.");
-        }
-        if (cmptr->cmsg_type != SCM_RIGHTS) {
-            LOG_ALWAYS_FATAL("Expected SCM_RIGHTS.");
-        }
-        incomingFd = *((int*) CMSG_DATA(cmptr));
-    } else {
-        LOG_ALWAYS_FATAL("Expected fd.");
-    }
-    
-    // The peer proxy this connection is for.
-    PeerProxy* peerProxy = masterProxy->connecting;
-    if (peerProxy == NULL) {
-        ALOGW("Received connection for unknown peer.");
-        closeWithWarning(incomingFd);
-    } else {
-        Peer* peer = masterProxy->peer;
-        
-        SelectableFd* selectableFd = selectorAdd(peer->selector, incomingFd);
-        if (selectableFd == NULL) {
-            ALOGW("Error adding fd to selector for %d.",
-                    peerProxy->credentials.pid);
-            closeWithWarning(incomingFd);
-            peerProxyKill(peerProxy, false);
-        }
-
-        peerProxySetFd(peerProxy, selectableFd);
-    }
-    
-    peerProxyExpectHeader(masterProxy);
-}
-
-/**
- * Frees an outgoing packet containing a connection.
- */
-static void outgoingPacketFreeSocket(OutgoingPacket* packet) {
-    closeWithWarning(packet->socket);
-    outgoingPacketFree(packet);
-}
-
-/**
- * Connects two known peers.
- */
-static void masterConnectPeers(PeerProxy* peerA, PeerProxy* peerB) {
-    int sockets[2];
-    int result = socketpair(AF_LOCAL, SOCK_STREAM, 0, sockets);
-    if (result == -1) {
-        ALOGW("socketpair() error: %s", strerror(errno));
-        // TODO: Send CONNECTION_FAILED packets to peers.
-        return;
-    }
-
-    OutgoingPacket* packetA = calloc(1, sizeof(OutgoingPacket));
-    OutgoingPacket* packetB = calloc(1, sizeof(OutgoingPacket));
-    if (packetA == NULL || packetB == NULL) {
-        free(packetA);
-        free(packetB);
-        ALOGW("malloc() error. Failed to tell process %d that process %d is"
-                " dead.", peerA->credentials.pid, peerB->credentials.pid);
-        return;
-    }
-   
-    packetA->header.type = CONNECTION;
-    packetB->header.type = CONNECTION;
-    
-    packetA->header.credentials = peerB->credentials;
-    packetB->header.credentials = peerA->credentials;
-
-    packetA->socket = sockets[0];
-    packetB->socket = sockets[1];
-
-    packetA->free = &outgoingPacketFreeSocket;
-    packetB->free = &outgoingPacketFreeSocket;
-   
-    peerLock(peerA->peer);
-    peerProxyEnqueueOutgoingPacket(peerA, packetA);   
-    peerProxyEnqueueOutgoingPacket(peerB, packetB);   
-    peerUnlock(peerA->peer);
-}
-
-/**
- * Informs a peer that the peer they're trying to connect to couldn't be
- * found.
- */
-static void masterReportConnectionError(PeerProxy* peerProxy,
-        Credentials credentials) {
-    OutgoingPacket* packet = calloc(1, sizeof(OutgoingPacket));
-    if (packet == NULL) {
-        ALOGW("malloc() error. Failed to tell process %d that process %d is"
-                " dead.", peerProxy->credentials.pid, credentials.pid);
-        return;
-    }
-   
-    packet->header.type = CONNECTION_ERROR;
-    packet->header.credentials = credentials;
-    packet->free = &outgoingPacketFree;
-    
-    peerProxyLockAndEnqueueOutgoingPacket(peerProxy, packet);   
-}
-
-/**
- * Handles a request to be connected to another peer.
- */
-static void masterHandleConnectionRequest(PeerProxy* peerProxy, 
-        Header* header) {
-    Peer* master = peerProxy->peer;
-    pid_t targetPid = header->credentials.pid;
-    if (!hashmapContainsKey(peerProxy->connections, &targetPid)) {
-        // We haven't connected these peers yet.
-        PeerProxy* targetPeer 
-            = (PeerProxy*) hashmapGet(master->peerProxies, &targetPid);
-        if (targetPeer == NULL) {
-            // Unknown process.
-            masterReportConnectionError(peerProxy, header->credentials);
-        } else {
-            masterConnectPeers(peerProxy, targetPeer);
-        }
-    }
-    
-    // This packet is complete. Get ready for the next one.
-    peerProxyExpectHeader(peerProxy);
-}
-
-/**
- * The master told us this peer is dead.
- */
-static void masterProxyHandleConnectionError(PeerProxy* masterProxy,
-        Header* header) {
-    Peer* peer = masterProxy->peer;
-    
-    // Look up the peer proxy.
-    pid_t pid = header->credentials.pid;
-    PeerProxy* peerProxy = NULL;
-    peerLock(peer);
-    peerProxy = hashmapGet(peer->peerProxies, &pid);
-    peerUnlock(peer);
-
-    if (peerProxy != NULL) {
-        ALOGI("Couldn't connect to %d.", pid);
-        peerProxyKill(peerProxy, false);
-    } else {
-        ALOGW("Peer proxy for %d not found. This shouldn't happen.", pid);
-    }
-    
-    peerProxyExpectHeader(masterProxy);
-}
-
-/**
- * Handles a packet header.
- */
-static void peerProxyHandleHeader(PeerProxy* peerProxy, Header* header) {
-    switch (header->type) {
-        case CONNECTION_REQUEST:
-            masterHandleConnectionRequest(peerProxy, header);
-            break;
-        case CONNECTION:
-            masterProxyExpectConnection(peerProxy, header);
-            break;
-        case CONNECTION_ERROR:
-            masterProxyHandleConnectionError(peerProxy, header);
-            break;
-        case BYTES:    
-            peerProxyExpectBytes(peerProxy, header);
-            break;
-        default:
-            ALOGW("Invalid packet type from %d: %d", peerProxy->credentials.pid, 
-                    header->type);
-            peerProxyKill(peerProxy, false);
-    }
-}
-
-/**
- * Buffers input sent by peer. May be called multiple times until the entire
- * buffer is filled. Returns true when the buffer is full.
- */
-static bool peerProxyBufferInput(PeerProxy* peerProxy) {
-    Buffer* in = peerProxy->inputBuffer;
-    ssize_t size = bufferRead(in, peerProxy->fd->fd);
-    if (size < 0) {
-        peerProxyHandleError(peerProxy, "read");
-        return false;
-    } else if (size == 0) {
-        // EOF.
-    	ALOGI("EOF");
-        peerProxyKill(peerProxy, false);
-        return false;
-    } else if (bufferReadComplete(in)) {
-        // We're done!
-        return true;
-    } else {
-        // Continue reading.
-        return false;
-    }
-}
-
-/**
- * Reads input from a peer process.
- */
-static void peerProxyRead(SelectableFd* fd) {
-    ALOGD("Reading...");
-    PeerProxy* peerProxy = (PeerProxy*) fd->data;
-    int state = peerProxy->inputState;
-    Buffer* in = peerProxy->inputBuffer;
-    switch (state) {
-        case READING_HEADER:
-            if (peerProxyBufferInput(peerProxy)) {
-                ALOGD("Header read.");
-                // We've read the complete header.
-                Header* header = (Header*) in->data;
-                peerProxyHandleHeader(peerProxy, header);
-            }
-            break;
-        case READING_BYTES:
-            ALOGD("Reading bytes...");
-            if (peerProxyBufferInput(peerProxy)) {
-                ALOGD("Bytes read.");
-                // We have the complete packet. Notify bytes listener.
-                peerProxy->peer->onBytes(peerProxy->credentials,
-                    in->data, in->size);
-                        
-                // Get ready for the next packet.
-                peerProxyExpectHeader(peerProxy);
-            }
-            break;
-        case ACCEPTING_CONNECTION:
-            masterProxyAcceptConnection(peerProxy);
-            break;
-        default:
-            LOG_ALWAYS_FATAL("Unknown state: %d", state);
-    }
-}
-
-static PeerProxy* peerProxyCreate(Peer* peer, Credentials credentials) {
-    PeerProxy* peerProxy = calloc(1, sizeof(PeerProxy));
-    if (peerProxy == NULL) {
-        return NULL;
-    }
-   
-    peerProxy->inputBuffer = bufferCreate(sizeof(Header));
-    if (peerProxy->inputBuffer == NULL) {
-        free(peerProxy);
-        return NULL;
-    }
-
-    peerProxy->peer = peer;
-    peerProxy->credentials = credentials;
-
-    // Initial state == expecting a header.
-    peerProxyExpectHeader(peerProxy); 
-  
-    // Add this proxy to the map. Make sure the key points to the stable memory
-    // inside of the peer proxy itself.
-    pid_t* pid = &(peerProxy->credentials.pid);
-    hashmapPut(peer->peerProxies, pid, peerProxy);
-    return peerProxy;
-}
-
-/** Accepts a connection to the master peer. */
-static void masterAcceptConnection(SelectableFd* listenerFd) {
-    // Accept connection.
-    int socket = accept(listenerFd->fd, NULL, NULL);
-    if (socket == -1) {
-        ALOGW("accept() error: %s", strerror(errno));
-        return;
-    }
-    
-    ALOGD("Accepted connection as fd %d.", socket);
-    
-    // Get credentials.
-    Credentials credentials;
-    struct ucred ucredentials;
-    socklen_t credentialsSize = sizeof(struct ucred);
-    int result = getsockopt(socket, SOL_SOCKET, SO_PEERCRED, 
-                &ucredentials, &credentialsSize);
-    // We might want to verify credentialsSize.
-    if (result == -1) {
-        ALOGW("getsockopt() error: %s", strerror(errno));
-        closeWithWarning(socket);
-        return;
-    }
-
-    // Copy values into our own structure so we know we have the types right.
-    credentials.pid = ucredentials.pid;
-    credentials.uid = ucredentials.uid;
-    credentials.gid = ucredentials.gid;
-    
-    ALOGI("Accepted connection from process %d.", credentials.pid);
-   
-    Peer* masterPeer = (Peer*) listenerFd->data;
-    
-    peerLock(masterPeer);
-    
-    // Make sure we don't already have a connection from that process.
-    PeerProxy* peerProxy 
-        = hashmapGet(masterPeer->peerProxies, &credentials.pid);
-    if (peerProxy != NULL) {
-        peerUnlock(masterPeer);
-        ALOGW("Alread connected to process %d.", credentials.pid);
-        closeWithWarning(socket);
-        return;
-    }
-   
-    // Add connection to the selector.
-    SelectableFd* socketFd = selectorAdd(masterPeer->selector, socket);
-    if (socketFd == NULL) {
-        peerUnlock(masterPeer);
-        ALOGW("malloc() failed.");
-        closeWithWarning(socket);
-        return;
-    }
-
-    // Create a peer proxy.
-    peerProxy = peerProxyCreate(masterPeer, credentials);
-    peerUnlock(masterPeer);
-    if (peerProxy == NULL) {
-        ALOGW("malloc() failed.");
-        socketFd->remove = true;
-        closeWithWarning(socket);
-    }
-    peerProxy->connections = hashmapCreate(10, &pidHash, &pidEquals);
-    peerProxySetFd(peerProxy, socketFd);
-}
-
-/**
- * Creates the local peer.
- */
-static Peer* peerCreate() {
-    Peer* peer = calloc(1, sizeof(Peer));
-    if (peer == NULL) {
-        LOG_ALWAYS_FATAL("malloc() error.");
-    }
-    peer->peerProxies = hashmapCreate(10, &pidHash, &pidEquals);
-    peer->selector = selectorCreate();
-    
-    pthread_mutexattr_t attributes;
-    if (pthread_mutexattr_init(&attributes) != 0) {
-        LOG_ALWAYS_FATAL("pthread_mutexattr_init() error.");
-    }
-    if (pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE) != 0) {
-        LOG_ALWAYS_FATAL("pthread_mutexattr_settype() error.");
-    }
-    if (pthread_mutex_init(&peer->mutex, &attributes) != 0) {
-        LOG_ALWAYS_FATAL("pthread_mutex_init() error.");
-    }
-    
-    peer->pid = getpid();
-    return peer;
-}
-
-/** The local peer. */
-static Peer* localPeer;
-
-/** Frees a packet of bytes. */
-static void outgoingPacketFreeBytes(OutgoingPacket* packet) {
-    ALOGD("Freeing outgoing packet.");
-    bufferFree(packet->bytes);
-    free(packet);
-}
-
-/**
- * Sends a packet of bytes to a remote peer. Returns 0 on success.
- *
- * Returns -1 if an error occurs. Sets errno to ENOMEM if memory couldn't be
- * allocated. Sets errno to EHOSTDOWN if the peer died recently. Sets errno
- * to EINVAL if pid is the same as the local pid.
- */
-int peerSendBytes(pid_t pid, const char* bytes, size_t size) {
-	Peer* peer = localPeer;
-    assert(peer != NULL);
-
-    OutgoingPacket* packet = calloc(1, sizeof(OutgoingPacket));
-    if (packet == NULL) {
-        errno = ENOMEM;
-        return -1;
-    }
-
-    Buffer* copy = bufferCreate(size); 
-    if (copy == NULL) {
-        free(packet);
-        errno = ENOMEM;
-        return -1;
-    }
-
-    // Copy data.
-    memcpy(copy->data, bytes, size);
-    copy->size = size;
-    
-    packet->bytes = copy;
-    packet->header.type = BYTES;
-    packet->header.size = size;
-    packet->free = outgoingPacketFreeBytes;
-    bufferPrepareForWrite(packet->bytes);
-    
-    peerLock(peer);
-    
-    PeerProxy* peerProxy = peerProxyGetOrCreate(peer, pid, true);
-    if (peerProxy == NULL) {
-        // The peer is already dead or we couldn't alloc memory. Either way,
-        // errno is set.
-        peerUnlock(peer);
-        packet->free(packet); 
-        return -1;
-    } else {
-        peerProxyEnqueueOutgoingPacket(peerProxy, packet);
-        peerUnlock(peer);
-        selectorWakeUp(peer->selector);
-        return 0; 
-    }
-}
-
-/** Keeps track of how to free shared bytes. */
-typedef struct {
-    void (*free)(void* context);
-    void* context;
-} SharedBytesFreer;
-
-/** Frees shared bytes. */
-static void outgoingPacketFreeSharedBytes(OutgoingPacket* packet) {
-    SharedBytesFreer* sharedBytesFreer 
-        = (SharedBytesFreer*) packet->context;
-    sharedBytesFreer->free(sharedBytesFreer->context);
-    free(sharedBytesFreer);
-    free(packet);
-}
-
-/**
- * Sends a packet of bytes to a remote peer without copying the bytes. Calls
- * free() with context after the bytes have been sent.
- *
- * Returns -1 if an error occurs. Sets errno to ENOMEM if memory couldn't be
- * allocated. Sets errno to EHOSTDOWN if the peer died recently. Sets errno
- * to EINVAL if pid is the same as the local pid.
- */
-int peerSendSharedBytes(pid_t pid, char* bytes, size_t size,
-        void (*free)(void* context), void* context) {
-    Peer* peer = localPeer;
-    assert(peer != NULL);
-
-    OutgoingPacket* packet = calloc(1, sizeof(OutgoingPacket));
-    if (packet == NULL) {
-        errno = ENOMEM;
-        return -1;
-    }
-
-    Buffer* wrapper = bufferWrap(bytes, size, size);
-    if (wrapper == NULL) {
-        free(packet);
-        errno = ENOMEM;
-        return -1;
-    }
-
-    SharedBytesFreer* sharedBytesFreer = malloc(sizeof(SharedBytesFreer));
-    if (sharedBytesFreer == NULL) {
-        free(packet);
-        free(wrapper);
-        errno = ENOMEM;
-        return -1;
-    }
-    sharedBytesFreer->free = free;
-    sharedBytesFreer->context = context;
-    
-    packet->bytes = wrapper;
-    packet->context = sharedBytesFreer;
-    packet->header.type = BYTES;
-    packet->header.size = size;
-    packet->free = &outgoingPacketFreeSharedBytes;
-    bufferPrepareForWrite(packet->bytes);
-    
-    peerLock(peer);
-    
-    PeerProxy* peerProxy = peerProxyGetOrCreate(peer, pid, true);
-    if (peerProxy == NULL) {
-        // The peer is already dead or we couldn't alloc memory. Either way,
-        // errno is set.
-        peerUnlock(peer);
-        packet->free(packet); 
-        return -1;
-    } else {
-        peerProxyEnqueueOutgoingPacket(peerProxy, packet);
-        peerUnlock(peer);
-        selectorWakeUp(peer->selector);
-        return 0; 
-    }
-}
-
-/**
- * Starts the master peer. The master peer differs from other peers in that
- * it is responsible for connecting the other peers. You can only have one
- * master peer.
- *
- * Goes into an I/O loop and does not return.
- */
-void masterPeerInitialize(BytesListener* bytesListener, 
-        DeathListener* deathListener) {
-    // Create and bind socket.
-    int listenerSocket = socket(AF_LOCAL, SOCK_STREAM, 0);
-    if (listenerSocket == -1) {
-        LOG_ALWAYS_FATAL("socket() error: %s", strerror(errno));
-    }
-    unlink(MASTER_PATH);
-    int result = bind(listenerSocket, (SocketAddress*) getMasterAddress(), 
-            sizeof(UnixAddress));
-    if (result == -1) {
-        LOG_ALWAYS_FATAL("bind() error: %s", strerror(errno));
-    }
-
-    ALOGD("Listener socket: %d",  listenerSocket);
-    
-    // Queue up to 16 connections.
-    result = listen(listenerSocket, 16);
-    if (result != 0) {
-        LOG_ALWAYS_FATAL("listen() error: %s", strerror(errno));
-    }
-
-    // Make socket non-blocking.
-    setNonBlocking(listenerSocket);
-
-    // Create the peer for this process. Fail if we already have one.
-    if (localPeer != NULL) {
-        LOG_ALWAYS_FATAL("Peer is already initialized.");
-    }
-    localPeer = peerCreate();
-    if (localPeer == NULL) {
-        LOG_ALWAYS_FATAL("malloc() failed.");
-    }
-    localPeer->master = true;
-    localPeer->onBytes = bytesListener;
-    localPeer->onDeath = deathListener;
-    
-    // Make listener socket selectable.
-    SelectableFd* listenerFd = selectorAdd(localPeer->selector, listenerSocket);
-    if (listenerFd == NULL) {
-        LOG_ALWAYS_FATAL("malloc() error.");
-    }
-    listenerFd->data = localPeer;
-    listenerFd->onReadable = &masterAcceptConnection;
-}
-
-/**
- * Starts a local peer.
- *
- * Goes into an I/O loop and does not return.
- */
-void peerInitialize(BytesListener* bytesListener, 
-        DeathListener* deathListener) {
-    // Connect to master peer.
-    int masterSocket = socket(AF_LOCAL, SOCK_STREAM, 0);
-    if (masterSocket == -1) {
-        LOG_ALWAYS_FATAL("socket() error: %s", strerror(errno));
-    }
-    int result = connect(masterSocket, (SocketAddress*) getMasterAddress(),
-            sizeof(UnixAddress));
-    if (result != 0) {
-        LOG_ALWAYS_FATAL("connect() error: %s", strerror(errno));
-    }
-
-    // Create the peer for this process. Fail if we already have one.
-    if (localPeer != NULL) {
-        LOG_ALWAYS_FATAL("Peer is already initialized.");
-    }
-    localPeer = peerCreate();
-    if (localPeer == NULL) {
-        LOG_ALWAYS_FATAL("malloc() failed.");
-    }
-    localPeer->onBytes = bytesListener;
-    localPeer->onDeath = deathListener;
-    
-    // Make connection selectable.
-    SelectableFd* masterFd = selectorAdd(localPeer->selector, masterSocket);
-    if (masterFd == NULL) {
-        LOG_ALWAYS_FATAL("malloc() error.");
-    }
-
-    // Create a peer proxy for the master peer.
-    PeerProxy* masterProxy = peerProxyCreate(localPeer, MASTER_CREDENTIALS);
-    if (masterProxy == NULL) {
-        LOG_ALWAYS_FATAL("malloc() error.");
-    }
-    peerProxySetFd(masterProxy, masterFd);
-    masterProxy->master = true;
-    localPeer->masterProxy = masterProxy;
-}
-
-/** Starts the master peer I/O loop. Doesn't return. */
-void peerLoop() {
-    assert(localPeer != NULL);
-    
-    // Start selector.
-    selectorLoop(localPeer->selector);
-}
-
diff --git a/libcutils/qsort_r_compat.c b/libcutils/qsort_r_compat.c
deleted file mode 100644
index 8971cb5..0000000
--- a/libcutils/qsort_r_compat.c
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdlib.h>
-#include <cutils/qsort_r_compat.h>
-
-#if HAVE_BSD_QSORT_R
-
-/*
- * BSD qsort_r parameter order is as we have defined here.
- */
-
-void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
-        int (*compar)(void*, const void* , const void*)) {
-    qsort_r(base, nel, width, thunk, compar);
-}
-
-#elif HAVE_GNU_QSORT_R
-
-/*
- * GNU qsort_r parameter order places the thunk parameter last.
- */
-
-struct compar_data {
-    void* thunk;
-    int (*compar)(void*, const void* , const void*);
-};
-
-static int compar_wrapper(const void* a, const void* b, void* data) {
-    struct compar_data* compar_data = (struct compar_data*)data;
-    return compar_data->compar(compar_data->thunk, a, b);
-}
-
-void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
-        int (*compar)(void*, const void* , const void*)) {
-    struct compar_data compar_data;
-    compar_data.thunk = thunk;
-    compar_data.compar = compar;
-    qsort_r(base, nel, width, compar_wrapper, &compar_data);
-}
-
-#else
-
-/*
- * Emulate qsort_r using thread local storage to access the thunk data.
- */
-
-#include <cutils/threads.h>
-
-static thread_store_t compar_data_key = THREAD_STORE_INITIALIZER;
-
-struct compar_data {
-    void* thunk;
-    int (*compar)(void*, const void* , const void*);
-};
-
-static int compar_wrapper(const void* a, const void* b) {
-    struct compar_data* compar_data = (struct compar_data*)thread_store_get(&compar_data_key);
-    return compar_data->compar(compar_data->thunk, a, b);
-}
-
-void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
-        int (*compar)(void*, const void* , const void*)) {
-    struct compar_data compar_data;
-    compar_data.thunk = thunk;
-    compar_data.compar = compar;
-    thread_store_set(&compar_data_key, &compar_data, NULL);
-    qsort(base, nel, width, compar_wrapper);
-}
-
-#endif
diff --git a/libcutils/record_stream.c b/libcutils/record_stream.c
deleted file mode 100644
index 6994904..0000000
--- a/libcutils/record_stream.c
+++ /dev/null
@@ -1,186 +0,0 @@
-/* libs/cutils/record_stream.c
-**
-** Copyright 2006, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License"); 
-** you may not use this file except in compliance with the License. 
-** You may obtain a copy of the License at 
-**
-**     http://www.apache.org/licenses/LICENSE-2.0 
-**
-** Unless required by applicable law or agreed to in writing, software 
-** distributed under the License is distributed on an "AS IS" BASIS, 
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
-** See the License for the specific language governing permissions and 
-** limitations under the License.
-*/
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <assert.h>
-#include <errno.h>
-#include <cutils/record_stream.h>
-#include <string.h>
-#include <stdint.h>
-#ifdef HAVE_WINSOCK
-#include <winsock2.h>   /* for ntohl */
-#else
-#include <netinet/in.h>
-#endif
-
-#define HEADER_SIZE 4
-
-struct RecordStream {
-    int fd;
-    size_t maxRecordLen;
-
-    unsigned char *buffer;
-
-    unsigned char *unconsumed;
-    unsigned char *read_end;
-    unsigned char *buffer_end;
-};
-
-
-extern RecordStream *record_stream_new(int fd, size_t maxRecordLen)
-{
-    RecordStream *ret;
-
-    assert (maxRecordLen <= 0xffff);
-
-    ret = (RecordStream *)calloc(1, sizeof(RecordStream));
-
-    ret->fd = fd;
-    ret->maxRecordLen = maxRecordLen;
-    ret->buffer = (unsigned char *)malloc (maxRecordLen + HEADER_SIZE);
-    
-    ret->unconsumed = ret->buffer;
-    ret->read_end = ret->buffer;
-    ret->buffer_end = ret->buffer + maxRecordLen + HEADER_SIZE;
-
-    return ret;
-}
-
-
-extern void record_stream_free(RecordStream *rs)
-{
-    free(rs->buffer);
-    free(rs);
-}
-
-
-/* returns NULL; if there isn't a full record in the buffer */
-static unsigned char * getEndOfRecord (unsigned char *p_begin,
-                                            unsigned char *p_end)
-{
-    size_t len;
-    unsigned char * p_ret;
-
-    if (p_end < p_begin + HEADER_SIZE) {
-        return NULL;
-    }
-
-    //First four bytes are length
-    len = ntohl(*((uint32_t *)p_begin));
-
-    p_ret = p_begin + HEADER_SIZE + len;
-
-    if (p_end < p_ret) {
-        return NULL;
-    }
-
-    return p_ret;
-}
-
-static void *getNextRecord (RecordStream *p_rs, size_t *p_outRecordLen)
-{
-    unsigned char *record_start, *record_end;
-
-    record_end = getEndOfRecord (p_rs->unconsumed, p_rs->read_end);
-
-    if (record_end != NULL) {
-        /* one full line in the buffer */
-        record_start = p_rs->unconsumed + HEADER_SIZE;
-        p_rs->unconsumed = record_end;
-
-        *p_outRecordLen = record_end - record_start;
-
-        return record_start;
-    }
-
-    return NULL;
-}
-
-/**
- * Reads the next record from stream fd
- * Records are prefixed by a 16-bit big endian length value
- * Records may not be larger than maxRecordLen
- *
- * Doesn't guard against EINTR
- *
- * p_outRecord and p_outRecordLen may not be NULL
- *
- * Return 0 on success, -1 on fail
- * Returns 0 with *p_outRecord set to NULL on end of stream
- * Returns -1 / errno = EAGAIN if it needs to read again
- */
-int record_stream_get_next (RecordStream *p_rs, void ** p_outRecord, 
-                                    size_t *p_outRecordLen)
-{
-    void *ret;
-
-    ssize_t countRead;
-
-    /* is there one record already in the buffer? */
-    ret = getNextRecord (p_rs, p_outRecordLen);
-
-    if (ret != NULL) {
-        *p_outRecord = ret;
-        return 0;
-    }
-
-    // if the buffer is full and we don't have a full record
-    if (p_rs->unconsumed == p_rs->buffer 
-        && p_rs->read_end == p_rs->buffer_end
-    ) {
-        // this should never happen
-        //ALOGE("max record length exceeded\n");
-        assert (0);
-        errno = EFBIG;
-        return -1;
-    }
-
-    if (p_rs->unconsumed != p_rs->buffer) {
-        // move remainder to the beginning of the buffer
-        size_t toMove;
-
-        toMove = p_rs->read_end - p_rs->unconsumed;
-        if (toMove) {
-            memmove(p_rs->buffer, p_rs->unconsumed, toMove);
-        }
-
-        p_rs->read_end = p_rs->buffer + toMove;
-        p_rs->unconsumed = p_rs->buffer;
-    }
-
-    countRead = read (p_rs->fd, p_rs->read_end, p_rs->buffer_end - p_rs->read_end);
-
-    if (countRead <= 0) {
-        /* note: end-of-stream drops through here too */
-        *p_outRecord = NULL;
-        return countRead;
-    }
-
-    p_rs->read_end += countRead;
-
-    ret = getNextRecord (p_rs, p_outRecordLen);
-
-    if (ret == NULL) {
-        /* not enough of a buffer to for a whole command */
-        errno = EAGAIN;
-        return -1;
-    }
-
-    *p_outRecord = ret;        
-    return 0;
-}
diff --git a/libcutils/selector.c b/libcutils/selector.c
deleted file mode 100644
index 3776bbb..0000000
--- a/libcutils/selector.c
+++ /dev/null
@@ -1,263 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "selector"
-
-#include <assert.h>
-#include <errno.h>
-#include <pthread.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/array.h>
-#include <cutils/selector.h>
-
-#include "loghack.h"
-
-struct Selector {
-    Array* selectableFds;
-    bool looping;
-    fd_set readFds;
-    fd_set writeFds;
-    fd_set exceptFds;
-    int maxFd;
-    int wakeupPipe[2];
-    SelectableFd* wakeupFd;
-
-    bool inSelect;
-    pthread_mutex_t inSelectLock; 
-};
-
-/** Reads and ignores wake up data. */ 
-static void eatWakeupData(SelectableFd* wakeupFd) {
-    static char garbage[64];
-    if (read(wakeupFd->fd, garbage, sizeof(garbage)) < 0) {
-        if (errno == EINTR) {
-            ALOGI("read() interrupted.");    
-        } else {
-            LOG_ALWAYS_FATAL("This should never happen: %s", strerror(errno));
-        }
-    }
-}
-
-static void setInSelect(Selector* selector, bool inSelect) {
-    pthread_mutex_lock(&selector->inSelectLock);
-    selector->inSelect = inSelect;
-    pthread_mutex_unlock(&selector->inSelectLock);
-}
-
-static bool isInSelect(Selector* selector) {
-    pthread_mutex_lock(&selector->inSelectLock);
-    bool inSelect = selector->inSelect;
-    pthread_mutex_unlock(&selector->inSelectLock);
-    return inSelect;
-}
-
-void selectorWakeUp(Selector* selector) {
-    if (!isInSelect(selector)) {
-        // We only need to write wake-up data if we're blocked in select().
-        return;
-    }
-    
-    static char garbage[1];
-    if (write(selector->wakeupPipe[1], garbage, sizeof(garbage)) < 0) {
-        if (errno == EINTR) {
-            ALOGI("read() interrupted.");    
-        } else {
-            LOG_ALWAYS_FATAL("This should never happen: %s", strerror(errno));
-        }
-    }
-}
-
-Selector* selectorCreate(void) {
-    Selector* selector = calloc(1, sizeof(Selector));
-    if (selector == NULL) {
-        LOG_ALWAYS_FATAL("malloc() error.");
-    }
-    selector->selectableFds = arrayCreate();
-    
-    // Set up wake-up pipe.
-    if (pipe(selector->wakeupPipe) < 0) {
-        LOG_ALWAYS_FATAL("pipe() error: %s", strerror(errno));
-    }
-    
-    ALOGD("Wakeup fd: %d", selector->wakeupPipe[0]);
-    
-    SelectableFd* wakeupFd = selectorAdd(selector, selector->wakeupPipe[0]);
-    if (wakeupFd == NULL) {
-        LOG_ALWAYS_FATAL("malloc() error.");
-    }
-    wakeupFd->onReadable = &eatWakeupData; 
-    
-    pthread_mutex_init(&selector->inSelectLock, NULL);
-
-    return selector;
-}
-
-SelectableFd* selectorAdd(Selector* selector, int fd) {
-    assert(selector != NULL);
-
-    SelectableFd* selectableFd = calloc(1, sizeof(SelectableFd));
-    if (selectableFd != NULL) {
-        selectableFd->selector = selector;
-        selectableFd->fd = fd;
-    
-        arrayAdd(selector->selectableFds, selectableFd);
-    }
-
-    return selectableFd;
-}
-
-/**
- * Adds an fd to the given set if the callback is non-null. Returns true
- * if the fd was added.
- */
-static inline bool maybeAdd(SelectableFd* selectableFd,
-        void (*callback)(SelectableFd*), fd_set* fdSet) {
-    if (callback != NULL) {
-        FD_SET(selectableFd->fd, fdSet);
-        return true;
-    }
-    return false;
-}
-
-/**
- * Removes stale file descriptors and initializes file descriptor sets.
- */
-static void prepareForSelect(Selector* selector) {
-    fd_set* exceptFds = &selector->exceptFds;
-    fd_set* readFds = &selector->readFds;
-    fd_set* writeFds = &selector->writeFds;
-    
-    FD_ZERO(exceptFds);
-    FD_ZERO(readFds);
-    FD_ZERO(writeFds);
-
-    Array* selectableFds = selector->selectableFds;
-    int i = 0;
-    selector->maxFd = 0;
-    int size = arraySize(selectableFds);
-    while (i < size) {
-        SelectableFd* selectableFd = arrayGet(selectableFds, i);
-        if (selectableFd->remove) {
-            // This descriptor should be removed.
-            arrayRemove(selectableFds, i);
-            size--;
-            if (selectableFd->onRemove != NULL) {
-                selectableFd->onRemove(selectableFd);
-            }
-            free(selectableFd);
-        } else {
-            if (selectableFd->beforeSelect != NULL) {
-                selectableFd->beforeSelect(selectableFd);
-            }
-            
-            bool inSet = false;
-            if (maybeAdd(selectableFd, selectableFd->onExcept, exceptFds)) {
-                ALOGD("Selecting fd %d for writing...", selectableFd->fd);
-                inSet = true;
-            }
-            if (maybeAdd(selectableFd, selectableFd->onReadable, readFds)) {
-                ALOGD("Selecting fd %d for reading...", selectableFd->fd);
-                inSet = true;
-            }
-            if (maybeAdd(selectableFd, selectableFd->onWritable, writeFds)) {
-                inSet = true;
-            }
-
-            if (inSet) {
-                // If the fd is in a set, check it against max.
-                int fd = selectableFd->fd;
-                if (fd > selector->maxFd) {
-                    selector->maxFd = fd;
-                }
-            }
-            
-            // Move to next descriptor.
-            i++;
-        }
-    }
-}
-
-/**
- * Invokes a callback if the callback is non-null and the fd is in the given
- * set.
- */
-static inline void maybeInvoke(SelectableFd* selectableFd,
-        void (*callback)(SelectableFd*), fd_set* fdSet) {
-    if (callback != NULL && !selectableFd->remove && 
-            FD_ISSET(selectableFd->fd, fdSet)) {
-        ALOGD("Selected fd %d.", selectableFd->fd);
-        callback(selectableFd);
-    }
-}
-
-/**
- * Notifies user if file descriptors are readable or writable, or if
- * out-of-band data is present.
- */
-static void fireEvents(Selector* selector) {
-    Array* selectableFds = selector->selectableFds;
-    int size = arraySize(selectableFds);
-    int i;
-    for (i = 0; i < size; i++) {
-        SelectableFd* selectableFd = arrayGet(selectableFds, i);
-        maybeInvoke(selectableFd, selectableFd->onExcept,
-                &selector->exceptFds);
-        maybeInvoke(selectableFd, selectableFd->onReadable,
-                &selector->readFds);
-        maybeInvoke(selectableFd, selectableFd->onWritable,
-                &selector->writeFds);
-    }
-}
-
-void selectorLoop(Selector* selector) {
-    // Make sure we're not already looping.
-    if (selector->looping) {
-        LOG_ALWAYS_FATAL("Already looping.");
-    }
-    selector->looping = true;
-    
-    while (true) {
-        setInSelect(selector, true);
-        
-        prepareForSelect(selector);
-
-        ALOGD("Entering select().");
-        
-        // Select file descriptors.
-        int result = select(selector->maxFd + 1, &selector->readFds, 
-                &selector->writeFds, &selector->exceptFds, NULL);
-        
-        ALOGD("Exiting select().");
-        
-        setInSelect(selector, false);
-        
-        if (result == -1) {
-            // Abort on everything except EINTR.
-            if (errno == EINTR) {
-                ALOGI("select() interrupted.");    
-            } else {
-                LOG_ALWAYS_FATAL("select() error: %s", 
-                        strerror(errno));
-            }
-        } else if (result > 0) {
-            fireEvents(selector);
-        }
-    }
-}
diff --git a/libcutils/zygote.c b/libcutils/zygote.c
deleted file mode 100644
index 37236e8..0000000
--- a/libcutils/zygote.c
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "Zygote"
-
-#include <cutils/sockets.h>
-#include <cutils/zygote.h>
-#include <cutils/log.h>
-
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-#include <time.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <arpa/inet.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#define ZYGOTE_SOCKET "zygote"
-
-#define ZYGOTE_RETRY_COUNT 1000
-#define ZYGOTE_RETRY_MILLIS 500
-
-static void replace_nl(char *str);
-
-/*
- * If sendStdio is non-zero, the current process's stdio file descriptors
- * will be sent and inherited by the spawned process.
- */
-static int send_request(int fd, int sendStdio, int argc, const char **argv)
-{
-#ifndef HAVE_ANDROID_OS
-    // not supported on simulator targets
-    //ALOGE("zygote_* not supported on simulator targets");
-    return -1;
-#else /* HAVE_ANDROID_OS */
-    uint32_t pid;
-    int i;
-    struct iovec ivs[2];
-    struct msghdr msg;
-    char argc_buffer[12];
-    const char *newline_string = "\n";
-    struct cmsghdr *cmsg;
-    char msgbuf[CMSG_SPACE(sizeof(int) * 3)];
-    int *cmsg_payload;
-    ssize_t ret;
-
-    memset(&msg, 0, sizeof(msg));
-    memset(&ivs, 0, sizeof(ivs));
-
-    // First line is arg count 
-    snprintf(argc_buffer, sizeof(argc_buffer), "%d\n", argc);
-
-    ivs[0].iov_base = argc_buffer;
-    ivs[0].iov_len = strlen(argc_buffer);
-
-    msg.msg_iov = ivs;
-    msg.msg_iovlen = 1;
-
-    if (sendStdio != 0) {
-        // Pass the file descriptors with the first write
-        msg.msg_control = msgbuf;
-        msg.msg_controllen = sizeof msgbuf;
-
-        cmsg = CMSG_FIRSTHDR(&msg);
-
-        cmsg->cmsg_len = CMSG_LEN(3 * sizeof(int));
-        cmsg->cmsg_level = SOL_SOCKET;
-        cmsg->cmsg_type = SCM_RIGHTS;
-
-        cmsg_payload = (int *)CMSG_DATA(cmsg);
-        cmsg_payload[0] = STDIN_FILENO;
-        cmsg_payload[1] = STDOUT_FILENO;
-        cmsg_payload[2] = STDERR_FILENO;
-    }
-
-    do {
-        ret = sendmsg(fd, &msg, MSG_NOSIGNAL);
-    } while (ret < 0 && errno == EINTR);
-
-    if (ret < 0) {
-        return -1;
-    }
-
-    // Only send the fd's once
-    msg.msg_control = NULL;
-    msg.msg_controllen = 0;
-
-    // replace any newlines with spaces and send the args
-    for (i = 0; i < argc; i++) {
-        char *tofree = NULL;
-        const char *toprint;
-
-        toprint = argv[i];
-
-        if (strchr(toprint, '\n') != NULL) {
-            tofree = strdup(toprint);
-            toprint = tofree;
-            replace_nl(tofree);
-        }
-
-        ivs[0].iov_base = (char *)toprint;
-        ivs[0].iov_len = strlen(toprint);
-        ivs[1].iov_base = (char *)newline_string;
-        ivs[1].iov_len = 1;
-
-        msg.msg_iovlen = 2;
-
-        do {
-            ret = sendmsg(fd, &msg, MSG_NOSIGNAL);
-        } while (ret < 0 && errno == EINTR);
-
-        if (tofree != NULL) {
-            free(tofree);
-        }
-
-        if (ret < 0) {
-            return -1;
-        }
-    }
-
-    // Read the pid, as a 4-byte network-order integer
-
-    ivs[0].iov_base = &pid;
-    ivs[0].iov_len = sizeof(pid);
-    msg.msg_iovlen = 1;
-
-    do {
-        do {
-            ret = recvmsg(fd, &msg, MSG_NOSIGNAL | MSG_WAITALL);
-        } while (ret < 0 && errno == EINTR);
-
-        if (ret < 0) {
-            return -1;
-        }
-
-        ivs[0].iov_len -= ret;
-        ivs[0].iov_base += ret;
-    } while (ivs[0].iov_len > 0);
-
-    pid = ntohl(pid);
-
-    return pid;
-#endif /* HAVE_ANDROID_OS */
-}
-
-/**
- * Spawns a new dalvik instance via the Zygote process. The non-zygote
- * arguments are passed to com.android.internal.os.RuntimeInit(). The
- * first non-option argument should be a class name in the system class path.
- *
- * The arg list  may start with zygote params such as --set-uid.
- *
- * If sendStdio is non-zero, the current process's stdio file descriptors
- * will be sent and inherited by the spawned process.
- *
- * The pid of the child process is returned, or -1 if an error was 
- * encountered.
- *
- * zygote_run_oneshot waits up to ZYGOTE_RETRY_COUNT * 
- * ZYGOTE_RETRY_MILLIS for the zygote socket to be available.
- */
-int zygote_run_oneshot(int sendStdio, int argc, const char **argv) 
-{
-    int fd = -1;
-    int err;
-    int i;
-    int retries;
-    int pid;
-    const char **newargv = argv;
-    const int newargc = argc;
-
-    for (retries = 0; (fd < 0) && (retries < ZYGOTE_RETRY_COUNT); retries++) {
-        if (retries > 0) { 
-            struct timespec ts;
-
-            memset(&ts, 0, sizeof(ts));
-            ts.tv_nsec = ZYGOTE_RETRY_MILLIS * 1000 * 1000;
-
-            do {
-                err = nanosleep (&ts, &ts);
-            } while (err < 0 && errno == EINTR);
-        }
-        fd = socket_local_client(ZYGOTE_SOCKET, AF_LOCAL, 
-                ANDROID_SOCKET_NAMESPACE_RESERVED);
-    }
-
-    if (fd < 0) {
-        return -1;
-    }
-
-    pid = send_request(fd, 0, newargc, newargv);
-
-    do {
-        err = close(fd);
-    } while (err < 0 && errno == EINTR);
-
-    return pid;
-}
-
-/**
- * Replaces all occurrances of newline with space.
- */
-static void replace_nl(char *str)
-{
-    for(; *str; str++) {
-        if (*str == '\n') {
-            *str = ' ';
-        }
-    }
-}
-
-
-
diff --git a/libmincrypt/Android.mk b/libmincrypt/Android.mk
index f58eab9..090d0e5 100644
--- a/libmincrypt/Android.mk
+++ b/libmincrypt/Android.mk
@@ -4,15 +4,15 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := libmincrypt
-LOCAL_SRC_FILES := rsa.c rsa_e_3.c rsa_e_f4.c sha.c
+LOCAL_SRC_FILES := rsa.c sha.c sha256.c
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := libmincrypt
-LOCAL_SRC_FILES := rsa.c rsa_e_3.c rsa_e_f4.c sha.c
+LOCAL_SRC_FILES := rsa.c sha.c sha256.c
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 
-# TODO: drop the hyphen once these are checked in
-include $(LOCAL_PATH)/tools/Android.mk
+include $(LOCAL_PATH)/tools/Android.mk \
+        $(LOCAL_PATH)/test/Android.mk
diff --git a/libmincrypt/rsa.c b/libmincrypt/rsa.c
index b4ee6af..9061b3a 100644
--- a/libmincrypt/rsa.c
+++ b/libmincrypt/rsa.c
@@ -26,29 +26,283 @@
 */
 
 #include "mincrypt/rsa.h"
+#include "mincrypt/sha.h"
+#include "mincrypt/sha256.h"
 
-int RSA_e_f4_verify(const RSAPublicKey* key,
-                    const uint8_t* signature,
-                    const int len,
-                    const uint8_t* sha);
+// a[] -= mod
+static void subM(const RSAPublicKey* key,
+                 uint32_t* a) {
+    int64_t A = 0;
+    int i;
+    for (i = 0; i < key->len; ++i) {
+        A += (uint64_t)a[i] - key->n[i];
+        a[i] = (uint32_t)A;
+        A >>= 32;
+    }
+}
 
-int RSA_e_3_verify(const RSAPublicKey *key,
-                   const uint8_t *signature,
-                   const int len,
-                   const uint8_t *sha);
+// return a[] >= mod
+static int geM(const RSAPublicKey* key,
+               const uint32_t* a) {
+    int i;
+    for (i = key->len; i;) {
+        --i;
+        if (a[i] < key->n[i]) return 0;
+        if (a[i] > key->n[i]) return 1;
+    }
+    return 1;  // equal
+}
 
+// montgomery c[] += a * b[] / R % mod
+static void montMulAdd(const RSAPublicKey* key,
+                       uint32_t* c,
+                       const uint32_t a,
+                       const uint32_t* b) {
+    uint64_t A = (uint64_t)a * b[0] + c[0];
+    uint32_t d0 = (uint32_t)A * key->n0inv;
+    uint64_t B = (uint64_t)d0 * key->n[0] + (uint32_t)A;
+    int i;
+
+    for (i = 1; i < key->len; ++i) {
+        A = (A >> 32) + (uint64_t)a * b[i] + c[i];
+        B = (B >> 32) + (uint64_t)d0 * key->n[i] + (uint32_t)A;
+        c[i - 1] = (uint32_t)B;
+    }
+
+    A = (A >> 32) + (B >> 32);
+
+    c[i - 1] = (uint32_t)A;
+
+    if (A >> 32) {
+        subM(key, c);
+    }
+}
+
+// montgomery c[] = a[] * b[] / R % mod
+static void montMul(const RSAPublicKey* key,
+                    uint32_t* c,
+                    const uint32_t* a,
+                    const uint32_t* b) {
+    int i;
+    for (i = 0; i < key->len; ++i) {
+        c[i] = 0;
+    }
+    for (i = 0; i < key->len; ++i) {
+        montMulAdd(key, c, a[i], b);
+    }
+}
+
+// In-place public exponentiation.
+// Input and output big-endian byte array in inout.
+static void modpow(const RSAPublicKey* key,
+                   uint8_t* inout) {
+    uint32_t a[RSANUMWORDS];
+    uint32_t aR[RSANUMWORDS];
+    uint32_t aaR[RSANUMWORDS];
+    uint32_t* aaa = 0;
+    int i;
+
+    // Convert from big endian byte array to little endian word array.
+    for (i = 0; i < key->len; ++i) {
+        uint32_t tmp =
+            (inout[((key->len - 1 - i) * 4) + 0] << 24) |
+            (inout[((key->len - 1 - i) * 4) + 1] << 16) |
+            (inout[((key->len - 1 - i) * 4) + 2] << 8) |
+            (inout[((key->len - 1 - i) * 4) + 3] << 0);
+        a[i] = tmp;
+    }
+
+    if (key->exponent == 65537) {
+        aaa = aaR;  // Re-use location.
+        montMul(key, aR, a, key->rr);  // aR = a * RR / R mod M
+        for (i = 0; i < 16; i += 2) {
+            montMul(key, aaR, aR, aR);  // aaR = aR * aR / R mod M
+            montMul(key, aR, aaR, aaR);  // aR = aaR * aaR / R mod M
+        }
+        montMul(key, aaa, aR, a);  // aaa = aR * a / R mod M
+    } else if (key->exponent == 3) {
+        aaa = aR;  // Re-use location.
+        montMul(key, aR, a, key->rr);  /* aR = a * RR / R mod M   */
+        montMul(key, aaR, aR, aR);     /* aaR = aR * aR / R mod M */
+        montMul(key, aaa, aaR, a);     /* aaa = aaR * a / R mod M */
+    }
+
+    // Make sure aaa < mod; aaa is at most 1x mod too large.
+    if (geM(key, aaa)) {
+        subM(key, aaa);
+    }
+
+    // Convert to bigendian byte array
+    for (i = key->len - 1; i >= 0; --i) {
+        uint32_t tmp = aaa[i];
+        *inout++ = tmp >> 24;
+        *inout++ = tmp >> 16;
+        *inout++ = tmp >> 8;
+        *inout++ = tmp >> 0;
+    }
+}
+
+// Expected PKCS1.5 signature padding bytes, for a keytool RSA signature.
+// Has the 0-length optional parameter encoded in the ASN1 (as opposed to the
+// other flavor which omits the optional parameter entirely). This code does not
+// accept signatures without the optional parameter.
+
+/*
+static const uint8_t sha_padding[RSANUMBYTES] = {
+    0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0x21, 0x30,
+    0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a,
+    0x05, 0x00, 0x04, 0x14,
+
+    // 20 bytes of hash go here.
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
+};
+*/
+
+// SHA-1 of PKCS1.5 signature sha_padding for 2048 bit, as above.
+// At the location of the bytes of the hash all 00 are hashed.
+static const uint8_t kExpectedPadShaRsa2048[SHA_DIGEST_SIZE] = {
+    0xdc, 0xbd, 0xbe, 0x42, 0xd5, 0xf5, 0xa7, 0x2e,
+    0x6e, 0xfc, 0xf5, 0x5d, 0xaf, 0x9d, 0xea, 0x68,
+    0x7c, 0xfb, 0xf1, 0x67
+};
+
+/*
+static const uint8_t sha256_padding[RSANUMBYTES] = {
+    0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0x31, 0x30,
+    0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
+    0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20,
+
+    // 32 bytes of hash go here.
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+};
+*/
+
+// SHA-256 of PKCS1.5 signature sha256_padding for 2048 bit, as above.
+// At the location of the bytes of the hash all 00 are hashed.
+static const uint8_t kExpectedPadSha256Rsa2048[SHA256_DIGEST_SIZE] = {
+    0xab, 0x28, 0x8d, 0x8a, 0xd7, 0xd9, 0x59, 0x92,
+    0xba, 0xcc, 0xf8, 0x67, 0x20, 0xe1, 0x15, 0x2e,
+    0x39, 0x8d, 0x80, 0x36, 0xd6, 0x6f, 0xf0, 0xfd,
+    0x90, 0xe8, 0x7d, 0x8b, 0xe1, 0x7c, 0x87, 0x59,
+};
+
+// Verify a 2048-bit RSA PKCS1.5 signature against an expected hash.
+// Both e=3 and e=65537 are supported.  hash_len may be
+// SHA_DIGEST_SIZE (== 20) to indicate a SHA-1 hash, or
+// SHA256_DIGEST_SIZE (== 32) to indicate a SHA-256 hash.  No other
+// values are supported.
+//
+// Returns 1 on successful verification, 0 on failure.
 int RSA_verify(const RSAPublicKey *key,
                const uint8_t *signature,
                const int len,
-               const uint8_t *sha) {
-    switch (key->exponent) {
-        case 3:
-            return RSA_e_3_verify(key, signature, len, sha);
+               const uint8_t *hash,
+               const int hash_len) {
+    uint8_t buf[RSANUMBYTES];
+    int i;
+    const uint8_t* padding_hash;
+
+    if (key->len != RSANUMWORDS) {
+        return 0;  // Wrong key passed in.
+    }
+
+    if (len != sizeof(buf)) {
+        return 0;  // Wrong input length.
+    }
+
+    if (hash_len != SHA_DIGEST_SIZE &&
+        hash_len != SHA256_DIGEST_SIZE) {
+        return 0;  // Unsupported hash.
+    }
+
+    if (key->exponent != 3 && key->exponent != 65537) {
+        return 0;  // Unsupported exponent.
+    }
+
+    for (i = 0; i < len; ++i) {  // Copy input to local workspace.
+        buf[i] = signature[i];
+    }
+
+    modpow(key, buf);  // In-place exponentiation.
+
+    // Xor sha portion, so it all becomes 00 iff equal.
+    for (i = len - hash_len; i < len; ++i) {
+        buf[i] ^= *hash++;
+    }
+
+    // Hash resulting buf, in-place.
+    switch (hash_len) {
+        case SHA_DIGEST_SIZE:
+            padding_hash = kExpectedPadShaRsa2048;
+            SHA_hash(buf, len, buf);
             break;
-        case 65537:
-            return RSA_e_f4_verify(key, signature, len, sha);
+        case SHA256_DIGEST_SIZE:
+            padding_hash = kExpectedPadSha256Rsa2048;
+            SHA256_hash(buf, len, buf);
             break;
         default:
             return 0;
     }
+
+    // Compare against expected hash value.
+    for (i = 0; i < hash_len; ++i) {
+        if (buf[i] != padding_hash[i]) {
+            return 0;
+        }
+    }
+
+    return 1;  // All checked out OK.
 }
diff --git a/libmincrypt/rsa_e_3.c b/libmincrypt/rsa_e_3.c
deleted file mode 100644
index c8c02c4..0000000
--- a/libmincrypt/rsa_e_3.c
+++ /dev/null
@@ -1,202 +0,0 @@
-/* rsa_e_3.c
-**
-** Copyright 2008, The Android Open Source Project
-**
-** 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 Google Inc. ``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 Google Inc. 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 "mincrypt/rsa.h"
-#include "mincrypt/sha.h"
-
-/* a[] -= mod */
-static void subM(const RSAPublicKey *key, uint32_t *a) {
-    int64_t A = 0;
-    int i;
-    for (i = 0; i < key->len; ++i) {
-        A += (uint64_t)a[i] - key->n[i];
-        a[i] = (uint32_t)A;
-        A >>= 32;
-    }
-}
-
-/* return a[] >= mod */
-static int geM(const RSAPublicKey *key, const uint32_t *a) {
-    int i;
-    for (i = key->len; i;) {
-        --i;
-        if (a[i] < key->n[i]) return 0;
-        if (a[i] > key->n[i]) return 1;
-    }
-    return 1;  /* equal */
-}
-
-/* montgomery c[] += a * b[] / R % mod */
-static void montMulAdd(const RSAPublicKey *key,
-                       uint32_t* c,
-                       const uint32_t a,
-                       const uint32_t* b) {
-    uint64_t A = (uint64_t)a * b[0] + c[0];
-    uint32_t d0 = (uint32_t)A * key->n0inv;
-    uint64_t B = (uint64_t)d0 * key->n[0] + (uint32_t)A;
-    int i;
-
-    for (i = 1; i < key->len; ++i) {
-        A = (A >> 32) + (uint64_t)a * b[i] + c[i];
-        B = (B >> 32) + (uint64_t)d0 * key->n[i] + (uint32_t)A;
-        c[i - 1] = (uint32_t)B;
-    }
-
-    A = (A >> 32) + (B >> 32);
-
-    c[i - 1] = (uint32_t)A;
-
-    if (A >> 32) {
-        subM(key, c);
-    }
-}
-
-/* montgomery c[] = a[] * b[] / R % mod */
-static void montMul(const RSAPublicKey *key,
-                    uint32_t* c,
-                    const uint32_t* a,
-                    const uint32_t* b) {
-    int i;
-    for (i = 0; i < key->len; ++i) {
-        c[i] = 0;
-    }
-    for (i = 0; i < key->len; ++i) {
-        montMulAdd(key, c, a[i], b);
-    }
-}
-
-/* In-place public exponentiation.
-** Input and output big-endian byte array in inout.
-*/
-static void modpow3(const RSAPublicKey *key,
-                    uint8_t* inout) {
-    uint32_t a[RSANUMWORDS];
-    uint32_t aR[RSANUMWORDS];
-    uint32_t aaR[RSANUMWORDS];
-    uint32_t *aaa = aR;  /* Re-use location. */
-    int i;
-
-    /* Convert from big endian byte array to little endian word array. */
-    for (i = 0; i < key->len; ++i) {
-        uint32_t tmp =
-            (inout[((key->len - 1 - i) * 4) + 0] << 24) |
-            (inout[((key->len - 1 - i) * 4) + 1] << 16) |
-            (inout[((key->len - 1 - i) * 4) + 2] << 8) |
-            (inout[((key->len - 1 - i) * 4) + 3] << 0);
-        a[i] = tmp;
-    }
-
-    montMul(key, aR, a, key->rr);  /* aR = a * RR / R mod M   */
-    montMul(key, aaR, aR, aR);     /* aaR = aR * aR / R mod M */
-    montMul(key, aaa, aaR, a);     /* aaa = aaR * a / R mod M */
-
-    /* Make sure aaa < mod; aaa is at most 1x mod too large. */
-    if (geM(key, aaa)) {
-        subM(key, aaa);
-    }
-
-    /* Convert to bigendian byte array */
-    for (i = key->len - 1; i >= 0; --i) {
-        uint32_t tmp = aaa[i];
-        *inout++ = tmp >> 24;
-        *inout++ = tmp >> 16;
-        *inout++ = tmp >> 8;
-        *inout++ = tmp >> 0;
-    }
-}
-
-/* Expected PKCS1.5 signature padding bytes, for a keytool RSA signature.
-** Has the 0-length optional parameter encoded in the ASN1 (as opposed to the
-** other flavor which omits the optional parameter entirely). This code does not
-** accept signatures without the optional parameter.
-*/
-static const uint8_t padding[RSANUMBYTES - SHA_DIGEST_SIZE] = {
-    0x00,0x01,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
-    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
-    0x30,0x21,0x30,0x09,0x06,0x05,0x2b,0x0e,0x03,0x02,0x1a,0x05,0x00,
-    0x04,0x14
-};
-
-/* Verify a 2048 bit RSA e=3 PKCS1.5 signature against an expected SHA-1 hash.
-** Returns 0 on failure, 1 on success.
-*/
-int RSA_e_3_verify(const RSAPublicKey *key,
-                   const uint8_t *signature,
-                   const int len,
-                   const uint8_t *sha) {
-    uint8_t buf[RSANUMBYTES];
-    int i;
-
-    if (key->len != RSANUMWORDS) {
-        return 0;  /* Wrong key passed in. */
-    }
-
-    if (len != sizeof(buf)) {
-        return 0;  /* Wrong input length. */
-    }
-
-  if (key->exponent != 3) {
-      return 0;  // Wrong exponent.
-  }
-
-    for (i = 0; i < len; ++i) {
-        buf[i] = signature[i];
-    }
-
-    modpow3(key, buf);
-
-    /* Check pkcs1.5 padding bytes. */
-    for (i = 0; i < (int) sizeof(padding); ++i) {
-        if (buf[i] != padding[i]) {
-            return 0;
-        }
-    }
-
-    /* Check sha digest matches. */
-    for (; i < len; ++i) {
-        if (buf[i] != *sha++) {
-            return 0;
-        }
-    }
-
-    return 1;
-}
diff --git a/libmincrypt/rsa_e_f4.c b/libmincrypt/rsa_e_f4.c
deleted file mode 100644
index 6701bcc..0000000
--- a/libmincrypt/rsa_e_f4.c
+++ /dev/null
@@ -1,196 +0,0 @@
-/* rsa_e_f4.c
-**
-** Copyright 2012, The Android Open Source Project
-**
-** 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 Google Inc. ``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 Google Inc. 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 "mincrypt/rsa.h"
-#include "mincrypt/sha.h"
-
-// a[] -= mod
-static void subM(const RSAPublicKey* key,
-                 uint32_t* a) {
-  int64_t A = 0;
-  int i;
-  for (i = 0; i < key->len; ++i) {
-    A += (uint64_t)a[i] - key->n[i];
-    a[i] = (uint32_t)A;
-    A >>= 32;
-  }
-}
-
-// return a[] >= mod
-static int geM(const RSAPublicKey* key,
-               const uint32_t* a) {
-  int i;
-  for (i = key->len; i;) {
-    --i;
-    if (a[i] < key->n[i]) return 0;
-    if (a[i] > key->n[i]) return 1;
-  }
-  return 1;  // equal
-}
-
-// montgomery c[] += a * b[] / R % mod
-static void montMulAdd(const RSAPublicKey* key,
-                       uint32_t* c,
-                       const uint32_t a,
-                       const uint32_t* b) {
-  uint64_t A = (uint64_t)a * b[0] + c[0];
-  uint32_t d0 = (uint32_t)A * key->n0inv;
-  uint64_t B = (uint64_t)d0 * key->n[0] + (uint32_t)A;
-  int i;
-
-  for (i = 1; i < key->len; ++i) {
-    A = (A >> 32) + (uint64_t)a * b[i] + c[i];
-    B = (B >> 32) + (uint64_t)d0 * key->n[i] + (uint32_t)A;
-    c[i - 1] = (uint32_t)B;
-  }
-
-  A = (A >> 32) + (B >> 32);
-
-  c[i - 1] = (uint32_t)A;
-
-  if (A >> 32) {
-    subM(key, c);
-  }
-}
-
-// montgomery c[] = a[] * b[] / R % mod
-static void montMul(const RSAPublicKey* key,
-                    uint32_t* c,
-                    const uint32_t* a,
-                    const uint32_t* b) {
-  int i;
-  for (i = 0; i < key->len; ++i) {
-    c[i] = 0;
-  }
-  for (i = 0; i < key->len; ++i) {
-    montMulAdd(key, c, a[i], b);
-  }
-}
-
-// In-place public exponentiation.
-// Input and output big-endian byte array in inout.
-static void modpowF4(const RSAPublicKey* key,
-                     uint8_t* inout) {
-  uint32_t a[RSANUMWORDS];
-  uint32_t aR[RSANUMWORDS];
-  uint32_t aaR[RSANUMWORDS];
-  uint32_t* aaa = aaR;  // Re-use location.
-  int i;
-
-  // Convert from big endian byte array to little endian word array.
-  for (i = 0; i < key->len; ++i) {
-    uint32_t tmp =
-      (inout[((key->len - 1 - i) * 4) + 0] << 24) |
-      (inout[((key->len - 1 - i) * 4) + 1] << 16) |
-      (inout[((key->len - 1 - i) * 4) + 2] << 8) |
-      (inout[((key->len - 1 - i) * 4) + 3] << 0);
-    a[i] = tmp;
-  }
-
-  montMul(key, aR, a, key->rr);  // aR = a * RR / R mod M
-  for (i = 0; i < 16; i += 2) {
-    montMul(key, aaR, aR, aR);  // aaR = aR * aR / R mod M
-    montMul(key, aR, aaR, aaR);  // aR = aaR * aaR / R mod M
-  }
-  montMul(key, aaa, aR, a);  // aaa = aR * a / R mod M
-
-  // Make sure aaa < mod; aaa is at most 1x mod too large.
-  if (geM(key, aaa)) {
-    subM(key, aaa);
-  }
-
-  // Convert to bigendian byte array
-  for (i = key->len - 1; i >= 0; --i) {
-    uint32_t tmp = aaa[i];
-    *inout++ = tmp >> 24;
-    *inout++ = tmp >> 16;
-    *inout++ = tmp >> 8;
-    *inout++ = tmp >> 0;
-  }
-}
-
-// Expected PKCS1.5 signature padding bytes, for a keytool RSA signature.
-// Has the 0-length optional parameter encoded in the ASN1 (as opposed to the
-// other flavor which omits the optional parameter entirely). This code does not
-// accept signatures without the optional parameter.
-/*
-static const uint8_t padding[RSANUMBYTES] = {
-0x00,0x01,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x30,0x21,0x30,0x09,0x06,0x05,0x2b,0x0e,0x03,0x02,0x1a,0x05,0x00,0x04,0x14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
-};
-*/
-
-// SHA-1 of PKCS1.5 signature padding for 2048 bit, as above.
-// At the location of the bytes of the hash all 00 are hashed.
-static const uint8_t kExpectedPadShaRsa2048[SHA_DIGEST_SIZE] = {
-  0xdc, 0xbd, 0xbe, 0x42, 0xd5, 0xf5, 0xa7, 0x2e, 0x6e, 0xfc,
-  0xf5, 0x5d, 0xaf, 0x9d, 0xea, 0x68, 0x7c, 0xfb, 0xf1, 0x67
-};
-
-// Verify a 2048 bit RSA e=65537 PKCS1.5 signature against an expected
-// SHA-1 hash.  Returns 0 on failure, 1 on success.
-int RSA_e_f4_verify(const RSAPublicKey* key,
-                    const uint8_t* signature,
-                    const int len,
-                    const uint8_t* sha) {
-  uint8_t buf[RSANUMBYTES];
-  int i;
-
-  if (key->len != RSANUMWORDS) {
-    return 0;  // Wrong key passed in.
-  }
-
-  if (len != sizeof(buf)) {
-    return 0;  // Wrong input length.
-  }
-
-  if (key->exponent != 65537) {
-      return 0;  // Wrong exponent.
-  }
-
-  for (i = 0; i < len; ++i) {  // Copy input to local workspace.
-    buf[i] = signature[i];
-  }
-
-  modpowF4(key, buf);  // In-place exponentiation.
-
-  // Xor sha portion, so it all becomes 00 iff equal.
-  for (i = len - SHA_DIGEST_SIZE; i < len; ++i) {
-    buf[i] ^= *sha++;
-  }
-
-  // Hash resulting buf, in-place.
-  SHA(buf, len, buf);
-
-  // Compare against expected hash value.
-  for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
-    if (buf[i] != kExpectedPadShaRsa2048[i]) {
-      return 0;
-    }
-  }
-
-  return 1;  // All checked out OK.
-}
diff --git a/libmincrypt/sha.c b/libmincrypt/sha.c
index e089d79..5bef32e 100644
--- a/libmincrypt/sha.c
+++ b/libmincrypt/sha.c
@@ -1,6 +1,6 @@
 /* sha.c
 **
-** Copyright 2008, The Android Open Source Project
+** Copyright 2013, The Android Open Source Project
 **
 ** Redistribution and use in source and binary forms, with or without
 ** modification, are permitted provided that the following conditions are met:
@@ -25,177 +25,20 @@
 ** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
+// Optimized for minimal code size.
+
 #include "mincrypt/sha.h"
 
-// Some machines lack byteswap.h and endian.h.  These have to use the
-// slower code, even if they're little-endian.
-
-#if defined(HAVE_ENDIAN_H) && defined(HAVE_LITTLE_ENDIAN)
-
-#include <byteswap.h>
-#include <memory.h>
-
-// This version is about 28% faster than the generic version below,
-// but assumes little-endianness.
-
-static inline uint32_t ror27(uint32_t val) {
-    return (val >> 27) | (val << 5);
-}
-static inline uint32_t ror2(uint32_t val) {
-    return (val >> 2) | (val << 30);
-}
-static inline uint32_t ror31(uint32_t val) {
-    return (val >> 31) | (val << 1);
-}
-
-static void SHA1_Transform(SHA_CTX* ctx) {
-    uint32_t W[80];
-    register uint32_t A, B, C, D, E;
-    int t;
-
-    A = ctx->state[0];
-    B = ctx->state[1];
-    C = ctx->state[2];
-    D = ctx->state[3];
-    E = ctx->state[4];
-
-#define SHA_F1(A,B,C,D,E,t)                     \
-    E += ror27(A) +                             \
-        (W[t] = bswap_32(ctx->buf.w[t])) +      \
-        (D^(B&(C^D))) + 0x5A827999;             \
-    B = ror2(B);
-
-    for (t = 0; t < 15; t += 5) {
-        SHA_F1(A,B,C,D,E,t + 0);
-        SHA_F1(E,A,B,C,D,t + 1);
-        SHA_F1(D,E,A,B,C,t + 2);
-        SHA_F1(C,D,E,A,B,t + 3);
-        SHA_F1(B,C,D,E,A,t + 4);
-    }
-    SHA_F1(A,B,C,D,E,t + 0);  // 16th one, t == 15
-
-#undef SHA_F1
-
-#define SHA_F1(A,B,C,D,E,t)                                     \
-    E += ror27(A) +                                             \
-        (W[t] = ror31(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])) +   \
-        (D^(B&(C^D))) + 0x5A827999;                             \
-    B = ror2(B);
-
-    SHA_F1(E,A,B,C,D,t + 1);
-    SHA_F1(D,E,A,B,C,t + 2);
-    SHA_F1(C,D,E,A,B,t + 3);
-    SHA_F1(B,C,D,E,A,t + 4);
-
-#undef SHA_F1
-
-#define SHA_F2(A,B,C,D,E,t)                                     \
-    E += ror27(A) +                                             \
-        (W[t] = ror31(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])) +   \
-        (B^C^D) + 0x6ED9EBA1;                                   \
-    B = ror2(B);
-
-    for (t = 20; t < 40; t += 5) {
-        SHA_F2(A,B,C,D,E,t + 0);
-        SHA_F2(E,A,B,C,D,t + 1);
-        SHA_F2(D,E,A,B,C,t + 2);
-        SHA_F2(C,D,E,A,B,t + 3);
-        SHA_F2(B,C,D,E,A,t + 4);
-    }
-
-#undef SHA_F2
-
-#define SHA_F3(A,B,C,D,E,t)                                     \
-    E += ror27(A) +                                             \
-        (W[t] = ror31(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])) +   \
-        ((B&C)|(D&(B|C))) + 0x8F1BBCDC;                         \
-    B = ror2(B);
-
-    for (; t < 60; t += 5) {
-        SHA_F3(A,B,C,D,E,t + 0);
-        SHA_F3(E,A,B,C,D,t + 1);
-        SHA_F3(D,E,A,B,C,t + 2);
-        SHA_F3(C,D,E,A,B,t + 3);
-        SHA_F3(B,C,D,E,A,t + 4);
-    }
-
-#undef SHA_F3
-
-#define SHA_F4(A,B,C,D,E,t)                                     \
-    E += ror27(A) +                                             \
-        (W[t] = ror31(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16])) +   \
-        (B^C^D) + 0xCA62C1D6;                                   \
-    B = ror2(B);
-
-    for (; t < 80; t += 5) {
-        SHA_F4(A,B,C,D,E,t + 0);
-        SHA_F4(E,A,B,C,D,t + 1);
-        SHA_F4(D,E,A,B,C,t + 2);
-        SHA_F4(C,D,E,A,B,t + 3);
-        SHA_F4(B,C,D,E,A,t + 4);
-    }
-
-#undef SHA_F4
-
-    ctx->state[0] += A;
-    ctx->state[1] += B;
-    ctx->state[2] += C;
-    ctx->state[3] += D;
-    ctx->state[4] += E;
-}
-
-void SHA_update(SHA_CTX* ctx, const void* data, int len) {
-    int i = ctx->count % sizeof(ctx->buf);
-    const uint8_t* p = (const uint8_t*)data;
-
-    ctx->count += len;
-
-    while (len > sizeof(ctx->buf) - i) {
-        memcpy(&ctx->buf.b[i], p, sizeof(ctx->buf) - i);
-        len -= sizeof(ctx->buf) - i;
-        p += sizeof(ctx->buf) - i;
-        SHA1_Transform(ctx);
-        i = 0;
-    }
-
-    while (len--) {
-        ctx->buf.b[i++] = *p++;
-        if (i == sizeof(ctx->buf)) {
-            SHA1_Transform(ctx);
-            i = 0;
-        }
-    }
-}
-
-
-const uint8_t* SHA_final(SHA_CTX* ctx) {
-    uint64_t cnt = ctx->count * 8;
-    int i;
-
-    SHA_update(ctx, (uint8_t*)"\x80", 1);
-    while ((ctx->count % sizeof(ctx->buf)) != (sizeof(ctx->buf) - 8)) {
-        SHA_update(ctx, (uint8_t*)"\0", 1);
-    }
-    for (i = 0; i < 8; ++i) {
-        uint8_t tmp = cnt >> ((7 - i) * 8);
-        SHA_update(ctx, &tmp, 1);
-    }
-
-    for (i = 0; i < 5; i++) {
-        ctx->buf.w[i] = bswap_32(ctx->state[i]);
-    }
-
-    return ctx->buf.b;
-}
-
-#else   // #if defined(HAVE_ENDIAN_H) && defined(HAVE_LITTLE_ENDIAN)
+#include <stdio.h>
+#include <string.h>
+#include <stdint.h>
 
 #define rol(bits, value) (((value) << (bits)) | ((value) >> (32 - (bits))))
 
-static void SHA1_transform(SHA_CTX *ctx) {
+static void SHA1_Transform(SHA_CTX* ctx) {
     uint32_t W[80];
     uint32_t A, B, C, D, E;
-    uint8_t *p = ctx->buf;
+    uint8_t* p = ctx->buf;
     int t;
 
     for(t = 0; t < 16; ++t) {
@@ -242,31 +85,52 @@
     ctx->state[4] += E;
 }
 
-void SHA_update(SHA_CTX *ctx, const void *data, int len) {
-    int i = ctx->count % sizeof(ctx->buf);
+static const HASH_VTAB SHA_VTAB = {
+    SHA_init,
+    SHA_update,
+    SHA_final,
+    SHA_hash,
+    SHA_DIGEST_SIZE
+};
+
+void SHA_init(SHA_CTX* ctx) {
+    ctx->f = &SHA_VTAB;
+    ctx->state[0] = 0x67452301;
+    ctx->state[1] = 0xEFCDAB89;
+    ctx->state[2] = 0x98BADCFE;
+    ctx->state[3] = 0x10325476;
+    ctx->state[4] = 0xC3D2E1F0;
+    ctx->count = 0;
+}
+
+
+void SHA_update(SHA_CTX* ctx, const void* data, int len) {
+    int i = (int) (ctx->count & 63);
     const uint8_t* p = (const uint8_t*)data;
 
     ctx->count += len;
 
     while (len--) {
         ctx->buf[i++] = *p++;
-        if (i == sizeof(ctx->buf)) {
-            SHA1_transform(ctx);
+        if (i == 64) {
+            SHA1_Transform(ctx);
             i = 0;
         }
     }
 }
-const uint8_t *SHA_final(SHA_CTX *ctx) {
+
+
+const uint8_t* SHA_final(SHA_CTX* ctx) {
     uint8_t *p = ctx->buf;
     uint64_t cnt = ctx->count * 8;
     int i;
 
     SHA_update(ctx, (uint8_t*)"\x80", 1);
-    while ((ctx->count % sizeof(ctx->buf)) != (sizeof(ctx->buf) - 8)) {
+    while ((ctx->count & 63) != 56) {
         SHA_update(ctx, (uint8_t*)"\0", 1);
     }
     for (i = 0; i < 8; ++i) {
-        uint8_t tmp = cnt >> ((7 - i) * 8);
+        uint8_t tmp = (uint8_t) (cnt >> ((7 - i) * 8));
         SHA_update(ctx, &tmp, 1);
     }
 
@@ -281,27 +145,11 @@
     return ctx->buf;
 }
 
-#endif // endianness
-
-void SHA_init(SHA_CTX* ctx) {
-    ctx->state[0] = 0x67452301;
-    ctx->state[1] = 0xEFCDAB89;
-    ctx->state[2] = 0x98BADCFE;
-    ctx->state[3] = 0x10325476;
-    ctx->state[4] = 0xC3D2E1F0;
-    ctx->count = 0;
-}
-
 /* Convenience function */
-const uint8_t* SHA(const void *data, int len, uint8_t *digest) {
-    const uint8_t *p;
-    int i;
+const uint8_t* SHA_hash(const void* data, int len, uint8_t* digest) {
     SHA_CTX ctx;
     SHA_init(&ctx);
     SHA_update(&ctx, data, len);
-    p = SHA_final(&ctx);
-    for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
-        digest[i] = *p++;
-    }
+    memcpy(digest, SHA_final(&ctx), SHA_DIGEST_SIZE);
     return digest;
 }
diff --git a/libmincrypt/sha256.c b/libmincrypt/sha256.c
new file mode 100644
index 0000000..eb6e308
--- /dev/null
+++ b/libmincrypt/sha256.c
@@ -0,0 +1,184 @@
+/* sha256.c
+**
+** Copyright 2013, The Android Open Source Project
+**
+** 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 Google Inc. ``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 Google Inc. 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.
+*/
+
+// Optimized for minimal code size.
+
+#include "mincrypt/sha256.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <stdint.h>
+
+#define ror(value, bits) (((value) >> (bits)) | ((value) << (32 - (bits))))
+#define shr(value, bits) ((value) >> (bits))
+
+static const uint32_t K[64] = {
+    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
+    0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+    0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
+    0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
+    0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+    0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
+    0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
+    0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+    0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };
+
+static void SHA256_Transform(SHA256_CTX* ctx) {
+    uint32_t W[64];
+    uint32_t A, B, C, D, E, F, G, H;
+    uint8_t* p = ctx->buf;
+    int t;
+
+    for(t = 0; t < 16; ++t) {
+        uint32_t tmp =  *p++ << 24;
+        tmp |= *p++ << 16;
+        tmp |= *p++ << 8;
+        tmp |= *p++;
+        W[t] = tmp;
+    }
+
+    for(; t < 64; t++) {
+        uint32_t s0 = ror(W[t-15], 7) ^ ror(W[t-15], 18) ^ shr(W[t-15], 3);
+        uint32_t s1 = ror(W[t-2], 17) ^ ror(W[t-2], 19) ^ shr(W[t-2], 10);
+        W[t] = W[t-16] + s0 + W[t-7] + s1;
+    }
+
+    A = ctx->state[0];
+    B = ctx->state[1];
+    C = ctx->state[2];
+    D = ctx->state[3];
+    E = ctx->state[4];
+    F = ctx->state[5];
+    G = ctx->state[6];
+    H = ctx->state[7];
+
+    for(t = 0; t < 64; t++) {
+        uint32_t s0 = ror(A, 2) ^ ror(A, 13) ^ ror(A, 22);
+        uint32_t maj = (A & B) ^ (A & C) ^ (B & C);
+        uint32_t t2 = s0 + maj;
+        uint32_t s1 = ror(E, 6) ^ ror(E, 11) ^ ror(E, 25);
+        uint32_t ch = (E & F) ^ ((~E) & G);
+        uint32_t t1 = H + s1 + ch + K[t] + W[t];
+
+        H = G;
+        G = F;
+        F = E;
+        E = D + t1;
+        D = C;
+        C = B;
+        B = A;
+        A = t1 + t2;
+    }
+
+    ctx->state[0] += A;
+    ctx->state[1] += B;
+    ctx->state[2] += C;
+    ctx->state[3] += D;
+    ctx->state[4] += E;
+    ctx->state[5] += F;
+    ctx->state[6] += G;
+    ctx->state[7] += H;
+}
+
+static const HASH_VTAB SHA256_VTAB = {
+    SHA256_init,
+    SHA256_update,
+    SHA256_final,
+    SHA256_hash,
+    SHA256_DIGEST_SIZE
+};
+
+void SHA256_init(SHA256_CTX* ctx) {
+    ctx->f = &SHA256_VTAB;
+    ctx->state[0] = 0x6a09e667;
+    ctx->state[1] = 0xbb67ae85;
+    ctx->state[2] = 0x3c6ef372;
+    ctx->state[3] = 0xa54ff53a;
+    ctx->state[4] = 0x510e527f;
+    ctx->state[5] = 0x9b05688c;
+    ctx->state[6] = 0x1f83d9ab;
+    ctx->state[7] = 0x5be0cd19;
+    ctx->count = 0;
+}
+
+
+void SHA256_update(SHA256_CTX* ctx, const void* data, int len) {
+    int i = (int) (ctx->count & 63);
+    const uint8_t* p = (const uint8_t*)data;
+
+    ctx->count += len;
+
+    while (len--) {
+        ctx->buf[i++] = *p++;
+        if (i == 64) {
+            SHA256_Transform(ctx);
+            i = 0;
+        }
+    }
+}
+
+
+const uint8_t* SHA256_final(SHA256_CTX* ctx) {
+    uint8_t *p = ctx->buf;
+    uint64_t cnt = ctx->count * 8;
+    int i;
+
+    SHA256_update(ctx, (uint8_t*)"\x80", 1);
+    while ((ctx->count & 63) != 56) {
+        SHA256_update(ctx, (uint8_t*)"\0", 1);
+    }
+    for (i = 0; i < 8; ++i) {
+        uint8_t tmp = (uint8_t) (cnt >> ((7 - i) * 8));
+        SHA256_update(ctx, &tmp, 1);
+    }
+
+    for (i = 0; i < 8; i++) {
+        uint32_t tmp = ctx->state[i];
+        *p++ = tmp >> 24;
+        *p++ = tmp >> 16;
+        *p++ = tmp >> 8;
+        *p++ = tmp >> 0;
+    }
+
+    return ctx->buf;
+}
+
+/* Convenience function */
+const uint8_t* SHA256_hash(const void* data, int len, uint8_t* digest) {
+    SHA256_CTX ctx;
+    SHA256_init(&ctx);
+    SHA256_update(&ctx, data, len);
+    memcpy(digest, SHA256_final(&ctx), SHA256_DIGEST_SIZE);
+    return digest;
+}
diff --git a/libmincrypt/test/Android.mk b/libmincrypt/test/Android.mk
new file mode 100644
index 0000000..a28ccd8
--- /dev/null
+++ b/libmincrypt/test/Android.mk
@@ -0,0 +1,10 @@
+# Copyright 2013 The Android Open Source Project
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := rsa_test
+LOCAL_SRC_FILES := rsa_test.c
+LOCAL_STATIC_LIBRARIES := libmincrypt
+include $(BUILD_HOST_EXECUTABLE)
+
diff --git a/libmincrypt/test/rsa_test.c b/libmincrypt/test/rsa_test.c
new file mode 100644
index 0000000..17862dc
--- /dev/null
+++ b/libmincrypt/test/rsa_test.c
@@ -0,0 +1,838 @@
+/* rsa_test.c
+**
+** Copyright 2013, The Android Open Source Project
+**
+** 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 Google Inc. ``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 Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <stdio.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "mincrypt/rsa.h"
+#include "mincrypt/sha.h"
+
+// RSA test data taken from:
+//
+//   ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
+
+// This is the result (reformatted) of running DumpPublicKey on:
+//
+//   # Example 15: A 2048-bit RSA key pair
+//   # -----------------------------------
+//
+//
+//   # Public key
+//   # ----------
+//
+//   # Modulus:
+//   df 27 1f d2 5f 86 44 49 6b 0c 81 be 4b d5 02 97
+//   ef 09 9b 00 2a 6f d6 77 27 eb 44 9c ea 56 6e d6
+//   a3 98 1a 71 31 2a 14 1c ab c9 81 5c 12 09 e3 20
+//   a2 5b 32 46 4e 99 99 f1 8c a1 3a 9f d3 89 25 58
+//   f9 e0 ad ef dd 36 50 dd 23 a3 f0 36 d6 0f e3 98
+//   84 37 06 a4 0b 0b 84 62 c8 be e3 bc e1 2f 1f 28
+//   60 c2 44 4c dc 6a 44 47 6a 75 ff 4a a2 42 73 cc
+//   be 3b f8 02 48 46 5f 8f f8 c3 a7 f3 36 7d fc 0d
+//   f5 b6 50 9a 4f 82 81 1c ed d8 1c da aa 73 c4 91
+//   da 41 21 70 d5 44 d4 ba 96 b9 7f 0a fc 80 65 49
+//   8d 3a 49 fd 91 09 92 a1 f0 72 5b e2 4f 46 5c fe
+//   7e 0e ab f6 78 99 6c 50 bc 5e 75 24 ab f7 3f 15
+//   e5 be f7 d5 18 39 4e 31 38 ce 49 44 50 6a aa af
+//   3f 9b 23 6d ca b8 fc 00 f8 7a f5 96 fd c3 d9 d6
+//   c7 5c d5 08 36 2f ae 2c be dd cc 4c 74 50 b1 7b
+//   77 6c 07 9e cc a1 f2 56 35 1a 43 b9 7d be 21 53
+//
+//   # Exponent:
+//   01 00 01
+
+RSAPublicKey key_15 = {
+    .len = 64,
+    .n0inv = 0xf0053525,
+    .n = {2109612371u,890913721u,3433165398u,2003568542u,
+          1951445371u,3202206796u,909094444u,3344749832u,
+          4257470934u,4168807830u,3401120768u,1067131757u,
+          1349167791u,953043268u,406408753u,3854497749u,
+          2885107477u,3160306980u,2023320656u,2114890742u,
+          1330011390u,4034026466u,2433323681u,2369407485u,
+          4236272969u,2528739082u,3578057914u,3661701488u,
+          2859713681u,3990363354u,1333952796u,4122366106u,
+          914226189u,4173572083u,1212571535u,3191601154u,
+          2722264012u,1786117962u,3697951815u,1623344204u,
+          3777961768u,3367953340u,185304162u,2218198692u,
+          3591365528u,597946422u,3711324381u,4192251375u,
+          3548980568u,2359376543u,1318689265u,2723885638u,
+          302637856u,2882109788u,824841244u,2744654449u,
+          3931533014u,669729948u,711972471u,4010384128u,
+          1272251031u,1795981758u,1602634825u,3743883218u},
+    .rr = {820482522u,2494434288u,1082168230u,731376296u,
+           1306039452u,3139792975u,2575869288u,3874938710u,
+           3198185181u,153506080u,1236489694u,1061859740u,
+           1174461268u,115279508u,1782749185u,238124145u,
+           3587596076u,2259236093u,1112265915u,4048059865u,
+           3890381098u,999426242u,794481771u,3804065613u,
+           2786019148u,461403875u,3072256692u,4079652654u,
+           3056719901u,1871565394u,212974856u,3359008174u,
+           1397773937u,3796256698u,914342841u,1097174457u,
+           3322220191u,3170814748u,2439215020u,618719336u,
+           3629353460u,496817177u,317052742u,380264245u,
+           1976007217u,2697736152u,312540864u,4291855337u,
+           697006561u,4234182488u,3904590917u,2609582216u,
+           451424084u,1805773827u,776344974u,1064489733u,
+           2633377036u,1954826648u,3202815814u,2240368662u,
+           2618582484u,2211196815u,4107362845u,3640258615u},
+    .exponent = 65537,
+};
+
+// PKCS#1 v1.5 Signature Example 15.1
+
+char* message_1 =
+    "f4 5d 55 f3 55 51 e9 75 d6 a8 dc 7e a9 f4 88 59"
+    "39 40 cc 75 69 4a 27 8f 27 e5 78 a1 63 d8 39 b3"
+    "40 40 84 18 08 cf 9c 58 c9 b8 72 8b f5 f9 ce 8e"
+    "e8 11 ea 91 71 4f 47 ba b9 2d 0f 6d 5a 26 fc fe"
+    "ea 6c d9 3b 91 0c 0a 2c 96 3e 64 eb 18 23 f1 02"
+    "75 3d 41 f0 33 59 10 ad 3a 97 71 04 f1 aa f6 c3"
+    "74 27 16 a9 75 5d 11 b8 ee d6 90 47 7f 44 5c 5d"
+    "27 20 8b 2e 28 43 30 fa 3d 30 14 23 fa 7f 2d 08"
+    "6e 0a d0 b8 92 b9 db 54 4e 45 6d 3f 0d ab 85 d9"
+    "53 c1 2d 34 0a a8 73 ed a7 27 c8 a6 49 db 7f a6"
+    "37 40 e2 5e 9a f1 53 3b 30 7e 61 32 99 93 11 0e"
+    "95 19 4e 03 93 99 c3 82 4d 24 c5 1f 22 b2 6b de"
+    "10 24 cd 39 59 58 a2 df eb 48 16 a6 e8 ad ed b5"
+    "0b 1f 6b 56 d0 b3 06 0f f0 f1 c4 cb 0d 0e 00 1d"
+    "d5 9d 73 be 12";
+
+char* signature_1 =
+    "b7 5a 54 66 b6 5d 0f 30 0e f5 38 33 f2 17 5c 8a"
+    "34 7a 38 04 fc 63 45 1d c9 02 f0 b7 1f 90 83 45"
+    "9e d3 7a 51 79 a3 b7 23 a5 3f 10 51 64 2d 77 37"
+    "4c 4c 6c 8d bb 1c a2 05 25 f5 c9 f3 2d b7 76 95"
+    "35 56 da 31 29 0e 22 19 74 82 ce b6 99 06 c4 6a"
+    "75 8f b0 e7 40 9b a8 01 07 7d 2a 0a 20 ea e7 d1"
+    "d6 d3 92 ab 49 57 e8 6b 76 f0 65 2d 68 b8 39 88"
+    "a7 8f 26 e1 11 72 ea 60 9b f8 49 fb bd 78 ad 7e"
+    "dc e2 1d e6 62 a0 81 36 8c 04 06 07 ce e2 9d b0"
+    "62 72 27 f4 49 63 ad 17 1d 22 93 b6 33 a3 92 e3"
+    "31 dc a5 4f e3 08 27 52 f4 3f 63 c1 61 b4 47 a4"
+    "c6 5a 68 75 67 0d 5f 66 00 fc c8 60 a1 ca eb 0a"
+    "88 f8 fd ec 4e 56 43 98 a5 c4 6c 87 f6 8c e0 70"
+    "01 f6 21 3a be 0a b5 62 5f 87 d1 90 25 f0 8d 81"
+    "da c7 bd 45 86 bc 93 82 19 1f 6d 28 80 f6 22 7e"
+    "5d f3 ee d2 1e 77 92 d2 49 48 04 87 f3 65 52 61";
+
+// PKCS#1 v1.5 Signature Example 15.2
+
+char *message_2 =
+    "c1 4b 4c 60 75 b2 f9 aa d6 61 de f4 ec fd 3c b9 "
+    "33 c6 23 f4 e6 3b f5 34 10 d2 f0 16 d1 ab 98 e2 "
+    "72 9e cc f8 00 6c d8 e0 80 50 73 7d 95 fd bf 29 "
+    "6b 66 f5 b9 79 2a 90 29 36 c4 f7 ac 69 f5 14 53 "
+    "ce 43 69 45 2d c2 2d 96 f0 37 74 81 14 66 20 00 "
+    "dd 9c d3 a5 e1 79 f4 e0 f8 1f a6 a0 31 1c a1 ae "
+    "e6 51 9a 0f 63 ce c7 8d 27 bb 72 63 93 fb 7f 1f "
+    "88 cd e7 c9 7f 8a 66 cd 66 30 12 81 da c3 f3 a4 "
+    "33 24 8c 75 d6 c2 dc d7 08 b6 a9 7b 0a 3f 32 5e "
+    "0b 29 64 f8 a5 81 9e 47 9b ";
+
+char* signature_2 =
+    "af a7 34 34 62 be a1 22 cc 14 9f ca 70 ab da e7"
+    "94 46 67 7d b5 37 36 66 af 7d c3 13 01 5f 4d e7"
+    "86 e6 e3 94 94 6f ad 3c c0 e2 b0 2b ed ba 50 47"
+    "fe 9e 2d 7d 09 97 05 e4 a3 9f 28 68 32 79 cf 0a"
+    "c8 5c 15 30 41 22 42 c0 e9 18 95 3b e0 00 e9 39"
+    "cf 3b f1 82 52 5e 19 93 70 fa 79 07 eb a6 9d 5d"
+    "b4 63 10 17 c0 e3 6d f7 03 79 b5 db 8d 4c 69 5a"
+    "97 9a 8e 61 73 22 40 65 d7 dc 15 13 2e f2 8c d8"
+    "22 79 51 63 06 3b 54 c6 51 14 1b e8 6d 36 e3 67"
+    "35 bc 61 f3 1f ca 57 4e 53 09 f3 a3 bb df 91 ef"
+    "f1 2b 99 e9 cc 17 44 f1 ee 9a 1b d2 2c 5b ad 96"
+    "ad 48 19 29 25 1f 03 43 fd 36 bc f0 ac de 7f 11"
+    "e5 ad 60 97 77 21 20 27 96 fe 06 1f 9a da 1f c4"
+    "c8 e0 0d 60 22 a8 35 75 85 ff e9 fd d5 93 31 a2"
+    "8c 4a a3 12 15 88 fb 6c f6 83 96 d8 ac 05 46 59"
+    "95 00 c9 70 85 00 a5 97 2b d5 4f 72 cf 8d b0 c8";
+
+// PKCS#1 v1.5 Signature Example 15.3
+
+char* message_3 =
+    "d0 23 71 ad 7e e4 8b bf db 27 63 de 7a 84 3b 94 "
+    "08 ce 5e b5 ab f8 47 ca 3d 73 59 86 df 84 e9 06 "
+    "0b db cd d3 a5 5b a5 5d de 20 d4 76 1e 1a 21 d2 "
+    "25 c1 a1 86 f4 ac 4b 30 19 d3 ad f7 8f e6 33 46 "
+    "67 f5 6f 70 c9 01 a0 a2 70 0c 6f 0d 56 ad d7 19 "
+    "59 2d c8 8f 6d 23 06 c7 00 9f 6e 7a 63 5b 4c b3 "
+    "a5 02 df e6 8d dc 58 d0 3b e1 0a 11 70 00 4f e7 "
+    "4d d3 e4 6b 82 59 1f f7 54 14 f0 c4 a0 3e 60 5e "
+    "20 52 4f 24 16 f1 2e ca 58 9f 11 1b 75 d6 39 c6 "
+    "1b aa 80 ca fd 05 cf 35 00 24 4a 21 9e d9 ce d9 "
+    "f0 b1 02 97 18 2b 65 3b 52 6f 40 0f 29 53 ba 21 "
+    "4d 5b cd 47 88 41 32 87 2a e9 0d 4d 6b 1f 42 15 "
+    "39 f9 f3 46 62 a5 6d c0 e7 b4 b9 23 b6 23 1e 30 "
+    "d2 67 67 97 81 7f 7c 33 7b 5a c8 24 ba 93 14 3b "
+    "33 81 fa 3d ce 0e 6a eb d3 8e 67 73 51 87 b1 eb "
+    "d9 5c 02 ";
+
+char* signature_3 =
+    "3b ac 63 f8 6e 3b 70 27 12 03 10 6b 9c 79 aa bd"
+    "9f 47 7c 56 e4 ee 58 a4 fc e5 ba f2 ca b4 96 0f"
+    "88 39 1c 9c 23 69 8b e7 5c 99 ae df 9e 1a bf 17"
+    "05 be 1d ac 33 14 0a db 48 eb 31 f4 50 bb 9e fe"
+    "83 b7 b9 0d b7 f1 57 6d 33 f4 0c 1c ba 4b 8d 6b"
+    "1d 33 23 56 4b 0f 17 74 11 4f a7 c0 8e 6d 1e 20"
+    "dd 8f bb a9 b6 ac 7a d4 1e 26 b4 56 8f 4a 8a ac"
+    "bf d1 78 a8 f8 d2 c9 d5 f5 b8 81 12 93 5a 8b c9"
+    "ae 32 cd a4 0b 8d 20 37 55 10 73 50 96 53 68 18"
+    "ce 2b 2d b7 1a 97 72 c9 b0 dd a0 9a e1 01 52 fa"
+    "11 46 62 18 d0 91 b5 3d 92 54 30 61 b7 29 4a 55"
+    "be 82 ff 35 d5 c3 2f a2 33 f0 5a aa c7 58 50 30"
+    "7e cf 81 38 3c 11 16 74 39 7b 1a 1b 9d 3b f7 61"
+    "2c cb e5 ba cd 2b 38 f0 a9 83 97 b2 4c 83 65 8f"
+    "b6 c0 b4 14 0e f1 19 70 c4 63 0d 44 34 4e 76 ea"
+    "ed 74 dc be e8 11 db f6 57 59 41 f0 8a 65 23 b8";
+
+// PKCS#1 v1.5 Signature Example 15.4
+
+char* message_4 =
+    "29 03 55 84 ab 7e 02 26 a9 ec 4b 02 e8 dc f1 27 "
+    "2d c9 a4 1d 73 e2 82 00 07 b0 f6 e2 1f ec cd 5b "
+    "d9 db b9 ef 88 cd 67 58 76 9e e1 f9 56 da 7a d1 "
+    "84 41 de 6f ab 83 86 db c6 93 ";
+
+char* signature_4 =
+    "28 d8 e3 fc d5 dd db 21 ff bd 8d f1 63 0d 73 77"
+    "aa 26 51 e1 4c ad 1c 0e 43 cc c5 2f 90 7f 94 6d"
+    "66 de 72 54 e2 7a 6c 19 0e b0 22 ee 89 ec f6 22"
+    "4b 09 7b 71 06 8c d6 07 28 a1 ae d6 4b 80 e5 45"
+    "7b d3 10 6d d9 17 06 c9 37 c9 79 5f 2b 36 36 7f"
+    "f1 53 dc 25 19 a8 db 9b df 2c 80 74 30 c4 51 de"
+    "17 bb cd 0c e7 82 b3 e8 f1 02 4d 90 62 4d ea 7f"
+    "1e ed c7 42 0b 7e 7c aa 65 77 ce f4 31 41 a7 26"
+    "42 06 58 0e 44 a1 67 df 5e 41 ee a0 e6 9a 80 54"
+    "54 c4 0e ef c1 3f 48 e4 23 d7 a3 2d 02 ed 42 c0"
+    "ab 03 d0 a7 cf 70 c5 86 0a c9 2e 03 ee 00 5b 60"
+    "ff 35 03 42 4b 98 cc 89 45 68 c7 c5 6a 02 33 55"
+    "1c eb e5 88 cf 8b 01 67 b7 df 13 ad ca d8 28 67"
+    "68 10 49 9c 70 4d a7 ae 23 41 4d 69 e3 c0 d2 db"
+    "5d cb c2 61 3b c1 20 42 1f 9e 36 53 c5 a8 76 72"
+    "97 64 3c 7e 07 40 de 01 63 55 45 3d 6c 95 ae 72";
+
+// PKCS#1 v1.5 Signature Example 15.5
+
+char* message_5 =
+    "bd a3 a1 c7 90 59 ea e5 98 30 8d 3d f6 09 ";
+
+char* signature_5 =
+    "a1 56 17 6c b9 67 77 c7 fb 96 10 5d bd 91 3b c4"
+    "f7 40 54 f6 80 7c 60 08 a1 a9 56 ea 92 c1 f8 1c"
+    "b8 97 dc 4b 92 ef 9f 4e 40 66 8d c7 c5 56 90 1a"
+    "cb 6c f2 69 fe 61 5b 0f b7 2b 30 a5 13 38 69 23"
+    "14 b0 e5 87 8a 88 c2 c7 77 4b d1 69 39 b5 ab d8"
+    "2b 44 29 d6 7b d7 ac 8e 5e a7 fe 92 4e 20 a6 ec"
+    "66 22 91 f2 54 8d 73 4f 66 34 86 8b 03 9a a5 f9"
+    "d4 d9 06 b2 d0 cb 85 85 bf 42 85 47 af c9 1c 6e"
+    "20 52 dd cd 00 1c 3e f8 c8 ee fc 3b 6b 2a 82 b6"
+    "f9 c8 8c 56 f2 e2 c3 cb 0b e4 b8 0d a9 5e ba 37"
+    "1d 8b 5f 60 f9 25 38 74 3d db b5 da 29 72 c7 1f"
+    "e7 b9 f1 b7 90 26 8a 0e 77 0f c5 eb 4d 5d d8 52"
+    "47 d4 8a e2 ec 3f 26 25 5a 39 85 52 02 06 a1 f2"
+    "68 e4 83 e9 db b1 d5 ca b1 90 91 76 06 de 31 e7"
+    "c5 18 2d 8f 15 1b f4 1d fe cc ae d7 cd e6 90 b2"
+    "16 47 10 6b 49 0c 72 9d 54 a8 fe 28 02 a6 d1 26";
+
+// PKCS#1 v1.5 Signature Example 15.6
+
+char* message_6 =
+    "c1 87 91 5e 4e 87 da 81 c0 8e d4 35 6a 0c ce ac "
+    "1c 4f b5 c0 46 b4 52 81 b3 87 ec 28 f1 ab fd 56 "
+    "7e 54 6b 23 6b 37 d0 1a e7 1d 3b 28 34 36 5d 3d "
+    "f3 80 b7 50 61 b7 36 b0 13 0b 07 0b e5 8a e8 a4 "
+    "6d 12 16 63 61 b6 13 db c4 7d fa eb 4c a7 46 45 "
+    "6c 2e 88 83 85 52 5c ca 9d d1 c3 c7 a9 ad a7 6d "
+    "6c ";;
+
+char* signature_6 =
+    "9c ab 74 16 36 08 66 9f 75 55 a3 33 cf 19 6f e3"
+    "a0 e9 e5 eb 1a 32 d3 4b b5 c8 5f f6 89 aa ab 0e"
+    "3e 65 66 8e d3 b1 15 3f 94 eb 3d 8b e3 79 b8 ee"
+    "f0 07 c4 a0 2c 70 71 ce 30 d8 bb 34 1e 58 c6 20"
+    "f7 3d 37 b4 ec bf 48 be 29 4f 6c 9e 0e cb 5e 63"
+    "fe c4 1f 12 0e 55 53 df a0 eb eb bb 72 64 0a 95"
+    "37 ba dc b4 51 33 02 29 d9 f7 10 f6 2e 3e d8 ec"
+    "78 4e 50 ee 1d 92 62 b4 26 71 34 00 11 d7 d0 98"
+    "c6 f2 55 7b 21 31 fa 9b d0 25 46 36 59 7e 88 ec"
+    "b3 5a 24 0e f0 fd 85 95 71 24 df 80 80 fe e1 e1"
+    "49 af 93 99 89 e8 6b 26 c8 5a 58 81 fa e8 67 3d"
+    "9f d4 08 00 dd 13 4e b9 bd b6 41 0f 42 0b 0a a9"
+    "7b 20 ef cf 2e b0 c8 07 fa eb 83 a3 cc d9 b5 1d"
+    "45 53 e4 1d fc 0d f6 ca 80 a1 e8 1d c2 34 bb 83"
+    "89 dd 19 5a 38 b4 2d e4 ed c4 9d 34 64 78 b9 f1"
+    "1f 05 57 20 5f 5b 0b d7 ff e9 c8 50 f3 96 d7 c4";;
+
+// PKCS#1 v1.5 Signature Example 15.7
+
+char* message_7 =
+    "ab fa 2e cb 7d 29 bd 5b cb 99 31 ce 2b ad 2f 74 "
+    "38 3e 95 68 3c ee 11 02 2f 08 e8 e7 d0 b8 fa 05 "
+    "8b f9 eb 7e b5 f9 88 68 b5 bb 1f b5 c3 1c ed a3 "
+    "a6 4f 1a 12 cd f2 0f cd 0e 5a 24 6d 7a 17 73 d8 "
+    "db a0 e3 b2 77 54 5b ab e5 8f 2b 96 e3 f4 ed c1 "
+    "8e ab f5 cd 2a 56 0f ca 75 fe 96 e0 7d 85 9d ef "
+    "b2 56 4f 3a 34 f1 6f 11 e9 1b 3a 71 7b 41 af 53 "
+    "f6 60 53 23 00 1a a4 06 c6 ";
+
+char* signature_7 =
+    "c4 b4 37 bc f7 03 f3 52 e1 fa f7 4e b9 62 20 39"
+    "42 6b 56 72 ca f2 a7 b3 81 c6 c4 f0 19 1e 7e 4a"
+    "98 f0 ee bc d6 f4 17 84 c2 53 7f f0 f9 9e 74 98"
+    "2c 87 20 1b fb c6 5e ae 83 2d b7 1d 16 da ca db"
+    "09 77 e5 c5 04 67 9e 40 be 0f 9d b0 6f fd 84 8d"
+    "d2 e5 c3 8a 7e c0 21 e7 f6 8c 47 df d3 8c c3 54"
+    "49 3d 53 39 b4 59 5a 5b f3 1e 3f 8f 13 81 68 07"
+    "37 3d f6 ad 0d c7 e7 31 e5 1a d1 9e b4 75 4b 13"
+    "44 85 84 2f e7 09 d3 78 44 4d 8e 36 b1 72 4a 4f"
+    "da 21 ca fe e6 53 ab 80 74 7f 79 52 ee 80 4d ea"
+    "b1 03 9d 84 13 99 45 bb f4 be 82 00 87 53 f3 c5"
+    "4c 78 21 a1 d2 41 f4 21 79 c7 94 ef 70 42 bb f9"
+    "95 56 56 22 2e 45 c3 43 69 a3 84 69 7b 6a e7 42"
+    "e1 8f a5 ca 7a ba d2 7d 9f e7 10 52 e3 31 0d 0f"
+    "52 c8 d1 2e a3 3b f0 53 a3 00 f4 af c4 f0 98 df"
+    "4e 6d 88 67 79 d6 45 94 d3 69 15 8f db c1 f6 94";
+
+// PKCS#1 v1.5 Signature Example 15.8
+
+char* message_8 =
+    "df 40 44 a8 9a 83 e9 fc bf 12 62 54 0a e3 03 8b "
+    "bc 90 f2 b2 62 8b f2 a4 46 7a c6 77 22 d8 54 6b "
+    "3a 71 cb 0e a4 16 69 d5 b4 d6 18 59 c1 b4 e4 7c "
+    "ec c5 93 3f 75 7e c8 6d b0 64 4e 31 18 12 d0 0f "
+    "b8 02 f0 34 00 63 9c 0e 36 4d ae 5a eb c5 79 1b "
+    "c6 55 76 23 61 bc 43 c5 3d 3c 78 86 76 8f 79 68 "
+    "c1 c5 44 c6 f7 9f 7b e8 20 c7 e2 bd 2f 9d 73 e6 "
+    "2d ed 6d 2e 93 7e 6a 6d ae f9 0e e3 7a 1a 52 a5 "
+    "4f 00 e3 1a dd d6 48 94 cf 4c 02 e1 60 99 e2 9f "
+    "9e b7 f1 a7 bb 7f 84 c4 7a 2b 59 48 13 be 02 a1 "
+    "7b 7f c4 3b 34 c2 2c 91 92 52 64 12 6c 89 f8 6b "
+    "b4 d8 7f 3e f1 31 29 6c 53 a3 08 e0 33 1d ac 8b "
+    "af 3b 63 42 22 66 ec ef 2b 90 78 15 35 db da 41 "
+    "cb d0 cf 22 a8 cb fb 53 2e c6 8f c6 af b2 ac 06 ";
+
+char* signature_8 =
+    "14 14 b3 85 67 ae 6d 97 3e de 4a 06 84 2d cc 0e"
+    "05 59 b1 9e 65 a4 88 9b db ab d0 fd 02 80 68 29"
+    "13 ba cd 5d c2 f0 1b 30 bb 19 eb 81 0b 7d 9d ed"
+    "32 b2 84 f1 47 bb e7 71 c9 30 c6 05 2a a7 34 13"
+    "90 a8 49 f8 1d a9 cd 11 e5 ec cf 24 6d ba e9 5f"
+    "a9 58 28 e9 ae 0c a3 55 03 25 32 6d ee f9 f4 95"
+    "30 ba 44 1b ed 4a c2 9c 02 9c 9a 27 36 b1 a4 19"
+    "0b 85 08 4a d1 50 42 6b 46 d7 f8 5b d7 02 f4 8d"
+    "ac 5f 71 33 0b c4 23 a7 66 c6 5c c1 dc ab 20 d3"
+    "d3 bb a7 2b 63 b3 ef 82 44 d4 2f 15 7c b7 e3 a8"
+    "ba 5c 05 27 2c 64 cc 1a d2 1a 13 49 3c 39 11 f6"
+    "0b 4e 9f 4e cc 99 00 eb 05 6e e5 9d 6f e4 b8 ff"
+    "6e 80 48 cc c0 f3 8f 28 36 fd 3d fe 91 bf 4a 38"
+    "6e 1e cc 2c 32 83 9f 0c a4 d1 b2 7a 56 8f a9 40"
+    "dd 64 ad 16 bd 01 25 d0 34 8e 38 30 85 f0 88 94"
+    "86 1c a1 89 87 22 7d 37 b4 2b 58 4a 83 57 cb 04";
+
+// PKCS#1 v1.5 Signature Example 15.9
+
+char* message_9 =
+    "ea 94 1f f0 6f 86 c2 26 92 7f cf 0e 3b 11 b0 87 "
+    "26 76 17 0c 1b fc 33 bd a8 e2 65 c7 77 71 f9 d0 "
+    "85 01 64 a5 ee cb cc 5c e8 27 fb fa 07 c8 52 14 "
+    "79 6d 81 27 e8 ca a8 18 94 ea 61 ce b1 44 9e 72 "
+    "fe a0 a4 c9 43 b2 da 6d 9b 10 5f e0 53 b9 03 9a "
+    "9c c5 3d 42 0b 75 39 fa b2 23 9c 6b 51 d1 7e 69 "
+    "4c 95 7d 4b 0f 09 84 46 18 79 a0 75 9c 44 01 be "
+    "ec d4 c6 06 a0 af bd 7a 07 6f 50 a2 df c2 80 7f "
+    "24 f1 91 9b aa 77 46 d3 a6 4e 26 8e d3 f5 f8 e6 "
+    "da 83 a2 a5 c9 15 2f 83 7c b0 78 12 bd 5b a7 d3 "
+    "a0 79 85 de 88 11 3c 17 96 e9 b4 66 ec 29 9c 5a "
+    "c1 05 9e 27 f0 94 15 ";
+
+char* signature_9 =
+    "ce eb 84 cc b4 e9 09 92 65 65 07 21 ee a0 e8 ec"
+    "89 ca 25 bd 35 4d 4f 64 56 49 67 be 9d 4b 08 b3"
+    "f1 c0 18 53 9c 9d 37 1c f8 96 1f 22 91 fb e0 dc"
+    "2f 2f 95 fe a4 7b 63 9f 1e 12 f4 bc 38 1c ef 0c"
+    "2b 7a 7b 95 c3 ad f2 76 05 b7 f6 39 98 c3 cb ad"
+    "54 28 08 c3 82 2e 06 4d 4a d1 40 93 67 9e 6e 01"
+    "41 8a 6d 5c 05 96 84 cd 56 e3 4e d6 5a b6 05 b8"
+    "de 4f cf a6 40 47 4a 54 a8 25 1b bb 73 26 a4 2d"
+    "08 58 5c fc fc 95 67 69 b1 5b 6d 7f df 7d a8 4f"
+    "81 97 6e aa 41 d6 92 38 0f f1 0e ae cf e0 a5 79"
+    "68 29 09 b5 52 1f ad e8 54 d7 97 b8 a0 34 5b 9a"
+    "86 4e 05 88 f6 ca dd bf 65 f1 77 99 8e 18 0d 1f"
+    "10 24 43 e6 dc a5 3a 94 82 3c aa 9c 3b 35 f3 22"
+    "58 3c 70 3a f6 74 76 15 9e c7 ec 93 d1 76 9b 30"
+    "0a f0 e7 15 7d c2 98 c6 cd 2d ee 22 62 f8 cd dc"
+    "10 f1 1e 01 74 14 71 bb fd 65 18 a1 75 73 45 75";
+
+// PKCS#1 v1.5 Signature Example 15.10
+
+char* message_10 =
+    "d8 b8 16 45 c1 3c d7 ec f5 d0 0e d2 c9 1b 9a cd "
+    "46 c1 55 68 e5 30 3c 4a 97 75 ed e7 6b 48 40 3d "
+    "6b e5 6c 05 b6 b1 cf 77 c6 e7 5d e0 96 c5 cb 35 "
+    "51 cb 6f a9 64 f3 c8 79 cf 58 9d 28 e1 da 2f 9d "
+    "ec ";
+
+char* signature_10 =
+    "27 45 07 4c a9 71 75 d9 92 e2 b4 47 91 c3 23 c5"
+    "71 67 16 5c dd 8d a5 79 cd ef 46 86 b9 bb 40 4b"
+    "d3 6a 56 50 4e b1 fd 77 0f 60 bf a1 88 a7 b2 4b"
+    "0c 91 e8 81 c2 4e 35 b0 4d c4 dd 4c e3 85 66 bc"
+    "c9 ce 54 f4 9a 17 5f c9 d0 b2 25 22 d9 57 90 47"
+    "f9 ed 42 ec a8 3f 76 4a 10 16 39 97 94 7e 7d 2b"
+    "52 ff 08 98 0e 7e 7c 22 57 93 7b 23 f3 d2 79 d4"
+    "cd 17 d6 f4 95 54 63 73 d9 83 d5 36 ef d7 d1 b6"
+    "71 81 ca 2c b5 0a c6 16 c5 c7 ab fb b9 26 0b 91"
+    "b1 a3 8e 47 24 20 01 ff 45 2f 8d e1 0c a6 ea ea"
+    "dc af 9e dc 28 95 6f 28 a7 11 29 1f c9 a8 08 78"
+    "b8 ba 4c fe 25 b8 28 1c b8 0b c9 cd 6d 2b d1 82"
+    "52 46 ee be 25 2d 99 57 ef 93 70 73 52 08 4e 6d"
+    "36 d4 23 55 1b f2 66 a8 53 40 fb 4a 6a f3 70 88"
+    "0a ab 07 15 3d 01 f4 8d 08 6d f0 bf be c0 5e 7b"
+    "44 3b 97 e7 17 18 97 0e 2f 4b f6 20 23 e9 5b 67";
+
+// PKCS#1 v1.5 Signature Example 15.11
+
+char* message_11 =
+    "e5 73 9b 6c 14 c9 2d 51 0d 95 b8 26 93 33 37 ff "
+    "0d 24 ef 72 1a c4 ef 64 c2 ba d2 64 be 8b 44 ef "
+    "a1 51 6e 08 a2 7e b6 b6 11 d3 30 1d f0 06 2d ae "
+    "fc 73 a8 c0 d9 2e 2c 52 1f ac bc 7b 26 47 38 76 "
+    "7e a6 fc 97 d5 88 a0 ba f6 ce 50 ad f7 9e 60 0b "
+    "d2 9e 34 5f cb 1d ba 71 ac 5c 02 89 02 3f e4 a8 "
+    "2b 46 a5 40 77 19 19 7d 2e 95 8e 35 31 fd 54 ae "
+    "f9 03 aa bb 43 55 f8 83 18 99 4e d3 c3 dd 62 f4 "
+    "20 a7 ";
+
+char* signature_11 =
+    "be 40 a5 fb 94 f1 13 e1 b3 ef f6 b6 a3 39 86 f2"
+    "02 e3 63 f0 74 83 b7 92 e6 8d fa 55 54 df 04 66"
+    "cc 32 15 09 50 78 3b 4d 96 8b 63 9a 04 fd 2f b9"
+    "7f 6e b9 67 02 1f 5a dc cb 9f ca 95 ac c8 f2 cd"
+    "88 5a 38 0b 0a 4e 82 bc 76 07 64 db ab 88 c1 e6"
+    "c0 25 5c aa 94 f2 32 19 9d 6f 59 7c c9 14 5b 00"
+    "e3 d4 ba 34 6b 55 9a 88 33 ad 15 16 ad 51 63 f0"
+    "16 af 6a 59 83 1c 82 ea 13 c8 22 4d 84 d0 76 5a"
+    "9d 12 38 4d a4 60 a8 53 1b 4c 40 7e 04 f4 f3 50"
+    "70 9e b9 f0 8f 5b 22 0f fb 45 ab f6 b7 5d 15 79"
+    "fd 3f 1e b5 5f c7 5b 00 af 8b a3 b0 87 82 7f e9"
+    "ae 9f b4 f6 c5 fa 63 03 1f e5 82 85 2f e2 83 4f"
+    "9c 89 bf f5 3e 25 52 21 6b c7 c1 d4 a3 d5 dc 2b"
+    "a6 95 5c d9 b1 7d 13 63 e7 fe e8 ed 76 29 75 3f"
+    "f3 12 5e dd 48 52 1a e3 b9 b0 32 17 f4 49 6d 0d"
+    "8e de 57 ac bc 5b d4 de ae 74 a5 6f 86 67 1d e2";
+
+// PKCS#1 v1.5 Signature Example 15.12
+
+char* message_12 =
+    "7a f4 28 35 91 7a 88 d6 b3 c6 71 6b a2 f5 b0 d5 "
+    "b2 0b d4 e2 e6 e5 74 e0 6a f1 ee f7 c8 11 31 be "
+    "22 bf 81 28 b9 cb c6 ec 00 27 5b a8 02 94 a5 d1 "
+    "17 2d 08 24 a7 9e 8f dd 83 01 83 e4 c0 0b 96 78 "
+    "28 67 b1 22 7f ea 24 9a ad 32 ff c5 fe 00 7b c5 "
+    "1f 21 79 2f 72 8d ed a8 b5 70 8a a9 9c ab ab 20 "
+    "a4 aa 78 3e d8 6f 0f 27 b5 d5 63 f4 2e 07 15 8c "
+    "ea 72 d0 97 aa 68 87 ec 41 1d d0 12 91 2a 5e 03 "
+    "2b bf a6 78 50 71 44 bc c9 5f 39 b5 8b e7 bf d1 "
+    "75 9a db 9a 91 fa 1d 6d 82 26 a8 34 3a 8b 84 9d "
+    "ae 76 f7 b9 82 24 d5 9e 28 f7 81 f1 3e ce 60 5f "
+    "84 f6 c9 0b ae 5f 8c f3 78 81 6f 40 20 a7 dd a1 "
+    "be d9 0c 92 a2 36 34 d2 03 fa c3 fc d8 6d 68 d3 "
+    "18 2a 7d 9c ca be 7b 07 95 f5 c6 55 e9 ac c4 e3 "
+    "ec 18 51 40 d1 0c ef 05 34 64 ab 17 5c 83 bd 83 "
+    "93 5e 3d ab af 34 62 ee be 63 d1 5f 57 3d 26 9a ";
+
+char* signature_12 =
+    "4e 78 c5 90 2b 80 79 14 d1 2f a5 37 ae 68 71 c8"
+    "6d b8 02 1e 55 d1 ad b8 eb 0c cf 1b 8f 36 ab 7d"
+    "ad 1f 68 2e 94 7a 62 70 72 f0 3e 62 73 71 78 1d"
+    "33 22 1d 17 4a be 46 0d bd 88 56 0c 22 f6 90 11"
+    "6e 2f bb e6 e9 64 36 3a 3e 52 83 bb 5d 94 6e f1"
+    "c0 04 7e ba 03 8c 75 6c 40 be 79 23 05 58 09 b0"
+    "e9 f3 4a 03 a5 88 15 eb dd e7 67 93 1f 01 8f 6f"
+    "18 78 f2 ef 4f 47 dd 37 40 51 dd 48 68 5d ed 6e"
+    "fb 3e a8 02 1f 44 be 1d 7d 14 93 98 f9 8e a9 c0"
+    "8d 62 88 8e bb 56 19 2d 17 74 7b 6b 8e 17 09 54"
+    "31 f1 25 a8 a8 e9 96 2a a3 1c 28 52 64 e0 8f b2"
+    "1a ac 33 6c e6 c3 8a a3 75 e4 2b c9 2a b0 ab 91"
+    "03 84 31 e1 f9 2c 39 d2 af 5d ed 7e 43 bc 15 1e"
+    "6e be a4 c3 e2 58 3a f3 43 7e 82 c4 3c 5e 3b 5b"
+    "07 cf 03 59 68 3d 22 98 e3 59 48 ed 80 6c 06 3c"
+    "60 6e a1 78 15 0b 1e fc 15 85 69 34 c7 25 5c fe";
+
+// PKCS#1 v1.5 Signature Example 15.13
+
+char* message_13 =
+    "eb ae f3 f9 f2 3b df e5 fa 6b 8a f4 c2 08 c1 89 "
+    "f2 25 1b f3 2f 5f 13 7b 9d e4 40 63 78 68 6b 3f "
+    "07 21 f6 2d 24 cb 86 88 d6 fc 41 a2 7c ba e2 1d "
+    "30 e4 29 fe ac c7 11 19 41 c2 77 ";
+
+char* signature_13 =
+    "c4 8d be f5 07 11 4f 03 c9 5f af be b4 df 1b fa"
+    "88 e0 18 4a 33 cc 4f 8a 9a 10 35 ff 7f 82 2a 5e"
+    "38 cd a1 87 23 91 5f f0 78 24 44 29 e0 f6 08 1c"
+    "14 fd 83 33 1f a6 5c 6b a7 bb 9a 12 db f6 62 23"
+    "74 cd 0c a5 7d e3 77 4e 2b d7 ae 82 36 77 d0 61"
+    "d5 3a e9 c4 04 0d 2d a7 ef 70 14 f3 bb dc 95 a3"
+    "61 a4 38 55 c8 ce 9b 97 ec ab ce 17 4d 92 62 85"
+    "14 2b 53 4a 30 87 f9 f4 ef 74 51 1e c7 42 b0 d5"
+    "68 56 03 fa f4 03 b5 07 2b 98 5d f4 6a df 2d 25"
+    "29 a0 2d 40 71 1e 21 90 91 70 52 37 1b 79 b7 49"
+    "b8 3a bf 0a e2 94 86 c3 f2 f6 24 77 b2 bd 36 2b"
+    "03 9c 01 3c 0c 50 76 ef 52 0d bb 40 5f 42 ce e9"
+    "54 25 c3 73 a9 75 e1 cd d0 32 c4 96 22 c8 50 79"
+    "b0 9e 88 da b2 b1 39 69 ef 7a 72 39 73 78 10 40"
+    "45 9f 57 d5 01 36 38 48 3d e2 d9 1c b3 c4 90 da"
+    "81 c4 6d e6 cd 76 ea 8a 0c 8f 6f e3 31 71 2d 24";
+
+// PKCS#1 v1.5 Signature Example 15.14
+
+char* message_14 =
+    "c5 a2 71 12 78 76 1d fc dd 4f 0c 99 e6 f5 61 9d "
+    "6c 48 b5 d4 c1 a8 09 82 fa a6 b4 cf 1c f7 a6 0f "
+    "f3 27 ab ef 93 c8 01 42 9e fd e0 86 40 85 81 46 "
+    "10 56 ac c3 3f 3d 04 f5 ad a2 12 16 ca cd 5f d1 "
+    "f9 ed 83 20 3e 0e 2f e6 13 8e 3e ae 84 24 e5 91 "
+    "5a 08 3f 3f 7a b7 60 52 c8 be 55 ae 88 2d 6e c1 "
+    "48 2b 1e 45 c5 da e9 f4 10 15 40 53 27 02 2e c3 "
+    "2f 0e a2 42 97 63 b2 55 04 3b 19 58 ee 3c f6 d6 "
+    "39 83 59 6e b3 85 84 4f 85 28 cc 9a 98 65 83 5d "
+    "c5 11 3c 02 b8 0d 0f ca 68 aa 25 e7 2b ca ae b3 "
+    "cf 9d 79 d8 4f 98 4f d4 17 ";
+
+char* signature_14 =
+    "6b d5 25 7a a0 66 11 fb 46 60 08 7c b4 bc 4a 9e"
+    "44 91 59 d3 16 52 bd 98 08 44 da f3 b1 c7 b3 53"
+    "f8 e5 61 42 f7 ea 98 57 43 3b 18 57 3b 4d ee de"
+    "81 8a 93 b0 29 02 97 78 3f 1a 2f 23 cb c7 27 97"
+    "a6 72 53 7f 01 f6 24 84 cd 41 62 c3 21 4b 9a c6"
+    "28 22 4c 5d e0 1f 32 bb 9b 76 b2 73 54 f2 b1 51"
+    "d0 e8 c4 21 3e 46 15 ad 0b c7 1f 51 5e 30 0d 6a"
+    "64 c6 74 34 11 ff fd e8 e5 ff 19 0e 54 92 30 43"
+    "12 6e cf c4 c4 53 90 22 66 8f b6 75 f2 5c 07 e2"
+    "00 99 ee 31 5b 98 d6 af ec 4b 1a 9a 93 dc 33 49"
+    "6a 15 bd 6f de 16 63 a7 d4 9b 9f 1e 63 9d 38 66"
+    "4b 37 a0 10 b1 f3 5e 65 86 82 d9 cd 63 e5 7d e0"
+    "f1 5e 8b dd 09 65 58 f0 7e c0 ca a2 18 a8 c0 6f"
+    "47 88 45 39 40 28 7c 9d 34 b6 d4 0a 3f 09 bf 77"
+    "99 fe 98 ae 4e b4 9f 3f f4 1c 50 40 a5 0c ef c9"
+    "bd f2 39 4b 74 9c f1 64 48 0d f1 ab 68 80 27 3b";
+
+// PKCS#1 v1.5 Signature Example 15.15
+
+char* message_15 =
+    "9b f8 aa 25 3b 87 2e a7 7a 7e 23 47 6b e2 6b 23 "
+    "29 57 8c f6 ac 9e a2 80 5b 35 7f 6f c3 ad 13 0d "
+    "ba eb 3d 86 9a 13 cc e7 a8 08 bb bb c9 69 85 7e "
+    "03 94 5c 7b b6 1d f1 b5 c2 58 9b 8e 04 6c 2a 5d "
+    "7e 40 57 b1 a7 4f 24 c7 11 21 63 64 28 85 29 ec "
+    "95 70 f2 51 97 21 3b e1 f5 c2 e5 96 f8 bf 8b 2c "
+    "f3 cb 38 aa 56 ff e5 e3 1d f7 39 58 20 e9 4e cf "
+    "3b 11 89 a9 65 dc f9 a9 cb 42 98 d3 c8 8b 29 23 "
+    "c1 9f c6 bc 34 aa ce ca d4 e0 93 1a 7c 4e 5d 73 "
+    "dc 86 df a7 98 a8 47 6d 82 46 3e ef aa 90 a8 a9 "
+    "19 2a b0 8b 23 08 8d d5 8e 12 80 f7 d7 2e 45 48 "
+    "39 6b aa c1 12 25 2d d5 c5 34 6a db 20 04 a2 f7 "
+    "10 1c cc 89 9c c7 fa fa e8 bb e2 95 73 88 96 a5 "
+    "b2 01 22 85 01 4e f6 ";
+
+char* signature_15 =
+    "27 f7 f4 da 9b d6 10 10 6e f5 7d 32 38 3a 44 8a"
+    "8a 62 45 c8 3d c1 30 9c 6d 77 0d 35 7b a8 9e 73"
+    "f2 ad 08 32 06 2e b0 fe 0a c9 15 57 5b cd 6b 8b"
+    "ca db 4e 2b a6 fa 9d a7 3a 59 17 51 52 b2 d4 fe"
+    "72 b0 70 c9 b7 37 9e 50 00 0e 55 e6 c2 69 f6 65"
+    "8c 93 79 72 79 7d 3a dd 69 f1 30 e3 4b 85 bd ec"
+    "9f 3a 9b 39 22 02 d6 f3 e4 30 d0 9c ac a8 22 77"
+    "59 ab 82 5f 70 12 d2 ff 4b 5b 62 c8 50 4d ba d8"
+    "55 c0 5e dd 5c ab 5a 4c cc dc 67 f0 1d d6 51 7c"
+    "7d 41 c4 3e 2a 49 57 af f1 9d b6 f1 8b 17 85 9a"
+    "f0 bc 84 ab 67 14 6e c1 a4 a6 0a 17 d7 e0 5f 8b"
+    "4f 9c ed 6a d1 09 08 d8 d7 8f 7f c8 8b 76 ad c8"
+    "29 0f 87 da f2 a7 be 10 ae 40 85 21 39 5d 54 ed"
+    "25 56 fb 76 61 85 4a 73 0c e3 d8 2c 71 a8 d4 93"
+    "ec 49 a3 78 ac 8a 3c 74 43 9f 7c c5 55 ba 13 f8"
+    "59 07 08 90 ee 18 ff 65 8f a4 d7 41 96 9d 70 a5";
+
+// PKCS#1 v1.5 Signature Example 15.16
+
+char* message_16 =
+    "32 47 48 30 e2 20 37 54 c8 bf 06 81 dc 4f 84 2a "
+    "fe 36 09 30 37 86 16 c1 08 e8 33 65 6e 56 40 c8 "
+    "68 56 88 5b b0 5d 1e b9 43 8e fe de 67 92 63 de "
+    "07 cb 39 55 3f 6a 25 e0 06 b0 a5 23 11 a0 63 ca "
+    "08 82 66 d2 56 4f f6 49 0c 46 b5 60 98 18 54 8f "
+    "88 76 4d ad 34 a2 5e 3a 85 d5 75 02 3f 0b 9e 66 "
+    "50 48 a0 3c 35 05 79 a9 d3 24 46 c7 bb 96 cc 92 "
+    "e0 65 ab 94 d3 c8 95 2e 8d f6 8e f0 d9 fa 45 6b "
+    "3a 06 bb 80 e3 bb c4 b2 8e 6a 94 b6 d0 ff 76 96 "
+    "a6 4e fe 05 e7 35 fe a0 25 d7 bd bc 41 39 f3 a3 "
+    "b5 46 07 5c ba 7e fa 94 73 74 d3 f0 ac 80 a6 8d "
+    "76 5f 5d f6 21 0b ca 06 9a 2d 88 64 7a f7 ea 04 "
+    "2d ac 69 0c b5 73 78 ec 07 77 61 4f b8 b6 5f f4 "
+    "53 ca 6b 7d ce 60 98 45 1a 2f 8c 0d a9 bf ec f1 "
+    "fd f3 91 bb aa 4e 2a 91 ca 18 a1 12 1a 75 23 a2 "
+    "ab d4 25 14 f4 89 e8 ";
+
+char* signature_16 =
+    "69 17 43 72 57 c2 2c cb 54 03 29 0c 3d ee 82 d9"
+    "cf 75 50 b3 1b d3 1c 51 bd 57 bf d3 5d 45 2a b4"
+    "db 7c 4b e6 b2 e2 5a c9 a5 9a 1d 2a 7f eb 62 7f"
+    "0a fd 49 76 b3 00 3c c9 cf fd 88 96 50 5e c3 82"
+    "f2 65 10 4d 4c f8 c9 32 fa 9f e8 6e 00 87 07 95"
+    "99 12 38 9d a4 b2 d6 b3 69 b3 6a 5e 72 e2 9d 24"
+    "c9 a9 8c 9d 31 a3 ab 44 e6 43 e6 94 12 66 a4 7a"
+    "45 e3 44 6c e8 77 6a be 24 1a 8f 5f c6 42 3b 24"
+    "b1 ff 25 0d c2 c3 a8 17 23 53 56 10 77 e8 50 a7"
+    "69 b2 5f 03 25 da c8 89 65 a3 b9 b4 72 c4 94 e9"
+    "5f 71 9b 4e ac 33 2c aa 7a 65 c7 df e4 6d 9a a7"
+    "e6 e0 0f 52 5f 30 3d d6 3a b7 91 92 18 90 18 68"
+    "f9 33 7f 8c d2 6a af e6 f3 3b 7f b2 c9 88 10 af"
+    "19 f7 fc b2 82 ba 15 77 91 2c 1d 36 89 75 fd 5d"
+    "44 0b 86 e1 0c 19 97 15 fa 0b 6f 42 50 b5 33 73"
+    "2d 0b ef e1 54 51 50 fc 47 b8 76 de 09 b0 0a 94";
+
+// PKCS#1 v1.5 Signature Example 15.17
+
+char* message_17 =
+    "00 8e 59 50 5e af b5 50 aa e5 e8 45 58 4c eb b0 "
+    "0b 6d e1 73 3e 9f 95 d4 2c 88 2a 5b be b5 ce 1c "
+    "57 e1 19 e7 c0 d4 da ca 9f 1f f7 87 02 17 f7 cf "
+    "d8 a6 b3 73 97 7c ac 9c ab 8e 71 e4 20 ";
+
+char* signature_17 =
+    "92 25 03 b6 73 ee 5f 3e 69 1e 1c a8 5e 9f f4 17"
+    "3c f7 2b 05 ac 2c 13 1d a5 60 35 93 e3 bc 25 9c"
+    "94 c1 f7 d3 a0 6a 5b 98 91 bf 11 3f a3 9e 59 ff"
+    "7c 1e d6 46 5e 90 80 49 cb 89 e4 e1 25 cd 37 d2"
+    "ff d9 22 7a 41 b4 a0 a1 9c 0a 44 fb bf 3d e5 5b"
+    "ab 80 20 87 a3 bb 8d 4f f6 68 ee 6b bb 8a d8 9e"
+    "68 57 a7 9a 9c 72 78 19 90 df cf 92 cd 51 94 04"
+    "c9 50 f1 3d 11 43 c3 18 4f 1d 25 0c 90 e1 7a c6"
+    "ce 36 16 3b 98 95 62 7a d6 ff ec 14 22 44 1f 55"
+    "e4 49 9d ba 9b e8 95 46 ae 8b c6 3c ca 01 dd 08"
+    "46 3a e7 f1 fc e3 d8 93 99 69 38 77 8c 18 12 e6"
+    "74 ad 9c 30 9c 5a cc a3 fd e4 4e 7d d8 69 59 93"
+    "e9 c1 fa 87 ac da 99 ec e5 c8 49 9e 46 89 57 ad"
+    "66 35 9b f1 2a 51 ad be 78 d3 a2 13 b4 49 bf 0b"
+    "5f 8d 4d 49 6a cf 03 d3 03 3b 7c cd 19 6b c2 2f"
+    "68 fb 7b ef 4f 69 7c 5e a2 b3 50 62 f4 8a 36 dd";
+
+// PKCS#1 v1.5 Signature Example 15.18
+
+char* message_18 =
+    "6a bc 54 cf 8d 1d ff 1f 53 b1 7d 81 60 36 88 78 "
+    "a8 78 8c c6 d2 2f a5 c2 25 8c 88 e6 60 b0 9a 89 "
+    "33 f9 f2 c0 50 4d da dc 21 f6 e7 5e 0b 83 3b eb "
+    "55 52 29 de e6 56 b9 04 7b 92 f6 2e 76 b8 ff cc "
+    "60 da b0 6b 80 ";
+
+char* signature_18 =
+    "0b 6d af 42 f7 a8 62 14 7e 41 74 93 c2 c4 01 ef"
+    "ae 32 63 6a b4 cb d4 41 92 bb f5 f1 95 b5 0a e0"
+    "96 a4 75 a1 61 4f 0a 9f a8 f7 a0 26 cb 46 c6 50"
+    "6e 51 8e 33 d8 3e 56 47 7a 87 5a ca 8c 7e 71 4c"
+    "e1 bd bd 61 ef 5d 53 52 39 b3 3f 2b fd d6 17 71"
+    "ba b6 27 76 d7 81 71 a1 42 3c ea 87 31 f8 2e 60"
+    "76 6d 64 54 26 56 20 b1 5f 5c 5a 58 4f 55 f9 5b"
+    "80 2f e7 8c 57 4e d5 da cf c8 31 f3 cf 2b 05 02"
+    "c0 b2 98 f2 5c cf 11 f9 73 b3 1f 85 e4 74 42 19"
+    "85 f3 cf f7 02 df 39 46 ef 0a 66 05 68 21 11 b2"
+    "f5 5b 1f 8a b0 d2 ea 3a 68 3c 69 98 5e ad 93 ed"
+    "44 9e a4 8f 03 58 dd f7 08 02 cb 41 de 2f d8 3f"
+    "3c 80 80 82 d8 49 36 94 8e 0c 84 a1 31 b4 92 78"
+    "27 46 05 27 bb 5c d2 4b fa b7 b4 8e 07 1b 24 17"
+    "19 30 f9 97 63 27 2f 97 97 bc b7 6f 1d 24 81 57"
+    "55 58 fc f2 60 b1 f0 e5 54 eb b3 df 3c fc b9 58";
+
+// PKCS#1 v1.5 Signature Example 15.19
+
+char* message_19 =
+    "af 2d 78 15 2c f1 0e fe 01 d2 74 f2 17 b1 77 f6 "
+    "b0 1b 5e 74 9f 15 67 71 5d a3 24 85 9c d3 dd 88 "
+    "db 84 8e c7 9f 48 db ba 7b 6f 1d 33 11 1e f3 1b "
+    "64 89 9e 73 91 c2 bf fd 69 f4 90 25 cf 20 1f c5 "
+    "85 db d1 54 2c 1c 77 8a 2c e7 a7 ee 10 8a 30 9f "
+    "ec a2 6d 13 3a 5f fe dc 4e 86 9d cd 76 56 59 6a "
+    "c8 42 7e a3 ef 6e 3f d7 8f e9 9d 8d dc 71 d8 39 "
+    "f6 78 6e 0d a6 e7 86 bd 62 b3 a4 f1 9b 89 1a 56 "
+    "15 7a 55 4e c2 a2 b3 9e 25 a1 d7 c7 d3 73 21 c7 "
+    "a1 d9 46 cf 4f be 75 8d 92 76 f0 85 63 44 9d 67 "
+    "41 4a 2c 03 0f 42 51 cf e2 21 3d 04 a5 41 06 37 "
+    "87 ";
+
+char* signature_19 =
+    "20 9c 61 15 78 57 38 7b 71 e2 4b f3 dd 56 41 45"
+    "50 50 3b ec 18 0f f5 3b dd 9b ac 06 2a 2d 49 95"
+    "09 bf 99 12 81 b7 95 27 df 91 36 61 5b 7a 6d 9d"
+    "b3 a1 03 b5 35 e0 20 2a 2c ac a1 97 a7 b7 4e 53"
+    "56 f3 dd 59 5b 49 ac fd 9d 30 04 9a 98 ca 88 f6"
+    "25 bc a1 d5 f2 2a 39 2d 8a 74 9e fb 6e ed 9b 78"
+    "21 d3 11 0a c0 d2 44 19 9e cb 4a a3 d7 35 a8 3a"
+    "2e 88 93 c6 bf 85 81 38 3c ca ee 83 46 35 b7 fa"
+    "1f af fa 45 b1 3d 15 c1 da 33 af 71 e8 93 03 d6"
+    "80 90 ff 62 ee 61 5f df 5a 84 d1 20 71 1d a5 3c"
+    "28 89 19 8a b3 83 17 a9 73 4a b2 7d 67 92 4c ea"
+    "74 15 6f f9 9b ef 98 76 bb 5c 33 9e 93 74 52 83"
+    "e1 b3 4e 07 22 26 b8 80 45 e0 17 e9 f0 5b 2a 8c"
+    "41 67 40 25 8e 22 3b 26 90 02 74 91 73 22 73 f3"
+    "22 9d 9e f2 b1 b3 80 7e 32 10 18 92 0a d3 e5 3d"
+    "ae 47 e6 d9 39 5c 18 4b 93 a3 74 c6 71 fa a2 ce";
+
+// PKCS#1 v1.5 Signature Example 15.20
+
+char* message_20 =
+    "40 ee 99 24 58 d6 f6 14 86 d2 56 76 a9 6d d2 cb "
+    "93 a3 7f 04 b1 78 48 2f 2b 18 6c f8 82 15 27 0d "
+    "ba 29 d7 86 d7 74 b0 c5 e7 8c 7f 6e 56 a9 56 e7 "
+    "f7 39 50 a2 b0 c0 c1 0a 08 db cd 67 e5 b2 10 bb "
+    "21 c5 8e 27 67 d4 4f 7d d4 01 4e 39 66 14 3b f7 "
+    "e3 d6 6f f0 c0 9b e4 c5 5f 93 b3 99 94 b8 51 8d "
+    "9c 1d 76 d5 b4 73 74 de a0 8f 15 7d 57 d7 06 34 "
+    "97 8f 38 56 e0 e5 b4 81 af bb db 5a 3a c4 8d 48 "
+    "4b e9 2c 93 de 22 91 78 35 4c 2d e5 26 e9 c6 5a "
+    "31 ed e1 ef 68 cb 63 98 d7 91 16 84 fe c0 ba bc "
+    "3a 78 1a 66 66 07 83 50 69 74 d0 e1 48 25 10 1c "
+    "3b fa ea ";
+
+char* signature_20 =
+    "92 75 02 b8 24 af c4 25 13 ca 65 70 de 33 8b 8a"
+    "64 c3 a8 5e b8 28 d3 19 36 24 f2 7e 8b 10 29 c5"
+    "5c 11 9c 97 33 b1 8f 58 49 b3 50 09 18 bc c0 05"
+    "51 d9 a8 fd f5 3a 97 74 9f a8 dc 48 0d 6f e9 74"
+    "2a 58 71 f9 73 92 65 28 97 2a 1a f4 9e 39 25 b0"
+    "ad f1 4a 84 27 19 b4 a5 a2 d8 9f a9 c0 b6 60 5d"
+    "21 2b ed 1e 67 23 b9 34 06 ad 30 e8 68 29 a5 c7"
+    "19 b8 90 b3 89 30 6d c5 50 64 86 ee 2f 36 a8 df"
+    "e0 a9 6a f6 78 c9 cb d6 af f3 97 ca 20 0e 3e dc"
+    "1e 36 bd 2f 08 b3 1d 54 0c 0c b2 82 a9 55 9e 4a"
+    "dd 4f c9 e6 49 2e ed 0c cb d3 a6 98 2e 5f aa 2d"
+    "dd 17 be 47 41 7c 80 b4 e5 45 2d 31 f7 24 01 a0"
+    "42 32 51 09 54 4d 95 4c 01 93 90 79 d4 09 a5 c3"
+    "78 d7 51 2d fc 2d 2a 71 ef cc 34 32 a7 65 d1 c6"
+    "a5 2c fc e8 99 cd 79 b1 5b 4f c3 72 36 41 ef 6b"
+    "d0 0a cc 10 40 7e 5d f5 8d d1 c3 c5 c5 59 a5 06";
+
+
+unsigned char* parsehex(char* str, int* len) {
+    // result can't be longer than input
+    unsigned char* result = malloc(strlen(str));
+
+    unsigned char* p = result;
+    *len = 0;
+
+    while (*str) {
+        int b;
+
+        while (isspace(*str)) str++;
+
+        switch (*str) {
+            case '0': case '1': case '2': case '3': case '4':
+            case '5': case '6': case '7': case '8': case '9':
+                b = (*str - '0') << 4; break;
+            case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
+                b = (*str - 'a' + 10) << 4; break;
+            case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+                b = (*str - 'A' + 10) << 4; break;
+            case '\0':
+                return result;
+            default:
+                return NULL;
+        }
+        str++;
+
+        while (isspace(*str)) str++;
+
+        switch (*str) {
+            case '0': case '1': case '2': case '3': case '4':
+            case '5': case '6': case '7': case '8': case '9':
+                b |= *str - '0'; break;
+            case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
+                b |= *str - 'a' + 10; break;
+            case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+                b |= *str - 'A' + 10; break;
+            default:
+                return NULL;
+        }
+        str++;
+
+        *p++ = b;
+        ++*len;
+    }
+
+    return result;
+}
+
+
+int main(int arg, char** argv) {
+
+    unsigned char hash[SHA_DIGEST_SIZE];
+
+    unsigned char* message;
+    int mlen;
+    unsigned char* signature;
+    int slen;
+
+#define TEST_MESSAGE(n) do {\
+    message = parsehex(message_##n, &mlen); \
+    SHA_hash(message, mlen, hash); \
+    signature = parsehex(signature_##n, &slen); \
+    int result = RSA_verify(&key_15, signature, slen, hash, sizeof(hash)); \
+    printf("message %d: %s\n", n, result ? "verified" : "not verified"); \
+    success = success && result; \
+    } while(0)
+
+    int success = 1;
+
+    TEST_MESSAGE(1);
+    TEST_MESSAGE(2);
+    TEST_MESSAGE(3);
+    TEST_MESSAGE(4);
+    TEST_MESSAGE(5);
+    TEST_MESSAGE(6);
+    TEST_MESSAGE(7);
+    TEST_MESSAGE(8);
+    TEST_MESSAGE(9);
+    TEST_MESSAGE(10);
+    TEST_MESSAGE(11);
+    TEST_MESSAGE(12);
+    TEST_MESSAGE(13);
+    TEST_MESSAGE(14);
+    TEST_MESSAGE(15);
+    TEST_MESSAGE(16);
+    TEST_MESSAGE(17);
+    TEST_MESSAGE(18);
+    TEST_MESSAGE(19);
+    TEST_MESSAGE(20);
+
+    printf("\n%s\n\n", success ? "PASS" : "FAIL");
+
+    return !success;
+}
diff --git a/libmincrypt/tools/DumpPublicKey.java b/libmincrypt/tools/DumpPublicKey.java
index 12b4f56..7189116 100644
--- a/libmincrypt/tools/DumpPublicKey.java
+++ b/libmincrypt/tools/DumpPublicKey.java
@@ -19,7 +19,7 @@
 import java.io.FileInputStream;
 import java.math.BigInteger;
 import java.security.cert.CertificateFactory;
-import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
 import java.security.KeyStore;
 import java.security.Key;
 import java.security.PublicKey;
@@ -34,20 +34,22 @@
     /**
      * @param key to perform sanity checks on
      * @return version number of key.  Supported versions are:
-     *     1: 2048-bit key with e=3
-     *     2: 2048-bit key with e=65537
+     *     1: 2048-bit RSA key with e=3 and SHA-1 hash
+     *     2: 2048-bit RSA key with e=65537 and SHA-1 hash
+     *     3: 2048-bit RSA key with e=3 and SHA-256 hash
+     *     4: 2048-bit RSA key with e=65537 and SHA-256 hash
      * @throws Exception if the key has the wrong size or public exponent
 
      */
-    static int check(RSAPublicKey key) throws Exception {
+    static int check(RSAPublicKey key, boolean useSHA256) throws Exception {
         BigInteger pubexp = key.getPublicExponent();
         BigInteger modulus = key.getModulus();
         int version;
 
         if (pubexp.equals(BigInteger.valueOf(3))) {
-            version = 1;
+            version = useSHA256 ? 3 : 1;
         } else if (pubexp.equals(BigInteger.valueOf(65537))) {
-            version = 2;
+            version = useSHA256 ? 4 : 2;
         } else {
             throw new Exception("Public exponent should be 3 or 65537 but is " +
                                 pubexp.toString(10) + ".");
@@ -67,8 +69,8 @@
      *    version 1 key, the string will be a C initializer; this is
      *    not true for newer key versions.
      */
-    static String print(RSAPublicKey key) throws Exception {
-        int version = check(key);
+    static String print(RSAPublicKey key, boolean useSHA256) throws Exception {
+        int version = check(key, useSHA256);
 
         BigInteger N = key.getModulus();
 
@@ -135,10 +137,27 @@
             for (int i = 0; i < args.length; i++) {
                 FileInputStream input = new FileInputStream(args[i]);
                 CertificateFactory cf = CertificateFactory.getInstance("X.509");
-                Certificate cert = cf.generateCertificate(input);
+                X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
+
+                boolean useSHA256 = false;
+                String sigAlg = cert.getSigAlgName();
+                if ("SHA1withRSA".equals(sigAlg) || "MD5withRSA".equals(sigAlg)) {
+                    // SignApk has historically accepted "MD5withRSA"
+                    // certificates, but treated them as "SHA1withRSA"
+                    // anyway.  Continue to do so for backwards
+                    // compatibility.
+                  useSHA256 = false;
+                } else if ("SHA256withRSA".equals(sigAlg)) {
+                  useSHA256 = true;
+                } else {
+                  System.err.println(args[i] + ": unsupported signature algorithm \"" +
+                                     sigAlg + "\"");
+                  System.exit(1);
+                }
+
                 RSAPublicKey key = (RSAPublicKey) (cert.getPublicKey());
-                check(key);
-                System.out.print(print(key));
+                check(key, useSHA256);
+                System.out.print(print(key, useSHA256));
                 System.out.println(i < args.length - 1 ? "," : "");
             }
         } catch (Exception e) {
diff --git a/reboot/Android.mk b/reboot/Android.mk
new file mode 100644
index 0000000..4db0c1e
--- /dev/null
+++ b/reboot/Android.mk
@@ -0,0 +1,12 @@
+# Copyright 2013 The Android Open Source Project
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= reboot.c
+
+LOCAL_SHARED_LIBRARIES:= libcutils
+
+LOCAL_MODULE:= reboot
+
+include $(BUILD_EXECUTABLE)
diff --git a/reboot/reboot.c b/reboot/reboot.c
new file mode 100644
index 0000000..0e5170d
--- /dev/null
+++ b/reboot/reboot.c
@@ -0,0 +1,73 @@
+/*
+ * 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 <stdio.h>
+#include <stdlib.h>
+#include <cutils/properties.h>
+#include <cutils/android_reboot.h>
+#include <unistd.h>
+
+int main(int argc, char *argv[])
+{
+    int ret;
+    size_t prop_len;
+    char property_val[PROPERTY_VALUE_MAX];
+    const char *cmd = "reboot";
+    char *optarg = "";
+
+    opterr = 0;
+    do {
+        int c;
+
+        c = getopt(argc, argv, "p");
+
+        if (c == EOF) {
+            break;
+        }
+
+        switch (c) {
+        case 'p':
+            cmd = "shutdown";
+            break;
+        case '?':
+            fprintf(stderr, "usage: %s [-p] [rebootcommand]\n", argv[0]);
+            exit(EXIT_FAILURE);
+        }
+    } while (1);
+
+    if(argc > optind + 1) {
+        fprintf(stderr, "%s: too many arguments\n", argv[0]);
+        exit(EXIT_FAILURE);
+    }
+
+    if (argc > optind)
+        optarg = argv[optind];
+
+    prop_len = snprintf(property_val, sizeof(property_val), "%s,%s", cmd, optarg);
+    if (prop_len >= sizeof(property_val)) {
+        fprintf(stderr, "reboot command too long: %s\n", optarg);
+        exit(EXIT_FAILURE);
+    }
+
+    ret = property_set(ANDROID_RB_PROPERTY, property_val);
+    if(ret < 0) {
+        perror("reboot");
+        exit(EXIT_FAILURE);
+    }
+    fprintf(stderr, "Done\n");
+    return 0;
+}
diff --git a/rootdir/init.rc b/rootdir/init.rc
index aec9e63..09017af 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -370,9 +370,6 @@
     setprop net.tcp.buffersize.gprs    4092,8760,11680,4096,8760,11680
     setprop net.tcp.buffersize.evdo    4094,87380,262144,4096,16384,262144
 
-# Set this property so surfaceflinger is not started by system_init
-    setprop system_init.startsurfaceflinger 0
-
     class_start core
     class_start main
 
@@ -402,6 +399,9 @@
     class_reset late_start
     class_reset main
 
+on property:sys.powerctl=*
+    powerctl ${sys.powerctl}
+
 ## Daemon processes to be run by init.
 ##
 service ueventd /sbin/ueventd
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index c764690..565ec2a 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -16,7 +16,6 @@
 	rm \
 	mkdir \
 	rmdir \
-	reboot \
 	getevent \
 	sendevent \
 	date \
diff --git a/toolbox/mount.c b/toolbox/mount.c
index bcda2a2..66ae8b1 100644
--- a/toolbox/mount.c
+++ b/toolbox/mount.c
@@ -138,6 +138,24 @@
 	return rwflag;
 }
 
+/*
+ * Mark the given block device as read-write, using the BLKROSET ioctl.
+ */
+static void fs_set_blk_rw(const char *blockdev)
+{
+    int fd;
+    int OFF = 0;
+
+    fd = open(blockdev, O_RDONLY);
+    if (fd < 0) {
+        // should never happen
+        return;
+    }
+
+    ioctl(fd, BLKROSET, &OFF);
+    close(fd);
+}
+
 static char *progname;
 
 static struct extra_opts extra;
@@ -179,6 +197,10 @@
         dev = loopdev;
     }
 
+    if ((rwflag & MS_RDONLY) == 0) {
+        fs_set_blk_rw(dev);
+    }
+
 	while ((s = strsep(&type, ",")) != NULL) {
 retry:
 		if (mount(dev, dir, s, rwflag, data) == -1) {
diff --git a/toolbox/reboot.c b/toolbox/reboot.c
deleted file mode 100644
index f8546de..0000000
--- a/toolbox/reboot.c
+++ /dev/null
@@ -1,58 +0,0 @@
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <cutils/android_reboot.h>
-#include <unistd.h>
-
-int reboot_main(int argc, char *argv[])
-{
-    int ret;
-    int nosync = 0;
-    int poweroff = 0;
-    int flags = 0;
-
-    opterr = 0;
-    do {
-        int c;
-
-        c = getopt(argc, argv, "np");
-        
-        if (c == EOF) {
-            break;
-        }
-        
-        switch (c) {
-        case 'n':
-            nosync = 1;
-            break;
-        case 'p':
-            poweroff = 1;
-            break;
-        case '?':
-            fprintf(stderr, "usage: %s [-n] [-p] [rebootcommand]\n", argv[0]);
-            exit(EXIT_FAILURE);
-        }
-    } while (1);
-
-    if(argc > optind + 1) {
-        fprintf(stderr, "%s: too many arguments\n", argv[0]);
-        exit(EXIT_FAILURE);
-    }
-
-    if(nosync)
-        /* also set NO_REMOUNT_RO as remount ro includes an implicit sync */
-        flags = ANDROID_RB_FLAG_NO_SYNC | ANDROID_RB_FLAG_NO_REMOUNT_RO;
-
-    if(poweroff)
-        ret = android_reboot(ANDROID_RB_POWEROFF, flags, 0);
-    else if(argc > optind)
-        ret = android_reboot(ANDROID_RB_RESTART2, flags, argv[optind]);
-    else
-        ret = android_reboot(ANDROID_RB_RESTART, flags, 0);
-    if(ret < 0) {
-        perror("reboot");
-        exit(EXIT_FAILURE);
-    }
-    fprintf(stderr, "reboot returned\n");
-    return 0;
-}
diff --git a/toolbox/rm.c b/toolbox/rm.c
index 3a24bec..127cbc4 100644
--- a/toolbox/rm.c
+++ b/toolbox/rm.c
@@ -103,8 +103,8 @@
             ret = unlink_recursive(argv[i], flags);
         } else {
             ret = unlink(argv[i]);
-            if (errno == ENOENT && (flags & OPT_FORCE)) {
-                return 0;
+            if (ret < 0 && errno == ENOENT && (flags & OPT_FORCE)) {
+                continue;
             }
         }