bootstrap/core/build_steps/
compile.rs

1//! Implementation of compiling various phases of the compiler and standard
2//! library.
3//!
4//! This module contains some of the real meat in the bootstrap build system
5//! which is where Cargo is used to compile the standard library, libtest, and
6//! the compiler. This module is also responsible for assembling the sysroot as it
7//! goes along from the output of the previous stage.
8
9use std::borrow::Cow;
10use std::collections::HashSet;
11use std::ffi::OsStr;
12use std::io::BufReader;
13use std::io::prelude::*;
14use std::path::{Path, PathBuf};
15use std::{env, fs, str};
16
17use serde_derive::Deserialize;
18#[cfg(feature = "tracing")]
19use tracing::{instrument, span};
20
21use crate::core::build_steps::gcc::{Gcc, GccOutput, add_cg_gcc_cargo_flags};
22use crate::core::build_steps::tool::{RustcPrivateCompilers, SourceType, copy_lld_artifacts};
23use crate::core::build_steps::{dist, llvm};
24use crate::core::builder;
25use crate::core::builder::{
26    Builder, Cargo, Kind, RunConfig, ShouldRun, Step, StepMetadata, crate_description,
27};
28use crate::core::config::{DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection};
29use crate::utils::build_stamp;
30use crate::utils::build_stamp::BuildStamp;
31use crate::utils::exec::command;
32use crate::utils::helpers::{
33    exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date,
34};
35use crate::{
36    CLang, CodegenBackendKind, Compiler, DependencyType, FileType, GitRepo, LLVM_TOOLS, Mode,
37    debug, trace,
38};
39
40/// Build a standard library for the given `target` using the given `compiler`.
41#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct Std {
43    pub target: TargetSelection,
44    pub compiler: Compiler,
45    /// Whether to build only a subset of crates in the standard library.
46    ///
47    /// This shouldn't be used from other steps; see the comment on [`Rustc`].
48    crates: Vec<String>,
49    /// When using download-rustc, we need to use a new build of `std` for running unit tests of Std itself,
50    /// but we need to use the downloaded copy of std for linking to rustdoc. Allow this to be overridden by `builder.ensure` from other steps.
51    force_recompile: bool,
52    extra_rust_args: &'static [&'static str],
53    is_for_mir_opt_tests: bool,
54}
55
56impl Std {
57    pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
58        Self {
59            target,
60            compiler,
61            crates: Default::default(),
62            force_recompile: false,
63            extra_rust_args: &[],
64            is_for_mir_opt_tests: false,
65        }
66    }
67
68    pub fn force_recompile(mut self, force_recompile: bool) -> Self {
69        self.force_recompile = force_recompile;
70        self
71    }
72
73    #[expect(clippy::wrong_self_convention)]
74    pub fn is_for_mir_opt_tests(mut self, is_for_mir_opt_tests: bool) -> Self {
75        self.is_for_mir_opt_tests = is_for_mir_opt_tests;
76        self
77    }
78
79    pub fn extra_rust_args(mut self, extra_rust_args: &'static [&'static str]) -> Self {
80        self.extra_rust_args = extra_rust_args;
81        self
82    }
83
84    fn copy_extra_objects(
85        &self,
86        builder: &Builder<'_>,
87        compiler: &Compiler,
88        target: TargetSelection,
89    ) -> Vec<(PathBuf, DependencyType)> {
90        let mut deps = Vec::new();
91        if !self.is_for_mir_opt_tests {
92            deps.extend(copy_third_party_objects(builder, compiler, target));
93            deps.extend(copy_self_contained_objects(builder, compiler, target));
94        }
95        deps
96    }
97}
98
99impl Step for Std {
100    type Output = ();
101    const DEFAULT: bool = true;
102
103    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
104        run.crate_or_deps("sysroot").path("library")
105    }
106
107    #[cfg_attr(feature = "tracing", instrument(level = "trace", name = "Std::make_run", skip_all))]
108    fn make_run(run: RunConfig<'_>) {
109        let crates = std_crates_for_run_make(&run);
110        let builder = run.builder;
111
112        // Force compilation of the standard library from source if the `library` is modified. This allows
113        // library team to compile the standard library without needing to compile the compiler with
114        // the `rust.download-rustc=true` option.
115        let force_recompile = builder.rust_info().is_managed_git_subrepository()
116            && builder.download_rustc()
117            && builder.config.has_changes_from_upstream(&["library"]);
118
119        trace!("is managed git repo: {}", builder.rust_info().is_managed_git_subrepository());
120        trace!("download_rustc: {}", builder.download_rustc());
121        trace!(force_recompile);
122
123        run.builder.ensure(Std {
124            compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
125            target: run.target,
126            crates,
127            force_recompile,
128            extra_rust_args: &[],
129            is_for_mir_opt_tests: false,
130        });
131    }
132
133    /// Builds the standard library.
134    ///
135    /// This will build the standard library for a particular stage of the build
136    /// using the `compiler` targeting the `target` architecture. The artifacts
137    /// created will also be linked into the sysroot directory.
138    #[cfg_attr(
139        feature = "tracing",
140        instrument(
141            level = "debug",
142            name = "Std::run",
143            skip_all,
144            fields(
145                target = ?self.target,
146                compiler = ?self.compiler,
147                force_recompile = self.force_recompile
148            ),
149        ),
150    )]
151    fn run(self, builder: &Builder<'_>) {
152        let target = self.target;
153
154        // We already have std ready to be used for stage 0.
155        if self.compiler.stage == 0 {
156            let compiler = self.compiler;
157            builder.ensure(StdLink::from_std(self, compiler));
158
159            return;
160        }
161
162        let build_compiler = if builder.download_rustc() && self.force_recompile {
163            // When there are changes in the library tree with CI-rustc, we want to build
164            // the stageN library and that requires using stageN-1 compiler.
165            builder.compiler(self.compiler.stage.saturating_sub(1), builder.config.host_target)
166        } else {
167            self.compiler
168        };
169
170        // When using `download-rustc`, we already have artifacts for the host available. Don't
171        // recompile them.
172        if builder.download_rustc()
173            && builder.config.is_host_target(target)
174            && !self.force_recompile
175        {
176            let sysroot =
177                builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
178            cp_rustc_component_to_ci_sysroot(
179                builder,
180                &sysroot,
181                builder.config.ci_rust_std_contents(),
182            );
183            return;
184        }
185
186        if builder.config.keep_stage.contains(&build_compiler.stage)
187            || builder.config.keep_stage_std.contains(&build_compiler.stage)
188        {
189            trace!(keep_stage = ?builder.config.keep_stage);
190            trace!(keep_stage_std = ?builder.config.keep_stage_std);
191
192            builder.info("WARNING: Using a potentially old libstd. This may not behave well.");
193
194            builder.ensure(StartupObjects { compiler: build_compiler, target });
195
196            self.copy_extra_objects(builder, &build_compiler, target);
197
198            builder.ensure(StdLink::from_std(self, build_compiler));
199            return;
200        }
201
202        let mut target_deps = builder.ensure(StartupObjects { compiler: build_compiler, target });
203
204        let compiler_to_use =
205            builder.compiler_for(build_compiler.stage, build_compiler.host, target);
206        trace!(?compiler_to_use);
207
208        if compiler_to_use != build_compiler
209            // Never uplift std unless we have compiled stage 1; if stage 1 is compiled,
210            // uplift it from there.
211            //
212            // FIXME: improve `fn compiler_for` to avoid adding stage condition here.
213            && build_compiler.stage > 1
214        {
215            trace!(
216                ?compiler_to_use,
217                ?build_compiler,
218                "build_compiler != compiler_to_use, uplifting library"
219            );
220
221            builder.std(compiler_to_use, target);
222            let msg = if compiler_to_use.host == target {
223                format!(
224                    "Uplifting library (stage{} -> stage{})",
225                    compiler_to_use.stage, build_compiler.stage
226                )
227            } else {
228                format!(
229                    "Uplifting library (stage{}:{} -> stage{}:{})",
230                    compiler_to_use.stage, compiler_to_use.host, build_compiler.stage, target
231                )
232            };
233            builder.info(&msg);
234
235            // Even if we're not building std this stage, the new sysroot must
236            // still contain the third party objects needed by various targets.
237            self.copy_extra_objects(builder, &build_compiler, target);
238
239            builder.ensure(StdLink::from_std(self, compiler_to_use));
240            return;
241        }
242
243        trace!(
244            ?compiler_to_use,
245            ?build_compiler,
246            "compiler == compiler_to_use, handling not-cross-compile scenario"
247        );
248
249        target_deps.extend(self.copy_extra_objects(builder, &build_compiler, target));
250
251        // We build a sysroot for mir-opt tests using the same trick that Miri does: A check build
252        // with -Zalways-encode-mir. This frees us from the need to have a target linker, and the
253        // fact that this is a check build integrates nicely with run_cargo.
254        let mut cargo = if self.is_for_mir_opt_tests {
255            trace!("building special sysroot for mir-opt tests");
256            let mut cargo = builder::Cargo::new_for_mir_opt_tests(
257                builder,
258                build_compiler,
259                Mode::Std,
260                SourceType::InTree,
261                target,
262                Kind::Check,
263            );
264            cargo.rustflag("-Zalways-encode-mir");
265            cargo.arg("--manifest-path").arg(builder.src.join("library/sysroot/Cargo.toml"));
266            cargo
267        } else {
268            trace!("building regular sysroot");
269            let mut cargo = builder::Cargo::new(
270                builder,
271                build_compiler,
272                Mode::Std,
273                SourceType::InTree,
274                target,
275                Kind::Build,
276            );
277            std_cargo(builder, target, &mut cargo);
278            for krate in &*self.crates {
279                cargo.arg("-p").arg(krate);
280            }
281            cargo
282        };
283
284        // See src/bootstrap/synthetic_targets.rs
285        if target.is_synthetic() {
286            cargo.env("RUSTC_BOOTSTRAP_SYNTHETIC_TARGET", "1");
287        }
288        for rustflag in self.extra_rust_args.iter() {
289            cargo.rustflag(rustflag);
290        }
291
292        let _guard = builder.msg(
293            Kind::Build,
294            format_args!("library artifacts{}", crate_description(&self.crates)),
295            Mode::Std,
296            build_compiler,
297            target,
298        );
299        run_cargo(
300            builder,
301            cargo,
302            vec![],
303            &build_stamp::libstd_stamp(builder, build_compiler, target),
304            target_deps,
305            self.is_for_mir_opt_tests, // is_check
306            false,
307        );
308
309        builder.ensure(StdLink::from_std(
310            self,
311            builder.compiler(build_compiler.stage, builder.config.host_target),
312        ));
313    }
314
315    fn metadata(&self) -> Option<StepMetadata> {
316        Some(StepMetadata::build("std", self.target).built_by(self.compiler))
317    }
318}
319
320fn copy_and_stamp(
321    builder: &Builder<'_>,
322    libdir: &Path,
323    sourcedir: &Path,
324    name: &str,
325    target_deps: &mut Vec<(PathBuf, DependencyType)>,
326    dependency_type: DependencyType,
327) {
328    let target = libdir.join(name);
329    builder.copy_link(&sourcedir.join(name), &target, FileType::Regular);
330
331    target_deps.push((target, dependency_type));
332}
333
334fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
335    let libunwind_path = builder.ensure(llvm::Libunwind { target });
336    let libunwind_source = libunwind_path.join("libunwind.a");
337    let libunwind_target = libdir.join("libunwind.a");
338    builder.copy_link(&libunwind_source, &libunwind_target, FileType::NativeLibrary);
339    libunwind_target
340}
341
342/// Copies third party objects needed by various targets.
343fn copy_third_party_objects(
344    builder: &Builder<'_>,
345    compiler: &Compiler,
346    target: TargetSelection,
347) -> Vec<(PathBuf, DependencyType)> {
348    let mut target_deps = vec![];
349
350    if builder.config.needs_sanitizer_runtime_built(target) && compiler.stage != 0 {
351        // The sanitizers are only copied in stage1 or above,
352        // to avoid creating dependency on LLVM.
353        target_deps.extend(
354            copy_sanitizers(builder, compiler, target)
355                .into_iter()
356                .map(|d| (d, DependencyType::Target)),
357        );
358    }
359
360    if target == "x86_64-fortanix-unknown-sgx"
361        || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
362            && (target.contains("linux") || target.contains("fuchsia") || target.contains("aix"))
363    {
364        let libunwind_path =
365            copy_llvm_libunwind(builder, target, &builder.sysroot_target_libdir(*compiler, target));
366        target_deps.push((libunwind_path, DependencyType::Target));
367    }
368
369    target_deps
370}
371
372/// Copies third party objects needed by various targets for self-contained linkage.
373fn copy_self_contained_objects(
374    builder: &Builder<'_>,
375    compiler: &Compiler,
376    target: TargetSelection,
377) -> Vec<(PathBuf, DependencyType)> {
378    let libdir_self_contained =
379        builder.sysroot_target_libdir(*compiler, target).join("self-contained");
380    t!(fs::create_dir_all(&libdir_self_contained));
381    let mut target_deps = vec![];
382
383    // Copies the libc and CRT objects.
384    //
385    // rustc historically provides a more self-contained installation for musl targets
386    // not requiring the presence of a native musl toolchain. For example, it can fall back
387    // to using gcc from a glibc-targeting toolchain for linking.
388    // To do that we have to distribute musl startup objects as a part of Rust toolchain
389    // and link with them manually in the self-contained mode.
390    if target.needs_crt_begin_end() {
391        let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
392            panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
393        });
394        if !target.starts_with("wasm32") {
395            for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
396                copy_and_stamp(
397                    builder,
398                    &libdir_self_contained,
399                    &srcdir,
400                    obj,
401                    &mut target_deps,
402                    DependencyType::TargetSelfContained,
403                );
404            }
405            let crt_path = builder.ensure(llvm::CrtBeginEnd { target });
406            for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
407                let src = crt_path.join(obj);
408                let target = libdir_self_contained.join(obj);
409                builder.copy_link(&src, &target, FileType::NativeLibrary);
410                target_deps.push((target, DependencyType::TargetSelfContained));
411            }
412        } else {
413            // For wasm32 targets, we need to copy the libc.a and crt1-command.o files from the
414            // musl-libdir, but we don't need the other files.
415            for &obj in &["libc.a", "crt1-command.o"] {
416                copy_and_stamp(
417                    builder,
418                    &libdir_self_contained,
419                    &srcdir,
420                    obj,
421                    &mut target_deps,
422                    DependencyType::TargetSelfContained,
423                );
424            }
425        }
426        if !target.starts_with("s390x") {
427            let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
428            target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
429        }
430    } else if target.contains("-wasi") {
431        let srcdir = builder.wasi_libdir(target).unwrap_or_else(|| {
432            panic!(
433                "Target {:?} does not have a \"wasi-root\" key in bootstrap.toml \
434                    or `$WASI_SDK_PATH` set",
435                target.triple
436            )
437        });
438        for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
439            copy_and_stamp(
440                builder,
441                &libdir_self_contained,
442                &srcdir,
443                obj,
444                &mut target_deps,
445                DependencyType::TargetSelfContained,
446            );
447        }
448    } else if target.is_windows_gnu() {
449        for obj in ["crt2.o", "dllcrt2.o"].iter() {
450            let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
451            let dst = libdir_self_contained.join(obj);
452            builder.copy_link(&src, &dst, FileType::NativeLibrary);
453            target_deps.push((dst, DependencyType::TargetSelfContained));
454        }
455    }
456
457    target_deps
458}
459
460/// Resolves standard library crates for `Std::run_make` for any build kind (like check, doc,
461/// build, clippy, etc.).
462pub fn std_crates_for_run_make(run: &RunConfig<'_>) -> Vec<String> {
463    let mut crates = run.make_run_crates(builder::Alias::Library);
464
465    // For no_std targets, we only want to check core and alloc
466    // Regardless of core/alloc being selected explicitly or via the "library" default alias,
467    // we only want to keep these two crates.
468    // The set of no_std crates should be kept in sync with what `Builder::std_cargo` does.
469    // Note: an alternative design would be to return an enum from this function (Default vs Subset)
470    // of crates. However, several steps currently pass `-p <package>` even if all crates are
471    // selected, because Cargo behaves differently in that case. To keep that behavior without
472    // making further changes, we pre-filter the no-std crates here.
473    let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
474    if target_is_no_std {
475        crates.retain(|c| c == "core" || c == "alloc");
476    }
477    crates
478}
479
480/// Tries to find LLVM's `compiler-rt` source directory, for building `library/profiler_builtins`.
481///
482/// Normally it lives in the `src/llvm-project` submodule, but if we will be using a
483/// downloaded copy of CI LLVM, then we try to use the `compiler-rt` sources from
484/// there instead, which lets us avoid checking out the LLVM submodule.
485fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
486    // Try to use `compiler-rt` sources from downloaded CI LLVM, if possible.
487    if builder.config.llvm_from_ci {
488        // CI LLVM might not have been downloaded yet, so try to download it now.
489        builder.config.maybe_download_ci_llvm();
490        let ci_llvm_compiler_rt = builder.config.ci_llvm_root().join("compiler-rt");
491        if ci_llvm_compiler_rt.exists() {
492            return ci_llvm_compiler_rt;
493        }
494    }
495
496    // Otherwise, fall back to requiring the LLVM submodule.
497    builder.require_submodule("src/llvm-project", {
498        Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
499    });
500    builder.src.join("src/llvm-project/compiler-rt")
501}
502
503/// Configure cargo to compile the standard library, adding appropriate env vars
504/// and such.
505pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, cargo: &mut Cargo) {
506    // rustc already ensures that it builds with the minimum deployment
507    // target, so ideally we shouldn't need to do anything here.
508    //
509    // However, `cc` currently defaults to a higher version for backwards
510    // compatibility, which means that compiler-rt, which is built via
511    // compiler-builtins' build script, gets built with a higher deployment
512    // target. This in turn causes warnings while linking, and is generally
513    // a compatibility hazard.
514    //
515    // So, at least until https://github.com/rust-lang/cc-rs/issues/1171, or
516    // perhaps https://github.com/rust-lang/cargo/issues/13115 is resolved, we
517    // explicitly set the deployment target environment variables to avoid
518    // this issue.
519    //
520    // This place also serves as an extension point if we ever wanted to raise
521    // rustc's default deployment target while keeping the prebuilt `std` at
522    // a lower version, so it's kinda nice to have in any case.
523    if target.contains("apple") && !builder.config.dry_run() {
524        // Query rustc for the deployment target, and the associated env var.
525        // The env var is one of the standard `*_DEPLOYMENT_TARGET` vars, i.e.
526        // `MACOSX_DEPLOYMENT_TARGET`, `IPHONEOS_DEPLOYMENT_TARGET`, etc.
527        let mut cmd = command(builder.rustc(cargo.compiler()));
528        cmd.arg("--target").arg(target.rustc_target_arg());
529        cmd.arg("--print=deployment-target");
530        let output = cmd.run_capture_stdout(builder).stdout();
531
532        let (env_var, value) = output.split_once('=').unwrap();
533        // Unconditionally set the env var (if it was set in the environment
534        // already, rustc should've picked that up).
535        cargo.env(env_var.trim(), value.trim());
536
537        // Allow CI to override the deployment target for `std` on macOS.
538        //
539        // This is useful because we might want the host tooling LLVM, `rustc`
540        // and Cargo to have a different deployment target than `std` itself
541        // (currently, these two versions are the same, but in the past, we
542        // supported macOS 10.7 for user code and macOS 10.8 in host tooling).
543        //
544        // It is not necessary on the other platforms, since only macOS has
545        // support for host tooling.
546        if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
547            cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
548        }
549    }
550
551    // Paths needed by `library/profiler_builtins/build.rs`.
552    if let Some(path) = builder.config.profiler_path(target) {
553        cargo.env("LLVM_PROFILER_RT_LIB", path);
554    } else if builder.config.profiler_enabled(target) {
555        let compiler_rt = compiler_rt_for_profiler(builder);
556        // Currently this is separate from the env var used by `compiler_builtins`
557        // (below) so that adding support for CI LLVM here doesn't risk breaking
558        // the compiler builtins. But they could be unified if desired.
559        cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
560    }
561
562    // Determine if we're going to compile in optimized C intrinsics to
563    // the `compiler-builtins` crate. These intrinsics live in LLVM's
564    // `compiler-rt` repository.
565    //
566    // Note that this shouldn't affect the correctness of `compiler-builtins`,
567    // but only its speed. Some intrinsics in C haven't been translated to Rust
568    // yet but that's pretty rare. Other intrinsics have optimized
569    // implementations in C which have only had slower versions ported to Rust,
570    // so we favor the C version where we can, but it's not critical.
571    //
572    // If `compiler-rt` is available ensure that the `c` feature of the
573    // `compiler-builtins` crate is enabled and it's configured to learn where
574    // `compiler-rt` is located.
575    let compiler_builtins_c_feature = if builder.config.optimized_compiler_builtins(target) {
576        // NOTE: this interacts strangely with `llvm-has-rust-patches`. In that case, we enforce `submodules = false`, so this is a no-op.
577        // But, the user could still decide to manually use an in-tree submodule.
578        //
579        // NOTE: if we're using system llvm, we'll end up building a version of `compiler-rt` that doesn't match the LLVM we're linking to.
580        // That's probably ok? At least, the difference wasn't enforced before. There's a comment in
581        // the compiler_builtins build script that makes me nervous, though:
582        // https://github.com/rust-lang/compiler-builtins/blob/31ee4544dbe47903ce771270d6e3bea8654e9e50/build.rs#L575-L579
583        builder.require_submodule(
584            "src/llvm-project",
585            Some(
586                "The `build.optimized-compiler-builtins` config option \
587                 requires `compiler-rt` sources from LLVM.",
588            ),
589        );
590        let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
591        assert!(compiler_builtins_root.exists());
592        // The path to `compiler-rt` is also used by `profiler_builtins` (above),
593        // so if you're changing something here please also change that as appropriate.
594        cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
595        " compiler-builtins-c"
596    } else {
597        ""
598    };
599
600    // `libtest` uses this to know whether or not to support
601    // `-Zunstable-options`.
602    if !builder.unstable_features() {
603        cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
604    }
605
606    let mut features = String::new();
607
608    if builder.no_std(target) == Some(true) {
609        features += " compiler-builtins-mem";
610        if !target.starts_with("bpf") {
611            features.push_str(compiler_builtins_c_feature);
612        }
613
614        // for no-std targets we only compile a few no_std crates
615        cargo
616            .args(["-p", "alloc"])
617            .arg("--manifest-path")
618            .arg(builder.src.join("library/alloc/Cargo.toml"))
619            .arg("--features")
620            .arg(features);
621    } else {
622        features += &builder.std_features(target);
623        features.push_str(compiler_builtins_c_feature);
624
625        cargo
626            .arg("--features")
627            .arg(features)
628            .arg("--manifest-path")
629            .arg(builder.src.join("library/sysroot/Cargo.toml"));
630
631        // Help the libc crate compile by assisting it in finding various
632        // sysroot native libraries.
633        if target.contains("musl")
634            && let Some(p) = builder.musl_libdir(target)
635        {
636            let root = format!("native={}", p.to_str().unwrap());
637            cargo.rustflag("-L").rustflag(&root);
638        }
639
640        if target.contains("-wasi")
641            && let Some(dir) = builder.wasi_libdir(target)
642        {
643            let root = format!("native={}", dir.to_str().unwrap());
644            cargo.rustflag("-L").rustflag(&root);
645        }
646    }
647
648    // By default, rustc uses `-Cembed-bitcode=yes`, and Cargo overrides that
649    // with `-Cembed-bitcode=no` for non-LTO builds. However, libstd must be
650    // built with bitcode so that the produced rlibs can be used for both LTO
651    // builds (which use bitcode) and non-LTO builds (which use object code).
652    // So we override the override here!
653    cargo.rustflag("-Cembed-bitcode=yes");
654
655    if builder.config.rust_lto == RustcLto::Off {
656        cargo.rustflag("-Clto=off");
657    }
658
659    // By default, rustc does not include unwind tables unless they are required
660    // for a particular target. They are not required by RISC-V targets, but
661    // compiling the standard library with them means that users can get
662    // backtraces without having to recompile the standard library themselves.
663    //
664    // This choice was discussed in https://github.com/rust-lang/rust/pull/69890
665    if target.contains("riscv") {
666        cargo.rustflag("-Cforce-unwind-tables=yes");
667    }
668
669    // Enable frame pointers by default for the library. Note that they are still controlled by a
670    // separate setting for the compiler.
671    cargo.rustflag("-Zunstable-options");
672    cargo.rustflag("-Cforce-frame-pointers=non-leaf");
673
674    let html_root =
675        format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
676    cargo.rustflag(&html_root);
677    cargo.rustdocflag(&html_root);
678
679    cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
680}
681
682#[derive(Debug, Clone, PartialEq, Eq, Hash)]
683pub struct StdLink {
684    pub compiler: Compiler,
685    pub target_compiler: Compiler,
686    pub target: TargetSelection,
687    /// Not actually used; only present to make sure the cache invalidation is correct.
688    crates: Vec<String>,
689    /// See [`Std::force_recompile`].
690    force_recompile: bool,
691}
692
693impl StdLink {
694    pub fn from_std(std: Std, host_compiler: Compiler) -> Self {
695        Self {
696            compiler: host_compiler,
697            target_compiler: std.compiler,
698            target: std.target,
699            crates: std.crates,
700            force_recompile: std.force_recompile,
701        }
702    }
703}
704
705impl Step for StdLink {
706    type Output = ();
707
708    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
709        run.never()
710    }
711
712    /// Link all libstd rlibs/dylibs into the sysroot location.
713    ///
714    /// Links those artifacts generated by `compiler` to the `stage` compiler's
715    /// sysroot for the specified `host` and `target`.
716    ///
717    /// Note that this assumes that `compiler` has already generated the libstd
718    /// libraries for `target`, and this method will find them in the relevant
719    /// output directory.
720    #[cfg_attr(
721        feature = "tracing",
722        instrument(
723            level = "trace",
724            name = "StdLink::run",
725            skip_all,
726            fields(
727                compiler = ?self.compiler,
728                target_compiler = ?self.target_compiler,
729                target = ?self.target
730            ),
731        ),
732    )]
733    fn run(self, builder: &Builder<'_>) {
734        let compiler = self.compiler;
735        let target_compiler = self.target_compiler;
736        let target = self.target;
737
738        // NOTE: intentionally does *not* check `target == builder.build` to avoid having to add the same check in `test::Crate`.
739        let (libdir, hostdir) = if !self.force_recompile && builder.download_rustc() {
740            // NOTE: copies part of `sysroot_libdir` to avoid having to add a new `force_recompile` argument there too
741            let lib = builder.sysroot_libdir_relative(self.compiler);
742            let sysroot = builder.ensure(crate::core::build_steps::compile::Sysroot {
743                compiler: self.compiler,
744                force_recompile: self.force_recompile,
745            });
746            let libdir = sysroot.join(lib).join("rustlib").join(target).join("lib");
747            let hostdir = sysroot.join(lib).join("rustlib").join(compiler.host).join("lib");
748            (libdir, hostdir)
749        } else {
750            let libdir = builder.sysroot_target_libdir(target_compiler, target);
751            let hostdir = builder.sysroot_target_libdir(target_compiler, compiler.host);
752            (libdir, hostdir)
753        };
754
755        let is_downloaded_beta_stage0 = builder
756            .build
757            .config
758            .initial_rustc
759            .starts_with(builder.out.join(compiler.host).join("stage0/bin"));
760
761        // Special case for stage0, to make `rustup toolchain link` and `x dist --stage 0`
762        // work for stage0-sysroot. We only do this if the stage0 compiler comes from beta,
763        // and is not set to a custom path.
764        if compiler.stage == 0 && is_downloaded_beta_stage0 {
765            // Copy bin files from stage0/bin to stage0-sysroot/bin
766            let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
767
768            let host = compiler.host;
769            let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
770            let sysroot_bin_dir = sysroot.join("bin");
771            t!(fs::create_dir_all(&sysroot_bin_dir));
772            builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
773
774            let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
775            t!(fs::create_dir_all(sysroot.join("lib")));
776            builder.cp_link_r(&stage0_lib_dir, &sysroot.join("lib"));
777
778            // Copy codegen-backends from stage0
779            let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
780            t!(fs::create_dir_all(&sysroot_codegen_backends));
781            let stage0_codegen_backends = builder
782                .out
783                .join(host)
784                .join("stage0/lib/rustlib")
785                .join(host)
786                .join("codegen-backends");
787            if stage0_codegen_backends.exists() {
788                builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
789            }
790        } else if compiler.stage == 0 {
791            let sysroot = builder.out.join(compiler.host.triple).join("stage0-sysroot");
792
793            if builder.local_rebuild {
794                // On local rebuilds this path might be a symlink to the project root,
795                // which can be read-only (e.g., on CI). So remove it before copying
796                // the stage0 lib.
797                let _ = fs::remove_dir_all(sysroot.join("lib/rustlib/src/rust"));
798            }
799
800            builder.cp_link_r(&builder.initial_sysroot.join("lib"), &sysroot.join("lib"));
801        } else {
802            if builder.download_rustc() {
803                // Ensure there are no CI-rustc std artifacts.
804                let _ = fs::remove_dir_all(&libdir);
805                let _ = fs::remove_dir_all(&hostdir);
806            }
807
808            add_to_sysroot(
809                builder,
810                &libdir,
811                &hostdir,
812                &build_stamp::libstd_stamp(builder, compiler, target),
813            );
814        }
815    }
816}
817
818/// Copies sanitizer runtime libraries into target libdir.
819fn copy_sanitizers(
820    builder: &Builder<'_>,
821    compiler: &Compiler,
822    target: TargetSelection,
823) -> Vec<PathBuf> {
824    let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
825
826    if builder.config.dry_run() {
827        return Vec::new();
828    }
829
830    let mut target_deps = Vec::new();
831    let libdir = builder.sysroot_target_libdir(*compiler, target);
832
833    for runtime in &runtimes {
834        let dst = libdir.join(&runtime.name);
835        builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
836
837        // The `aarch64-apple-ios-macabi` and `x86_64-apple-ios-macabi` are also supported for
838        // sanitizers, but they share a sanitizer runtime with `${arch}-apple-darwin`, so we do
839        // not list them here to rename and sign the runtime library.
840        if target == "x86_64-apple-darwin"
841            || target == "aarch64-apple-darwin"
842            || target == "aarch64-apple-ios"
843            || target == "aarch64-apple-ios-sim"
844            || target == "x86_64-apple-ios"
845        {
846            // Update the library’s install name to reflect that it has been renamed.
847            apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
848            // Upon renaming the install name, the code signature of the file will invalidate,
849            // so we will sign it again.
850            apple_darwin_sign_file(builder, &dst);
851        }
852
853        target_deps.push(dst);
854    }
855
856    target_deps
857}
858
859fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
860    command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
861}
862
863fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
864    command("codesign")
865        .arg("-f") // Force to rewrite the existing signature
866        .arg("-s")
867        .arg("-")
868        .arg(file_path)
869        .run(builder);
870}
871
872#[derive(Debug, Clone, PartialEq, Eq, Hash)]
873pub struct StartupObjects {
874    pub compiler: Compiler,
875    pub target: TargetSelection,
876}
877
878impl Step for StartupObjects {
879    type Output = Vec<(PathBuf, DependencyType)>;
880
881    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
882        run.path("library/rtstartup")
883    }
884
885    fn make_run(run: RunConfig<'_>) {
886        run.builder.ensure(StartupObjects {
887            compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
888            target: run.target,
889        });
890    }
891
892    /// Builds and prepare startup objects like rsbegin.o and rsend.o
893    ///
894    /// These are primarily used on Windows right now for linking executables/dlls.
895    /// They don't require any library support as they're just plain old object
896    /// files, so we just use the nightly snapshot compiler to always build them (as
897    /// no other compilers are guaranteed to be available).
898    #[cfg_attr(
899        feature = "tracing",
900        instrument(
901            level = "trace",
902            name = "StartupObjects::run",
903            skip_all,
904            fields(compiler = ?self.compiler, target = ?self.target),
905        ),
906    )]
907    fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
908        let for_compiler = self.compiler;
909        let target = self.target;
910        if !target.is_windows_gnu() {
911            return vec![];
912        }
913
914        let mut target_deps = vec![];
915
916        let src_dir = &builder.src.join("library").join("rtstartup");
917        let dst_dir = &builder.native_dir(target).join("rtstartup");
918        let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
919        t!(fs::create_dir_all(dst_dir));
920
921        for file in &["rsbegin", "rsend"] {
922            let src_file = &src_dir.join(file.to_string() + ".rs");
923            let dst_file = &dst_dir.join(file.to_string() + ".o");
924            if !up_to_date(src_file, dst_file) {
925                let mut cmd = command(&builder.initial_rustc);
926                cmd.env("RUSTC_BOOTSTRAP", "1");
927                if !builder.local_rebuild {
928                    // a local_rebuild compiler already has stage1 features
929                    cmd.arg("--cfg").arg("bootstrap");
930                }
931                cmd.arg("--target")
932                    .arg(target.rustc_target_arg())
933                    .arg("--emit=obj")
934                    .arg("-o")
935                    .arg(dst_file)
936                    .arg(src_file)
937                    .run(builder);
938            }
939
940            let obj = sysroot_dir.join((*file).to_string() + ".o");
941            builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
942            target_deps.push((obj, DependencyType::Target));
943        }
944
945        target_deps
946    }
947}
948
949fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
950    let ci_rustc_dir = builder.config.ci_rustc_dir();
951
952    for file in contents {
953        let src = ci_rustc_dir.join(&file);
954        let dst = sysroot.join(file);
955        if src.is_dir() {
956            t!(fs::create_dir_all(dst));
957        } else {
958            builder.copy_link(&src, &dst, FileType::Regular);
959        }
960    }
961}
962
963/// Build rustc using the passed `build_compiler`.
964///
965/// - Makes sure that `build_compiler` has a standard library prepared for its host target,
966///   so that it can compile build scripts and proc macros when building this `rustc`.
967/// - Makes sure that `build_compiler` has a standard library prepared for `target`,
968///   so that the built `rustc` can *link to it* and use it at runtime.
969#[derive(Debug, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
970pub struct Rustc {
971    /// The target on which rustc will run (its host).
972    pub target: TargetSelection,
973    /// The **previous** compiler used to compile this rustc.
974    pub build_compiler: Compiler,
975    /// Whether to build a subset of crates, rather than the whole compiler.
976    ///
977    /// This should only be requested by the user, not used within bootstrap itself.
978    /// Using it within bootstrap can lead to confusing situation where lints are replayed
979    /// in two different steps.
980    crates: Vec<String>,
981}
982
983impl Rustc {
984    pub fn new(build_compiler: Compiler, target: TargetSelection) -> Self {
985        Self { target, build_compiler, crates: Default::default() }
986    }
987}
988
989impl Step for Rustc {
990    /// We return the stage of the "actual" compiler (not the uplifted one).
991    ///
992    /// By "actual" we refer to the uplifting logic where we may not compile the requested stage;
993    /// instead, we uplift it from the previous stages. Which can lead to bootstrap failures in
994    /// specific situations where we request stage X from other steps. However we may end up
995    /// uplifting it from stage Y, causing the other stage to fail when attempting to link with
996    /// stage X which was never actually built.
997    type Output = u32;
998    const ONLY_HOSTS: bool = true;
999    const DEFAULT: bool = false;
1000
1001    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1002        let mut crates = run.builder.in_tree_crates("rustc-main", None);
1003        for (i, krate) in crates.iter().enumerate() {
1004            // We can't allow `build rustc` as an alias for this Step, because that's reserved by `Assemble`.
1005            // Ideally Assemble would use `build compiler` instead, but that seems too confusing to be worth the breaking change.
1006            if krate.name == "rustc-main" {
1007                crates.swap_remove(i);
1008                break;
1009            }
1010        }
1011        run.crates(crates)
1012    }
1013
1014    fn make_run(run: RunConfig<'_>) {
1015        // If only `compiler` was passed, do not run this step.
1016        // Instead the `Assemble` step will take care of compiling Rustc.
1017        if run.builder.paths == vec![PathBuf::from("compiler")] {
1018            return;
1019        }
1020
1021        let crates = run.cargo_crates_in_set();
1022        run.builder.ensure(Rustc {
1023            build_compiler: run
1024                .builder
1025                .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1026            target: run.target,
1027            crates,
1028        });
1029    }
1030
1031    /// Builds the compiler.
1032    ///
1033    /// This will build the compiler for a particular stage of the build using
1034    /// the `build_compiler` targeting the `target` architecture. The artifacts
1035    /// created will also be linked into the sysroot directory.
1036    #[cfg_attr(
1037        feature = "tracing",
1038        instrument(
1039            level = "debug",
1040            name = "Rustc::run",
1041            skip_all,
1042            fields(previous_compiler = ?self.build_compiler, target = ?self.target),
1043        ),
1044    )]
1045    fn run(self, builder: &Builder<'_>) -> u32 {
1046        let build_compiler = self.build_compiler;
1047        let target = self.target;
1048
1049        // NOTE: the ABI of the stage0 compiler is different from the ABI of the downloaded compiler,
1050        // so its artifacts can't be reused.
1051        if builder.download_rustc() && build_compiler.stage != 0 {
1052            trace!(stage = build_compiler.stage, "`download_rustc` requested");
1053
1054            let sysroot =
1055                builder.ensure(Sysroot { compiler: build_compiler, force_recompile: false });
1056            cp_rustc_component_to_ci_sysroot(
1057                builder,
1058                &sysroot,
1059                builder.config.ci_rustc_dev_contents(),
1060            );
1061            return build_compiler.stage;
1062        }
1063
1064        // Build a standard library for `target` using the `build_compiler`.
1065        // This will be the standard library that the rustc which we build *links to*.
1066        builder.std(build_compiler, target);
1067
1068        if builder.config.keep_stage.contains(&build_compiler.stage) {
1069            trace!(stage = build_compiler.stage, "`keep-stage` requested");
1070
1071            builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1072            builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1073            builder.ensure(RustcLink::from_rustc(self, build_compiler));
1074
1075            return build_compiler.stage;
1076        }
1077
1078        let compiler_to_use =
1079            builder.compiler_for(build_compiler.stage, build_compiler.host, target);
1080        if compiler_to_use != build_compiler {
1081            builder.ensure(Rustc::new(compiler_to_use, target));
1082            let msg = if compiler_to_use.host == target {
1083                format!(
1084                    "Uplifting rustc (stage{} -> stage{})",
1085                    compiler_to_use.stage,
1086                    build_compiler.stage + 1
1087                )
1088            } else {
1089                format!(
1090                    "Uplifting rustc (stage{}:{} -> stage{}:{})",
1091                    compiler_to_use.stage,
1092                    compiler_to_use.host,
1093                    build_compiler.stage + 1,
1094                    target
1095                )
1096            };
1097            builder.info(&msg);
1098            builder.ensure(RustcLink::from_rustc(self, compiler_to_use));
1099            return compiler_to_use.stage;
1100        }
1101
1102        // Build a standard library for the current host target using the `build_compiler`.
1103        // This standard library will be used when building `rustc` for compiling
1104        // build scripts and proc macros.
1105        // If we are not cross-compiling, the Std build above will be the same one as the one we
1106        // prepare here.
1107        builder.std(
1108            builder.compiler(self.build_compiler.stage, builder.config.host_target),
1109            builder.config.host_target,
1110        );
1111
1112        let mut cargo = builder::Cargo::new(
1113            builder,
1114            build_compiler,
1115            Mode::Rustc,
1116            SourceType::InTree,
1117            target,
1118            Kind::Build,
1119        );
1120
1121        rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
1122
1123        // NB: all RUSTFLAGS should be added to `rustc_cargo()` so they will be
1124        // consistently applied by check/doc/test modes too.
1125
1126        for krate in &*self.crates {
1127            cargo.arg("-p").arg(krate);
1128        }
1129
1130        if builder.build.config.enable_bolt_settings && build_compiler.stage == 1 {
1131            // Relocations are required for BOLT to work.
1132            cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1133        }
1134
1135        let _guard = builder.msg(
1136            Kind::Build,
1137            format_args!("compiler artifacts{}", crate_description(&self.crates)),
1138            Mode::Rustc,
1139            build_compiler,
1140            target,
1141        );
1142        let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
1143        run_cargo(
1144            builder,
1145            cargo,
1146            vec![],
1147            &stamp,
1148            vec![],
1149            false,
1150            true, // Only ship rustc_driver.so and .rmeta files, not all intermediate .rlib files.
1151        );
1152
1153        let target_root_dir = stamp.path().parent().unwrap();
1154        // When building `librustc_driver.so` (like `libLLVM.so`) on linux, it can contain
1155        // unexpected debuginfo from dependencies, for example from the C++ standard library used in
1156        // our LLVM wrapper. Unless we're explicitly requesting `librustc_driver` to be built with
1157        // debuginfo (via the debuginfo level of the executables using it): strip this debuginfo
1158        // away after the fact.
1159        if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1160            && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1161        {
1162            let rustc_driver = target_root_dir.join("librustc_driver.so");
1163            strip_debug(builder, target, &rustc_driver);
1164        }
1165
1166        if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1167            // Due to LTO a lot of debug info from C++ dependencies such as jemalloc can make it into
1168            // our final binaries
1169            strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1170        }
1171
1172        builder.ensure(RustcLink::from_rustc(
1173            self,
1174            builder.compiler(build_compiler.stage, builder.config.host_target),
1175        ));
1176
1177        build_compiler.stage
1178    }
1179
1180    fn metadata(&self) -> Option<StepMetadata> {
1181        Some(StepMetadata::build("rustc", self.target).built_by(self.build_compiler))
1182    }
1183}
1184
1185pub fn rustc_cargo(
1186    builder: &Builder<'_>,
1187    cargo: &mut Cargo,
1188    target: TargetSelection,
1189    build_compiler: &Compiler,
1190    crates: &[String],
1191) {
1192    cargo
1193        .arg("--features")
1194        .arg(builder.rustc_features(builder.kind, target, crates))
1195        .arg("--manifest-path")
1196        .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1197
1198    cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1199
1200    // If the rustc output is piped to e.g. `head -n1` we want the process to be killed, rather than
1201    // having an error bubble up and cause a panic.
1202    //
1203    // FIXME(jieyouxu): this flag is load-bearing for rustc to not ICE on broken pipes, because
1204    // rustc internally sometimes uses std `println!` -- but std `println!` by default will panic on
1205    // broken pipes, and uncaught panics will manifest as an ICE. The compiler *should* handle this
1206    // properly, but this flag is set in the meantime to paper over the I/O errors.
1207    //
1208    // See <https://github.com/rust-lang/rust/issues/131059> for details.
1209    //
1210    // Also see the discussion for properly handling I/O errors related to broken pipes, i.e. safe
1211    // variants of `println!` in
1212    // <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Internal.20lint.20for.20raw.20.60print!.60.20and.20.60println!.60.3F>.
1213    cargo.rustflag("-Zon-broken-pipe=kill");
1214
1215    // We want to link against registerEnzyme and in the future we want to use additional
1216    // functionality from Enzyme core. For that we need to link against Enzyme.
1217    if builder.config.llvm_enzyme {
1218        let arch = builder.build.host_target;
1219        let enzyme_dir = builder.build.out.join(arch).join("enzyme").join("lib");
1220        cargo.rustflag("-L").rustflag(enzyme_dir.to_str().expect("Invalid path"));
1221
1222        if let Some(llvm_config) = builder.llvm_config(builder.config.host_target) {
1223            let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
1224            cargo.rustflag("-l").rustflag(&format!("Enzyme-{llvm_version_major}"));
1225        }
1226    }
1227
1228    // Building with protected visibility reduces the number of dynamic relocations needed, giving
1229    // us a faster startup time. However GNU ld < 2.40 will error if we try to link a shared object
1230    // with direct references to protected symbols, so for now we only use protected symbols if
1231    // linking with LLD is enabled.
1232    if builder.build.config.lld_mode.is_used() {
1233        cargo.rustflag("-Zdefault-visibility=protected");
1234    }
1235
1236    if is_lto_stage(build_compiler) {
1237        match builder.config.rust_lto {
1238            RustcLto::Thin | RustcLto::Fat => {
1239                // Since using LTO for optimizing dylibs is currently experimental,
1240                // we need to pass -Zdylib-lto.
1241                cargo.rustflag("-Zdylib-lto");
1242                // Cargo by default passes `-Cembed-bitcode=no` and doesn't pass `-Clto` when
1243                // compiling dylibs (and their dependencies), even when LTO is enabled for the
1244                // crate. Therefore, we need to override `-Clto` and `-Cembed-bitcode` here.
1245                let lto_type = match builder.config.rust_lto {
1246                    RustcLto::Thin => "thin",
1247                    RustcLto::Fat => "fat",
1248                    _ => unreachable!(),
1249                };
1250                cargo.rustflag(&format!("-Clto={lto_type}"));
1251                cargo.rustflag("-Cembed-bitcode=yes");
1252            }
1253            RustcLto::ThinLocal => { /* Do nothing, this is the default */ }
1254            RustcLto::Off => {
1255                cargo.rustflag("-Clto=off");
1256            }
1257        }
1258    } else if builder.config.rust_lto == RustcLto::Off {
1259        cargo.rustflag("-Clto=off");
1260    }
1261
1262    // With LLD, we can use ICF (identical code folding) to reduce the executable size
1263    // of librustc_driver/rustc and to improve i-cache utilization.
1264    //
1265    // -Wl,[link options] doesn't work on MSVC. However, /OPT:ICF (technically /OPT:REF,ICF)
1266    // is already on by default in MSVC optimized builds, which is interpreted as --icf=all:
1267    // https://github.com/llvm/llvm-project/blob/3329cec2f79185bafd678f310fafadba2a8c76d2/lld/COFF/Driver.cpp#L1746
1268    // https://github.com/rust-lang/rust/blob/f22819bcce4abaff7d1246a56eec493418f9f4ee/compiler/rustc_codegen_ssa/src/back/linker.rs#L827
1269    if builder.config.lld_mode.is_used() && !build_compiler.host.is_msvc() {
1270        cargo.rustflag("-Clink-args=-Wl,--icf=all");
1271    }
1272
1273    if builder.config.rust_profile_use.is_some() && builder.config.rust_profile_generate.is_some() {
1274        panic!("Cannot use and generate PGO profiles at the same time");
1275    }
1276    let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
1277        if build_compiler.stage == 1 {
1278            cargo.rustflag(&format!("-Cprofile-generate={path}"));
1279            // Apparently necessary to avoid overflowing the counters during
1280            // a Cargo build profile
1281            cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
1282            true
1283        } else {
1284            false
1285        }
1286    } else if let Some(path) = &builder.config.rust_profile_use {
1287        if build_compiler.stage == 1 {
1288            cargo.rustflag(&format!("-Cprofile-use={path}"));
1289            if builder.is_verbose() {
1290                cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
1291            }
1292            true
1293        } else {
1294            false
1295        }
1296    } else {
1297        false
1298    };
1299    if is_collecting {
1300        // Ensure paths to Rust sources are relative, not absolute.
1301        cargo.rustflag(&format!(
1302            "-Cllvm-args=-static-func-strip-dirname-prefix={}",
1303            builder.config.src.components().count()
1304        ));
1305    }
1306
1307    // The stage0 compiler changes infrequently and does not directly depend on code
1308    // in the current working directory. Therefore, caching it with sccache should be
1309    // useful.
1310    // This is only performed for non-incremental builds, as ccache cannot deal with these.
1311    if let Some(ref ccache) = builder.config.ccache
1312        && build_compiler.stage == 0
1313        && !builder.config.incremental
1314    {
1315        cargo.env("RUSTC_WRAPPER", ccache);
1316    }
1317
1318    rustc_cargo_env(builder, cargo, target);
1319}
1320
1321pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1322    // Set some configuration variables picked up by build scripts and
1323    // the compiler alike
1324    cargo
1325        .env("CFG_RELEASE", builder.rust_release())
1326        .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1327        .env("CFG_VERSION", builder.rust_version());
1328
1329    // Some tools like Cargo detect their own git information in build scripts. When omit-git-hash
1330    // is enabled in bootstrap.toml, we pass this environment variable to tell build scripts to avoid
1331    // detecting git information on their own.
1332    if builder.config.omit_git_hash {
1333        cargo.env("CFG_OMIT_GIT_HASH", "1");
1334    }
1335
1336    if let Some(backend) = builder.config.default_codegen_backend(target) {
1337        cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", backend.name());
1338    }
1339
1340    let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1341    let target_config = builder.config.target_config.get(&target);
1342
1343    cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1344
1345    if let Some(ref ver_date) = builder.rust_info().commit_date() {
1346        cargo.env("CFG_VER_DATE", ver_date);
1347    }
1348    if let Some(ref ver_hash) = builder.rust_info().sha() {
1349        cargo.env("CFG_VER_HASH", ver_hash);
1350    }
1351    if !builder.unstable_features() {
1352        cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1353    }
1354
1355    // Prefer the current target's own default_linker, else a globally
1356    // specified one.
1357    if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1358        cargo.env("CFG_DEFAULT_LINKER", s);
1359    } else if let Some(ref s) = builder.config.rustc_default_linker {
1360        cargo.env("CFG_DEFAULT_LINKER", s);
1361    }
1362
1363    // Enable rustc's env var for `rust-lld` when requested.
1364    if builder.config.lld_enabled {
1365        cargo.env("CFG_USE_SELF_CONTAINED_LINKER", "1");
1366    }
1367
1368    if builder.config.rust_verify_llvm_ir {
1369        cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1370    }
1371
1372    if builder.config.llvm_enzyme {
1373        cargo.rustflag("--cfg=llvm_enzyme");
1374    }
1375
1376    // These conditionals represent a tension between three forces:
1377    // - For non-check builds, we need to define some LLVM-related environment
1378    //   variables, requiring LLVM to have been built.
1379    // - For check builds, we want to avoid building LLVM if possible.
1380    // - Check builds and non-check builds should have the same environment if
1381    //   possible, to avoid unnecessary rebuilds due to cache-busting.
1382    //
1383    // Therefore we try to avoid building LLVM for check builds, but only if
1384    // building LLVM would be expensive. If "building" LLVM is cheap
1385    // (i.e. it's already built or is downloadable), we prefer to maintain a
1386    // consistent environment between check and non-check builds.
1387    if builder.config.llvm_enabled(target) {
1388        let building_llvm_is_expensive =
1389            crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false)
1390                .should_build();
1391
1392        let skip_llvm = (builder.kind == Kind::Check) && building_llvm_is_expensive;
1393        if !skip_llvm {
1394            rustc_llvm_env(builder, cargo, target)
1395        }
1396    }
1397
1398    // Build jemalloc on AArch64 with support for page sizes up to 64K
1399    // See: https://github.com/rust-lang/rust/pull/135081
1400    if builder.config.jemalloc(target)
1401        && target.starts_with("aarch64")
1402        && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none()
1403    {
1404        cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1405    }
1406}
1407
1408/// Pass down configuration from the LLVM build into the build of
1409/// rustc_llvm and rustc_codegen_llvm.
1410///
1411/// Note that this has the side-effect of _building LLVM_, which is sometimes
1412/// unwanted (e.g. for check builds).
1413fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1414    if builder.config.is_rust_llvm(target) {
1415        cargo.env("LLVM_RUSTLLVM", "1");
1416    }
1417    if builder.config.llvm_enzyme {
1418        cargo.env("LLVM_ENZYME", "1");
1419    }
1420    let llvm::LlvmResult { llvm_config, .. } = builder.ensure(llvm::Llvm { target });
1421    cargo.env("LLVM_CONFIG", &llvm_config);
1422
1423    // Some LLVM linker flags (-L and -l) may be needed to link `rustc_llvm`. Its build script
1424    // expects these to be passed via the `LLVM_LINKER_FLAGS` env variable, separated by
1425    // whitespace.
1426    //
1427    // For example:
1428    // - on windows, when `clang-cl` is used with instrumentation, we need to manually add
1429    // clang's runtime library resource directory so that the profiler runtime library can be
1430    // found. This is to avoid the linker errors about undefined references to
1431    // `__llvm_profile_instrument_memop` when linking `rustc_driver`.
1432    let mut llvm_linker_flags = String::new();
1433    if builder.config.llvm_profile_generate
1434        && target.is_msvc()
1435        && let Some(ref clang_cl_path) = builder.config.llvm_clang_cl
1436    {
1437        // Add clang's runtime library directory to the search path
1438        let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1439        llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
1440    }
1441
1442    // The config can also specify its own llvm linker flags.
1443    if let Some(ref s) = builder.config.llvm_ldflags {
1444        if !llvm_linker_flags.is_empty() {
1445            llvm_linker_flags.push(' ');
1446        }
1447        llvm_linker_flags.push_str(s);
1448    }
1449
1450    // Set the linker flags via the env var that `rustc_llvm`'s build script will read.
1451    if !llvm_linker_flags.is_empty() {
1452        cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
1453    }
1454
1455    // Building with a static libstdc++ is only supported on Linux and windows-gnu* right now,
1456    // not for MSVC or macOS
1457    if builder.config.llvm_static_stdcpp
1458        && !target.contains("freebsd")
1459        && !target.is_msvc()
1460        && !target.contains("apple")
1461        && !target.contains("solaris")
1462    {
1463        let libstdcxx_name =
1464            if target.contains("windows-gnullvm") { "libc++.a" } else { "libstdc++.a" };
1465        let file = compiler_file(
1466            builder,
1467            &builder.cxx(target).unwrap(),
1468            target,
1469            CLang::Cxx,
1470            libstdcxx_name,
1471        );
1472        cargo.env("LLVM_STATIC_STDCPP", file);
1473    }
1474    if builder.llvm_link_shared() {
1475        cargo.env("LLVM_LINK_SHARED", "1");
1476    }
1477    if builder.config.llvm_use_libcxx {
1478        cargo.env("LLVM_USE_LIBCXX", "1");
1479    }
1480    if builder.config.llvm_assertions {
1481        cargo.env("LLVM_ASSERTIONS", "1");
1482    }
1483}
1484
1485/// `RustcLink` copies all of the rlibs from the rustc build into the previous stage's sysroot.
1486/// This is necessary for tools using `rustc_private`, where the previous compiler will build
1487/// a tool against the next compiler.
1488/// To build a tool against a compiler, the rlibs of that compiler that it links against
1489/// must be in the sysroot of the compiler that's doing the compiling.
1490#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1491struct RustcLink {
1492    /// The compiler whose rlibs we are copying around.
1493    pub compiler: Compiler,
1494    /// This is the compiler into whose sysroot we want to copy the rlibs into.
1495    pub previous_stage_compiler: Compiler,
1496    pub target: TargetSelection,
1497    /// Not actually used; only present to make sure the cache invalidation is correct.
1498    crates: Vec<String>,
1499}
1500
1501impl RustcLink {
1502    fn from_rustc(rustc: Rustc, host_compiler: Compiler) -> Self {
1503        Self {
1504            compiler: host_compiler,
1505            previous_stage_compiler: rustc.build_compiler,
1506            target: rustc.target,
1507            crates: rustc.crates,
1508        }
1509    }
1510}
1511
1512impl Step for RustcLink {
1513    type Output = ();
1514
1515    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1516        run.never()
1517    }
1518
1519    /// Same as `std_link`, only for librustc
1520    #[cfg_attr(
1521        feature = "tracing",
1522        instrument(
1523            level = "trace",
1524            name = "RustcLink::run",
1525            skip_all,
1526            fields(
1527                compiler = ?self.compiler,
1528                previous_stage_compiler = ?self.previous_stage_compiler,
1529                target = ?self.target,
1530            ),
1531        ),
1532    )]
1533    fn run(self, builder: &Builder<'_>) {
1534        let compiler = self.compiler;
1535        let previous_stage_compiler = self.previous_stage_compiler;
1536        let target = self.target;
1537        add_to_sysroot(
1538            builder,
1539            &builder.sysroot_target_libdir(previous_stage_compiler, target),
1540            &builder.sysroot_target_libdir(previous_stage_compiler, compiler.host),
1541            &build_stamp::librustc_stamp(builder, compiler, target),
1542        );
1543    }
1544}
1545
1546/// Output of the `compile::GccCodegenBackend` step.
1547/// It includes the path to the libgccjit library on which this backend depends.
1548#[derive(Clone)]
1549pub struct GccCodegenBackendOutput {
1550    stamp: BuildStamp,
1551    gcc: GccOutput,
1552}
1553
1554#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1555pub struct GccCodegenBackend {
1556    compilers: RustcPrivateCompilers,
1557}
1558
1559impl Step for GccCodegenBackend {
1560    type Output = GccCodegenBackendOutput;
1561
1562    const ONLY_HOSTS: bool = true;
1563
1564    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1565        run.alias("rustc_codegen_gcc").alias("cg_gcc")
1566    }
1567
1568    fn make_run(run: RunConfig<'_>) {
1569        run.builder.ensure(GccCodegenBackend {
1570            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1571        });
1572    }
1573
1574    #[cfg_attr(
1575        feature = "tracing",
1576        instrument(
1577            level = "debug",
1578            name = "GccCodegenBackend::run",
1579            skip_all,
1580            fields(
1581                compilers = ?self.compilers,
1582            ),
1583        ),
1584    )]
1585    fn run(self, builder: &Builder<'_>) -> Self::Output {
1586        let target = self.compilers.target();
1587        let build_compiler = self.compilers.build_compiler();
1588
1589        let stamp = build_stamp::codegen_backend_stamp(
1590            builder,
1591            build_compiler,
1592            target,
1593            &CodegenBackendKind::Gcc,
1594        );
1595
1596        let gcc = builder.ensure(Gcc { target });
1597
1598        if builder.config.keep_stage.contains(&build_compiler.stage) {
1599            trace!("`keep-stage` requested");
1600            builder.info(
1601                "WARNING: Using a potentially old codegen backend. \
1602                This may not behave well.",
1603            );
1604            // Codegen backends are linked separately from this step today, so we don't do
1605            // anything here.
1606            return GccCodegenBackendOutput { stamp, gcc };
1607        }
1608
1609        let mut cargo = builder::Cargo::new(
1610            builder,
1611            build_compiler,
1612            Mode::Codegen,
1613            SourceType::InTree,
1614            target,
1615            Kind::Build,
1616        );
1617        cargo.arg("--manifest-path").arg(builder.src.join("compiler/rustc_codegen_gcc/Cargo.toml"));
1618        rustc_cargo_env(builder, &mut cargo, target);
1619
1620        add_cg_gcc_cargo_flags(&mut cargo, &gcc);
1621
1622        let _guard =
1623            builder.msg(Kind::Build, "codegen backend gcc", Mode::Codegen, build_compiler, target);
1624        let files = run_cargo(builder, cargo, vec![], &stamp, vec![], false, false);
1625
1626        GccCodegenBackendOutput {
1627            stamp: write_codegen_backend_stamp(stamp, files, builder.config.dry_run()),
1628            gcc,
1629        }
1630    }
1631
1632    fn metadata(&self) -> Option<StepMetadata> {
1633        Some(
1634            StepMetadata::build("rustc_codegen_gcc", self.compilers.target())
1635                .built_by(self.compilers.build_compiler()),
1636        )
1637    }
1638}
1639
1640#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1641pub struct CraneliftCodegenBackend {
1642    pub compilers: RustcPrivateCompilers,
1643}
1644
1645impl Step for CraneliftCodegenBackend {
1646    type Output = BuildStamp;
1647    const ONLY_HOSTS: bool = true;
1648
1649    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1650        run.alias("rustc_codegen_cranelift").alias("cg_clif")
1651    }
1652
1653    fn make_run(run: RunConfig<'_>) {
1654        run.builder.ensure(CraneliftCodegenBackend {
1655            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1656        });
1657    }
1658
1659    #[cfg_attr(
1660        feature = "tracing",
1661        instrument(
1662            level = "debug",
1663            name = "CraneliftCodegenBackend::run",
1664            skip_all,
1665            fields(
1666                compilers = ?self.compilers,
1667            ),
1668        ),
1669    )]
1670    fn run(self, builder: &Builder<'_>) -> Self::Output {
1671        let target = self.compilers.target();
1672        let build_compiler = self.compilers.build_compiler();
1673
1674        let stamp = build_stamp::codegen_backend_stamp(
1675            builder,
1676            build_compiler,
1677            target,
1678            &CodegenBackendKind::Cranelift,
1679        );
1680
1681        if builder.config.keep_stage.contains(&build_compiler.stage) {
1682            trace!("`keep-stage` requested");
1683            builder.info(
1684                "WARNING: Using a potentially old codegen backend. \
1685                This may not behave well.",
1686            );
1687            // Codegen backends are linked separately from this step today, so we don't do
1688            // anything here.
1689            return stamp;
1690        }
1691
1692        let mut cargo = builder::Cargo::new(
1693            builder,
1694            build_compiler,
1695            Mode::Codegen,
1696            SourceType::InTree,
1697            target,
1698            Kind::Build,
1699        );
1700        cargo
1701            .arg("--manifest-path")
1702            .arg(builder.src.join("compiler/rustc_codegen_cranelift/Cargo.toml"));
1703        rustc_cargo_env(builder, &mut cargo, target);
1704
1705        let _guard = builder.msg(
1706            Kind::Build,
1707            "codegen backend cranelift",
1708            Mode::Codegen,
1709            build_compiler,
1710            target,
1711        );
1712        let files = run_cargo(builder, cargo, vec![], &stamp, vec![], false, false);
1713        write_codegen_backend_stamp(stamp, files, builder.config.dry_run())
1714    }
1715
1716    fn metadata(&self) -> Option<StepMetadata> {
1717        Some(
1718            StepMetadata::build("rustc_codegen_cranelift", self.compilers.target())
1719                .built_by(self.compilers.build_compiler()),
1720        )
1721    }
1722}
1723
1724/// Write filtered `files` into the passed build stamp and returns it.
1725fn write_codegen_backend_stamp(
1726    mut stamp: BuildStamp,
1727    files: Vec<PathBuf>,
1728    dry_run: bool,
1729) -> BuildStamp {
1730    if dry_run {
1731        return stamp;
1732    }
1733
1734    let mut files = files.into_iter().filter(|f| {
1735        let filename = f.file_name().unwrap().to_str().unwrap();
1736        is_dylib(f) && filename.contains("rustc_codegen_")
1737    });
1738    let codegen_backend = match files.next() {
1739        Some(f) => f,
1740        None => panic!("no dylibs built for codegen backend?"),
1741    };
1742    if let Some(f) = files.next() {
1743        panic!("codegen backend built two dylibs:\n{}\n{}", codegen_backend.display(), f.display());
1744    }
1745
1746    let codegen_backend = codegen_backend.to_str().unwrap();
1747    stamp = stamp.add_stamp(codegen_backend);
1748    t!(stamp.write());
1749    stamp
1750}
1751
1752/// Creates the `codegen-backends` folder for a compiler that's about to be
1753/// assembled as a complete compiler.
1754///
1755/// This will take the codegen artifacts recorded in the given `stamp` and link them
1756/// into an appropriate location for `target_compiler` to be a functional
1757/// compiler.
1758fn copy_codegen_backends_to_sysroot(
1759    builder: &Builder<'_>,
1760    stamp: BuildStamp,
1761    target_compiler: Compiler,
1762) {
1763    // Note that this step is different than all the other `*Link` steps in
1764    // that it's not assembling a bunch of libraries but rather is primarily
1765    // moving the codegen backend into place. The codegen backend of rustc is
1766    // not linked into the main compiler by default but is rather dynamically
1767    // selected at runtime for inclusion.
1768    //
1769    // Here we're looking for the output dylib of the `CodegenBackend` step and
1770    // we're copying that into the `codegen-backends` folder.
1771    let dst = builder.sysroot_codegen_backends(target_compiler);
1772    t!(fs::create_dir_all(&dst), dst);
1773
1774    if builder.config.dry_run() {
1775        return;
1776    }
1777
1778    if stamp.path().exists() {
1779        let file = get_codegen_backend_file(&stamp);
1780        builder.copy_link(
1781            &file,
1782            &dst.join(normalize_codegen_backend_name(builder, &file)),
1783            FileType::NativeLibrary,
1784        );
1785    }
1786}
1787
1788/// Gets the path to a dynamic codegen backend library from its build stamp.
1789pub fn get_codegen_backend_file(stamp: &BuildStamp) -> PathBuf {
1790    PathBuf::from(t!(fs::read_to_string(stamp.path())))
1791}
1792
1793/// Normalize the name of a dynamic codegen backend library.
1794pub fn normalize_codegen_backend_name(builder: &Builder<'_>, path: &Path) -> String {
1795    let filename = path.file_name().unwrap().to_str().unwrap();
1796    // change e.g. `librustc_codegen_cranelift-xxxxxx.so` to
1797    // `librustc_codegen_cranelift-release.so`
1798    let dash = filename.find('-').unwrap();
1799    let dot = filename.find('.').unwrap();
1800    format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1801}
1802
1803pub fn compiler_file(
1804    builder: &Builder<'_>,
1805    compiler: &Path,
1806    target: TargetSelection,
1807    c: CLang,
1808    file: &str,
1809) -> PathBuf {
1810    if builder.config.dry_run() {
1811        return PathBuf::new();
1812    }
1813    let mut cmd = command(compiler);
1814    cmd.args(builder.cc_handled_clags(target, c));
1815    cmd.args(builder.cc_unhandled_cflags(target, GitRepo::Rustc, c));
1816    cmd.arg(format!("-print-file-name={file}"));
1817    let out = cmd.run_capture_stdout(builder).stdout();
1818    PathBuf::from(out.trim())
1819}
1820
1821#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1822pub struct Sysroot {
1823    pub compiler: Compiler,
1824    /// See [`Std::force_recompile`].
1825    force_recompile: bool,
1826}
1827
1828impl Sysroot {
1829    pub(crate) fn new(compiler: Compiler) -> Self {
1830        Sysroot { compiler, force_recompile: false }
1831    }
1832}
1833
1834impl Step for Sysroot {
1835    type Output = PathBuf;
1836
1837    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1838        run.never()
1839    }
1840
1841    /// Returns the sysroot that `compiler` is supposed to use.
1842    /// For the stage0 compiler, this is stage0-sysroot (because of the initial std build).
1843    /// For all other stages, it's the same stage directory that the compiler lives in.
1844    #[cfg_attr(
1845        feature = "tracing",
1846        instrument(
1847            level = "debug",
1848            name = "Sysroot::run",
1849            skip_all,
1850            fields(compiler = ?self.compiler),
1851        ),
1852    )]
1853    fn run(self, builder: &Builder<'_>) -> PathBuf {
1854        let compiler = self.compiler;
1855        let host_dir = builder.out.join(compiler.host);
1856
1857        let sysroot_dir = |stage| {
1858            if stage == 0 {
1859                host_dir.join("stage0-sysroot")
1860            } else if self.force_recompile && stage == compiler.stage {
1861                host_dir.join(format!("stage{stage}-test-sysroot"))
1862            } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1863                host_dir.join("ci-rustc-sysroot")
1864            } else {
1865                host_dir.join(format!("stage{stage}"))
1866            }
1867        };
1868        let sysroot = sysroot_dir(compiler.stage);
1869        trace!(stage = ?compiler.stage, ?sysroot);
1870
1871        builder
1872            .verbose(|| println!("Removing sysroot {} to avoid caching bugs", sysroot.display()));
1873        let _ = fs::remove_dir_all(&sysroot);
1874        t!(fs::create_dir_all(&sysroot));
1875
1876        // In some cases(see https://github.com/rust-lang/rust/issues/109314), when the stage0
1877        // compiler relies on more recent version of LLVM than the stage0 compiler, it may not
1878        // be able to locate the correct LLVM in the sysroot. This situation typically occurs
1879        // when we upgrade LLVM version while the stage0 compiler continues to use an older version.
1880        //
1881        // Make sure to add the correct version of LLVM into the stage0 sysroot.
1882        if compiler.stage == 0 {
1883            dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1884        }
1885
1886        // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0.
1887        if builder.download_rustc() && compiler.stage != 0 {
1888            assert_eq!(
1889                builder.config.host_target, compiler.host,
1890                "Cross-compiling is not yet supported with `download-rustc`",
1891            );
1892
1893            // #102002, cleanup old toolchain folders when using download-rustc so people don't use them by accident.
1894            for stage in 0..=2 {
1895                if stage != compiler.stage {
1896                    let dir = sysroot_dir(stage);
1897                    if !dir.ends_with("ci-rustc-sysroot") {
1898                        let _ = fs::remove_dir_all(dir);
1899                    }
1900                }
1901            }
1902
1903            // Copy the compiler into the correct sysroot.
1904            // NOTE(#108767): We intentionally don't copy `rustc-dev` artifacts until they're requested with `builder.ensure(Rustc)`.
1905            // This fixes an issue where we'd have multiple copies of libc in the sysroot with no way to tell which to load.
1906            // There are a few quirks of bootstrap that interact to make this reliable:
1907            // 1. The order `Step`s are run is hard-coded in `builder.rs` and not configurable. This
1908            //    avoids e.g. reordering `test::UiFulldeps` before `test::Ui` and causing the latter to
1909            //    fail because of duplicate metadata.
1910            // 2. The sysroot is deleted and recreated between each invocation, so running `x test
1911            //    ui-fulldeps && x test ui` can't cause failures.
1912            let mut filtered_files = Vec::new();
1913            let mut add_filtered_files = |suffix, contents| {
1914                for path in contents {
1915                    let path = Path::new(&path);
1916                    if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
1917                        filtered_files.push(path.file_name().unwrap().to_owned());
1918                    }
1919                }
1920            };
1921            let suffix = format!("lib/rustlib/{}/lib", compiler.host);
1922            add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
1923            // NOTE: we can't copy std eagerly because `stage2-test-sysroot` needs to have only the
1924            // newly compiled std, not the downloaded std.
1925            add_filtered_files("lib", builder.config.ci_rust_std_contents());
1926
1927            let filtered_extensions = [
1928                OsStr::new("rmeta"),
1929                OsStr::new("rlib"),
1930                // FIXME: this is wrong when compiler.host != build, but we don't support that today
1931                OsStr::new(std::env::consts::DLL_EXTENSION),
1932            ];
1933            let ci_rustc_dir = builder.config.ci_rustc_dir();
1934            builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
1935                if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
1936                    return true;
1937                }
1938                if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
1939                    return true;
1940                }
1941                if !filtered_files.iter().all(|f| f != path.file_name().unwrap()) {
1942                    builder.verbose_than(1, || println!("ignoring {}", path.display()));
1943                    false
1944                } else {
1945                    true
1946                }
1947            });
1948        }
1949
1950        // Symlink the source root into the same location inside the sysroot,
1951        // where `rust-src` component would go (`$sysroot/lib/rustlib/src/rust`),
1952        // so that any tools relying on `rust-src` also work for local builds,
1953        // and also for translating the virtual `/rustc/$hash` back to the real
1954        // directory (for running tests with `rust.remap-debuginfo = true`).
1955        if compiler.stage != 0 {
1956            let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
1957            t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
1958            let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
1959            if let Err(e) =
1960                symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust)
1961            {
1962                eprintln!(
1963                    "ERROR: creating symbolic link `{}` to `{}` failed with {}",
1964                    sysroot_lib_rustlib_src_rust.display(),
1965                    builder.src.display(),
1966                    e,
1967                );
1968                if builder.config.rust_remap_debuginfo {
1969                    eprintln!(
1970                        "ERROR: some `tests/ui` tests will fail when lacking `{}`",
1971                        sysroot_lib_rustlib_src_rust.display(),
1972                    );
1973                }
1974                build_helper::exit!(1);
1975            }
1976        }
1977
1978        // rustc-src component is already part of CI rustc's sysroot
1979        if !builder.download_rustc() {
1980            let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
1981            t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
1982            let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
1983            if let Err(e) =
1984                symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
1985            {
1986                eprintln!(
1987                    "ERROR: creating symbolic link `{}` to `{}` failed with {}",
1988                    sysroot_lib_rustlib_rustcsrc_rust.display(),
1989                    builder.src.display(),
1990                    e,
1991                );
1992                build_helper::exit!(1);
1993            }
1994        }
1995
1996        sysroot
1997    }
1998}
1999
2000#[derive(Debug, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
2001pub struct Assemble {
2002    /// The compiler which we will produce in this step. Assemble itself will
2003    /// take care of ensuring that the necessary prerequisites to do so exist,
2004    /// that is, this target can be a stage2 compiler and Assemble will build
2005    /// previous stages for you.
2006    pub target_compiler: Compiler,
2007}
2008
2009impl Step for Assemble {
2010    type Output = Compiler;
2011    const ONLY_HOSTS: bool = true;
2012
2013    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2014        run.path("compiler/rustc").path("compiler")
2015    }
2016
2017    fn make_run(run: RunConfig<'_>) {
2018        run.builder.ensure(Assemble {
2019            target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2020        });
2021    }
2022
2023    /// Prepare a new compiler from the artifacts in `stage`
2024    ///
2025    /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
2026    /// must have been previously produced by the `stage - 1` builder.build
2027    /// compiler.
2028    #[cfg_attr(
2029        feature = "tracing",
2030        instrument(
2031            level = "debug",
2032            name = "Assemble::run",
2033            skip_all,
2034            fields(target_compiler = ?self.target_compiler),
2035        ),
2036    )]
2037    fn run(self, builder: &Builder<'_>) -> Compiler {
2038        let target_compiler = self.target_compiler;
2039
2040        if target_compiler.stage == 0 {
2041            trace!("stage 0 build compiler is always available, simply returning");
2042            assert_eq!(
2043                builder.config.host_target, target_compiler.host,
2044                "Cannot obtain compiler for non-native build triple at stage 0"
2045            );
2046            // The stage 0 compiler for the build triple is always pre-built.
2047            return target_compiler;
2048        }
2049
2050        // We prepend this bin directory to the user PATH when linking Rust binaries. To
2051        // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
2052        let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2053        let libdir_bin = libdir.parent().unwrap().join("bin");
2054        t!(fs::create_dir_all(&libdir_bin));
2055
2056        if builder.config.llvm_enabled(target_compiler.host) {
2057            trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
2058
2059            let llvm::LlvmResult { llvm_config, .. } =
2060                builder.ensure(llvm::Llvm { target: target_compiler.host });
2061            if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
2062                trace!("LLVM tools enabled");
2063
2064                let llvm_bin_dir =
2065                    command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
2066                let llvm_bin_dir = Path::new(llvm_bin_dir.trim());
2067
2068                // Since we've already built the LLVM tools, install them to the sysroot.
2069                // This is the equivalent of installing the `llvm-tools-preview` component via
2070                // rustup, and lets developers use a locally built toolchain to
2071                // build projects that expect llvm tools to be present in the sysroot
2072                // (e.g. the `bootimage` crate).
2073
2074                #[cfg(feature = "tracing")]
2075                let _llvm_tools_span =
2076                    span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
2077                        .entered();
2078                for tool in LLVM_TOOLS {
2079                    trace!("installing `{tool}`");
2080                    let tool_exe = exe(tool, target_compiler.host);
2081                    let src_path = llvm_bin_dir.join(&tool_exe);
2082
2083                    // When using `download-ci-llvm`, some of the tools may not exist, so skip trying to copy them.
2084                    if !src_path.exists() && builder.config.llvm_from_ci {
2085                        eprintln!("{} does not exist; skipping copy", src_path.display());
2086                        continue;
2087                    }
2088
2089                    // There is a chance that these tools are being installed from an external LLVM.
2090                    // Use `Builder::resolve_symlink_and_copy` instead of `Builder::copy_link` to ensure
2091                    // we are copying the original file not the symlinked path, which causes issues for
2092                    // tarball distribution.
2093                    //
2094                    // See https://github.com/rust-lang/rust/issues/135554.
2095                    builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
2096                }
2097            }
2098        }
2099
2100        let maybe_install_llvm_bitcode_linker = || {
2101            if builder.config.llvm_bitcode_linker_enabled {
2102                trace!("llvm-bitcode-linker enabled, installing");
2103                let llvm_bitcode_linker = builder.ensure(
2104                    crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler(
2105                        builder,
2106                        target_compiler,
2107                    ),
2108                );
2109
2110                // Copy the llvm-bitcode-linker to the self-contained binary directory
2111                let bindir_self_contained = builder
2112                    .sysroot(target_compiler)
2113                    .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host));
2114                let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2115
2116                t!(fs::create_dir_all(&bindir_self_contained));
2117                builder.copy_link(
2118                    &llvm_bitcode_linker.tool_path,
2119                    &bindir_self_contained.join(tool_exe),
2120                    FileType::Executable,
2121                );
2122            }
2123        };
2124
2125        // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0.
2126        if builder.download_rustc() {
2127            trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2128
2129            builder.std(target_compiler, target_compiler.host);
2130            let sysroot =
2131                builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2132            // Ensure that `libLLVM.so` ends up in the newly created target directory,
2133            // so that tools using `rustc_private` can use it.
2134            dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2135            // Lower stages use `ci-rustc-sysroot`, not stageN
2136            if target_compiler.stage == builder.top_stage {
2137                builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage));
2138            }
2139
2140            // FIXME: this is incomplete, we do not copy a bunch of other stuff to the downloaded
2141            // sysroot...
2142            maybe_install_llvm_bitcode_linker();
2143
2144            return target_compiler;
2145        }
2146
2147        // Get the compiler that we'll use to bootstrap ourselves.
2148        //
2149        // Note that this is where the recursive nature of the bootstrap
2150        // happens, as this will request the previous stage's compiler on
2151        // downwards to stage 0.
2152        //
2153        // Also note that we're building a compiler for the host platform. We
2154        // only assume that we can run `build` artifacts, which means that to
2155        // produce some other architecture compiler we need to start from
2156        // `build` to get there.
2157        //
2158        // FIXME: It may be faster if we build just a stage 1 compiler and then
2159        //        use that to bootstrap this compiler forward.
2160        debug!(
2161            "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2162            target_compiler.stage - 1,
2163            builder.config.host_target,
2164        );
2165        let mut build_compiler =
2166            builder.compiler(target_compiler.stage - 1, builder.config.host_target);
2167
2168        // Build enzyme
2169        if builder.config.llvm_enzyme && !builder.config.dry_run() {
2170            debug!("`llvm_enzyme` requested");
2171            let enzyme_install = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2172            if let Some(llvm_config) = builder.llvm_config(builder.config.host_target) {
2173                let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
2174                let lib_ext = std::env::consts::DLL_EXTENSION;
2175                let libenzyme = format!("libEnzyme-{llvm_version_major}");
2176                let src_lib =
2177                    enzyme_install.join("build/Enzyme").join(&libenzyme).with_extension(lib_ext);
2178                let libdir = builder.sysroot_target_libdir(build_compiler, build_compiler.host);
2179                let target_libdir =
2180                    builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2181                let dst_lib = libdir.join(&libenzyme).with_extension(lib_ext);
2182                let target_dst_lib = target_libdir.join(&libenzyme).with_extension(lib_ext);
2183                builder.copy_link(&src_lib, &dst_lib, FileType::NativeLibrary);
2184                builder.copy_link(&src_lib, &target_dst_lib, FileType::NativeLibrary);
2185            }
2186        }
2187
2188        // Build the libraries for this compiler to link to (i.e., the libraries
2189        // it uses at runtime). NOTE: Crates the target compiler compiles don't
2190        // link to these. (FIXME: Is that correct? It seems to be correct most
2191        // of the time but I think we do link to these for stage2/bin compilers
2192        // when not performing a full bootstrap).
2193        debug!(
2194            ?build_compiler,
2195            "target_compiler.host" = ?target_compiler.host,
2196            "building compiler libraries to link to"
2197        );
2198        let actual_stage = builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2199        // Current build_compiler.stage might be uplifted instead of being built; so update it
2200        // to not fail while linking the artifacts.
2201        debug!(
2202            "(old) build_compiler.stage" = build_compiler.stage,
2203            "(adjusted) build_compiler.stage" = actual_stage,
2204            "temporarily adjusting `build_compiler.stage` to account for uplifted libraries"
2205        );
2206        build_compiler.stage = actual_stage;
2207
2208        let stage = target_compiler.stage;
2209        let host = target_compiler.host;
2210        let (host_info, dir_name) = if build_compiler.host == host {
2211            ("".into(), "host".into())
2212        } else {
2213            (format!(" ({host})"), host.to_string())
2214        };
2215        // NOTE: "Creating a sysroot" is somewhat inconsistent with our internal terminology, since
2216        // sysroots can temporarily be empty until we put the compiler inside. However,
2217        // `ensure(Sysroot)` isn't really something that's user facing, so there shouldn't be any
2218        // ambiguity.
2219        let msg = format!(
2220            "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2221        );
2222        builder.info(&msg);
2223
2224        // Link in all dylibs to the libdir
2225        let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2226        let proc_macros = builder
2227            .read_stamp_file(&stamp)
2228            .into_iter()
2229            .filter_map(|(path, dependency_type)| {
2230                if dependency_type == DependencyType::Host {
2231                    Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2232                } else {
2233                    None
2234                }
2235            })
2236            .collect::<HashSet<_>>();
2237
2238        let sysroot = builder.sysroot(target_compiler);
2239        let rustc_libdir = builder.rustc_libdir(target_compiler);
2240        t!(fs::create_dir_all(&rustc_libdir));
2241        let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2242        for f in builder.read_dir(&src_libdir) {
2243            let filename = f.file_name().into_string().unwrap();
2244
2245            let is_proc_macro = proc_macros.contains(&filename);
2246            let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2247
2248            // If we link statically to stdlib, do not copy the libstd dynamic library file
2249            // FIXME: Also do this for Windows once incremental post-optimization stage0 tests
2250            // work without std.dll (see https://github.com/rust-lang/rust/pull/131188).
2251            let can_be_rustc_dynamic_dep = if builder
2252                .link_std_into_rustc_driver(target_compiler.host)
2253                && !target_compiler.host.is_windows()
2254            {
2255                let is_std = filename.starts_with("std-") || filename.starts_with("libstd-");
2256                !is_std
2257            } else {
2258                true
2259            };
2260
2261            if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2262                builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2263            }
2264        }
2265
2266        {
2267            #[cfg(feature = "tracing")]
2268            let _codegen_backend_span =
2269                span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2270
2271            for backend in builder.config.enabled_codegen_backends(target_compiler.host) {
2272                // FIXME: this is a horrible hack used to make `x check` work when other codegen
2273                // backends are enabled.
2274                // `x check` will check stage 1 rustc, which copies its rmetas to the stage0 sysroot.
2275                // Then it checks codegen backends, which correctly use these rmetas.
2276                // Then it needs to check std, but for that it needs to build stage 1 rustc.
2277                // This copies the build rmetas into the stage0 sysroot, effectively poisoning it,
2278                // because we then have both check and build rmetas in the same sysroot.
2279                // That would be fine on its own. However, when another codegen backend is enabled,
2280                // then building stage 1 rustc implies also building stage 1 codegen backend (even if
2281                // it isn't used for anything). And since that tries to use the poisoned
2282                // rmetas, it fails to build.
2283                // We don't actually need to build rustc-private codegen backends for checking std,
2284                // so instead we skip that.
2285                // Note: this would be also an issue for other rustc-private tools, but that is "solved"
2286                // by check::Std being last in the list of checked things (see
2287                // `Builder::get_step_descriptions`).
2288                if builder.kind == Kind::Check && builder.top_stage == 1 {
2289                    continue;
2290                }
2291
2292                let prepare_compilers = || {
2293                    RustcPrivateCompilers::from_build_and_target_compiler(
2294                        build_compiler,
2295                        target_compiler,
2296                    )
2297                };
2298
2299                match backend {
2300                    CodegenBackendKind::Cranelift => {
2301                        let stamp = builder
2302                            .ensure(CraneliftCodegenBackend { compilers: prepare_compilers() });
2303                        copy_codegen_backends_to_sysroot(builder, stamp, target_compiler);
2304                    }
2305                    CodegenBackendKind::Gcc => {
2306                        let output =
2307                            builder.ensure(GccCodegenBackend { compilers: prepare_compilers() });
2308                        copy_codegen_backends_to_sysroot(builder, output.stamp, target_compiler);
2309                        // Also copy libgccjit to the library sysroot, so that it is available for
2310                        // the codegen backend.
2311                        output.gcc.install_to(builder, &rustc_libdir);
2312                    }
2313                    CodegenBackendKind::Llvm | CodegenBackendKind::Custom(_) => continue,
2314                }
2315            }
2316        }
2317
2318        if builder.config.lld_enabled {
2319            let lld_wrapper =
2320                builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler(
2321                    builder,
2322                    target_compiler,
2323                ));
2324            copy_lld_artifacts(builder, lld_wrapper, target_compiler);
2325        }
2326
2327        if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2328            debug!(
2329                "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2330                workaround faulty homebrew `strip`s"
2331            );
2332
2333            // `llvm-strip` is used by rustc, which is actually just a symlink to `llvm-objcopy`, so
2334            // copy and rename `llvm-objcopy`.
2335            //
2336            // But only do so if llvm-tools are enabled, as bootstrap compiler might not contain any
2337            // LLVM tools, e.g. for cg_clif.
2338            // See <https://github.com/rust-lang/rust/issues/132719>.
2339            let src_exe = exe("llvm-objcopy", target_compiler.host);
2340            let dst_exe = exe("rust-objcopy", target_compiler.host);
2341            builder.copy_link(
2342                &libdir_bin.join(src_exe),
2343                &libdir_bin.join(dst_exe),
2344                FileType::Executable,
2345            );
2346        }
2347
2348        // In addition to `rust-lld` also install `wasm-component-ld` when
2349        // is enabled. This is used by the `wasm32-wasip2` target of Rust.
2350        if builder.tool_enabled("wasm-component-ld") {
2351            let wasm_component = builder.ensure(
2352                crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler(
2353                    builder,
2354                    target_compiler,
2355                ),
2356            );
2357            builder.copy_link(
2358                &wasm_component.tool_path,
2359                &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2360                FileType::Executable,
2361            );
2362        }
2363
2364        maybe_install_llvm_bitcode_linker();
2365
2366        // Ensure that `libLLVM.so` ends up in the newly build compiler directory,
2367        // so that it can be found when the newly built `rustc` is run.
2368        debug!(
2369            "target_compiler.host" = ?target_compiler.host,
2370            ?sysroot,
2371            "ensuring availability of `libLLVM.so` in compiler directory"
2372        );
2373        dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2374        dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2375
2376        // Link the compiler binary itself into place
2377        let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2378        let rustc = out_dir.join(exe("rustc-main", host));
2379        let bindir = sysroot.join("bin");
2380        t!(fs::create_dir_all(bindir));
2381        let compiler = builder.rustc(target_compiler);
2382        debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2383        builder.copy_link(&rustc, &compiler, FileType::Executable);
2384
2385        target_compiler
2386    }
2387}
2388
2389/// Link some files into a rustc sysroot.
2390///
2391/// For a particular stage this will link the file listed in `stamp` into the
2392/// `sysroot_dst` provided.
2393pub fn add_to_sysroot(
2394    builder: &Builder<'_>,
2395    sysroot_dst: &Path,
2396    sysroot_host_dst: &Path,
2397    stamp: &BuildStamp,
2398) {
2399    let self_contained_dst = &sysroot_dst.join("self-contained");
2400    t!(fs::create_dir_all(sysroot_dst));
2401    t!(fs::create_dir_all(sysroot_host_dst));
2402    t!(fs::create_dir_all(self_contained_dst));
2403    for (path, dependency_type) in builder.read_stamp_file(stamp) {
2404        let dst = match dependency_type {
2405            DependencyType::Host => sysroot_host_dst,
2406            DependencyType::Target => sysroot_dst,
2407            DependencyType::TargetSelfContained => self_contained_dst,
2408        };
2409        builder.copy_link(&path, &dst.join(path.file_name().unwrap()), FileType::Regular);
2410    }
2411}
2412
2413pub fn run_cargo(
2414    builder: &Builder<'_>,
2415    cargo: Cargo,
2416    tail_args: Vec<String>,
2417    stamp: &BuildStamp,
2418    additional_target_deps: Vec<(PathBuf, DependencyType)>,
2419    is_check: bool,
2420    rlib_only_metadata: bool,
2421) -> Vec<PathBuf> {
2422    // `target_root_dir` looks like $dir/$target/release
2423    let target_root_dir = stamp.path().parent().unwrap();
2424    // `target_deps_dir` looks like $dir/$target/release/deps
2425    let target_deps_dir = target_root_dir.join("deps");
2426    // `host_root_dir` looks like $dir/release
2427    let host_root_dir = target_root_dir
2428        .parent()
2429        .unwrap() // chop off `release`
2430        .parent()
2431        .unwrap() // chop off `$target`
2432        .join(target_root_dir.file_name().unwrap());
2433
2434    // Spawn Cargo slurping up its JSON output. We'll start building up the
2435    // `deps` array of all files it generated along with a `toplevel` array of
2436    // files we need to probe for later.
2437    let mut deps = Vec::new();
2438    let mut toplevel = Vec::new();
2439    let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2440        let (filenames_vec, crate_types) = match msg {
2441            CargoMessage::CompilerArtifact {
2442                filenames,
2443                target: CargoTarget { crate_types },
2444                ..
2445            } => {
2446                let mut f: Vec<String> = filenames.into_iter().map(|s| s.into_owned()).collect();
2447                f.sort(); // Sort the filenames
2448                (f, crate_types)
2449            }
2450            _ => return,
2451        };
2452        for filename in filenames_vec {
2453            // Skip files like executables
2454            let mut keep = false;
2455            if filename.ends_with(".lib")
2456                || filename.ends_with(".a")
2457                || is_debug_info(&filename)
2458                || is_dylib(Path::new(&*filename))
2459            {
2460                // Always keep native libraries, rust dylibs and debuginfo
2461                keep = true;
2462            }
2463            if is_check && filename.ends_with(".rmeta") {
2464                // During check builds we need to keep crate metadata
2465                keep = true;
2466            } else if rlib_only_metadata {
2467                if filename.contains("jemalloc_sys")
2468                    || filename.contains("rustc_public_bridge")
2469                    || filename.contains("rustc_public")
2470                {
2471                    // jemalloc_sys and rustc_public_bridge are not linked into librustc_driver.so,
2472                    // so we need to distribute them as rlib to be able to use them.
2473                    keep |= filename.ends_with(".rlib");
2474                } else {
2475                    // Distribute the rest of the rustc crates as rmeta files only to reduce
2476                    // the tarball sizes by about 50%. The object files are linked into
2477                    // librustc_driver.so, so it is still possible to link against them.
2478                    keep |= filename.ends_with(".rmeta");
2479                }
2480            } else {
2481                // In all other cases keep all rlibs
2482                keep |= filename.ends_with(".rlib");
2483            }
2484
2485            if !keep {
2486                continue;
2487            }
2488
2489            let filename = Path::new(&*filename);
2490
2491            // If this was an output file in the "host dir" we don't actually
2492            // worry about it, it's not relevant for us
2493            if filename.starts_with(&host_root_dir) {
2494                // Unless it's a proc macro used in the compiler
2495                if crate_types.iter().any(|t| t == "proc-macro") {
2496                    deps.push((filename.to_path_buf(), DependencyType::Host));
2497                }
2498                continue;
2499            }
2500
2501            // If this was output in the `deps` dir then this is a precise file
2502            // name (hash included) so we start tracking it.
2503            if filename.starts_with(&target_deps_dir) {
2504                deps.push((filename.to_path_buf(), DependencyType::Target));
2505                continue;
2506            }
2507
2508            // Otherwise this was a "top level artifact" which right now doesn't
2509            // have a hash in the name, but there's a version of this file in
2510            // the `deps` folder which *does* have a hash in the name. That's
2511            // the one we'll want to we'll probe for it later.
2512            //
2513            // We do not use `Path::file_stem` or `Path::extension` here,
2514            // because some generated files may have multiple extensions e.g.
2515            // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
2516            // split the file name by the last extension (`.lib`) while we need
2517            // to split by all extensions (`.dll.lib`).
2518            let expected_len = t!(filename.metadata()).len();
2519            let filename = filename.file_name().unwrap().to_str().unwrap();
2520            let mut parts = filename.splitn(2, '.');
2521            let file_stem = parts.next().unwrap().to_owned();
2522            let extension = parts.next().unwrap().to_owned();
2523
2524            toplevel.push((file_stem, extension, expected_len));
2525        }
2526    });
2527
2528    if !ok {
2529        crate::exit!(1);
2530    }
2531
2532    if builder.config.dry_run() {
2533        return Vec::new();
2534    }
2535
2536    // Ok now we need to actually find all the files listed in `toplevel`. We've
2537    // got a list of prefix/extensions and we basically just need to find the
2538    // most recent file in the `deps` folder corresponding to each one.
2539    let contents = target_deps_dir
2540        .read_dir()
2541        .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_deps_dir.display(), e))
2542        .map(|e| t!(e))
2543        .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2544        .collect::<Vec<_>>();
2545    for (prefix, extension, expected_len) in toplevel {
2546        let candidates = contents.iter().filter(|&(_, filename, meta)| {
2547            meta.len() == expected_len
2548                && filename
2549                    .strip_prefix(&prefix[..])
2550                    .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2551                    .unwrap_or(false)
2552        });
2553        let max = candidates.max_by_key(|&(_, _, metadata)| {
2554            metadata.modified().expect("mtime should be available on all relevant OSes")
2555        });
2556        let path_to_add = match max {
2557            Some(triple) => triple.0.to_str().unwrap(),
2558            None => panic!("no output generated for {prefix:?} {extension:?}"),
2559        };
2560        if is_dylib(Path::new(path_to_add)) {
2561            let candidate = format!("{path_to_add}.lib");
2562            let candidate = PathBuf::from(candidate);
2563            if candidate.exists() {
2564                deps.push((candidate, DependencyType::Target));
2565            }
2566        }
2567        deps.push((path_to_add.into(), DependencyType::Target));
2568    }
2569
2570    deps.extend(additional_target_deps);
2571    deps.sort();
2572    let mut new_contents = Vec::new();
2573    for (dep, dependency_type) in deps.iter() {
2574        new_contents.extend(match *dependency_type {
2575            DependencyType::Host => b"h",
2576            DependencyType::Target => b"t",
2577            DependencyType::TargetSelfContained => b"s",
2578        });
2579        new_contents.extend(dep.to_str().unwrap().as_bytes());
2580        new_contents.extend(b"\0");
2581    }
2582    t!(fs::write(stamp.path(), &new_contents));
2583    deps.into_iter().map(|(d, _)| d).collect()
2584}
2585
2586pub fn stream_cargo(
2587    builder: &Builder<'_>,
2588    cargo: Cargo,
2589    tail_args: Vec<String>,
2590    cb: &mut dyn FnMut(CargoMessage<'_>),
2591) -> bool {
2592    let mut cmd = cargo.into_cmd();
2593
2594    #[cfg(feature = "tracing")]
2595    let _run_span = crate::trace_cmd!(cmd);
2596
2597    // Instruct Cargo to give us json messages on stdout, critically leaving
2598    // stderr as piped so we can get those pretty colors.
2599    let mut message_format = if builder.config.json_output {
2600        String::from("json")
2601    } else {
2602        String::from("json-render-diagnostics")
2603    };
2604    if let Some(s) = &builder.config.rustc_error_format {
2605        message_format.push_str(",json-diagnostic-");
2606        message_format.push_str(s);
2607    }
2608    cmd.arg("--message-format").arg(message_format);
2609
2610    for arg in tail_args {
2611        cmd.arg(arg);
2612    }
2613
2614    builder.verbose(|| println!("running: {cmd:?}"));
2615
2616    let streaming_command = cmd.stream_capture_stdout(&builder.config.exec_ctx);
2617
2618    let Some(mut streaming_command) = streaming_command else {
2619        return true;
2620    };
2621
2622    // Spawn Cargo slurping up its JSON output. We'll start building up the
2623    // `deps` array of all files it generated along with a `toplevel` array of
2624    // files we need to probe for later.
2625    let stdout = BufReader::new(streaming_command.stdout.take().unwrap());
2626    for line in stdout.lines() {
2627        let line = t!(line);
2628        match serde_json::from_str::<CargoMessage<'_>>(&line) {
2629            Ok(msg) => {
2630                if builder.config.json_output {
2631                    // Forward JSON to stdout.
2632                    println!("{line}");
2633                }
2634                cb(msg)
2635            }
2636            // If this was informational, just print it out and continue
2637            Err(_) => println!("{line}"),
2638        }
2639    }
2640
2641    // Make sure Cargo actually succeeded after we read all of its stdout.
2642    let status = t!(streaming_command.wait(&builder.config.exec_ctx));
2643    if builder.is_verbose() && !status.success() {
2644        eprintln!(
2645            "command did not execute successfully: {cmd:?}\n\
2646                  expected success, got: {status}"
2647        );
2648    }
2649
2650    status.success()
2651}
2652
2653#[derive(Deserialize)]
2654pub struct CargoTarget<'a> {
2655    crate_types: Vec<Cow<'a, str>>,
2656}
2657
2658#[derive(Deserialize)]
2659#[serde(tag = "reason", rename_all = "kebab-case")]
2660pub enum CargoMessage<'a> {
2661    CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2662    BuildScriptExecuted,
2663    BuildFinished,
2664}
2665
2666pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2667    // FIXME: to make things simpler for now, limit this to the host and target where we know
2668    // `strip -g` is both available and will fix the issue, i.e. on a x64 linux host that is not
2669    // cross-compiling. Expand this to other appropriate targets in the future.
2670    if target != "x86_64-unknown-linux-gnu"
2671        || !builder.config.is_host_target(target)
2672        || !path.exists()
2673    {
2674        return;
2675    }
2676
2677    let previous_mtime = t!(t!(path.metadata()).modified());
2678    command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2679
2680    let file = t!(fs::File::open(path));
2681
2682    // After running `strip`, we have to set the file modification time to what it was before,
2683    // otherwise we risk Cargo invalidating its fingerprint and rebuilding the world next time
2684    // bootstrap is invoked.
2685    //
2686    // An example of this is if we run this on librustc_driver.so. In the first invocation:
2687    // - Cargo will build librustc_driver.so (mtime of 1)
2688    // - Cargo will build rustc-main (mtime of 2)
2689    // - Bootstrap will strip librustc_driver.so (changing the mtime to 3).
2690    //
2691    // In the second invocation of bootstrap, Cargo will see that the mtime of librustc_driver.so
2692    // is greater than the mtime of rustc-main, and will rebuild rustc-main. That will then cause
2693    // everything else (standard library, future stages...) to be rebuilt.
2694    t!(file.set_modified(previous_mtime));
2695}
2696
2697/// We only use LTO for stage 2+, to speed up build time of intermediate stages.
2698pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2699    build_compiler.stage != 0
2700}