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