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
::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
,
68 #[cfg(feature = "build-metrics")]
74 #[cfg(all(unix, not(target_os = "haiku")))]
76 pub unsafe fn setup(build
: &mut crate::Build
) {
77 if build
.config
.low_priority
{
78 libc
::setpriority(libc
::PRIO_PGRP
as _
, 0, 10);
83 #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))]
85 pub unsafe fn setup(_build
: &mut crate::Build
) {}
88 pub use crate::builder
::PathSet
;
89 use crate::cache
::{Interned, INTERNER}
;
90 pub use crate::config
::Config
;
91 pub use crate::flags
::Subcommand
;
92 use termcolor
::{ColorChoice, StandardStream, WriteColor}
;
94 const LLVM_TOOLS
: &[&str] = &[
95 "llvm-cov", // used to generate coverage report
96 "llvm-nm", // used to inspect binaries; it shows symbol names, their sizes and visibility
97 "llvm-objcopy", // used to transform ELFs into binary format which flashing tools consume
98 "llvm-objdump", // used to disassemble programs
99 "llvm-profdata", // used to inspect and merge files generated by profiles
100 "llvm-readobj", // used to get information from ELFs/objects that the other tools don't provide
101 "llvm-size", // used to prints the size of the linker sections of a program
102 "llvm-strip", // used to discard symbols from binary files to reduce their size
103 "llvm-ar", // used for creating and modifying archive files
104 "llvm-as", // used to convert LLVM assembly to LLVM bitcode
105 "llvm-dis", // used to disassemble LLVM bitcode
106 "llc", // used to compile LLVM bytecode
107 "opt", // used to optimize LLVM bytecode
110 /// LLD file names for all flavors.
111 const LLD_FILE_NAMES
: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
113 pub const VERSION
: usize = 2;
115 /// Extra --check-cfg to add when building
116 /// (Mode restriction, config name, config values (if any))
117 const EXTRA_CHECK_CFGS
: &[(Option
<Mode
>, &'
static str, Option
<&[&'
static str]>)] = &[
118 (None
, "bootstrap", None
),
119 (Some(Mode
::Rustc
), "parallel_compiler", None
),
120 (Some(Mode
::ToolRustc
), "parallel_compiler", None
),
121 (Some(Mode
::Codegen
), "parallel_compiler", None
),
122 (Some(Mode
::Std
), "stdarch_intel_sde", None
),
123 (Some(Mode
::Std
), "no_fp_fmt_parse", None
),
124 (Some(Mode
::Std
), "no_global_oom_handling", None
),
125 (Some(Mode
::Std
), "no_rc", None
),
126 (Some(Mode
::Std
), "no_sync", None
),
127 (Some(Mode
::Std
), "freebsd12", None
),
128 (Some(Mode
::Std
), "freebsd13", None
),
129 (Some(Mode
::Std
), "backtrace_in_libstd", None
),
130 /* Extra values not defined in the built-in targets yet, but used in std */
131 (Some(Mode
::Std
), "target_env", Some(&["libnx"])),
132 // (Some(Mode::Std), "target_os", Some(&[])),
133 // #[cfg(bootstrap)] loongarch64
134 (Some(Mode
::Std
), "target_arch", Some(&["asmjs", "spirv", "nvptx", "xtensa", "loongarch64"])),
135 /* Extra names used by dependencies */
136 // FIXME: Used by serde_json, but we should not be triggering on external dependencies.
137 (Some(Mode
::Rustc
), "no_btreemap_remove_entry", None
),
138 (Some(Mode
::ToolRustc
), "no_btreemap_remove_entry", None
),
139 // FIXME: Used by crossbeam-utils, but we should not be triggering on external dependencies.
140 (Some(Mode
::Rustc
), "crossbeam_loom", None
),
141 (Some(Mode
::ToolRustc
), "crossbeam_loom", None
),
142 // FIXME: Used by proc-macro2, but we should not be triggering on external dependencies.
143 (Some(Mode
::Rustc
), "span_locations", None
),
144 (Some(Mode
::ToolRustc
), "span_locations", None
),
145 // FIXME: Used by rustix, but we should not be triggering on external dependencies.
146 (Some(Mode
::Rustc
), "rustix_use_libc", None
),
147 (Some(Mode
::ToolRustc
), "rustix_use_libc", None
),
148 // FIXME: Used by filetime, but we should not be triggering on external dependencies.
149 (Some(Mode
::Rustc
), "emulate_second_only_system", None
),
150 (Some(Mode
::ToolRustc
), "emulate_second_only_system", None
),
151 // Needed to avoid the need to copy windows.lib into the sysroot.
152 (Some(Mode
::Rustc
), "windows_raw_dylib", None
),
153 (Some(Mode
::ToolRustc
), "windows_raw_dylib", None
),
154 // #[cfg(bootstrap)] ohos
155 (Some(Mode
::Std
), "target_env", Some(&["ohos"])),
158 /// A structure representing a Rust compiler.
160 /// Each compiler has a `stage` that it is associated with and a `host` that
161 /// corresponds to the platform the compiler runs on. This structure is used as
162 /// a parameter to many methods below.
163 #[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
164 pub struct Compiler
{
166 host
: TargetSelection
,
169 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
171 /// Run normal tests and doc tests (default).
173 /// Do not run any doc tests.
175 /// Only run doc tests.
184 /// Global configuration for the build system.
186 /// This structure transitively contains all configuration for the build system.
187 /// All filesystem-encoded configuration is in `config`, all flags are in
188 /// `flags`, and then parsed or probed information is listed in the keys below.
190 /// This structure is a parameter of almost all methods in the build system,
191 /// although most functions are implemented as free functions rather than
192 /// methods specifically on this structure itself (to make it easier to
194 #[cfg_attr(not(feature = "build-metrics"), derive(Clone))]
196 /// User-specified configuration from `config.toml`.
199 // Version information
202 // Properties derived from the above configuration
205 bootstrap_out
: PathBuf
,
206 cargo_info
: channel
::GitInfo
,
207 rust_analyzer_info
: channel
::GitInfo
,
208 clippy_info
: channel
::GitInfo
,
209 miri_info
: channel
::GitInfo
,
210 rustfmt_info
: channel
::GitInfo
,
211 in_tree_llvm_info
: channel
::GitInfo
,
217 // Targets for which to build
218 build
: TargetSelection
,
219 hosts
: Vec
<TargetSelection
>,
220 targets
: Vec
<TargetSelection
>,
222 initial_rustc
: PathBuf
,
223 initial_cargo
: PathBuf
,
224 initial_lld
: PathBuf
,
225 initial_libdir
: PathBuf
,
227 // Runtime state filled in later on
228 // C/C++ compilers and archiver for all targets
229 cc
: HashMap
<TargetSelection
, cc
::Tool
>,
230 cxx
: HashMap
<TargetSelection
, cc
::Tool
>,
231 ar
: HashMap
<TargetSelection
, PathBuf
>,
232 ranlib
: HashMap
<TargetSelection
, PathBuf
>,
234 // allow bidirectional lookups: both name -> path and path -> name
235 crates
: HashMap
<Interned
<String
>, Crate
>,
236 crate_paths
: HashMap
<PathBuf
, Interned
<String
>>,
239 delayed_failures
: RefCell
<Vec
<String
>>,
240 prerelease_version
: Cell
<Option
<u32>>,
242 RefCell
<HashMap
<TargetSelection
, HashMap
<String
, (&'
static str, PathBuf
, Vec
<String
>)>>>,
244 #[cfg(feature = "build-metrics")]
245 metrics
: metrics
::BuildMetrics
,
248 #[derive(Debug, Clone)]
250 name
: Interned
<String
>,
251 deps
: HashSet
<Interned
<String
>>,
256 fn local_path(&self, build
: &Build
) -> PathBuf
{
257 self.path
.strip_prefix(&build
.config
.src
).unwrap().into()
261 /// When building Rust various objects are handled differently.
262 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
263 pub enum DependencyType
{
264 /// Libraries originating from proc-macros.
266 /// Typical Rust libraries.
268 /// Non Rust libraries and objects shipped to ease usage of certain targets.
272 /// The various "modes" of invoking Cargo.
274 /// These entries currently correspond to the various output directories of the
275 /// build system, with each mod generating output in a different directory.
276 #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
278 /// Build the standard library, placing output in the "stageN-std" directory.
281 /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
284 /// Build a codegen backend for rustc, placing the output in the "stageN-codegen" directory.
287 /// Build a tool, placing output in the "stage0-bootstrap-tools"
288 /// directory. This is for miscellaneous sets of tools that are built
289 /// using the bootstrap stage0 compiler in its entirety (target libraries
290 /// and all). Typically these tools compile with stable Rust.
293 /// Build a tool which uses the locally built std, placing output in the
294 /// "stageN-tools" directory. Its usage is quite rare, mainly used by
295 /// compiletest which needs libtest.
298 /// Build a tool which uses the locally built rustc and the target std,
299 /// placing the output in the "stageN-tools" directory. This is used for
300 /// anything that needs a fully functional rustc, such as rustdoc, clippy,
301 /// cargo, rls, rustfmt, miri, etc.
306 pub fn is_tool(&self) -> bool
{
307 matches
!(self, Mode
::ToolBootstrap
| Mode
::ToolRustc
| Mode
::ToolStd
)
310 pub fn must_support_dlopen(&self) -> bool
{
311 matches
!(self, Mode
::Std
| Mode
::Codegen
)
320 macro_rules
! forward
{
321 ( $
( $
fn:ident( $
($param
:ident
: $ty
:ty
),* ) $
( -> $ret
:ty
)?
),+ $
(,)?
) => {
323 $
( fn $
fn(&self, $
($param
: $ty
),* ) $
( -> $ret
)?
{
324 self.config
.$
fn( $
($param
),* )
332 is_verbose() -> bool
,
333 create(path
: &Path
, s
: &str),
335 tempdir() -> PathBuf
,
336 try_run(cmd
: &mut Command
) -> bool
,
337 llvm_link_shared() -> bool
,
338 download_rustc() -> bool
,
339 initial_rustfmt() -> Option
<PathBuf
>,
343 /// Creates a new set of build configuration from the `flags` on the command
344 /// line and the filesystem `config`.
346 /// By default all build output will be placed in the current directory.
347 pub fn new(mut config
: Config
) -> Build
{
348 let src
= config
.src
.clone();
349 let out
= config
.out
.clone();
352 // keep this consistent with the equivalent check in x.py:
353 // https://github.com/rust-lang/rust/blob/a8a33cf27166d3eabaffc58ed3799e054af3b0c6/src/bootstrap/bootstrap.py#L796-L797
354 let is_sudo
= match env
::var_os("SUDO_USER") {
355 Some(_sudo_user
) => {
356 let uid
= unsafe { libc::getuid() }
;
364 let omit_git_hash
= config
.omit_git_hash
;
365 let rust_info
= channel
::GitInfo
::new(omit_git_hash
, &src
);
366 let cargo_info
= channel
::GitInfo
::new(omit_git_hash
, &src
.join("src/tools/cargo"));
367 let rust_analyzer_info
=
368 channel
::GitInfo
::new(omit_git_hash
, &src
.join("src/tools/rust-analyzer"));
369 let clippy_info
= channel
::GitInfo
::new(omit_git_hash
, &src
.join("src/tools/clippy"));
370 let miri_info
= channel
::GitInfo
::new(omit_git_hash
, &src
.join("src/tools/miri"));
371 let rustfmt_info
= channel
::GitInfo
::new(omit_git_hash
, &src
.join("src/tools/rustfmt"));
373 // we always try to use git for LLVM builds
374 let in_tree_llvm_info
= channel
::GitInfo
::new(false, &src
.join("src/llvm-project"));
376 let initial_target_libdir_str
= if config
.dry_run() {
377 "/dummy/lib/path/to/lib/".to_string()
380 Command
::new(&config
.initial_rustc
)
382 .arg(config
.build
.rustc_target_arg())
384 .arg("target-libdir"),
387 let initial_target_dir
= Path
::new(&initial_target_libdir_str
).parent().unwrap();
388 let initial_lld
= initial_target_dir
.join("bin").join("rust-lld");
390 let initial_sysroot
= if config
.dry_run() {
393 output(Command
::new(&config
.initial_rustc
).arg("--print").arg("sysroot"))
395 let initial_libdir
= initial_target_dir
400 .strip_prefix(initial_sysroot
.trim())
404 let version
= std
::fs
::read_to_string(src
.join("src").join("version"))
405 .expect("failed to read src/version");
406 let version
= version
.trim();
408 let bootstrap_out
= std
::env
::current_exe()
409 .expect("could not determine path to running process")
413 if !bootstrap_out
.join(exe("rustc", config
.build
)).exists() && !cfg
!(test
) {
414 // this restriction can be lifted whenever https://github.com/rust-lang/rfcs/pull/3028 is implemented
416 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
417 bootstrap_out
.display()
421 if rust_info
.is_from_tarball() && config
.description
.is_none() {
422 config
.description
= Some("built from a source tarball".to_owned());
425 let mut build
= Build
{
426 initial_rustc
: config
.initial_rustc
.clone(),
427 initial_cargo
: config
.initial_cargo
.clone(),
430 local_rebuild
: config
.local_rebuild
,
431 fail_fast
: config
.cmd
.fail_fast(),
432 doc_tests
: config
.cmd
.doc_tests(),
433 verbosity
: config
.verbose
,
436 hosts
: config
.hosts
.clone(),
437 targets
: config
.targets
.clone(),
440 version
: version
.to_string(),
454 ranlib
: HashMap
::new(),
455 crates
: HashMap
::new(),
456 crate_paths
: HashMap
::new(),
458 ci_env
: CiEnv
::current(),
459 delayed_failures
: RefCell
::new(Vec
::new()),
460 prerelease_version
: Cell
::new(None
),
461 tool_artifacts
: Default
::default(),
463 #[cfg(feature = "build-metrics")]
464 metrics
: metrics
::BuildMetrics
::init(),
467 // If local-rust is the same major.minor as the current version, then force a
469 let local_version_verbose
=
470 output(Command
::new(&build
.initial_rustc
).arg("--version").arg("--verbose"));
471 let local_release
= local_version_verbose
473 .filter_map(|x
| x
.strip_prefix("release:"))
477 if local_release
.split('
.'
).take(2).eq(version
.split('
.'
).take(2)) {
478 build
.verbose(&format
!("auto-detected local-rebuild {}", local_release
));
479 build
.local_rebuild
= true;
482 build
.verbose("finding compilers");
483 cc_detect
::find(&mut build
);
484 // When running `setup`, the profile is about to change, so any requirements we have now may
485 // be different on the next invocation. Don't check for them until the next time x.py is
486 // run. This is ok because `setup` never runs any build commands, so it won't fail if commands are missing.
488 // Similarly, for `setup` we don't actually need submodules or cargo metadata.
489 if !matches
!(build
.config
.cmd
, Subcommand
::Setup { .. }
) {
490 build
.verbose("running sanity check");
491 sanity
::check(&mut build
);
493 // Make sure we update these before gathering metadata so we don't get an error about missing
495 let rust_submodules
= ["src/tools/cargo", "library/backtrace", "library/stdarch"];
496 for s
in rust_submodules
{
497 build
.update_submodule(Path
::new(s
));
499 // Now, update all existing submodules.
500 build
.update_existing_submodules();
502 build
.verbose("learning about cargo");
503 metadata
::build(&mut build
);
506 // Make a symbolic link so we can use a consistent directory in the documentation.
507 let build_triple
= build
.out
.join(&build
.build
.triple
);
508 t
!(fs
::create_dir_all(&build_triple
));
509 let host
= build
.out
.join("host");
510 if host
.is_symlink() {
511 // Left over from a previous build; overwrite it.
512 // This matters if `build.build` has changed between invocations.
514 t
!(fs
::remove_dir(&host
));
516 t
!(fs
::remove_file(&host
));
519 symlink_dir(&build
.config
, &build_triple
, &host
),
520 format
!("symlink_dir({} => {}) failed", host
.display(), build_triple
.display())
526 // modified from `check_submodule` and `update_submodule` in bootstrap.py
527 /// Given a path to the directory of a submodule, update it.
529 /// `relative_path` should be relative to the root of the git repository, not an absolute path.
530 pub(crate) fn update_submodule(&self, relative_path
: &Path
) {
531 fn dir_is_empty(dir
: &Path
) -> bool
{
532 t
!(std
::fs
::read_dir(dir
)).next().is_none()
535 if !self.config
.submodules(&self.rust_info()) {
539 let absolute_path
= self.config
.src
.join(relative_path
);
541 // NOTE: The check for the empty directory is here because when running x.py the first time,
542 // the submodule won't be checked out. Check it out now so we can build it.
543 if !channel
::GitInfo
::new(false, &absolute_path
).is_managed_git_subrepository()
544 && !dir_is_empty(&absolute_path
)
550 let checked_out_hash
=
551 output(Command
::new("git").args(&["rev-parse", "HEAD"]).current_dir(&absolute_path
));
553 let recorded
= output(
555 .args(&["ls-tree", "HEAD"])
557 .current_dir(&self.config
.src
),
559 let actual_hash
= recorded
562 .unwrap_or_else(|| panic
!("unexpected output `{}`", recorded
));
565 if actual_hash
== checked_out_hash
.trim_end() {
566 // already checked out
570 println
!("Updating submodule {}", relative_path
.display());
573 .args(&["submodule", "-q", "sync"])
575 .current_dir(&self.config
.src
),
578 // Try passing `--progress` to start, then run git again without if that fails.
579 let update
= |progress
: bool
| {
580 // Git is buggy and will try to fetch submodules from the tracking branch for *this* repository,
581 // even though that has no relation to the upstream for the submodule.
582 let current_branch
= {
586 .args(["symbolic-ref", "--short", "HEAD"])
587 .stderr(Stdio
::inherit())
589 let output
= t
!(output
);
590 if output
.status
.success() {
591 Some(String
::from_utf8(output
.stdout
).unwrap().trim().to_owned())
597 let mut git
= self.config
.git();
598 if let Some(branch
) = current_branch
{
599 git
.arg("-c").arg(format
!("branch.{branch}.remote=origin"));
601 git
.args(&["submodule", "update", "--init", "--recursive", "--depth=1"]);
603 git
.arg("--progress");
605 git
.arg(relative_path
);
608 // NOTE: doesn't use `try_run` because this shouldn't print an error if it fails.
609 if !update(true).status().map_or(false, |status
| status
.success()) {
610 self.run(&mut update(false));
613 // Save any local changes, but avoid running `git stash pop` if there are none (since it will exit with an error).
614 let has_local_modifications
= !self.try_run(
616 .args(&["diff-index", "--quiet", "HEAD"])
617 .current_dir(&absolute_path
),
619 if has_local_modifications
{
620 self.run(Command
::new("git").args(&["stash", "push"]).current_dir(&absolute_path
));
623 self.run(Command
::new("git").args(&["reset", "-q", "--hard"]).current_dir(&absolute_path
));
624 self.run(Command
::new("git").args(&["clean", "-qdfx"]).current_dir(&absolute_path
));
626 if has_local_modifications
{
627 self.run(Command
::new("git").args(&["stash", "pop"]).current_dir(absolute_path
));
631 /// If any submodule has been initialized already, sync it unconditionally.
632 /// This avoids contributors checking in a submodule change by accident.
633 pub fn update_existing_submodules(&self) {
634 // Avoid running git when there isn't a git checkout.
635 if !self.config
.submodules(&self.rust_info()) {
641 .args(&["config", "--file"])
642 .arg(&self.config
.src
.join(".gitmodules"))
643 .args(&["--get-regexp", "path"]),
645 for line
in output
.lines() {
646 // Look for `submodule.$name.path = $path`
647 // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer`
648 let submodule
= Path
::new(line
.splitn(2, ' '
).nth(1).unwrap());
649 // Don't update the submodule unless it's already been cloned.
650 if channel
::GitInfo
::new(false, submodule
).is_managed_git_subrepository() {
651 self.update_submodule(submodule
);
656 /// Executes the entire build, as configured by the flags and configuration.
657 pub fn build(&mut self) {
662 // Download rustfmt early so that it can be used in rust-analyzer configs.
663 let _
= &builder
::Builder
::new(&self).initial_rustfmt();
665 // hardcoded subcommands
666 match &self.config
.cmd
{
667 Subcommand
::Format { check, paths }
=> {
668 return format
::format(&builder
::Builder
::new(&self), *check
, &paths
);
670 Subcommand
::Suggest { run }
=> {
671 return suggest
::suggest(&builder
::Builder
::new(&self), *run
);
677 let builder
= builder
::Builder
::new(&self);
678 if let Some(path
) = builder
.paths
.get(0) {
679 if path
== Path
::new("nonexistent/path/to/trigger/cargo/metadata") {
685 if !self.config
.dry_run() {
687 self.config
.dry_run
= DryRun
::SelfCheck
;
688 let builder
= builder
::Builder
::new(&self);
689 builder
.execute_cli();
691 self.config
.dry_run
= DryRun
::Disabled
;
692 let builder
= builder
::Builder
::new(&self);
693 builder
.execute_cli();
695 let builder
= builder
::Builder
::new(&self);
696 builder
.execute_cli();
699 // Check for postponed failures from `test --no-fail-fast`.
700 let failures
= self.delayed_failures
.borrow();
701 if failures
.len() > 0 {
702 eprintln
!("\n{} command(s) did not execute successfully:\n", failures
.len());
703 for failure
in failures
.iter() {
704 eprintln
!(" - {}\n", failure
);
709 #[cfg(feature = "build-metrics")]
710 self.metrics
.persist(self);
713 /// Clear out `dir` if `input` is newer.
715 /// After this executes, it will also ensure that `dir` exists.
716 fn clear_if_dirty(&self, dir
: &Path
, input
: &Path
) -> bool
{
717 let stamp
= dir
.join(".stamp");
718 let mut cleared
= false;
719 if mtime(&stamp
) < mtime(input
) {
720 self.verbose(&format
!("Dirty - {}", dir
.display()));
721 let _
= fs
::remove_dir_all(dir
);
723 } else if stamp
.exists() {
726 t
!(fs
::create_dir_all(dir
));
727 t
!(File
::create(stamp
));
731 fn rust_info(&self) -> &GitInfo
{
732 &self.config
.rust_info
735 /// Gets the space-separated set of activated features for the standard
737 fn std_features(&self, target
: TargetSelection
) -> String
{
738 let mut features
= " panic-unwind".to_string();
740 match self.config
.llvm_libunwind(target
) {
741 LlvmLibunwind
::InTree
=> features
.push_str(" llvm-libunwind"),
742 LlvmLibunwind
::System
=> features
.push_str(" system-llvm-libunwind"),
743 LlvmLibunwind
::No
=> {}
745 if self.config
.backtrace
{
746 features
.push_str(" backtrace");
748 if self.config
.profiler_enabled(target
) {
749 features
.push_str(" profiler");
754 /// Gets the space-separated set of activated features for the compiler.
755 fn rustc_features(&self, kind
: Kind
) -> String
{
756 let mut features
= vec
![];
757 if self.config
.jemalloc
{
758 features
.push("jemalloc");
760 if self.config
.llvm_enabled() || kind
== Kind
::Check
{
761 features
.push("llvm");
763 // keep in sync with `bootstrap/compile.rs:rustc_cargo_env`
764 if self.config
.rustc_parallel
{
765 features
.push("rustc_use_parallel_compiler");
768 // If debug logging is on, then we want the default for tracing:
769 // https://github.com/tokio-rs/tracing/blob/3dd5c03d907afdf2c39444a29931833335171554/tracing/src/level_filters.rs#L26
770 // which is everything (including debug/trace/etc.)
771 // if its unset, if debug_assertions is on, then debug_logging will also be on
772 // as well as tracing *ignoring* this feature when debug_assertions is on
773 if !self.config
.rust_debug_logging
{
774 features
.push("max_level_info");
780 /// Component directory that Cargo will produce output into (e.g.
782 fn cargo_dir(&self) -> &'
static str {
783 if self.config
.rust_optimize { "release" }
else { "debug" }
786 fn tools_dir(&self, compiler
: Compiler
) -> PathBuf
{
789 .join(&*compiler
.host
.triple
)
790 .join(format
!("stage{}-tools-bin", compiler
.stage
));
791 t
!(fs
::create_dir_all(&out
));
795 /// Returns the root directory for all output generated in a particular
796 /// stage when running with a particular host compiler.
798 /// The mode indicates what the root directory is for.
799 fn stage_out(&self, compiler
: Compiler
, mode
: Mode
) -> PathBuf
{
800 let suffix
= match mode
{
802 Mode
::Rustc
=> "-rustc",
803 Mode
::Codegen
=> "-codegen",
804 Mode
::ToolBootstrap
=> "-bootstrap-tools",
805 Mode
::ToolStd
| Mode
::ToolRustc
=> "-tools",
807 self.out
.join(&*compiler
.host
.triple
).join(format
!("stage{}{}", compiler
.stage
, suffix
))
810 /// Returns the root output directory for all Cargo output in a given stage,
811 /// running a particular compiler, whether or not we're building the
812 /// standard library, and targeting the specified architecture.
813 fn cargo_out(&self, compiler
: Compiler
, mode
: Mode
, target
: TargetSelection
) -> PathBuf
{
814 self.stage_out(compiler
, mode
).join(&*target
.triple
).join(self.cargo_dir())
817 /// Directory where the extracted `rustc-dev` component is stored.
818 fn ci_rustc_dir(&self, target
: TargetSelection
) -> PathBuf
{
819 self.out
.join(&*target
.triple
).join("ci-rustc")
822 /// Root output directory for LLVM compiled for `target`
824 /// Note that if LLVM is configured externally then the directory returned
825 /// will likely be empty.
826 fn llvm_out(&self, target
: TargetSelection
) -> PathBuf
{
827 self.out
.join(&*target
.triple
).join("llvm")
830 fn lld_out(&self, target
: TargetSelection
) -> PathBuf
{
831 self.out
.join(&*target
.triple
).join("lld")
834 /// Output directory for all documentation for a target
835 fn doc_out(&self, target
: TargetSelection
) -> PathBuf
{
836 self.out
.join(&*target
.triple
).join("doc")
839 /// Output directory for all JSON-formatted documentation for a target
840 fn json_doc_out(&self, target
: TargetSelection
) -> PathBuf
{
841 self.out
.join(&*target
.triple
).join("json-doc")
844 fn test_out(&self, target
: TargetSelection
) -> PathBuf
{
845 self.out
.join(&*target
.triple
).join("test")
848 /// Output directory for all documentation for a target
849 fn compiler_doc_out(&self, target
: TargetSelection
) -> PathBuf
{
850 self.out
.join(&*target
.triple
).join("compiler-doc")
853 /// Output directory for some generated md crate documentation for a target (temporary)
854 fn md_doc_out(&self, target
: TargetSelection
) -> Interned
<PathBuf
> {
855 INTERNER
.intern_path(self.out
.join(&*target
.triple
).join("md-doc"))
858 /// Returns `true` if no custom `llvm-config` is set for the specified target.
860 /// If no custom `llvm-config` was specified then Rust's llvm will be used.
861 fn is_rust_llvm(&self, target
: TargetSelection
) -> bool
{
862 match self.config
.target_config
.get(&target
) {
863 Some(Target { llvm_has_rust_patches: Some(patched), .. }
) => *patched
,
864 Some(Target { llvm_config, .. }
) => {
865 // If the user set llvm-config we assume Rust is not patched,
866 // but first check to see if it was configured by llvm-from-ci.
867 (self.config
.llvm_from_ci
&& target
== self.config
.build
) || llvm_config
.is_none()
873 /// Returns the path to `FileCheck` binary for the specified target
874 fn llvm_filecheck(&self, target
: TargetSelection
) -> PathBuf
{
875 let target_config
= self.config
.target_config
.get(&target
);
876 if let Some(s
) = target_config
.and_then(|c
| c
.llvm_filecheck
.as_ref()) {
878 } else if let Some(s
) = target_config
.and_then(|c
| c
.llvm_config
.as_ref()) {
879 let llvm_bindir
= output(Command
::new(s
).arg("--bindir"));
880 let filecheck
= Path
::new(llvm_bindir
.trim()).join(exe("FileCheck", target
));
881 if filecheck
.exists() {
884 // On Fedora the system LLVM installs FileCheck in the
885 // llvm subdirectory of the libdir.
886 let llvm_libdir
= output(Command
::new(s
).arg("--libdir"));
888 Path
::new(llvm_libdir
.trim()).join("llvm").join(exe("FileCheck", target
));
889 if lib_filecheck
.exists() {
892 // Return the most normal file name, even though
893 // it doesn't exist, so that any error message
899 let base
= self.llvm_out(target
).join("build");
900 let base
= if !self.ninja() && target
.contains("msvc") {
901 if self.config
.llvm_optimize
{
902 if self.config
.llvm_release_debuginfo
{
903 base
.join("RelWithDebInfo")
913 base
.join("bin").join(exe("FileCheck", target
))
917 /// Directory for libraries built from C/C++ code and shared between stages.
918 fn native_dir(&self, target
: TargetSelection
) -> PathBuf
{
919 self.out
.join(&*target
.triple
).join("native")
922 /// Root output directory for rust_test_helpers library compiled for
924 fn test_helpers_out(&self, target
: TargetSelection
) -> PathBuf
{
925 self.native_dir(target
).join("rust-test-helpers")
928 /// Adds the `RUST_TEST_THREADS` env var if necessary
929 fn add_rust_test_threads(&self, cmd
: &mut Command
) {
930 if env
::var_os("RUST_TEST_THREADS").is_none() {
931 cmd
.env("RUST_TEST_THREADS", self.jobs().to_string());
935 /// Returns the libdir of the snapshot compiler.
936 fn rustc_snapshot_libdir(&self) -> PathBuf
{
937 self.rustc_snapshot_sysroot().join(libdir(self.config
.build
))
940 /// Returns the sysroot of the snapshot compiler.
941 fn rustc_snapshot_sysroot(&self) -> &Path
{
942 static SYSROOT_CACHE
: OnceCell
<PathBuf
> = once_cell
::sync
::OnceCell
::new();
943 SYSROOT_CACHE
.get_or_init(|| {
944 let mut rustc
= Command
::new(&self.initial_rustc
);
945 rustc
.args(&["--print", "sysroot"]);
946 output(&mut rustc
).trim().into()
950 /// Runs a command, printing out nice contextual information if it fails.
951 fn run(&self, cmd
: &mut Command
) {
952 if self.config
.dry_run() {
955 self.verbose(&format
!("running: {:?}", cmd
));
956 run(cmd
, self.is_verbose())
959 /// Runs a command, printing out nice contextual information if it fails.
960 fn run_quiet(&self, cmd
: &mut Command
) {
961 if self.config
.dry_run() {
964 self.verbose(&format
!("running: {:?}", cmd
));
968 /// Runs a command, printing out nice contextual information if it fails.
969 /// Exits if the command failed to execute at all, otherwise returns its
970 /// `status.success()`.
971 fn try_run_quiet(&self, cmd
: &mut Command
) -> bool
{
972 if self.config
.dry_run() {
975 self.verbose(&format
!("running: {:?}", cmd
));
976 try_run_suppressed(cmd
)
979 pub fn is_verbose_than(&self, level
: usize) -> bool
{
980 self.verbosity
> level
983 /// Prints a message if this build is configured in more verbose mode than `level`.
984 fn verbose_than(&self, level
: usize, msg
: &str) {
985 if self.is_verbose_than(level
) {
990 fn info(&self, msg
: &str) {
991 match self.config
.dry_run
{
992 DryRun
::SelfCheck
=> return,
993 DryRun
::Disabled
| DryRun
::UserSelected
=> {
999 /// Returns the number of parallel jobs that have been configured for this
1001 fn jobs(&self) -> u32 {
1002 self.config
.jobs
.unwrap_or_else(|| {
1003 std
::thread
::available_parallelism().map_or(1, std
::num
::NonZeroUsize
::get
) as u32
1007 fn debuginfo_map_to(&self, which
: GitRepo
) -> Option
<String
> {
1008 if !self.config
.rust_remap_debuginfo
{
1014 let sha
= self.rust_sha().unwrap_or(&self.version
);
1015 Some(format
!("/rustc/{}", sha
))
1017 GitRepo
::Llvm
=> Some(String
::from("/rustc/llvm")),
1021 /// Returns the path to the C compiler for the target specified.
1022 fn cc(&self, target
: TargetSelection
) -> &Path
{
1023 self.cc
[&target
].path()
1026 /// Returns a list of flags to pass to the C compiler for the target
1028 fn cflags(&self, target
: TargetSelection
, which
: GitRepo
, c
: CLang
) -> Vec
<String
> {
1029 let base
= match c
{
1030 CLang
::C
=> &self.cc
[&target
],
1031 CLang
::Cxx
=> &self.cxx
[&target
],
1034 // Filter out -O and /O (the optimization flags) that we picked up from
1035 // cc-rs because the build scripts will determine that for themselves.
1039 .map(|s
| s
.to_string_lossy().into_owned())
1040 .filter(|s
| !s
.starts_with("-O") && !s
.starts_with("/O"))
1041 .collect
::<Vec
<String
>>();
1043 // If we're compiling on macOS then we add a few unconditional flags
1044 // indicating that we want libc++ (more filled out than libstdc++) and
1045 // we want to compile for 10.7. This way we can ensure that
1046 // LLVM/etc are all properly compiled.
1047 if target
.contains("apple-darwin") {
1048 base
.push("-stdlib=libc++".into());
1051 // Work around an apparently bad MinGW / GCC optimization,
1052 // See: https://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
1053 // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
1054 if &*target
.triple
== "i686-pc-windows-gnu" {
1055 base
.push("-fno-omit-frame-pointer".into());
1058 if let Some(map_to
) = self.debuginfo_map_to(which
) {
1059 let map
= format
!("{}={}", self.src
.display(), map_to
);
1060 let cc
= self.cc(target
);
1061 if cc
.ends_with("clang") || cc
.ends_with("gcc") {
1062 base
.push(format
!("-fdebug-prefix-map={}", map
));
1063 } else if cc
.ends_with("clang-cl.exe") {
1064 base
.push("-Xclang".into());
1065 base
.push(format
!("-fdebug-prefix-map={}", map
));
1071 /// Returns the path to the `ar` archive utility for the target specified.
1072 fn ar(&self, target
: TargetSelection
) -> Option
<&Path
> {
1073 self.ar
.get(&target
).map(|p
| &**p
)
1076 /// Returns the path to the `ranlib` utility for the target specified.
1077 fn ranlib(&self, target
: TargetSelection
) -> Option
<&Path
> {
1078 self.ranlib
.get(&target
).map(|p
| &**p
)
1081 /// Returns the path to the C++ compiler for the target specified.
1082 fn cxx(&self, target
: TargetSelection
) -> Result
<&Path
, String
> {
1083 match self.cxx
.get(&target
) {
1084 Some(p
) => Ok(p
.path()),
1086 Err(format
!("target `{}` is not configured as a host, only as a target", target
))
1091 /// Returns the path to the linker for the given target if it needs to be overridden.
1092 fn linker(&self, target
: TargetSelection
) -> Option
<&Path
> {
1093 if let Some(linker
) = self.config
.target_config
.get(&target
).and_then(|c
| c
.linker
.as_ref())
1096 } else if target
.contains("vxworks") {
1097 // need to use CXX compiler as linker to resolve the exception functions
1098 // that are only existed in CXX libraries
1099 Some(self.cxx
[&target
].path())
1100 } else if target
!= self.config
.build
1101 && util
::use_host_linker(target
)
1102 && !target
.contains("msvc")
1104 Some(self.cc(target
))
1105 } else if self.config
.use_lld
&& !self.is_fuse_ld_lld(target
) && self.build
== target
{
1106 Some(&self.initial_lld
)
1112 // LLD is used through `-fuse-ld=lld` rather than directly.
1113 // Only MSVC targets use LLD directly at the moment.
1114 fn is_fuse_ld_lld(&self, target
: TargetSelection
) -> bool
{
1115 self.config
.use_lld
&& !target
.contains("msvc")
1118 fn lld_flags(&self, target
: TargetSelection
) -> impl Iterator
<Item
= String
> {
1119 let mut options
= [None
, None
];
1121 if self.config
.use_lld
{
1122 if self.is_fuse_ld_lld(target
) {
1123 options
[0] = Some("-Clink-arg=-fuse-ld=lld".to_string());
1126 let no_threads
= util
::lld_flag_no_threads(target
.contains("windows"));
1127 options
[1] = Some(format
!("-Clink-arg=-Wl,{}", no_threads
));
1130 IntoIterator
::into_iter(options
).flatten()
1133 /// Returns if this target should statically link the C runtime, if specified
1134 fn crt_static(&self, target
: TargetSelection
) -> Option
<bool
> {
1135 if target
.contains("pc-windows-msvc") {
1138 self.config
.target_config
.get(&target
).and_then(|t
| t
.crt_static
)
1142 /// Returns the "musl root" for this `target`, if defined
1143 fn musl_root(&self, target
: TargetSelection
) -> Option
<&Path
> {
1147 .and_then(|t
| t
.musl_root
.as_ref())
1148 .or_else(|| self.config
.musl_root
.as_ref())
1152 /// Returns the "musl libdir" for this `target`.
1153 fn musl_libdir(&self, target
: TargetSelection
) -> Option
<PathBuf
> {
1154 let t
= self.config
.target_config
.get(&target
)?
;
1155 if let libdir @
Some(_
) = &t
.musl_libdir
{
1156 return libdir
.clone();
1158 self.musl_root(target
).map(|root
| root
.join("lib"))
1161 /// Returns the sysroot for the wasi target, if defined
1162 fn wasi_root(&self, target
: TargetSelection
) -> Option
<&Path
> {
1163 self.config
.target_config
.get(&target
).and_then(|t
| t
.wasi_root
.as_ref()).map(|p
| &**p
)
1166 /// Returns `true` if this is a no-std `target`, if defined
1167 fn no_std(&self, target
: TargetSelection
) -> Option
<bool
> {
1168 self.config
.target_config
.get(&target
).map(|t
| t
.no_std
)
1171 /// Returns `true` if the target will be tested using the `remote-test-client`
1172 /// and `remote-test-server` binaries.
1173 fn remote_tested(&self, target
: TargetSelection
) -> bool
{
1174 self.qemu_rootfs(target
).is_some()
1175 || target
.contains("android")
1176 || env
::var_os("TEST_DEVICE_ADDR").is_some()
1179 /// Returns the root of the "rootfs" image that this target will be using,
1180 /// if one was configured.
1182 /// If `Some` is returned then that means that tests for this target are
1183 /// emulated with QEMU and binaries will need to be shipped to the emulator.
1184 fn qemu_rootfs(&self, target
: TargetSelection
) -> Option
<&Path
> {
1185 self.config
.target_config
.get(&target
).and_then(|t
| t
.qemu_rootfs
.as_ref()).map(|p
| &**p
)
1188 /// Path to the python interpreter to use
1189 fn python(&self) -> &Path
{
1190 if self.config
.build
.ends_with("apple-darwin") {
1191 // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1192 // LLDB plugin's compiled module which only works with the system python
1193 // (namely not Homebrew-installed python)
1194 Path
::new("/usr/bin/python3")
1199 .expect("python is required for running LLDB or rustdoc tests")
1203 /// Temporary directory that extended error information is emitted to.
1204 fn extended_error_dir(&self) -> PathBuf
{
1205 self.out
.join("tmp/extended-error-metadata")
1208 /// Tests whether the `compiler` compiling for `target` should be forced to
1209 /// use a stage1 compiler instead.
1211 /// Currently, by default, the build system does not perform a "full
1212 /// bootstrap" by default where we compile the compiler three times.
1213 /// Instead, we compile the compiler two times. The final stage (stage2)
1214 /// just copies the libraries from the previous stage, which is what this
1217 /// Here we return `true` if:
1219 /// * The build isn't performing a full bootstrap
1220 /// * The `compiler` is in the final stage, 2
1221 /// * We're not cross-compiling, so the artifacts are already available in
1224 /// When all of these conditions are met the build will lift artifacts from
1225 /// the previous stage forward.
1226 fn force_use_stage1(&self, stage
: u32, target
: TargetSelection
) -> bool
{
1227 !self.config
.full_bootstrap
1228 && !self.config
.download_rustc()
1230 && (self.hosts
.iter().any(|h
| *h
== target
) || target
== self.build
)
1233 /// Checks whether the `compiler` compiling for `target` should be forced to
1234 /// use a stage2 compiler instead.
1236 /// When we download the pre-compiled version of rustc and compiler stage is >= 2,
1237 /// it should be forced to use a stage2 compiler.
1238 fn force_use_stage2(&self, stage
: u32) -> bool
{
1239 self.config
.download_rustc() && stage
>= 2
1242 /// Given `num` in the form "a.b.c" return a "release string" which
1243 /// describes the release version number.
1245 /// For example on nightly this returns "a.b.c-nightly", on beta it returns
1246 /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
1247 fn release(&self, num
: &str) -> String
{
1248 match &self.config
.channel
[..] {
1249 "stable" => num
.to_string(),
1251 if self.rust_info().is_managed_git_subrepository() && !self.config
.omit_git_hash
{
1252 format
!("{}-beta.{}", num
, self.beta_prerelease_version())
1254 format
!("{}-beta", num
)
1257 "nightly" => format
!("{}-nightly", num
),
1258 _
=> format
!("{}-dev", num
),
1262 fn beta_prerelease_version(&self) -> u32 {
1263 if let Some(s
) = self.prerelease_version
.get() {
1267 // Figure out how many merge commits happened since we branched off master.
1268 // That's our beta number!
1269 // (Note that we use a `..` range, not the `...` symmetric difference.)
1271 output(self.config
.git().arg("rev-list").arg("--count").arg("--merges").arg(format
!(
1272 "refs/remotes/origin/{}..HEAD",
1273 self.config
.stage0_metadata
.config
.nightly_branch
1275 let n
= count
.trim().parse().unwrap();
1276 self.prerelease_version
.set(Some(n
));
1280 /// Returns the value of `release` above for Rust itself.
1281 fn rust_release(&self) -> String
{
1282 self.release(&self.version
)
1285 /// Returns the "package version" for a component given the `num` release
1288 /// The package version is typically what shows up in the names of tarballs.
1289 /// For channels like beta/nightly it's just the channel name, otherwise
1290 /// it's the `num` provided.
1291 fn package_vers(&self, num
: &str) -> String
{
1292 match &self.config
.channel
[..] {
1293 "stable" => num
.to_string(),
1294 "beta" => "beta".to_string(),
1295 "nightly" => "nightly".to_string(),
1296 _
=> format
!("{}-dev", num
),
1300 /// Returns the value of `package_vers` above for Rust itself.
1301 fn rust_package_vers(&self) -> String
{
1302 self.package_vers(&self.version
)
1305 /// Returns the `version` string associated with this compiler for Rust
1308 /// Note that this is a descriptive string which includes the commit date,
1309 /// sha, version, etc.
1310 fn rust_version(&self) -> String
{
1311 let mut version
= self.rust_info().version(self, &self.version
);
1312 if let Some(ref s
) = self.config
.description
{
1313 version
.push_str(" (");
1314 version
.push_str(s
);
1320 /// Returns the full commit hash.
1321 fn rust_sha(&self) -> Option
<&str> {
1322 self.rust_info().sha()
1325 /// Returns the `a.b.c` version that the given package is at.
1326 fn release_num(&self, package
: &str) -> String
{
1327 let toml_file_name
= self.src
.join(&format
!("src/tools/{}/Cargo.toml", package
));
1328 let toml
= t
!(fs
::read_to_string(&toml_file_name
));
1329 for line
in toml
.lines() {
1330 if let Some(stripped
) =
1331 line
.strip_prefix("version = \"").and_then(|s
| s
.strip_suffix("\""))
1333 return stripped
.to_owned();
1337 panic
!("failed to find version in {}'s Cargo.toml", package
)
1340 /// Returns `true` if unstable features should be enabled for the compiler
1342 fn unstable_features(&self) -> bool
{
1343 match &self.config
.channel
[..] {
1344 "stable" | "beta" => false,
1345 "nightly" | _
=> true,
1349 /// Returns a Vec of all the dependencies of the given root crate,
1350 /// including transitive dependencies and the root itself. Only includes
1351 /// "local" crates (those in the local source tree, not from a registry).
1352 fn in_tree_crates(&self, root
: &str, target
: Option
<TargetSelection
>) -> Vec
<&Crate
> {
1353 let mut ret
= Vec
::new();
1354 let mut list
= vec
![INTERNER
.intern_str(root
)];
1355 let mut visited
= HashSet
::new();
1356 while let Some(krate
) = list
.pop() {
1360 .unwrap_or_else(|| panic
!("metadata missing for {krate}: {:?}", self.crates
));
1362 for dep
in &krate
.deps
{
1363 if !self.crates
.contains_key(dep
) {
1364 // Ignore non-workspace members.
1367 // Don't include optional deps if their features are not
1368 // enabled. Ideally this would be computed from `cargo
1369 // metadata --features …`, but that is somewhat slow. In
1370 // the future, we may want to consider just filtering all
1371 // build and dev dependencies in metadata::build.
1372 if visited
.insert(dep
)
1373 && (dep
!= "profiler_builtins"
1375 .map(|t
| self.config
.profiler_enabled(t
))
1376 .unwrap_or_else(|| self.config
.any_profiler_enabled()))
1377 && (dep
!= "rustc_codegen_llvm" || self.config
.llvm_enabled())
1386 fn read_stamp_file(&self, stamp
: &Path
) -> Vec
<(PathBuf
, DependencyType
)> {
1387 if self.config
.dry_run() {
1391 if !stamp
.exists() {
1393 "Error: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1396 crate::detail_exit(1);
1399 let mut paths
= Vec
::new();
1400 let contents
= t
!(fs
::read(stamp
), &stamp
);
1401 // This is the method we use for extracting paths from the stamp file passed to us. See
1402 // run_cargo for more information (in compile.rs).
1403 for part
in contents
.split(|b
| *b
== 0) {
1404 if part
.is_empty() {
1407 let dependency_type
= match part
[0] as char {
1408 'h'
=> DependencyType
::Host
,
1409 's'
=> DependencyType
::TargetSelfContained
,
1410 't'
=> DependencyType
::Target
,
1411 _
=> unreachable
!(),
1413 let path
= PathBuf
::from(t
!(str::from_utf8(&part
[1..])));
1414 paths
.push((path
, dependency_type
));
1419 /// Copies a file from `src` to `dst`
1420 pub fn copy(&self, src
: &Path
, dst
: &Path
) {
1421 self.copy_internal(src
, dst
, false);
1424 fn copy_internal(&self, src
: &Path
, dst
: &Path
, dereference_symlinks
: bool
) {
1425 if self.config
.dry_run() {
1428 self.verbose_than(1, &format
!("Copy {:?} to {:?}", src
, dst
));
1432 let _
= fs
::remove_file(&dst
);
1433 let metadata
= t
!(src
.symlink_metadata());
1434 let mut src
= src
.to_path_buf();
1435 if metadata
.file_type().is_symlink() {
1436 if dereference_symlinks
{
1437 src
= t
!(fs
::canonicalize(src
));
1439 let link
= t
!(fs
::read_link(src
));
1440 t
!(self.symlink_file(link
, dst
));
1444 if let Ok(()) = fs
::hard_link(&src
, dst
) {
1445 // Attempt to "easy copy" by creating a hard link
1446 // (symlinks don't work on windows), but if that fails
1447 // just fall back to a slow `copy` operation.
1449 if let Err(e
) = fs
::copy(&src
, dst
) {
1450 panic
!("failed to copy `{}` to `{}`: {}", src
.display(), dst
.display(), e
)
1452 t
!(fs
::set_permissions(dst
, metadata
.permissions()));
1453 let atime
= FileTime
::from_last_access_time(&metadata
);
1454 let mtime
= FileTime
::from_last_modification_time(&metadata
);
1455 t
!(filetime
::set_file_times(dst
, atime
, mtime
));
1459 /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1460 /// when this function is called.
1461 pub fn cp_r(&self, src
: &Path
, dst
: &Path
) {
1462 if self.config
.dry_run() {
1465 for f
in self.read_dir(src
) {
1466 let path
= f
.path();
1467 let name
= path
.file_name().unwrap();
1468 let dst
= dst
.join(name
);
1469 if t
!(f
.file_type()).is_dir() {
1470 t
!(fs
::create_dir_all(&dst
));
1471 self.cp_r(&path
, &dst
);
1473 let _
= fs
::remove_file(&dst
);
1474 self.copy(&path
, &dst
);
1479 /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1480 /// when this function is called. Unwanted files or directories can be skipped
1481 /// by returning `false` from the filter function.
1482 pub fn cp_filtered(&self, src
: &Path
, dst
: &Path
, filter
: &dyn Fn(&Path
) -> bool
) {
1483 // Immediately recurse with an empty relative path
1484 self.recurse_(src
, dst
, Path
::new(""), filter
)
1487 // Inner function does the actual work
1488 fn recurse_(&self, src
: &Path
, dst
: &Path
, relative
: &Path
, filter
: &dyn Fn(&Path
) -> bool
) {
1489 for f
in self.read_dir(src
) {
1490 let path
= f
.path();
1491 let name
= path
.file_name().unwrap();
1492 let dst
= dst
.join(name
);
1493 let relative
= relative
.join(name
);
1494 // Only copy file or directory if the filter function returns true
1495 if filter(&relative
) {
1496 if t
!(f
.file_type()).is_dir() {
1497 let _
= fs
::remove_dir_all(&dst
);
1498 self.create_dir(&dst
);
1499 self.recurse_(&path
, &dst
, &relative
, filter
);
1501 let _
= fs
::remove_file(&dst
);
1502 self.copy(&path
, &dst
);
1508 fn copy_to_folder(&self, src
: &Path
, dest_folder
: &Path
) {
1509 let file_name
= src
.file_name().unwrap();
1510 let dest
= dest_folder
.join(file_name
);
1511 self.copy(src
, &dest
);
1514 fn install(&self, src
: &Path
, dstdir
: &Path
, perms
: u32) {
1515 if self.config
.dry_run() {
1518 let dst
= dstdir
.join(src
.file_name().unwrap());
1519 self.verbose_than(1, &format
!("Install {:?} to {:?}", src
, dst
));
1520 t
!(fs
::create_dir_all(dstdir
));
1522 panic
!("Error: File \"{}\" not found!", src
.display());
1524 self.copy_internal(src
, &dst
, true);
1528 fn read(&self, path
: &Path
) -> String
{
1529 if self.config
.dry_run() {
1530 return String
::new();
1532 t
!(fs
::read_to_string(path
))
1535 fn create_dir(&self, dir
: &Path
) {
1536 if self.config
.dry_run() {
1539 t
!(fs
::create_dir_all(dir
))
1542 fn remove_dir(&self, dir
: &Path
) {
1543 if self.config
.dry_run() {
1546 t
!(fs
::remove_dir_all(dir
))
1549 fn read_dir(&self, dir
: &Path
) -> impl Iterator
<Item
= fs
::DirEntry
> {
1550 let iter
= match fs
::read_dir(dir
) {
1552 Err(_
) if self.config
.dry_run() => return vec
![].into_iter(),
1553 Err(err
) => panic
!("could not read dir {:?}: {:?}", dir
, err
),
1555 iter
.map(|e
| t
!(e
)).collect
::<Vec
<_
>>().into_iter()
1558 fn symlink_file
<P
: AsRef
<Path
>, Q
: AsRef
<Path
>>(&self, src
: P
, link
: Q
) -> io
::Result
<()> {
1560 use std
::os
::unix
::fs
::symlink
as symlink_file
;
1562 use std
::os
::windows
::fs
::symlink_file
;
1563 if !self.config
.dry_run() { symlink_file(src.as_ref(), link.as_ref()) }
else { Ok(()) }
1566 /// Returns if config.ninja is enabled, and checks for ninja existence,
1567 /// exiting with a nicer error message if not.
1568 fn ninja(&self) -> bool
{
1569 let mut cmd_finder
= crate::sanity
::Finder
::new();
1571 if self.config
.ninja_in_file
{
1572 // Some Linux distros rename `ninja` to `ninja-build`.
1573 // CMake can work with either binary name.
1574 if cmd_finder
.maybe_have("ninja-build").is_none()
1575 && cmd_finder
.maybe_have("ninja").is_none()
1579 Couldn't find required command: ninja (or ninja-build)
1581 You should install ninja as described at
1582 <https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1583 or set `ninja = false` in the `[llvm]` section of `config.toml`.
1584 Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1585 to download LLVM rather than building it.
1592 // If ninja isn't enabled but we're building for MSVC then we try
1593 // doubly hard to enable it. It was realized in #43767 that the msbuild
1594 // CMake generator for MSVC doesn't respect configuration options like
1595 // disabling LLVM assertions, which can often be quite important!
1597 // In these cases we automatically enable Ninja if we find it in the
1599 if !self.config
.ninja_in_file
&& self.config
.build
.contains("msvc") {
1600 if cmd_finder
.maybe_have("ninja").is_some() {
1605 self.config
.ninja_in_file
1608 pub fn colored_stdout
<R
, F
: FnOnce(&mut dyn WriteColor
) -> R
>(&self, f
: F
) -> R
{
1609 self.colored_stream_inner(StandardStream
::stdout
, self.config
.stdout_is_tty
, f
)
1612 pub fn colored_stderr
<R
, F
: FnOnce(&mut dyn WriteColor
) -> R
>(&self, f
: F
) -> R
{
1613 self.colored_stream_inner(StandardStream
::stderr
, self.config
.stderr_is_tty
, f
)
1616 fn colored_stream_inner
<R
, F
, C
>(&self, constructor
: C
, is_tty
: bool
, f
: F
) -> R
1618 C
: Fn(ColorChoice
) -> StandardStream
,
1619 F
: FnOnce(&mut dyn WriteColor
) -> R
,
1621 let choice
= match self.config
.color
{
1622 flags
::Color
::Always
=> ColorChoice
::Always
,
1623 flags
::Color
::Never
=> ColorChoice
::Never
,
1624 flags
::Color
::Auto
if !is_tty
=> ColorChoice
::Never
,
1625 flags
::Color
::Auto
=> ColorChoice
::Auto
,
1627 let mut stream
= constructor(choice
);
1628 let result
= f(&mut stream
);
1629 stream
.reset().unwrap();
1635 fn chmod(path
: &Path
, perms
: u32) {
1636 use std
::os
::unix
::fs
::*;
1637 t
!(fs
::set_permissions(path
, fs
::Permissions
::from_mode(perms
)));
1640 fn chmod(_path
: &Path
, _perms
: u32) {}
1642 /// If code is not 0 (successful exit status), exit status is 101 (rust's default error code.)
1643 /// If the test is running and code is an error code, it will cause a panic.
1644 fn detail_exit(code
: i32) -> ! {
1645 // if in test and code is an error code, panic with status code provided
1647 panic
!("status code: {}", code
);
1649 // otherwise,exit with provided status code
1650 std
::process
::exit(code
);
1655 pub fn with_stage(mut self, stage
: u32) -> Compiler
{
1660 /// Returns `true` if this is a snapshot compiler for `build`'s configuration
1661 pub fn is_snapshot(&self, build
: &Build
) -> bool
{
1662 self.stage
== 0 && self.host
== build
.build
1665 /// Returns if this compiler should be treated as a final stage one in the
1666 /// current build session.
1667 /// This takes into account whether we're performing a full bootstrap or
1668 /// not; don't directly compare the stage with `2`!
1669 pub fn is_final_stage(&self, build
: &Build
) -> bool
{
1670 let final_stage
= if build
.config
.full_bootstrap { 2 }
else { 1 }
;
1671 self.stage
>= final_stage
1675 fn envify(s
: &str) -> String
{
1681 .flat_map(|c
| c
.to_uppercase())