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