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