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