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};
24 use std::io::ErrorKind;
25 use std::path::{Path, PathBuf};
26 use std::process::{Command, Stdio};
29 use build_helper::ci::CiEnv;
31 use config::{DryRun, Target};
32 use filetime::FileTime;
33 use once_cell::sync::OnceCell;
35 use crate::builder::Kind;
36 use crate::config::{LlvmLibunwind, TargetSelection};
38 exe, libdir, mtime, output, run, run_suppressed, symlink_dir, try_run_suppressed,
67 #[cfg(feature = "build-metrics")]
73 #[cfg(all(unix, not(target_os = "haiku")))]
75 pub unsafe fn setup(build: &mut crate::Build) {
76 if build.config.low_priority {
77 libc::setpriority(libc::PRIO_PGRP as _, 0, 10);
82 #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))]
84 pub unsafe fn setup(_build: &mut crate::Build) {}
87 pub use crate::builder::PathSet;
88 use crate::cache::{Interned, INTERNER};
89 pub use crate::config::Config;
90 pub use crate::flags::Subcommand;
92 const LLVM_TOOLS: &[&str] = &[
93 "llvm-cov", // used to generate coverage report
94 "llvm-nm", // used to inspect binaries; it shows symbol names, their sizes and visibility
95 "llvm-objcopy", // used to transform ELFs into binary format which flashing tools consume
96 "llvm-objdump", // used to disassemble programs
97 "llvm-profdata", // used to inspect and merge files generated by profiles
98 "llvm-readobj", // used to get information from ELFs/objects that the other tools don't provide
99 "llvm-size", // used to prints the size of the linker sections of a program
100 "llvm-strip", // used to discard symbols from binary files to reduce their size
101 "llvm-ar", // used for creating and modifying archive files
102 "llvm-as", // used to convert LLVM assembly to LLVM bitcode
103 "llvm-dis", // used to disassemble LLVM bitcode
104 "llc", // used to compile LLVM bytecode
105 "opt", // used to optimize LLVM bytecode
108 /// LLD file names for all flavors.
109 const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
111 pub const VERSION: usize = 2;
113 /// Extra --check-cfg to add when building
114 /// (Mode restriction, config name, config values (if any))
115 const EXTRA_CHECK_CFGS: &[(Option<Mode>, &'static str, Option<&[&'static str]>)] = &[
116 (None, "bootstrap", None),
117 (Some(Mode::Rustc), "parallel_compiler", None),
118 (Some(Mode::ToolRustc), "parallel_compiler", None),
119 (Some(Mode::Codegen), "parallel_compiler", None),
120 (Some(Mode::Std), "stdarch_intel_sde", None),
121 (Some(Mode::Std), "no_fp_fmt_parse", None),
122 (Some(Mode::Std), "no_global_oom_handling", None),
123 (Some(Mode::Std), "no_rc", None),
124 (Some(Mode::Std), "no_sync", None),
125 (Some(Mode::Std), "freebsd12", None),
126 (Some(Mode::Std), "backtrace_in_libstd", None),
127 /* Extra values not defined in the built-in targets yet, but used in std */
128 (Some(Mode::Std), "target_env", Some(&["libnx"])),
129 // (Some(Mode::Std), "target_os", Some(&[])),
130 (Some(Mode::Std), "target_arch", Some(&["asmjs", "spirv", "nvptx", "xtensa"])),
131 /* Extra names used by dependencies */
132 // FIXME: Used by serde_json, but we should not be triggering on external dependencies.
133 (Some(Mode::Rustc), "no_btreemap_remove_entry", None),
134 (Some(Mode::ToolRustc), "no_btreemap_remove_entry", None),
135 // FIXME: Used by crossbeam-utils, but we should not be triggering on external dependencies.
136 (Some(Mode::Rustc), "crossbeam_loom", None),
137 (Some(Mode::ToolRustc), "crossbeam_loom", None),
138 // FIXME: Used by proc-macro2, but we should not be triggering on external dependencies.
139 (Some(Mode::Rustc), "span_locations", None),
140 (Some(Mode::ToolRustc), "span_locations", None),
141 // FIXME: Used by rustix, but we should not be triggering on external dependencies.
142 (Some(Mode::Rustc), "rustix_use_libc", None),
143 (Some(Mode::ToolRustc), "rustix_use_libc", None),
144 // FIXME: Used by filetime, but we should not be triggering on external dependencies.
145 (Some(Mode::Rustc), "emulate_second_only_system", None),
146 (Some(Mode::ToolRustc), "emulate_second_only_system", None),
149 /// A structure representing a Rust compiler.
151 /// Each compiler has a `stage` that it is associated with and a `host` that
152 /// corresponds to the platform the compiler runs on. This structure is used as
153 /// a parameter to many methods below.
154 #[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
155 pub struct Compiler {
157 host: TargetSelection,
160 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
162 /// Run normal tests and doc tests (default).
164 /// Do not run any doc tests.
166 /// Only run doc tests.
175 /// Global configuration for the build system.
177 /// This structure transitively contains all configuration for the build system.
178 /// All filesystem-encoded configuration is in `config`, all flags are in
179 /// `flags`, and then parsed or probed information is listed in the keys below.
181 /// This structure is a parameter of almost all methods in the build system,
182 /// although most functions are implemented as free functions rather than
183 /// methods specifically on this structure itself (to make it easier to
186 /// User-specified configuration from `config.toml`.
189 // Version information
192 // Properties derived from the above configuration
195 bootstrap_out: PathBuf,
196 cargo_info: channel::GitInfo,
197 rust_analyzer_info: channel::GitInfo,
198 clippy_info: channel::GitInfo,
199 miri_info: channel::GitInfo,
200 rustfmt_info: channel::GitInfo,
201 in_tree_llvm_info: channel::GitInfo,
207 // Targets for which to build
208 build: TargetSelection,
209 hosts: Vec<TargetSelection>,
210 targets: Vec<TargetSelection>,
212 initial_rustc: PathBuf,
213 initial_cargo: PathBuf,
214 initial_lld: PathBuf,
215 initial_libdir: PathBuf,
217 // Runtime state filled in later on
218 // C/C++ compilers and archiver for all targets
219 cc: HashMap<TargetSelection, cc::Tool>,
220 cxx: HashMap<TargetSelection, cc::Tool>,
221 ar: HashMap<TargetSelection, PathBuf>,
222 ranlib: HashMap<TargetSelection, PathBuf>,
224 // allow bidirectional lookups: both name -> path and path -> name
225 crates: HashMap<Interned<String>, Crate>,
226 crate_paths: HashMap<PathBuf, Interned<String>>,
229 delayed_failures: RefCell<Vec<String>>,
230 prerelease_version: Cell<Option<u32>>,
232 RefCell<HashMap<TargetSelection, HashMap<String, (&'static str, PathBuf, Vec<String>)>>>,
234 #[cfg(feature = "build-metrics")]
235 metrics: metrics::BuildMetrics,
240 name: Interned<String>,
241 deps: HashSet<Interned<String>>,
246 fn local_path(&self, build: &Build) -> PathBuf {
247 self.path.strip_prefix(&build.config.src).unwrap().into()
251 /// When building Rust various objects are handled differently.
252 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
253 pub enum DependencyType {
254 /// Libraries originating from proc-macros.
256 /// Typical Rust libraries.
258 /// Non Rust libraries and objects shipped to ease usage of certain targets.
262 /// The various "modes" of invoking Cargo.
264 /// These entries currently correspond to the various output directories of the
265 /// build system, with each mod generating output in a different directory.
266 #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
268 /// Build the standard library, placing output in the "stageN-std" directory.
271 /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
274 /// Build a codegen backend for rustc, placing the output in the "stageN-codegen" directory.
277 /// Build a tool, placing output in the "stage0-bootstrap-tools"
278 /// directory. This is for miscellaneous sets of tools that are built
279 /// using the bootstrap stage0 compiler in its entirety (target libraries
280 /// and all). Typically these tools compile with stable Rust.
283 /// Build a tool which uses the locally built std, placing output in the
284 /// "stageN-tools" directory. Its usage is quite rare, mainly used by
285 /// compiletest which needs libtest.
288 /// Build a tool which uses the locally built rustc and the target std,
289 /// placing the output in the "stageN-tools" directory. This is used for
290 /// anything that needs a fully functional rustc, such as rustdoc, clippy,
291 /// cargo, rls, rustfmt, miri, etc.
296 pub fn is_tool(&self) -> bool {
297 matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd)
300 pub fn must_support_dlopen(&self) -> bool {
301 matches!(self, Mode::Std | Mode::Codegen)
310 macro_rules! forward {
311 ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
313 $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
314 self.config.$fn( $($param),* )
322 is_verbose() -> bool,
323 create(path: &Path, s: &str),
325 tempdir() -> PathBuf,
326 try_run(cmd: &mut Command) -> bool,
327 llvm_link_shared() -> bool,
328 download_rustc() -> bool,
329 initial_rustfmt() -> Option<PathBuf>,
333 /// Creates a new set of build configuration from the `flags` on the command
334 /// line and the filesystem `config`.
336 /// By default all build output will be placed in the current directory.
337 pub fn new(mut config: Config) -> Build {
338 let src = config.src.clone();
339 let out = config.out.clone();
342 // keep this consistent with the equivalent check in x.py:
343 // https://github.com/rust-lang/rust/blob/a8a33cf27166d3eabaffc58ed3799e054af3b0c6/src/bootstrap/bootstrap.py#L796-L797
344 let is_sudo = match env::var_os("SUDO_USER") {
345 Some(_sudo_user) => {
346 let uid = unsafe { libc::getuid() };
354 let ignore_git = config.ignore_git;
355 let rust_info = channel::GitInfo::new(ignore_git, &src);
356 let cargo_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/cargo"));
357 let rust_analyzer_info =
358 channel::GitInfo::new(ignore_git, &src.join("src/tools/rust-analyzer"));
359 let clippy_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/clippy"));
360 let miri_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/miri"));
361 let rustfmt_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/rustfmt"));
363 // we always try to use git for LLVM builds
364 let in_tree_llvm_info = channel::GitInfo::new(false, &src.join("src/llvm-project"));
366 let initial_target_libdir_str = if config.dry_run() {
367 "/dummy/lib/path/to/lib/".to_string()
370 Command::new(&config.initial_rustc)
372 .arg(config.build.rustc_target_arg())
374 .arg("target-libdir"),
377 let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
378 let initial_lld = initial_target_dir.join("bin").join("rust-lld");
380 let initial_sysroot = if config.dry_run() {
383 output(Command::new(&config.initial_rustc).arg("--print").arg("sysroot"))
385 let initial_libdir = initial_target_dir
390 .strip_prefix(initial_sysroot.trim())
394 let version = std::fs::read_to_string(src.join("src").join("version"))
395 .expect("failed to read src/version");
396 let version = version.trim();
398 let bootstrap_out = std::env::current_exe()
399 .expect("could not determine path to running process")
403 if !bootstrap_out.join(exe("rustc", config.build)).exists() && !cfg!(test) {
404 // this restriction can be lifted whenever https://github.com/rust-lang/rfcs/pull/3028 is implemented
406 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
407 bootstrap_out.display()
411 if rust_info.is_from_tarball() && config.description.is_none() {
412 config.description = Some("built from a source tarball".to_owned());
415 let mut build = Build {
416 initial_rustc: config.initial_rustc.clone(),
417 initial_cargo: config.initial_cargo.clone(),
420 local_rebuild: config.local_rebuild,
421 fail_fast: config.cmd.fail_fast(),
422 doc_tests: config.cmd.doc_tests(),
423 verbosity: config.verbose,
426 hosts: config.hosts.clone(),
427 targets: config.targets.clone(),
430 version: version.to_string(),
444 ranlib: HashMap::new(),
445 crates: HashMap::new(),
446 crate_paths: HashMap::new(),
448 ci_env: CiEnv::current(),
449 delayed_failures: RefCell::new(Vec::new()),
450 prerelease_version: Cell::new(None),
451 tool_artifacts: Default::default(),
453 #[cfg(feature = "build-metrics")]
454 metrics: metrics::BuildMetrics::init(),
457 // If local-rust is the same major.minor as the current version, then force a
459 let local_version_verbose =
460 output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
461 let local_release = local_version_verbose
463 .filter_map(|x| x.strip_prefix("release:"))
467 if local_release.split('.').take(2).eq(version.split('.').take(2)) {
468 build.verbose(&format!("auto-detected local-rebuild {}", local_release));
469 build.local_rebuild = true;
472 build.verbose("finding compilers");
473 cc_detect::find(&mut build);
474 // When running `setup`, the profile is about to change, so any requirements we have now may
475 // be different on the next invocation. Don't check for them until the next time x.py is
476 // run. This is ok because `setup` never runs any build commands, so it won't fail if commands are missing.
478 // Similarly, for `setup` we don't actually need submodules or cargo metadata.
479 if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
480 build.verbose("running sanity check");
481 sanity::check(&mut build);
483 // Make sure we update these before gathering metadata so we don't get an error about missing
485 let rust_submodules = [
486 "src/tools/rust-installer",
491 for s in rust_submodules {
492 build.update_submodule(Path::new(s));
494 // Now, update all existing submodules.
495 build.update_existing_submodules();
497 build.verbose("learning about cargo");
498 metadata::build(&mut build);
501 // Make a symbolic link so we can use a consistent directory in the documentation.
502 let build_triple = build.out.join(&build.build.triple);
503 let host = build.out.join("host");
504 if let Err(e) = symlink_dir(&build.config, &build_triple, &host) {
505 if e.kind() != ErrorKind::AlreadyExists {
507 "symlink_dir({} => {}) failed with {}",
509 build_triple.display(),
518 // modified from `check_submodule` and `update_submodule` in bootstrap.py
519 /// Given a path to the directory of a submodule, update it.
521 /// `relative_path` should be relative to the root of the git repository, not an absolute path.
522 pub(crate) fn update_submodule(&self, relative_path: &Path) {
523 fn dir_is_empty(dir: &Path) -> bool {
524 t!(std::fs::read_dir(dir)).next().is_none()
527 if !self.config.submodules(&self.rust_info()) {
531 let absolute_path = self.config.src.join(relative_path);
533 // NOTE: The check for the empty directory is here because when running x.py the first time,
534 // the submodule won't be checked out. Check it out now so we can build it.
535 if !channel::GitInfo::new(false, &absolute_path).is_managed_git_subrepository()
536 && !dir_is_empty(&absolute_path)
542 let checked_out_hash =
543 output(Command::new("git").args(&["rev-parse", "HEAD"]).current_dir(&absolute_path));
545 let recorded = output(
547 .args(&["ls-tree", "HEAD"])
549 .current_dir(&self.config.src),
551 let actual_hash = recorded
554 .unwrap_or_else(|| panic!("unexpected output `{}`", recorded));
557 if actual_hash == checked_out_hash.trim_end() {
558 // already checked out
562 println!("Updating submodule {}", relative_path.display());
565 .args(&["submodule", "-q", "sync"])
567 .current_dir(&self.config.src),
570 // Try passing `--progress` to start, then run git again without if that fails.
571 let update = |progress: bool| {
572 // Git is buggy and will try to fetch submodules from the tracking branch for *this* repository,
573 // even though that has no relation to the upstream for the submodule.
574 let current_branch = {
578 .args(["symbolic-ref", "--short", "HEAD"])
579 .stderr(Stdio::inherit())
581 let output = t!(output);
582 if output.status.success() {
583 Some(String::from_utf8(output.stdout).unwrap().trim().to_owned())
589 let mut git = self.config.git();
590 if let Some(branch) = current_branch {
591 git.arg("-c").arg(format!("branch.{branch}.remote=origin"));
593 git.args(&["submodule", "update", "--init", "--recursive", "--depth=1"]);
595 git.arg("--progress");
597 git.arg(relative_path);
600 // NOTE: doesn't use `try_run` because this shouldn't print an error if it fails.
601 if !update(true).status().map_or(false, |status| status.success()) {
602 self.run(&mut update(false));
605 // Save any local changes, but avoid running `git stash pop` if there are none (since it will exit with an error).
606 let has_local_modifications = !self.try_run(
608 .args(&["diff-index", "--quiet", "HEAD"])
609 .current_dir(&absolute_path),
611 if has_local_modifications {
612 self.run(Command::new("git").args(&["stash", "push"]).current_dir(&absolute_path));
615 self.run(Command::new("git").args(&["reset", "-q", "--hard"]).current_dir(&absolute_path));
616 self.run(Command::new("git").args(&["clean", "-qdfx"]).current_dir(&absolute_path));
618 if has_local_modifications {
619 self.run(Command::new("git").args(&["stash", "pop"]).current_dir(absolute_path));
623 /// If any submodule has been initialized already, sync it unconditionally.
624 /// This avoids contributors checking in a submodule change by accident.
625 pub fn update_existing_submodules(&self) {
626 // Avoid running git when there isn't a git checkout.
627 if !self.config.submodules(&self.rust_info()) {
633 .args(&["config", "--file"])
634 .arg(&self.config.src.join(".gitmodules"))
635 .args(&["--get-regexp", "path"]),
637 for line in output.lines() {
638 // Look for `submodule.$name.path = $path`
639 // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer`
640 let submodule = Path::new(line.splitn(2, ' ').nth(1).unwrap());
641 // Don't update the submodule unless it's already been cloned.
642 if channel::GitInfo::new(false, submodule).is_managed_git_subrepository() {
643 self.update_submodule(submodule);
648 /// Executes the entire build, as configured by the flags and configuration.
649 pub fn build(&mut self) {
654 if let Subcommand::Format { check, paths } = &self.config.cmd {
655 return format::format(&builder::Builder::new(&self), *check, &paths);
658 // Download rustfmt early so that it can be used in rust-analyzer configs.
659 let _ = &builder::Builder::new(&self).initial_rustfmt();
662 let builder = builder::Builder::new(&self);
663 if let Some(path) = builder.paths.get(0) {
664 if path == Path::new("nonexistent/path/to/trigger/cargo/metadata") {
670 if !self.config.dry_run() {
672 self.config.dry_run = DryRun::SelfCheck;
673 let builder = builder::Builder::new(&self);
674 builder.execute_cli();
676 self.config.dry_run = DryRun::Disabled;
677 let builder = builder::Builder::new(&self);
678 builder.execute_cli();
680 let builder = builder::Builder::new(&self);
681 builder.execute_cli();
684 // Check for postponed failures from `test --no-fail-fast`.
685 let failures = self.delayed_failures.borrow();
686 if failures.len() > 0 {
687 eprintln!("\n{} command(s) did not execute successfully:\n", failures.len());
688 for failure in failures.iter() {
689 eprintln!(" - {}\n", failure);
694 #[cfg(feature = "build-metrics")]
695 self.metrics.persist(self);
698 /// Clear out `dir` if `input` is newer.
700 /// After this executes, it will also ensure that `dir` exists.
701 fn clear_if_dirty(&self, dir: &Path, input: &Path) -> bool {
702 let stamp = dir.join(".stamp");
703 let mut cleared = false;
704 if mtime(&stamp) < mtime(input) {
705 self.verbose(&format!("Dirty - {}", dir.display()));
706 let _ = fs::remove_dir_all(dir);
708 } else if stamp.exists() {
711 t!(fs::create_dir_all(dir));
712 t!(File::create(stamp));
716 fn rust_info(&self) -> &GitInfo {
717 &self.config.rust_info
720 /// Gets the space-separated set of activated features for the standard
722 fn std_features(&self, target: TargetSelection) -> String {
723 let mut features = " panic-unwind".to_string();
725 match self.config.llvm_libunwind(target) {
726 LlvmLibunwind::InTree => features.push_str(" llvm-libunwind"),
727 LlvmLibunwind::System => features.push_str(" system-llvm-libunwind"),
728 LlvmLibunwind::No => {}
730 if self.config.backtrace {
731 features.push_str(" backtrace");
733 if self.config.profiler_enabled(target) {
734 features.push_str(" profiler");
739 /// Gets the space-separated set of activated features for the compiler.
740 fn rustc_features(&self, kind: Kind) -> String {
741 let mut features = vec![];
742 if self.config.jemalloc {
743 features.push("jemalloc");
745 if self.config.llvm_enabled() || kind == Kind::Check {
746 features.push("llvm");
748 // keep in sync with `bootstrap/compile.rs:rustc_cargo_env`
749 if self.config.rustc_parallel {
750 features.push("rustc_use_parallel_compiler");
753 // If debug logging is on, then we want the default for tracing:
754 // https://github.com/tokio-rs/tracing/blob/3dd5c03d907afdf2c39444a29931833335171554/tracing/src/level_filters.rs#L26
755 // which is everything (including debug/trace/etc.)
756 // if its unset, if debug_assertions is on, then debug_logging will also be on
757 // as well as tracing *ignoring* this feature when debug_assertions is on
758 if !self.config.rust_debug_logging {
759 features.push("max_level_info");
765 /// Component directory that Cargo will produce output into (e.g.
767 fn cargo_dir(&self) -> &'static str {
768 if self.config.rust_optimize { "release" } else { "debug" }
771 fn tools_dir(&self, compiler: Compiler) -> PathBuf {
774 .join(&*compiler.host.triple)
775 .join(format!("stage{}-tools-bin", compiler.stage));
776 t!(fs::create_dir_all(&out));
780 /// Returns the root directory for all output generated in a particular
781 /// stage when running with a particular host compiler.
783 /// The mode indicates what the root directory is for.
784 fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
785 let suffix = match mode {
787 Mode::Rustc => "-rustc",
788 Mode::Codegen => "-codegen",
789 Mode::ToolBootstrap => "-bootstrap-tools",
790 Mode::ToolStd | Mode::ToolRustc => "-tools",
792 self.out.join(&*compiler.host.triple).join(format!("stage{}{}", compiler.stage, suffix))
795 /// Returns the root output directory for all Cargo output in a given stage,
796 /// running a particular compiler, whether or not we're building the
797 /// standard library, and targeting the specified architecture.
798 fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
799 self.stage_out(compiler, mode).join(&*target.triple).join(self.cargo_dir())
802 /// Root output directory for LLVM compiled for `target`
804 /// Note that if LLVM is configured externally then the directory returned
805 /// will likely be empty.
806 fn llvm_out(&self, target: TargetSelection) -> PathBuf {
807 self.out.join(&*target.triple).join("llvm")
810 fn lld_out(&self, target: TargetSelection) -> PathBuf {
811 self.out.join(&*target.triple).join("lld")
814 /// Output directory for all documentation for a target
815 fn doc_out(&self, target: TargetSelection) -> PathBuf {
816 self.out.join(&*target.triple).join("doc")
819 /// Output directory for all JSON-formatted documentation for a target
820 fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
821 self.out.join(&*target.triple).join("json-doc")
824 fn test_out(&self, target: TargetSelection) -> PathBuf {
825 self.out.join(&*target.triple).join("test")
828 /// Output directory for all documentation for a target
829 fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
830 self.out.join(&*target.triple).join("compiler-doc")
833 /// Output directory for some generated md crate documentation for a target (temporary)
834 fn md_doc_out(&self, target: TargetSelection) -> Interned<PathBuf> {
835 INTERNER.intern_path(self.out.join(&*target.triple).join("md-doc"))
838 /// Returns `true` if no custom `llvm-config` is set for the specified target.
840 /// If no custom `llvm-config` was specified then Rust's llvm will be used.
841 fn is_rust_llvm(&self, target: TargetSelection) -> bool {
842 match self.config.target_config.get(&target) {
843 Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
844 Some(Target { llvm_config, .. }) => {
845 // If the user set llvm-config we assume Rust is not patched,
846 // but first check to see if it was configured by llvm-from-ci.
847 (self.config.llvm_from_ci && target == self.config.build) || llvm_config.is_none()
853 /// Returns the path to `FileCheck` binary for the specified target
854 fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
855 let target_config = self.config.target_config.get(&target);
856 if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
858 } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
859 let llvm_bindir = output(Command::new(s).arg("--bindir"));
860 let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
861 if filecheck.exists() {
864 // On Fedora the system LLVM installs FileCheck in the
865 // llvm subdirectory of the libdir.
866 let llvm_libdir = output(Command::new(s).arg("--libdir"));
868 Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
869 if lib_filecheck.exists() {
872 // Return the most normal file name, even though
873 // it doesn't exist, so that any error message
879 let base = self.llvm_out(target).join("build");
880 let base = if !self.ninja() && target.contains("msvc") {
881 if self.config.llvm_optimize {
882 if self.config.llvm_release_debuginfo {
883 base.join("RelWithDebInfo")
893 base.join("bin").join(exe("FileCheck", target))
897 /// Directory for libraries built from C/C++ code and shared between stages.
898 fn native_dir(&self, target: TargetSelection) -> PathBuf {
899 self.out.join(&*target.triple).join("native")
902 /// Root output directory for rust_test_helpers library compiled for
904 fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
905 self.native_dir(target).join("rust-test-helpers")
908 /// Adds the `RUST_TEST_THREADS` env var if necessary
909 fn add_rust_test_threads(&self, cmd: &mut Command) {
910 if env::var_os("RUST_TEST_THREADS").is_none() {
911 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
915 /// Returns the libdir of the snapshot compiler.
916 fn rustc_snapshot_libdir(&self) -> PathBuf {
917 self.rustc_snapshot_sysroot().join(libdir(self.config.build))
920 /// Returns the sysroot of the snapshot compiler.
921 fn rustc_snapshot_sysroot(&self) -> &Path {
922 static SYSROOT_CACHE: OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
923 SYSROOT_CACHE.get_or_init(|| {
924 let mut rustc = Command::new(&self.initial_rustc);
925 rustc.args(&["--print", "sysroot"]);
926 output(&mut rustc).trim().into()
930 /// Runs a command, printing out nice contextual information if it fails.
931 fn run(&self, cmd: &mut Command) {
932 if self.config.dry_run() {
935 self.verbose(&format!("running: {:?}", cmd));
936 run(cmd, self.is_verbose())
939 /// Runs a command, printing out nice contextual information if it fails.
940 fn run_quiet(&self, cmd: &mut Command) {
941 if self.config.dry_run() {
944 self.verbose(&format!("running: {:?}", cmd));
948 /// Runs a command, printing out nice contextual information if it fails.
949 /// Exits if the command failed to execute at all, otherwise returns its
950 /// `status.success()`.
951 fn try_run_quiet(&self, cmd: &mut Command) -> bool {
952 if self.config.dry_run() {
955 self.verbose(&format!("running: {:?}", cmd));
956 try_run_suppressed(cmd)
959 pub fn is_verbose_than(&self, level: usize) -> bool {
960 self.verbosity > level
963 /// Prints a message if this build is configured in more verbose mode than `level`.
964 fn verbose_than(&self, level: usize, msg: &str) {
965 if self.is_verbose_than(level) {
970 fn info(&self, msg: &str) {
971 match self.config.dry_run {
972 DryRun::SelfCheck => return,
973 DryRun::Disabled | DryRun::UserSelected => {
979 /// Returns the number of parallel jobs that have been configured for this
981 fn jobs(&self) -> u32 {
982 self.config.jobs.unwrap_or_else(|| {
983 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
987 fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
988 if !self.config.rust_remap_debuginfo {
994 let sha = self.rust_sha().unwrap_or(&self.version);
995 Some(format!("/rustc/{}", sha))
997 GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1001 /// Returns the path to the C compiler for the target specified.
1002 fn cc(&self, target: TargetSelection) -> &Path {
1003 self.cc[&target].path()
1006 /// Returns a list of flags to pass to the C compiler for the target
1008 fn cflags(&self, target: TargetSelection, which: GitRepo, c: CLang) -> Vec<String> {
1009 let base = match c {
1010 CLang::C => &self.cc[&target],
1011 CLang::Cxx => &self.cxx[&target],
1014 // Filter out -O and /O (the optimization flags) that we picked up from
1015 // cc-rs because the build scripts will determine that for themselves.
1019 .map(|s| s.to_string_lossy().into_owned())
1020 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1021 .collect::<Vec<String>>();
1023 // If we're compiling on macOS then we add a few unconditional flags
1024 // indicating that we want libc++ (more filled out than libstdc++) and
1025 // we want to compile for 10.7. This way we can ensure that
1026 // LLVM/etc are all properly compiled.
1027 if target.contains("apple-darwin") {
1028 base.push("-stdlib=libc++".into());
1031 // Work around an apparently bad MinGW / GCC optimization,
1032 // See: https://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
1033 // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
1034 if &*target.triple == "i686-pc-windows-gnu" {
1035 base.push("-fno-omit-frame-pointer".into());
1038 if let Some(map_to) = self.debuginfo_map_to(which) {
1039 let map = format!("{}={}", self.src.display(), map_to);
1040 let cc = self.cc(target);
1041 if cc.ends_with("clang") || cc.ends_with("gcc") {
1042 base.push(format!("-fdebug-prefix-map={}", map));
1043 } else if cc.ends_with("clang-cl.exe") {
1044 base.push("-Xclang".into());
1045 base.push(format!("-fdebug-prefix-map={}", map));
1051 /// Returns the path to the `ar` archive utility for the target specified.
1052 fn ar(&self, target: TargetSelection) -> Option<&Path> {
1053 self.ar.get(&target).map(|p| &**p)
1056 /// Returns the path to the `ranlib` utility for the target specified.
1057 fn ranlib(&self, target: TargetSelection) -> Option<&Path> {
1058 self.ranlib.get(&target).map(|p| &**p)
1061 /// Returns the path to the C++ compiler for the target specified.
1062 fn cxx(&self, target: TargetSelection) -> Result<&Path, String> {
1063 match self.cxx.get(&target) {
1064 Some(p) => Ok(p.path()),
1066 Err(format!("target `{}` is not configured as a host, only as a target", target))
1071 /// Returns the path to the linker for the given target if it needs to be overridden.
1072 fn linker(&self, target: TargetSelection) -> Option<&Path> {
1073 if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.as_ref())
1076 } else if target.contains("vxworks") {
1077 // need to use CXX compiler as linker to resolve the exception functions
1078 // that are only existed in CXX libraries
1079 Some(self.cxx[&target].path())
1080 } else if target != self.config.build
1081 && util::use_host_linker(target)
1082 && !target.contains("msvc")
1084 Some(self.cc(target))
1085 } else if self.config.use_lld && !self.is_fuse_ld_lld(target) && self.build == target {
1086 Some(&self.initial_lld)
1092 // LLD is used through `-fuse-ld=lld` rather than directly.
1093 // Only MSVC targets use LLD directly at the moment.
1094 fn is_fuse_ld_lld(&self, target: TargetSelection) -> bool {
1095 self.config.use_lld && !target.contains("msvc")
1098 fn lld_flags(&self, target: TargetSelection) -> impl Iterator<Item = String> {
1099 let mut options = [None, None];
1101 if self.config.use_lld {
1102 if self.is_fuse_ld_lld(target) {
1103 options[0] = Some("-Clink-arg=-fuse-ld=lld".to_string());
1106 let no_threads = util::lld_flag_no_threads(target.contains("windows"));
1107 options[1] = Some(format!("-Clink-arg=-Wl,{}", no_threads));
1110 IntoIterator::into_iter(options).flatten()
1113 /// Returns if this target should statically link the C runtime, if specified
1114 fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1115 if target.contains("pc-windows-msvc") {
1118 self.config.target_config.get(&target).and_then(|t| t.crt_static)
1122 /// Returns the "musl root" for this `target`, if defined
1123 fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1127 .and_then(|t| t.musl_root.as_ref())
1128 .or_else(|| self.config.musl_root.as_ref())
1132 /// Returns the "musl libdir" for this `target`.
1133 fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1134 let t = self.config.target_config.get(&target)?;
1135 if let libdir @ Some(_) = &t.musl_libdir {
1136 return libdir.clone();
1138 self.musl_root(target).map(|root| root.join("lib"))
1141 /// Returns the sysroot for the wasi target, if defined
1142 fn wasi_root(&self, target: TargetSelection) -> Option<&Path> {
1143 self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p)
1146 /// Returns `true` if this is a no-std `target`, if defined
1147 fn no_std(&self, target: TargetSelection) -> Option<bool> {
1148 self.config.target_config.get(&target).map(|t| t.no_std)
1151 /// Returns `true` if the target will be tested using the `remote-test-client`
1152 /// and `remote-test-server` binaries.
1153 fn remote_tested(&self, target: TargetSelection) -> bool {
1154 self.qemu_rootfs(target).is_some()
1155 || target.contains("android")
1156 || env::var_os("TEST_DEVICE_ADDR").is_some()
1159 /// Returns the root of the "rootfs" image that this target will be using,
1160 /// if one was configured.
1162 /// If `Some` is returned then that means that tests for this target are
1163 /// emulated with QEMU and binaries will need to be shipped to the emulator.
1164 fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1165 self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1168 /// Path to the python interpreter to use
1169 fn python(&self) -> &Path {
1170 if self.config.build.ends_with("apple-darwin") {
1171 // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1172 // LLDB plugin's compiled module which only works with the system python
1173 // (namely not Homebrew-installed python)
1174 Path::new("/usr/bin/python3")
1179 .expect("python is required for running LLDB or rustdoc tests")
1183 /// Temporary directory that extended error information is emitted to.
1184 fn extended_error_dir(&self) -> PathBuf {
1185 self.out.join("tmp/extended-error-metadata")
1188 /// Tests whether the `compiler` compiling for `target` should be forced to
1189 /// use a stage1 compiler instead.
1191 /// Currently, by default, the build system does not perform a "full
1192 /// bootstrap" by default where we compile the compiler three times.
1193 /// Instead, we compile the compiler two times. The final stage (stage2)
1194 /// just copies the libraries from the previous stage, which is what this
1197 /// Here we return `true` if:
1199 /// * The build isn't performing a full bootstrap
1200 /// * The `compiler` is in the final stage, 2
1201 /// * We're not cross-compiling, so the artifacts are already available in
1204 /// When all of these conditions are met the build will lift artifacts from
1205 /// the previous stage forward.
1206 fn force_use_stage1(&self, compiler: Compiler, target: TargetSelection) -> bool {
1207 !self.config.full_bootstrap
1208 && compiler.stage >= 2
1209 && (self.hosts.iter().any(|h| *h == target) || target == self.build)
1212 /// Given `num` in the form "a.b.c" return a "release string" which
1213 /// describes the release version number.
1215 /// For example on nightly this returns "a.b.c-nightly", on beta it returns
1216 /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
1217 fn release(&self, num: &str) -> String {
1218 match &self.config.channel[..] {
1219 "stable" => num.to_string(),
1221 if self.rust_info().is_managed_git_subrepository() && !self.config.ignore_git {
1222 format!("{}-beta.{}", num, self.beta_prerelease_version())
1224 format!("{}-beta", num)
1227 "nightly" => format!("{}-nightly", num),
1228 _ => format!("{}-dev", num),
1232 fn beta_prerelease_version(&self) -> u32 {
1233 if let Some(s) = self.prerelease_version.get() {
1237 // Figure out how many merge commits happened since we branched off master.
1238 // That's our beta number!
1239 // (Note that we use a `..` range, not the `...` symmetric difference.)
1241 output(self.config.git().arg("rev-list").arg("--count").arg("--merges").arg(format!(
1242 "refs/remotes/origin/{}..HEAD",
1243 self.config.stage0_metadata.config.nightly_branch
1245 let n = count.trim().parse().unwrap();
1246 self.prerelease_version.set(Some(n));
1250 /// Returns the value of `release` above for Rust itself.
1251 fn rust_release(&self) -> String {
1252 self.release(&self.version)
1255 /// Returns the "package version" for a component given the `num` release
1258 /// The package version is typically what shows up in the names of tarballs.
1259 /// For channels like beta/nightly it's just the channel name, otherwise
1260 /// it's the `num` provided.
1261 fn package_vers(&self, num: &str) -> String {
1262 match &self.config.channel[..] {
1263 "stable" => num.to_string(),
1264 "beta" => "beta".to_string(),
1265 "nightly" => "nightly".to_string(),
1266 _ => format!("{}-dev", num),
1270 /// Returns the value of `package_vers` above for Rust itself.
1271 fn rust_package_vers(&self) -> String {
1272 self.package_vers(&self.version)
1275 /// Returns the `version` string associated with this compiler for Rust
1278 /// Note that this is a descriptive string which includes the commit date,
1279 /// sha, version, etc.
1280 fn rust_version(&self) -> String {
1281 let mut version = self.rust_info().version(self, &self.version);
1282 if let Some(ref s) = self.config.description {
1283 version.push_str(" (");
1284 version.push_str(s);
1290 /// Returns the full commit hash.
1291 fn rust_sha(&self) -> Option<&str> {
1292 self.rust_info().sha()
1295 /// Returns the `a.b.c` version that the given package is at.
1296 fn release_num(&self, package: &str) -> String {
1297 let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
1298 let toml = t!(fs::read_to_string(&toml_file_name));
1299 for line in toml.lines() {
1300 if let Some(stripped) =
1301 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix("\""))
1303 return stripped.to_owned();
1307 panic!("failed to find version in {}'s Cargo.toml", package)
1310 /// Returns `true` if unstable features should be enabled for the compiler
1312 fn unstable_features(&self) -> bool {
1313 match &self.config.channel[..] {
1314 "stable" | "beta" => false,
1315 "nightly" | _ => true,
1319 /// Returns a Vec of all the dependencies of the given root crate,
1320 /// including transitive dependencies and the root itself. Only includes
1321 /// "local" crates (those in the local source tree, not from a registry).
1322 fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1323 let mut ret = Vec::new();
1324 let mut list = vec![INTERNER.intern_str(root)];
1325 let mut visited = HashSet::new();
1326 while let Some(krate) = list.pop() {
1330 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1332 for dep in &krate.deps {
1333 if !self.crates.contains_key(dep) {
1334 // Ignore non-workspace members.
1337 // Don't include optional deps if their features are not
1338 // enabled. Ideally this would be computed from `cargo
1339 // metadata --features …`, but that is somewhat slow. In
1340 // the future, we may want to consider just filtering all
1341 // build and dev dependencies in metadata::build.
1342 if visited.insert(dep)
1343 && (dep != "profiler_builtins"
1345 .map(|t| self.config.profiler_enabled(t))
1346 .unwrap_or_else(|| self.config.any_profiler_enabled()))
1347 && (dep != "rustc_codegen_llvm" || self.config.llvm_enabled())
1356 fn read_stamp_file(&self, stamp: &Path) -> Vec<(PathBuf, DependencyType)> {
1357 if self.config.dry_run() {
1361 if !stamp.exists() {
1363 "Error: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1366 crate::detail_exit(1);
1369 let mut paths = Vec::new();
1370 let contents = t!(fs::read(stamp), &stamp);
1371 // This is the method we use for extracting paths from the stamp file passed to us. See
1372 // run_cargo for more information (in compile.rs).
1373 for part in contents.split(|b| *b == 0) {
1374 if part.is_empty() {
1377 let dependency_type = match part[0] as char {
1378 'h' => DependencyType::Host,
1379 's' => DependencyType::TargetSelfContained,
1380 't' => DependencyType::Target,
1381 _ => unreachable!(),
1383 let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1384 paths.push((path, dependency_type));
1389 /// Copies a file from `src` to `dst`
1390 pub fn copy(&self, src: &Path, dst: &Path) {
1391 self.copy_internal(src, dst, false);
1394 fn copy_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1395 if self.config.dry_run() {
1398 self.verbose_than(1, &format!("Copy {:?} to {:?}", src, dst));
1402 let _ = fs::remove_file(&dst);
1403 let metadata = t!(src.symlink_metadata());
1404 let mut src = src.to_path_buf();
1405 if metadata.file_type().is_symlink() {
1406 if dereference_symlinks {
1407 src = t!(fs::canonicalize(src));
1409 let link = t!(fs::read_link(src));
1410 t!(self.symlink_file(link, dst));
1414 if let Ok(()) = fs::hard_link(&src, dst) {
1415 // Attempt to "easy copy" by creating a hard link
1416 // (symlinks don't work on windows), but if that fails
1417 // just fall back to a slow `copy` operation.
1419 if let Err(e) = fs::copy(&src, dst) {
1420 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1422 t!(fs::set_permissions(dst, metadata.permissions()));
1423 let atime = FileTime::from_last_access_time(&metadata);
1424 let mtime = FileTime::from_last_modification_time(&metadata);
1425 t!(filetime::set_file_times(dst, atime, mtime));
1429 /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1430 /// when this function is called.
1431 pub fn cp_r(&self, src: &Path, dst: &Path) {
1432 if self.config.dry_run() {
1435 for f in self.read_dir(src) {
1436 let path = f.path();
1437 let name = path.file_name().unwrap();
1438 let dst = dst.join(name);
1439 if t!(f.file_type()).is_dir() {
1440 t!(fs::create_dir_all(&dst));
1441 self.cp_r(&path, &dst);
1443 let _ = fs::remove_file(&dst);
1444 self.copy(&path, &dst);
1449 /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1450 /// when this function is called. Unwanted files or directories can be skipped
1451 /// by returning `false` from the filter function.
1452 pub fn cp_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1453 // Immediately recurse with an empty relative path
1454 self.recurse_(src, dst, Path::new(""), filter)
1457 // Inner function does the actual work
1458 fn recurse_(&self, src: &Path, dst: &Path, relative: &Path, filter: &dyn Fn(&Path) -> bool) {
1459 for f in self.read_dir(src) {
1460 let path = f.path();
1461 let name = path.file_name().unwrap();
1462 let dst = dst.join(name);
1463 let relative = relative.join(name);
1464 // Only copy file or directory if the filter function returns true
1465 if filter(&relative) {
1466 if t!(f.file_type()).is_dir() {
1467 let _ = fs::remove_dir_all(&dst);
1468 self.create_dir(&dst);
1469 self.recurse_(&path, &dst, &relative, filter);
1471 let _ = fs::remove_file(&dst);
1472 self.copy(&path, &dst);
1478 fn copy_to_folder(&self, src: &Path, dest_folder: &Path) {
1479 let file_name = src.file_name().unwrap();
1480 let dest = dest_folder.join(file_name);
1481 self.copy(src, &dest);
1484 fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1485 if self.config.dry_run() {
1488 let dst = dstdir.join(src.file_name().unwrap());
1489 self.verbose_than(1, &format!("Install {:?} to {:?}", src, dst));
1490 t!(fs::create_dir_all(dstdir));
1492 panic!("Error: File \"{}\" not found!", src.display());
1494 self.copy_internal(src, &dst, true);
1498 fn read(&self, path: &Path) -> String {
1499 if self.config.dry_run() {
1500 return String::new();
1502 t!(fs::read_to_string(path))
1505 fn create_dir(&self, dir: &Path) {
1506 if self.config.dry_run() {
1509 t!(fs::create_dir_all(dir))
1512 fn remove_dir(&self, dir: &Path) {
1513 if self.config.dry_run() {
1516 t!(fs::remove_dir_all(dir))
1519 fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1520 let iter = match fs::read_dir(dir) {
1522 Err(_) if self.config.dry_run() => return vec![].into_iter(),
1523 Err(err) => panic!("could not read dir {:?}: {:?}", dir, err),
1525 iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1528 fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1530 use std::os::unix::fs::symlink as symlink_file;
1532 use std::os::windows::fs::symlink_file;
1533 if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1536 /// Returns if config.ninja is enabled, and checks for ninja existence,
1537 /// exiting with a nicer error message if not.
1538 fn ninja(&self) -> bool {
1539 let mut cmd_finder = crate::sanity::Finder::new();
1541 if self.config.ninja_in_file {
1542 // Some Linux distros rename `ninja` to `ninja-build`.
1543 // CMake can work with either binary name.
1544 if cmd_finder.maybe_have("ninja-build").is_none()
1545 && cmd_finder.maybe_have("ninja").is_none()
1549 Couldn't find required command: ninja (or ninja-build)
1551 You should install ninja as described at
1552 <https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1553 or set `ninja = false` in the `[llvm]` section of `config.toml`.
1554 Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1555 to download LLVM rather than building it.
1562 // If ninja isn't enabled but we're building for MSVC then we try
1563 // doubly hard to enable it. It was realized in #43767 that the msbuild
1564 // CMake generator for MSVC doesn't respect configuration options like
1565 // disabling LLVM assertions, which can often be quite important!
1567 // In these cases we automatically enable Ninja if we find it in the
1569 if !self.config.ninja_in_file && self.config.build.contains("msvc") {
1570 if cmd_finder.maybe_have("ninja").is_some() {
1575 self.config.ninja_in_file
1580 fn chmod(path: &Path, perms: u32) {
1581 use std::os::unix::fs::*;
1582 t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1585 fn chmod(_path: &Path, _perms: u32) {}
1587 /// If code is not 0 (successful exit status), exit status is 101 (rust's default error code.)
1588 /// If the test is running and code is an error code, it will cause a panic.
1589 fn detail_exit(code: i32) -> ! {
1590 // if in test and code is an error code, panic with status code provided
1592 panic!("status code: {}", code);
1594 // otherwise,exit with provided status code
1595 std::process::exit(code);
1600 pub fn with_stage(mut self, stage: u32) -> Compiler {
1605 /// Returns `true` if this is a snapshot compiler for `build`'s configuration
1606 pub fn is_snapshot(&self, build: &Build) -> bool {
1607 self.stage == 0 && self.host == build.build
1610 /// Returns if this compiler should be treated as a final stage one in the
1611 /// current build session.
1612 /// This takes into account whether we're performing a full bootstrap or
1613 /// not; don't directly compare the stage with `2`!
1614 pub fn is_final_stage(&self, build: &Build) -> bool {
1615 let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
1616 self.stage >= final_stage
1620 fn envify(s: &str) -> String {
1626 .flat_map(|c| c.to_uppercase())