Skip to main content

bootstrap/core/builder/
cargo.rs

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