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