Skip to main content

bootstrap/core/
sanity.rs

1//! Sanity checking and tool selection performed by bootstrap.
2//!
3//! This module ensures that the build environment is correctly set up before
4//! executing any build tasks. It verifies required programs exist (like git and
5//! cmake when needed), selects some tools based on the environment (like the
6//! Python interpreter), and validates that C compilers for cross-compiling are
7//! available.
8//!
9//! In theory if we get past this phase it's a bug if a build fails, but in
10//! practice that's likely not true!
11
12use 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::flags::Subcommand;
21use crate::core::config::{CompilerBuiltins, DebuggerPath, Target};
22use crate::utils::exec::command;
23use crate::utils::helpers::{self, t};
24
25pub struct Finder {
26    cache: HashMap<OsString, Option<PathBuf>>,
27    path: OsString,
28}
29
30/// During sanity checks, we search for target tuples to determine if they exist in the compiler's
31/// built-in target list (`rustc --print target-list`). While a target tuple may be present in the
32/// in-tree compiler, the stage 0 compiler might not yet know about it (assuming not operating with
33/// local-rebuild). In such cases, we handle the targets missing from stage 0 in this list.
34///
35/// Targets can be removed from this list during the usual release process bootstrap compiler bumps,
36/// when the newly-bumped stage 0 compiler now knows about the formerly-missing targets.
37const STAGE0_MISSING_TARGETS: &[&str] = &[
38    // just a dummy comment so the list doesn't get onelined
39    "aarch64-unknown-l4re-uclibc",
40];
41
42/// Minimum version threshold for libstdc++ required when using prebuilt LLVM
43/// from CI (with`llvm.download-ci-llvm` option).
44const LIBSTDCXX_MIN_VERSION_THRESHOLD: usize = 8;
45
46impl Finder {
47    pub fn new() -> Self {
48        Self { cache: HashMap::new(), path: env::var_os("PATH").unwrap_or_default() }
49    }
50
51    pub fn maybe_have<S: Into<OsString>>(&mut self, cmd: S) -> Option<PathBuf> {
52        let cmd: OsString = cmd.into();
53        let path = &self.path;
54        self.cache
55            .entry(cmd.clone())
56            .or_insert_with(|| {
57                for path in env::split_paths(path) {
58                    let target = path.join(&cmd);
59                    let mut cmd_exe = cmd.clone();
60                    cmd_exe.push(".exe");
61
62                    if target.is_file()                   // some/path/git
63                    || path.join(&cmd_exe).exists()   // some/path/git.exe
64                    || target.join(&cmd_exe).exists()
65                    // some/path/git/git.exe
66                    {
67                        return Some(target);
68                    }
69                }
70                None
71            })
72            .clone()
73    }
74
75    pub fn must_have<S: AsRef<OsStr>>(&mut self, cmd: S) -> PathBuf {
76        self.maybe_have(&cmd).unwrap_or_else(|| {
77            panic!("\n\ncouldn't find required command: {:?}\n\n", cmd.as_ref());
78        })
79    }
80}
81
82pub fn check(build: &mut Build) {
83    let mut skip_target_sanity =
84        env::var_os("BOOTSTRAP_SKIP_TARGET_SANITY").is_some_and(|s| s == "1" || s == "true");
85
86    skip_target_sanity |= matches!(build.config.cmd, Subcommand::Check { .. });
87
88    // Skip target sanity checks when we are doing anything with mir-opt tests or Miri
89    let skipped_paths = [OsStr::new("mir-opt"), OsStr::new("miri")];
90    skip_target_sanity |= build.config.paths.iter().any(|path| {
91        path.components().any(|component| skipped_paths.contains(&component.as_os_str()))
92    });
93
94    let path = env::var_os("PATH").unwrap_or_default();
95    // On Windows, quotes are invalid characters for filename paths, and if
96    // one is present as part of the PATH then that can lead to the system
97    // being unable to identify the files properly. See
98    // https://github.com/rust-lang/rust/issues/34959 for more details.
99    if cfg!(windows) && path.to_string_lossy().contains('\"') {
100        panic!("PATH contains invalid character '\"'");
101    }
102
103    let mut cmd_finder = Finder::new();
104    // If we've got a git directory we're gonna need git to update
105    // submodules and learn about various other aspects.
106    if build.rust_info().is_managed_git_subrepository() {
107        cmd_finder.must_have("git");
108    }
109
110    // Ensure that a compatible version of libstdc++ is available on the system when using `llvm.download-ci-llvm`.
111    if cfg!(not(test))
112        && !build.config.dry_run()
113        && !build.host_target.is_msvc()
114        && build.config.llvm_ci_mode.download_from_ci()
115    {
116        let builder = Builder::new(build);
117        let libcxx_version = builder.ensure(tool::LibcxxVersionTool { target: build.host_target });
118
119        match libcxx_version {
120            tool::LibcxxVersion::Gnu(version) => {
121                if LIBSTDCXX_MIN_VERSION_THRESHOLD > version {
122                    eprintln!(
123                        "\nYour system's libstdc++ version is too old for the `llvm.download-ci-llvm` option."
124                    );
125                    eprintln!("Current version detected: '{version}'");
126                    eprintln!("Minimum required version: '{LIBSTDCXX_MIN_VERSION_THRESHOLD}'");
127                    eprintln!(
128                        "Consider upgrading libstdc++ or disabling the `llvm.download-ci-llvm` option."
129                    );
130                    eprintln!(
131                        "If you choose to upgrade libstdc++, run `x clean` or delete `build/host/libcxx-version` manually after the upgrade."
132                    );
133                }
134            }
135            tool::LibcxxVersion::Llvm(_) => {
136                // FIXME: Handle libc++ version check.
137            }
138        }
139    }
140
141    // We need cmake, but only if we're actually building LLVM or sanitizers.
142    let building_llvm = !build.config.llvm_ci_mode.download_from_ci()
143        && !build.config.local_rebuild
144        && build.hosts.iter().any(|host| {
145            build.config.llvm_enabled(*host)
146                && build
147                    .config
148                    .target_config
149                    .get(host)
150                    .map(|config| config.llvm_config.is_none())
151                    .unwrap_or(true)
152        });
153
154    let need_cmake = building_llvm || build.config.any_sanitizers_to_build();
155    if need_cmake && cmd_finder.maybe_have("cmake").is_none() {
156        eprintln!(
157            "
158Couldn't find required command: cmake
159
160You should install cmake, or set `download-ci-llvm = true` in the
161`[llvm]` section of `bootstrap.toml` to download LLVM rather
162than building it.
163"
164        );
165        helpers::exit_process(1);
166    }
167
168    build.config.python = build
169        .config
170        .python
171        .take()
172        .map(|p| cmd_finder.must_have(p))
173        .or_else(|| env::var_os("BOOTSTRAP_PYTHON").map(PathBuf::from)) // set by bootstrap.py
174        .or_else(|| cmd_finder.maybe_have("python"))
175        .or_else(|| cmd_finder.maybe_have("python3"))
176        .or_else(|| cmd_finder.maybe_have("python2"));
177
178    build.config.nodejs = build
179        .config
180        .nodejs
181        .take()
182        .map(|p| cmd_finder.must_have(p))
183        .or_else(|| cmd_finder.maybe_have("node"))
184        .or_else(|| cmd_finder.maybe_have("nodejs"));
185
186    build.config.yarn = build
187        .config
188        .yarn
189        .take()
190        .map(|p| cmd_finder.must_have(p))
191        .or_else(|| cmd_finder.maybe_have("yarn"));
192
193    build.config.gdb = build.config.gdb.take().map(|p| match p {
194        DebuggerPath::Discover => DebuggerPath::Discover,
195        DebuggerPath::Path(path) => DebuggerPath::Path(cmd_finder.must_have(path)),
196    });
197
198    build.config.reuse = build
199        .config
200        .reuse
201        .take()
202        .map(|p| cmd_finder.must_have(p))
203        .or_else(|| cmd_finder.maybe_have("reuse"));
204
205    let stage0_supported_target_list: HashSet<String> = command(&build.config.initial_rustc)
206        .args(["--print", "target-list"])
207        .run_in_dry_run()
208        .run_capture_stdout(&build)
209        .stdout()
210        .lines()
211        .map(|s| s.to_string())
212        .collect();
213
214    // Compiler tools like `cc` and `ar` are not configured for cross-targets on certain subcommands
215    // because they are not needed.
216    //
217    // See `cc_detect::find` for more details.
218    let skip_tools_checks = build.config.dry_run()
219        || matches!(
220            build.config.cmd,
221            Subcommand::Clean { .. }
222                | Subcommand::Check { .. }
223                | Subcommand::Format { .. }
224                | Subcommand::Setup { .. }
225        );
226
227    // We're gonna build some custom C code here and there, host triples
228    // also build some C++ shims for LLVM so we need a C++ compiler.
229    for target in &build.targets {
230        // On emscripten we don't actually need the C compiler to just
231        // build the target artifacts, only for testing. For the sake
232        // of easier bot configuration, just skip detection.
233        if target.contains("emscripten") {
234            continue;
235        }
236
237        // We don't use a C compiler on wasm32
238        if target.contains("wasm32") {
239            continue;
240        }
241
242        if target.contains("motor") {
243            continue;
244        }
245
246        // skip check for cross-targets
247        if skip_target_sanity && target != &build.host_target {
248            continue;
249        }
250
251        // Ignore fake targets that are only used for unit tests in bootstrap.
252        if cfg!(not(test)) && !skip_target_sanity && !build.local_rebuild {
253            let mut has_target = false;
254            let target_str = target.to_string();
255
256            let missing_targets_hashset: HashSet<_> =
257                STAGE0_MISSING_TARGETS.iter().map(|t| t.to_string()).collect();
258            let duplicated_targets: Vec<_> =
259                stage0_supported_target_list.intersection(&missing_targets_hashset).collect();
260
261            if !duplicated_targets.is_empty() {
262                println!(
263                    "Following targets supported from the stage0 compiler, please remove them from STAGE0_MISSING_TARGETS list."
264                );
265                for duplicated_target in duplicated_targets {
266                    println!("  {duplicated_target}");
267                }
268                std::process::exit(1);
269            }
270
271            // Check if it's a built-in target.
272            has_target |= stage0_supported_target_list.contains(&target_str);
273            has_target |= STAGE0_MISSING_TARGETS.contains(&target_str.as_str());
274
275            if !has_target {
276                // This might also be a custom target, so check the target file that could have been specified by the user.
277                if target.filepath().is_some_and(|p| p.exists()) {
278                    has_target = true;
279                } else if let Some(custom_target_path) = env::var_os("RUST_TARGET_PATH") {
280                    let mut target_filename = OsString::from(&target_str);
281                    // Target filename ends with `.json`.
282                    target_filename.push(".json");
283
284                    // Recursively traverse through nested directories.
285                    let walker = walkdir::WalkDir::new(custom_target_path).into_iter();
286                    for entry in walker.filter_map(|e| e.ok()) {
287                        has_target |= entry.file_name() == target_filename;
288                    }
289                }
290            }
291
292            if !has_target {
293                panic!(
294                    "{target_str}: No such target exists in the target list,\n\
295                     make sure to correctly specify the location \
296                     of the JSON specification file \
297                     for custom targets!\n\
298                     Use BOOTSTRAP_SKIP_TARGET_SANITY=1 to \
299                     bypass this check."
300                );
301            }
302        }
303
304        if !skip_tools_checks {
305            cmd_finder.must_have(build.cc(*target));
306            if let Some(ar) = build.ar(*target) {
307                cmd_finder.must_have(ar);
308            }
309        }
310    }
311
312    if !skip_tools_checks {
313        for host in &build.hosts {
314            cmd_finder.must_have(build.cxx(*host).unwrap());
315        }
316    }
317
318    for target in &build.targets {
319        build
320            .config
321            .target_config
322            .entry(*target)
323            .or_insert_with(|| Target::from_triple(&target.triple));
324
325        // compiler-rt c fallbacks for wasm cannot be built with gcc
326        if target.contains("wasm")
327            && (*build.config.optimized_compiler_builtins(*target)
328                != CompilerBuiltins::BuildRustOnly
329                || build.config.rust_std_features.contains("compiler-builtins-c"))
330        {
331            let cc_tool = build.cc_tool(*target);
332            if !cc_tool.is_like_clang() && !cc_tool.path().ends_with("emcc") {
333                // emcc works as well
334                panic!(
335                    "Clang is required to build C code for Wasm targets, got `{}` instead\n\
336                    this is because compiler-builtins is configured to build C source. Either \
337                    ensure Clang is used, or adjust this configuration.",
338                    cc_tool.path().display()
339                );
340            }
341        }
342
343        if (target.contains("-none-") || target.contains("nvptx"))
344            && build.no_std(*target) == Some(false)
345        {
346            panic!("All the *-none-* and nvptx* targets are no-std targets")
347        }
348
349        // skip check for cross-targets
350        if skip_target_sanity && target != &build.host_target {
351            continue;
352        }
353
354        // Make sure musl-root is valid.
355        if target.contains("musl") && !target.contains("unikraft") {
356            match build.musl_libdir(*target) {
357                Some(libdir) => {
358                    if fs::metadata(libdir.join("libc.a")).is_err() {
359                        panic!("couldn't find libc.a in musl libdir: {}", libdir.display());
360                    }
361                }
362                None => panic!(
363                    "when targeting MUSL either the rust.musl-root \
364                            option or the target.$TARGET.musl-root option must \
365                            be specified in bootstrap.toml"
366                ),
367            }
368        }
369
370        if need_cmake && target.is_msvc() {
371            // There are three builds of cmake on windows: MSVC, MinGW, and
372            // Cygwin. The Cygwin build does not have generators for Visual
373            // Studio, so detect that here and error.
374            let out =
375                command("cmake").arg("--help").run_in_dry_run().run_capture_stdout(&build).stdout();
376            if !out.contains("Visual Studio") {
377                panic!(
378                    "
379cmake does not support Visual Studio generators.
380
381This is likely due to it being an msys/cygwin build of cmake,
382rather than the required windows version, built using MinGW
383or Visual Studio.
384
385If you are building under msys2 try installing the mingw-w64-x86_64-cmake
386package instead of cmake:
387
388$ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
389"
390                );
391            }
392        }
393
394        // For testing `wasm32-wasip2`-and-beyond it's required to have
395        // `wasm-component-ld`. This is enabled by default via `tool_enabled`
396        // but if it's disabled then double-check it's present on the system.
397        if target.contains("wasip")
398            && !target.contains("wasip1")
399            && !build.tool_enabled("wasm-component-ld")
400        {
401            cmd_finder.must_have("wasm-component-ld");
402        }
403
404        // aarch64-unknown-linux-pauthtest must use clang
405        if !skip_tools_checks && target.is_pauthtest() {
406            let cc_tool = build.cc_tool(*target);
407            let linker_path = build
408                .linker(*target)
409                .unwrap_or_else(|| panic!("{} requires an explicit clang linker", target.triple));
410
411            if !cc_tool.is_like_clang() {
412                panic!(
413                    "Clang is required to build C code for {} target, got:\n\
414                     cc tool: `{}`,\n\
415                     linker: `{}`\n",
416                    target.triple,
417                    cc_tool.path().display(),
418                    linker_path.display(),
419                );
420            }
421            let cc_canon = t!(fs::canonicalize(cc_tool.path()));
422            let linker_canon = t!(fs::canonicalize(&linker_path));
423            if cc_canon != linker_canon {
424                panic!(
425                    "CC and Linker are expected to be the same for {} target, got:\n\
426                     CC: `{}`,\n\
427                     Linker: `{}`\n",
428                    target.triple,
429                    cc_canon.display(),
430                    linker_canon.display(),
431                );
432            }
433
434            let output =
435                command(cc_tool.path()).arg("-dumpversion").run_capture_stdout(&build).stdout();
436            let version_str = output.trim();
437            let mut parts = version_str.split('.').map(|s| s.parse::<u32>().unwrap_or(0));
438            let major = parts.next().unwrap_or(0);
439            let minor = parts.next().unwrap_or(0);
440            let patch = parts.next().unwrap_or(0);
441            if (major, minor, patch) < (22, 1, 0) {
442                panic!(
443                    "clang version too old: {} ({} target trequires >= 22.1.0), path: {}",
444                    target.triple,
445                    version_str,
446                    cc_tool.path().display()
447                );
448            }
449        }
450    }
451
452    if let Some(ref s) = build.config.ccache {
453        cmd_finder.must_have(s);
454    }
455}