win32: adb start-server shows stdout/stderr output from actual server

When launching the adb server (typically from adb start-server),
redirect stdout/stderr to anonymous pipes which are read by threads in
the parent process, to make error diagnosis easier.

If there is an error during adb start-server, the output looks like:

> adb start-server
* daemon not running. starting it now on port 5037 *
error: could not blah                 # from server process
could not read ok from ADB Server     # from launch_server
* failed to start daemon *            # from adb_connect
error: cannot connect to daemon       # from adb_commandline

Fix handle-leaks in launch_server by using new unique_handle class
that is based on std::unique_ptr.

In the server, close stdin and redirect to adb.log *before* sending the
ACK, so that any errors are reported early instead of after the ACK.

Change-Id: I943881210a0ea9458fc36851339f916c3d6a0830
Signed-off-by: Spencer Low <CompareAndSwap@gmail.com>
diff --git a/sysdeps_win32.cpp b/sysdeps_win32.cpp
index f534d61..015f89e 100644
--- a/sysdeps_win32.cpp
+++ b/sysdeps_win32.cpp
@@ -112,6 +112,22 @@
   return msg;
 }
 
+void handle_deleter::operator()(HANDLE h) {
+    // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
+    // implying that NULL is a valid handle, but this is probably impossible.
+    // Other APIs like CreateEvent() are documented to return NULL on error,
+    // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
+    // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
+    // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
+    // only need to check for INVALID_HANDLE_VALUE.
+    if (h != INVALID_HANDLE_VALUE) {
+        if (!CloseHandle(h)) {
+            D("CloseHandle(%p) failed: %s\n", h,
+              SystemErrorCodeToString(GetLastError()).c_str());
+        }
+    }
+}
+
 /**************************************************************************/
 /**************************************************************************/
 /*****                                                                *****/