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