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