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