]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Also report the call site of PME errors locally.
[rust.git] / src / bootstrap / builder.rs
1 use std::any::{type_name, Any};
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::env;
5 use std::ffi::OsStr;
6 use std::fmt::{Debug, Write};
7 use std::fs;
8 use std::hash::Hash;
9 use std::ops::Deref;
10 use std::path::{Component, Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
13
14 use crate::cache::{Cache, Interned, INTERNER};
15 use crate::compile;
16 use crate::config::{SplitDebuginfo, TargetSelection};
17 use crate::dist;
18 use crate::doc;
19 use crate::flags::{Color, Subcommand};
20 use crate::install;
21 use crate::native;
22 use crate::run;
23 use crate::test;
24 use crate::tool::{self, SourceType};
25 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir, output, t};
26 use crate::EXTRA_CHECK_CFGS;
27 use crate::{check, Config};
28 use crate::{Build, CLang, DocTests, GitRepo, Mode};
29
30 pub use crate::Compiler;
31 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
32 use once_cell::sync::Lazy;
33
34 pub struct Builder<'a> {
35     pub build: &'a Build,
36     pub top_stage: u32,
37     pub kind: Kind,
38     cache: Cache,
39     stack: RefCell<Vec<Box<dyn Any>>>,
40     time_spent_on_dependencies: Cell<Duration>,
41     pub paths: Vec<PathBuf>,
42 }
43
44 impl<'a> Deref for Builder<'a> {
45     type Target = Build;
46
47     fn deref(&self) -> &Self::Target {
48         self.build
49     }
50 }
51
52 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
53     /// `PathBuf` when directories are created or to return a `Compiler` once
54     /// it's been assembled.
55     type Output: Clone;
56
57     /// Whether this step is run by default as part of its respective phase.
58     /// `true` here can still be overwritten by `should_run` calling `default_condition`.
59     const DEFAULT: bool = false;
60
61     /// If true, then this rule should be skipped if --target was specified, but --host was not
62     const ONLY_HOSTS: bool = false;
63
64     /// Primary function to execute this rule. Can call `builder.ensure()`
65     /// with other steps to run those.
66     fn run(self, builder: &Builder<'_>) -> Self::Output;
67
68     /// When bootstrap is passed a set of paths, this controls whether this rule
69     /// will execute. However, it does not get called in a "default" context
70     /// when we are not passed any paths; in that case, `make_run` is called
71     /// directly.
72     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
73
74     /// Builds up a "root" rule, either as a default rule or from a path passed
75     /// to us.
76     ///
77     /// When path is `None`, we are executing in a context where no paths were
78     /// passed. When `./x.py build` is run, for example, this rule could get
79     /// called if it is in the correct list below with a path of `None`.
80     fn make_run(_run: RunConfig<'_>) {
81         // It is reasonable to not have an implementation of make_run for rules
82         // who do not want to get called from the root context. This means that
83         // they are likely dependencies (e.g., sysroot creation) or similar, and
84         // as such calling them from ./x.py isn't logical.
85         unimplemented!()
86     }
87 }
88
89 pub struct RunConfig<'a> {
90     pub builder: &'a Builder<'a>,
91     pub target: TargetSelection,
92     pub path: PathBuf,
93 }
94
95 impl RunConfig<'_> {
96     pub fn build_triple(&self) -> TargetSelection {
97         self.builder.build.build
98     }
99 }
100
101 struct StepDescription {
102     default: bool,
103     only_hosts: bool,
104     should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
105     make_run: fn(RunConfig<'_>),
106     name: &'static str,
107     kind: Kind,
108 }
109
110 #[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
111 pub struct TaskPath {
112     pub path: PathBuf,
113     pub kind: Option<Kind>,
114 }
115
116 impl TaskPath {
117     pub fn parse(path: impl Into<PathBuf>) -> TaskPath {
118         let mut kind = None;
119         let mut path = path.into();
120
121         let mut components = path.components();
122         if let Some(Component::Normal(os_str)) = components.next() {
123             if let Some(str) = os_str.to_str() {
124                 if let Some((found_kind, found_prefix)) = str.split_once("::") {
125                     if found_kind.is_empty() {
126                         panic!("empty kind in task path {}", path.display());
127                     }
128                     kind = Kind::parse(found_kind);
129                     assert!(kind.is_some());
130                     path = Path::new(found_prefix).join(components.as_path());
131                 }
132             }
133         }
134
135         TaskPath { path, kind }
136     }
137 }
138
139 impl Debug for TaskPath {
140     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141         if let Some(kind) = &self.kind {
142             write!(f, "{}::", kind.as_str())?;
143         }
144         write!(f, "{}", self.path.display())
145     }
146 }
147
148 /// Collection of paths used to match a task rule.
149 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
150 pub enum PathSet {
151     /// A collection of individual paths.
152     ///
153     /// These are generally matched as a path suffix. For example, a
154     /// command-line value of `libstd` will match if `src/libstd` is in the
155     /// set.
156     Set(BTreeSet<TaskPath>),
157     /// A "suite" of paths.
158     ///
159     /// These can match as a path suffix (like `Set`), or as a prefix. For
160     /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
161     /// will match `src/test/ui`. A command-line value of `ui` would also
162     /// match `src/test/ui`.
163     Suite(TaskPath),
164 }
165
166 impl PathSet {
167     fn empty() -> PathSet {
168         PathSet::Set(BTreeSet::new())
169     }
170
171     fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
172         let mut set = BTreeSet::new();
173         set.insert(TaskPath { path: path.into(), kind: Some(kind) });
174         PathSet::Set(set)
175     }
176
177     fn has(&self, needle: &Path, module: Option<Kind>) -> bool {
178         let check = |p: &TaskPath| {
179             if let (Some(p_kind), Some(kind)) = (&p.kind, module) {
180                 p.path.ends_with(needle) && *p_kind == kind
181             } else {
182                 p.path.ends_with(needle)
183             }
184         };
185
186         match self {
187             PathSet::Set(set) => set.iter().any(check),
188             PathSet::Suite(suite) => check(suite),
189         }
190     }
191
192     fn path(&self, builder: &Builder<'_>) -> PathBuf {
193         match self {
194             PathSet::Set(set) => {
195                 set.iter().next().map(|p| &p.path).unwrap_or(&builder.build.src).clone()
196             }
197             PathSet::Suite(path) => path.path.clone(),
198         }
199     }
200 }
201
202 impl StepDescription {
203     fn from<S: Step>(kind: Kind) -> StepDescription {
204         StepDescription {
205             default: S::DEFAULT,
206             only_hosts: S::ONLY_HOSTS,
207             should_run: S::should_run,
208             make_run: S::make_run,
209             name: std::any::type_name::<S>(),
210             kind,
211         }
212     }
213
214     fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
215         if self.is_excluded(builder, pathset) {
216             return;
217         }
218
219         // Determine the targets participating in this rule.
220         let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
221
222         for target in targets {
223             let run = RunConfig { builder, path: pathset.path(builder), target: *target };
224             (self.make_run)(run);
225         }
226     }
227
228     fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
229         if builder.config.exclude.iter().any(|e| pathset.has(&e.path, e.kind)) {
230             eprintln!("Skipping {:?} because it is excluded", pathset);
231             return true;
232         }
233
234         if !builder.config.exclude.is_empty() {
235             builder.verbose(&format!(
236                 "{:?} not skipped for {:?} -- not in {:?}",
237                 pathset, self.name, builder.config.exclude
238             ));
239         }
240         false
241     }
242
243     fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
244         let should_runs = v
245             .iter()
246             .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
247             .collect::<Vec<_>>();
248
249         // sanity checks on rules
250         for (desc, should_run) in v.iter().zip(&should_runs) {
251             assert!(
252                 !should_run.paths.is_empty(),
253                 "{:?} should have at least one pathset",
254                 desc.name
255             );
256         }
257
258         if paths.is_empty() || builder.config.include_default_paths {
259             for (desc, should_run) in v.iter().zip(&should_runs) {
260                 if desc.default && should_run.is_really_default() {
261                     for pathset in &should_run.paths {
262                         desc.maybe_run(builder, pathset);
263                     }
264                 }
265             }
266         }
267
268         for path in paths {
269             // strip CurDir prefix if present
270             let path = match path.strip_prefix(".") {
271                 Ok(p) => p,
272                 Err(_) => path,
273             };
274
275             let mut attempted_run = false;
276             for (desc, should_run) in v.iter().zip(&should_runs) {
277                 if let Some(suite) = should_run.is_suite_path(path) {
278                     attempted_run = true;
279                     desc.maybe_run(builder, suite);
280                 } else if let Some(pathset) = should_run.pathset_for_path(path, desc.kind) {
281                     attempted_run = true;
282                     desc.maybe_run(builder, pathset);
283                 }
284             }
285
286             if !attempted_run {
287                 panic!("error: no rules matched {}", path.display());
288             }
289         }
290     }
291 }
292
293 enum ReallyDefault<'a> {
294     Bool(bool),
295     Lazy(Lazy<bool, Box<dyn Fn() -> bool + 'a>>),
296 }
297
298 pub struct ShouldRun<'a> {
299     pub builder: &'a Builder<'a>,
300     kind: Kind,
301
302     // use a BTreeSet to maintain sort order
303     paths: BTreeSet<PathSet>,
304
305     // If this is a default rule, this is an additional constraint placed on
306     // its run. Generally something like compiler docs being enabled.
307     is_really_default: ReallyDefault<'a>,
308 }
309
310 impl<'a> ShouldRun<'a> {
311     fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
312         ShouldRun {
313             builder,
314             kind,
315             paths: BTreeSet::new(),
316             is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
317         }
318     }
319
320     pub fn default_condition(mut self, cond: bool) -> Self {
321         self.is_really_default = ReallyDefault::Bool(cond);
322         self
323     }
324
325     pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
326         self.is_really_default = ReallyDefault::Lazy(Lazy::new(lazy_cond));
327         self
328     }
329
330     pub fn is_really_default(&self) -> bool {
331         match &self.is_really_default {
332             ReallyDefault::Bool(val) => *val,
333             ReallyDefault::Lazy(lazy) => *lazy.deref(),
334         }
335     }
336
337     /// Indicates it should run if the command-line selects the given crate or
338     /// any of its (local) dependencies.
339     ///
340     /// Compared to `krate`, this treats the dependencies as aliases for the
341     /// same job. Generally it is preferred to use `krate`, and treat each
342     /// individual path separately. For example `./x.py test src/liballoc`
343     /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
344     /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
345     /// `all_krates` should probably be removed at some point.
346     pub fn all_krates(mut self, name: &str) -> Self {
347         let mut set = BTreeSet::new();
348         for krate in self.builder.in_tree_crates(name, None) {
349             let path = krate.local_path(self.builder);
350             set.insert(TaskPath { path, kind: Some(self.kind) });
351         }
352         self.paths.insert(PathSet::Set(set));
353         self
354     }
355
356     /// Indicates it should run if the command-line selects the given crate or
357     /// any of its (local) dependencies.
358     ///
359     /// `make_run` will be called separately for each matching command-line path.
360     pub fn krate(mut self, name: &str) -> Self {
361         for krate in self.builder.in_tree_crates(name, None) {
362             let path = krate.local_path(self.builder);
363             self.paths.insert(PathSet::one(path, self.kind));
364         }
365         self
366     }
367
368     // single alias, which does not correspond to any on-disk path
369     pub fn alias(mut self, alias: &str) -> Self {
370         assert!(
371             !self.builder.src.join(alias).exists(),
372             "use `builder.path()` for real paths: {}",
373             alias
374         );
375         self.paths.insert(PathSet::Set(
376             std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
377         ));
378         self
379     }
380
381     // single, non-aliased path
382     pub fn path(self, path: &str) -> Self {
383         self.paths(&[path])
384     }
385
386     // multiple aliases for the same job
387     pub fn paths(mut self, paths: &[&str]) -> Self {
388         self.paths.insert(PathSet::Set(
389             paths
390                 .iter()
391                 .map(|p| {
392                     // FIXME(#96188): make sure this is actually a path.
393                     // This currently breaks for paths within submodules.
394                     //assert!(
395                     //    self.builder.src.join(p).exists(),
396                     //    "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {}",
397                     //    p
398                     //);
399                     TaskPath { path: p.into(), kind: Some(self.kind) }
400                 })
401                 .collect(),
402         ));
403         self
404     }
405
406     pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
407         self.paths.iter().find(|pathset| match pathset {
408             PathSet::Suite(p) => path.starts_with(&p.path),
409             PathSet::Set(_) => false,
410         })
411     }
412
413     pub fn suite_path(mut self, suite: &str) -> Self {
414         self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
415         self
416     }
417
418     // allows being more explicit about why should_run in Step returns the value passed to it
419     pub fn never(mut self) -> ShouldRun<'a> {
420         self.paths.insert(PathSet::empty());
421         self
422     }
423
424     fn pathset_for_path(&self, path: &Path, kind: Kind) -> Option<&PathSet> {
425         self.paths.iter().find(|pathset| pathset.has(path, Some(kind)))
426     }
427 }
428
429 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
430 pub enum Kind {
431     Build,
432     Check,
433     Clippy,
434     Fix,
435     Format,
436     Test,
437     Bench,
438     Doc,
439     Clean,
440     Dist,
441     Install,
442     Run,
443     Setup,
444 }
445
446 impl Kind {
447     pub fn parse(string: &str) -> Option<Kind> {
448         // these strings, including the one-letter aliases, must match the x.py help text
449         Some(match string {
450             "build" | "b" => Kind::Build,
451             "check" | "c" => Kind::Check,
452             "clippy" => Kind::Clippy,
453             "fix" => Kind::Fix,
454             "fmt" => Kind::Format,
455             "test" | "t" => Kind::Test,
456             "bench" => Kind::Bench,
457             "doc" | "d" => Kind::Doc,
458             "clean" => Kind::Clean,
459             "dist" => Kind::Dist,
460             "install" => Kind::Install,
461             "run" | "r" => Kind::Run,
462             "setup" => Kind::Setup,
463             _ => return None,
464         })
465     }
466
467     pub fn as_str(&self) -> &'static str {
468         match self {
469             Kind::Build => "build",
470             Kind::Check => "check",
471             Kind::Clippy => "clippy",
472             Kind::Fix => "fix",
473             Kind::Format => "fmt",
474             Kind::Test => "test",
475             Kind::Bench => "bench",
476             Kind::Doc => "doc",
477             Kind::Clean => "clean",
478             Kind::Dist => "dist",
479             Kind::Install => "install",
480             Kind::Run => "run",
481             Kind::Setup => "setup",
482         }
483     }
484 }
485
486 impl<'a> Builder<'a> {
487     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
488         macro_rules! describe {
489             ($($rule:ty),+ $(,)?) => {{
490                 vec![$(StepDescription::from::<$rule>(kind)),+]
491             }};
492         }
493         match kind {
494             Kind::Build => describe!(
495                 compile::Std,
496                 compile::Assemble,
497                 compile::CodegenBackend,
498                 compile::StartupObjects,
499                 tool::BuildManifest,
500                 tool::Rustbook,
501                 tool::ErrorIndex,
502                 tool::UnstableBookGen,
503                 tool::Tidy,
504                 tool::Linkchecker,
505                 tool::CargoTest,
506                 tool::Compiletest,
507                 tool::RemoteTestServer,
508                 tool::RemoteTestClient,
509                 tool::RustInstaller,
510                 tool::Cargo,
511                 tool::Rls,
512                 tool::RustAnalyzer,
513                 tool::RustDemangler,
514                 tool::Rustdoc,
515                 tool::Clippy,
516                 tool::CargoClippy,
517                 native::Llvm,
518                 native::Sanitizers,
519                 tool::Rustfmt,
520                 tool::Miri,
521                 tool::CargoMiri,
522                 native::Lld,
523                 native::CrtBeginEnd
524             ),
525             Kind::Check => describe!(
526                 check::Std,
527                 check::Rustc,
528                 check::Rustdoc,
529                 check::CodegenBackend,
530                 check::Clippy,
531                 check::Miri,
532                 check::Rls,
533                 check::Rustfmt,
534                 check::Bootstrap
535             ),
536             Kind::Test => describe!(
537                 crate::toolstate::ToolStateCheck,
538                 test::ExpandYamlAnchors,
539                 test::Tidy,
540                 test::Ui,
541                 test::RunPassValgrind,
542                 test::MirOpt,
543                 test::Codegen,
544                 test::CodegenUnits,
545                 test::Assembly,
546                 test::Incremental,
547                 test::Debuginfo,
548                 test::UiFullDeps,
549                 test::Rustdoc,
550                 test::Pretty,
551                 test::Crate,
552                 test::CrateLibrustc,
553                 test::CrateRustdoc,
554                 test::CrateRustdocJsonTypes,
555                 test::Linkcheck,
556                 test::TierCheck,
557                 test::Cargotest,
558                 test::Cargo,
559                 test::Rls,
560                 test::ErrorIndex,
561                 test::Distcheck,
562                 test::RunMakeFullDeps,
563                 test::Nomicon,
564                 test::Reference,
565                 test::RustdocBook,
566                 test::RustByExample,
567                 test::TheBook,
568                 test::UnstableBook,
569                 test::RustcBook,
570                 test::LintDocs,
571                 test::RustcGuide,
572                 test::EmbeddedBook,
573                 test::EditionGuide,
574                 test::Rustfmt,
575                 test::Miri,
576                 test::Clippy,
577                 test::RustDemangler,
578                 test::CompiletestTest,
579                 test::RustdocJSStd,
580                 test::RustdocJSNotStd,
581                 test::RustdocGUI,
582                 test::RustdocTheme,
583                 test::RustdocUi,
584                 test::RustdocJson,
585                 test::HtmlCheck,
586                 // Run bootstrap close to the end as it's unlikely to fail
587                 test::Bootstrap,
588                 // Run run-make last, since these won't pass without make on Windows
589                 test::RunMake,
590             ),
591             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
592             Kind::Doc => describe!(
593                 doc::UnstableBook,
594                 doc::UnstableBookGen,
595                 doc::TheBook,
596                 doc::Standalone,
597                 doc::Std,
598                 doc::Rustc,
599                 doc::Rustdoc,
600                 doc::Rustfmt,
601                 doc::ErrorIndex,
602                 doc::Nomicon,
603                 doc::Reference,
604                 doc::RustdocBook,
605                 doc::RustByExample,
606                 doc::RustcBook,
607                 doc::CargoBook,
608                 doc::Clippy,
609                 doc::EmbeddedBook,
610                 doc::EditionGuide,
611             ),
612             Kind::Dist => describe!(
613                 dist::Docs,
614                 dist::RustcDocs,
615                 dist::Mingw,
616                 dist::Rustc,
617                 dist::DebuggerScripts,
618                 dist::Std,
619                 dist::RustcDev,
620                 dist::Analysis,
621                 dist::Src,
622                 dist::Cargo,
623                 dist::Rls,
624                 dist::RustAnalyzer,
625                 dist::Rustfmt,
626                 dist::RustDemangler,
627                 dist::Clippy,
628                 dist::Miri,
629                 dist::LlvmTools,
630                 dist::RustDev,
631                 dist::Extended,
632                 // It seems that PlainSourceTarball somehow changes how some of the tools
633                 // perceive their dependencies (see #93033) which would invalidate fingerprints
634                 // and force us to rebuild tools after vendoring dependencies.
635                 // To work around this, create the Tarball after building all the tools.
636                 dist::PlainSourceTarball,
637                 dist::BuildManifest,
638                 dist::ReproducibleArtifacts,
639             ),
640             Kind::Install => describe!(
641                 install::Docs,
642                 install::Std,
643                 install::Cargo,
644                 install::Rls,
645                 install::RustAnalyzer,
646                 install::Rustfmt,
647                 install::RustDemangler,
648                 install::Clippy,
649                 install::Miri,
650                 install::Analysis,
651                 install::Src,
652                 install::Rustc
653             ),
654             Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest, run::BumpStage0),
655             // These commands either don't use paths, or they're special-cased in Build::build()
656             Kind::Clean | Kind::Clippy | Kind::Fix | Kind::Format | Kind::Setup => vec![],
657         }
658     }
659
660     pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
661         let step_descriptions = Builder::get_step_descriptions(kind);
662         if step_descriptions.is_empty() {
663             return None;
664         }
665
666         let builder = Self::new_internal(build, kind, vec![]);
667         let builder = &builder;
668         // The "build" kind here is just a placeholder, it will be replaced with something else in
669         // the following statement.
670         let mut should_run = ShouldRun::new(builder, Kind::Build);
671         for desc in step_descriptions {
672             should_run.kind = desc.kind;
673             should_run = (desc.should_run)(should_run);
674         }
675         let mut help = String::from("Available paths:\n");
676         let mut add_path = |path: &Path| {
677             t!(write!(help, "    ./x.py {} {}\n", kind.as_str(), path.display()));
678         };
679         for pathset in should_run.paths {
680             match pathset {
681                 PathSet::Set(set) => {
682                     for path in set {
683                         add_path(&path.path);
684                     }
685                 }
686                 PathSet::Suite(path) => {
687                     add_path(&path.path.join("..."));
688                 }
689             }
690         }
691         Some(help)
692     }
693
694     fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
695         Builder {
696             build,
697             top_stage: build.config.stage,
698             kind,
699             cache: Cache::new(),
700             stack: RefCell::new(Vec::new()),
701             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
702             paths,
703         }
704     }
705
706     pub fn new(build: &Build) -> Builder<'_> {
707         let (kind, paths) = match build.config.cmd {
708             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
709             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
710             Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
711             Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
712             Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
713             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
714             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
715             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
716             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
717             Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
718             Subcommand::Format { .. } | Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
719                 panic!()
720             }
721         };
722
723         Self::new_internal(build, kind, paths.to_owned())
724     }
725
726     pub fn execute_cli(&self) {
727         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
728     }
729
730     pub fn default_doc(&self, paths: &[PathBuf]) {
731         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
732     }
733
734     /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
735     pub fn doc_rust_lang_org_channel(&self) -> String {
736         let channel = match &*self.config.channel {
737             "stable" => &self.version,
738             "beta" => "beta",
739             "nightly" | "dev" => "nightly",
740             // custom build of rustdoc maybe? link to the latest stable docs just in case
741             _ => "stable",
742         };
743         "https://doc.rust-lang.org/".to_owned() + channel
744     }
745
746     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
747         StepDescription::run(v, self, paths);
748     }
749
750     /// Obtain a compiler at a given stage and for a given host. Explicitly does
751     /// not take `Compiler` since all `Compiler` instances are meant to be
752     /// obtained through this function, since it ensures that they are valid
753     /// (i.e., built and assembled).
754     pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
755         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
756     }
757
758     /// Similar to `compiler`, except handles the full-bootstrap option to
759     /// silently use the stage1 compiler instead of a stage2 compiler if one is
760     /// requested.
761     ///
762     /// Note that this does *not* have the side effect of creating
763     /// `compiler(stage, host)`, unlike `compiler` above which does have such
764     /// a side effect. The returned compiler here can only be used to compile
765     /// new artifacts, it can't be used to rely on the presence of a particular
766     /// sysroot.
767     ///
768     /// See `force_use_stage1` for documentation on what each argument is.
769     pub fn compiler_for(
770         &self,
771         stage: u32,
772         host: TargetSelection,
773         target: TargetSelection,
774     ) -> Compiler {
775         if self.build.force_use_stage1(Compiler { stage, host }, target) {
776             self.compiler(1, self.config.build)
777         } else {
778             self.compiler(stage, host)
779         }
780     }
781
782     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
783         self.ensure(compile::Sysroot { compiler })
784     }
785
786     /// Returns the libdir where the standard library and other artifacts are
787     /// found for a compiler's sysroot.
788     pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
789         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
790         struct Libdir {
791             compiler: Compiler,
792             target: TargetSelection,
793         }
794         impl Step for Libdir {
795             type Output = Interned<PathBuf>;
796
797             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
798                 run.never()
799             }
800
801             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
802                 let lib = builder.sysroot_libdir_relative(self.compiler);
803                 let sysroot = builder
804                     .sysroot(self.compiler)
805                     .join(lib)
806                     .join("rustlib")
807                     .join(self.target.triple)
808                     .join("lib");
809                 // Avoid deleting the rustlib/ directory we just copied
810                 // (in `impl Step for Sysroot`).
811                 if !builder.config.download_rustc {
812                     let _ = fs::remove_dir_all(&sysroot);
813                     t!(fs::create_dir_all(&sysroot));
814                 }
815                 INTERNER.intern_path(sysroot)
816             }
817         }
818         self.ensure(Libdir { compiler, target })
819     }
820
821     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
822         self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
823     }
824
825     /// Returns the compiler's libdir where it stores the dynamic libraries that
826     /// it itself links against.
827     ///
828     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
829     /// Windows.
830     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
831         if compiler.is_snapshot(self) {
832             self.rustc_snapshot_libdir()
833         } else {
834             match self.config.libdir_relative() {
835                 Some(relative_libdir) if compiler.stage >= 1 => {
836                     self.sysroot(compiler).join(relative_libdir)
837                 }
838                 _ => self.sysroot(compiler).join(libdir(compiler.host)),
839             }
840         }
841     }
842
843     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
844     /// it itself links against.
845     ///
846     /// For example this returns `lib` on Unix and `bin` on
847     /// Windows.
848     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
849         if compiler.is_snapshot(self) {
850             libdir(self.config.build).as_ref()
851         } else {
852             match self.config.libdir_relative() {
853                 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
854                 _ => libdir(compiler.host).as_ref(),
855             }
856         }
857     }
858
859     /// Returns the compiler's relative libdir where the standard library and other artifacts are
860     /// found for a compiler's sysroot.
861     ///
862     /// For example this returns `lib` on Unix and Windows.
863     pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
864         match self.config.libdir_relative() {
865             Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
866             _ if compiler.stage == 0 => &self.build.initial_libdir,
867             _ => Path::new("lib"),
868         }
869     }
870
871     pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
872         let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
873
874         // Ensure that the downloaded LLVM libraries can be found.
875         if self.config.llvm_from_ci {
876             let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
877             dylib_dirs.push(ci_llvm_lib);
878         }
879
880         dylib_dirs
881     }
882
883     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
884     /// library lookup path.
885     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
886         // Windows doesn't need dylib path munging because the dlls for the
887         // compiler live next to the compiler and the system will find them
888         // automatically.
889         if cfg!(windows) {
890             return;
891         }
892
893         add_dylib_path(self.rustc_lib_paths(compiler), cmd);
894     }
895
896     /// Gets a path to the compiler specified.
897     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
898         if compiler.is_snapshot(self) {
899             self.initial_rustc.clone()
900         } else {
901             self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
902         }
903     }
904
905     /// Gets the paths to all of the compiler's codegen backends.
906     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
907         fs::read_dir(self.sysroot_codegen_backends(compiler))
908             .into_iter()
909             .flatten()
910             .filter_map(Result::ok)
911             .map(|entry| entry.path())
912     }
913
914     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
915         self.ensure(tool::Rustdoc { compiler })
916     }
917
918     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
919         let mut cmd = Command::new(&self.bootstrap_out.join("rustdoc"));
920         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
921             .env("RUSTC_SYSROOT", self.sysroot(compiler))
922             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
923             // equivalently to rustc.
924             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
925             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
926             .env("RUSTDOC_REAL", self.rustdoc(compiler))
927             .env("RUSTC_BOOTSTRAP", "1");
928
929         cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
930
931         if self.config.deny_warnings {
932             cmd.arg("-Dwarnings");
933         }
934         cmd.arg("-Znormalize-docs");
935
936         // Remove make-related flags that can cause jobserver problems.
937         cmd.env_remove("MAKEFLAGS");
938         cmd.env_remove("MFLAGS");
939
940         if let Some(linker) = self.linker(compiler.host) {
941             cmd.env("RUSTDOC_LINKER", linker);
942         }
943         if self.is_fuse_ld_lld(compiler.host) {
944             cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
945         }
946         cmd
947     }
948
949     /// Return the path to `llvm-config` for the target, if it exists.
950     ///
951     /// Note that this returns `None` if LLVM is disabled, or if we're in a
952     /// check build or dry-run, where there's no need to build all of LLVM.
953     fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
954         if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
955             let llvm_config = self.ensure(native::Llvm { target });
956             if llvm_config.is_file() {
957                 return Some(llvm_config);
958             }
959         }
960         None
961     }
962
963     /// Convenience wrapper to allow `builder.llvm_link_shared()` instead of `builder.config.llvm_link_shared(&builder)`.
964     pub(crate) fn llvm_link_shared(&self) -> bool {
965         Config::llvm_link_shared(self)
966     }
967
968     /// Prepares an invocation of `cargo` to be run.
969     ///
970     /// This will create a `Command` that represents a pending execution of
971     /// Cargo. This cargo will be configured to use `compiler` as the actual
972     /// rustc compiler, its output will be scoped by `mode`'s output directory,
973     /// it will pass the `--target` flag for the specified `target`, and will be
974     /// executing the Cargo command `cmd`.
975     pub fn cargo(
976         &self,
977         compiler: Compiler,
978         mode: Mode,
979         source_type: SourceType,
980         target: TargetSelection,
981         cmd: &str,
982     ) -> Cargo {
983         let mut cargo = Command::new(&self.initial_cargo);
984         let out_dir = self.stage_out(compiler, mode);
985
986         // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
987         // so we need to explicitly clear out if they've been updated.
988         for backend in self.codegen_backends(compiler) {
989             self.clear_if_dirty(&out_dir, &backend);
990         }
991
992         if cmd == "doc" || cmd == "rustdoc" {
993             let my_out = match mode {
994                 // This is the intended out directory for compiler documentation.
995                 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
996                 Mode::Std => out_dir.join(target.triple).join("doc"),
997                 _ => panic!("doc mode {:?} not expected", mode),
998             };
999             let rustdoc = self.rustdoc(compiler);
1000             self.clear_if_dirty(&my_out, &rustdoc);
1001         }
1002
1003         cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
1004
1005         let profile_var = |name: &str| {
1006             let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
1007             format!("CARGO_PROFILE_{}_{}", profile, name)
1008         };
1009
1010         // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
1011         // needs to not accidentally link to libLLVM in stage0/lib.
1012         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
1013         if let Some(e) = env::var_os(util::dylib_path_var()) {
1014             cargo.env("REAL_LIBRARY_PATH", e);
1015         }
1016
1017         // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
1018         // from out of tree it shouldn't matter, since x.py is only used for
1019         // building in-tree.
1020         let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
1021         match self.build.config.color {
1022             Color::Always => {
1023                 cargo.arg("--color=always");
1024                 for log in &color_logs {
1025                     cargo.env(log, "always");
1026                 }
1027             }
1028             Color::Never => {
1029                 cargo.arg("--color=never");
1030                 for log in &color_logs {
1031                     cargo.env(log, "never");
1032                 }
1033             }
1034             Color::Auto => {} // nothing to do
1035         }
1036
1037         if cmd != "install" {
1038             cargo.arg("--target").arg(target.rustc_target_arg());
1039         } else {
1040             assert_eq!(target, compiler.host);
1041         }
1042
1043         // Set a flag for `check`/`clippy`/`fix`, so that certain build
1044         // scripts can do less work (i.e. not building/requiring LLVM).
1045         if cmd == "check" || cmd == "clippy" || cmd == "fix" {
1046             // If we've not yet built LLVM, or it's stale, then bust
1047             // the rustc_llvm cache. That will always work, even though it
1048             // may mean that on the next non-check build we'll need to rebuild
1049             // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
1050             // of work comparatively, and we'd likely need to rebuild it anyway,
1051             // so that's okay.
1052             if crate::native::prebuilt_llvm_config(self, target).is_err() {
1053                 cargo.env("RUST_CHECK", "1");
1054             }
1055         }
1056
1057         let stage = if compiler.stage == 0 && self.local_rebuild {
1058             // Assume the local-rebuild rustc already has stage1 features.
1059             1
1060         } else {
1061             compiler.stage
1062         };
1063
1064         let mut rustflags = Rustflags::new(target);
1065         if stage != 0 {
1066             if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
1067                 cargo.args(s.split_whitespace());
1068             }
1069             rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
1070         } else {
1071             if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
1072                 cargo.args(s.split_whitespace());
1073             }
1074             rustflags.env("RUSTFLAGS_BOOTSTRAP");
1075             if cmd == "clippy" {
1076                 // clippy overwrites sysroot if we pass it to cargo.
1077                 // Pass it directly to clippy instead.
1078                 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
1079                 // so it has no way of knowing the sysroot.
1080                 rustflags.arg("--sysroot");
1081                 rustflags.arg(
1082                     self.sysroot(compiler)
1083                         .as_os_str()
1084                         .to_str()
1085                         .expect("sysroot must be valid UTF-8"),
1086                 );
1087                 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
1088                 cargo.arg("-Zunstable-options");
1089                 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
1090                 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
1091                 let output = host_version.and_then(|output| {
1092                     if output.status.success() {
1093                         Ok(output)
1094                     } else {
1095                         Err(())
1096                     }
1097                 }).unwrap_or_else(|_| {
1098                     eprintln!(
1099                         "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
1100                     );
1101                     eprintln!("help: try `rustup component add clippy`");
1102                     std::process::exit(1);
1103                 });
1104                 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
1105                     rustflags.arg("--cfg=bootstrap");
1106                 }
1107             } else {
1108                 rustflags.arg("--cfg=bootstrap");
1109             }
1110         }
1111
1112         let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
1113             Some(setting) => {
1114                 // If an explicit setting is given, use that
1115                 setting
1116             }
1117             None => {
1118                 if mode == Mode::Std {
1119                     // The standard library defaults to the legacy scheme
1120                     false
1121                 } else {
1122                     // The compiler and tools default to the new scheme
1123                     true
1124                 }
1125             }
1126         };
1127
1128         if use_new_symbol_mangling {
1129             rustflags.arg("-Csymbol-mangling-version=v0");
1130         } else {
1131             rustflags.arg("-Csymbol-mangling-version=legacy");
1132             rustflags.arg("-Zunstable-options");
1133         }
1134
1135         // #[cfg(not(bootstrap)]
1136         if stage != 0 {
1137             // Enable cfg checking of cargo features
1138             // FIXME: De-comment this when cargo beta get support for it
1139             // cargo.arg("-Zcheck-cfg-features");
1140
1141             // Enable cfg checking of rustc well-known names
1142             rustflags
1143                 .arg("-Zunstable-options")
1144                 // Enable checking of well known names
1145                 .arg("--check-cfg=names()")
1146                 // Enable checking of well known values
1147                 .arg("--check-cfg=values()");
1148
1149             // Add extra cfg not defined in rustc
1150             for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
1151                 if *restricted_mode == None || *restricted_mode == Some(mode) {
1152                     // Creating a string of the values by concatenating each value:
1153                     // ',"tvos","watchos"' or '' (nothing) when there are no values
1154                     let values = match values {
1155                         Some(values) => values
1156                             .iter()
1157                             .map(|val| [",", "\"", val, "\""])
1158                             .flatten()
1159                             .collect::<String>(),
1160                         None => String::new(),
1161                     };
1162                     rustflags.arg(&format!("--check-cfg=values({name}{values})"));
1163                 }
1164             }
1165         }
1166
1167         // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1168         // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1169         // #71458.
1170         let mut rustdocflags = rustflags.clone();
1171         rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1172         if stage == 0 {
1173             rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1174         } else {
1175             rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1176         }
1177
1178         if let Ok(s) = env::var("CARGOFLAGS") {
1179             cargo.args(s.split_whitespace());
1180         }
1181
1182         match mode {
1183             Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1184             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1185                 // Build proc macros both for the host and the target
1186                 if target != compiler.host && cmd != "check" {
1187                     cargo.arg("-Zdual-proc-macros");
1188                     rustflags.arg("-Zdual-proc-macros");
1189                 }
1190             }
1191         }
1192
1193         // This tells Cargo (and in turn, rustc) to output more complete
1194         // dependency information.  Most importantly for rustbuild, this
1195         // includes sysroot artifacts, like libstd, which means that we don't
1196         // need to track those in rustbuild (an error prone process!). This
1197         // feature is currently unstable as there may be some bugs and such, but
1198         // it represents a big improvement in rustbuild's reliability on
1199         // rebuilds, so we're using it here.
1200         //
1201         // For some additional context, see #63470 (the PR originally adding
1202         // this), as well as #63012 which is the tracking issue for this
1203         // feature on the rustc side.
1204         cargo.arg("-Zbinary-dep-depinfo");
1205
1206         cargo.arg("-j").arg(self.jobs().to_string());
1207         // Remove make-related flags to ensure Cargo can correctly set things up
1208         cargo.env_remove("MAKEFLAGS");
1209         cargo.env_remove("MFLAGS");
1210
1211         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1212         // Force cargo to output binaries with disambiguating hashes in the name
1213         let mut metadata = if compiler.stage == 0 {
1214             // Treat stage0 like a special channel, whether it's a normal prior-
1215             // release rustc or a local rebuild with the same version, so we
1216             // never mix these libraries by accident.
1217             "bootstrap".to_string()
1218         } else {
1219             self.config.channel.to_string()
1220         };
1221         // We want to make sure that none of the dependencies between
1222         // std/test/rustc unify with one another. This is done for weird linkage
1223         // reasons but the gist of the problem is that if librustc, libtest, and
1224         // libstd all depend on libc from crates.io (which they actually do) we
1225         // want to make sure they all get distinct versions. Things get really
1226         // weird if we try to unify all these dependencies right now, namely
1227         // around how many times the library is linked in dynamic libraries and
1228         // such. If rustc were a static executable or if we didn't ship dylibs
1229         // this wouldn't be a problem, but we do, so it is. This is in general
1230         // just here to make sure things build right. If you can remove this and
1231         // things still build right, please do!
1232         match mode {
1233             Mode::Std => metadata.push_str("std"),
1234             // When we're building rustc tools, they're built with a search path
1235             // that contains things built during the rustc build. For example,
1236             // bitflags is built during the rustc build, and is a dependency of
1237             // rustdoc as well. We're building rustdoc in a different target
1238             // directory, though, which means that Cargo will rebuild the
1239             // dependency. When we go on to build rustdoc, we'll look for
1240             // bitflags, and find two different copies: one built during the
1241             // rustc step and one that we just built. This isn't always a
1242             // problem, somehow -- not really clear why -- but we know that this
1243             // fixes things.
1244             Mode::ToolRustc => metadata.push_str("tool-rustc"),
1245             // Same for codegen backends.
1246             Mode::Codegen => metadata.push_str("codegen"),
1247             _ => {}
1248         }
1249         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1250
1251         if cmd == "clippy" {
1252             rustflags.arg("-Zforce-unstable-if-unmarked");
1253         }
1254
1255         rustflags.arg("-Zmacro-backtrace");
1256
1257         let want_rustdoc = self.doc_tests != DocTests::No;
1258
1259         // We synthetically interpret a stage0 compiler used to build tools as a
1260         // "raw" compiler in that it's the exact snapshot we download. Normally
1261         // the stage0 build means it uses libraries build by the stage0
1262         // compiler, but for tools we just use the precompiled libraries that
1263         // we've downloaded
1264         let use_snapshot = mode == Mode::ToolBootstrap;
1265         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1266
1267         let maybe_sysroot = self.sysroot(compiler);
1268         let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1269         let libdir = self.rustc_libdir(compiler);
1270
1271         // Clear the output directory if the real rustc we're using has changed;
1272         // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1273         //
1274         // Avoid doing this during dry run as that usually means the relevant
1275         // compiler is not yet linked/copied properly.
1276         //
1277         // Only clear out the directory if we're compiling std; otherwise, we
1278         // should let Cargo take care of things for us (via depdep info)
1279         if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1280             self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1281         }
1282
1283         // Customize the compiler we're running. Specify the compiler to cargo
1284         // as our shim and then pass it some various options used to configure
1285         // how the actual compiler itself is called.
1286         //
1287         // These variables are primarily all read by
1288         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1289         cargo
1290             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1291             .env("RUSTC_REAL", self.rustc(compiler))
1292             .env("RUSTC_STAGE", stage.to_string())
1293             .env("RUSTC_SYSROOT", &sysroot)
1294             .env("RUSTC_LIBDIR", &libdir)
1295             .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
1296             .env(
1297                 "RUSTDOC_REAL",
1298                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1299                     self.rustdoc(compiler)
1300                 } else {
1301                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1302                 },
1303             )
1304             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1305             .env("RUSTC_BREAK_ON_ICE", "1");
1306         // Clippy support is a hack and uses the default `cargo-clippy` in path.
1307         // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1308         if cmd != "clippy" {
1309             cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
1310         }
1311
1312         // Dealing with rpath here is a little special, so let's go into some
1313         // detail. First off, `-rpath` is a linker option on Unix platforms
1314         // which adds to the runtime dynamic loader path when looking for
1315         // dynamic libraries. We use this by default on Unix platforms to ensure
1316         // that our nightlies behave the same on Windows, that is they work out
1317         // of the box. This can be disabled, of course, but basically that's why
1318         // we're gated on RUSTC_RPATH here.
1319         //
1320         // Ok, so the astute might be wondering "why isn't `-C rpath` used
1321         // here?" and that is indeed a good question to ask. This codegen
1322         // option is the compiler's current interface to generating an rpath.
1323         // Unfortunately it doesn't quite suffice for us. The flag currently
1324         // takes no value as an argument, so the compiler calculates what it
1325         // should pass to the linker as `-rpath`. This unfortunately is based on
1326         // the **compile time** directory structure which when building with
1327         // Cargo will be very different than the runtime directory structure.
1328         //
1329         // All that's a really long winded way of saying that if we use
1330         // `-Crpath` then the executables generated have the wrong rpath of
1331         // something like `$ORIGIN/deps` when in fact the way we distribute
1332         // rustc requires the rpath to be `$ORIGIN/../lib`.
1333         //
1334         // So, all in all, to set up the correct rpath we pass the linker
1335         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1336         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1337         // to change a flag in a binary?
1338         if self.config.rust_rpath && util::use_host_linker(target) {
1339             let rpath = if target.contains("apple") {
1340                 // Note that we need to take one extra step on macOS to also pass
1341                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1342                 // do that we pass a weird flag to the compiler to get it to do
1343                 // so. Note that this is definitely a hack, and we should likely
1344                 // flesh out rpath support more fully in the future.
1345                 rustflags.arg("-Zosx-rpath-install-name");
1346                 Some("-Wl,-rpath,@loader_path/../lib")
1347             } else if !target.contains("windows") {
1348                 rustflags.arg("-Clink-args=-Wl,-z,origin");
1349                 Some("-Wl,-rpath,$ORIGIN/../lib")
1350             } else {
1351                 None
1352             };
1353             if let Some(rpath) = rpath {
1354                 rustflags.arg(&format!("-Clink-args={}", rpath));
1355             }
1356         }
1357
1358         if let Some(host_linker) = self.linker(compiler.host) {
1359             cargo.env("RUSTC_HOST_LINKER", host_linker);
1360         }
1361         if self.is_fuse_ld_lld(compiler.host) {
1362             cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1363             cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1364         }
1365
1366         if let Some(target_linker) = self.linker(target) {
1367             let target = crate::envify(&target.triple);
1368             cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1369         }
1370         if self.is_fuse_ld_lld(target) {
1371             rustflags.arg("-Clink-args=-fuse-ld=lld");
1372         }
1373         self.lld_flags(target).for_each(|flag| {
1374             rustdocflags.arg(&flag);
1375         });
1376
1377         if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1378             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1379         }
1380
1381         let debuginfo_level = match mode {
1382             Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1383             Mode::Std => self.config.rust_debuginfo_level_std,
1384             Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1385                 self.config.rust_debuginfo_level_tools
1386             }
1387         };
1388         cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1389         cargo.env(
1390             profile_var("DEBUG_ASSERTIONS"),
1391             if mode == Mode::Std {
1392                 self.config.rust_debug_assertions_std.to_string()
1393             } else {
1394                 self.config.rust_debug_assertions.to_string()
1395             },
1396         );
1397         cargo.env(
1398             profile_var("OVERFLOW_CHECKS"),
1399             if mode == Mode::Std {
1400                 self.config.rust_overflow_checks_std.to_string()
1401             } else {
1402                 self.config.rust_overflow_checks.to_string()
1403             },
1404         );
1405
1406         // FIXME(davidtwco): #[cfg(not(bootstrap))] - #95612 needs to be in the bootstrap compiler
1407         // for this conditional to be removed.
1408         if !target.contains("windows") || compiler.stage >= 1 {
1409             if target.contains("linux") || target.contains("windows") {
1410                 rustflags.arg("-Zunstable-options");
1411             }
1412             match self.config.rust_split_debuginfo {
1413                 SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
1414                 SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
1415                 SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
1416             };
1417         }
1418
1419         if self.config.cmd.bless() {
1420             // Bless `expect!` tests.
1421             cargo.env("UPDATE_EXPECT", "1");
1422         }
1423
1424         if !mode.is_tool() {
1425             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1426         }
1427
1428         if let Some(x) = self.crt_static(target) {
1429             if x {
1430                 rustflags.arg("-Ctarget-feature=+crt-static");
1431             } else {
1432                 rustflags.arg("-Ctarget-feature=-crt-static");
1433             }
1434         }
1435
1436         if let Some(x) = self.crt_static(compiler.host) {
1437             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1438         }
1439
1440         if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1441             let map = format!("{}={}", self.build.src.display(), map_to);
1442             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1443
1444             // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1445             // in order to opportunistically reverse it later.
1446             cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1447         }
1448
1449         // Enable usage of unstable features
1450         cargo.env("RUSTC_BOOTSTRAP", "1");
1451         self.add_rust_test_threads(&mut cargo);
1452
1453         // Almost all of the crates that we compile as part of the bootstrap may
1454         // have a build script, including the standard library. To compile a
1455         // build script, however, it itself needs a standard library! This
1456         // introduces a bit of a pickle when we're compiling the standard
1457         // library itself.
1458         //
1459         // To work around this we actually end up using the snapshot compiler
1460         // (stage0) for compiling build scripts of the standard library itself.
1461         // The stage0 compiler is guaranteed to have a libstd available for use.
1462         //
1463         // For other crates, however, we know that we've already got a standard
1464         // library up and running, so we can use the normal compiler to compile
1465         // build scripts in that situation.
1466         if mode == Mode::Std {
1467             cargo
1468                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1469                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1470         } else {
1471             cargo
1472                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1473                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1474         }
1475
1476         // Tools that use compiler libraries may inherit the `-lLLVM` link
1477         // requirement, but the `-L` library path is not propagated across
1478         // separate Cargo projects. We can add LLVM's library path to the
1479         // platform-specific environment variable as a workaround.
1480         if mode == Mode::ToolRustc || mode == Mode::Codegen {
1481             if let Some(llvm_config) = self.llvm_config(target) {
1482                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1483                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1484             }
1485         }
1486
1487         // Compile everything except libraries and proc macros with the more
1488         // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1489         // so we can't use it by default in general, but we can use it for tools
1490         // and our own internal libraries.
1491         if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1492             rustflags.arg("-Ztls-model=initial-exec");
1493         }
1494
1495         if self.config.incremental {
1496             cargo.env("CARGO_INCREMENTAL", "1");
1497         } else {
1498             // Don't rely on any default setting for incr. comp. in Cargo
1499             cargo.env("CARGO_INCREMENTAL", "0");
1500         }
1501
1502         if let Some(ref on_fail) = self.config.on_fail {
1503             cargo.env("RUSTC_ON_FAIL", on_fail);
1504         }
1505
1506         if self.config.print_step_timings {
1507             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1508         }
1509
1510         if self.config.print_step_rusage {
1511             cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1512         }
1513
1514         if self.config.backtrace_on_ice {
1515             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1516         }
1517
1518         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1519
1520         if source_type == SourceType::InTree {
1521             let mut lint_flags = Vec::new();
1522             // When extending this list, add the new lints to the RUSTFLAGS of the
1523             // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1524             // some code doesn't go through this `rustc` wrapper.
1525             lint_flags.push("-Wrust_2018_idioms");
1526             lint_flags.push("-Wunused_lifetimes");
1527             lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1528
1529             if self.config.deny_warnings {
1530                 lint_flags.push("-Dwarnings");
1531                 rustdocflags.arg("-Dwarnings");
1532             }
1533
1534             // This does not use RUSTFLAGS due to caching issues with Cargo.
1535             // Clippy is treated as an "in tree" tool, but shares the same
1536             // cache as other "submodule" tools. With these options set in
1537             // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1538             // By injecting this into the rustc wrapper, this circumvents
1539             // Cargo's fingerprint detection. This is fine because lint flags
1540             // are always ignored in dependencies. Eventually this should be
1541             // fixed via better support from Cargo.
1542             cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1543
1544             rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1545         }
1546
1547         if mode == Mode::Rustc {
1548             rustflags.arg("-Zunstable-options");
1549             rustflags.arg("-Wrustc::internal");
1550         }
1551
1552         // Throughout the build Cargo can execute a number of build scripts
1553         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1554         // obtained previously to those build scripts.
1555         // Build scripts use either the `cc` crate or `configure/make` so we pass
1556         // the options through environment variables that are fetched and understood by both.
1557         //
1558         // FIXME: the guard against msvc shouldn't need to be here
1559         if target.contains("msvc") {
1560             if let Some(ref cl) = self.config.llvm_clang_cl {
1561                 cargo.env("CC", cl).env("CXX", cl);
1562             }
1563         } else {
1564             let ccache = self.config.ccache.as_ref();
1565             let ccacheify = |s: &Path| {
1566                 let ccache = match ccache {
1567                     Some(ref s) => s,
1568                     None => return s.display().to_string(),
1569                 };
1570                 // FIXME: the cc-rs crate only recognizes the literal strings
1571                 // `ccache` and `sccache` when doing caching compilations, so we
1572                 // mirror that here. It should probably be fixed upstream to
1573                 // accept a new env var or otherwise work with custom ccache
1574                 // vars.
1575                 match &ccache[..] {
1576                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1577                     _ => s.display().to_string(),
1578                 }
1579             };
1580             let cc = ccacheify(&self.cc(target));
1581             cargo.env(format!("CC_{}", target.triple), &cc);
1582
1583             let cflags = self.cflags(target, GitRepo::Rustc, CLang::C).join(" ");
1584             cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1585
1586             if let Some(ar) = self.ar(target) {
1587                 let ranlib = format!("{} s", ar.display());
1588                 cargo
1589                     .env(format!("AR_{}", target.triple), ar)
1590                     .env(format!("RANLIB_{}", target.triple), ranlib);
1591             }
1592
1593             if let Ok(cxx) = self.cxx(target) {
1594                 let cxx = ccacheify(&cxx);
1595                 let cxxflags = self.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");
1596                 cargo
1597                     .env(format!("CXX_{}", target.triple), &cxx)
1598                     .env(format!("CXXFLAGS_{}", target.triple), cxxflags);
1599             }
1600         }
1601
1602         if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1603             rustflags.arg("-Zsave-analysis");
1604             cargo.env(
1605                 "RUST_SAVE_ANALYSIS_CONFIG",
1606                 "{\"output_file\": null,\"full_docs\": false,\
1607                        \"pub_only\": true,\"reachable_only\": false,\
1608                        \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1609             );
1610         }
1611
1612         // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1613         // when compiling the standard library, since this might be linked into the final outputs
1614         // produced by rustc. Since this mitigation is only available on Windows, only enable it
1615         // for the standard library in case the compiler is run on a non-Windows platform.
1616         // This is not needed for stage 0 artifacts because these will only be used for building
1617         // the stage 1 compiler.
1618         if cfg!(windows)
1619             && mode == Mode::Std
1620             && self.config.control_flow_guard
1621             && compiler.stage >= 1
1622         {
1623             rustflags.arg("-Ccontrol-flow-guard");
1624         }
1625
1626         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1627         // This replaces spaces with newlines because RUSTDOCFLAGS does not
1628         // support arguments with regular spaces. Hopefully someday Cargo will
1629         // have space support.
1630         let rust_version = self.rust_version().replace(' ', "\n");
1631         rustdocflags.arg("--crate-version").arg(&rust_version);
1632
1633         // Environment variables *required* throughout the build
1634         //
1635         // FIXME: should update code to not require this env var
1636         cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1637
1638         // Set this for all builds to make sure doc builds also get it.
1639         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1640
1641         // This one's a bit tricky. As of the time of this writing the compiler
1642         // links to the `winapi` crate on crates.io. This crate provides raw
1643         // bindings to Windows system functions, sort of like libc does for
1644         // Unix. This crate also, however, provides "import libraries" for the
1645         // MinGW targets. There's an import library per dll in the windows
1646         // distribution which is what's linked to. These custom import libraries
1647         // are used because the winapi crate can reference Windows functions not
1648         // present in the MinGW import libraries.
1649         //
1650         // For example MinGW may ship libdbghelp.a, but it may not have
1651         // references to all the functions in the dbghelp dll. Instead the
1652         // custom import library for dbghelp in the winapi crates has all this
1653         // information.
1654         //
1655         // Unfortunately for us though the import libraries are linked by
1656         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1657         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1658         // conflict with the system MinGW ones). This consequently means that
1659         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1660         // DLL) when linked against *again*, for example with procedural macros
1661         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1662         // `-lwinapi_foo` to the linker again. This isn't actually available in
1663         // our distribution, however, so the link fails.
1664         //
1665         // To solve this problem we tell winapi to not use its bundled import
1666         // libraries. This means that it will link to the system MinGW import
1667         // libraries by default, and the `-ldylib=foo` directives will still get
1668         // passed to the final linker, but they'll look like `-lfoo` which can
1669         // be resolved because MinGW has the import library. The downside is we
1670         // don't get newer functions from Windows, but we don't use any of them
1671         // anyway.
1672         if !mode.is_tool() {
1673             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1674         }
1675
1676         for _ in 0..self.verbosity {
1677             cargo.arg("-v");
1678         }
1679
1680         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1681             (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1682                 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1683             }
1684             _ => {
1685                 // Don't set anything
1686             }
1687         }
1688
1689         if self.config.rust_optimize {
1690             // FIXME: cargo bench/install do not accept `--release`
1691             if cmd != "bench" && cmd != "install" {
1692                 cargo.arg("--release");
1693             }
1694         }
1695
1696         if self.config.locked_deps {
1697             cargo.arg("--locked");
1698         }
1699         if self.config.vendor || self.is_sudo {
1700             cargo.arg("--frozen");
1701         }
1702
1703         // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1704         cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1705
1706         self.ci_env.force_coloring_in_ci(&mut cargo);
1707
1708         // When we build Rust dylibs they're all intended for intermediate
1709         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1710         // linking all deps statically into the dylib.
1711         if matches!(mode, Mode::Std | Mode::Rustc) {
1712             rustflags.arg("-Cprefer-dynamic");
1713         }
1714
1715         // When building incrementally we default to a lower ThinLTO import limit
1716         // (unless explicitly specified otherwise). This will produce a somewhat
1717         // slower code but give way better compile times.
1718         {
1719             let limit = match self.config.rust_thin_lto_import_instr_limit {
1720                 Some(limit) => Some(limit),
1721                 None if self.config.incremental => Some(10),
1722                 _ => None,
1723             };
1724
1725             if let Some(limit) = limit {
1726                 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1727             }
1728         }
1729
1730         Cargo { command: cargo, rustflags, rustdocflags }
1731     }
1732
1733     /// Ensure that a given step is built, returning its output. This will
1734     /// cache the step, so it is safe (and good!) to call this as often as
1735     /// needed to ensure that all dependencies are built.
1736     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1737         {
1738             let mut stack = self.stack.borrow_mut();
1739             for stack_step in stack.iter() {
1740                 // should skip
1741                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1742                     continue;
1743                 }
1744                 let mut out = String::new();
1745                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1746                 for el in stack.iter().rev() {
1747                     out += &format!("\t{:?}\n", el);
1748                 }
1749                 panic!("{}", out);
1750             }
1751             if let Some(out) = self.cache.get(&step) {
1752                 self.verbose_than(1, &format!("{}c {:?}", "  ".repeat(stack.len()), step));
1753
1754                 return out;
1755             }
1756             self.verbose_than(1, &format!("{}> {:?}", "  ".repeat(stack.len()), step));
1757             stack.push(Box::new(step.clone()));
1758         }
1759
1760         let (out, dur) = {
1761             let start = Instant::now();
1762             let zero = Duration::new(0, 0);
1763             let parent = self.time_spent_on_dependencies.replace(zero);
1764             let out = step.clone().run(self);
1765             let dur = start.elapsed();
1766             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1767             (out, dur - deps)
1768         };
1769
1770         if self.config.print_step_timings && !self.config.dry_run {
1771             let step_string = format!("{:?}", step);
1772             let brace_index = step_string.find("{").unwrap_or(0);
1773             let type_string = type_name::<S>();
1774             println!(
1775                 "[TIMING] {} {} -- {}.{:03}",
1776                 &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1777                 &step_string[brace_index..],
1778                 dur.as_secs(),
1779                 dur.subsec_millis()
1780             );
1781         }
1782
1783         {
1784             let mut stack = self.stack.borrow_mut();
1785             let cur_step = stack.pop().expect("step stack empty");
1786             assert_eq!(cur_step.downcast_ref(), Some(&step));
1787         }
1788         self.verbose_than(1, &format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
1789         self.cache.put(step, out.clone());
1790         out
1791     }
1792
1793     /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1794     /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1795     /// needed to ensure that all dependencies are build.
1796     pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1797         &'a self,
1798         step: S,
1799         kind: Kind,
1800     ) -> S::Output {
1801         let desc = StepDescription::from::<S>(kind);
1802         let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1803
1804         // Avoid running steps contained in --exclude
1805         for pathset in &should_run.paths {
1806             if desc.is_excluded(self, pathset) {
1807                 return None;
1808             }
1809         }
1810
1811         // Only execute if it's supposed to run as default
1812         if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1813     }
1814
1815     /// Checks if any of the "should_run" paths is in the `Builder` paths.
1816     pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1817         let desc = StepDescription::from::<S>(kind);
1818         let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1819
1820         for path in &self.paths {
1821             if should_run.paths.iter().any(|s| s.has(path, Some(desc.kind)))
1822                 && !desc.is_excluded(
1823                     self,
1824                     &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1825                 )
1826             {
1827                 return true;
1828             }
1829         }
1830
1831         false
1832     }
1833 }
1834
1835 #[cfg(test)]
1836 mod tests;
1837
1838 #[derive(Debug, Clone)]
1839 struct Rustflags(String, TargetSelection);
1840
1841 impl Rustflags {
1842     fn new(target: TargetSelection) -> Rustflags {
1843         let mut ret = Rustflags(String::new(), target);
1844         ret.propagate_cargo_env("RUSTFLAGS");
1845         ret
1846     }
1847
1848     /// By default, cargo will pick up on various variables in the environment. However, bootstrap
1849     /// reuses those variables to pass additional flags to rustdoc, so by default they get overridden.
1850     /// Explicitly add back any previous value in the environment.
1851     ///
1852     /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
1853     fn propagate_cargo_env(&mut self, prefix: &str) {
1854         // Inherit `RUSTFLAGS` by default ...
1855         self.env(prefix);
1856
1857         // ... and also handle target-specific env RUSTFLAGS if they're configured.
1858         let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
1859         self.env(&target_specific);
1860     }
1861
1862     fn env(&mut self, env: &str) {
1863         if let Ok(s) = env::var(env) {
1864             for part in s.split(' ') {
1865                 self.arg(part);
1866             }
1867         }
1868     }
1869
1870     fn arg(&mut self, arg: &str) -> &mut Self {
1871         assert_eq!(arg.split(' ').count(), 1);
1872         if !self.0.is_empty() {
1873             self.0.push(' ');
1874         }
1875         self.0.push_str(arg);
1876         self
1877     }
1878 }
1879
1880 #[derive(Debug)]
1881 pub struct Cargo {
1882     command: Command,
1883     rustflags: Rustflags,
1884     rustdocflags: Rustflags,
1885 }
1886
1887 impl Cargo {
1888     pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
1889         self.rustdocflags.arg(arg);
1890         self
1891     }
1892     pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1893         self.rustflags.arg(arg);
1894         self
1895     }
1896
1897     pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1898         self.command.arg(arg.as_ref());
1899         self
1900     }
1901
1902     pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1903     where
1904         I: IntoIterator<Item = S>,
1905         S: AsRef<OsStr>,
1906     {
1907         for arg in args {
1908             self.arg(arg.as_ref());
1909         }
1910         self
1911     }
1912
1913     pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1914         // These are managed through rustflag/rustdocflag interfaces.
1915         assert_ne!(key.as_ref(), "RUSTFLAGS");
1916         assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
1917         self.command.env(key.as_ref(), value.as_ref());
1918         self
1919     }
1920
1921     pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
1922         builder.add_rustc_lib_path(compiler, &mut self.command);
1923     }
1924
1925     pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
1926         self.command.current_dir(dir);
1927         self
1928     }
1929 }
1930
1931 impl From<Cargo> for Command {
1932     fn from(mut cargo: Cargo) -> Command {
1933         let rustflags = &cargo.rustflags.0;
1934         if !rustflags.is_empty() {
1935             cargo.command.env("RUSTFLAGS", rustflags);
1936         }
1937
1938         let rustdocflags = &cargo.rustdocflags.0;
1939         if !rustdocflags.is_empty() {
1940             cargo.command.env("RUSTDOCFLAGS", rustdocflags);
1941         }
1942
1943         cargo.command
1944     }
1945 }