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