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