Skip to main content

bootstrap/core/builder/
cargo.rs

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