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