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