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