Skip to main content

cuno_toolchain/
run.rs

1//! Running the programs detection asks (vswhere, compilers), behind a trait so
2//! that tests can answer for them.
3
4use std::ffi::OsStr;
5#[cfg(test)]
6use std::ffi::OsString;
7use std::io::{self, Read};
8use std::path::Path;
9#[cfg(test)]
10use std::path::PathBuf;
11use std::process::{Command, Stdio};
12use std::sync::mpsc;
13use std::time::{Duration, Instant};
14
15use cuno_core::Env;
16
17/// What a finished program returned.
18#[derive(Clone, Debug, Default)]
19pub struct Output {
20    /// Whether it exited with code 0.
21    pub success: bool,
22    /// Everything it wrote to stdout, as bytes: console programs on Windows
23    /// write in the console code page, not UTF-8.
24    pub stdout: Vec<u8>,
25    /// Everything it wrote to stderr, as bytes.
26    pub stderr: Vec<u8>,
27}
28
29/// Runs a program and waits for it.
30pub trait Runner {
31    /// Runs `program` with `args` and exactly the environment `env` (nothing
32    /// inherited from the process running cuno); `Err` when it could not be
33    /// started, or did not finish in time (`ErrorKind::TimedOut`).
34    fn run(&self, program: &Path, args: &[&OsStr], env: &Env) -> std::io::Result<Output>;
35
36    /// [`Runner::run`] in the working directory `cwd`. A runner that does
37    /// not start processes may ignore it.
38    fn run_in(
39        &self,
40        program: &Path,
41        args: &[&OsStr],
42        env: &Env,
43        cwd: &Path,
44    ) -> std::io::Result<Output> {
45        let _ = cwd;
46        self.run(program, args, env)
47    }
48}
49
50/// How long a tool may run before it is stopped (`docs/en/specs/toolchain.md`,
51/// "Detection").
52pub const TOOL_TIMEOUT: Duration = Duration::from_secs(30);
53
54/// The real [`Runner`], which starts processes and stops any that runs
55/// longer than [`TOOL_TIMEOUT`]. The binary passes it in.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub struct SystemRunner {
58    /// How long a tool may run; [`TOOL_TIMEOUT`] outside this module's tests.
59    limit: Duration,
60}
61
62impl SystemRunner {
63    /// A runner with the limit the spec gives.
64    pub const fn new() -> SystemRunner {
65        SystemRunner {
66            limit: TOOL_TIMEOUT,
67        }
68    }
69
70    /// A runner that stops a tool after `limit` instead: for work rather
71    /// than a probe, such as clang-tidy analysing a source
72    /// (`docs/en/specs/commands.md`, "`cuno lint`").
73    pub const fn with_limit(limit: Duration) -> SystemRunner {
74        SystemRunner { limit }
75    }
76}
77
78impl Default for SystemRunner {
79    fn default() -> SystemRunner {
80        SystemRunner::new()
81    }
82}
83
84impl Runner for SystemRunner {
85    /// Runs `program` with stdin closed, stopping it once the limit has
86    /// passed.
87    fn run(&self, program: &Path, args: &[&OsStr], env: &Env) -> io::Result<Output> {
88        self.wait(Command::new(program).args(args), env)
89    }
90
91    fn run_in(&self, program: &Path, args: &[&OsStr], env: &Env, cwd: &Path) -> io::Result<Output> {
92        self.wait(Command::new(program).args(args).current_dir(cwd), env)
93    }
94}
95
96impl SystemRunner {
97    /// Starts `command` with exactly `env` and stdin closed, and waits for
98    /// it, stopping it once the limit has passed.
99    fn wait(&self, command: &mut Command, env: &Env) -> io::Result<Output> {
100        let limit = self.limit;
101        let mut child = command
102            .env_clear()
103            .envs(env.vars())
104            .stdin(Stdio::null())
105            .stdout(Stdio::piped())
106            .stderr(Stdio::piped())
107            .spawn()?;
108        let timed_out = || {
109            io::Error::new(
110                io::ErrorKind::TimedOut,
111                format!(
112                    "did not finish within {} seconds and was stopped",
113                    limit.as_secs_f64()
114                ),
115            )
116        };
117        // Each pipe is drained on its own thread, so a child that fills one
118        // cannot stall waiting for cuno to read it. The bytes come back over a
119        // channel rather than by joining, so that waiting for them is bounded
120        // by the same deadline: a process the tool started can keep a pipe open
121        // after the tool itself has exited.
122        let drain = |pipe: Option<Box<dyn Read + Send>>| {
123            let (send, receive) = mpsc::channel();
124            std::thread::spawn(move || {
125                let mut bytes = Vec::new();
126                if let Some(mut pipe) = pipe {
127                    let _ = pipe.read_to_end(&mut bytes);
128                }
129                let _ = send.send(bytes);
130            });
131            receive
132        };
133        let stdout = drain(child.stdout.take().map(|p| Box::new(p) as _));
134        let stderr = drain(child.stderr.take().map(|p| Box::new(p) as _));
135        let deadline = Instant::now() + limit;
136        let status = loop {
137            match child.try_wait() {
138                Ok(Some(status)) => break status,
139                Ok(None) => {}
140                // Not left running when its state cannot be read.
141                Err(e) => {
142                    let _ = child.kill();
143                    let _ = child.wait();
144                    return Err(e);
145                }
146            }
147            if Instant::now() >= deadline {
148                let _ = child.kill();
149                let _ = child.wait();
150                return Err(timed_out());
151            }
152            std::thread::sleep(Duration::from_millis(10));
153        };
154        let collect = |pipe: mpsc::Receiver<Vec<u8>>| {
155            pipe.recv_timeout(deadline.saturating_duration_since(Instant::now()))
156                .map_err(|_| timed_out())
157        };
158        Ok(Output {
159            success: status.success(),
160            stdout: collect(stdout)?,
161            stderr: collect(stderr)?,
162        })
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use cuno_core::NameCase;
170
171    /// Mutation: drop `env_clear`, or the `envs` call; this test fails (the
172    /// child would see the test process's environment, or not the given one).
173    #[cfg(windows)]
174    #[test]
175    fn the_child_sees_exactly_the_given_environment() {
176        let comspec = std::env::var_os("ComSpec").expect("ComSpec is set on Windows");
177        let root = std::env::var_os("SystemRoot").expect("SystemRoot is set on Windows");
178        let env = Env::from_pairs(
179            [
180                ("SystemRoot".into(), root),
181                ("CUNO_RUN_PROBE".into(), "given".into()),
182            ],
183            NameCase::Insensitive,
184        );
185        let out = SystemRunner::new()
186            .run(
187                comspec.as_ref(),
188                &["/d".as_ref(), "/c".as_ref(), "set".as_ref()],
189                &env,
190            )
191            .unwrap();
192        let text = String::from_utf8_lossy(&out.stdout);
193        assert!(text.lines().any(|l| l == "CUNO_RUN_PROBE=given"), "{text}");
194        assert!(
195            !text
196                .lines()
197                .any(|l| l.to_ascii_uppercase().starts_with("PATH=")),
198            "{text}"
199        );
200    }
201
202    /// The helpers below run as child processes of the tests: the test binary
203    /// runs itself with `--ignored --exact <helper>`, and each helper does its
204    /// work only when its variable is set, so `cargo test -- --ignored` stays
205    /// harmless.
206    fn helper(name: &str) -> (PathBuf, Vec<OsString>) {
207        let args = ["--ignored", "--exact", name, "--nocapture"]
208            .map(OsString::from)
209            .to_vec();
210        (std::env::current_exe().unwrap(), args)
211    }
212
213    fn run_helper(runner: SystemRunner, name: &str, env: &Env) -> io::Result<Output> {
214        let (program, args) = helper(name);
215        let args: Vec<&OsStr> = args.iter().map(|a| a.as_os_str()).collect();
216        runner.run(&program, &args, env)
217    }
218
219    fn limited(limit: Duration) -> SystemRunner {
220        SystemRunner { limit }
221    }
222
223    /// Sleeps, then writes the file `CUNO_SLEEP_MARKER` names.
224    #[test]
225    #[ignore]
226    fn sleeps_then_marks() {
227        if let Some(marker) = std::env::var_os("CUNO_SLEEP_MARKER") {
228            std::thread::sleep(Duration::from_secs(3));
229            std::fs::write(marker, "finished").unwrap();
230        }
231    }
232
233    /// Starts [`sleeps_then_marks`] with this process's stdout, then exits at
234    /// once, leaving the pipe open behind it.
235    #[test]
236    #[ignore]
237    fn exits_leaving_a_sleeper() {
238        if std::env::var_os("CUNO_LEAVE_SLEEPER").is_some() {
239            let (program, args) = helper("run::tests::sleeps_then_marks");
240            // Deliberately not waited for: leaving it running is the point.
241            #[allow(clippy::zombie_processes)]
242            Command::new(program)
243                .args(args)
244                .stdout(Stdio::inherit())
245                .spawn()
246                .unwrap();
247        }
248    }
249
250    /// Writes more than a pipe holds to both streams, then fails.
251    #[test]
252    #[ignore]
253    fn floods_both_streams_then_fails() {
254        if std::env::var_os("CUNO_FLOOD").is_some() {
255            use std::io::Write;
256            let line = "0123456789abcdef".repeat(64);
257            for _ in 0..200 {
258                println!("out {line}");
259                let _ = writeln!(io::stderr(), "err {line}");
260            }
261            std::process::exit(3);
262        }
263    }
264
265    /// Reads stdin to its end and says so.
266    #[test]
267    #[ignore]
268    fn reads_stdin_to_the_end() {
269        if std::env::var_os("CUNO_READ_STDIN").is_some() {
270            let mut input = Vec::new();
271            io::stdin().read_to_end(&mut input).unwrap();
272            println!("stdin ended");
273        }
274    }
275
276    /// Runs [`reads_stdin_to_the_end`] through a runner, as a child whose
277    /// own stdin the test keeps open, and reports what came back.
278    #[test]
279    #[ignore]
280    fn runs_a_reader_of_stdin() {
281        if std::env::var_os("CUNO_RUN_READER").is_some() {
282            let env = Env::from_process()
283                .without(&["CUNO_RUN_READER"])
284                .with("CUNO_READ_STDIN", "1".into());
285            match run_helper(
286                limited(Duration::from_secs(5)),
287                "run::tests::reads_stdin_to_the_end",
288                &env,
289            ) {
290                Ok(out) => println!(
291                    "reader: {}",
292                    String::from_utf8_lossy(&out.stdout).contains("stdin ended")
293                ),
294                Err(e) => println!("reader: {e}"),
295            }
296        }
297    }
298
299    /// Mutation: change the limit the spec gives, or have `SystemRunner`
300    /// default to another; this test fails.
301    #[test]
302    fn the_system_runner_stops_tools_after_thirty_seconds() {
303        assert_eq!(TOOL_TIMEOUT, Duration::from_secs(30));
304        assert_eq!(SystemRunner::new().limit, TOOL_TIMEOUT);
305        assert_eq!(SystemRunner::default(), SystemRunner::new());
306    }
307
308    /// Mutation: wait without a deadline, run with another limit than the
309    /// runner's, or return at the deadline without stopping the tool; this
310    /// test fails (it returns late, or the tool finishes and writes its
311    /// marker).
312    #[test]
313    fn a_tool_past_the_limit_is_stopped() {
314        let dir = tempfile::tempdir().unwrap();
315        let marker = dir.path().join("marker");
316        let env = Env::from_process().with("CUNO_SLEEP_MARKER", marker.clone().into());
317        let started = Instant::now();
318        let err = run_helper(
319            limited(Duration::from_millis(300)),
320            "run::tests::sleeps_then_marks",
321            &env,
322        )
323        .unwrap_err();
324        assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}");
325        assert!(err.to_string().contains("0.3 seconds"), "{err}");
326        assert!(
327            started.elapsed() < Duration::from_secs(2),
328            "{:?}",
329            started.elapsed()
330        );
331        std::thread::sleep(Duration::from_secs(4));
332        assert!(!marker.exists(), "the tool kept running after the limit");
333    }
334
335    /// Mutation: wait for the output without the deadline (join the readers);
336    /// this test fails (it returns only when the left-behind process exits).
337    #[test]
338    fn output_held_open_after_exit_is_waited_for_only_until_the_limit() {
339        let dir = tempfile::tempdir().unwrap();
340        let env = Env::from_process()
341            .with("CUNO_SLEEP_MARKER", dir.path().join("marker").into())
342            .with("CUNO_LEAVE_SLEEPER", "1".into());
343        let started = Instant::now();
344        let err = run_helper(
345            limited(Duration::from_millis(1500)),
346            "run::tests::exits_leaving_a_sleeper",
347            &env,
348        )
349        .unwrap_err();
350        assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}");
351        assert!(
352            started.elapsed() < Duration::from_millis(2500),
353            "{:?}",
354            started.elapsed()
355        );
356    }
357
358    /// Mutation: report every run as a success, drop or swap stderr, or read
359    /// the pipes only after the tool exits (it then blocks on a full pipe
360    /// until the limit); this test fails.
361    #[test]
362    fn a_failing_tool_returns_both_streams_in_full() {
363        let env = Env::from_process().with("CUNO_FLOOD", "1".into());
364        let out = run_helper(
365            limited(Duration::from_secs(20)),
366            "run::tests::floods_both_streams_then_fails",
367            &env,
368        )
369        .unwrap();
370        assert!(!out.success);
371        let count = |bytes: &[u8], prefix: &str| {
372            String::from_utf8_lossy(bytes)
373                .lines()
374                .filter(|l| l.starts_with(prefix))
375                .count()
376        };
377        assert_eq!(count(&out.stdout, "out "), 200);
378        assert_eq!(count(&out.stderr, "err "), 200);
379        assert_eq!(count(&out.stdout, "err "), 0);
380    }
381
382    /// Mutation: let the tool inherit cuno's stdin instead of closing it;
383    /// this test fails (a tool reading its input then waits until the
384    /// limit, here on a pipe the test keeps open).
385    #[test]
386    fn a_tool_sees_its_stdin_closed() {
387        let (program, args) = helper("run::tests::runs_a_reader_of_stdin");
388        let mut middle = Command::new(program)
389            .args(args)
390            .env("CUNO_RUN_READER", "1")
391            .stdin(Stdio::piped())
392            .stdout(Stdio::piped())
393            .spawn()
394            .unwrap();
395        let _open = middle.stdin.take();
396        let mut text = String::new();
397        middle
398            .stdout
399            .take()
400            .unwrap()
401            .read_to_string(&mut text)
402            .unwrap();
403        middle.wait().unwrap();
404        assert!(text.contains("reader: true"), "{text}");
405    }
406}