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