1use std::collections::{HashMap, HashSet};
13use std::ffi::{OsStr, OsString};
14use std::path::PathBuf;
15use std::{env, fs};
16
17use crate::Build;
18use crate::core::build_steps::tool;
19use crate::core::builder::Builder;
20use crate::core::config::{CompilerBuiltins, DebuggerPath, Subcommand, Target};
21use crate::utils::exec::command;
22use crate::utils::helpers::t;
23
24pub struct Finder {
25 cache: HashMap<OsString, Option<PathBuf>>,
26 path: OsString,
27}
28
29const STAGE0_MISSING_TARGETS: &[&str] = &[
37 "aarch64-unknown-l4re-uclibc",
39];
40
41const LIBSTDCXX_MIN_VERSION_THRESHOLD: usize = 8;
44
45impl Finder {
46 pub fn new() -> Self {
47 Self { cache: HashMap::new(), path: env::var_os("PATH").unwrap_or_default() }
48 }
49
50 pub fn maybe_have<S: Into<OsString>>(&mut self, cmd: S) -> Option<PathBuf> {
51 let cmd: OsString = cmd.into();
52 let path = &self.path;
53 self.cache
54 .entry(cmd.clone())
55 .or_insert_with(|| {
56 for path in env::split_paths(path) {
57 let target = path.join(&cmd);
58 let mut cmd_exe = cmd.clone();
59 cmd_exe.push(".exe");
60
61 if target.is_file() || path.join(&cmd_exe).exists() || target.join(&cmd_exe).exists()
64 {
66 return Some(target);
67 }
68 }
69 None
70 })
71 .clone()
72 }
73
74 pub fn must_have<S: AsRef<OsStr>>(&mut self, cmd: S) -> PathBuf {
75 self.maybe_have(&cmd).unwrap_or_else(|| {
76 panic!("\n\ncouldn't find required command: {:?}\n\n", cmd.as_ref());
77 })
78 }
79}
80
81pub fn check(build: &mut Build) {
82 let mut skip_target_sanity =
83 env::var_os("BOOTSTRAP_SKIP_TARGET_SANITY").is_some_and(|s| s == "1" || s == "true");
84
85 skip_target_sanity |= matches!(build.config.cmd, Subcommand::Check { .. });
86
87 let skipped_paths = [OsStr::new("mir-opt"), OsStr::new("miri")];
89 skip_target_sanity |= build.config.paths.iter().any(|path| {
90 path.components().any(|component| skipped_paths.contains(&component.as_os_str()))
91 });
92
93 let path = env::var_os("PATH").unwrap_or_default();
94 if cfg!(windows) && path.to_string_lossy().contains('\"') {
99 panic!("PATH contains invalid character '\"'");
100 }
101
102 let mut cmd_finder = Finder::new();
103 if build.rust_info().is_managed_git_subrepository() {
106 cmd_finder.must_have("git");
107 }
108
109 if cfg!(not(test))
111 && !build.config.dry_run()
112 && !build.host_target.is_msvc()
113 && build.config.llvm_from_ci
114 {
115 let builder = Builder::new(build);
116 let libcxx_version = builder.ensure(tool::LibcxxVersionTool { target: build.host_target });
117
118 match libcxx_version {
119 tool::LibcxxVersion::Gnu(version) => {
120 if LIBSTDCXX_MIN_VERSION_THRESHOLD > version {
121 eprintln!(
122 "\nYour system's libstdc++ version is too old for the `llvm.download-ci-llvm` option."
123 );
124 eprintln!("Current version detected: '{version}'");
125 eprintln!("Minimum required version: '{LIBSTDCXX_MIN_VERSION_THRESHOLD}'");
126 eprintln!(
127 "Consider upgrading libstdc++ or disabling the `llvm.download-ci-llvm` option."
128 );
129 eprintln!(
130 "If you choose to upgrade libstdc++, run `x clean` or delete `build/host/libcxx-version` manually after the upgrade."
131 );
132 }
133 }
134 tool::LibcxxVersion::Llvm(_) => {
135 }
137 }
138 }
139
140 let building_llvm = !build.config.llvm_from_ci
142 && !build.config.local_rebuild
143 && build.hosts.iter().any(|host| {
144 build.config.llvm_enabled(*host)
145 && build
146 .config
147 .target_config
148 .get(host)
149 .map(|config| config.llvm_config.is_none())
150 .unwrap_or(true)
151 });
152
153 let need_cmake = building_llvm || build.config.any_sanitizers_to_build();
154 if need_cmake && cmd_finder.maybe_have("cmake").is_none() {
155 eprintln!(
156 "
157Couldn't find required command: cmake
158
159You should install cmake, or set `download-ci-llvm = true` in the
160`[llvm]` section of `bootstrap.toml` to download LLVM rather
161than building it.
162"
163 );
164 crate::exit!(1);
165 }
166
167 build.config.python = build
168 .config
169 .python
170 .take()
171 .map(|p| cmd_finder.must_have(p))
172 .or_else(|| env::var_os("BOOTSTRAP_PYTHON").map(PathBuf::from)) .or_else(|| cmd_finder.maybe_have("python"))
174 .or_else(|| cmd_finder.maybe_have("python3"))
175 .or_else(|| cmd_finder.maybe_have("python2"));
176
177 build.config.nodejs = build
178 .config
179 .nodejs
180 .take()
181 .map(|p| cmd_finder.must_have(p))
182 .or_else(|| cmd_finder.maybe_have("node"))
183 .or_else(|| cmd_finder.maybe_have("nodejs"));
184
185 build.config.yarn = build
186 .config
187 .yarn
188 .take()
189 .map(|p| cmd_finder.must_have(p))
190 .or_else(|| cmd_finder.maybe_have("yarn"));
191
192 build.config.gdb = build.config.gdb.take().map(|p| match p {
193 DebuggerPath::Discover => DebuggerPath::Discover,
194 DebuggerPath::Path(path) => DebuggerPath::Path(cmd_finder.must_have(path)),
195 });
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 }
316
317 for target in &build.targets {
318 build
319 .config
320 .target_config
321 .entry(*target)
322 .or_insert_with(|| Target::from_triple(&target.triple));
323
324 if target.contains("wasm")
326 && (*build.config.optimized_compiler_builtins(*target)
327 != CompilerBuiltins::BuildRustOnly
328 || build.config.rust_std_features.contains("compiler-builtins-c"))
329 {
330 let cc_tool = build.cc_tool(*target);
331 if !cc_tool.is_like_clang() && !cc_tool.path().ends_with("emcc") {
332 panic!(
334 "Clang is required to build C code for Wasm targets, got `{}` instead\n\
335 this is because compiler-builtins is configured to build C source. Either \
336 ensure Clang is used, or adjust this configuration.",
337 cc_tool.path().display()
338 );
339 }
340 }
341
342 if (target.contains("-none-") || target.contains("nvptx"))
343 && build.no_std(*target) == Some(false)
344 {
345 panic!("All the *-none-* and nvptx* targets are no-std targets")
346 }
347
348 if skip_target_sanity && target != &build.host_target {
350 continue;
351 }
352
353 if target.contains("musl") && !target.contains("unikraft") {
355 match build.musl_libdir(*target) {
356 Some(libdir) => {
357 if fs::metadata(libdir.join("libc.a")).is_err() {
358 panic!("couldn't find libc.a in musl libdir: {}", libdir.display());
359 }
360 }
361 None => panic!(
362 "when targeting MUSL either the rust.musl-root \
363 option or the target.$TARGET.musl-root option must \
364 be specified in bootstrap.toml"
365 ),
366 }
367 }
368
369 if need_cmake && target.is_msvc() {
370 let out =
374 command("cmake").arg("--help").run_in_dry_run().run_capture_stdout(&build).stdout();
375 if !out.contains("Visual Studio") {
376 panic!(
377 "
378cmake does not support Visual Studio generators.
379
380This is likely due to it being an msys/cygwin build of cmake,
381rather than the required windows version, built using MinGW
382or Visual Studio.
383
384If you are building under msys2 try installing the mingw-w64-x86_64-cmake
385package instead of cmake:
386
387$ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
388"
389 );
390 }
391 }
392
393 if target.contains("wasip")
397 && !target.contains("wasip1")
398 && !build.tool_enabled("wasm-component-ld")
399 {
400 cmd_finder.must_have("wasm-component-ld");
401 }
402
403 if !skip_tools_checks && target.is_pauthtest() {
405 let cc_tool = build.cc_tool(*target);
406 let linker_path = build
407 .linker(*target)
408 .unwrap_or_else(|| panic!("{} requires an explicit clang linker", target.triple));
409
410 if !cc_tool.is_like_clang() {
411 panic!(
412 "Clang is required to build C code for {} target, got:\n\
413 cc tool: `{}`,\n\
414 linker: `{}`\n",
415 target.triple,
416 cc_tool.path().display(),
417 linker_path.display(),
418 );
419 }
420 let cc_canon = t!(fs::canonicalize(cc_tool.path()));
421 let linker_canon = t!(fs::canonicalize(&linker_path));
422 if cc_canon != linker_canon {
423 panic!(
424 "CC and Linker are expected to be the same for {} target, got:\n\
425 CC: `{}`,\n\
426 Linker: `{}`\n",
427 target.triple,
428 cc_canon.display(),
429 linker_canon.display(),
430 );
431 }
432
433 let output =
434 command(cc_tool.path()).arg("-dumpversion").run_capture_stdout(&build).stdout();
435 let version_str = output.trim();
436 let mut parts = version_str.split('.').map(|s| s.parse::<u32>().unwrap_or(0));
437 let major = parts.next().unwrap_or(0);
438 let minor = parts.next().unwrap_or(0);
439 let patch = parts.next().unwrap_or(0);
440 if (major, minor, patch) < (22, 1, 0) {
441 panic!(
442 "clang version too old: {} ({} target trequires >= 22.1.0), path: {}",
443 target.triple,
444 version_str,
445 cc_tool.path().display()
446 );
447 }
448 }
449 }
450
451 if let Some(ref s) = build.config.ccache {
452 cmd_finder.must_have(s);
453 }
454}