bootstrap/core/builder/
cargo.rs

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