adb: add watchdog.

Bug: http://b/171526334
Test: adbd_test
Change-Id: I6fdb01855a4c0796bbf1e06efb24dd16120b5a26
diff --git a/adb.cpp b/adb.cpp
index 08986b7..f9ed3d4 100644
--- a/adb.cpp
+++ b/adb.cpp
@@ -70,6 +70,25 @@
 #include "client/usb.h"
 #endif
 
+#if !ADB_HOST && defined(__ANDROID__)
+#include "daemon/watchdog.h"
+
+static std::atomic<int> active_connections = 0;
+
+static void IncrementActiveConnections() {
+    if (active_connections++ == 0) {
+        watchdog::Stop();
+    }
+}
+
+static void DecrementActiveConnections() {
+    if (--active_connections == 0) {
+        watchdog::Start();
+    }
+}
+
+#endif
+
 std::string adb_version() {
     // Don't change the format of this --- it's parsed by ddmlib.
     return android::base::StringPrintf(
@@ -111,6 +130,8 @@
     t->online = 1;
 #if ADB_HOST
     t->SetConnectionEstablished(true);
+#elif defined(__ANDROID__)
+    IncrementActiveConnections();
 #endif
 }
 
@@ -123,6 +144,10 @@
 
     LOG(INFO) << t->serial_name() << ": offline";
 
+#if !ADB_HOST && defined(__ANDROID__)
+    DecrementActiveConnections();
+#endif
+
     t->SetConnectionState(kCsOffline);
 
     // Close the associated usb