Skip to main content

bootstrap/core/builder/
cargo.rs

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