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