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