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