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