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