1 //! Implementation of rustbuild, the Rust build system.
3 //! This module, and its descendants, are the implementation of the Rust build
4 //! system. Most of this build system is backed by Cargo but the outer layer
5 //! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
6 //! builds, building artifacts like LLVM, etc. The goals of rustbuild are:
8 //! * To be an easily understandable, easily extensible, and maintainable build
10 //! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
11 //! crates.io and Cargo.
12 //! * A standard interface to build across all platforms, including MSVC
14 //! ## Further information
16 //! More documentation can be found in each respective module below, and you can
17 //! also check out the `src/bootstrap/README.md` file for more information.
19 use std::cell::{Cell, RefCell};
20 use std::collections::{HashMap, HashSet};
22 use std::fs::{self, File};
23 use std::io::ErrorKind;
24 use std::path::{Path, PathBuf};
25 use std::process::{Command, Stdio};
28 use build_helper::ci::CiEnv;
30 use config::{DryRun, Target};
31 use filetime::FileTime;
32 use once_cell::sync::OnceCell;
34 use crate::builder::Kind;
35 use crate::config::{LlvmLibunwind, TargetSelection};
37 exe, libdir, mtime, output, run, run_suppressed, symlink_dir, try_run_suppressed,
66 #[cfg(feature = "build-metrics")]
72 #[cfg(all(unix, not(target_os = "haiku")))]
74 pub unsafe fn setup(build: &mut crate::Build) {
75 if build.config.low_priority {
76 libc::setpriority(libc::PRIO_PGRP as _, 0, 10);
81 #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))]
83 pub unsafe fn setup(_build: &mut crate::Build) {}
86 pub use crate::builder::PathSet;
87 use crate::cache::{Interned, INTERNER};
88 pub use crate::config::Config;
89 pub use crate::flags::Subcommand;
91 const LLVM_TOOLS: &[&str] = &[
92 "llvm-cov", // used to generate coverage report
93 "llvm-nm", // used to inspect binaries; it shows symbol names, their sizes and visibility
94 "llvm-objcopy", // used to transform ELFs into binary format which flashing tools consume
95 "llvm-objdump", // used to disassemble programs
96 "llvm-profdata", // used to inspect and merge files generated by profiles
97 "llvm-readobj", // used to get information from ELFs/objects that the other tools don't provide
98 "llvm-size", // used to prints the size of the linker sections of a program
99 "llvm-strip", // used to discard symbols from binary files to reduce their size
100 "llvm-ar", // used for creating and modifying archive files
101 "llvm-as", // used to convert LLVM assembly to LLVM bitcode
102 "llvm-dis", // used to disassemble LLVM bitcode
103 "llc", // used to compile LLVM bytecode
104 "opt", // used to optimize LLVM bytecode
107 /// LLD file names for all flavors.
108 const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
110 pub const VERSION: usize = 2;
112 /// Extra --check-cfg to add when building
113 /// (Mode restriction, config name, config values (if any))
114 const EXTRA_CHECK_CFGS: &[(Option<Mode>, &'static str, Option<&[&'static str]>)] = &[
115 (None, "bootstrap", None),
116 (Some(Mode::Rustc), "parallel_compiler", None),
117 (Some(Mode::ToolRustc), "parallel_compiler", None),
118 (Some(Mode::Codegen), "parallel_compiler", None),
119 (Some(Mode::Std), "stdarch_intel_sde", None),
120 (Some(Mode::Std), "no_fp_fmt_parse", None),
121 (Some(Mode::Std), "no_global_oom_handling", None),
122 (Some(Mode::Std), "no_rc", None),
123 (Some(Mode::Std), "no_sync", None),
124 (Some(Mode::Std), "freebsd12", None),
125 (Some(Mode::Std), "backtrace_in_libstd", None),
126 /* Extra values not defined in the built-in targets yet, but used in std */
127 (Some(Mode::Std), "target_env", Some(&["libnx"])),
128 // (Some(Mode::Std), "target_os", Some(&[])),
129 (Some(Mode::Std), "target_arch", Some(&["asmjs", "spirv", "nvptx", "xtensa"])),
130 /* Extra names used by dependencies */
131 // FIXME: Used by serde_json, but we should not be triggering on external dependencies.
132 (Some(Mode::Rustc), "no_btreemap_remove_entry", None),
133 (Some(Mode::ToolRustc), "no_btreemap_remove_entry", None),
134 // FIXME: Used by crossbeam-utils, but we should not be triggering on external dependencies.
135 (Some(Mode::Rustc), "crossbeam_loom", None),
136 (Some(Mode::ToolRustc), "crossbeam_loom", None),
137 // FIXME: Used by proc-macro2, but we should not be triggering on external dependencies.
138 (Some(Mode::Rustc), "span_locations", None),
139 (Some(Mode::ToolRustc), "span_locations", None),
140 // FIXME: Used by rustix, but we should not be triggering on external dependencies.
141 (Some(Mode::Rustc), "rustix_use_libc", None),
142 (Some(Mode::ToolRustc), "rustix_use_libc", None),
143 // FIXME: Used by filetime, but we should not be triggering on external dependencies.
144 (Some(Mode::Rustc), "emulate_second_only_system", None),
145 (Some(Mode::ToolRustc), "emulate_second_only_system", None),
148 /// A structure representing a Rust compiler.
150 /// Each compiler has a `stage` that it is associated with and a `host` that
151 /// corresponds to the platform the compiler runs on. This structure is used as
152 /// a parameter to many methods below.
153 #[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
154 pub struct Compiler {
156 host: TargetSelection,
159 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
161 /// Run normal tests and doc tests (default).
163 /// Do not run any doc tests.
165 /// Only run doc tests.
174 /// Global configuration for the build system.
176 /// This structure transitively contains all configuration for the build system.
177 /// All filesystem-encoded configuration is in `config`, all flags are in
178 /// `flags`, and then parsed or probed information is listed in the keys below.
180 /// This structure is a parameter of almost all methods in the build system,
181 /// although most functions are implemented as free functions rather than
182 /// methods specifically on this structure itself (to make it easier to
185 /// User-specified configuration from `config.toml`.
188 // Version information
191 // Properties derived from the above configuration
194 bootstrap_out: PathBuf,
195 cargo_info: channel::GitInfo,
196 rust_analyzer_info: channel::GitInfo,
197 clippy_info: channel::GitInfo,
198 miri_info: channel::GitInfo,
199 rustfmt_info: channel::GitInfo,
200 in_tree_llvm_info: channel::GitInfo,
206 // Targets for which to build
207 build: TargetSelection,
208 hosts: Vec<TargetSelection>,
209 targets: Vec<TargetSelection>,
211 initial_rustc: PathBuf,
212 initial_cargo: PathBuf,
213 initial_lld: PathBuf,
214 initial_libdir: PathBuf,
216 // Runtime state filled in later on
217 // C/C++ compilers and archiver for all targets
218 cc: HashMap<TargetSelection, cc::Tool>,
219 cxx: HashMap<TargetSelection, cc::Tool>,
220 ar: HashMap<TargetSelection, PathBuf>,
221 ranlib: HashMap<TargetSelection, PathBuf>,
223 // allow bidirectional lookups: both name -> path and path -> name
224 crates: HashMap<Interned<String>, Crate>,
225 crate_paths: HashMap<PathBuf, Interned<String>>,
228 delayed_failures: RefCell<Vec<String>>,
229 prerelease_version: Cell<Option<u32>>,
231 RefCell<HashMap<TargetSelection, HashMap<String, (&'static str, PathBuf, Vec<String>)>>>,
233 #[cfg(feature = "build-metrics")]
234 metrics: metrics::BuildMetrics,
239 name: Interned<String>,
240 deps: HashSet<Interned<String>>,
245 fn local_path(&self, build: &Build) -> PathBuf {
246 self.path.strip_prefix(&build.config.src).unwrap().into()
250 /// When building Rust various objects are handled differently.
251 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
252 pub enum DependencyType {
253 /// Libraries originating from proc-macros.
255 /// Typical Rust libraries.
257 /// Non Rust libraries and objects shipped to ease usage of certain targets.
261 /// The various "modes" of invoking Cargo.
263 /// These entries currently correspond to the various output directories of the
264 /// build system, with each mod generating output in a different directory.
265 #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
267 /// Build the standard library, placing output in the "stageN-std" directory.
270 /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
273 /// Build a codegen backend for rustc, placing the output in the "stageN-codegen" directory.
276 /// Build a tool, placing output in the "stage0-bootstrap-tools"
277 /// directory. This is for miscellaneous sets of tools that are built
278 /// using the bootstrap stage0 compiler in its entirety (target libraries
279 /// and all). Typically these tools compile with stable Rust.
282 /// Build a tool which uses the locally built std, placing output in the
283 /// "stageN-tools" directory. Its usage is quite rare, mainly used by
284 /// compiletest which needs libtest.
287 /// Build a tool which uses the locally built rustc and the target std,
288 /// placing the output in the "stageN-tools" directory. This is used for
289 /// anything that needs a fully functional rustc, such as rustdoc, clippy,
290 /// cargo, rls, rustfmt, miri, etc.
295 pub fn is_tool(&self) -> bool {
296 matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd)
299 pub fn must_support_dlopen(&self) -> bool {
300 matches!(self, Mode::Std | Mode::Codegen)
309 macro_rules! forward {
310 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
312 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
313 self.config.$fn( $($param),* )
321 is_verbose() -> bool,
322 create(path: &Path, s: &str),
324 tempdir() -> PathBuf,
325 try_run(cmd: &mut Command) -> bool,
326 llvm_link_shared() -> bool,
327 download_rustc() -> bool,
328 initial_rustfmt() -> Option<PathBuf>,
332 /// Creates a new set of build configuration from the `flags` on the command
333 /// line and the filesystem `config`.
335 /// By default all build output will be placed in the current directory.
336 pub fn new(mut config: Config) -> Build {
337 let src = config.src.clone();
338 let out = config.out.clone();
341 // keep this consistent with the equivalent check in x.py:
342 // https://github.com/rust-lang/rust/blob/a8a33cf27166d3eabaffc58ed3799e054af3b0c6/src/bootstrap/bootstrap.py#L796-L797
343 let is_sudo = match env::var_os("SUDO_USER") {
344 Some(_sudo_user) => {
345 let uid = unsafe { libc::getuid() };
353 let ignore_git = config.ignore_git;
354 let rust_info = channel::GitInfo::new(ignore_git, &src);
355 let cargo_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/cargo"));
356 let rust_analyzer_info =
357 channel::GitInfo::new(ignore_git, &src.join("src/tools/rust-analyzer"));
358 let clippy_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/clippy"));
359 let miri_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/miri"));
360 let rustfmt_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/rustfmt"));
362 // we always try to use git for LLVM builds
363 let in_tree_llvm_info = channel::GitInfo::new(false, &src.join("src/llvm-project"));
365 let initial_target_libdir_str = if config.dry_run() {
366 "/dummy/lib/path/to/lib/".to_string()
369 Command::new(&config.initial_rustc)
371 .arg(config.build.rustc_target_arg())
373 .arg("target-libdir"),
376 let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
377 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
379 let initial_sysroot = if config.dry_run() {
382 output(Command::new(&config.initial_rustc).arg("--print").arg("sysroot"))
384 let initial_libdir = initial_target_dir
389 .strip_prefix(initial_sysroot.trim())
393 let version = std::fs::read_to_string(src.join("src").join("version"))
394 .expect("failed to read src/version");
395 let version = version.trim();
397 let bootstrap_out = std::env::current_exe()
398 .expect("could not determine path to running process")
402 if !bootstrap_out.join(exe("rustc", config.build)).exists() && !cfg!(test) {
403 // this restriction can be lifted whenever https://github.com/rust-lang/rfcs/pull/3028 is implemented
405 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
406 bootstrap_out.display()
410 if rust_info.is_from_tarball() && config.description.is_none() {
411 config.description = Some("built from a source tarball".to_owned());
414 let mut build = Build {
415 initial_rustc: config.initial_rustc.clone(),
416 initial_cargo: config.initial_cargo.clone(),
419 local_rebuild: config.local_rebuild,
420 fail_fast: config.cmd.fail_fast(),
421 doc_tests: config.cmd.doc_tests(),
422 verbosity: config.verbose,
425 hosts: config.hosts.clone(),
426 targets: config.targets.clone(),
429 version: version.to_string(),
443 ranlib: HashMap::new(),
444 crates: HashMap::new(),
445 crate_paths: HashMap::new(),
447 ci_env: CiEnv::current(),
448 delayed_failures: RefCell::new(Vec::new()),
449 prerelease_version: Cell::new(None),
450 tool_artifacts: Default::default(),
452 #[cfg(feature = "build-metrics")]
453 metrics: metrics::BuildMetrics::init(),
456 // If local-rust is the same major.minor as the current version, then force a
458 let local_version_verbose =
459 output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
460 let local_release = local_version_verbose
462 .filter_map(|x| x.strip_prefix("release:"))
466 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
467 build.verbose(&format!("auto-detected local-rebuild {}", local_release));
468 build.local_rebuild = true;
471 build.verbose("finding compilers");
472 cc_detect::find(&mut build);
473 // When running `setup`, the profile is about to change, so any requirements we have now may
474 // be different on the next invocation. Don't check for them until the next time x.py is
475 // run. This is ok because `setup` never runs any build commands, so it won't fail if commands are missing.
477 // Similarly, for `setup` we don't actually need submodules or cargo metadata.
478 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
479 build.verbose("running sanity check");
480 sanity::check(&mut build);
482 // Make sure we update these before gathering metadata so we don't get an error about missing
484 let rust_submodules = [
485 "src/tools/rust-installer",
490 for s in rust_submodules {
491 build.update_submodule(Path::new(s));
493 // Now, update all existing submodules.
494 build.update_existing_submodules();
496 build.verbose("learning about cargo");
497 metadata::build(&mut build);
500 // Make a symbolic link so we can use a consistent directory in the documentation.
501 let build_triple = build.out.join(&build.build.triple);
502 let host = build.out.join("host");
503 if let Err(e) = symlink_dir(&build.config, &build_triple, &host) {
504 if e.kind() != ErrorKind::AlreadyExists {
506 "symlink_dir({} => {}) failed with {}",
508 build_triple.display(),
517 // modified from `check_submodule` and `update_submodule` in bootstrap.py
518 /// Given a path to the directory of a submodule, update it.
520 /// `relative_path` should be relative to the root of the git repository, not an absolute path.
521 pub(crate) fn update_submodule(&self, relative_path: &Path) {
522 fn dir_is_empty(dir: &Path) -> bool {
523 t!(std::fs::read_dir(dir)).next().is_none()
526 if !self.config.submodules(&self.rust_info()) {
530 let absolute_path = self.config.src.join(relative_path);
532 // NOTE: The check for the empty directory is here because when running x.py the first time,
533 // the submodule won't be checked out. Check it out now so we can build it.
534 if !channel::GitInfo::new(false, &absolute_path).is_managed_git_subrepository()
535 && !dir_is_empty(&absolute_path)
541 let checked_out_hash =
542 output(Command::new("git").args(&["rev-parse", "HEAD"]).current_dir(&absolute_path));
544 let recorded = output(
546 .args(&["ls-tree", "HEAD"])
548 .current_dir(&self.config.src),
550 let actual_hash = recorded
553 .unwrap_or_else(|| panic!("unexpected output `{}`", recorded));
556 if actual_hash == checked_out_hash.trim_end() {
557 // already checked out
561 println!("Updating submodule {}", relative_path.display());
564 .args(&["submodule", "-q", "sync"])
566 .current_dir(&self.config.src),
569 // Try passing `--progress` to start, then run git again without if that fails.
570 let update = |progress: bool| {
571 // Git is buggy and will try to fetch submodules from the tracking branch for *this* repository,
572 // even though that has no relation to the upstream for the submodule.
573 let current_branch = {
577 .args(["symbolic-ref", "--short", "HEAD"])
578 .stderr(Stdio::inherit())
580 let output = t!(output);
581 if output.status.success() {
582 Some(String::from_utf8(output.stdout).unwrap().trim().to_owned())
588 let mut git = self.config.git();
589 if let Some(branch) = current_branch {
590 git.arg("-c").arg(format!("branch.{branch}.remote=origin"));
592 git.args(&["submodule", "update", "--init", "--recursive", "--depth=1"]);
594 git.arg("--progress");
596 git.arg(relative_path);
599 // NOTE: doesn't use `try_run` because this shouldn't print an error if it fails.
600 if !update(true).status().map_or(false, |status| status.success()) {
601 self.run(&mut update(false));
604 // Save any local changes, but avoid running `git stash pop` if there are none (since it will exit with an error).
605 let has_local_modifications = !self.try_run(
607 .args(&["diff-index", "--quiet", "HEAD"])
608 .current_dir(&absolute_path),
610 if has_local_modifications {
611 self.run(Command::new("git").args(&["stash", "push"]).current_dir(&absolute_path));
614 self.run(Command::new("git").args(&["reset", "-q", "--hard"]).current_dir(&absolute_path));
615 self.run(Command::new("git").args(&["clean", "-qdfx"]).current_dir(&absolute_path));
617 if has_local_modifications {
618 self.run(Command::new("git").args(&["stash", "pop"]).current_dir(absolute_path));
622 /// If any submodule has been initialized already, sync it unconditionally.
623 /// This avoids contributors checking in a submodule change by accident.
624 pub fn update_existing_submodules(&self) {
625 // Avoid running git when there isn't a git checkout.
626 if !self.config.submodules(&self.rust_info()) {
632 .args(&["config", "--file"])
633 .arg(&self.config.src.join(".gitmodules"))
634 .args(&["--get-regexp", "path"]),
636 for line in output.lines() {
637 // Look for `submodule.$name.path = $path`
638 // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer`
639 let submodule = Path::new(line.splitn(2, ' ').nth(1).unwrap());
640 // Don't update the submodule unless it's already been cloned.
641 if channel::GitInfo::new(false, submodule).is_managed_git_subrepository() {
642 self.update_submodule(submodule);
647 /// Executes the entire build, as configured by the flags and configuration.
648 pub fn build(&mut self) {
653 if let Subcommand::Format { check, paths } = &self.config.cmd {
654 return format::format(&builder::Builder::new(&self), *check, &paths);
657 // Download rustfmt early so that it can be used in rust-analyzer configs.
658 let _ = &builder::Builder::new(&self).initial_rustfmt();
661 let builder = builder::Builder::new(&self);
662 if let Some(path) = builder.paths.get(0) {
663 if path == Path::new("nonexistent/path/to/trigger/cargo/metadata") {
669 if !self.config.dry_run() {
671 self.config.dry_run = DryRun::SelfCheck;
672 let builder = builder::Builder::new(&self);
673 builder.execute_cli();
675 self.config.dry_run = DryRun::Disabled;
676 let builder = builder::Builder::new(&self);
677 builder.execute_cli();
679 let builder = builder::Builder::new(&self);
680 builder.execute_cli();
683 // Check for postponed failures from `test --no-fail-fast`.
684 let failures = self.delayed_failures.borrow();
685 if failures.len() > 0 {
686 eprintln!("\n{} command(s) did not execute successfully:\n", failures.len());
687 for failure in failures.iter() {
688 eprintln!(" - {}\n", failure);
693 #[cfg(feature = "build-metrics")]
694 self.metrics.persist(self);
697 /// Clear out `dir` if `input` is newer.
699 /// After this executes, it will also ensure that `dir` exists.
700 fn clear_if_dirty(&self, dir: &Path, input: &Path) -> bool {
701 let stamp = dir.join(".stamp");
702 let mut cleared = false;
703 if mtime(&stamp) < mtime(input) {
704 self.verbose(&format!("Dirty - {}", dir.display()));
705 let _ = fs::remove_dir_all(dir);
707 } else if stamp.exists() {
710 t!(fs::create_dir_all(dir));
711 t!(File::create(stamp));
715 fn rust_info(&self) -> &GitInfo {
716 &self.config.rust_info
719 /// Gets the space-separated set of activated features for the standard
721 fn std_features(&self, target: TargetSelection) -> String {
722 let mut features = " panic-unwind".to_string();
724 match self.config.llvm_libunwind(target) {
725 LlvmLibunwind::InTree => features.push_str(" llvm-libunwind"),
726 LlvmLibunwind::System => features.push_str(" system-llvm-libunwind"),
727 LlvmLibunwind::No => {}
729 if self.config.backtrace {
730 features.push_str(" backtrace");
732 if self.config.profiler_enabled(target) {
733 features.push_str(" profiler");
738 /// Gets the space-separated set of activated features for the compiler.
739 fn rustc_features(&self, kind: Kind) -> String {
740 let mut features = vec![];
741 if self.config.jemalloc {
742 features.push("jemalloc");
744 if self.config.llvm_enabled() || kind == Kind::Check {
745 features.push("llvm");
747 // keep in sync with `bootstrap/compile.rs:rustc_cargo_env`
748 if self.config.rustc_parallel {
749 features.push("rustc_use_parallel_compiler");
752 // If debug logging is on, then we want the default for tracing:
753 // https://github.com/tokio-rs/tracing/blob/3dd5c03d907afdf2c39444a29931833335171554/tracing/src/level_filters.rs#L26
754 // which is everything (including debug/trace/etc.)
755 // if its unset, if debug_assertions is on, then debug_logging will also be on
756 // as well as tracing *ignoring* this feature when debug_assertions is on
757 if !self.config.rust_debug_logging {
758 features.push("max_level_info");
764 /// Component directory that Cargo will produce output into (e.g.
766 fn cargo_dir(&self) -> &'static str {
767 if self.config.rust_optimize { "release" } else { "debug" }
770 fn tools_dir(&self, compiler: Compiler) -> PathBuf {
773 .join(&*compiler.host.triple)
774 .join(format!("stage{}-tools-bin", compiler.stage));
775 t!(fs::create_dir_all(&out));
779 /// Returns the root directory for all output generated in a particular
780 /// stage when running with a particular host compiler.
782 /// The mode indicates what the root directory is for.
783 fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
784 let suffix = match mode {
786 Mode::Rustc => "-rustc",
787 Mode::Codegen => "-codegen",
788 Mode::ToolBootstrap => "-bootstrap-tools",
789 Mode::ToolStd | Mode::ToolRustc => "-tools",
791 self.out.join(&*compiler.host.triple).join(format!("stage{}{}", compiler.stage, suffix))
794 /// Returns the root output directory for all Cargo output in a given stage,
795 /// running a particular compiler, whether or not we're building the
796 /// standard library, and targeting the specified architecture.
797 fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
798 self.stage_out(compiler, mode).join(&*target.triple).join(self.cargo_dir())
801 /// Root output directory for LLVM compiled for `target`
803 /// Note that if LLVM is configured externally then the directory returned
804 /// will likely be empty.
805 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
806 self.out.join(&*target.triple).join("llvm")
809 fn lld_out(&self, target: TargetSelection) -> PathBuf {
810 self.out.join(&*target.triple).join("lld")
813 /// Output directory for all documentation for a target
814 fn doc_out(&self, target: TargetSelection) -> PathBuf {
815 self.out.join(&*target.triple).join("doc")
818 /// Output directory for all JSON-formatted documentation for a target
819 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
820 self.out.join(&*target.triple).join("json-doc")
823 fn test_out(&self, target: TargetSelection) -> PathBuf {
824 self.out.join(&*target.triple).join("test")
827 /// Output directory for all documentation for a target
828 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
829 self.out.join(&*target.triple).join("compiler-doc")
832 /// Output directory for some generated md crate documentation for a target (temporary)
833 fn md_doc_out(&self, target: TargetSelection) -> Interned<PathBuf> {
834 INTERNER.intern_path(self.out.join(&*target.triple).join("md-doc"))
837 /// Returns `true` if no custom `llvm-config` is set for the specified target.
839 /// If no custom `llvm-config` was specified then Rust's llvm will be used.
840 fn is_rust_llvm(&self, target: TargetSelection) -> bool {
841 match self.config.target_config.get(&target) {
842 Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
843 Some(Target { llvm_config, .. }) => {
844 // If the user set llvm-config we assume Rust is not patched,
845 // but first check to see if it was configured by llvm-from-ci.
846 (self.config.llvm_from_ci && target == self.config.build) || llvm_config.is_none()
852 /// Returns the path to `FileCheck` binary for the specified target
853 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
854 let target_config = self.config.target_config.get(&target);
855 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
857 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
858 let llvm_bindir = output(Command::new(s).arg("--bindir"));
859 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
860 if filecheck.exists() {
863 // On Fedora the system LLVM installs FileCheck in the
864 // llvm subdirectory of the libdir.
865 let llvm_libdir = output(Command::new(s).arg("--libdir"));
867 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
868 if lib_filecheck.exists() {
871 // Return the most normal file name, even though
872 // it doesn't exist, so that any error message
878 let base = self.llvm_out(target).join("build");
879 let base = if !self.ninja() && target.contains("msvc") {
880 if self.config.llvm_optimize {
881 if self.config.llvm_release_debuginfo {
882 base.join("RelWithDebInfo")
892 base.join("bin").join(exe("FileCheck", target))
896 /// Directory for libraries built from C/C++ code and shared between stages.
897 fn native_dir(&self, target: TargetSelection) -> PathBuf {
898 self.out.join(&*target.triple).join("native")
901 /// Root output directory for rust_test_helpers library compiled for
903 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
904 self.native_dir(target).join("rust-test-helpers")
907 /// Adds the `RUST_TEST_THREADS` env var if necessary
908 fn add_rust_test_threads(&self, cmd: &mut Command) {
909 if env::var_os("RUST_TEST_THREADS").is_none() {
910 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
914 /// Returns the libdir of the snapshot compiler.
915 fn rustc_snapshot_libdir(&self) -> PathBuf {
916 self.rustc_snapshot_sysroot().join(libdir(self.config.build))
919 /// Returns the sysroot of the snapshot compiler.
920 fn rustc_snapshot_sysroot(&self) -> &Path {
921 static SYSROOT_CACHE: OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
922 SYSROOT_CACHE.get_or_init(|| {
923 let mut rustc = Command::new(&self.initial_rustc);
924 rustc.args(&["--print", "sysroot"]);
925 output(&mut rustc).trim().into()
929 /// Runs a command, printing out nice contextual information if it fails.
930 fn run(&self, cmd: &mut Command) {
931 if self.config.dry_run() {
934 self.verbose(&format!("running: {:?}", cmd));
935 run(cmd, self.is_verbose())
938 /// Runs a command, printing out nice contextual information if it fails.
939 fn run_quiet(&self, cmd: &mut Command) {
940 if self.config.dry_run() {
943 self.verbose(&format!("running: {:?}", cmd));
947 /// Runs a command, printing out nice contextual information if it fails.
948 /// Exits if the command failed to execute at all, otherwise returns its
949 /// `status.success()`.
950 fn try_run_quiet(&self, cmd: &mut Command) -> bool {
951 if self.config.dry_run() {
954 self.verbose(&format!("running: {:?}", cmd));
955 try_run_suppressed(cmd)
958 pub fn is_verbose_than(&self, level: usize) -> bool {
959 self.verbosity > level
962 /// Prints a message if this build is configured in more verbose mode than `level`.
963 fn verbose_than(&self, level: usize, msg: &str) {
964 if self.is_verbose_than(level) {
969 fn info(&self, msg: &str) {
970 match self.config.dry_run {
971 DryRun::SelfCheck => return,
972 DryRun::Disabled | DryRun::UserSelected => {
978 /// Returns the number of parallel jobs that have been configured for this
980 fn jobs(&self) -> u32 {
981 self.config.jobs.unwrap_or_else(|| {
982 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
986 fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
987 if !self.config.rust_remap_debuginfo {
993 let sha = self.rust_sha().unwrap_or(&self.version);
994 Some(format!("/rustc/{}", sha))
996 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1000 /// Returns the path to the C compiler for the target specified.
1001 fn cc(&self, target: TargetSelection) -> &Path {
1002 self.cc[&target].path()
1005 /// Returns a list of flags to pass to the C compiler for the target
1007 fn cflags(&self, target: TargetSelection, which: GitRepo, c: CLang) -> Vec<String> {
1008 let base = match c {
1009 CLang::C => &self.cc[&target],
1010 CLang::Cxx => &self.cxx[&target],
1013 // Filter out -O and /O (the optimization flags) that we picked up from
1014 // cc-rs because the build scripts will determine that for themselves.
1018 .map(|s| s.to_string_lossy().into_owned())
1019 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1020 .collect::<Vec<String>>();
1022 // If we're compiling on macOS then we add a few unconditional flags
1023 // indicating that we want libc++ (more filled out than libstdc++) and
1024 // we want to compile for 10.7. This way we can ensure that
1025 // LLVM/etc are all properly compiled.
1026 if target.contains("apple-darwin") {
1027 base.push("-stdlib=libc++".into());
1030 // Work around an apparently bad MinGW / GCC optimization,
1031 // See: https://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
1032 // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
1033 if &*target.triple == "i686-pc-windows-gnu" {
1034 base.push("-fno-omit-frame-pointer".into());
1037 if let Some(map_to) = self.debuginfo_map_to(which) {
1038 let map = format!("{}={}", self.src.display(), map_to);
1039 let cc = self.cc(target);
1040 if cc.ends_with("clang") || cc.ends_with("gcc") {
1041 base.push(format!("-fdebug-prefix-map={}", map));
1042 } else if cc.ends_with("clang-cl.exe") {
1043 base.push("-Xclang".into());
1044 base.push(format!("-fdebug-prefix-map={}", map));
1050 /// Returns the path to the `ar` archive utility for the target specified.
1051 fn ar(&self, target: TargetSelection) -> Option<&Path> {
1052 self.ar.get(&target).map(|p| &**p)
1055 /// Returns the path to the `ranlib` utility for the target specified.
1056 fn ranlib(&self, target: TargetSelection) -> Option<&Path> {
1057 self.ranlib.get(&target).map(|p| &**p)
1060 /// Returns the path to the C++ compiler for the target specified.
1061 fn cxx(&self, target: TargetSelection) -> Result<&Path, String> {
1062 match self.cxx.get(&target) {
1063 Some(p) => Ok(p.path()),
1065 Err(format!("target `{}` is not configured as a host, only as a target", target))
1070 /// Returns the path to the linker for the given target if it needs to be overridden.
1071 fn linker(&self, target: TargetSelection) -> Option<&Path> {
1072 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.as_ref())
1075 } else if target.contains("vxworks") {
1076 // need to use CXX compiler as linker to resolve the exception functions
1077 // that are only existed in CXX libraries
1078 Some(self.cxx[&target].path())
1079 } else if target != self.config.build
1080 && util::use_host_linker(target)
1081 && !target.contains("msvc")
1083 Some(self.cc(target))
1084 } else if self.config.use_lld && !self.is_fuse_ld_lld(target) && self.build == target {
1085 Some(&self.initial_lld)
1091 // LLD is used through `-fuse-ld=lld` rather than directly.
1092 // Only MSVC targets use LLD directly at the moment.
1093 fn is_fuse_ld_lld(&self, target: TargetSelection) -> bool {
1094 self.config.use_lld && !target.contains("msvc")
1097 fn lld_flags(&self, target: TargetSelection) -> impl Iterator<Item = String> {
1098 let mut options = [None, None];
1100 if self.config.use_lld {
1101 if self.is_fuse_ld_lld(target) {
1102 options[0] = Some("-Clink-arg=-fuse-ld=lld".to_string());
1105 let no_threads = util::lld_flag_no_threads(target.contains("windows"));
1106 options[1] = Some(format!("-Clink-arg=-Wl,{}", no_threads));
1109 IntoIterator::into_iter(options).flatten()
1112 /// Returns if this target should statically link the C runtime, if specified
1113 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1114 if target.contains("pc-windows-msvc") {
1117 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1121 /// Returns the "musl root" for this `target`, if defined
1122 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1126 .and_then(|t| t.musl_root.as_ref())
1127 .or_else(|| self.config.musl_root.as_ref())
1131 /// Returns the "musl libdir" for this `target`.
1132 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1133 let t = self.config.target_config.get(&target)?;
1134 if let libdir @ Some(_) = &t.musl_libdir {
1135 return libdir.clone();
1137 self.musl_root(target).map(|root| root.join("lib"))
1140 /// Returns the sysroot for the wasi target, if defined
1141 fn wasi_root(&self, target: TargetSelection) -> Option<&Path> {
1142 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p)
1145 /// Returns `true` if this is a no-std `target`, if defined
1146 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1147 self.config.target_config.get(&target).map(|t| t.no_std)
1150 /// Returns `true` if the target will be tested using the `remote-test-client`
1151 /// and `remote-test-server` binaries.
1152 fn remote_tested(&self, target: TargetSelection) -> bool {
1153 self.qemu_rootfs(target).is_some()
1154 || target.contains("android")
1155 || env::var_os("TEST_DEVICE_ADDR").is_some()
1158 /// Returns the root of the "rootfs" image that this target will be using,
1159 /// if one was configured.
1161 /// If `Some` is returned then that means that tests for this target are
1162 /// emulated with QEMU and binaries will need to be shipped to the emulator.
1163 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1164 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1167 /// Path to the python interpreter to use
1168 fn python(&self) -> &Path {
1169 if self.config.build.ends_with("apple-darwin") {
1170 // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1171 // LLDB plugin's compiled module which only works with the system python
1172 // (namely not Homebrew-installed python)
1173 Path::new("/usr/bin/python3")
1178 .expect("python is required for running LLDB or rustdoc tests")
1182 /// Temporary directory that extended error information is emitted to.
1183 fn extended_error_dir(&self) -> PathBuf {
1184 self.out.join("tmp/extended-error-metadata")
1187 /// Tests whether the `compiler` compiling for `target` should be forced to
1188 /// use a stage1 compiler instead.
1190 /// Currently, by default, the build system does not perform a "full
1191 /// bootstrap" by default where we compile the compiler three times.
1192 /// Instead, we compile the compiler two times. The final stage (stage2)
1193 /// just copies the libraries from the previous stage, which is what this
1196 /// Here we return `true` if:
1198 /// * The build isn't performing a full bootstrap
1199 /// * The `compiler` is in the final stage, 2
1200 /// * We're not cross-compiling, so the artifacts are already available in
1203 /// When all of these conditions are met the build will lift artifacts from
1204 /// the previous stage forward.
1205 fn force_use_stage1(&self, compiler: Compiler, target: TargetSelection) -> bool {
1206 !self.config.full_bootstrap
1207 && compiler.stage >= 2
1208 && (self.hosts.iter().any(|h| *h == target) || target == self.build)
1211 /// Given `num` in the form "a.b.c" return a "release string" which
1212 /// describes the release version number.
1214 /// For example on nightly this returns "a.b.c-nightly", on beta it returns
1215 /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
1216 fn release(&self, num: &str) -> String {
1217 match &self.config.channel[..] {
1218 "stable" => num.to_string(),
1220 if self.rust_info().is_managed_git_subrepository() && !self.config.ignore_git {
1221 format!("{}-beta.{}", num, self.beta_prerelease_version())
1223 format!("{}-beta", num)
1226 "nightly" => format!("{}-nightly", num),
1227 _ => format!("{}-dev", num),
1231 fn beta_prerelease_version(&self) -> u32 {
1232 if let Some(s) = self.prerelease_version.get() {
1236 // Figure out how many merge commits happened since we branched off master.
1237 // That's our beta number!
1238 // (Note that we use a `..` range, not the `...` symmetric difference.)
1240 output(self.config.git().arg("rev-list").arg("--count").arg("--merges").arg(format!(
1241 "refs/remotes/origin/{}..HEAD",
1242 self.config.stage0_metadata.config.nightly_branch
1244 let n = count.trim().parse().unwrap();
1245 self.prerelease_version.set(Some(n));
1249 /// Returns the value of `release` above for Rust itself.
1250 fn rust_release(&self) -> String {
1251 self.release(&self.version)
1254 /// Returns the "package version" for a component given the `num` release
1257 /// The package version is typically what shows up in the names of tarballs.
1258 /// For channels like beta/nightly it's just the channel name, otherwise
1259 /// it's the `num` provided.
1260 fn package_vers(&self, num: &str) -> String {
1261 match &self.config.channel[..] {
1262 "stable" => num.to_string(),
1263 "beta" => "beta".to_string(),
1264 "nightly" => "nightly".to_string(),
1265 _ => format!("{}-dev", num),
1269 /// Returns the value of `package_vers` above for Rust itself.
1270 fn rust_package_vers(&self) -> String {
1271 self.package_vers(&self.version)
1274 /// Returns the `version` string associated with this compiler for Rust
1277 /// Note that this is a descriptive string which includes the commit date,
1278 /// sha, version, etc.
1279 fn rust_version(&self) -> String {
1280 let mut version = self.rust_info().version(self, &self.version);
1281 if let Some(ref s) = self.config.description {
1282 version.push_str(" (");
1283 version.push_str(s);
1289 /// Returns the full commit hash.
1290 fn rust_sha(&self) -> Option<&str> {
1291 self.rust_info().sha()
1294 /// Returns the `a.b.c` version that the given package is at.
1295 fn release_num(&self, package: &str) -> String {
1296 let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
1297 let toml = t!(fs::read_to_string(&toml_file_name));
1298 for line in toml.lines() {
1299 if let Some(stripped) =
1300 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix("\""))
1302 return stripped.to_owned();
1306 panic!("failed to find version in {}'s Cargo.toml", package)
1309 /// Returns `true` if unstable features should be enabled for the compiler
1311 fn unstable_features(&self) -> bool {
1312 match &self.config.channel[..] {
1313 "stable" | "beta" => false,
1314 "nightly" | _ => true,
1318 /// Returns a Vec of all the dependencies of the given root crate,
1319 /// including transitive dependencies and the root itself. Only includes
1320 /// "local" crates (those in the local source tree, not from a registry).
1321 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1322 let mut ret = Vec::new();
1323 let mut list = vec![INTERNER.intern_str(root)];
1324 let mut visited = HashSet::new();
1325 while let Some(krate) = list.pop() {
1329 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1331 for dep in &krate.deps {
1332 if !self.crates.contains_key(dep) {
1333 // Ignore non-workspace members.
1336 // Don't include optional deps if their features are not
1337 // enabled. Ideally this would be computed from `cargo
1338 // metadata --features …`, but that is somewhat slow. In
1339 // the future, we may want to consider just filtering all
1340 // build and dev dependencies in metadata::build.
1341 if visited.insert(dep)
1342 && (dep != "profiler_builtins"
1344 .map(|t| self.config.profiler_enabled(t))
1345 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1346 && (dep != "rustc_codegen_llvm" || self.config.llvm_enabled())
1355 fn read_stamp_file(&self, stamp: &Path) -> Vec<(PathBuf, DependencyType)> {
1356 if self.config.dry_run() {
1360 if !stamp.exists() {
1362 "Error: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1365 crate::detail_exit(1);
1368 let mut paths = Vec::new();
1369 let contents = t!(fs::read(stamp), &stamp);
1370 // This is the method we use for extracting paths from the stamp file passed to us. See
1371 // run_cargo for more information (in compile.rs).
1372 for part in contents.split(|b| *b == 0) {
1373 if part.is_empty() {
1376 let dependency_type = match part[0] as char {
1377 'h' => DependencyType::Host,
1378 's' => DependencyType::TargetSelfContained,
1379 't' => DependencyType::Target,
1380 _ => unreachable!(),
1382 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1383 paths.push((path, dependency_type));
1388 /// Copies a file from `src` to `dst`
1389 pub fn copy(&self, src: &Path, dst: &Path) {
1390 self.copy_internal(src, dst, false);
1393 fn copy_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1394 if self.config.dry_run() {
1397 self.verbose_than(1, &format!("Copy {:?} to {:?}", src, dst));
1401 let _ = fs::remove_file(&dst);
1402 let metadata = t!(src.symlink_metadata());
1403 let mut src = src.to_path_buf();
1404 if metadata.file_type().is_symlink() {
1405 if dereference_symlinks {
1406 src = t!(fs::canonicalize(src));
1408 let link = t!(fs::read_link(src));
1409 t!(self.config.symlink_file(link, dst));
1413 if let Ok(()) = fs::hard_link(&src, dst) {
1414 // Attempt to "easy copy" by creating a hard link
1415 // (symlinks don't work on windows), but if that fails
1416 // just fall back to a slow `copy` operation.
1418 if let Err(e) = fs::copy(&src, dst) {
1419 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1421 t!(fs::set_permissions(dst, metadata.permissions()));
1422 let atime = FileTime::from_last_access_time(&metadata);
1423 let mtime = FileTime::from_last_modification_time(&metadata);
1424 t!(filetime::set_file_times(dst, atime, mtime));
1428 /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1429 /// when this function is called.
1430 pub fn cp_r(&self, src: &Path, dst: &Path) {
1431 if self.config.dry_run() {
1434 for f in self.read_dir(src) {
1435 let path = f.path();
1436 let name = path.file_name().unwrap();
1437 let dst = dst.join(name);
1438 if t!(f.file_type()).is_dir() {
1439 t!(fs::create_dir_all(&dst));
1440 self.cp_r(&path, &dst);
1442 let _ = fs::remove_file(&dst);
1443 self.copy(&path, &dst);
1448 /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1449 /// when this function is called. Unwanted files or directories can be skipped
1450 /// by returning `false` from the filter function.
1451 pub fn cp_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1452 // Immediately recurse with an empty relative path
1453 self.recurse_(src, dst, Path::new(""), filter)
1456 // Inner function does the actual work
1457 fn recurse_(&self, src: &Path, dst: &Path, relative: &Path, filter: &dyn Fn(&Path) -> bool) {
1458 for f in self.read_dir(src) {
1459 let path = f.path();
1460 let name = path.file_name().unwrap();
1461 let dst = dst.join(name);
1462 let relative = relative.join(name);
1463 // Only copy file or directory if the filter function returns true
1464 if filter(&relative) {
1465 if t!(f.file_type()).is_dir() {
1466 let _ = fs::remove_dir_all(&dst);
1467 self.create_dir(&dst);
1468 self.recurse_(&path, &dst, &relative, filter);
1470 let _ = fs::remove_file(&dst);
1471 self.copy(&path, &dst);
1477 fn copy_to_folder(&self, src: &Path, dest_folder: &Path) {
1478 let file_name = src.file_name().unwrap();
1479 let dest = dest_folder.join(file_name);
1480 self.copy(src, &dest);
1483 fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1484 if self.config.dry_run() {
1487 let dst = dstdir.join(src.file_name().unwrap());
1488 self.verbose_than(1, &format!("Install {:?} to {:?}", src, dst));
1489 t!(fs::create_dir_all(dstdir));
1491 panic!("Error: File \"{}\" not found!", src.display());
1493 self.copy_internal(src, &dst, true);
1497 fn read(&self, path: &Path) -> String {
1498 if self.config.dry_run() {
1499 return String::new();
1501 t!(fs::read_to_string(path))
1504 fn create_dir(&self, dir: &Path) {
1505 if self.config.dry_run() {
1508 t!(fs::create_dir_all(dir))
1511 fn remove_dir(&self, dir: &Path) {
1512 if self.config.dry_run() {
1515 t!(fs::remove_dir_all(dir))
1518 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1519 let iter = match fs::read_dir(dir) {
1521 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1522 Err(err) => panic!("could not read dir {:?}: {:?}", dir, err),
1524 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1527 /// Returns if config.ninja is enabled, and checks for ninja existence,
1528 /// exiting with a nicer error message if not.
1529 fn ninja(&self) -> bool {
1530 let mut cmd_finder = crate::sanity::Finder::new();
1532 if self.config.ninja_in_file {
1533 // Some Linux distros rename `ninja` to `ninja-build`.
1534 // CMake can work with either binary name.
1535 if cmd_finder.maybe_have("ninja-build").is_none()
1536 && cmd_finder.maybe_have("ninja").is_none()
1540 Couldn't find required command: ninja (or ninja-build)
1542 You should install ninja as described at
1543 <https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1544 or set `ninja = false` in the `[llvm]` section of `config.toml`.
1545 Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1546 to download LLVM rather than building it.
1553 // If ninja isn't enabled but we're building for MSVC then we try
1554 // doubly hard to enable it. It was realized in #43767 that the msbuild
1555 // CMake generator for MSVC doesn't respect configuration options like
1556 // disabling LLVM assertions, which can often be quite important!
1558 // In these cases we automatically enable Ninja if we find it in the
1560 if !self.config.ninja_in_file && self.config.build.contains("msvc") {
1561 if cmd_finder.maybe_have("ninja").is_some() {
1566 self.config.ninja_in_file
1571 fn chmod(path: &Path, perms: u32) {
1572 use std::os::unix::fs::*;
1573 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1576 fn chmod(_path: &Path, _perms: u32) {}
1578 /// If code is not 0 (successful exit status), exit status is 101 (rust's default error code.)
1579 /// If the test is running and code is an error code, it will cause a panic.
1580 fn detail_exit(code: i32) -> ! {
1581 // if in test and code is an error code, panic with status code provided
1583 panic!("status code: {}", code);
1585 // otherwise,exit with provided status code
1586 std::process::exit(code);
1591 pub fn with_stage(mut self, stage: u32) -> Compiler {
1596 /// Returns `true` if this is a snapshot compiler for `build`'s configuration
1597 pub fn is_snapshot(&self, build: &Build) -> bool {
1598 self.stage == 0 && self.host == build.build
1601 /// Returns if this compiler should be treated as a final stage one in the
1602 /// current build session.
1603 /// This takes into account whether we're performing a full bootstrap or
1604 /// not; don't directly compare the stage with `2`!
1605 pub fn is_final_stage(&self, build: &Build) -> bool {
1606 let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
1607 self.stage >= final_stage
1611 fn envify(s: &str) -> String {
1617 .flat_map(|c| c.to_uppercase())