Debian Codegraph @

debian/rust-vendor/ctrlc/tests/main/harness.rs

raw
1 // Copyright (c) 2023 CtrlC developers
2 // Licensed under the Apache License, Version 2.0
3 // <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5 // license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
6 // at your option. All files in the project carrying such
7 // notice may not be copied, modified, or distributed except
8 // according to those terms.
9
10 #[cfg(unix)]
11 pub mod platform {
12 use std::io;
13
14 pub unsafe fn setup() -> io::Result<()> {
15 Ok(())
16 }
17
18 pub unsafe fn cleanup() -> io::Result<()> {
19 Ok(())
20 }
21
22 pub unsafe fn raise_ctrl_c() {
23 nix::sys::signal::raise(nix::sys::signal::SIGINT).unwrap();
24 }
25
26 pub unsafe fn print(fmt: ::std::fmt::Arguments) {
27 use self::io::Write;
28 let stdout = ::std::io::stdout();
29 stdout.lock().write_fmt(fmt).unwrap();
30 }
31 }
32
33 #[cfg(windows)]
34 pub mod platform {
35 use std::io;
36 use std::ptr;
37 use windows_sys::Win32::Foundation::{
38 GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE,
39 };
40 use windows_sys::Win32::Storage::FileSystem::{
41 CreateFileA, WriteFile, FILE_SHARE_WRITE, OPEN_EXISTING,
42 };
43 use windows_sys::Win32::System::Console::{
44 AllocConsole, AttachConsole, FreeConsole, GenerateConsoleCtrlEvent, GetConsoleMode,
45 GetStdHandle, SetStdHandle, ATTACH_PARENT_PROCESS, CTRL_C_EVENT, STD_ERROR_HANDLE,
46 STD_OUTPUT_HANDLE,
47 };
48
49 /// Stores a piped stdout handle or a cache that gets
50 /// flushed when we reattached to the old console.
51 enum Output {
52 Pipe(HANDLE),
53 Cached(Vec<u8>),
54 }
55
56 static mut OLD_OUT: *mut Output = 0 as *mut Output;
57
58 impl io::Write for Output {
59 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
60 match *self {
61 Output::Pipe(handle) => unsafe {
62 let mut n = 0u32;
63 if WriteFile(
64 handle,
65 buf.as_ptr(),
66 buf.len() as u32,
67 &mut n as *mut u32,
68 ptr::null_mut(),
69 ) == 0
70 {
71 Err(io::Error::last_os_error())
72 } else {
73 Ok(n as usize)
74 }
75 },
76 Output::Cached(ref mut s) => s.write(buf),
77 }
78 }
79
80 fn flush(&mut self) -> io::Result<()> {
81 Ok(())
82 }
83 }
84
85 impl Output {
86 /// Stores current piped stdout or creates a new output cache that will
87 /// be written to stdout at a later time.
88 fn new() -> io::Result<Output> {
89 unsafe {
90 let stdout = GetStdHandle(STD_OUTPUT_HANDLE);
91 if stdout.is_null() || stdout == INVALID_HANDLE_VALUE {
92 return Err(io::Error::last_os_error());
93 }
94
95 let mut out = 0u32;
96 match GetConsoleMode(stdout, &mut out as *mut u32) {
97 0 => Ok(Output::Pipe(stdout)),
98 _ => Ok(Output::Cached(Vec::new())),
99 }
100 }
101 }
102
103 /// Set stdout/stderr and flush cache.
104 unsafe fn set_as_std(self) -> io::Result<()> {
105 let stdout = match self {
106 Output::Pipe(h) => h,
107 Output::Cached(_) => get_stdout()?,
108 };
109
110 if SetStdHandle(STD_OUTPUT_HANDLE, stdout) == 0 {
111 return Err(io::Error::last_os_error());
112 }
113
114 if SetStdHandle(STD_ERROR_HANDLE, stdout) == 0 {
115 return Err(io::Error::last_os_error());
116 }
117
118 match self {
119 Output::Pipe(_) => Ok(()),
120 Output::Cached(ref s) => {
121 // Write cached output
122 use self::io::Write;
123 let out = io::stdout();
124 out.lock().write_all(&s[..])?;
125 Ok(())
126 }
127 }
128 }
129 }
130
131 unsafe fn get_stdout() -> io::Result<HANDLE> {
132 let stdout = CreateFileA(
133 "CONOUT$\0".as_ptr(),
134 GENERIC_READ | GENERIC_WRITE,
135 FILE_SHARE_WRITE,
136 ptr::null_mut(),
137 OPEN_EXISTING,
138 0,
139 0 as HANDLE,
140 );
141
142 if stdout.is_null() || stdout == INVALID_HANDLE_VALUE {
143 Err(io::Error::last_os_error())
144 } else {
145 Ok(stdout)
146 }
147 }
148
149 /// Detach from the current console and create a new one,
150 /// We do this because GenerateConsoleCtrlEvent() sends ctrl-c events
151 /// to all processes on the same console. We want events to be received
152 /// only by our process.
153 ///
154 /// This breaks rust's stdout pre 1.18.0. Rust used to
155 /// [cache the std handles](https://github.com/rust-lang/rust/pull/40516)
156 ///
157 pub unsafe fn setup() -> io::Result<()> {
158 let old_out = Output::new()?;
159
160 if FreeConsole() == 0 {
161 return Err(io::Error::last_os_error());
162 }
163
164 if AllocConsole() == 0 {
165 return Err(io::Error::last_os_error());
166 }
167
168 // AllocConsole will not always set stdout/stderr to the to the console buffer
169 // of the new terminal.
170
171 let stdout = get_stdout()?;
172 if SetStdHandle(STD_OUTPUT_HANDLE, stdout) == 0 {
173 return Err(io::Error::last_os_error());
174 }
175
176 if SetStdHandle(STD_ERROR_HANDLE, stdout) == 0 {
177 return Err(io::Error::last_os_error());
178 }
179
180 OLD_OUT = Box::into_raw(Box::new(old_out));
181
182 Ok(())
183 }
184
185 /// Reattach to the old console.
186 pub unsafe fn cleanup() -> io::Result<()> {
187 if FreeConsole() == 0 {
188 return Err(io::Error::last_os_error());
189 }
190
191 if AttachConsole(ATTACH_PARENT_PROCESS) == 0 {
192 return Err(io::Error::last_os_error());
193 }
194
195 Box::from_raw(OLD_OUT).set_as_std()?;
196
197 Ok(())
198 }
199
200 /// This will signal the whole process group.
201 pub unsafe fn raise_ctrl_c() {
202 assert!(GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) != 0);
203 }
204
205 /// Print to both consoles, this is not thread safe.
206 pub unsafe fn print(fmt: ::std::fmt::Arguments) {
207 use self::io::Write;
208 {
209 let stdout = io::stdout();
210 stdout.lock().write_fmt(fmt).unwrap();
211 }
212 {
213 assert!(!OLD_OUT.is_null());
214 (*OLD_OUT).write_fmt(fmt).unwrap();
215 }
216 }
217 }
218
219 macro_rules! run_tests {
220 ( $($test_fn:ident),* ) => {
221 unsafe {
222 $(
223 harness::platform::print(format_args!("test {} ... ", stringify!($test_fn)));
224 $test_fn();
225 harness::platform::print(format_args!("ok\n"));
226 )*
227 }
228 }
229 }
230
231 pub fn run_harness(f: fn()) {
232 unsafe {
233 platform::setup().unwrap();
234 }
235
236 let default = std::panic::take_hook();
237 std::panic::set_hook(Box::new(move |info| {
238 unsafe {
239 platform::cleanup().unwrap();
240 }
241 (default)(info);
242 }));
243
244 println!("");
245 f();
246 println!("");
247
248 unsafe {
249 platform::cleanup().unwrap();
250 }
251 }