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