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,
591 dist::PlainSourceTarball,
603 dist::ReproducibleArtifacts,
605 Kind::Install => describe!(
610 install::RustAnalyzer,
612 install::RustDemangler,
619 Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest, run::BumpStage0),
623 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
624 let kind = match subcommand {
625 "build" => Kind::Build,
627 "test" => Kind::Test,
628 "bench" => Kind::Bench,
629 "dist" => Kind::Dist,
630 "install" => Kind::Install,
634 let builder = Self::new_internal(build, kind, vec![]);
635 let builder = &builder;
636 // The "build" kind here is just a placeholder, it will be replaced with something else in
637 // the following statement.
638 let mut should_run = ShouldRun::new(builder, Kind::Build);
639 for desc in Builder::get_step_descriptions(builder.kind) {
640 should_run.kind = desc.kind;
641 should_run = (desc.should_run)(should_run);
643 let mut help = String::from("Available paths:\n");
644 let mut add_path = |path: &Path| {
645 help.push_str(&format!(" ./x.py {} {}\n", subcommand, path.display()));
647 for pathset in should_run.paths {
649 PathSet::Set(set) => {
651 add_path(&path.path);
654 PathSet::Suite(path) => {
655 add_path(&path.path.join("..."));
662 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
665 top_stage: build.config.stage,
668 stack: RefCell::new(Vec::new()),
669 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
674 pub fn new(build: &Build) -> Builder<'_> {
675 let (kind, paths) = match build.config.cmd {
676 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
677 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
678 Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
679 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
680 Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
681 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
682 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
683 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
684 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
685 Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
686 Subcommand::Format { .. } | Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
691 Self::new_internal(build, kind, paths.to_owned())
694 pub fn execute_cli(&self) {
695 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
698 pub fn default_doc(&self, paths: &[PathBuf]) {
699 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
702 /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
703 pub fn doc_rust_lang_org_channel(&self) -> String {
704 let channel = match &*self.config.channel {
705 "stable" => &self.version,
707 "nightly" | "dev" => "nightly",
708 // custom build of rustdoc maybe? link to the latest stable docs just in case
711 "https://doc.rust-lang.org/".to_owned() + channel
714 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
715 StepDescription::run(v, self, paths);
718 /// Obtain a compiler at a given stage and for a given host. Explicitly does
719 /// not take `Compiler` since all `Compiler` instances are meant to be
720 /// obtained through this function, since it ensures that they are valid
721 /// (i.e., built and assembled).
722 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
723 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
726 /// Similar to `compiler`, except handles the full-bootstrap option to
727 /// silently use the stage1 compiler instead of a stage2 compiler if one is
730 /// Note that this does *not* have the side effect of creating
731 /// `compiler(stage, host)`, unlike `compiler` above which does have such
732 /// a side effect. The returned compiler here can only be used to compile
733 /// new artifacts, it can't be used to rely on the presence of a particular
736 /// See `force_use_stage1` for documentation on what each argument is.
740 host: TargetSelection,
741 target: TargetSelection,
743 if self.build.force_use_stage1(Compiler { stage, host }, target) {
744 self.compiler(1, self.config.build)
746 self.compiler(stage, host)
750 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
751 self.ensure(compile::Sysroot { compiler })
754 /// Returns the libdir where the standard library and other artifacts are
755 /// found for a compiler's sysroot.
756 pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
757 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
760 target: TargetSelection,
762 impl Step for Libdir {
763 type Output = Interned<PathBuf>;
765 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
769 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
770 let lib = builder.sysroot_libdir_relative(self.compiler);
771 let sysroot = builder
772 .sysroot(self.compiler)
775 .join(self.target.triple)
777 // Avoid deleting the rustlib/ directory we just copied
778 // (in `impl Step for Sysroot`).
779 if !builder.config.download_rustc {
780 let _ = fs::remove_dir_all(&sysroot);
781 t!(fs::create_dir_all(&sysroot));
783 INTERNER.intern_path(sysroot)
786 self.ensure(Libdir { compiler, target })
789 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
790 self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
793 /// Returns the compiler's libdir where it stores the dynamic libraries that
794 /// it itself links against.
796 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
798 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
799 if compiler.is_snapshot(self) {
800 self.rustc_snapshot_libdir()
802 match self.config.libdir_relative() {
803 Some(relative_libdir) if compiler.stage >= 1 => {
804 self.sysroot(compiler).join(relative_libdir)
806 _ => self.sysroot(compiler).join(libdir(compiler.host)),
811 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
812 /// it itself links against.
814 /// For example this returns `lib` on Unix and `bin` on
816 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
817 if compiler.is_snapshot(self) {
818 libdir(self.config.build).as_ref()
820 match self.config.libdir_relative() {
821 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
822 _ => libdir(compiler.host).as_ref(),
827 /// Returns the compiler's relative libdir where the standard library and other artifacts are
828 /// found for a compiler's sysroot.
830 /// For example this returns `lib` on Unix and Windows.
831 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
832 match self.config.libdir_relative() {
833 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
834 _ if compiler.stage == 0 => &self.build.initial_libdir,
835 _ => Path::new("lib"),
839 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
840 /// library lookup path.
841 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
842 // Windows doesn't need dylib path munging because the dlls for the
843 // compiler live next to the compiler and the system will find them
849 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
851 // Ensure that the downloaded LLVM libraries can be found.
852 if self.config.llvm_from_ci {
853 let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
854 dylib_dirs.push(ci_llvm_lib);
857 add_dylib_path(dylib_dirs, cmd);
860 /// Gets a path to the compiler specified.
861 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
862 if compiler.is_snapshot(self) {
863 self.initial_rustc.clone()
865 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
869 /// Gets the paths to all of the compiler's codegen backends.
870 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
871 fs::read_dir(self.sysroot_codegen_backends(compiler))
874 .filter_map(Result::ok)
875 .map(|entry| entry.path())
878 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
879 self.ensure(tool::Rustdoc { compiler })
882 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
883 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
884 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
885 .env("RUSTC_SYSROOT", self.sysroot(compiler))
886 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
887 // equivalently to rustc.
888 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
889 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
890 .env("RUSTDOC_REAL", self.rustdoc(compiler))
891 .env("RUSTC_BOOTSTRAP", "1");
893 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
895 if self.config.deny_warnings {
896 cmd.arg("-Dwarnings");
898 cmd.arg("-Znormalize-docs");
900 // Remove make-related flags that can cause jobserver problems.
901 cmd.env_remove("MAKEFLAGS");
902 cmd.env_remove("MFLAGS");
904 if let Some(linker) = self.linker(compiler.host) {
905 cmd.env("RUSTDOC_LINKER", linker);
907 if self.is_fuse_ld_lld(compiler.host) {
908 cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
913 /// Return the path to `llvm-config` for the target, if it exists.
915 /// Note that this returns `None` if LLVM is disabled, or if we're in a
916 /// check build or dry-run, where there's no need to build all of LLVM.
917 fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
918 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
919 let llvm_config = self.ensure(native::Llvm { target });
920 if llvm_config.is_file() {
921 return Some(llvm_config);
927 /// Prepares an invocation of `cargo` to be run.
929 /// This will create a `Command` that represents a pending execution of
930 /// Cargo. This cargo will be configured to use `compiler` as the actual
931 /// rustc compiler, its output will be scoped by `mode`'s output directory,
932 /// it will pass the `--target` flag for the specified `target`, and will be
933 /// executing the Cargo command `cmd`.
938 source_type: SourceType,
939 target: TargetSelection,
942 let mut cargo = Command::new(&self.initial_cargo);
943 let out_dir = self.stage_out(compiler, mode);
945 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
946 // so we need to explicitly clear out if they've been updated.
947 for backend in self.codegen_backends(compiler) {
948 self.clear_if_dirty(&out_dir, &backend);
951 if cmd == "doc" || cmd == "rustdoc" {
952 let my_out = match mode {
953 // This is the intended out directory for compiler documentation.
954 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
955 Mode::Std => out_dir.join(target.triple).join("doc"),
956 _ => panic!("doc mode {:?} not expected", mode),
958 let rustdoc = self.rustdoc(compiler);
959 self.clear_if_dirty(&my_out, &rustdoc);
962 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
964 let profile_var = |name: &str| {
965 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
966 format!("CARGO_PROFILE_{}_{}", profile, name)
969 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
970 // needs to not accidentally link to libLLVM in stage0/lib.
971 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
972 if let Some(e) = env::var_os(util::dylib_path_var()) {
973 cargo.env("REAL_LIBRARY_PATH", e);
976 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
977 // from out of tree it shouldn't matter, since x.py is only used for
979 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
980 match self.build.config.color {
982 cargo.arg("--color=always");
983 for log in &color_logs {
984 cargo.env(log, "always");
988 cargo.arg("--color=never");
989 for log in &color_logs {
990 cargo.env(log, "never");
993 Color::Auto => {} // nothing to do
996 if cmd != "install" {
997 cargo.arg("--target").arg(target.rustc_target_arg());
999 assert_eq!(target, compiler.host);
1002 // Set a flag for `check`/`clippy`/`fix`, so that certain build
1003 // scripts can do less work (i.e. not building/requiring LLVM).
1004 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
1005 // If we've not yet built LLVM, or it's stale, then bust
1006 // the rustc_llvm cache. That will always work, even though it
1007 // may mean that on the next non-check build we'll need to rebuild
1008 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
1009 // of work comparitively, and we'd likely need to rebuild it anyway,
1011 if crate::native::prebuilt_llvm_config(self, target).is_err() {
1012 cargo.env("RUST_CHECK", "1");
1016 let stage = if compiler.stage == 0 && self.local_rebuild {
1017 // Assume the local-rebuild rustc already has stage1 features.
1023 let mut rustflags = Rustflags::new(target);
1025 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
1026 cargo.args(s.split_whitespace());
1028 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
1030 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
1031 cargo.args(s.split_whitespace());
1033 rustflags.env("RUSTFLAGS_BOOTSTRAP");
1034 if cmd == "clippy" {
1035 // clippy overwrites sysroot if we pass it to cargo.
1036 // Pass it directly to clippy instead.
1037 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
1038 // so it has no way of knowing the sysroot.
1039 rustflags.arg("--sysroot");
1041 self.sysroot(compiler)
1044 .expect("sysroot must be valid UTF-8"),
1046 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
1047 cargo.arg("-Zunstable-options");
1048 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
1049 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
1050 let output = host_version.and_then(|output| {
1051 if output.status.success() {
1056 }).unwrap_or_else(|_| {
1058 "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
1060 eprintln!("help: try `rustup component add clippy`");
1061 std::process::exit(1);
1063 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
1064 rustflags.arg("--cfg=bootstrap");
1067 rustflags.arg("--cfg=bootstrap");
1071 let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
1073 // If an explicit setting is given, use that
1077 if mode == Mode::Std {
1078 // The standard library defaults to the legacy scheme
1081 // The compiler and tools default to the new scheme
1087 // cfg(bootstrap) -- drop the compiler.stage == 0 branch.
1088 if compiler.stage == 0 {
1089 if use_new_symbol_mangling {
1090 rustflags.arg("-Zsymbol-mangling-version=v0");
1092 rustflags.arg("-Zsymbol-mangling-version=legacy");
1095 if use_new_symbol_mangling {
1096 rustflags.arg("-Csymbol-mangling-version=v0");
1098 rustflags.arg("-Csymbol-mangling-version=legacy");
1099 rustflags.arg("-Zunstable-options");
1103 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1104 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1106 let mut rustdocflags = rustflags.clone();
1107 rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1109 rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1111 rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1114 if let Ok(s) = env::var("CARGOFLAGS") {
1115 cargo.args(s.split_whitespace());
1119 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1120 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1121 // Build proc macros both for the host and the target
1122 if target != compiler.host && cmd != "check" {
1123 cargo.arg("-Zdual-proc-macros");
1124 rustflags.arg("-Zdual-proc-macros");
1129 // This tells Cargo (and in turn, rustc) to output more complete
1130 // dependency information. Most importantly for rustbuild, this
1131 // includes sysroot artifacts, like libstd, which means that we don't
1132 // need to track those in rustbuild (an error prone process!). This
1133 // feature is currently unstable as there may be some bugs and such, but
1134 // it represents a big improvement in rustbuild's reliability on
1135 // rebuilds, so we're using it here.
1137 // For some additional context, see #63470 (the PR originally adding
1138 // this), as well as #63012 which is the tracking issue for this
1139 // feature on the rustc side.
1140 cargo.arg("-Zbinary-dep-depinfo");
1142 cargo.arg("-j").arg(self.jobs().to_string());
1143 // Remove make-related flags to ensure Cargo can correctly set things up
1144 cargo.env_remove("MAKEFLAGS");
1145 cargo.env_remove("MFLAGS");
1147 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1148 // Force cargo to output binaries with disambiguating hashes in the name
1149 let mut metadata = if compiler.stage == 0 {
1150 // Treat stage0 like a special channel, whether it's a normal prior-
1151 // release rustc or a local rebuild with the same version, so we
1152 // never mix these libraries by accident.
1153 "bootstrap".to_string()
1155 self.config.channel.to_string()
1157 // We want to make sure that none of the dependencies between
1158 // std/test/rustc unify with one another. This is done for weird linkage
1159 // reasons but the gist of the problem is that if librustc, libtest, and
1160 // libstd all depend on libc from crates.io (which they actually do) we
1161 // want to make sure they all get distinct versions. Things get really
1162 // weird if we try to unify all these dependencies right now, namely
1163 // around how many times the library is linked in dynamic libraries and
1164 // such. If rustc were a static executable or if we didn't ship dylibs
1165 // this wouldn't be a problem, but we do, so it is. This is in general
1166 // just here to make sure things build right. If you can remove this and
1167 // things still build right, please do!
1169 Mode::Std => metadata.push_str("std"),
1170 // When we're building rustc tools, they're built with a search path
1171 // that contains things built during the rustc build. For example,
1172 // bitflags is built during the rustc build, and is a dependency of
1173 // rustdoc as well. We're building rustdoc in a different target
1174 // directory, though, which means that Cargo will rebuild the
1175 // dependency. When we go on to build rustdoc, we'll look for
1176 // bitflags, and find two different copies: one built during the
1177 // rustc step and one that we just built. This isn't always a
1178 // problem, somehow -- not really clear why -- but we know that this
1180 Mode::ToolRustc => metadata.push_str("tool-rustc"),
1181 // Same for codegen backends.
1182 Mode::Codegen => metadata.push_str("codegen"),
1185 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1187 if cmd == "clippy" {
1188 rustflags.arg("-Zforce-unstable-if-unmarked");
1191 rustflags.arg("-Zmacro-backtrace");
1193 let want_rustdoc = self.doc_tests != DocTests::No;
1195 // We synthetically interpret a stage0 compiler used to build tools as a
1196 // "raw" compiler in that it's the exact snapshot we download. Normally
1197 // the stage0 build means it uses libraries build by the stage0
1198 // compiler, but for tools we just use the precompiled libraries that
1200 let use_snapshot = mode == Mode::ToolBootstrap;
1201 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1203 let maybe_sysroot = self.sysroot(compiler);
1204 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1205 let libdir = self.rustc_libdir(compiler);
1207 // Clear the output directory if the real rustc we're using has changed;
1208 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1210 // Avoid doing this during dry run as that usually means the relevant
1211 // compiler is not yet linked/copied properly.
1213 // Only clear out the directory if we're compiling std; otherwise, we
1214 // should let Cargo take care of things for us (via depdep info)
1215 if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1216 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1219 // Customize the compiler we're running. Specify the compiler to cargo
1220 // as our shim and then pass it some various options used to configure
1221 // how the actual compiler itself is called.
1223 // These variables are primarily all read by
1224 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1226 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1227 .env("RUSTC_REAL", self.rustc(compiler))
1228 .env("RUSTC_STAGE", stage.to_string())
1229 .env("RUSTC_SYSROOT", &sysroot)
1230 .env("RUSTC_LIBDIR", &libdir)
1231 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
1234 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1235 self.rustdoc(compiler)
1237 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1240 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1241 .env("RUSTC_BREAK_ON_ICE", "1");
1242 // Clippy support is a hack and uses the default `cargo-clippy` in path.
1243 // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1244 if cmd != "clippy" {
1245 cargo.env("RUSTC", self.out.join("bootstrap/debug/rustc"));
1248 // Dealing with rpath here is a little special, so let's go into some
1249 // detail. First off, `-rpath` is a linker option on Unix platforms
1250 // which adds to the runtime dynamic loader path when looking for
1251 // dynamic libraries. We use this by default on Unix platforms to ensure
1252 // that our nightlies behave the same on Windows, that is they work out
1253 // of the box. This can be disabled, of course, but basically that's why
1254 // we're gated on RUSTC_RPATH here.
1256 // Ok, so the astute might be wondering "why isn't `-C rpath` used
1257 // here?" and that is indeed a good question to ask. This codegen
1258 // option is the compiler's current interface to generating an rpath.
1259 // Unfortunately it doesn't quite suffice for us. The flag currently
1260 // takes no value as an argument, so the compiler calculates what it
1261 // should pass to the linker as `-rpath`. This unfortunately is based on
1262 // the **compile time** directory structure which when building with
1263 // Cargo will be very different than the runtime directory structure.
1265 // All that's a really long winded way of saying that if we use
1266 // `-Crpath` then the executables generated have the wrong rpath of
1267 // something like `$ORIGIN/deps` when in fact the way we distribute
1268 // rustc requires the rpath to be `$ORIGIN/../lib`.
1270 // So, all in all, to set up the correct rpath we pass the linker
1271 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1272 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1273 // to change a flag in a binary?
1274 if self.config.rust_rpath && util::use_host_linker(target) {
1275 let rpath = if target.contains("apple") {
1276 // Note that we need to take one extra step on macOS to also pass
1277 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1278 // do that we pass a weird flag to the compiler to get it to do
1279 // so. Note that this is definitely a hack, and we should likely
1280 // flesh out rpath support more fully in the future.
1281 rustflags.arg("-Zosx-rpath-install-name");
1282 Some("-Wl,-rpath,@loader_path/../lib")
1283 } else if !target.contains("windows") {
1284 rustflags.arg("-Clink-args=-Wl,-z,origin");
1285 Some("-Wl,-rpath,$ORIGIN/../lib")
1289 if let Some(rpath) = rpath {
1290 rustflags.arg(&format!("-Clink-args={}", rpath));
1294 if let Some(host_linker) = self.linker(compiler.host) {
1295 cargo.env("RUSTC_HOST_LINKER", host_linker);
1297 if self.is_fuse_ld_lld(compiler.host) {
1298 cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1299 cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1302 if let Some(target_linker) = self.linker(target) {
1303 let target = crate::envify(&target.triple);
1304 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1306 if self.is_fuse_ld_lld(target) {
1307 rustflags.arg("-Clink-args=-fuse-ld=lld");
1309 self.lld_flags(target).for_each(|flag| {
1310 rustdocflags.arg(&flag);
1313 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1314 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1317 let debuginfo_level = match mode {
1318 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1319 Mode::Std => self.config.rust_debuginfo_level_std,
1320 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1321 self.config.rust_debuginfo_level_tools
1324 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1326 profile_var("DEBUG_ASSERTIONS"),
1327 if mode == Mode::Std {
1328 self.config.rust_debug_assertions_std.to_string()
1330 self.config.rust_debug_assertions.to_string()
1334 profile_var("OVERFLOW_CHECKS"),
1335 if mode == Mode::Std {
1336 self.config.rust_overflow_checks_std.to_string()
1338 self.config.rust_overflow_checks.to_string()
1342 // `dsymutil` adds time to builds on Apple platforms for no clear benefit, and also makes
1343 // it more difficult for debuggers to find debug info. The compiler currently defaults to
1344 // running `dsymutil` to preserve its historical default, but when compiling the compiler
1345 // itself, we skip it by default since we know it's safe to do so in that case.
1346 // See https://github.com/rust-lang/rust/issues/79361 for more info on this flag.
1347 if target.contains("apple") {
1348 if self.config.rust_run_dsymutil {
1349 rustflags.arg("-Csplit-debuginfo=packed");
1351 rustflags.arg("-Csplit-debuginfo=unpacked");
1355 if self.config.cmd.bless() {
1356 // Bless `expect!` tests.
1357 cargo.env("UPDATE_EXPECT", "1");
1360 if !mode.is_tool() {
1361 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1364 if let Some(x) = self.crt_static(target) {
1366 rustflags.arg("-Ctarget-feature=+crt-static");
1368 rustflags.arg("-Ctarget-feature=-crt-static");
1372 if let Some(x) = self.crt_static(compiler.host) {
1373 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1376 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1377 let map = format!("{}={}", self.build.src.display(), map_to);
1378 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1380 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1381 // in order to opportunistically reverse it later.
1382 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1385 // Enable usage of unstable features
1386 cargo.env("RUSTC_BOOTSTRAP", "1");
1387 self.add_rust_test_threads(&mut cargo);
1389 // Almost all of the crates that we compile as part of the bootstrap may
1390 // have a build script, including the standard library. To compile a
1391 // build script, however, it itself needs a standard library! This
1392 // introduces a bit of a pickle when we're compiling the standard
1395 // To work around this we actually end up using the snapshot compiler
1396 // (stage0) for compiling build scripts of the standard library itself.
1397 // The stage0 compiler is guaranteed to have a libstd available for use.
1399 // For other crates, however, we know that we've already got a standard
1400 // library up and running, so we can use the normal compiler to compile
1401 // build scripts in that situation.
1402 if mode == Mode::Std {
1404 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1405 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1408 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1409 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1412 // Tools that use compiler libraries may inherit the `-lLLVM` link
1413 // requirement, but the `-L` library path is not propagated across
1414 // separate Cargo projects. We can add LLVM's library path to the
1415 // platform-specific environment variable as a workaround.
1416 if mode == Mode::ToolRustc || mode == Mode::Codegen {
1417 if let Some(llvm_config) = self.llvm_config(target) {
1418 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1419 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1423 // Compile everything except libraries and proc macros with the more
1424 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1425 // so we can't use it by default in general, but we can use it for tools
1426 // and our own internal libraries.
1427 if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1428 rustflags.arg("-Ztls-model=initial-exec");
1431 if self.config.incremental {
1432 cargo.env("CARGO_INCREMENTAL", "1");
1434 // Don't rely on any default setting for incr. comp. in Cargo
1435 cargo.env("CARGO_INCREMENTAL", "0");
1438 if let Some(ref on_fail) = self.config.on_fail {
1439 cargo.env("RUSTC_ON_FAIL", on_fail);
1442 if self.config.print_step_timings {
1443 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1446 if self.config.print_step_rusage {
1447 cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1450 if self.config.backtrace_on_ice {
1451 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1454 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1456 if source_type == SourceType::InTree {
1457 let mut lint_flags = Vec::new();
1458 // When extending this list, add the new lints to the RUSTFLAGS of the
1459 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1460 // some code doesn't go through this `rustc` wrapper.
1461 lint_flags.push("-Wrust_2018_idioms");
1462 lint_flags.push("-Wunused_lifetimes");
1463 lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1465 if self.config.deny_warnings {
1466 lint_flags.push("-Dwarnings");
1467 rustdocflags.arg("-Dwarnings");
1470 // This does not use RUSTFLAGS due to caching issues with Cargo.
1471 // Clippy is treated as an "in tree" tool, but shares the same
1472 // cache as other "submodule" tools. With these options set in
1473 // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1474 // By injecting this into the rustc wrapper, this circumvents
1475 // Cargo's fingerprint detection. This is fine because lint flags
1476 // are always ignored in dependencies. Eventually this should be
1477 // fixed via better support from Cargo.
1478 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1480 rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1483 if mode == Mode::Rustc {
1484 rustflags.arg("-Zunstable-options");
1485 rustflags.arg("-Wrustc::internal");
1488 // Throughout the build Cargo can execute a number of build scripts
1489 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1490 // obtained previously to those build scripts.
1491 // Build scripts use either the `cc` crate or `configure/make` so we pass
1492 // the options through environment variables that are fetched and understood by both.
1494 // FIXME: the guard against msvc shouldn't need to be here
1495 if target.contains("msvc") {
1496 if let Some(ref cl) = self.config.llvm_clang_cl {
1497 cargo.env("CC", cl).env("CXX", cl);
1500 let ccache = self.config.ccache.as_ref();
1501 let ccacheify = |s: &Path| {
1502 let ccache = match ccache {
1504 None => return s.display().to_string(),
1506 // FIXME: the cc-rs crate only recognizes the literal strings
1507 // `ccache` and `sccache` when doing caching compilations, so we
1508 // mirror that here. It should probably be fixed upstream to
1509 // accept a new env var or otherwise work with custom ccache
1512 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1513 _ => s.display().to_string(),
1516 let cc = ccacheify(&self.cc(target));
1517 cargo.env(format!("CC_{}", target.triple), &cc);
1519 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1520 cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1522 if let Some(ar) = self.ar(target) {
1523 let ranlib = format!("{} s", ar.display());
1525 .env(format!("AR_{}", target.triple), ar)
1526 .env(format!("RANLIB_{}", target.triple), ranlib);
1529 if let Ok(cxx) = self.cxx(target) {
1530 let cxx = ccacheify(&cxx);
1532 .env(format!("CXX_{}", target.triple), &cxx)
1533 .env(format!("CXXFLAGS_{}", target.triple), cflags);
1537 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1538 rustflags.arg("-Zsave-analysis");
1540 "RUST_SAVE_ANALYSIS_CONFIG",
1541 "{\"output_file\": null,\"full_docs\": false,\
1542 \"pub_only\": true,\"reachable_only\": false,\
1543 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1547 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1548 // when compiling the standard library, since this might be linked into the final outputs
1549 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1550 // for the standard library in case the compiler is run on a non-Windows platform.
1551 // This is not needed for stage 0 artifacts because these will only be used for building
1552 // the stage 1 compiler.
1554 && mode == Mode::Std
1555 && self.config.control_flow_guard
1556 && compiler.stage >= 1
1558 rustflags.arg("-Ccontrol-flow-guard");
1561 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1562 // This replaces spaces with newlines because RUSTDOCFLAGS does not
1563 // support arguments with regular spaces. Hopefully someday Cargo will
1564 // have space support.
1565 let rust_version = self.rust_version().replace(' ', "\n");
1566 rustdocflags.arg("--crate-version").arg(&rust_version);
1568 // Environment variables *required* throughout the build
1570 // FIXME: should update code to not require this env var
1571 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1573 // Set this for all builds to make sure doc builds also get it.
1574 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1576 // This one's a bit tricky. As of the time of this writing the compiler
1577 // links to the `winapi` crate on crates.io. This crate provides raw
1578 // bindings to Windows system functions, sort of like libc does for
1579 // Unix. This crate also, however, provides "import libraries" for the
1580 // MinGW targets. There's an import library per dll in the windows
1581 // distribution which is what's linked to. These custom import libraries
1582 // are used because the winapi crate can reference Windows functions not
1583 // present in the MinGW import libraries.
1585 // For example MinGW may ship libdbghelp.a, but it may not have
1586 // references to all the functions in the dbghelp dll. Instead the
1587 // custom import library for dbghelp in the winapi crates has all this
1590 // Unfortunately for us though the import libraries are linked by
1591 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1592 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1593 // conflict with the system MinGW ones). This consequently means that
1594 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1595 // DLL) when linked against *again*, for example with procedural macros
1596 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1597 // `-lwinapi_foo` to the linker again. This isn't actually available in
1598 // our distribution, however, so the link fails.
1600 // To solve this problem we tell winapi to not use its bundled import
1601 // libraries. This means that it will link to the system MinGW import
1602 // libraries by default, and the `-ldylib=foo` directives will still get
1603 // passed to the final linker, but they'll look like `-lfoo` which can
1604 // be resolved because MinGW has the import library. The downside is we
1605 // don't get newer functions from Windows, but we don't use any of them
1607 if !mode.is_tool() {
1608 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1611 for _ in 0..self.verbosity {
1615 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1616 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1617 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1620 // Don't set anything
1624 if self.config.rust_optimize {
1625 // FIXME: cargo bench/install do not accept `--release`
1626 if cmd != "bench" && cmd != "install" {
1627 cargo.arg("--release");
1631 if self.config.locked_deps {
1632 cargo.arg("--locked");
1634 if self.config.vendor || self.is_sudo {
1635 cargo.arg("--frozen");
1638 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1639 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1641 self.ci_env.force_coloring_in_ci(&mut cargo);
1643 // When we build Rust dylibs they're all intended for intermediate
1644 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1645 // linking all deps statically into the dylib.
1646 if matches!(mode, Mode::Std | Mode::Rustc) {
1647 rustflags.arg("-Cprefer-dynamic");
1650 // When building incrementally we default to a lower ThinLTO import limit
1651 // (unless explicitly specified otherwise). This will produce a somewhat
1652 // slower code but give way better compile times.
1654 let limit = match self.config.rust_thin_lto_import_instr_limit {
1655 Some(limit) => Some(limit),
1656 None if self.config.incremental => Some(10),
1660 if let Some(limit) = limit {
1661 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1665 Cargo { command: cargo, rustflags, rustdocflags }
1668 /// Ensure that a given step is built, returning its output. This will
1669 /// cache the step, so it is safe (and good!) to call this as often as
1670 /// needed to ensure that all dependencies are built.
1671 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1673 let mut stack = self.stack.borrow_mut();
1674 for stack_step in stack.iter() {
1676 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1679 let mut out = String::new();
1680 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1681 for el in stack.iter().rev() {
1682 out += &format!("\t{:?}\n", el);
1686 if let Some(out) = self.cache.get(&step) {
1687 self.verbose_than(1, &format!("{}c {:?}", " ".repeat(stack.len()), step));
1691 self.verbose_than(1, &format!("{}> {:?}", " ".repeat(stack.len()), step));
1692 stack.push(Box::new(step.clone()));
1696 let start = Instant::now();
1697 let zero = Duration::new(0, 0);
1698 let parent = self.time_spent_on_dependencies.replace(zero);
1699 let out = step.clone().run(self);
1700 let dur = start.elapsed();
1701 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1705 if self.config.print_step_timings && !self.config.dry_run {
1706 println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1710 let mut stack = self.stack.borrow_mut();
1711 let cur_step = stack.pop().expect("step stack empty");
1712 assert_eq!(cur_step.downcast_ref(), Some(&step));
1714 self.verbose_than(1, &format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1715 self.cache.put(step, out.clone());
1719 /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1720 /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1721 /// needed to ensure that all dependencies are build.
1722 pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1727 let desc = StepDescription::from::<S>(kind);
1728 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1730 // Avoid running steps contained in --exclude
1731 for pathset in &should_run.paths {
1732 if desc.is_excluded(self, pathset) {
1737 // Only execute if it's supposed to run as default
1738 if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1741 /// Checks if any of the "should_run" paths is in the `Builder` paths.
1742 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1743 let desc = StepDescription::from::<S>(kind);
1744 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1746 for path in &self.paths {
1747 if should_run.paths.iter().any(|s| s.has(path, Some(desc.kind)))
1748 && !desc.is_excluded(
1750 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind.into()) }),
1764 #[derive(Debug, Clone)]
1765 struct Rustflags(String, TargetSelection);
1768 fn new(target: TargetSelection) -> Rustflags {
1769 let mut ret = Rustflags(String::new(), target);
1770 ret.propagate_cargo_env("RUSTFLAGS");
1774 /// By default, cargo will pick up on various variables in the environment. However, bootstrap
1775 /// reuses those variables to pass additional flags to rustdoc, so by default they get overriden.
1776 /// Explicitly add back any previous value in the environment.
1778 /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
1779 fn propagate_cargo_env(&mut self, prefix: &str) {
1780 // Inherit `RUSTFLAGS` by default ...
1783 // ... and also handle target-specific env RUSTFLAGS if they're configured.
1784 let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
1785 self.env(&target_specific);
1788 fn env(&mut self, env: &str) {
1789 if let Ok(s) = env::var(env) {
1790 for part in s.split(' ') {
1796 fn arg(&mut self, arg: &str) -> &mut Self {
1797 assert_eq!(arg.split(' ').count(), 1);
1798 if !self.0.is_empty() {
1801 self.0.push_str(arg);
1809 rustflags: Rustflags,
1810 rustdocflags: Rustflags,
1814 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
1815 self.rustdocflags.arg(arg);
1818 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1819 self.rustflags.arg(arg);
1823 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1824 self.command.arg(arg.as_ref());
1828 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1830 I: IntoIterator<Item = S>,
1834 self.arg(arg.as_ref());
1839 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1840 // These are managed through rustflag/rustdocflag interfaces.
1841 assert_ne!(key.as_ref(), "RUSTFLAGS");
1842 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
1843 self.command.env(key.as_ref(), value.as_ref());
1847 pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
1848 builder.add_rustc_lib_path(compiler, &mut self.command);
1851 pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
1852 self.command.current_dir(dir);
1857 impl From<Cargo> for Command {
1858 fn from(mut cargo: Cargo) -> Command {
1859 let rustflags = &cargo.rustflags.0;
1860 if !rustflags.is_empty() {
1861 cargo.command.env("RUSTFLAGS", rustflags);
1864 let rustdocflags = &cargo.rustdocflags.0;
1865 if !rustdocflags.is_empty() {
1866 cargo.command.env("RUSTDOCFLAGS", rustdocflags);