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::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 // Bootstrap makes a lot of assumptions about the artifacts produced in the target
437 // directory. If users override the "build directory" using `build-dir`
438 // (https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-dir), then
439 // bootstrap couldn't find these artifacts. So we forcefully override that option to our
440 // target directory here.
441 // In the future, we could attempt to read the build-dir location from Cargo and actually
442 // respect it.
443 cargo.env("CARGO_BUILD_BUILD_DIR", &out_dir);
444
445 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
446 // from out of tree it shouldn't matter, since x.py is only used for
447 // building in-tree.
448 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
449 match self.build.config.color {
450 Color::Always => {
451 cargo.arg("--color=always");
452 for log in &color_logs {
453 cargo.env(log, "always");
454 }
455 }
456 Color::Never => {
457 cargo.arg("--color=never");
458 for log in &color_logs {
459 cargo.env(log, "never");
460 }
461 }
462 Color::Auto => {} // nothing to do
463 }
464
465 if cmd_kind != Kind::Install {
466 cargo.arg("--target").arg(target.rustc_target_arg());
467 } else {
468 assert_eq!(target, compiler.host);
469 }
470
471 // Remove make-related flags to ensure Cargo can correctly set things up
472 cargo.env_remove("MAKEFLAGS");
473 cargo.env_remove("MFLAGS");
474
475 cargo
476 }
477
478 /// This will create a [`BootstrapCommand`] that represents a pending execution of cargo. This
479 /// cargo will be configured to use `compiler` as the actual rustc compiler, its output will be
480 /// scoped by `mode`'s output directory, it will pass the `--target` flag for the specified
481 /// `target`, and will be executing the Cargo command `cmd`. `cmd` can be `miri-cmd` for
482 /// commands to be run with Miri.
483 fn cargo(
484 &self,
485 compiler: Compiler,
486 mode: Mode,
487 source_type: SourceType,
488 target: TargetSelection,
489 cmd_kind: Kind,
490 ) -> Cargo {
491 let mut cargo = self.bare_cargo(compiler, mode, target, cmd_kind);
492 let out_dir = self.stage_out(compiler, mode);
493
494 let mut hostflags = HostFlags::default();
495
496 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
497 // so we need to explicitly clear out if they've been updated.
498 for backend in self.codegen_backends(compiler) {
499 build_stamp::clear_if_dirty(self, &out_dir, &backend);
500 }
501
502 if cmd_kind == Kind::Doc {
503 let my_out = match mode {
504 // This is the intended out directory for compiler documentation.
505 Mode::Rustc | Mode::ToolRustc | Mode::ToolBootstrap => {
506 self.compiler_doc_out(target)
507 }
508 Mode::Std => {
509 if self.config.cmd.json() {
510 out_dir.join(target).join("json-doc")
511 } else {
512 out_dir.join(target).join("doc")
513 }
514 }
515 _ => panic!("doc mode {mode:?} not expected"),
516 };
517 let rustdoc = self.rustdoc_for_compiler(compiler);
518 build_stamp::clear_if_dirty(self, &my_out, &rustdoc);
519 }
520
521 let profile_var = |name: &str| cargo_profile_var(name, &self.config);
522
523 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
524 // needs to not accidentally link to libLLVM in stage0/lib.
525 cargo.env("REAL_LIBRARY_PATH_VAR", helpers::dylib_path_var());
526 if let Some(e) = env::var_os(helpers::dylib_path_var()) {
527 cargo.env("REAL_LIBRARY_PATH", e);
528 }
529
530 // Set a flag for `check`/`clippy`/`fix`, so that certain build
531 // scripts can do less work (i.e. not building/requiring LLVM).
532 if matches!(cmd_kind, Kind::Check | Kind::Clippy | Kind::Fix) {
533 // If we've not yet built LLVM, or it's stale, then bust
534 // the rustc_llvm cache. That will always work, even though it
535 // may mean that on the next non-check build we'll need to rebuild
536 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
537 // of work comparatively, and we'd likely need to rebuild it anyway,
538 // so that's okay.
539 if crate::core::build_steps::llvm::prebuilt_llvm_config(self, target, false)
540 .should_build()
541 {
542 cargo.env("RUST_CHECK", "1");
543 }
544 }
545
546 let build_compiler_stage = if compiler.stage == 0 && self.local_rebuild {
547 // Assume the local-rebuild rustc already has stage1 features.
548 1
549 } else {
550 compiler.stage
551 };
552
553 // We synthetically interpret a stage0 compiler used to build tools as a
554 // "raw" compiler in that it's the exact snapshot we download. For things like
555 // ToolRustc, we would have to use the artificial stage0-sysroot compiler instead.
556 let use_snapshot =
557 mode == Mode::ToolBootstrap || (mode == Mode::ToolTarget && build_compiler_stage == 0);
558 assert!(!use_snapshot || build_compiler_stage == 0 || self.local_rebuild);
559
560 let sysroot = if use_snapshot {
561 self.rustc_snapshot_sysroot().to_path_buf()
562 } else {
563 self.sysroot(compiler)
564 };
565 let libdir = self.rustc_libdir(compiler);
566
567 let sysroot_str = sysroot.as_os_str().to_str().expect("sysroot should be UTF-8");
568 if self.is_verbose() && !matches!(self.config.get_dry_run(), DryRun::SelfCheck) {
569 println!("using sysroot {sysroot_str}");
570 }
571
572 let mut rustflags = Rustflags::new(target);
573 if build_compiler_stage != 0 {
574 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
575 cargo.args(s.split_whitespace());
576 }
577 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
578 } else {
579 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
580 cargo.args(s.split_whitespace());
581 }
582 rustflags.env("RUSTFLAGS_BOOTSTRAP");
583 rustflags.arg("--cfg=bootstrap");
584 }
585
586 if cmd_kind == Kind::Clippy {
587 // clippy overwrites sysroot if we pass it to cargo.
588 // Pass it directly to clippy instead.
589 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
590 // so it has no way of knowing the sysroot.
591 rustflags.arg("--sysroot");
592 rustflags.arg(sysroot_str);
593 }
594
595 let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
596 Some(setting) => {
597 // If an explicit setting is given, use that
598 setting
599 }
600 None => {
601 if mode == Mode::Std {
602 // The standard library defaults to the legacy scheme
603 false
604 } else {
605 // The compiler and tools default to the new scheme
606 true
607 }
608 }
609 };
610
611 // By default, windows-rs depends on a native library that doesn't get copied into the
612 // sysroot. Passing this cfg enables raw-dylib support instead, which makes the native
613 // library unnecessary. This can be removed when windows-rs enables raw-dylib
614 // unconditionally.
615 if let Mode::Rustc | Mode::ToolRustc | Mode::ToolBootstrap | Mode::ToolTarget = mode {
616 rustflags.arg("--cfg=windows_raw_dylib");
617 }
618
619 if use_new_symbol_mangling {
620 rustflags.arg("-Csymbol-mangling-version=v0");
621 } else {
622 rustflags.arg("-Csymbol-mangling-version=legacy");
623 }
624
625 // FIXME: the following components don't build with `-Zrandomize-layout` yet:
626 // - rust-analyzer, due to the rowan crate
627 // so we exclude an entire category of steps here due to lack of fine-grained control over
628 // rustflags.
629 if self.config.rust_randomize_layout && mode != Mode::ToolRustc {
630 rustflags.arg("-Zrandomize-layout");
631 }
632
633 // Enable compile-time checking of `cfg` names, values and Cargo `features`.
634 //
635 // Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like
636 // backtrace, core_simd, std_float, ...), those dependencies have their own
637 // features but cargo isn't involved in the #[path] process and so cannot pass the
638 // complete list of features, so for that reason we don't enable checking of
639 // features for std crates.
640 if mode == Mode::Std {
641 rustflags.arg("--check-cfg=cfg(feature,values(any()))");
642 }
643
644 // Add extra cfg not defined in/by rustc
645 //
646 // Note: Although it would seems that "-Zunstable-options" to `rustflags` is useless as
647 // cargo would implicitly add it, it was discover that sometimes bootstrap only use
648 // `rustflags` without `cargo` making it required.
649 rustflags.arg("-Zunstable-options");
650 for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
651 if restricted_mode.is_none() || *restricted_mode == Some(mode) {
652 rustflags.arg(&check_cfg_arg(name, *values));
653
654 if *name == "bootstrap" {
655 // Cargo doesn't pass RUSTFLAGS to proc_macros:
656 // https://github.com/rust-lang/cargo/issues/4423
657 // Thus, if we are on stage 0, we explicitly set `--cfg=bootstrap`.
658 // We also declare that the flag is expected, which we need to do to not
659 // get warnings about it being unexpected.
660 hostflags.arg(check_cfg_arg(name, *values));
661 }
662 }
663 }
664
665 // FIXME(rust-lang/cargo#5754) we shouldn't be using special command arguments
666 // to the host invocation here, but rather Cargo should know what flags to pass rustc
667 // itself.
668 if build_compiler_stage == 0 {
669 hostflags.arg("--cfg=bootstrap");
670 }
671
672 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
673 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
674 // #71458.
675 let mut rustdocflags = rustflags.clone();
676 rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
677 if build_compiler_stage == 0 {
678 rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
679 } else {
680 rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
681 }
682
683 if let Ok(s) = env::var("CARGOFLAGS") {
684 cargo.args(s.split_whitespace());
685 }
686
687 match mode {
688 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {}
689 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
690 // Build proc macros both for the host and the target unless proc-macros are not
691 // supported by the target.
692 if target != compiler.host && cmd_kind != Kind::Check {
693 let mut rustc_cmd = command(self.rustc(compiler));
694 self.add_rustc_lib_path(compiler, &mut rustc_cmd);
695
696 let error = rustc_cmd
697 .arg("--target")
698 .arg(target.rustc_target_arg())
699 .arg("--print=file-names")
700 .arg("--crate-type=proc-macro")
701 .arg("-")
702 .stdin(std::process::Stdio::null())
703 .run_capture(self)
704 .stderr();
705
706 let not_supported = error
707 .lines()
708 .any(|line| line.contains("unsupported crate type `proc-macro`"));
709 if !not_supported {
710 cargo.arg("-Zdual-proc-macros");
711 rustflags.arg("-Zdual-proc-macros");
712 }
713 }
714 }
715 }
716
717 // This tells Cargo (and in turn, rustc) to output more complete
718 // dependency information. Most importantly for bootstrap, this
719 // includes sysroot artifacts, like libstd, which means that we don't
720 // need to track those in bootstrap (an error prone process!). This
721 // feature is currently unstable as there may be some bugs and such, but
722 // it represents a big improvement in bootstrap's reliability on
723 // rebuilds, so we're using it here.
724 //
725 // For some additional context, see #63470 (the PR originally adding
726 // this), as well as #63012 which is the tracking issue for this
727 // feature on the rustc side.
728 cargo.arg("-Zbinary-dep-depinfo");
729 let allow_features = match mode {
730 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {
731 // Restrict the allowed features so we don't depend on nightly
732 // accidentally.
733 //
734 // binary-dep-depinfo is used by bootstrap itself for all
735 // compilations.
736 //
737 // Lots of tools depend on proc_macro2 and proc-macro-error.
738 // Those have build scripts which assume nightly features are
739 // available if the `rustc` version is "nighty" or "dev". See
740 // bin/rustc.rs for why that is a problem. Instead of labeling
741 // those features for each individual tool that needs them,
742 // just blanket allow them here.
743 //
744 // If this is ever removed, be sure to add something else in
745 // its place to keep the restrictions in place (or make a way
746 // to unset RUSTC_BOOTSTRAP).
747 "binary-dep-depinfo,proc_macro_span,proc_macro_span_shrink,proc_macro_diagnostic"
748 .to_string()
749 }
750 Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustc => String::new(),
751 };
752
753 cargo.arg("-j").arg(self.jobs().to_string());
754
755 // Make cargo emit diagnostics relative to the rustc src dir.
756 cargo.arg(format!("-Zroot-dir={}", self.src.display()));
757
758 if self.config.compile_time_deps {
759 // Build only build scripts and proc-macros for rust-analyzer when requested.
760 cargo.arg("-Zunstable-options");
761 cargo.arg("--compile-time-deps");
762 }
763
764 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
765 // Force cargo to output binaries with disambiguating hashes in the name
766 let mut metadata = if compiler.stage == 0 {
767 // Treat stage0 like a special channel, whether it's a normal prior-
768 // release rustc or a local rebuild with the same version, so we
769 // never mix these libraries by accident.
770 "bootstrap".to_string()
771 } else {
772 self.config.channel.to_string()
773 };
774 // We want to make sure that none of the dependencies between
775 // std/test/rustc unify with one another. This is done for weird linkage
776 // reasons but the gist of the problem is that if librustc, libtest, and
777 // libstd all depend on libc from crates.io (which they actually do) we
778 // want to make sure they all get distinct versions. Things get really
779 // weird if we try to unify all these dependencies right now, namely
780 // around how many times the library is linked in dynamic libraries and
781 // such. If rustc were a static executable or if we didn't ship dylibs
782 // this wouldn't be a problem, but we do, so it is. This is in general
783 // just here to make sure things build right. If you can remove this and
784 // things still build right, please do!
785 match mode {
786 Mode::Std => metadata.push_str("std"),
787 // When we're building rustc tools, they're built with a search path
788 // that contains things built during the rustc build. For example,
789 // bitflags is built during the rustc build, and is a dependency of
790 // rustdoc as well. We're building rustdoc in a different target
791 // directory, though, which means that Cargo will rebuild the
792 // dependency. When we go on to build rustdoc, we'll look for
793 // bitflags, and find two different copies: one built during the
794 // rustc step and one that we just built. This isn't always a
795 // problem, somehow -- not really clear why -- but we know that this
796 // fixes things.
797 Mode::ToolRustc => metadata.push_str("tool-rustc"),
798 // Same for codegen backends.
799 Mode::Codegen => metadata.push_str("codegen"),
800 _ => {}
801 }
802 // `rustc_driver`'s version number is always `0.0.0`, which can cause linker search path
803 // problems on side-by-side installs because we don't include the version number of the
804 // `rustc_driver` being built. This can cause builds of different version numbers to produce
805 // `librustc_driver*.so` artifacts that end up with identical filename hashes.
806 metadata.push_str(&self.version);
807
808 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
809
810 if cmd_kind == Kind::Clippy {
811 rustflags.arg("-Zforce-unstable-if-unmarked");
812 }
813
814 rustflags.arg("-Zmacro-backtrace");
815
816 let want_rustdoc = self.doc_tests != DocTests::No;
817
818 // Clear the output directory if the real rustc we're using has changed;
819 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
820 //
821 // Avoid doing this during dry run as that usually means the relevant
822 // compiler is not yet linked/copied properly.
823 //
824 // Only clear out the directory if we're compiling std; otherwise, we
825 // should let Cargo take care of things for us (via depdep info)
826 if !self.config.dry_run() && mode == Mode::Std && cmd_kind == Kind::Build {
827 build_stamp::clear_if_dirty(self, &out_dir, &self.rustc(compiler));
828 }
829
830 let rustdoc_path = match cmd_kind {
831 Kind::Doc | Kind::Test | Kind::MiriTest => self.rustdoc_for_compiler(compiler),
832 _ => PathBuf::from("/path/to/nowhere/rustdoc/not/required"),
833 };
834
835 // Customize the compiler we're running. Specify the compiler to cargo
836 // as our shim and then pass it some various options used to configure
837 // how the actual compiler itself is called.
838 //
839 // These variables are primarily all read by
840 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
841 cargo
842 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
843 .env("RUSTC_REAL", self.rustc(compiler))
844 .env("RUSTC_STAGE", build_compiler_stage.to_string())
845 .env("RUSTC_SYSROOT", sysroot)
846 .env("RUSTC_LIBDIR", libdir)
847 .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
848 .env("RUSTDOC_REAL", rustdoc_path)
849 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
850 .env("RUSTC_BREAK_ON_ICE", "1");
851
852 // Set RUSTC_WRAPPER to the bootstrap shim, which switches between beta and in-tree
853 // sysroot depending on whether we're building build scripts.
854 // NOTE: we intentionally use RUSTC_WRAPPER so that we can support clippy - RUSTC is not
855 // respected by clippy-driver; RUSTC_WRAPPER happens earlier, before clippy runs.
856 cargo.env("RUSTC_WRAPPER", self.bootstrap_out.join("rustc"));
857 // NOTE: we also need to set RUSTC so cargo can run `rustc -vV`; apparently that ignores RUSTC_WRAPPER >:(
858 cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
859
860 // Someone might have set some previous rustc wrapper (e.g.
861 // sccache) before bootstrap overrode it. Respect that variable.
862 if let Some(existing_wrapper) = env::var_os("RUSTC_WRAPPER") {
863 cargo.env("RUSTC_WRAPPER_REAL", existing_wrapper);
864 }
865
866 // If this is for `miri-test`, prepare the sysroots.
867 if cmd_kind == Kind::MiriTest {
868 self.std(compiler, compiler.host);
869 let host_sysroot = self.sysroot(compiler);
870 let miri_sysroot = test::Miri::build_miri_sysroot(self, compiler, target);
871 cargo.env("MIRI_SYSROOT", &miri_sysroot);
872 cargo.env("MIRI_HOST_SYSROOT", &host_sysroot);
873 }
874
875 cargo.env(profile_var("STRIP"), self.config.rust_strip.to_string());
876
877 if let Some(stack_protector) = &self.config.rust_stack_protector {
878 rustflags.arg(&format!("-Zstack-protector={stack_protector}"));
879 }
880
881 if !matches!(cmd_kind, Kind::Build | Kind::Check | Kind::Clippy | Kind::Fix) && want_rustdoc
882 {
883 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
884 }
885
886 let debuginfo_level = match mode {
887 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
888 Mode::Std => self.config.rust_debuginfo_level_std,
889 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc | Mode::ToolTarget => {
890 self.config.rust_debuginfo_level_tools
891 }
892 };
893 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
894 if let Some(opt_level) = &self.config.rust_optimize.get_opt_level() {
895 cargo.env(profile_var("OPT_LEVEL"), opt_level);
896 }
897 cargo.env(
898 profile_var("DEBUG_ASSERTIONS"),
899 match mode {
900 Mode::Std => self.config.std_debug_assertions,
901 Mode::Rustc | Mode::Codegen => self.config.rustc_debug_assertions,
902 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc | Mode::ToolTarget => {
903 self.config.tools_debug_assertions
904 }
905 }
906 .to_string(),
907 );
908 cargo.env(
909 profile_var("OVERFLOW_CHECKS"),
910 if mode == Mode::Std {
911 self.config.rust_overflow_checks_std.to_string()
912 } else {
913 self.config.rust_overflow_checks.to_string()
914 },
915 );
916
917 match self.config.split_debuginfo(target) {
918 SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
919 SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
920 SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
921 };
922
923 if self.config.cmd.bless() {
924 // Bless `expect!` tests.
925 cargo.env("UPDATE_EXPECT", "1");
926 }
927
928 if !mode.is_tool() {
929 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
930 }
931
932 if let Some(x) = self.crt_static(target) {
933 if x {
934 rustflags.arg("-Ctarget-feature=+crt-static");
935 } else {
936 rustflags.arg("-Ctarget-feature=-crt-static");
937 }
938 }
939
940 if let Some(x) = self.crt_static(compiler.host) {
941 let sign = if x { "+" } else { "-" };
942 hostflags.arg(format!("-Ctarget-feature={sign}crt-static"));
943 }
944
945 // `rustc` needs to know the remapping scheme, in order to know how to reverse it (unremap)
946 // later. Two env vars are set and made available to the compiler
947 //
948 // - `CFG_VIRTUAL_RUST_SOURCE_BASE_DIR`: `rust-src` remap scheme (`NonCompiler`)
949 // - `CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR`: `rustc-dev` remap scheme (`Compiler`)
950 //
951 // Keep this scheme in sync with `rustc_metadata::rmeta::decoder`'s
952 // `try_to_translate_virtual_to_real`.
953 //
954 // `RUSTC_DEBUGINFO_MAP` is used to pass through to the underlying rustc
955 // `--remap-path-prefix`.
956 match mode {
957 Mode::Rustc | Mode::Codegen => {
958 if let Some(ref map_to) =
959 self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::NonCompiler)
960 {
961 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
962 }
963
964 if let Some(ref map_to) =
965 self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::Compiler)
966 {
967 // When building compiler sources, we want to apply the compiler remap scheme.
968 cargo.env(
969 "RUSTC_DEBUGINFO_MAP",
970 format!("{}={}", self.build.src.display(), map_to),
971 );
972 cargo.env("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR", map_to);
973 }
974 }
975 Mode::Std
976 | Mode::ToolBootstrap
977 | Mode::ToolRustc
978 | Mode::ToolStd
979 | Mode::ToolTarget => {
980 if let Some(ref map_to) =
981 self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::NonCompiler)
982 {
983 cargo.env(
984 "RUSTC_DEBUGINFO_MAP",
985 format!("{}={}", self.build.src.display(), map_to),
986 );
987 }
988 }
989 }
990
991 if self.config.rust_remap_debuginfo {
992 let mut env_var = OsString::new();
993 if let Some(vendor) = self.build.vendored_crates_path() {
994 env_var.push(vendor);
995 env_var.push("=/rust/deps");
996 } else {
997 let registry_src = t!(home::cargo_home()).join("registry").join("src");
998 for entry in t!(std::fs::read_dir(registry_src)) {
999 if !env_var.is_empty() {
1000 env_var.push("\t");
1001 }
1002 env_var.push(t!(entry).path());
1003 env_var.push("=/rust/deps");
1004 }
1005 }
1006 cargo.env("RUSTC_CARGO_REGISTRY_SRC_TO_REMAP", env_var);
1007 }
1008
1009 // Enable usage of unstable features
1010 cargo.env("RUSTC_BOOTSTRAP", "1");
1011
1012 if self.config.dump_bootstrap_shims {
1013 prepare_behaviour_dump_dir(self.build);
1014
1015 cargo
1016 .env("DUMP_BOOTSTRAP_SHIMS", self.build.out.join("bootstrap-shims-dump"))
1017 .env("BUILD_OUT", &self.build.out)
1018 .env("CARGO_HOME", t!(home::cargo_home()));
1019 };
1020
1021 self.add_rust_test_threads(&mut cargo);
1022
1023 // Almost all of the crates that we compile as part of the bootstrap may
1024 // have a build script, including the standard library. To compile a
1025 // build script, however, it itself needs a standard library! This
1026 // introduces a bit of a pickle when we're compiling the standard
1027 // library itself.
1028 //
1029 // To work around this we actually end up using the snapshot compiler
1030 // (stage0) for compiling build scripts of the standard library itself.
1031 // The stage0 compiler is guaranteed to have a libstd available for use.
1032 //
1033 // For other crates, however, we know that we've already got a standard
1034 // library up and running, so we can use the normal compiler to compile
1035 // build scripts in that situation.
1036 if mode == Mode::Std {
1037 cargo
1038 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1039 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1040 } else {
1041 cargo
1042 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1043 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1044 }
1045
1046 // Tools that use compiler libraries may inherit the `-lLLVM` link
1047 // requirement, but the `-L` library path is not propagated across
1048 // separate Cargo projects. We can add LLVM's library path to the
1049 // rustc args as a workaround.
1050 if (mode == Mode::ToolRustc || mode == Mode::Codegen)
1051 && let Some(llvm_config) = self.llvm_config(target)
1052 {
1053 let llvm_libdir =
1054 command(llvm_config).arg("--libdir").run_capture_stdout(self).stdout();
1055 if target.is_msvc() {
1056 rustflags.arg(&format!("-Clink-arg=-LIBPATH:{llvm_libdir}"));
1057 } else {
1058 rustflags.arg(&format!("-Clink-arg=-L{llvm_libdir}"));
1059 }
1060 }
1061
1062 // Compile everything except libraries and proc macros with the more
1063 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1064 // so we can't use it by default in general, but we can use it for tools
1065 // and our own internal libraries.
1066 //
1067 // Cygwin only supports emutls.
1068 if !mode.must_support_dlopen()
1069 && !target.triple.starts_with("powerpc-")
1070 && !target.triple.contains("cygwin")
1071 {
1072 cargo.env("RUSTC_TLS_MODEL_INITIAL_EXEC", "1");
1073 }
1074
1075 // Ignore incremental modes except for stage0, since we're
1076 // not guaranteeing correctness across builds if the compiler
1077 // is changing under your feet.
1078 if self.config.incremental && compiler.stage == 0 {
1079 cargo.env("CARGO_INCREMENTAL", "1");
1080 } else {
1081 // Don't rely on any default setting for incr. comp. in Cargo
1082 cargo.env("CARGO_INCREMENTAL", "0");
1083 }
1084
1085 if let Some(ref on_fail) = self.config.on_fail {
1086 cargo.env("RUSTC_ON_FAIL", on_fail);
1087 }
1088
1089 if self.config.print_step_timings {
1090 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1091 }
1092
1093 if self.config.print_step_rusage {
1094 cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1095 }
1096
1097 if self.config.backtrace_on_ice {
1098 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1099 }
1100
1101 if self.is_verbose() {
1102 // This provides very useful logs especially when debugging build cache-related stuff.
1103 cargo.env("CARGO_LOG", "cargo::core::compiler::fingerprint=info");
1104 }
1105
1106 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1107
1108 // Downstream forks of the Rust compiler might want to use a custom libc to add support for
1109 // targets that are not yet available upstream. Adding a patch to replace libc with a
1110 // custom one would cause compilation errors though, because Cargo would interpret the
1111 // custom libc as part of the workspace, and apply the check-cfg lints on it.
1112 //
1113 // The libc build script emits check-cfg flags only when this environment variable is set,
1114 // so this line allows the use of custom libcs.
1115 cargo.env("LIBC_CHECK_CFG", "1");
1116
1117 let mut lint_flags = Vec::new();
1118
1119 // Lints for all in-tree code: compiler, rustdoc, cranelift, gcc,
1120 // clippy, rustfmt, rust-analyzer, etc.
1121 if source_type == SourceType::InTree {
1122 // When extending this list, add the new lints to the RUSTFLAGS of the
1123 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1124 // some code doesn't go through this `rustc` wrapper.
1125 lint_flags.push("-Wrust_2018_idioms");
1126 lint_flags.push("-Wunused_lifetimes");
1127
1128 if self.config.deny_warnings {
1129 lint_flags.push("-Dwarnings");
1130 rustdocflags.arg("-Dwarnings");
1131 }
1132
1133 rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1134 }
1135
1136 // Lints just for `compiler/` crates.
1137 if mode == Mode::Rustc {
1138 lint_flags.push("-Wrustc::internal");
1139 lint_flags.push("-Drustc::symbol_intern_string_literal");
1140 // FIXME(edition_2024): Change this to `-Wrust_2024_idioms` when all
1141 // of the individual lints are satisfied.
1142 lint_flags.push("-Wkeyword_idents_2024");
1143 lint_flags.push("-Wunreachable_pub");
1144 lint_flags.push("-Wunsafe_op_in_unsafe_fn");
1145 lint_flags.push("-Wunused_crate_dependencies");
1146 }
1147
1148 // This does not use RUSTFLAGS for two reasons.
1149 // - Due to caching issues with Cargo. Clippy is treated as an "in
1150 // tree" tool, but shares the same cache as other "submodule" tools.
1151 // With these options set in RUSTFLAGS, that causes *every* shared
1152 // dependency to be rebuilt. By injecting this into the rustc
1153 // wrapper, this circumvents Cargo's fingerprint detection. This is
1154 // fine because lint flags are always ignored in dependencies.
1155 // Eventually this should be fixed via better support from Cargo.
1156 // - RUSTFLAGS is ignored for proc macro crates that are being built on
1157 // the host (because `--target` is given). But we want the lint flags
1158 // to be applied to proc macro crates.
1159 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1160
1161 if self.config.rust_frame_pointers {
1162 rustflags.arg("-Cforce-frame-pointers=true");
1163 }
1164
1165 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1166 // when compiling the standard library, since this might be linked into the final outputs
1167 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1168 // for the standard library in case the compiler is run on a non-Windows platform.
1169 // This is not needed for stage 0 artifacts because these will only be used for building
1170 // the stage 1 compiler.
1171 if cfg!(windows)
1172 && mode == Mode::Std
1173 && self.config.control_flow_guard
1174 && compiler.stage >= 1
1175 {
1176 rustflags.arg("-Ccontrol-flow-guard");
1177 }
1178
1179 // If EHCont Guard is enabled, pass the `-Zehcont-guard` flag to rustc when compiling the
1180 // standard library, since this might be linked into the final outputs produced by rustc.
1181 // Since this mitigation is only available on Windows, only enable it for the standard
1182 // library in case the compiler is run on a non-Windows platform.
1183 // This is not needed for stage 0 artifacts because these will only be used for building
1184 // the stage 1 compiler.
1185 if cfg!(windows) && mode == Mode::Std && self.config.ehcont_guard && compiler.stage >= 1 {
1186 rustflags.arg("-Zehcont-guard");
1187 }
1188
1189 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1190 // This replaces spaces with tabs because RUSTDOCFLAGS does not
1191 // support arguments with regular spaces. Hopefully someday Cargo will
1192 // have space support.
1193 let rust_version = self.rust_version().replace(' ', "\t");
1194 rustdocflags.arg("--crate-version").arg(&rust_version);
1195
1196 // Environment variables *required* throughout the build
1197 //
1198 // FIXME: should update code to not require this env var
1199
1200 // The host this new compiler will *run* on.
1201 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1202 // The host this new compiler is being *built* on.
1203 cargo.env("CFG_COMPILER_BUILD_TRIPLE", compiler.host.triple);
1204
1205 // Set this for all builds to make sure doc builds also get it.
1206 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1207
1208 // This one's a bit tricky. As of the time of this writing the compiler
1209 // links to the `winapi` crate on crates.io. This crate provides raw
1210 // bindings to Windows system functions, sort of like libc does for
1211 // Unix. This crate also, however, provides "import libraries" for the
1212 // MinGW targets. There's an import library per dll in the windows
1213 // distribution which is what's linked to. These custom import libraries
1214 // are used because the winapi crate can reference Windows functions not
1215 // present in the MinGW import libraries.
1216 //
1217 // For example MinGW may ship libdbghelp.a, but it may not have
1218 // references to all the functions in the dbghelp dll. Instead the
1219 // custom import library for dbghelp in the winapi crates has all this
1220 // information.
1221 //
1222 // Unfortunately for us though the import libraries are linked by
1223 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1224 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1225 // conflict with the system MinGW ones). This consequently means that
1226 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1227 // DLL) when linked against *again*, for example with procedural macros
1228 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1229 // `-lwinapi_foo` to the linker again. This isn't actually available in
1230 // our distribution, however, so the link fails.
1231 //
1232 // To solve this problem we tell winapi to not use its bundled import
1233 // libraries. This means that it will link to the system MinGW import
1234 // libraries by default, and the `-ldylib=foo` directives will still get
1235 // passed to the final linker, but they'll look like `-lfoo` which can
1236 // be resolved because MinGW has the import library. The downside is we
1237 // don't get newer functions from Windows, but we don't use any of them
1238 // anyway.
1239 if !mode.is_tool() {
1240 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1241 }
1242
1243 for _ in 0..self.verbosity {
1244 cargo.arg("-v");
1245 }
1246
1247 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1248 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1249 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1250 }
1251 _ => {
1252 // Don't set anything
1253 }
1254 }
1255
1256 if self.config.locked_deps {
1257 cargo.arg("--locked");
1258 }
1259 if self.config.vendor || self.is_sudo {
1260 cargo.arg("--frozen");
1261 }
1262
1263 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1264 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1265
1266 cargo.force_coloring_in_ci();
1267
1268 // When we build Rust dylibs they're all intended for intermediate
1269 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1270 // linking all deps statically into the dylib.
1271 if matches!(mode, Mode::Std) {
1272 rustflags.arg("-Cprefer-dynamic");
1273 }
1274 if matches!(mode, Mode::Rustc) && !self.link_std_into_rustc_driver(target) {
1275 rustflags.arg("-Cprefer-dynamic");
1276 }
1277
1278 cargo.env(
1279 "RUSTC_LINK_STD_INTO_RUSTC_DRIVER",
1280 if self.link_std_into_rustc_driver(target) { "1" } else { "0" },
1281 );
1282
1283 // When building incrementally we default to a lower ThinLTO import limit
1284 // (unless explicitly specified otherwise). This will produce a somewhat
1285 // slower code but give way better compile times.
1286 {
1287 let limit = match self.config.rust_thin_lto_import_instr_limit {
1288 Some(limit) => Some(limit),
1289 None if self.config.incremental => Some(10),
1290 _ => None,
1291 };
1292
1293 if let Some(limit) = limit
1294 && (build_compiler_stage == 0
1295 || self.config.default_codegen_backend(target).unwrap_or_default().is_llvm())
1296 {
1297 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={limit}"));
1298 }
1299 }
1300
1301 if matches!(mode, Mode::Std) {
1302 if let Some(mir_opt_level) = self.config.rust_validate_mir_opts {
1303 rustflags.arg("-Zvalidate-mir");
1304 rustflags.arg(&format!("-Zmir-opt-level={mir_opt_level}"));
1305 }
1306 if self.config.rust_randomize_layout {
1307 rustflags.arg("--cfg=randomized_layouts");
1308 }
1309 // Always enable inlining MIR when building the standard library.
1310 // Without this flag, MIR inlining is disabled when incremental compilation is enabled.
1311 // That causes some mir-opt tests which inline functions from the standard library to
1312 // break when incremental compilation is enabled. So this overrides the "no inlining
1313 // during incremental builds" heuristic for the standard library.
1314 rustflags.arg("-Zinline-mir");
1315
1316 // Similarly, we need to keep debug info for functions inlined into other std functions,
1317 // even if we're not going to output debuginfo for the crate we're currently building,
1318 // so that it'll be available when downstream consumers of std try to use it.
1319 rustflags.arg("-Zinline-mir-preserve-debug");
1320
1321 rustflags.arg("-Zmir_strip_debuginfo=locals-in-tiny-functions");
1322 }
1323
1324 let release_build = self.config.rust_optimize.is_release() &&
1325 // cargo bench/install do not accept `--release` and miri doesn't want it
1326 !matches!(cmd_kind, Kind::Bench | Kind::Install | Kind::Miri | Kind::MiriSetup | Kind::MiriTest);
1327
1328 Cargo {
1329 command: cargo,
1330 args: vec![],
1331 compiler,
1332 target,
1333 rustflags,
1334 rustdocflags,
1335 hostflags,
1336 allow_features,
1337 release_build,
1338 }
1339 }
1340}
1341
1342pub fn cargo_profile_var(name: &str, config: &Config) -> String {
1343 let profile = if config.rust_optimize.is_release() { "RELEASE" } else { "DEV" };
1344 format!("CARGO_PROFILE_{profile}_{name}")
1345}