Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / widget / windows / WindowsConsole.cpp
blobc8e7eb1a11a2556b1a2b9f7543053509d1c1dc89
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "WindowsConsole.h"
8 #include <windows.h>
9 #include <fcntl.h>
10 #include <cstdio>
11 #include <io.h>
13 namespace mozilla {
15 static void AssignStdHandle(const char* aPath, const char* aMode, FILE* aStream,
16 DWORD aStdHandle) {
17 // Visual Studio's _fileno() returns -2 for the standard
18 // streams if they aren't associated with an output stream.
19 const int fd = _fileno(aStream);
20 if (fd == -2) {
21 freopen(aPath, aMode, aStream);
22 return;
24 if (fd < 0) {
25 return;
28 const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
29 if (handle == INVALID_HANDLE_VALUE) {
30 return;
33 const HANDLE oldHandle = GetStdHandle(aStdHandle);
34 if (handle == oldHandle) {
35 return;
38 SetStdHandle(aStdHandle, handle);
41 // This code attaches the process to the appropriate console.
42 void UseParentConsole() {
43 if (AttachConsole(ATTACH_PARENT_PROCESS)) {
44 // Redirect the standard streams to the existing console, but
45 // only if they haven't been redirected to a valid file.
46 AssignStdHandle("CONOUT$", "w", stdout, STD_OUTPUT_HANDLE);
47 // There is no CONERR$, so use CONOUT$ for stderr as well.
48 AssignStdHandle("CONOUT$", "w", stderr, STD_ERROR_HANDLE);
49 AssignStdHandle("CONIN$", "r", stdin, STD_INPUT_HANDLE);
53 } // namespace mozilla