Merge "Add missing includes."
diff --git a/.gitignore b/.gitignore
index b25c15b..2f836aa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
 *~
+*.pyc
diff --git a/adb/adb.cpp b/adb/adb.cpp
index dd6c555..821b785 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -630,7 +630,7 @@
     ZeroMemory( &startup, sizeof(startup) );
     startup.cb = sizeof(startup);
     startup.hStdInput  = nul_read;
-    startup.hStdOutput = pipe_write;
+    startup.hStdOutput = nul_write;
     startup.hStdError  = nul_write;
     startup.dwFlags    = STARTF_USESTDHANDLES;
 
@@ -645,9 +645,23 @@
                 SystemErrorCodeToString(GetLastError()).c_str());
         return -1;
     }
+
+    // Verify that the pipe_write handle value can be passed on the command line
+    // as %d and that the rest of adb code can pass it around in an int.
+    const int pipe_write_as_int = cast_handle_to_int(pipe_write);
+    if (cast_int_to_handle(pipe_write_as_int) != pipe_write) {
+        // If this fires, either handle values are larger than 32-bits or else
+        // there is a bug in our casting.
+        // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
+        fprintf(stderr, "CreatePipe handle value too large: 0x%p\n",
+                pipe_write);
+        return -1;
+    }
+
     WCHAR args[64];
     snwprintf(args, arraysize(args),
-              L"adb -P %d fork-server server", server_port);
+              L"adb -P %d fork-server server --reply-fd %d", server_port,
+              pipe_write_as_int);
     ret = CreateProcessW(
             program_path,                              /* program path  */
             args,
diff --git a/adb/client/main.cpp b/adb/client/main.cpp
index af3a6a1..73acbb0 100644
--- a/adb/client/main.cpp
+++ b/adb/client/main.cpp
@@ -160,16 +160,24 @@
     // Inform our parent that we are up and running.
     if (is_daemon) {
 #if defined(_WIN32)
-        // Change stdout mode to binary so \n => \r\n translation does not
-        // occur. In a moment stdout will be reopened to the daemon log file
-        // anyway.
-        _setmode(ack_reply_fd, _O_BINARY);
-#endif
+        const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
+        const CHAR ack[] = "OK\n";
+        const DWORD bytes_to_write = arraysize(ack) - 1;
+        DWORD written = 0;
+        if (!WriteFile(ack_reply_handle, ack, bytes_to_write, &written, NULL)) {
+            fatal("adb: cannot write ACK to handle 0x%p: %s", ack_reply_handle,
+                  SystemErrorCodeToString(GetLastError()).c_str());
+        }
+        if (written != bytes_to_write) {
+            fatal("adb: cannot write %lu bytes of ACK: only wrote %lu bytes",
+                  bytes_to_write, written);
+        }
+        CloseHandle(ack_reply_handle);
+#else
         // TODO(danalbert): Can't use SendOkay because we're sending "OK\n", not
         // "OKAY".
         android::base::WriteStringToFd("OK\n", ack_reply_fd);
-#if !defined(_WIN32)
-        adb_close(ack_reply_fd);
+        unix_close(ack_reply_fd);
 #endif
         close_stdin();
         setup_daemon_logging();
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 2e182e8..1e1690e 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -953,14 +953,7 @@
     int is_server = 0;
     int r;
     TransportType transport_type = kTransportAny;
-
-#if defined(_WIN32)
-    // TODO(compareandswap): Windows should use a separate reply fd too.
-    int ack_reply_fd = STDOUT_FILENO;
-#else
     int ack_reply_fd = -1;
-#endif
-
 
     // If defined, this should be an absolute path to
     // the directory containing all of the various system images
@@ -1003,7 +996,14 @@
             argc--;
             argv++;
             ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
+#ifdef _WIN32
+            const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
+            if ((GetStdHandle(STD_INPUT_HANDLE) == ack_reply_handle) ||
+                (GetStdHandle(STD_OUTPUT_HANDLE) == ack_reply_handle) ||
+                (GetStdHandle(STD_ERROR_HANDLE) == ack_reply_handle)) {
+#else
             if (ack_reply_fd <= 2) { // Disallow stdin, stdout, and stderr.
+#endif
                 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
                 return usage();
             }
@@ -1084,7 +1084,7 @@
 
     if (is_server) {
         if (no_daemon || is_daemon) {
-            if (ack_reply_fd == -1) {
+            if (is_daemon && (ack_reply_fd == -1)) {
                 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
                 return usage();
             }
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index 9189955..6f3c443 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -338,6 +338,23 @@
     char** narrow_args;
 };
 
+// Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
+// so they can fit in an int. To convert back, we just need to sign-extend.
+// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
+// Note that this does not make a HANDLE value work with APIs like open(), nor
+// does this make a value from open() passable to APIs taking a HANDLE. This
+// just lets you take a HANDLE, pass it around as an int, and then use it again
+// as a HANDLE.
+inline int cast_handle_to_int(const HANDLE h) {
+    // truncate
+    return static_cast<int>(reinterpret_cast<INT_PTR>(h));
+}
+
+inline HANDLE cast_int_to_handle(const int fd) {
+    // sign-extend
+    return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
+}
+
 #else /* !_WIN32 a.k.a. Unix */
 
 #include "fdevent.h"
diff --git a/adb/usb_windows.cpp b/adb/usb_windows.cpp
index 4c9a152..b8cc5cf 100644
--- a/adb/usb_windows.cpp
+++ b/adb/usb_windows.cpp
@@ -33,6 +33,10 @@
 /** Structure usb_handle describes our connection to the usb device via
   AdbWinApi.dll. This structure is returned from usb_open() routine and
   is expected in each subsequent call that is accessing the device.
+
+  Most members are protected by usb_lock, except for adb_{read,write}_pipe which
+  rely on AdbWinApi.dll's handle validation and AdbCloseHandle(endpoint)'s
+  ability to break a thread out of pipe IO.
 */
 struct usb_handle {
   /// Previous entry in the list of opened usb handles
@@ -86,6 +90,9 @@
 /// registers usb transport for them.
 void find_devices();
 
+/// Kicks all USB devices
+static void kick_devices();
+
 /// Entry point for thread that polls (every second) for new usb interfaces.
 /// This routine calls find_devices in infinite loop.
 void* device_poll_thread(void* unused);
@@ -111,9 +118,6 @@
 /// Closes opened usb handle
 int usb_close(usb_handle* handle);
 
-/// Gets interface (device) name for an opened usb handle
-const char *usb_name(usb_handle* handle);
-
 int known_device_locked(const char* dev_name) {
   usb_handle* usb;
 
@@ -177,17 +181,99 @@
   return NULL;
 }
 
+static LRESULT CALLBACK _power_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam,
+                                           LPARAM lParam) {
+  switch (uMsg) {
+  case WM_POWERBROADCAST:
+    switch (wParam) {
+    case PBT_APMRESUMEAUTOMATIC:
+      // Resuming from sleep or hibernation, so kick all existing USB devices
+      // and then allow the device_poll_thread to redetect USB devices from
+      // scratch. If we don't do this, existing USB devices will never respond
+      // to us because they'll be waiting for the connect/auth handshake.
+      D("Received (WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC) notification, "
+        "so kicking all USB devices\n");
+      kick_devices();
+      return TRUE;
+    }
+  }
+  return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+}
+
+static void* _power_notification_thread(void* unused) {
+  // This uses a thread with its own window message pump to get power
+  // notifications. If adb runs from a non-interactive service account, this
+  // might not work (not sure). If that happens to not work, we could use
+  // heavyweight WMI APIs to get power notifications. But for the common case
+  // of a developer's interactive session, a window message pump is more
+  // appropriate.
+  D("Created power notification thread\n");
+
+  // Window class names are process specific.
+  static const WCHAR kPowerNotificationWindowClassName[] =
+    L"PowerNotificationWindow";
+
+  // Get the HINSTANCE corresponding to the module that _power_window_proc
+  // is in (the main module).
+  const HINSTANCE instance = GetModuleHandleW(NULL);
+  if (!instance) {
+    // This is such a common API call that this should never fail.
+    fatal("GetModuleHandleW failed: %s",
+          SystemErrorCodeToString(GetLastError()).c_str());
+  }
+
+  WNDCLASSEXW wndclass;
+  memset(&wndclass, 0, sizeof(wndclass));
+  wndclass.cbSize = sizeof(wndclass);
+  wndclass.lpfnWndProc = _power_window_proc;
+  wndclass.hInstance = instance;
+  wndclass.lpszClassName = kPowerNotificationWindowClassName;
+  if (!RegisterClassExW(&wndclass)) {
+    fatal("RegisterClassExW failed: %s",
+          SystemErrorCodeToString(GetLastError()).c_str());
+  }
+
+  if (!CreateWindowExW(WS_EX_NOACTIVATE, kPowerNotificationWindowClassName,
+                       L"ADB Power Notification Window", WS_POPUP, 0, 0, 0, 0,
+                       NULL, NULL, instance, NULL)) {
+    fatal("CreateWindowExW failed: %s",
+          SystemErrorCodeToString(GetLastError()).c_str());
+  }
+
+  MSG msg;
+  while (GetMessageW(&msg, NULL, 0, 0)) {
+    TranslateMessage(&msg);
+    DispatchMessageW(&msg);
+  }
+
+  // GetMessageW() will return false if a quit message is posted. We don't
+  // do that, but it might be possible for that to occur when logging off or
+  // shutting down. Not a big deal since the whole process will be going away
+  // soon anyway.
+  D("Power notification thread exiting\n");
+
+  return NULL;
+}
+
 void usb_init() {
   if (!adb_thread_create(device_poll_thread, nullptr)) {
-    fatal_errno("cannot create input thread");
+    fatal_errno("cannot create device poll thread");
+  }
+  if (!adb_thread_create(_power_notification_thread, nullptr)) {
+    fatal_errno("cannot create power notification thread");
   }
 }
 
 usb_handle* do_usb_open(const wchar_t* interface_name) {
+  unsigned long name_len = 0;
+
   // Allocate our handle
-  usb_handle* ret = (usb_handle*)malloc(sizeof(usb_handle));
-  if (NULL == ret)
-    return NULL;
+  usb_handle* ret = (usb_handle*)calloc(1, sizeof(usb_handle));
+  if (NULL == ret) {
+    D("Could not allocate %u bytes for usb_handle: %s\n", sizeof(usb_handle),
+      strerror(errno));
+    goto fail;
+  }
 
   // Set linkers back to the handle
   ret->next = ret;
@@ -195,11 +281,10 @@
 
   // Create interface.
   ret->adb_interface = AdbCreateInterfaceByName(interface_name);
-
   if (NULL == ret->adb_interface) {
-    free(ret);
-    errno = GetLastError();
-    return NULL;
+    D("AdbCreateInterfaceByName failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
   }
 
   // Open read pipe (endpoint)
@@ -207,45 +292,60 @@
     AdbOpenDefaultBulkReadEndpoint(ret->adb_interface,
                                    AdbOpenAccessTypeReadWrite,
                                    AdbOpenSharingModeReadWrite);
-  if (NULL != ret->adb_read_pipe) {
-    // Open write pipe (endpoint)
-    ret->adb_write_pipe =
-      AdbOpenDefaultBulkWriteEndpoint(ret->adb_interface,
-                                      AdbOpenAccessTypeReadWrite,
-                                      AdbOpenSharingModeReadWrite);
-    if (NULL != ret->adb_write_pipe) {
-      // Save interface name
-      unsigned long name_len = 0;
-
-      // First get expected name length
-      AdbGetInterfaceName(ret->adb_interface,
-                          NULL,
-                          &name_len,
-                          true);
-      if (0 != name_len) {
-        ret->interface_name = (char*)malloc(name_len);
-
-        if (NULL != ret->interface_name) {
-          // Now save the name
-          if (AdbGetInterfaceName(ret->adb_interface,
-                                  ret->interface_name,
-                                  &name_len,
-                                  true)) {
-            // We're done at this point
-            return ret;
-          }
-        } else {
-          SetLastError(ERROR_OUTOFMEMORY);
-        }
-      }
-    }
+  if (NULL == ret->adb_read_pipe) {
+    D("AdbOpenDefaultBulkReadEndpoint failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
   }
 
-  // Something went wrong.
-  int saved_errno = GetLastError();
-  usb_cleanup_handle(ret);
-  free(ret);
-  SetLastError(saved_errno);
+  // Open write pipe (endpoint)
+  ret->adb_write_pipe =
+    AdbOpenDefaultBulkWriteEndpoint(ret->adb_interface,
+                                    AdbOpenAccessTypeReadWrite,
+                                    AdbOpenSharingModeReadWrite);
+  if (NULL == ret->adb_write_pipe) {
+    D("AdbOpenDefaultBulkWriteEndpoint failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
+  }
+
+  // Save interface name
+  // First get expected name length
+  AdbGetInterfaceName(ret->adb_interface,
+                      NULL,
+                      &name_len,
+                      true);
+  if (0 == name_len) {
+    D("AdbGetInterfaceName returned name length of zero: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
+  }
+
+  ret->interface_name = (char*)malloc(name_len);
+  if (NULL == ret->interface_name) {
+    D("Could not allocate %lu bytes for interface_name: %s\n", name_len,
+      strerror(errno));
+    goto fail;
+  }
+
+  // Now save the name
+  if (!AdbGetInterfaceName(ret->adb_interface,
+                           ret->interface_name,
+                           &name_len,
+                           true)) {
+    D("AdbGetInterfaceName failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
+    goto fail;
+  }
+
+  // We're done at this point
+  return ret;
+
+fail:
+  if (NULL != ret) {
+    usb_cleanup_handle(ret);
+    free(ret);
+  }
 
   return NULL;
 }
@@ -253,92 +353,130 @@
 int usb_write(usb_handle* handle, const void* data, int len) {
   unsigned long time_out = 5000;
   unsigned long written = 0;
-  int ret;
+  int err = 0;
 
   D("usb_write %d\n", len);
-  if (NULL != handle) {
-    // Perform write
-    ret = AdbWriteEndpointSync(handle->adb_write_pipe,
-                               (void*)data,
-                               (unsigned long)len,
-                               &written,
-                               time_out);
-    int saved_errno = GetLastError();
-
-    if (ret) {
-      // Make sure that we've written what we were asked to write
-      D("usb_write got: %ld, expected: %d\n", written, len);
-      if (written == (unsigned long)len) {
-        if(handle->zero_mask && (len & handle->zero_mask) == 0) {
-          // Send a zero length packet
-          AdbWriteEndpointSync(handle->adb_write_pipe,
-                               (void*)data,
-                               0,
-                               &written,
-                               time_out);
-        }
-        return 0;
-      }
-    } else {
-      // assume ERROR_INVALID_HANDLE indicates we are disconnected
-      if (saved_errno == ERROR_INVALID_HANDLE)
-        usb_kick(handle);
-    }
-    errno = saved_errno;
-  } else {
-    D("usb_write NULL handle\n");
-    SetLastError(ERROR_INVALID_HANDLE);
+  if (NULL == handle) {
+    D("usb_write was passed NULL handle\n");
+    err = EINVAL;
+    goto fail;
   }
 
-  D("usb_write failed: %d\n", errno);
+  // Perform write
+  if (!AdbWriteEndpointSync(handle->adb_write_pipe,
+                            (void*)data,
+                            (unsigned long)len,
+                            &written,
+                            time_out)) {
+    D("AdbWriteEndpointSync failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
+    err = EIO;
+    goto fail;
+  }
 
+  // Make sure that we've written what we were asked to write
+  D("usb_write got: %ld, expected: %d\n", written, len);
+  if (written != (unsigned long)len) {
+    // If this occurs, this code should be changed to repeatedly call
+    // AdbWriteEndpointSync() until all bytes are written.
+    D("AdbWriteEndpointSync was supposed to write %d, but only wrote %ld\n",
+      len, written);
+    err = EIO;
+    goto fail;
+  }
+
+  if (handle->zero_mask && (len & handle->zero_mask) == 0) {
+    // Send a zero length packet
+    if (!AdbWriteEndpointSync(handle->adb_write_pipe,
+                              (void*)data,
+                              0,
+                              &written,
+                              time_out)) {
+      D("AdbWriteEndpointSync of zero length packet failed: %s\n",
+        SystemErrorCodeToString(GetLastError()).c_str());
+      err = EIO;
+      goto fail;
+    }
+  }
+
+  return 0;
+
+fail:
+  // Any failure should cause us to kick the device instead of leaving it a
+  // zombie state with potential to hang.
+  if (NULL != handle) {
+    D("Kicking device due to error in usb_write\n");
+    usb_kick(handle);
+  }
+
+  D("usb_write failed\n");
+  errno = err;
   return -1;
 }
 
 int usb_read(usb_handle *handle, void* data, int len) {
   unsigned long time_out = 0;
   unsigned long read = 0;
+  int err = 0;
 
   D("usb_read %d\n", len);
-  if (handle != nullptr) {
-    while (len > 0) {
-      int ret = AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read, time_out);
-      int saved_errno = GetLastError();
-      D("usb_write got: %ld, expected: %d, errno: %d\n", read, len, saved_errno);
-      if (ret) {
-        data = (char *)data + read;
-        len -= read;
-
-        if (len == 0)
-          return 0;
-      } else {
-        // assume ERROR_INVALID_HANDLE indicates we are disconnected
-        if (saved_errno == ERROR_INVALID_HANDLE)
-          usb_kick(handle);
-        break;
-      }
-      errno = saved_errno;
-    }
-  } else {
-    D("usb_read NULL handle\n");
-    SetLastError(ERROR_INVALID_HANDLE);
+  if (NULL == handle) {
+    D("usb_read was passed NULL handle\n");
+    err = EINVAL;
+    goto fail;
   }
 
-  D("usb_read failed: %d\n", errno);
+  while (len > 0) {
+    if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read,
+                             time_out)) {
+      D("AdbReadEndpointSync failed: %s\n",
+        SystemErrorCodeToString(GetLastError()).c_str());
+      err = EIO;
+      goto fail;
+    }
+    D("usb_read got: %ld, expected: %d\n", read, len);
 
+    data = (char *)data + read;
+    len -= read;
+  }
+
+  return 0;
+
+fail:
+  // Any failure should cause us to kick the device instead of leaving it a
+  // zombie state with potential to hang.
+  if (NULL != handle) {
+    D("Kicking device due to error in usb_read\n");
+    usb_kick(handle);
+  }
+
+  D("usb_read failed\n");
+  errno = err;
   return -1;
 }
 
+// Wrapper around AdbCloseHandle() that logs diagnostics.
+static void _adb_close_handle(ADBAPIHANDLE adb_handle) {
+  if (!AdbCloseHandle(adb_handle)) {
+    D("AdbCloseHandle(%p) failed: %s\n", adb_handle,
+      SystemErrorCodeToString(GetLastError()).c_str());
+  }
+}
+
 void usb_cleanup_handle(usb_handle* handle) {
+  D("usb_cleanup_handle\n");
   if (NULL != handle) {
     if (NULL != handle->interface_name)
       free(handle->interface_name);
+    // AdbCloseHandle(pipe) will break any threads out of pending IO calls and
+    // wait until the pipe no longer uses the interface. Then we can
+    // AdbCloseHandle() the interface.
     if (NULL != handle->adb_write_pipe)
-      AdbCloseHandle(handle->adb_write_pipe);
+      _adb_close_handle(handle->adb_write_pipe);
     if (NULL != handle->adb_read_pipe)
-      AdbCloseHandle(handle->adb_read_pipe);
+      _adb_close_handle(handle->adb_read_pipe);
     if (NULL != handle->adb_interface)
-      AdbCloseHandle(handle->adb_interface);
+      _adb_close_handle(handle->adb_interface);
 
     handle->interface_name = NULL;
     handle->adb_write_pipe = NULL;
@@ -347,16 +485,22 @@
   }
 }
 
+static void usb_kick_locked(usb_handle* handle) {
+  // The reason the lock must be acquired before calling this function is in
+  // case multiple threads are trying to kick the same device at the same time.
+  usb_cleanup_handle(handle);
+}
+
 void usb_kick(usb_handle* handle) {
+  D("usb_kick\n");
   if (NULL != handle) {
     adb_mutex_lock(&usb_lock);
 
-    usb_cleanup_handle(handle);
+    usb_kick_locked(handle);
 
     adb_mutex_unlock(&usb_lock);
   } else {
-    SetLastError(ERROR_INVALID_HANDLE);
-    errno = ERROR_INVALID_HANDLE;
+    errno = EINVAL;
   }
 }
 
@@ -384,16 +528,6 @@
   return 0;
 }
 
-const char *usb_name(usb_handle* handle) {
-  if (NULL == handle) {
-    SetLastError(ERROR_INVALID_HANDLE);
-    errno = ERROR_INVALID_HANDLE;
-    return NULL;
-  }
-
-  return (const char*)handle->interface_name;
-}
-
 int recognized_device(usb_handle* handle) {
   if (NULL == handle)
     return 0;
@@ -403,6 +537,8 @@
 
   if (!AdbGetUsbDeviceDescriptor(handle->adb_interface,
                                  &device_desc)) {
+    D("AdbGetUsbDeviceDescriptor failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
     return 0;
   }
 
@@ -411,6 +547,8 @@
 
   if (!AdbGetUsbInterfaceDescriptor(handle->adb_interface,
                                     &interf_desc)) {
+    D("AdbGetUsbInterfaceDescriptor failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
     return 0;
   }
 
@@ -427,6 +565,10 @@
       // assuming zero is a valid bulk endpoint ID
       if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
         handle->zero_mask = endpoint_info.max_packet_size - 1;
+        D("device zero_mask: 0x%x\n", handle->zero_mask);
+      } else {
+        D("AdbGetEndpointInformation failed: %s\n",
+          SystemErrorCodeToString(GetLastError()).c_str());
       }
     }
 
@@ -448,8 +590,11 @@
   ADBAPIHANDLE enum_handle =
     AdbEnumInterfaces(usb_class_id, true, true, true);
 
-  if (NULL == enum_handle)
+  if (NULL == enum_handle) {
+    D("AdbEnumInterfaces failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
     return;
+  }
 
   while (AdbNextInterface(enum_handle, next_interface, &entry_buffer_size)) {
     // TODO: FIXME - temp hack converting wchar_t into char.
@@ -486,7 +631,8 @@
               free(handle);
             }
           } else {
-            D("cannot get serial number\n");
+            D("cannot get serial number: %s\n",
+              SystemErrorCodeToString(GetLastError()).c_str());
             usb_cleanup_handle(handle);
             free(handle);
           }
@@ -500,5 +646,21 @@
     entry_buffer_size = sizeof(entry_buffer);
   }
 
-  AdbCloseHandle(enum_handle);
+  if (GetLastError() != ERROR_NO_MORE_ITEMS) {
+    // Only ERROR_NO_MORE_ITEMS is expected at the end of enumeration.
+    D("AdbNextInterface failed: %s\n",
+      SystemErrorCodeToString(GetLastError()).c_str());
+  }
+
+  _adb_close_handle(enum_handle);
+}
+
+static void kick_devices() {
+  // Need to acquire lock to safely walk the list which might be modified
+  // by another thread.
+  adb_mutex_lock(&usb_lock);
+  for (usb_handle* usb = handle_list.next; usb != &handle_list; usb = usb->next) {
+    usb_kick_locked(usb);
+  }
+  adb_mutex_unlock(&usb_lock);
 }
diff --git a/init/init_parser.cpp b/init/init_parser.cpp
index 3ed1d58..12f44f7 100644
--- a/init/init_parser.cpp
+++ b/init/init_parser.cpp
@@ -315,10 +315,14 @@
 
     int nargs = 0;
 
+    //TODO: Use a parser with const input and remove this copy
+    std::vector<char> data_copy(data.begin(), data.end());
+    data_copy.push_back('\0');
+
     parse_state state;
     state.filename = fn;
     state.line = 0;
-    state.ptr = strdup(data.c_str());  // TODO: fix this code!
+    state.ptr = &data_copy[0];
     state.nexttoken = 0;
     state.parse_line = parse_line_no_op;
 
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 0f5071b..b9e8973 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -218,18 +218,25 @@
 }
 
 // If we're using more than 256K of memory for log entries, prune
-// at least 10% of the log entries.
+// at least 10% of the log entries. For sizes above 1M, prune at
+// least 1% of the log entries.
 //
 // mLogElementsLock must be held when this function is called.
 void LogBuffer::maybePrune(log_id_t id) {
     size_t sizes = stats.sizes(id);
-    if (sizes > log_buffer_size(id)) {
-        size_t sizeOver90Percent = sizes - ((log_buffer_size(id) * 9) / 10);
-        size_t elements = stats.elements(id);
-        unsigned long pruneRows = elements * sizeOver90Percent / sizes;
-        elements /= 10;
-        if (pruneRows <= elements) {
-            pruneRows = elements;
+    unsigned long maxSize = log_buffer_size(id);
+    if (sizes > maxSize) {
+        size_t sizeOver, minElements, elements = stats.elements(id);
+        if (maxSize > (4 * LOG_BUFFER_SIZE)) {
+            sizeOver = sizes - ((maxSize * 99) / 100);
+            minElements = elements / 100;
+        } else {
+            sizeOver = sizes - ((maxSize * 9) / 10);
+            minElements = elements / 10;
+        }
+        unsigned long pruneRows = elements * sizeOver / sizes;
+        if (pruneRows <= minElements) {
+            pruneRows = minElements;
         }
         prune(id, pruneRows);
     }
diff --git a/metricsd/Android.mk b/metricsd/Android.mk
new file mode 100644
index 0000000..9edba6e
--- /dev/null
+++ b/metricsd/Android.mk
@@ -0,0 +1,116 @@
+# Copyright (C) 2015 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.
+
+LOCAL_PATH := $(call my-dir)
+
+ifeq ($(HOST_OS),linux)
+
+metrics_cpp_extension := .cc
+libmetrics_sources := \
+  c_metrics_library.cc \
+  metrics_library.cc \
+  serialization/metric_sample.cc \
+  serialization/serialization_utils.cc
+
+metrics_client_sources := \
+  metrics_client.cc
+
+metrics_daemon_sources := \
+  metrics_daemon.cc \
+  metrics_daemon_main.cc \
+  persistent_integer.cc \
+  uploader/metrics_hashes.cc \
+  uploader/metrics_log_base.cc \
+  uploader/metrics_log.cc \
+  uploader/sender_http.cc \
+  uploader/system_profile_cache.cc \
+  uploader/upload_service.cc \
+  serialization/metric_sample.cc \
+  serialization/serialization_utils.cc
+
+metrics_CFLAGS := -Wall \
+  -D__BRILLO__ \
+  -Wno-char-subscripts \
+  -Wno-missing-field-initializers \
+  -Wno-unused-function \
+  -Wno-unused-parameter \
+  -Werror \
+  -fvisibility=default
+metrics_CPPFLAGS := -Wno-non-virtual-dtor \
+  -Wno-sign-promo \
+  -Wno-strict-aliasing \
+  -fvisibility=default
+metrics_includes := external/gtest/include \
+  $(LOCAL_PATH)/include
+metrics_shared_libraries := libchrome libchromeos
+
+# Shared library for metrics.
+# ========================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := libmetrics
+LOCAL_C_INCLUDES := $(metrics_includes)
+LOCAL_CFLAGS := $(metrics_CFLAGS)
+LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
+LOCAL_CPPFLAGS := $(metrics_CPPFLAGS)
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_SHARED_LIBRARIES := $(metrics_shared_libraries)
+LOCAL_SRC_FILES := $(libmetrics_sources)
+include $(BUILD_SHARED_LIBRARY)
+
+# CLI client for metrics.
+# ========================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := metrics_client
+LOCAL_C_INCLUDES := $(metrics_includes)
+LOCAL_CFLAGS := $(metrics_CFLAGS)
+LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
+LOCAL_CPPFLAGS := $(metrics_CPPFLAGS)
+LOCAL_SHARED_LIBRARIES := $(metrics_shared_libraries) \
+  libmetrics
+LOCAL_SRC_FILES := $(metrics_client_sources)
+include $(BUILD_EXECUTABLE)
+
+# Protobuf library for metrics_daemon.
+# ========================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := metrics_daemon_protos
+LOCAL_MODULE_CLASS := STATIC_LIBRARIES
+generated_sources_dir := $(call local-generated-sources-dir)
+LOCAL_EXPORT_C_INCLUDE_DIRS += \
+    $(generated_sources_dir)/proto/system/core/metricsd
+LOCAL_SRC_FILES :=  $(call all-proto-files-under,uploader/proto)
+LOCAL_STATIC_LIBRARIES := libprotobuf-cpp-lite
+include $(BUILD_STATIC_LIBRARY)
+
+# metrics daemon.
+# ========================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := metrics_daemon
+LOCAL_C_INCLUDES := $(metrics_includes) \
+  external/libchromeos
+LOCAL_CFLAGS := $(metrics_CFLAGS)
+LOCAL_CPP_EXTENSION := $(metrics_cpp_extension)
+LOCAL_CPPFLAGS := $(metrics_CPPFLAGS)
+LOCAL_RTTI_FLAG := -frtti
+LOCAL_SHARED_LIBRARIES := $(metrics_shared_libraries) \
+  libmetrics \
+  libprotobuf-cpp-lite \
+  libchromeos-http \
+  libchromeos-dbus \
+  libdbus
+LOCAL_SRC_FILES := $(metrics_daemon_sources)
+LOCAL_STATIC_LIBRARIES := metrics_daemon_protos
+include $(BUILD_EXECUTABLE)
+
+endif # HOST_OS == linux
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index aa92af7..ae880c3 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -56,7 +56,6 @@
     stop \
     top \
     uptime \
-    watchprops \
 
 ALL_TOOLS = $(BSD_TOOLS) $(OUR_TOOLS)
 
diff --git a/toolbox/watchprops.c b/toolbox/watchprops.c
deleted file mode 100644
index cd62922..0000000
--- a/toolbox/watchprops.c
+++ /dev/null
@@ -1,92 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <errno.h>
-
-#include <cutils/properties.h>
-#include <cutils/hashmap.h>
-
-#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
-#include <sys/_system_properties.h>
-
-static int str_hash(void *key)
-{
-    return hashmapHash(key, strlen(key));
-}
-
-static bool str_equals(void *keyA, void *keyB)
-{
-    return strcmp(keyA, keyB) == 0;
-}
-
-static void announce(char *name, char *value)
-{
-    unsigned char *x;
-    
-    for(x = (unsigned char *)value; *x; x++) {
-        if((*x < 32) || (*x > 127)) *x = '.';
-    }
-
-    fprintf(stderr,"%10d %s = '%s'\n", (int) time(0), name, value);
-}
-
-static void add_to_watchlist(Hashmap *watchlist, const char *name,
-        const prop_info *pi)
-{
-    char *key = strdup(name);
-    unsigned *value = malloc(sizeof(unsigned));
-    if (!key || !value)
-        exit(1);
-
-    *value = __system_property_serial(pi);
-    hashmapPut(watchlist, key, value);
-}
-
-static void populate_watchlist(const prop_info *pi, void *cookie)
-{
-    Hashmap *watchlist = cookie;
-    char name[PROP_NAME_MAX];
-    char value_unused[PROP_VALUE_MAX];
-
-    __system_property_read(pi, name, value_unused);
-    add_to_watchlist(watchlist, name, pi);
-}
-
-static void update_watchlist(const prop_info *pi, void *cookie)
-{
-    Hashmap *watchlist = cookie;
-    char name[PROP_NAME_MAX];
-    char value[PROP_VALUE_MAX];
-    unsigned *serial;
-
-    __system_property_read(pi, name, value);
-    serial = hashmapGet(watchlist, name);
-    if (!serial) {
-        add_to_watchlist(watchlist, name, pi);
-        announce(name, value);
-    } else {
-        unsigned tmp = __system_property_serial(pi);
-        if (*serial != tmp) {
-            *serial = tmp;
-            announce(name, value);
-        }
-    }
-}
-
-int watchprops_main(int argc, char *argv[])
-{
-    unsigned serial;
-    
-    Hashmap *watchlist = hashmapCreate(1024, str_hash, str_equals);
-    if (!watchlist)
-        exit(1);
-
-    __system_property_foreach(populate_watchlist, watchlist);
-
-    for(serial = 0;;) {
-        serial = __system_property_wait_any(serial);
-        __system_property_foreach(update_watchlist, watchlist);
-    }
-    return 0;
-}