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