bootstrap/core/builder/cargo.rs
1use std::ffi::{OsStr, OsString};
2use std::path::{Path, PathBuf};
3use std::sync::OnceLock;
4use std::{env, fs};
5
6use super::{Builder, Kind};
7use crate::core::build_steps::compile::is_lto_stage;
8use crate::core::build_steps::llvm::Llvm;
9use crate::core::build_steps::test;
10use crate::core::build_steps::tool::SourceType;
11use crate::core::compiler::Compiler;
12use crate::core::config::flags::{Color, Subcommand};
13use crate::core::config::toml::pgo::PgoConfig;
14use crate::core::config::{
15 CompressDebuginfo, Config, DryRun, RustcLto, SplitDebuginfo, TargetSelection,
16};
17use crate::core::session::{CLang, Mode, RemapScheme};
18use crate::utils::build_stamp;
19use crate::utils::exec::{BootstrapCommand, command};
20use crate::utils::helpers::{self, LldThreads, check_cfg_arg, envify, linker_flags, t};
21
22/// Extra `--check-cfg` to add when building the compiler or tools
23/// (Mode restriction, config name, config values (if any))
24#[expect(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above.
25const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
26 (Some(Mode::Rustc), "bootstrap", None),
27 (Some(Mode::Codegen), "bootstrap", None),
28 (Some(Mode::ToolRustcPrivate), "bootstrap", None),
29 (Some(Mode::ToolStd), "bootstrap", None),
30 (Some(Mode::ToolRustcPrivate), "rust_analyzer", None),
31 (Some(Mode::ToolStd), "rust_analyzer", None),
32 // Any library specific cfgs like `target_os`, `target_arch` should be put in
33 // priority the `[lints.rust.unexpected_cfgs.check-cfg]` table
34 // in the appropriate `library/{std,alloc,core}/Cargo.toml`
35];
36
37/// Represents flag values in `String` form with a `\x1f` delimiter to pass to the compiler later.
38///
39/// Flags are emitted via `CARGO_ENCODED_RUSTFLAGS` / `CARGO_ENCODED_RUSTDOCFLAGS`,
40/// which use `\x1f` (ASCII Unit Separator) as the delimiter and therefore allow spaces
41/// within individual flag values (e.g. paths from `llvm-config --libdir`).
42///
43/// `-Z crate-attr` flags will be applied recursively on the target code using the
44/// `rustc_parse::parser::Parser`. See `rustc_builtin_macros::cmdline_attrs::inject` for more
45/// information.
46#[derive(Debug, Clone)]
47struct Rustflags(String, TargetSelection);
48
49impl Rustflags {
50 fn new(target: TargetSelection) -> Rustflags {
51 Rustflags(String::new(), target)
52 }
53
54 /// By default, cargo will pick up on various variables in the environment. However, bootstrap
55 /// reuses those variables to pass additional flags to rustdoc, so by default they get
56 /// overridden. Explicitly add back any previous value in the environment.
57 ///
58 /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
59 fn propagate_cargo_env(&mut self, prefix: &str) {
60 // Inherit `RUSTFLAGS` by default ...
61 self.env(prefix);
62
63 // ... and also handle target-specific env RUSTFLAGS if they're configured.
64 let target_specific = format!("CARGO_TARGET_{}_{}", envify(&self.1.triple), prefix);
65 self.env(&target_specific);
66 }
67
68 fn env(&mut self, env: &str) {
69 if let Ok(s) = env::var(env) {
70 for part in s.split(' ') {
71 self.arg(part);
72 }
73 }
74 }
75
76 fn arg(&mut self, arg: &str) -> &mut Self {
77 assert!(
78 !arg.contains('\x1f'),
79 "rustflag must not contain the ASCII unit separator (\\x1f): {arg:?}"
80 );
81 if !arg.is_empty() {
82 if !self.0.is_empty() {
83 self.0.push('\x1f');
84 }
85 self.0.push_str(arg);
86 }
87 self
88 }
89
90 fn propagate_rustflag_envs(&mut self, build_compiler_stage: u32) {
91 self.propagate_cargo_env("RUSTFLAGS");
92 if build_compiler_stage != 0 {
93 self.env("RUSTFLAGS_NOT_BOOTSTRAP");
94 } else {
95 self.env("RUSTFLAGS_BOOTSTRAP");
96 self.arg("--cfg=bootstrap");
97 }
98 }
99}
100
101/// Picks the environment variable and value to pass a set of [`Rustflags`] to cargo.
102///
103/// `flags` is the `\x1f`-separated string built by [`Rustflags`]. We prefer the plain,
104/// space-separated form (`RUSTFLAGS`/`RUSTDOCFLAGS`) so the command stays readable and
105/// copy-pasteable in bootstrap's debug output, and only fall back to the `CARGO_ENCODED_*` form
106/// (which keeps the `\x1f` separators) when a flag value contains a space that the plain,
107/// whitespace-split form can't represent. See <https://github.com/rust-lang/rust/issues/158749>.
108pub(super) fn flags_env(
109 plain: &'static str,
110 encoded: &'static str,
111 flags: &str,
112) -> (&'static str, String) {
113 // A space can only appear inside a flag value, since the separators are `\x1f`.
114 if flags.contains(' ') {
115 (encoded, flags.to_string())
116 } else {
117 (plain, flags.replace('\x1f', " "))
118 }
119}
120
121/// Flags that are passed to the `rustc` shim binary. These flags will only be applied when
122/// compiling host code, i.e. when `--target` is unset.
123#[derive(Debug, Default)]
124struct HostFlags {
125 rustc: Vec<String>,
126}
127
128impl HostFlags {
129 const SEPARATOR: &'static str = " ";
130
131 /// Adds a host rustc flag.
132 fn arg<S: Into<String>>(&mut self, flag: S) {
133 let value = flag.into().trim().to_string();
134 assert!(!value.contains(Self::SEPARATOR));
135 self.rustc.push(value);
136 }
137
138 /// Encodes all the flags into a single string.
139 fn encode(self) -> String {
140 self.rustc.join(Self::SEPARATOR)
141 }
142}
143
144#[derive(Debug)]
145pub(crate) struct Cargo {
146 command: BootstrapCommand,
147 args: Vec<OsString>,
148 compiler: Compiler,
149 mode: Mode,
150 target: TargetSelection,
151 rustflags: Rustflags,
152 rustdocflags: Rustflags,
153 hostflags: HostFlags,
154 allow_features: String,
155 build_compiler_stage: u32,
156 extra_rustflags: Vec<String>,
157 profile: Option<&'static str>,
158 kind: Kind,
159}
160
161impl Cargo {
162 /// Calls [`Builder::cargo`] and [`Cargo::configure_linker`] to prepare an invocation of `cargo`
163 /// to be run.
164 #[track_caller]
165 pub(crate) fn new(
166 builder: &Builder<'_>,
167 compiler: Compiler,
168 mode: Mode,
169 source_type: SourceType,
170 target: TargetSelection,
171 cmd_kind: Kind,
172 ) -> Cargo {
173 let mut cargo = builder.cargo(compiler, mode, source_type, target, cmd_kind);
174 if target.synthetic {
175 cargo.arg("-Zjson-target-spec");
176 }
177
178 match cmd_kind {
179 // No need to configure the target linker for these command types.
180 Kind::Clean | Kind::Check | Kind::Format | Kind::Setup => {}
181 _ => {
182 cargo.configure_linker(builder);
183 }
184 }
185
186 cargo
187 }
188
189 pub(crate) fn release_build(&mut self, release_build: bool) {
190 self.profile = if release_build { Some("release") } else { None };
191 }
192
193 #[expect(dead_code, reason = "general-purpose, currently unused")]
194 pub(crate) fn profile(&mut self, profile: &'static str) {
195 self.profile = Some(profile);
196 }
197
198 pub(crate) fn compiler(&self) -> Compiler {
199 self.compiler
200 }
201
202 pub(crate) fn mode(&self) -> Mode {
203 self.mode
204 }
205
206 pub(crate) fn into_cmd(self) -> BootstrapCommand {
207 self.into()
208 }
209
210 pub(crate) fn kind(&self) -> Kind {
211 self.kind
212 }
213
214 /// Same as [`Cargo::new`] except this one doesn't configure the linker with
215 /// [`Cargo::configure_linker`].
216 #[track_caller]
217 pub(crate) fn new_for_mir_opt_tests(
218 builder: &Builder<'_>,
219 compiler: Compiler,
220 mode: Mode,
221 source_type: SourceType,
222 target: TargetSelection,
223 cmd_kind: Kind,
224 ) -> Cargo {
225 let mut cargo = builder.cargo(compiler, mode, source_type, target, cmd_kind);
226 if target.synthetic {
227 cargo.arg("-Zjson-target-spec");
228 }
229 cargo
230 }
231
232 pub(crate) fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
233 self.rustdocflags.arg(arg);
234 self
235 }
236
237 pub(crate) fn rustflag(&mut self, arg: &str) -> &mut Cargo {
238 self.rustflags.arg(arg);
239 self
240 }
241
242 pub(crate) fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
243 self.args.push(arg.as_ref().into());
244 self
245 }
246
247 pub(crate) fn args<I, S>(&mut self, args: I) -> &mut Cargo
248 where
249 I: IntoIterator<Item = S>,
250 S: AsRef<OsStr>,
251 {
252 for arg in args {
253 self.arg(arg.as_ref());
254 }
255 self
256 }
257
258 /// Add an env var to the cargo command instance. Note that `RUSTFLAGS`/`RUSTDOCFLAGS` must go
259 /// through [`Cargo::rustdocflags`] and [`Cargo::rustflags`] because inconsistent `RUSTFLAGS`
260 /// and `RUSTDOCFLAGS` usages will trigger spurious rebuilds.
261 pub(crate) fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
262 assert_ne!(key.as_ref(), "RUSTFLAGS");
263 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
264 self.command.env(key.as_ref(), value.as_ref());
265 self
266 }
267
268 /// Append a value to an env var of the cargo command instance.
269 /// If the variable was unset previously, this is equivalent to [`Cargo::env`].
270 /// If the variable was already set, this will append `delimiter` and then `value` to it.
271 ///
272 /// Note that this only considers the existence of the env. var. configured on this `Cargo`
273 /// instance. It does not look at the environment of this process.
274 pub(crate) fn append_to_env(
275 &mut self,
276 key: impl AsRef<OsStr>,
277 value: impl AsRef<OsStr>,
278 delimiter: impl AsRef<OsStr>,
279 ) -> &mut Cargo {
280 assert_ne!(key.as_ref(), "RUSTFLAGS");
281 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
282
283 let key = key.as_ref();
284 if let Some((_, Some(previous_value))) = self.command.get_envs().find(|(k, _)| *k == key) {
285 let mut combined: OsString = previous_value.to_os_string();
286 combined.push(delimiter.as_ref());
287 combined.push(value.as_ref());
288 self.env(key, combined)
289 } else {
290 self.env(key, value)
291 }
292 }
293
294 pub(crate) fn add_rustc_lib_path(&mut self, builder: &Builder<'_>) {
295 builder.add_rustc_lib_path(self.compiler, &mut self.command);
296 }
297
298 pub(crate) fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
299 self.command.current_dir(dir);
300 self
301 }
302
303 /// Adds nightly-only features that this invocation is allowed to use.
304 ///
305 /// By default, all nightly features are allowed. Once this is called, it will be restricted to
306 /// the given set.
307 pub(crate) fn allow_features(&mut self, features: &str) -> &mut Cargo {
308 if !self.allow_features.is_empty() {
309 self.allow_features.push(',');
310 }
311 self.allow_features.push_str(features);
312 self
313 }
314
315 // FIXME(onur-ozkan): Add coverage to make sure modifications to this function
316 // doesn't cause cache invalidations (e.g., #130108).
317 fn configure_linker(&mut self, builder: &Builder<'_>) -> &mut Cargo {
318 let target = self.target;
319 let compiler = self.compiler;
320
321 // Dealing with rpath here is a little special, so let's go into some
322 // detail. First off, `-rpath` is a linker option on Unix platforms
323 // which adds to the runtime dynamic loader path when looking for
324 // dynamic libraries. We use this by default on Unix platforms to ensure
325 // that our nightlies behave the same on Windows, that is they work out
326 // of the box. This can be disabled by setting `rpath = false` in `[rust]`
327 // table of `bootstrap.toml`
328 //
329 // Ok, so the astute might be wondering "why isn't `-C rpath` used
330 // here?" and that is indeed a good question to ask. This codegen
331 // option is the compiler's current interface to generating an rpath.
332 // Unfortunately it doesn't quite suffice for us. The flag currently
333 // takes no value as an argument, so the compiler calculates what it
334 // should pass to the linker as `-rpath`. This unfortunately is based on
335 // the **compile time** directory structure which when building with
336 // Cargo will be very different than the runtime directory structure.
337 //
338 // All that's a really long winded way of saying that if we use
339 // `-Crpath` then the executables generated have the wrong rpath of
340 // something like `$ORIGIN/deps` when in fact the way we distribute
341 // rustc requires the rpath to be `$ORIGIN/../lib`.
342 //
343 // So, all in all, to set up the correct rpath we pass the linker
344 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
345 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
346 // to change a flag in a binary?
347 if builder.config.rpath_enabled(target) && helpers::use_host_linker(target) {
348 let libdir = builder.sysroot_libdir_relative(compiler).to_str().unwrap();
349 let rpath = if target.contains("apple") {
350 // Note that we need to take one extra step on macOS to also pass
351 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
352 // do that we pass a weird flag to the compiler to get it to do
353 // so. Note that this is definitely a hack, and we should likely
354 // flesh out rpath support more fully in the future.
355 self.rustflags.arg("-Zosx-rpath-install-name");
356 Some(format!("-Wl,-rpath,@loader_path/../{libdir}"))
357 } else if !target.is_windows()
358 && !target.contains("cygwin")
359 && !target.contains("aix")
360 && !target.contains("xous")
361 {
362 self.rustflags.arg("-Clink-args=-Wl,-z,origin");
363 Some(format!("-Wl,-rpath,$ORIGIN/../{libdir}"))
364 } else {
365 None
366 };
367 if let Some(rpath) = rpath {
368 self.rustflags.arg(&format!("-Clink-args={rpath}"));
369 }
370 }
371
372 // We need to set host linker flags for compiling build scripts and proc-macros.
373 // This is done the same way as the target linker flags below, so cargo won't see
374 // any fingerprint difference between host==target versus cross-compiled targets
375 // when it comes to those host build artifacts.
376 if let Some(host_linker) = builder.linker(compiler.host) {
377 let host = envify(&compiler.host.triple);
378 self.command.env(format!("CARGO_TARGET_{host}_LINKER"), host_linker);
379 }
380 for arg in linker_flags(builder, compiler.host, LldThreads::Yes) {
381 self.hostflags.arg(&arg);
382 }
383
384 if let Some(target_linker) = builder.linker(target) {
385 let target = envify(&target.triple);
386 self.command.env(format!("CARGO_TARGET_{target}_LINKER"), target_linker);
387 }
388 // We want to set -Clinker using Cargo, therefore we only call `linker_flags` and not
389 // `linker_args` here. Cargo will pass that to both rustc and rustdoc invocations.
390 for flag in linker_flags(builder, target, LldThreads::Yes) {
391 self.rustflags.arg(&flag);
392 }
393 for arg in linker_flags(builder, target, LldThreads::Yes) {
394 self.rustdocflags.arg(&arg);
395 }
396
397 match builder.config.compress_debuginfo(target) {
398 CompressDebuginfo::Zlib => {
399 // Do not enable Zlib compression on:
400 // - Windows, because MSVC/PDB doesn't support it
401 // - macOS, because its linker doesn't know the flag
402 // - Cygwin, because its linker may not support the flag
403 if !self.target.is_windows() && !self.target.is_apple() && !self.target.is_cygwin()
404 {
405 // If we link through cc, we need the -Wl prefix.
406 // If we don't, then we must not add it, because the linker wouldn't
407 // understand it.
408 if helpers::use_host_linker(target) {
409 self.rustflags.arg("-Clink-arg=-Wl,--compress-debug-sections=zlib");
410 } else {
411 self.rustflags.arg("-Clink-arg=--compress-debug-sections=zlib");
412 }
413 }
414 }
415 CompressDebuginfo::Off => {}
416 }
417
418 // Ignore linker warnings for now. These are complicated to fix and don't affect the build.
419 // FIXME: we should really investigate these...
420 self.rustflags.arg("-Alinker-messages");
421
422 // Throughout the build Cargo can execute a number of build scripts
423 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
424 // obtained previously to those build scripts.
425 // Build scripts use either the `cc` crate or `configure/make` so we pass
426 // the options through environment variables that are fetched and understood by both.
427 //
428 // FIXME: the guard against msvc shouldn't need to be here
429 if target.is_msvc() {
430 if let Some(ref cl) = builder.config.llvm_clang_cl {
431 // FIXME: There is a bug in Clang 18 when building for ARM64:
432 // https://github.com/llvm/llvm-project/pull/81849. This is
433 // fixed in LLVM 19, but can't be backported.
434 if !target.starts_with("aarch64") && !target.starts_with("arm64ec") {
435 self.command.env("CC", cl).env("CXX", cl);
436 }
437 }
438 } else {
439 let ccache = builder.config.ccache.as_ref();
440 let ccacheify = |s: &Path| {
441 let ccache = match ccache {
442 Some(ref s) => s,
443 None => return s.display().to_string(),
444 };
445 // FIXME: the cc-rs crate only recognizes the literal strings
446 // `ccache` and `sccache` when doing caching compilations, so we
447 // mirror that here. It should probably be fixed upstream to
448 // accept a new env var or otherwise work with custom ccache
449 // vars.
450 match &ccache[..] {
451 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
452 _ => s.display().to_string(),
453 }
454 };
455 let triple_underscored = target.triple.replace('-', "_");
456 let cc = ccacheify(&builder.cc(target));
457 self.command.env(format!("CC_{triple_underscored}"), &cc);
458
459 // Compiling C deps, like jemalloc and llvm-wrapper, should be with
460 // the same LTO mode as the Rust code they are linked into.
461 //
462 // Std's C deps, e.g. compiler_builtins, ship inside rlibs that
463 // end users consume directly. Building with `-flto` may break
464 // non-LLVM linkers or mismatch on bitcode versions. Therefore we
465 // must not build std in LTO mode here.
466 let lto_cflag = if matches!(self.mode, Mode::Rustc | Mode::ToolRustcPrivate)
467 && is_lto_stage(&self.compiler)
468 && builder.cc_tool(target).is_like_clang()
469 // Exclude aarch64-linux as we can't assume the user has an LTO-capable linker
470 // (and these files get distributed in the rustc-dev component).
471 // FIXME: this means the argument above about doing this for rustc but not std makes
472 // no sense. We distribute rlibs for both, so both need to be linkable by users. I
473 // guess we just don't want to risk this for std, but are less worried about
474 // breaking rustc-dev.
475 && !target.starts_with("aarch64-unknown-linux")
476 {
477 match builder.config.rust_lto {
478 RustcLto::Thin => Some("-flto=thin"),
479 RustcLto::Fat => Some("-flto=full"),
480 RustcLto::ThinLocal | RustcLto::Off => None,
481 }
482 } else {
483 None
484 };
485
486 // Extend `CFLAGS_$TARGET` with our extra flags.
487 let env = format!("CFLAGS_{triple_underscored}");
488 let mut cflags = builder.cc_unhandled_cflags(target, CLang::C).join(" ");
489 if let Some(lto_cflag) = lto_cflag {
490 cflags.push(' ');
491 cflags.push_str(lto_cflag);
492 }
493 if let Ok(var) = std::env::var(&env) {
494 cflags.push(' ');
495 cflags.push_str(&var);
496 }
497 self.command.env(env, &cflags);
498
499 if let Some(ar) = builder.ar(target) {
500 let ranlib = format!("{} s", ar.display());
501 self.command
502 .env(format!("AR_{triple_underscored}"), ar)
503 .env(format!("RANLIB_{triple_underscored}"), ranlib);
504 }
505
506 if let Ok(cxx) = builder.cxx(target) {
507 let cxx = ccacheify(&cxx);
508 self.command.env(format!("CXX_{triple_underscored}"), &cxx);
509
510 // Extend `CXXFLAGS_$TARGET` with our extra flags.
511 let env = format!("CXXFLAGS_{triple_underscored}");
512 let mut cxxflags = builder.cc_unhandled_cflags(target, CLang::Cxx).join(" ");
513 if let Some(lto_cflag) = lto_cflag {
514 cxxflags.push(' ');
515 cxxflags.push_str(lto_cflag);
516 }
517 if let Ok(var) = std::env::var(&env) {
518 cxxflags.push(' ');
519 cxxflags.push_str(&var);
520 }
521 self.command.env(&env, cxxflags);
522 }
523 }
524
525 self
526 }
527}
528
529impl From<Cargo> for BootstrapCommand {
530 fn from(mut cargo: Cargo) -> BootstrapCommand {
531 if let Some(profile) = cargo.profile {
532 cargo.args.insert(0, format!("--profile={profile}").into());
533 }
534
535 for arg in &cargo.extra_rustflags {
536 cargo.rustflags.arg(arg);
537 cargo.rustdocflags.arg(arg);
538 }
539
540 // Propagate the envs here at the very end to make sure they override any previously set flags.
541 cargo.rustflags.propagate_rustflag_envs(cargo.build_compiler_stage);
542 cargo.rustdocflags.propagate_rustflag_envs(cargo.build_compiler_stage);
543
544 cargo.rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
545
546 if cargo.build_compiler_stage == 0 {
547 cargo.rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
548 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
549 cargo.args(s.split_whitespace());
550 }
551 } else {
552 cargo.rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
553 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
554 cargo.args(s.split_whitespace());
555 }
556 }
557
558 if let Ok(s) = env::var("CARGOFLAGS") {
559 cargo.args(s.split_whitespace());
560 }
561
562 cargo.command.args(cargo.args);
563
564 // Unset any inherited flag variables (plain and encoded) so cargo uses only the flags
565 // bootstrap sets below. Flags from the caller's environment have already been folded into
566 // the Rustflags struct via `propagate_cargo_env`. This also matters because we may set the
567 // plain form below, which cargo ignores when `CARGO_ENCODED_RUSTFLAGS` is also present.
568 cargo.command.env_remove("RUSTFLAGS");
569 cargo.command.env_remove("CARGO_ENCODED_RUSTFLAGS");
570 cargo.command.env_remove("RUSTDOCFLAGS");
571 cargo.command.env_remove("CARGO_ENCODED_RUSTDOCFLAGS");
572
573 if !cargo.rustflags.0.is_empty() {
574 let (var, value) =
575 flags_env("RUSTFLAGS", "CARGO_ENCODED_RUSTFLAGS", &cargo.rustflags.0);
576 cargo.command.env(var, value);
577 }
578
579 if !cargo.rustdocflags.0.is_empty() {
580 let (var, value) =
581 flags_env("RUSTDOCFLAGS", "CARGO_ENCODED_RUSTDOCFLAGS", &cargo.rustdocflags.0);
582 cargo.command.env(var, value);
583 }
584
585 let encoded_hostflags = cargo.hostflags.encode();
586 if !encoded_hostflags.is_empty() {
587 cargo.command.env("RUSTC_HOST_FLAGS", encoded_hostflags);
588 }
589
590 if !cargo.allow_features.is_empty() {
591 cargo.command.env("RUSTC_ALLOW_FEATURES", cargo.allow_features);
592 }
593
594 cargo.command
595 }
596}
597
598impl Builder<'_> {
599 /// Like [`Builder::cargo`], but only passes flags that are valid for all commands.
600 #[track_caller]
601 pub(crate) fn bare_cargo(
602 &self,
603 compiler: Compiler,
604 mode: Mode,
605 target: TargetSelection,
606 cmd_kind: Kind,
607 ) -> BootstrapCommand {
608 let mut cargo = match cmd_kind {
609 Kind::Clippy => {
610 let mut cargo = self.cargo_clippy_cmd(compiler);
611 cargo.arg(cmd_kind.as_str());
612 cargo
613 }
614 Kind::MiriSetup => {
615 let mut cargo = self.cargo_miri_cmd(compiler);
616 cargo.arg("miri").arg("setup");
617 cargo
618 }
619 Kind::MiriTest => {
620 let mut cargo = self.cargo_miri_cmd(compiler);
621 cargo.arg("miri").arg("test");
622 cargo
623 }
624 _ => {
625 let mut cargo = command(&self.initial_cargo);
626 cargo.arg(cmd_kind.as_str());
627 cargo
628 }
629 };
630
631 // Optionally suppress cargo output.
632 if self.config.quiet {
633 cargo.arg("--quiet");
634 }
635
636 // Run cargo from the source root so it can find .cargo/config.
637 // This matters when using vendoring and the working directory is outside the repository.
638 cargo.current_dir(&self.src);
639
640 let out_dir = self.stage_out(compiler, mode);
641 cargo.env("CARGO_TARGET_DIR", &out_dir);
642
643 // Bootstrap makes a lot of assumptions about the artifacts produced in the target
644 // directory. If users override the "build directory" using `build-dir`
645 // (https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-dir), then
646 // bootstrap couldn't find these artifacts. So we forcefully override that option to our
647 // target directory here.
648 // In the future, we could attempt to read the build-dir location from Cargo and actually
649 // respect it.
650 cargo.env("CARGO_BUILD_BUILD_DIR", &out_dir);
651
652 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
653 // from out of tree it shouldn't matter, since x.py is only used for
654 // building in-tree.
655 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
656 match self.sess.config.color {
657 Color::Always => {
658 cargo.arg("--color=always");
659 for log in &color_logs {
660 cargo.env(log, "always");
661 }
662 }
663 Color::Never => {
664 cargo.arg("--color=never");
665 for log in &color_logs {
666 cargo.env(log, "never");
667 }
668 }
669 Color::Auto => {} // nothing to do
670 }
671
672 if cmd_kind != Kind::Install {
673 cargo.arg("--target").arg(target.rustc_target_arg());
674 } else {
675 assert_eq!(target, compiler.host);
676 }
677
678 // Bootstrap only supports modern FIFO jobservers. Older pipe-based jobservers can run into
679 // "invalid file descriptor" errors, as the jobserver file descriptors are not inherited by
680 // scripts like bootstrap.py, while the environment variable is propagated. So, we pass
681 // MAKEFLAGS only if we detect a FIFO jobserver, otherwise we clear it.
682 let has_modern_jobserver = env::var("MAKEFLAGS")
683 .map(|flags| flags.contains("--jobserver-auth=fifo:"))
684 .unwrap_or(false);
685
686 if !has_modern_jobserver {
687 cargo.env_remove("MAKEFLAGS");
688 cargo.env_remove("MFLAGS");
689 }
690
691 cargo
692 }
693
694 /// This will create a [`BootstrapCommand`] that represents a pending execution of cargo. This
695 /// cargo will be configured to use `compiler` as the actual rustc compiler, its output will be
696 /// scoped by `mode`'s output directory, it will pass the `--target` flag for the specified
697 /// `target`, and will be executing the Cargo command `cmd`. `cmd` can be `miri-cmd` for
698 /// commands to be run with Miri.
699 #[track_caller]
700 fn cargo(
701 &self,
702 compiler: Compiler,
703 mode: Mode,
704 source_type: SourceType,
705 target: TargetSelection,
706 cmd_kind: Kind,
707 ) -> Cargo {
708 let mut cargo = self.bare_cargo(compiler, mode, target, cmd_kind);
709 let out_dir = self.stage_out(compiler, mode);
710
711 let mut hostflags = HostFlags::default();
712
713 cargo.env("CARGO_UNSTABLE_BUILD_DIR_NEW_LAYOUT", "true");
714
715 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
716 // so we need to explicitly clear out if they've been updated.
717 for backend in self.codegen_backends(compiler) {
718 build_stamp::clear_if_dirty(self, &out_dir, &backend);
719 }
720
721 if self.config.cmd.timings() {
722 cargo.arg("--timings");
723 }
724
725 if cmd_kind == Kind::Doc {
726 // Will be stabilized soon -> let's dogfood it.
727 // No effect on doc output but massive doc-generation time improvements.
728 cargo.arg("-Zrustdoc-mergeable-info");
729
730 // FIXME: remove this directory clearing here, and do it explicitly in individua doc
731 // steps, to reduce dependency on implicit doc output paths.
732 let my_out = match mode {
733 // This is the intended out directory for compiler documentation.
734 Mode::Rustc | Mode::ToolRustcPrivate | Mode::ToolBootstrap | Mode::ToolTarget => {
735 self.compiler_doc_out(target)
736 }
737 Mode::Std => {
738 if self.config.cmd.json() {
739 out_dir.join(target).join("json-doc")
740 } else {
741 out_dir.join(target).join("doc")
742 }
743 }
744 _ => panic!("doc mode {mode:?} not expected"),
745 };
746 let rustdoc = self.rustdoc_for_compiler(compiler);
747 build_stamp::clear_if_dirty(self, &my_out, &rustdoc);
748 }
749
750 let profile_var = |name: &str| cargo_profile_var(name, &self.config, mode);
751
752 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
753 // needs to not accidentally link to libLLVM in stage0/lib.
754 cargo.env("REAL_LIBRARY_PATH_VAR", helpers::dylib_path_var());
755 if let Some(e) = env::var_os(helpers::dylib_path_var()) {
756 cargo.env("REAL_LIBRARY_PATH", e);
757 }
758
759 // Forward `./x fix --allow-dirty` from bootstrap to cargo.
760 if matches!(cmd_kind, Kind::Fix)
761 && let Subcommand::Fix { allow_dirty } = self.config.cmd
762 && allow_dirty
763 {
764 cargo.arg("--allow-dirty");
765 }
766
767 let build_compiler_stage = if compiler.stage == 0 && self.local_rebuild {
768 // Assume the local-rebuild rustc already has stage1 features.
769 1
770 } else {
771 compiler.stage
772 };
773
774 // We synthetically interpret a stage0 compiler used to build tools as a
775 // "raw" compiler in that it's the exact snapshot we download. For things like
776 // ToolRustcPrivate, we would have to use the artificial stage0-sysroot compiler instead.
777 let use_snapshot =
778 mode == Mode::ToolBootstrap || (mode == Mode::ToolTarget && build_compiler_stage == 0);
779 assert!(!use_snapshot || build_compiler_stage == 0 || self.local_rebuild);
780
781 let sysroot = if use_snapshot {
782 self.rustc_snapshot_sysroot().to_path_buf()
783 } else {
784 self.sysroot(compiler)
785 };
786 let libdir = self.rustc_libdir(compiler);
787
788 let sysroot_str = sysroot.as_os_str().to_str().expect("sysroot should be UTF-8");
789 if self.is_verbose() && !matches!(self.config.get_dry_run(), DryRun::SelfCheck) {
790 println!("using sysroot {sysroot_str}");
791 }
792
793 let mut rustflags = Rustflags::new(target);
794
795 if cmd_kind == Kind::Clippy {
796 // clippy overwrites sysroot if we pass it to cargo.
797 // Pass it directly to clippy instead.
798 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
799 // so it has no way of knowing the sysroot.
800 rustflags.arg("--sysroot");
801 rustflags.arg(sysroot_str);
802 }
803
804 // By default, windows-rs depends on a native library that doesn't get copied into the
805 // sysroot. Passing this cfg enables raw-dylib support instead, which makes the native
806 // library unnecessary. This can be removed when windows-rs enables raw-dylib
807 // unconditionally.
808 if let Mode::Rustc | Mode::ToolRustcPrivate | Mode::ToolBootstrap | Mode::ToolTarget = mode
809 {
810 rustflags.arg("--cfg=windows_raw_dylib");
811 }
812
813 // When unset, follow the default of the compiler flag - the compiler, tools and std use v0
814 if let Some(usm) = self.config.rust_new_symbol_mangling {
815 rustflags.arg(if usm {
816 "-Csymbol-mangling-version=v0"
817 } else {
818 "-Csymbol-mangling-version=legacy"
819 });
820 }
821
822 // Always enable move/copy annotations for profiler visibility (non-stage0 only).
823 // Note that -Zannotate-moves is only effective with debugging info enabled.
824 if build_compiler_stage >= 1 {
825 if let Some(limit) = self.config.rust_annotate_moves_size_limit {
826 rustflags.arg(&format!("-Zannotate-moves={limit}"));
827 } else {
828 rustflags.arg("-Zannotate-moves");
829 }
830 }
831
832 // FIXME: the following components don't build with `-Zrandomize-layout` yet:
833 // - rust-analyzer, due to the rowan crate
834 // so we exclude an entire category of steps here due to lack of fine-grained control over
835 // rustflags.
836 if self.config.rust_randomize_layout && mode != Mode::ToolRustcPrivate {
837 rustflags.arg("-Zrandomize-layout");
838 }
839
840 // Enable compile-time checking of `cfg` names, values and Cargo `features`.
841 //
842 // Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like
843 // backtrace, core_simd, std_float, ...), those dependencies have their own
844 // features but cargo isn't involved in the #[path] process and so cannot pass the
845 // complete list of features, so for that reason we don't enable checking of
846 // features for std crates.
847 if mode == Mode::Std {
848 rustflags.arg("--check-cfg=cfg(feature,values(any()))");
849 }
850
851 // Add extra cfg not defined in/by rustc
852 //
853 // Note: Although it would seems that "-Zunstable-options" to `rustflags` is useless as
854 // cargo would implicitly add it, it was discover that sometimes bootstrap only use
855 // `rustflags` without `cargo` making it required.
856 rustflags.arg("-Zunstable-options");
857
858 // Add parallel frontend threads configuration
859 if let Some(threads) = self.config.rust_parallel_frontend_threads {
860 rustflags.arg(&format!("-Zthreads={threads}"));
861 }
862
863 for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
864 if restricted_mode.is_none() || *restricted_mode == Some(mode) {
865 rustflags.arg(&check_cfg_arg(name, *values));
866
867 if *name == "bootstrap" {
868 // Cargo doesn't pass RUSTFLAGS to proc_macros:
869 // https://github.com/rust-lang/cargo/issues/4423
870 // Thus, if we are on stage 0, we explicitly set `--cfg=bootstrap`.
871 // We also declare that the flag is expected, which we need to do to not
872 // get warnings about it being unexpected.
873 hostflags.arg(check_cfg_arg(name, *values));
874 }
875 }
876 }
877
878 // FIXME(rust-lang/cargo#5754) we shouldn't be using special command arguments
879 // to the host invocation here, but rather Cargo should know what flags to pass rustc
880 // itself.
881 if build_compiler_stage == 0 {
882 hostflags.arg("--cfg=bootstrap");
883 }
884
885 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
886 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
887 // #71458.
888 let mut rustdocflags = rustflags.clone();
889
890 match mode {
891 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {}
892 Mode::Rustc | Mode::Codegen | Mode::ToolRustcPrivate => {
893 // Build proc macros both for the host and the target unless proc-macros are not
894 // supported by the target.
895 if target != compiler.host && cmd_kind != Kind::Check {
896 let error = self
897 .rustc_cmd(compiler)
898 .arg("--target")
899 .arg(target.rustc_target_arg())
900 // FIXME(#152709): -Zunstable-options is to handle JSON targets.
901 // Remove when JSON targets are stabilized.
902 .arg("-Zunstable-options")
903 .env("RUSTC_BOOTSTRAP", "1")
904 .arg("--print=file-names")
905 .arg("--crate-type=proc-macro")
906 .arg("-")
907 .stdin(std::process::Stdio::null())
908 .run_capture(self)
909 .stderr();
910
911 let not_supported = error
912 .lines()
913 .any(|line| line.contains("unsupported crate type `proc-macro`"));
914 if !not_supported {
915 cargo.arg("-Zdual-proc-macros");
916 rustflags.arg("-Zdual-proc-macros");
917 }
918 }
919 }
920 }
921
922 // This tells Cargo (and in turn, rustc) to output more complete
923 // dependency information. Most importantly for bootstrap, this
924 // includes sysroot artifacts, like libstd, which means that we don't
925 // need to track those in bootstrap (an error prone process!). This
926 // feature is currently unstable as there may be some bugs and such, but
927 // it represents a big improvement in bootstrap's reliability on
928 // rebuilds, so we're using it here.
929 //
930 // For some additional context, see #63470 (the PR originally adding
931 // this), as well as #63012 which is the tracking issue for this
932 // feature on the rustc side.
933 cargo.arg("-Zbinary-dep-depinfo");
934 let allow_features = match mode {
935 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {
936 // Restrict the allowed features so we don't depend on nightly
937 // accidentally.
938 //
939 // binary-dep-depinfo is used by bootstrap itself for all
940 // compilations.
941 //
942 // Lots of tools depend on proc_macro2 and proc-macro-error.
943 // Those have build scripts which assume nightly features are
944 // available if the `rustc` version is "nighty" or "dev". See
945 // bin/rustc.rs for why that is a problem. Instead of labeling
946 // those features for each individual tool that needs them,
947 // just blanket allow them here.
948 //
949 // If this is ever removed, be sure to add something else in
950 // its place to keep the restrictions in place (or make a way
951 // to unset RUSTC_BOOTSTRAP).
952 "binary-dep-depinfo,proc_macro_span,proc_macro_span_shrink,proc_macro_diagnostic"
953 .to_string()
954 }
955 Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustcPrivate => String::new(),
956 };
957
958 cargo.arg("-j").arg(self.jobs().to_string());
959
960 // Make cargo emit diagnostics relative to the rustc src dir.
961 cargo.arg(format!("-Zroot-dir={}", self.src.display()));
962
963 if self.config.compile_time_deps {
964 // Build only build scripts and proc-macros for rust-analyzer when requested.
965 cargo.arg("-Zunstable-options");
966 cargo.arg("--compile-time-deps");
967 }
968
969 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
970 // Force cargo to output binaries with disambiguating hashes in the name
971 let mut metadata = if compiler.stage == 0 {
972 // Treat stage0 like a special channel, whether it's a normal prior-
973 // release rustc or a local rebuild with the same version, so we
974 // never mix these libraries by accident.
975 "bootstrap".to_string()
976 } else {
977 self.config.channel.to_string()
978 };
979 // We want to make sure that none of the dependencies between
980 // std/test/rustc unify with one another. This is done for weird linkage
981 // reasons but the gist of the problem is that if librustc, libtest, and
982 // libstd all depend on libc from crates.io (which they actually do) we
983 // want to make sure they all get distinct versions. Things get really
984 // weird if we try to unify all these dependencies right now, namely
985 // around how many times the library is linked in dynamic libraries and
986 // such. If rustc were a static executable or if we didn't ship dylibs
987 // this wouldn't be a problem, but we do, so it is. This is in general
988 // just here to make sure things build right. If you can remove this and
989 // things still build right, please do!
990 match mode {
991 Mode::Std => metadata.push_str("std"),
992 // When we're building rustc tools, they're built with a search path
993 // that contains things built during the rustc build. For example,
994 // bitflags is built during the rustc build, and is a dependency of
995 // rustdoc as well. We're building rustdoc in a different target
996 // directory, though, which means that Cargo will rebuild the
997 // dependency. When we go on to build rustdoc, we'll look for
998 // bitflags, and find two different copies: one built during the
999 // rustc step and one that we just built. This isn't always a
1000 // problem, somehow -- not really clear why -- but we know that this
1001 // fixes things.
1002 Mode::ToolRustcPrivate => metadata.push_str("tool-rustc"),
1003 // Same for codegen backends.
1004 Mode::Codegen => metadata.push_str("codegen"),
1005 _ => {}
1006 }
1007 // `rustc_driver`'s version number is always `0.0.0`, which can cause linker search path
1008 // problems on side-by-side installs because we don't include the version number of the
1009 // `rustc_driver` being built. This can cause builds of different version numbers to produce
1010 // `librustc_driver*.so` artifacts that end up with identical filename hashes.
1011 metadata.push_str(&self.version);
1012
1013 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1014
1015 if cmd_kind == Kind::Clippy {
1016 rustflags.arg("-Zforce-unstable-if-unmarked");
1017 }
1018
1019 rustflags.arg("-Zmacro-backtrace");
1020
1021 // Clear the output directory if the real rustc we're using has changed;
1022 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1023 //
1024 // Avoid doing this during dry run as that usually means the relevant
1025 // compiler is not yet linked/copied properly.
1026 //
1027 // Only clear out the directory if we're running Cargo on std; otherwise, we
1028 // should let Cargo take care of things for us (via depdep info)
1029 if !self.config.dry_run() && mode == Mode::Std {
1030 build_stamp::clear_if_dirty(self, &out_dir, &self.rustc(compiler));
1031 }
1032
1033 let rustdoc_path = match cmd_kind {
1034 Kind::Doc => self.rustdoc_for_compiler(compiler),
1035 Kind::Test | Kind::MiriTest if self.test_target.runs_doctests() => {
1036 self.rustdoc_for_compiler(compiler)
1037 }
1038 _ => PathBuf::from("/path/to/nowhere/rustdoc/not/required"),
1039 };
1040
1041 // Customize the compiler we're running. Specify the compiler to cargo
1042 // as our shim and then pass it some various options used to configure
1043 // how the actual compiler itself is called.
1044 //
1045 // These variables are primarily all read by
1046 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1047 cargo
1048 .env("RUSTC_REAL", self.rustc(compiler))
1049 .env("RUSTC_STAGE", build_compiler_stage.to_string())
1050 .env("RUSTC_SYSROOT", sysroot)
1051 .env("RUSTC_LIBDIR", &libdir)
1052 .env("RUSTDOC_LIBDIR", libdir)
1053 .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
1054 .env("RUSTDOC_REAL", rustdoc_path);
1055
1056 if self.config.rust_break_on_ice {
1057 cargo.env("RUSTC_BREAK_ON_ICE", "1");
1058 }
1059
1060 // Set RUSTC_WRAPPER to the bootstrap shim, which switches between beta and in-tree
1061 // sysroot depending on whether we're building build scripts.
1062 // NOTE: we intentionally use RUSTC_WRAPPER so that we can support clippy - RUSTC is not
1063 // respected by clippy-driver; RUSTC_WRAPPER happens earlier, before clippy runs.
1064 cargo.env("RUSTC_WRAPPER", self.bootstrap_out.join("rustc"));
1065 // NOTE: we also need to set RUSTC so cargo can run `rustc -vV`; apparently that ignores RUSTC_WRAPPER >:(
1066 cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
1067
1068 // Someone might have set some previous rustc wrapper (e.g.
1069 // sccache) before bootstrap overrode it. Respect that variable.
1070 if let Some(existing_wrapper) = env::var_os("RUSTC_WRAPPER") {
1071 cargo.env("RUSTC_WRAPPER_REAL", existing_wrapper);
1072 }
1073
1074 // If this is for `miri-test`, prepare the sysroots.
1075 if cmd_kind == Kind::MiriTest {
1076 self.std(compiler, compiler.host);
1077 let host_sysroot = self.sysroot(compiler);
1078 let miri_sysroot = test::Miri::build_miri_sysroot(self, compiler, target);
1079 cargo.env("MIRI_SYSROOT", &miri_sysroot);
1080 cargo.env("MIRI_HOST_SYSROOT", &host_sysroot);
1081 }
1082
1083 cargo.env(profile_var("STRIP"), self.config.rust_strip.to_string());
1084
1085 if let Some(stack_protector) = &self.config.rust_stack_protector {
1086 rustflags.arg(&format!("-Zstack-protector={stack_protector}"));
1087 }
1088
1089 let debuginfo_level = match mode {
1090 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1091 Mode::Std => self.config.rust_debuginfo_level_std,
1092 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustcPrivate | Mode::ToolTarget => {
1093 self.config.rust_debuginfo_level_tools
1094 }
1095 };
1096 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1097 if let Some(opt_level) = &self.config.rust_optimize.get_opt_level() {
1098 cargo.env(profile_var("OPT_LEVEL"), opt_level);
1099 }
1100 cargo.env(
1101 profile_var("DEBUG_ASSERTIONS"),
1102 match mode {
1103 Mode::Std => self.config.std_debug_assertions,
1104 Mode::Rustc | Mode::Codegen => self.config.rustc_debug_assertions,
1105 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustcPrivate | Mode::ToolTarget => {
1106 self.config.tools_debug_assertions
1107 }
1108 }
1109 .to_string(),
1110 );
1111 cargo.env(
1112 profile_var("OVERFLOW_CHECKS"),
1113 if mode == Mode::Std {
1114 self.config.rust_overflow_checks_std.to_string()
1115 } else {
1116 self.config.rust_overflow_checks.to_string()
1117 },
1118 );
1119
1120 match self.config.split_debuginfo(target) {
1121 SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
1122 SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
1123 SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
1124 };
1125
1126 if self.config.cmd.bless() {
1127 // Bless `expect!` tests.
1128 cargo.env("UPDATE_EXPECT", "1");
1129 }
1130
1131 // Set an environment variable that tells the rustc/rustdoc wrapper
1132 // binary to pass `-Zforce-unstable-if-unmarked` to the real compiler.
1133 match mode {
1134 // Any library crate that's part of the sysroot should be marked unstable
1135 // (including third-party dependencies), unless it uses a staged_api
1136 // `#![stable(..)]` attribute to explicitly mark itself stable.
1137 Mode::Std | Mode::Codegen | Mode::Rustc => {
1138 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1139 }
1140
1141 // For everything else, crate stability shouldn't matter, so don't set a flag.
1142 Mode::ToolBootstrap | Mode::ToolRustcPrivate | Mode::ToolStd | Mode::ToolTarget => {}
1143 }
1144
1145 if let Some(x) = self.crt_static(target) {
1146 if x {
1147 rustflags.arg("-Ctarget-feature=+crt-static");
1148 } else {
1149 rustflags.arg("-Ctarget-feature=-crt-static");
1150 }
1151 }
1152
1153 if let Some(x) = self.crt_static(compiler.host) {
1154 let sign = if x { "+" } else { "-" };
1155 hostflags.arg(format!("-Ctarget-feature={sign}crt-static"));
1156 }
1157
1158 // `rustc` needs to know the remapping scheme, in order to know how to reverse it (unremap)
1159 // later. Two env vars are set and made available to the compiler
1160 //
1161 // - `CFG_VIRTUAL_RUST_SOURCE_BASE_DIR`: `rust-src` remap scheme (`NonCompiler`)
1162 // - `CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR`: `rustc-dev` remap scheme (`Compiler`)
1163 //
1164 // Keep this scheme in sync with `rustc_metadata::rmeta::decoder`'s
1165 // `try_to_translate_virtual_to_real`.
1166 let trim_paths = |cargo: &mut BootstrapCommand, ws_remap: &str| {
1167 cargo.arg("-Ztrim-paths");
1168 cargo.arg("--config").arg("profile.release.trim-paths='all'");
1169 cargo.arg("--config").arg("profile.dev.trim-paths='all'");
1170 // This is an internal contract with cargo.
1171 // bootstrap needs workspace sources remapped to `/rust{c,-dev}/<sha>` instead of `.`
1172 // See <https://github.com/rust-lang/cargo/issues/17309>.
1173 cargo.env("__CARGO_RUSTC_BOOTSTRAP_WS_REMAP", ws_remap);
1174 };
1175
1176 match mode {
1177 Mode::Rustc | Mode::Codegen => {
1178 if let Some(ref map_to) = self.sess.debuginfo_map_to(RemapScheme::NonCompiler) {
1179 // Tell the compiler which prefix was used for remapping the standard library
1180 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1181 }
1182
1183 if let Some(ref map_to) = self.sess.debuginfo_map_to(RemapScheme::Compiler) {
1184 // Tell the compiler which prefix was used for remapping the compiler it-self
1185 cargo.env("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR", map_to);
1186
1187 trim_paths(&mut cargo, map_to);
1188 }
1189 }
1190 Mode::Std
1191 | Mode::ToolBootstrap
1192 | Mode::ToolRustcPrivate
1193 | Mode::ToolStd
1194 | Mode::ToolTarget => {
1195 if let Some(ref map_to) = self.sess.debuginfo_map_to(RemapScheme::NonCompiler) {
1196 trim_paths(&mut cargo, map_to);
1197 }
1198 }
1199 }
1200
1201 // Enable usage of unstable features
1202 cargo.env("RUSTC_BOOTSTRAP", "1");
1203
1204 cargo.arg("-Zembed-metadata=no");
1205
1206 if self.config.dump_bootstrap_shims {
1207 prepare_shims_dump_dir(self);
1208
1209 cargo
1210 .env("DUMP_BOOTSTRAP_SHIMS", self.sess.out.join("bootstrap-shims-dump"))
1211 .env("BUILD_OUT", &self.sess.out)
1212 .env("CARGO_HOME", t!(home::cargo_home()));
1213 };
1214
1215 self.add_rust_test_threads(&mut cargo);
1216
1217 // Almost all of the crates that we compile as part of the bootstrap may
1218 // have a build script, including the standard library. To compile a
1219 // build script, however, it itself needs a standard library! This
1220 // introduces a bit of a pickle when we're compiling the standard
1221 // library itself.
1222 //
1223 // To work around this we actually end up using the snapshot compiler
1224 // (stage0) for compiling build scripts of the standard library itself.
1225 // The stage0 compiler is guaranteed to have a libstd available for use.
1226 //
1227 // For other crates, however, we know that we've already got a standard
1228 // library up and running, so we can use the normal compiler to compile
1229 // build scripts in that situation.
1230 if mode == Mode::Std {
1231 cargo
1232 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1233 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1234 } else {
1235 cargo
1236 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1237 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1238 }
1239
1240 // Tools that use compiler libraries may inherit the `-lLLVM` link
1241 // requirement, but the `-L` library path is not propagated across
1242 // separate Cargo projects. We can add LLVM's library path to the
1243 // rustc args as a workaround.
1244 if (mode == Mode::ToolRustcPrivate || mode == Mode::Codegen)
1245 && self.is_llvm_enabled_for(target)
1246 {
1247 let llvm_libdir = if self.config.is_host_target(target) {
1248 command(self.host_llvm_config())
1249 .cached()
1250 .arg("--libdir")
1251 .run_capture_stdout(self)
1252 .stdout()
1253 .trim()
1254 .to_owned()
1255 } else {
1256 let llvm_output = self.ensure(Llvm { target });
1257 llvm_output.root_dir().join("lib").to_string_lossy().into_owned()
1258 };
1259 if target.is_msvc() {
1260 rustflags.arg(&format!("-Clink-arg=-LIBPATH:{llvm_libdir}"));
1261 } else {
1262 rustflags.arg(&format!("-Clink-arg=-L{llvm_libdir}"));
1263 }
1264 }
1265
1266 // Compile everything except libraries and proc macros with the more
1267 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1268 // so we can't use it by default in general, but we can use it for tools
1269 // and our own internal libraries.
1270 //
1271 // Cygwin only supports emutls.
1272 if !mode.must_support_dlopen()
1273 && !target.triple.starts_with("powerpc-")
1274 && !target.triple.contains("cygwin")
1275 {
1276 cargo.env("RUSTC_TLS_MODEL_INITIAL_EXEC", "1");
1277 }
1278
1279 // Ignore incremental modes except for stage0, since we're
1280 // not guaranteeing correctness across builds if the compiler
1281 // is changing under your feet.
1282 if self.config.incremental && compiler.stage == 0 {
1283 cargo.env("CARGO_INCREMENTAL", "1");
1284 } else {
1285 // Don't rely on any default setting for incr. comp. in Cargo
1286 cargo.env("CARGO_INCREMENTAL", "0");
1287 }
1288
1289 if let Some(ref on_fail) = self.config.on_fail {
1290 cargo.env("RUSTC_ON_FAIL", on_fail);
1291 }
1292
1293 if self.config.print_step_timings {
1294 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1295 }
1296
1297 if self.config.print_step_rusage {
1298 cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1299 }
1300
1301 if self.config.backtrace_on_ice {
1302 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1303 }
1304
1305 if self.verbosity >= 2 {
1306 // This provides very useful logs especially when debugging build cache-related stuff.
1307 cargo.env("CARGO_LOG", "cargo::core::compiler::fingerprint=info");
1308 }
1309
1310 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1311
1312 // Downstream forks of the Rust compiler might want to use a custom libc to add support for
1313 // targets that are not yet available upstream. Adding a patch to replace libc with a
1314 // custom one would cause compilation errors though, because Cargo would interpret the
1315 // custom libc as part of the workspace, and apply the check-cfg lints on it.
1316 //
1317 // The libc build script emits check-cfg flags only when this environment variable is set,
1318 // so this line allows the use of custom libcs.
1319 cargo.env("LIBC_CHECK_CFG", "1");
1320
1321 let mut lint_flags = Vec::new();
1322
1323 // Lints for all in-tree code: compiler, rustdoc, cranelift, gcc,
1324 // clippy, rustfmt, rust-analyzer, etc.
1325 if source_type == SourceType::InTree {
1326 // When extending this list, add the new lints to the RUSTFLAGS of the
1327 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1328 // some code doesn't go through this `rustc` wrapper.
1329 lint_flags.push("-Wrust_2018_idioms");
1330 lint_flags.push("-Wunused_lifetimes");
1331
1332 if self.config.deny_warnings {
1333 // We use this instead of `lint_flags` so that we don't have to rebuild all
1334 // workspace dependencies when `deny-warnings` changes, but we still get an error
1335 // immediately instead of having to wait until the next rebuild.
1336 cargo.env("CARGO_BUILD_WARNINGS", "deny");
1337 }
1338
1339 rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1340 }
1341
1342 // Lints just for `compiler/` crates.
1343 if mode == Mode::Rustc {
1344 lint_flags.push("-Wrustc::internal");
1345 lint_flags.push("-Drustc::symbol_intern_string_literal");
1346 // FIXME(edition_2024): Change this to `-Wrust_2024_idioms` when all
1347 // of the individual lints are satisfied.
1348 lint_flags.push("-Wkeyword_idents_2024");
1349 lint_flags.push("-Wunreachable_pub");
1350 lint_flags.push("-Wunsafe_op_in_unsafe_fn");
1351 lint_flags.push("-Wunused_crate_dependencies");
1352 }
1353
1354 // This does not use RUSTFLAGS for two reasons.
1355 // - Due to caching issues with Cargo. Clippy is treated as an "in
1356 // tree" tool, but shares the same cache as other "submodule" tools.
1357 // With these options set in RUSTFLAGS, that causes *every* shared
1358 // dependency to be rebuilt. By injecting this into the rustc
1359 // wrapper, this circumvents Cargo's fingerprint detection. This is
1360 // fine because lint flags are always ignored in dependencies.
1361 // Eventually this should be fixed via better support from Cargo.
1362 // - RUSTFLAGS is ignored for proc macro crates that are being built on
1363 // the host (because `--target` is given). But we want the lint flags
1364 // to be applied to proc macro crates.
1365 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1366
1367 if self.config.rust_frame_pointers {
1368 rustflags.arg("-Cforce-frame-pointers=true");
1369 }
1370
1371 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1372 // when compiling the standard library, since this might be linked into the final outputs
1373 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1374 // for the standard library in case the compiler is run on a non-Windows platform.
1375 if cfg!(windows) && mode == Mode::Std && self.config.control_flow_guard {
1376 rustflags.arg("-Ccontrol-flow-guard");
1377 }
1378
1379 // If EHCont Guard is enabled, pass the `-Zehcont-guard` flag to rustc when compiling the
1380 // standard library, since this might be linked into the final outputs produced by rustc.
1381 // Since this mitigation is only available on Windows, only enable it for the standard
1382 // library in case the compiler is run on a non-Windows platform.
1383 if cfg!(windows) && mode == Mode::Std && self.config.ehcont_guard {
1384 rustflags.arg("-Zehcont-guard");
1385 }
1386
1387 // Optionally override the rc.exe when compiling rustc on Windows.
1388 if let Some(windows_rc) = &self.config.windows_rc {
1389 cargo.env("RUSTC_WINDOWS_RC", windows_rc);
1390 }
1391
1392 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1393 // This replaces spaces with tabs because RUSTDOCFLAGS does not
1394 // support arguments with regular spaces. Hopefully someday Cargo will
1395 // have space support.
1396 let rust_version = self.rust_version().replace(' ', "\t");
1397 rustdocflags.arg("--crate-version").arg(&rust_version);
1398
1399 // Environment variables *required* throughout the build
1400
1401 // The host this new compiler is being *built* on.
1402 cargo.env("CFG_COMPILER_BUILD_TRIPLE", compiler.host.triple);
1403
1404 // Set this for all builds to make sure doc builds also get it.
1405 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1406
1407 // verbose cargo output is very noisy, so only enable it with -vv
1408 for _ in 0..self.verbosity.saturating_sub(1) {
1409 cargo.arg("--verbose");
1410 }
1411
1412 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1413 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1414 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1415 }
1416 _ => {
1417 // Don't set anything
1418 }
1419 }
1420
1421 if self.config.locked_deps {
1422 cargo.arg("--locked");
1423 }
1424 if self.config.vendor || self.is_sudo {
1425 cargo.arg("--frozen");
1426 }
1427
1428 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1429 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1430
1431 if self.config.is_running_on_ci() {
1432 // Tell cargo to use colored output for nicer logs in CI, even
1433 // though CI isn't printing to a terminal.
1434 // Also set an explicit `TERM=xterm` so that cargo doesn't warn
1435 // about TERM not being set.
1436 cargo.env("TERM", "xterm").args(["--color=always"]);
1437 };
1438
1439 // When we build Rust dylibs they're all intended for intermediate
1440 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1441 // linking all deps statically into the dylib.
1442 if matches!(mode, Mode::Std) {
1443 rustflags.arg("-Cprefer-dynamic");
1444 }
1445
1446 // When building incrementally we default to a lower ThinLTO import limit
1447 // (unless explicitly specified otherwise). This will produce a somewhat
1448 // slower code but give way better compile times.
1449 {
1450 let limit = match self.config.rust_thin_lto_import_instr_limit {
1451 Some(limit) => Some(limit),
1452 None if self.config.incremental => Some(10),
1453 _ => None,
1454 };
1455
1456 if let Some(limit) = limit
1457 && (build_compiler_stage == 0
1458 || self.config.default_codegen_backend(target).is_llvm())
1459 {
1460 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={limit}"));
1461 }
1462 }
1463
1464 if matches!(mode, Mode::Std) {
1465 if let Some(mir_opt_level) = self.config.rust_validate_mir_opts {
1466 rustflags.arg("-Zvalidate-mir");
1467 rustflags.arg(&format!("-Zmir-opt-level={mir_opt_level}"));
1468 }
1469 if self.config.rust_randomize_layout {
1470 rustflags.arg("--cfg=randomized_layouts");
1471 }
1472 // Always enable inlining MIR when building the standard library.
1473 // Without this flag, MIR inlining is disabled when incremental compilation is enabled.
1474 // That causes some mir-opt tests which inline functions from the standard library to
1475 // break when incremental compilation is enabled. So this overrides the "no inlining
1476 // during incremental builds" heuristic for the standard library.
1477 rustflags.arg("-Zinline-mir");
1478
1479 // Similarly, we need to keep debug info for functions inlined into other std functions,
1480 // even if we're not going to output debuginfo for the crate we're currently building,
1481 // so that it'll be available when downstream consumers of std try to use it.
1482 rustflags.arg("-Zinline-mir-preserve-debug");
1483
1484 rustflags.arg("-Zmir_strip_debuginfo=locals-in-tiny-functions");
1485 }
1486
1487 // take target-specific extra rustflags if any otherwise take `rust.rustflags`
1488 let extra_rustflags = self
1489 .config
1490 .target_config
1491 .get(&target)
1492 .map(|t| &t.rustflags)
1493 .unwrap_or(&self.config.rust_rustflags)
1494 .clone();
1495
1496 let profile =
1497 if matches!(cmd_kind, Kind::Bench | Kind::Miri | Kind::MiriSetup | Kind::MiriTest) {
1498 // Use the default profile for bench/miri
1499 None
1500 } else {
1501 match (mode, self.config.rust_optimize.is_release()) {
1502 // Some std configuration exists in its own profile
1503 (Mode::Std, _) => Some("dist"),
1504 (_, true) => Some("release"),
1505 (_, false) => Some("dev"),
1506 }
1507 };
1508
1509 Cargo {
1510 command: cargo,
1511 args: vec![],
1512 compiler,
1513 mode,
1514 target,
1515 rustflags,
1516 rustdocflags,
1517 hostflags,
1518 allow_features,
1519 build_compiler_stage,
1520 extra_rustflags,
1521 profile,
1522 kind: cmd_kind,
1523 }
1524 }
1525}
1526
1527pub(crate) fn cargo_profile_var(name: &str, config: &Config, mode: Mode) -> String {
1528 let profile = match (mode, config.rust_optimize.is_release()) {
1529 // Some std configuration exists in its own profile
1530 (Mode::Std, _) => "DIST",
1531 (_, true) => "RELEASE",
1532 (_, false) => "DEV",
1533 };
1534 format!("CARGO_PROFILE_{profile}_{name}")
1535}
1536
1537/// Applies PGO compile flags to the given Cargo invocation based on the given PGO config.
1538/// PGO flags are only applied when compiling a stage2 component.
1539pub(crate) fn apply_pgo(
1540 builder: &Builder<'_>,
1541 cargo: &mut Cargo,
1542 build_compiler: Compiler,
1543 config: &PgoConfig,
1544) {
1545 let is_collecting = if let Some(path) = &config.generate_profile {
1546 if build_compiler.stage == 1 {
1547 cargo
1548 .rustflag(&format!("-Cprofile-generate={}", path.to_str().expect("non-UTF8 path")));
1549 // Apparently necessary to avoid overflowing the counters during
1550 // a Cargo build profile
1551 cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
1552 true
1553 } else {
1554 false
1555 }
1556 } else if let Some(path) = &config.use_profile {
1557 if build_compiler.stage == 1 {
1558 cargo.rustflag(&format!("-Cprofile-use={}", path.to_str().expect("non-UTF8 path")));
1559 if builder.is_verbose() {
1560 cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
1561 }
1562 true
1563 } else {
1564 false
1565 }
1566 } else {
1567 false
1568 };
1569 if is_collecting {
1570 // Ensure paths to Rust sources are relative, not absolute.
1571 cargo.rustflag(&format!(
1572 "-Cllvm-args=-static-func-strip-dirname-prefix={}",
1573 builder.config.src.components().count()
1574 ));
1575 }
1576}
1577
1578/// Ensures that the behavior dump directory is properly initialized.
1579fn prepare_shims_dump_dir(builder: &Builder<'_>) {
1580 static INITIALIZED: OnceLock<bool> = OnceLock::new();
1581
1582 let dump_path = builder.out.join("bootstrap-shims-dump");
1583
1584 let initialized = INITIALIZED.get().unwrap_or(&false);
1585 if !initialized {
1586 // clear old dumps
1587 if dump_path.exists() {
1588 t!(fs::remove_dir_all(&dump_path));
1589 }
1590
1591 t!(fs::create_dir_all(&dump_path));
1592
1593 t!(INITIALIZED.set(true));
1594 }
1595}