From 3d97f4997039beb5cbc5e0b668c1cb2ffa69a76f Mon Sep 17 00:00:00 2001 From: Laszlo Csomor Date: Thu, 16 Mar 2017 12:58:23 +0000 Subject: [PATCH] Bazel client, Windows: fix console handling bugs Fix 3 bugs in blaze_util_windows: - off-by-one error in the loop ensuring the std handles are all open - don't auto-close stdout's HANDLE after querying the console window's size - error-handling for when stdout is redirected thus ::GetStdHandle returns an invalid handle See https://github.com/bazelbuild/bazel/issues/2107 -- PiperOrigin-RevId: 150310578 MOS_MIGRATED_REVID=150310578 --- src/main/cpp/blaze_util_windows.cc | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/main/cpp/blaze_util_windows.cc b/src/main/cpp/blaze_util_windows.cc index 4607491868a865..15d39a536413ac 100644 --- a/src/main/cpp/blaze_util_windows.cc +++ b/src/main/cpp/blaze_util_windows.cc @@ -1115,7 +1115,7 @@ void SetupStdStreams() { #ifdef COMPILER_MSVC static const DWORD stdhandles[] = {STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE}; - for (int i = 0; i < 2; ++i) { + for (int i = 0; i <= 2; ++i) { HANDLE handle = ::GetStdHandle(stdhandles[i]); if (handle == INVALID_HANDLE_VALUE || handle == NULL) { // Ensure we have open fds to each std* stream. Otherwise we can end up @@ -1346,18 +1346,17 @@ int GetTerminalColumns() { } } -#ifdef COMPILER_MSVC - // This code path is MSVC-only because when running under MSYS there's no - // Windows console attached so GetConsoleScreenBufferInfo fails. - windows_util::AutoHandle stdout_handle(::GetStdHandle(STD_OUTPUT_HANDLE)); - CONSOLE_SCREEN_BUFFER_INFO screen_info; - if (GetConsoleScreenBufferInfo(stdout_handle, &screen_info)) { - int width = 1 + screen_info.srWindow.Right - screen_info.srWindow.Left; - if (width > 1) { - return width; + HANDLE stdout_handle = ::GetStdHandle(STD_OUTPUT_HANDLE); + if (stdout_handle != INVALID_HANDLE_VALUE) { + // stdout_handle may be invalid when stdout is redirected. + CONSOLE_SCREEN_BUFFER_INFO screen_info; + if (GetConsoleScreenBufferInfo(stdout_handle, &screen_info)) { + int width = 1 + screen_info.srWindow.Right - screen_info.srWindow.Left; + if (width > 1) { + return width; + } } } -#endif // COMPILER_MSVC return 80; // default if not a terminal. }