Merge "Remove deprecated Android.mk files"
diff --git a/adb/adb.h b/adb/adb.h
index cb38e61..9227eb1 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -188,7 +188,7 @@
 
 
 void local_init(int port);
-void local_connect(int port);
+bool local_connect(int port);
 int  local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error);
 
 // USB host/client interface.
diff --git a/adb/adb_auth.cpp b/adb/adb_auth.cpp
index 1ffab09..215bbe6 100644
--- a/adb/adb_auth.cpp
+++ b/adb/adb_auth.cpp
@@ -72,19 +72,23 @@
 void send_auth_publickey(atransport *t)
 {
     D("Calling send_auth_publickey");
-    apacket *p = get_apacket();
-    int ret;
-
-    ret = adb_auth_get_userkey(p->data, MAX_PAYLOAD_V1);
-    if (!ret) {
+    std::string key = adb_auth_get_userkey();
+    if (key.empty()) {
         D("Failed to get user public key");
-        put_apacket(p);
         return;
     }
 
+    if (key.size() >= MAX_PAYLOAD_V1) {
+        D("User public key too large (%zu B)", key.size());
+        return;
+    }
+
+    apacket* p = get_apacket();
+    memcpy(p->data, key.c_str(), key.size() + 1);
+
     p->msg.command = A_AUTH;
     p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
-    p->msg.data_length = ret;
+    p->msg.data_length = key.size();
     send_packet(p, t);
 }
 
diff --git a/adb/adb_auth.h b/adb/adb_auth.h
index 1ab5e1a..6363bb4 100644
--- a/adb/adb_auth.h
+++ b/adb/adb_auth.h
@@ -41,7 +41,7 @@
 int adb_auth_sign(void *key, const unsigned char* token, size_t token_size,
                   unsigned char* sig);
 void *adb_auth_nextkey(void *current);
-int adb_auth_get_userkey(unsigned char *data, size_t len);
+std::string adb_auth_get_userkey();
 
 static inline int adb_auth_generate_token(void *token, size_t token_size) {
     return 0;
@@ -60,9 +60,7 @@
     return 0;
 }
 static inline void *adb_auth_nextkey(void *current) { return NULL; }
-static inline int adb_auth_get_userkey(unsigned char *data, size_t len) {
-    return 0;
-}
+static inline std::string adb_auth_get_userkey() { return ""; }
 
 void adbd_auth_init(void);
 void adbd_cloexec_auth_socket();
diff --git a/adb/adb_auth_host.cpp b/adb/adb_auth_host.cpp
index ab641eb..03cebe9 100644
--- a/adb/adb_auth_host.cpp
+++ b/adb/adb_auth_host.cpp
@@ -18,26 +18,17 @@
 
 #include "sysdeps.h"
 #include "adb_auth.h"
+#include "adb_utils.h"
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
-#ifdef _WIN32
-#  ifndef WIN32_LEAN_AND_MEAN
-#    define WIN32_LEAN_AND_MEAN
-#  endif
-#  include "windows.h"
-#  include "shlobj.h"
-#else
-#  include <sys/types.h>
-#  include <sys/stat.h>
-#  include <unistd.h>
-#endif
-
 #include "adb.h"
 
 #include <android-base/errors.h>
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <crypto_utils/android_pubkey.h>
 #include <cutils/list.h>
@@ -247,46 +238,23 @@
 
 static int get_user_keyfilepath(char *filename, size_t len)
 {
-    const char *format, *home;
-    char android_dir[PATH_MAX];
+    const std::string home = adb_get_homedir_path(true);
+    D("home '%s'", home.c_str());
+
+    const std::string android_dir =
+            android::base::StringPrintf("%s%c%s", home.c_str(),
+                                        OS_PATH_SEPARATOR, ANDROID_PATH);
+
     struct stat buf;
-#ifdef _WIN32
-    std::string home_str;
-    home = getenv("ANDROID_SDK_HOME");
-    if (!home) {
-        WCHAR path[MAX_PATH];
-        const HRESULT hr = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path);
-        if (FAILED(hr)) {
-            D("SHGetFolderPathW failed: %s", android::base::SystemErrorCodeToString(hr).c_str());
-            return -1;
-        }
-        if (!android::base::WideToUTF8(path, &home_str)) {
-            return -1;
-        }
-        home = home_str.c_str();
-    }
-    format = "%s\\%s";
-#else
-    home = getenv("HOME");
-    if (!home)
-        return -1;
-    format = "%s/%s";
-#endif
-
-    D("home '%s'", home);
-
-    if (snprintf(android_dir, sizeof(android_dir), format, home,
-                        ANDROID_PATH) >= (int)sizeof(android_dir))
-        return -1;
-
-    if (stat(android_dir, &buf)) {
-        if (adb_mkdir(android_dir, 0750) < 0) {
-            D("Cannot mkdir '%s'", android_dir);
+    if (stat(android_dir.c_str(), &buf)) {
+        if (adb_mkdir(android_dir.c_str(), 0750) < 0) {
+            D("Cannot mkdir '%s'", android_dir.c_str());
             return -1;
         }
     }
 
-    return snprintf(filename, len, format, android_dir, ADB_KEY_FILE);
+    return snprintf(filename, len, "%s%c%s",
+                    android_dir.c_str(), OS_PATH_SEPARATOR, ADB_KEY_FILE);
 }
 
 static int get_user_key(struct listnode *list)
@@ -367,39 +335,21 @@
     return NULL;
 }
 
-int adb_auth_get_userkey(unsigned char *data, size_t len)
-{
+std::string adb_auth_get_userkey() {
     char path[PATH_MAX];
     int ret = get_user_keyfilepath(path, sizeof(path) - 4);
     if (ret < 0 || ret >= (signed)(sizeof(path) - 4)) {
         D("Error getting user key filename");
-        return 0;
+        return "";
     }
     strcat(path, ".pub");
 
-    // TODO(danalbert): ReadFileToString
-    // Note that on Windows, load_file() does not do CR/LF translation, but
-    // ReadFileToString() uses the C Runtime which uses CR/LF translation by
-    // default (by is overridable with _setmode()).
-    unsigned size;
-    char* file_data = reinterpret_cast<char*>(load_file(path, &size));
-    if (file_data == nullptr) {
+    std::string content;
+    if (!android::base::ReadFileToString(path, &content)) {
         D("Can't load '%s'", path);
-        return 0;
+        return "";
     }
-
-    if (len < (size_t)(size + 1)) {
-        D("%s: Content too large ret=%d", path, size);
-        free(file_data);
-        return 0;
-    }
-
-    memcpy(data, file_data, size);
-    free(file_data);
-    file_data = nullptr;
-    data[size] = '\0';
-
-    return size + 1;
+    return content;
 }
 
 int adb_auth_keygen(const char* filename) {
diff --git a/adb/adb_utils.cpp b/adb/adb_utils.cpp
index 5d4755f..31ec8af 100644
--- a/adb/adb_utils.cpp
+++ b/adb/adb_utils.cpp
@@ -35,6 +35,14 @@
 #include "adb_trace.h"
 #include "sysdeps.h"
 
+#ifdef _WIN32
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN
+#  endif
+#  include "windows.h"
+#  include "shlobj.h"
+#endif
+
 ADB_MUTEX_DEFINE(basename_lock);
 ADB_MUTEX_DEFINE(dirname_lock);
 
@@ -254,3 +262,30 @@
 
     return true;
 }
+
+std::string adb_get_homedir_path(bool check_env_first) {
+#ifdef _WIN32
+    if (check_env_first) {
+        if (const char* const home = getenv("ANDROID_SDK_HOME")) {
+            return home;
+        }
+    }
+
+    WCHAR path[MAX_PATH];
+    const HRESULT hr = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path);
+    if (FAILED(hr)) {
+        D("SHGetFolderPathW failed: %s", android::base::SystemErrorCodeToString(hr).c_str());
+        return {};
+    }
+    std::string home_str;
+    if (!android::base::WideToUTF8(path, &home_str)) {
+        return {};
+    }
+    return home_str;
+#else
+    if (const char* const home = getenv("HOME")) {
+        return home;
+    }
+    return {};
+#endif
+}
diff --git a/adb/adb_utils.h b/adb/adb_utils.h
index 22eb4d2..f6b4b26 100644
--- a/adb/adb_utils.h
+++ b/adb/adb_utils.h
@@ -32,6 +32,12 @@
 std::string adb_basename(const std::string& path);
 std::string adb_dirname(const std::string& path);
 
+// Return the user's home directory.
+// |check_env_first| - if true, on Windows check the ANDROID_SDK_HOME
+// environment variable before trying the WinAPI call (useful when looking for
+// the .android directory)
+std::string adb_get_homedir_path(bool check_env_first);
+
 bool mkdirs(const std::string& path);
 
 std::string escape_arg(const std::string& s);
@@ -60,42 +66,4 @@
 
 using unique_fd = android::base::unique_fd_impl<AdbCloser>;
 
-class ScopedFd {
-  public:
-    ScopedFd() {
-    }
-
-    ~ScopedFd() {
-        Reset();
-    }
-
-    void Reset(int fd = -1) {
-        if (fd != fd_) {
-            if (valid()) {
-                adb_close(fd_);
-            }
-            fd_ = fd;
-        }
-    }
-
-    int Release() {
-        int temp = fd_;
-        fd_ = -1;
-        return temp;
-    }
-
-    bool valid() const {
-        return fd_ >= 0;
-    }
-
-    int fd() const {
-        return fd_;
-    }
-
-  private:
-    int fd_ = -1;
-
-    DISALLOW_COPY_AND_ASSIGN(ScopedFd);
-};
-
 #endif
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 868470c..82fa19a 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -35,6 +35,7 @@
 #include <string>
 #include <vector>
 
+#include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
@@ -871,47 +872,47 @@
  *   we hang up.
  */
 static int adb_sideload_host(const char* fn) {
-    unsigned sz;
-    size_t xfer = 0;
-    int status;
-    int last_percent = -1;
-    int opt = SIDELOAD_HOST_BLOCK_SIZE;
-
     printf("loading: '%s'", fn);
     fflush(stdout);
-    uint8_t* data = reinterpret_cast<uint8_t*>(load_file(fn, &sz));
-    if (data == 0) {
+
+    std::string content;
+    if (!android::base::ReadFileToString(fn, &content)) {
         printf("\n");
         fprintf(stderr, "* cannot read '%s' *\n", fn);
         return -1;
     }
 
+    const uint8_t* data = reinterpret_cast<const uint8_t*>(content.data());
+    unsigned sz = content.size();
+
     std::string service =
             android::base::StringPrintf("sideload-host:%d:%d", sz, SIDELOAD_HOST_BLOCK_SIZE);
     std::string error;
-    int fd = adb_connect(service, &error);
-    if (fd < 0) {
+    unique_fd fd(adb_connect(service, &error));
+    if (fd >= 0) {
         // Try falling back to the older sideload method.  Maybe this
         // is an older device that doesn't support sideload-host.
         printf("\n");
-        status = adb_download_buffer("sideload", fn, data, sz, true);
-        goto done;
+        return adb_download_buffer("sideload", fn, data, sz, true);
     }
 
-    opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
+    int opt = SIDELOAD_HOST_BLOCK_SIZE;
+    adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
 
+    size_t xfer = 0;
+    int last_percent = -1;
     while (true) {
         char buf[9];
         if (!ReadFdExactly(fd, buf, 8)) {
             fprintf(stderr, "* failed to read command: %s\n", strerror(errno));
-            status = -1;
-            goto done;
+            return -1;
         }
         buf[8] = '\0';
 
         if (strcmp("DONEDONE", buf) == 0) {
-            status = 0;
-            break;
+            printf("\rTotal xfer: %.2fx%*s\n",
+                   (double)xfer / (sz ? sz : 1), (int)strlen(fn)+10, "");
+            return 0;
         }
 
         int block = strtol(buf, NULL, 10);
@@ -919,21 +920,19 @@
         size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
         if (offset >= sz) {
             fprintf(stderr, "* attempt to read block %d past end\n", block);
-            status = -1;
-            goto done;
+            return -1;
         }
-        uint8_t* start = data + offset;
+        const uint8_t* start = data + offset;
         size_t offset_end = offset + SIDELOAD_HOST_BLOCK_SIZE;
         size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
         if (offset_end > sz) {
             to_write = sz - offset;
         }
 
-        if(!WriteFdExactly(fd, start, to_write)) {
+        if (!WriteFdExactly(fd, start, to_write)) {
             adb_status(fd, &error);
             fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
-            status = -1;
-            goto done;
+            return -1;
         }
         xfer += to_write;
 
@@ -950,13 +949,6 @@
             last_percent = percent;
         }
     }
-
-    printf("\rTotal xfer: %.2fx%*s\n", (double)xfer / (sz ? sz : 1), (int)strlen(fn)+10, "");
-
-  done:
-    if (fd >= 0) adb_close(fd);
-    free(data);
-    return status;
 }
 
 /**
@@ -1067,10 +1059,9 @@
 
 static bool adb_root(const char* command) {
     std::string error;
-    ScopedFd fd;
 
-    fd.Reset(adb_connect(android::base::StringPrintf("%s:", command), &error));
-    if (!fd.valid()) {
+    unique_fd fd(adb_connect(android::base::StringPrintf("%s:", command), &error));
+    if (fd < 0) {
         fprintf(stderr, "adb: unable to connect for %s: %s\n", command, error.c_str());
         return false;
     }
@@ -1080,7 +1071,7 @@
     char* cur = buf;
     ssize_t bytes_left = sizeof(buf);
     while (bytes_left > 0) {
-        ssize_t bytes_read = adb_read(fd.fd(), cur, bytes_left);
+        ssize_t bytes_read = adb_read(fd, cur, bytes_left);
         if (bytes_read == 0) {
             break;
         } else if (bytes_read < 0) {
diff --git a/adb/console.cpp b/adb/console.cpp
index 15c6abd..e9b90a5 100644
--- a/adb/console.cpp
+++ b/adb/console.cpp
@@ -26,6 +26,31 @@
 #include "adb.h"
 #include "adb_client.h"
 #include "adb_io.h"
+#include "adb_utils.h"
+
+// Return the console authentication command for the emulator, if needed
+static std::string adb_construct_auth_command() {
+    static const char auth_token_filename[] = ".emulator_console_auth_token";
+
+    std::string auth_token_path = adb_get_homedir_path(false);
+    auth_token_path += OS_PATH_SEPARATOR;
+    auth_token_path += auth_token_filename;
+
+    // read the token
+    std::string token;
+    if (!android::base::ReadFileToString(auth_token_path, &token)
+        || token.empty()) {
+        // we either can't read the file, or it doesn't exist, or it's empty -
+        // either way we won't add any authentication command.
+        return {};
+    }
+
+    // now construct and return the actual command: "auth <token>\n"
+    std::string command = "auth ";
+    command += token;
+    command += '\n';
+    return command;
+}
 
 // Return the console port of the currently connected emulator (if any) or -1 if
 // there is no emulator, and -2 if there is more than one.
@@ -88,11 +113,11 @@
         return 1;
     }
 
-    std::string commands;
+    std::string commands = adb_construct_auth_command();
 
     for (int i = 1; i < argc; i++) {
         commands.append(argv[i]);
-        commands.append(i == argc - 1 ? "\n" : " ");
+        commands.push_back(i == argc - 1 ? '\n' : ' ');
     }
 
     commands.append("quit\n");
diff --git a/adb/shell_service.cpp b/adb/shell_service.cpp
index 374b468..e8dad58 100644
--- a/adb/shell_service.cpp
+++ b/adb/shell_service.cpp
@@ -136,14 +136,14 @@
 }
 
 // Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
-bool CreateSocketpair(ScopedFd* fd1, ScopedFd* fd2) {
+bool CreateSocketpair(unique_fd* fd1, unique_fd* fd2) {
     int sockets[2];
     if (adb_socketpair(sockets) < 0) {
         PLOG(ERROR) << "cannot create socket pair";
         return false;
     }
-    fd1->Reset(sockets[0]);
-    fd2->Reset(sockets[1]);
+    fd1->reset(sockets[0]);
+    fd2->reset(sockets[1]);
     return true;
 }
 
@@ -155,7 +155,7 @@
 
     const std::string& command() const { return command_; }
 
-    int local_socket_fd() const { return local_socket_sfd_.fd(); }
+    int local_socket_fd() const { return local_socket_sfd_; }
 
     pid_t pid() const { return pid_; }
 
@@ -165,19 +165,19 @@
 
   private:
     // Opens the file at |pts_name|.
-    int OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd);
+    int OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd);
 
     static void ThreadHandler(void* userdata);
     void PassDataStreams();
     void WaitForExit();
 
-    ScopedFd* SelectLoop(fd_set* master_read_set_ptr,
-                         fd_set* master_write_set_ptr);
+    unique_fd* SelectLoop(fd_set* master_read_set_ptr,
+                          fd_set* master_write_set_ptr);
 
     // Input/output stream handlers. Success returns nullptr, failure returns
     // a pointer to the failed FD.
-    ScopedFd* PassInput();
-    ScopedFd* PassOutput(ScopedFd* sfd, ShellProtocol::Id id);
+    unique_fd* PassInput();
+    unique_fd* PassOutput(unique_fd* sfd, ShellProtocol::Id id);
 
     const std::string command_;
     const std::string terminal_type_;
@@ -185,10 +185,10 @@
     SubprocessType type_;
     SubprocessProtocol protocol_;
     pid_t pid_ = -1;
-    ScopedFd local_socket_sfd_;
+    unique_fd local_socket_sfd_;
 
     // Shell protocol variables.
-    ScopedFd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
+    unique_fd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
     std::unique_ptr<ShellProtocol> input_, output_;
     size_t input_bytes_left_ = 0;
 
@@ -220,8 +220,8 @@
 }
 
 bool Subprocess::ForkAndExec(std::string* error) {
-    ScopedFd child_stdinout_sfd, child_stderr_sfd;
-    ScopedFd parent_error_sfd, child_error_sfd;
+    unique_fd child_stdinout_sfd, child_stderr_sfd;
+    unique_fd parent_error_sfd, child_error_sfd;
     char pts_name[PATH_MAX];
 
     if (command_.empty()) {
@@ -285,7 +285,7 @@
         int fd;
         pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
         if (pid_ > 0) {
-          stdinout_sfd_.Reset(fd);
+          stdinout_sfd_.reset(fd);
         }
     } else {
         if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
@@ -313,40 +313,39 @@
         init_subproc_child();
 
         if (type_ == SubprocessType::kPty) {
-            child_stdinout_sfd.Reset(OpenPtyChildFd(pts_name, &child_error_sfd));
+            child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd));
         }
 
-        dup2(child_stdinout_sfd.fd(), STDIN_FILENO);
-        dup2(child_stdinout_sfd.fd(), STDOUT_FILENO);
-        dup2(child_stderr_sfd.valid() ? child_stderr_sfd.fd() : child_stdinout_sfd.fd(),
-             STDERR_FILENO);
+        dup2(child_stdinout_sfd, STDIN_FILENO);
+        dup2(child_stdinout_sfd, STDOUT_FILENO);
+        dup2(child_stderr_sfd != -1 ? child_stderr_sfd : child_stdinout_sfd, STDERR_FILENO);
 
         // exec doesn't trigger destructors, close the FDs manually.
-        stdinout_sfd_.Reset();
-        stderr_sfd_.Reset();
-        child_stdinout_sfd.Reset();
-        child_stderr_sfd.Reset();
-        parent_error_sfd.Reset();
-        close_on_exec(child_error_sfd.fd());
+        stdinout_sfd_.reset(-1);
+        stderr_sfd_.reset(-1);
+        child_stdinout_sfd.reset(-1);
+        child_stderr_sfd.reset(-1);
+        parent_error_sfd.reset(-1);
+        close_on_exec(child_error_sfd);
 
         if (command_.empty()) {
             execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
         } else {
             execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
         }
-        WriteFdExactly(child_error_sfd.fd(), "exec '" _PATH_BSHELL "' failed: ");
-        WriteFdExactly(child_error_sfd.fd(), strerror(errno));
-        child_error_sfd.Reset();
+        WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: ");
+        WriteFdExactly(child_error_sfd, strerror(errno));
+        child_error_sfd.reset(-1);
         _Exit(1);
     }
 
     // Subprocess parent.
     D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
-      stdinout_sfd_.fd(), stderr_sfd_.fd());
+      stdinout_sfd_.get(), stderr_sfd_.get());
 
     // Wait to make sure the subprocess exec'd without error.
-    child_error_sfd.Reset();
-    std::string error_message = ReadAll(parent_error_sfd.fd());
+    child_error_sfd.reset(-1);
+    std::string error_message = ReadAll(parent_error_sfd);
     if (!error_message.empty()) {
         *error = error_message;
         return false;
@@ -356,7 +355,7 @@
     if (protocol_ == SubprocessProtocol::kNone) {
         // No protocol: all streams pass through the stdinout FD and hook
         // directly into the local socket for raw data transfer.
-        local_socket_sfd_.Reset(stdinout_sfd_.Release());
+        local_socket_sfd_.reset(stdinout_sfd_.release());
     } else {
         // Shell protocol: create another socketpair to intercept data.
         if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
@@ -365,10 +364,10 @@
             kill(pid_, SIGKILL);
             return false;
         }
-        D("protocol FD = %d", protocol_sfd_.fd());
+        D("protocol FD = %d", protocol_sfd_.get());
 
-        input_.reset(new ShellProtocol(protocol_sfd_.fd()));
-        output_.reset(new ShellProtocol(protocol_sfd_.fd()));
+        input_.reset(new ShellProtocol(protocol_sfd_));
+        output_.reset(new ShellProtocol(protocol_sfd_));
         if (!input_ || !output_) {
             *error = "failed to allocate shell protocol objects";
             kill(pid_, SIGKILL);
@@ -379,7 +378,7 @@
         // likely but could happen under unusual circumstances, such as if we
         // write a ton of data to stdin but the subprocess never reads it and
         // the pipe fills up.
-        for (int fd : {stdinout_sfd_.fd(), stderr_sfd_.fd()}) {
+        for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) {
             if (fd >= 0) {
                 if (!set_file_block_mode(fd, false)) {
                     *error = android::base::StringPrintf(
@@ -402,7 +401,7 @@
     return true;
 }
 
-int Subprocess::OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd) {
+int Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) {
     int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
     if (child_fd == -1) {
         // Don't use WriteFdFmt; since we're in the fork() child we don't want
@@ -410,7 +409,7 @@
         const char* messages[] = {"child failed to open pseudo-term slave ",
                                   pts_name, ": ", strerror(errno)};
         for (const char* message : messages) {
-            WriteFdExactly(error_sfd->fd(), message);
+            WriteFdExactly(*error_sfd, message);
         }
         abort();
     }
@@ -419,16 +418,16 @@
         termios tattr;
         if (tcgetattr(child_fd, &tattr) == -1) {
             int saved_errno = errno;
-            WriteFdExactly(error_sfd->fd(), "tcgetattr failed: ");
-            WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
+            WriteFdExactly(*error_sfd, "tcgetattr failed: ");
+            WriteFdExactly(*error_sfd, strerror(saved_errno));
             abort();
         }
 
         cfmakeraw(&tattr);
         if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
             int saved_errno = errno;
-            WriteFdExactly(error_sfd->fd(), "tcsetattr failed: ");
-            WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
+            WriteFdExactly(*error_sfd, "tcsetattr failed: ");
+            WriteFdExactly(*error_sfd, strerror(saved_errno));
             abort();
         }
     }
@@ -449,7 +448,7 @@
 }
 
 void Subprocess::PassDataStreams() {
-    if (!protocol_sfd_.valid()) {
+    if (protocol_sfd_ == -1) {
         return;
     }
 
@@ -457,21 +456,20 @@
     fd_set master_read_set, master_write_set;
     FD_ZERO(&master_read_set);
     FD_ZERO(&master_write_set);
-    for (ScopedFd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
-        if (sfd->valid()) {
-            FD_SET(sfd->fd(), &master_read_set);
+    for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
+        if (*sfd != -1) {
+            FD_SET(*sfd, &master_read_set);
         }
     }
 
     // Pass data until the protocol FD or both the subprocess pipes die, at
     // which point we can't pass any more data.
-    while (protocol_sfd_.valid() &&
-            (stdinout_sfd_.valid() || stderr_sfd_.valid())) {
-        ScopedFd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
+    while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
+        unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
         if (dead_sfd) {
-            D("closing FD %d", dead_sfd->fd());
-            FD_CLR(dead_sfd->fd(), &master_read_set);
-            FD_CLR(dead_sfd->fd(), &master_write_set);
+            D("closing FD %d", dead_sfd->get());
+            FD_CLR(*dead_sfd, &master_read_set);
+            FD_CLR(*dead_sfd, &master_write_set);
             if (dead_sfd == &protocol_sfd_) {
                 // Using SIGHUP is a decent general way to indicate that the
                 // controlling process is going away. If specific signals are
@@ -480,25 +478,24 @@
                 D("protocol FD died, sending SIGHUP to pid %d", pid_);
                 kill(pid_, SIGHUP);
             }
-            dead_sfd->Reset();
+            dead_sfd->reset(-1);
         }
     }
 }
 
 namespace {
 
-inline bool ValidAndInSet(const ScopedFd& sfd, fd_set* set) {
-    return sfd.valid() && FD_ISSET(sfd.fd(), set);
+inline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) {
+    return sfd != -1 && FD_ISSET(sfd, set);
 }
 
 }   // namespace
 
-ScopedFd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
-                                 fd_set* master_write_set_ptr) {
+unique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
+                                  fd_set* master_write_set_ptr) {
     fd_set read_set, write_set;
-    int select_n = std::max(std::max(protocol_sfd_.fd(), stdinout_sfd_.fd()),
-                            stderr_sfd_.fd()) + 1;
-    ScopedFd* dead_sfd = nullptr;
+    int select_n = std::max(std::max(protocol_sfd_, stdinout_sfd_), stderr_sfd_) + 1;
+    unique_fd* dead_sfd = nullptr;
 
     // Keep calling select() and passing data until an FD closes/errors.
     while (!dead_sfd) {
@@ -509,8 +506,8 @@
                 continue;
             } else {
                 PLOG(ERROR) << "select failed, closing subprocess pipes";
-                stdinout_sfd_.Reset();
-                stderr_sfd_.Reset();
+                stdinout_sfd_.reset(-1);
+                stderr_sfd_.reset(-1);
                 return nullptr;
             }
         }
@@ -530,8 +527,8 @@
             dead_sfd = PassInput();
             // If we didn't finish writing, block on stdin write.
             if (input_bytes_left_) {
-                FD_CLR(protocol_sfd_.fd(), master_read_set_ptr);
-                FD_SET(stdinout_sfd_.fd(), master_write_set_ptr);
+                FD_CLR(protocol_sfd_, master_read_set_ptr);
+                FD_SET(stdinout_sfd_, master_write_set_ptr);
             }
         }
 
@@ -540,8 +537,8 @@
             dead_sfd = PassInput();
             // If we finished writing, go back to blocking on protocol read.
             if (!input_bytes_left_) {
-                FD_SET(protocol_sfd_.fd(), master_read_set_ptr);
-                FD_CLR(stdinout_sfd_.fd(), master_write_set_ptr);
+                FD_SET(protocol_sfd_, master_read_set_ptr);
+                FD_CLR(stdinout_sfd_, master_write_set_ptr);
             }
         }
     }  // while (!dead_sfd)
@@ -549,19 +546,18 @@
     return dead_sfd;
 }
 
-ScopedFd* Subprocess::PassInput() {
+unique_fd* Subprocess::PassInput() {
     // Only read a new packet if we've finished writing the last one.
     if (!input_bytes_left_) {
         if (!input_->Read()) {
             // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
             if (errno != 0) {
-                PLOG(ERROR) << "error reading protocol FD "
-                            << protocol_sfd_.fd();
+                PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
             }
             return &protocol_sfd_;
         }
 
-        if (stdinout_sfd_.valid()) {
+        if (stdinout_sfd_ != -1) {
             switch (input_->id()) {
                 case ShellProtocol::kIdWindowSizeChange:
                     int rows, cols, x_pixels, y_pixels;
@@ -572,7 +568,7 @@
                         ws.ws_col = cols;
                         ws.ws_xpixel = x_pixels;
                         ws.ws_ypixel = y_pixels;
-                        ioctl(stdinout_sfd_.fd(), TIOCSWINSZ, &ws);
+                        ioctl(stdinout_sfd_, TIOCSWINSZ, &ws);
                     }
                     break;
                 case ShellProtocol::kIdStdin:
@@ -580,11 +576,11 @@
                     break;
                 case ShellProtocol::kIdCloseStdin:
                     if (type_ == SubprocessType::kRaw) {
-                        if (adb_shutdown(stdinout_sfd_.fd(), SHUT_WR) == 0) {
+                        if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
                             return nullptr;
                         }
                         PLOG(ERROR) << "failed to shutdown writes to FD "
-                                    << stdinout_sfd_.fd();
+                                    << stdinout_sfd_;
                         return &stdinout_sfd_;
                     } else {
                         // PTYs can't close just input, so rather than close the
@@ -593,7 +589,7 @@
                         // non-interactively which is rare and unsupported.
                         // If necessary, the client can manually close the shell
                         // with `exit` or by killing the adb client process.
-                        D("can't close input for PTY FD %d", stdinout_sfd_.fd());
+                        D("can't close input for PTY FD %d", stdinout_sfd_.get());
                     }
                     break;
             }
@@ -602,11 +598,10 @@
 
     if (input_bytes_left_ > 0) {
         int index = input_->data_length() - input_bytes_left_;
-        int bytes = adb_write(stdinout_sfd_.fd(), input_->data() + index,
-                              input_bytes_left_);
+        int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
         if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
             if (bytes < 0) {
-                PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.fd();
+                PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_;
             }
             // stdin is done, mark this packet as finished and we'll just start
             // dumping any further data received from the protocol FD.
@@ -620,20 +615,20 @@
     return nullptr;
 }
 
-ScopedFd* Subprocess::PassOutput(ScopedFd* sfd, ShellProtocol::Id id) {
-    int bytes = adb_read(sfd->fd(), output_->data(), output_->data_capacity());
+unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
+    int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
     if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
         // read() returns EIO if a PTY closes; don't report this as an error,
         // it just means the subprocess completed.
         if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
-            PLOG(ERROR) << "error reading output FD " << sfd->fd();
+            PLOG(ERROR) << "error reading output FD " << *sfd;
         }
         return sfd;
     }
 
     if (bytes > 0 && !output_->Write(id, bytes)) {
         if (errno != 0) {
-            PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.fd();
+            PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
         }
         return &protocol_sfd_;
     }
@@ -665,25 +660,25 @@
     }
 
     // If we have an open protocol FD send an exit packet.
-    if (protocol_sfd_.valid()) {
+    if (protocol_sfd_ != -1) {
         output_->data()[0] = exit_code;
         if (output_->Write(ShellProtocol::kIdExit, 1)) {
             D("wrote the exit code packet: %d", exit_code);
         } else {
             PLOG(ERROR) << "failed to write the exit code packet";
         }
-        protocol_sfd_.Reset();
+        protocol_sfd_.reset(-1);
     }
 
     // Pass the local socket FD to the shell cleanup fdevent.
     if (SHELL_EXIT_NOTIFY_FD >= 0) {
-        int fd = local_socket_sfd_.fd();
+        int fd = local_socket_sfd_;
         if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
             D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
               fd, SHELL_EXIT_NOTIFY_FD, pid_);
             // The shell exit fdevent now owns the FD and will close it once
             // the last bit of data flushes through.
-            local_socket_sfd_.Release();
+            static_cast<void>(local_socket_sfd_.release());
         } else {
             PLOG(ERROR) << "failed to write fd " << fd
                         << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index 639f8eb..212c1c3 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -269,9 +269,6 @@
 int unix_isatty(int fd);
 #define  isatty  ___xxx_isatty
 
-/* normally provided by <cutils/misc.h> */
-extern void*  load_file(const char*  pathname, unsigned*  psize);
-
 static __inline__ void  adb_sleep_ms( int  mseconds )
 {
     Sleep( mseconds );
@@ -458,7 +455,6 @@
 
 #else /* !_WIN32 a.k.a. Unix */
 
-#include <cutils/misc.h>
 #include <cutils/sockets.h>
 #include <cutils/threads.h>
 #include <fcntl.h>
diff --git a/adb/sysdeps/condition_variable.h b/adb/sysdeps/condition_variable.h
new file mode 100644
index 0000000..117cd40
--- /dev/null
+++ b/adb/sysdeps/condition_variable.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#pragma once
+
+#include <condition_variable>
+
+#include "sysdeps/mutex.h"
+
+#if defined(_WIN32)
+
+#include <windows.h>
+
+#include <android-base/macros.h>
+
+// The prebuilt version of mingw we use doesn't support condition_variable.
+// Therefore, implement our own using the Windows primitives.
+// Put them directly into the std namespace, so that when they're actually available, the build
+// breaks until they're removed.
+
+namespace std {
+
+class condition_variable {
+  public:
+    condition_variable() {
+        InitializeConditionVariable(&cond_);
+    }
+
+    void wait(std::unique_lock<std::mutex>& lock) {
+        std::mutex *m = lock.mutex();
+        m->lock_count_--;
+        SleepConditionVariableCS(&cond_, m->native_handle(), INFINITE);
+        m->lock_count_++;
+    }
+
+    void notify_one() {
+        WakeConditionVariable(&cond_);
+    }
+
+  private:
+    CONDITION_VARIABLE cond_;
+
+    DISALLOW_COPY_AND_ASSIGN(condition_variable);
+};
+
+}
+
+#endif  // defined(_WIN32)
diff --git a/adb/sysdeps/mutex.h b/adb/sysdeps/mutex.h
index 73c9e6e..226f7f1 100644
--- a/adb/sysdeps/mutex.h
+++ b/adb/sysdeps/mutex.h
@@ -1,5 +1,3 @@
-#pragma once
-
 /*
  * Copyright (C) 2016 The Android Open Source Project
  *
@@ -16,6 +14,7 @@
  * limitations under the License.
  */
 
+#pragma once
 #if defined(_WIN32)
 
 #include <windows.h>
@@ -35,34 +34,42 @@
 // CRITICAL_SECTION is recursive, so just wrap it in a Mutex-compatible class.
 class recursive_mutex {
   public:
+    typedef CRITICAL_SECTION* native_handle_type;
+
     recursive_mutex() {
-        InitializeCriticalSection(&mutex_);
+        InitializeCriticalSection(&cs_);
     }
 
     ~recursive_mutex() {
-        DeleteCriticalSection(&mutex_);
+        DeleteCriticalSection(&cs_);
     }
 
     void lock() {
-        EnterCriticalSection(&mutex_);
+        EnterCriticalSection(&cs_);
     }
 
     bool try_lock() {
-        return TryEnterCriticalSection(&mutex_);
+        return TryEnterCriticalSection(&cs_);
     }
 
     void unlock() {
-        LeaveCriticalSection(&mutex_);
+        LeaveCriticalSection(&cs_);
+    }
+
+    native_handle_type native_handle() {
+        return &cs_;
     }
 
   private:
-    CRITICAL_SECTION mutex_;
+    CRITICAL_SECTION cs_;
 
     DISALLOW_COPY_AND_ASSIGN(recursive_mutex);
 };
 
 class mutex {
   public:
+    typedef CRITICAL_SECTION* native_handle_type;
+
     mutex() {
     }
 
@@ -97,11 +104,17 @@
         return true;
     }
 
+    native_handle_type native_handle() {
+        return mutex_.native_handle();
+    }
+
   private:
     recursive_mutex mutex_;
     size_t lock_count_ = 0;
+
+    friend class condition_variable;
 };
 
 }
 
-#endif
+#endif  // defined(_WIN32)
diff --git a/adb/sysdeps_test.cpp b/adb/sysdeps_test.cpp
index 395d22d..740f283 100644
--- a/adb/sysdeps_test.cpp
+++ b/adb/sysdeps_test.cpp
@@ -20,6 +20,8 @@
 
 #include "adb_io.h"
 #include "sysdeps.h"
+#include "sysdeps/condition_variable.h"
+#include "sysdeps/mutex.h"
 
 static void increment_atomic_int(void* c) {
     sleep(1);
@@ -245,7 +247,6 @@
     }
 }
 
-#include "sysdeps/mutex.h"
 TEST(sysdeps_mutex, mutex_smoke) {
     static std::atomic<bool> finished(false);
     static std::mutex &m = *new std::mutex();
@@ -301,3 +302,21 @@
     m.lock();
     m.unlock();
 }
+
+TEST(sysdeps_condition_variable, smoke) {
+    static std::mutex &m = *new std::mutex;
+    static std::condition_variable &cond = *new std::condition_variable;
+    static volatile bool flag = false;
+
+    std::unique_lock<std::mutex> lock(m);
+    adb_thread_create([](void*) {
+        m.lock();
+        flag = true;
+        cond.notify_one();
+        m.unlock();
+    }, nullptr);
+
+    while (!flag) {
+        cond.wait(lock);
+    }
+}
diff --git a/adb/sysdeps_win32.cpp b/adb/sysdeps_win32.cpp
index faf7f3e..f94d6fc 100644
--- a/adb/sysdeps_win32.cpp
+++ b/adb/sysdeps_win32.cpp
@@ -110,62 +110,6 @@
 /**************************************************************************/
 /**************************************************************************/
 /*****                                                                *****/
-/*****      replaces libs/cutils/load_file.c                          *****/
-/*****                                                                *****/
-/**************************************************************************/
-/**************************************************************************/
-
-void *load_file(const char *fn, unsigned *_sz)
-{
-    HANDLE    file;
-    char     *data;
-    DWORD     file_size;
-
-    std::wstring fn_wide;
-    if (!android::base::UTF8ToWide(fn, &fn_wide))
-        return NULL;
-
-    file = CreateFileW( fn_wide.c_str(),
-                        GENERIC_READ,
-                        FILE_SHARE_READ,
-                        NULL,
-                        OPEN_EXISTING,
-                        0,
-                        NULL );
-
-    if (file == INVALID_HANDLE_VALUE)
-        return NULL;
-
-    file_size = GetFileSize( file, NULL );
-    data      = NULL;
-
-    if (file_size > 0) {
-        data = (char*) malloc( file_size + 1 );
-        if (data == NULL) {
-            D("load_file: could not allocate %ld bytes", file_size );
-            file_size = 0;
-        } else {
-            DWORD  out_bytes;
-
-            if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
-                 out_bytes != file_size )
-            {
-                D("load_file: could not read %ld bytes from '%s'", file_size, fn);
-                free(data);
-                data      = NULL;
-                file_size = 0;
-            }
-        }
-    }
-    CloseHandle( file );
-
-    *_sz = (unsigned) file_size;
-    return  data;
-}
-
-/**************************************************************************/
-/**************************************************************************/
-/*****                                                                *****/
 /*****    common file descriptor handling                             *****/
 /*****                                                                *****/
 /**************************************************************************/
diff --git a/adb/transport.cpp b/adb/transport.cpp
index 55082a5..65b05b8 100644
--- a/adb/transport.cpp
+++ b/adb/transport.cpp
@@ -952,6 +952,8 @@
     for (const auto& transport : pending_list) {
         if (transport->serial && strcmp(serial, transport->serial) == 0) {
             adb_mutex_unlock(&transport_lock);
+            VLOG(TRANSPORT) << "socket transport " << transport->serial
+                << " is already in pending_list and fails to register";
             delete t;
             return -1;
         }
@@ -960,6 +962,8 @@
     for (const auto& transport : transport_list) {
         if (transport->serial && strcmp(serial, transport->serial) == 0) {
             adb_mutex_unlock(&transport_lock);
+            VLOG(TRANSPORT) << "socket transport " << transport->serial
+                << " is already in transport_list and fails to register";
             delete t;
             return -1;
         }
@@ -992,8 +996,7 @@
 void kick_all_tcp_devices() {
     adb_mutex_lock(&transport_lock);
     for (auto& t : transport_list) {
-        // TCP/IP devices have adb_port == 0.
-        if (t->type == kTransportLocal && t->adb_port == 0) {
+        if (t->IsTcpDevice()) {
             // Kicking breaks the read_transport thread of this transport out of any read, then
             // the read_transport thread will notify the main thread to make this transport
             // offline. Then the main thread will notify the write_transport thread to exit.
diff --git a/adb/transport.h b/adb/transport.h
index 35d7b50..46d472b 100644
--- a/adb/transport.h
+++ b/adb/transport.h
@@ -87,7 +87,22 @@
     char* model = nullptr;
     char* device = nullptr;
     char* devpath = nullptr;
-    int adb_port = -1;  // Use for emulators (local transport)
+    void SetLocalPortForEmulator(int port) {
+        CHECK_EQ(local_port_for_emulator_, -1);
+        local_port_for_emulator_ = port;
+    }
+
+    bool GetLocalPortForEmulator(int* port) const {
+        if (type == kTransportLocal && local_port_for_emulator_ != -1) {
+            *port = local_port_for_emulator_;
+            return true;
+        }
+        return false;
+    }
+
+    bool IsTcpDevice() const {
+        return type == kTransportLocal && local_port_for_emulator_ == -1;
+    }
 
     void* key = nullptr;
     unsigned char token[TOKEN_SIZE] = {};
@@ -128,6 +143,7 @@
     bool MatchesTarget(const std::string& target) const;
 
 private:
+    int local_port_for_emulator_ = -1;
     bool kicked_ = false;
     void (*kick_func_)(atransport*) = nullptr;
 
diff --git a/adb/transport_local.cpp b/adb/transport_local.cpp
index c1c88a9..31b5ad6 100644
--- a/adb/transport_local.cpp
+++ b/adb/transport_local.cpp
@@ -17,6 +17,8 @@
 #define TRACE_TAG TRANSPORT
 
 #include "sysdeps.h"
+#include "sysdeps/condition_variable.h"
+#include "sysdeps/mutex.h"
 #include "transport.h"
 
 #include <errno.h>
@@ -25,6 +27,8 @@
 #include <string.h>
 #include <sys/types.h>
 
+#include <vector>
+
 #include <android-base/stringprintf.h>
 #include <cutils/sockets.h>
 
@@ -85,9 +89,9 @@
     return 0;
 }
 
-void local_connect(int port) {
+bool local_connect(int port) {
     std::string dummy;
-    local_connect_arbitrary_ports(port-1, port, &dummy);
+    return local_connect_arbitrary_ports(port-1, port, &dummy) == 0;
 }
 
 int local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error) {
@@ -121,18 +125,71 @@
 }
 
 #if ADB_HOST
+
+static void PollAllLocalPortsForEmulator() {
+    int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
+    int count = ADB_LOCAL_TRANSPORT_MAX;
+
+    // Try to connect to any number of running emulator instances.
+    for ( ; count > 0; count--, port += 2 ) {
+        local_connect(port);
+    }
+}
+
+// Retry the disconnected local port for 60 times, and sleep 1 second between two retries.
+constexpr uint32_t LOCAL_PORT_RETRY_COUNT = 60;
+constexpr uint32_t LOCAL_PORT_RETRY_INTERVAL_IN_MS = 1000;
+
+struct RetryPort {
+    int port;
+    uint32_t retry_count;
+};
+
+// Retry emulators just kicked.
+static std::vector<RetryPort>& retry_ports = *new std::vector<RetryPort>;
+std::mutex &retry_ports_lock = *new std::mutex;
+std::condition_variable &retry_ports_cond = *new std::condition_variable;
+
 static void client_socket_thread(void* x) {
     adb_thread_setname("client_socket_thread");
     D("transport: client_socket_thread() starting");
+    PollAllLocalPortsForEmulator();
     while (true) {
-        int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
-        int count = ADB_LOCAL_TRANSPORT_MAX;
-
-        // Try to connect to any number of running emulator instances.
-        for ( ; count > 0; count--, port += 2 ) {
-            local_connect(port);
+        std::vector<RetryPort> ports;
+        // Collect retry ports.
+        {
+            std::unique_lock<std::mutex> lock(retry_ports_lock);
+            while (retry_ports.empty()) {
+                retry_ports_cond.wait(lock);
+            }
+            retry_ports.swap(ports);
         }
-        sleep(1);
+        // Sleep here instead of the end of loop, because if we immediately try to reconnect
+        // the emulator just kicked, the adbd on the emulator may not have time to remove the
+        // just kicked transport.
+        adb_sleep_ms(LOCAL_PORT_RETRY_INTERVAL_IN_MS);
+
+        // Try connecting retry ports.
+        std::vector<RetryPort> next_ports;
+        for (auto& port : ports) {
+            VLOG(TRANSPORT) << "retry port " << port.port << ", last retry_count "
+                << port.retry_count;
+            if (local_connect(port.port)) {
+                VLOG(TRANSPORT) << "retry port " << port.port << " successfully";
+                continue;
+            }
+            if (--port.retry_count > 0) {
+                next_ports.push_back(port);
+            } else {
+                VLOG(TRANSPORT) << "stop retrying port " << port.port;
+            }
+        }
+
+        // Copy back left retry ports.
+        {
+            std::unique_lock<std::mutex> lock(retry_ports_lock);
+            retry_ports.insert(retry_ports.end(), next_ports.begin(), next_ports.end());
+        }
     }
 }
 
@@ -341,17 +398,32 @@
         t->sfd = -1;
         adb_close(fd);
     }
+#if ADB_HOST
+    int local_port;
+    if (t->GetLocalPortForEmulator(&local_port)) {
+        VLOG(TRANSPORT) << "remote_close, local_port = " << local_port;
+        std::unique_lock<std::mutex> lock(retry_ports_lock);
+        RetryPort port;
+        port.port = local_port;
+        port.retry_count = LOCAL_PORT_RETRY_COUNT;
+        retry_ports.push_back(port);
+        retry_ports_cond.notify_one();
+    }
+#endif
 }
 
 
 #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)
+static 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];
+        int local_port;
+        if (local_transports[i] && local_transports[i]->GetLocalPortForEmulator(&local_port)) {
+            if (local_port == adb_port) {
+                return local_transports[i];
+            }
         }
     }
     return NULL;
@@ -398,13 +470,12 @@
     t->sync_token = 1;
     t->connection_state = kCsOffline;
     t->type = kTransportLocal;
-    t->adb_port = 0;
 
 #if ADB_HOST
     if (local) {
         adb_mutex_lock( &local_transports_lock );
         {
-            t->adb_port = adb_port;
+            t->SetLocalPortForEmulator(adb_port);
             atransport* existing_transport =
                     find_emulator_transport_by_adb_port_locked(adb_port);
             int index = get_available_local_transport_index_locked();
diff --git a/base/include/android-base/logging.h b/base/include/android-base/logging.h
index b86c232..56e2dde 100644
--- a/base/include/android-base/logging.h
+++ b/base/include/android-base/logging.h
@@ -194,13 +194,13 @@
 
 // Helper for CHECK_STRxx(s1,s2) macros.
 #define CHECK_STROP(s1, s2, sense)                                         \
-  if (LIKELY((strcmp(s1, s2) == 0) == sense))                              \
+  if (LIKELY((strcmp(s1, s2) == 0) == (sense)))                            \
     ;                                                                      \
   else                                                                     \
     ABORT_AFTER_LOG_FATAL                                                  \
     LOG(FATAL) << "Check failed: "                                         \
-               << "\"" << s1 << "\""                                       \
-               << (sense ? " == " : " != ") << "\"" << s2 << "\""
+               << "\"" << (s1) << "\""                                     \
+               << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
 
 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
@@ -213,7 +213,7 @@
     if (rc != 0) {                                                     \
       errno = rc;                                                      \
       ABORT_AFTER_LOG_FATAL                                            \
-      PLOG(FATAL) << #call << " failed for " << what; \
+      PLOG(FATAL) << #call << " failed for " << (what);                \
     }                                                                  \
   } while (false)
 
diff --git a/fs_mgr/Android.mk b/fs_mgr/Android.mk
index d0d5630..7da3ca4 100644
--- a/fs_mgr/Android.mk
+++ b/fs_mgr/Android.mk
@@ -10,7 +10,8 @@
     libcrypto_utils_static \
     libcrypto_static \
     libext4_utils_static \
-    libsquashfs_utils
+    libsquashfs_utils \
+    libselinux
 
 include $(CLEAR_VARS)
 LOCAL_CLANG := true
diff --git a/fs_mgr/fs_mgr_format.c b/fs_mgr/fs_mgr_format.c
index c63ff67..6c5b1eb 100644
--- a/fs_mgr/fs_mgr_format.c
+++ b/fs_mgr/fs_mgr_format.c
@@ -23,6 +23,11 @@
 #include <errno.h>
 #include <cutils/partition_utils.h>
 #include <sys/mount.h>
+
+#include <selinux/selinux.h>
+#include <selinux/label.h>
+#include <selinux/android.h>
+
 #include "ext4_utils.h"
 #include "ext4.h"
 #include "make_ext4fs.h"
@@ -47,17 +52,29 @@
         return -1;
     }
 
+    struct selabel_handle *sehandle = selinux_android_file_context_handle();
+    if (!sehandle) {
+        /* libselinux logs specific error */
+        ERROR("Cannot initialize android file_contexts");
+        close(fd);
+        return -1;
+    }
+
     /* Format the partition using the calculated length */
     reset_ext4fs_info();
     info.len = (off64_t)dev_sz;
 
     /* Use make_ext4fs_internal to avoid wiping an already-wiped partition. */
-    rc = make_ext4fs_internal(fd, NULL, NULL, fs_mnt_point, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL);
+    rc = make_ext4fs_internal(fd, NULL, NULL, fs_mnt_point, 0, 0, 0, 0, 0, 0, sehandle, 0, 0, NULL);
     if (rc) {
         ERROR("make_ext4fs returned %d.\n", rc);
     }
     close(fd);
 
+    if (sehandle) {
+        selabel_close(sehandle);
+    }
+
     return rc;
 }
 
diff --git a/fs_mgr/fs_mgr_priv_verity.h b/fs_mgr/fs_mgr_priv_verity.h
index cd673f3..d9e17bb 100644
--- a/fs_mgr/fs_mgr_priv_verity.h
+++ b/fs_mgr/fs_mgr_priv_verity.h
@@ -16,8 +16,8 @@
 
 #include <sys/cdefs.h>
 
-#define FS_MGR_SETUP_VERITY_DISABLED -2
-#define FS_MGR_SETUP_VERITY_FAIL -1
+#define FS_MGR_SETUP_VERITY_DISABLED (-2)
+#define FS_MGR_SETUP_VERITY_FAIL (-1)
 #define FS_MGR_SETUP_VERITY_SUCCESS 0
 
 __BEGIN_DECLS
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
index c5e1f32..b498618 100644
--- a/fs_mgr/include/fs_mgr.h
+++ b/fs_mgr/include/fs_mgr.h
@@ -80,11 +80,11 @@
 #define FS_MGR_MNTALL_DEV_NEEDS_ENCRYPTION 2
 #define FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED 1
 #define FS_MGR_MNTALL_DEV_NOT_ENCRYPTED 0
-#define FS_MGR_MNTALL_FAIL -1
+#define FS_MGR_MNTALL_FAIL (-1)
 int fs_mgr_mount_all(struct fstab *fstab);
 
-#define FS_MGR_DOMNT_FAILED -1
-#define FS_MGR_DOMNT_BUSY -2
+#define FS_MGR_DOMNT_FAILED (-1)
+#define FS_MGR_DOMNT_BUSY (-2)
 int fs_mgr_do_mount(struct fstab *fstab, char *n_name, char *n_blk_device,
                     char *tmp_mount_point);
 int fs_mgr_do_tmpfs_mount(char *n_name);
diff --git a/init/ueventd_parser.cpp b/init/ueventd_parser.cpp
index 09f4638..baff58c 100644
--- a/init/ueventd_parser.cpp
+++ b/init/ueventd_parser.cpp
@@ -38,7 +38,7 @@
 #include "ueventd_keywords.h"
 
 #define KEYWORD(symbol, flags, nargs) \
-    [ K_##symbol ] = { #symbol, nargs + 1, flags, },
+    [ K_##symbol ] = { #symbol, (nargs) + 1, flags, },
 
 static struct {
     const char *name;
diff --git a/libbacktrace/Android.mk b/libbacktrace/Android.mk
index 632b1b6..356ab8b 100644
--- a/libbacktrace/Android.mk
+++ b/libbacktrace/Android.mk
@@ -25,7 +25,9 @@
 
 libbacktrace_common_cppflags := \
 	-std=gnu++11 \
-	-I external/libunwind/include/tdep \
+
+libbacktrace_common_c_includes := \
+	external/libunwind/include/tdep \
 
 # The latest clang (r230699) does not allow SP/PC to be declared in inline asm lists.
 libbacktrace_common_clang_cflags += \
diff --git a/libbinderwrapper/real_binder_wrapper.h b/libbinderwrapper/real_binder_wrapper.h
index 1675432..fa05383 100644
--- a/libbinderwrapper/real_binder_wrapper.h
+++ b/libbinderwrapper/real_binder_wrapper.h
@@ -17,6 +17,8 @@
 #ifndef SYSTEM_CORE_LIBBINDERWRAPPER_REAL_BINDER_WRAPPER_H_
 #define SYSTEM_CORE_LIBBINDERWRAPPER_REAL_BINDER_WRAPPER_H_
 
+#include <map>
+
 #include <base/macros.h>
 #include <binderwrapper/binder_wrapper.h>
 
diff --git a/libcutils/strdup8to16.c b/libcutils/strdup8to16.c
index 63e5ca4..c23cf8b 100644
--- a/libcutils/strdup8to16.c
+++ b/libcutils/strdup8to16.c
@@ -27,7 +27,7 @@
 #define UTF16_REPLACEMENT_CHAR 0xfffd
 
 /* Clever trick from Dianne that returns 1-4 depending on leading bit sequence*/
-#define UTF8_SEQ_LENGTH(ch) (((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1)
+#define UTF8_SEQ_LENGTH(ch) (((0xe5000000 >> (((ch) >> 3) & 0x1e)) & 3) + 1)
 
 /* note: macro expands to multiple lines */
 #define UTF8_SHIFT_AND_MASK(unicode, byte)  \
diff --git a/liblog/Android.bp b/liblog/Android.bp
index 7a95dbd..81a510e 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -24,7 +24,6 @@
 ]
 liblog_host_sources = [
     "fake_log_device.c",
-    //"event.logtags",
     "fake_writer.c",
 ]
 liblog_target_sources = [
@@ -87,6 +86,7 @@
         "-DLIBLOG_LOG_TAG=1005",
         "-DSNET_EVENT_LOG_TAG=1397638484",
     ],
+    logtags: ["event.logtags"],
     compile_multilib: "both",
     stl: "none",
 }
diff --git a/libnativebridge/Android.mk b/libnativebridge/Android.mk
index d20d44c..b88621e 100644
--- a/libnativebridge/Android.mk
+++ b/libnativebridge/Android.mk
@@ -10,12 +10,11 @@
 LOCAL_MODULE:= libnativebridge
 
 LOCAL_SRC_FILES:= $(NATIVE_BRIDGE_COMMON_SRC_FILES)
-LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_SHARED_LIBRARIES := liblog libdl
 LOCAL_CLANG := true
 LOCAL_CPP_EXTENSION := .cc
 LOCAL_CFLAGS += -Werror -Wall
 LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
-LOCAL_LDFLAGS := -ldl
 LOCAL_MULTILIB := both
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/libnativebridge/tests/Android.nativebridge-dummy.mk b/libnativebridge/tests/Android.nativebridge-dummy.mk
index 2efc176..551765a 100644
--- a/libnativebridge/tests/Android.nativebridge-dummy.mk
+++ b/libnativebridge/tests/Android.nativebridge-dummy.mk
@@ -13,7 +13,7 @@
 LOCAL_CLANG := true
 LOCAL_CFLAGS += -Werror -Wall
 LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
-LOCAL_LDFLAGS := -ldl
+LOCAL_SHARED_LIBRARIES := libdl
 LOCAL_MULTILIB := both
 
 include $(BUILD_SHARED_LIBRARY)
@@ -49,7 +49,7 @@
 LOCAL_CLANG := true
 LOCAL_CFLAGS += -Werror -Wall
 LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
-LOCAL_LDFLAGS := -ldl
+LOCAL_SHARED_LIBRARIES := libdl
 LOCAL_MULTILIB := both
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/libnativeloader/Android.mk b/libnativeloader/Android.mk
index 632c6c8..c81c671 100644
--- a/libnativeloader/Android.mk
+++ b/libnativeloader/Android.mk
@@ -12,12 +12,11 @@
 LOCAL_MODULE:= libnativeloader
 
 LOCAL_SRC_FILES:= $(native_loader_common_src_files)
-LOCAL_SHARED_LIBRARIES := libnativehelper liblog libcutils
+LOCAL_SHARED_LIBRARIES := libnativehelper liblog libcutils libdl
 LOCAL_STATIC_LIBRARIES := libbase
 LOCAL_CLANG := true
 LOCAL_CFLAGS := $(native_loader_common_cflags)
 LOCAL_CPPFLAGS := -std=gnu++14 -fvisibility=hidden
-LOCAL_LDFLAGS := -ldl
 LOCAL_MULTILIB := both
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
diff --git a/libpixelflinger/codeflinger/disassem.c b/libpixelflinger/codeflinger/disassem.c
index 39dd614..5cbd63d 100644
--- a/libpixelflinger/codeflinger/disassem.c
+++ b/libpixelflinger/codeflinger/disassem.c
@@ -279,14 +279,14 @@
 	"4.0", "5.0", "0.5", "10.0"
 };
 
-#define insn_condition(x)	arm32_insn_conditions[(x >> 28) & 0x0f]
-#define insn_blktrans(x)	insn_block_transfers[(x >> 23) & 3]
-#define insn_stkblktrans(x)	insn_stack_block_transfers[(3*((x >> 20)&1))^((x >> 23)&3)]
-#define op2_shift(x)		op_shifts[(x >> 5) & 3]
-#define insn_fparnd(x)		insn_fpa_rounding[(x >> 5) & 0x03]
-#define insn_fpaprec(x)		insn_fpa_precision[(((x >> 18) & 2)|(x >> 7)) & 1]
-#define insn_fpaprect(x)	insn_fpa_precision[(((x >> 21) & 2)|(x >> 15)) & 1]
-#define insn_fpaimm(x)		insn_fpaconstants[x & 0x07]
+#define insn_condition(x)	arm32_insn_conditions[((x) >> 28) & 0x0f]
+#define insn_blktrans(x)	insn_block_transfers[((x) >> 23) & 3]
+#define insn_stkblktrans(x)	insn_stack_block_transfers[(3*(((x) >> 20)&1))^(((x) >> 23)&3)]
+#define op2_shift(x)		op_shifts[((x) >> 5) & 3]
+#define insn_fparnd(x)		insn_fpa_rounding[((x) >> 5) & 0x03]
+#define insn_fpaprec(x)		insn_fpa_precision[((((x) >> 18) & 2)|((x) >> 7)) & 1]
+#define insn_fpaprect(x)	insn_fpa_precision[((((x) >> 21) & 2)|((x) >> 15)) & 1]
+#define insn_fpaimm(x)		insn_fpaconstants[(x) & 0x07]
 
 /* Local prototypes */
 static void disasm_register_shift(const disasm_interface_t *di, u_int insn);
diff --git a/libpixelflinger/include/private/pixelflinger/ggl_context.h b/libpixelflinger/include/private/pixelflinger/ggl_context.h
index d45dabc..563b0f1 100644
--- a/libpixelflinger/include/private/pixelflinger/ggl_context.h
+++ b/libpixelflinger/include/private/pixelflinger/ggl_context.h
@@ -120,7 +120,7 @@
 template<bool> struct CTA;
 template<> struct CTA<true> { };
 
-#define GGL_CONTEXT(con, c)         context_t *con = static_cast<context_t *>(c)
+#define GGL_CONTEXT(con, c)         context_t *(con) = static_cast<context_t *>(c) /* NOLINT */
 #define GGL_OFFSETOF(field)         uintptr_t(&(((context_t*)0)->field))
 #define GGL_INIT_PROC(p, f)         p.f = ggl_ ## f;
 #define GGL_BETWEEN(x, L, H)        (uint32_t((x)-(L)) <= ((H)-(L)))
@@ -136,14 +136,14 @@
 // ----------------------------------------------------------------------------
 
 #define GGL_RESERVE_NEEDS(name, l, s)                               \
-    const uint32_t  GGL_NEEDS_##name##_MASK = (((1LU<<(s))-1)<<l);  \
+    const uint32_t  GGL_NEEDS_##name##_MASK = (((1LU<<(s))-1)<<(l));  \
     const uint32_t  GGL_NEEDS_##name##_SHIFT = (l);
 
 #define GGL_BUILD_NEEDS(val, name)                                  \
     (((val)<<(GGL_NEEDS_##name##_SHIFT)) & GGL_NEEDS_##name##_MASK)
 
 #define GGL_READ_NEEDS(name, n)                                     \
-    (uint32_t(n & GGL_NEEDS_##name##_MASK) >> GGL_NEEDS_##name##_SHIFT)
+    (uint32_t((n) & GGL_NEEDS_##name##_MASK) >> GGL_NEEDS_##name##_SHIFT)
 
 #define GGL_NEED_MASK(name)     (uint32_t(GGL_NEEDS_##name##_MASK))
 #define GGL_NEED(name, val)     GGL_BUILD_NEEDS(val, name)
diff --git a/metricsd/uploader/metrics_log_base.cc b/metricsd/uploader/metrics_log_base.cc
index 1a60b4f..f23bd63 100644
--- a/metricsd/uploader/metrics_log_base.cc
+++ b/metricsd/uploader/metrics_log_base.cc
@@ -16,6 +16,8 @@
 
 #include "uploader/metrics_log_base.h"
 
+#include <memory>
+
 #include "base/build_time.h"
 #include "base/metrics/histogram_base.h"
 #include "base/metrics/histogram_samples.h"
@@ -125,7 +127,7 @@
   histogram_proto->set_name_hash(Hash(histogram_name));
   histogram_proto->set_sum(snapshot.sum());
 
-  for (scoped_ptr<SampleCountIterator> it = snapshot.Iterator(); !it->Done();
+  for (std::unique_ptr<SampleCountIterator> it = snapshot.Iterator(); !it->Done();
        it->Next()) {
     HistogramBase::Sample min;
     HistogramBase::Sample max;
diff --git a/rootdir/init.rc b/rootdir/init.rc
index ef70bf2..a359713 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -571,6 +571,11 @@
 on property:sys.sysctl.tcp_def_init_rwnd=*
     write /proc/sys/net/ipv4/tcp_default_init_rwnd ${sys.sysctl.tcp_def_init_rwnd}
 
+on property:security.perf_harden=0
+    write /proc/sys/kernel/perf_event_paranoid 1
+
+on property:security.perf_harden=1
+    write /proc/sys/kernel/perf_event_paranoid 3
 
 ## Daemon processes to be run by init.
 ##
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index d151ad6..ba04364 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -3,7 +3,6 @@
 
 common_cflags := \
     -Werror -Wno-unused-parameter -Wno-unused-const-variable \
-    -I$(LOCAL_PATH)/upstream-netbsd/include/ \
     -include bsd-compatibility.h \
 
 
@@ -21,6 +20,7 @@
     upstream-netbsd/lib/libc/string/swab.c \
     upstream-netbsd/lib/libutil/raise_default_signal.c
 LOCAL_CFLAGS += $(common_cflags) -Dmain=dd_main -DNO_CONV
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
 LOCAL_MODULE := libtoolbox_dd
 include $(BUILD_STATIC_LIBRARY)
 
@@ -49,6 +49,7 @@
     $(patsubst %,%.c,$(OUR_TOOLS)) \
 
 LOCAL_CFLAGS += $(common_cflags)
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
 LOCAL_CONLYFLAGS += -std=gnu99
 
 LOCAL_SHARED_LIBRARIES := \
@@ -95,6 +96,7 @@
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES := r.c
 LOCAL_CFLAGS += $(common_cflags)
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
 LOCAL_MODULE := r
 LOCAL_MODULE_TAGS := debug
 include $(BUILD_EXECUTABLE)
@@ -109,6 +111,7 @@
     upstream-netbsd/usr.bin/grep/queue.c \
     upstream-netbsd/usr.bin/grep/util.c
 LOCAL_CFLAGS += $(common_cflags)
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
 LOCAL_MODULE := grep
 LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,egrep fgrep,ln -sf grep $(TARGET_OUT)/bin/$(t);)
 include $(BUILD_EXECUTABLE)
diff --git a/toolbox/bsd-compatibility.h b/toolbox/bsd-compatibility.h
index 434d370..7c3ddd4 100644
--- a/toolbox/bsd-compatibility.h
+++ b/toolbox/bsd-compatibility.h
@@ -43,7 +43,7 @@
 #define __type_fit(t, a) (0 == 0)
 
 // TODO: should this be in our <sys/cdefs.h>?
-#define __arraycount(a) (sizeof(a) / sizeof(a[0]))
+#define __arraycount(a) (sizeof(a) / sizeof((a)[0]))
 
 // This at least matches GNU dd(1) behavior.
 #define SIGINFO SIGUSR1