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