]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Auto merge of #64823 - cuviper:min-std, r=Mark-Simulacrum
[rust.git] / src / bootstrap / builder.rs
1 use std::any::Any;
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::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::RustcDev,
447                 dist::Analysis,
448                 dist::Src,
449                 dist::PlainSourceTarball,
450                 dist::Cargo,
451                 dist::Rls,
452                 dist::Rustfmt,
453                 dist::Clippy,
454                 dist::Miri,
455                 dist::LlvmTools,
456                 dist::Lldb,
457                 dist::Extended,
458                 dist::HashSign
459             ),
460             Kind::Install => describe!(
461                 install::Docs,
462                 install::Std,
463                 install::Cargo,
464                 install::Rls,
465                 install::Rustfmt,
466                 install::Clippy,
467                 install::Miri,
468                 install::Analysis,
469                 install::Src,
470                 install::Rustc
471             ),
472         }
473     }
474
475     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
476         let kind = match subcommand {
477             "build" => Kind::Build,
478             "doc" => Kind::Doc,
479             "test" => Kind::Test,
480             "bench" => Kind::Bench,
481             "dist" => Kind::Dist,
482             "install" => Kind::Install,
483             _ => return None,
484         };
485
486         let builder = Builder {
487             build,
488             top_stage: build.config.stage.unwrap_or(2),
489             kind,
490             cache: Cache::new(),
491             stack: RefCell::new(Vec::new()),
492             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
493             paths: vec![],
494             graph_nodes: RefCell::new(HashMap::new()),
495             graph: RefCell::new(Graph::new()),
496             parent: Cell::new(None),
497         };
498
499         let builder = &builder;
500         let mut should_run = ShouldRun::new(builder);
501         for desc in Builder::get_step_descriptions(builder.kind) {
502             should_run = (desc.should_run)(should_run);
503         }
504         let mut help = String::from("Available paths:\n");
505         for pathset in should_run.paths {
506             if let PathSet::Set(set) = pathset {
507                 set.iter().for_each(|path| {
508                     help.push_str(
509                         format!("    ./x.py {} {}\n", subcommand, path.display()).as_str(),
510                     )
511                 })
512             }
513         }
514         Some(help)
515     }
516
517     pub fn new(build: &Build) -> Builder<'_> {
518         let (kind, paths) = match build.config.cmd {
519             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
520             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
521             Subcommand::Clippy { ref paths } => (Kind::Clippy, &paths[..]),
522             Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
523             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
524             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
525             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
526             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
527             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
528             Subcommand::Clean { .. } => panic!(),
529         };
530
531         let builder = Builder {
532             build,
533             top_stage: build.config.stage.unwrap_or(2),
534             kind,
535             cache: Cache::new(),
536             stack: RefCell::new(Vec::new()),
537             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
538             paths: paths.to_owned(),
539             graph_nodes: RefCell::new(HashMap::new()),
540             graph: RefCell::new(Graph::new()),
541             parent: Cell::new(None),
542         };
543
544         builder
545     }
546
547     pub fn execute_cli(&self) -> Graph<String, bool> {
548         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
549         self.graph.borrow().clone()
550     }
551
552     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
553         let paths = paths.unwrap_or(&[]);
554         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
555     }
556
557     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
558         StepDescription::run(v, self, paths);
559     }
560
561     /// Obtain a compiler at a given stage and for a given host. Explicitly does
562     /// not take `Compiler` since all `Compiler` instances are meant to be
563     /// obtained through this function, since it ensures that they are valid
564     /// (i.e., built and assembled).
565     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
566         self.ensure(compile::Assemble {
567             target_compiler: Compiler { stage, host },
568         })
569     }
570
571     /// Similar to `compiler`, except handles the full-bootstrap option to
572     /// silently use the stage1 compiler instead of a stage2 compiler if one is
573     /// requested.
574     ///
575     /// Note that this does *not* have the side effect of creating
576     /// `compiler(stage, host)`, unlike `compiler` above which does have such
577     /// a side effect. The returned compiler here can only be used to compile
578     /// new artifacts, it can't be used to rely on the presence of a particular
579     /// sysroot.
580     ///
581     /// See `force_use_stage1` for documentation on what each argument is.
582     pub fn compiler_for(
583         &self,
584         stage: u32,
585         host: Interned<String>,
586         target: Interned<String>,
587     ) -> Compiler {
588         if self.build.force_use_stage1(Compiler { stage, host }, target) {
589             self.compiler(1, self.config.build)
590         } else {
591             self.compiler(stage, host)
592         }
593     }
594
595     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
596         self.ensure(compile::Sysroot { compiler })
597     }
598
599     /// Returns the libdir where the standard library and other artifacts are
600     /// found for a compiler's sysroot.
601     pub fn sysroot_libdir(
602         &self,
603         compiler: Compiler,
604         target: Interned<String>,
605     ) -> Interned<PathBuf> {
606         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
607         struct Libdir {
608             compiler: Compiler,
609             target: Interned<String>,
610         }
611         impl Step for Libdir {
612             type Output = Interned<PathBuf>;
613
614             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
615                 run.never()
616             }
617
618             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
619                 let lib = builder.sysroot_libdir_relative(self.compiler);
620                 let sysroot = builder
621                     .sysroot(self.compiler)
622                     .join(lib)
623                     .join("rustlib")
624                     .join(self.target)
625                     .join("lib");
626                 let _ = fs::remove_dir_all(&sysroot);
627                 t!(fs::create_dir_all(&sysroot));
628                 INTERNER.intern_path(sysroot)
629             }
630         }
631         self.ensure(Libdir { compiler, target })
632     }
633
634     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
635         self.sysroot_libdir(compiler, compiler.host)
636             .with_file_name(self.config.rust_codegen_backends_dir.clone())
637     }
638
639     /// Returns the compiler's libdir where it stores the dynamic libraries that
640     /// it itself links against.
641     ///
642     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
643     /// Windows.
644     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
645         if compiler.is_snapshot(self) {
646             self.rustc_snapshot_libdir()
647         } else {
648             match self.config.libdir_relative() {
649                 Some(relative_libdir) if compiler.stage >= 1
650                     => self.sysroot(compiler).join(relative_libdir),
651                 _ => self.sysroot(compiler).join(libdir(&compiler.host))
652             }
653         }
654     }
655
656     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
657     /// it itself links against.
658     ///
659     /// For example this returns `lib` on Unix and `bin` on
660     /// Windows.
661     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
662         if compiler.is_snapshot(self) {
663             libdir(&self.config.build).as_ref()
664         } else {
665             match self.config.libdir_relative() {
666                 Some(relative_libdir) if compiler.stage >= 1
667                     => relative_libdir,
668                 _ => libdir(&compiler.host).as_ref()
669             }
670         }
671     }
672
673     /// Returns the compiler's relative libdir where the standard library and other artifacts are
674     /// found for a compiler's sysroot.
675     ///
676     /// For example this returns `lib` on Unix and Windows.
677     pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
678         match self.config.libdir_relative() {
679             Some(relative_libdir) if compiler.stage >= 1
680                 => relative_libdir,
681             _ => Path::new("lib")
682         }
683     }
684
685     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
686     /// library lookup path.
687     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Cargo) {
688         // Windows doesn't need dylib path munging because the dlls for the
689         // compiler live next to the compiler and the system will find them
690         // automatically.
691         if cfg!(windows) {
692             return;
693         }
694
695         add_lib_path(vec![self.rustc_libdir(compiler)], &mut cmd.command);
696     }
697
698     /// Gets a path to the compiler specified.
699     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
700         if compiler.is_snapshot(self) {
701             self.initial_rustc.clone()
702         } else {
703             self.sysroot(compiler)
704                 .join("bin")
705                 .join(exe("rustc", &compiler.host))
706         }
707     }
708
709     /// Gets the paths to all of the compiler's codegen backends.
710     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
711         fs::read_dir(self.sysroot_codegen_backends(compiler))
712             .into_iter()
713             .flatten()
714             .filter_map(Result::ok)
715             .map(|entry| entry.path())
716     }
717
718     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
719         self.ensure(tool::Rustdoc { compiler })
720     }
721
722     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
723         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
724         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
725             .env("RUSTC_SYSROOT", self.sysroot(compiler))
726             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
727             // equivalently to rustc.
728             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
729             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
730             .env("RUSTDOC_REAL", self.rustdoc(compiler))
731             .env("RUSTDOC_CRATE_VERSION", self.rust_version())
732             .env("RUSTC_BOOTSTRAP", "1");
733
734         // Remove make-related flags that can cause jobserver problems.
735         cmd.env_remove("MAKEFLAGS");
736         cmd.env_remove("MFLAGS");
737
738         if let Some(linker) = self.linker(compiler.host) {
739             cmd.env("RUSTC_TARGET_LINKER", linker);
740         }
741         cmd
742     }
743
744     /// Prepares an invocation of `cargo` to be run.
745     ///
746     /// This will create a `Command` that represents a pending execution of
747     /// Cargo. This cargo will be configured to use `compiler` as the actual
748     /// rustc compiler, its output will be scoped by `mode`'s output directory,
749     /// it will pass the `--target` flag for the specified `target`, and will be
750     /// executing the Cargo command `cmd`.
751     pub fn cargo(
752         &self,
753         compiler: Compiler,
754         mode: Mode,
755         target: Interned<String>,
756         cmd: &str,
757     ) -> Cargo {
758         let mut cargo = Command::new(&self.initial_cargo);
759         let out_dir = self.stage_out(compiler, mode);
760
761         // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
762         // so we need to explicitly clear out if they've been updated.
763         for backend in self.codegen_backends(compiler) {
764             self.clear_if_dirty(&out_dir, &backend);
765         }
766
767         if cmd == "doc" || cmd == "rustdoc" {
768             let my_out = match mode {
769                 // This is the intended out directory for compiler documentation.
770                 Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
771                 _ => self.crate_doc_out(target),
772             };
773             let rustdoc = self.rustdoc(compiler);
774             self.clear_if_dirty(&my_out, &rustdoc);
775         }
776
777         cargo
778             .env("CARGO_TARGET_DIR", out_dir)
779             .arg(cmd)
780             .arg("-Zconfig-profile");
781
782         let profile_var = |name: &str| {
783             let profile = if self.config.rust_optimize {
784                 "RELEASE"
785             } else {
786                 "DEV"
787             };
788             format!("CARGO_PROFILE_{}_{}", profile, name)
789         };
790
791         // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
792         // needs to not accidentally link to libLLVM in stage0/lib.
793         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
794         if let Some(e) = env::var_os(util::dylib_path_var()) {
795             cargo.env("REAL_LIBRARY_PATH", e);
796         }
797
798         if cmd != "install" {
799             cargo.arg("--target")
800                  .arg(target);
801         } else {
802             assert_eq!(target, compiler.host);
803         }
804
805         // Set a flag for `check`/`clippy`/`fix`, so that certain build
806         // scripts can do less work (e.g. not building/requiring LLVM).
807         if cmd == "check" || cmd == "clippy" || cmd == "fix" {
808             cargo.env("RUST_CHECK", "1");
809         }
810
811         let stage;
812         if compiler.stage == 0 && self.local_rebuild {
813             // Assume the local-rebuild rustc already has stage1 features.
814             stage = 1;
815         } else {
816             stage = compiler.stage;
817         }
818
819         let mut rustflags = Rustflags::new(&target);
820         if stage != 0 {
821             if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
822                 cargo.args(s.split_whitespace());
823             }
824             rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
825         } else {
826             if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
827                 cargo.args(s.split_whitespace());
828             }
829             rustflags.env("RUSTFLAGS_BOOTSTRAP");
830             rustflags.arg("--cfg=bootstrap");
831         }
832
833         if let Ok(s) = env::var("CARGOFLAGS") {
834             cargo.args(s.split_whitespace());
835         }
836
837         match mode {
838             Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {},
839             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
840                 // Build proc macros both for the host and the target
841                 if target != compiler.host && cmd != "check" {
842                     cargo.arg("-Zdual-proc-macros");
843                     rustflags.arg("-Zdual-proc-macros");
844                 }
845             },
846         }
847
848         // This tells Cargo (and in turn, rustc) to output more complete
849         // dependency information.  Most importantly for rustbuild, this
850         // includes sysroot artifacts, like libstd, which means that we don't
851         // need to track those in rustbuild (an error prone process!). This
852         // feature is currently unstable as there may be some bugs and such, but
853         // it represents a big improvement in rustbuild's reliability on
854         // rebuilds, so we're using it here.
855         //
856         // For some additional context, see #63470 (the PR originally adding
857         // this), as well as #63012 which is the tracking issue for this
858         // feature on the rustc side.
859         cargo.arg("-Zbinary-dep-depinfo");
860
861         cargo.arg("-j").arg(self.jobs().to_string());
862         // Remove make-related flags to ensure Cargo can correctly set things up
863         cargo.env_remove("MAKEFLAGS");
864         cargo.env_remove("MFLAGS");
865
866         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
867         // Force cargo to output binaries with disambiguating hashes in the name
868         let mut metadata = if compiler.stage == 0 {
869             // Treat stage0 like a special channel, whether it's a normal prior-
870             // release rustc or a local rebuild with the same version, so we
871             // never mix these libraries by accident.
872             "bootstrap".to_string()
873         } else {
874             self.config.channel.to_string()
875         };
876         // We want to make sure that none of the dependencies between
877         // std/test/rustc unify with one another. This is done for weird linkage
878         // reasons but the gist of the problem is that if librustc, libtest, and
879         // libstd all depend on libc from crates.io (which they actually do) we
880         // want to make sure they all get distinct versions. Things get really
881         // weird if we try to unify all these dependencies right now, namely
882         // around how many times the library is linked in dynamic libraries and
883         // such. If rustc were a static executable or if we didn't ship dylibs
884         // this wouldn't be a problem, but we do, so it is. This is in general
885         // just here to make sure things build right. If you can remove this and
886         // things still build right, please do!
887         match mode {
888             Mode::Std => metadata.push_str("std"),
889             _ => {},
890         }
891         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
892
893         if cmd == "clippy" {
894             rustflags.arg("-Zforce-unstable-if-unmarked");
895         }
896
897         rustflags.arg("-Zexternal-macro-backtrace");
898
899         let want_rustdoc = self.doc_tests != DocTests::No;
900
901         // We synthetically interpret a stage0 compiler used to build tools as a
902         // "raw" compiler in that it's the exact snapshot we download. Normally
903         // the stage0 build means it uses libraries build by the stage0
904         // compiler, but for tools we just use the precompiled libraries that
905         // we've downloaded
906         let use_snapshot = mode == Mode::ToolBootstrap;
907         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
908
909         let maybe_sysroot = self.sysroot(compiler);
910         let sysroot = if use_snapshot {
911             self.rustc_snapshot_sysroot()
912         } else {
913             &maybe_sysroot
914         };
915         let libdir = self.rustc_libdir(compiler);
916
917         // Customize the compiler we're running. Specify the compiler to cargo
918         // as our shim and then pass it some various options used to configure
919         // how the actual compiler itself is called.
920         //
921         // These variables are primarily all read by
922         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
923         cargo
924             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
925             .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
926             .env("RUSTC_REAL", self.rustc(compiler))
927             .env("RUSTC_STAGE", stage.to_string())
928             .env(
929                 "RUSTC_DEBUG_ASSERTIONS",
930                 self.config.rust_debug_assertions.to_string(),
931             )
932             .env("RUSTC_SYSROOT", &sysroot)
933             .env("RUSTC_LIBDIR", &libdir)
934             .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
935             .env(
936                 "RUSTDOC_REAL",
937                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
938                     self.rustdoc(compiler)
939                 } else {
940                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
941                 },
942             )
943             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
944             .env("RUSTC_BREAK_ON_ICE", "1");
945
946         // Dealing with rpath here is a little special, so let's go into some
947         // detail. First off, `-rpath` is a linker option on Unix platforms
948         // which adds to the runtime dynamic loader path when looking for
949         // dynamic libraries. We use this by default on Unix platforms to ensure
950         // that our nightlies behave the same on Windows, that is they work out
951         // of the box. This can be disabled, of course, but basically that's why
952         // we're gated on RUSTC_RPATH here.
953         //
954         // Ok, so the astute might be wondering "why isn't `-C rpath` used
955         // here?" and that is indeed a good question to task. This codegen
956         // option is the compiler's current interface to generating an rpath.
957         // Unfortunately it doesn't quite suffice for us. The flag currently
958         // takes no value as an argument, so the compiler calculates what it
959         // should pass to the linker as `-rpath`. This unfortunately is based on
960         // the **compile time** directory structure which when building with
961         // Cargo will be very different than the runtime directory structure.
962         //
963         // All that's a really long winded way of saying that if we use
964         // `-Crpath` then the executables generated have the wrong rpath of
965         // something like `$ORIGIN/deps` when in fact the way we distribute
966         // rustc requires the rpath to be `$ORIGIN/../lib`.
967         //
968         // So, all in all, to set up the correct rpath we pass the linker
969         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
970         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
971         // to change a flag in a binary?
972         if self.config.rust_rpath {
973             let rpath = if target.contains("apple") {
974
975                 // Note that we need to take one extra step on macOS to also pass
976                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
977                 // do that we pass a weird flag to the compiler to get it to do
978                 // so. Note that this is definitely a hack, and we should likely
979                 // flesh out rpath support more fully in the future.
980                 rustflags.arg("-Zosx-rpath-install-name");
981                 Some("-Wl,-rpath,@loader_path/../lib")
982             } else if !target.contains("windows") &&
983                       !target.contains("wasm32") &&
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 }