Skip to content

Commit a23678c

Browse files
committed
Fix switch_stdout_to on Windows7
The switch_stdout_to test was broken on Windows7, as the test infrastructure would refuse to delete the temporary test folder because the switch-stdout-output file we redirected the stdout to was still opened. To fix this issue, we make switch_stdout_to return the previous handle, and add a new switch_stdout_to call at the end of the test to return the stdio handles to their original state. The handle the second switch_stdout_to returns will be automatically closed, which should allow the temporary test folder to be deleted properly.
1 parent 91bbdd9 commit a23678c

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

library/std/tests/switch-stdout.rs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,32 +5,47 @@ use std::io::{Read, Write};
55

66
mod common;
77

8+
#[cfg(windows)]
9+
use std::os::windows::io::OwnedHandle;
10+
811
#[cfg(unix)]
9-
fn switch_stdout_to(file: File) {
12+
use std::os::fd::OwnedFd;
13+
14+
#[cfg(unix)]
15+
fn switch_stdout_to(file: OwnedFd) -> OwnedFd {
1016
use std::os::unix::prelude::*;
1117

1218
extern "C" {
19+
fn dup(old: i32) -> i32;
1320
fn dup2(old: i32, new: i32) -> i32;
1421
}
1522

1623
unsafe {
24+
let orig_fd = unsafe { dup(1) };
25+
assert_ne!(orig_hdl, -1);
1726
assert_eq!(dup2(file.as_raw_fd(), 1), 1);
27+
OwnedFd::from_raw_fd(orig_fd)
1828
}
1929
}
2030

2131
#[cfg(windows)]
22-
fn switch_stdout_to(file: File) {
32+
fn switch_stdout_to(file: OwnedHandle) -> OwnedHandle {
2333
use std::os::windows::prelude::*;
2434

2535
extern "system" {
36+
fn GetStdHandle(nStdHandle: u32) -> *mut u8;
2637
fn SetStdHandle(nStdHandle: u32, handle: *mut u8) -> i32;
2738
}
2839

2940
const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32;
41+
const INVALID_HANDLE_VALUE: *mut u8 = !0 as *mut u8;
3042

3143
unsafe {
44+
let orig_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
45+
assert!(!orig_hdl.is_null() && orig_hdl != INVALID_HANDLE_VALUE);
3246
let rc = SetStdHandle(STD_OUTPUT_HANDLE, file.into_raw_handle() as *mut _);
3347
assert!(rc != 0);
48+
OwnedHandle::from_raw_handle(orig_hdl as _)
3449
}
3550
}
3651

@@ -43,10 +58,12 @@ fn switch_stdout() {
4358
let mut stdout = std::io::stdout();
4459
stdout.write(b"foo\n").unwrap();
4560
stdout.flush().unwrap();
46-
switch_stdout_to(f);
61+
let orig_hdl = switch_stdout_to(f.into());
4762
stdout.write(b"bar\n").unwrap();
4863
stdout.flush().unwrap();
4964

65+
switch_stdout_to(orig_hdl);
66+
5067
let mut contents = String::new();
5168
File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
5269
assert_eq!(contents, "bar\n");

0 commit comments

Comments
 (0)