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