1 use std::any::{type_name, Any};
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
6 use std::fmt::{Debug, Write};
10 use std::path::{Component, Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
14 use crate::cache::{Cache, Interned, INTERNER};
15 use crate::config::{SplitDebuginfo, TargetSelection};
17 use crate::flags::{Color, Subcommand};
23 use crate::tool::{self, SourceType};
24 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir, output, t};
25 use crate::EXTRA_CHECK_CFGS;
26 use crate::{check, compile, Crate};
27 use crate::{clean, dist};
28 use crate::{Build, CLang, DocTests, GitRepo, Mode};
30 pub use crate::Compiler;
31 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
32 use once_cell::sync::Lazy;
34 pub struct Builder<'a> {
39 stack: RefCell<Vec<Box<dyn Any>>>,
40 time_spent_on_dependencies: Cell<Duration>,
41 pub paths: Vec<PathBuf>,
44 impl<'a> Deref for Builder<'a> {
47 fn deref(&self) -> &Self::Target {
52 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
53 /// `PathBuf` when directories are created or to return a `Compiler` once
54 /// it's been assembled.
57 /// Whether this step is run by default as part of its respective phase.
58 /// `true` here can still be overwritten by `should_run` calling `default_condition`.
59 const DEFAULT: bool = false;
61 /// If true, then this rule should be skipped if --target was specified, but --host was not
62 const ONLY_HOSTS: bool = false;
64 /// Primary function to execute this rule. Can call `builder.ensure()`
65 /// with other steps to run those.
66 fn run(self, builder: &Builder<'_>) -> Self::Output;
68 /// When bootstrap is passed a set of paths, this controls whether this rule
69 /// will execute. However, it does not get called in a "default" context
70 /// when we are not passed any paths; in that case, `make_run` is called
72 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
74 /// Builds up a "root" rule, either as a default rule or from a path passed
77 /// When path is `None`, we are executing in a context where no paths were
78 /// passed. When `./x.py build` is run, for example, this rule could get
79 /// called if it is in the correct list below with a path of `None`.
80 fn make_run(_run: RunConfig<'_>) {
81 // It is reasonable to not have an implementation of make_run for rules
82 // who do not want to get called from the root context. This means that
83 // they are likely dependencies (e.g., sysroot creation) or similar, and
84 // as such calling them from ./x.py isn't logical.
89 pub struct RunConfig<'a> {
90 pub builder: &'a Builder<'a>,
91 pub target: TargetSelection,
92 pub paths: Vec<PathSet>,
96 pub fn build_triple(&self) -> TargetSelection {
97 self.builder.build.build
100 /// Return a list of crate names selected by `run.paths`.
101 pub fn cargo_crates_in_set(&self) -> Interned<Vec<String>> {
102 let mut crates = Vec::new();
103 for krate in &self.paths {
104 let path = krate.assert_single_path();
105 let crate_name = self.builder.crate_paths[&path.path];
106 crates.push(crate_name.to_string());
108 INTERNER.intern_list(crates)
112 /// A description of the crates in this set, suitable for passing to `builder.info`.
114 /// `crates` should be generated by [`RunConfig::cargo_crates_in_set`].
115 pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
116 if crates.is_empty() {
120 let mut descr = String::from(" {");
121 descr.push_str(crates[0].as_ref());
122 for krate in &crates[1..] {
123 descr.push_str(", ");
124 descr.push_str(krate.as_ref());
130 struct StepDescription {
133 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
134 make_run: fn(RunConfig<'_>),
139 #[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
140 pub struct TaskPath {
142 pub kind: Option<Kind>,
146 pub fn parse(path: impl Into<PathBuf>) -> TaskPath {
148 let mut path = path.into();
150 let mut components = path.components();
151 if let Some(Component::Normal(os_str)) = components.next() {
152 if let Some(str) = os_str.to_str() {
153 if let Some((found_kind, found_prefix)) = str.split_once("::") {
154 if found_kind.is_empty() {
155 panic!("empty kind in task path {}", path.display());
157 kind = Kind::parse(found_kind);
158 assert!(kind.is_some());
159 path = Path::new(found_prefix).join(components.as_path());
164 TaskPath { path, kind }
168 impl Debug for TaskPath {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 if let Some(kind) = &self.kind {
171 write!(f, "{}::", kind.as_str())?;
173 write!(f, "{}", self.path.display())
177 /// Collection of paths used to match a task rule.
178 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
180 /// A collection of individual paths or aliases.
182 /// These are generally matched as a path suffix. For example, a
183 /// command-line value of `std` will match if `library/std` is in the
186 /// NOTE: the paths within a set should always be aliases of one another.
187 /// For example, `src/librustdoc` and `src/tools/rustdoc` should be in the same set,
188 /// but `library/core` and `library/std` generally should not, unless there's no way (for that Step)
189 /// to build them separately.
190 Set(BTreeSet<TaskPath>),
191 /// A "suite" of paths.
193 /// These can match as a path suffix (like `Set`), or as a prefix. For
194 /// example, a command-line value of `tests/ui/abi/variadic-ffi.rs`
195 /// will match `tests/ui`. A command-line value of `ui` would also
196 /// match `tests/ui`.
201 fn empty() -> PathSet {
202 PathSet::Set(BTreeSet::new())
205 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
206 let mut set = BTreeSet::new();
207 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
211 fn has(&self, needle: &Path, module: Option<Kind>) -> bool {
213 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
214 PathSet::Suite(suite) => Self::check(suite, needle, module),
219 fn check(p: &TaskPath, needle: &Path, module: Option<Kind>) -> bool {
220 if let (Some(p_kind), Some(kind)) = (&p.kind, module) {
221 p.path.ends_with(needle) && *p_kind == kind
223 p.path.ends_with(needle)
227 /// Return all `TaskPath`s in `Self` that contain any of the `needles`, removing the
230 /// This is used for `StepDescription::krate`, which passes all matching crates at once to
231 /// `Step::make_run`, rather than calling it many times with a single crate.
232 /// See `tests.rs` for examples.
233 fn intersection_removing_matches(
235 needles: &mut Vec<&Path>,
236 module: Option<Kind>,
238 let mut check = |p| {
239 for (i, n) in needles.iter().enumerate() {
240 let matched = Self::check(p, n, module);
249 PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
250 PathSet::Suite(suite) => {
260 /// A convenience wrapper for Steps which know they have no aliases and all their sets contain only a single path.
262 /// This can be used with [`ShouldRun::krate`], [`ShouldRun::path`], or [`ShouldRun::alias`].
264 pub fn assert_single_path(&self) -> &TaskPath {
266 PathSet::Set(set) => {
267 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
268 set.iter().next().unwrap()
270 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
275 impl StepDescription {
276 fn from<S: Step>(kind: Kind) -> StepDescription {
279 only_hosts: S::ONLY_HOSTS,
280 should_run: S::should_run,
281 make_run: S::make_run,
282 name: std::any::type_name::<S>(),
287 fn maybe_run(&self, builder: &Builder<'_>, pathsets: Vec<PathSet>) {
288 if pathsets.iter().any(|set| self.is_excluded(builder, set)) {
292 // Determine the targets participating in this rule.
293 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
295 for target in targets {
296 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
297 (self.make_run)(run);
301 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
302 if builder.config.exclude.iter().any(|e| pathset.has(&e.path, e.kind)) {
303 println!("Skipping {:?} because it is excluded", pathset);
307 if !builder.config.exclude.is_empty() {
308 builder.verbose(&format!(
309 "{:?} not skipped for {:?} -- not in {:?}",
310 pathset, self.name, builder.config.exclude
316 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
319 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
320 .collect::<Vec<_>>();
322 // sanity checks on rules
323 for (desc, should_run) in v.iter().zip(&should_runs) {
325 !should_run.paths.is_empty(),
326 "{:?} should have at least one pathset",
331 if paths.is_empty() || builder.config.include_default_paths {
332 for (desc, should_run) in v.iter().zip(&should_runs) {
333 if desc.default && should_run.is_really_default() {
334 desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
339 // strip CurDir prefix if present
340 let mut paths: Vec<_> =
341 paths.into_iter().map(|p| p.strip_prefix(".").unwrap_or(p)).collect();
343 // Handle all test suite paths.
344 // (This is separate from the loop below to avoid having to handle multiple paths in `is_suite_path` somehow.)
345 paths.retain(|path| {
346 for (desc, should_run) in v.iter().zip(&should_runs) {
347 if let Some(suite) = should_run.is_suite_path(&path) {
348 desc.maybe_run(builder, vec![suite.clone()]);
355 if paths.is_empty() {
359 // Handle all PathSets.
360 for (desc, should_run) in v.iter().zip(&should_runs) {
361 let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
362 if !pathsets.is_empty() {
363 desc.maybe_run(builder, pathsets);
367 if !paths.is_empty() {
368 eprintln!("error: no `{}` rules matched {:?}", builder.kind.as_str(), paths,);
370 "help: run `x.py {} --help --verbose` to show a list of available paths",
371 builder.kind.as_str()
374 "note: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
376 crate::detail_exit(1);
381 enum ReallyDefault<'a> {
383 Lazy(Lazy<bool, Box<dyn Fn() -> bool + 'a>>),
386 pub struct ShouldRun<'a> {
387 pub builder: &'a Builder<'a>,
390 // use a BTreeSet to maintain sort order
391 paths: BTreeSet<PathSet>,
393 // If this is a default rule, this is an additional constraint placed on
394 // its run. Generally something like compiler docs being enabled.
395 is_really_default: ReallyDefault<'a>,
398 impl<'a> ShouldRun<'a> {
399 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
403 paths: BTreeSet::new(),
404 is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
408 pub fn default_condition(mut self, cond: bool) -> Self {
409 self.is_really_default = ReallyDefault::Bool(cond);
413 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
414 self.is_really_default = ReallyDefault::Lazy(Lazy::new(lazy_cond));
418 pub fn is_really_default(&self) -> bool {
419 match &self.is_really_default {
420 ReallyDefault::Bool(val) => *val,
421 ReallyDefault::Lazy(lazy) => *lazy.deref(),
425 /// Indicates it should run if the command-line selects the given crate or
426 /// any of its (local) dependencies.
428 /// Compared to `krate`, this treats the dependencies as aliases for the
429 /// same job. Generally it is preferred to use `krate`, and treat each
430 /// individual path separately. For example `./x.py test src/liballoc`
431 /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
432 /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
433 /// `all_krates` should probably be removed at some point.
434 pub fn all_krates(mut self, name: &str) -> Self {
435 let mut set = BTreeSet::new();
436 for krate in self.builder.in_tree_crates(name, None) {
437 let path = krate.local_path(self.builder);
438 set.insert(TaskPath { path, kind: Some(self.kind) });
440 self.paths.insert(PathSet::Set(set));
444 /// Indicates it should run if the command-line selects the given crate or
445 /// any of its (local) dependencies.
447 /// `make_run` will be called a single time with all matching command-line paths.
448 pub fn crate_or_deps(self, name: &str) -> Self {
449 let crates = self.builder.in_tree_crates(name, None);
453 /// Indicates it should run if the command-line selects any of the given crates.
455 /// `make_run` will be called a single time with all matching command-line paths.
456 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
457 for krate in crates {
458 let path = krate.local_path(self.builder);
459 self.paths.insert(PathSet::one(path, self.kind));
464 // single alias, which does not correspond to any on-disk path
465 pub fn alias(mut self, alias: &str) -> Self {
466 // exceptional case for `Kind::Setup` because its `library`
467 // and `compiler` options would otherwise naively match with
468 // `compiler` and `library` folders respectively.
470 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
471 "use `builder.path()` for real paths: {}",
474 self.paths.insert(PathSet::Set(
475 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
480 // single, non-aliased path
481 pub fn path(self, path: &str) -> Self {
485 // multiple aliases for the same job
486 pub fn paths(mut self, paths: &[&str]) -> Self {
487 self.paths.insert(PathSet::Set(
491 // FIXME(#96188): make sure this is actually a path.
492 // This currently breaks for paths within submodules.
494 // self.builder.src.join(p).exists(),
495 // "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {}",
498 TaskPath { path: p.into(), kind: Some(self.kind) }
505 /// Handles individual files (not directories) within a test suite.
506 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
507 self.paths.iter().find(|pathset| match pathset {
508 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
509 PathSet::Set(_) => false,
513 pub fn suite_path(mut self, suite: &str) -> Self {
514 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
518 // allows being more explicit about why should_run in Step returns the value passed to it
519 pub fn never(mut self) -> ShouldRun<'a> {
520 self.paths.insert(PathSet::empty());
524 /// Given a set of requested paths, return the subset which match the Step for this `ShouldRun`,
525 /// removing the matches from `paths`.
527 /// NOTE: this returns multiple PathSets to allow for the possibility of multiple units of work
528 /// within the same step. For example, `test::Crate` allows testing multiple crates in the same
529 /// cargo invocation, which are put into separate sets because they aren't aliases.
531 /// The reason we return PathSet instead of PathBuf is to allow for aliases that mean the same thing
532 /// (for now, just `all_krates` and `paths`, but we may want to add an `aliases` function in the future?)
533 fn pathset_for_paths_removing_matches(
535 paths: &mut Vec<&Path>,
538 let mut sets = vec![];
539 for pathset in &self.paths {
540 let subset = pathset.intersection_removing_matches(paths, Some(kind));
541 if subset != PathSet::empty() {
549 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
567 pub fn parse(string: &str) -> Option<Kind> {
568 // these strings, including the one-letter aliases, must match the x.py help text
570 "build" | "b" => Kind::Build,
571 "check" | "c" => Kind::Check,
572 "clippy" => Kind::Clippy,
574 "fmt" => Kind::Format,
575 "test" | "t" => Kind::Test,
576 "bench" => Kind::Bench,
577 "doc" | "d" => Kind::Doc,
578 "clean" => Kind::Clean,
579 "dist" => Kind::Dist,
580 "install" => Kind::Install,
581 "run" | "r" => Kind::Run,
582 "setup" => Kind::Setup,
587 pub fn as_str(&self) -> &'static str {
589 Kind::Build => "build",
590 Kind::Check => "check",
591 Kind::Clippy => "clippy",
593 Kind::Format => "fmt",
594 Kind::Test => "test",
595 Kind::Bench => "bench",
597 Kind::Clean => "clean",
598 Kind::Dist => "dist",
599 Kind::Install => "install",
601 Kind::Setup => "setup",
606 impl<'a> Builder<'a> {
607 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
608 macro_rules! describe {
609 ($($rule:ty),+ $(,)?) => {{
610 vec![$(StepDescription::from::<$rule>(kind)),+]
614 Kind::Build => describe!(
618 compile::CodegenBackend,
619 compile::StartupObjects,
623 tool::UnstableBookGen,
628 tool::RemoteTestServer,
629 tool::RemoteTestClient,
634 tool::RustAnalyzerProcMacroSrv,
647 Kind::Check | Kind::Clippy | Kind::Fix => describe!(
651 check::CodegenBackend,
655 check::MiroptTestTools,
661 Kind::Test => describe!(
662 crate::toolstate::ToolStateCheck,
663 test::ExpandYamlAnchors,
667 test::RunPassValgrind,
680 test::CrateRustdocJsonTypes,
681 test::CrateJsonDocLint,
684 test::ReplacePlaceholderTest,
690 test::RunMakeFullDeps,
706 test::CompiletestTest,
708 test::RustdocJSNotStd,
714 // Run bootstrap close to the end as it's unlikely to fail
716 // Run run-make last, since these won't pass without make on Windows
719 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
720 Kind::Doc => describe!(
722 doc::UnstableBookGen,
744 Kind::Dist => describe!(
765 // It seems that PlainSourceTarball somehow changes how some of the tools
766 // perceive their dependencies (see #93033) which would invalidate fingerprints
767 // and force us to rebuild tools after vendoring dependencies.
768 // To work around this, create the Tarball after building all the tools.
769 dist::PlainSourceTarball,
771 dist::ReproducibleArtifacts,
773 Kind::Install => describe!(
777 install::RustAnalyzer,
779 install::RustDemangler,
787 Kind::Run => describe!(
788 run::ExpandYamlAnchors,
791 run::ReplaceVersionPlaceholder,
793 run::CollectLicenseMetadata,
794 run::GenerateCopyright,
796 Kind::Setup => describe!(setup::Profile),
797 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
798 // special-cased in Build::build()
799 Kind::Format => vec![],
803 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
804 let step_descriptions = Builder::get_step_descriptions(kind);
805 if step_descriptions.is_empty() {
809 let builder = Self::new_internal(build, kind, vec![]);
810 let builder = &builder;
811 // The "build" kind here is just a placeholder, it will be replaced with something else in
812 // the following statement.
813 let mut should_run = ShouldRun::new(builder, Kind::Build);
814 for desc in step_descriptions {
815 should_run.kind = desc.kind;
816 should_run = (desc.should_run)(should_run);
818 let mut help = String::from("Available paths:\n");
819 let mut add_path = |path: &Path| {
820 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
822 for pathset in should_run.paths {
824 PathSet::Set(set) => {
826 add_path(&path.path);
829 PathSet::Suite(path) => {
830 add_path(&path.path.join("..."));
837 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
840 top_stage: build.config.stage,
843 stack: RefCell::new(Vec::new()),
844 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
849 pub fn new(build: &Build) -> Builder<'_> {
850 let (kind, paths) = match build.config.cmd {
851 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
852 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
853 Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
854 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
855 Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
856 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
857 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
858 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
859 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
860 Subcommand::Run { ref paths, .. } => (Kind::Run, &paths[..]),
861 Subcommand::Clean { ref paths, .. } => (Kind::Clean, &paths[..]),
862 Subcommand::Format { .. } => (Kind::Format, &[][..]),
863 Subcommand::Setup { profile: ref path } => (
865 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
869 Self::new_internal(build, kind, paths.to_owned())
872 pub fn execute_cli(&self) {
873 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
876 pub fn default_doc(&self, paths: &[PathBuf]) {
877 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
880 /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
881 pub fn doc_rust_lang_org_channel(&self) -> String {
882 let channel = match &*self.config.channel {
883 "stable" => &self.version,
885 "nightly" | "dev" => "nightly",
886 // custom build of rustdoc maybe? link to the latest stable docs just in case
889 "https://doc.rust-lang.org/".to_owned() + channel
892 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
893 StepDescription::run(v, self, paths);
896 /// Obtain a compiler at a given stage and for a given host. Explicitly does
897 /// not take `Compiler` since all `Compiler` instances are meant to be
898 /// obtained through this function, since it ensures that they are valid
899 /// (i.e., built and assembled).
900 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
901 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
904 /// Similar to `compiler`, except handles the full-bootstrap option to
905 /// silently use the stage1 compiler instead of a stage2 compiler if one is
908 /// Note that this does *not* have the side effect of creating
909 /// `compiler(stage, host)`, unlike `compiler` above which does have such
910 /// a side effect. The returned compiler here can only be used to compile
911 /// new artifacts, it can't be used to rely on the presence of a particular
914 /// See `force_use_stage1` for documentation on what each argument is.
918 host: TargetSelection,
919 target: TargetSelection,
921 if self.build.force_use_stage1(Compiler { stage, host }, target) {
922 self.compiler(1, self.config.build)
924 self.compiler(stage, host)
928 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
929 self.ensure(compile::Sysroot { compiler })
932 /// Returns the libdir where the standard library and other artifacts are
933 /// found for a compiler's sysroot.
934 pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
935 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
938 target: TargetSelection,
940 impl Step for Libdir {
941 type Output = Interned<PathBuf>;
943 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
947 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
948 let lib = builder.sysroot_libdir_relative(self.compiler);
949 let sysroot = builder
950 .sysroot(self.compiler)
953 .join(self.target.triple)
955 // Avoid deleting the rustlib/ directory we just copied
956 // (in `impl Step for Sysroot`).
957 if !builder.download_rustc() {
958 let _ = fs::remove_dir_all(&sysroot);
959 t!(fs::create_dir_all(&sysroot));
961 INTERNER.intern_path(sysroot)
964 self.ensure(Libdir { compiler, target })
967 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
968 self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
971 /// Returns the compiler's libdir where it stores the dynamic libraries that
972 /// it itself links against.
974 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
976 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
977 if compiler.is_snapshot(self) {
978 self.rustc_snapshot_libdir()
980 match self.config.libdir_relative() {
981 Some(relative_libdir) if compiler.stage >= 1 => {
982 self.sysroot(compiler).join(relative_libdir)
984 _ => self.sysroot(compiler).join(libdir(compiler.host)),
989 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
990 /// it itself links against.
992 /// For example this returns `lib` on Unix and `bin` on
994 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
995 if compiler.is_snapshot(self) {
996 libdir(self.config.build).as_ref()
998 match self.config.libdir_relative() {
999 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1000 _ => libdir(compiler.host).as_ref(),
1005 /// Returns the compiler's relative libdir where the standard library and other artifacts are
1006 /// found for a compiler's sysroot.
1008 /// For example this returns `lib` on Unix and Windows.
1009 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1010 match self.config.libdir_relative() {
1011 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1012 _ if compiler.stage == 0 => &self.build.initial_libdir,
1013 _ => Path::new("lib"),
1017 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1018 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1020 // Ensure that the downloaded LLVM libraries can be found.
1021 if self.config.llvm_from_ci {
1022 let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
1023 dylib_dirs.push(ci_llvm_lib);
1029 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1030 /// library lookup path.
1031 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
1032 // Windows doesn't need dylib path munging because the dlls for the
1033 // compiler live next to the compiler and the system will find them
1039 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1042 /// Gets a path to the compiler specified.
1043 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1044 if compiler.is_snapshot(self) {
1045 self.initial_rustc.clone()
1047 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1051 /// Gets the paths to all of the compiler's codegen backends.
1052 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1053 fs::read_dir(self.sysroot_codegen_backends(compiler))
1056 .filter_map(Result::ok)
1057 .map(|entry| entry.path())
1060 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
1061 self.ensure(tool::Rustdoc { compiler })
1064 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
1065 let mut cmd = Command::new(&self.bootstrap_out.join("rustdoc"));
1066 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1067 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1068 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1069 // equivalently to rustc.
1070 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1071 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1072 .env("RUSTDOC_REAL", self.rustdoc(compiler))
1073 .env("RUSTC_BOOTSTRAP", "1");
1075 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1077 if self.config.deny_warnings {
1078 cmd.arg("-Dwarnings");
1080 cmd.arg("-Znormalize-docs");
1082 // Remove make-related flags that can cause jobserver problems.
1083 cmd.env_remove("MAKEFLAGS");
1084 cmd.env_remove("MFLAGS");
1086 if let Some(linker) = self.linker(compiler.host) {
1087 cmd.env("RUSTDOC_LINKER", linker);
1089 if self.is_fuse_ld_lld(compiler.host) {
1090 cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
1095 /// Return the path to `llvm-config` for the target, if it exists.
1097 /// Note that this returns `None` if LLVM is disabled, or if we're in a
1098 /// check build or dry-run, where there's no need to build all of LLVM.
1099 fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1100 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run() {
1101 let native::LlvmResult { llvm_config, .. } = self.ensure(native::Llvm { target });
1102 if llvm_config.is_file() {
1103 return Some(llvm_config);
1109 /// Like `cargo`, but only passes flags that are valid for all commands.
1114 target: TargetSelection,
1117 let mut cargo = Command::new(&self.initial_cargo);
1118 // Run cargo from the source root so it can find .cargo/config.
1119 // This matters when using vendoring and the working directory is outside the repository.
1120 cargo.current_dir(&self.src);
1122 let out_dir = self.stage_out(compiler, mode);
1123 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
1125 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
1126 // from out of tree it shouldn't matter, since x.py is only used for
1127 // building in-tree.
1128 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
1129 match self.build.config.color {
1131 cargo.arg("--color=always");
1132 for log in &color_logs {
1133 cargo.env(log, "always");
1137 cargo.arg("--color=never");
1138 for log in &color_logs {
1139 cargo.env(log, "never");
1142 Color::Auto => {} // nothing to do
1145 if cmd != "install" {
1146 cargo.arg("--target").arg(target.rustc_target_arg());
1148 assert_eq!(target, compiler.host);
1151 if self.config.rust_optimize {
1152 // FIXME: cargo bench/install do not accept `--release`
1153 if cmd != "bench" && cmd != "install" {
1154 cargo.arg("--release");
1158 // Remove make-related flags to ensure Cargo can correctly set things up
1159 cargo.env_remove("MAKEFLAGS");
1160 cargo.env_remove("MFLAGS");
1165 /// Prepares an invocation of `cargo` to be run.
1167 /// This will create a `Command` that represents a pending execution of
1168 /// Cargo. This cargo will be configured to use `compiler` as the actual
1169 /// rustc compiler, its output will be scoped by `mode`'s output directory,
1170 /// it will pass the `--target` flag for the specified `target`, and will be
1171 /// executing the Cargo command `cmd`.
1176 source_type: SourceType,
1177 target: TargetSelection,
1180 let mut cargo = self.bare_cargo(compiler, mode, target, cmd);
1181 let out_dir = self.stage_out(compiler, mode);
1183 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
1184 // so we need to explicitly clear out if they've been updated.
1185 for backend in self.codegen_backends(compiler) {
1186 self.clear_if_dirty(&out_dir, &backend);
1189 if cmd == "doc" || cmd == "rustdoc" {
1190 let my_out = match mode {
1191 // This is the intended out directory for compiler documentation.
1192 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
1194 if self.config.cmd.json() {
1195 out_dir.join(target.triple).join("json-doc")
1197 out_dir.join(target.triple).join("doc")
1200 _ => panic!("doc mode {:?} not expected", mode),
1202 let rustdoc = self.rustdoc(compiler);
1203 self.clear_if_dirty(&my_out, &rustdoc);
1206 let profile_var = |name: &str| {
1207 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
1208 format!("CARGO_PROFILE_{}_{}", profile, name)
1211 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
1212 // needs to not accidentally link to libLLVM in stage0/lib.
1213 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
1214 if let Some(e) = env::var_os(util::dylib_path_var()) {
1215 cargo.env("REAL_LIBRARY_PATH", e);
1218 // Set a flag for `check`/`clippy`/`fix`, so that certain build
1219 // scripts can do less work (i.e. not building/requiring LLVM).
1220 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
1221 // If we've not yet built LLVM, or it's stale, then bust
1222 // the rustc_llvm cache. That will always work, even though it
1223 // may mean that on the next non-check build we'll need to rebuild
1224 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
1225 // of work comparatively, and we'd likely need to rebuild it anyway,
1227 if crate::native::prebuilt_llvm_config(self, target).is_err() {
1228 cargo.env("RUST_CHECK", "1");
1232 let stage = if compiler.stage == 0 && self.local_rebuild {
1233 // Assume the local-rebuild rustc already has stage1 features.
1239 let mut rustflags = Rustflags::new(target);
1241 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
1242 cargo.args(s.split_whitespace());
1244 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
1246 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
1247 cargo.args(s.split_whitespace());
1249 rustflags.env("RUSTFLAGS_BOOTSTRAP");
1250 if cmd == "clippy" {
1251 // clippy overwrites sysroot if we pass it to cargo.
1252 // Pass it directly to clippy instead.
1253 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
1254 // so it has no way of knowing the sysroot.
1255 rustflags.arg("--sysroot");
1257 self.sysroot(compiler)
1260 .expect("sysroot must be valid UTF-8"),
1262 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
1263 cargo.arg("-Zunstable-options");
1264 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
1265 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
1266 let output = host_version.and_then(|output| {
1267 if output.status.success() {
1272 }).unwrap_or_else(|_| {
1274 "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
1276 eprintln!("help: try `rustup component add clippy`");
1277 crate::detail_exit(1);
1279 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
1280 rustflags.arg("--cfg=bootstrap");
1283 rustflags.arg("--cfg=bootstrap");
1287 let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
1289 // If an explicit setting is given, use that
1293 if mode == Mode::Std {
1294 // The standard library defaults to the legacy scheme
1297 // The compiler and tools default to the new scheme
1303 if use_new_symbol_mangling {
1304 rustflags.arg("-Csymbol-mangling-version=v0");
1306 rustflags.arg("-Csymbol-mangling-version=legacy");
1307 rustflags.arg("-Zunstable-options");
1310 // Enable cfg checking of cargo features for everything but std and also enable cfg
1311 // checking of names and values.
1313 // Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like
1314 // backtrace, core_simd, std_float, ...), those dependencies have their own
1315 // features but cargo isn't involved in the #[path] process and so cannot pass the
1316 // complete list of features, so for that reason we don't enable checking of
1317 // features for std crates.
1318 cargo.arg(if mode != Mode::Std {
1319 "-Zcheck-cfg=names,values,output,features"
1321 "-Zcheck-cfg=names,values,output"
1324 // Add extra cfg not defined in/by rustc
1326 // Note: Altrough it would seems that "-Zunstable-options" to `rustflags` is useless as
1327 // cargo would implicitly add it, it was discover that sometimes bootstrap only use
1328 // `rustflags` without `cargo` making it required.
1329 rustflags.arg("-Zunstable-options");
1330 for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
1331 if *restricted_mode == None || *restricted_mode == Some(mode) {
1332 // Creating a string of the values by concatenating each value:
1333 // ',"tvos","watchos"' or '' (nothing) when there are no values
1334 let values = match values {
1335 Some(values) => values
1337 .map(|val| [",", "\"", val, "\""])
1339 .collect::<String>(),
1340 None => String::new(),
1342 rustflags.arg(&format!("--check-cfg=values({name}{values})"));
1346 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1347 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1349 let mut rustdocflags = rustflags.clone();
1350 rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1352 rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1354 rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1357 if let Ok(s) = env::var("CARGOFLAGS") {
1358 cargo.args(s.split_whitespace());
1362 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1363 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1364 // Build proc macros both for the host and the target
1365 if target != compiler.host && cmd != "check" {
1366 cargo.arg("-Zdual-proc-macros");
1367 rustflags.arg("-Zdual-proc-macros");
1372 // This tells Cargo (and in turn, rustc) to output more complete
1373 // dependency information. Most importantly for rustbuild, this
1374 // includes sysroot artifacts, like libstd, which means that we don't
1375 // need to track those in rustbuild (an error prone process!). This
1376 // feature is currently unstable as there may be some bugs and such, but
1377 // it represents a big improvement in rustbuild's reliability on
1378 // rebuilds, so we're using it here.
1380 // For some additional context, see #63470 (the PR originally adding
1381 // this), as well as #63012 which is the tracking issue for this
1382 // feature on the rustc side.
1383 cargo.arg("-Zbinary-dep-depinfo");
1384 let allow_features = match mode {
1385 Mode::ToolBootstrap | Mode::ToolStd => {
1386 // Restrict the allowed features so we don't depend on nightly
1389 // binary-dep-depinfo is used by rustbuild itself for all
1392 // Lots of tools depend on proc_macro2 and proc-macro-error.
1393 // Those have build scripts which assume nightly features are
1394 // available if the `rustc` version is "nighty" or "dev". See
1395 // bin/rustc.rs for why that is a problem. Instead of labeling
1396 // those features for each individual tool that needs them,
1397 // just blanket allow them here.
1399 // If this is ever removed, be sure to add something else in
1400 // its place to keep the restrictions in place (or make a way
1401 // to unset RUSTC_BOOTSTRAP).
1402 "binary-dep-depinfo,proc_macro_span,proc_macro_span_shrink,proc_macro_diagnostic"
1405 Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustc => String::new(),
1408 cargo.arg("-j").arg(self.jobs().to_string());
1410 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1411 // Force cargo to output binaries with disambiguating hashes in the name
1412 let mut metadata = if compiler.stage == 0 {
1413 // Treat stage0 like a special channel, whether it's a normal prior-
1414 // release rustc or a local rebuild with the same version, so we
1415 // never mix these libraries by accident.
1416 "bootstrap".to_string()
1418 self.config.channel.to_string()
1420 // We want to make sure that none of the dependencies between
1421 // std/test/rustc unify with one another. This is done for weird linkage
1422 // reasons but the gist of the problem is that if librustc, libtest, and
1423 // libstd all depend on libc from crates.io (which they actually do) we
1424 // want to make sure they all get distinct versions. Things get really
1425 // weird if we try to unify all these dependencies right now, namely
1426 // around how many times the library is linked in dynamic libraries and
1427 // such. If rustc were a static executable or if we didn't ship dylibs
1428 // this wouldn't be a problem, but we do, so it is. This is in general
1429 // just here to make sure things build right. If you can remove this and
1430 // things still build right, please do!
1432 Mode::Std => metadata.push_str("std"),
1433 // When we're building rustc tools, they're built with a search path
1434 // that contains things built during the rustc build. For example,
1435 // bitflags is built during the rustc build, and is a dependency of
1436 // rustdoc as well. We're building rustdoc in a different target
1437 // directory, though, which means that Cargo will rebuild the
1438 // dependency. When we go on to build rustdoc, we'll look for
1439 // bitflags, and find two different copies: one built during the
1440 // rustc step and one that we just built. This isn't always a
1441 // problem, somehow -- not really clear why -- but we know that this
1443 Mode::ToolRustc => metadata.push_str("tool-rustc"),
1444 // Same for codegen backends.
1445 Mode::Codegen => metadata.push_str("codegen"),
1448 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1450 if cmd == "clippy" {
1451 rustflags.arg("-Zforce-unstable-if-unmarked");
1454 rustflags.arg("-Zmacro-backtrace");
1456 let want_rustdoc = self.doc_tests != DocTests::No;
1458 // We synthetically interpret a stage0 compiler used to build tools as a
1459 // "raw" compiler in that it's the exact snapshot we download. Normally
1460 // the stage0 build means it uses libraries build by the stage0
1461 // compiler, but for tools we just use the precompiled libraries that
1463 let use_snapshot = mode == Mode::ToolBootstrap;
1464 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1466 let maybe_sysroot = self.sysroot(compiler);
1467 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1468 let libdir = self.rustc_libdir(compiler);
1470 // Clear the output directory if the real rustc we're using has changed;
1471 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1473 // Avoid doing this during dry run as that usually means the relevant
1474 // compiler is not yet linked/copied properly.
1476 // Only clear out the directory if we're compiling std; otherwise, we
1477 // should let Cargo take care of things for us (via depdep info)
1478 if !self.config.dry_run() && mode == Mode::Std && cmd == "build" {
1479 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1482 // Customize the compiler we're running. Specify the compiler to cargo
1483 // as our shim and then pass it some various options used to configure
1484 // how the actual compiler itself is called.
1486 // These variables are primarily all read by
1487 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1489 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1490 .env("RUSTC_REAL", self.rustc(compiler))
1491 .env("RUSTC_STAGE", stage.to_string())
1492 .env("RUSTC_SYSROOT", &sysroot)
1493 .env("RUSTC_LIBDIR", &libdir)
1494 .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
1497 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1498 self.rustdoc(compiler)
1500 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1503 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1504 .env("RUSTC_BREAK_ON_ICE", "1");
1505 // Clippy support is a hack and uses the default `cargo-clippy` in path.
1506 // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1507 if cmd != "clippy" {
1508 cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
1511 // Dealing with rpath here is a little special, so let's go into some
1512 // detail. First off, `-rpath` is a linker option on Unix platforms
1513 // which adds to the runtime dynamic loader path when looking for
1514 // dynamic libraries. We use this by default on Unix platforms to ensure
1515 // that our nightlies behave the same on Windows, that is they work out
1516 // of the box. This can be disabled, of course, but basically that's why
1517 // we're gated on RUSTC_RPATH here.
1519 // Ok, so the astute might be wondering "why isn't `-C rpath` used
1520 // here?" and that is indeed a good question to ask. This codegen
1521 // option is the compiler's current interface to generating an rpath.
1522 // Unfortunately it doesn't quite suffice for us. The flag currently
1523 // takes no value as an argument, so the compiler calculates what it
1524 // should pass to the linker as `-rpath`. This unfortunately is based on
1525 // the **compile time** directory structure which when building with
1526 // Cargo will be very different than the runtime directory structure.
1528 // All that's a really long winded way of saying that if we use
1529 // `-Crpath` then the executables generated have the wrong rpath of
1530 // something like `$ORIGIN/deps` when in fact the way we distribute
1531 // rustc requires the rpath to be `$ORIGIN/../lib`.
1533 // So, all in all, to set up the correct rpath we pass the linker
1534 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1535 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1536 // to change a flag in a binary?
1537 if self.config.rust_rpath && util::use_host_linker(target) {
1538 let rpath = if target.contains("apple") {
1539 // Note that we need to take one extra step on macOS to also pass
1540 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1541 // do that we pass a weird flag to the compiler to get it to do
1542 // so. Note that this is definitely a hack, and we should likely
1543 // flesh out rpath support more fully in the future.
1544 rustflags.arg("-Zosx-rpath-install-name");
1545 Some("-Wl,-rpath,@loader_path/../lib")
1546 } else if !target.contains("windows") {
1547 rustflags.arg("-Clink-args=-Wl,-z,origin");
1548 Some("-Wl,-rpath,$ORIGIN/../lib")
1552 if let Some(rpath) = rpath {
1553 rustflags.arg(&format!("-Clink-args={}", rpath));
1557 if let Some(host_linker) = self.linker(compiler.host) {
1558 cargo.env("RUSTC_HOST_LINKER", host_linker);
1560 if self.is_fuse_ld_lld(compiler.host) {
1561 cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1562 cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1565 if let Some(target_linker) = self.linker(target) {
1566 let target = crate::envify(&target.triple);
1567 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1569 if self.is_fuse_ld_lld(target) {
1570 rustflags.arg("-Clink-args=-fuse-ld=lld");
1572 self.lld_flags(target).for_each(|flag| {
1573 rustdocflags.arg(&flag);
1576 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1577 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1580 let debuginfo_level = match mode {
1581 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1582 Mode::Std => self.config.rust_debuginfo_level_std,
1583 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1584 self.config.rust_debuginfo_level_tools
1587 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1589 profile_var("DEBUG_ASSERTIONS"),
1590 if mode == Mode::Std {
1591 self.config.rust_debug_assertions_std.to_string()
1593 self.config.rust_debug_assertions.to_string()
1597 profile_var("OVERFLOW_CHECKS"),
1598 if mode == Mode::Std {
1599 self.config.rust_overflow_checks_std.to_string()
1601 self.config.rust_overflow_checks.to_string()
1605 let split_debuginfo_is_stable = target.contains("linux")
1606 || target.contains("apple")
1607 || (target.contains("msvc")
1608 && self.config.rust_split_debuginfo == SplitDebuginfo::Packed)
1609 || (target.contains("windows")
1610 && self.config.rust_split_debuginfo == SplitDebuginfo::Off);
1612 if !split_debuginfo_is_stable {
1613 rustflags.arg("-Zunstable-options");
1615 match self.config.rust_split_debuginfo {
1616 SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
1617 SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
1618 SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
1621 if self.config.cmd.bless() {
1622 // Bless `expect!` tests.
1623 cargo.env("UPDATE_EXPECT", "1");
1626 if !mode.is_tool() {
1627 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1630 if let Some(x) = self.crt_static(target) {
1632 rustflags.arg("-Ctarget-feature=+crt-static");
1634 rustflags.arg("-Ctarget-feature=-crt-static");
1638 if let Some(x) = self.crt_static(compiler.host) {
1639 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1642 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1643 let map = format!("{}={}", self.build.src.display(), map_to);
1644 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1646 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1647 // in order to opportunistically reverse it later.
1648 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1651 // Enable usage of unstable features
1652 cargo.env("RUSTC_BOOTSTRAP", "1");
1653 self.add_rust_test_threads(&mut cargo);
1655 // Almost all of the crates that we compile as part of the bootstrap may
1656 // have a build script, including the standard library. To compile a
1657 // build script, however, it itself needs a standard library! This
1658 // introduces a bit of a pickle when we're compiling the standard
1661 // To work around this we actually end up using the snapshot compiler
1662 // (stage0) for compiling build scripts of the standard library itself.
1663 // The stage0 compiler is guaranteed to have a libstd available for use.
1665 // For other crates, however, we know that we've already got a standard
1666 // library up and running, so we can use the normal compiler to compile
1667 // build scripts in that situation.
1668 if mode == Mode::Std {
1670 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1671 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1674 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1675 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1678 // Tools that use compiler libraries may inherit the `-lLLVM` link
1679 // requirement, but the `-L` library path is not propagated across
1680 // separate Cargo projects. We can add LLVM's library path to the
1681 // platform-specific environment variable as a workaround.
1682 if mode == Mode::ToolRustc || mode == Mode::Codegen {
1683 if let Some(llvm_config) = self.llvm_config(target) {
1684 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1685 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1689 // Compile everything except libraries and proc macros with the more
1690 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1691 // so we can't use it by default in general, but we can use it for tools
1692 // and our own internal libraries.
1693 if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1694 cargo.env("RUSTC_TLS_MODEL_INITIAL_EXEC", "1");
1697 if self.config.incremental {
1698 cargo.env("CARGO_INCREMENTAL", "1");
1700 // Don't rely on any default setting for incr. comp. in Cargo
1701 cargo.env("CARGO_INCREMENTAL", "0");
1704 if let Some(ref on_fail) = self.config.on_fail {
1705 cargo.env("RUSTC_ON_FAIL", on_fail);
1708 if self.config.print_step_timings {
1709 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1712 if self.config.print_step_rusage {
1713 cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1716 if self.config.backtrace_on_ice {
1717 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1720 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1722 if source_type == SourceType::InTree {
1723 let mut lint_flags = Vec::new();
1724 // When extending this list, add the new lints to the RUSTFLAGS of the
1725 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1726 // some code doesn't go through this `rustc` wrapper.
1727 lint_flags.push("-Wrust_2018_idioms");
1728 lint_flags.push("-Wunused_lifetimes");
1729 lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1731 if self.config.deny_warnings {
1732 lint_flags.push("-Dwarnings");
1733 rustdocflags.arg("-Dwarnings");
1736 // This does not use RUSTFLAGS due to caching issues with Cargo.
1737 // Clippy is treated as an "in tree" tool, but shares the same
1738 // cache as other "submodule" tools. With these options set in
1739 // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1740 // By injecting this into the rustc wrapper, this circumvents
1741 // Cargo's fingerprint detection. This is fine because lint flags
1742 // are always ignored in dependencies. Eventually this should be
1743 // fixed via better support from Cargo.
1744 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1746 rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1749 if mode == Mode::Rustc {
1750 rustflags.arg("-Zunstable-options");
1751 rustflags.arg("-Wrustc::internal");
1754 // Throughout the build Cargo can execute a number of build scripts
1755 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1756 // obtained previously to those build scripts.
1757 // Build scripts use either the `cc` crate or `configure/make` so we pass
1758 // the options through environment variables that are fetched and understood by both.
1760 // FIXME: the guard against msvc shouldn't need to be here
1761 if target.contains("msvc") {
1762 if let Some(ref cl) = self.config.llvm_clang_cl {
1763 cargo.env("CC", cl).env("CXX", cl);
1766 let ccache = self.config.ccache.as_ref();
1767 let ccacheify = |s: &Path| {
1768 let ccache = match ccache {
1770 None => return s.display().to_string(),
1772 // FIXME: the cc-rs crate only recognizes the literal strings
1773 // `ccache` and `sccache` when doing caching compilations, so we
1774 // mirror that here. It should probably be fixed upstream to
1775 // accept a new env var or otherwise work with custom ccache
1778 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1779 _ => s.display().to_string(),
1782 let triple_underscored = target.triple.replace("-", "_");
1783 let cc = ccacheify(&self.cc(target));
1784 cargo.env(format!("CC_{}", triple_underscored), &cc);
1786 let cflags = self.cflags(target, GitRepo::Rustc, CLang::C).join(" ");
1787 cargo.env(format!("CFLAGS_{}", triple_underscored), &cflags);
1789 if let Some(ar) = self.ar(target) {
1790 let ranlib = format!("{} s", ar.display());
1792 .env(format!("AR_{}", triple_underscored), ar)
1793 .env(format!("RANLIB_{}", triple_underscored), ranlib);
1796 if let Ok(cxx) = self.cxx(target) {
1797 let cxx = ccacheify(&cxx);
1798 let cxxflags = self.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");
1800 .env(format!("CXX_{}", triple_underscored), &cxx)
1801 .env(format!("CXXFLAGS_{}", triple_underscored), cxxflags);
1805 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1806 rustflags.arg("-Zsave-analysis");
1808 "RUST_SAVE_ANALYSIS_CONFIG",
1809 "{\"output_file\": null,\"full_docs\": false,\
1810 \"pub_only\": true,\"reachable_only\": false,\
1811 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1815 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1816 // when compiling the standard library, since this might be linked into the final outputs
1817 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1818 // for the standard library in case the compiler is run on a non-Windows platform.
1819 // This is not needed for stage 0 artifacts because these will only be used for building
1820 // the stage 1 compiler.
1822 && mode == Mode::Std
1823 && self.config.control_flow_guard
1824 && compiler.stage >= 1
1826 rustflags.arg("-Ccontrol-flow-guard");
1829 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1830 // This replaces spaces with newlines because RUSTDOCFLAGS does not
1831 // support arguments with regular spaces. Hopefully someday Cargo will
1832 // have space support.
1833 let rust_version = self.rust_version().replace(' ', "\n");
1834 rustdocflags.arg("--crate-version").arg(&rust_version);
1836 // Environment variables *required* throughout the build
1838 // FIXME: should update code to not require this env var
1839 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1841 // Set this for all builds to make sure doc builds also get it.
1842 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1844 // This one's a bit tricky. As of the time of this writing the compiler
1845 // links to the `winapi` crate on crates.io. This crate provides raw
1846 // bindings to Windows system functions, sort of like libc does for
1847 // Unix. This crate also, however, provides "import libraries" for the
1848 // MinGW targets. There's an import library per dll in the windows
1849 // distribution which is what's linked to. These custom import libraries
1850 // are used because the winapi crate can reference Windows functions not
1851 // present in the MinGW import libraries.
1853 // For example MinGW may ship libdbghelp.a, but it may not have
1854 // references to all the functions in the dbghelp dll. Instead the
1855 // custom import library for dbghelp in the winapi crates has all this
1858 // Unfortunately for us though the import libraries are linked by
1859 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1860 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1861 // conflict with the system MinGW ones). This consequently means that
1862 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1863 // DLL) when linked against *again*, for example with procedural macros
1864 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1865 // `-lwinapi_foo` to the linker again. This isn't actually available in
1866 // our distribution, however, so the link fails.
1868 // To solve this problem we tell winapi to not use its bundled import
1869 // libraries. This means that it will link to the system MinGW import
1870 // libraries by default, and the `-ldylib=foo` directives will still get
1871 // passed to the final linker, but they'll look like `-lfoo` which can
1872 // be resolved because MinGW has the import library. The downside is we
1873 // don't get newer functions from Windows, but we don't use any of them
1875 if !mode.is_tool() {
1876 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1879 for _ in 0..self.verbosity {
1883 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1884 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1885 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1888 // Don't set anything
1892 if self.config.locked_deps {
1893 cargo.arg("--locked");
1895 if self.config.vendor || self.is_sudo {
1896 cargo.arg("--frozen");
1899 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1900 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1902 self.ci_env.force_coloring_in_ci(&mut cargo);
1904 // When we build Rust dylibs they're all intended for intermediate
1905 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1906 // linking all deps statically into the dylib.
1907 if matches!(mode, Mode::Std | Mode::Rustc) {
1908 rustflags.arg("-Cprefer-dynamic");
1911 // When building incrementally we default to a lower ThinLTO import limit
1912 // (unless explicitly specified otherwise). This will produce a somewhat
1913 // slower code but give way better compile times.
1915 let limit = match self.config.rust_thin_lto_import_instr_limit {
1916 Some(limit) => Some(limit),
1917 None if self.config.incremental => Some(10),
1921 if let Some(limit) = limit {
1922 if stage == 0 || self.config.default_codegen_backend().unwrap_or_default() == "llvm"
1924 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1929 Cargo { command: cargo, rustflags, rustdocflags, allow_features }
1932 /// Ensure that a given step is built, returning its output. This will
1933 /// cache the step, so it is safe (and good!) to call this as often as
1934 /// needed to ensure that all dependencies are built.
1935 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1937 let mut stack = self.stack.borrow_mut();
1938 for stack_step in stack.iter() {
1940 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1943 let mut out = String::new();
1944 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1945 for el in stack.iter().rev() {
1946 out += &format!("\t{:?}\n", el);
1950 if let Some(out) = self.cache.get(&step) {
1951 self.verbose_than(1, &format!("{}c {:?}", " ".repeat(stack.len()), step));
1955 self.verbose_than(1, &format!("{}> {:?}", " ".repeat(stack.len()), step));
1956 stack.push(Box::new(step.clone()));
1959 #[cfg(feature = "build-metrics")]
1960 self.metrics.enter_step(&step);
1963 let start = Instant::now();
1964 let zero = Duration::new(0, 0);
1965 let parent = self.time_spent_on_dependencies.replace(zero);
1966 let out = step.clone().run(self);
1967 let dur = start.elapsed();
1968 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1972 if self.config.print_step_timings && !self.config.dry_run() {
1973 let step_string = format!("{:?}", step);
1974 let brace_index = step_string.find("{").unwrap_or(0);
1975 let type_string = type_name::<S>();
1977 "[TIMING] {} {} -- {}.{:03}",
1978 &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1979 &step_string[brace_index..],
1985 #[cfg(feature = "build-metrics")]
1986 self.metrics.exit_step();
1989 let mut stack = self.stack.borrow_mut();
1990 let cur_step = stack.pop().expect("step stack empty");
1991 assert_eq!(cur_step.downcast_ref(), Some(&step));
1993 self.verbose_than(1, &format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1994 self.cache.put(step, out.clone());
1998 /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1999 /// its output. This will cache the step, so it's safe (and good!) to call this as often as
2000 /// needed to ensure that all dependencies are build.
2001 pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
2006 let desc = StepDescription::from::<S>(kind);
2007 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
2009 // Avoid running steps contained in --exclude
2010 for pathset in &should_run.paths {
2011 if desc.is_excluded(self, pathset) {
2016 // Only execute if it's supposed to run as default
2017 if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
2020 /// Checks if any of the "should_run" paths is in the `Builder` paths.
2021 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
2022 let desc = StepDescription::from::<S>(kind);
2023 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
2025 for path in &self.paths {
2026 if should_run.paths.iter().any(|s| s.has(path, Some(desc.kind)))
2027 && !desc.is_excluded(
2029 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
2039 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
2040 if self.was_invoked_explicitly::<S>(Kind::Doc) {
2041 self.open_in_browser(path);
2045 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
2046 if self.config.dry_run() || !self.config.cmd.open() {
2050 let path = path.as_ref();
2051 self.info(&format!("Opening doc {}", path.display()));
2052 if let Err(err) = opener::open(path) {
2053 self.info(&format!("{}\n", err));
2061 #[derive(Debug, Clone)]
2062 struct Rustflags(String, TargetSelection);
2065 fn new(target: TargetSelection) -> Rustflags {
2066 let mut ret = Rustflags(String::new(), target);
2067 ret.propagate_cargo_env("RUSTFLAGS");
2071 /// By default, cargo will pick up on various variables in the environment. However, bootstrap
2072 /// reuses those variables to pass additional flags to rustdoc, so by default they get overridden.
2073 /// Explicitly add back any previous value in the environment.
2075 /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
2076 fn propagate_cargo_env(&mut self, prefix: &str) {
2077 // Inherit `RUSTFLAGS` by default ...
2080 // ... and also handle target-specific env RUSTFLAGS if they're configured.
2081 let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
2082 self.env(&target_specific);
2085 fn env(&mut self, env: &str) {
2086 if let Ok(s) = env::var(env) {
2087 for part in s.split(' ') {
2093 fn arg(&mut self, arg: &str) -> &mut Self {
2094 assert_eq!(arg.split(' ').count(), 1);
2095 if !self.0.is_empty() {
2098 self.0.push_str(arg);
2106 rustflags: Rustflags,
2107 rustdocflags: Rustflags,
2108 allow_features: String,
2112 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
2113 self.rustdocflags.arg(arg);
2116 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
2117 self.rustflags.arg(arg);
2121 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
2122 self.command.arg(arg.as_ref());
2126 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
2128 I: IntoIterator<Item = S>,
2132 self.arg(arg.as_ref());
2137 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
2138 // These are managed through rustflag/rustdocflag interfaces.
2139 assert_ne!(key.as_ref(), "RUSTFLAGS");
2140 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
2141 self.command.env(key.as_ref(), value.as_ref());
2145 pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
2146 builder.add_rustc_lib_path(compiler, &mut self.command);
2149 pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
2150 self.command.current_dir(dir);
2154 /// Adds nightly-only features that this invocation is allowed to use.
2156 /// By default, all nightly features are allowed. Once this is called, it
2157 /// will be restricted to the given set.
2158 pub fn allow_features(&mut self, features: &str) -> &mut Cargo {
2159 if !self.allow_features.is_empty() {
2160 self.allow_features.push(',');
2162 self.allow_features.push_str(features);
2167 impl From<Cargo> for Command {
2168 fn from(mut cargo: Cargo) -> Command {
2169 let rustflags = &cargo.rustflags.0;
2170 if !rustflags.is_empty() {
2171 cargo.command.env("RUSTFLAGS", rustflags);
2174 let rustdocflags = &cargo.rustdocflags.0;
2175 if !rustdocflags.is_empty() {
2176 cargo.command.env("RUSTDOCFLAGS", rustdocflags);
2179 if !cargo.allow_features.is_empty() {
2180 cargo.command.env("RUSTC_ALLOW_FEATURES", cargo.allow_features);