Skip to main content

cuno_toolchain/
gcc.rs

1//! MinGW GCC: finding `gcc` (and the `g++` beside it). See
2//! `docs/en/specs/toolchain.md`, "MinGW (GCC)".
3//!
4//! Nothing here runs unless GCC is wanted: the detection of every build
5//! (`prepare::detect`) does not call it, so an MSVC or Clang build, `cuno
6//! fmt` and `cuno lint` never start a GCC.
7
8use std::ffi::OsStr;
9use std::path::{Path, PathBuf};
10
11use cuno_core::Env;
12
13use crate::prepare::TOOL_OPTION_VARIABLES;
14use crate::{HostOs, Runner, ToolchainError, Version};
15
16/// The MSYS2 directories searched on Windows after `PATH`, in order: the
17/// UCRT64 environment, then MINGW64 (whose GCC is found, and refused for
18/// its C runtime, so the error can say why).
19const MSYS2_DIRS: [&str; 2] = [r"C:\msys64\ucrt64\bin", r"C:\msys64\mingw64\bin"];
20
21/// Where a copy of GCC was found.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub enum Origin {
24    /// The path written in `[toolchain.paths] gcc`.
25    Configured,
26    /// A directory on `PATH`.
27    Path,
28    /// One of MSYS2's standard directories.
29    Msys2,
30}
31
32/// One copy of GCC.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct Gcc {
35    /// `gcc`; its `g++` is the one in the same directory.
36    pub path: PathBuf,
37    /// What running it told.
38    pub probe: Probe,
39    /// Where it was found.
40    pub origin: Origin,
41}
42
43impl Gcc {
44    /// The version, when it gave one.
45    pub fn version(&self) -> Option<Version> {
46        match &self.probe {
47            Probe::Ran { version, .. } => Some(*version),
48            _ => None,
49        }
50    }
51
52    /// The `g++` beside it (`docs/en/specs/toolchain.md`, "MinGW (GCC)").
53    pub fn cxx(&self, host: HostOs) -> PathBuf {
54        self.path.with_file_name(host.executable("g++"))
55    }
56}
57
58/// What running a copy of GCC told, each from output no locale changes
59/// (`docs/en/specs/toolchain.md`, "MinGW (GCC)").
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub enum Probe {
62    /// It ran and gave its version.
63    Ran {
64        /// What `-dumpfullversion` printed (`14.2.0`).
65        version: Version,
66        /// Whether `--version`'s first line marks a snapshot
67        /// (`experimental`, `prerelease`).
68        prerelease: bool,
69        /// What `-dumpmachine` printed (`x86_64-w64-mingw32`), if anything.
70        target: Option<String>,
71        /// Whether its C runtime is UCRT: its `_mingw.h` defines `_UCRT`.
72        ucrt: bool,
73    },
74    /// It ran but gave no version that could be read.
75    NoVersion,
76    /// It could not be started, or exited with an error.
77    Failed,
78}
79
80/// Every copy of GCC, in the spec's search order: the configured path,
81/// `PATH` (absolute entries only), then MSYS2's standard directories (on
82/// Windows). The same file found twice is listed once. Not finding GCC is
83/// not an error; a configured path with no file is.
84pub fn find_gcc(
85    env: &Env,
86    host: HostOs,
87    explicit: Option<&Path>,
88    run: &dyn Runner,
89) -> Result<Vec<Gcc>, ToolchainError> {
90    let msys2: Vec<PathBuf> = MSYS2_DIRS.iter().map(PathBuf::from).collect();
91    find_in(env, host, explicit, &msys2, run)
92}
93
94/// [`find_gcc`] with MSYS2's directories given, so a test can stand them in.
95fn find_in(
96    env: &Env,
97    host: HostOs,
98    explicit: Option<&Path>,
99    msys2: &[PathBuf],
100    run: &dyn Runner,
101) -> Result<Vec<Gcc>, ToolchainError> {
102    let mut candidates: Vec<(PathBuf, Origin)> = Vec::new();
103    if let Some(path) = explicit {
104        if !path.is_file() {
105            return Err(ToolchainError::ConfiguredToolMissing {
106                setting: "[toolchain.paths] gcc".to_owned(),
107                path: path.to_owned(),
108            });
109        }
110        candidates.push((path.to_owned(), Origin::Configured));
111    }
112    let file = host.executable("gcc");
113    let mut dirs: Vec<(PathBuf, Origin)> = env
114        .search_dirs()
115        .into_iter()
116        .map(|dir| (dir, Origin::Path))
117        .collect();
118    if host == HostOs::Windows {
119        dirs.extend(msys2.iter().map(|d| (d.clone(), Origin::Msys2)));
120    }
121    candidates.extend(
122        dirs.into_iter()
123            .map(|(dir, origin)| (dir.join(&file), origin))
124            .filter(|(path, _)| path.is_file()),
125    );
126    let mut seen: Vec<PathBuf> = Vec::new();
127    let mut found = Vec::new();
128    for (path, origin) in candidates {
129        let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
130        if seen.contains(&identity) {
131            continue;
132        }
133        seen.push(identity);
134        let probe = probe(&path, host, run, env);
135        found.push(Gcc {
136            path,
137            probe,
138            origin,
139        });
140    }
141    Ok(found)
142}
143
144/// What `gcc` prints for `args`, when it ran and succeeded.
145/// It runs in its own directory, which holds no headers: `-include` looks
146/// in the working directory first, and cuno's is the project's.
147fn ask(path: &Path, args: &[&str], run: &dyn Runner, env: &Env) -> Option<String> {
148    let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect();
149    let cwd = path.parent().unwrap_or(Path::new("."));
150    run.run_in(path, &args, env, cwd)
151        .ok()
152        .filter(|o| o.success)
153        .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
154}
155
156/// The environment `gcc` runs in, for detection and the build alike: `env`
157/// without the variables compilers read flags and paths from
158/// ([`TOOL_OPTION_VARIABLES`]), so detection judges the GCC the build
159/// runs, and with the directory holding `gcc` first on `PATH`, since its
160/// compiler proper loads DLLs from there and fails silently when it is not
161/// on `PATH` (`docs/en/specs/toolchain.md`, "MinGW (GCC)").
162pub fn env_for(gcc: &Path, env: &Env) -> Env {
163    let env = &env.without(&TOOL_OPTION_VARIABLES);
164    let Some(dir) = gcc.parent() else {
165        return env.clone();
166    };
167    let rest = env
168        .get("PATH")
169        .map(|p| std::env::split_paths(p).collect::<Vec<_>>())
170        .unwrap_or_default();
171    match std::env::join_paths(std::iter::once(dir.to_owned()).chain(rest)) {
172        Ok(path) => env.with("PATH", path),
173        Err(_) => env.clone(),
174    }
175}
176
177/// Runs `gcc` for its version, whether it is a snapshot, its target and
178/// its C runtime, with its own directory first on `PATH`.
179fn probe(path: &Path, host: HostOs, run: &dyn Runner, env: &Env) -> Probe {
180    let env = &env_for(path, env);
181    let Some(full) = ask(path, &["-dumpfullversion"], run, env) else {
182        return Probe::Failed;
183    };
184    let Some(version) = Version::find_in(full.trim()) else {
185        return Probe::NoVersion;
186    };
187    let banner = ask(path, &["--version"], run, env).unwrap_or_default();
188    let first = banner.lines().next().unwrap_or_default();
189    let prerelease = first.contains("experimental") || first.contains("prerelease");
190    let target = ask(path, &["-dumpmachine"], run, env)
191        .map(|t| t.trim().to_owned())
192        .filter(|t| !t.is_empty());
193    let empty_input = match host {
194        HostOs::Windows => "NUL",
195        HostOs::Other => "/dev/null",
196    };
197    let args = ["-dM", "-E", "-x", "c", "-include", "_mingw.h", empty_input];
198    // A GCC that cannot preprocess cannot build either; calling it MSVCRT
199    // would send its user to install the GCC they already have.
200    let Some(macros) = ask(path, &args, run, env) else {
201        return Probe::Failed;
202    };
203    let ucrt = macros.lines().any(|l| {
204        let mut words = l.split_whitespace();
205        words.next() == Some("#define") && words.next() == Some("_UCRT")
206    });
207    Probe::Ran {
208        version,
209        prerelease,
210        target,
211        ucrt,
212    }
213}
214
215/// What a GCC builds with besides its command line, which the build records
216/// so that a change to it is not missed (`docs/en/specs/build.md`,
217/// "Deciding what changed").
218#[derive(Clone, Debug, Default, PartialEq, Eq)]
219pub struct Install {
220    /// The directories it searches for `#include <...>`, in its order: they
221    /// play the part `INCLUDE` plays for MSVC, so a header a project puts in
222    /// front of one of them is looked for by its name inside them
223    /// (`sys/stat.h`, not `stat.h`).
224    pub include: Vec<PathBuf>,
225    /// Each runtime file it links into every program, with its size and
226    /// time: MSYS2 updates these (crt, winpthreads) without changing GCC's
227    /// version.
228    pub runtime: Vec<String>,
229}
230
231/// The files GCC links into every program, statically: its start-up code,
232/// MinGW's runtime, its own and the C++ runtime, and winpthread.
233pub const RUNTIME_FILES: [&str; 9] = [
234    "crt2.o",
235    "libmingw32.a",
236    "libmingwex.a",
237    "libgcc.a",
238    "libgcc_eh.a",
239    "libstdc++.a",
240    "libstdc++exp.a",
241    "libwinpthread.a",
242    "libucrt.a",
243];
244
245/// Asks the GCC at `path` where its headers and libraries are, in `env`
246/// (the build's, with GCC's directory on `PATH`) and in its own directory,
247/// with its messages untranslated so they can be read.
248pub fn install(
249    path: &Path,
250    host: HostOs,
251    env: &Env,
252    run: &dyn Runner,
253) -> Result<Install, ToolchainError> {
254    let env = env.with("LC_ALL", "C".into()).without(&["LANGUAGE"]);
255    let cwd = path.parent().unwrap_or(Path::new("."));
256    let empty_input = match host {
257        HostOs::Windows => "NUL",
258        HostOs::Other => "/dev/null",
259    };
260    let ask = |asked: &'static str, args: &[&str], stderr: bool| {
261        let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect();
262        let unreadable = move |output: String| ToolchainError::GccUnreadable {
263            path: path.to_owned(),
264            asked,
265            output,
266        };
267        let output = run
268            .run_in(path, &args, &env, cwd)
269            .map_err(|e| unreadable(e.to_string()))?;
270        let text = String::from_utf8_lossy(if stderr {
271            &output.stderr
272        } else {
273            &output.stdout
274        })
275        .into_owned();
276        if !output.success {
277            return Err(unreadable(
278                String::from_utf8_lossy(&output.stderr).into_owned(),
279            ));
280        }
281        Ok((text, unreadable))
282    };
283    // C++'s list holds C's, and its own headers before them.
284    let (verbose, unreadable) = ask(
285        "where its headers are",
286        &["-E", "-v", "-x", "c++", empty_input],
287        true,
288    )?;
289    let include = search_list(&verbose).ok_or_else(|| unreadable(verbose.clone()))?;
290    let (dirs, unreadable) = ask("where its libraries are", &["-print-search-dirs"], false)?;
291    let libraries = dirs
292        .lines()
293        .find_map(|l| l.strip_prefix("libraries: ="))
294        .ok_or_else(|| unreadable(dirs.clone()))?;
295    let libraries: Vec<PathBuf> = std::env::split_paths(libraries)
296        .map(|d| normal(&d))
297        .collect();
298    let runtime = RUNTIME_FILES
299        .iter()
300        .filter_map(|name| libraries.iter().map(|d| d.join(name)).find(|p| p.is_file()))
301        .map(|file| stamp(&file))
302        .collect();
303    Ok(Install { include, runtime })
304}
305
306/// The directories between `#include <...> search starts here:` and `End
307/// of search list.` in `gcc -E -v`'s stderr, or `None` without both.
308fn search_list(stderr: &str) -> Option<Vec<PathBuf>> {
309    let mut lines = stderr.lines();
310    lines.find(|l| l.trim() == "#include <...> search starts here:")?;
311    let mut dirs = Vec::new();
312    for line in lines {
313        if line.trim() == "End of search list." {
314            return Some(dirs);
315        }
316        dirs.push(normal(Path::new(line.trim())));
317    }
318    None
319}
320
321/// `path` with its `.` and `..` resolved by name, as GCC prints them
322/// (`.../lib/gcc/x86_64-w64-mingw32/16.2.0/../../../../include`); not
323/// canonicalised, which on Windows gives a `\\?\` path.
324fn normal(path: &Path) -> PathBuf {
325    use std::path::Component;
326    let mut out = PathBuf::new();
327    for part in path.components() {
328        match part {
329            Component::CurDir => {}
330            Component::ParentDir => {
331                out.pop();
332            }
333            other => out.push(other),
334        }
335    }
336    out
337}
338
339/// `file` with its size and modification time, to tell an update.
340fn stamp(file: &Path) -> String {
341    let meta = std::fs::metadata(file).ok();
342    let len = meta.as_ref().map_or(0, std::fs::Metadata::len);
343    let time = meta
344        .and_then(|m| m.modified().ok())
345        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
346        .map_or(0, |d| d.as_nanos());
347    format!("{} {len} {time}", file.display())
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353    use crate::Output;
354    use cuno_core::NameCase;
355
356    /// Answers as the GCC in each directory would, by the directory's name:
357    /// `v<major>` is `<major>.2.0`, UCRT, MinGW; `msvcrt` lacks `_UCRT`;
358    /// as a real one, any of them gives `_UCRT` only from `-include
359    /// _mingw.h`, run with its own directory first on `PATH`;
360    /// `exp` and `pre` are snapshots; `linux` targets Linux; `nover` gives
361    /// no version; `nomachine` fails `-dumpmachine`; `blank` prints an empty
362    /// target; `nocc1` cannot preprocess; `broken` fails everything.
363    struct ByDir;
364
365    impl Runner for ByDir {
366        /// As if in a project whose root holds a `_mingw.h` of its own.
367        fn run(&self, program: &Path, args: &[&OsStr], env: &Env) -> std::io::Result<Output> {
368            self.run_in(program, args, env, Path::new("project"))
369        }
370
371        fn run_in(
372            &self,
373            program: &Path,
374            args: &[&OsStr],
375            env: &Env,
376            cwd: &Path,
377        ) -> std::io::Result<Output> {
378            let dir = program
379                .parent()
380                .unwrap()
381                .file_name()
382                .unwrap()
383                .to_string_lossy()
384                .into_owned();
385            let arg = args[0].to_string_lossy().into_owned();
386            let ok = |text: &str| Output {
387                success: true,
388                stdout: text.as_bytes().to_vec(),
389                stderr: Vec::new(),
390            };
391            let failed = Output {
392                success: false,
393                stdout: Vec::new(),
394                stderr: b"boom".to_vec(),
395            };
396            if dir == "broken" {
397                return Ok(failed);
398            }
399            Ok(match arg.as_str() {
400                "-dumpfullversion" => match dir.as_str() {
401                    "nover" => ok("unknown\n"),
402                    "exp" | "pre" => ok("15.0.1\n"),
403                    "linux" | "msvcrt" | "nomachine" | "blank" | "nocc1" => ok("13.2.0\n"),
404                    _ => ok(&format!("{}.2.0\n", dir.trim_start_matches('v'))),
405                },
406                "--version" => match dir.as_str() {
407                    "exp" => ok("gcc.exe (GCC) 15.0.1 20260101 (experimental)\n"),
408                    "pre" => ok("gcc.exe (GCC) 15.0.1 20260101 (prerelease)\n"),
409                    // A vendor name with a number of its own, which is not
410                    // the version.
411                    _ => ok("gcc.exe (Buildroot 2023.02.1) 99.9.9\nCopyright 3.1.4\n"),
412                },
413                "-dumpmachine" => match dir.as_str() {
414                    "linux" => ok("x86_64-linux-gnu\n"),
415                    "nomachine" => failed,
416                    "blank" => ok("\n"),
417                    _ => ok("x86_64-w64-mingw32\n"),
418                },
419                "-dM" => {
420                    let first_on_path = env
421                        .get("PATH")
422                        .and_then(|p| std::env::split_paths(p).next());
423                    let header = args.windows(2).any(|w| w == ["-include", "_mingw.h"]);
424                    if dir == "nocc1" || first_on_path.as_deref() != program.parent() {
425                        // Its compiler proper finds no DLLs: exit 1, silent.
426                        Output {
427                            success: false,
428                            stdout: Vec::new(),
429                            stderr: Vec::new(),
430                        }
431                    } else if cwd != program.parent().unwrap() {
432                        // The project's `_mingw.h` was read instead.
433                        ok("#define __MINGW64__ 1\n")
434                    } else if !header || matches!(dir.as_str(), "msvcrt" | "linux") {
435                        ok("#define __MINGW64__ 1\n#define _UCRTX 1\n")
436                    } else {
437                        // No trailing space, which the real one prints.
438                        ok("#define __MINGW64__ 1\n#define _UCRT\n")
439                    }
440                }
441                _ => failed,
442            })
443        }
444    }
445
446    fn gcc_in(dir: &Path) -> PathBuf {
447        std::fs::create_dir_all(dir).unwrap();
448        let path = dir.join("gcc.exe");
449        std::fs::write(&path, "").unwrap();
450        path
451    }
452
453    fn env_with_path(dirs: &[&Path]) -> Env {
454        let path = std::env::join_paths(dirs).unwrap();
455        Env::from_pairs([("PATH".into(), path)], NameCase::Insensitive)
456    }
457
458    fn find(env: &Env, explicit: Option<&Path>) -> Vec<Gcc> {
459        find_in(env, HostOs::Windows, explicit, &[], &ByDir).unwrap()
460    }
461
462    /// The configured path comes first, then `PATH` in order; a file
463    /// reached twice, even by another spelling, is listed once; the version
464    /// is `-dumpfullversion`'s, never a number in the banner; a UCRT GCC
465    /// whose directory is not first on `PATH` is still found to be UCRT.
466    ///
467    /// Mutation: search `PATH` before the configured path, compare paths as
468    /// written, read the version from the banner, check `_UCRT` without
469    /// `-include _mingw.h`, run GCC with the caller's `PATH`, or run it in
470    /// the project (whose `_mingw.h` shadows GCC's); this test fails.
471    #[test]
472    fn copies_are_found_in_order_once_each() {
473        let root = tempfile::tempdir().unwrap();
474        let configured = gcc_in(&root.path().join("v13"));
475        let on_path = gcc_in(&root.path().join("v14"));
476        let respelled = root.path().join("v14").join("..").join("v14");
477        let env = env_with_path(&[
478            on_path.parent().unwrap(),
479            &respelled,
480            configured.parent().unwrap(),
481        ]);
482        let found = find(&env, Some(&configured));
483        let listed: Vec<(&Path, &Origin, Option<Version>)> = found
484            .iter()
485            .map(|g| (g.path.as_path(), &g.origin, g.version()))
486            .collect();
487        assert_eq!(
488            listed,
489            [
490                (
491                    configured.as_path(),
492                    &Origin::Configured,
493                    Version::find_in("13.2.0")
494                ),
495                (on_path.as_path(), &Origin::Path, Version::find_in("14.2.0")),
496            ]
497        );
498        assert_eq!(
499            found[0].probe,
500            Probe::Ran {
501                version: Version::find_in("13.2.0").unwrap(),
502                prerelease: false,
503                target: Some("x86_64-w64-mingw32".to_owned()),
504                ucrt: true,
505            }
506        );
507    }
508
509    /// Snapshots by either word, another target, no version, a run that
510    /// fails, a failed or empty `-dumpmachine`, a C runtime other than UCRT,
511    /// and a GCC that cannot preprocess (failed, not MSVCRT) are each
512    /// recorded as such, not dropped.
513    ///
514    /// Mutation: miss `experimental` or `prerelease`, keep an empty target,
515    /// ignore `-dumpmachine` failing, record no version as failed, take
516    /// `_UCRTX` for `_UCRT`, require a space after `_UCRT`, record a GCC that
517    /// cannot preprocess as MSVCRT, or leave a copy out; this test fails.
518    #[test]
519    fn what_each_copy_is_is_recorded() {
520        let root = tempfile::tempdir().unwrap();
521        let names = [
522            "exp",
523            "pre",
524            "linux",
525            "nover",
526            "broken",
527            "nomachine",
528            "blank",
529            "msvcrt",
530            "nocc1",
531            "v15",
532        ];
533        let dirs: Vec<PathBuf> = names
534            .iter()
535            .map(|n| gcc_in(&root.path().join(n)).parent().unwrap().to_owned())
536            .collect();
537        let env = env_with_path(&dirs.iter().map(PathBuf::as_path).collect::<Vec<_>>());
538        let found = find(&env, None);
539        assert_eq!(found.len(), names.len());
540        let ran = |i: usize| match &found[i].probe {
541            Probe::Ran {
542                prerelease,
543                target,
544                ucrt,
545                ..
546            } => (*prerelease, target.clone(), *ucrt),
547            other => panic!("{}: {other:?}", names[i]),
548        };
549        assert!(ran(0).0, "experimental");
550        assert!(ran(1).0, "prerelease");
551        assert_eq!(ran(2).1.as_deref(), Some("x86_64-linux-gnu"));
552        assert_eq!(found[3].probe, Probe::NoVersion);
553        assert_eq!(found[4].probe, Probe::Failed);
554        assert_eq!(ran(5).1, None, "a failed -dumpmachine");
555        assert_eq!(ran(6).1, None, "an empty -dumpmachine");
556        assert!(!ran(7).2, "MSVCRT");
557        assert_eq!(found[8].probe, Probe::Failed, "cannot preprocess");
558        assert!(ran(9).2, "`#define _UCRT` with nothing after it");
559    }
560
561    /// GCC's directory goes in front of `PATH`, and the rest stays, in order.
562    ///
563    /// Mutation: drop the rest of `PATH`, or put the directory last; this
564    /// test fails.
565    #[test]
566    fn gcc_s_directory_goes_in_front_of_path() {
567        let root = tempfile::tempdir().unwrap();
568        let (a, b) = (root.path().join("a"), root.path().join("b"));
569        let gcc = root.path().join("gcc").join("gcc.exe");
570        let env = env_for(&gcc, &env_with_path(&[&a, &b]));
571        let path: Vec<PathBuf> = std::env::split_paths(env.get("PATH").unwrap()).collect();
572        assert_eq!(path, [root.path().join("gcc"), a, b]);
573    }
574
575    /// A `CPATH` holding another `_mingw.h` would make the UCRT check read
576    /// it; detection runs GCC without the variables the build leaves out,
577    /// so it judges the GCC the build runs. The runner records every
578    /// question GCC was asked while one of them reached it.
579    ///
580    /// Mutation: keep the variables in `env_for`, or ask any one question
581    /// (`--version`, `-dumpmachine`, ...) in the environment detection was
582    /// given; this test fails.
583    #[test]
584    fn detection_runs_gcc_without_the_variables_the_build_leaves_out() {
585        struct Recording {
586            told: std::cell::RefCell<Vec<String>>,
587        }
588
589        impl Runner for Recording {
590            fn run(&self, _: &Path, args: &[&OsStr], env: &Env) -> std::io::Result<Output> {
591                let asked = args[0].to_string_lossy().into_owned();
592                if TOOL_OPTION_VARIABLES.iter().any(|v| env.get(v).is_some()) {
593                    self.told.borrow_mut().push(asked.clone());
594                }
595                let text = match asked.as_str() {
596                    "-dumpfullversion" => "15.2.0",
597                    "-dumpmachine" => "x86_64-w64-mingw32",
598                    "-dM" => "#define _UCRT 1",
599                    _ => "",
600                };
601                Ok(Output {
602                    success: true,
603                    stdout: text.as_bytes().to_vec(),
604                    stderr: Vec::new(),
605                })
606            }
607        }
608
609        let root = tempfile::tempdir().unwrap();
610        let gcc = root.path().join("gcc.exe");
611        std::fs::write(&gcc, "").unwrap();
612        for name in TOOL_OPTION_VARIABLES {
613            let env = env_with_path(&[]).with(name, "C:/elsewhere".into());
614            let runner = Recording {
615                told: Default::default(),
616            };
617            let found = find_in(&env, HostOs::Windows, Some(&gcc), &[], &runner).unwrap();
618            assert!(matches!(found[0].probe, Probe::Ran { ucrt: true, .. }));
619            assert!(
620                runner.told.borrow().is_empty(),
621                "{name} reached GCC when asked {:?}",
622                runner.told.borrow()
623            );
624        }
625    }
626
627    /// A configured path with no file is an error naming the setting.
628    ///
629    /// Mutation: skip a missing configured file; this test fails.
630    #[test]
631    fn a_configured_path_with_no_file_is_an_error() {
632        let root = tempfile::tempdir().unwrap();
633        let missing = root.path().join("nowhere").join("gcc.exe");
634        let err = find_in(
635            &env_with_path(&[]),
636            HostOs::Windows,
637            Some(&missing),
638            &[],
639            &ByDir,
640        )
641        .unwrap_err();
642        assert!(
643            matches!(&err, ToolchainError::ConfiguredToolMissing { setting, .. } if setting == "[toolchain.paths] gcc"),
644            "{err:?}"
645        );
646    }
647
648    /// Only absolute `PATH` entries are searched.
649    ///
650    /// Mutation: keep a relative entry; this test fails.
651    #[test]
652    fn only_absolute_path_entries_are_searched() {
653        let root = tempfile::tempdir().unwrap();
654        let env = env_with_path(&[Path::new("relative"), root.path()]);
655        assert_eq!(env.search_dirs(), [root.path().to_owned()]);
656    }
657
658    /// On Windows MSYS2's directories come after `PATH`, in the order
659    /// given, UCRT64 first; elsewhere they are not searched. `g++` is the
660    /// one beside the `gcc`.
661    ///
662    /// Mutation: search MSYS2 before `PATH`, swap the two MSYS2
663    /// directories, search them off Windows, or look for `g++` elsewhere;
664    /// this test fails.
665    #[test]
666    fn msys2_comes_after_path_and_g_plus_plus_is_beside_gcc() {
667        assert_eq!(
668            MSYS2_DIRS,
669            [r"C:\msys64\ucrt64\bin", r"C:\msys64\mingw64\bin"]
670        );
671        let root = tempfile::tempdir().unwrap();
672        let ucrt = gcc_in(&root.path().join("v14"));
673        let mingw = gcc_in(&root.path().join("v12"));
674        let on_path = gcc_in(&root.path().join("v13"));
675        let env = env_with_path(&[on_path.parent().unwrap()]);
676        let msys2 = [
677            ucrt.parent().unwrap().to_owned(),
678            mingw.parent().unwrap().to_owned(),
679        ];
680        let found = find_in(&env, HostOs::Windows, None, &msys2, &ByDir).unwrap();
681        let order: Vec<(&Path, &Origin)> = found
682            .iter()
683            .map(|g| (g.path.as_path(), &g.origin))
684            .collect();
685        assert_eq!(
686            order,
687            [
688                (on_path.as_path(), &Origin::Path),
689                (ucrt.as_path(), &Origin::Msys2),
690                (mingw.as_path(), &Origin::Msys2),
691            ]
692        );
693        // Off Windows the file is `gcc`, and MSYS2 is not searched, though
694        // its directories hold one.
695        for gcc in [&on_path, &ucrt, &mingw] {
696            std::fs::write(gcc.with_file_name("gcc"), "").unwrap();
697        }
698        let elsewhere = find_in(&env, HostOs::Other, None, &msys2, &ByDir).unwrap();
699        assert_eq!(elsewhere.len(), 1);
700        assert_eq!(
701            found[1].cxx(HostOs::Windows),
702            ucrt.with_file_name("g++.exe")
703        );
704    }
705}