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