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.h b/sysdeps.h
index 6f3c443..a58a762 100644
--- a/sysdeps.h
+++ b/sysdeps.h
@@ -71,6 +71,7 @@
 #include <windows.h>
 #include <ws2tcpip.h>
 
+#include <memory>   // unique_ptr
 #include <string>   // Prototypes for narrow() and widen() use std::(w)string.
 
 #include "fdevent.h"
@@ -355,6 +356,21 @@
     return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
 }
 
+// Deleter for unique_handle. Adapted from many sources, including:
+// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
+// https://visualstudiomagazine.com/articles/2013/09/01/get-a-handle-on-the-windows-api.aspx
+class handle_deleter {
+public:
+    typedef HANDLE pointer;
+
+    void operator()(HANDLE h);
+};
+
+// Like std::unique_ptr, but for Windows HANDLE objects that should be
+// CloseHandle()'d. Operator bool() only checks if the handle != nullptr,
+// but does not check if the handle != INVALID_HANDLE_VALUE.
+typedef std::unique_ptr<HANDLE, handle_deleter> unique_handle;
+
 #else /* !_WIN32 a.k.a. Unix */
 
 #include "fdevent.h"