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