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