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