bootstrap/core/
sanity.rs

1//! Sanity checking performed by bootstrap before actually executing anything.
2//!
3//! This module contains the implementation of ensuring that the build
4//! environment looks reasonable before progressing. This will verify that
5//! various programs like git and python exist, along with ensuring that all C
6//! compilers for cross-compiling are found.
7//!
8//! In theory if we get past this phase it's a bug if a build fails, but in
9//! practice that's likely not true!
10
11use std::collections::{HashMap, HashSet};
12use std::ffi::{OsStr, OsString};
13use std::path::PathBuf;
14use std::{env, fs};
15
16#[cfg(not(test))]
17use crate::builder::Builder;
18use crate::builder::Kind;
19#[cfg(not(test))]
20use crate::core::build_steps::tool;
21use crate::core::config::Target;
22use crate::utils::exec::command;
23use crate::{Build, Subcommand};
24
25pub struct Finder {
26    cache: HashMap<OsString, Option<PathBuf>>,
27    path: OsString,
28}
29
30// During sanity checks, we search for target names to determine if they exist in the compiler's built-in
31// target list (`rustc --print target-list`). While a target name may be present in the stage2 compiler,
32// it might not yet be included in stage0. In such cases, we handle the targets missing from stage0 in this list.
33//
34// Targets can be removed from this list once they are present in the stage0 compiler (usually by updating the beta compiler of the bootstrap).
35const STAGE0_MISSING_TARGETS: &[&str] = &[
36    "armv7a-vex-v5",
37    // just a dummy comment so the list doesn't get onelined
38    "aarch64_be-unknown-hermit",
39    "aarch64_be-unknown-none-softfloat",
40];
41
42/// Minimum version threshold for libstdc++ required when using prebuilt LLVM
43/// from CI (with`llvm.download-ci-llvm` option).
44#[cfg(not(test))]
45const LIBSTDCXX_MIN_VERSION_THRESHOLD: usize = 8;
46
47impl Finder {
48    pub fn new() -> Self {
49        Self { cache: HashMap::new(), path: env::var_os("PATH").unwrap_or_default() }
50    }
51
52    pub fn maybe_have<S: Into<OsString>>(&mut self, cmd: S) -> Option<PathBuf> {
53        let cmd: OsString = cmd.into();
54        let path = &self.path;
55        self.cache
56            .entry(cmd.clone())
57            .or_insert_with(|| {
58                for path in env::split_paths(path) {
59                    let target = path.join(&cmd);
60                    let mut cmd_exe = cmd.clone();
61                    cmd_exe.push(".exe");
62
63                    if target.is_file()                   // some/path/git
64                    || path.join(&cmd_exe).exists()   // some/path/git.exe
65                    || target.join(&cmd_exe).exists()
66                    // some/path/git/git.exe
67                    {
68                        return Some(target);
69                    }
70                }
71                None
72            })
73            .clone()
74    }
75
76    pub fn must_have<S: AsRef<OsStr>>(&mut self, cmd: S) -> PathBuf {
77        self.maybe_have(&cmd).unwrap_or_else(|| {
78            panic!("\n\ncouldn't find required command: {:?}\n\n", cmd.as_ref());
79        })
80    }
81}
82
83pub fn check(build: &mut Build) {
84    let mut skip_target_sanity =
85        env::var_os("BOOTSTRAP_SKIP_TARGET_SANITY").is_some_and(|s| s == "1" || s == "true");
86
87    skip_target_sanity |= build.config.cmd.kind() == Kind::Check;
88
89    // Skip target sanity checks when we are doing anything with mir-opt tests or Miri
90    let skipped_paths = [OsStr::new("mir-opt"), OsStr::new("miri")];
91    skip_target_sanity |= build.config.paths.iter().any(|path| {
92        path.components().any(|component| skipped_paths.contains(&component.as_os_str()))
93    });
94
95    let path = env::var_os("PATH").unwrap_or_default();
96    // On Windows, quotes are invalid characters for filename paths, and if
97    // one is present as part of the PATH then that can lead to the system
98    // being unable to identify the files properly. See
99    // https://github.com/rust-lang/rust/issues/34959 for more details.
100    if cfg!(windows) && path.to_string_lossy().contains('\"') {
101        panic!("PATH contains invalid character '\"'");
102    }
103
104    let mut cmd_finder = Finder::new();
105    // If we've got a git directory we're gonna need git to update
106    // submodules and learn about various other aspects.
107    if build.rust_info().is_managed_git_subrepository() {
108        cmd_finder.must_have("git");
109    }
110
111    // Ensure that a compatible version of libstdc++ is available on the system when using `llvm.download-ci-llvm`.
112    #[cfg(not(test))]
113    if !build.config.dry_run() && !build.host_target.is_msvc() && build.config.llvm_from_ci {
114        let builder = Builder::new(build);
115        let libcxx_version = builder.ensure(tool::LibcxxVersionTool { target: build.host_target });
116
117        match libcxx_version {
118            tool::LibcxxVersion::Gnu(version) => {
119                if LIBSTDCXX_MIN_VERSION_THRESHOLD > version {
120                    eprintln!(
121                        "\nYour system's libstdc++ version is too old for the `llvm.download-ci-llvm` option."
122                    );
123                    eprintln!("Current version detected: '{version}'");
124                    eprintln!("Minimum required version: '{LIBSTDCXX_MIN_VERSION_THRESHOLD}'");
125                    eprintln!(
126                        "Consider upgrading libstdc++ or disabling the `llvm.download-ci-llvm` option."
127                    );
128                    eprintln!(
129                        "If you choose to upgrade libstdc++, run `x clean` or delete `build/host/libcxx-version` manually after the upgrade."
130                    );
131                }
132            }
133            tool::LibcxxVersion::Llvm(_) => {
134                // FIXME: Handle libc++ version check.
135            }
136        }
137    }
138
139    // We need cmake, but only if we're actually building LLVM or sanitizers.
140    let building_llvm = !build.config.llvm_from_ci
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)) // set by bootstrap.py
171        .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.npm = build
184        .config
185        .npm
186        .take()
187        .map(|p| cmd_finder.must_have(p))
188        .or_else(|| cmd_finder.maybe_have("npm"));
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    // Compiler tools like `cc` and `ar` are not configured for cross-targets on certain subcommands
214    // because they are not needed.
215    //
216    // See `cc_detect::find` for more details.
217    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    // We're gonna build some custom C code here and there, host triples
227    // also build some C++ shims for LLVM so we need a C++ compiler.
228    for target in &build.targets {
229        // On emscripten we don't actually need the C compiler to just
230        // build the target artifacts, only for testing. For the sake
231        // of easier bot configuration, just skip detection.
232        if target.contains("emscripten") {
233            continue;
234        }
235
236        // We don't use a C compiler on wasm32
237        if target.contains("wasm32") {
238            continue;
239        }
240
241        // skip check for cross-targets
242        if skip_target_sanity && target != &build.host_target {
243            continue;
244        }
245
246        // Ignore fake targets that are only used for unit tests in bootstrap.
247        if cfg!(not(test)) && !skip_target_sanity && !build.local_rebuild {
248            let mut has_target = false;
249            let target_str = target.to_string();
250
251            let missing_targets_hashset: HashSet<_> =
252                STAGE0_MISSING_TARGETS.iter().map(|t| t.to_string()).collect();
253            let duplicated_targets: Vec<_> =
254                stage0_supported_target_list.intersection(&missing_targets_hashset).collect();
255
256            if !duplicated_targets.is_empty() {
257                println!(
258                    "Following targets supported from the stage0 compiler, please remove them from STAGE0_MISSING_TARGETS list."
259                );
260                for duplicated_target in duplicated_targets {
261                    println!("  {duplicated_target}");
262                }
263                std::process::exit(1);
264            }
265
266            // Check if it's a built-in target.
267            has_target |= stage0_supported_target_list.contains(&target_str);
268            has_target |= STAGE0_MISSING_TARGETS.contains(&target_str.as_str());
269
270            if !has_target {
271                // This might also be a custom target, so check the target file that could have been specified by the user.
272                if target.filepath().is_some_and(|p| p.exists()) {
273                    has_target = true;
274                } else if let Some(custom_target_path) = env::var_os("RUST_TARGET_PATH") {
275                    let mut target_filename = OsString::from(&target_str);
276                    // Target filename ends with `.json`.
277                    target_filename.push(".json");
278
279                    // Recursively traverse through nested directories.
280                    let walker = walkdir::WalkDir::new(custom_target_path).into_iter();
281                    for entry in walker.filter_map(|e| e.ok()) {
282                        has_target |= entry.file_name() == target_filename;
283                    }
284                }
285            }
286
287            if !has_target {
288                panic!(
289                    "No such target exists in the target list,\n\
290                     make sure to correctly specify the location \
291                     of the JSON specification file \
292                     for custom targets!\n\
293                     Use BOOTSTRAP_SKIP_TARGET_SANITY=1 to \
294                     bypass this check."
295                );
296            }
297        }
298
299        if !skip_tools_checks {
300            cmd_finder.must_have(build.cc(*target));
301            if let Some(ar) = build.ar(*target) {
302                cmd_finder.must_have(ar);
303            }
304        }
305    }
306
307    if !skip_tools_checks {
308        for host in &build.hosts {
309            cmd_finder.must_have(build.cxx(*host).unwrap());
310
311            if build.config.llvm_enabled(*host) {
312                // Externally configured LLVM requires FileCheck to exist
313                let filecheck = build.llvm_filecheck(build.host_target);
314                if !filecheck.starts_with(&build.out)
315                    && !filecheck.exists()
316                    && build.config.codegen_tests
317                {
318                    panic!("FileCheck executable {filecheck:?} does not exist");
319                }
320            }
321        }
322    }
323
324    for target in &build.targets {
325        build
326            .config
327            .target_config
328            .entry(*target)
329            .or_insert_with(|| Target::from_triple(&target.triple));
330
331        // compiler-rt c fallbacks for wasm cannot be built with gcc
332        if target.contains("wasm")
333            && (build.config.optimized_compiler_builtins(*target)
334                || build.config.rust_std_features.contains("compiler-builtins-c"))
335        {
336            let cc_tool = build.cc_tool(*target);
337            if !cc_tool.is_like_clang() && !cc_tool.path().ends_with("emcc") {
338                // emcc works as well
339                panic!(
340                    "Clang is required to build C code for Wasm targets, got `{}` instead\n\
341                    this is because compiler-builtins is configured to build C source. Either \
342                    ensure Clang is used, or adjust this configuration.",
343                    cc_tool.path().display()
344                );
345            }
346        }
347
348        if (target.contains("-none-") || target.contains("nvptx"))
349            && build.no_std(*target) == Some(false)
350        {
351            panic!("All the *-none-* and nvptx* targets are no-std targets")
352        }
353
354        // skip check for cross-targets
355        if skip_target_sanity && target != &build.host_target {
356            continue;
357        }
358
359        // Make sure musl-root is valid.
360        if target.contains("musl") && !target.contains("unikraft") {
361            match build.musl_libdir(*target) {
362                Some(libdir) => {
363                    if fs::metadata(libdir.join("libc.a")).is_err() {
364                        panic!("couldn't find libc.a in musl libdir: {}", libdir.display());
365                    }
366                }
367                None => panic!(
368                    "when targeting MUSL either the rust.musl-root \
369                            option or the target.$TARGET.musl-root option must \
370                            be specified in bootstrap.toml"
371                ),
372            }
373        }
374
375        if need_cmake && target.is_msvc() {
376            // There are three builds of cmake on windows: MSVC, MinGW, and
377            // Cygwin. The Cygwin build does not have generators for Visual
378            // Studio, so detect that here and error.
379            let out =
380                command("cmake").arg("--help").run_in_dry_run().run_capture_stdout(&build).stdout();
381            if !out.contains("Visual Studio") {
382                panic!(
383                    "
384cmake does not support Visual Studio generators.
385
386This is likely due to it being an msys/cygwin build of cmake,
387rather than the required windows version, built using MinGW
388or Visual Studio.
389
390If you are building under msys2 try installing the mingw-w64-x86_64-cmake
391package instead of cmake:
392
393$ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
394"
395                );
396            }
397        }
398    }
399
400    if let Some(ref s) = build.config.ccache {
401        cmd_finder.must_have(s);
402    }
403}