1use 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
16const MSYS2_DIRS: [&str; 2] = [r"C:\msys64\ucrt64\bin", r"C:\msys64\mingw64\bin"];
20
21#[derive(Clone, Debug, PartialEq, Eq)]
23pub enum Origin {
24 Configured,
26 Path,
28 Msys2,
30}
31
32#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct Gcc {
35 pub path: PathBuf,
37 pub probe: Probe,
39 pub origin: Origin,
41}
42
43impl Gcc {
44 pub fn version(&self) -> Option<Version> {
46 match &self.probe {
47 Probe::Ran { version, .. } => Some(*version),
48 _ => None,
49 }
50 }
51
52 pub fn cxx(&self, host: HostOs) -> PathBuf {
54 self.path.with_file_name(host.executable("g++"))
55 }
56}
57
58#[derive(Clone, Debug, PartialEq, Eq)]
61pub enum Probe {
62 Ran {
64 version: Version,
66 prerelease: bool,
69 target: Option<String>,
71 ucrt: bool,
73 },
74 NoVersion,
76 Failed,
78}
79
80pub 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
94fn 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
144fn 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
156pub 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
177fn 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 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
219pub struct Install {
220 pub include: Vec<PathBuf>,
225 pub runtime: Vec<String>,
229}
230
231pub 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
245pub 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 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
306fn 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
321fn 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
339fn 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 struct ByDir;
364
365 impl Runner for ByDir {
366 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 _ => 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 Output {
427 success: false,
428 stdout: Vec::new(),
429 stderr: Vec::new(),
430 }
431 } else if cwd != program.parent().unwrap() {
432 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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}