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