Skip to content

Commit 489b73b

Browse files
committed
Make is_terminal fail fast if a process has no console at all
If a process has no console, it'll have NULL in place of a console handle, so return early with `false` in that case without making any OS calls.
1 parent 016e874 commit 489b73b

File tree

1 file changed

+9
-1
lines changed
  • library/std/src/sys/windows

1 file changed

+9
-1
lines changed

library/std/src/sys/windows/io.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,11 @@ pub fn is_terminal(h: &impl AsHandle) -> bool {
9090
unsafe fn handle_is_console(handle: BorrowedHandle<'_>) -> bool {
9191
let handle = handle.as_raw_handle();
9292

93+
// A null handle means the process has no console.
94+
if handle.is_null() {
95+
return false;
96+
}
97+
9398
let mut out = 0;
9499
if c::GetConsoleMode(handle, &mut out) != 0 {
95100
// False positives aren't possible. If we got a console then we definitely have a console.
@@ -102,7 +107,10 @@ unsafe fn handle_is_console(handle: BorrowedHandle<'_>) -> bool {
102107
// trust the negative.
103108
for std_handle in [c::STD_INPUT_HANDLE, c::STD_OUTPUT_HANDLE, c::STD_ERROR_HANDLE] {
104109
let std_handle = c::GetStdHandle(std_handle);
105-
if std_handle != handle && c::GetConsoleMode(std_handle, &mut out) != 0 {
110+
if !std_handle.is_null()
111+
&& std_handle != handle
112+
&& c::GetConsoleMode(std_handle, &mut out) != 0
113+
{
106114
return false;
107115
}
108116
}

0 commit comments

Comments
 (0)