1use std::collections::{HashMap, HashSet};
13use std::ffi::{OsStr, OsString};
14use std::path::PathBuf;
15use std::{env, fs};
16
17use crate::builder::{Builder, Kind};
18use crate::core::build_steps::tool;
19use crate::core::config::{CompilerBuiltins, Target};
20use crate::utils::exec::command;
21use crate::{Build, Subcommand, t};
22
23pub struct Finder {
24 cache: HashMap<OsString, Option<PathBuf>>,
25 path: OsString,
26}
27
28const STAGE0_MISSING_TARGETS: &[&str] = &[
36 ];
38
39const LIBSTDCXX_MIN_VERSION_THRESHOLD: usize = 8;
42
43impl Finder {
44 pub fn new() -> Self {
45 Self { cache: HashMap::new(), path: env::var_os("PATH").unwrap_or_default() }
46 }
47
48 pub fn maybe_have<S: Into<OsString>>(&mut self, cmd: S) -> Option<PathBuf> {
49 let cmd: OsString = cmd.into();
50 let path = &self.path;
51 self.cache
52 .entry(cmd.clone())
53 .or_insert_with(|| {
54 for path in env::split_paths(path) {
55 let target = path.join(&cmd);
56 let mut cmd_exe = cmd.clone();
57 cmd_exe.push(".exe");
58
59 if target.is_file() || path.join(&cmd_exe).exists() || target.join(&cmd_exe).exists()
62 {
64 return Some(target);
65 }
66 }
67 None
68 })
69 .clone()
70 }
71
72 pub fn must_have<S: AsRef<OsStr>>(&mut self, cmd: S) -> PathBuf {
73 self.maybe_have(&cmd).unwrap_or_else(|| {
74 panic!("\n\ncouldn't find required command: {:?}\n\n", cmd.as_ref());
75 })
76 }
77}
78
79pub fn check(build: &mut Build) {
80 let mut skip_target_sanity =
81 env::var_os("BOOTSTRAP_SKIP_TARGET_SANITY").is_some_and(|s| s == "1" || s == "true");
82
83 skip_target_sanity |= build.config.cmd.kind() == Kind::Check;
84
85 let skipped_paths = [OsStr::new("mir-opt"), OsStr::new("miri")];
87 skip_target_sanity |= build.config.paths.iter().any(|path| {
88 path.components().any(|component| skipped_paths.contains(&component.as_os_str()))
89 });
90
91 let path = env::var_os("PATH").unwrap_or_default();
92 if cfg!(windows) && path.to_string_lossy().contains('\"') {
97 panic!("PATH contains invalid character '\"'");
98 }
99
100 let mut cmd_finder = Finder::new();
101 if build.rust_info().is_managed_git_subrepository() {
104 cmd_finder.must_have("git");
105 }
106
107 if cfg!(not(test))
109 && !build.config.dry_run()
110 && !build.host_target.is_msvc()
111 && build.config.llvm_from_ci
112 {
113 let builder = Builder::new(build);
114 let libcxx_version = builder.ensure(tool::LibcxxVersionTool { target: build.host_target });
115
116 match libcxx_version {
117 tool::LibcxxVersion::Gnu(version) => {
118 if LIBSTDCXX_MIN_VERSION_THRESHOLD > version {
119 eprintln!(
120 "\nYour system's libstdc++ version is too old for the `llvm.download-ci-llvm` option."
121 );
122 eprintln!("Current version detected: '{version}'");
123 eprintln!("Minimum required version: '{LIBSTDCXX_MIN_VERSION_THRESHOLD}'");
124 eprintln!(
125 "Consider upgrading libstdc++ or disabling the `llvm.download-ci-llvm` option."
126 );
127 eprintln!(
128 "If you choose to upgrade libstdc++, run `x clean` or delete `build/host/libcxx-version` manually after the upgrade."
129 );
130 }
131 }
132 tool::LibcxxVersion::Llvm(_) => {
133 }
135 }
136 }
137
138 let building_llvm = !build.config.llvm_from_ci
140 && !build.config.local_rebuild
141 && build.hosts.iter().any(|host| {
142 build.config.llvm_enabled(*host)
143 && build
144 .config
145 .target_config
146 .get(host)
147 .map(|config| config.llvm_config.is_none())
148 .unwrap_or(true)
149 });
150
151 let need_cmake = building_llvm || build.config.any_sanitizers_to_build();
152 if need_cmake && cmd_finder.maybe_have("cmake").is_none() {
153 eprintln!(
154 "
155Couldn't find required command: cmake
156
157You should install cmake, or set `download-ci-llvm = true` in the
158`[llvm]` section of `bootstrap.toml` to download LLVM rather
159than building it.
160"
161 );
162 crate::exit!(1);
163 }
164
165 build.config.python = build
166 .config
167 .python
168 .take()
169 .map(|p| cmd_finder.must_have(p))
170 .or_else(|| env::var_os("BOOTSTRAP_PYTHON").map(PathBuf::from)) .or_else(|| cmd_finder.maybe_have("python"))
172 .or_else(|| cmd_finder.maybe_have("python3"))
173 .or_else(|| cmd_finder.maybe_have("python2"));
174
175 build.config.nodejs = build
176 .config
177 .nodejs
178 .take()
179 .map(|p| cmd_finder.must_have(p))
180 .or_else(|| cmd_finder.maybe_have("node"))
181 .or_else(|| cmd_finder.maybe_have("nodejs"));
182
183 build.config.yarn = build
184 .config
185 .yarn
186 .take()
187 .map(|p| cmd_finder.must_have(p))
188 .or_else(|| cmd_finder.maybe_have("yarn"));
189
190 build.config.gdb = build
191 .config
192 .gdb
193 .take()
194 .map(|p| cmd_finder.must_have(p))
195 .or_else(|| cmd_finder.maybe_have("gdb"));
196
197 build.config.reuse = build
198 .config
199 .reuse
200 .take()
201 .map(|p| cmd_finder.must_have(p))
202 .or_else(|| cmd_finder.maybe_have("reuse"));
203
204 let stage0_supported_target_list: HashSet<String> = command(&build.config.initial_rustc)
205 .args(["--print", "target-list"])
206 .run_in_dry_run()
207 .run_capture_stdout(&build)
208 .stdout()
209 .lines()
210 .map(|s| s.to_string())
211 .collect();
212
213 let skip_tools_checks = build.config.dry_run()
218 || matches!(
219 build.config.cmd,
220 Subcommand::Clean { .. }
221 | Subcommand::Check { .. }
222 | Subcommand::Format { .. }
223 | Subcommand::Setup { .. }
224 );
225
226 for target in &build.targets {
229 if target.contains("emscripten") {
233 continue;
234 }
235
236 if target.contains("wasm32") {
238 continue;
239 }
240
241 if target.contains("motor") {
242 continue;
243 }
244
245 if skip_target_sanity && target != &build.host_target {
247 continue;
248 }
249
250 if cfg!(not(test)) && !skip_target_sanity && !build.local_rebuild {
252 let mut has_target = false;
253 let target_str = target.to_string();
254
255 let missing_targets_hashset: HashSet<_> =
256 STAGE0_MISSING_TARGETS.iter().map(|t| t.to_string()).collect();
257 let duplicated_targets: Vec<_> =
258 stage0_supported_target_list.intersection(&missing_targets_hashset).collect();
259
260 if !duplicated_targets.is_empty() {
261 println!(
262 "Following targets supported from the stage0 compiler, please remove them from STAGE0_MISSING_TARGETS list."
263 );
264 for duplicated_target in duplicated_targets {
265 println!(" {duplicated_target}");
266 }
267 std::process::exit(1);
268 }
269
270 has_target |= stage0_supported_target_list.contains(&target_str);
272 has_target |= STAGE0_MISSING_TARGETS.contains(&target_str.as_str());
273
274 if !has_target {
275 if target.filepath().is_some_and(|p| p.exists()) {
277 has_target = true;
278 } else if let Some(custom_target_path) = env::var_os("RUST_TARGET_PATH") {
279 let mut target_filename = OsString::from(&target_str);
280 target_filename.push(".json");
282
283 let walker = walkdir::WalkDir::new(custom_target_path).into_iter();
285 for entry in walker.filter_map(|e| e.ok()) {
286 has_target |= entry.file_name() == target_filename;
287 }
288 }
289 }
290
291 if !has_target {
292 panic!(
293 "{target_str}: No such target exists in the target list,\n\
294 make sure to correctly specify the location \
295 of the JSON specification file \
296 for custom targets!\n\
297 Use BOOTSTRAP_SKIP_TARGET_SANITY=1 to \
298 bypass this check."
299 );
300 }
301 }
302
303 if !skip_tools_checks {
304 cmd_finder.must_have(build.cc(*target));
305 if let Some(ar) = build.ar(*target) {
306 cmd_finder.must_have(ar);
307 }
308 }
309 }
310
311 if !skip_tools_checks {
312 for host in &build.hosts {
313 cmd_finder.must_have(build.cxx(*host).unwrap());
314
315 if build.config.llvm_enabled(*host) {
316 let filecheck = build.llvm_filecheck(build.host_target);
318 if !filecheck.starts_with(&build.out)
319 && !filecheck.exists()
320 && build.config.codegen_tests
321 {
322 panic!("FileCheck executable {filecheck:?} does not exist");
323 }
324 }
325 }
326 }
327
328 for target in &build.targets {
329 build
330 .config
331 .target_config
332 .entry(*target)
333 .or_insert_with(|| Target::from_triple(&target.triple));
334
335 if target.contains("wasm")
337 && (*build.config.optimized_compiler_builtins(*target)
338 != CompilerBuiltins::BuildRustOnly
339 || build.config.rust_std_features.contains("compiler-builtins-c"))
340 {
341 let cc_tool = build.cc_tool(*target);
342 if !cc_tool.is_like_clang() && !cc_tool.path().ends_with("emcc") {
343 panic!(
345 "Clang is required to build C code for Wasm targets, got `{}` instead\n\
346 this is because compiler-builtins is configured to build C source. Either \
347 ensure Clang is used, or adjust this configuration.",
348 cc_tool.path().display()
349 );
350 }
351 }
352
353 if (target.contains("-none-") || target.contains("nvptx"))
354 && build.no_std(*target) == Some(false)
355 {
356 panic!("All the *-none-* and nvptx* targets are no-std targets")
357 }
358
359 if skip_target_sanity && target != &build.host_target {
361 continue;
362 }
363
364 if target.contains("musl") && !target.contains("unikraft") {
366 match build.musl_libdir(*target) {
367 Some(libdir) => {
368 if fs::metadata(libdir.join("libc.a")).is_err() {
369 panic!("couldn't find libc.a in musl libdir: {}", libdir.display());
370 }
371 }
372 None => panic!(
373 "when targeting MUSL either the rust.musl-root \
374 option or the target.$TARGET.musl-root option must \
375 be specified in bootstrap.toml"
376 ),
377 }
378 }
379
380 if need_cmake && target.is_msvc() {
381 let out =
385 command("cmake").arg("--help").run_in_dry_run().run_capture_stdout(&build).stdout();
386 if !out.contains("Visual Studio") {
387 panic!(
388 "
389cmake does not support Visual Studio generators.
390
391This is likely due to it being an msys/cygwin build of cmake,
392rather than the required windows version, built using MinGW
393or Visual Studio.
394
395If you are building under msys2 try installing the mingw-w64-x86_64-cmake
396package instead of cmake:
397
398$ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
399"
400 );
401 }
402 }
403
404 if target.contains("wasip")
408 && !target.contains("wasip1")
409 && !build.tool_enabled("wasm-component-ld")
410 {
411 cmd_finder.must_have("wasm-component-ld");
412 }
413
414 if !skip_tools_checks && target.is_pauthtest() {
416 let cc_tool = build.cc_tool(*target);
417 let linker_path = build
418 .linker(*target)
419 .unwrap_or_else(|| panic!("{} requires an explicit clang linker", target.triple));
420
421 if !cc_tool.is_like_clang() {
422 panic!(
423 "Clang is required to build C code for {} target, got:\n\
424 cc tool: `{}`,\n\
425 linker: `{}`\n",
426 target.triple,
427 cc_tool.path().display(),
428 linker_path.display(),
429 );
430 }
431 let cc_canon = t!(fs::canonicalize(cc_tool.path()));
432 let linker_canon = t!(fs::canonicalize(&linker_path));
433 if cc_canon != linker_canon {
434 panic!(
435 "CC and Linker are expected to be the same for {} target, got:\n\
436 CC: `{}`,\n\
437 Linker: `{}`\n",
438 target.triple,
439 cc_canon.display(),
440 linker_canon.display(),
441 );
442 }
443
444 let output =
445 command(cc_tool.path()).arg("-dumpversion").run_capture_stdout(&build).stdout();
446 let version_str = output.trim();
447 let mut parts = version_str.split('.').map(|s| s.parse::<u32>().unwrap_or(0));
448 let major = parts.next().unwrap_or(0);
449 let minor = parts.next().unwrap_or(0);
450 let patch = parts.next().unwrap_or(0);
451 if (major, minor, patch) < (22, 1, 0) {
452 panic!(
453 "clang version too old: {} ({} target trequires >= 22.1.0), path: {}",
454 target.triple,
455 version_str,
456 cc_tool.path().display()
457 );
458 }
459 }
460 }
461
462 if let Some(ref s) = build.config.ccache {
463 cmd_finder.must_have(s);
464 }
465}