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