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::core::build_steps::tool;
18use crate::core::builder::Builder;
19use crate::core::config::flags::Subcommand;
20use crate::core::config::{CompilerBuiltins, DebuggerPath, Target};
21use crate::core::session::Session;
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];
40
41/// Minimum version threshold for libstdc++ required when using prebuilt LLVM
42/// from CI (with`llvm.download-ci-llvm` option).
43const 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()                   // some/path/git
62                    || path.join(&cmd_exe).exists()   // some/path/git.exe
63                    || target.join(&cmd_exe).exists()
64                    // some/path/git/git.exe
65                    {
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(crate) fn check(sess: &mut Session) {
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!(sess.config.cmd, Subcommand::Check { .. });
86
87    // Skip target sanity checks when we are doing anything with mir-opt tests or Miri
88    let skipped_paths = [OsStr::new("mir-opt"), OsStr::new("miri")];
89    skip_target_sanity |= sess.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    // On Windows, quotes are invalid characters for filename paths, and if
95    // one is present as part of the PATH then that can lead to the system
96    // being unable to identify the files properly. See
97    // https://github.com/rust-lang/rust/issues/34959 for more details.
98    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 we've got a git directory we're gonna need git to update
104    // submodules and learn about various other aspects.
105    if sess.rust_info().is_managed_git_subrepository() {
106        cmd_finder.must_have("git");
107    }
108
109    // Ensure that a compatible version of libstdc++ is available on the system when using `llvm.download-ci-llvm`.
110    if cfg!(not(test))
111        && !sess.config.dry_run()
112        && !sess.host_target.is_msvc()
113        && sess.config.llvm_ci_mode.download_from_ci()
114    {
115        let builder = Builder::new(sess);
116        let libcxx_version = builder.ensure(tool::LibcxxVersionTool { target: sess.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                // FIXME: Handle libc++ version check.
136            }
137        }
138    }
139
140    // We need cmake, but only if we're actually building LLVM or sanitizers.
141    let building_llvm = !sess.config.llvm_ci_mode.download_from_ci()
142        && !sess.config.local_rebuild
143        && sess.hosts.iter().any(|host| {
144            sess.config.llvm_enabled(*host)
145                && sess
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 || sess.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        helpers::exit_process(1);
165    }
166
167    sess.config.python = sess
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)) // set by bootstrap.py
173        .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    sess.config.nodejs = sess
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    sess.config.yarn = sess
186        .config
187        .yarn
188        .take()
189        .map(|p| cmd_finder.must_have(p))
190        .or_else(|| cmd_finder.maybe_have("yarn"));
191
192    sess.config.gdb = sess.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    sess.config.reuse = sess
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(&sess.initial_rustc)
205        .args(["--print", "target-list"])
206        .run_in_dry_run()
207        .run_capture_stdout(&sess)
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 = sess.config.dry_run()
218        || matches!(
219            sess.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 &sess.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        if target.contains("motor") {
242            continue;
243        }
244
245        // skip check for cross-targets
246        if skip_target_sanity && target != &sess.host_target {
247            continue;
248        }
249
250        // Ignore fake targets that are only used for unit tests in bootstrap.
251        if cfg!(not(test)) && !skip_target_sanity && !sess.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            // Check if it's a built-in target.
271            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                // This might also be a custom target, so check the target file that could have been specified by the user.
276                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 ends with `.json`.
281                    target_filename.push(".json");
282
283                    // Recursively traverse through nested directories.
284                    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(sess.cc(*target));
305            if let Some(ar) = sess.ar(*target) {
306                cmd_finder.must_have(ar);
307            }
308        }
309    }
310
311    if !skip_tools_checks {
312        for host in &sess.hosts {
313            cmd_finder.must_have(sess.cxx(*host).unwrap());
314        }
315    }
316
317    for target in &sess.config.targets {
318        sess.config
319            .target_config
320            .entry(*target)
321            .or_insert_with(|| Target::from_triple(&target.triple));
322
323        // compiler-rt c fallbacks for wasm cannot be built with gcc
324        if target.contains("wasm")
325            && (*sess.config.optimized_compiler_builtins(*target)
326                != CompilerBuiltins::BuildRustOnly
327                || sess.config.rust_std_features.contains("compiler-builtins-c"))
328        {
329            let cc_tool = sess.cc_tool(*target);
330            if !cc_tool.is_like_clang() && !cc_tool.path().ends_with("emcc") {
331                // emcc works as well
332                panic!(
333                    "Clang is required to build C code for Wasm targets, got `{}` instead\n\
334                    this is because compiler-builtins is configured to build C source. Either \
335                    ensure Clang is used, or adjust this configuration.",
336                    cc_tool.path().display()
337                );
338            }
339        }
340
341        if (target.contains("-none-") || target.contains("nvptx"))
342            && sess.no_std(*target) == Some(false)
343        {
344            panic!("All the *-none-* and nvptx* targets are no-std targets")
345        }
346
347        // skip check for cross-targets
348        if skip_target_sanity && target != &sess.host_target {
349            continue;
350        }
351
352        // Make sure musl-root is valid.
353        if target.contains("musl") && !target.contains("unikraft") {
354            match sess.musl_libdir(*target) {
355                Some(libdir) => {
356                    if fs::metadata(libdir.join("libc.a")).is_err() {
357                        panic!("couldn't find libc.a in musl libdir: {}", libdir.display());
358                    }
359                }
360                None => panic!(
361                    "when targeting MUSL either the rust.musl-root \
362                            option or the target.$TARGET.musl-root option must \
363                            be specified in bootstrap.toml"
364                ),
365            }
366        }
367
368        if need_cmake && target.is_msvc() {
369            // There are three builds of cmake on windows: MSVC, MinGW, and
370            // Cygwin. The Cygwin build does not have generators for Visual
371            // Studio, so detect that here and error.
372            let out =
373                command("cmake").arg("--help").run_in_dry_run().run_capture_stdout(&sess).stdout();
374            if !out.contains("Visual Studio") {
375                panic!(
376                    "
377cmake does not support Visual Studio generators.
378
379This is likely due to it being an msys/cygwin build of cmake,
380rather than the required windows version, built using MinGW
381or Visual Studio.
382
383If you are building under msys2 try installing the mingw-w64-x86_64-cmake
384package instead of cmake:
385
386$ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
387"
388                );
389            }
390        }
391
392        // For testing `wasm32-wasip2`-and-beyond it's required to have
393        // `wasm-component-ld`. This is enabled by default via `tool_enabled`
394        // but if it's disabled then double-check it's present on the system.
395        if target.contains("wasip")
396            && !target.contains("wasip1")
397            && !sess.tool_enabled("wasm-component-ld")
398        {
399            cmd_finder.must_have("wasm-component-ld");
400        }
401
402        // aarch64-unknown-linux-pauthtest must use clang
403        if !skip_tools_checks && target.is_pauthtest() {
404            let cc_tool = sess.cc_tool(*target);
405            let linker_path = sess
406                .linker(*target)
407                .unwrap_or_else(|| panic!("{} requires an explicit clang linker", target.triple));
408
409            if !cc_tool.is_like_clang() {
410                panic!(
411                    "Clang is required to build C code for {} target, got:\n\
412                     cc tool: `{}`,\n\
413                     linker: `{}`\n",
414                    target.triple,
415                    cc_tool.path().display(),
416                    linker_path.display(),
417                );
418            }
419            let cc_canon = t!(fs::canonicalize(cc_tool.path()));
420            let linker_canon = t!(fs::canonicalize(&linker_path));
421            if cc_canon != linker_canon {
422                panic!(
423                    "CC and Linker are expected to be the same for {} target, got:\n\
424                     CC: `{}`,\n\
425                     Linker: `{}`\n",
426                    target.triple,
427                    cc_canon.display(),
428                    linker_canon.display(),
429                );
430            }
431
432            let output =
433                command(cc_tool.path()).arg("-dumpversion").run_capture_stdout(&sess).stdout();
434            let version_str = output.trim();
435            let mut parts = version_str.split('.').map(|s| s.parse::<u32>().unwrap_or(0));
436            let major = parts.next().unwrap_or(0);
437            let minor = parts.next().unwrap_or(0);
438            let patch = parts.next().unwrap_or(0);
439            if (major, minor, patch) < (22, 1, 0) {
440                panic!(
441                    "clang version too old: {} ({} target trequires >= 22.1.0), path: {}",
442                    target.triple,
443                    version_str,
444                    cc_tool.path().display()
445                );
446            }
447        }
448    }
449
450    if let Some(ref s) = sess.config.ccache {
451        cmd_finder.must_have(s);
452    }
453}