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