Merge "Fix incorrect path name check."
diff --git a/adb/Android.mk b/adb/Android.mk
index 3828ed3..3cadee3 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -63,7 +63,6 @@
 	file_sync_client.c \
 	$(EXTRA_SRCS) \
 	$(USB_SRCS) \
-	usb_vendors.c
 
 LOCAL_C_INCLUDES += external/openssl/include
 
@@ -157,7 +156,6 @@
 	file_sync_client.c \
 	get_my_path_linux.c \
 	usb_linux.c \
-	usb_vendors.c \
 	fdevent.c
 
 LOCAL_CFLAGS := \
diff --git a/adb/adb.c b/adb/adb.c
index 68a6026..1834472 100644
--- a/adb/adb.c
+++ b/adb/adb.c
@@ -41,8 +41,6 @@
 #include <sys/prctl.h>
 #include <getopt.h>
 #include <selinux/selinux.h>
-#else
-#include "usb_vendors.h"
 #endif
 
 #if ADB_TRACE
@@ -1320,7 +1318,6 @@
 #ifdef WORKAROUND_BUG6558362
     if(is_daemon) adb_set_affinity();
 #endif
-    usb_vendors_init();
     usb_init();
     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
     adb_auth_init();
@@ -1351,14 +1348,13 @@
     ** AID_LOG to read system logs (adb logcat)
     ** AID_INPUT to diagnose input issues (getevent)
     ** AID_INET to diagnose network issues (netcfg, ping)
-    ** AID_GRAPHICS to access the frame buffer
     ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
     ** AID_SDCARD_R to allow reading from the SD card
     ** AID_SDCARD_RW to allow writing to the SD card
     ** AID_NET_BW_STATS to read out qtaguid statistics
     */
-    gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
-                       AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
+    gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_NET_BT,
+                       AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
                        AID_NET_BW_STATS };
     if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
         exit(1);
diff --git a/adb/adb.h b/adb/adb.h
index 4f06800..6f5f997 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -375,7 +375,6 @@
 int is_adb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol);
 #endif
 
-unsigned host_to_le32(unsigned n);
 int adb_commandline(int argc, char **argv);
 
 int connection_state(atransport *t);
diff --git a/adb/file_sync_service.h b/adb/file_sync_service.h
index 5dd2e80..c3c8574 100644
--- a/adb/file_sync_service.h
+++ b/adb/file_sync_service.h
@@ -17,22 +17,10 @@
 #ifndef _FILE_SYNC_SERVICE_H_
 #define _FILE_SYNC_SERVICE_H_
 
-#ifdef HAVE_BIG_ENDIAN
-static inline unsigned __swap_uint32(unsigned x) 
-{
-    return (((x) & 0xFF000000) >> 24)
-        | (((x) & 0x00FF0000) >> 8)
-        | (((x) & 0x0000FF00) << 8)
-        | (((x) & 0x000000FF) << 24);
-}
-#define htoll(x) __swap_uint32(x)
-#define ltohl(x) __swap_uint32(x)
-#define MKID(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((a) << 24))
-#else
 #define htoll(x) (x)
 #define ltohl(x) (x)
+
 #define MKID(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
-#endif
 
 #define ID_STAT MKID('S','T','A','T')
 #define ID_LIST MKID('L','I','S','T')
diff --git a/adb/get_my_path_darwin.c b/adb/get_my_path_darwin.c
index 9141b57..ff1396c 100644
--- a/adb/get_my_path_darwin.c
+++ b/adb/get_my_path_darwin.c
@@ -20,11 +20,11 @@
 void get_my_path(char *s, size_t maxLen)
 {
     CFBundleRef mainBundle = CFBundleGetMainBundle();
-    CFURLRef bundleURL = CFBundleCopyBundleURL(mainBundle);
-    CFStringRef bundlePathString = CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle);
-    CFRelease(bundleURL);
+    CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle);
+    CFStringRef executablePathString = CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle);
+    CFRelease(executableURL);
 
-    CFStringGetCString(bundlePathString, s, maxLen, kCFStringEncodingASCII);
-    CFRelease(bundlePathString);
+    CFStringGetFileSystemRepresentation(executablePathString, s, maxLen);
+    CFRelease(executablePathString);
 }
 
diff --git a/adb/transport_local.c b/adb/transport_local.c
index 948cc15..6c4e220 100644
--- a/adb/transport_local.c
+++ b/adb/transport_local.c
@@ -28,21 +28,6 @@
 #define  TRACE_TAG  TRACE_TRANSPORT
 #include "adb.h"
 
-#ifdef HAVE_BIG_ENDIAN
-#define H4(x)	(((x) & 0xFF000000) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | (((x) & 0x000000FF) << 24)
-static inline void fix_endians(apacket *p)
-{
-    p->msg.command     = H4(p->msg.command);
-    p->msg.arg0        = H4(p->msg.arg0);
-    p->msg.arg1        = H4(p->msg.arg1);
-    p->msg.data_length = H4(p->msg.data_length);
-    p->msg.data_check  = H4(p->msg.data_check);
-    p->msg.magic       = H4(p->msg.magic);
-}
-#else
-#define fix_endians(p) do {} while (0)
-#endif
-
 #if ADB_HOST
 /* we keep a list of opened transports. The atransport struct knows to which
  * local transport it is connected. The list is used to detect when we're
@@ -62,12 +47,6 @@
         return -1;
     }
 
-    fix_endians(p);
-
-#if 0 && defined HAVE_BIG_ENDIAN
-    D("read remote packet: %04x arg0=%0x arg1=%0x data_length=%0x data_check=%0x magic=%0x\n",
-      p->msg.command, p->msg.arg0, p->msg.arg1, p->msg.data_length, p->msg.data_check, p->msg.magic);
-#endif
     if(check_header(p)) {
         D("bad header: terminated (data)\n");
         return -1;
@@ -90,12 +69,6 @@
 {
     int   length = p->msg.data_length;
 
-    fix_endians(p);
-
-#if 0 && defined HAVE_BIG_ENDIAN
-    D("write remote packet: %04x arg0=%0x arg1=%0x data_length=%0x data_check=%0x magic=%0x\n",
-      p->msg.command, p->msg.arg0, p->msg.arg1, p->msg.data_length, p->msg.data_check, p->msg.magic);
-#endif
     if(writex(t->sfd, &p->msg, sizeof(amessage) + length)) {
         D("remote local: write terminated\n");
         return -1;
diff --git a/adb/transport_usb.c b/adb/transport_usb.c
index ee6b637..1138ddd 100644
--- a/adb/transport_usb.c
+++ b/adb/transport_usb.c
@@ -23,33 +23,6 @@
 #define  TRACE_TAG  TRACE_TRANSPORT
 #include "adb.h"
 
-#if ADB_HOST
-#include "usb_vendors.h"
-#endif
-
-#ifdef HAVE_BIG_ENDIAN
-#define H4(x)	(((x) & 0xFF000000) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | (((x) & 0x000000FF) << 24)
-static inline void fix_endians(apacket *p)
-{
-    p->msg.command     = H4(p->msg.command);
-    p->msg.arg0        = H4(p->msg.arg0);
-    p->msg.arg1        = H4(p->msg.arg1);
-    p->msg.data_length = H4(p->msg.data_length);
-    p->msg.data_check  = H4(p->msg.data_check);
-    p->msg.magic       = H4(p->msg.magic);
-}
-unsigned host_to_le32(unsigned n)
-{
-    return H4(n);
-}
-#else
-#define fix_endians(p) do {} while (0)
-unsigned host_to_le32(unsigned n)
-{
-    return n;
-}
-#endif
-
 static int remote_read(apacket *p, atransport *t)
 {
     if(usb_read(t->usb, &p->msg, sizeof(amessage))){
@@ -57,8 +30,6 @@
         return -1;
     }
 
-    fix_endians(p);
-
     if(check_header(p)) {
         D("remote usb: check_header failed\n");
         return -1;
@@ -83,8 +54,6 @@
 {
     unsigned size = p->msg.data_length;
 
-    fix_endians(p);
-
     if(usb_write(t->usb, &p->msg, sizeof(amessage))) {
         D("remote usb: 1 - write terminated\n");
         return -1;
@@ -131,18 +100,6 @@
 #if ADB_HOST
 int is_adb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol)
 {
-    unsigned i;
-    for (i = 0; i < vendorIdCount; i++) {
-        if (vid == vendorIds[i]) {
-            if (usb_class == ADB_CLASS && usb_subclass == ADB_SUBCLASS &&
-                    usb_protocol == ADB_PROTOCOL) {
-                return 1;
-            }
-
-            return 0;
-        }
-    }
-
-    return 0;
+    return (usb_class == ADB_CLASS && usb_subclass == ADB_SUBCLASS && usb_protocol == ADB_PROTOCOL);
 }
 #endif
diff --git a/adb/usb_osx.c b/adb/usb_osx.c
index ee893f5..ba157f1 100644
--- a/adb/usb_osx.c
+++ b/adb/usb_osx.c
@@ -28,12 +28,11 @@
 
 #define TRACE_TAG   TRACE_USB
 #include "adb.h"
-#include "usb_vendors.h"
 
 #define  DBG   D
 
 static IONotificationPortRef    notificationPort = 0;
-static io_iterator_t*           notificationIterators;
+static io_iterator_t            notificationIterator;
 
 struct usb_handle
 {
@@ -61,8 +60,6 @@
 {
     CFMutableDictionaryRef  matchingDict;
     CFRunLoopSourceRef      runLoopSource;
-    SInt32                  vendor, if_subclass, if_protocol;
-    unsigned                i;
 
     //* To set up asynchronous notifications, create a notification port and
     //* add its run loop event source to the program's run loop
@@ -70,47 +67,33 @@
     runLoopSource = IONotificationPortGetRunLoopSource(notificationPort);
     CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
 
-    memset(notificationIterators, 0, sizeof(notificationIterators));
+    //* Create our matching dictionary to find the Android device's
+    //* adb interface
+    //* IOServiceAddMatchingNotification consumes the reference, so we do
+    //* not need to release this
+    matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
 
-    //* loop through all supported vendors
-    for (i = 0; i < vendorIdCount; i++) {
-        //* Create our matching dictionary to find the Android device's
-        //* adb interface
-        //* IOServiceAddMatchingNotification consumes the reference, so we do
-        //* not need to release this
-        matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
-
-        if (!matchingDict) {
-            DBG("ERR: Couldn't create USB matching dictionary.\n");
-            return -1;
-        }
-
-        //* Match based on vendor id, interface subclass and protocol
-        vendor = vendorIds[i];
-        if_subclass = ADB_SUBCLASS;
-        if_protocol = ADB_PROTOCOL;
-        CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID),
-                             CFNumberCreate(kCFAllocatorDefault,
-                                            kCFNumberSInt32Type, &vendor));
-        CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceSubClass),
-                             CFNumberCreate(kCFAllocatorDefault,
-                                            kCFNumberSInt32Type, &if_subclass));
-        CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceProtocol),
-                             CFNumberCreate(kCFAllocatorDefault,
-                                            kCFNumberSInt32Type, &if_protocol));
-        IOServiceAddMatchingNotification(
-                notificationPort,
-                kIOFirstMatchNotification,
-                matchingDict,
-                AndroidInterfaceAdded,
-                NULL,
-                &notificationIterators[i]);
-
-        //* Iterate over set of matching interfaces to access already-present
-        //* devices and to arm the notification
-        AndroidInterfaceAdded(NULL, notificationIterators[i]);
+    if (!matchingDict) {
+        DBG("ERR: Couldn't create USB matching dictionary.\n");
+        return -1;
     }
 
+    //* We have to get notifications for all potential candidates and test them
+    //* at connection time because the matching rules don't allow for a
+    //* USB interface class of 0xff for class+subclass+protocol matches
+    //* See https://developer.apple.com/library/mac/qa/qa1076/_index.html
+    IOServiceAddMatchingNotification(
+            notificationPort,
+            kIOFirstMatchNotification,
+            matchingDict,
+            AndroidInterfaceAdded,
+            NULL,
+            &notificationIterator);
+
+    //* Iterate over set of matching interfaces to access already-present
+    //* devices and to arm the notification
+    AndroidInterfaceAdded(NULL, notificationIterator);
+
     return 0;
 }
 
@@ -126,6 +109,7 @@
     HRESULT                  result;
     SInt32                   score;
     UInt32                   locationId;
+    UInt8                    class, subclass, protocol;
     UInt16                   vendor;
     UInt16                   product;
     UInt8                    serialIndex;
@@ -156,6 +140,16 @@
             continue;
         }
 
+        kr = (*iface)->GetInterfaceClass(iface, &class);
+        kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
+        kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
+        if(class != ADB_CLASS || subclass != ADB_SUBCLASS || protocol != ADB_PROTOCOL) {
+            // Ignore non-ADB devices.
+            DBG("Ignoring interface with incorrect class/subclass/protocol - %d, %d, %d\n", class, subclass, protocol);
+            (*iface)->Release(iface);
+            continue;
+        }
+
         //* this gets us an ioservice, with which we will find the actual
         //* device; after getting a plugin, and querying the interface, of
         //* course.
@@ -192,7 +186,6 @@
 
         //* Now after all that, we actually have a ref to the device and
         //* the interface that matched our criteria
-
         kr = (*dev)->GetDeviceVendor(dev, &vendor);
         kr = (*dev)->GetDeviceProduct(dev, &product);
         kr = (*dev)->GetLocationID(dev, &locationId);
@@ -385,8 +378,6 @@
 
 void* RunLoopThread(void* unused)
 {
-    unsigned i;
-
     InitUSB();
 
     currentRunLoop = CFRunLoopGetCurrent();
@@ -399,9 +390,7 @@
     CFRunLoopRun();
     currentRunLoop = 0;
 
-    for (i = 0; i < vendorIdCount; i++) {
-        IOObjectRelease(notificationIterators[i]);
-    }
+    IOObjectRelease(notificationIterator);
     IONotificationPortDestroy(notificationPort);
 
     DBG("RunLoopThread done\n");
@@ -416,9 +405,6 @@
     {
         adb_thread_t    tid;
 
-        notificationIterators = (io_iterator_t*)malloc(
-            vendorIdCount * sizeof(io_iterator_t));
-
         adb_mutex_init(&start_lock, NULL);
         adb_cond_init(&start_cond, NULL);
 
@@ -443,11 +429,6 @@
     close_usb_devices();
     if (currentRunLoop)
         CFRunLoopStop(currentRunLoop);
-
-    if (notificationIterators != NULL) {
-        free(notificationIterators);
-        notificationIterators = NULL;
-    }
 }
 
 int usb_write(usb_handle *handle, const void *buf, int len)
diff --git a/adb/usb_vendors.c b/adb/usb_vendors.c
deleted file mode 100755
index 3b08907..0000000
--- a/adb/usb_vendors.c
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "usb_vendors.h"
-
-#include <stdio.h>
-
-#ifdef _WIN32
-#  define WIN32_LEAN_AND_MEAN
-#  include "windows.h"
-#  include "shlobj.h"
-#else
-#  include <unistd.h>
-#  include <sys/stat.h>
-#endif
-
-#include "sysdeps.h"
-#include "adb.h"
-
-#define ANDROID_PATH            ".android"
-#define ANDROID_ADB_INI         "adb_usb.ini"
-
-#define TRACE_TAG               TRACE_USB
-
-/* Keep the list below sorted alphabetically by #define name */
-// Acer's USB Vendor ID
-#define VENDOR_ID_ACER          0x0502
-// Alco's  USB Vendor ID
-#define VENDOR_ID_ALCO          0x1914
-// Allwinner's USB Vendor ID
-#define VENDOR_ID_ALLWINNER     0x1F3A
-// Amlogic's USB Vendor ID
-#define VENDOR_ID_AMLOGIC       0x1b8e
-// AnyDATA's USB Vendor ID
-#define VENDOR_ID_ANYDATA       0x16D5
-// Archos's USB Vendor ID
-#define VENDOR_ID_ARCHOS        0x0E79
-// Asus's USB Vendor ID
-#define VENDOR_ID_ASUS          0x0b05
-// BYD's USB Vendor ID
-#define VENDOR_ID_BYD           0x1D91
-// Compal's USB Vendor ID
-#define VENDOR_ID_COMPAL        0x04B7
-// Compalcomm's USB Vendor ID
-#define VENDOR_ID_COMPALCOMM    0x1219
-// Dell's USB Vendor ID
-#define VENDOR_ID_DELL          0x413c
-// ECS's USB Vendor ID
-#define VENDOR_ID_ECS           0x03fc
-// EMERGING_TECH's USB Vendor ID
-#define VENDOR_ID_EMERGING_TECH 0x297F
-// Emerson's USB Vendor ID
-#define VENDOR_ID_EMERSON       0x2207
-// Foxconn's USB Vendor ID
-#define VENDOR_ID_FOXCONN       0x0489
-// Fujitsu's USB Vendor ID
-#define VENDOR_ID_FUJITSU       0x04C5
-// Funai's USB Vendor ID
-#define VENDOR_ID_FUNAI         0x0F1C
-// Garmin-Asus's USB Vendor ID
-#define VENDOR_ID_GARMIN_ASUS   0x091E
-// Gigabyte's USB Vendor ID
-#define VENDOR_ID_GIGABYTE      0x0414
-// Gigaset's USB Vendor ID
-#define VENDOR_ID_GIGASET       0x1E85
-// GIONEE's USB Vendor ID
-#define VENDOR_ID_GIONEE        0x271D
-// Google's USB Vendor ID
-#define VENDOR_ID_GOOGLE        0x18d1
-// Haier's USB Vendor ID
-#define VENDOR_ID_HAIER         0x201E
-// Harris's USB Vendor ID
-#define VENDOR_ID_HARRIS        0x19A5
-// Hisense's USB Vendor ID
-#define VENDOR_ID_HISENSE       0x109b
-// HP's USB Vendor ID
-#define VENDOR_ID_HP            0x03f0
-// HTC's USB Vendor ID
-#define VENDOR_ID_HTC           0x0bb4
-// Huawei's USB Vendor ID
-#define VENDOR_ID_HUAWEI        0x12D1
-// INQ Mobile's USB Vendor ID
-#define VENDOR_ID_INQ_MOBILE    0x2314
-// Intel's USB Vendor ID
-#define VENDOR_ID_INTEL         0x8087
-// Intermec's USB Vendor ID
-#define VENDOR_ID_INTERMEC      0x067e
-// IRiver's USB Vendor ID
-#define VENDOR_ID_IRIVER        0x2420
-// K-Touch's USB Vendor ID
-#define VENDOR_ID_K_TOUCH       0x24E3
-// KT Tech's USB Vendor ID
-#define VENDOR_ID_KT_TECH       0x2116
-// Kobo's USB Vendor ID
-#define VENDOR_ID_KOBO          0x2237
-// Kyocera's USB Vendor ID
-#define VENDOR_ID_KYOCERA       0x0482
-// Lab126's USB Vendor ID
-#define VENDOR_ID_LAB126        0x1949
-// Lenovo's USB Vendor ID
-#define VENDOR_ID_LENOVO        0x17EF
-// LenovoMobile's USB Vendor ID
-#define VENDOR_ID_LENOVOMOBILE  0x2006
-// LG's USB Vendor ID
-#define VENDOR_ID_LGE           0x1004
-// Lumigon's USB Vendor ID
-#define VENDOR_ID_LUMIGON       0x25E3
-// Micromax's USB Vendor ID
-#define VENDOR_ID_MICROMAX      0x2A96
-// Motorola's USB Vendor ID
-#define VENDOR_ID_MOTOROLA      0x22b8
-// MSI's USB Vendor ID
-#define VENDOR_ID_MSI           0x0DB0
-// MTK's USB Vendor ID
-#define VENDOR_ID_MTK           0x0e8d
-// NEC's USB Vendor ID
-#define VENDOR_ID_NEC           0x0409
-// B&N Nook's USB Vendor ID
-#define VENDOR_ID_NOOK          0x2080
-// Nvidia's USB Vendor ID
-#define VENDOR_ID_NVIDIA        0x0955
-// OPPO's USB Vendor ID
-#define VENDOR_ID_OPPO          0x22D9
-// On-The-Go-Video's USB Vendor ID
-#define VENDOR_ID_OTGV          0x2257
-// OUYA's USB Vendor ID
-#define VENDOR_ID_OUYA          0x2836
-// Pantech's USB Vendor ID
-#define VENDOR_ID_PANTECH       0x10A9
-// Pegatron's USB Vendor ID
-#define VENDOR_ID_PEGATRON      0x1D4D
-// Philips's USB Vendor ID
-#define VENDOR_ID_PHILIPS       0x0471
-// Panasonic Mobile Communication's USB Vendor ID
-#define VENDOR_ID_PMC           0x04DA
-// Positivo's USB Vendor ID
-#define VENDOR_ID_POSITIVO      0x1662
-// Prestigio's USB Vendor ID
-#define VENDOR_ID_PRESTIGIO     0x29e4
-// Qisda's USB Vendor ID
-#define VENDOR_ID_QISDA         0x1D45
-// Qualcomm's USB Vendor ID
-#define VENDOR_ID_QUALCOMM      0x05c6
-// Quanta's USB Vendor ID
-#define VENDOR_ID_QUANTA        0x0408
-// Razer's USB Vendor ID
-#define VENDOR_ID_RAZER         0x1532
-// Rockchip's USB Vendor ID
-#define VENDOR_ID_ROCKCHIP      0x2207
-// Samsung's USB Vendor ID
-#define VENDOR_ID_SAMSUNG       0x04e8
-// Sharp's USB Vendor ID
-#define VENDOR_ID_SHARP         0x04dd
-// SK Telesys's USB Vendor ID
-#define VENDOR_ID_SK_TELESYS    0x1F53
-// Smartisan's USB Vendor ID
-#define VENDOR_ID_SMARTISAN     0x29a9
-// Sonim Tech's USB Vendor ID
-#define VENDOR_ID_SONIM_TECH    0x1d9c
-// Sony's USB Vendor ID
-#define VENDOR_ID_SONY          0x054C
-// Sony Ericsson's USB Vendor ID
-#define VENDOR_ID_SONY_ERICSSON 0x0FCE
-// T & A Mobile Phones' USB Vendor ID
-#define VENDOR_ID_T_AND_A       0x1BBB
-// TechFaith's USB Vendor ID
-#define VENDOR_ID_TECHFAITH     0x1d09
-// Teleepoch's USB Vendor ID
-#define VENDOR_ID_TELEEPOCH     0x2340
-// Texas Instruments's USB Vendor ID
-#define VENDOR_ID_TI            0x0451
-// Toshiba's USB Vendor ID
-#define VENDOR_ID_TOSHIBA       0x0930
-// TrekStor's USB Vendor ID
-#define VENDOR_ID_TREKSTOR      0x1E68
-// Unowhy's USB Vendor ID
-#define VENDOR_ID_UNOWHY        0x2A49
-// Vizio's USB Vendor ID
-#define VENDOR_ID_VIZIO         0xE040
-// Wacom's USB Vendor ID
-#define VENDOR_ID_WACOM         0x0531
-// Xiaomi's USB Vendor ID
-#define VENDOR_ID_XIAOMI        0x2717
-// YotaDevices's USB Vendor ID
-#define VENDOR_ID_YOTADEVICES   0x2916
-// Yulong Coolpad's USB Vendor ID
-#define VENDOR_ID_YULONG_COOLPAD 0x1EBF
-// ZTE's USB Vendor ID
-#define VENDOR_ID_ZTE           0x19D2
-/* Keep the list above sorted alphabetically by #define name */
-
-/** built-in vendor list */
-/* Keep the list below sorted alphabetically */
-int builtInVendorIds[] = {
-    VENDOR_ID_ACER,
-    VENDOR_ID_ALCO,
-    VENDOR_ID_ALLWINNER,
-    VENDOR_ID_AMLOGIC,
-    VENDOR_ID_ANYDATA,
-    VENDOR_ID_ARCHOS,
-    VENDOR_ID_ASUS,
-    VENDOR_ID_BYD,
-    VENDOR_ID_COMPAL,
-    VENDOR_ID_COMPALCOMM,
-    VENDOR_ID_DELL,
-    VENDOR_ID_ECS,
-    VENDOR_ID_EMERGING_TECH,
-    VENDOR_ID_EMERSON,
-    VENDOR_ID_FOXCONN,
-    VENDOR_ID_FUJITSU,
-    VENDOR_ID_FUNAI,
-    VENDOR_ID_GARMIN_ASUS,
-    VENDOR_ID_GIGABYTE,
-    VENDOR_ID_GIGASET,
-    VENDOR_ID_GIONEE,
-    VENDOR_ID_GOOGLE,
-    VENDOR_ID_HAIER,
-    VENDOR_ID_HARRIS,
-    VENDOR_ID_HISENSE,
-    VENDOR_ID_HP,
-    VENDOR_ID_HTC,
-    VENDOR_ID_HUAWEI,
-    VENDOR_ID_INQ_MOBILE,
-    VENDOR_ID_INTEL,
-    VENDOR_ID_INTERMEC,
-    VENDOR_ID_IRIVER,
-    VENDOR_ID_KOBO,
-    VENDOR_ID_K_TOUCH,
-    VENDOR_ID_KT_TECH,
-    VENDOR_ID_KYOCERA,
-    VENDOR_ID_LAB126,
-    VENDOR_ID_LENOVO,
-    VENDOR_ID_LENOVOMOBILE,
-    VENDOR_ID_LGE,
-    VENDOR_ID_LUMIGON,
-    VENDOR_ID_MICROMAX,
-    VENDOR_ID_MOTOROLA,
-    VENDOR_ID_MSI,
-    VENDOR_ID_MTK,
-    VENDOR_ID_NEC,
-    VENDOR_ID_NOOK,
-    VENDOR_ID_NVIDIA,
-    VENDOR_ID_OPPO,
-    VENDOR_ID_OTGV,
-    VENDOR_ID_OUYA,
-    VENDOR_ID_PANTECH,
-    VENDOR_ID_PEGATRON,
-    VENDOR_ID_PHILIPS,
-    VENDOR_ID_PMC,
-    VENDOR_ID_POSITIVO,
-    VENDOR_ID_PRESTIGIO,
-    VENDOR_ID_QISDA,
-    VENDOR_ID_QUALCOMM,
-    VENDOR_ID_QUANTA,
-    VENDOR_ID_RAZER,
-    VENDOR_ID_ROCKCHIP,
-    VENDOR_ID_SAMSUNG,
-    VENDOR_ID_SHARP,
-    VENDOR_ID_SK_TELESYS,
-    VENDOR_ID_SMARTISAN,
-    VENDOR_ID_SONIM_TECH,
-    VENDOR_ID_SONY,
-    VENDOR_ID_SONY_ERICSSON,
-    VENDOR_ID_T_AND_A,
-    VENDOR_ID_TECHFAITH,
-    VENDOR_ID_TELEEPOCH,
-    VENDOR_ID_TI,
-    VENDOR_ID_TOSHIBA,
-    VENDOR_ID_TREKSTOR,
-    VENDOR_ID_UNOWHY,
-    VENDOR_ID_VIZIO,
-    VENDOR_ID_WACOM,
-    VENDOR_ID_XIAOMI,
-    VENDOR_ID_YOTADEVICES,
-    VENDOR_ID_YULONG_COOLPAD,
-    VENDOR_ID_ZTE,
-};
-/* Keep the list above sorted alphabetically */
-
-#define BUILT_IN_VENDOR_COUNT    (sizeof(builtInVendorIds)/sizeof(builtInVendorIds[0]))
-
-/* max number of supported vendor ids (built-in + 3rd party). increase as needed */
-#define VENDOR_COUNT_MAX         128
-
-int vendorIds[VENDOR_COUNT_MAX];
-unsigned vendorIdCount = 0;
-
-int get_adb_usb_ini(char* buff, size_t len);
-
-void usb_vendors_init(void)
-{
-    if (VENDOR_COUNT_MAX < BUILT_IN_VENDOR_COUNT) {
-        fprintf(stderr, "VENDOR_COUNT_MAX not big enough for built-in vendor list.\n");
-        exit(2);
-    }
-
-    /* add the built-in vendors at the beginning of the array */
-    memcpy(vendorIds, builtInVendorIds, sizeof(builtInVendorIds));
-
-    /* default array size is the number of built-in vendors */
-    vendorIdCount = BUILT_IN_VENDOR_COUNT;
-
-    if (VENDOR_COUNT_MAX == BUILT_IN_VENDOR_COUNT)
-        return;
-
-    char temp[PATH_MAX];
-    if (get_adb_usb_ini(temp, sizeof(temp)) == 0) {
-        FILE * f = fopen(temp, "rt");
-
-        if (f != NULL) {
-            /* The vendor id file is pretty basic. 1 vendor id per line.
-               Lines starting with # are comments */
-            while (fgets(temp, sizeof(temp), f) != NULL) {
-                if (temp[0] == '#')
-                    continue;
-
-                long value = strtol(temp, NULL, 0);
-                if (errno == EINVAL || errno == ERANGE || value > INT_MAX || value < 0) {
-                    fprintf(stderr, "Invalid content in %s. Quitting.\n", ANDROID_ADB_INI);
-                    exit(2);
-                }
-
-                vendorIds[vendorIdCount++] = (int)value;
-
-                /* make sure we don't go beyond the array */
-                if (vendorIdCount == VENDOR_COUNT_MAX) {
-                    break;
-                }
-            }
-            fclose(f);
-        }
-    }
-}
-
-/* Utils methods */
-
-/* builds the path to the adb vendor id file. returns 0 if success */
-int build_path(char* buff, size_t len, const char* format, const char* home)
-{
-    if (snprintf(buff, len, format, home, ANDROID_PATH, ANDROID_ADB_INI) >= (signed)len) {
-        return 1;
-    }
-
-    return 0;
-}
-
-/* fills buff with the path to the adb vendor id file. returns 0 if success */
-int get_adb_usb_ini(char* buff, size_t len)
-{
-#ifdef _WIN32
-    const char* home = getenv("ANDROID_SDK_HOME");
-    if (home != NULL) {
-        return build_path(buff, len, "%s\\%s\\%s", home);
-    } else {
-        char path[MAX_PATH];
-        SHGetFolderPath( NULL, CSIDL_PROFILE, NULL, 0, path);
-        return build_path(buff, len, "%s\\%s\\%s", path);
-    }
-#else
-    const char* home = getenv("HOME");
-    if (home == NULL)
-        home = "/tmp";
-
-    return build_path(buff, len, "%s/%s/%s", home);
-#endif
-}
diff --git a/adb/usb_vendors.h b/adb/usb_vendors.h
deleted file mode 100644
index cee23a1..0000000
--- a/adb/usb_vendors.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __USB_VENDORS_H
-#define __USB_VENDORS_H
-
-extern int vendorIds[];
-extern unsigned  vendorIdCount;
-
-void usb_vendors_init(void);
-
-#endif
diff --git a/adf/libadf/tests/Android.mk b/adf/libadf/tests/Android.mk
new file mode 100644
index 0000000..93efafa
--- /dev/null
+++ b/adf/libadf/tests/Android.mk
@@ -0,0 +1,22 @@
+#
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+LOCAL_PATH := $(my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := adf_test.cpp
+LOCAL_MODULE := adf-unit-tests
+LOCAL_STATIC_LIBRARIES := libadf
+include $(BUILD_NATIVE_TEST)
diff --git a/adf/libadf/tests/adf_test.cpp b/adf/libadf/tests/adf_test.cpp
new file mode 100644
index 0000000..d95330d
--- /dev/null
+++ b/adf/libadf/tests/adf_test.cpp
@@ -0,0 +1,342 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+
+#include <adf/adf.h>
+#include <gtest/gtest.h>
+#include <sys/mman.h>
+
+class AdfTest : public testing::Test {
+public:
+    AdfTest() : intf_id(0), intf(-1), eng_id(0), eng(-1) { }
+
+    virtual void SetUp() {
+        int err = adf_device_open(dev_id, O_RDWR, &dev);
+        ASSERT_GE(err, 0) << "opening ADF device " << dev_id <<
+                " failed: " << strerror(-err);
+
+        err = adf_find_simple_post_configuration(&dev, fmt8888, n_fmt8888,
+                &intf_id, &eng_id);
+        ASSERT_GE(err, 0) << "finding ADF configuration failed: " <<
+                strerror(-err);
+
+        intf = adf_interface_open(&dev, intf_id, O_RDWR);
+        ASSERT_GE(intf, 0) << "opening ADF interface " << dev_id << "." <<
+                intf_id << " failed: " << strerror(-intf);
+
+        eng = adf_overlay_engine_open(&dev, eng_id, O_RDWR);
+        ASSERT_GE(eng, 0) << "opening ADF overlay engine " << dev_id << "." <<
+                eng_id << " failed: " << strerror(-eng);
+    }
+
+    virtual void TearDown() {
+        if (eng >= 0)
+            close(eng);
+        if (intf >= 0)
+            close(intf);
+        adf_device_close(&dev);
+    }
+
+    void get8888Format(uint32_t &fmt, char fmt_str[ADF_FORMAT_STR_SIZE]) {
+        adf_overlay_engine_data data;
+        int err = adf_get_overlay_engine_data(eng, &data);
+        ASSERT_GE(err, 0) << "getting ADF overlay engine data failed: " <<
+                strerror(-err);
+
+        for (size_t i = 0; i < data.n_supported_formats; i++) {
+            for (size_t j = 0; j < n_fmt8888; j++) {
+                if (data.supported_formats[i] == fmt8888[j]) {
+                    fmt = data.supported_formats[i];
+                    adf_format_str(fmt, fmt_str);
+                    adf_free_overlay_engine_data(&data);
+                    return;
+                }
+            }
+        }
+
+        adf_free_overlay_engine_data(&data);
+        FAIL(); /* this should never happen */
+    }
+
+    void drawCheckerboard(void *buf, uint32_t w, uint32_t h, uint32_t pitch) {
+        uint8_t *buf8 = reinterpret_cast<uint8_t *>(buf);
+        for (uint32_t y = 0; y < h / 2; y++) {
+            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
+            for (uint32_t x = 0; x < w / 2; x++)
+                scanline[x] = 0xFF0000FF;
+            for (uint32_t x = w / 2; x < w; x++)
+                scanline[x] = 0xFF00FFFF;
+        }
+        for (uint32_t y = h / 2; y < h; y++) {
+            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
+            for (uint32_t x = 0; x < w / 2; x++)
+                scanline[x] = 0xFFFF00FF;
+            for (uint32_t x = w / 2; x < w; x++)
+                scanline[x] = 0xFFFFFFFF;
+        }
+    }
+
+    /* various helpers to call ADF and die on failure */
+
+    void getInterfaceData(adf_interface_data &data) {
+         int err = adf_get_interface_data(intf, &data);
+         ASSERT_GE(err, 0) << "getting ADF interface data failed: " <<
+                 strerror(-err);
+    }
+
+    void getCurrentMode(uint32_t &w, uint32_t &h) {
+        adf_interface_data data;
+        ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
+        w = data.current_mode.hdisplay;
+        h = data.current_mode.vdisplay;
+        adf_free_interface_data(&data);
+    }
+
+    void blank(uint8_t mode) {
+        int err = adf_interface_blank(intf, mode);
+        ASSERT_FALSE(err < 0 && err != -EBUSY) <<
+                "unblanking interface failed: " << strerror(-err);
+    }
+
+    void attach() {
+        int err = adf_device_attach(&dev, eng_id, intf_id);
+        ASSERT_FALSE(err < 0 && err != -EALREADY) <<
+                "attaching overlay engine " << eng_id << " to interface " <<
+                intf_id << " failed: " << strerror(-err);
+    }
+
+    void detach() {
+        int err = adf_device_detach(&dev, eng_id, intf_id);
+        ASSERT_FALSE(err < 0 && err != -EINVAL) <<
+                "detaching overlay engine " << eng_id << " from interface " <<
+                intf_id << " failed: " << strerror(-err);
+    }
+
+    void readVsyncTimestamp(uint64_t &timestamp) {
+        adf_event *event;
+        int err = adf_read_event(intf, &event);
+        ASSERT_GE(err, 0) << "reading ADF event failed: " << strerror(-err);
+
+        ASSERT_EQ(ADF_EVENT_VSYNC, event->type);
+        ASSERT_EQ(sizeof(adf_vsync_event), event->length);
+
+        adf_vsync_event *vsync_event =
+                reinterpret_cast<adf_vsync_event *>(event);
+        timestamp = vsync_event->timestamp;
+        free(event);
+    }
+
+protected:
+    adf_device dev;
+    adf_id_t intf_id;
+    int intf;
+    adf_id_t eng_id;
+    int eng;
+
+private:
+    const static adf_id_t dev_id = 0;
+    const static __u32 fmt8888[];
+    const static size_t n_fmt8888;
+};
+
+const __u32 AdfTest::fmt8888[] = {
+   DRM_FORMAT_XRGB8888,
+   DRM_FORMAT_XBGR8888,
+   DRM_FORMAT_RGBX8888,
+   DRM_FORMAT_BGRX8888,
+   DRM_FORMAT_ARGB8888,
+   DRM_FORMAT_ABGR8888,
+   DRM_FORMAT_RGBA8888,
+   DRM_FORMAT_BGRA8888
+};
+const size_t AdfTest::n_fmt8888 = sizeof(fmt8888) / sizeof(fmt8888[0]);
+
+TEST(adf, devices) {
+    adf_id_t *devs;
+    ssize_t n_devs = adf_devices(&devs);
+    free(devs);
+
+    ASSERT_GE(n_devs, 0) << "enumerating ADF devices failed: " <<
+            strerror(-n_devs);
+    ASSERT_TRUE(devs != NULL);
+}
+
+TEST_F(AdfTest, device_data) {
+    adf_device_data data;
+    int err = adf_get_device_data(&dev, &data);
+    ASSERT_GE(err, 0) << "getting ADF device data failed: " << strerror(-err);
+
+    EXPECT_LT(data.n_attachments, ADF_MAX_ATTACHMENTS);
+    EXPECT_GT(data.n_allowed_attachments, 0);
+    EXPECT_LT(data.n_allowed_attachments, ADF_MAX_ATTACHMENTS);
+    EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE);
+    adf_free_device_data(&data);
+}
+
+TEST_F(AdfTest, interface_data) {
+    adf_interface_data data;
+    ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
+
+    EXPECT_LT(data.type, ADF_INTF_TYPE_MAX);
+    EXPECT_LE(data.dpms_state, DRM_MODE_DPMS_OFF);
+    EXPECT_EQ(1, data.hotplug_detect);
+    EXPECT_GT(data.n_available_modes, 0);
+    EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE);
+    adf_free_interface_data(&data);
+}
+
+TEST_F(AdfTest, overlay_engine_data) {
+    adf_overlay_engine_data data;
+    int err = adf_get_overlay_engine_data(eng, &data);
+    ASSERT_GE(err, 0) << "getting ADF overlay engine failed: " <<
+            strerror(-err);
+
+    EXPECT_GT(data.n_supported_formats, 0);
+    EXPECT_LT(data.n_supported_formats, ADF_MAX_SUPPORTED_FORMATS);
+    EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE);
+    adf_free_overlay_engine_data(&data);
+}
+
+TEST_F(AdfTest, blank) {
+    int err = adf_interface_blank(intf, (uint8_t)-1);
+    EXPECT_EQ(-EINVAL, err) << "setting bogus DPMS mode should have failed";
+
+    err = adf_interface_blank(eng, DRM_MODE_DPMS_OFF);
+    EXPECT_EQ(-EINVAL, err) << "blanking overlay engine should have failed";
+
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_OFF));
+    err = adf_interface_blank(intf, DRM_MODE_DPMS_OFF);
+    EXPECT_EQ(-EBUSY, err) << "blanking interface twice should have failed";
+
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
+    err = adf_interface_blank(intf, DRM_MODE_DPMS_ON);
+    EXPECT_EQ(-EBUSY, err) << "unblanking interface twice should have failed";
+
+    adf_interface_data data;
+    ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
+    EXPECT_EQ(DRM_MODE_DPMS_ON, data.dpms_state);
+    adf_free_interface_data(&data);
+}
+
+TEST_F(AdfTest, event) {
+    int err = adf_set_event(intf, ADF_EVENT_TYPE_MAX, true);
+    EXPECT_EQ(-EINVAL, err) << "enabling bogus ADF event should have failed";
+
+    err = adf_set_event(intf, ADF_EVENT_TYPE_MAX, false);
+    EXPECT_EQ(-EINVAL, err) << "disabling bogus ADF event should have failed";
+
+    err = adf_set_event(intf, ADF_EVENT_VSYNC, true);
+    ASSERT_GE(err, 0) << "enabling vsync event failed: " << strerror(-err);
+
+    err = adf_set_event(intf, ADF_EVENT_VSYNC, true);
+    EXPECT_EQ(-EALREADY, err) <<
+            "enabling vsync event twice should have failed";
+
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
+
+    uint64_t timestamp1, timestamp2;
+    ASSERT_NO_FATAL_FAILURE(readVsyncTimestamp(timestamp1));
+    ASSERT_NO_FATAL_FAILURE(readVsyncTimestamp(timestamp2));
+    EXPECT_GT(timestamp2, timestamp1);
+
+    err = adf_set_event(intf, ADF_EVENT_VSYNC, false);
+    EXPECT_GE(err, 0) << "disabling vsync event failed: " << strerror(-err);
+
+    err = adf_set_event(intf, ADF_EVENT_VSYNC, false);
+    EXPECT_EQ(-EALREADY, err) <<
+            "disabling vsync event twice should have failed";
+}
+
+TEST_F(AdfTest, attach) {
+    ASSERT_NO_FATAL_FAILURE(attach());
+    int err = adf_device_attach(&dev, eng_id, intf_id);
+    EXPECT_EQ(-EALREADY, err) << "attaching overlay engine " << eng_id <<
+            " to interface " << intf_id << " twice should have failed";
+
+    ASSERT_NO_FATAL_FAILURE(detach());
+    err = adf_device_detach(&dev, eng_id, intf_id);
+    EXPECT_EQ(-EINVAL, err) << "detaching overlay engine " << eng_id <<
+            " from interface " << intf_id << " twice should have failed";
+
+    err = adf_device_attach(&dev, eng_id, ADF_MAX_INTERFACES);
+    EXPECT_EQ(-EINVAL, err) << "attaching overlay engine " << eng_id <<
+            " to bogus interface should have failed";
+
+    err = adf_device_detach(&dev, eng_id, ADF_MAX_INTERFACES);
+    EXPECT_EQ(-EINVAL, err) << "detaching overlay engine " << eng_id <<
+            " from bogus interface should have failed";
+}
+
+TEST_F(AdfTest, simple_buffer_alloc) {
+    uint32_t w = 0, h = 0;
+    ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h));
+
+    uint32_t format;
+    char format_str[ADF_FORMAT_STR_SIZE];
+    ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str));
+
+    uint32_t offset;
+    uint32_t pitch;
+    int buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset,
+            &pitch);
+    EXPECT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-buf_fd);
+    EXPECT_GE(pitch, w * 4);
+    close(buf_fd);
+
+    buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, 0xDEADBEEF, &offset,
+            &pitch);
+    /* n.b.: ADF only allows simple buffers with built-in RGB formats,
+       so this should fail even if a driver supports custom format 0xDEADBEEF */
+    EXPECT_EQ(-EINVAL, buf_fd) <<
+            "allocating buffer with bogus format should have failed";
+}
+
+TEST_F(AdfTest, simple_buffer) {
+    uint32_t w = 0, h = 0;
+    ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h));
+
+    uint32_t format = 0;
+    char format_str[ADF_FORMAT_STR_SIZE];
+    ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str));
+
+    uint32_t offset;
+    uint32_t pitch;
+    int buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset,
+            &pitch);
+    ASSERT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-buf_fd);
+    EXPECT_GE(pitch, w * 4);
+
+    void *mapped = mmap(NULL, pitch * h, PROT_WRITE, MAP_SHARED, buf_fd,
+            offset);
+    ASSERT_NE(mapped, MAP_FAILED) << "mapping " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-errno);
+    drawCheckerboard(mapped, w, h, pitch);
+    munmap(mapped, pitch * h);
+
+    ASSERT_NO_FATAL_FAILURE(attach());
+    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
+
+    int release_fence = adf_interface_simple_post(intf, eng_id, w, h, format,
+            buf_fd, offset, pitch, -1);
+    close(buf_fd);
+    ASSERT_GE(release_fence, 0) << "posting " << w << "x" << h << " " <<
+            format_str << " buffer failed: " << strerror(-release_fence);
+    close(release_fence);
+}
diff --git a/fastboot/fastboot.c b/fastboot/fastboot.c
index ddd3aa5..92a61f8 100644
--- a/fastboot/fastboot.c
+++ b/fastboot/fastboot.c
@@ -988,6 +988,7 @@
     unsigned sz;
     int status;
     int c;
+    int longindex;
 
     const struct option longopts[] = {
         {"base", required_argument, 0, 'b'},
@@ -996,13 +997,14 @@
         {"ramdisk_offset", required_argument, 0, 'r'},
         {"tags_offset", required_argument, 0, 't'},
         {"help", 0, 0, 'h'},
+        {"unbuffered", 0, 0, 0},
         {0, 0, 0, 0}
     };
 
     serial = getenv("ANDROID_SERIAL");
 
     while (1) {
-        c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, NULL);
+        c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, &longindex);
         if (c < 0) {
             break;
         }
@@ -1063,6 +1065,12 @@
             break;
         case '?':
             return 1;
+        case 0:
+            if (strcmp("unbuffered", longopts[longindex].name) == 0) {
+                setvbuf(stdout, NULL, _IONBF, 0);
+                setvbuf(stderr, NULL, _IONBF, 0);
+            }
+            break;
         default:
             abort();
         }
diff --git a/fastboot/util_osx.c b/fastboot/util_osx.c
index e80a8f3..e718562 100644
--- a/fastboot/util_osx.c
+++ b/fastboot/util_osx.c
@@ -32,12 +32,12 @@
 void get_my_path(char s[PATH_MAX])
 {
     CFBundleRef mainBundle = CFBundleGetMainBundle();
-    CFURLRef bundleURL = CFBundleCopyBundleURL(mainBundle);
-    CFStringRef bundlePathString = CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle);
-    CFRelease(bundleURL);
+    CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle);
+    CFStringRef executablePathString = CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle);
+    CFRelease(executableURL);
 
-    CFStringGetCString(bundlePathString, s, PATH_MAX - 1, kCFStringEncodingASCII);
-    CFRelease(bundlePathString);
+    CFStringGetFileSystemRepresentation(executablePathString, s, PATH_MAX-1);
+    CFRelease(executablePathString);
 
 	char *x;
     x = strrchr(s, '/');
diff --git a/fastbootd/commands/virtual_partitions.c b/fastbootd/commands/virtual_partitions.c
index 813f485..9da4020 100644
--- a/fastbootd/commands/virtual_partitions.c
+++ b/fastbootd/commands/virtual_partitions.c
@@ -30,6 +30,9 @@
  */
 
 #include "commands/virtual_partitions.h"
+
+#include <string.h>
+
 #include "debug.h"
 
 static struct virtual_partition *partitions = NULL;
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index 4a6b702..06497c2 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -389,7 +389,6 @@
             if (!strcmp(name, ".") || !strcmp(name, ".."))
                 continue;
 
-            char buf[20];
             // Look for "type" file in each subdirectory
             path.clear();
             path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH, name);
diff --git a/healthd/healthd.cpp b/healthd/healthd.cpp
index 30a4b42..b34583d 100644
--- a/healthd/healthd.cpp
+++ b/healthd/healthd.cpp
@@ -64,7 +64,6 @@
 #define MAX_EPOLL_EVENTS 40
 static int uevent_fd;
 static int wakealarm_fd;
-static int binder_fd;
 
 // -1 for no epoll timeout
 static int awake_poll_interval = -1;
diff --git a/healthd/healthd_mode_charger.cpp b/healthd/healthd_mode_charger.cpp
index 394feb8..291cb6c 100644
--- a/healthd/healthd_mode_charger.cpp
+++ b/healthd/healthd_mode_charger.cpp
@@ -350,7 +350,6 @@
 static void update_screen_state(struct charger *charger, int64_t now)
 {
     struct animation *batt_anim = charger->batt_anim;
-    int cur_frame;
     int disp_time;
 
     if (!batt_anim->run || now < charger->next_screen_transition)
@@ -393,7 +392,6 @@
     /* animation starting, set up the animation */
     if (batt_anim->cur_frame == 0) {
         int batt_cap;
-        int ret;
 
         LOGV("[%" PRId64 "] animation starting\n", now);
         batt_cap = get_battery_capacity();
@@ -517,7 +515,6 @@
 static void process_key(struct charger *charger, int code, int64_t now)
 {
     struct key_state *key = &charger->keys[code];
-    int64_t next_key_check;
 
     if (code == KEY_POWER) {
         if (key->down) {
@@ -590,7 +587,6 @@
 {
     struct charger *charger = &charger_state;
     int64_t now = curr_time_ms();
-    int ret;
 
     handle_input_state(charger, now);
     handle_power_supply_state(charger, now);
@@ -625,8 +621,6 @@
     int64_t now = curr_time_ms();
     int64_t next_event = INT64_MAX;
     int64_t timeout;
-    struct input_event ev;
-    int ret;
 
     LOGV("[%" PRId64 "] next screen: %" PRId64 " next key: %" PRId64 " next pwr: %" PRId64 "\n", now,
          charger->next_screen_transition, charger->next_key_check,
diff --git a/include/log/uio.h b/include/log/uio.h
index a71f515..7059da5 100644
--- a/include/log/uio.h
+++ b/include/log/uio.h
@@ -14,20 +14,23 @@
  * limitations under the License.
  */
 
-//
-// implementation of sys/uio.h for platforms that don't have it (Win32)
-//
 #ifndef _LIBS_CUTILS_UIO_H
 #define _LIBS_CUTILS_UIO_H
 
-#ifdef HAVE_SYS_UIO_H
+#if !defined(_WIN32)
+
 #include <sys/uio.h>
+
 #else
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+//
+// Implementation of sys/uio.h for Win32.
+//
+
 #include <stddef.h>
 
 struct iovec {
@@ -42,7 +45,7 @@
 }
 #endif
 
-#endif /* !HAVE_SYS_UIO_H */
+#endif
 
 #endif /* _LIBS_UTILS_UIO_H */
 
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index b2f91a5..5efe2e1 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -232,7 +232,6 @@
     { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.goldfish.sh" },
     { 00440, AID_ROOT,      AID_SHELL,     0, "system/etc/init.trout.rc" },
     { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.ril" },
-    { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.testmenu" },
     { 00550, AID_DHCP,      AID_SHELL,     0, "system/etc/dhcpcd/dhcpcd-run-hooks" },
     { 00444, AID_RADIO,     AID_AUDIO,     0, "system/etc/AudioPara4.csv" },
     { 00555, AID_ROOT,      AID_ROOT,      0, "system/etc/ppp/*" },
diff --git a/include/utils/Compat.h b/include/utils/Compat.h
index 20a6920..0df40a1 100644
--- a/include/utils/Compat.h
+++ b/include/utils/Compat.h
@@ -44,6 +44,17 @@
 #endif
 
 /*
+ * Needed for cases where something should be constexpr if possible, but not
+ * being constexpr is fine if in pre-C++11 code (such as a const static float
+ * member variable).
+ */
+#if __cplusplus >= 201103L
+#define CONSTEXPR constexpr
+#else
+#define CONSTEXPR
+#endif
+
+/*
  * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
  * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
  * not already defined, then define it here.
diff --git a/include/utils/Endian.h b/include/utils/Endian.h
index 19f2504..591cae0 100644
--- a/include/utils/Endian.h
+++ b/include/utils/Endian.h
@@ -20,21 +20,16 @@
 #ifndef _LIBS_UTILS_ENDIAN_H
 #define _LIBS_UTILS_ENDIAN_H
 
-#if defined(HAVE_ENDIAN_H)
-
-#include <endian.h>
-
-#else /*not HAVE_ENDIAN_H*/
+#if defined(__APPLE__) || defined(_WIN32)
 
 #define __BIG_ENDIAN 0x1000
 #define __LITTLE_ENDIAN 0x0001
+#define __BYTE_ORDER __LITTLE_ENDIAN
 
-#if defined(HAVE_LITTLE_ENDIAN)
-# define __BYTE_ORDER __LITTLE_ENDIAN
 #else
-# define __BYTE_ORDER __BIG_ENDIAN
-#endif
 
-#endif /*not HAVE_ENDIAN_H*/
+#include <endian.h>
+
+#endif
 
 #endif /*_LIBS_UTILS_ENDIAN_H*/
diff --git a/init/Android.mk b/init/Android.mk
index 72c2272..8cda879 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -51,25 +51,9 @@
 	libmincrypt \
 	libext4_utils_static
 
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
+# Create symlinks
+LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \
+    ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \
+    ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd
 
 include $(BUILD_EXECUTABLE)
-
-# Make a symlink from /sbin/ueventd and /sbin/watchdogd to /init
-SYMLINKS := \
-	$(TARGET_ROOT_OUT)/sbin/ueventd \
-	$(TARGET_ROOT_OUT)/sbin/watchdogd
-
-$(SYMLINKS): INIT_BINARY := $(LOCAL_MODULE)
-$(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk
-	@echo "Symlink: $@ -> ../$(INIT_BINARY)"
-	@mkdir -p $(dir $@)
-	@rm -rf $@
-	$(hide) ln -sf ../$(INIT_BINARY) $@
-
-ALL_DEFAULT_INSTALLED_MODULES += $(SYMLINKS)
-
-# We need this so that the installed files could be picked up based on the
-# local module name
-ALL_MODULES.$(LOCAL_MODULE).INSTALLED := \
-    $(ALL_MODULES.$(LOCAL_MODULE).INSTALLED) $(SYMLINKS)
diff --git a/init/builtins.c b/init/builtins.c
index 7f4daa7..5d2a517 100644
--- a/init/builtins.c
+++ b/init/builtins.c
@@ -501,7 +501,6 @@
     int ret = -1;
     int child_ret = -1;
     int status;
-    const char *prop;
     struct fstab *fstab;
 
     if (nargs != 2) {
diff --git a/init/devices.c b/init/devices.c
index a95111a..dde43df 100644
--- a/init/devices.c
+++ b/init/devices.c
@@ -191,7 +191,6 @@
 static mode_t get_device_perm(const char *path, const char **links,
                 unsigned *uid, unsigned *gid)
 {
-    mode_t perm;
     struct listnode *node;
     struct perm_node *perm_node;
     struct perms_ *dp;
@@ -497,15 +496,10 @@
     struct platform_node *pdev;
     char *slash;
     const char *type;
-    int width;
     char buf[256];
     char link_path[256];
-    int fd;
     int link_num = 0;
-    int ret;
     char *p;
-    unsigned int size;
-    struct stat info;
 
     pdev = find_platform_device(uevent->path);
     if (pdev) {
@@ -926,7 +920,6 @@
 static void handle_firmware_event(struct uevent *uevent)
 {
     pid_t pid;
-    int ret;
 
     if(strcmp(uevent->subsystem, "firmware"))
         return;
@@ -1045,15 +1038,18 @@
     fcntl(device_fd, F_SETFD, FD_CLOEXEC);
     fcntl(device_fd, F_SETFL, O_NONBLOCK);
 
-    if (stat(coldboot_done, &info) < 0) {
+    if (stat(COLDBOOT_DONE, &info) < 0) {
         t0 = get_usecs();
         coldboot("/sys/class");
         coldboot("/sys/block");
         coldboot("/sys/devices");
         t1 = get_usecs();
-        fd = open(coldboot_done, O_WRONLY|O_CREAT, 0000);
+        fd = open(COLDBOOT_DONE, O_WRONLY|O_CREAT, 0000);
         close(fd);
         log_event_print("coldboot %ld uS\n", ((long) (t1 - t0)));
+        // t0 & t1 are unused if the log isn't doing anything.
+        (void)t0;
+        (void)t1;
     } else {
         log_event_print("skipping coldboot, already done\n");
     }
diff --git a/init/init.c b/init/init.c
index 99474e6..2b82937 100644
--- a/init/init.c
+++ b/init/init.c
@@ -76,7 +76,6 @@
 
 static struct action *cur_action = NULL;
 static struct command *cur_command = NULL;
-static struct listnode *command_queue = NULL;
 
 void notify_service_state(const char *name, const char *state)
 {
@@ -170,7 +169,6 @@
     struct stat s;
     pid_t pid;
     int needs_console;
-    int n;
     char *scon = NULL;
     int rc;
 
@@ -578,10 +576,10 @@
 static int wait_for_coldboot_done_action(int nargs, char **args)
 {
     int ret;
-    INFO("wait for %s\n", coldboot_done);
-    ret = wait_for_file(coldboot_done, COMMAND_RETRY_TIMEOUT);
+    INFO("wait for %s\n", COLDBOOT_DONE);
+    ret = wait_for_file(COLDBOOT_DONE, COMMAND_RETRY_TIMEOUT);
     if (ret)
-        ERROR("Timed out waiting for %s\n", coldboot_done);
+        ERROR("Timed out waiting for %s\n", COLDBOOT_DONE);
     return ret;
 }
 
@@ -1003,9 +1001,6 @@
 {
     int fd_count = 0;
     struct pollfd ufds[4];
-    char *tmpdev;
-    char* debuggable;
-    char tmp[32];
     int property_set_fd_init = 0;
     int signal_fd_init = 0;
     int keychord_fd_init = 0;
diff --git a/init/init_parser.c b/init/init_parser.c
index 6466db2..2b4db8e 100644
--- a/init/init_parser.c
+++ b/init/init_parser.c
@@ -187,19 +187,14 @@
 
 int expand_props(char *dst, const char *src, int dst_size)
 {
-    int cnt = 0;
     char *dst_ptr = dst;
     const char *src_ptr = src;
-    int src_len;
-    int idx = 0;
     int ret = 0;
     int left = dst_size - 1;
 
     if (!src || !dst || dst_size == 0)
         return -1;
 
-    src_len = strlen(src);
-
     /* - variables can either be $x.y or ${x.y}, in case they are only part
      *   of the string.
      * - will accept $$ as a literal $.
@@ -847,7 +842,6 @@
 {
     struct command *cmd;
     struct action *act = state->context;
-    int (*func)(int nargs, char **args);
     int kw, n;
 
     if (nargs == 0) {
diff --git a/init/property_service.c b/init/property_service.c
index 44658c5..1f98e13 100644
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -63,7 +63,6 @@
 
 static int init_workspace(workspace *w, size_t size)
 {
-    void *data;
     int fd = open(PROP_FILENAME, O_RDONLY | O_NOFOLLOW);
     if (fd < 0)
         return -1;
@@ -142,9 +141,6 @@
  */
 static int check_perms(const char *name, char *sctx)
 {
-    int i;
-    unsigned int app_id;
-
     if(!strncmp(name, "ro.", 3))
         name +=3;
 
@@ -261,7 +257,6 @@
     prop_msg msg;
     int s;
     int r;
-    int res;
     struct ucred cr;
     struct sockaddr_un addr;
     socklen_t addr_size = sizeof(addr);
diff --git a/init/util.h b/init/util.h
index 04b8129..4cfe99d 100644
--- a/init/util.h
+++ b/init/util.h
@@ -22,7 +22,7 @@
 
 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
 
-static const char *coldboot_done = "/dev/.coldboot_done";
+#define COLDBOOT_DONE "/dev/.coldboot_done"
 
 int mtd_name_to_number(const char *name);
 int create_socket(const char *name, int type, mode_t perm,
diff --git a/libcutils/socket_local_client.c b/libcutils/socket_local_client.c
index ddcc2da..7b42daa 100644
--- a/libcutils/socket_local_client.c
+++ b/libcutils/socket_local_client.c
@@ -52,7 +52,7 @@
 
     switch (namespaceId) {
         case ANDROID_SOCKET_NAMESPACE_ABSTRACT:
-#ifdef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE
+#if defined(__linux__)
             namelen  = strlen(name);
 
             // Test with length +1 for the *initial* '\0'.
@@ -67,7 +67,7 @@
             
             p_addr->sun_path[0] = 0;
             memcpy(p_addr->sun_path + 1, name, namelen);
-#else /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/
+#else
             /* this OS doesn't have the Linux abstract namespace */
 
             namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX);
@@ -79,7 +79,7 @@
 
             strcpy(p_addr->sun_path, FILESYSTEM_SOCKET_PREFIX);
             strcat(p_addr->sun_path, name);
-#endif /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/
+#endif
         break;
 
         case ANDROID_SOCKET_NAMESPACE_RESERVED:
diff --git a/libcutils/socket_local_server.c b/libcutils/socket_local_server.c
index 7628fe4..60eb86b 100644
--- a/libcutils/socket_local_server.c
+++ b/libcutils/socket_local_server.c
@@ -66,7 +66,7 @@
     }
 
     /* basically: if this is a filesystem path, unlink first */
-#ifndef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE
+#if !defined(__linux__)
     if (1) {
 #else
     if (namespaceId == ANDROID_SOCKET_NAMESPACE_RESERVED
diff --git a/libcutils/socket_network_client.c b/libcutils/socket_network_client.c
index 4826033..e0031ba 100644
--- a/libcutils/socket_network_client.c
+++ b/libcutils/socket_network_client.c
@@ -45,7 +45,6 @@
 {
     struct hostent *hp;
     struct sockaddr_in addr;
-    socklen_t alen;
     int s;
     int flags = 0, error = 0, ret = 0;
     fd_set rset, wset;
diff --git a/libion/ion.c b/libion/ion.c
index 80bdc2a..a79525d 100644
--- a/libion/ion.c
+++ b/libion/ion.c
@@ -117,7 +117,6 @@
 
 int ion_share(int fd, ion_user_handle_t handle, int *share_fd)
 {
-    int map_fd;
     int ret;
     struct ion_fd_data data = {
         .handle = handle,
diff --git a/libion/ion_test.c b/libion/ion_test.c
index 8872282..b7d5583 100644
--- a/libion/ion_test.c
+++ b/libion/ion_test.c
@@ -164,8 +164,9 @@
         printf("master->master? [%10s]\n", ptr);
         if (recvmsg(sd[0], &msg, 0) < 0)
             perror("master recv 1");
+        close(fd);
+        _exit(0);
     } else {
-        struct msghdr msg;
         struct cmsghdr *cmsg;
         char* ptr;
         int fd, recv_fd;
@@ -205,6 +206,7 @@
         strcpy(ptr, "child");
         printf("child sending msg 2\n");
         sendmsg(sd[1], &child_msg, 0);
+        close(fd);
     }
 }
 
diff --git a/liblog/fake_log_device.c b/liblog/fake_log_device.c
index b8d87bb..117e154 100644
--- a/liblog/fake_log_device.c
+++ b/liblog/fake_log_device.c
@@ -320,9 +320,9 @@
     return priorityStrings[idx];
 }
 
-#ifndef HAVE_WRITEV
+#if defined(_WIN32)
 /*
- * Some platforms like WIN32 do not have writev().
+ * WIN32 does not have writev().
  * Make up something to replace it.
  */
 static ssize_t fake_writev(int fd, const struct iovec *iov, int iovcnt) {
diff --git a/liblog/log_read.c b/liblog/log_read.c
index ca5a1a7..2f21a5d 100644
--- a/liblog/log_read.c
+++ b/liblog/log_read.c
@@ -72,7 +72,7 @@
 
     switch (namespaceId) {
     case ANDROID_SOCKET_NAMESPACE_ABSTRACT:
-#ifdef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE
+#if defined(__linux__)
         namelen  = strlen(name);
 
         /* Test with length +1 for the *initial* '\0'. */
@@ -87,7 +87,7 @@
 
         p_addr->sun_path[0] = 0;
         memcpy(p_addr->sun_path + 1, name, namelen);
-#else /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/
+#else
         /* this OS doesn't have the Linux abstract namespace */
 
         namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX);
@@ -99,7 +99,7 @@
 
         strcpy(p_addr->sun_path, FILESYSTEM_SOCKET_PREFIX);
         strcat(p_addr->sun_path, name);
-#endif /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/
+#endif
         break;
 
     case ANDROID_SOCKET_NAMESPACE_RESERVED:
diff --git a/liblog/logprint.c b/liblog/logprint.c
index 9b5a543..5987782 100644
--- a/liblog/logprint.c
+++ b/liblog/logprint.c
@@ -344,15 +344,6 @@
     return -1;
 }
 
-static inline char * strip_end(char *str)
-{
-    char *end = str + strlen(str) - 1;
-
-    while (end >= str && isspace(*end))
-        *end-- = '\0';
-    return str;
-}
-
 /**
  * Splits a wire-format buffer into an AndroidLogEntry
  * entry allocated by caller. Pointers will point directly into buf
diff --git a/liblog/uio.c b/liblog/uio.c
index 24a6507..f77cc49 100644
--- a/liblog/uio.c
+++ b/liblog/uio.c
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef HAVE_SYS_UIO_H
+#if defined(_WIN32)
 
 #include <log/uio.h>
 #include <unistd.h>
@@ -73,4 +73,4 @@
     return total;
 }
 
-#endif /* !HAVE_SYS_UIO_H */
+#endif
diff --git a/libnetutils/dhcp_utils.c b/libnetutils/dhcp_utils.c
index e1df874..0f7c384 100644
--- a/libnetutils/dhcp_utils.c
+++ b/libnetutils/dhcp_utils.c
@@ -166,14 +166,6 @@
     return 0;
 }
 
-static const char *ipaddr_to_string(in_addr_t addr)
-{
-    struct in_addr in_addr;
-
-    in_addr.s_addr = addr;
-    return inet_ntoa(in_addr);
-}
-
 /*
  * Start the dhcp client daemon, and wait for it to finish
  * configuring the interface.
@@ -242,7 +234,6 @@
         return -1;
     }
     if (strcmp(prop_value, "ok") == 0) {
-        char dns_prop_name[PROPERTY_KEY_MAX];
         if (fill_ip_info(interface, ipaddr, gateway, prefixLength, dns,
                 server, lease, vendorInfo, domain, mtu) == -1) {
             return -1;
diff --git a/libnetutils/dhcpclient.c b/libnetutils/dhcpclient.c
index b58120e..700b02f 100644
--- a/libnetutils/dhcpclient.c
+++ b/libnetutils/dhcpclient.c
@@ -150,7 +150,7 @@
 
 void dump_dhcp_info(dhcp_info *info)
 {
-    char addr[20], gway[20], mask[20];
+    char addr[20], gway[20];
     ALOGD("--- dhcp %s (%d) ---",
             dhcp_type_to_name(info->type), info->type);
     strcpy(addr, ipaddr(info->ipaddr));
diff --git a/libnetutils/ifc_utils.c b/libnetutils/ifc_utils.c
index 913f51e..bfe7121 100644
--- a/libnetutils/ifc_utils.c
+++ b/libnetutils/ifc_utils.c
@@ -421,7 +421,6 @@
 
 int ifc_set_hwaddr(const char *name, const void *ptr)
 {
-    int r;
     struct ifreq ifr;
     ifc_init_ifr(name, &ifr);
 
diff --git a/libnetutils/packet.c b/libnetutils/packet.c
index 3cdefb0..a878dd3 100644
--- a/libnetutils/packet.c
+++ b/libnetutils/packet.c
@@ -41,7 +41,7 @@
 
 int open_raw_socket(const char *ifname __attribute__((unused)), uint8_t *hwaddr, int if_index)
 {
-    int s, flag;
+    int s;
     struct sockaddr_ll bindaddr;
 
     if((s = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) {
diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp
index 49f5903..4b09f24 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -20,6 +20,7 @@
 #include <assert.h>
 #include <dirent.h>
 #include <fcntl.h>
+#include <inttypes.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -100,7 +101,7 @@
 
     ctx->buf_len += ret;
     ctx->buf[ctx->buf_len] = 0;
-    SLOGV("Read %d to buffer: %s", ret, ctx->buf);
+    SLOGV("Read %zd to buffer: %s", ret, ctx->buf);
 
     assert(ctx->buf_len <= sizeof(ctx->buf));
 
@@ -251,7 +252,7 @@
 {
     int processes;
     int sleep_us = 100;
-    long startTime = android::uptimeMillis();
+    int64_t startTime = android::uptimeMillis();
 
     while ((processes = killProcessGroupOnce(uid, initialPid, signal)) > 0) {
         SLOGV("killed %d processes for processgroup %d\n", processes, initialPid);
@@ -265,7 +266,7 @@
         }
     }
 
-    SLOGV("Killed process group uid %d pid %d in %ldms, %d procs remain", uid, initialPid,
+    SLOGV("Killed process group uid %d pid %d in %" PRId64 "ms, %d procs remain", uid, initialPid,
             android::uptimeMillis()-startTime, processes);
 
     if (processes == 0) {
@@ -279,12 +280,12 @@
 {
     int ret;
 
-    ret = mkdir(path, 0750);
+    ret = mkdir(path, mode);
     if (ret < 0 && errno != EEXIST) {
         return -errno;
     }
 
-    ret = chown(path, AID_SYSTEM, AID_SYSTEM);
+    ret = chown(path, uid, gid);
     if (ret < 0) {
         ret = -errno;
         rmdir(path);
diff --git a/libsuspend/autosuspend_autosleep.c b/libsuspend/autosuspend_autosleep.c
index 5451615..0d31e74 100644
--- a/libsuspend/autosuspend_autosleep.c
+++ b/libsuspend/autosuspend_autosleep.c
@@ -84,7 +84,6 @@
 
 struct autosuspend_ops *autosuspend_autosleep_init(void)
 {
-    int ret;
     char buf[80];
 
     autosleep_fd = open(SYS_POWER_AUTOSLEEP, O_WRONLY);
diff --git a/libutils/Unicode.cpp b/libutils/Unicode.cpp
index 378d2a7..fb876c9 100644
--- a/libutils/Unicode.cpp
+++ b/libutils/Unicode.cpp
@@ -24,17 +24,10 @@
 # undef  nhtos
 # undef  htons
 
-# ifdef HAVE_LITTLE_ENDIAN
-#  define ntohl(x)    ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
-#  define htonl(x)    ntohl(x)
-#  define ntohs(x)    ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
-#  define htons(x)    ntohs(x)
-# else
-#  define ntohl(x)    (x)
-#  define htonl(x)    (x)
-#  define ntohs(x)    (x)
-#  define htons(x)    (x)
-# endif
+# define ntohl(x)    ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) )
+# define htonl(x)    ntohl(x)
+# define ntohs(x)    ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) )
+# define htons(x)    ntohs(x)
 #else
 # include <netinet/in.h>
 #endif
@@ -47,8 +40,9 @@
 // Surrogates aren't valid for UTF-32 characters, so define some
 // constants that will let us screen them out.
 static const char32_t kUnicodeSurrogateHighStart  = 0x0000D800;
-static const char32_t kUnicodeSurrogateHighEnd    = 0x0000DBFF;
-static const char32_t kUnicodeSurrogateLowStart   = 0x0000DC00;
+// Unused, here for completeness:
+// static const char32_t kUnicodeSurrogateHighEnd = 0x0000DBFF;
+// static const char32_t kUnicodeSurrogateLowStart = 0x0000DC00;
 static const char32_t kUnicodeSurrogateLowEnd     = 0x0000DFFF;
 static const char32_t kUnicodeSurrogateStart      = kUnicodeSurrogateHighStart;
 static const char32_t kUnicodeSurrogateEnd        = kUnicodeSurrogateLowEnd;
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index d5d4700..92150c3 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -193,7 +193,6 @@
 #undef DISALLOW_IMPLICIT_CONSTRUCTORS
 
 static const uint32_t kGPBDDFlagMask = 0x0008;         // mask value that signifies that the entry has a DD
-static const uint32_t kMaxErrorLen = 1024;
 
 // The maximum size of a central directory or a file
 // comment in bytes.
@@ -744,7 +743,7 @@
 // as a side effect of this call.
 static inline ssize_t ReadAtOffset(int fd, uint8_t* buf, size_t len,
                                    off64_t off) {
-#ifdef HAVE_PREAD
+#if !defined(_WIN32)
   return TEMP_FAILURE_RETRY(pread64(fd, buf, len, off));
 #else
   // The only supported platform that doesn't support pread at the moment
@@ -756,7 +755,7 @@
   }
 
   return TEMP_FAILURE_RETRY(read(fd, buf, len));
-#endif  // HAVE_PREAD
+#endif
 }
 
 static int32_t FindEntry(const ZipArchive* archive, const int ent,
diff --git a/lmkd/lmkd.c b/lmkd/lmkd.c
index a534a24..7bbc811 100644
--- a/lmkd/lmkd.c
+++ b/lmkd/lmkd.c
@@ -607,7 +607,6 @@
 static int find_and_kill_process(int other_free, int other_file, bool first)
 {
     int i;
-    int r;
     int min_score_adj = OOM_ADJUST_MAX + 1;
     int minfree = 0;
     int killed_size = 0;
@@ -643,7 +642,6 @@
 }
 
 static void mp_event(uint32_t events __unused) {
-    int i;
     int ret;
     unsigned long long evcount;
     struct sysmeminfo mi;
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index b1412ff..b358485 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -548,7 +548,6 @@
             static const char rotated_log_filename_prefix[] = "log.txt.";
             static const size_t rotated_log_filename_prefix_len =
                 strlen(rotated_log_filename_prefix);
-            static const char total[] = "total ";
             static const char log_filename[] = "log.txt";
 
             if (!strncmp(buffer, rotated_log_filename_prefix, rotated_log_filename_prefix_len)) {
diff --git a/rootdir/etc/init.testmenu b/rootdir/etc/init.testmenu
deleted file mode 100755
index 7ae16d5..0000000
--- a/rootdir/etc/init.testmenu
+++ /dev/null
@@ -1,322 +0,0 @@
-#!/system/bin/sh
-
-atdev=/dev/omap_csmi_tty0
-pppdev=/dev/omap_csmi_tty1
-
-n1=`cat /data/phoneentry1 2>/dev/null`
-n2=`cat /data/phoneentry2 2>/dev/null`
-n3=`cat /data/phoneentry3 2>/dev/null`
-n1=${n1:-"*#06#"}
-n2=${n2:-"*#06#"}
-n3=${n3:-"*#06#"}
-phoneoutputpid=
-eventoutputpid=
-notifypid=
-notifytoggle=false
-pppdpid=
-powerdidletime=120
-
-# map phone specific keys
-setkey -k 0xe4 -v 0x23 # map #
-setkey -k 0xe3 -v 0x2a # map *
-setkey -k 231 -v 513 # map send to newline
-#setkey -k 0x67 -v 0x20b # map up to scroll back
-#setkey -k 0x6c -v 0x20a # map down to scroll forward
-setkey -k 0x73 -v 0x20b # map volume up to scroll back
-setkey -k 0x72 -v 0x20a # map volume down to scroll forward
-setkey -k 0x60 -v 0x211 # map PoC to next console
-
-# tuttle keys
-setkey -k 0x38 -v 0x703 # map leftalt to alt
-setkey -k 0x9b -v 0x703 # map mail to alt
-setkey -t 8 -k 0x9b -v 0x703 # map alt-mail to alt
-setkey -t 8 -k 0x10 -v 0x21 # map alt-q to !
-setkey -t 8 -k 0x11 -v 0x31 # map alt-w to 1
-setkey -t 8 -k 0x12 -v 0x32 # map alt-e to 2
-setkey -t 8 -k 0x13 -v 0x33 # map alt-r to 3
-setkey -t 8 -k 0x14 -v 0x2b # map alt-t to +
-setkey -t 8 -k 0x15 -v 0x28 # map alt-y to (
-setkey -t 8 -k 0x16 -v 0x29 # map alt-u to )
-setkey -t 8 -k 0x17 -v 0x2d # map alt-i to -
-setkey -t 8 -k 0x18 -v 0x5f # map alt-o to _
-setkey -t 8 -k 0x19 -v 0x22 # map alt-p to "
-setkey -t 8 -k 0x1e -v 0x23 # map alt-a to #
-setkey -t 8 -k 0x1f -v 0x34 # map alt-s to 4
-setkey -t 8 -k 0x20 -v 0x35 # map alt-d to 5
-setkey -t 8 -k 0x21 -v 0x36 # map alt-f to 6
-setkey -t 8 -k 0x22 -v 0x2f # map alt-g to /
-setkey -t 8 -k 0x23 -v 0x3f # map alt-h to ?
-setkey -t 8 -k 0x24 -v 0xa3 # map alt-j to pound
-setkey -t 8 -k 0x25 -v 0x24 # map alt-k to $
-setkey -t 8 -k 0x2c -v 0x2a # map alt-z to *
-setkey -t 8 -k 0x2d -v 0x37 # map alt-x to 7
-setkey -t 8 -k 0x2e -v 0x38 # map alt-c to 8
-setkey -t 8 -k 0x2f -v 0x39 # map alt-v to 9
-setkey -t 8 -k 0x30 -v 0x7c # map alt-b to |
-setkey -t 8 -k 0x31 -v 0x40 # map alt-n to @
-setkey -t 8 -k 0x32 -v 0x3d # map alt-m to =
-setkey -t 8 -k 0x33 -v 0x3b # map alt-, to ;
-setkey -t 8 -k 0x34 -v 0x3a # map alt-. to :
-setkey -t 8 -k 0x0f -v 0x30 # map alt-tab to 0
-setkey -t 8 -k 0x67 -v 0x20b # map alt-up to scroll back
-setkey -t 8 -k 0x6c -v 0x20a # map alt-down to scroll forward
-
-while true
-do
-	echo
-	echo "------------------------------"
-	echo " 1: init commands"
-	echo " 2: call commands"
-	echo " 3: misc phone"
-	echo " 4: phone debug output"
-	echo " 5: test data connection"
-	echo " 6: start runtime"
-	echo " 7: start runtime w/output"
-	echo " 8: stop runtime"
-	echo " 9: misc"
-	echo -n ": "
-	while true
-	do
-		c=`readtty -t 50 -f -a 1234567890#`
-		case "$c" in
-			"" ) ;;
-			* ) break;
-		esac
-	done
-	echo Got key -$c-
-	case $c in
-		"1" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Print phone output"
-				echo " 2: ATQ0V1E1+CMEE=2;+CREG=0"
-				echo " 3: AT+CFUN=1"
-				echo " 4: AT+COPS=0"
-				echo " 5: AT+CREG?"
-				echo " 6: Stop phone output"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234560#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) kill $phoneoutputpid; cat $atdev & phoneoutputpid=$! ;;
-					"2" ) echo -e "ATQ0V1E1+CMEE=2;+CREG=0\r" >$atdev;;
-					"3" ) echo -e "AT+CFUN=1\r" >$atdev;;
-					"4" ) echo -e "AT+COPS=0\r" >$atdev;;
-					"5" ) echo -e "AT+CREG?\r" >$atdev;;
-					"6" ) kill $phoneoutputpid; phoneoutputpid= ;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"2" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Dial: ATD $n1;"
-				echo " 2: Dial: ATD $n2;"
-				echo " 3: Dial: ATD $n3;"
-				echo " 4: Set number for 1"
-				echo " 5: Set number for 2"
-				echo " 6: Set number for 3"
-				echo " 7: Dial: ATD ...;"
-				echo " 8: Hang up: ATH"
-				echo " 9: Answer: ATA"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234567890#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) echo "Dialing $n1"; echo -e "ATD $n1;\r" >$atdev;;
-					"2" ) echo "Dialing $n2"; echo -e "ATD $n2;\r" >$atdev;;
-					"3" ) echo "Dialing $n3"; echo -e "ATD $n3;\r" >$atdev;;
-					"4" ) echo -n "Number: "; read n1; echo $n1 >/data/phoneentry1;;
-					"5" ) echo -n "Number: "; read n2; echo $n2 >/data/phoneentry2;;
-					"6" ) echo -n "Number: "; read n3; echo $n3 >/data/phoneentry3;;
-					"7" ) echo -n "Number: "; read n; echo "Dialing $n"; echo -e "ATD $n;\r" >$atdev;;
-					"8" ) echo -e "ATH\r" >$atdev;;
-					"9" ) echo -e "ATA\r" >$atdev;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"3" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Save FFS data"
-				echo " 2: Load user FFS data"
-				echo " 3: Load system FFS data"
-				echo " 4: Reset FFS data"
-				echo " 5: Set uplink gain"
-				echo " 6: Set echo"
-				echo " 7: cat /dev/omap_csmi_battery_t"
-				echo " 8: cat /dev/omap_csmi_htc"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 123456780#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) cat /dev/omap_csmi_ffs >/data/ffsdata;;
-					"2" ) cat /data/ffsdata >/dev/omap_csmi_ffs;;
-					"3" ) cat /system/ffsdata >/dev/omap_csmi_ffs;;
-					"4" ) echo - >/dev/omap_csmi_ffs;;
-					"5" )
-						echo -n "Gain: "; read g;
-						echo gu$g >/tmp/gain;
-						cat /tmp/gain 2>/dev/null >/dev/omap_csmi_audio_tes
-					;;
-					"6" )
-						echo -n "Echo param (hex): "; read e;
-						echo "e0x$e" >/tmp/echo;
-						cat /tmp/echo 2>/dev/null >/dev/omap_csmi_audio_tes
-					;;
-					"7" ) cat /dev/omap_csmi_battery_t;;
-					"8" ) cat /dev/omap_csmi_htc;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"4" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Toggle debug I/O"
-				echo " 2: Toggle debug Flow"
-				echo " 3: Toggle debug Interrupt"
-				echo " 4: Toggle debug Info"
-				echo " 5: Toggle GSM run state"
-				echo " 6: Clear GSM data area"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234560#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) echo -n "i" >/sys/devices/system/omap_csmi/debug;;
-					"2" ) echo -n "f" >/sys/devices/system/omap_csmi/debug;;
-					"3" ) echo -n "I" >/sys/devices/system/omap_csmi/debug;;
-					"4" ) echo -n "F" >/sys/devices/system/omap_csmi/debug;;
-					"5" ) echo -n "s" >/sys/devices/system/omap_csmi/debug;;
-					"6" ) echo -n "c" >/sys/devices/system/omap_csmi/debug;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"5" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Start pppd - userspace"
-				echo " 2: Start pppd - kernel"
-				echo " 3: Start pppd - kernel <at1"
-				echo " 4: Configure ppp data to at2"
-				echo " 5: Test with HTTP GET"
-				echo " 6: Kill pppd"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234560#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) kill $pppdpid; pppd notty < $pppdev > $pppdev & pppdpid=$!;;
-					"2" ) kill $pppdpid; pppd nodetach $pppdev & pppdpid=$!;;
-					"3" ) kill &pppdpid; pppd nodetach $pppdev connect "sh -c \"chat -v -f /etc/ppp/connect-data <$atdev >$atdev\"" & pppdpid=$!;;
-					"4" ) echo -e 'AT%DATA=2,"UART",1,,"SER","UART",0\r' >$atdev;;
-					"5" ) test-data-connection;;
-					"6" ) kill $pppdpid; pppdpid=;;
-					"0" ) break;;
-				esac
-			done
-		;;
-		"6" )
-			echo
-			echo ------------------------
-			echo Starting android runtime
-			echo ------------------------
-			start
-		;;
-		"7" )
-			echo
-			echo ------------------------
-			echo Starting android runtime
-			echo ------------------------
-			if exists /data/singleproc
-			then
-				single_process="-s"
-			else
-				single_process=""
-			fi
-			start runtime $single_process
-		;;
-		"8" )
-			stop
-		;;
-		"9" )
-			while true; do
-				echo
-				echo "------------------------------"
-				echo " 1: Print events"
-				echo " 2: Stop event output"
-				if $notifytoggle
-				then
-					echo " 3: stop notify"
-				else
-					echo " 3: notify /sys/android_power"
-				fi
-				echo " 4: start powerd"
-				echo " 5: start powerd verbose"
-				echo " 6: stop powerd"
-				echo " 7: set powerd idletime ($powerdidletime)"
-				echo " 8: start multitap shell"
-				if exists /data/singleproc
-				then
-					echo " 9: enable multiprocess"
-				else
-					echo " 9: disable multiprocess"
-				fi
-				echo " c: start shell"
-				echo " 0: back"
-				echo -n ": "
-				c=`readtty -f -a 1234567890c#`
-				echo Got key -$c-
-				case "$c" in
-					"1" ) kill $eventoutputpid; getevent & eventoutputpid=$! ;;
-					"2" ) kill $eventoutputpid; eventoutputpid= ;;
-					"3" )
-						if $notifytoggle
-						then
-							kill $notifypid
-							notifypid=
-							notifytoggle=false
-						else
-							kill $notifypid
-							notify -m 0x00000002 -c 0 -p -v 0 -w 30 /sys/android_power &
-							notifypid=$!
-							notifytoggle=true
-						fi
-					;;
-					"4" ) start powerd -i $powerdidletime ;;
-					"5" ) start powerd -i $powerdidletime -v ;;
-					"6" ) stop powerd ;;
-					"7" ) echo -n "Idle time (seconds): "; read powerdidletime ;;
-					"8" )
-						readtty -f -p -t 10 -e "[ ~" | sh -i
-					;;
-					"9" )
-						if exists /data/singleproc
-						then
-							echo "Enabling multiprocess environment."
-							rm /data/singleproc
-						else
-							echo "Disabling multiprocess environment."
-							echo >/data/singleproc "true"
-						fi
-					;;
-					"c" ) sh -i <>/dev/tty0 1>&0 2>&1 ;;
-					"0" ) break;;
-				esac
-			done
-		;;
-	esac
-done
-
diff --git a/sdcard/sdcard.c b/sdcard/sdcard.c
index 9ba81ff..2318978 100644
--- a/sdcard/sdcard.c
+++ b/sdcard/sdcard.c
@@ -1834,7 +1834,7 @@
             "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
             fd, uid, gid);
 
-    res = mount("/dev/fuse", dest_path, "fuse", MS_NOSUID | MS_NODEV, opts);
+    res = mount("/dev/fuse", dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC, opts);
     if (res < 0) {
         ERROR("cannot mount fuse filesystem: %s\n", strerror(errno));
         goto error;
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index 3304e2a..0bb8535 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -52,13 +52,6 @@
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-freebsd/usr.bin/false/false.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=false_main
-LOCAL_MODULE := libtoolbox_false
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
 LOCAL_SRC_FILES := \
     upstream-netbsd/usr.bin/grep/fastgrep.c \
     upstream-netbsd/usr.bin/grep/file.c \
@@ -92,13 +85,6 @@
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/usr.bin/printenv/printenv.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=printenv_main
-LOCAL_MODULE := libtoolbox_printenv
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
 LOCAL_SRC_FILES := upstream-netbsd/bin/rm/rm.c
 LOCAL_CFLAGS += $(common_cflags) -Dmain=rm_main
 LOCAL_MODULE := libtoolbox_rm
@@ -112,27 +98,6 @@
 LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
 include $(BUILD_STATIC_LIBRARY)
 
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/sleep/sleep.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=sleep_main
-LOCAL_MODULE := libtoolbox_sleep
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/sync/sync.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=sync_main
-LOCAL_MODULE := libtoolbox_sync
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-freebsd/usr.bin/true/true.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=true_main
-LOCAL_MODULE := libtoolbox_true
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
 
 include $(CLEAR_VARS)
 
@@ -142,26 +107,19 @@
     cp \
     dd \
     du \
-    false \
     grep \
     kill \
     ln \
     mv \
-    printenv \
     rm \
     rmdir \
-    sleep \
-    sync \
-    true \
 
 OUR_TOOLS := \
     chcon \
     chmod \
-    clear \
     cmp \
     date \
     df \
-    dmesg \
     getenforce \
     getevent \
     getprop \
@@ -170,29 +128,24 @@
     id \
     ifconfig \
     iftop \
-    insmod \
     ioctl \
     ionice \
     load_policy \
     log \
     ls \
-    lsmod \
     lsof \
     md5 \
     mkdir \
     mknod \
-    mkswap \
     mount \
     nandread \
     netstat \
     newfs_msdos \
-    nohup \
     notify \
     ps \
     readlink \
     renice \
     restorecon \
-    rmmod \
     route \
     runcon \
     schedtop \
@@ -203,8 +156,6 @@
     smd \
     start \
     stop \
-    swapoff \
-    swapon \
     top \
     touch \
     umount \
@@ -235,16 +186,14 @@
     libcutils \
     libselinux \
 
-# libusbhost is only used by lsusb, and that isn't usually included in toolbox.
-# The linker strips out all the unused library code in the normal case.
-LOCAL_STATIC_LIBRARIES := \
-    libusbhost \
-
 LOCAL_WHOLE_STATIC_LIBRARIES := $(patsubst %,libtoolbox_%,$(BSD_TOOLS))
 
 LOCAL_MODULE := toolbox
 LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
 
+# Install the symlinks.
+LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,$(ALL_TOOLS),ln -sf toolbox $(TARGET_OUT)/bin/$(t);)
+
 # Including this will define $(intermediates).
 #
 include $(BUILD_EXECUTABLE)
@@ -258,22 +207,6 @@
 $(TOOLS_H):
 	$(transform-generated-source)
 
-# Make symbolic link launchers for each tool.
-SYMLINKS := $(addprefix $(TARGET_OUT)/bin/,$(ALL_TOOLS))
-$(SYMLINKS): TOOLBOX_BINARY := $(LOCAL_MODULE)
-$(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk
-	@echo "Symlink: $@ -> $(TOOLBOX_BINARY)"
-	@mkdir -p $(dir $@)
-	@rm -rf $@
-	$(hide) ln -sf $(TOOLBOX_BINARY) $@
-
-ALL_DEFAULT_INSTALLED_MODULES += $(SYMLINKS)
-
-# We need this so that the installed files could be picked up based on the
-# local module name
-ALL_MODULES.$(LOCAL_MODULE).INSTALLED := \
-    $(ALL_MODULES.$(LOCAL_MODULE).INSTALLED) $(SYMLINKS)
-
 
 # We only want 'r' on userdebug and eng builds.
 include $(CLEAR_VARS)
diff --git a/toolbox/alarm.c b/toolbox/alarm.c
deleted file mode 100644
index 9bd58aa..0000000
--- a/toolbox/alarm.c
+++ /dev/null
@@ -1,190 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <string.h>
-#include <errno.h>
-#include <time.h>
-#include <asm/ioctl.h>
-//#include <linux/rtc.h>
-#include <linux/android_alarm.h>
-
-int alarm_main(int argc, char *argv[])
-{
-	int c;
-    int res;
-	struct tm tm;
-	time_t t;
-	struct timespec ts;
-//	struct rtc_time rtc_time;
-	char strbuf[26];
-	int afd;
-	int nfd;
-//	struct timeval timeout = { 0, 0 };
-    int wait = 0;
-	fd_set rfds;
-	const char wake_lock_id[] = "alarm_test"; 
-	int waitalarmmask = 0;
-
-    int useutc = 0;
-	android_alarm_type_t alarmtype_low = ANDROID_ALARM_RTC_WAKEUP;
-	android_alarm_type_t alarmtype_high = ANDROID_ALARM_RTC_WAKEUP;
-	android_alarm_type_t alarmtype = 0;
-
-    do {
-        //c = getopt(argc, argv, "uw:");
-        c = getopt(argc, argv, "uwat:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'u':
-            useutc = 1;
-            break;
-		case 't':
-			alarmtype_low = alarmtype_high = strtol(optarg, NULL, 0);
-			break;
-		case 'a':
-			alarmtype_low = ANDROID_ALARM_RTC_WAKEUP;
-			alarmtype_high = ANDROID_ALARM_TYPE_COUNT - 1;
-			break;
-        case 'w':
-            //timeout.tv_sec = strtol(optarg, NULL, 0);
-            wait = 1;
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-    if(optind + 2 < argc) {
-        fprintf(stderr,"%s [-uwa] [-t type] [seconds]\n", argv[0]);
-        return 1;
-    }
-
-    afd = open("/dev/alarm", O_RDWR);
-    if(afd < 0) {
-        fprintf(stderr, "Unable to open rtc: %s\n", strerror(errno));
-        return 1;
-    }
-
-    if(optind == argc) {
-		for(alarmtype = alarmtype_low; alarmtype <= alarmtype_high; alarmtype++) {
-			waitalarmmask |= 1U << alarmtype;
-		}
-#if 0
-        res = ioctl(fd, RTC_ALM_READ, &tm);
-        if(res < 0) {
-            fprintf(stderr, "Unable to read alarm: %s\n", strerror(errno));
-			return 1;
-        }
-#endif
-#if 0
-		t = timegm(&tm);
-        if(useutc)
-            gmtime_r(&t, &tm);
-        else
-            localtime_r(&t, &tm);
-#endif
-#if 0
-        asctime_r(&tm, strbuf);
-        printf("%s", strbuf);
-#endif
-    }
-    else if(optind + 1 == argc) {
-#if 0
-        res = ioctl(fd, RTC_RD_TIME, &tm);
-        if(res < 0) {
-            fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno));
-			return 1;
-        }
-        asctime_r(&tm, strbuf);
-        printf("Now: %s", strbuf);
-        time(&tv.tv_sec);
-#endif
-#if 0
-		time(&ts.tv_sec);
-		ts.tv_nsec = 0;
-		
-        //strptime(argv[optind], NULL, &tm);
-        //tv.tv_sec = mktime(&tm);
-        //tv.tv_usec = 0;
-#endif
-		for(alarmtype = alarmtype_low; alarmtype <= alarmtype_high; alarmtype++) {
-			waitalarmmask |= 1U << alarmtype;
-		    res = ioctl(afd, ANDROID_ALARM_GET_TIME(alarmtype), &ts);
-		    if(res < 0) {
-		        fprintf(stderr, "Unable to get current time: %s\n", strerror(errno));
-				return 1;
-		    }
-		    ts.tv_sec += strtol(argv[optind], NULL, 0);
-		    //strtotimeval(argv[optind], &tv);
-			gmtime_r(&ts.tv_sec, &tm);
-		    printf("time %s -> %ld.%09ld\n", argv[optind], ts.tv_sec, ts.tv_nsec);
-		    asctime_r(&tm, strbuf);
-		    printf("Requested %s", strbuf);
-			
-		    res = ioctl(afd, ANDROID_ALARM_SET(alarmtype), &ts);
-		    if(res < 0) {
-		        fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno));
-				return 1;
-		    }
-		}
-#if 0
-        res = ioctl(fd, RTC_ALM_SET, &tm);
-        if(res < 0) {
-            fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno));
-			return 1;
-        }
-        res = ioctl(fd, RTC_AIE_ON);
-        if(res < 0) {
-            fprintf(stderr, "Unable to enable alarm: %s\n", strerror(errno));
-			return 1;
-        }
-#endif
-    }
-    else {
-        fprintf(stderr,"%s [-u] [date]\n", argv[0]);
-        return 1;
-    }
-
-	if(wait) {
-		while(waitalarmmask) {
-			printf("wait for alarm %x\n", waitalarmmask);
-			res = ioctl(afd, ANDROID_ALARM_WAIT);
-			if(res < 0) {
-				fprintf(stderr, "alarm wait failed\n");
-			}
-			printf("got alarm %x\n", res);
-			waitalarmmask &= ~res;
-			nfd = open("/sys/android_power/acquire_full_wake_lock", O_RDWR);
-			write(nfd, wake_lock_id, sizeof(wake_lock_id) - 1);
-			close(nfd);
-			//sleep(5);
-			nfd = open("/sys/android_power/release_wake_lock", O_RDWR);
-			write(nfd, wake_lock_id, sizeof(wake_lock_id) - 1);
-			close(nfd);
-		}
-		printf("done\n");
-	}
-#if 0	
-	FD_ZERO(&rfds);
-	FD_SET(fd, &rfds);
-	res = select(fd + 1, &rfds, NULL, NULL, &timeout);
-    if(res < 0) {
-        fprintf(stderr, "select failed: %s\n", strerror(errno));
-		return 1;
-    }
-	if(res > 0) {
-		int event;
-		read(fd, &event, sizeof(event));
-		fprintf(stderr, "got %x\n", event);
-	}
-	else {
-		fprintf(stderr, "timeout waiting for alarm\n");
-	}
-#endif
-
-    close(afd);
-
-    return 0;
-}
diff --git a/toolbox/clear.c b/toolbox/clear.c
deleted file mode 100644
index df46ad2..0000000
--- a/toolbox/clear.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2012, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <stdio.h>
-
-int clear_main(int argc, char **argv) {
-    /* This prints the clear screen and move cursor to top-left corner control
-     * characters for VT100 terminals. This means it will not work on
-     * non-VT100 compliant terminals, namely Windows' cmd.exe, but should
-     * work on anything unix-y. */
-    fputs("\x1b[2J\x1b[H", stdout);
-    return 0;
-}
diff --git a/toolbox/dmesg.c b/toolbox/dmesg.c
deleted file mode 100644
index 9c73b00..0000000
--- a/toolbox/dmesg.c
+++ /dev/null
@@ -1,58 +0,0 @@
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <errno.h>
-#include <sys/klog.h>
-#include <string.h>
-
-#define FALLBACK_KLOG_BUF_SHIFT	17	/* CONFIG_LOG_BUF_SHIFT from our kernel */
-#define FALLBACK_KLOG_BUF_LEN	(1 << FALLBACK_KLOG_BUF_SHIFT)
-
-int dmesg_main(int argc, char **argv)
-{
-    char *buffer;
-    char *p;
-    ssize_t ret;
-    int n, op, klog_buf_len;
-
-    klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
-
-    if (klog_buf_len <= 0) {
-        klog_buf_len = FALLBACK_KLOG_BUF_LEN;
-    }
-
-    buffer = (char *)malloc(klog_buf_len + 1);
-
-    if (!buffer) {
-        perror("malloc");
-        return EXIT_FAILURE;
-    }
-
-    p = buffer;
-
-    if((argc == 2) && (!strcmp(argv[1],"-c"))) {
-        op = KLOG_READ_CLEAR;
-    } else {
-        op = KLOG_READ_ALL;
-    }
-
-    n = klogctl(op, buffer, klog_buf_len);
-    if (n < 0) {
-        perror("klogctl");
-        return EXIT_FAILURE;
-    }
-    buffer[n] = '\0';
-
-    while((ret = write(STDOUT_FILENO, p, n))) {
-        if (ret == -1) {
-	    if (errno == EINTR)
-                continue;
-	    perror("write");
-	    return EXIT_FAILURE;
-	}
-	p += ret;
-	n -= ret;
-    }
-
-    return 0;
-}
diff --git a/toolbox/exists.c b/toolbox/exists.c
deleted file mode 100644
index e348668..0000000
--- a/toolbox/exists.c
+++ /dev/null
@@ -1,16 +0,0 @@
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-int exists_main(int argc, char *argv[])
-{
-    struct stat s;
-
-    if(argc < 2) return 1;
-
-    if(stat(argv[1], &s)) {
-        return 1;
-    } else {
-        return 0;
-    }
-}
diff --git a/toolbox/insmod.c b/toolbox/insmod.c
deleted file mode 100644
index d252433..0000000
--- a/toolbox/insmod.c
+++ /dev/null
@@ -1,97 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <malloc.h>
-#include <errno.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-extern int init_module(void *, unsigned long, const char *);
-
-static void *read_file(const char *filename, ssize_t *_size)
-{
-	int ret, fd;
-	struct stat sb;
-	ssize_t size;
-	void *buffer = NULL;
-
-	/* open the file */
-	fd = open(filename, O_RDONLY);
-	if (fd < 0)
-		return NULL;
-
-	/* find out how big it is */
-	if (fstat(fd, &sb) < 0)
-		goto bail;
-	size = sb.st_size;
-
-	/* allocate memory for it to be read into */
-	buffer = malloc(size);
-	if (!buffer)
-		goto bail;
-
-	/* slurp it into our buffer */
-	ret = read(fd, buffer, size);
-	if (ret != size)
-		goto bail;
-
-	/* let the caller know how big it is */
-	*_size = size;
-
-bail:
-	close(fd);
-	return buffer;
-}
-
-int insmod_main(int argc, char **argv)
-{
-	void *file;
-	ssize_t size = 0;
-	char opts[1024];
-	int ret;
-
-	/* make sure we've got an argument */
-	if (argc < 2) {
-		fprintf(stderr, "usage: insmod <module.o>\n");
-		return -1;
-	}
-
-	/* read the file into memory */
-	file = read_file(argv[1], &size);
-	if (!file) {
-		fprintf(stderr, "insmod: can't open '%s'\n", argv[1]);
-		return -1;
-	}
-
-	opts[0] = '\0';
-	if (argc > 2) {
-		int i, len;
-		char *end = opts + sizeof(opts) - 1;
-		char *ptr = opts;
-
-		for (i = 2; (i < argc) && (ptr < end); i++) {
-			len = MIN(strlen(argv[i]), (size_t)(end - ptr));
-			memcpy(ptr, argv[i], len);
-			ptr += len;
-			*ptr++ = ' ';
-		}
-		*(ptr - 1) = '\0';
-	}
-
-	/* pass it to the kernel */
-	ret = init_module(file, size, opts);
-	if (ret != 0) {
-		fprintf(stderr,
-                "insmod: init_module '%s' failed (%s)\n",
-                argv[1], strerror(errno));
-	}
-
-	/* free the file buffer */
-	free(file);
-
-	return ret;
-}
-
diff --git a/toolbox/lsmod.c b/toolbox/lsmod.c
deleted file mode 100644
index 8b55ee6..0000000
--- a/toolbox/lsmod.c
+++ /dev/null
@@ -1,10 +0,0 @@
-#include <stdio.h>
-
-extern int cat_main(int argc, char **argv);
-
-int lsmod_main(int argc, char **argv)
-{
-	char *cat_argv[] = { "cat", "/proc/modules", NULL };
-	return cat_main(2, cat_argv);
-}
-
diff --git a/toolbox/lsusb.c b/toolbox/lsusb.c
deleted file mode 100644
index 236e74b..0000000
--- a/toolbox/lsusb.c
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <endian.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdint.h>
-#include <string.h>
-
-#include <usbhost/usbhost.h>
-
-static int verbose = 0;
-static char str_buff[4096];
-
-static const char *get_str(struct usb_device *dev, int id)
-{
-    char *str = usb_device_get_string(dev, id);
-
-    if (id && str) {
-        strlcpy(str_buff, str, sizeof(str_buff));
-        free(str);
-    } else {
-        snprintf(str_buff, sizeof(str_buff), "%02x", id);
-    }
-
-    return str_buff;
-}
-
-
-static void lsusb_parse_device_descriptor(struct usb_device *dev,
-                                          struct usb_device_descriptor *desc)
-{
-    printf("  Device Descriptor\n");
-    printf("\tbcdUSB: %04x\n", letoh16(desc->bcdUSB));
-    printf("\tbDeviceClass: %02x\n", desc->bDeviceClass);
-    printf("\tbDeviceSubClass: %02x\n", desc->bDeviceSubClass);
-    printf("\tbDeviceProtocol: %02x\n", desc->bDeviceProtocol);
-    printf("\tbMaxPacketSize0: %02x\n", desc->bMaxPacketSize0);
-    printf("\tidVendor: %04x\n", letoh16(desc->idVendor));
-    printf("\tidProduct: %04x\n", letoh16(desc->idProduct));
-    printf("\tbcdDevice: %04x\n", letoh16(desc->bcdDevice));
-    printf("\tiManufacturer: %s\n", get_str(dev, desc->iManufacturer));
-    printf("\tiProduct: %s\n", get_str(dev, desc->iProduct));
-    printf("\tiSerialNumber: %s\n", get_str(dev,desc->iSerialNumber));
-    printf("\tbNumConfiguration: %02x\n", desc->bNumConfigurations);
-    printf("\n");
-}
-
-static void lsusb_parse_config_descriptor(struct usb_device *dev,
-                                          struct usb_config_descriptor *desc)
-{
-    printf("  Config Descriptor\n");
-    printf("\twTotalLength: %04x\n", letoh16(desc->wTotalLength));
-    printf("\tbNumInterfaces: %02x\n", desc->bNumInterfaces);
-    printf("\tbConfigurationValue: %02x\n", desc->bConfigurationValue);
-    printf("\tiConfiguration: %s\n", get_str(dev, desc->iConfiguration));
-    printf("\tbmAttributes: %02x\n", desc->bmAttributes);
-    printf("\tbMaxPower: %d mA\n", desc->bMaxPower * 2);
-    printf("\n");
-}
-
-static void lsusb_parse_interface_descriptor(struct usb_device *dev,
-                                             struct usb_interface_descriptor *desc)
-{
-    printf("  Interface Descriptor\n");
-    printf("\tbInterfaceNumber: %02x\n", desc->bInterfaceNumber);
-    printf("\tbAlternateSetting: %02x\n", desc->bAlternateSetting);
-    printf("\tbNumEndpoints: %02x\n", desc->bNumEndpoints);
-    printf("\tbInterfaceClass: %02x\n", desc->bInterfaceClass);
-    printf("\tbInterfaceSubClass: %02x\n", desc->bInterfaceSubClass);
-    printf("\tbInterfaceProtocol: %02x\n", desc->bInterfaceProtocol);
-    printf("\tiInterface: %s\n", get_str(dev, desc->iInterface));
-    printf("\n");
-}
-
-static void lsusb_parse_endpoint_descriptor(struct usb_device *dev,
-                                            struct usb_endpoint_descriptor *desc)
-{
-    printf("  Endpoint Descriptor\n");
-    printf("\tbEndpointAddress: %02x\n", desc->bEndpointAddress);
-    printf("\tbmAttributes: %02x\n", desc->bmAttributes);
-    printf("\twMaxPacketSize: %02x\n", letoh16(desc->wMaxPacketSize));
-    printf("\tbInterval: %02x\n", desc->bInterval);
-    printf("\tbRefresh: %02x\n", desc->bRefresh);
-    printf("\tbSynchAddress: %02x\n", desc->bSynchAddress);
-    printf("\n");
-}
-
-static void lsusb_dump_descriptor(struct usb_device *dev,
-                                  struct usb_descriptor_header *desc)
-{
-    int i;
-    printf("  Descriptor type %02x\n", desc->bDescriptorType);
-
-    for (i = 0; i < desc->bLength; i++ ) {
-        if ((i % 16) == 0)
-            printf("\t%02x:", i);
-        printf(" %02x", ((uint8_t *)desc)[i]);
-        if ((i % 16) == 15)
-            printf("\n");
-    }
-
-    if ((i % 16) != 0)
-        printf("\n");
-    printf("\n");
-}
-
-static void lsusb_parse_descriptor(struct usb_device *dev,
-                                   struct usb_descriptor_header *desc)
-{
-    switch (desc->bDescriptorType) {
-    case USB_DT_DEVICE:
-        lsusb_parse_device_descriptor(dev, (struct usb_device_descriptor *) desc);
-        break;
-
-    case USB_DT_CONFIG:
-        lsusb_parse_config_descriptor(dev, (struct usb_config_descriptor *) desc);
-        break;
-
-    case USB_DT_INTERFACE:
-        lsusb_parse_interface_descriptor(dev, (struct usb_interface_descriptor *) desc);
-        break;
-
-    case USB_DT_ENDPOINT:
-        lsusb_parse_endpoint_descriptor(dev, (struct usb_endpoint_descriptor *) desc);
-        break;
-
-    default:
-        lsusb_dump_descriptor(dev, desc);
-
-        break;
-    }
-}
-
-static int lsusb_device_added(const char *dev_name, void *client_data)
-{
-    struct usb_device *dev = usb_device_open(dev_name);
-
-    if (!dev) {
-        fprintf(stderr, "can't open device %s: %s\n", dev_name, strerror(errno));
-        return 0;
-    }
-
-    if (verbose) {
-        struct usb_descriptor_iter iter;
-        struct usb_descriptor_header *desc;
-
-        printf("%s:\n", dev_name);
-
-        usb_descriptor_iter_init(dev, &iter);
-
-        while ((desc = usb_descriptor_iter_next(&iter)) != NULL)
-            lsusb_parse_descriptor(dev, desc);
-
-    } else {
-        uint16_t vid, pid;
-        char *mfg_name, *product_name, *serial;
-
-        vid = usb_device_get_vendor_id(dev);
-        pid = usb_device_get_product_id(dev);
-        mfg_name = usb_device_get_manufacturer_name(dev);
-        product_name = usb_device_get_product_name(dev);
-        serial = usb_device_get_serial(dev);
-
-        printf("%s: %04x:%04x %s %s %s\n", dev_name, vid, pid,
-               mfg_name, product_name, serial);
-
-        free(mfg_name);
-        free(product_name);
-        free(serial);
-    }
-
-    usb_device_close(dev);
-
-    return 0;
-}
-
-static int lsusb_device_removed(const char *dev_name, void *client_data)
-{
-    return 0;
-}
-
-
-static int lsusb_discovery_done(void *client_data)
-{
-    return 1;
-}
-
-
-
-int lsusb_main(int argc, char **argv)
-{
-    struct usb_host_context *ctx;
-
-    if (argc == 2 && !strcmp(argv[1], "-v"))
-        verbose = 1;
-
-    ctx = usb_host_init();
-    if (!ctx) {
-        perror("usb_host_init:");
-        return 1;
-    }
-
-    usb_host_run(ctx,
-                 lsusb_device_added,
-                 lsusb_device_removed,
-                 lsusb_discovery_done,
-                 NULL);
-
-    usb_host_cleanup(ctx);
-
-    return 0;
-}
-
diff --git a/toolbox/mkswap.c b/toolbox/mkswap.c
deleted file mode 100644
index ad66353..0000000
--- a/toolbox/mkswap.c
+++ /dev/null
@@ -1,91 +0,0 @@
-#include <fcntl.h>
-#include <linux/fs.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <sys/swap.h>
-#include <sys/types.h>
-
-/* This is not in a uapi header. */
-struct linux_swap_header {
-    char            bootbits[1024]; /* Space for disklabel etc. */
-    uint32_t        version;
-    uint32_t        last_page;
-    uint32_t        nr_badpages;
-    unsigned char   sws_uuid[16];
-    unsigned char   sws_volume[16];
-    uint32_t        padding[117];
-    uint32_t        badpages[1];
-};
-
-#define MAGIC_SWAP_HEADER     "SWAPSPACE2"
-#define MAGIC_SWAP_HEADER_LEN 10
-#define MIN_PAGES             10
-
-int mkswap_main(int argc, char **argv)
-{
-    if (argc != 2) {
-        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
-        return EXIT_FAILURE;
-    }
-
-    int fd = open(argv[1], O_RDWR);
-    if (fd < 0) {
-        fprintf(stderr, "Cannot open %s: %s\n", argv[1], strerror(errno));
-        return EXIT_FAILURE;
-    }
-
-    /* Determine the length of the swap file */
-    off64_t swap_size;
-    struct stat sb;
-    if (fstat(fd, &sb)) {
-        fprintf(stderr, "Couldn't fstat file: %s\n", strerror(errno));
-        return EXIT_FAILURE;
-    }
-    if (S_ISBLK(sb.st_mode)) {
-        if (ioctl(fd, BLKGETSIZE64, &swap_size) < 0) {
-            fprintf(stderr, "Couldn't determine block device size: %s\n", strerror(errno));
-            return EXIT_FAILURE;
-        }
-    } else {
-        swap_size = sb.st_size;
-    }
-
-    int pagesize = getpagesize();
-    if (swap_size < MIN_PAGES * pagesize) {
-        fprintf(stderr, "Swap file needs to be at least %d KiB\n", (MIN_PAGES * pagesize) >> 10);
-        return EXIT_FAILURE;
-    }
-
-    struct linux_swap_header sw_hdr;
-    memset(&sw_hdr, 0, sizeof(sw_hdr));
-    sw_hdr.version = 1;
-    sw_hdr.last_page = (swap_size / pagesize) - 1;
-
-    ssize_t len = write(fd, &sw_hdr, sizeof(sw_hdr));
-    if (len != sizeof(sw_hdr)) {
-        fprintf(stderr, "Failed to write swap header into %s: %s\n", argv[1], strerror(errno));
-        return EXIT_FAILURE;
-    }
-
-    /* Write the magic header */
-    if (lseek(fd, pagesize - MAGIC_SWAP_HEADER_LEN, SEEK_SET) < 0) {
-        fprintf(stderr, "Failed to seek into %s: %s\n", argv[1], strerror(errno));
-        return EXIT_FAILURE;
-    }
-
-    len = write(fd, MAGIC_SWAP_HEADER, MAGIC_SWAP_HEADER_LEN);
-    if (len != MAGIC_SWAP_HEADER_LEN) {
-        fprintf(stderr, "Failed to write magic swap header into %s: %s\n", argv[1], strerror(errno));
-        return EXIT_FAILURE;
-    }
-
-    if (fsync(fd) < 0) {
-        fprintf(stderr, "Failed to sync %s: %s\n", argv[1], strerror(errno));
-        return EXIT_FAILURE;
-    }
-
-    close(fd);
-    return EXIT_SUCCESS;
-}
diff --git a/toolbox/nohup.c b/toolbox/nohup.c
deleted file mode 100644
index 363999d..0000000
--- a/toolbox/nohup.c
+++ /dev/null
@@ -1,26 +0,0 @@
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-int nohup_main(int argc, char *argv[])
-{
-    if (argc < 2) {
-        fprintf(stderr, "Usage: %s [-n] program args...\n", argv[0]);
-        return EXIT_FAILURE;
-    }
-    signal(SIGHUP, SIG_IGN);
-    argv++;
-    if (strcmp(argv[0], "-n") == 0) {
-        argv++;
-        signal(SIGINT, SIG_IGN);
-        signal(SIGSTOP, SIG_IGN);
-        signal(SIGTTIN, SIG_IGN);
-        signal(SIGTTOU, SIG_IGN);
-        signal(SIGQUIT, SIG_IGN);
-        signal(SIGTERM, SIG_IGN);
-    }
-    execvp(argv[0], argv);
-    perror(argv[0]);
-    return EXIT_FAILURE;
-}
diff --git a/toolbox/notify.c b/toolbox/notify.c
index c983ed5..8ce346c 100644
--- a/toolbox/notify.c
+++ b/toolbox/notify.c
@@ -101,14 +101,17 @@
 			else if(verbose >= 1)
 		        printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
 			if(print_files && (event->mask & IN_MODIFY)) {
-				char filename[512];
+				char* filename = file_names[event->wd + id_offset];
+				char* alloc_buf = NULL;
 				ssize_t read_len;
 				char *display_name;
 				int buflen;
-				strcpy(filename, file_names[event->wd + id_offset]);
 				if(event->len) {
-					strcat(filename, "/");
-					strcat(filename, event->name);
+					if(asprintf(&alloc_buf, "%s/%s", filename, event->name) < 0) {
+						fprintf(stderr, "asprintf failed, %s\n", strerror(errno));
+						return 1;
+					}
+					filename = alloc_buf;
 				}
 				ffd = open(filename, O_RDONLY);
 				display_name = (verbose >= 2 || event->len == 0) ? filename : event->name;
@@ -132,6 +135,7 @@
 					printf("%s: %s", display_name, buf);
 				}
 				close(ffd);
+				free(alloc_buf);
 			}
 	        if(event_count && --event_count == 0)
 	            return 0;
diff --git a/toolbox/readtty.c b/toolbox/readtty.c
deleted file mode 100644
index 2b27548..0000000
--- a/toolbox/readtty.c
+++ /dev/null
@@ -1,183 +0,0 @@
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/mman.h>
-#include <fcntl.h>
-#include <string.h>
-#include <termios.h>
-#include <unistd.h>
-
-struct {
-    char key;
-    char *chars;
-} map[] = {
-    { '1', "_ -1?!,.:;\"'<=>()_" },
-    { '2', "Cabc2ABC" },
-    { '3', "Fdef3DEF" },
-    { '4', "Ighi4GHI" },
-    { '5', "Ljkl5JKL" },
-    { '6', "Omno6MNO" },
-    { '7', "Spqrs7PQRS" },
-    { '8', "Vtuv8TUV" },
-    { '9', "Zwxyz9WXYZ" },
-    { '0', "*+&0@/#*" },
-};
-
-char next_char(char key, char current)
-{
-    int i;
-    char *next;
-    for(i = 0; i < sizeof(map) / sizeof(map[0]); i++) {
-        if(key == map[i].key) {
-            next = strchr(map[i].chars, current);
-            if(next && next[1])
-                return next[1];
-            return map[i].chars[1];
-        }
-    }
-    return key;
-}
-
-char prev_char(char key, char current)
-{
-    int i;
-    char *next;
-    for(i = 0; i < sizeof(map) / sizeof(map[0]); i++) {
-        if(key == map[i].key) {
-            next = strchr(map[i].chars+1, current);
-            if(next && next[-1])
-                return next[-1];
-            return map[i].chars[1];
-        }
-    }
-    return key;
-}
-
-int readtty_main(int argc, char *argv[])
-{
-    int c;
-    //int flags;
-    char buf[1];
-    int res;
-    struct termios ttyarg;
-    struct termios savedttyarg;
-    int nonblock = 0;
-    int timeout = 0;
-    int flush = 0;
-    int phone = 0;
-    char *accept = NULL;
-    char *rejectstring = NULL;
-    char last_char_in = 0;
-    char current_char = 0;
-    char *exit_string = NULL;
-    int exit_match = 0;
-
-    do {
-        c = getopt(argc, argv, "nt:fa:r:pe:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 't':
-            timeout = atoi(optarg);
-            break;
-        case 'n':
-            nonblock = 1;
-            break;
-        case 'f':
-            flush = 1;
-            break;
-        case 'a':
-            accept = optarg;
-            break;
-        case 'r':
-            rejectstring = optarg;
-            break;
-        case 'p':
-            phone = 1;
-            break;
-        case 'e':
-            exit_string = optarg;
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-
-    if(flush)
-        tcflush(STDIN_FILENO, TCIFLUSH);
-    ioctl(STDIN_FILENO, TCGETS , &savedttyarg) ;       /* set changed tty arguments */
-    ttyarg = savedttyarg;
-    ttyarg.c_cc[VMIN] = (timeout > 0 || nonblock) ? 0 : 1;                /* minimum of 0 chars */
-    ttyarg.c_cc[VTIME] = timeout;              /* wait max 15/10 sec */
-    ttyarg.c_iflag = BRKINT | ICRNL; 
-    ttyarg.c_lflag &= ~(ECHO | ICANON);
-    ioctl(STDIN_FILENO, TCSETS , &ttyarg);
-
-    while (1) {
-        res = read(STDIN_FILENO, buf, 1);
-        if(res <= 0) {
-            if(phone) {
-                if(current_char) {
-                    write(STDERR_FILENO, &current_char, 1);
-                    write(STDOUT_FILENO, &current_char, 1);
-                    if(exit_string && current_char == exit_string[exit_match]) {
-                        exit_match++;
-                        if(exit_string[exit_match] == '\0')
-                            break;
-                    }
-                    else
-                        exit_match = 0;
-                    current_char = 0;
-                }
-                continue;
-            }
-            break;
-        }
-        if(accept && strchr(accept, buf[0]) == NULL) {
-            if(rejectstring) {
-                write(STDOUT_FILENO, rejectstring, strlen(rejectstring));
-                break;
-            }
-            if(flush)
-                tcflush(STDIN_FILENO, TCIFLUSH);
-            continue;
-        }
-        if(phone) {
-            //if(!isprint(buf[0])) {
-            //  fprintf(stderr, "got unprintable character 0x%x\n", buf[0]);
-            //}
-            if(buf[0] == '\0') {
-                if(current_char) {
-                    current_char = prev_char(last_char_in, current_char);
-                    write(STDERR_FILENO, &current_char, 1);
-                    write(STDERR_FILENO, "\b", 1);
-                }
-                continue;
-            }
-            if(current_char && buf[0] != last_char_in) {
-                write(STDERR_FILENO, &current_char, 1);
-                write(STDOUT_FILENO, &current_char, 1);
-                if(exit_string && current_char == exit_string[exit_match]) {
-                    exit_match++;
-                    if(exit_string[exit_match] == '\0')
-                        break;
-                }
-                else
-                    exit_match = 0;
-                current_char = 0;
-            }
-            last_char_in = buf[0];
-            current_char = next_char(last_char_in, current_char);
-            write(STDERR_FILENO, &current_char, 1);
-            write(STDERR_FILENO, "\b", 1);
-            continue;
-        }
-        write(STDOUT_FILENO, buf, 1);
-        break;
-    }
-    ioctl(STDIN_FILENO, TCSETS , &savedttyarg) ;       /* set changed tty arguments */
-
-    return 0;
-}
diff --git a/toolbox/rmmod.c b/toolbox/rmmod.c
deleted file mode 100644
index c7e0d6a..0000000
--- a/toolbox/rmmod.c
+++ /dev/null
@@ -1,53 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <malloc.h>
-#include <errno.h>
-#include <asm/unistd.h>
-
-extern int delete_module(const char *, unsigned int);
-
-int rmmod_main(int argc, char **argv)
-{
-	int ret, i;
-	char *modname, *dot;
-
-	/* make sure we've got an argument */
-	if (argc < 2) {
-		fprintf(stderr, "usage: rmmod <module>\n");
-		return -1;
-	}
-
-	/* if given /foo/bar/blah.ko, make a weak attempt
-	 * to convert to "blah", just for convenience
-	 */
-	modname = strrchr(argv[1], '/');
-	if (!modname)
-		modname = argv[1];
-	else modname++;
-
-	dot = strchr(argv[1], '.');
-	if (dot)
-		*dot = '\0';
-
-	/* Replace "-" with "_". This would keep rmmod
-	 * compatible with module-init-tools version of
-	 * rmmod
-	 */
-	for (i = 0; modname[i] != '\0'; i++) {
-		if (modname[i] == '-')
-			modname[i] = '_';
-	}
-
-	/* pass it to the kernel */
-	ret = delete_module(modname, O_NONBLOCK | O_EXCL);
-	if (ret != 0) {
-		fprintf(stderr, "rmmod: delete_module '%s' failed (errno %d)\n",
-						modname, errno);
-		return -1;
-	}
-
-	return 0;
-}
-
diff --git a/toolbox/rotatefb.c b/toolbox/rotatefb.c
deleted file mode 100644
index 2ff4127..0000000
--- a/toolbox/rotatefb.c
+++ /dev/null
@@ -1,71 +0,0 @@
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/mman.h>
-#include <fcntl.h>
-#include <string.h>
-#include <termios.h>
-#include <unistd.h>
-#include <errno.h>
-#include <linux/fb.h>
-
-
-int rotatefb_main(int argc, char *argv[])
-{
-    int c;
-    char *fbdev = "/dev/graphics/fb0";
-    int rotation = 0;
-    int fd;
-    int res;
-    struct fb_var_screeninfo fbinfo;
-
-    do {
-        c = getopt(argc, argv, "d:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'd':
-            fbdev = optarg;
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-
-    if(optind + 1 != argc) {
-        fprintf(stderr, "%s: specify rotation\n", argv[0]);
-        exit(1);
-    }
-    rotation = atoi(argv[optind]);
-
-    fd = open(fbdev, O_RDWR);
-    if(fd < 0) {
-        fprintf(stderr, "cannot open %s\n", fbdev);
-        return 1;
-    }
-
-    res = ioctl(fd, FBIOGET_VSCREENINFO, &fbinfo);
-    if(res < 0) {
-        fprintf(stderr, "failed to get fbinfo: %s\n", strerror(errno));
-        return 1;
-    }
-    if((fbinfo.rotate ^ rotation) & 1) {
-        unsigned int xres = fbinfo.yres;
-        fbinfo.yres = fbinfo.xres;
-        fbinfo.xres = xres;
-        fbinfo.xres_virtual = fbinfo.xres;
-        fbinfo.yres_virtual = fbinfo.yres * 2;
-        if(fbinfo.yoffset == xres)
-            fbinfo.yoffset = fbinfo.yres;
-    }
-    fbinfo.rotate = rotation; 
-    res = ioctl(fd, FBIOPUT_VSCREENINFO, &fbinfo);
-    if(res < 0) {
-        fprintf(stderr, "failed to set fbinfo: %s\n", strerror(errno));
-        return 1;
-    }
-
-    return 0;
-}
diff --git a/toolbox/setkey.c b/toolbox/setkey.c
deleted file mode 100644
index 1ff2774..0000000
--- a/toolbox/setkey.c
+++ /dev/null
@@ -1,89 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <string.h>
-#include <linux/kd.h>
-#include <linux/vt.h>
-#include <errno.h>
-
-static void setkey_usage(char *argv[])
-{
-    fprintf(stderr, "%s [-t <table>] [-k <index>] [-v value] [-r] [-h]\n"
-            "  -t <table> Select table\n"
-            "  -k <index> Select key\n"
-            "  -v <value> Set entry\n"
-            "  -r         Read current entry\n"
-            "  -h         Print help\n", argv[0]);
-}
-
-#define TTYDEV	"/dev/tty0"
-
-int setkey_main(int argc, char *argv[])
-{
-    int fd;
-    struct kbentry kbe;
-    int did_something = 0;
-
-    kbe.kb_table = 0;
-    kbe.kb_index = -1;
-    kbe.kb_value = 0;
-
-    fd = open(TTYDEV, O_RDWR | O_SYNC);
-    if (fd < 0) {
-        fprintf(stderr, "open %s: %s\n", TTYDEV, strerror(errno));
-        return 1;
-    }
-
-    do {
-        int c, ret;
-
-        c = getopt(argc, argv, "t:k:v:hr");
-        if (c == EOF)
-            break;
-
-        switch (c) {
-        case 't':
-            kbe.kb_table = strtol(optarg, NULL, 0);
-            break;
-        case 'k':
-            kbe.kb_index = strtol(optarg, NULL, 0);
-            break;
-        case 'v':
-            kbe.kb_value = strtol(optarg, NULL, 0);
-            ret = ioctl(fd, KDSKBENT, &kbe);
-            if (ret < 0) {
-                fprintf(stderr, "KDSKBENT %d %d %d failed: %s\n",
-                        kbe.kb_table, kbe.kb_index, kbe.kb_value,
-                        strerror(errno));
-                return 1;
-            }
-            did_something = 1;
-            break;
-        case 'r':
-            ret = ioctl(fd, KDGKBENT, &kbe);
-            if (ret < 0) {
-                fprintf(stderr, "KDGKBENT %d %d  failed: %s\n",
-                        kbe.kb_table, kbe.kb_index, strerror(errno));
-                return 1;
-            }
-            printf("0x%x 0x%x 0x%x\n",
-                   kbe.kb_table, kbe.kb_index, kbe.kb_value);
-            did_something = 1;
-            break;
-        case 'h':
-            setkey_usage(argv);
-            return 1;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            return 1;
-        }
-    } while (1);
-
-    if(optind != argc || !did_something) {
-        setkey_usage(argv);
-        return 1;
-    }
-
-    return 0;
-}
diff --git a/toolbox/swapoff.c b/toolbox/swapoff.c
deleted file mode 100644
index 477494e..0000000
--- a/toolbox/swapoff.c
+++ /dev/null
@@ -1,20 +0,0 @@
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/swap.h>
-
-int swapoff_main(int argc, char **argv)
-{
-    int err = 0;
-
-    if (argc != 2) {
-        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
-        return -EINVAL;
-    }
-
-    err = swapoff(argv[1]);
-    if (err) {
-        fprintf(stderr, "swapoff failed for %s: %s\n", argv[1], strerror(errno));
-    }
-
-    return err;
-}
diff --git a/toolbox/swapon.c b/toolbox/swapon.c
deleted file mode 100644
index 51b4ff1..0000000
--- a/toolbox/swapon.c
+++ /dev/null
@@ -1,66 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <getopt.h>
-#include <sys/swap.h>
-
-static void usage(char *name)
-{
-    fprintf(stderr, "Usage: %s [-p prio] <filename>\n"
-        "        prio must be between 0 and %d\n", name, SWAP_FLAG_PRIO_MASK);
-}
-
-static int parse_prio(char *prio_str)
-{
-    unsigned long p = strtoul(prio_str, NULL, 10);
-
-    return (p > SWAP_FLAG_PRIO_MASK)? -1 : (int)p;
-}
-
-int swapon_main(int argc, char **argv)
-{
-    int err = 0;
-    int flags = 0;
-    int prio;
-
-    opterr = 0;
-    do {
-        int c = getopt(argc, argv, "hp:");
-        if (c == -1)
-            break;
-
-        switch (c) {
-            case 'p':
-                if (optarg != NULL)
-                    prio = parse_prio(optarg);
-                else
-                    prio = -1;
-
-                if (prio < 0) {
-                    usage(argv[0]);
-                    return -EINVAL;
-                }
-                flags |= SWAP_FLAG_PREFER;
-                flags |= (prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK;
-                break;
-            case 'h':
-                usage(argv[0]);
-                return 0;
-            case '?':
-                fprintf(stderr, "unknown option: %c\n", optopt);
-                return -EINVAL;
-        }
-    } while (1);
-
-    if (optind != argc - 1) {
-        usage(argv[0]);
-        return -EINVAL;
-    }
-
-    err = swapon(argv[argc - 1], flags);
-    if (err) {
-        fprintf(stderr, "swapon failed for %s: %s\n", argv[argc - 1], strerror(errno));
-    }
-
-    return err;
-}
diff --git a/toolbox/syren.c b/toolbox/syren.c
deleted file mode 100644
index 47c2460..0000000
--- a/toolbox/syren.c
+++ /dev/null
@@ -1,158 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <malloc.h>
-
-/* ioctl crap */
-#define SYREN_RD		101
-#define SYREN_WR		102
-#define SYREN_OLD_RD	108
-#define SYREN_OLD_WR	109
-
-struct syren_io_args {
-	unsigned long	page;
-	unsigned long	addr;
-	unsigned long	value;
-};
-
-typedef struct {
-	u_char			page;
-	u_char			addr;
-	const char		*name;
-} syren_reg;
-
-static syren_reg registers[] = {
-	{ 0, 0x04, "TOGBR1" },
-	{ 0, 0x05, "TOGBR2" },
-	{ 0, 0x06, "VBDCTRL" },
-	{ 1, 0x07, "VBUCTRL" },
-	{ 1, 0x08, "VBCTRL" },
-	{ 1, 0x09, "PWDNRG" },
-	{ 1, 0x0a, "VBPOP" },
-	{ 1, 0x0b, "VBCTRL2" },
-	{ 1, 0x0f, "VAUDCTRL" },
-	{ 1, 0x10, "VAUSCTRL" },
-	{ 1, 0x11, "VAUOCTRL" },
-	{ 1, 0x12, "VAUDPLL" },
-	{ 1, 0x17, "VRPCSIMR" },
-	{ 0, 0, 0 }
-};
-
-static syren_reg *find_reg(const char *name)
-{
-	int i;
-
-	for (i = 0; registers[i].name != 0; i++) {
-		if (!strcasecmp(registers[i].name, name))
-			return &registers[i];
-	}
-
-	return NULL;
-}
-
-static int usage(void)
-{
-	fprintf(stderr, "usage: syren [r/w] [REGNAME | page:addr] (value)\n");
-	return 1;
-}
-
-int
-syren_main(int argc, char **argv)
-{
-	int cmd = -1;
-	syren_reg *r;
-	struct syren_io_args sio;
-	char name[32];
-	int fd;
-
-	if (argc < 3) {
-		return usage();
-	}
-
-	switch(argv[1][0]) {
-	case 'r':
-		cmd = SYREN_RD;
-		break;
-	case 'w':
-		cmd = SYREN_WR;
-		break;
-	case 'R':
-		cmd = SYREN_OLD_RD;
-		break;
-	case 'W':
-		cmd = SYREN_OLD_WR;
-		break;
-	default:
-		return usage();
-	}
-
-	if (cmd == SYREN_WR || cmd == SYREN_OLD_WR) {
-		if (argc < 4)
-			return usage();
-		sio.value = strtoul(argv[3], 0, 0);
-	}
-
-	fd = open("/dev/eac", O_RDONLY);
-	if (fd < 0) {
-		fprintf(stderr, "can't open /dev/eac\n");
-		return 1;
-	}
-
-	if (strcasecmp(argv[2], "all") == 0) {
-		int i;
-		if (cmd != SYREN_RD && cmd != SYREN_OLD_RD) {
-			fprintf(stderr, "can only read all registers\n");
-			return 1;
-		}
-
-		for (i = 0; registers[i].name; i++) {
-			sio.page = registers[i].page;
-			sio.addr = registers[i].addr;
-			if (ioctl(fd, cmd, &sio) < 0) {
-				fprintf(stderr, "%s: error\n", registers[i].name);
-			} else {
-				fprintf(stderr, "%s: %04x\n", registers[i].name, sio.value);
-			}
-		}
-
-		close(fd);
-		return 0;
-	}
-
-	r = find_reg(argv[2]);
-	if (r == NULL) {
-		if(strlen(argv[2]) >= sizeof(name)){
-			fprintf(stderr, "REGNAME too long\n");
-			return 0;
-		}
-		strlcpy(name, argv[2], sizeof(name));
-		char *addr_str = strchr(argv[2], ':');
-		if (addr_str == NULL)
-			return usage();
-		*addr_str++ = 0;
-		sio.page = strtoul(argv[2], 0, 0);
-		sio.addr = strtoul(addr_str, 0, 0);
-	} else {
-		strlcpy(name, r->name, sizeof(name));
-		sio.page = r->page;
-		sio.addr = r->addr;
-	}
-
-	if (ioctl(fd, cmd, &sio) < 0) {
-		fprintf(stderr, "ioctl(%d) failed\n", cmd);
-		return 1;
-	}
-
-	if (cmd == SYREN_RD || cmd == SYREN_OLD_RD) {
-		printf("%s: %04x\n", name, sio.value);
-	} else {
-		printf("wrote %04x to %s\n", sio.value, name);
-	}
-
-	close(fd);
-
-	return 0;
-}
-
diff --git a/toolbox/upstream-freebsd/usr.bin/false/false.c b/toolbox/upstream-freebsd/usr.bin/false/false.c
deleted file mode 100644
index 99948bc..0000000
--- a/toolbox/upstream-freebsd/usr.bin/false/false.c
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 1988, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 4. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef lint
-static const char copyright[] =
-"@(#) Copyright (c) 1988, 1993\n\
-	The Regents of the University of California.  All rights reserved.\n";
-#endif /* not lint */
-
-#ifndef lint
-static const char sccsid[] = "@(#)false.c	8.1 (Berkeley) 6/6/93";
-#endif /* not lint */
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-int
-main(void)
-{
-	return 1;
-}
diff --git a/toolbox/upstream-freebsd/usr.bin/true/true.c b/toolbox/upstream-freebsd/usr.bin/true/true.c
deleted file mode 100644
index a557f58..0000000
--- a/toolbox/upstream-freebsd/usr.bin/true/true.c
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 1988, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 4. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * $FreeBSD$
- */
-
-#ifndef lint
-static const char copyright[] =
-"@(#) Copyright (c) 1988, 1993\n\
-	The Regents of the University of California.  All rights reserved.\n";
-#endif /* not lint */
-
-#ifndef lint
-static const char sccsid[] = "@(#)true.c	8.1 (Berkeley) 6/9/93";
-#endif /* not lint */
-
-int
-main(void)
-{
-	return 0;
-}
diff --git a/toolbox/upstream-netbsd/bin/sleep/sleep.c b/toolbox/upstream-netbsd/bin/sleep/sleep.c
deleted file mode 100644
index 4349af4..0000000
--- a/toolbox/upstream-netbsd/bin/sleep/sleep.c
+++ /dev/null
@@ -1,159 +0,0 @@
-/* $NetBSD: sleep.c,v 1.24 2011/08/29 14:51:19 joerg Exp $ */
-
-/*
- * Copyright (c) 1988, 1993, 1994
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1988, 1993, 1994\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)sleep.c	8.3 (Berkeley) 4/2/94";
-#else
-__RCSID("$NetBSD: sleep.c,v 1.24 2011/08/29 14:51:19 joerg Exp $");
-#endif
-#endif /* not lint */
-
-#include <ctype.h>
-#include <err.h>
-#include <locale.h>
-#include <math.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-#include <unistd.h>
-
-__dead static void alarmhandle(int);
-__dead static void usage(void);
-
-static volatile sig_atomic_t report_requested;
-static void
-report_request(int signo __unused)
-{
-
-	report_requested = 1;
-}
-
-int
-main(int argc, char *argv[])
-{
-	char *arg, *temp;
-	double fval, ival, val;
-	struct timespec ntime;
-	time_t original;
-	int ch, fracflag, rv;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	(void)signal(SIGALRM, alarmhandle);
-
-	while ((ch = getopt(argc, argv, "")) != -1)
-		switch(ch) {
-		default:
-			usage();
-		}
-	argc -= optind;
-	argv += optind;
-
-	if (argc != 1)
-		usage();
-
-	/*
-	 * Okay, why not just use atof for everything? Why bother
-	 * checking if there is a fraction in use? Because the old
-	 * sleep handled the full range of integers, that's why, and a
-	 * double can't handle a large long. This is fairly useless
-	 * given how large a number a double can hold on most
-	 * machines, but now we won't ever have trouble. If you want
-	 * 1000000000.9 seconds of sleep, well, that's your
-	 * problem. Why use an isdigit() check instead of checking for
-	 * a period? Because doing it this way means locales will be
-	 * handled transparently by the atof code.
-	 */
-	fracflag = 0;
-	arg = *argv;
-	for (temp = arg; *temp != '\0'; temp++)
-		if (!isdigit((unsigned char)*temp))
-			fracflag++;
-
-	if (fracflag) {
-		val = atof(arg);
-		if (val <= 0)
-			usage();
-		ival = floor(val);
-		fval = (1000000000 * (val-ival));
-		ntime.tv_sec = ival;
-		ntime.tv_nsec = fval;
-	}
-	else {
-		ntime.tv_sec = atol(arg);
-		if (ntime.tv_sec <= 0)
-			return EXIT_SUCCESS;
-		ntime.tv_nsec = 0;
-	}
-
-	original = ntime.tv_sec;
-	signal(SIGINFO, report_request);
-	while ((rv = nanosleep(&ntime, &ntime)) != 0) {
-		if (report_requested) {
-		/* Reporting does not bother with nanoseconds. */
-			warnx("about %d second(s) left out of the original %d",
-			(int)ntime.tv_sec, (int)original);
-			report_requested = 0;
-		} else
-			break;
-	}
-
-	if (rv == -1)
-		err(EXIT_FAILURE, "nanosleep failed");
-
-	return EXIT_SUCCESS;
-	/* NOTREACHED */
-}
-
-static void
-usage(void)
-{
-	(void)fprintf(stderr, "usage: %s seconds\n", getprogname());
-	exit(EXIT_FAILURE);
-	/* NOTREACHED */
-}
-
-/* ARGSUSED */
-static void
-alarmhandle(int i)
-{
-	_exit(EXIT_SUCCESS);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/bin/sync/sync.c b/toolbox/upstream-netbsd/bin/sync/sync.c
deleted file mode 100644
index 2b9c367..0000000
--- a/toolbox/upstream-netbsd/bin/sync/sync.c
+++ /dev/null
@@ -1,59 +0,0 @@
-/* $NetBSD: sync.c,v 1.13 2008/07/20 00:52:40 lukem Exp $ */
-
-/*
- * Copyright (c) 1987, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1987, 1993\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)sync.c	8.1 (Berkeley) 5/31/93";
-#else
-__RCSID("$NetBSD: sync.c,v 1.13 2008/07/20 00:52:40 lukem Exp $");
-#endif
-#endif /* not lint */
-
-#include <stdlib.h>
-#include <unistd.h>
-
-int main(int, char *[]);
-
-/* ARGSUSED */
-int
-main(int argc, char *argv[])
-{
-	setprogname(argv[0]);
-	sync();
-	exit(0);
-	/* NOTREACHED */
-}
diff --git a/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c b/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c
deleted file mode 100644
index e15384f..0000000
--- a/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c
+++ /dev/null
@@ -1,102 +0,0 @@
-/*	$NetBSD: printenv.c,v 1.12 2011/09/06 18:26:55 joerg Exp $	*/
-
-/*
- * Copyright (c) 1987, 1993
- *    The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1987, 1993\
- The Regents of the University of California.  All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-/*static char sccsid[] = "from: @(#)printenv.c	8.2 (Berkeley) 5/4/95";*/
-__RCSID("$NetBSD: printenv.c,v 1.12 2011/09/06 18:26:55 joerg Exp $");
-#endif /* not lint */
-
-#include <sys/types.h>
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <err.h>
-
-__dead static void usage(void);
-
-/*
- * printenv
- *
- * Bill Joy, UCB
- * February, 1979
- */
-int
-main(int argc, char *argv[])
-{
-	extern char **environ;
-	char *cp, **ep;
-	size_t len;
-	int ch;
-
-	while ((ch = getopt(argc, argv, "")) != -1)
-		switch(ch) {
-		case '?':
-		default:
-			usage();
-		}
-	argc -= optind;
-	argv += optind;
-
-	if (argc == 0) {
-		for (ep = environ; *ep; ep++)
-			(void)printf("%s\n", *ep);
-		exit(0);
-	}
-	if (argc != 1)
-		usage();
-	if (strchr(*argv, '=') != NULL)
-		errx(1, "Invalid environment variable %s", *argv);
-	len = strlen(*argv);
-	for (ep = environ; *ep; ep++)
-		if (!memcmp(*ep, *argv, len)) {
-			cp = *ep + len;
-			if (!*cp || *cp == '=') {
-				(void)printf("%s\n", *cp ? cp + 1 : cp);
-				exit(0);
-			}
-		}
-	exit(1);
-}
-
-static void
-usage(void)
-{
-	(void)fprintf(stderr, "Usage: printenv [name]\n");
-	exit(1);
-}