Skip to main content

bootstrap/core/builder/
cargo.rs

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