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