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