Merge "Revert "android_ids: move to bionic""
diff --git a/adb/adb_trace.h b/adb/adb_trace.h
index 5206a99..aaffa29 100644
--- a/adb/adb_trace.h
+++ b/adb/adb_trace.h
@@ -58,4 +58,8 @@
 void adb_trace_init(char**);
 void adb_trace_enable(AdbTrace trace_tag);
 
+#define ATRACE_TAG ATRACE_TAG_ADB
+#include <cutils/trace.h>
+#include <utils/Trace.h>
+
 #endif /* __ADB_TRACE_H */
diff --git a/adb/file_sync_service.cpp b/adb/file_sync_service.cpp
index 43c877e..e667bf8 100644
--- a/adb/file_sync_service.cpp
+++ b/adb/file_sync_service.cpp
@@ -39,10 +39,13 @@
 
 #include "adb.h"
 #include "adb_io.h"
+#include "adb_trace.h"
 #include "adb_utils.h"
 #include "security_log_tags.h"
 #include "sysdeps/errno.h"
 
+using android::base::StringPrintf;
+
 static bool should_use_fs_config(const std::string& path) {
     // TODO: use fs_config to configure permissions on /data.
     return android::base::StartsWith(path, "/system/") ||
@@ -152,7 +155,7 @@
     if (!d) goto done;
 
     while ((de = readdir(d.get()))) {
-        std::string filename(android::base::StringPrintf("%s/%s", path, de->d_name));
+        std::string filename(StringPrintf("%s/%s", path, de->d_name));
 
         struct stat st;
         if (lstat(filename.c_str(), &st) == 0) {
@@ -191,7 +194,7 @@
 }
 
 static bool SendSyncFailErrno(int fd, const std::string& reason) {
-    return SendSyncFail(fd, android::base::StringPrintf("%s: %s", reason.c_str(), strerror(errno)));
+    return SendSyncFail(fd, StringPrintf("%s: %s", reason.c_str(), strerror(errno)));
 }
 
 static bool handle_send_file(int s, const char* path, uid_t uid, gid_t gid, uint64_t capabilities,
@@ -433,9 +436,31 @@
     return WriteFdExactly(s, &msg.data, sizeof(msg.data));
 }
 
+static const char* sync_id_to_name(uint32_t id) {
+  switch (id) {
+    case ID_LSTAT_V1:
+      return "lstat_v1";
+    case ID_LSTAT_V2:
+      return "lstat_v2";
+    case ID_STAT_V2:
+      return "stat_v2";
+    case ID_LIST:
+      return "list";
+    case ID_SEND:
+      return "send";
+    case ID_RECV:
+      return "recv";
+    case ID_QUIT:
+        return "quit";
+    default:
+        return "???";
+  }
+}
+
 static bool handle_sync_command(int fd, std::vector<char>& buffer) {
     D("sync: waiting for request");
 
+    ATRACE_CALL();
     SyncRequest request;
     if (!ReadFdExactly(fd, &request, sizeof(request))) {
         SendSyncFail(fd, "command read failure");
@@ -453,9 +478,11 @@
     }
     name[path_length] = 0;
 
-    const char* id = reinterpret_cast<const char*>(&request.id);
-    D("sync: '%.4s' '%s'", id, name);
+    std::string id_name = sync_id_to_name(request.id);
+    std::string trace_name = StringPrintf("%s(%s)", id_name.c_str(), name);
+    ATRACE_NAME(trace_name.c_str());
 
+    D("sync: %s('%s')", id_name.c_str(), name);
     switch (request.id) {
         case ID_LSTAT_V1:
             if (!do_lstat_v1(fd, name)) return false;
@@ -476,8 +503,7 @@
         case ID_QUIT:
             return false;
         default:
-            SendSyncFail(
-                fd, android::base::StringPrintf("unknown command '%.4s' (%08x)", id, request.id));
+            SendSyncFail(fd, StringPrintf("unknown command %08x", request.id));
             return false;
     }
 
diff --git a/adb/transport.cpp b/adb/transport.cpp
index 7b82b19..60f3b5c 100644
--- a/adb/transport.cpp
+++ b/adb/transport.cpp
@@ -37,6 +37,7 @@
 
 #include "adb.h"
 #include "adb_auth.h"
+#include "adb_trace.h"
 #include "adb_utils.h"
 #include "diagnose_usb.h"
 
@@ -52,16 +53,15 @@
 const char* const kFeatureStat2 = "stat_v2";
 
 static std::string dump_packet(const char* name, const char* func, apacket* p) {
-    unsigned  command = p->msg.command;
-    int       len     = p->msg.data_length;
-    char      cmd[9];
-    char      arg0[12], arg1[12];
-    int       n;
+    unsigned command = p->msg.command;
+    int len = p->msg.data_length;
+    char cmd[9];
+    char arg0[12], arg1[12];
+    int n;
 
     for (n = 0; n < 4; n++) {
-        int  b = (command >> (n*8)) & 255;
-        if (b < 32 || b >= 127)
-            break;
+        int b = (command >> (n * 8)) & 255;
+        if (b < 32 || b >= 127) break;
         cmd[n] = (char)b;
     }
     if (n == 4) {
@@ -82,25 +82,24 @@
     else
         snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
 
-    std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ",
-                                                     name, func, cmd, arg0, arg1, len);
+    std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
+                                                     func, cmd, arg0, arg1, len);
     result += dump_hex(p->data, len);
     return result;
 }
 
-static int
-read_packet(int  fd, const char* name, apacket** ppacket)
-{
+static int read_packet(int fd, const char* name, apacket** ppacket) {
+    ATRACE_NAME("read_packet");
     char buff[8];
     if (!name) {
         snprintf(buff, sizeof buff, "fd=%d", fd);
         name = buff;
     }
-    char* p = reinterpret_cast<char*>(ppacket);  /* really read a packet address */
+    char* p = reinterpret_cast<char*>(ppacket); /* really read a packet address */
     int len = sizeof(apacket*);
-    while(len > 0) {
+    while (len > 0) {
         int r = adb_read(fd, p, len);
-        if(r > 0) {
+        if (r > 0) {
             len -= r;
             p += r;
         } else {
@@ -113,20 +112,19 @@
     return 0;
 }
 
-static int
-write_packet(int  fd, const char* name, apacket** ppacket)
-{
+static int write_packet(int fd, const char* name, apacket** ppacket) {
+    ATRACE_NAME("write_packet");
     char buff[8];
     if (!name) {
         snprintf(buff, sizeof buff, "fd=%d", fd);
         name = buff;
     }
     VLOG(TRANSPORT) << dump_packet(name, "to remote", *ppacket);
-    char* p = reinterpret_cast<char*>(ppacket);  /* we really write the packet address */
+    char* p = reinterpret_cast<char*>(ppacket); /* we really write the packet address */
     int len = sizeof(apacket*);
-    while(len > 0) {
+    while (len > 0) {
         int r = adb_write(fd, p, len);
-        if(r > 0) {
+        if (r > 0) {
             len -= r;
             p += r;
         } else {
@@ -137,16 +135,15 @@
     return 0;
 }
 
-static void transport_socket_events(int fd, unsigned events, void *_t)
-{
-    atransport *t = reinterpret_cast<atransport*>(_t);
+static void transport_socket_events(int fd, unsigned events, void* _t) {
+    atransport* t = reinterpret_cast<atransport*>(_t);
     D("transport_socket_events(fd=%d, events=%04x,...)", fd, events);
-    if(events & FDE_READ){
-        apacket *p = 0;
-        if(read_packet(fd, t->serial, &p)){
+    if (events & FDE_READ) {
+        apacket* p = 0;
+        if (read_packet(fd, t->serial, &p)) {
             D("%s: failed to read packet from transport socket on fd %d", t->serial, fd);
         } else {
-            handle_packet(p, (atransport *) _t);
+            handle_packet(p, (atransport*)_t);
         }
     }
 }
@@ -180,40 +177,43 @@
 // read_transport thread reads data from a transport (representing a usb/tcp connection),
 // and makes the main thread call handle_packet().
 static void read_transport_thread(void* _t) {
-    atransport *t = reinterpret_cast<atransport*>(_t);
-    apacket *p;
+    atransport* t = reinterpret_cast<atransport*>(_t);
+    apacket* p;
 
-    adb_thread_setname(android::base::StringPrintf("<-%s",
-                                                   (t->serial != nullptr ? t->serial : "transport")));
-    D("%s: starting read_transport thread on fd %d, SYNC online (%d)",
-       t->serial, t->fd, t->sync_token + 1);
+    adb_thread_setname(
+        android::base::StringPrintf("<-%s", (t->serial != nullptr ? t->serial : "transport")));
+    D("%s: starting read_transport thread on fd %d, SYNC online (%d)", t->serial, t->fd,
+      t->sync_token + 1);
     p = get_apacket();
     p->msg.command = A_SYNC;
     p->msg.arg0 = 1;
     p->msg.arg1 = ++(t->sync_token);
     p->msg.magic = A_SYNC ^ 0xffffffff;
-    if(write_packet(t->fd, t->serial, &p)) {
+    if (write_packet(t->fd, t->serial, &p)) {
         put_apacket(p);
         D("%s: failed to write SYNC packet", t->serial);
         goto oops;
     }
 
     D("%s: data pump started", t->serial);
-    for(;;) {
+    for (;;) {
+        ATRACE_NAME("read_transport loop");
         p = get_apacket();
 
-        if(t->read_from_remote(p, t) == 0){
-            D("%s: received remote packet, sending to transport",
-              t->serial);
-            if(write_packet(t->fd, t->serial, &p)){
+        {
+            ATRACE_NAME("read_transport read_remote");
+            if (t->read_from_remote(p, t) != 0) {
+                D("%s: remote read failed for transport", t->serial);
                 put_apacket(p);
-                D("%s: failed to write apacket to transport", t->serial);
-                goto oops;
+                break;
             }
-        } else {
-            D("%s: remote read failed for transport", t->serial);
+        }
+
+        D("%s: received remote packet, sending to transport", t->serial);
+        if (write_packet(t->fd, t->serial, &p)) {
             put_apacket(p);
-            break;
+            D("%s: failed to write apacket to transport", t->serial);
+            goto oops;
         }
     }
 
@@ -223,7 +223,7 @@
     p->msg.arg0 = 0;
     p->msg.arg1 = 0;
     p->msg.magic = A_SYNC ^ 0xffffffff;
-    if(write_packet(t->fd, t->serial, &p)) {
+    if (write_packet(t->fd, t->serial, &p)) {
         put_apacket(p);
         D("%s: failed to write SYNC apacket to transport", t->serial);
     }
@@ -237,38 +237,38 @@
 // write_transport thread gets packets sent by the main thread (through send_packet()),
 // and writes to a transport (representing a usb/tcp connection).
 static void write_transport_thread(void* _t) {
-    atransport *t = reinterpret_cast<atransport*>(_t);
-    apacket *p;
+    atransport* t = reinterpret_cast<atransport*>(_t);
+    apacket* p;
     int active = 0;
 
-    adb_thread_setname(android::base::StringPrintf("->%s",
-                                                   (t->serial != nullptr ? t->serial : "transport")));
-    D("%s: starting write_transport thread, reading from fd %d",
-       t->serial, t->fd);
+    adb_thread_setname(
+        android::base::StringPrintf("->%s", (t->serial != nullptr ? t->serial : "transport")));
+    D("%s: starting write_transport thread, reading from fd %d", t->serial, t->fd);
 
-    for(;;){
-        if(read_packet(t->fd, t->serial, &p)) {
-            D("%s: failed to read apacket from transport on fd %d",
-               t->serial, t->fd );
+    for (;;) {
+        ATRACE_NAME("write_transport loop");
+        if (read_packet(t->fd, t->serial, &p)) {
+            D("%s: failed to read apacket from transport on fd %d", t->serial, t->fd);
             break;
         }
-        if(p->msg.command == A_SYNC){
-            if(p->msg.arg0 == 0) {
+
+        if (p->msg.command == A_SYNC) {
+            if (p->msg.arg0 == 0) {
                 D("%s: transport SYNC offline", t->serial);
                 put_apacket(p);
                 break;
             } else {
-                if(p->msg.arg1 == t->sync_token) {
+                if (p->msg.arg1 == t->sync_token) {
                     D("%s: transport SYNC online", t->serial);
                     active = 1;
                 } else {
-                    D("%s: transport ignoring SYNC %d != %d",
-                      t->serial, p->msg.arg1, t->sync_token);
+                    D("%s: transport ignoring SYNC %d != %d", t->serial, p->msg.arg1, t->sync_token);
                 }
             }
         } else {
-            if(active) {
+            if (active) {
                 D("%s: transport got packet, sending to remote", t->serial);
+                ATRACE_NAME("write_transport write_remote");
                 t->write_to_remote(p, t);
             } else {
                 D("%s: transport ignoring packet while offline", t->serial);
@@ -296,7 +296,6 @@
 static int transport_registration_recv = -1;
 static fdevent transport_registration_fde;
 
-
 #if ADB_HOST
 
 /* this adds support required by the 'track-devices' service.
@@ -305,19 +304,17 @@
  * live TCP connection
  */
 struct device_tracker {
-    asocket          socket;
-    int              update_needed;
-    device_tracker*  next;
+    asocket socket;
+    int update_needed;
+    device_tracker* next;
 };
 
 /* linked list of all device trackers */
-static device_tracker*   device_tracker_list;
+static device_tracker* device_tracker_list;
 
-static void
-device_tracker_remove( device_tracker*  tracker )
-{
-    device_tracker**  pnode = &device_tracker_list;
-    device_tracker*   node  = *pnode;
+static void device_tracker_remove(device_tracker* tracker) {
+    device_tracker** pnode = &device_tracker_list;
+    device_tracker* node = *pnode;
 
     std::lock_guard<std::mutex> lock(transport_lock);
     while (node) {
@@ -326,17 +323,15 @@
             break;
         }
         pnode = &node->next;
-        node  = *pnode;
+        node = *pnode;
     }
 }
 
-static void
-device_tracker_close( asocket*  socket )
-{
-    device_tracker*  tracker = (device_tracker*) socket;
-    asocket*         peer    = socket->peer;
+static void device_tracker_close(asocket* socket) {
+    device_tracker* tracker = (device_tracker*)socket;
+    asocket* peer = socket->peer;
 
-    D( "device tracker %p removed", tracker);
+    D("device tracker %p removed", tracker);
     if (peer) {
         peer->peer = NULL;
         peer->close(peer);
@@ -345,9 +340,7 @@
     free(tracker);
 }
 
-static int
-device_tracker_enqueue( asocket*  socket, apacket*  p )
-{
+static int device_tracker_enqueue(asocket* socket, apacket* p) {
     /* you can't read from a device tracker, close immediately */
     put_apacket(p);
     device_tracker_close(socket);
@@ -377,26 +370,23 @@
     }
 }
 
-asocket*
-create_device_tracker(void)
-{
+asocket* create_device_tracker(void) {
     device_tracker* tracker = reinterpret_cast<device_tracker*>(calloc(1, sizeof(*tracker)));
     if (tracker == nullptr) fatal("cannot allocate device tracker");
 
-    D( "device tracker %p created", tracker);
+    D("device tracker %p created", tracker);
 
     tracker->socket.enqueue = device_tracker_enqueue;
-    tracker->socket.ready   = device_tracker_ready;
-    tracker->socket.close   = device_tracker_close;
-    tracker->update_needed  = 1;
+    tracker->socket.ready = device_tracker_ready;
+    tracker->socket.close = device_tracker_close;
+    tracker->update_needed = 1;
 
-    tracker->next       = device_tracker_list;
+    tracker->next = device_tracker_list;
     device_tracker_list = tracker;
 
     return &tracker->socket;
 }
 
-
 // Call this function each time the transport list has changed.
 void update_transports() {
     std::string transports = list_transports(false);
@@ -416,26 +406,23 @@
     // Nothing to do on the device side.
 }
 
-#endif // ADB_HOST
+#endif  // ADB_HOST
 
-struct tmsg
-{
-    atransport *transport;
-    int         action;
+struct tmsg {
+    atransport* transport;
+    int action;
 };
 
-static int
-transport_read_action(int  fd, struct tmsg*  m)
-{
-    char *p   = (char*)m;
-    int   len = sizeof(*m);
-    int   r;
+static int transport_read_action(int fd, struct tmsg* m) {
+    char* p = (char*)m;
+    int len = sizeof(*m);
+    int r;
 
-    while(len > 0) {
+    while (len > 0) {
         r = adb_read(fd, p, len);
-        if(r > 0) {
+        if (r > 0) {
             len -= r;
-            p   += r;
+            p += r;
         } else {
             D("transport_read_action: on fd %d: %s", fd, strerror(errno));
             return -1;
@@ -444,18 +431,16 @@
     return 0;
 }
 
-static int
-transport_write_action(int  fd, struct tmsg*  m)
-{
-    char *p   = (char*)m;
-    int   len = sizeof(*m);
-    int   r;
+static int transport_write_action(int fd, struct tmsg* m) {
+    char* p = (char*)m;
+    int len = sizeof(*m);
+    int r;
 
-    while(len > 0) {
+    while (len > 0) {
         r = adb_write(fd, p, len);
-        if(r > 0) {
+        if (r > 0) {
             len -= r;
-            p   += r;
+            p += r;
         } else {
             D("transport_write_action: on fd %d: %s", fd, strerror(errno));
             return -1;
@@ -464,17 +449,16 @@
     return 0;
 }
 
-static void transport_registration_func(int _fd, unsigned ev, void *data)
-{
+static void transport_registration_func(int _fd, unsigned ev, void* data) {
     tmsg m;
     int s[2];
-    atransport *t;
+    atransport* t;
 
-    if(!(ev & FDE_READ)) {
+    if (!(ev & FDE_READ)) {
         return;
     }
 
-    if(transport_read_action(_fd, &m)) {
+    if (transport_read_action(_fd, &m)) {
         fatal_errno("cannot read transport registration socket");
     }
 
@@ -483,9 +467,9 @@
     if (m.action == 0) {
         D("transport: %s removing and free'ing %d", t->serial, t->transport_socket);
 
-            /* IMPORTANT: the remove closes one half of the
-            ** socket pair.  The close closes the other half.
-            */
+        /* IMPORTANT: the remove closes one half of the
+        ** socket pair.  The close closes the other half.
+        */
         fdevent_remove(&(t->transport_fde));
         adb_close(t->fd);
 
@@ -494,16 +478,11 @@
             transport_list.remove(t);
         }
 
-        if (t->product)
-            free(t->product);
-        if (t->serial)
-            free(t->serial);
-        if (t->model)
-            free(t->model);
-        if (t->device)
-            free(t->device);
-        if (t->devpath)
-            free(t->devpath);
+        if (t->product) free(t->product);
+        if (t->serial) free(t->serial);
+        if (t->model) free(t->model);
+        if (t->device) free(t->device);
+        if (t->devpath) free(t->devpath);
 
         delete t;
 
@@ -525,10 +504,7 @@
         t->transport_socket = s[0];
         t->fd = s[1];
 
-        fdevent_install(&(t->transport_fde),
-                        t->transport_socket,
-                        transport_socket_events,
-                        t);
+        fdevent_install(&(t->transport_fde), t->transport_socket, transport_socket_events, t);
 
         fdevent_set(&(t->transport_fde), FDE_READ);
 
@@ -550,11 +526,10 @@
     update_transports();
 }
 
-void init_transport_registration(void)
-{
+void init_transport_registration(void) {
     int s[2];
 
-    if(adb_socketpair(s)){
+    if (adb_socketpair(s)) {
         fatal_errno("cannot open transport registration socketpair");
     }
     D("socketpair: (%d,%d)", s[0], s[1]);
@@ -562,38 +537,33 @@
     transport_registration_send = s[0];
     transport_registration_recv = s[1];
 
-    fdevent_install(&transport_registration_fde,
-                    transport_registration_recv,
-                    transport_registration_func,
-                    0);
+    fdevent_install(&transport_registration_fde, transport_registration_recv,
+                    transport_registration_func, 0);
 
     fdevent_set(&transport_registration_fde, FDE_READ);
 }
 
 /* the fdevent select pump is single threaded */
-static void register_transport(atransport *transport)
-{
+static void register_transport(atransport* transport) {
     tmsg m;
     m.transport = transport;
     m.action = 1;
     D("transport: %s registered", transport->serial);
-    if(transport_write_action(transport_registration_send, &m)) {
+    if (transport_write_action(transport_registration_send, &m)) {
         fatal_errno("cannot write transport registration socket\n");
     }
 }
 
-static void remove_transport(atransport *transport)
-{
+static void remove_transport(atransport* transport) {
     tmsg m;
     m.transport = transport;
     m.action = 0;
     D("transport: %s removed", transport->serial);
-    if(transport_write_action(transport_registration_send, &m)) {
+    if (transport_write_action(transport_registration_send, &m)) {
         fatal_errno("cannot write transport registration socket\n");
     }
 }
 
-
 static void transport_unref(atransport* t) {
     CHECK(t != nullptr);
 
@@ -609,37 +579,31 @@
     }
 }
 
-static int qual_match(const char *to_test,
-                      const char *prefix, const char *qual, bool sanitize_qual)
-{
-    if (!to_test || !*to_test)
-        /* Return true if both the qual and to_test are null strings. */
+static int qual_match(const char* to_test, const char* prefix, const char* qual,
+                      bool sanitize_qual) {
+    if (!to_test || !*to_test) /* Return true if both the qual and to_test are null strings. */
         return !qual || !*qual;
 
-    if (!qual)
-        return 0;
+    if (!qual) return 0;
 
     if (prefix) {
         while (*prefix) {
-            if (*prefix++ != *to_test++)
-                return 0;
+            if (*prefix++ != *to_test++) return 0;
         }
     }
 
     while (*qual) {
         char ch = *qual++;
-        if (sanitize_qual && !isalnum(ch))
-            ch = '_';
-        if (ch != *to_test++)
-            return 0;
+        if (sanitize_qual && !isalnum(ch)) ch = '_';
+        if (ch != *to_test++) return 0;
     }
 
     /* Everything matched so far.  Return true if *to_test is a NUL. */
     return !*to_test;
 }
 
-atransport* acquire_one_transport(TransportType type, const char* serial,
-                                  bool* is_ambiguous, std::string* error_out) {
+atransport* acquire_one_transport(TransportType type, const char* serial, bool* is_ambiguous,
+                                  std::string* error_out) {
     atransport* result = nullptr;
 
     if (serial) {
@@ -737,15 +701,24 @@
 
 const std::string atransport::connection_state_name() const {
     switch (connection_state) {
-        case kCsOffline: return "offline";
-        case kCsBootloader: return "bootloader";
-        case kCsDevice: return "device";
-        case kCsHost: return "host";
-        case kCsRecovery: return "recovery";
-        case kCsNoPerm: return UsbNoPermissionsShortHelpText();
-        case kCsSideload: return "sideload";
-        case kCsUnauthorized: return "unauthorized";
-        default: return "unknown";
+        case kCsOffline:
+            return "offline";
+        case kCsBootloader:
+            return "bootloader";
+        case kCsDevice:
+            return "device";
+        case kCsHost:
+            return "host";
+        case kCsRecovery:
+            return "recovery";
+        case kCsNoPerm:
+            return UsbNoPermissionsShortHelpText();
+        case kCsSideload:
+            return "sideload";
+        case kCsUnauthorized:
+            return "unauthorized";
+        default:
+            return "unknown";
     }
 }
 
@@ -771,9 +744,7 @@
 const FeatureSet& supported_features() {
     // Local static allocation to avoid global non-POD variables.
     static const FeatureSet* features = new FeatureSet{
-        kFeatureShell2,
-        kFeatureCmd,
-        kFeatureStat2,
+        kFeatureShell2, kFeatureCmd, kFeatureStat2,
         // Increment ADB_SERVER_VERSION whenever the feature list changes to
         // make sure that the adb client and server features stay in sync
         // (http://b/24370690).
@@ -791,14 +762,12 @@
         return FeatureSet();
     }
 
-    auto names = android::base::Split(features_string,
-                                      {kFeatureStringDelimiter});
+    auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
     return FeatureSet(names.begin(), names.end());
 }
 
 bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
-    return feature_set.count(feature) > 0 &&
-            supported_features().count(feature) > 0;
+    return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
 }
 
 bool atransport::has_feature(const std::string& feature) const {
@@ -834,21 +803,20 @@
 
             // For fastboot compatibility, ignore protocol prefixes.
             if (android::base::StartsWith(target, "tcp:") ||
-                    android::base::StartsWith(target, "udp:")) {
+                android::base::StartsWith(target, "udp:")) {
                 local_target_ptr += 4;
             }
 
             // Parse our |serial| and the given |target| to check if the hostnames and ports match.
             std::string serial_host, error;
             int serial_port = -1;
-            if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr,
-                                               &error)) {
+            if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
                 // |target| may omit the port to default to ours.
                 std::string target_host;
                 int target_port = serial_port;
                 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
                                                    nullptr, &error) &&
-                        serial_host == target_host && serial_port == target_port) {
+                    serial_host == target_host && serial_port == target_port) {
                     return true;
                 }
             }
@@ -863,8 +831,8 @@
 
 #if ADB_HOST
 
-static void append_transport_info(std::string* result, const char* key,
-                                  const char* value, bool sanitize) {
+static void append_transport_info(std::string* result, const char* key, const char* value,
+                                  bool sanitize) {
     if (value == nullptr || *value == '\0') {
         return;
     }
@@ -877,8 +845,7 @@
     }
 }
 
-static void append_transport(const atransport* t, std::string* result,
-                             bool long_listing) {
+static void append_transport(const atransport* t, std::string* result, bool long_listing) {
     const char* serial = t->serial;
     if (!serial || !serial[0]) {
         serial = "(no serial number)";
@@ -889,8 +856,7 @@
         *result += '\t';
         *result += t->connection_state_name();
     } else {
-        android::base::StringAppendF(result, "%-22s %s", serial,
-                                     t->connection_state_name().c_str());
+        android::base::StringAppendF(result, "%-22s %s", serial, t->connection_state_name().c_str());
 
         append_transport_info(result, "", t->devpath, false);
         append_transport_info(result, "product:", t->product, false);
@@ -923,9 +889,9 @@
 void close_usb_devices() {
     close_usb_devices([](const atransport*) { return true; });
 }
-#endif // ADB_HOST
+#endif  // ADB_HOST
 
-int register_socket_transport(int s, const char *serial, int port, int local) {
+int register_socket_transport(int s, const char* serial, int port, int local) {
     atransport* t = new atransport();
 
     if (!serial) {
@@ -944,7 +910,7 @@
     for (const auto& transport : pending_list) {
         if (transport->serial && strcmp(serial, transport->serial) == 0) {
             VLOG(TRANSPORT) << "socket transport " << transport->serial
-                << " is already in pending_list and fails to register";
+                            << " is already in pending_list and fails to register";
             delete t;
             return -1;
         }
@@ -953,7 +919,7 @@
     for (const auto& transport : transport_list) {
         if (transport->serial && strcmp(serial, transport->serial) == 0) {
             VLOG(TRANSPORT) << "socket transport " << transport->serial
-                << " is already in transport_list and fails to register";
+                            << " is already in transport_list and fails to register";
             delete t;
             return -1;
         }
@@ -969,7 +935,7 @@
 }
 
 #if ADB_HOST
-atransport *find_transport(const char *serial) {
+atransport* find_transport(const char* serial) {
     atransport* result = nullptr;
 
     std::lock_guard<std::mutex> lock(transport_lock);
@@ -998,14 +964,13 @@
 
 #endif
 
-void register_usb_transport(usb_handle* usb, const char* serial,
-                            const char* devpath, unsigned writeable) {
+void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
+                            unsigned writeable) {
     atransport* t = new atransport();
 
-    D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb,
-      serial ? serial : "");
+    D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
     init_usb_transport(t, usb, (writeable ? kCsOffline : kCsNoPerm));
-    if(serial) {
+    if (serial) {
         t->serial = strdup(serial);
     }
 
@@ -1022,23 +987,21 @@
 }
 
 // This should only be used for transports with connection_state == kCsNoPerm.
-void unregister_usb_transport(usb_handle *usb) {
+void unregister_usb_transport(usb_handle* usb) {
     std::lock_guard<std::mutex> lock(transport_lock);
-    transport_list.remove_if([usb](atransport* t) {
-        return t->usb == usb && t->connection_state == kCsNoPerm;
-    });
+    transport_list.remove_if(
+        [usb](atransport* t) { return t->usb == usb && t->connection_state == kCsNoPerm; });
 }
 
-int check_header(apacket *p, atransport *t)
-{
-    if(p->msg.magic != (p->msg.command ^ 0xffffffff)) {
+int check_header(apacket* p, atransport* t) {
+    if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
         VLOG(RWX) << "check_header(): invalid magic";
         return -1;
     }
 
-    if(p->msg.data_length > t->get_max_payload()) {
-        VLOG(RWX) << "check_header(): " << p->msg.data_length << " atransport::max_payload = "
-                  << t->get_max_payload();
+    if (p->msg.data_length > t->get_max_payload()) {
+        VLOG(RWX) << "check_header(): " << p->msg.data_length
+                  << " atransport::max_payload = " << t->get_max_payload();
         return -1;
     }
 
diff --git a/include/cutils/trace.h b/include/cutils/trace.h
index 0f00417..fcbdc9b 100644
--- a/include/cutils/trace.h
+++ b/include/cutils/trace.h
@@ -71,7 +71,8 @@
 #define ATRACE_TAG_SYSTEM_SERVER    (1<<19)
 #define ATRACE_TAG_DATABASE         (1<<20)
 #define ATRACE_TAG_NETWORK          (1<<21)
-#define ATRACE_TAG_LAST             ATRACE_TAG_NETWORK
+#define ATRACE_TAG_ADB              (1<<22)
+#define ATRACE_TAG_LAST             ATRACE_TAG_ADB
 
 // Reserved for initialization.
 #define ATRACE_TAG_NOT_READY        (1ULL<<63)
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index c9e1923..3031562 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -19,6 +19,33 @@
 ** by the device side of adb.
 */
 
+/*
+ * This file is consumed by build/tools/fs_config and is used
+ * for generating various files. Anything #define AID_<name>
+ * becomes the mapping for getpwnam/getpwuid, etc. The <name>
+ * field is lowercased.
+ * For example:
+ * #define AID_FOO_BAR 6666 becomes a friendly name of "foo_bar"
+ *
+ * The above holds true with the exception of:
+ *   mediacodec
+ *   mediaex
+ *   mediadrm
+ * Whose friendly names do not match the #define statements.
+ *
+ * Additionally, AID_OEM_RESERVED_START and AID_OEM_RESERVED_END
+ * can be used to define reserved OEM ranges used for sanity checks
+ * during the build process. The rules are, they must end with START/END
+ * The proper convention is incrementing a number like so:
+ * AID_OEM_RESERVED_START
+ * AID_OEM_RESERVED_1_START
+ * AID_OEM_RESERVED_2_START
+ * ...
+ * The same applies to the END.
+ * They are not required to be in order, but must not overlap each other and
+ * must define a START and END'ing range. START must be smaller than END.
+ */
+
 #ifndef _ANDROID_FILESYSTEM_CONFIG_H_
 #define _ANDROID_FILESYSTEM_CONFIG_H_
 
diff --git a/include/utils/FastStrcmp.h b/include/utils/FastStrcmp.h
new file mode 100644
index 0000000..3844e7d
--- /dev/null
+++ b/include/utils/FastStrcmp.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2014-2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _ANDROID_UTILS_FASTSTRCMP_H__
+#define _ANDROID_UTILS_FASTSTRCMP_H__
+
+#ifdef __cplusplus
+
+// Optimized for instruction cache locality
+//
+// Template class fastcmp used to create more time-efficient str*cmp
+// functions by pre-checking the first character before resorting
+// to calling the underlying string function.  Profiled with a
+// measurable speedup when used in hot code.  Usage is of the form:
+//
+//  fastcmp<strncmp>(str1, str2, len)
+//
+// NB: Does not work for the case insensitive str*cmp functions.
+// NB: Returns boolean, do not use if expecting to check negative value.
+//     Thus not semantically identical to the expected function behavior.
+
+template <int (*cmp)(const char *l, const char *r, const size_t s)>
+static inline int fastcmp(const char *l, const char *r, const size_t s) {
+    return (*l != *r) || cmp(l + 1, r + 1, s - 1);
+}
+
+template <int (*cmp)(const void *l, const void *r, const size_t s)>
+static inline int fastcmp(const void *lv, const void *rv, const size_t s) {
+    const char *l = static_cast<const char *>(lv);
+    const char *r = static_cast<const char *>(rv);
+    return (*l != *r) || cmp(l + 1, r + 1, s - 1);
+}
+
+template <int (*cmp)(const char *l, const char *r)>
+static inline int fastcmp(const char *l, const char *r) {
+    return (*l != *r) || cmp(l + 1, r + 1);
+}
+
+#endif
+
+#endif // _ANDROID_UTILS_FASTSTRCMP_H__
diff --git a/include/utils/Trace.h b/include/utils/Trace.h
index 6ba68f6..eeba40d 100644
--- a/include/utils/Trace.h
+++ b/include/utils/Trace.h
@@ -33,10 +33,10 @@
 
 // See <cutils/trace.h> for more ATRACE_* macros.
 
-// ATRACE_NAME traces the beginning and end of the current scope.  To trace
-// the correct start and end times this macro should be declared first in the
-// scope body.
-#define ATRACE_NAME(name) android::ScopedTrace ___tracer(ATRACE_TAG, name)
+// ATRACE_NAME traces from its location until the end of its enclosing scope.
+#define _PASTE(x, y) x ## y
+#define PASTE(x, y) _PASTE(x,y)
+#define ATRACE_NAME(name) android::ScopedTrace PASTE(___tracer, __LINE__) (ATRACE_TAG, name)
 // ATRACE_CALL is an ATRACE_NAME that uses the current function name.
 #define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
 
diff --git a/init/service.cpp b/init/service.cpp
index a7eaf66..e967a7c 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -567,9 +567,9 @@
             console_ = default_console;
         }
 
-        bool have_console = (open(console_.c_str(), O_RDWR | O_CLOEXEC) != -1);
+        bool have_console = (access(console_.c_str(), R_OK | W_OK) != -1);
         if (!have_console) {
-            PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
+            PLOG(ERROR) << "service '" << name_ << "' cannot gain read/write access to console '" << console_ << "'";
             flags_ |= SVC_DISABLED;
             return false;
         }
diff --git a/logd/LogBufferElement.cpp b/logd/LogBufferElement.cpp
index f5c60c7..ec91f2a 100644
--- a/logd/LogBufferElement.cpp
+++ b/logd/LogBufferElement.cpp
@@ -89,7 +89,7 @@
         size_t name_len = strlen(name);
         // KISS: ToDo: Only checks prefix truncated, not suffix, or both
         if ((retval_len < name_len)
-                && !fast<strcmp>(retval, name + name_len - retval_len)) {
+                && !fastcmp<strcmp>(retval, name + name_len - retval_len)) {
             free(retval);
             retval = name;
         } else {
diff --git a/logd/LogKlog.cpp b/logd/LogKlog.cpp
index 7073535..0b49fc1 100644
--- a/logd/LogKlog.cpp
+++ b/logd/LogKlog.cpp
@@ -321,7 +321,7 @@
                 }
                 --len;
             } while (*s++ != c);
-        } while (fast<memcmp>(s, needle, needleLen));
+        } while (fastcmp<memcmp>(s, needle, needleLen));
         s--;
     }
     return s;
@@ -640,7 +640,7 @@
 
     static const char infoBrace[] = "[INFO]";
     static const size_t infoBraceLen = strlen(infoBrace);
-    if ((taglen >= infoBraceLen) && !fast<strncmp>(p, infoBrace, infoBraceLen)) {
+    if ((taglen >= infoBraceLen) && !fastcmp<strncmp>(p, infoBrace, infoBraceLen)) {
         // <PRI>[<TIME>] "[INFO]"<tag> ":" message
         bt = p + infoBraceLen;
         taglen -= infoBraceLen;
@@ -675,7 +675,7 @@
             p = cp + 1;
         } else if ((taglen > size) && (tolower(*bt) == tolower(*cp))) {
             // clean up any tag stutter
-            if (!fast<strncasecmp>(bt + 1, cp + 1, size - 1)) { // no match
+            if (!fastcmp<strncasecmp>(bt + 1, cp + 1, size - 1)) { // no match
                 // <PRI>[<TIME>] <tag> <tag> : message
                 // <PRI>[<TIME>] <tag> <tag>: message
                 // <PRI>[<TIME>] <tag> '<tag>.<num>' : message
@@ -697,8 +697,8 @@
                 static const char host[] = "_host";
                 static const size_t hostlen = strlen(host);
                 if ((size > hostlen) &&
-                        !fast<strncmp>(bt + size - hostlen, host, hostlen) &&
-                        !fast<strncmp>(bt + 1, cp + 1, size - hostlen - 1)) {
+                        !fastcmp<strncmp>(bt + size - hostlen, host, hostlen) &&
+                        !fastcmp<strncmp>(bt + 1, cp + 1, size - hostlen - 1)) {
                     const char *b = cp;
                     cp += size - hostlen;
                     taglen -= size - hostlen;
@@ -746,10 +746,10 @@
         // register names like x18 but not driver names like en0
             || ((size == 3) && (isdigit(tag[1]) && isdigit(tag[2])))
         // blacklist
-            || ((size == cpuLen) && !fast<strncmp>(tag, cpu, cpuLen))
-            || ((size == warningLen) && !fast<strncasecmp>(tag, warning, warningLen))
-            || ((size == errorLen) && !fast<strncasecmp>(tag, error, errorLen))
-            || ((size == infoLen) && !fast<strncasecmp>(tag, info, infoLen))) {
+            || ((size == cpuLen) && !fastcmp<strncmp>(tag, cpu, cpuLen))
+            || ((size == warningLen) && !fastcmp<strncasecmp>(tag, warning, warningLen))
+            || ((size == errorLen) && !fastcmp<strncasecmp>(tag, error, errorLen))
+            || ((size == infoLen) && !fastcmp<strncasecmp>(tag, info, infoLen))) {
         p = start;
         etag = tag = "";
     }
@@ -761,7 +761,7 @@
     const char *mp = strnrchr(tag, ']', taglen);
     if (mp && (++mp < etag)) {
         size_t s = etag - mp;
-        if (((s + s) < taglen) && !fast<memcmp>(mp, mp - 1 - s, s)) {
+        if (((s + s) < taglen) && !fastcmp<memcmp>(mp, mp - 1 - s, s)) {
             taglen = mp - tag;
         }
     }
diff --git a/logd/LogReader.cpp b/logd/LogReader.cpp
index 61d4c49..1b50b4e 100644
--- a/logd/LogReader.cpp
+++ b/logd/LogReader.cpp
@@ -108,7 +108,7 @@
     }
 
     bool nonBlock = false;
-    if (!fast<strncmp>(buffer, "dumpAndClose", 12)) {
+    if (!fastcmp<strncmp>(buffer, "dumpAndClose", 12)) {
         // Allow writer to get some cycles, and wait for pending notifications
         sched_yield();
         LogTimeEntry::lock();
diff --git a/logd/LogStatistics.cpp b/logd/LogStatistics.cpp
index d4b48ef..bab87ba 100644
--- a/logd/LogStatistics.cpp
+++ b/logd/LogStatistics.cpp
@@ -53,7 +53,7 @@
             if (ret > 0) {
                 buffer[sizeof(buffer)-1] = '\0';
                 // frameworks intermediate state
-                if (fast<strcmp>(buffer, "<pre-initialized>")) {
+                if (fastcmp<strcmp>(buffer, "<pre-initialized>")) {
                     retval = strdup(buffer);
                 }
             }
@@ -209,7 +209,7 @@
             if (nameTmp) {
                 if (!name) {
                     name = strdup(nameTmp);
-                } else if (fast<strcmp>(name, nameTmp)) {
+                } else if (fastcmp<strcmp>(name, nameTmp)) {
                     free(const_cast<char *>(name));
                     name = NULL;
                     break;
diff --git a/logd/LogStatistics.h b/logd/LogStatistics.h
index 1f598af..cb7ae2b 100644
--- a/logd/LogStatistics.h
+++ b/logd/LogStatistics.h
@@ -307,7 +307,7 @@
     const char*getName() const { return name; }
 
     inline void add(pid_t newPid) {
-        if (name && !fast<strncmp>(name, "zygote", 6)) {
+        if (name && !fastcmp<strncmp>(name, "zygote", 6)) {
             free(name);
             name = NULL;
         }
@@ -368,7 +368,7 @@
     const char*getName() const { return name; }
 
     inline void add(pid_t incomingTid) {
-        if (name && !fast<strncmp>(name, "zygote", 6)) {
+        if (name && !fastcmp<strncmp>(name, "zygote", 6)) {
             free(name);
             name = NULL;
         }
diff --git a/logd/LogUtils.h b/logd/LogUtils.h
index 44ac742..ec68062 100644
--- a/logd/LogUtils.h
+++ b/logd/LogUtils.h
@@ -20,6 +20,7 @@
 #include <sys/cdefs.h>
 #include <sys/types.h>
 
+#include <utils/FastStrcmp.h>
 #include <private/android_logger.h>
 #include <sysutils/SocketClient.h>
 
@@ -50,21 +51,4 @@
             (id == LOG_ID_RADIO) || (id == LOG_ID_EVENTS);
 }
 
-template <int (*cmp)(const char *l, const char *r, const size_t s)>
-static inline int fast(const char *l, const char *r, const size_t s) {
-    return (*l != *r) || cmp(l + 1, r + 1, s - 1);
-}
-
-template <int (*cmp)(const void *l, const void *r, const size_t s)>
-static inline int fast(const void *lv, const void *rv, const size_t s) {
-    const char *l = static_cast<const char *>(lv);
-    const char *r = static_cast<const char *>(rv);
-    return (*l != *r) || cmp(l + 1, r + 1, s - 1);
-}
-
-template <int (*cmp)(const char *l, const char *r)>
-static inline int fast(const char *l, const char *r) {
-    return (*l != *r) || cmp(l + 1, r + 1);
-}
-
 #endif // _LOGD_LOG_UTILS_H__