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