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