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