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