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