]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Rollup merge of #106100 - scottmcm:derived-less-than-test, r=compiler-errors
[rust.git] / src / bootstrap / builder.rs
1 use std::any::{type_name, Any};
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::env;
5 use std::ffi::OsStr;
6 use std::fmt::{Debug, Write};
7 use std::fs::{self};
8 use std::hash::Hash;
9 use std::ops::Deref;
10 use std::path::{Component, Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
13
14 use crate::cache::{Cache, Interned, INTERNER};
15 use crate::config::{SplitDebuginfo, TargetSelection};
16 use crate::dist;
17 use crate::doc;
18 use crate::flags::{Color, Subcommand};
19 use crate::install;
20 use crate::native;
21 use crate::run;
22 use crate::setup;
23 use crate::test;
24 use crate::tool::{self, SourceType};
25 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir, output, t};
26 use crate::EXTRA_CHECK_CFGS;
27 use crate::{check, compile, Crate};
28 use crate::{Build, CLang, DocTests, GitRepo, Mode};
29
30 pub use crate::Compiler;
31 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
32 use once_cell::sync::Lazy;
33
34 pub struct Builder<'a> {
35     pub build: &'a Build,
36     pub top_stage: u32,
37     pub kind: Kind,
38     cache: Cache,
39     stack: RefCell<Vec<Box<dyn Any>>>,
40     time_spent_on_dependencies: Cell<Duration>,
41     pub paths: Vec<PathBuf>,
42 }
43
44 impl<'a> Deref for Builder<'a> {
45     type Target = Build;
46
47     fn deref(&self) -> &Self::Target {
48         self.build
49     }
50 }
51
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.
55     type Output: Clone;
56
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;
60
61     /// If true, then this rule should be skipped if --target was specified, but --host was not
62     const ONLY_HOSTS: bool = false;
63
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;
67
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
71     /// directly.
72     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
73
74     /// Builds up a "root" rule, either as a default rule or from a path passed
75     /// to us.
76     ///
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.
85         unimplemented!()
86     }
87 }
88
89 pub struct RunConfig<'a> {
90     pub builder: &'a Builder<'a>,
91     pub target: TargetSelection,
92     pub paths: Vec<PathSet>,
93 }
94
95 impl RunConfig<'_> {
96     pub fn build_triple(&self) -> TargetSelection {
97         self.builder.build.build
98     }
99 }
100
101 struct StepDescription {
102     default: bool,
103     only_hosts: bool,
104     should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
105     make_run: fn(RunConfig<'_>),
106     name: &'static str,
107     kind: Kind,
108 }
109
110 #[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
111 pub struct TaskPath {
112     pub path: PathBuf,
113     pub kind: Option<Kind>,
114 }
115
116 impl TaskPath {
117     pub fn parse(path: impl Into<PathBuf>) -> TaskPath {
118         let mut kind = None;
119         let mut path = path.into();
120
121         let mut components = path.components();
122         if let Some(Component::Normal(os_str)) = components.next() {
123             if let Some(str) = os_str.to_str() {
124                 if let Some((found_kind, found_prefix)) = str.split_once("::") {
125                     if found_kind.is_empty() {
126                         panic!("empty kind in task path {}", path.display());
127                     }
128                     kind = Kind::parse(found_kind);
129                     assert!(kind.is_some());
130                     path = Path::new(found_prefix).join(components.as_path());
131                 }
132             }
133         }
134
135         TaskPath { path, kind }
136     }
137 }
138
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())?;
143         }
144         write!(f, "{}", self.path.display())
145     }
146 }
147
148 /// Collection of paths used to match a task rule.
149 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
150 pub enum PathSet {
151     /// A collection of individual paths or aliases.
152     ///
153     /// These are generally matched as a path suffix. For example, a
154     /// command-line value of `std` will match if `library/std` is in the
155     /// set.
156     ///
157     /// NOTE: the paths within a set should always be aliases of one another.
158     /// For example, `src/librustdoc` and `src/tools/rustdoc` should be in the same set,
159     /// but `library/core` and `library/std` generally should not, unless there's no way (for that Step)
160     /// to build them separately.
161     Set(BTreeSet<TaskPath>),
162     /// A "suite" of paths.
163     ///
164     /// These can match as a path suffix (like `Set`), or as a prefix. For
165     /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
166     /// will match `src/test/ui`. A command-line value of `ui` would also
167     /// match `src/test/ui`.
168     Suite(TaskPath),
169 }
170
171 impl PathSet {
172     fn empty() -> PathSet {
173         PathSet::Set(BTreeSet::new())
174     }
175
176     fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
177         let mut set = BTreeSet::new();
178         set.insert(TaskPath { path: path.into(), kind: Some(kind) });
179         PathSet::Set(set)
180     }
181
182     fn has(&self, needle: &Path, module: Option<Kind>) -> bool {
183         match self {
184             PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
185             PathSet::Suite(suite) => Self::check(suite, needle, module),
186         }
187     }
188
189     // internal use only
190     fn check(p: &TaskPath, needle: &Path, module: Option<Kind>) -> bool {
191         if let (Some(p_kind), Some(kind)) = (&p.kind, module) {
192             p.path.ends_with(needle) && *p_kind == kind
193         } else {
194             p.path.ends_with(needle)
195         }
196     }
197
198     /// Return all `TaskPath`s in `Self` that contain any of the `needles`, removing the
199     /// matched needles.
200     ///
201     /// This is used for `StepDescription::krate`, which passes all matching crates at once to
202     /// `Step::make_run`, rather than calling it many times with a single crate.
203     /// See `tests.rs` for examples.
204     fn intersection_removing_matches(
205         &self,
206         needles: &mut Vec<&Path>,
207         module: Option<Kind>,
208     ) -> PathSet {
209         let mut check = |p| {
210             for (i, n) in needles.iter().enumerate() {
211                 let matched = Self::check(p, n, module);
212                 if matched {
213                     needles.remove(i);
214                     return true;
215                 }
216             }
217             false
218         };
219         match self {
220             PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
221             PathSet::Suite(suite) => {
222                 if check(suite) {
223                     self.clone()
224                 } else {
225                     PathSet::empty()
226                 }
227             }
228         }
229     }
230
231     /// A convenience wrapper for Steps which know they have no aliases and all their sets contain only a single path.
232     ///
233     /// This can be used with [`ShouldRun::krate`], [`ShouldRun::path`], or [`ShouldRun::alias`].
234     #[track_caller]
235     pub fn assert_single_path(&self) -> &TaskPath {
236         match self {
237             PathSet::Set(set) => {
238                 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
239                 set.iter().next().unwrap()
240             }
241             PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
242         }
243     }
244 }
245
246 impl StepDescription {
247     fn from<S: Step>(kind: Kind) -> StepDescription {
248         StepDescription {
249             default: S::DEFAULT,
250             only_hosts: S::ONLY_HOSTS,
251             should_run: S::should_run,
252             make_run: S::make_run,
253             name: std::any::type_name::<S>(),
254             kind,
255         }
256     }
257
258     fn maybe_run(&self, builder: &Builder<'_>, pathsets: Vec<PathSet>) {
259         if pathsets.iter().any(|set| self.is_excluded(builder, set)) {
260             return;
261         }
262
263         // Determine the targets participating in this rule.
264         let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
265
266         for target in targets {
267             let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
268             (self.make_run)(run);
269         }
270     }
271
272     fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
273         if builder.config.exclude.iter().any(|e| pathset.has(&e.path, e.kind)) {
274             println!("Skipping {:?} because it is excluded", pathset);
275             return true;
276         }
277
278         if !builder.config.exclude.is_empty() {
279             builder.verbose(&format!(
280                 "{:?} not skipped for {:?} -- not in {:?}",
281                 pathset, self.name, builder.config.exclude
282             ));
283         }
284         false
285     }
286
287     fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
288         let should_runs = v
289             .iter()
290             .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
291             .collect::<Vec<_>>();
292
293         // sanity checks on rules
294         for (desc, should_run) in v.iter().zip(&should_runs) {
295             assert!(
296                 !should_run.paths.is_empty(),
297                 "{:?} should have at least one pathset",
298                 desc.name
299             );
300         }
301
302         if paths.is_empty() || builder.config.include_default_paths {
303             for (desc, should_run) in v.iter().zip(&should_runs) {
304                 if desc.default && should_run.is_really_default() {
305                     desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
306                 }
307             }
308         }
309
310         // strip CurDir prefix if present
311         let mut paths: Vec<_> =
312             paths.into_iter().map(|p| p.strip_prefix(".").unwrap_or(p)).collect();
313
314         // Handle all test suite paths.
315         // (This is separate from the loop below to avoid having to handle multiple paths in `is_suite_path` somehow.)
316         paths.retain(|path| {
317             for (desc, should_run) in v.iter().zip(&should_runs) {
318                 if let Some(suite) = should_run.is_suite_path(&path) {
319                     desc.maybe_run(builder, vec![suite.clone()]);
320                     return false;
321                 }
322             }
323             true
324         });
325
326         if paths.is_empty() {
327             return;
328         }
329
330         // Handle all PathSets.
331         for (desc, should_run) in v.iter().zip(&should_runs) {
332             let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
333             if !pathsets.is_empty() {
334                 desc.maybe_run(builder, pathsets);
335             }
336         }
337
338         if !paths.is_empty() {
339             eprintln!("error: no `{}` rules matched {:?}", builder.kind.as_str(), paths,);
340             eprintln!(
341                 "help: run `x.py {} --help --verbose` to show a list of available paths",
342                 builder.kind.as_str()
343             );
344             eprintln!(
345                 "note: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
346             );
347             crate::detail_exit(1);
348         }
349     }
350 }
351
352 enum ReallyDefault<'a> {
353     Bool(bool),
354     Lazy(Lazy<bool, Box<dyn Fn() -> bool + 'a>>),
355 }
356
357 pub struct ShouldRun<'a> {
358     pub builder: &'a Builder<'a>,
359     kind: Kind,
360
361     // use a BTreeSet to maintain sort order
362     paths: BTreeSet<PathSet>,
363
364     // If this is a default rule, this is an additional constraint placed on
365     // its run. Generally something like compiler docs being enabled.
366     is_really_default: ReallyDefault<'a>,
367 }
368
369 impl<'a> ShouldRun<'a> {
370     fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
371         ShouldRun {
372             builder,
373             kind,
374             paths: BTreeSet::new(),
375             is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
376         }
377     }
378
379     pub fn default_condition(mut self, cond: bool) -> Self {
380         self.is_really_default = ReallyDefault::Bool(cond);
381         self
382     }
383
384     pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
385         self.is_really_default = ReallyDefault::Lazy(Lazy::new(lazy_cond));
386         self
387     }
388
389     pub fn is_really_default(&self) -> bool {
390         match &self.is_really_default {
391             ReallyDefault::Bool(val) => *val,
392             ReallyDefault::Lazy(lazy) => *lazy.deref(),
393         }
394     }
395
396     /// Indicates it should run if the command-line selects the given crate or
397     /// any of its (local) dependencies.
398     ///
399     /// Compared to `krate`, this treats the dependencies as aliases for the
400     /// same job. Generally it is preferred to use `krate`, and treat each
401     /// individual path separately. For example `./x.py test src/liballoc`
402     /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
403     /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
404     /// `all_krates` should probably be removed at some point.
405     pub fn all_krates(mut self, name: &str) -> Self {
406         let mut set = BTreeSet::new();
407         for krate in self.builder.in_tree_crates(name, None) {
408             let path = krate.local_path(self.builder);
409             set.insert(TaskPath { path, kind: Some(self.kind) });
410         }
411         self.paths.insert(PathSet::Set(set));
412         self
413     }
414
415     /// Indicates it should run if the command-line selects the given crate or
416     /// any of its (local) dependencies.
417     ///
418     /// `make_run` will be called a single time with all matching command-line paths.
419     pub fn crate_or_deps(self, name: &str) -> Self {
420         let crates = self.builder.in_tree_crates(name, None);
421         self.crates(crates)
422     }
423
424     /// Indicates it should run if the command-line selects any of the given crates.
425     ///
426     /// `make_run` will be called a single time with all matching command-line paths.
427     pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
428         for krate in crates {
429             let path = krate.local_path(self.builder);
430             self.paths.insert(PathSet::one(path, self.kind));
431         }
432         self
433     }
434
435     // single alias, which does not correspond to any on-disk path
436     pub fn alias(mut self, alias: &str) -> Self {
437         // exceptional case for `Kind::Setup` because its `library`
438         // and `compiler` options would otherwise naively match with
439         // `compiler` and `library` folders respectively.
440         assert!(
441             self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
442             "use `builder.path()` for real paths: {}",
443             alias
444         );
445         self.paths.insert(PathSet::Set(
446             std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
447         ));
448         self
449     }
450
451     // single, non-aliased path
452     pub fn path(self, path: &str) -> Self {
453         self.paths(&[path])
454     }
455
456     // multiple aliases for the same job
457     pub fn paths(mut self, paths: &[&str]) -> Self {
458         self.paths.insert(PathSet::Set(
459             paths
460                 .iter()
461                 .map(|p| {
462                     // FIXME(#96188): make sure this is actually a path.
463                     // This currently breaks for paths within submodules.
464                     //assert!(
465                     //    self.builder.src.join(p).exists(),
466                     //    "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {}",
467                     //    p
468                     //);
469                     TaskPath { path: p.into(), kind: Some(self.kind) }
470                 })
471                 .collect(),
472         ));
473         self
474     }
475
476     /// Handles individual files (not directories) within a test suite.
477     fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
478         self.paths.iter().find(|pathset| match pathset {
479             PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
480             PathSet::Set(_) => false,
481         })
482     }
483
484     pub fn suite_path(mut self, suite: &str) -> Self {
485         self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
486         self
487     }
488
489     // allows being more explicit about why should_run in Step returns the value passed to it
490     pub fn never(mut self) -> ShouldRun<'a> {
491         self.paths.insert(PathSet::empty());
492         self
493     }
494
495     /// Given a set of requested paths, return the subset which match the Step for this `ShouldRun`,
496     /// removing the matches from `paths`.
497     ///
498     /// NOTE: this returns multiple PathSets to allow for the possibility of multiple units of work
499     /// within the same step. For example, `test::Crate` allows testing multiple crates in the same
500     /// cargo invocation, which are put into separate sets because they aren't aliases.
501     ///
502     /// The reason we return PathSet instead of PathBuf is to allow for aliases that mean the same thing
503     /// (for now, just `all_krates` and `paths`, but we may want to add an `aliases` function in the future?)
504     fn pathset_for_paths_removing_matches(
505         &self,
506         paths: &mut Vec<&Path>,
507         kind: Kind,
508     ) -> Vec<PathSet> {
509         let mut sets = vec![];
510         for pathset in &self.paths {
511             let subset = pathset.intersection_removing_matches(paths, Some(kind));
512             if subset != PathSet::empty() {
513                 sets.push(subset);
514             }
515         }
516         sets
517     }
518 }
519
520 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
521 pub enum Kind {
522     Build,
523     Check,
524     Clippy,
525     Fix,
526     Format,
527     Test,
528     Bench,
529     Doc,
530     Clean,
531     Dist,
532     Install,
533     Run,
534     Setup,
535 }
536
537 impl Kind {
538     pub fn parse(string: &str) -> Option<Kind> {
539         // these strings, including the one-letter aliases, must match the x.py help text
540         Some(match string {
541             "build" | "b" => Kind::Build,
542             "check" | "c" => Kind::Check,
543             "clippy" => Kind::Clippy,
544             "fix" => Kind::Fix,
545             "fmt" => Kind::Format,
546             "test" | "t" => Kind::Test,
547             "bench" => Kind::Bench,
548             "doc" | "d" => Kind::Doc,
549             "clean" => Kind::Clean,
550             "dist" => Kind::Dist,
551             "install" => Kind::Install,
552             "run" | "r" => Kind::Run,
553             "setup" => Kind::Setup,
554             _ => return None,
555         })
556     }
557
558     pub fn as_str(&self) -> &'static str {
559         match self {
560             Kind::Build => "build",
561             Kind::Check => "check",
562             Kind::Clippy => "clippy",
563             Kind::Fix => "fix",
564             Kind::Format => "fmt",
565             Kind::Test => "test",
566             Kind::Bench => "bench",
567             Kind::Doc => "doc",
568             Kind::Clean => "clean",
569             Kind::Dist => "dist",
570             Kind::Install => "install",
571             Kind::Run => "run",
572             Kind::Setup => "setup",
573         }
574     }
575 }
576
577 impl<'a> Builder<'a> {
578     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
579         macro_rules! describe {
580             ($($rule:ty),+ $(,)?) => {{
581                 vec![$(StepDescription::from::<$rule>(kind)),+]
582             }};
583         }
584         match kind {
585             Kind::Build => describe!(
586                 compile::Std,
587                 compile::Rustc,
588                 compile::Assemble,
589                 compile::CodegenBackend,
590                 compile::StartupObjects,
591                 tool::BuildManifest,
592                 tool::Rustbook,
593                 tool::ErrorIndex,
594                 tool::UnstableBookGen,
595                 tool::Tidy,
596                 tool::Linkchecker,
597                 tool::CargoTest,
598                 tool::Compiletest,
599                 tool::RemoteTestServer,
600                 tool::RemoteTestClient,
601                 tool::RustInstaller,
602                 tool::Cargo,
603                 tool::Rls,
604                 tool::RustAnalyzer,
605                 tool::RustAnalyzerProcMacroSrv,
606                 tool::RustDemangler,
607                 tool::Rustdoc,
608                 tool::Clippy,
609                 tool::CargoClippy,
610                 native::Llvm,
611                 native::Sanitizers,
612                 tool::Rustfmt,
613                 tool::Miri,
614                 tool::CargoMiri,
615                 native::Lld,
616                 native::CrtBeginEnd
617             ),
618             Kind::Check | Kind::Clippy | Kind::Fix => describe!(
619                 check::Std,
620                 check::Rustc,
621                 check::Rustdoc,
622                 check::CodegenBackend,
623                 check::Clippy,
624                 check::Miri,
625                 check::CargoMiri,
626                 check::MiroptTestTools,
627                 check::Rls,
628                 check::RustAnalyzer,
629                 check::Rustfmt,
630                 check::Bootstrap
631             ),
632             Kind::Test => describe!(
633                 crate::toolstate::ToolStateCheck,
634                 test::ExpandYamlAnchors,
635                 test::Tidy,
636                 test::Ui,
637                 test::RunPassValgrind,
638                 test::MirOpt,
639                 test::Codegen,
640                 test::CodegenUnits,
641                 test::Assembly,
642                 test::Incremental,
643                 test::Debuginfo,
644                 test::UiFullDeps,
645                 test::Rustdoc,
646                 test::Pretty,
647                 test::Crate,
648                 test::CrateLibrustc,
649                 test::CrateRustdoc,
650                 test::CrateRustdocJsonTypes,
651                 test::CrateJsonDocLint,
652                 test::Linkcheck,
653                 test::TierCheck,
654                 test::ReplacePlaceholderTest,
655                 test::Cargotest,
656                 test::Cargo,
657                 test::RustAnalyzer,
658                 test::ErrorIndex,
659                 test::Distcheck,
660                 test::RunMakeFullDeps,
661                 test::Nomicon,
662                 test::Reference,
663                 test::RustdocBook,
664                 test::RustByExample,
665                 test::TheBook,
666                 test::UnstableBook,
667                 test::RustcBook,
668                 test::LintDocs,
669                 test::RustcGuide,
670                 test::EmbeddedBook,
671                 test::EditionGuide,
672                 test::Rustfmt,
673                 test::Miri,
674                 test::Clippy,
675                 test::RustDemangler,
676                 test::CompiletestTest,
677                 test::RustdocJSStd,
678                 test::RustdocJSNotStd,
679                 test::RustdocGUI,
680                 test::RustdocTheme,
681                 test::RustdocUi,
682                 test::RustdocJson,
683                 test::HtmlCheck,
684                 // Run bootstrap close to the end as it's unlikely to fail
685                 test::Bootstrap,
686                 // Run run-make last, since these won't pass without make on Windows
687                 test::RunMake,
688             ),
689             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
690             Kind::Doc => describe!(
691                 doc::UnstableBook,
692                 doc::UnstableBookGen,
693                 doc::TheBook,
694                 doc::Standalone,
695                 doc::Std,
696                 doc::Rustc,
697                 doc::Rustdoc,
698                 doc::Rustfmt,
699                 doc::ErrorIndex,
700                 doc::Nomicon,
701                 doc::Reference,
702                 doc::RustdocBook,
703                 doc::RustByExample,
704                 doc::RustcBook,
705                 doc::Cargo,
706                 doc::CargoBook,
707                 doc::Clippy,
708                 doc::ClippyBook,
709                 doc::Miri,
710                 doc::EmbeddedBook,
711                 doc::EditionGuide,
712                 doc::StyleGuide,
713             ),
714             Kind::Dist => describe!(
715                 dist::Docs,
716                 dist::RustcDocs,
717                 dist::JsonDocs,
718                 dist::Mingw,
719                 dist::Rustc,
720                 dist::Std,
721                 dist::RustcDev,
722                 dist::Analysis,
723                 dist::Src,
724                 dist::Cargo,
725                 dist::Rls,
726                 dist::RustAnalyzer,
727                 dist::Rustfmt,
728                 dist::RustDemangler,
729                 dist::Clippy,
730                 dist::Miri,
731                 dist::LlvmTools,
732                 dist::RustDev,
733                 dist::Bootstrap,
734                 dist::Extended,
735                 // It seems that PlainSourceTarball somehow changes how some of the tools
736                 // perceive their dependencies (see #93033) which would invalidate fingerprints
737                 // and force us to rebuild tools after vendoring dependencies.
738                 // To work around this, create the Tarball after building all the tools.
739                 dist::PlainSourceTarball,
740                 dist::BuildManifest,
741                 dist::ReproducibleArtifacts,
742             ),
743             Kind::Install => describe!(
744                 install::Docs,
745                 install::Std,
746                 install::Cargo,
747                 install::RustAnalyzer,
748                 install::Rustfmt,
749                 install::RustDemangler,
750                 install::Clippy,
751                 install::Miri,
752                 install::LlvmTools,
753                 install::Analysis,
754                 install::Src,
755                 install::Rustc
756             ),
757             Kind::Run => describe!(
758                 run::ExpandYamlAnchors,
759                 run::BuildManifest,
760                 run::BumpStage0,
761                 run::ReplaceVersionPlaceholder,
762                 run::Miri,
763                 run::CollectLicenseMetadata,
764                 run::GenerateCopyright,
765             ),
766             Kind::Setup => describe!(setup::Profile),
767             // These commands either don't use paths, or they're special-cased in Build::build()
768             Kind::Clean | Kind::Format => vec![],
769         }
770     }
771
772     pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
773         let step_descriptions = Builder::get_step_descriptions(kind);
774         if step_descriptions.is_empty() {
775             return None;
776         }
777
778         let builder = Self::new_internal(build, kind, vec![]);
779         let builder = &builder;
780         // The "build" kind here is just a placeholder, it will be replaced with something else in
781         // the following statement.
782         let mut should_run = ShouldRun::new(builder, Kind::Build);
783         for desc in step_descriptions {
784             should_run.kind = desc.kind;
785             should_run = (desc.should_run)(should_run);
786         }
787         let mut help = String::from("Available paths:\n");
788         let mut add_path = |path: &Path| {
789             t!(write!(help, "    ./x.py {} {}\n", kind.as_str(), path.display()));
790         };
791         for pathset in should_run.paths {
792             match pathset {
793                 PathSet::Set(set) => {
794                     for path in set {
795                         add_path(&path.path);
796                     }
797                 }
798                 PathSet::Suite(path) => {
799                     add_path(&path.path.join("..."));
800                 }
801             }
802         }
803         Some(help)
804     }
805
806     fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
807         Builder {
808             build,
809             top_stage: build.config.stage,
810             kind,
811             cache: Cache::new(),
812             stack: RefCell::new(Vec::new()),
813             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
814             paths,
815         }
816     }
817
818     pub fn new(build: &Build) -> Builder<'_> {
819         let (kind, paths) = match build.config.cmd {
820             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
821             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
822             Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
823             Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
824             Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
825             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
826             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
827             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
828             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
829             Subcommand::Run { ref paths, .. } => (Kind::Run, &paths[..]),
830             Subcommand::Format { .. } => (Kind::Format, &[][..]),
831             Subcommand::Setup { profile: ref path } => (
832                 Kind::Setup,
833                 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
834             ),
835             Subcommand::Clean { .. } => {
836                 panic!()
837             }
838         };
839
840         Self::new_internal(build, kind, paths.to_owned())
841     }
842
843     pub fn execute_cli(&self) {
844         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
845     }
846
847     pub fn default_doc(&self, paths: &[PathBuf]) {
848         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
849     }
850
851     /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
852     pub fn doc_rust_lang_org_channel(&self) -> String {
853         let channel = match &*self.config.channel {
854             "stable" => &self.version,
855             "beta" => "beta",
856             "nightly" | "dev" => "nightly",
857             // custom build of rustdoc maybe? link to the latest stable docs just in case
858             _ => "stable",
859         };
860         "https://doc.rust-lang.org/".to_owned() + channel
861     }
862
863     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
864         StepDescription::run(v, self, paths);
865     }
866
867     /// Obtain a compiler at a given stage and for a given host. Explicitly does
868     /// not take `Compiler` since all `Compiler` instances are meant to be
869     /// obtained through this function, since it ensures that they are valid
870     /// (i.e., built and assembled).
871     pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
872         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
873     }
874
875     /// Similar to `compiler`, except handles the full-bootstrap option to
876     /// silently use the stage1 compiler instead of a stage2 compiler if one is
877     /// requested.
878     ///
879     /// Note that this does *not* have the side effect of creating
880     /// `compiler(stage, host)`, unlike `compiler` above which does have such
881     /// a side effect. The returned compiler here can only be used to compile
882     /// new artifacts, it can't be used to rely on the presence of a particular
883     /// sysroot.
884     ///
885     /// See `force_use_stage1` for documentation on what each argument is.
886     pub fn compiler_for(
887         &self,
888         stage: u32,
889         host: TargetSelection,
890         target: TargetSelection,
891     ) -> Compiler {
892         if self.build.force_use_stage1(Compiler { stage, host }, target) {
893             self.compiler(1, self.config.build)
894         } else {
895             self.compiler(stage, host)
896         }
897     }
898
899     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
900         self.ensure(compile::Sysroot { compiler })
901     }
902
903     /// Returns the libdir where the standard library and other artifacts are
904     /// found for a compiler's sysroot.
905     pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
906         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
907         struct Libdir {
908             compiler: Compiler,
909             target: TargetSelection,
910         }
911         impl Step for Libdir {
912             type Output = Interned<PathBuf>;
913
914             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
915                 run.never()
916             }
917
918             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
919                 let lib = builder.sysroot_libdir_relative(self.compiler);
920                 let sysroot = builder
921                     .sysroot(self.compiler)
922                     .join(lib)
923                     .join("rustlib")
924                     .join(self.target.triple)
925                     .join("lib");
926                 // Avoid deleting the rustlib/ directory we just copied
927                 // (in `impl Step for Sysroot`).
928                 if !builder.download_rustc() {
929                     let _ = fs::remove_dir_all(&sysroot);
930                     t!(fs::create_dir_all(&sysroot));
931                 }
932                 INTERNER.intern_path(sysroot)
933             }
934         }
935         self.ensure(Libdir { compiler, target })
936     }
937
938     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
939         self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
940     }
941
942     /// Returns the compiler's libdir where it stores the dynamic libraries that
943     /// it itself links against.
944     ///
945     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
946     /// Windows.
947     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
948         if compiler.is_snapshot(self) {
949             self.rustc_snapshot_libdir()
950         } else {
951             match self.config.libdir_relative() {
952                 Some(relative_libdir) if compiler.stage >= 1 => {
953                     self.sysroot(compiler).join(relative_libdir)
954                 }
955                 _ => self.sysroot(compiler).join(libdir(compiler.host)),
956             }
957         }
958     }
959
960     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
961     /// it itself links against.
962     ///
963     /// For example this returns `lib` on Unix and `bin` on
964     /// Windows.
965     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
966         if compiler.is_snapshot(self) {
967             libdir(self.config.build).as_ref()
968         } else {
969             match self.config.libdir_relative() {
970                 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
971                 _ => libdir(compiler.host).as_ref(),
972             }
973         }
974     }
975
976     /// Returns the compiler's relative libdir where the standard library and other artifacts are
977     /// found for a compiler's sysroot.
978     ///
979     /// For example this returns `lib` on Unix and Windows.
980     pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
981         match self.config.libdir_relative() {
982             Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
983             _ if compiler.stage == 0 => &self.build.initial_libdir,
984             _ => Path::new("lib"),
985         }
986     }
987
988     pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
989         let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
990
991         // Ensure that the downloaded LLVM libraries can be found.
992         if self.config.llvm_from_ci {
993             let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
994             dylib_dirs.push(ci_llvm_lib);
995         }
996
997         dylib_dirs
998     }
999
1000     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1001     /// library lookup path.
1002     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
1003         // Windows doesn't need dylib path munging because the dlls for the
1004         // compiler live next to the compiler and the system will find them
1005         // automatically.
1006         if cfg!(windows) {
1007             return;
1008         }
1009
1010         add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1011     }
1012
1013     /// Gets a path to the compiler specified.
1014     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1015         if compiler.is_snapshot(self) {
1016             self.initial_rustc.clone()
1017         } else {
1018             self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1019         }
1020     }
1021
1022     /// Gets the paths to all of the compiler's codegen backends.
1023     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1024         fs::read_dir(self.sysroot_codegen_backends(compiler))
1025             .into_iter()
1026             .flatten()
1027             .filter_map(Result::ok)
1028             .map(|entry| entry.path())
1029     }
1030
1031     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
1032         self.ensure(tool::Rustdoc { compiler })
1033     }
1034
1035     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
1036         let mut cmd = Command::new(&self.bootstrap_out.join("rustdoc"));
1037         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1038             .env("RUSTC_SYSROOT", self.sysroot(compiler))
1039             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1040             // equivalently to rustc.
1041             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1042             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1043             .env("RUSTDOC_REAL", self.rustdoc(compiler))
1044             .env("RUSTC_BOOTSTRAP", "1");
1045
1046         cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1047
1048         if self.config.deny_warnings {
1049             cmd.arg("-Dwarnings");
1050         }
1051         cmd.arg("-Znormalize-docs");
1052
1053         // Remove make-related flags that can cause jobserver problems.
1054         cmd.env_remove("MAKEFLAGS");
1055         cmd.env_remove("MFLAGS");
1056
1057         if let Some(linker) = self.linker(compiler.host) {
1058             cmd.env("RUSTDOC_LINKER", linker);
1059         }
1060         if self.is_fuse_ld_lld(compiler.host) {
1061             cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
1062         }
1063         cmd
1064     }
1065
1066     /// Return the path to `llvm-config` for the target, if it exists.
1067     ///
1068     /// Note that this returns `None` if LLVM is disabled, or if we're in a
1069     /// check build or dry-run, where there's no need to build all of LLVM.
1070     fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1071         if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run() {
1072             let native::LlvmResult { llvm_config, .. } = self.ensure(native::Llvm { target });
1073             if llvm_config.is_file() {
1074                 return Some(llvm_config);
1075             }
1076         }
1077         None
1078     }
1079
1080     /// Prepares an invocation of `cargo` to be run.
1081     ///
1082     /// This will create a `Command` that represents a pending execution of
1083     /// Cargo. This cargo will be configured to use `compiler` as the actual
1084     /// rustc compiler, its output will be scoped by `mode`'s output directory,
1085     /// it will pass the `--target` flag for the specified `target`, and will be
1086     /// executing the Cargo command `cmd`.
1087     pub fn cargo(
1088         &self,
1089         compiler: Compiler,
1090         mode: Mode,
1091         source_type: SourceType,
1092         target: TargetSelection,
1093         cmd: &str,
1094     ) -> Cargo {
1095         let mut cargo = Command::new(&self.initial_cargo);
1096         let out_dir = self.stage_out(compiler, mode);
1097         // Run cargo from the source root so it can find .cargo/config.
1098         // This matters when using vendoring and the working directory is outside the repository.
1099         cargo.current_dir(&self.src);
1100
1101         // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
1102         // so we need to explicitly clear out if they've been updated.
1103         for backend in self.codegen_backends(compiler) {
1104             self.clear_if_dirty(&out_dir, &backend);
1105         }
1106
1107         if cmd == "doc" || cmd == "rustdoc" {
1108             let my_out = match mode {
1109                 // This is the intended out directory for compiler documentation.
1110                 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
1111                 Mode::Std => {
1112                     if self.config.cmd.json() {
1113                         out_dir.join(target.triple).join("json-doc")
1114                     } else {
1115                         out_dir.join(target.triple).join("doc")
1116                     }
1117                 }
1118                 _ => panic!("doc mode {:?} not expected", mode),
1119             };
1120             let rustdoc = self.rustdoc(compiler);
1121             self.clear_if_dirty(&my_out, &rustdoc);
1122         }
1123
1124         cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
1125
1126         let profile_var = |name: &str| {
1127             let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
1128             format!("CARGO_PROFILE_{}_{}", profile, name)
1129         };
1130
1131         // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
1132         // needs to not accidentally link to libLLVM in stage0/lib.
1133         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
1134         if let Some(e) = env::var_os(util::dylib_path_var()) {
1135             cargo.env("REAL_LIBRARY_PATH", e);
1136         }
1137
1138         // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
1139         // from out of tree it shouldn't matter, since x.py is only used for
1140         // building in-tree.
1141         let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
1142         match self.build.config.color {
1143             Color::Always => {
1144                 cargo.arg("--color=always");
1145                 for log in &color_logs {
1146                     cargo.env(log, "always");
1147                 }
1148             }
1149             Color::Never => {
1150                 cargo.arg("--color=never");
1151                 for log in &color_logs {
1152                     cargo.env(log, "never");
1153                 }
1154             }
1155             Color::Auto => {} // nothing to do
1156         }
1157
1158         if cmd != "install" {
1159             cargo.arg("--target").arg(target.rustc_target_arg());
1160         } else {
1161             assert_eq!(target, compiler.host);
1162         }
1163
1164         // Set a flag for `check`/`clippy`/`fix`, so that certain build
1165         // scripts can do less work (i.e. not building/requiring LLVM).
1166         if cmd == "check" || cmd == "clippy" || cmd == "fix" {
1167             // If we've not yet built LLVM, or it's stale, then bust
1168             // the rustc_llvm cache. That will always work, even though it
1169             // may mean that on the next non-check build we'll need to rebuild
1170             // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
1171             // of work comparatively, and we'd likely need to rebuild it anyway,
1172             // so that's okay.
1173             if crate::native::prebuilt_llvm_config(self, target).is_err() {
1174                 cargo.env("RUST_CHECK", "1");
1175             }
1176         }
1177
1178         let stage = if compiler.stage == 0 && self.local_rebuild {
1179             // Assume the local-rebuild rustc already has stage1 features.
1180             1
1181         } else {
1182             compiler.stage
1183         };
1184
1185         let mut rustflags = Rustflags::new(target);
1186         if stage != 0 {
1187             if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
1188                 cargo.args(s.split_whitespace());
1189             }
1190             rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
1191         } else {
1192             if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
1193                 cargo.args(s.split_whitespace());
1194             }
1195             rustflags.env("RUSTFLAGS_BOOTSTRAP");
1196             if cmd == "clippy" {
1197                 // clippy overwrites sysroot if we pass it to cargo.
1198                 // Pass it directly to clippy instead.
1199                 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
1200                 // so it has no way of knowing the sysroot.
1201                 rustflags.arg("--sysroot");
1202                 rustflags.arg(
1203                     self.sysroot(compiler)
1204                         .as_os_str()
1205                         .to_str()
1206                         .expect("sysroot must be valid UTF-8"),
1207                 );
1208                 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
1209                 cargo.arg("-Zunstable-options");
1210                 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
1211                 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
1212                 let output = host_version.and_then(|output| {
1213                     if output.status.success() {
1214                         Ok(output)
1215                     } else {
1216                         Err(())
1217                     }
1218                 }).unwrap_or_else(|_| {
1219                     eprintln!(
1220                         "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
1221                     );
1222                     eprintln!("help: try `rustup component add clippy`");
1223                     crate::detail_exit(1);
1224                 });
1225                 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
1226                     rustflags.arg("--cfg=bootstrap");
1227                 }
1228             } else {
1229                 rustflags.arg("--cfg=bootstrap");
1230             }
1231         }
1232
1233         let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
1234             Some(setting) => {
1235                 // If an explicit setting is given, use that
1236                 setting
1237             }
1238             None => {
1239                 if mode == Mode::Std {
1240                     // The standard library defaults to the legacy scheme
1241                     false
1242                 } else {
1243                     // The compiler and tools default to the new scheme
1244                     true
1245                 }
1246             }
1247         };
1248
1249         if use_new_symbol_mangling {
1250             rustflags.arg("-Csymbol-mangling-version=v0");
1251         } else {
1252             rustflags.arg("-Csymbol-mangling-version=legacy");
1253             rustflags.arg("-Zunstable-options");
1254         }
1255
1256         // Enable cfg checking of cargo features for everything but std and also enable cfg
1257         // checking of names and values.
1258         //
1259         // Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like
1260         // backtrace, core_simd, std_float, ...), those dependencies have their own
1261         // features but cargo isn't involved in the #[path] process and so cannot pass the
1262         // complete list of features, so for that reason we don't enable checking of
1263         // features for std crates.
1264         cargo.arg(if mode != Mode::Std {
1265             "-Zcheck-cfg=names,values,output,features"
1266         } else {
1267             "-Zcheck-cfg=names,values,output"
1268         });
1269
1270         // Add extra cfg not defined in/by rustc
1271         //
1272         // Note: Altrough it would seems that "-Zunstable-options" to `rustflags` is useless as
1273         // cargo would implicitly add it, it was discover that sometimes bootstrap only use
1274         // `rustflags` without `cargo` making it required.
1275         rustflags.arg("-Zunstable-options");
1276         for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
1277             if *restricted_mode == None || *restricted_mode == Some(mode) {
1278                 // Creating a string of the values by concatenating each value:
1279                 // ',"tvos","watchos"' or '' (nothing) when there are no values
1280                 let values = match values {
1281                     Some(values) => values
1282                         .iter()
1283                         .map(|val| [",", "\"", val, "\""])
1284                         .flatten()
1285                         .collect::<String>(),
1286                     None => String::new(),
1287                 };
1288                 rustflags.arg(&format!("--check-cfg=values({name}{values})"));
1289             }
1290         }
1291
1292         // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1293         // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1294         // #71458.
1295         let mut rustdocflags = rustflags.clone();
1296         rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1297         if stage == 0 {
1298             rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1299         } else {
1300             rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1301         }
1302
1303         if let Ok(s) = env::var("CARGOFLAGS") {
1304             cargo.args(s.split_whitespace());
1305         }
1306
1307         match mode {
1308             Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1309             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1310                 // Build proc macros both for the host and the target
1311                 if target != compiler.host && cmd != "check" {
1312                     cargo.arg("-Zdual-proc-macros");
1313                     rustflags.arg("-Zdual-proc-macros");
1314                 }
1315             }
1316         }
1317
1318         // This tells Cargo (and in turn, rustc) to output more complete
1319         // dependency information.  Most importantly for rustbuild, this
1320         // includes sysroot artifacts, like libstd, which means that we don't
1321         // need to track those in rustbuild (an error prone process!). This
1322         // feature is currently unstable as there may be some bugs and such, but
1323         // it represents a big improvement in rustbuild's reliability on
1324         // rebuilds, so we're using it here.
1325         //
1326         // For some additional context, see #63470 (the PR originally adding
1327         // this), as well as #63012 which is the tracking issue for this
1328         // feature on the rustc side.
1329         cargo.arg("-Zbinary-dep-depinfo");
1330         match mode {
1331             Mode::ToolBootstrap => {
1332                 // Restrict the allowed features to those passed by rustbuild, so we don't depend on nightly accidentally.
1333                 rustflags.arg("-Zallow-features=binary-dep-depinfo");
1334             }
1335             Mode::ToolStd => {
1336                 // Right now this is just compiletest and a few other tools that build on stable.
1337                 // Allow them to use `feature(test)`, but nothing else.
1338                 rustflags.arg("-Zallow-features=binary-dep-depinfo,test,proc_macro_internals,proc_macro_diagnostic,proc_macro_span");
1339             }
1340             Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {}
1341         }
1342
1343         cargo.arg("-j").arg(self.jobs().to_string());
1344         // Remove make-related flags to ensure Cargo can correctly set things up
1345         cargo.env_remove("MAKEFLAGS");
1346         cargo.env_remove("MFLAGS");
1347
1348         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1349         // Force cargo to output binaries with disambiguating hashes in the name
1350         let mut metadata = if compiler.stage == 0 {
1351             // Treat stage0 like a special channel, whether it's a normal prior-
1352             // release rustc or a local rebuild with the same version, so we
1353             // never mix these libraries by accident.
1354             "bootstrap".to_string()
1355         } else {
1356             self.config.channel.to_string()
1357         };
1358         // We want to make sure that none of the dependencies between
1359         // std/test/rustc unify with one another. This is done for weird linkage
1360         // reasons but the gist of the problem is that if librustc, libtest, and
1361         // libstd all depend on libc from crates.io (which they actually do) we
1362         // want to make sure they all get distinct versions. Things get really
1363         // weird if we try to unify all these dependencies right now, namely
1364         // around how many times the library is linked in dynamic libraries and
1365         // such. If rustc were a static executable or if we didn't ship dylibs
1366         // this wouldn't be a problem, but we do, so it is. This is in general
1367         // just here to make sure things build right. If you can remove this and
1368         // things still build right, please do!
1369         match mode {
1370             Mode::Std => metadata.push_str("std"),
1371             // When we're building rustc tools, they're built with a search path
1372             // that contains things built during the rustc build. For example,
1373             // bitflags is built during the rustc build, and is a dependency of
1374             // rustdoc as well. We're building rustdoc in a different target
1375             // directory, though, which means that Cargo will rebuild the
1376             // dependency. When we go on to build rustdoc, we'll look for
1377             // bitflags, and find two different copies: one built during the
1378             // rustc step and one that we just built. This isn't always a
1379             // problem, somehow -- not really clear why -- but we know that this
1380             // fixes things.
1381             Mode::ToolRustc => metadata.push_str("tool-rustc"),
1382             // Same for codegen backends.
1383             Mode::Codegen => metadata.push_str("codegen"),
1384             _ => {}
1385         }
1386         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1387
1388         if cmd == "clippy" {
1389             rustflags.arg("-Zforce-unstable-if-unmarked");
1390         }
1391
1392         rustflags.arg("-Zmacro-backtrace");
1393
1394         let want_rustdoc = self.doc_tests != DocTests::No;
1395
1396         // We synthetically interpret a stage0 compiler used to build tools as a
1397         // "raw" compiler in that it's the exact snapshot we download. Normally
1398         // the stage0 build means it uses libraries build by the stage0
1399         // compiler, but for tools we just use the precompiled libraries that
1400         // we've downloaded
1401         let use_snapshot = mode == Mode::ToolBootstrap;
1402         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1403
1404         let maybe_sysroot = self.sysroot(compiler);
1405         let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1406         let libdir = self.rustc_libdir(compiler);
1407
1408         // Clear the output directory if the real rustc we're using has changed;
1409         // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1410         //
1411         // Avoid doing this during dry run as that usually means the relevant
1412         // compiler is not yet linked/copied properly.
1413         //
1414         // Only clear out the directory if we're compiling std; otherwise, we
1415         // should let Cargo take care of things for us (via depdep info)
1416         if !self.config.dry_run() && mode == Mode::Std && cmd == "build" {
1417             self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1418         }
1419
1420         // Customize the compiler we're running. Specify the compiler to cargo
1421         // as our shim and then pass it some various options used to configure
1422         // how the actual compiler itself is called.
1423         //
1424         // These variables are primarily all read by
1425         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1426         cargo
1427             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1428             .env("RUSTC_REAL", self.rustc(compiler))
1429             .env("RUSTC_STAGE", stage.to_string())
1430             .env("RUSTC_SYSROOT", &sysroot)
1431             .env("RUSTC_LIBDIR", &libdir)
1432             .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
1433             .env(
1434                 "RUSTDOC_REAL",
1435                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1436                     self.rustdoc(compiler)
1437                 } else {
1438                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1439                 },
1440             )
1441             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1442             .env("RUSTC_BREAK_ON_ICE", "1");
1443         // Clippy support is a hack and uses the default `cargo-clippy` in path.
1444         // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1445         if cmd != "clippy" {
1446             cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
1447         }
1448
1449         // Dealing with rpath here is a little special, so let's go into some
1450         // detail. First off, `-rpath` is a linker option on Unix platforms
1451         // which adds to the runtime dynamic loader path when looking for
1452         // dynamic libraries. We use this by default on Unix platforms to ensure
1453         // that our nightlies behave the same on Windows, that is they work out
1454         // of the box. This can be disabled, of course, but basically that's why
1455         // we're gated on RUSTC_RPATH here.
1456         //
1457         // Ok, so the astute might be wondering "why isn't `-C rpath` used
1458         // here?" and that is indeed a good question to ask. This codegen
1459         // option is the compiler's current interface to generating an rpath.
1460         // Unfortunately it doesn't quite suffice for us. The flag currently
1461         // takes no value as an argument, so the compiler calculates what it
1462         // should pass to the linker as `-rpath`. This unfortunately is based on
1463         // the **compile time** directory structure which when building with
1464         // Cargo will be very different than the runtime directory structure.
1465         //
1466         // All that's a really long winded way of saying that if we use
1467         // `-Crpath` then the executables generated have the wrong rpath of
1468         // something like `$ORIGIN/deps` when in fact the way we distribute
1469         // rustc requires the rpath to be `$ORIGIN/../lib`.
1470         //
1471         // So, all in all, to set up the correct rpath we pass the linker
1472         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1473         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1474         // to change a flag in a binary?
1475         if self.config.rust_rpath && util::use_host_linker(target) {
1476             let rpath = if target.contains("apple") {
1477                 // Note that we need to take one extra step on macOS to also pass
1478                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1479                 // do that we pass a weird flag to the compiler to get it to do
1480                 // so. Note that this is definitely a hack, and we should likely
1481                 // flesh out rpath support more fully in the future.
1482                 rustflags.arg("-Zosx-rpath-install-name");
1483                 Some("-Wl,-rpath,@loader_path/../lib")
1484             } else if !target.contains("windows") {
1485                 rustflags.arg("-Clink-args=-Wl,-z,origin");
1486                 Some("-Wl,-rpath,$ORIGIN/../lib")
1487             } else {
1488                 None
1489             };
1490             if let Some(rpath) = rpath {
1491                 rustflags.arg(&format!("-Clink-args={}", rpath));
1492             }
1493         }
1494
1495         if let Some(host_linker) = self.linker(compiler.host) {
1496             cargo.env("RUSTC_HOST_LINKER", host_linker);
1497         }
1498         if self.is_fuse_ld_lld(compiler.host) {
1499             cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1500             cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1501         }
1502
1503         if let Some(target_linker) = self.linker(target) {
1504             let target = crate::envify(&target.triple);
1505             cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1506         }
1507         if self.is_fuse_ld_lld(target) {
1508             rustflags.arg("-Clink-args=-fuse-ld=lld");
1509         }
1510         self.lld_flags(target).for_each(|flag| {
1511             rustdocflags.arg(&flag);
1512         });
1513
1514         if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1515             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1516         }
1517
1518         let debuginfo_level = match mode {
1519             Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1520             Mode::Std => self.config.rust_debuginfo_level_std,
1521             Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1522                 self.config.rust_debuginfo_level_tools
1523             }
1524         };
1525         cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1526         cargo.env(
1527             profile_var("DEBUG_ASSERTIONS"),
1528             if mode == Mode::Std {
1529                 self.config.rust_debug_assertions_std.to_string()
1530             } else {
1531                 self.config.rust_debug_assertions.to_string()
1532             },
1533         );
1534         cargo.env(
1535             profile_var("OVERFLOW_CHECKS"),
1536             if mode == Mode::Std {
1537                 self.config.rust_overflow_checks_std.to_string()
1538             } else {
1539                 self.config.rust_overflow_checks.to_string()
1540             },
1541         );
1542
1543         let split_debuginfo_is_stable = target.contains("linux")
1544             || target.contains("apple")
1545             || (target.contains("msvc")
1546                 && self.config.rust_split_debuginfo == SplitDebuginfo::Packed)
1547             || (target.contains("windows")
1548                 && self.config.rust_split_debuginfo == SplitDebuginfo::Off);
1549
1550         if !split_debuginfo_is_stable {
1551             rustflags.arg("-Zunstable-options");
1552         }
1553         match self.config.rust_split_debuginfo {
1554             SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
1555             SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
1556             SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
1557         };
1558
1559         if self.config.cmd.bless() {
1560             // Bless `expect!` tests.
1561             cargo.env("UPDATE_EXPECT", "1");
1562         }
1563
1564         if !mode.is_tool() {
1565             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1566         }
1567
1568         if let Some(x) = self.crt_static(target) {
1569             if x {
1570                 rustflags.arg("-Ctarget-feature=+crt-static");
1571             } else {
1572                 rustflags.arg("-Ctarget-feature=-crt-static");
1573             }
1574         }
1575
1576         if let Some(x) = self.crt_static(compiler.host) {
1577             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1578         }
1579
1580         if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1581             let map = format!("{}={}", self.build.src.display(), map_to);
1582             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1583
1584             // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1585             // in order to opportunistically reverse it later.
1586             cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1587         }
1588
1589         // Enable usage of unstable features
1590         cargo.env("RUSTC_BOOTSTRAP", "1");
1591         self.add_rust_test_threads(&mut cargo);
1592
1593         // Almost all of the crates that we compile as part of the bootstrap may
1594         // have a build script, including the standard library. To compile a
1595         // build script, however, it itself needs a standard library! This
1596         // introduces a bit of a pickle when we're compiling the standard
1597         // library itself.
1598         //
1599         // To work around this we actually end up using the snapshot compiler
1600         // (stage0) for compiling build scripts of the standard library itself.
1601         // The stage0 compiler is guaranteed to have a libstd available for use.
1602         //
1603         // For other crates, however, we know that we've already got a standard
1604         // library up and running, so we can use the normal compiler to compile
1605         // build scripts in that situation.
1606         if mode == Mode::Std {
1607             cargo
1608                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1609                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1610         } else {
1611             cargo
1612                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1613                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1614         }
1615
1616         // Tools that use compiler libraries may inherit the `-lLLVM` link
1617         // requirement, but the `-L` library path is not propagated across
1618         // separate Cargo projects. We can add LLVM's library path to the
1619         // platform-specific environment variable as a workaround.
1620         if mode == Mode::ToolRustc || mode == Mode::Codegen {
1621             if let Some(llvm_config) = self.llvm_config(target) {
1622                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1623                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1624             }
1625         }
1626
1627         // Compile everything except libraries and proc macros with the more
1628         // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1629         // so we can't use it by default in general, but we can use it for tools
1630         // and our own internal libraries.
1631         if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1632             cargo.env("RUSTC_TLS_MODEL_INITIAL_EXEC", "1");
1633         }
1634
1635         if self.config.incremental {
1636             cargo.env("CARGO_INCREMENTAL", "1");
1637         } else {
1638             // Don't rely on any default setting for incr. comp. in Cargo
1639             cargo.env("CARGO_INCREMENTAL", "0");
1640         }
1641
1642         if let Some(ref on_fail) = self.config.on_fail {
1643             cargo.env("RUSTC_ON_FAIL", on_fail);
1644         }
1645
1646         if self.config.print_step_timings {
1647             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1648         }
1649
1650         if self.config.print_step_rusage {
1651             cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1652         }
1653
1654         if self.config.backtrace_on_ice {
1655             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1656         }
1657
1658         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1659
1660         if source_type == SourceType::InTree {
1661             let mut lint_flags = Vec::new();
1662             // When extending this list, add the new lints to the RUSTFLAGS of the
1663             // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1664             // some code doesn't go through this `rustc` wrapper.
1665             lint_flags.push("-Wrust_2018_idioms");
1666             lint_flags.push("-Wunused_lifetimes");
1667             lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1668
1669             if self.config.deny_warnings {
1670                 lint_flags.push("-Dwarnings");
1671                 rustdocflags.arg("-Dwarnings");
1672             }
1673
1674             // This does not use RUSTFLAGS due to caching issues with Cargo.
1675             // Clippy is treated as an "in tree" tool, but shares the same
1676             // cache as other "submodule" tools. With these options set in
1677             // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1678             // By injecting this into the rustc wrapper, this circumvents
1679             // Cargo's fingerprint detection. This is fine because lint flags
1680             // are always ignored in dependencies. Eventually this should be
1681             // fixed via better support from Cargo.
1682             cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1683
1684             rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1685         }
1686
1687         if mode == Mode::Rustc {
1688             rustflags.arg("-Zunstable-options");
1689             rustflags.arg("-Wrustc::internal");
1690         }
1691
1692         // Throughout the build Cargo can execute a number of build scripts
1693         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1694         // obtained previously to those build scripts.
1695         // Build scripts use either the `cc` crate or `configure/make` so we pass
1696         // the options through environment variables that are fetched and understood by both.
1697         //
1698         // FIXME: the guard against msvc shouldn't need to be here
1699         if target.contains("msvc") {
1700             if let Some(ref cl) = self.config.llvm_clang_cl {
1701                 cargo.env("CC", cl).env("CXX", cl);
1702             }
1703         } else {
1704             let ccache = self.config.ccache.as_ref();
1705             let ccacheify = |s: &Path| {
1706                 let ccache = match ccache {
1707                     Some(ref s) => s,
1708                     None => return s.display().to_string(),
1709                 };
1710                 // FIXME: the cc-rs crate only recognizes the literal strings
1711                 // `ccache` and `sccache` when doing caching compilations, so we
1712                 // mirror that here. It should probably be fixed upstream to
1713                 // accept a new env var or otherwise work with custom ccache
1714                 // vars.
1715                 match &ccache[..] {
1716                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1717                     _ => s.display().to_string(),
1718                 }
1719             };
1720             let triple_underscored = target.triple.replace("-", "_");
1721             let cc = ccacheify(&self.cc(target));
1722             cargo.env(format!("CC_{}", triple_underscored), &cc);
1723
1724             let cflags = self.cflags(target, GitRepo::Rustc, CLang::C).join(" ");
1725             cargo.env(format!("CFLAGS_{}", triple_underscored), &cflags);
1726
1727             if let Some(ar) = self.ar(target) {
1728                 let ranlib = format!("{} s", ar.display());
1729                 cargo
1730                     .env(format!("AR_{}", triple_underscored), ar)
1731                     .env(format!("RANLIB_{}", triple_underscored), ranlib);
1732             }
1733
1734             if let Ok(cxx) = self.cxx(target) {
1735                 let cxx = ccacheify(&cxx);
1736                 let cxxflags = self.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");
1737                 cargo
1738                     .env(format!("CXX_{}", triple_underscored), &cxx)
1739                     .env(format!("CXXFLAGS_{}", triple_underscored), cxxflags);
1740             }
1741         }
1742
1743         if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1744             rustflags.arg("-Zsave-analysis");
1745             cargo.env(
1746                 "RUST_SAVE_ANALYSIS_CONFIG",
1747                 "{\"output_file\": null,\"full_docs\": false,\
1748                        \"pub_only\": true,\"reachable_only\": false,\
1749                        \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1750             );
1751         }
1752
1753         // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1754         // when compiling the standard library, since this might be linked into the final outputs
1755         // produced by rustc. Since this mitigation is only available on Windows, only enable it
1756         // for the standard library in case the compiler is run on a non-Windows platform.
1757         // This is not needed for stage 0 artifacts because these will only be used for building
1758         // the stage 1 compiler.
1759         if cfg!(windows)
1760             && mode == Mode::Std
1761             && self.config.control_flow_guard
1762             && compiler.stage >= 1
1763         {
1764             rustflags.arg("-Ccontrol-flow-guard");
1765         }
1766
1767         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1768         // This replaces spaces with newlines because RUSTDOCFLAGS does not
1769         // support arguments with regular spaces. Hopefully someday Cargo will
1770         // have space support.
1771         let rust_version = self.rust_version().replace(' ', "\n");
1772         rustdocflags.arg("--crate-version").arg(&rust_version);
1773
1774         // Environment variables *required* throughout the build
1775         //
1776         // FIXME: should update code to not require this env var
1777         cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1778
1779         // Set this for all builds to make sure doc builds also get it.
1780         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1781
1782         // This one's a bit tricky. As of the time of this writing the compiler
1783         // links to the `winapi` crate on crates.io. This crate provides raw
1784         // bindings to Windows system functions, sort of like libc does for
1785         // Unix. This crate also, however, provides "import libraries" for the
1786         // MinGW targets. There's an import library per dll in the windows
1787         // distribution which is what's linked to. These custom import libraries
1788         // are used because the winapi crate can reference Windows functions not
1789         // present in the MinGW import libraries.
1790         //
1791         // For example MinGW may ship libdbghelp.a, but it may not have
1792         // references to all the functions in the dbghelp dll. Instead the
1793         // custom import library for dbghelp in the winapi crates has all this
1794         // information.
1795         //
1796         // Unfortunately for us though the import libraries are linked by
1797         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1798         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1799         // conflict with the system MinGW ones). This consequently means that
1800         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1801         // DLL) when linked against *again*, for example with procedural macros
1802         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1803         // `-lwinapi_foo` to the linker again. This isn't actually available in
1804         // our distribution, however, so the link fails.
1805         //
1806         // To solve this problem we tell winapi to not use its bundled import
1807         // libraries. This means that it will link to the system MinGW import
1808         // libraries by default, and the `-ldylib=foo` directives will still get
1809         // passed to the final linker, but they'll look like `-lfoo` which can
1810         // be resolved because MinGW has the import library. The downside is we
1811         // don't get newer functions from Windows, but we don't use any of them
1812         // anyway.
1813         if !mode.is_tool() {
1814             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1815         }
1816
1817         for _ in 0..self.verbosity {
1818             cargo.arg("-v");
1819         }
1820
1821         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1822             (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1823                 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1824             }
1825             _ => {
1826                 // Don't set anything
1827             }
1828         }
1829
1830         if self.config.rust_optimize {
1831             // FIXME: cargo bench/install do not accept `--release`
1832             if cmd != "bench" && cmd != "install" {
1833                 cargo.arg("--release");
1834             }
1835         }
1836
1837         if self.config.locked_deps {
1838             cargo.arg("--locked");
1839         }
1840         if self.config.vendor || self.is_sudo {
1841             cargo.arg("--frozen");
1842         }
1843
1844         // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1845         cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1846
1847         self.ci_env.force_coloring_in_ci(&mut cargo);
1848
1849         // When we build Rust dylibs they're all intended for intermediate
1850         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1851         // linking all deps statically into the dylib.
1852         if matches!(mode, Mode::Std | Mode::Rustc) {
1853             rustflags.arg("-Cprefer-dynamic");
1854         }
1855
1856         // When building incrementally we default to a lower ThinLTO import limit
1857         // (unless explicitly specified otherwise). This will produce a somewhat
1858         // slower code but give way better compile times.
1859         {
1860             let limit = match self.config.rust_thin_lto_import_instr_limit {
1861                 Some(limit) => Some(limit),
1862                 None if self.config.incremental => Some(10),
1863                 _ => None,
1864             };
1865
1866             if let Some(limit) = limit {
1867                 if stage == 0 || self.config.default_codegen_backend().unwrap_or_default() == "llvm"
1868                 {
1869                     rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1870                 }
1871             }
1872         }
1873
1874         Cargo { command: cargo, rustflags, rustdocflags }
1875     }
1876
1877     /// Ensure that a given step is built, returning its output. This will
1878     /// cache the step, so it is safe (and good!) to call this as often as
1879     /// needed to ensure that all dependencies are built.
1880     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1881         {
1882             let mut stack = self.stack.borrow_mut();
1883             for stack_step in stack.iter() {
1884                 // should skip
1885                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1886                     continue;
1887                 }
1888                 let mut out = String::new();
1889                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1890                 for el in stack.iter().rev() {
1891                     out += &format!("\t{:?}\n", el);
1892                 }
1893                 panic!("{}", out);
1894             }
1895             if let Some(out) = self.cache.get(&step) {
1896                 self.verbose_than(1, &format!("{}c {:?}", "  ".repeat(stack.len()), step));
1897
1898                 return out;
1899             }
1900             self.verbose_than(1, &format!("{}> {:?}", "  ".repeat(stack.len()), step));
1901             stack.push(Box::new(step.clone()));
1902         }
1903
1904         #[cfg(feature = "build-metrics")]
1905         self.metrics.enter_step(&step);
1906
1907         let (out, dur) = {
1908             let start = Instant::now();
1909             let zero = Duration::new(0, 0);
1910             let parent = self.time_spent_on_dependencies.replace(zero);
1911             let out = step.clone().run(self);
1912             let dur = start.elapsed();
1913             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1914             (out, dur - deps)
1915         };
1916
1917         if self.config.print_step_timings && !self.config.dry_run() {
1918             let step_string = format!("{:?}", step);
1919             let brace_index = step_string.find("{").unwrap_or(0);
1920             let type_string = type_name::<S>();
1921             println!(
1922                 "[TIMING] {} {} -- {}.{:03}",
1923                 &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1924                 &step_string[brace_index..],
1925                 dur.as_secs(),
1926                 dur.subsec_millis()
1927             );
1928         }
1929
1930         #[cfg(feature = "build-metrics")]
1931         self.metrics.exit_step();
1932
1933         {
1934             let mut stack = self.stack.borrow_mut();
1935             let cur_step = stack.pop().expect("step stack empty");
1936             assert_eq!(cur_step.downcast_ref(), Some(&step));
1937         }
1938         self.verbose_than(1, &format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
1939         self.cache.put(step, out.clone());
1940         out
1941     }
1942
1943     /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1944     /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1945     /// needed to ensure that all dependencies are build.
1946     pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1947         &'a self,
1948         step: S,
1949         kind: Kind,
1950     ) -> S::Output {
1951         let desc = StepDescription::from::<S>(kind);
1952         let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1953
1954         // Avoid running steps contained in --exclude
1955         for pathset in &should_run.paths {
1956             if desc.is_excluded(self, pathset) {
1957                 return None;
1958             }
1959         }
1960
1961         // Only execute if it's supposed to run as default
1962         if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1963     }
1964
1965     /// Checks if any of the "should_run" paths is in the `Builder` paths.
1966     pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1967         let desc = StepDescription::from::<S>(kind);
1968         let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1969
1970         for path in &self.paths {
1971             if should_run.paths.iter().any(|s| s.has(path, Some(desc.kind)))
1972                 && !desc.is_excluded(
1973                     self,
1974                     &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1975                 )
1976             {
1977                 return true;
1978             }
1979         }
1980
1981         false
1982     }
1983
1984     pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1985         if self.was_invoked_explicitly::<S>(Kind::Doc) {
1986             self.open_in_browser(path);
1987         }
1988     }
1989
1990     pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1991         if self.config.dry_run() || !self.config.cmd.open() {
1992             return;
1993         }
1994
1995         let path = path.as_ref();
1996         self.info(&format!("Opening doc {}", path.display()));
1997         if let Err(err) = opener::open(path) {
1998             self.info(&format!("{}\n", err));
1999         }
2000     }
2001 }
2002
2003 #[cfg(test)]
2004 mod tests;
2005
2006 #[derive(Debug, Clone)]
2007 struct Rustflags(String, TargetSelection);
2008
2009 impl Rustflags {
2010     fn new(target: TargetSelection) -> Rustflags {
2011         let mut ret = Rustflags(String::new(), target);
2012         ret.propagate_cargo_env("RUSTFLAGS");
2013         ret
2014     }
2015
2016     /// By default, cargo will pick up on various variables in the environment. However, bootstrap
2017     /// reuses those variables to pass additional flags to rustdoc, so by default they get overridden.
2018     /// Explicitly add back any previous value in the environment.
2019     ///
2020     /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
2021     fn propagate_cargo_env(&mut self, prefix: &str) {
2022         // Inherit `RUSTFLAGS` by default ...
2023         self.env(prefix);
2024
2025         // ... and also handle target-specific env RUSTFLAGS if they're configured.
2026         let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
2027         self.env(&target_specific);
2028     }
2029
2030     fn env(&mut self, env: &str) {
2031         if let Ok(s) = env::var(env) {
2032             for part in s.split(' ') {
2033                 self.arg(part);
2034             }
2035         }
2036     }
2037
2038     fn arg(&mut self, arg: &str) -> &mut Self {
2039         assert_eq!(arg.split(' ').count(), 1);
2040         if !self.0.is_empty() {
2041             self.0.push(' ');
2042         }
2043         self.0.push_str(arg);
2044         self
2045     }
2046 }
2047
2048 #[derive(Debug)]
2049 pub struct Cargo {
2050     command: Command,
2051     rustflags: Rustflags,
2052     rustdocflags: Rustflags,
2053 }
2054
2055 impl Cargo {
2056     pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
2057         self.rustdocflags.arg(arg);
2058         self
2059     }
2060     pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
2061         self.rustflags.arg(arg);
2062         self
2063     }
2064
2065     pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
2066         self.command.arg(arg.as_ref());
2067         self
2068     }
2069
2070     pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
2071     where
2072         I: IntoIterator<Item = S>,
2073         S: AsRef<OsStr>,
2074     {
2075         for arg in args {
2076             self.arg(arg.as_ref());
2077         }
2078         self
2079     }
2080
2081     pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
2082         // These are managed through rustflag/rustdocflag interfaces.
2083         assert_ne!(key.as_ref(), "RUSTFLAGS");
2084         assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
2085         self.command.env(key.as_ref(), value.as_ref());
2086         self
2087     }
2088
2089     pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
2090         builder.add_rustc_lib_path(compiler, &mut self.command);
2091     }
2092
2093     pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
2094         self.command.current_dir(dir);
2095         self
2096     }
2097 }
2098
2099 impl From<Cargo> for Command {
2100     fn from(mut cargo: Cargo) -> Command {
2101         let rustflags = &cargo.rustflags.0;
2102         if !rustflags.is_empty() {
2103             cargo.command.env("RUSTFLAGS", rustflags);
2104         }
2105
2106         let rustdocflags = &cargo.rustdocflags.0;
2107         if !rustdocflags.is_empty() {
2108             cargo.command.env("RUSTDOCFLAGS", rustdocflags);
2109         }
2110
2111         cargo.command
2112     }
2113 }