Skip to main content

bootstrap/core/builder/
cargo.rs

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