]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Fix ABI, run and fix more tests, re-enable CI for PRs
[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             rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
821         } else {
822             rustflags.env("RUSTFLAGS_BOOTSTRAP");
823             rustflags.arg("--cfg=bootstrap");
824         }
825
826         match mode {
827             Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {},
828             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
829                 // Build proc macros both for the host and the target
830                 if target != compiler.host && cmd != "check" {
831                     cargo.arg("-Zdual-proc-macros");
832                     rustflags.arg("-Zdual-proc-macros");
833                 }
834             },
835         }
836
837         // This tells Cargo (and in turn, rustc) to output more complete
838         // dependency information.  Most importantly for rustbuild, this
839         // includes sysroot artifacts, like libstd, which means that we don't
840         // need to track those in rustbuild (an error prone process!). This
841         // feature is currently unstable as there may be some bugs and such, but
842         // it represents a big improvement in rustbuild's reliability on
843         // rebuilds, so we're using it here.
844         //
845         // For some additional context, see #63470 (the PR originally adding
846         // this), as well as #63012 which is the tracking issue for this
847         // feature on the rustc side.
848         cargo.arg("-Zbinary-dep-depinfo");
849
850         cargo.arg("-j").arg(self.jobs().to_string());
851         // Remove make-related flags to ensure Cargo can correctly set things up
852         cargo.env_remove("MAKEFLAGS");
853         cargo.env_remove("MFLAGS");
854
855         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
856         // Force cargo to output binaries with disambiguating hashes in the name
857         let mut metadata = if compiler.stage == 0 {
858             // Treat stage0 like a special channel, whether it's a normal prior-
859             // release rustc or a local rebuild with the same version, so we
860             // never mix these libraries by accident.
861             "bootstrap".to_string()
862         } else {
863             self.config.channel.to_string()
864         };
865         // We want to make sure that none of the dependencies between
866         // std/test/rustc unify with one another. This is done for weird linkage
867         // reasons but the gist of the problem is that if librustc, libtest, and
868         // libstd all depend on libc from crates.io (which they actually do) we
869         // want to make sure they all get distinct versions. Things get really
870         // weird if we try to unify all these dependencies right now, namely
871         // around how many times the library is linked in dynamic libraries and
872         // such. If rustc were a static executable or if we didn't ship dylibs
873         // this wouldn't be a problem, but we do, so it is. This is in general
874         // just here to make sure things build right. If you can remove this and
875         // things still build right, please do!
876         match mode {
877             Mode::Std => metadata.push_str("std"),
878             _ => {},
879         }
880         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
881
882         if cmd == "clippy" {
883             rustflags.arg("-Zforce-unstable-if-unmarked");
884         }
885
886         rustflags.arg("-Zexternal-macro-backtrace");
887
888         let want_rustdoc = self.doc_tests != DocTests::No;
889
890         // We synthetically interpret a stage0 compiler used to build tools as a
891         // "raw" compiler in that it's the exact snapshot we download. Normally
892         // the stage0 build means it uses libraries build by the stage0
893         // compiler, but for tools we just use the precompiled libraries that
894         // we've downloaded
895         let use_snapshot = mode == Mode::ToolBootstrap;
896         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
897
898         let maybe_sysroot = self.sysroot(compiler);
899         let sysroot = if use_snapshot {
900             self.rustc_snapshot_sysroot()
901         } else {
902             &maybe_sysroot
903         };
904         let libdir = self.rustc_libdir(compiler);
905
906         // Customize the compiler we're running. Specify the compiler to cargo
907         // as our shim and then pass it some various options used to configure
908         // how the actual compiler itself is called.
909         //
910         // These variables are primarily all read by
911         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
912         cargo
913             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
914             .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
915             .env("RUSTC_REAL", self.rustc(compiler))
916             .env("RUSTC_STAGE", stage.to_string())
917             .env(
918                 "RUSTC_DEBUG_ASSERTIONS",
919                 self.config.rust_debug_assertions.to_string(),
920             )
921             .env("RUSTC_SYSROOT", &sysroot)
922             .env("RUSTC_LIBDIR", &libdir)
923             .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
924             .env(
925                 "RUSTDOC_REAL",
926                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
927                     self.rustdoc(compiler)
928                 } else {
929                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
930                 },
931             )
932             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
933             .env("RUSTC_BREAK_ON_ICE", "1");
934
935         // Dealing with rpath here is a little special, so let's go into some
936         // detail. First off, `-rpath` is a linker option on Unix platforms
937         // which adds to the runtime dynamic loader path when looking for
938         // dynamic libraries. We use this by default on Unix platforms to ensure
939         // that our nightlies behave the same on Windows, that is they work out
940         // of the box. This can be disabled, of course, but basically that's why
941         // we're gated on RUSTC_RPATH here.
942         //
943         // Ok, so the astute might be wondering "why isn't `-C rpath` used
944         // here?" and that is indeed a good question to task. This codegen
945         // option is the compiler's current interface to generating an rpath.
946         // Unfortunately it doesn't quite suffice for us. The flag currently
947         // takes no value as an argument, so the compiler calculates what it
948         // should pass to the linker as `-rpath`. This unfortunately is based on
949         // the **compile time** directory structure which when building with
950         // Cargo will be very different than the runtime directory structure.
951         //
952         // All that's a really long winded way of saying that if we use
953         // `-Crpath` then the executables generated have the wrong rpath of
954         // something like `$ORIGIN/deps` when in fact the way we distribute
955         // rustc requires the rpath to be `$ORIGIN/../lib`.
956         //
957         // So, all in all, to set up the correct rpath we pass the linker
958         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
959         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
960         // to change a flag in a binary?
961         if self.config.rust_rpath {
962             let rpath = if target.contains("apple") {
963
964                 // Note that we need to take one extra step on macOS to also pass
965                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
966                 // do that we pass a weird flag to the compiler to get it to do
967                 // so. Note that this is definitely a hack, and we should likely
968                 // flesh out rpath support more fully in the future.
969                 rustflags.arg("-Zosx-rpath-install-name");
970                 Some("-Wl,-rpath,@loader_path/../lib")
971             } else if !target.contains("windows") &&
972                       !target.contains("wasm32") &&
973                       !target.contains("emscripten") &&
974                       !target.contains("fuchsia") {
975                 Some("-Wl,-rpath,$ORIGIN/../lib")
976             } else {
977                 None
978             };
979             if let Some(rpath) = rpath {
980                 rustflags.arg(&format!("-Clink-args={}", rpath));
981             }
982         }
983
984         if let Some(host_linker) = self.linker(compiler.host) {
985             cargo.env("RUSTC_HOST_LINKER", host_linker);
986         }
987         if let Some(target_linker) = self.linker(target) {
988             let target = crate::envify(&target);
989             cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
990         }
991         if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
992             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
993         }
994
995         let debuginfo_level = match mode {
996             Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
997             Mode::Std => self.config.rust_debuginfo_level_std,
998             Mode::ToolBootstrap | Mode::ToolStd |
999             Mode::ToolRustc => self.config.rust_debuginfo_level_tools,
1000         };
1001         cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1002
1003         if !mode.is_tool() {
1004             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1005         }
1006
1007         if let Some(x) = self.crt_static(target) {
1008             if x {
1009                 rustflags.arg("-Ctarget-feature=+crt-static");
1010             } else {
1011                 rustflags.arg("-Ctarget-feature=-crt-static");
1012             }
1013         }
1014
1015         if let Some(x) = self.crt_static(compiler.host) {
1016             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1017         }
1018
1019         if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
1020             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1021         }
1022
1023         // Enable usage of unstable features
1024         cargo.env("RUSTC_BOOTSTRAP", "1");
1025         self.add_rust_test_threads(&mut cargo);
1026
1027         // Almost all of the crates that we compile as part of the bootstrap may
1028         // have a build script, including the standard library. To compile a
1029         // build script, however, it itself needs a standard library! This
1030         // introduces a bit of a pickle when we're compiling the standard
1031         // library itself.
1032         //
1033         // To work around this we actually end up using the snapshot compiler
1034         // (stage0) for compiling build scripts of the standard library itself.
1035         // The stage0 compiler is guaranteed to have a libstd available for use.
1036         //
1037         // For other crates, however, we know that we've already got a standard
1038         // library up and running, so we can use the normal compiler to compile
1039         // build scripts in that situation.
1040         if mode == Mode::Std {
1041             cargo
1042                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1043                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1044         } else {
1045             cargo
1046                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1047                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1048         }
1049
1050         if self.config.incremental {
1051             cargo.env("CARGO_INCREMENTAL", "1");
1052         } else {
1053             // Don't rely on any default setting for incr. comp. in Cargo
1054             cargo.env("CARGO_INCREMENTAL", "0");
1055         }
1056
1057         if let Some(ref on_fail) = self.config.on_fail {
1058             cargo.env("RUSTC_ON_FAIL", on_fail);
1059         }
1060
1061         if self.config.print_step_timings {
1062             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1063         }
1064
1065         if self.config.backtrace_on_ice {
1066             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1067         }
1068
1069         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1070
1071         if !mode.is_tool() {
1072             // When extending this list, add the new lints to the RUSTFLAGS of the
1073             // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1074             // some code doesn't go through this `rustc` wrapper.
1075             rustflags.arg("-Wrust_2018_idioms");
1076             rustflags.arg("-Wunused_lifetimes");
1077
1078             if self.config.deny_warnings {
1079                 rustflags.arg("-Dwarnings");
1080             }
1081         }
1082
1083         if let Mode::Rustc | Mode::Codegen = mode {
1084             rustflags.arg("-Zunstable-options");
1085             rustflags.arg("-Wrustc::internal");
1086         }
1087
1088         // Throughout the build Cargo can execute a number of build scripts
1089         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1090         // obtained previously to those build scripts.
1091         // Build scripts use either the `cc` crate or `configure/make` so we pass
1092         // the options through environment variables that are fetched and understood by both.
1093         //
1094         // FIXME: the guard against msvc shouldn't need to be here
1095         if target.contains("msvc") {
1096             if let Some(ref cl) = self.config.llvm_clang_cl {
1097                 cargo.env("CC", cl).env("CXX", cl);
1098             }
1099         } else {
1100             let ccache = self.config.ccache.as_ref();
1101             let ccacheify = |s: &Path| {
1102                 let ccache = match ccache {
1103                     Some(ref s) => s,
1104                     None => return s.display().to_string(),
1105                 };
1106                 // FIXME: the cc-rs crate only recognizes the literal strings
1107                 // `ccache` and `sccache` when doing caching compilations, so we
1108                 // mirror that here. It should probably be fixed upstream to
1109                 // accept a new env var or otherwise work with custom ccache
1110                 // vars.
1111                 match &ccache[..] {
1112                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1113                     _ => s.display().to_string(),
1114                 }
1115             };
1116             let cc = ccacheify(&self.cc(target));
1117             cargo.env(format!("CC_{}", target), &cc);
1118
1119             let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1120             cargo
1121                 .env(format!("CFLAGS_{}", target), cflags.clone());
1122
1123             if let Some(ar) = self.ar(target) {
1124                 let ranlib = format!("{} s", ar.display());
1125                 cargo
1126                     .env(format!("AR_{}", target), ar)
1127                     .env(format!("RANLIB_{}", target), ranlib);
1128             }
1129
1130             if let Ok(cxx) = self.cxx(target) {
1131                 let cxx = ccacheify(&cxx);
1132                 cargo
1133                     .env(format!("CXX_{}", target), &cxx)
1134                     .env(format!("CXXFLAGS_{}", target), cflags);
1135             }
1136         }
1137
1138         if mode == Mode::Std
1139             && self.config.extended
1140             && compiler.is_final_stage(self)
1141         {
1142             rustflags.arg("-Zsave-analysis");
1143             cargo.env("RUST_SAVE_ANALYSIS_CONFIG",
1144                       "{\"output_file\": null,\"full_docs\": false,\
1145                        \"pub_only\": true,\"reachable_only\": false,\
1146                        \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
1147         }
1148
1149         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1150         cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1151
1152         // Environment variables *required* throughout the build
1153         //
1154         // FIXME: should update code to not require this env var
1155         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1156
1157         // Set this for all builds to make sure doc builds also get it.
1158         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1159
1160         // This one's a bit tricky. As of the time of this writing the compiler
1161         // links to the `winapi` crate on crates.io. This crate provides raw
1162         // bindings to Windows system functions, sort of like libc does for
1163         // Unix. This crate also, however, provides "import libraries" for the
1164         // MinGW targets. There's an import library per dll in the windows
1165         // distribution which is what's linked to. These custom import libraries
1166         // are used because the winapi crate can reference Windows functions not
1167         // present in the MinGW import libraries.
1168         //
1169         // For example MinGW may ship libdbghelp.a, but it may not have
1170         // references to all the functions in the dbghelp dll. Instead the
1171         // custom import library for dbghelp in the winapi crates has all this
1172         // information.
1173         //
1174         // Unfortunately for us though the import libraries are linked by
1175         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1176         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1177         // conflict with the system MinGW ones). This consequently means that
1178         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1179         // DLL) when linked against *again*, for example with procedural macros
1180         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1181         // `-lwinapi_foo` to the linker again. This isn't actually available in
1182         // our distribution, however, so the link fails.
1183         //
1184         // To solve this problem we tell winapi to not use its bundled import
1185         // libraries. This means that it will link to the system MinGW import
1186         // libraries by default, and the `-ldylib=foo` directives will still get
1187         // passed to the final linker, but they'll look like `-lfoo` which can
1188         // be resolved because MinGW has the import library. The downside is we
1189         // don't get newer functions from Windows, but we don't use any of them
1190         // anyway.
1191         if !mode.is_tool() {
1192             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1193         }
1194
1195         for _ in 1..self.verbosity {
1196             cargo.arg("-v");
1197         }
1198
1199         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1200             (Mode::Std, Some(n), _) |
1201             (_, _, Some(n)) => {
1202                 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1203             }
1204             _ => {
1205                 // Don't set anything
1206             }
1207         }
1208
1209         if self.config.rust_optimize {
1210             // FIXME: cargo bench/install do not accept `--release`
1211             if cmd != "bench" && cmd != "install" {
1212                 cargo.arg("--release");
1213             }
1214         }
1215
1216         if self.config.locked_deps {
1217             cargo.arg("--locked");
1218         }
1219         if self.config.vendor || self.is_sudo {
1220             cargo.arg("--frozen");
1221         }
1222
1223         cargo.env("RUSTC_INSTALL_BINDIR", &self.config.bindir);
1224
1225         self.ci_env.force_coloring_in_ci(&mut cargo);
1226
1227         // When we build Rust dylibs they're all intended for intermediate
1228         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1229         // linking all deps statically into the dylib.
1230         if let Mode::Std | Mode::Rustc | Mode::Codegen = mode {
1231             rustflags.arg("-Cprefer-dynamic");
1232         }
1233
1234         Cargo {
1235             command: cargo,
1236             rustflags,
1237         }
1238     }
1239
1240     /// Ensure that a given step is built, returning its output. This will
1241     /// cache the step, so it is safe (and good!) to call this as often as
1242     /// needed to ensure that all dependencies are built.
1243     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1244         {
1245             let mut stack = self.stack.borrow_mut();
1246             for stack_step in stack.iter() {
1247                 // should skip
1248                 if stack_step
1249                     .downcast_ref::<S>()
1250                     .map_or(true, |stack_step| *stack_step != step)
1251                 {
1252                     continue;
1253                 }
1254                 let mut out = String::new();
1255                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1256                 for el in stack.iter().rev() {
1257                     out += &format!("\t{:?}\n", el);
1258                 }
1259                 panic!(out);
1260             }
1261             if let Some(out) = self.cache.get(&step) {
1262                 self.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
1263
1264                 {
1265                     let mut graph = self.graph.borrow_mut();
1266                     let parent = self.parent.get();
1267                     let us = *self
1268                         .graph_nodes
1269                         .borrow_mut()
1270                         .entry(format!("{:?}", step))
1271                         .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1272                     if let Some(parent) = parent {
1273                         graph.add_edge(parent, us, false);
1274                     }
1275                 }
1276
1277                 return out;
1278             }
1279             self.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
1280             stack.push(Box::new(step.clone()));
1281         }
1282
1283         let prev_parent = self.parent.get();
1284
1285         {
1286             let mut graph = self.graph.borrow_mut();
1287             let parent = self.parent.get();
1288             let us = *self
1289                 .graph_nodes
1290                 .borrow_mut()
1291                 .entry(format!("{:?}", step))
1292                 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1293             self.parent.set(Some(us));
1294             if let Some(parent) = parent {
1295                 graph.add_edge(parent, us, true);
1296             }
1297         }
1298
1299         let (out, dur) = {
1300             let start = Instant::now();
1301             let zero = Duration::new(0, 0);
1302             let parent = self.time_spent_on_dependencies.replace(zero);
1303             let out = step.clone().run(self);
1304             let dur = start.elapsed();
1305             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1306             (out, dur - deps)
1307         };
1308
1309         self.parent.set(prev_parent);
1310
1311         if self.config.print_step_timings && dur > Duration::from_millis(100) {
1312             println!(
1313                 "[TIMING] {:?} -- {}.{:03}",
1314                 step,
1315                 dur.as_secs(),
1316                 dur.subsec_nanos() / 1_000_000
1317             );
1318         }
1319
1320         {
1321             let mut stack = self.stack.borrow_mut();
1322             let cur_step = stack.pop().expect("step stack empty");
1323             assert_eq!(cur_step.downcast_ref(), Some(&step));
1324         }
1325         self.verbose(&format!(
1326             "{}< {:?}",
1327             "  ".repeat(self.stack.borrow().len()),
1328             step
1329         ));
1330         self.cache.put(step, out.clone());
1331         out
1332     }
1333 }
1334
1335 #[cfg(test)]
1336 mod tests;
1337
1338 #[derive(Debug)]
1339 struct Rustflags(String);
1340
1341 impl Rustflags {
1342     fn new(target: &str) -> Rustflags {
1343         let mut ret = Rustflags(String::new());
1344
1345         // Inherit `RUSTFLAGS` by default ...
1346         ret.env("RUSTFLAGS");
1347
1348         // ... and also handle target-specific env RUSTFLAGS if they're
1349         // configured.
1350         let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(target));
1351         ret.env(&target_specific);
1352
1353         ret
1354     }
1355
1356     fn env(&mut self, env: &str) {
1357         if let Ok(s) = env::var(env) {
1358             for part in s.split_whitespace() {
1359                 self.arg(part);
1360             }
1361         }
1362     }
1363
1364     fn arg(&mut self, arg: &str) -> &mut Self {
1365         assert_eq!(arg.split_whitespace().count(), 1);
1366         if self.0.len() > 0 {
1367             self.0.push_str(" ");
1368         }
1369         self.0.push_str(arg);
1370         self
1371     }
1372 }
1373
1374 #[derive(Debug)]
1375 pub struct Cargo {
1376     command: Command,
1377     rustflags: Rustflags,
1378 }
1379
1380 impl Cargo {
1381     pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1382         self.rustflags.arg(arg);
1383         self
1384     }
1385
1386     pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1387         self.command.arg(arg.as_ref());
1388         self
1389     }
1390
1391     pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1392         where I: IntoIterator<Item=S>, S: AsRef<OsStr>
1393     {
1394         for arg in args {
1395             self.arg(arg.as_ref());
1396         }
1397         self
1398     }
1399
1400     pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1401         self.command.env(key.as_ref(), value.as_ref());
1402         self
1403     }
1404 }
1405
1406 impl From<Cargo> for Command {
1407     fn from(mut cargo: Cargo) -> Command {
1408         cargo.command.env("RUSTFLAGS", &cargo.rustflags.0);
1409         cargo.command
1410     }
1411 }