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