Fix adb flakiness on reboot

bug: 31950237

There are two lists of active ADB transports (devices),
and with the emulator, they can go out of sync.

This CL more conservatively checks if there are no
transports in either list before commiting to
register a new transport for the emulator.

Change-Id: Id1201dc59c70825881dad80925c2e5bcc13dbd5e
(cherry picked from commit edaedfd5da41b2f5aa14b4d52742a6d8caa49214)
diff --git a/adb/adb.h b/adb/adb.h
index 971b8da..b1d9896 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -160,8 +160,10 @@
 int  init_socket_transport(atransport *t, int s, int port, int local);
 void init_usb_transport(atransport *t, usb_handle *usb, ConnectionState state);
 
+std::string getEmulatorSerialString(int console_port);
 #if ADB_HOST
 atransport* find_emulator_transport_by_adb_port(int adb_port);
+atransport* find_emulator_transport_by_console_port(int console_port);
 #endif
 
 int service_to_fd(const char* name, const atransport* transport);
diff --git a/adb/transport_local.cpp b/adb/transport_local.cpp
index 4f3e1f5..1f5a258 100644
--- a/adb/transport_local.cpp
+++ b/adb/transport_local.cpp
@@ -99,7 +99,8 @@
     int fd = -1;
 
 #if ADB_HOST
-    if (find_emulator_transport_by_adb_port(adb_port) != nullptr) {
+    if (find_emulator_transport_by_adb_port(adb_port) != nullptr ||
+        find_emulator_transport_by_console_port(console_port) != nullptr) {
         return -1;
     }
 
@@ -116,7 +117,7 @@
         D("client: connected on remote on fd %d", fd);
         close_on_exec(fd);
         disable_tcp_nagle(fd);
-        std::string serial = android::base::StringPrintf("emulator-%d", console_port);
+        std::string serial = getEmulatorSerialString(console_port);
         if (register_socket_transport(fd, serial.c_str(), adb_port, 1) == 0) {
             return 0;
         }
@@ -360,6 +361,11 @@
     return NULL;
 }
 
+std::string getEmulatorSerialString(int console_port)
+{
+    return android::base::StringPrintf("emulator-%d", console_port);
+}
+
 atransport* find_emulator_transport_by_adb_port(int adb_port)
 {
     adb_mutex_lock( &local_transports_lock );
@@ -368,6 +374,12 @@
     return result;
 }
 
+atransport* find_emulator_transport_by_console_port(int console_port)
+{
+    return find_transport(getEmulatorSerialString(console_port).c_str());
+}
+
+
 /* Only call this function if you already hold local_transports_lock. */
 int get_available_local_transport_index_locked()
 {