2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
10 use std::path::{Component, Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
14 use build_helper::{output, t};
16 use crate::cache::{Cache, Interned, INTERNER};
19 use crate::config::TargetSelection;
22 use crate::flags::{Color, Subcommand};
27 use crate::tool::{self, SourceType};
28 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir};
29 use crate::{Build, DocTests, GitRepo, Mode};
31 pub use crate::Compiler;
32 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
33 use once_cell::sync::Lazy;
35 pub struct Builder<'a> {
40 stack: RefCell<Vec<Box<dyn Any>>>,
41 time_spent_on_dependencies: Cell<Duration>,
42 pub paths: Vec<PathBuf>,
45 impl<'a> Deref for Builder<'a> {
48 fn deref(&self) -> &Self::Target {
53 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
54 /// `PathBuf` when directories are created or to return a `Compiler` once
55 /// it's been assembled.
58 /// Whether this step is run by default as part of its respective phase.
59 /// `true` here can still be overwritten by `should_run` calling `default_condition`.
60 const DEFAULT: bool = false;
62 /// If true, then this rule should be skipped if --target was specified, but --host was not
63 const ONLY_HOSTS: bool = false;
65 /// Primary function to execute this rule. Can call `builder.ensure()`
66 /// with other steps to run those.
67 fn run(self, builder: &Builder<'_>) -> Self::Output;
69 /// When bootstrap is passed a set of paths, this controls whether this rule
70 /// will execute. However, it does not get called in a "default" context
71 /// when we are not passed any paths; in that case, `make_run` is called
73 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
75 /// Builds up a "root" rule, either as a default rule or from a path passed
78 /// When path is `None`, we are executing in a context where no paths were
79 /// passed. When `./x.py build` is run, for example, this rule could get
80 /// called if it is in the correct list below with a path of `None`.
81 fn make_run(_run: RunConfig<'_>) {
82 // It is reasonable to not have an implementation of make_run for rules
83 // who do not want to get called from the root context. This means that
84 // they are likely dependencies (e.g., sysroot creation) or similar, and
85 // as such calling them from ./x.py isn't logical.
90 pub struct RunConfig<'a> {
91 pub builder: &'a Builder<'a>,
92 pub target: TargetSelection,
97 pub fn build_triple(&self) -> TargetSelection {
98 self.builder.build.build
102 struct StepDescription {
105 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
106 make_run: fn(RunConfig<'_>),
111 #[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
112 pub struct TaskPath {
114 pub kind: Option<Kind>,
118 pub fn parse(path: impl Into<PathBuf>) -> TaskPath {
120 let mut path = path.into();
122 let mut components = path.components();
123 if let Some(Component::Normal(os_str)) = components.next() {
124 if let Some(str) = os_str.to_str() {
125 if let Some((found_kind, found_prefix)) = str.split_once("::") {
126 if found_kind.is_empty() {
127 panic!("empty kind in task path {}", path.display());
129 kind = Some(Kind::parse(found_kind));
130 path = Path::new(found_prefix).join(components.as_path());
135 TaskPath { path, kind }
139 impl Debug for TaskPath {
140 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141 if let Some(kind) = &self.kind {
142 write!(f, "{}::", kind.as_str())?;
144 write!(f, "{}", self.path.display())
148 /// Collection of paths used to match a task rule.
149 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
151 /// A collection of individual paths.
153 /// These are generally matched as a path suffix. For example, a
154 /// command-line value of `libstd` will match if `src/libstd` is in the
156 Set(BTreeSet<TaskPath>),
157 /// A "suite" of paths.
159 /// These can match as a path suffix (like `Set`), or as a prefix. For
160 /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
161 /// will match `src/test/ui`. A command-line value of `ui` would also
162 /// match `src/test/ui`.
167 fn empty() -> PathSet {
168 PathSet::Set(BTreeSet::new())
171 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
172 let mut set = BTreeSet::new();
173 set.insert(TaskPath { path: path.into(), kind: Some(kind.into()) });
177 fn has(&self, needle: &Path, module: Option<Kind>) -> bool {
178 let check = |p: &TaskPath| {
179 if let (Some(p_kind), Some(kind)) = (&p.kind, module) {
180 p.path.ends_with(needle) && *p_kind == kind
182 p.path.ends_with(needle)
187 PathSet::Set(set) => set.iter().any(check),
188 PathSet::Suite(suite) => check(suite),
192 fn path(&self, builder: &Builder<'_>) -> PathBuf {
194 PathSet::Set(set) => {
195 set.iter().next().map(|p| &p.path).unwrap_or(&builder.build.src).clone()
197 PathSet::Suite(path) => path.path.clone(),
202 impl StepDescription {
203 fn from<S: Step>(kind: Kind) -> StepDescription {
206 only_hosts: S::ONLY_HOSTS,
207 should_run: S::should_run,
208 make_run: S::make_run,
209 name: std::any::type_name::<S>(),
214 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
215 if self.is_excluded(builder, pathset) {
219 // Determine the targets participating in this rule.
220 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
222 for target in targets {
223 let run = RunConfig { builder, path: pathset.path(builder), target: *target };
224 (self.make_run)(run);
228 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
229 if builder.config.exclude.iter().any(|e| pathset.has(&e.path, e.kind)) {
230 eprintln!("Skipping {:?} because it is excluded", pathset);
234 if !builder.config.exclude.is_empty() {
236 "{:?} not skipped for {:?} -- not in {:?}",
237 pathset, self.name, builder.config.exclude
243 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
246 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
247 .collect::<Vec<_>>();
249 // sanity checks on rules
250 for (desc, should_run) in v.iter().zip(&should_runs) {
252 !should_run.paths.is_empty(),
253 "{:?} should have at least one pathset",
258 if paths.is_empty() || builder.config.include_default_paths {
259 for (desc, should_run) in v.iter().zip(&should_runs) {
260 if desc.default && should_run.is_really_default() {
261 for pathset in &should_run.paths {
262 desc.maybe_run(builder, pathset);
269 // strip CurDir prefix if present
270 let path = match path.strip_prefix(".") {
275 let mut attempted_run = false;
276 for (desc, should_run) in v.iter().zip(&should_runs) {
277 if let Some(suite) = should_run.is_suite_path(path) {
278 attempted_run = true;
279 desc.maybe_run(builder, suite);
280 } else if let Some(pathset) = should_run.pathset_for_path(path, desc.kind) {
281 attempted_run = true;
282 desc.maybe_run(builder, pathset);
287 panic!("error: no rules matched {}", path.display());
293 enum ReallyDefault<'a> {
295 Lazy(Lazy<bool, Box<dyn Fn() -> bool + 'a>>),
298 pub struct ShouldRun<'a> {
299 pub builder: &'a Builder<'a>,
302 // use a BTreeSet to maintain sort order
303 paths: BTreeSet<PathSet>,
305 // If this is a default rule, this is an additional constraint placed on
306 // its run. Generally something like compiler docs being enabled.
307 is_really_default: ReallyDefault<'a>,
310 impl<'a> ShouldRun<'a> {
311 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
315 paths: BTreeSet::new(),
316 is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
320 pub fn default_condition(mut self, cond: bool) -> Self {
321 self.is_really_default = ReallyDefault::Bool(cond);
325 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
326 self.is_really_default = ReallyDefault::Lazy(Lazy::new(lazy_cond));
330 pub fn is_really_default(&self) -> bool {
331 match &self.is_really_default {
332 ReallyDefault::Bool(val) => *val,
333 ReallyDefault::Lazy(lazy) => *lazy.deref(),
337 /// Indicates it should run if the command-line selects the given crate or
338 /// any of its (local) dependencies.
340 /// Compared to `krate`, this treats the dependencies as aliases for the
341 /// same job. Generally it is preferred to use `krate`, and treat each
342 /// individual path separately. For example `./x.py test src/liballoc`
343 /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
344 /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
345 /// `all_krates` should probably be removed at some point.
346 pub fn all_krates(mut self, name: &str) -> Self {
347 let mut set = BTreeSet::new();
348 for krate in self.builder.in_tree_crates(name, None) {
349 let path = krate.local_path(self.builder);
350 set.insert(TaskPath { path, kind: Some(self.kind) });
352 self.paths.insert(PathSet::Set(set));
356 /// Indicates it should run if the command-line selects the given crate or
357 /// any of its (local) dependencies.
359 /// `make_run` will be called separately for each matching command-line path.
360 pub fn krate(mut self, name: &str) -> Self {
361 for krate in self.builder.in_tree_crates(name, None) {
362 let path = krate.local_path(self.builder);
363 self.paths.insert(PathSet::one(path, self.kind));
368 // single, non-aliased path
369 pub fn path(self, path: &str) -> Self {
373 // multiple aliases for the same job
374 pub fn paths(mut self, paths: &[&str]) -> Self {
375 self.paths.insert(PathSet::Set(
378 .map(|p| TaskPath { path: p.into(), kind: Some(self.kind.into()) })
384 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
385 self.paths.iter().find(|pathset| match pathset {
386 PathSet::Suite(p) => path.starts_with(&p.path),
387 PathSet::Set(_) => false,
391 pub fn suite_path(mut self, suite: &str) -> Self {
393 .insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind.into()) }));
397 // allows being more explicit about why should_run in Step returns the value passed to it
398 pub fn never(mut self) -> ShouldRun<'a> {
399 self.paths.insert(PathSet::empty());
403 fn pathset_for_path(&self, path: &Path, kind: Kind) -> Option<&PathSet> {
404 self.paths.iter().find(|pathset| pathset.has(path, Some(kind)))
408 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
423 fn parse(string: &str) -> Kind {
425 "build" => Kind::Build,
426 "check" => Kind::Check,
427 "clippy" => Kind::Clippy,
429 "test" => Kind::Test,
430 "bench" => Kind::Bench,
431 "dist" => Kind::Dist,
433 "install" => Kind::Install,
435 other => panic!("unknown kind: {}", other),
439 fn as_str(&self) -> &'static str {
441 Kind::Build => "build",
442 Kind::Check => "check",
443 Kind::Clippy => "clippy",
445 Kind::Test => "test",
446 Kind::Bench => "bench",
447 Kind::Dist => "dist",
449 Kind::Install => "install",
455 impl<'a> Builder<'a> {
456 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
457 macro_rules! describe {
458 ($($rule:ty),+ $(,)?) => {{
459 vec![$(StepDescription::from::<$rule>(kind)),+]
463 Kind::Build => describe!(
466 compile::CodegenBackend,
467 compile::StartupObjects,
471 tool::UnstableBookGen,
476 tool::RemoteTestServer,
477 tool::RemoteTestClient,
494 Kind::Check | Kind::Clippy { .. } | Kind::Fix => describe!(
498 check::CodegenBackend,
505 Kind::Test => describe!(
506 crate::toolstate::ToolStateCheck,
507 test::ExpandYamlAnchors,
510 test::RunPassValgrind,
523 test::CrateRustdocJsonTypes,
531 test::RunMakeFullDeps,
547 test::CompiletestTest,
549 test::RustdocJSNotStd,
555 // Run bootstrap close to the end as it's unlikely to fail
557 // Run run-make last, since these won't pass without make on Windows
560 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
561 Kind::Doc => describe!(
563 doc::UnstableBookGen,
581 Kind::Dist => describe!(
586 dist::DebuggerScripts,
601 // It seems that PlainSourceTarball somehow changes how some of the tools
602 // perceive their dependencies (see #93033) which would invaliate fingerprints
603 // and force us to rebuild tools after vendoring dependencies.
604 // To work around this, create the Tarball after building all the tools.
605 dist::PlainSourceTarball,
607 dist::ReproducibleArtifacts,
609 Kind::Install => describe!(
614 install::RustAnalyzer,
616 install::RustDemangler,
623 Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest, run::BumpStage0),
627 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
628 let kind = match subcommand {
629 "build" => Kind::Build,
631 "test" => Kind::Test,
632 "bench" => Kind::Bench,
633 "dist" => Kind::Dist,
634 "install" => Kind::Install,
638 let builder = Self::new_internal(build, kind, vec![]);
639 let builder = &builder;
640 // The "build" kind here is just a placeholder, it will be replaced with something else in
641 // the following statement.
642 let mut should_run = ShouldRun::new(builder, Kind::Build);
643 for desc in Builder::get_step_descriptions(builder.kind) {
644 should_run.kind = desc.kind;
645 should_run = (desc.should_run)(should_run);
647 let mut help = String::from("Available paths:\n");
648 let mut add_path = |path: &Path| {
649 help.push_str(&format!(" ./x.py {} {}\n", subcommand, path.display()));
651 for pathset in should_run.paths {
653 PathSet::Set(set) => {
655 add_path(&path.path);
658 PathSet::Suite(path) => {
659 add_path(&path.path.join("..."));
666 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
669 top_stage: build.config.stage,
672 stack: RefCell::new(Vec::new()),
673 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
678 pub fn new(build: &Build) -> Builder<'_> {
679 let (kind, paths) = match build.config.cmd {
680 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
681 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
682 Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
683 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
684 Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
685 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
686 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
687 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
688 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
689 Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
690 Subcommand::Format { .. } | Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
695 Self::new_internal(build, kind, paths.to_owned())
698 pub fn execute_cli(&self) {
699 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
702 pub fn default_doc(&self, paths: &[PathBuf]) {
703 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
706 /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
707 pub fn doc_rust_lang_org_channel(&self) -> String {
708 let channel = match &*self.config.channel {
709 "stable" => &self.version,
711 "nightly" | "dev" => "nightly",
712 // custom build of rustdoc maybe? link to the latest stable docs just in case
715 "https://doc.rust-lang.org/".to_owned() + channel
718 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
719 StepDescription::run(v, self, paths);
722 /// Obtain a compiler at a given stage and for a given host. Explicitly does
723 /// not take `Compiler` since all `Compiler` instances are meant to be
724 /// obtained through this function, since it ensures that they are valid
725 /// (i.e., built and assembled).
726 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
727 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
730 /// Similar to `compiler`, except handles the full-bootstrap option to
731 /// silently use the stage1 compiler instead of a stage2 compiler if one is
734 /// Note that this does *not* have the side effect of creating
735 /// `compiler(stage, host)`, unlike `compiler` above which does have such
736 /// a side effect. The returned compiler here can only be used to compile
737 /// new artifacts, it can't be used to rely on the presence of a particular
740 /// See `force_use_stage1` for documentation on what each argument is.
744 host: TargetSelection,
745 target: TargetSelection,
747 if self.build.force_use_stage1(Compiler { stage, host }, target) {
748 self.compiler(1, self.config.build)
750 self.compiler(stage, host)
754 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
755 self.ensure(compile::Sysroot { compiler })
758 /// Returns the libdir where the standard library and other artifacts are
759 /// found for a compiler's sysroot.
760 pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
761 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
764 target: TargetSelection,
766 impl Step for Libdir {
767 type Output = Interned<PathBuf>;
769 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
773 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
774 let lib = builder.sysroot_libdir_relative(self.compiler);
775 let sysroot = builder
776 .sysroot(self.compiler)
779 .join(self.target.triple)
781 // Avoid deleting the rustlib/ directory we just copied
782 // (in `impl Step for Sysroot`).
783 if !builder.config.download_rustc {
784 let _ = fs::remove_dir_all(&sysroot);
785 t!(fs::create_dir_all(&sysroot));
787 INTERNER.intern_path(sysroot)
790 self.ensure(Libdir { compiler, target })
793 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
794 self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
797 /// Returns the compiler's libdir where it stores the dynamic libraries that
798 /// it itself links against.
800 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
802 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
803 if compiler.is_snapshot(self) {
804 self.rustc_snapshot_libdir()
806 match self.config.libdir_relative() {
807 Some(relative_libdir) if compiler.stage >= 1 => {
808 self.sysroot(compiler).join(relative_libdir)
810 _ => self.sysroot(compiler).join(libdir(compiler.host)),
815 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
816 /// it itself links against.
818 /// For example this returns `lib` on Unix and `bin` on
820 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
821 if compiler.is_snapshot(self) {
822 libdir(self.config.build).as_ref()
824 match self.config.libdir_relative() {
825 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
826 _ => libdir(compiler.host).as_ref(),
831 /// Returns the compiler's relative libdir where the standard library and other artifacts are
832 /// found for a compiler's sysroot.
834 /// For example this returns `lib` on Unix and Windows.
835 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
836 match self.config.libdir_relative() {
837 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
838 _ if compiler.stage == 0 => &self.build.initial_libdir,
839 _ => Path::new("lib"),
843 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
844 /// library lookup path.
845 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
846 // Windows doesn't need dylib path munging because the dlls for the
847 // compiler live next to the compiler and the system will find them
853 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
855 // Ensure that the downloaded LLVM libraries can be found.
856 if self.config.llvm_from_ci {
857 let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
858 dylib_dirs.push(ci_llvm_lib);
861 add_dylib_path(dylib_dirs, cmd);
864 /// Gets a path to the compiler specified.
865 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
866 if compiler.is_snapshot(self) {
867 self.initial_rustc.clone()
869 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
873 /// Gets the paths to all of the compiler's codegen backends.
874 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
875 fs::read_dir(self.sysroot_codegen_backends(compiler))
878 .filter_map(Result::ok)
879 .map(|entry| entry.path())
882 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
883 self.ensure(tool::Rustdoc { compiler })
886 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
887 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
888 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
889 .env("RUSTC_SYSROOT", self.sysroot(compiler))
890 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
891 // equivalently to rustc.
892 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
893 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
894 .env("RUSTDOC_REAL", self.rustdoc(compiler))
895 .env("RUSTC_BOOTSTRAP", "1");
897 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
899 if self.config.deny_warnings {
900 cmd.arg("-Dwarnings");
902 cmd.arg("-Znormalize-docs");
904 // Remove make-related flags that can cause jobserver problems.
905 cmd.env_remove("MAKEFLAGS");
906 cmd.env_remove("MFLAGS");
908 if let Some(linker) = self.linker(compiler.host) {
909 cmd.env("RUSTDOC_LINKER", linker);
911 if self.is_fuse_ld_lld(compiler.host) {
912 cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
917 /// Return the path to `llvm-config` for the target, if it exists.
919 /// Note that this returns `None` if LLVM is disabled, or if we're in a
920 /// check build or dry-run, where there's no need to build all of LLVM.
921 fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
922 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
923 let llvm_config = self.ensure(native::Llvm { target });
924 if llvm_config.is_file() {
925 return Some(llvm_config);
931 /// Prepares an invocation of `cargo` to be run.
933 /// This will create a `Command` that represents a pending execution of
934 /// Cargo. This cargo will be configured to use `compiler` as the actual
935 /// rustc compiler, its output will be scoped by `mode`'s output directory,
936 /// it will pass the `--target` flag for the specified `target`, and will be
937 /// executing the Cargo command `cmd`.
942 source_type: SourceType,
943 target: TargetSelection,
946 let mut cargo = Command::new(&self.initial_cargo);
947 let out_dir = self.stage_out(compiler, mode);
949 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
950 // so we need to explicitly clear out if they've been updated.
951 for backend in self.codegen_backends(compiler) {
952 self.clear_if_dirty(&out_dir, &backend);
955 if cmd == "doc" || cmd == "rustdoc" {
956 let my_out = match mode {
957 // This is the intended out directory for compiler documentation.
958 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
959 Mode::Std => out_dir.join(target.triple).join("doc"),
960 _ => panic!("doc mode {:?} not expected", mode),
962 let rustdoc = self.rustdoc(compiler);
963 self.clear_if_dirty(&my_out, &rustdoc);
966 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
968 let profile_var = |name: &str| {
969 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
970 format!("CARGO_PROFILE_{}_{}", profile, name)
973 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
974 // needs to not accidentally link to libLLVM in stage0/lib.
975 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
976 if let Some(e) = env::var_os(util::dylib_path_var()) {
977 cargo.env("REAL_LIBRARY_PATH", e);
980 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
981 // from out of tree it shouldn't matter, since x.py is only used for
983 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
984 match self.build.config.color {
986 cargo.arg("--color=always");
987 for log in &color_logs {
988 cargo.env(log, "always");
992 cargo.arg("--color=never");
993 for log in &color_logs {
994 cargo.env(log, "never");
997 Color::Auto => {} // nothing to do
1000 if cmd != "install" {
1001 cargo.arg("--target").arg(target.rustc_target_arg());
1003 assert_eq!(target, compiler.host);
1006 // Set a flag for `check`/`clippy`/`fix`, so that certain build
1007 // scripts can do less work (i.e. not building/requiring LLVM).
1008 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
1009 // If we've not yet built LLVM, or it's stale, then bust
1010 // the rustc_llvm cache. That will always work, even though it
1011 // may mean that on the next non-check build we'll need to rebuild
1012 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
1013 // of work comparitively, and we'd likely need to rebuild it anyway,
1015 if crate::native::prebuilt_llvm_config(self, target).is_err() {
1016 cargo.env("RUST_CHECK", "1");
1020 let stage = if compiler.stage == 0 && self.local_rebuild {
1021 // Assume the local-rebuild rustc already has stage1 features.
1027 let mut rustflags = Rustflags::new(target);
1029 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
1030 cargo.args(s.split_whitespace());
1032 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
1034 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
1035 cargo.args(s.split_whitespace());
1037 rustflags.env("RUSTFLAGS_BOOTSTRAP");
1038 if cmd == "clippy" {
1039 // clippy overwrites sysroot if we pass it to cargo.
1040 // Pass it directly to clippy instead.
1041 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
1042 // so it has no way of knowing the sysroot.
1043 rustflags.arg("--sysroot");
1045 self.sysroot(compiler)
1048 .expect("sysroot must be valid UTF-8"),
1050 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
1051 cargo.arg("-Zunstable-options");
1052 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
1053 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
1054 let output = host_version.and_then(|output| {
1055 if output.status.success() {
1060 }).unwrap_or_else(|_| {
1062 "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
1064 eprintln!("help: try `rustup component add clippy`");
1065 std::process::exit(1);
1067 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
1068 rustflags.arg("--cfg=bootstrap");
1071 rustflags.arg("--cfg=bootstrap");
1075 let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
1077 // If an explicit setting is given, use that
1081 if mode == Mode::Std {
1082 // The standard library defaults to the legacy scheme
1085 // The compiler and tools default to the new scheme
1091 // cfg(bootstrap) -- drop the compiler.stage == 0 branch.
1092 if compiler.stage == 0 {
1093 if use_new_symbol_mangling {
1094 rustflags.arg("-Zsymbol-mangling-version=v0");
1096 rustflags.arg("-Zsymbol-mangling-version=legacy");
1099 if use_new_symbol_mangling {
1100 rustflags.arg("-Csymbol-mangling-version=v0");
1102 rustflags.arg("-Csymbol-mangling-version=legacy");
1103 rustflags.arg("-Zunstable-options");
1107 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1108 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1110 let mut rustdocflags = rustflags.clone();
1111 rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1113 rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1115 rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1118 if let Ok(s) = env::var("CARGOFLAGS") {
1119 cargo.args(s.split_whitespace());
1123 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1124 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1125 // Build proc macros both for the host and the target
1126 if target != compiler.host && cmd != "check" {
1127 cargo.arg("-Zdual-proc-macros");
1128 rustflags.arg("-Zdual-proc-macros");
1133 // This tells Cargo (and in turn, rustc) to output more complete
1134 // dependency information. Most importantly for rustbuild, this
1135 // includes sysroot artifacts, like libstd, which means that we don't
1136 // need to track those in rustbuild (an error prone process!). This
1137 // feature is currently unstable as there may be some bugs and such, but
1138 // it represents a big improvement in rustbuild's reliability on
1139 // rebuilds, so we're using it here.
1141 // For some additional context, see #63470 (the PR originally adding
1142 // this), as well as #63012 which is the tracking issue for this
1143 // feature on the rustc side.
1144 cargo.arg("-Zbinary-dep-depinfo");
1146 cargo.arg("-j").arg(self.jobs().to_string());
1147 // Remove make-related flags to ensure Cargo can correctly set things up
1148 cargo.env_remove("MAKEFLAGS");
1149 cargo.env_remove("MFLAGS");
1151 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1152 // Force cargo to output binaries with disambiguating hashes in the name
1153 let mut metadata = if compiler.stage == 0 {
1154 // Treat stage0 like a special channel, whether it's a normal prior-
1155 // release rustc or a local rebuild with the same version, so we
1156 // never mix these libraries by accident.
1157 "bootstrap".to_string()
1159 self.config.channel.to_string()
1161 // We want to make sure that none of the dependencies between
1162 // std/test/rustc unify with one another. This is done for weird linkage
1163 // reasons but the gist of the problem is that if librustc, libtest, and
1164 // libstd all depend on libc from crates.io (which they actually do) we
1165 // want to make sure they all get distinct versions. Things get really
1166 // weird if we try to unify all these dependencies right now, namely
1167 // around how many times the library is linked in dynamic libraries and
1168 // such. If rustc were a static executable or if we didn't ship dylibs
1169 // this wouldn't be a problem, but we do, so it is. This is in general
1170 // just here to make sure things build right. If you can remove this and
1171 // things still build right, please do!
1173 Mode::Std => metadata.push_str("std"),
1174 // When we're building rustc tools, they're built with a search path
1175 // that contains things built during the rustc build. For example,
1176 // bitflags is built during the rustc build, and is a dependency of
1177 // rustdoc as well. We're building rustdoc in a different target
1178 // directory, though, which means that Cargo will rebuild the
1179 // dependency. When we go on to build rustdoc, we'll look for
1180 // bitflags, and find two different copies: one built during the
1181 // rustc step and one that we just built. This isn't always a
1182 // problem, somehow -- not really clear why -- but we know that this
1184 Mode::ToolRustc => metadata.push_str("tool-rustc"),
1185 // Same for codegen backends.
1186 Mode::Codegen => metadata.push_str("codegen"),
1189 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1191 if cmd == "clippy" {
1192 rustflags.arg("-Zforce-unstable-if-unmarked");
1195 rustflags.arg("-Zmacro-backtrace");
1197 let want_rustdoc = self.doc_tests != DocTests::No;
1199 // We synthetically interpret a stage0 compiler used to build tools as a
1200 // "raw" compiler in that it's the exact snapshot we download. Normally
1201 // the stage0 build means it uses libraries build by the stage0
1202 // compiler, but for tools we just use the precompiled libraries that
1204 let use_snapshot = mode == Mode::ToolBootstrap;
1205 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1207 let maybe_sysroot = self.sysroot(compiler);
1208 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1209 let libdir = self.rustc_libdir(compiler);
1211 // Clear the output directory if the real rustc we're using has changed;
1212 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1214 // Avoid doing this during dry run as that usually means the relevant
1215 // compiler is not yet linked/copied properly.
1217 // Only clear out the directory if we're compiling std; otherwise, we
1218 // should let Cargo take care of things for us (via depdep info)
1219 if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1220 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1223 // Customize the compiler we're running. Specify the compiler to cargo
1224 // as our shim and then pass it some various options used to configure
1225 // how the actual compiler itself is called.
1227 // These variables are primarily all read by
1228 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1230 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1231 .env("RUSTC_REAL", self.rustc(compiler))
1232 .env("RUSTC_STAGE", stage.to_string())
1233 .env("RUSTC_SYSROOT", &sysroot)
1234 .env("RUSTC_LIBDIR", &libdir)
1235 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
1238 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1239 self.rustdoc(compiler)
1241 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1244 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1245 .env("RUSTC_BREAK_ON_ICE", "1");
1246 // Clippy support is a hack and uses the default `cargo-clippy` in path.
1247 // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1248 if cmd != "clippy" {
1249 cargo.env("RUSTC", self.out.join("bootstrap/debug/rustc"));
1252 // Dealing with rpath here is a little special, so let's go into some
1253 // detail. First off, `-rpath` is a linker option on Unix platforms
1254 // which adds to the runtime dynamic loader path when looking for
1255 // dynamic libraries. We use this by default on Unix platforms to ensure
1256 // that our nightlies behave the same on Windows, that is they work out
1257 // of the box. This can be disabled, of course, but basically that's why
1258 // we're gated on RUSTC_RPATH here.
1260 // Ok, so the astute might be wondering "why isn't `-C rpath` used
1261 // here?" and that is indeed a good question to ask. This codegen
1262 // option is the compiler's current interface to generating an rpath.
1263 // Unfortunately it doesn't quite suffice for us. The flag currently
1264 // takes no value as an argument, so the compiler calculates what it
1265 // should pass to the linker as `-rpath`. This unfortunately is based on
1266 // the **compile time** directory structure which when building with
1267 // Cargo will be very different than the runtime directory structure.
1269 // All that's a really long winded way of saying that if we use
1270 // `-Crpath` then the executables generated have the wrong rpath of
1271 // something like `$ORIGIN/deps` when in fact the way we distribute
1272 // rustc requires the rpath to be `$ORIGIN/../lib`.
1274 // So, all in all, to set up the correct rpath we pass the linker
1275 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1276 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1277 // to change a flag in a binary?
1278 if self.config.rust_rpath && util::use_host_linker(target) {
1279 let rpath = if target.contains("apple") {
1280 // Note that we need to take one extra step on macOS to also pass
1281 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1282 // do that we pass a weird flag to the compiler to get it to do
1283 // so. Note that this is definitely a hack, and we should likely
1284 // flesh out rpath support more fully in the future.
1285 rustflags.arg("-Zosx-rpath-install-name");
1286 Some("-Wl,-rpath,@loader_path/../lib")
1287 } else if !target.contains("windows") {
1288 rustflags.arg("-Clink-args=-Wl,-z,origin");
1289 Some("-Wl,-rpath,$ORIGIN/../lib")
1293 if let Some(rpath) = rpath {
1294 rustflags.arg(&format!("-Clink-args={}", rpath));
1298 if let Some(host_linker) = self.linker(compiler.host) {
1299 cargo.env("RUSTC_HOST_LINKER", host_linker);
1301 if self.is_fuse_ld_lld(compiler.host) {
1302 cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1303 cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1306 if let Some(target_linker) = self.linker(target) {
1307 let target = crate::envify(&target.triple);
1308 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1310 if self.is_fuse_ld_lld(target) {
1311 rustflags.arg("-Clink-args=-fuse-ld=lld");
1313 self.lld_flags(target).for_each(|flag| {
1314 rustdocflags.arg(&flag);
1317 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1318 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1321 let debuginfo_level = match mode {
1322 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1323 Mode::Std => self.config.rust_debuginfo_level_std,
1324 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1325 self.config.rust_debuginfo_level_tools
1328 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1330 profile_var("DEBUG_ASSERTIONS"),
1331 if mode == Mode::Std {
1332 self.config.rust_debug_assertions_std.to_string()
1334 self.config.rust_debug_assertions.to_string()
1338 profile_var("OVERFLOW_CHECKS"),
1339 if mode == Mode::Std {
1340 self.config.rust_overflow_checks_std.to_string()
1342 self.config.rust_overflow_checks.to_string()
1346 // `dsymutil` adds time to builds on Apple platforms for no clear benefit, and also makes
1347 // it more difficult for debuggers to find debug info. The compiler currently defaults to
1348 // running `dsymutil` to preserve its historical default, but when compiling the compiler
1349 // itself, we skip it by default since we know it's safe to do so in that case.
1350 // See https://github.com/rust-lang/rust/issues/79361 for more info on this flag.
1351 if target.contains("apple") {
1352 if self.config.rust_run_dsymutil {
1353 rustflags.arg("-Csplit-debuginfo=packed");
1355 rustflags.arg("-Csplit-debuginfo=unpacked");
1359 if self.config.cmd.bless() {
1360 // Bless `expect!` tests.
1361 cargo.env("UPDATE_EXPECT", "1");
1364 if !mode.is_tool() {
1365 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1368 if let Some(x) = self.crt_static(target) {
1370 rustflags.arg("-Ctarget-feature=+crt-static");
1372 rustflags.arg("-Ctarget-feature=-crt-static");
1376 if let Some(x) = self.crt_static(compiler.host) {
1377 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1380 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1381 let map = format!("{}={}", self.build.src.display(), map_to);
1382 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1384 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1385 // in order to opportunistically reverse it later.
1386 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1389 // Enable usage of unstable features
1390 cargo.env("RUSTC_BOOTSTRAP", "1");
1391 self.add_rust_test_threads(&mut cargo);
1393 // Almost all of the crates that we compile as part of the bootstrap may
1394 // have a build script, including the standard library. To compile a
1395 // build script, however, it itself needs a standard library! This
1396 // introduces a bit of a pickle when we're compiling the standard
1399 // To work around this we actually end up using the snapshot compiler
1400 // (stage0) for compiling build scripts of the standard library itself.
1401 // The stage0 compiler is guaranteed to have a libstd available for use.
1403 // For other crates, however, we know that we've already got a standard
1404 // library up and running, so we can use the normal compiler to compile
1405 // build scripts in that situation.
1406 if mode == Mode::Std {
1408 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1409 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1412 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1413 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1416 // Tools that use compiler libraries may inherit the `-lLLVM` link
1417 // requirement, but the `-L` library path is not propagated across
1418 // separate Cargo projects. We can add LLVM's library path to the
1419 // platform-specific environment variable as a workaround.
1420 if mode == Mode::ToolRustc || mode == Mode::Codegen {
1421 if let Some(llvm_config) = self.llvm_config(target) {
1422 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1423 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1427 // Compile everything except libraries and proc macros with the more
1428 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1429 // so we can't use it by default in general, but we can use it for tools
1430 // and our own internal libraries.
1431 if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1432 rustflags.arg("-Ztls-model=initial-exec");
1435 if self.config.incremental {
1436 cargo.env("CARGO_INCREMENTAL", "1");
1438 // Don't rely on any default setting for incr. comp. in Cargo
1439 cargo.env("CARGO_INCREMENTAL", "0");
1442 if let Some(ref on_fail) = self.config.on_fail {
1443 cargo.env("RUSTC_ON_FAIL", on_fail);
1446 if self.config.print_step_timings {
1447 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1450 if self.config.print_step_rusage {
1451 cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1454 if self.config.backtrace_on_ice {
1455 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1458 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1460 if source_type == SourceType::InTree {
1461 let mut lint_flags = Vec::new();
1462 // When extending this list, add the new lints to the RUSTFLAGS of the
1463 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1464 // some code doesn't go through this `rustc` wrapper.
1465 lint_flags.push("-Wrust_2018_idioms");
1466 lint_flags.push("-Wunused_lifetimes");
1467 lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1469 if self.config.deny_warnings {
1470 lint_flags.push("-Dwarnings");
1471 rustdocflags.arg("-Dwarnings");
1474 // This does not use RUSTFLAGS due to caching issues with Cargo.
1475 // Clippy is treated as an "in tree" tool, but shares the same
1476 // cache as other "submodule" tools. With these options set in
1477 // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1478 // By injecting this into the rustc wrapper, this circumvents
1479 // Cargo's fingerprint detection. This is fine because lint flags
1480 // are always ignored in dependencies. Eventually this should be
1481 // fixed via better support from Cargo.
1482 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1484 rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1487 if mode == Mode::Rustc {
1488 rustflags.arg("-Zunstable-options");
1489 rustflags.arg("-Wrustc::internal");
1492 // Throughout the build Cargo can execute a number of build scripts
1493 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1494 // obtained previously to those build scripts.
1495 // Build scripts use either the `cc` crate or `configure/make` so we pass
1496 // the options through environment variables that are fetched and understood by both.
1498 // FIXME: the guard against msvc shouldn't need to be here
1499 if target.contains("msvc") {
1500 if let Some(ref cl) = self.config.llvm_clang_cl {
1501 cargo.env("CC", cl).env("CXX", cl);
1504 let ccache = self.config.ccache.as_ref();
1505 let ccacheify = |s: &Path| {
1506 let ccache = match ccache {
1508 None => return s.display().to_string(),
1510 // FIXME: the cc-rs crate only recognizes the literal strings
1511 // `ccache` and `sccache` when doing caching compilations, so we
1512 // mirror that here. It should probably be fixed upstream to
1513 // accept a new env var or otherwise work with custom ccache
1516 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1517 _ => s.display().to_string(),
1520 let cc = ccacheify(&self.cc(target));
1521 cargo.env(format!("CC_{}", target.triple), &cc);
1523 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1524 cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1526 if let Some(ar) = self.ar(target) {
1527 let ranlib = format!("{} s", ar.display());
1529 .env(format!("AR_{}", target.triple), ar)
1530 .env(format!("RANLIB_{}", target.triple), ranlib);
1533 if let Ok(cxx) = self.cxx(target) {
1534 let cxx = ccacheify(&cxx);
1536 .env(format!("CXX_{}", target.triple), &cxx)
1537 .env(format!("CXXFLAGS_{}", target.triple), cflags);
1541 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1542 rustflags.arg("-Zsave-analysis");
1544 "RUST_SAVE_ANALYSIS_CONFIG",
1545 "{\"output_file\": null,\"full_docs\": false,\
1546 \"pub_only\": true,\"reachable_only\": false,\
1547 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1551 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1552 // when compiling the standard library, since this might be linked into the final outputs
1553 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1554 // for the standard library in case the compiler is run on a non-Windows platform.
1555 // This is not needed for stage 0 artifacts because these will only be used for building
1556 // the stage 1 compiler.
1558 && mode == Mode::Std
1559 && self.config.control_flow_guard
1560 && compiler.stage >= 1
1562 rustflags.arg("-Ccontrol-flow-guard");
1565 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1566 // This replaces spaces with newlines because RUSTDOCFLAGS does not
1567 // support arguments with regular spaces. Hopefully someday Cargo will
1568 // have space support.
1569 let rust_version = self.rust_version().replace(' ', "\n");
1570 rustdocflags.arg("--crate-version").arg(&rust_version);
1572 // Environment variables *required* throughout the build
1574 // FIXME: should update code to not require this env var
1575 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1577 // Set this for all builds to make sure doc builds also get it.
1578 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1580 // This one's a bit tricky. As of the time of this writing the compiler
1581 // links to the `winapi` crate on crates.io. This crate provides raw
1582 // bindings to Windows system functions, sort of like libc does for
1583 // Unix. This crate also, however, provides "import libraries" for the
1584 // MinGW targets. There's an import library per dll in the windows
1585 // distribution which is what's linked to. These custom import libraries
1586 // are used because the winapi crate can reference Windows functions not
1587 // present in the MinGW import libraries.
1589 // For example MinGW may ship libdbghelp.a, but it may not have
1590 // references to all the functions in the dbghelp dll. Instead the
1591 // custom import library for dbghelp in the winapi crates has all this
1594 // Unfortunately for us though the import libraries are linked by
1595 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1596 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1597 // conflict with the system MinGW ones). This consequently means that
1598 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1599 // DLL) when linked against *again*, for example with procedural macros
1600 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1601 // `-lwinapi_foo` to the linker again. This isn't actually available in
1602 // our distribution, however, so the link fails.
1604 // To solve this problem we tell winapi to not use its bundled import
1605 // libraries. This means that it will link to the system MinGW import
1606 // libraries by default, and the `-ldylib=foo` directives will still get
1607 // passed to the final linker, but they'll look like `-lfoo` which can
1608 // be resolved because MinGW has the import library. The downside is we
1609 // don't get newer functions from Windows, but we don't use any of them
1611 if !mode.is_tool() {
1612 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1615 for _ in 0..self.verbosity {
1619 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1620 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1621 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1624 // Don't set anything
1628 if self.config.rust_optimize {
1629 // FIXME: cargo bench/install do not accept `--release`
1630 if cmd != "bench" && cmd != "install" {
1631 cargo.arg("--release");
1635 if self.config.locked_deps {
1636 cargo.arg("--locked");
1638 if self.config.vendor || self.is_sudo {
1639 cargo.arg("--frozen");
1642 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1643 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1645 self.ci_env.force_coloring_in_ci(&mut cargo);
1647 // When we build Rust dylibs they're all intended for intermediate
1648 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1649 // linking all deps statically into the dylib.
1650 if matches!(mode, Mode::Std | Mode::Rustc) {
1651 rustflags.arg("-Cprefer-dynamic");
1654 // When building incrementally we default to a lower ThinLTO import limit
1655 // (unless explicitly specified otherwise). This will produce a somewhat
1656 // slower code but give way better compile times.
1658 let limit = match self.config.rust_thin_lto_import_instr_limit {
1659 Some(limit) => Some(limit),
1660 None if self.config.incremental => Some(10),
1664 if let Some(limit) = limit {
1665 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1669 Cargo { command: cargo, rustflags, rustdocflags }
1672 /// Ensure that a given step is built, returning its output. This will
1673 /// cache the step, so it is safe (and good!) to call this as often as
1674 /// needed to ensure that all dependencies are built.
1675 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1677 let mut stack = self.stack.borrow_mut();
1678 for stack_step in stack.iter() {
1680 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1683 let mut out = String::new();
1684 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1685 for el in stack.iter().rev() {
1686 out += &format!("\t{:?}\n", el);
1690 if let Some(out) = self.cache.get(&step) {
1691 self.verbose_than(1, &format!("{}c {:?}", " ".repeat(stack.len()), step));
1695 self.verbose_than(1, &format!("{}> {:?}", " ".repeat(stack.len()), step));
1696 stack.push(Box::new(step.clone()));
1700 let start = Instant::now();
1701 let zero = Duration::new(0, 0);
1702 let parent = self.time_spent_on_dependencies.replace(zero);
1703 let out = step.clone().run(self);
1704 let dur = start.elapsed();
1705 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1709 if self.config.print_step_timings && !self.config.dry_run {
1710 println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1714 let mut stack = self.stack.borrow_mut();
1715 let cur_step = stack.pop().expect("step stack empty");
1716 assert_eq!(cur_step.downcast_ref(), Some(&step));
1718 self.verbose_than(1, &format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1719 self.cache.put(step, out.clone());
1723 /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1724 /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1725 /// needed to ensure that all dependencies are build.
1726 pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1731 let desc = StepDescription::from::<S>(kind);
1732 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1734 // Avoid running steps contained in --exclude
1735 for pathset in &should_run.paths {
1736 if desc.is_excluded(self, pathset) {
1741 // Only execute if it's supposed to run as default
1742 if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1745 /// Checks if any of the "should_run" paths is in the `Builder` paths.
1746 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1747 let desc = StepDescription::from::<S>(kind);
1748 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1750 for path in &self.paths {
1751 if should_run.paths.iter().any(|s| s.has(path, Some(desc.kind)))
1752 && !desc.is_excluded(
1754 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind.into()) }),
1768 #[derive(Debug, Clone)]
1769 struct Rustflags(String, TargetSelection);
1772 fn new(target: TargetSelection) -> Rustflags {
1773 let mut ret = Rustflags(String::new(), target);
1774 ret.propagate_cargo_env("RUSTFLAGS");
1778 /// By default, cargo will pick up on various variables in the environment. However, bootstrap
1779 /// reuses those variables to pass additional flags to rustdoc, so by default they get overriden.
1780 /// Explicitly add back any previous value in the environment.
1782 /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
1783 fn propagate_cargo_env(&mut self, prefix: &str) {
1784 // Inherit `RUSTFLAGS` by default ...
1787 // ... and also handle target-specific env RUSTFLAGS if they're configured.
1788 let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
1789 self.env(&target_specific);
1792 fn env(&mut self, env: &str) {
1793 if let Ok(s) = env::var(env) {
1794 for part in s.split(' ') {
1800 fn arg(&mut self, arg: &str) -> &mut Self {
1801 assert_eq!(arg.split(' ').count(), 1);
1802 if !self.0.is_empty() {
1805 self.0.push_str(arg);
1813 rustflags: Rustflags,
1814 rustdocflags: Rustflags,
1818 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
1819 self.rustdocflags.arg(arg);
1822 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1823 self.rustflags.arg(arg);
1827 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1828 self.command.arg(arg.as_ref());
1832 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1834 I: IntoIterator<Item = S>,
1838 self.arg(arg.as_ref());
1843 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1844 // These are managed through rustflag/rustdocflag interfaces.
1845 assert_ne!(key.as_ref(), "RUSTFLAGS");
1846 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
1847 self.command.env(key.as_ref(), value.as_ref());
1851 pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
1852 builder.add_rustc_lib_path(compiler, &mut self.command);
1855 pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
1856 self.command.current_dir(dir);
1861 impl From<Cargo> for Command {
1862 fn from(mut cargo: Cargo) -> Command {
1863 let rustflags = &cargo.rustflags.0;
1864 if !rustflags.is_empty() {
1865 cargo.command.env("RUSTFLAGS", rustflags);
1868 let rustdocflags = &cargo.rustdocflags.0;
1869 if !rustdocflags.is_empty() {
1870 cargo.command.env("RUSTDOCFLAGS", rustdocflags);