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