From 190e36c5ea8047e42b10d8c626bb221b4f3d5b02 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Michael=20M=C3=BCller?= <michael@fds-team.de>
Date: Fri, 26 Feb 2016 21:35:52 +0100
Subject: krnl386.exe16: Really translate all invalid console handles into
 usable DOS handles.

---
 dlls/krnl386.exe16/file.c | 33 ++++++++++++++++++++-------------
 1 file changed, 20 insertions(+), 13 deletions(-)

diff --git a/dlls/krnl386.exe16/file.c b/dlls/krnl386.exe16/file.c
index b66b753..e6b1233 100644
--- a/dlls/krnl386.exe16/file.c
+++ b/dlls/krnl386.exe16/file.c
@@ -45,6 +45,17 @@ WINE_DEFAULT_DEBUG_CHANNEL(file);
 
 static HANDLE dos_handles[DOS_TABLE_SIZE];
 
+static void set_standard_handle(HANDLE *out, HANDLE null, HANDLE in)
+{
+    if (!in || in == INVALID_HANDLE_VALUE ||
+        !DuplicateHandle(GetCurrentProcess(), in, GetCurrentProcess(),
+                         out, 0, TRUE, DUPLICATE_SAME_ACCESS))
+    {
+        DuplicateHandle(GetCurrentProcess(), null, GetCurrentProcess(),
+                        out, 0, TRUE, DUPLICATE_SAME_ACCESS);
+    }
+}
+
 /***********************************************************************
  *           FILE_InitProcessDosHandles
  *
@@ -53,25 +64,21 @@ static HANDLE dos_handles[DOS_TABLE_SIZE];
  */
 static void FILE_InitProcessDosHandles( void )
 {
-    HANDLE hStdInput, hStdOutput, hStdError, hNull;
+    HANDLE hNull;
     static BOOL init_done /* = FALSE */;
-    HANDLE cp = GetCurrentProcess();
 
     if (init_done) return;
     init_done = TRUE;
-    hStdInput = GetStdHandle(STD_INPUT_HANDLE);
-    hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
-    hStdError = GetStdHandle(STD_ERROR_HANDLE);
+
     hNull = CreateFileA("NUL", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
+
     /* Invalid console handles need to translate to real DOS handles in a new process */
-    if (!hStdInput) hStdInput = hNull;
-    if (!hStdOutput) hStdOutput = hNull;
-    if (!hStdError) hStdError = hNull;
-    DuplicateHandle(cp, hStdInput, cp, &dos_handles[0], 0, TRUE, DUPLICATE_SAME_ACCESS);
-    DuplicateHandle(cp, hStdOutput, cp, &dos_handles[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
-    DuplicateHandle(cp, hStdError, cp, &dos_handles[2], 0, TRUE, DUPLICATE_SAME_ACCESS);
-    DuplicateHandle(cp, hStdError, cp, &dos_handles[3], 0, TRUE, DUPLICATE_SAME_ACCESS);
-    DuplicateHandle(cp, hStdError, cp, &dos_handles[4], 0, TRUE, DUPLICATE_SAME_ACCESS);
+    set_standard_handle(&dos_handles[0], hNull, GetStdHandle(STD_INPUT_HANDLE));
+    set_standard_handle(&dos_handles[1], hNull, GetStdHandle(STD_OUTPUT_HANDLE));
+    set_standard_handle(&dos_handles[2], hNull, GetStdHandle(STD_ERROR_HANDLE));
+    set_standard_handle(&dos_handles[3], hNull, GetStdHandle(STD_ERROR_HANDLE));
+    set_standard_handle(&dos_handles[4], hNull, GetStdHandle(STD_ERROR_HANDLE));
+
     CloseHandle(hNull);
 }
 
-- 
2.7.1

