use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use cuno_core::Env;
use crate::prepare::TOOL_OPTION_VARIABLES;
use crate::{HostOs, Runner, ToolchainError, Version};
const MSYS2_DIRS: [&str; 2] = [r"C:\msys64\ucrt64\bin", r"C:\msys64\mingw64\bin"];
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Origin {
Configured,
Path,
Msys2,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Gcc {
pub path: PathBuf,
pub probe: Probe,
pub origin: Origin,
}
impl Gcc {
pub fn version(&self) -> Option<Version> {
match &self.probe {
Probe::Ran { version, .. } => Some(*version),
_ => None,
}
}
pub fn cxx(&self, host: HostOs) -> PathBuf {
self.path.with_file_name(host.executable("g++"))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Probe {
Ran {
version: Version,
prerelease: bool,
target: Option<String>,
ucrt: bool,
},
NoVersion,
Failed,
}
pub fn find_gcc(
env: &Env,
host: HostOs,
explicit: Option<&Path>,
run: &dyn Runner,
) -> Result<Vec<Gcc>, ToolchainError> {
let msys2: Vec<PathBuf> = MSYS2_DIRS.iter().map(PathBuf::from).collect();
find_in(env, host, explicit, &msys2, run)
}
fn find_in(
env: &Env,
host: HostOs,
explicit: Option<&Path>,
msys2: &[PathBuf],
run: &dyn Runner,
) -> Result<Vec<Gcc>, ToolchainError> {
let mut candidates: Vec<(PathBuf, Origin)> = Vec::new();
if let Some(path) = explicit {
if !path.is_file() {
return Err(ToolchainError::ConfiguredToolMissing {
setting: "[toolchain.paths] gcc".to_owned(),
path: path.to_owned(),
});
}
candidates.push((path.to_owned(), Origin::Configured));
}
let file = host.executable("gcc");
let mut dirs: Vec<(PathBuf, Origin)> = path_dirs(env)
.into_iter()
.map(|dir| (dir, Origin::Path))
.collect();
if host == HostOs::Windows {
dirs.extend(msys2.iter().map(|d| (d.clone(), Origin::Msys2)));
}
candidates.extend(
dirs.into_iter()
.map(|(dir, origin)| (dir.join(&file), origin))
.filter(|(path, _)| path.is_file()),
);
let mut seen: Vec<PathBuf> = Vec::new();
let mut found = Vec::new();
for (path, origin) in candidates {
let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
if seen.contains(&identity) {
continue;
}
seen.push(identity);
let probe = probe(&path, host, run, env);
found.push(Gcc {
path,
probe,
origin,
});
}
Ok(found)
}
fn path_dirs(env: &Env) -> Vec<PathBuf> {
env.get("PATH")
.map(|path| {
std::env::split_paths(path)
.filter(|d| d.is_absolute())
.collect()
})
.unwrap_or_default()
}
fn ask(path: &Path, args: &[&str], run: &dyn Runner, env: &Env) -> Option<String> {
let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect();
let cwd = path.parent().unwrap_or(Path::new("."));
run.run_in(path, &args, env, cwd)
.ok()
.filter(|o| o.success)
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
}
pub fn env_for(gcc: &Path, env: &Env) -> Env {
let env = &env.without(&TOOL_OPTION_VARIABLES);
let Some(dir) = gcc.parent() else {
return env.clone();
};
let rest = env
.get("PATH")
.map(|p| std::env::split_paths(p).collect::<Vec<_>>())
.unwrap_or_default();
match std::env::join_paths(std::iter::once(dir.to_owned()).chain(rest)) {
Ok(path) => env.with("PATH", path),
Err(_) => env.clone(),
}
}
fn probe(path: &Path, host: HostOs, run: &dyn Runner, env: &Env) -> Probe {
let env = &env_for(path, env);
let Some(full) = ask(path, &["-dumpfullversion"], run, env) else {
return Probe::Failed;
};
let Some(version) = Version::find_in(full.trim()) else {
return Probe::NoVersion;
};
let banner = ask(path, &["--version"], run, env).unwrap_or_default();
let first = banner.lines().next().unwrap_or_default();
let prerelease = first.contains("experimental") || first.contains("prerelease");
let target = ask(path, &["-dumpmachine"], run, env)
.map(|t| t.trim().to_owned())
.filter(|t| !t.is_empty());
let empty_input = match host {
HostOs::Windows => "NUL",
HostOs::Other => "/dev/null",
};
let args = ["-dM", "-E", "-x", "c", "-include", "_mingw.h", empty_input];
let Some(macros) = ask(path, &args, run, env) else {
return Probe::Failed;
};
let ucrt = macros.lines().any(|l| {
let mut words = l.split_whitespace();
words.next() == Some("#define") && words.next() == Some("_UCRT")
});
Probe::Ran {
version,
prerelease,
target,
ucrt,
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Install {
pub include: Vec<PathBuf>,
pub runtime: Vec<String>,
}
pub const RUNTIME_FILES: [&str; 9] = [
"crt2.o",
"libmingw32.a",
"libmingwex.a",
"libgcc.a",
"libgcc_eh.a",
"libstdc++.a",
"libstdc++exp.a",
"libwinpthread.a",
"libucrt.a",
];
pub fn install(
path: &Path,
host: HostOs,
env: &Env,
run: &dyn Runner,
) -> Result<Install, ToolchainError> {
let env = env.with("LC_ALL", "C".into()).without(&["LANGUAGE"]);
let cwd = path.parent().unwrap_or(Path::new("."));
let empty_input = match host {
HostOs::Windows => "NUL",
HostOs::Other => "/dev/null",
};
let ask = |asked: &'static str, args: &[&str], stderr: bool| {
let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect();
let unreadable = move |output: String| ToolchainError::GccUnreadable {
path: path.to_owned(),
asked,
output,
};
let output = run
.run_in(path, &args, &env, cwd)
.map_err(|e| unreadable(e.to_string()))?;
let text = String::from_utf8_lossy(if stderr {
&output.stderr
} else {
&output.stdout
})
.into_owned();
if !output.success {
return Err(unreadable(
String::from_utf8_lossy(&output.stderr).into_owned(),
));
}
Ok((text, unreadable))
};
let (verbose, unreadable) = ask(
"where its headers are",
&["-E", "-v", "-x", "c++", empty_input],
true,
)?;
let include = search_list(&verbose).ok_or_else(|| unreadable(verbose.clone()))?;
let (dirs, unreadable) = ask("where its libraries are", &["-print-search-dirs"], false)?;
let libraries = dirs
.lines()
.find_map(|l| l.strip_prefix("libraries: ="))
.ok_or_else(|| unreadable(dirs.clone()))?;
let libraries: Vec<PathBuf> = std::env::split_paths(libraries)
.map(|d| normal(&d))
.collect();
let runtime = RUNTIME_FILES
.iter()
.filter_map(|name| libraries.iter().map(|d| d.join(name)).find(|p| p.is_file()))
.map(|file| stamp(&file))
.collect();
Ok(Install { include, runtime })
}
fn search_list(stderr: &str) -> Option<Vec<PathBuf>> {
let mut lines = stderr.lines();
lines.find(|l| l.trim() == "#include <...> search starts here:")?;
let mut dirs = Vec::new();
for line in lines {
if line.trim() == "End of search list." {
return Some(dirs);
}
dirs.push(normal(Path::new(line.trim())));
}
None
}
fn normal(path: &Path) -> PathBuf {
use std::path::Component;
let mut out = PathBuf::new();
for part in path.components() {
match part {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
fn stamp(file: &Path) -> String {
let meta = std::fs::metadata(file).ok();
let len = meta.as_ref().map_or(0, std::fs::Metadata::len);
let time = meta
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos());
format!("{} {len} {time}", file.display())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Output;
use cuno_core::NameCase;
struct ByDir;
impl Runner for ByDir {
fn run(&self, program: &Path, args: &[&OsStr], env: &Env) -> std::io::Result<Output> {
self.run_in(program, args, env, Path::new("project"))
}
fn run_in(
&self,
program: &Path,
args: &[&OsStr],
env: &Env,
cwd: &Path,
) -> std::io::Result<Output> {
let dir = program
.parent()
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
let arg = args[0].to_string_lossy().into_owned();
let ok = |text: &str| Output {
success: true,
stdout: text.as_bytes().to_vec(),
stderr: Vec::new(),
};
let failed = Output {
success: false,
stdout: Vec::new(),
stderr: b"boom".to_vec(),
};
if dir == "broken" {
return Ok(failed);
}
Ok(match arg.as_str() {
"-dumpfullversion" => match dir.as_str() {
"nover" => ok("unknown\n"),
"exp" | "pre" => ok("15.0.1\n"),
"linux" | "msvcrt" | "nomachine" | "blank" | "nocc1" => ok("13.2.0\n"),
_ => ok(&format!("{}.2.0\n", dir.trim_start_matches('v'))),
},
"--version" => match dir.as_str() {
"exp" => ok("gcc.exe (GCC) 15.0.1 20260101 (experimental)\n"),
"pre" => ok("gcc.exe (GCC) 15.0.1 20260101 (prerelease)\n"),
_ => ok("gcc.exe (Buildroot 2023.02.1) 99.9.9\nCopyright 3.1.4\n"),
},
"-dumpmachine" => match dir.as_str() {
"linux" => ok("x86_64-linux-gnu\n"),
"nomachine" => failed,
"blank" => ok("\n"),
_ => ok("x86_64-w64-mingw32\n"),
},
"-dM" => {
let first_on_path = env
.get("PATH")
.and_then(|p| std::env::split_paths(p).next());
let header = args.windows(2).any(|w| w == ["-include", "_mingw.h"]);
if dir == "nocc1" || first_on_path.as_deref() != program.parent() {
Output {
success: false,
stdout: Vec::new(),
stderr: Vec::new(),
}
} else if cwd != program.parent().unwrap() {
ok("#define __MINGW64__ 1\n")
} else if !header || matches!(dir.as_str(), "msvcrt" | "linux") {
ok("#define __MINGW64__ 1\n#define _UCRTX 1\n")
} else {
ok("#define __MINGW64__ 1\n#define _UCRT\n")
}
}
_ => failed,
})
}
}
fn gcc_in(dir: &Path) -> PathBuf {
std::fs::create_dir_all(dir).unwrap();
let path = dir.join("gcc.exe");
std::fs::write(&path, "").unwrap();
path
}
fn env_with_path(dirs: &[&Path]) -> Env {
let path = std::env::join_paths(dirs).unwrap();
Env::from_pairs([("PATH".into(), path)], NameCase::Insensitive)
}
fn find(env: &Env, explicit: Option<&Path>) -> Vec<Gcc> {
find_in(env, HostOs::Windows, explicit, &[], &ByDir).unwrap()
}
#[test]
fn copies_are_found_in_order_once_each() {
let root = tempfile::tempdir().unwrap();
let configured = gcc_in(&root.path().join("v13"));
let on_path = gcc_in(&root.path().join("v14"));
let respelled = root.path().join("v14").join("..").join("v14");
let env = env_with_path(&[
on_path.parent().unwrap(),
&respelled,
configured.parent().unwrap(),
]);
let found = find(&env, Some(&configured));
let listed: Vec<(&Path, &Origin, Option<Version>)> = found
.iter()
.map(|g| (g.path.as_path(), &g.origin, g.version()))
.collect();
assert_eq!(
listed,
[
(
configured.as_path(),
&Origin::Configured,
Version::find_in("13.2.0")
),
(on_path.as_path(), &Origin::Path, Version::find_in("14.2.0")),
]
);
assert_eq!(
found[0].probe,
Probe::Ran {
version: Version::find_in("13.2.0").unwrap(),
prerelease: false,
target: Some("x86_64-w64-mingw32".to_owned()),
ucrt: true,
}
);
}
#[test]
fn what_each_copy_is_is_recorded() {
let root = tempfile::tempdir().unwrap();
let names = [
"exp",
"pre",
"linux",
"nover",
"broken",
"nomachine",
"blank",
"msvcrt",
"nocc1",
"v15",
];
let dirs: Vec<PathBuf> = names
.iter()
.map(|n| gcc_in(&root.path().join(n)).parent().unwrap().to_owned())
.collect();
let env = env_with_path(&dirs.iter().map(PathBuf::as_path).collect::<Vec<_>>());
let found = find(&env, None);
assert_eq!(found.len(), names.len());
let ran = |i: usize| match &found[i].probe {
Probe::Ran {
prerelease,
target,
ucrt,
..
} => (*prerelease, target.clone(), *ucrt),
other => panic!("{}: {other:?}", names[i]),
};
assert!(ran(0).0, "experimental");
assert!(ran(1).0, "prerelease");
assert_eq!(ran(2).1.as_deref(), Some("x86_64-linux-gnu"));
assert_eq!(found[3].probe, Probe::NoVersion);
assert_eq!(found[4].probe, Probe::Failed);
assert_eq!(ran(5).1, None, "a failed -dumpmachine");
assert_eq!(ran(6).1, None, "an empty -dumpmachine");
assert!(!ran(7).2, "MSVCRT");
assert_eq!(found[8].probe, Probe::Failed, "cannot preprocess");
assert!(ran(9).2, "`#define _UCRT` with nothing after it");
}
#[test]
fn gcc_s_directory_goes_in_front_of_path() {
let root = tempfile::tempdir().unwrap();
let (a, b) = (root.path().join("a"), root.path().join("b"));
let gcc = root.path().join("gcc").join("gcc.exe");
let env = env_for(&gcc, &env_with_path(&[&a, &b]));
let path: Vec<PathBuf> = std::env::split_paths(env.get("PATH").unwrap()).collect();
assert_eq!(path, [root.path().join("gcc"), a, b]);
}
#[test]
fn detection_runs_gcc_without_the_variables_the_build_leaves_out() {
struct Recording {
told: std::cell::RefCell<Vec<String>>,
}
impl Runner for Recording {
fn run(&self, _: &Path, args: &[&OsStr], env: &Env) -> std::io::Result<Output> {
let asked = args[0].to_string_lossy().into_owned();
if TOOL_OPTION_VARIABLES.iter().any(|v| env.get(v).is_some()) {
self.told.borrow_mut().push(asked.clone());
}
let text = match asked.as_str() {
"-dumpfullversion" => "15.2.0",
"-dumpmachine" => "x86_64-w64-mingw32",
"-dM" => "#define _UCRT 1",
_ => "",
};
Ok(Output {
success: true,
stdout: text.as_bytes().to_vec(),
stderr: Vec::new(),
})
}
}
let root = tempfile::tempdir().unwrap();
let gcc = root.path().join("gcc.exe");
std::fs::write(&gcc, "").unwrap();
for name in TOOL_OPTION_VARIABLES {
let env = env_with_path(&[]).with(name, "C:/elsewhere".into());
let runner = Recording {
told: Default::default(),
};
let found = find_in(&env, HostOs::Windows, Some(&gcc), &[], &runner).unwrap();
assert!(matches!(found[0].probe, Probe::Ran { ucrt: true, .. }));
assert!(
runner.told.borrow().is_empty(),
"{name} reached GCC when asked {:?}",
runner.told.borrow()
);
}
}
#[test]
fn a_configured_path_with_no_file_is_an_error() {
let root = tempfile::tempdir().unwrap();
let missing = root.path().join("nowhere").join("gcc.exe");
let err = find_in(
&env_with_path(&[]),
HostOs::Windows,
Some(&missing),
&[],
&ByDir,
)
.unwrap_err();
assert!(
matches!(&err, ToolchainError::ConfiguredToolMissing { setting, .. } if setting == "[toolchain.paths] gcc"),
"{err:?}"
);
}
#[test]
fn only_absolute_path_entries_are_searched() {
let root = tempfile::tempdir().unwrap();
let env = env_with_path(&[Path::new("relative"), root.path()]);
assert_eq!(path_dirs(&env), [root.path().to_owned()]);
}
#[test]
fn msys2_comes_after_path_and_g_plus_plus_is_beside_gcc() {
assert_eq!(
MSYS2_DIRS,
[r"C:\msys64\ucrt64\bin", r"C:\msys64\mingw64\bin"]
);
let root = tempfile::tempdir().unwrap();
let ucrt = gcc_in(&root.path().join("v14"));
let mingw = gcc_in(&root.path().join("v12"));
let on_path = gcc_in(&root.path().join("v13"));
let env = env_with_path(&[on_path.parent().unwrap()]);
let msys2 = [
ucrt.parent().unwrap().to_owned(),
mingw.parent().unwrap().to_owned(),
];
let found = find_in(&env, HostOs::Windows, None, &msys2, &ByDir).unwrap();
let order: Vec<(&Path, &Origin)> = found
.iter()
.map(|g| (g.path.as_path(), &g.origin))
.collect();
assert_eq!(
order,
[
(on_path.as_path(), &Origin::Path),
(ucrt.as_path(), &Origin::Msys2),
(mingw.as_path(), &Origin::Msys2),
]
);
for gcc in [&on_path, &ucrt, &mingw] {
std::fs::write(gcc.with_file_name("gcc"), "").unwrap();
}
let elsewhere = find_in(&env, HostOs::Other, None, &msys2, &ByDir).unwrap();
assert_eq!(elsewhere.len(), 1);
assert_eq!(
found[1].cxx(HostOs::Windows),
ucrt.with_file_name("g++.exe")
);
}
}