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