]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Rollup merge of #98624 - davidtwco:translation-on-lints, r=compiler-errors
[rust.git] / src / bootstrap / builder.rs
1 use std::any::{type_name, Any};
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::env;
5 use std::ffi::{OsStr, OsString};
6 use std::fmt::{Debug, Write};
7 use std::fs::{self, File};
8 use std::hash::Hash;
9 use std::io::{BufRead, BufReader, ErrorKind};
10 use std::ops::Deref;
11 use std::path::{Component, Path, PathBuf};
12 use std::process::{Command, Stdio};
13 use std::time::{Duration, Instant};
14
15 use crate::cache::{Cache, Interned, INTERNER};
16 use crate::compile;
17 use crate::config::{SplitDebuginfo, TargetSelection};
18 use crate::dist;
19 use crate::doc;
20 use crate::flags::{Color, Subcommand};
21 use crate::install;
22 use crate::native;
23 use crate::run;
24 use crate::test;
25 use crate::tool::{self, SourceType};
26 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir, output, t};
27 use crate::EXTRA_CHECK_CFGS;
28 use crate::{check, Config};
29 use crate::{Build, CLang, DocTests, GitRepo, Mode};
30
31 pub use crate::Compiler;
32 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
33 use once_cell::sync::{Lazy, OnceCell};
34 use xz2::bufread::XzDecoder;
35
36 pub struct Builder<'a> {
37     pub build: &'a Build,
38     pub top_stage: u32,
39     pub kind: Kind,
40     cache: Cache,
41     stack: RefCell<Vec<Box<dyn Any>>>,
42     time_spent_on_dependencies: Cell<Duration>,
43     pub paths: Vec<PathBuf>,
44 }
45
46 impl<'a> Deref for Builder<'a> {
47     type Target = Build;
48
49     fn deref(&self) -> &Self::Target {
50         self.build
51     }
52 }
53
54 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
55     /// `PathBuf` when directories are created or to return a `Compiler` once
56     /// it's been assembled.
57     type Output: Clone;
58
59     /// Whether this step is run by default as part of its respective phase.
60     /// `true` here can still be overwritten by `should_run` calling `default_condition`.
61     const DEFAULT: bool = false;
62
63     /// If true, then this rule should be skipped if --target was specified, but --host was not
64     const ONLY_HOSTS: bool = false;
65
66     /// Primary function to execute this rule. Can call `builder.ensure()`
67     /// with other steps to run those.
68     fn run(self, builder: &Builder<'_>) -> Self::Output;
69
70     /// When bootstrap is passed a set of paths, this controls whether this rule
71     /// will execute. However, it does not get called in a "default" context
72     /// when we are not passed any paths; in that case, `make_run` is called
73     /// directly.
74     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
75
76     /// Builds up a "root" rule, either as a default rule or from a path passed
77     /// to us.
78     ///
79     /// When path is `None`, we are executing in a context where no paths were
80     /// passed. When `./x.py build` is run, for example, this rule could get
81     /// called if it is in the correct list below with a path of `None`.
82     fn make_run(_run: RunConfig<'_>) {
83         // It is reasonable to not have an implementation of make_run for rules
84         // who do not want to get called from the root context. This means that
85         // they are likely dependencies (e.g., sysroot creation) or similar, and
86         // as such calling them from ./x.py isn't logical.
87         unimplemented!()
88     }
89 }
90
91 pub struct RunConfig<'a> {
92     pub builder: &'a Builder<'a>,
93     pub target: TargetSelection,
94     pub paths: Vec<PathSet>,
95 }
96
97 impl RunConfig<'_> {
98     pub fn build_triple(&self) -> TargetSelection {
99         self.builder.build.build
100     }
101 }
102
103 struct StepDescription {
104     default: bool,
105     only_hosts: bool,
106     should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
107     make_run: fn(RunConfig<'_>),
108     name: &'static str,
109     kind: Kind,
110 }
111
112 #[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
113 pub struct TaskPath {
114     pub path: PathBuf,
115     pub kind: Option<Kind>,
116 }
117
118 impl TaskPath {
119     pub fn parse(path: impl Into<PathBuf>) -> TaskPath {
120         let mut kind = None;
121         let mut path = path.into();
122
123         let mut components = path.components();
124         if let Some(Component::Normal(os_str)) = components.next() {
125             if let Some(str) = os_str.to_str() {
126                 if let Some((found_kind, found_prefix)) = str.split_once("::") {
127                     if found_kind.is_empty() {
128                         panic!("empty kind in task path {}", path.display());
129                     }
130                     kind = Kind::parse(found_kind);
131                     assert!(kind.is_some());
132                     path = Path::new(found_prefix).join(components.as_path());
133                 }
134             }
135         }
136
137         TaskPath { path, kind }
138     }
139 }
140
141 impl Debug for TaskPath {
142     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143         if let Some(kind) = &self.kind {
144             write!(f, "{}::", kind.as_str())?;
145         }
146         write!(f, "{}", self.path.display())
147     }
148 }
149
150 /// Collection of paths used to match a task rule.
151 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
152 pub enum PathSet {
153     /// A collection of individual paths or aliases.
154     ///
155     /// These are generally matched as a path suffix. For example, a
156     /// command-line value of `std` will match if `library/std` is in the
157     /// set.
158     ///
159     /// NOTE: the paths within a set should always be aliases of one another.
160     /// For example, `src/librustdoc` and `src/tools/rustdoc` should be in the same set,
161     /// but `library/core` and `library/std` generally should not, unless there's no way (for that Step)
162     /// to build them separately.
163     Set(BTreeSet<TaskPath>),
164     /// A "suite" of paths.
165     ///
166     /// These can match as a path suffix (like `Set`), or as a prefix. For
167     /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
168     /// will match `src/test/ui`. A command-line value of `ui` would also
169     /// match `src/test/ui`.
170     Suite(TaskPath),
171 }
172
173 impl PathSet {
174     fn empty() -> PathSet {
175         PathSet::Set(BTreeSet::new())
176     }
177
178     fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
179         let mut set = BTreeSet::new();
180         set.insert(TaskPath { path: path.into(), kind: Some(kind) });
181         PathSet::Set(set)
182     }
183
184     fn has(&self, needle: &Path, module: Option<Kind>) -> bool {
185         match self {
186             PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
187             PathSet::Suite(suite) => Self::check(suite, needle, module),
188         }
189     }
190
191     // internal use only
192     fn check(p: &TaskPath, needle: &Path, module: Option<Kind>) -> bool {
193         if let (Some(p_kind), Some(kind)) = (&p.kind, module) {
194             p.path.ends_with(needle) && *p_kind == kind
195         } else {
196             p.path.ends_with(needle)
197         }
198     }
199
200     /// Return all `TaskPath`s in `Self` that contain any of the `needles`, removing the
201     /// matched needles.
202     ///
203     /// This is used for `StepDescription::krate`, which passes all matching crates at once to
204     /// `Step::make_run`, rather than calling it many times with a single crate.
205     /// See `tests.rs` for examples.
206     fn intersection_removing_matches(
207         &self,
208         needles: &mut Vec<&Path>,
209         module: Option<Kind>,
210     ) -> PathSet {
211         let mut check = |p| {
212             for (i, n) in needles.iter().enumerate() {
213                 let matched = Self::check(p, n, module);
214                 if matched {
215                     needles.remove(i);
216                     return true;
217                 }
218             }
219             false
220         };
221         match self {
222             PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
223             PathSet::Suite(suite) => {
224                 if check(suite) {
225                     self.clone()
226                 } else {
227                     PathSet::empty()
228                 }
229             }
230         }
231     }
232
233     /// A convenience wrapper for Steps which know they have no aliases and all their sets contain only a single path.
234     ///
235     /// This can be used with [`ShouldRun::krate`], [`ShouldRun::path`], or [`ShouldRun::alias`].
236     #[track_caller]
237     pub fn assert_single_path(&self) -> &TaskPath {
238         match self {
239             PathSet::Set(set) => {
240                 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
241                 set.iter().next().unwrap()
242             }
243             PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
244         }
245     }
246 }
247
248 impl StepDescription {
249     fn from<S: Step>(kind: Kind) -> StepDescription {
250         StepDescription {
251             default: S::DEFAULT,
252             only_hosts: S::ONLY_HOSTS,
253             should_run: S::should_run,
254             make_run: S::make_run,
255             name: std::any::type_name::<S>(),
256             kind,
257         }
258     }
259
260     fn maybe_run(&self, builder: &Builder<'_>, pathsets: Vec<PathSet>) {
261         if pathsets.iter().any(|set| self.is_excluded(builder, set)) {
262             return;
263         }
264
265         // Determine the targets participating in this rule.
266         let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
267
268         for target in targets {
269             let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
270             (self.make_run)(run);
271         }
272     }
273
274     fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
275         if builder.config.exclude.iter().any(|e| pathset.has(&e.path, e.kind)) {
276             println!("Skipping {:?} because it is excluded", pathset);
277             return true;
278         }
279
280         if !builder.config.exclude.is_empty() {
281             builder.verbose(&format!(
282                 "{:?} not skipped for {:?} -- not in {:?}",
283                 pathset, self.name, builder.config.exclude
284             ));
285         }
286         false
287     }
288
289     fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
290         let should_runs = v
291             .iter()
292             .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
293             .collect::<Vec<_>>();
294
295         // sanity checks on rules
296         for (desc, should_run) in v.iter().zip(&should_runs) {
297             assert!(
298                 !should_run.paths.is_empty(),
299                 "{:?} should have at least one pathset",
300                 desc.name
301             );
302         }
303
304         if paths.is_empty() || builder.config.include_default_paths {
305             for (desc, should_run) in v.iter().zip(&should_runs) {
306                 if desc.default && should_run.is_really_default() {
307                     for pathset in &should_run.paths {
308                         desc.maybe_run(builder, vec![pathset.clone()]);
309                     }
310                 }
311             }
312         }
313
314         // strip CurDir prefix if present
315         let mut paths: Vec<_> =
316             paths.into_iter().map(|p| p.strip_prefix(".").unwrap_or(p)).collect();
317
318         // Handle all test suite paths.
319         // (This is separate from the loop below to avoid having to handle multiple paths in `is_suite_path` somehow.)
320         paths.retain(|path| {
321             for (desc, should_run) in v.iter().zip(&should_runs) {
322                 if let Some(suite) = should_run.is_suite_path(&path) {
323                     desc.maybe_run(builder, vec![suite.clone()]);
324                     return false;
325                 }
326             }
327             true
328         });
329
330         if paths.is_empty() {
331             return;
332         }
333
334         // Handle all PathSets.
335         for (desc, should_run) in v.iter().zip(&should_runs) {
336             let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
337             if !pathsets.is_empty() {
338                 desc.maybe_run(builder, pathsets);
339             }
340         }
341
342         if !paths.is_empty() {
343             eprintln!("error: no `{}` rules matched {:?}", builder.kind.as_str(), paths,);
344             eprintln!(
345                 "help: run `x.py {} --help --verbose` to show a list of available paths",
346                 builder.kind.as_str()
347             );
348             eprintln!(
349                 "note: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
350             );
351             #[cfg(not(test))]
352             std::process::exit(1);
353             #[cfg(test)]
354             // so we can use #[should_panic]
355             panic!()
356         }
357     }
358 }
359
360 enum ReallyDefault<'a> {
361     Bool(bool),
362     Lazy(Lazy<bool, Box<dyn Fn() -> bool + 'a>>),
363 }
364
365 pub struct ShouldRun<'a> {
366     pub builder: &'a Builder<'a>,
367     kind: Kind,
368
369     // use a BTreeSet to maintain sort order
370     paths: BTreeSet<PathSet>,
371
372     // If this is a default rule, this is an additional constraint placed on
373     // its run. Generally something like compiler docs being enabled.
374     is_really_default: ReallyDefault<'a>,
375 }
376
377 impl<'a> ShouldRun<'a> {
378     fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
379         ShouldRun {
380             builder,
381             kind,
382             paths: BTreeSet::new(),
383             is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
384         }
385     }
386
387     pub fn default_condition(mut self, cond: bool) -> Self {
388         self.is_really_default = ReallyDefault::Bool(cond);
389         self
390     }
391
392     pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
393         self.is_really_default = ReallyDefault::Lazy(Lazy::new(lazy_cond));
394         self
395     }
396
397     pub fn is_really_default(&self) -> bool {
398         match &self.is_really_default {
399             ReallyDefault::Bool(val) => *val,
400             ReallyDefault::Lazy(lazy) => *lazy.deref(),
401         }
402     }
403
404     /// Indicates it should run if the command-line selects the given crate or
405     /// any of its (local) dependencies.
406     ///
407     /// Compared to `krate`, this treats the dependencies as aliases for the
408     /// same job. Generally it is preferred to use `krate`, and treat each
409     /// individual path separately. For example `./x.py test src/liballoc`
410     /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
411     /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
412     /// `all_krates` should probably be removed at some point.
413     pub fn all_krates(mut self, name: &str) -> Self {
414         let mut set = BTreeSet::new();
415         for krate in self.builder.in_tree_crates(name, None) {
416             let path = krate.local_path(self.builder);
417             set.insert(TaskPath { path, kind: Some(self.kind) });
418         }
419         self.paths.insert(PathSet::Set(set));
420         self
421     }
422
423     /// Indicates it should run if the command-line selects the given crate or
424     /// any of its (local) dependencies.
425     ///
426     /// `make_run` will be called a single time with all matching command-line paths.
427     pub fn krate(mut self, name: &str) -> Self {
428         for krate in self.builder.in_tree_crates(name, None) {
429             let path = krate.local_path(self.builder);
430             self.paths.insert(PathSet::one(path, self.kind));
431         }
432         self
433     }
434
435     // single alias, which does not correspond to any on-disk path
436     pub fn alias(mut self, alias: &str) -> Self {
437         assert!(
438             !self.builder.src.join(alias).exists(),
439             "use `builder.path()` for real paths: {}",
440             alias
441         );
442         self.paths.insert(PathSet::Set(
443             std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
444         ));
445         self
446     }
447
448     // single, non-aliased path
449     pub fn path(self, path: &str) -> Self {
450         self.paths(&[path])
451     }
452
453     // multiple aliases for the same job
454     pub fn paths(mut self, paths: &[&str]) -> Self {
455         self.paths.insert(PathSet::Set(
456             paths
457                 .iter()
458                 .map(|p| {
459                     // FIXME(#96188): make sure this is actually a path.
460                     // This currently breaks for paths within submodules.
461                     //assert!(
462                     //    self.builder.src.join(p).exists(),
463                     //    "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {}",
464                     //    p
465                     //);
466                     TaskPath { path: p.into(), kind: Some(self.kind) }
467                 })
468                 .collect(),
469         ));
470         self
471     }
472
473     /// Handles individual files (not directories) within a test suite.
474     fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
475         self.paths.iter().find(|pathset| match pathset {
476             PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
477             PathSet::Set(_) => false,
478         })
479     }
480
481     pub fn suite_path(mut self, suite: &str) -> Self {
482         self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
483         self
484     }
485
486     // allows being more explicit about why should_run in Step returns the value passed to it
487     pub fn never(mut self) -> ShouldRun<'a> {
488         self.paths.insert(PathSet::empty());
489         self
490     }
491
492     /// Given a set of requested paths, return the subset which match the Step for this `ShouldRun`,
493     /// removing the matches from `paths`.
494     ///
495     /// NOTE: this returns multiple PathSets to allow for the possibility of multiple units of work
496     /// within the same step. For example, `test::Crate` allows testing multiple crates in the same
497     /// cargo invocation, which are put into separate sets because they aren't aliases.
498     ///
499     /// The reason we return PathSet instead of PathBuf is to allow for aliases that mean the same thing
500     /// (for now, just `all_krates` and `paths`, but we may want to add an `aliases` function in the future?)
501     fn pathset_for_paths_removing_matches(
502         &self,
503         paths: &mut Vec<&Path>,
504         kind: Kind,
505     ) -> Vec<PathSet> {
506         let mut sets = vec![];
507         for pathset in &self.paths {
508             let subset = pathset.intersection_removing_matches(paths, Some(kind));
509             if subset != PathSet::empty() {
510                 sets.push(subset);
511             }
512         }
513         sets
514     }
515 }
516
517 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
518 pub enum Kind {
519     Build,
520     Check,
521     Clippy,
522     Fix,
523     Format,
524     Test,
525     Bench,
526     Doc,
527     Clean,
528     Dist,
529     Install,
530     Run,
531     Setup,
532 }
533
534 impl Kind {
535     pub fn parse(string: &str) -> Option<Kind> {
536         // these strings, including the one-letter aliases, must match the x.py help text
537         Some(match string {
538             "build" | "b" => Kind::Build,
539             "check" | "c" => Kind::Check,
540             "clippy" => Kind::Clippy,
541             "fix" => Kind::Fix,
542             "fmt" => Kind::Format,
543             "test" | "t" => Kind::Test,
544             "bench" => Kind::Bench,
545             "doc" | "d" => Kind::Doc,
546             "clean" => Kind::Clean,
547             "dist" => Kind::Dist,
548             "install" => Kind::Install,
549             "run" | "r" => Kind::Run,
550             "setup" => Kind::Setup,
551             _ => return None,
552         })
553     }
554
555     pub fn as_str(&self) -> &'static str {
556         match self {
557             Kind::Build => "build",
558             Kind::Check => "check",
559             Kind::Clippy => "clippy",
560             Kind::Fix => "fix",
561             Kind::Format => "fmt",
562             Kind::Test => "test",
563             Kind::Bench => "bench",
564             Kind::Doc => "doc",
565             Kind::Clean => "clean",
566             Kind::Dist => "dist",
567             Kind::Install => "install",
568             Kind::Run => "run",
569             Kind::Setup => "setup",
570         }
571     }
572 }
573
574 impl<'a> Builder<'a> {
575     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
576         macro_rules! describe {
577             ($($rule:ty),+ $(,)?) => {{
578                 vec![$(StepDescription::from::<$rule>(kind)),+]
579             }};
580         }
581         match kind {
582             Kind::Build => describe!(
583                 compile::Std,
584                 compile::Assemble,
585                 compile::CodegenBackend,
586                 compile::StartupObjects,
587                 tool::BuildManifest,
588                 tool::Rustbook,
589                 tool::ErrorIndex,
590                 tool::UnstableBookGen,
591                 tool::Tidy,
592                 tool::Linkchecker,
593                 tool::CargoTest,
594                 tool::Compiletest,
595                 tool::RemoteTestServer,
596                 tool::RemoteTestClient,
597                 tool::RustInstaller,
598                 tool::Cargo,
599                 tool::Rls,
600                 tool::RustAnalyzer,
601                 tool::RustDemangler,
602                 tool::Rustdoc,
603                 tool::Clippy,
604                 tool::CargoClippy,
605                 native::Llvm,
606                 native::Sanitizers,
607                 tool::Rustfmt,
608                 tool::Miri,
609                 tool::CargoMiri,
610                 native::Lld,
611                 native::CrtBeginEnd
612             ),
613             Kind::Check | Kind::Clippy | Kind::Fix => describe!(
614                 check::Std,
615                 check::Rustc,
616                 check::Rustdoc,
617                 check::CodegenBackend,
618                 check::Clippy,
619                 check::Miri,
620                 check::Rls,
621                 check::Rustfmt,
622                 check::Bootstrap
623             ),
624             Kind::Test => describe!(
625                 crate::toolstate::ToolStateCheck,
626                 test::ExpandYamlAnchors,
627                 test::Tidy,
628                 test::Ui,
629                 test::RunPassValgrind,
630                 test::MirOpt,
631                 test::Codegen,
632                 test::CodegenUnits,
633                 test::Assembly,
634                 test::Incremental,
635                 test::Debuginfo,
636                 test::UiFullDeps,
637                 test::Rustdoc,
638                 test::Pretty,
639                 test::Crate,
640                 test::CrateLibrustc,
641                 test::CrateRustdoc,
642                 test::CrateRustdocJsonTypes,
643                 test::Linkcheck,
644                 test::TierCheck,
645                 test::Cargotest,
646                 test::Cargo,
647                 test::Rls,
648                 test::ErrorIndex,
649                 test::Distcheck,
650                 test::RunMakeFullDeps,
651                 test::Nomicon,
652                 test::Reference,
653                 test::RustdocBook,
654                 test::RustByExample,
655                 test::TheBook,
656                 test::UnstableBook,
657                 test::RustcBook,
658                 test::LintDocs,
659                 test::RustcGuide,
660                 test::EmbeddedBook,
661                 test::EditionGuide,
662                 test::Rustfmt,
663                 test::Miri,
664                 test::Clippy,
665                 test::RustDemangler,
666                 test::CompiletestTest,
667                 test::RustdocJSStd,
668                 test::RustdocJSNotStd,
669                 test::RustdocGUI,
670                 test::RustdocTheme,
671                 test::RustdocUi,
672                 test::RustdocJson,
673                 test::HtmlCheck,
674                 // Run bootstrap close to the end as it's unlikely to fail
675                 test::Bootstrap,
676                 // Run run-make last, since these won't pass without make on Windows
677                 test::RunMake,
678             ),
679             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
680             Kind::Doc => describe!(
681                 doc::UnstableBook,
682                 doc::UnstableBookGen,
683                 doc::TheBook,
684                 doc::Standalone,
685                 doc::Std,
686                 doc::Rustc,
687                 doc::Rustdoc,
688                 doc::Rustfmt,
689                 doc::ErrorIndex,
690                 doc::Nomicon,
691                 doc::Reference,
692                 doc::RustdocBook,
693                 doc::RustByExample,
694                 doc::RustcBook,
695                 doc::CargoBook,
696                 doc::Clippy,
697                 doc::Miri,
698                 doc::EmbeddedBook,
699                 doc::EditionGuide,
700             ),
701             Kind::Dist => describe!(
702                 dist::Docs,
703                 dist::RustcDocs,
704                 dist::Mingw,
705                 dist::Rustc,
706                 dist::Std,
707                 dist::RustcDev,
708                 dist::Analysis,
709                 dist::Src,
710                 dist::Cargo,
711                 dist::Rls,
712                 dist::RustAnalyzer,
713                 dist::Rustfmt,
714                 dist::RustDemangler,
715                 dist::Clippy,
716                 dist::Miri,
717                 dist::LlvmTools,
718                 dist::RustDev,
719                 dist::Extended,
720                 // It seems that PlainSourceTarball somehow changes how some of the tools
721                 // perceive their dependencies (see #93033) which would invalidate fingerprints
722                 // and force us to rebuild tools after vendoring dependencies.
723                 // To work around this, create the Tarball after building all the tools.
724                 dist::PlainSourceTarball,
725                 dist::BuildManifest,
726                 dist::ReproducibleArtifacts,
727             ),
728             Kind::Install => describe!(
729                 install::Docs,
730                 install::Std,
731                 install::Cargo,
732                 install::Rls,
733                 install::RustAnalyzer,
734                 install::Rustfmt,
735                 install::RustDemangler,
736                 install::Clippy,
737                 install::Miri,
738                 install::Analysis,
739                 install::Src,
740                 install::Rustc
741             ),
742             Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest, run::BumpStage0),
743             // These commands either don't use paths, or they're special-cased in Build::build()
744             Kind::Clean | Kind::Format | Kind::Setup => vec![],
745         }
746     }
747
748     pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
749         let step_descriptions = Builder::get_step_descriptions(kind);
750         if step_descriptions.is_empty() {
751             return None;
752         }
753
754         let builder = Self::new_internal(build, kind, vec![]);
755         let builder = &builder;
756         // The "build" kind here is just a placeholder, it will be replaced with something else in
757         // the following statement.
758         let mut should_run = ShouldRun::new(builder, Kind::Build);
759         for desc in step_descriptions {
760             should_run.kind = desc.kind;
761             should_run = (desc.should_run)(should_run);
762         }
763         let mut help = String::from("Available paths:\n");
764         let mut add_path = |path: &Path| {
765             t!(write!(help, "    ./x.py {} {}\n", kind.as_str(), path.display()));
766         };
767         for pathset in should_run.paths {
768             match pathset {
769                 PathSet::Set(set) => {
770                     for path in set {
771                         add_path(&path.path);
772                     }
773                 }
774                 PathSet::Suite(path) => {
775                     add_path(&path.path.join("..."));
776                 }
777             }
778         }
779         Some(help)
780     }
781
782     fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
783         Builder {
784             build,
785             top_stage: build.config.stage,
786             kind,
787             cache: Cache::new(),
788             stack: RefCell::new(Vec::new()),
789             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
790             paths,
791         }
792     }
793
794     pub fn new(build: &Build) -> Builder<'_> {
795         let (kind, paths) = match build.config.cmd {
796             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
797             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
798             Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
799             Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
800             Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
801             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
802             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
803             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
804             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
805             Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
806             Subcommand::Format { .. } => (Kind::Format, &[][..]),
807             Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
808                 panic!()
809             }
810         };
811
812         Self::new_internal(build, kind, paths.to_owned())
813     }
814
815     pub fn execute_cli(&self) {
816         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
817     }
818
819     pub fn default_doc(&self, paths: &[PathBuf]) {
820         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
821     }
822
823     /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
824     pub fn doc_rust_lang_org_channel(&self) -> String {
825         let channel = match &*self.config.channel {
826             "stable" => &self.version,
827             "beta" => "beta",
828             "nightly" | "dev" => "nightly",
829             // custom build of rustdoc maybe? link to the latest stable docs just in case
830             _ => "stable",
831         };
832         "https://doc.rust-lang.org/".to_owned() + channel
833     }
834
835     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
836         StepDescription::run(v, self, paths);
837     }
838
839     /// Modifies the interpreter section of 'fname' to fix the dynamic linker,
840     /// or the RPATH section, to fix the dynamic library search path
841     ///
842     /// This is only required on NixOS and uses the PatchELF utility to
843     /// change the interpreter/RPATH of ELF executables.
844     ///
845     /// Please see https://nixos.org/patchelf.html for more information
846     pub(crate) fn fix_bin_or_dylib(&self, fname: &Path) {
847         // FIXME: cache NixOS detection?
848         match Command::new("uname").arg("-s").stderr(Stdio::inherit()).output() {
849             Err(_) => return,
850             Ok(output) if !output.status.success() => return,
851             Ok(output) => {
852                 let mut s = output.stdout;
853                 if s.last() == Some(&b'\n') {
854                     s.pop();
855                 }
856                 if s != b"Linux" {
857                     return;
858                 }
859             }
860         }
861
862         // If the user has asked binaries to be patched for Nix, then
863         // don't check for NixOS or `/lib`, just continue to the patching.
864         // NOTE: this intentionally comes after the Linux check:
865         // - patchelf only works with ELF files, so no need to run it on Mac or Windows
866         // - On other Unix systems, there is no stable syscall interface, so Nix doesn't manage the global libc.
867         if !self.config.patch_binaries_for_nix {
868             // Use `/etc/os-release` instead of `/etc/NIXOS`.
869             // The latter one does not exist on NixOS when using tmpfs as root.
870             const NIX_IDS: &[&str] = &["ID=nixos", "ID='nixos'", "ID=\"nixos\""];
871             let os_release = match File::open("/etc/os-release") {
872                 Err(e) if e.kind() == ErrorKind::NotFound => return,
873                 Err(e) => panic!("failed to access /etc/os-release: {}", e),
874                 Ok(f) => f,
875             };
876             if !BufReader::new(os_release).lines().any(|l| NIX_IDS.contains(&t!(l).trim())) {
877                 return;
878             }
879             if Path::new("/lib").exists() {
880                 return;
881             }
882         }
883
884         // At this point we're pretty sure the user is running NixOS or using Nix
885         println!("info: you seem to be using Nix. Attempting to patch {}", fname.display());
886
887         // Only build `.nix-deps` once.
888         static NIX_DEPS_DIR: OnceCell<PathBuf> = OnceCell::new();
889         let mut nix_build_succeeded = true;
890         let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
891             // Run `nix-build` to "build" each dependency (which will likely reuse
892             // the existing `/nix/store` copy, or at most download a pre-built copy).
893             //
894             // Importantly, we create a gc-root called `.nix-deps` in the `build/`
895             // directory, but still reference the actual `/nix/store` path in the rpath
896             // as it makes it significantly more robust against changes to the location of
897             // the `.nix-deps` location.
898             //
899             // bintools: Needed for the path of `ld-linux.so` (via `nix-support/dynamic-linker`).
900             // zlib: Needed as a system dependency of `libLLVM-*.so`.
901             // patchelf: Needed for patching ELF binaries (see doc comment above).
902             let nix_deps_dir = self.out.join(".nix-deps");
903             const NIX_EXPR: &str = "
904             with (import <nixpkgs> {});
905             symlinkJoin {
906                 name = \"rust-stage0-dependencies\";
907                 paths = [
908                     zlib
909                     patchelf
910                     stdenv.cc.bintools
911                 ];
912             }
913             ";
914             nix_build_succeeded = self.try_run(Command::new("nix-build").args(&[
915                 Path::new("-E"),
916                 Path::new(NIX_EXPR),
917                 Path::new("-o"),
918                 &nix_deps_dir,
919             ]));
920             nix_deps_dir
921         });
922         if !nix_build_succeeded {
923             return;
924         }
925
926         let mut patchelf = Command::new(nix_deps_dir.join("bin/patchelf"));
927         let rpath_entries = {
928             // ORIGIN is a relative default, all binary and dynamic libraries we ship
929             // appear to have this (even when `../lib` is redundant).
930             // NOTE: there are only two paths here, delimited by a `:`
931             let mut entries = OsString::from("$ORIGIN/../lib:");
932             entries.push(t!(fs::canonicalize(nix_deps_dir)));
933             entries.push("/lib");
934             entries
935         };
936         patchelf.args(&[OsString::from("--set-rpath"), rpath_entries]);
937         if !fname.extension().map_or(false, |ext| ext == "so") {
938             // Finally, set the corret .interp for binaries
939             let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
940             // FIXME: can we support utf8 here? `args` doesn't accept Vec<u8>, only OsString ...
941             let dynamic_linker = t!(String::from_utf8(t!(fs::read(dynamic_linker_path))));
942             patchelf.args(&["--set-interpreter", dynamic_linker.trim_end()]);
943         }
944
945         self.try_run(patchelf.arg(fname));
946     }
947
948     pub(crate) fn download_component(&self, url: &str, dest_path: &Path, help_on_error: &str) {
949         // Use a temporary file in case we crash while downloading, to avoid a corrupt download in cache/.
950         let tempfile = self.tempdir().join(dest_path.file_name().unwrap());
951         // While bootstrap itself only supports http and https downloads, downstream forks might
952         // need to download components from other protocols. The match allows them adding more
953         // protocols without worrying about merge conficts if we change the HTTP implementation.
954         match url.split_once("://").map(|(proto, _)| proto) {
955             Some("http") | Some("https") => {
956                 self.download_http_with_retries(&tempfile, url, help_on_error)
957             }
958             Some(other) => panic!("unsupported protocol {other} in {url}"),
959             None => panic!("no protocol in {url}"),
960         }
961         t!(std::fs::rename(&tempfile, dest_path));
962     }
963
964     fn download_http_with_retries(&self, tempfile: &Path, url: &str, help_on_error: &str) {
965         println!("downloading {}", url);
966         // Try curl. If that fails and we are on windows, fallback to PowerShell.
967         let mut curl = Command::new("curl");
968         curl.args(&[
969             "-#",
970             "-y",
971             "30",
972             "-Y",
973             "10", // timeout if speed is < 10 bytes/sec for > 30 seconds
974             "--connect-timeout",
975             "30", // timeout if cannot connect within 30 seconds
976             "--retry",
977             "3",
978             "-Sf",
979             "-o",
980         ]);
981         curl.arg(tempfile);
982         curl.arg(url);
983         if !self.check_run(&mut curl) {
984             if self.build.build.contains("windows-msvc") {
985                 println!("Fallback to PowerShell");
986                 for _ in 0..3 {
987                     if self.try_run(Command::new("PowerShell.exe").args(&[
988                         "/nologo",
989                         "-Command",
990                         "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
991                         &format!(
992                             "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
993                             url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
994                         ),
995                     ])) {
996                         return;
997                     }
998                     println!("\nspurious failure, trying again");
999                 }
1000             }
1001             if !help_on_error.is_empty() {
1002                 eprintln!("{}", help_on_error);
1003             }
1004             std::process::exit(1);
1005         }
1006     }
1007
1008     pub(crate) fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) {
1009         println!("extracting {} to {}", tarball.display(), dst.display());
1010         if !dst.exists() {
1011             t!(fs::create_dir_all(dst));
1012         }
1013
1014         // `tarball` ends with `.tar.xz`; strip that suffix
1015         // example: `rust-dev-nightly-x86_64-unknown-linux-gnu`
1016         let uncompressed_filename =
1017             Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
1018         let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
1019
1020         // decompress the file
1021         let data = t!(File::open(tarball));
1022         let decompressor = XzDecoder::new(BufReader::new(data));
1023
1024         let mut tar = tar::Archive::new(decompressor);
1025         for member in t!(tar.entries()) {
1026             let mut member = t!(member);
1027             let original_path = t!(member.path()).into_owned();
1028             // skip the top-level directory
1029             if original_path == directory_prefix {
1030                 continue;
1031             }
1032             let mut short_path = t!(original_path.strip_prefix(directory_prefix));
1033             if !short_path.starts_with(pattern) {
1034                 continue;
1035             }
1036             short_path = t!(short_path.strip_prefix(pattern));
1037             let dst_path = dst.join(short_path);
1038             self.verbose(&format!("extracting {} to {}", original_path.display(), dst.display()));
1039             if !t!(member.unpack_in(dst)) {
1040                 panic!("path traversal attack ??");
1041             }
1042             let src_path = dst.join(original_path);
1043             if src_path.is_dir() && dst_path.exists() {
1044                 continue;
1045             }
1046             t!(fs::rename(src_path, dst_path));
1047         }
1048         t!(fs::remove_dir_all(dst.join(directory_prefix)));
1049     }
1050
1051     /// Returns whether the SHA256 checksum of `path` matches `expected`.
1052     pub(crate) fn verify(&self, path: &Path, expected: &str) -> bool {
1053         use sha2::Digest;
1054
1055         self.verbose(&format!("verifying {}", path.display()));
1056         let mut hasher = sha2::Sha256::new();
1057         // FIXME: this is ok for rustfmt (4.1 MB large at time of writing), but it seems memory-intensive for rustc and larger components.
1058         // Consider using streaming IO instead?
1059         let contents = if self.config.dry_run { vec![] } else { t!(fs::read(path)) };
1060         hasher.update(&contents);
1061         let found = hex::encode(hasher.finalize().as_slice());
1062         let verified = found == expected;
1063         if !verified && !self.config.dry_run {
1064             println!(
1065                 "invalid checksum: \n\
1066                 found:    {found}\n\
1067                 expected: {expected}",
1068             );
1069         }
1070         return verified;
1071     }
1072
1073     /// Obtain a compiler at a given stage and for a given host. Explicitly does
1074     /// not take `Compiler` since all `Compiler` instances are meant to be
1075     /// obtained through this function, since it ensures that they are valid
1076     /// (i.e., built and assembled).
1077     pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1078         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
1079     }
1080
1081     /// Similar to `compiler`, except handles the full-bootstrap option to
1082     /// silently use the stage1 compiler instead of a stage2 compiler if one is
1083     /// requested.
1084     ///
1085     /// Note that this does *not* have the side effect of creating
1086     /// `compiler(stage, host)`, unlike `compiler` above which does have such
1087     /// a side effect. The returned compiler here can only be used to compile
1088     /// new artifacts, it can't be used to rely on the presence of a particular
1089     /// sysroot.
1090     ///
1091     /// See `force_use_stage1` for documentation on what each argument is.
1092     pub fn compiler_for(
1093         &self,
1094         stage: u32,
1095         host: TargetSelection,
1096         target: TargetSelection,
1097     ) -> Compiler {
1098         if self.build.force_use_stage1(Compiler { stage, host }, target) {
1099             self.compiler(1, self.config.build)
1100         } else {
1101             self.compiler(stage, host)
1102         }
1103     }
1104
1105     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
1106         self.ensure(compile::Sysroot { compiler })
1107     }
1108
1109     /// Returns the libdir where the standard library and other artifacts are
1110     /// found for a compiler's sysroot.
1111     pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
1112         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1113         struct Libdir {
1114             compiler: Compiler,
1115             target: TargetSelection,
1116         }
1117         impl Step for Libdir {
1118             type Output = Interned<PathBuf>;
1119
1120             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1121                 run.never()
1122             }
1123
1124             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
1125                 let lib = builder.sysroot_libdir_relative(self.compiler);
1126                 let sysroot = builder
1127                     .sysroot(self.compiler)
1128                     .join(lib)
1129                     .join("rustlib")
1130                     .join(self.target.triple)
1131                     .join("lib");
1132                 // Avoid deleting the rustlib/ directory we just copied
1133                 // (in `impl Step for Sysroot`).
1134                 if !builder.download_rustc() {
1135                     let _ = fs::remove_dir_all(&sysroot);
1136                     t!(fs::create_dir_all(&sysroot));
1137                 }
1138                 INTERNER.intern_path(sysroot)
1139             }
1140         }
1141         self.ensure(Libdir { compiler, target })
1142     }
1143
1144     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1145         self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1146     }
1147
1148     /// Returns the compiler's libdir where it stores the dynamic libraries that
1149     /// it itself links against.
1150     ///
1151     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
1152     /// Windows.
1153     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1154         if compiler.is_snapshot(self) {
1155             self.rustc_snapshot_libdir()
1156         } else {
1157             match self.config.libdir_relative() {
1158                 Some(relative_libdir) if compiler.stage >= 1 => {
1159                     self.sysroot(compiler).join(relative_libdir)
1160                 }
1161                 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1162             }
1163         }
1164     }
1165
1166     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
1167     /// it itself links against.
1168     ///
1169     /// For example this returns `lib` on Unix and `bin` on
1170     /// Windows.
1171     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1172         if compiler.is_snapshot(self) {
1173             libdir(self.config.build).as_ref()
1174         } else {
1175             match self.config.libdir_relative() {
1176                 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1177                 _ => libdir(compiler.host).as_ref(),
1178             }
1179         }
1180     }
1181
1182     /// Returns the compiler's relative libdir where the standard library and other artifacts are
1183     /// found for a compiler's sysroot.
1184     ///
1185     /// For example this returns `lib` on Unix and Windows.
1186     pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1187         match self.config.libdir_relative() {
1188             Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1189             _ if compiler.stage == 0 => &self.build.initial_libdir,
1190             _ => Path::new("lib"),
1191         }
1192     }
1193
1194     pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1195         let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1196
1197         // Ensure that the downloaded LLVM libraries can be found.
1198         if self.config.llvm_from_ci {
1199             let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
1200             dylib_dirs.push(ci_llvm_lib);
1201         }
1202
1203         dylib_dirs
1204     }
1205
1206     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1207     /// library lookup path.
1208     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
1209         // Windows doesn't need dylib path munging because the dlls for the
1210         // compiler live next to the compiler and the system will find them
1211         // automatically.
1212         if cfg!(windows) {
1213             return;
1214         }
1215
1216         add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1217     }
1218
1219     /// Gets a path to the compiler specified.
1220     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1221         if compiler.is_snapshot(self) {
1222             self.initial_rustc.clone()
1223         } else {
1224             self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1225         }
1226     }
1227
1228     /// Gets the paths to all of the compiler's codegen backends.
1229     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1230         fs::read_dir(self.sysroot_codegen_backends(compiler))
1231             .into_iter()
1232             .flatten()
1233             .filter_map(Result::ok)
1234             .map(|entry| entry.path())
1235     }
1236
1237     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
1238         self.ensure(tool::Rustdoc { compiler })
1239     }
1240
1241     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
1242         let mut cmd = Command::new(&self.bootstrap_out.join("rustdoc"));
1243         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1244             .env("RUSTC_SYSROOT", self.sysroot(compiler))
1245             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1246             // equivalently to rustc.
1247             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1248             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1249             .env("RUSTDOC_REAL", self.rustdoc(compiler))
1250             .env("RUSTC_BOOTSTRAP", "1");
1251
1252         cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1253
1254         if self.config.deny_warnings {
1255             cmd.arg("-Dwarnings");
1256         }
1257         cmd.arg("-Znormalize-docs");
1258
1259         // Remove make-related flags that can cause jobserver problems.
1260         cmd.env_remove("MAKEFLAGS");
1261         cmd.env_remove("MFLAGS");
1262
1263         if let Some(linker) = self.linker(compiler.host) {
1264             cmd.env("RUSTDOC_LINKER", linker);
1265         }
1266         if self.is_fuse_ld_lld(compiler.host) {
1267             cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
1268         }
1269         cmd
1270     }
1271
1272     /// Return the path to `llvm-config` for the target, if it exists.
1273     ///
1274     /// Note that this returns `None` if LLVM is disabled, or if we're in a
1275     /// check build or dry-run, where there's no need to build all of LLVM.
1276     fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1277         if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
1278             let llvm_config = self.ensure(native::Llvm { target });
1279             if llvm_config.is_file() {
1280                 return Some(llvm_config);
1281             }
1282         }
1283         None
1284     }
1285
1286     /// Convenience wrapper to allow `builder.llvm_link_shared()` instead of `builder.config.llvm_link_shared(&builder)`.
1287     pub(crate) fn llvm_link_shared(&self) -> bool {
1288         Config::llvm_link_shared(self)
1289     }
1290
1291     pub(crate) fn download_rustc(&self) -> bool {
1292         Config::download_rustc(self)
1293     }
1294
1295     pub(crate) fn initial_rustfmt(&self) -> Option<PathBuf> {
1296         Config::initial_rustfmt(self)
1297     }
1298
1299     /// Prepares an invocation of `cargo` to be run.
1300     ///
1301     /// This will create a `Command` that represents a pending execution of
1302     /// Cargo. This cargo will be configured to use `compiler` as the actual
1303     /// rustc compiler, its output will be scoped by `mode`'s output directory,
1304     /// it will pass the `--target` flag for the specified `target`, and will be
1305     /// executing the Cargo command `cmd`.
1306     pub fn cargo(
1307         &self,
1308         compiler: Compiler,
1309         mode: Mode,
1310         source_type: SourceType,
1311         target: TargetSelection,
1312         cmd: &str,
1313     ) -> Cargo {
1314         let mut cargo = Command::new(&self.initial_cargo);
1315         let out_dir = self.stage_out(compiler, mode);
1316
1317         // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
1318         // so we need to explicitly clear out if they've been updated.
1319         for backend in self.codegen_backends(compiler) {
1320             self.clear_if_dirty(&out_dir, &backend);
1321         }
1322
1323         if cmd == "doc" || cmd == "rustdoc" {
1324             let my_out = match mode {
1325                 // This is the intended out directory for compiler documentation.
1326                 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
1327                 Mode::Std => out_dir.join(target.triple).join("doc"),
1328                 _ => panic!("doc mode {:?} not expected", mode),
1329             };
1330             let rustdoc = self.rustdoc(compiler);
1331             self.clear_if_dirty(&my_out, &rustdoc);
1332         }
1333
1334         cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
1335
1336         let profile_var = |name: &str| {
1337             let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
1338             format!("CARGO_PROFILE_{}_{}", profile, name)
1339         };
1340
1341         // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
1342         // needs to not accidentally link to libLLVM in stage0/lib.
1343         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
1344         if let Some(e) = env::var_os(util::dylib_path_var()) {
1345             cargo.env("REAL_LIBRARY_PATH", e);
1346         }
1347
1348         // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
1349         // from out of tree it shouldn't matter, since x.py is only used for
1350         // building in-tree.
1351         let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
1352         match self.build.config.color {
1353             Color::Always => {
1354                 cargo.arg("--color=always");
1355                 for log in &color_logs {
1356                     cargo.env(log, "always");
1357                 }
1358             }
1359             Color::Never => {
1360                 cargo.arg("--color=never");
1361                 for log in &color_logs {
1362                     cargo.env(log, "never");
1363                 }
1364             }
1365             Color::Auto => {} // nothing to do
1366         }
1367
1368         if cmd != "install" {
1369             cargo.arg("--target").arg(target.rustc_target_arg());
1370         } else {
1371             assert_eq!(target, compiler.host);
1372         }
1373
1374         // Set a flag for `check`/`clippy`/`fix`, so that certain build
1375         // scripts can do less work (i.e. not building/requiring LLVM).
1376         if cmd == "check" || cmd == "clippy" || cmd == "fix" {
1377             // If we've not yet built LLVM, or it's stale, then bust
1378             // the rustc_llvm cache. That will always work, even though it
1379             // may mean that on the next non-check build we'll need to rebuild
1380             // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
1381             // of work comparatively, and we'd likely need to rebuild it anyway,
1382             // so that's okay.
1383             if crate::native::prebuilt_llvm_config(self, target).is_err() {
1384                 cargo.env("RUST_CHECK", "1");
1385             }
1386         }
1387
1388         let stage = if compiler.stage == 0 && self.local_rebuild {
1389             // Assume the local-rebuild rustc already has stage1 features.
1390             1
1391         } else {
1392             compiler.stage
1393         };
1394
1395         let mut rustflags = Rustflags::new(target);
1396         if stage != 0 {
1397             if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
1398                 cargo.args(s.split_whitespace());
1399             }
1400             rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
1401         } else {
1402             if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
1403                 cargo.args(s.split_whitespace());
1404             }
1405             rustflags.env("RUSTFLAGS_BOOTSTRAP");
1406             if cmd == "clippy" {
1407                 // clippy overwrites sysroot if we pass it to cargo.
1408                 // Pass it directly to clippy instead.
1409                 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
1410                 // so it has no way of knowing the sysroot.
1411                 rustflags.arg("--sysroot");
1412                 rustflags.arg(
1413                     self.sysroot(compiler)
1414                         .as_os_str()
1415                         .to_str()
1416                         .expect("sysroot must be valid UTF-8"),
1417                 );
1418                 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
1419                 cargo.arg("-Zunstable-options");
1420                 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
1421                 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
1422                 let output = host_version.and_then(|output| {
1423                     if output.status.success() {
1424                         Ok(output)
1425                     } else {
1426                         Err(())
1427                     }
1428                 }).unwrap_or_else(|_| {
1429                     eprintln!(
1430                         "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
1431                     );
1432                     eprintln!("help: try `rustup component add clippy`");
1433                     std::process::exit(1);
1434                 });
1435                 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
1436                     rustflags.arg("--cfg=bootstrap");
1437                 }
1438             } else {
1439                 rustflags.arg("--cfg=bootstrap");
1440             }
1441         }
1442
1443         let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
1444             Some(setting) => {
1445                 // If an explicit setting is given, use that
1446                 setting
1447             }
1448             None => {
1449                 if mode == Mode::Std {
1450                     // The standard library defaults to the legacy scheme
1451                     false
1452                 } else {
1453                     // The compiler and tools default to the new scheme
1454                     true
1455                 }
1456             }
1457         };
1458
1459         if use_new_symbol_mangling {
1460             rustflags.arg("-Csymbol-mangling-version=v0");
1461         } else {
1462             rustflags.arg("-Csymbol-mangling-version=legacy");
1463             rustflags.arg("-Zunstable-options");
1464         }
1465
1466         // FIXME(Urgau): This a hack as it shouldn't be gated on stage 0 but until `rustc_llvm`
1467         // is made to work with `--check-cfg` which is currently not easly possible until cargo
1468         // get some support for setting `--check-cfg` within build script, it's the least invasive
1469         // hack that still let's us have cfg checking for the vast majority of the codebase.
1470         if stage != 0 {
1471             // Enable cfg checking of cargo features for everything but std and also enable cfg
1472             // checking of names and values.
1473             //
1474             // Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like
1475             // backtrace, core_simd, std_float, ...), those dependencies have their own
1476             // features but cargo isn't involved in the #[path] process and so cannot pass the
1477             // complete list of features, so for that reason we don't enable checking of
1478             // features for std crates.
1479             cargo.arg(if mode != Mode::Std {
1480                 "-Zcheck-cfg=names,values,features"
1481             } else {
1482                 "-Zcheck-cfg=names,values"
1483             });
1484
1485             // Add extra cfg not defined in/by rustc
1486             //
1487             // Note: Altrough it would seems that "-Zunstable-options" to `rustflags` is useless as
1488             // cargo would implicitly add it, it was discover that sometimes bootstrap only use
1489             // `rustflags` without `cargo` making it required.
1490             rustflags.arg("-Zunstable-options");
1491             for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
1492                 if *restricted_mode == None || *restricted_mode == Some(mode) {
1493                     // Creating a string of the values by concatenating each value:
1494                     // ',"tvos","watchos"' or '' (nothing) when there are no values
1495                     let values = match values {
1496                         Some(values) => values
1497                             .iter()
1498                             .map(|val| [",", "\"", val, "\""])
1499                             .flatten()
1500                             .collect::<String>(),
1501                         None => String::new(),
1502                     };
1503                     rustflags.arg(&format!("--check-cfg=values({name}{values})"));
1504                 }
1505             }
1506         }
1507
1508         // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1509         // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1510         // #71458.
1511         let mut rustdocflags = rustflags.clone();
1512         rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1513         if stage == 0 {
1514             rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1515         } else {
1516             rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1517         }
1518
1519         if let Ok(s) = env::var("CARGOFLAGS") {
1520             cargo.args(s.split_whitespace());
1521         }
1522
1523         match mode {
1524             Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1525             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1526                 // Build proc macros both for the host and the target
1527                 if target != compiler.host && cmd != "check" {
1528                     cargo.arg("-Zdual-proc-macros");
1529                     rustflags.arg("-Zdual-proc-macros");
1530                 }
1531             }
1532         }
1533
1534         // This tells Cargo (and in turn, rustc) to output more complete
1535         // dependency information.  Most importantly for rustbuild, this
1536         // includes sysroot artifacts, like libstd, which means that we don't
1537         // need to track those in rustbuild (an error prone process!). This
1538         // feature is currently unstable as there may be some bugs and such, but
1539         // it represents a big improvement in rustbuild's reliability on
1540         // rebuilds, so we're using it here.
1541         //
1542         // For some additional context, see #63470 (the PR originally adding
1543         // this), as well as #63012 which is the tracking issue for this
1544         // feature on the rustc side.
1545         cargo.arg("-Zbinary-dep-depinfo");
1546         match mode {
1547             Mode::ToolBootstrap => {
1548                 // Restrict the allowed features to those passed by rustbuild, so we don't depend on nightly accidentally.
1549                 // HACK: because anyhow does feature detection in build.rs, we need to allow the backtrace feature too.
1550                 rustflags.arg("-Zallow-features=binary-dep-depinfo,backtrace");
1551             }
1552             Mode::ToolStd => {
1553                 // Right now this is just compiletest and a few other tools that build on stable.
1554                 // Allow them to use `feature(test)`, but nothing else.
1555                 rustflags.arg("-Zallow-features=binary-dep-depinfo,test,backtrace");
1556             }
1557             Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {}
1558         }
1559
1560         cargo.arg("-j").arg(self.jobs().to_string());
1561         // Remove make-related flags to ensure Cargo can correctly set things up
1562         cargo.env_remove("MAKEFLAGS");
1563         cargo.env_remove("MFLAGS");
1564
1565         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1566         // Force cargo to output binaries with disambiguating hashes in the name
1567         let mut metadata = if compiler.stage == 0 {
1568             // Treat stage0 like a special channel, whether it's a normal prior-
1569             // release rustc or a local rebuild with the same version, so we
1570             // never mix these libraries by accident.
1571             "bootstrap".to_string()
1572         } else {
1573             self.config.channel.to_string()
1574         };
1575         // We want to make sure that none of the dependencies between
1576         // std/test/rustc unify with one another. This is done for weird linkage
1577         // reasons but the gist of the problem is that if librustc, libtest, and
1578         // libstd all depend on libc from crates.io (which they actually do) we
1579         // want to make sure they all get distinct versions. Things get really
1580         // weird if we try to unify all these dependencies right now, namely
1581         // around how many times the library is linked in dynamic libraries and
1582         // such. If rustc were a static executable or if we didn't ship dylibs
1583         // this wouldn't be a problem, but we do, so it is. This is in general
1584         // just here to make sure things build right. If you can remove this and
1585         // things still build right, please do!
1586         match mode {
1587             Mode::Std => metadata.push_str("std"),
1588             // When we're building rustc tools, they're built with a search path
1589             // that contains things built during the rustc build. For example,
1590             // bitflags is built during the rustc build, and is a dependency of
1591             // rustdoc as well. We're building rustdoc in a different target
1592             // directory, though, which means that Cargo will rebuild the
1593             // dependency. When we go on to build rustdoc, we'll look for
1594             // bitflags, and find two different copies: one built during the
1595             // rustc step and one that we just built. This isn't always a
1596             // problem, somehow -- not really clear why -- but we know that this
1597             // fixes things.
1598             Mode::ToolRustc => metadata.push_str("tool-rustc"),
1599             // Same for codegen backends.
1600             Mode::Codegen => metadata.push_str("codegen"),
1601             _ => {}
1602         }
1603         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1604
1605         if cmd == "clippy" {
1606             rustflags.arg("-Zforce-unstable-if-unmarked");
1607         }
1608
1609         rustflags.arg("-Zmacro-backtrace");
1610
1611         let want_rustdoc = self.doc_tests != DocTests::No;
1612
1613         // We synthetically interpret a stage0 compiler used to build tools as a
1614         // "raw" compiler in that it's the exact snapshot we download. Normally
1615         // the stage0 build means it uses libraries build by the stage0
1616         // compiler, but for tools we just use the precompiled libraries that
1617         // we've downloaded
1618         let use_snapshot = mode == Mode::ToolBootstrap;
1619         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1620
1621         let maybe_sysroot = self.sysroot(compiler);
1622         let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1623         let libdir = self.rustc_libdir(compiler);
1624
1625         // Clear the output directory if the real rustc we're using has changed;
1626         // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1627         //
1628         // Avoid doing this during dry run as that usually means the relevant
1629         // compiler is not yet linked/copied properly.
1630         //
1631         // Only clear out the directory if we're compiling std; otherwise, we
1632         // should let Cargo take care of things for us (via depdep info)
1633         if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1634             self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1635         }
1636
1637         // Customize the compiler we're running. Specify the compiler to cargo
1638         // as our shim and then pass it some various options used to configure
1639         // how the actual compiler itself is called.
1640         //
1641         // These variables are primarily all read by
1642         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1643         cargo
1644             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1645             .env("RUSTC_REAL", self.rustc(compiler))
1646             .env("RUSTC_STAGE", stage.to_string())
1647             .env("RUSTC_SYSROOT", &sysroot)
1648             .env("RUSTC_LIBDIR", &libdir)
1649             .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
1650             .env(
1651                 "RUSTDOC_REAL",
1652                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1653                     self.rustdoc(compiler)
1654                 } else {
1655                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1656                 },
1657             )
1658             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1659             .env("RUSTC_BREAK_ON_ICE", "1");
1660         // Clippy support is a hack and uses the default `cargo-clippy` in path.
1661         // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1662         if cmd != "clippy" {
1663             cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
1664         }
1665
1666         // Dealing with rpath here is a little special, so let's go into some
1667         // detail. First off, `-rpath` is a linker option on Unix platforms
1668         // which adds to the runtime dynamic loader path when looking for
1669         // dynamic libraries. We use this by default on Unix platforms to ensure
1670         // that our nightlies behave the same on Windows, that is they work out
1671         // of the box. This can be disabled, of course, but basically that's why
1672         // we're gated on RUSTC_RPATH here.
1673         //
1674         // Ok, so the astute might be wondering "why isn't `-C rpath` used
1675         // here?" and that is indeed a good question to ask. This codegen
1676         // option is the compiler's current interface to generating an rpath.
1677         // Unfortunately it doesn't quite suffice for us. The flag currently
1678         // takes no value as an argument, so the compiler calculates what it
1679         // should pass to the linker as `-rpath`. This unfortunately is based on
1680         // the **compile time** directory structure which when building with
1681         // Cargo will be very different than the runtime directory structure.
1682         //
1683         // All that's a really long winded way of saying that if we use
1684         // `-Crpath` then the executables generated have the wrong rpath of
1685         // something like `$ORIGIN/deps` when in fact the way we distribute
1686         // rustc requires the rpath to be `$ORIGIN/../lib`.
1687         //
1688         // So, all in all, to set up the correct rpath we pass the linker
1689         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1690         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1691         // to change a flag in a binary?
1692         if self.config.rust_rpath && util::use_host_linker(target) {
1693             let rpath = if target.contains("apple") {
1694                 // Note that we need to take one extra step on macOS to also pass
1695                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1696                 // do that we pass a weird flag to the compiler to get it to do
1697                 // so. Note that this is definitely a hack, and we should likely
1698                 // flesh out rpath support more fully in the future.
1699                 rustflags.arg("-Zosx-rpath-install-name");
1700                 Some("-Wl,-rpath,@loader_path/../lib")
1701             } else if !target.contains("windows") {
1702                 rustflags.arg("-Clink-args=-Wl,-z,origin");
1703                 Some("-Wl,-rpath,$ORIGIN/../lib")
1704             } else {
1705                 None
1706             };
1707             if let Some(rpath) = rpath {
1708                 rustflags.arg(&format!("-Clink-args={}", rpath));
1709             }
1710         }
1711
1712         if let Some(host_linker) = self.linker(compiler.host) {
1713             cargo.env("RUSTC_HOST_LINKER", host_linker);
1714         }
1715         if self.is_fuse_ld_lld(compiler.host) {
1716             cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1717             cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1718         }
1719
1720         if let Some(target_linker) = self.linker(target) {
1721             let target = crate::envify(&target.triple);
1722             cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1723         }
1724         if self.is_fuse_ld_lld(target) {
1725             rustflags.arg("-Clink-args=-fuse-ld=lld");
1726         }
1727         self.lld_flags(target).for_each(|flag| {
1728             rustdocflags.arg(&flag);
1729         });
1730
1731         if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1732             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1733         }
1734
1735         let debuginfo_level = match mode {
1736             Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1737             Mode::Std => self.config.rust_debuginfo_level_std,
1738             Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1739                 self.config.rust_debuginfo_level_tools
1740             }
1741         };
1742         cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1743         cargo.env(
1744             profile_var("DEBUG_ASSERTIONS"),
1745             if mode == Mode::Std {
1746                 self.config.rust_debug_assertions_std.to_string()
1747             } else {
1748                 self.config.rust_debug_assertions.to_string()
1749             },
1750         );
1751         cargo.env(
1752             profile_var("OVERFLOW_CHECKS"),
1753             if mode == Mode::Std {
1754                 self.config.rust_overflow_checks_std.to_string()
1755             } else {
1756                 self.config.rust_overflow_checks.to_string()
1757             },
1758         );
1759
1760         if !target.contains("windows") {
1761             let needs_unstable_opts = target.contains("linux")
1762                 || target.contains("windows")
1763                 || target.contains("bsd")
1764                 || target.contains("dragonfly")
1765                 || target.contains("illumos");
1766
1767             if needs_unstable_opts {
1768                 rustflags.arg("-Zunstable-options");
1769             }
1770             match self.config.rust_split_debuginfo {
1771                 SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
1772                 SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
1773                 SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
1774             };
1775         }
1776
1777         if self.config.cmd.bless() {
1778             // Bless `expect!` tests.
1779             cargo.env("UPDATE_EXPECT", "1");
1780         }
1781
1782         if !mode.is_tool() {
1783             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1784         }
1785
1786         if let Some(x) = self.crt_static(target) {
1787             if x {
1788                 rustflags.arg("-Ctarget-feature=+crt-static");
1789             } else {
1790                 rustflags.arg("-Ctarget-feature=-crt-static");
1791             }
1792         }
1793
1794         if let Some(x) = self.crt_static(compiler.host) {
1795             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1796         }
1797
1798         if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1799             let map = format!("{}={}", self.build.src.display(), map_to);
1800             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1801
1802             // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1803             // in order to opportunistically reverse it later.
1804             cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1805         }
1806
1807         // Enable usage of unstable features
1808         cargo.env("RUSTC_BOOTSTRAP", "1");
1809         self.add_rust_test_threads(&mut cargo);
1810
1811         // Almost all of the crates that we compile as part of the bootstrap may
1812         // have a build script, including the standard library. To compile a
1813         // build script, however, it itself needs a standard library! This
1814         // introduces a bit of a pickle when we're compiling the standard
1815         // library itself.
1816         //
1817         // To work around this we actually end up using the snapshot compiler
1818         // (stage0) for compiling build scripts of the standard library itself.
1819         // The stage0 compiler is guaranteed to have a libstd available for use.
1820         //
1821         // For other crates, however, we know that we've already got a standard
1822         // library up and running, so we can use the normal compiler to compile
1823         // build scripts in that situation.
1824         if mode == Mode::Std {
1825             cargo
1826                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1827                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1828         } else {
1829             cargo
1830                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1831                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1832         }
1833
1834         // Tools that use compiler libraries may inherit the `-lLLVM` link
1835         // requirement, but the `-L` library path is not propagated across
1836         // separate Cargo projects. We can add LLVM's library path to the
1837         // platform-specific environment variable as a workaround.
1838         if mode == Mode::ToolRustc || mode == Mode::Codegen {
1839             if let Some(llvm_config) = self.llvm_config(target) {
1840                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1841                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1842             }
1843         }
1844
1845         // Compile everything except libraries and proc macros with the more
1846         // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1847         // so we can't use it by default in general, but we can use it for tools
1848         // and our own internal libraries.
1849         if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1850             rustflags.arg("-Ztls-model=initial-exec");
1851         }
1852
1853         if self.config.incremental {
1854             cargo.env("CARGO_INCREMENTAL", "1");
1855         } else {
1856             // Don't rely on any default setting for incr. comp. in Cargo
1857             cargo.env("CARGO_INCREMENTAL", "0");
1858         }
1859
1860         if let Some(ref on_fail) = self.config.on_fail {
1861             cargo.env("RUSTC_ON_FAIL", on_fail);
1862         }
1863
1864         if self.config.print_step_timings {
1865             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1866         }
1867
1868         if self.config.print_step_rusage {
1869             cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1870         }
1871
1872         if self.config.backtrace_on_ice {
1873             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1874         }
1875
1876         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1877
1878         if source_type == SourceType::InTree {
1879             let mut lint_flags = Vec::new();
1880             // When extending this list, add the new lints to the RUSTFLAGS of the
1881             // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1882             // some code doesn't go through this `rustc` wrapper.
1883             lint_flags.push("-Wrust_2018_idioms");
1884             lint_flags.push("-Wunused_lifetimes");
1885             lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1886
1887             if self.config.deny_warnings {
1888                 lint_flags.push("-Dwarnings");
1889                 rustdocflags.arg("-Dwarnings");
1890             }
1891
1892             // This does not use RUSTFLAGS due to caching issues with Cargo.
1893             // Clippy is treated as an "in tree" tool, but shares the same
1894             // cache as other "submodule" tools. With these options set in
1895             // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1896             // By injecting this into the rustc wrapper, this circumvents
1897             // Cargo's fingerprint detection. This is fine because lint flags
1898             // are always ignored in dependencies. Eventually this should be
1899             // fixed via better support from Cargo.
1900             cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1901
1902             rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1903         }
1904
1905         if mode == Mode::Rustc {
1906             rustflags.arg("-Zunstable-options");
1907             rustflags.arg("-Wrustc::internal");
1908         }
1909
1910         // Throughout the build Cargo can execute a number of build scripts
1911         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1912         // obtained previously to those build scripts.
1913         // Build scripts use either the `cc` crate or `configure/make` so we pass
1914         // the options through environment variables that are fetched and understood by both.
1915         //
1916         // FIXME: the guard against msvc shouldn't need to be here
1917         if target.contains("msvc") {
1918             if let Some(ref cl) = self.config.llvm_clang_cl {
1919                 cargo.env("CC", cl).env("CXX", cl);
1920             }
1921         } else {
1922             let ccache = self.config.ccache.as_ref();
1923             let ccacheify = |s: &Path| {
1924                 let ccache = match ccache {
1925                     Some(ref s) => s,
1926                     None => return s.display().to_string(),
1927                 };
1928                 // FIXME: the cc-rs crate only recognizes the literal strings
1929                 // `ccache` and `sccache` when doing caching compilations, so we
1930                 // mirror that here. It should probably be fixed upstream to
1931                 // accept a new env var or otherwise work with custom ccache
1932                 // vars.
1933                 match &ccache[..] {
1934                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1935                     _ => s.display().to_string(),
1936                 }
1937             };
1938             let cc = ccacheify(&self.cc(target));
1939             cargo.env(format!("CC_{}", target.triple), &cc);
1940
1941             let cflags = self.cflags(target, GitRepo::Rustc, CLang::C).join(" ");
1942             cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1943
1944             if let Some(ar) = self.ar(target) {
1945                 let ranlib = format!("{} s", ar.display());
1946                 cargo
1947                     .env(format!("AR_{}", target.triple), ar)
1948                     .env(format!("RANLIB_{}", target.triple), ranlib);
1949             }
1950
1951             if let Ok(cxx) = self.cxx(target) {
1952                 let cxx = ccacheify(&cxx);
1953                 let cxxflags = self.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");
1954                 cargo
1955                     .env(format!("CXX_{}", target.triple), &cxx)
1956                     .env(format!("CXXFLAGS_{}", target.triple), cxxflags);
1957             }
1958         }
1959
1960         if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1961             rustflags.arg("-Zsave-analysis");
1962             cargo.env(
1963                 "RUST_SAVE_ANALYSIS_CONFIG",
1964                 "{\"output_file\": null,\"full_docs\": false,\
1965                        \"pub_only\": true,\"reachable_only\": false,\
1966                        \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1967             );
1968         }
1969
1970         // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1971         // when compiling the standard library, since this might be linked into the final outputs
1972         // produced by rustc. Since this mitigation is only available on Windows, only enable it
1973         // for the standard library in case the compiler is run on a non-Windows platform.
1974         // This is not needed for stage 0 artifacts because these will only be used for building
1975         // the stage 1 compiler.
1976         if cfg!(windows)
1977             && mode == Mode::Std
1978             && self.config.control_flow_guard
1979             && compiler.stage >= 1
1980         {
1981             rustflags.arg("-Ccontrol-flow-guard");
1982         }
1983
1984         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1985         // This replaces spaces with newlines because RUSTDOCFLAGS does not
1986         // support arguments with regular spaces. Hopefully someday Cargo will
1987         // have space support.
1988         let rust_version = self.rust_version().replace(' ', "\n");
1989         rustdocflags.arg("--crate-version").arg(&rust_version);
1990
1991         // Environment variables *required* throughout the build
1992         //
1993         // FIXME: should update code to not require this env var
1994         cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1995
1996         // Set this for all builds to make sure doc builds also get it.
1997         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1998
1999         // This one's a bit tricky. As of the time of this writing the compiler
2000         // links to the `winapi` crate on crates.io. This crate provides raw
2001         // bindings to Windows system functions, sort of like libc does for
2002         // Unix. This crate also, however, provides "import libraries" for the
2003         // MinGW targets. There's an import library per dll in the windows
2004         // distribution which is what's linked to. These custom import libraries
2005         // are used because the winapi crate can reference Windows functions not
2006         // present in the MinGW import libraries.
2007         //
2008         // For example MinGW may ship libdbghelp.a, but it may not have
2009         // references to all the functions in the dbghelp dll. Instead the
2010         // custom import library for dbghelp in the winapi crates has all this
2011         // information.
2012         //
2013         // Unfortunately for us though the import libraries are linked by
2014         // default via `-ldylib=winapi_foo`. That is, they're linked with the
2015         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
2016         // conflict with the system MinGW ones). This consequently means that
2017         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
2018         // DLL) when linked against *again*, for example with procedural macros
2019         // or plugins, will trigger the propagation logic of `-ldylib`, passing
2020         // `-lwinapi_foo` to the linker again. This isn't actually available in
2021         // our distribution, however, so the link fails.
2022         //
2023         // To solve this problem we tell winapi to not use its bundled import
2024         // libraries. This means that it will link to the system MinGW import
2025         // libraries by default, and the `-ldylib=foo` directives will still get
2026         // passed to the final linker, but they'll look like `-lfoo` which can
2027         // be resolved because MinGW has the import library. The downside is we
2028         // don't get newer functions from Windows, but we don't use any of them
2029         // anyway.
2030         if !mode.is_tool() {
2031             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
2032         }
2033
2034         for _ in 0..self.verbosity {
2035             cargo.arg("-v");
2036         }
2037
2038         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
2039             (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
2040                 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
2041             }
2042             _ => {
2043                 // Don't set anything
2044             }
2045         }
2046
2047         if self.config.rust_optimize {
2048             // FIXME: cargo bench/install do not accept `--release`
2049             if cmd != "bench" && cmd != "install" {
2050                 cargo.arg("--release");
2051             }
2052         }
2053
2054         if self.config.locked_deps {
2055             cargo.arg("--locked");
2056         }
2057         if self.config.vendor || self.is_sudo {
2058             cargo.arg("--frozen");
2059         }
2060
2061         // Try to use a sysroot-relative bindir, in case it was configured absolutely.
2062         cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
2063
2064         self.ci_env.force_coloring_in_ci(&mut cargo);
2065
2066         // When we build Rust dylibs they're all intended for intermediate
2067         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
2068         // linking all deps statically into the dylib.
2069         if matches!(mode, Mode::Std | Mode::Rustc) {
2070             rustflags.arg("-Cprefer-dynamic");
2071         }
2072
2073         // When building incrementally we default to a lower ThinLTO import limit
2074         // (unless explicitly specified otherwise). This will produce a somewhat
2075         // slower code but give way better compile times.
2076         {
2077             let limit = match self.config.rust_thin_lto_import_instr_limit {
2078                 Some(limit) => Some(limit),
2079                 None if self.config.incremental => Some(10),
2080                 _ => None,
2081             };
2082
2083             if let Some(limit) = limit {
2084                 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
2085             }
2086         }
2087
2088         Cargo { command: cargo, rustflags, rustdocflags }
2089     }
2090
2091     /// Ensure that a given step is built, returning its output. This will
2092     /// cache the step, so it is safe (and good!) to call this as often as
2093     /// needed to ensure that all dependencies are built.
2094     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
2095         {
2096             let mut stack = self.stack.borrow_mut();
2097             for stack_step in stack.iter() {
2098                 // should skip
2099                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
2100                     continue;
2101                 }
2102                 let mut out = String::new();
2103                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
2104                 for el in stack.iter().rev() {
2105                     out += &format!("\t{:?}\n", el);
2106                 }
2107                 panic!("{}", out);
2108             }
2109             if let Some(out) = self.cache.get(&step) {
2110                 self.verbose_than(1, &format!("{}c {:?}", "  ".repeat(stack.len()), step));
2111
2112                 return out;
2113             }
2114             self.verbose_than(1, &format!("{}> {:?}", "  ".repeat(stack.len()), step));
2115             stack.push(Box::new(step.clone()));
2116         }
2117
2118         #[cfg(feature = "build-metrics")]
2119         self.metrics.enter_step(&step);
2120
2121         let (out, dur) = {
2122             let start = Instant::now();
2123             let zero = Duration::new(0, 0);
2124             let parent = self.time_spent_on_dependencies.replace(zero);
2125             let out = step.clone().run(self);
2126             let dur = start.elapsed();
2127             let deps = self.time_spent_on_dependencies.replace(parent + dur);
2128             (out, dur - deps)
2129         };
2130
2131         if self.config.print_step_timings && !self.config.dry_run {
2132             let step_string = format!("{:?}", step);
2133             let brace_index = step_string.find("{").unwrap_or(0);
2134             let type_string = type_name::<S>();
2135             println!(
2136                 "[TIMING] {} {} -- {}.{:03}",
2137                 &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
2138                 &step_string[brace_index..],
2139                 dur.as_secs(),
2140                 dur.subsec_millis()
2141             );
2142         }
2143
2144         #[cfg(feature = "build-metrics")]
2145         self.metrics.exit_step();
2146
2147         {
2148             let mut stack = self.stack.borrow_mut();
2149             let cur_step = stack.pop().expect("step stack empty");
2150             assert_eq!(cur_step.downcast_ref(), Some(&step));
2151         }
2152         self.verbose_than(1, &format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
2153         self.cache.put(step, out.clone());
2154         out
2155     }
2156
2157     /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
2158     /// its output. This will cache the step, so it's safe (and good!) to call this as often as
2159     /// needed to ensure that all dependencies are build.
2160     pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
2161         &'a self,
2162         step: S,
2163         kind: Kind,
2164     ) -> S::Output {
2165         let desc = StepDescription::from::<S>(kind);
2166         let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
2167
2168         // Avoid running steps contained in --exclude
2169         for pathset in &should_run.paths {
2170             if desc.is_excluded(self, pathset) {
2171                 return None;
2172             }
2173         }
2174
2175         // Only execute if it's supposed to run as default
2176         if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
2177     }
2178
2179     /// Checks if any of the "should_run" paths is in the `Builder` paths.
2180     pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
2181         let desc = StepDescription::from::<S>(kind);
2182         let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
2183
2184         for path in &self.paths {
2185             if should_run.paths.iter().any(|s| s.has(path, Some(desc.kind)))
2186                 && !desc.is_excluded(
2187                     self,
2188                     &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
2189                 )
2190             {
2191                 return true;
2192             }
2193         }
2194
2195         false
2196     }
2197 }
2198
2199 #[cfg(test)]
2200 mod tests;
2201
2202 #[derive(Debug, Clone)]
2203 struct Rustflags(String, TargetSelection);
2204
2205 impl Rustflags {
2206     fn new(target: TargetSelection) -> Rustflags {
2207         let mut ret = Rustflags(String::new(), target);
2208         ret.propagate_cargo_env("RUSTFLAGS");
2209         ret
2210     }
2211
2212     /// By default, cargo will pick up on various variables in the environment. However, bootstrap
2213     /// reuses those variables to pass additional flags to rustdoc, so by default they get overridden.
2214     /// Explicitly add back any previous value in the environment.
2215     ///
2216     /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
2217     fn propagate_cargo_env(&mut self, prefix: &str) {
2218         // Inherit `RUSTFLAGS` by default ...
2219         self.env(prefix);
2220
2221         // ... and also handle target-specific env RUSTFLAGS if they're configured.
2222         let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
2223         self.env(&target_specific);
2224     }
2225
2226     fn env(&mut self, env: &str) {
2227         if let Ok(s) = env::var(env) {
2228             for part in s.split(' ') {
2229                 self.arg(part);
2230             }
2231         }
2232     }
2233
2234     fn arg(&mut self, arg: &str) -> &mut Self {
2235         assert_eq!(arg.split(' ').count(), 1);
2236         if !self.0.is_empty() {
2237             self.0.push(' ');
2238         }
2239         self.0.push_str(arg);
2240         self
2241     }
2242 }
2243
2244 #[derive(Debug)]
2245 pub struct Cargo {
2246     command: Command,
2247     rustflags: Rustflags,
2248     rustdocflags: Rustflags,
2249 }
2250
2251 impl Cargo {
2252     pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
2253         self.rustdocflags.arg(arg);
2254         self
2255     }
2256     pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
2257         self.rustflags.arg(arg);
2258         self
2259     }
2260
2261     pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
2262         self.command.arg(arg.as_ref());
2263         self
2264     }
2265
2266     pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
2267     where
2268         I: IntoIterator<Item = S>,
2269         S: AsRef<OsStr>,
2270     {
2271         for arg in args {
2272             self.arg(arg.as_ref());
2273         }
2274         self
2275     }
2276
2277     pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
2278         // These are managed through rustflag/rustdocflag interfaces.
2279         assert_ne!(key.as_ref(), "RUSTFLAGS");
2280         assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
2281         self.command.env(key.as_ref(), value.as_ref());
2282         self
2283     }
2284
2285     pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
2286         builder.add_rustc_lib_path(compiler, &mut self.command);
2287     }
2288
2289     pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
2290         self.command.current_dir(dir);
2291         self
2292     }
2293 }
2294
2295 impl From<Cargo> for Command {
2296     fn from(mut cargo: Cargo) -> Command {
2297         let rustflags = &cargo.rustflags.0;
2298         if !rustflags.is_empty() {
2299             cargo.command.env("RUSTFLAGS", rustflags);
2300         }
2301
2302         let rustdocflags = &cargo.rustdocflags.0;
2303         if !rustdocflags.is_empty() {
2304             cargo.command.env("RUSTDOCFLAGS", rustdocflags);
2305         }
2306
2307         cargo.command
2308     }
2309 }