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