Merge "Spell system correctly"
diff --git a/adb/Android.mk b/adb/Android.mk
index 6325e53..740135e 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -57,7 +57,6 @@
 	file_sync_client.c \
 	$(EXTRA_SRCS) \
 	$(USB_SRCS) \
-	shlist.c \
 	utils.c \
 	usb_vendors.c
 
@@ -69,7 +68,7 @@
 endif
 
 LOCAL_CFLAGS += -O2 -g -DADB_HOST=1  -Wall -Wno-unused-parameter
-LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE -DSH_HISTORY
+LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE
 LOCAL_MODULE := adb
 
 LOCAL_STATIC_LIBRARIES := libzipfile libunz $(EXTRA_STATIC_LIBS)
diff --git a/adb/adb.c b/adb/adb.c
index 4655d7c..b1a0e62 100644
--- a/adb/adb.c
+++ b/adb/adb.c
@@ -966,6 +966,105 @@
     return 0;
 }
 
+#if ADB_HOST
+void connect_device(char* host, char* buffer, int buffer_size)
+{
+    int port, fd;
+    char* portstr = strchr(host, ':');
+    char hostbuf[100];
+    char serial[100];
+
+    strncpy(hostbuf, host, sizeof(hostbuf) - 1);
+    if (portstr) {
+        if (portstr - host >= sizeof(hostbuf)) {
+            snprintf(buffer, buffer_size, "bad host name %s", host);
+            return;
+        }
+        // zero terminate the host at the point we found the colon
+        hostbuf[portstr - host] = 0;
+        if (sscanf(portstr + 1, "%d", &port) == 0) {
+            snprintf(buffer, buffer_size, "bad port number %s", portstr);
+            return;
+        }
+    } else {
+        port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
+    }
+
+    snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
+    if (find_transport(serial)) {
+        snprintf(buffer, buffer_size, "already connected to %s", serial);
+        return;
+    }
+
+    fd = socket_network_client(hostbuf, port, SOCK_STREAM);
+    if (fd < 0) {
+        snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
+        return;
+    }
+
+    D("client: connected on remote on fd %d\n", fd);
+    close_on_exec(fd);
+    disable_tcp_nagle(fd);
+    register_socket_transport(fd, serial, port, 0);
+    snprintf(buffer, buffer_size, "connected to %s", serial);
+}
+
+void connect_emulator(char* port_spec, char* buffer, int buffer_size)
+{
+    char* port_separator = strchr(port_spec, ',');
+    if (!port_separator) {
+        snprintf(buffer, buffer_size,
+                "unable to parse '%s' as <console port>,<adb port>",
+                port_spec);
+        return;
+    }
+
+    // Zero-terminate console port and make port_separator point to 2nd port.
+    *port_separator++ = 0;
+    int console_port = strtol(port_spec, NULL, 0);
+    int adb_port = strtol(port_separator, NULL, 0);
+    if (!(console_port > 0 && adb_port > 0)) {
+        *(port_separator - 1) = ',';
+        snprintf(buffer, buffer_size,
+                "Invalid port numbers: Expected positive numbers, got '%s'",
+                port_spec);
+        return;
+    }
+
+    /* Check if the emulator is already known.
+     * Note: There's a small but harmless race condition here: An emulator not
+     * present just yet could be registered by another invocation right
+     * after doing this check here. However, local_connect protects
+     * against double-registration too. From here, a better error message
+     * can be produced. In the case of the race condition, the very specific
+     * error message won't be shown, but the data doesn't get corrupted. */
+    atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
+    if (known_emulator != NULL) {
+        snprintf(buffer, buffer_size,
+                "Emulator on port %d already registered.", adb_port);
+        return;
+    }
+
+    /* Check if more emulators can be registered. Similar unproblematic
+     * race condition as above. */
+    int candidate_slot = get_available_local_transport_index();
+    if (candidate_slot < 0) {
+        snprintf(buffer, buffer_size, "Cannot accept more emulators.");
+        return;
+    }
+
+    /* Preconditions met, try to connect to the emulator. */
+    if (!local_connect_arbitrary_ports(console_port, adb_port)) {
+        snprintf(buffer, buffer_size,
+                "Connected to emulator on ports %d,%d", console_port, adb_port);
+    } else {
+        snprintf(buffer, buffer_size,
+                "Could not connect to emulator on ports %d,%d",
+                console_port, adb_port);
+    }
+}
+#endif
+
 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
 {
     atransport *transport = NULL;
@@ -1023,43 +1122,16 @@
         return 0;
     }
 
-    // add a new TCP transport
+    // add a new TCP transport, device or emulator
     if (!strncmp(service, "connect:", 8)) {
         char buffer[4096];
-        int port, fd;
         char* host = service + 8;
-        char* portstr = strchr(host, ':');
-
-        if (!portstr) {
-            snprintf(buffer, sizeof(buffer), "unable to parse %s as <host>:<port>", host);
-            goto done;
+        if (!strncmp(host, "emu:", 4)) {
+            connect_emulator(host + 4, buffer, sizeof(buffer));
+        } else {
+            connect_device(host, buffer, sizeof(buffer));
         }
-        if (find_transport(host)) {
-            snprintf(buffer, sizeof(buffer), "Already connected to %s", host);
-            goto done;
-        }
-
-        // zero terminate host by overwriting the ':'
-        *portstr++ = 0;
-        if (sscanf(portstr, "%d", &port) == 0) {
-            snprintf(buffer, sizeof(buffer), "bad port number %s", portstr);
-            goto done;
-        }
-
-        fd = socket_network_client(host, port, SOCK_STREAM);
-        if (fd < 0) {
-            snprintf(buffer, sizeof(buffer), "unable to connect to %s:%d", host, port);
-            goto done;
-        }
-
-        D("client: connected on remote on fd %d\n", fd);
-        close_on_exec(fd);
-        disable_tcp_nagle(fd);
-        snprintf(buf, sizeof buf, "%s:%d", host, port);
-        register_socket_transport(fd, buf, port, 0);
-        snprintf(buffer, sizeof(buffer), "connected to %s:%d", host, port);
-
-done:
+        // Send response for emulator and device
         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
         writex(reply_fd, buf, strlen(buf));
         return 0;
@@ -1070,12 +1142,23 @@
         char buffer[4096];
         memset(buffer, 0, sizeof(buffer));
         char* serial = service + 11;
-        atransport *t = find_transport(serial);
-
-        if (t) {
-            unregister_transport(t);
+        if (serial[0] == 0) {
+            // disconnect from all TCP devices
+            unregister_all_tcp_transports();
         } else {
-            snprintf(buffer, sizeof(buffer), "No such device %s", serial);
+            char hostbuf[100];
+            // assume port 5555 if no port is specified
+            if (!strchr(serial, ':')) {
+                snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
+                serial = hostbuf;
+            }
+            atransport *t = find_transport(serial);
+
+            if (t) {
+                unregister_transport(t);
+            } else {
+                snprintf(buffer, sizeof(buffer), "No such device %s", serial);
+            }
         }
 
         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
diff --git a/adb/adb.h b/adb/adb.h
index a2b611e..3d2a77b 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -183,6 +183,7 @@
         /* used to identify transports for clients */
     char *serial;
     char *product;
+    int adb_port; // Use for emulators (local transport)
 
         /* a list of adisconnect callbacks called when the transport is kicked */
     int          kicked;
@@ -262,6 +263,9 @@
 void   kick_transport( atransport*  t );
 
 /* initialize a transport object's func pointers and state */
+#if ADB_HOST
+int get_available_local_transport_index();
+#endif
 int  init_socket_transport(atransport *t, int s, int port, int local);
 void init_usb_transport(atransport *t, usb_handle *usb, int state);
 
@@ -271,8 +275,9 @@
 /* cause new transports to be init'd and added to the list */
 void register_socket_transport(int s, const char *serial, int port, int local);
 
-/* this should only be used for the "adb disconnect" command */
+/* these should only be used for the "adb disconnect" command */
 void unregister_transport(atransport *t);
+void unregister_all_tcp_transports();
 
 void register_usb_transport(usb_handle *h, const char *serial, unsigned writeable);
 
@@ -280,6 +285,9 @@
 void unregister_usb_transport(usb_handle *usb);
 
 atransport *find_transport(const char *serial);
+#if ADB_HOST
+atransport* find_emulator_transport_by_adb_port(int adb_port);
+#endif
 
 int service_to_fd(const char *name);
 #if ADB_HOST
@@ -368,6 +376,7 @@
 
 void local_init(int port);
 int  local_connect(int  port);
+int  local_connect_arbitrary_ports(int console_port, int adb_port);
 
 /* usb host/client interface */
 void usb_init();
diff --git a/adb/commandline.c b/adb/commandline.c
index 8003a64..02e4658 100644
--- a/adb/commandline.c
+++ b/adb/commandline.c
@@ -37,11 +37,6 @@
 #include "adb_client.h"
 #include "file_sync_service.h"
 
-#ifdef SH_HISTORY
-#include "shlist.h"
-#include "history.h"
-#endif
-
 enum {
     IGNORE_DATA,
     WIPE_DATA,
@@ -105,8 +100,12 @@
         "                                 environment variable is used, which must\n"
         "                                 be an absolute path.\n"
         " devices                       - list all connected devices\n"
-        " connect <host>:<port>         - connect to a device via TCP/IP\n"
-        " disconnect <host>:<port>      - disconnect from a TCP/IP device\n"
+        " connect <host>[:<port>]       - connect to a device via TCP/IP\n"
+        "                                 Port 5555 is used by default if no port number is specified.\n"
+        " disconnect [<host>[:<port>]]  - disconnect from a TCP/IP device.\n"
+        "                                 Port 5555 is used by default if no port number is specified.\n"
+        "                                 Using this ocmmand with no additional arguments\n"
+        "                                 will disconnect from all connected TCP/IP devices.\n"
         "\n"
         "device commands:\n"
         "  adb push <local> <remote>    - copy file/dir to device\n"
@@ -232,23 +231,10 @@
     }
 }
 
-#ifdef SH_HISTORY
-int shItemCmp( void *val, void *idata )
-{
-    return( (strcmp( val, idata ) == 0) );
-}
-#endif
-
 static void *stdin_read_thread(void *x)
 {
     int fd, fdi;
     unsigned char buf[1024];
-#ifdef SH_HISTORY
-    unsigned char realbuf[1024], *buf_ptr;
-    SHLIST history;
-    SHLIST *item = &history;
-    int cmdlen = 0, ins_flag = 0;
-#endif
     int r, n;
     int state = 0;
 
@@ -257,9 +243,6 @@
     fdi = fds[1];
     free(fds);
 
-#ifdef SH_HISTORY
-    shListInitList( &history );
-#endif
     for(;;) {
         /* fdi is really the client's stdin, so use read, not adb_read here */
         r = unix_read(fdi, buf, 1024);
@@ -268,97 +251,34 @@
             if(errno == EINTR) continue;
             break;
         }
-#ifdef SH_HISTORY
-        if( (r == 3) &&                                       /* Arrow processing */
-            (memcmp( (void *)buf, SH_ARROW_ANY, 2 ) == 0) ) {
-            switch( buf[2] ) {
-                case SH_ARROW_UP:
-                    item = shListGetNextItem( &history, item );
-                    break;
-                case SH_ARROW_DOWN:
-                    item = shListGetPrevItem( &history, item );
-                    break;
-                default:
-                    item = NULL;
-                    break;
-            }
-            memset( buf, SH_DEL_CHAR, cmdlen );
-            if( item != NULL ) {
-                n = snprintf( (char *)(&buf[cmdlen]), sizeof buf - cmdlen, "%s", (char *)(item->data) );
-                memcpy( realbuf, item->data, n );
-            }
-            else { /* Clean buffer */
-                item = &history;
-                n = 0;
-            }
-            r = n + cmdlen;
-            cmdlen = n;
-            ins_flag = 0;
-            if( r == 0 )
-                continue;
-        }
-        else {
+        for(n = 0; n < r; n++){
+            switch(buf[n]) {
+            case '\n':
+                state = 1;
+                break;
+            case '\r':
+                state = 1;
+                break;
+            case '~':
+                if(state == 1) state++;
+                break;
+            case '.':
+                if(state == 2) {
+                    fprintf(stderr,"\n* disconnect *\n");
+#ifdef HAVE_TERMIO_H
+                    stdin_raw_restore(fdi);
 #endif
-            for(n = 0; n < r; n++){
-                switch(buf[n]) {
-                case '\n':
-#ifdef SH_HISTORY
-                    if( ins_flag && (SH_BLANK_CHAR <= realbuf[0]) ) {
-                        buf_ptr = malloc(cmdlen + 1);
-                        if( buf_ptr != NULL ) {
-                            memcpy( buf_ptr, realbuf, cmdlen );
-                            buf_ptr[cmdlen] = '\0';
-                            if( (item = shListFindItem( &history, (void *)buf_ptr, shItemCmp )) == NULL ) {
-                                shListInsFirstItem( &history, (void *)buf_ptr );
-                                item = &history;
-                            }
-                        }
-                    }
-                    cmdlen = 0;
-                    ins_flag = 0;
-#endif
-                    state = 1;
-                    break;
-                case '\r':
-                    state = 1;
-                    break;
-                case '~':
-                    if(state == 1) state++;
-                    break;
-                case '.':
-                    if(state == 2) {
-                        fprintf(stderr,"\n* disconnect *\n");
-    #ifdef HAVE_TERMIO_H
-                        stdin_raw_restore(fdi);
-    #endif
-                        exit(0);
-                    }
-                default:
-#ifdef SH_HISTORY
-                    if( buf[n] == SH_DEL_CHAR ) {
-                        if( cmdlen > 0 )
-                            cmdlen--;
-                    }
-                    else {
-                        realbuf[cmdlen] = buf[n];
-                        cmdlen++;
-                    }
-                    ins_flag = 1;
-#endif
-                    state = 0;
+                    exit(0);
                 }
+            default:
+                state = 0;
             }
-#ifdef SH_HISTORY
         }
-#endif
         r = adb_write(fd, buf, r);
         if(r <= 0) {
             break;
         }
     }
-#ifdef SH_HISTORY
-    shListDelAllItems( &history, (shListFree)free );
-#endif
     return 0;
 }
 
@@ -877,13 +797,33 @@
         }
     }
 
-    if(!strcmp(argv[0], "connect") || !strcmp(argv[0], "disconnect")) {
+    if(!strcmp(argv[0], "connect")) {
         char *tmp;
         if (argc != 2) {
-            fprintf(stderr, "Usage: adb %s <host>:<port>\n", argv[0]);
+            fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
             return 1;
         }
-        snprintf(buf, sizeof buf, "host:%s:%s", argv[0], argv[1]);
+        snprintf(buf, sizeof buf, "host:connect:%s", argv[1]);
+        tmp = adb_query(buf);
+        if(tmp) {
+            printf("%s\n", tmp);
+            return 0;
+        } else {
+            return 1;
+        }
+    }
+
+    if(!strcmp(argv[0], "disconnect")) {
+        char *tmp;
+        if (argc > 2) {
+            fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
+            return 1;
+        }
+        if (argc == 2) {
+            snprintf(buf, sizeof buf, "host:disconnect:%s", argv[1]);
+        } else {
+            snprintf(buf, sizeof buf, "host:disconnect:");
+        }
         tmp = adb_query(buf);
         if(tmp) {
             printf("%s\n", tmp);
diff --git a/adb/history.h b/adb/history.h
deleted file mode 100755
index ef86ad9..0000000
--- a/adb/history.h
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifndef _HISTORY_H_

-#define _HISTORY_H_

-

-#define SH_ARROW_ANY    "\x1b\x5b"

-#define SH_ARROW_UP     '\x41'

-#define SH_ARROW_DOWN   '\x42'

-#define SH_ARROW_RIGHT  '\x43'

-#define SH_ARROW_LEFT   '\x44'

-#define SH_DEL_CHAR     '\x7F'

-#define SH_BLANK_CHAR   '\x20'

-

-#endif

-

diff --git a/adb/remount_service.c b/adb/remount_service.c
index 26bc841..4cb41e7 100644
--- a/adb/remount_service.c
+++ b/adb/remount_service.c
@@ -30,19 +30,19 @@
 
 static int system_ro = 1;
 
-/* Returns the mount number of the requested partition from /proc/mtd */
-static int find_mount(const char *findme)
+/* Returns the device used to mount a directory in /proc/mounts */
+static char *find_mount(const char *dir)
 {
     int fd;
     int res;
     int size;
     char *token = NULL;
     const char delims[] = "\n";
-    char buf[1024];
+    char buf[4096];
 
-    fd = unix_open("/proc/mtd", O_RDONLY);
+    fd = unix_open("/proc/mounts", O_RDONLY);
     if (fd < 0)
-        return -errno;
+        return NULL;
 
     buf[sizeof(buf) - 1] = '\0';
     size = adb_read(fd, buf, sizeof(buf) - 1);
@@ -51,33 +51,41 @@
     token = strtok(buf, delims);
 
     while (token) {
-        char mtdname[16];
-        int mtdnum, mtdsize, mtderasesize;
+        char mount_dev[256];
+        char mount_dir[256];
+        int mount_freq;
+        int mount_passno;
 
-        res = sscanf(token, "mtd%d: %x %x %15s",
-                     &mtdnum, &mtdsize, &mtderasesize, mtdname);
-
-        if (res == 4 && !strcmp(mtdname, findme))
-            return mtdnum;
+        res = sscanf(token, "%255s %255s %*s %*s %d %d\n",
+                     mount_dev, mount_dir, &mount_freq, &mount_passno);
+        mount_dev[255] = 0;
+        mount_dir[255] = 0;
+        if (res == 4 && (strcmp(dir, mount_dir) == 0))
+            return strdup(mount_dev);
 
         token = strtok(NULL, delims);
     }
-    return -1;
+    return NULL;
 }
 
 /* Init mounts /system as read only, remount to enable writes. */
 static int remount_system()
 {
-    int num;
-    char source[64];
+    char *dev;
+
     if (system_ro == 0) {
         return 0;
     }
-    if ((num = find_mount("\"system\"")) < 0)
+
+    dev = find_mount("/system");
+
+    if (!dev)
         return -1;
 
-    snprintf(source, sizeof source, "/dev/block/mtdblock%d", num);
-    system_ro = mount(source, "/system", "yaffs2", MS_REMOUNT, NULL);
+    system_ro = mount(dev, "/system", "none", MS_REMOUNT, NULL);
+
+    free(dev);
+
     return system_ro;
 }
 
diff --git a/adb/shlist.c b/adb/shlist.c
deleted file mode 100755
index 44919ef..0000000
--- a/adb/shlist.c
+++ /dev/null
@@ -1,185 +0,0 @@
-/*-------------------------------------------------------------------*/
-/*                         List  Functionality                       */
-/*-------------------------------------------------------------------*/
-/* #define SH_LIST_DEBUG */
-/*-------------------------------------------------------------------*/
-#include <stdio.h>
-#include <stdlib.h>
-#include "shlist.h"
-/*-------------------------------------------------------------------*/
-void shListInitList( SHLIST *listPtr )
-{
-  listPtr->data = (void *)0L;
-  listPtr->next = listPtr;
-  listPtr->prev = listPtr;
-}
-
-SHLIST *shListFindItem( SHLIST *head, void *val, shListEqual func )
-{
-  SHLIST *item;
-
-  for(item=head->next;( item != head );item=item->next)
-    if( func ) {
-      if( func( val, item->data ) ) {
-        return( item );
-      }
-    }
-    else {
-      if( item->data == val ) {
-        return( item );
-      }
-    }
-  return( NULL );
-}
-
-SHLIST *shListGetLastItem( SHLIST *head )
-{
-  if( head->prev != head )
-    return( head->prev );
-  return( NULL );
-}
-
-SHLIST *shListGetFirstItem( SHLIST *head )
-{
-  if( head->next != head )
-    return( head->next );
-  return( NULL );
-}
-
-SHLIST *shListGetNItem( SHLIST *head, unsigned long num )
-{
-  SHLIST *item;
-  unsigned long i;
-
-  for(i=0,item=head->next;( (i < num) && (item != head) );i++,item=item->next);
-  if( item != head )
-    return( item );
-  return( NULL );
-}
-
-SHLIST *shListGetNextItem( SHLIST *head, SHLIST *item )
-{
-  if( item == NULL )
-    return( NULL );
-  if( item->next != head )
-    return( item->next );
-  return( NULL );
-}
-
-SHLIST *shListGetPrevItem( SHLIST *head, SHLIST *item )
-{
-  if( item == NULL )
-    return( NULL );
-  if( item->prev != head )
-    return( item->prev );
-  return( NULL );
-}
-
-void shListDelItem( SHLIST *head, SHLIST *item, shListFree func )
-{
-  if( item == NULL )
-    return;
-#ifdef SH_LIST_DEBUG
-  fprintf(stderr, "Del %lx\n", (unsigned long)(item->data));
-#endif
-  (item->prev)->next = item->next;
-  (item->next)->prev = item->prev;
-  if( func && item->data ) {
-    func( (void *)(item->data) );
-  }
-  free( item );
-  head->data = (void *)((unsigned long)(head->data) - 1);
-}
-
-void shListInsFirstItem( SHLIST *head, void *val )
-{ /* Insert to the beginning of the list */
-  SHLIST *item;
-
-  item = (SHLIST *)malloc( sizeof(SHLIST) );
-  if( item == NULL )
-    return;
-  item->data = val;
-  item->next = head->next;
-  item->prev = head;
-  (head->next)->prev = item;
-  head->next = item;
-#ifdef SH_LIST_DEBUG
-  fprintf(stderr, "Ins First %lx\n", (unsigned long)(item->data));
-#endif
-  head->data = (void *)((unsigned long)(head->data) + 1);
-}
-
-void shListInsLastItem( SHLIST *head, void *val )
-{ /* Insert to the end of the list */
-  SHLIST *item;
-
-  item = (SHLIST *)malloc( sizeof(SHLIST) );
-  if( item == NULL )
-    return;
-  item->data = val;
-  item->next = head;
-  item->prev = head->prev;
-  (head->prev)->next = item;
-  head->prev = item;
-#ifdef SH_LIST_DEBUG
-  fprintf(stderr, "Ins Last %lx\n", (unsigned long)(item->data));
-#endif
-  head->data = (void *)((unsigned long)(head->data) + 1);
-}
-
-void shListInsBeforeItem( SHLIST *head, void *val, void *etal, 
-                          shListCmp func )
-{
-  SHLIST *item, *iptr;
-
-  if( func == NULL )
-    shListInsFirstItem( head, val );
-  else {
-    item = (SHLIST *)malloc( sizeof(SHLIST) );
-    if( item == NULL )
-      return;
-    item->data = val;
-    for(iptr=head->next;( iptr != head );iptr=iptr->next)
-      if( func( val, iptr->data, etal ) )
-         break;
-    item->next = iptr;
-    item->prev = iptr->prev;
-    (iptr->prev)->next = item;
-    iptr->prev = item;
-#ifdef SH_LIST_DEBUG
-    fprintf(stderr, "Ins Before %lx\n", (unsigned long)(item->data));
-#endif
-    head->data = (void *)((unsigned long)(head->data) + 1);
-  }
-}
-
-void shListDelAllItems( SHLIST *head, shListFree func )
-{
-  SHLIST *item;
-
-  for(item=head->next;( item != head );) {
-    shListDelItem( head, item, func );
-    item = head->next;
-  }
-  head->data = (void *)0L;
-}
-
-void shListPrintAllItems( SHLIST *head, shListPrint func )
-{
-#ifdef SH_LIST_DEBUG
-  SHLIST *item;
-
-  for(item=head->next;( item != head );item=item->next)
-    if( func ) {
-      func(item->data);
-    }
-    else {
-      fprintf(stderr, "Item: %lx\n",(unsigned long)(item->data));
-    }
-#endif
-}
-
-unsigned long shListGetCount( SHLIST *head )
-{
-  return( (unsigned long)(head->data) );
-}
diff --git a/adb/shlist.h b/adb/shlist.h
deleted file mode 100755
index 0a9b07b..0000000
--- a/adb/shlist.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*-------------------------------------------------------------------*/
-/*                         List  Functionality                       */
-/*-------------------------------------------------------------------*/
-#ifndef _SHLIST_H_
-#define _SHLIST_H_
-
-typedef struct SHLIST_STRUC {
-  void *data;
-  struct SHLIST_STRUC *next;
-  struct SHLIST_STRUC *prev;
-} SHLIST;
-
-typedef int (*shListCmp)( void *valo, void *valn, void *etalon );
-typedef int (*shListPrint)( void *val );
-typedef void (*shListFree)( void *val );
-typedef int (*shListEqual)( void *val,  void *idata );
-
-void shListInitList( SHLIST *listPtr );
-SHLIST *shListFindItem( SHLIST *head, void *val, shListEqual func );
-SHLIST *shListGetFirstItem( SHLIST *head );
-SHLIST *shListGetNItem( SHLIST *head, unsigned long num );
-SHLIST *shListGetLastItem( SHLIST *head );
-SHLIST *shListGetNextItem( SHLIST *head, SHLIST *item );
-SHLIST *shListGetPrevItem( SHLIST *head, SHLIST *item );
-void shListDelItem( SHLIST *head, SHLIST *item, shListFree func );
-void shListInsFirstItem( SHLIST *head, void *val );
-void shListInsBeforeItem( SHLIST *head, void *val, void *etalon, 
-                          shListCmp func );
-void shListInsLastItem( SHLIST *head, void *val );
-void shListDelAllItems( SHLIST *head, shListFree func );
-void shListPrintAllItems( SHLIST *head, shListPrint func );
-unsigned long shListGetCount( SHLIST *head );
-
-#endif
diff --git a/adb/transport.c b/adb/transport.c
index c2877d2..62bdfdb 100644
--- a/adb/transport.c
+++ b/adb/transport.c
@@ -671,21 +671,26 @@
 }
 
 
+static void transport_unref_locked(atransport *t)
+{
+    t->ref_count--;
+    D("transport: %p R- (ref=%d)\n", t, t->ref_count);
+    if (t->ref_count == 0) {
+        D("transport: %p kicking and closing\n", t);
+        if (!t->kicked) {
+            t->kicked = 1;
+            t->kick(t);
+        }
+        t->close(t);
+        remove_transport(t);
+    }
+}
+
 static void transport_unref(atransport *t)
 {
     if (t) {
         adb_mutex_lock(&transport_lock);
-        t->ref_count--;
-        D("transport: %p R- (ref=%d)\n", t, t->ref_count);
-        if (t->ref_count == 0) {
-            D("transport: %p kicking and closing\n", t);
-            if (!t->kicked) {
-                t->kicked = 1;
-                t->kick(t);
-            }
-            t->close(t);
-            remove_transport(t);
-        }
+        transport_unref_locked(t);
         adb_mutex_unlock(&transport_lock);
     }
 }
@@ -894,6 +899,29 @@
     transport_unref(t);
 }
 
+// unregisters all non-emulator TCP transports
+void unregister_all_tcp_transports()
+{
+    atransport *t, *next;
+    adb_mutex_lock(&transport_lock);
+    for (t = transport_list.next; t != &transport_list; t = next) {
+        next = t->next;
+        if (t->type == kTransportLocal && t->adb_port == 0) {
+            t->next->prev = t->prev;
+            t->prev->next = next;
+            // we cannot call kick_transport when holding transport_lock
+            if (!t->kicked)
+            {
+                t->kicked = 1;
+                t->kick(t);
+            }
+            transport_unref_locked(t);
+        }
+     }
+
+    adb_mutex_unlock(&transport_lock);
+}
+
 #endif
 
 void register_usb_transport(usb_handle *usb, const char *serial, unsigned writeable)
diff --git a/adb/transport_local.c b/adb/transport_local.c
index cfd3b4b..8dfc98d 100644
--- a/adb/transport_local.c
+++ b/adb/transport_local.c
@@ -41,9 +41,9 @@
 #endif
 
 #if ADB_HOST
-/* we keep a list of opened transports, transport 0 is bound to 5555,
- * transport 1 to 5557, .. transport n to 5555 + n*2. the list is used
- * to detect when we're trying to connect twice to a given local transport
+/* 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
+ * trying to connect twice to a given local transport.
  */
 #define  ADB_LOCAL_TRANSPORT_MAX  16
 
@@ -102,7 +102,11 @@
 }
 
 
-int  local_connect(int  port)
+int local_connect(int port) {
+    return local_connect_arbitrary_ports(port-1, port);
+}
+
+int local_connect_arbitrary_ports(int console_port, int adb_port)
 {
     char buf[64];
     int  fd = -1;
@@ -110,19 +114,19 @@
 #if ADB_HOST
     const char *host = getenv("ADBHOST");
     if (host) {
-        fd = socket_network_client(host, port, SOCK_STREAM);
+        fd = socket_network_client(host, adb_port, SOCK_STREAM);
     }
 #endif
     if (fd < 0) {
-        fd = socket_loopback_client(port, SOCK_STREAM);
+        fd = socket_loopback_client(adb_port, SOCK_STREAM);
     }
 
     if (fd >= 0) {
         D("client: connected on remote on fd %d\n", fd);
         close_on_exec(fd);
         disable_tcp_nagle(fd);
-        snprintf(buf, sizeof buf, "%s%d", LOCAL_CLIENT_PREFIX, port - 1);
-        register_socket_transport(fd, buf, port, 1);
+        snprintf(buf, sizeof buf, "%s%d", LOCAL_CLIENT_PREFIX, console_port);
+        register_socket_transport(fd, buf, adb_port, 1);
         return 0;
     }
     return -1;
@@ -227,7 +231,50 @@
     adb_close(t->fd);
 }
 
-int init_socket_transport(atransport *t, int s, int port, int local)
+
+#if ADB_HOST
+/* Only call this function if you already hold local_transports_lock. */
+atransport* find_emulator_transport_by_adb_port_locked(int adb_port)
+{
+    int i;
+    for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) {
+        if (local_transports[i] && local_transports[i]->adb_port == adb_port) {
+            return local_transports[i];
+        }
+    }
+    return NULL;
+}
+
+atransport* find_emulator_transport_by_adb_port(int adb_port)
+{
+    adb_mutex_lock( &local_transports_lock );
+    atransport* result = find_emulator_transport_by_adb_port_locked(adb_port);
+    adb_mutex_unlock( &local_transports_lock );
+    return result;
+}
+
+/* Only call this function if you already hold local_transports_lock. */
+int get_available_local_transport_index_locked()
+{
+    int i;
+    for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) {
+        if (local_transports[i] == NULL) {
+            return i;
+        }
+    }
+    return -1;
+}
+
+int get_available_local_transport_index()
+{
+    adb_mutex_lock( &local_transports_lock );
+    int result = get_available_local_transport_index_locked();
+    adb_mutex_unlock( &local_transports_lock );
+    return result;
+}
+#endif
+
+int init_socket_transport(atransport *t, int s, int adb_port, int local)
 {
     int  fail = 0;
 
@@ -239,26 +286,30 @@
     t->sync_token = 1;
     t->connection_state = CS_OFFLINE;
     t->type = kTransportLocal;
+    t->adb_port = 0;
 
 #if ADB_HOST
     if (HOST && local) {
         adb_mutex_lock( &local_transports_lock );
         {
-            int  index = (port - DEFAULT_ADB_LOCAL_TRANSPORT_PORT)/2;
-
-            if (!(port & 1) || index < 0 || index >= ADB_LOCAL_TRANSPORT_MAX) {
-                D("bad local transport port number: %d\n", port);
-                fail = -1;
-            }
-            else if (local_transports[index] != NULL) {
+            t->adb_port = adb_port;
+            atransport* existing_transport =
+                    find_emulator_transport_by_adb_port_locked(adb_port);
+            int index = get_available_local_transport_index_locked();
+            if (existing_transport != NULL) {
                 D("local transport for port %d already registered (%p)?\n",
-                port, local_transports[index]);
+                adb_port, existing_transport);
                 fail = -1;
-            }
-            else
+            } else if (index < 0) {
+                // Too many emulators.
+                D("cannot register more emulators. Maximum is %d\n",
+                        ADB_LOCAL_TRANSPORT_MAX);
+                fail = -1;
+            } else {
                 local_transports[index] = t;
-        }
-        adb_mutex_unlock( &local_transports_lock );
+            }
+       }
+       adb_mutex_unlock( &local_transports_lock );
     }
 #endif
     return fail;
diff --git a/adb/usb_vendors.c b/adb/usb_vendors.c
index 7f3cb54..6d85fb1 100644
--- a/adb/usb_vendors.c
+++ b/adb/usb_vendors.c
@@ -67,6 +67,8 @@
 #define VENDOR_ID_KYOCERA       0x0482
 // Pantech's USB Vendor ID
 #define VENDOR_ID_PANTECH       0x10A9
+// Qualcomm's USB Vendor ID
+#define VENDOR_ID_QUALCOMM      0x05c6
 
 
 /** built-in vendor list */
@@ -87,6 +89,7 @@
     VENDOR_ID_ZTE,
     VENDOR_ID_KYOCERA,
     VENDOR_ID_PANTECH,
+    VENDOR_ID_QUALCOMM,
 };
 
 #define BUILT_IN_VENDOR_COUNT    (sizeof(builtInVendorIds)/sizeof(builtInVendorIds[0]))
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index 24b7c81..535f98c 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -51,6 +51,7 @@
 #define AID_SDCARD_RW     1015  /* external storage write access */
 #define AID_VPN           1016  /* vpn system */
 #define AID_KEYSTORE      1017  /* keystore subsystem */
+#define AID_USB           1018  /* USB devices */
 
 #define AID_SHELL         2000  /* adb and debug shell user */
 #define AID_CACHE         2001  /* cache access */
@@ -100,6 +101,7 @@
     { "sdcard_rw", AID_SDCARD_RW, },
     { "vpn",       AID_VPN, },
     { "keystore",  AID_KEYSTORE, },
+    { "usb",       AID_USB, },
     { "inet",      AID_INET, },
     { "net_raw",   AID_NET_RAW, },
     { "net_admin", AID_NET_ADMIN, },
diff --git a/init/builtins.c b/init/builtins.c
index b4af700..44faf17 100644
--- a/init/builtins.c
+++ b/init/builtins.c
@@ -255,6 +255,7 @@
     const char *name;
     unsigned flag;
 } mount_flags[] = {
+    { "move",       MS_MOVE },
     { "noatime",    MS_NOATIME },
     { "nosuid",     MS_NOSUID },
     { "nodev",      MS_NODEV },
diff --git a/init/devices.c b/init/devices.c
index 1dffcd4..401e254 100644
--- a/init/devices.c
+++ b/init/devices.c
@@ -157,6 +157,7 @@
     { "/dev/ts0710mux",     0640,   AID_RADIO,      AID_RADIO,      1 },
     { "/dev/ppp",           0660,   AID_RADIO,      AID_VPN,        0 },
     { "/dev/tun",           0640,   AID_VPN,        AID_VPN,        0 },
+    { "/dev/bus/usb/",      0660,   AID_ROOT,       AID_USB,        1 },
     { NULL, 0, 0, 0, 0 },
 };
 
@@ -373,6 +374,7 @@
 static void handle_device_event(struct uevent *uevent)
 {
     char devpath[96];
+    int devpath_ready = 0;
     char *base, *name;
     int block;
 
@@ -398,7 +400,26 @@
     } else {
         block = 0;
             /* this should probably be configurable somehow */
-        if(!strncmp(uevent->subsystem, "graphics", 8)) {
+        if (!strncmp(uevent->subsystem, "usb", 3)) {
+            if (!strcmp(uevent->subsystem, "usb")) {
+                /* This imitates the file system that would be created
+                 * if we were using devfs instead.
+                 * Minors are broken up into groups of 128, starting at "001"
+                 */
+                int bus_id = uevent->minor / 128 + 1;
+                int device_id = uevent->minor % 128 + 1;
+                /* build directories */
+                mkdir("/dev/bus", 0755);
+                mkdir("/dev/bus/usb", 0755);
+                snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d", bus_id);
+                mkdir(devpath, 0755);
+                snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d/%03d", bus_id, device_id);
+                devpath_ready = 1;
+            } else {
+                /* ignore other USB events */
+                return;
+            }
+        } else if (!strncmp(uevent->subsystem, "graphics", 8)) {
             base = "/dev/graphics/";
             mkdir(base, 0755);
         } else if (!strncmp(uevent->subsystem, "oncrpc", 6)) {
@@ -428,7 +449,8 @@
             base = "/dev/";
     }
 
-    snprintf(devpath, sizeof(devpath), "%s%s", base, name);
+    if (!devpath_ready)
+        snprintf(devpath, sizeof(devpath), "%s%s", base, name);
 
     if(!strcmp(uevent->action, "add")) {
         make_device(devpath, block, uevent->major, uevent->minor);
diff --git a/liblinenoise/Android.mk b/liblinenoise/Android.mk
new file mode 100644
index 0000000..b32a5f1
--- /dev/null
+++ b/liblinenoise/Android.mk
@@ -0,0 +1,12 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+# Static library
+# ========================================================
+
+include $(CLEAR_VARS)
+LOCAL_MODULE:= liblinenoise
+LOCAL_SRC_FILES := linenoise.c
+
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/liblinenoise/MODULE_LICENSE_BSD_LIKE b/liblinenoise/MODULE_LICENSE_BSD_LIKE
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/liblinenoise/MODULE_LICENSE_BSD_LIKE
diff --git a/liblinenoise/NOTICE b/liblinenoise/NOTICE
new file mode 100644
index 0000000..f61419e
--- /dev/null
+++ b/liblinenoise/NOTICE
@@ -0,0 +1,28 @@
+Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
+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 Redis 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.
\ No newline at end of file
diff --git a/liblinenoise/linenoise.c b/liblinenoise/linenoise.c
new file mode 100644
index 0000000..4f6775c
--- /dev/null
+++ b/liblinenoise/linenoise.c
@@ -0,0 +1,449 @@
+/* linenoise.c -- guerrilla line editing library against the idea that a
+ * line editing lib needs to be 20,000 lines of C code.
+ *
+ * You can find the latest source code at:
+ * 
+ *   http://github.com/antirez/linenoise
+ *
+ * Does a number of crazy assumptions that happen to be true in 99.9999% of
+ * the 2010 UNIX computers around.
+ *
+ * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
+ * 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 Redis 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.
+ *
+ * References:
+ * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
+ * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
+ *
+ * Todo list:
+ * - Switch to gets() if $TERM is something we can't support.
+ * - Filter bogus Ctrl+<char> combinations.
+ * - Win32 support
+ *
+ * Bloat:
+ * - Completion?
+ * - History search like Ctrl+r in readline?
+ *
+ * List of escape sequences used by this program, we do everything just
+ * with three sequences. In order to be so cheap we may have some
+ * flickering effect with some slow terminal, but the lesser sequences
+ * the more compatible.
+ *
+ * CHA (Cursor Horizontal Absolute)
+ *    Sequence: ESC [ n G
+ *    Effect: moves cursor to column n
+ *
+ * EL (Erase Line)
+ *    Sequence: ESC [ n K
+ *    Effect: if n is 0 or missing, clear from cursor to end of line
+ *    Effect: if n is 1, clear from beginning of line to cursor
+ *    Effect: if n is 2, clear entire line
+ *
+ * CUF (CUrsor Forward)
+ *    Sequence: ESC [ n C
+ *    Effect: moves cursor forward of n chars
+ * 
+ */
+
+#include <termios.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#define LINENOISE_MAX_LINE 4096
+static char *unsupported_term[] = {"dumb","cons25",NULL};
+
+static struct termios orig_termios; /* in order to restore at exit */
+static int rawmode = 0; /* for atexit() function to check if restore is needed*/
+static int atexit_registered = 0; /* register atexit just 1 time */
+static int history_max_len = 100;
+static int history_len = 0;
+char **history = NULL;
+
+static void linenoiseAtExit(void);
+int linenoiseHistoryAdd(const char *line);
+
+static int isUnsupportedTerm(void) {
+    char *term = getenv("TERM");
+    int j;
+
+    if (term == NULL) return 0;
+    for (j = 0; unsupported_term[j]; j++)
+        if (!strcasecmp(term,unsupported_term[j])) return 1;
+    return 0;
+}
+
+static void freeHistory(void) {
+    if (history) {
+        int j;
+
+        for (j = 0; j < history_len; j++)
+            free(history[j]);
+        free(history);
+    }
+}
+
+static int enableRawMode(int fd) {
+    struct termios raw;
+
+    if (!isatty(STDIN_FILENO)) goto fatal;
+    if (!atexit_registered) {
+        atexit(linenoiseAtExit);
+        atexit_registered = 1;
+    }
+    if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
+
+    raw = orig_termios;  /* modify the original mode */
+    /* input modes: no break, no CR to NL, no parity check, no strip char,
+     * no start/stop output control. */
+    raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
+    /* output modes - disable post processing */
+    raw.c_oflag &= ~(OPOST);
+    /* control modes - set 8 bit chars */
+    raw.c_cflag |= (CS8);
+    /* local modes - choing off, canonical off, no extended functions,
+     * no signal chars (^Z,^C) */
+    raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
+    /* control chars - set return condition: min number of bytes and timer.
+     * We want read to return every single byte, without timeout. */
+    raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
+
+    /* put terminal in raw mode */
+    if (tcsetattr(fd,TCSADRAIN,&raw) < 0) goto fatal;
+    rawmode = 1;
+    return 0;
+
+fatal:
+    errno = ENOTTY;
+    return -1;
+}
+
+static void disableRawMode(int fd) {
+    /* Don't even check the return value as it's too late. */
+    if (rawmode && tcsetattr(fd,TCSADRAIN,&orig_termios) != -1)
+        rawmode = 0;
+}
+
+/* At exit we'll try to fix the terminal to the initial conditions. */
+static void linenoiseAtExit(void) {
+    disableRawMode(STDIN_FILENO);
+    freeHistory();
+}
+
+static int getColumns(void) {
+    struct winsize ws;
+
+    if (ioctl(1, TIOCGWINSZ, &ws) == -1) return 4096;
+    if (ws.ws_col == 0) {
+        return 4096;
+    }
+    return ws.ws_col;
+}
+
+static int effectiveLen(const char* prompt) {
+    int col = 0;
+    char c;
+    // TODO: Handle escape sequences.
+    while ( (c = *prompt++) != 0 ) {
+        if (c == '\n') {
+            col = 0;
+        } else {
+            col++;
+        }
+    }
+    return col;
+}
+
+static void refreshLine(int fd, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
+    char seq[64];
+    size_t plen = effectiveLen(prompt);
+    
+    while((plen+pos) >= cols) {
+        buf++;
+        len--;
+        pos--;
+    }
+    while (plen+len > cols) {
+        len--;
+    }
+
+    /* Cursor to left edge */
+    snprintf(seq,64,"\x1b[0G");
+    if (write(fd,seq,strlen(seq)) == -1) return;
+    /* Write the prompt and the current buffer content */
+    if (write(fd,prompt,strlen(prompt)) == -1) return;
+    if (write(fd,buf,len) == -1) return;
+    /* Erase to right */
+    snprintf(seq,64,"\x1b[0K");
+    if (write(fd,seq,strlen(seq)) == -1) return;
+    /* Move cursor to original position. */
+    snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen));
+    if (write(fd,seq,strlen(seq)) == -1) return;
+}
+
+static int linenoisePrompt(int fd, char *buf, size_t buflen, const char *prompt) {
+    size_t plen = strlen(prompt);
+    size_t pos = 0;
+    size_t len = 0;
+    size_t cols = getColumns();
+    int history_index = 0;
+
+    buf[0] = '\0';
+    buflen--; /* Make sure there is always space for the nulterm */
+
+    /* The latest history entry is always our current buffer, that
+     * initially is just an empty string. */
+    linenoiseHistoryAdd("");
+    
+    if (write(fd,prompt,plen) == -1) return -1;
+    while(1) {
+        char c;
+        int nread;
+        char seq[2];
+
+        nread = read(fd,&c,1);
+        if (nread <= 0) return len;
+        switch(c) {
+        case 10:    /* line feed. */
+        case 13:    /* enter */
+            history_len--;
+            return len;
+        case 4:     /* ctrl-d */
+            history_len--;
+            return (len == 0) ? -1 : (int)len;
+        case 3:     /* ctrl-c */
+            errno = EAGAIN;
+            return -1;
+        case 127:   /* backspace */
+        case 8:     /* ctrl-h */
+            if (pos > 0 && len > 0) {
+                memmove(buf+pos-1,buf+pos,len-pos);
+                pos--;
+                len--;
+                buf[len] = '\0';
+                refreshLine(fd,prompt,buf,len,pos,cols);
+            }
+            break;
+        case 20:    /* ctrl-t */
+            if (pos > 0 && pos < len) {
+                int aux = buf[pos-1];
+                buf[pos-1] = buf[pos];
+                buf[pos] = aux;
+                if (pos != len-1) pos++;
+                refreshLine(fd,prompt,buf,len,pos,cols);
+            }
+            break;
+        case 2:     /* ctrl-b */
+            goto left_arrow;
+        case 6:     /* ctrl-f */
+            goto right_arrow;
+        case 16:    /* ctrl-p */
+            seq[1] = 65;
+            goto up_down_arrow;
+        case 14:    /* ctrl-n */
+            seq[1] = 66;
+            goto up_down_arrow;
+            break;
+        case 27:    /* escape sequence */
+            if (read(fd,seq,2) == -1) break;
+            if (seq[0] == 91 && seq[1] == 68) {
+left_arrow:
+                /* left arrow */
+                if (pos > 0) {
+                    pos--;
+                    refreshLine(fd,prompt,buf,len,pos,cols);
+                }
+            } else if (seq[0] == 91 && seq[1] == 67) {
+right_arrow:
+                /* right arrow */
+                if (pos != len) {
+                    pos++;
+                    refreshLine(fd,prompt,buf,len,pos,cols);
+                }
+            } else if (seq[0] == 91 && (seq[1] == 65 || seq[1] == 66)) {
+up_down_arrow:
+                /* up and down arrow: history */
+                if (history_len > 1) {
+                    /* Update the current history entry before to
+                     * overwrite it with tne next one. */
+                    free(history[history_len-1-history_index]);
+                    history[history_len-1-history_index] = strdup(buf);
+                    /* Show the new entry */
+                    history_index += (seq[1] == 65) ? 1 : -1;
+                    if (history_index < 0) {
+                        history_index = 0;
+                        break;
+                    } else if (history_index >= history_len) {
+                        history_index = history_len-1;
+                        break;
+                    }
+                    strncpy(buf,history[history_len-1-history_index],buflen);
+                    buf[buflen] = '\0';
+                    len = pos = strlen(buf);
+                    refreshLine(fd,prompt,buf,len,pos,cols);
+                }
+            }
+            break;
+        default:
+            if (len < buflen) {
+                if (len == pos) {
+                    buf[pos] = c;
+                    pos++;
+                    len++;
+                    buf[len] = '\0';
+                    if (plen+len < cols) {
+                        /* Avoid a full update of the line in the
+                         * trivial case. */
+                        if (write(fd,&c,1) == -1) return -1;
+                    } else {
+                        refreshLine(fd,prompt,buf,len,pos,cols);
+                    }
+                } else {
+                    memmove(buf+pos+1,buf+pos,len-pos);
+                    buf[pos] = c;
+                    len++;
+                    pos++;
+                    buf[len] = '\0';
+                    refreshLine(fd,prompt,buf,len,pos,cols);
+                }
+            }
+            break;
+        case 21: /* Ctrl+u, delete the whole line. */
+            buf[0] = '\0';
+            pos = len = 0;
+            refreshLine(fd,prompt,buf,len,pos,cols);
+            break;
+        case 11: /* Ctrl+k, delete from current to end of line. */
+            buf[pos] = '\0';
+            len = pos;
+            refreshLine(fd,prompt,buf,len,pos,cols);
+            break;
+        case 1: /* Ctrl+a, go to the start of the line */
+            pos = 0;
+            refreshLine(fd,prompt,buf,len,pos,cols);
+            break;
+        case 5: /* ctrl+e, go to the end of the line */
+            pos = len;
+            refreshLine(fd,prompt,buf,len,pos,cols);
+            break;
+        }
+    }
+    return len;
+}
+
+static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
+    int fd = STDIN_FILENO;
+    int count;
+
+    if (buflen == 0) {
+        errno = EINVAL;
+        return -1;
+    }
+    if (!isatty(STDIN_FILENO)) {
+        if (fgets(buf, buflen, stdin) == NULL) return -1;
+        count = strlen(buf);
+        if (count && buf[count-1] == '\n') {
+            count--;
+            buf[count] = '\0';
+        }
+    } else {
+        if (enableRawMode(fd) == -1) return -1;
+        count = linenoisePrompt(fd, buf, buflen, prompt);        
+        disableRawMode(fd);
+    }
+    return count;
+}
+
+char *linenoise(const char *prompt) {
+    char buf[LINENOISE_MAX_LINE];
+    int count;
+
+    if (isUnsupportedTerm()) {
+        size_t len;
+
+        printf("%s",prompt);
+        fflush(stdout);
+        if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
+        len = strlen(buf);
+        while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
+            len--;
+            buf[len] = '\0';
+        }
+        return strdup(buf);
+    } else {
+        count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
+        if (count == -1) return NULL;
+        return strdup(buf);
+    }
+}
+
+/* Using a circular buffer is smarter, but a bit more complex to handle. */
+int linenoiseHistoryAdd(const char *line) {
+    char *linecopy;
+
+    if (history_max_len == 0) return 0;
+    if (history == 0) {
+        history = malloc(sizeof(char*)*history_max_len);
+        if (history == NULL) return 0;
+        memset(history,0,(sizeof(char*)*history_max_len));
+    }
+    linecopy = strdup(line);
+    if (!linecopy) return 0;
+    if (history_len == history_max_len) {
+        memmove(history,history+1,sizeof(char*)*(history_max_len-1));
+        history_len--;
+    }
+    history[history_len] = linecopy;
+    history_len++;
+    return 1;
+}
+
+int linenoiseHistorySetMaxLen(int len) {
+    char **new;
+
+    if (len < 1) return 0;
+    if (history) {
+        int tocopy = history_len;
+
+        new = malloc(sizeof(char*)*len);
+        if (new == NULL) return 0;
+        if (len < tocopy) tocopy = len;
+        memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
+        free(history);
+        history = new;
+    }
+    history_max_len = len;
+    if (history_len > history_max_len)
+        history_len = history_max_len;
+    return 1;
+}
diff --git a/liblinenoise/linenoise.h b/liblinenoise/linenoise.h
new file mode 100644
index 0000000..57bf9d1
--- /dev/null
+++ b/liblinenoise/linenoise.h
@@ -0,0 +1,41 @@
+/* linenoise.h -- guerrilla line editing library against the idea that a
+ * line editing lib needs to be 20,000 lines of C code.
+ *
+ * See linenoise.c for more information.
+ *
+ * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
+ * 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 Redis 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.
+ */
+
+#ifndef __LINENOISE_H
+#define __LINENOISE_H
+
+char *linenoise(const char *prompt);
+int linenoiseHistoryAdd(const char *line);
+int linenoiseHistorySetMaxLen(int len);
+
+#endif /* __LINENOISE_H */
diff --git a/sh/Android.mk b/sh/Android.mk
index 09bb6ac..b5e5c38 100644
--- a/sh/Android.mk
+++ b/sh/Android.mk
@@ -31,7 +31,11 @@
 
 LOCAL_MODULE:= sh
 
-LOCAL_CFLAGS += -DSHELL
+LOCAL_CFLAGS += -DSHELL -DWITH_LINENOISE
+
+LOCAL_STATIC_LIBRARIES := liblinenoise
+
+LOCAL_C_INCLUDES += system/core/liblinenoise
 
 make_ash_files: PRIVATE_SRC_FILES := $(SRC_FILES)
 make_ash_files: PRIVATE_CFLAGS := $(LOCAL_CFLAGS)
diff --git a/sh/input.c b/sh/input.c
index a81fd7b..056ee8b 100644
--- a/sh/input.c
+++ b/sh/input.c
@@ -64,6 +64,10 @@
 #include "parser.h"
 #include "myhistedit.h"
 
+#ifdef WITH_LINENOISE
+#include "linenoise.h"
+#endif
+
 #define EOF_NLEFT -99		/* value of parsenleft when EOF pushed back */
 
 MKINIT
@@ -171,6 +175,9 @@
 	return pgetc_macro();
 }
 
+int in_interactive_mode() {
+    return parsefile != NULL && parsefile->fd == 0;
+}
 
 static int
 preadfd(void)
@@ -203,6 +210,45 @@
 
 	} else
 #endif
+#ifdef WITH_LINENOISE
+    if (parsefile->fd == 0) {
+        static char *rl_start;
+        static const char *rl_cp;
+        static int el_len;
+
+        if (rl_cp == NULL) {
+            rl_cp = rl_start = linenoise(getprompt(""));
+            if (rl_cp != NULL) {
+                el_len = strlen(rl_start);
+                if (el_len != 0) {
+                    /* Add non-blank lines to history. */
+                    linenoiseHistoryAdd(rl_start);
+                }
+                out2str("\n");
+                /* Client expects a newline at end of input, doesn't expect null */
+                rl_start[el_len++] = '\n';
+            }
+        }
+        if (rl_cp == NULL)
+            nr = 0;
+        else {
+            nr = el_len;
+            if (nr > BUFSIZ - 8)
+                nr = BUFSIZ - 8;
+            memcpy(buf, rl_cp, nr);
+            if (nr != el_len) {
+                el_len -= nr;
+                rl_cp += nr;
+            } else {
+                rl_cp = 0;
+                if (rl_start != NULL) {
+                    free(rl_start);
+                    rl_start = NULL;
+                }
+            }
+        }
+    } else
+#endif
 		nr = read(parsefile->fd, buf, BUFSIZ - 8);
 
 
diff --git a/sh/input.h b/sh/input.h
index a9d3a12..99c1b77 100644
--- a/sh/input.h
+++ b/sh/input.h
@@ -46,6 +46,7 @@
 extern char *parsenextc;	/* next character in input buffer */
 extern int init_editline;	/* 0 == not setup, 1 == OK, -1 == failed */
 
+int in_interactive_mode();
 char *pfgets(char *, int);
 int pgetc(void);
 int preadbuffer(void);
diff --git a/sh/parser.c b/sh/parser.c
index 67de58e..faf0268 100644
--- a/sh/parser.c
+++ b/sh/parser.c
@@ -1628,6 +1628,9 @@
 #ifdef WITH_HISTORY
 	if (!el)
 #endif
+#ifdef WITH_LINENOISE
+        if (! in_interactive_mode() )
+#endif
 		out2str(getprompt(NULL));
 }
 
diff --git a/sh/trap.c b/sh/trap.c
index b3b2db4..7cb5201 100644
--- a/sh/trap.c
+++ b/sh/trap.c
@@ -60,20 +60,6 @@
 #include "mystring.h"
 #include "var.h"
 
-static const char *sys_signame[NSIG] = {
-	"Unused",
-	"HUP",      "INT",    "QUIT",    "ILL",
-	"TRAP",     "ABRT",   "BUS",     "FPE",
-	"KILL",     "USR1",   "SEGV",    "USR2",
-	"PIPE",     "ALRM",   "TERM",
-	"Unknown",
-	"CHLD",
-	"CONT",     "STOP",   "TSTP",    "TTIN",
-	"TTOU",     "URG",    "XCPU",    "XFSZ",
-	"VTALRM",   "PROF",   "WINCH",   "IO",
-	"PWR",      "SYS"
-};
-
 /*
  * Sigmode records the current value of the signal handlers for the various
  * modes.  A value of zero means that the current handler is not known.
diff --git a/toolbox/route.c b/toolbox/route.c
index 4f66201..107e48a 100644
--- a/toolbox/route.c
+++ b/toolbox/route.c
@@ -61,7 +61,7 @@
         if (!strcmp(argv[2], "default")) {
             /* route add default dev wlan0 */
             if (argc > 4 && !strcmp(argv[3], "dev")) {
-                rt.rt_flags = RTF_UP | RTF_HOST;
+                rt.rt_flags = RTF_UP;
                 rt.rt_dev = argv[4];
                 errno = 0;
                 goto apply;