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