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