From 90fb8cb0ab86e87834ff331cb9b6075ef37251b7 Mon Sep 17 00:00:00 2001 From: Bert Belder Date: Wed, 10 Jun 2015 16:17:38 -0700 Subject: [PATCH] win,pipe: don't close fd 0-2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/libuv/libuv/pull/396 Reviewed-By: Saúl Ibarra Corretgé --- src/win/pipe.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/win/pipe.c b/src/win/pipe.c index 1a1970ab..8edfe42a 100644 --- a/src/win/pipe.c +++ b/src/win/pipe.c @@ -181,6 +181,7 @@ static HANDLE open_named_pipe(const WCHAR* name, DWORD* duplex_flags) { static void close_pipe(uv_pipe_t* pipe) { + assert(pipe->u.fd == -1 || pipe->u.fd > 2); if (pipe->u.fd == -1) CloseHandle(pipe->handle); else @@ -1884,6 +1885,27 @@ int uv_pipe_open(uv_pipe_t* pipe, uv_file file) { FILE_ACCESS_INFORMATION access; DWORD duplex_flags = 0; + if (os_handle == INVALID_HANDLE_VALUE) + return UV_EBADF; + + /* In order to avoid closing a stdio file descriptor 0-2, duplicate the + * underlying OS handle and forget about the original fd. + * We could also opt to use the original OS handle and just never close it, + * but then there would be no reliable way to cancel pending read operations + * upon close. + */ + if (file <= 2) { + if (!DuplicateHandle(INVALID_HANDLE_VALUE, + os_handle, + INVALID_HANDLE_VALUE, + &os_handle, + 0, + FALSE, + DUPLICATE_SAME_ACCESS)) + return uv_translate_sys_error(GetLastError()); + file = -1; + } + /* Determine what kind of permissions we have on this handle. * Cygwin opens the pipe in message mode, but we can support it, * just query the access flags and set the stream flags accordingly.