Skip to main content

bootstrap/core/build_steps/
dist.rs

1//! Implementation of the various distribution aspects of the compiler.
2//!
3//! This module is responsible for creating tarballs of the standard library,
4//! compiler, and documentation. This ends up being what we distribute to
5//! everyone as well.
6//!
7//! No tarball is actually created literally in this file, but rather we shell
8//! out to `rust-installer` still. This may one day be replaced with bits and
9//! pieces of `rustup.rs`!
10
11use std::collections::HashSet;
12use std::ffi::OsStr;
13use std::io::Write;
14use std::path::{Path, PathBuf};
15use std::{env, fs};
16
17use object::BinaryFormat;
18use object::read::archive::ArchiveFile;
19#[cfg(feature = "tracing")]
20use tracing::instrument;
21
22use crate::core::backend::CodegenBackendKind;
23use crate::core::build_steps::compile::{
24    get_codegen_backend_file, libgccjit_path_relative_to_cg_dir, normalize_codegen_backend_name,
25};
26use crate::core::build_steps::doc::{CompilerWithTools, DocumentationFormat};
27use crate::core::build_steps::gcc::GccTargetPair;
28use crate::core::build_steps::llvm::{
29    LLVM_CI_LINK_TYPE_PATH, LlvmBuildStatus, LlvmKind, get_llvm_build_status,
30};
31use crate::core::build_steps::tool::{
32    self, RustcPrivateCompilers, ToolTargetBuildMode, get_tool_target_compiler,
33};
34use crate::core::build_steps::vendor::Vendor;
35use crate::core::build_steps::{compile, llvm};
36use crate::core::builder::{
37    Builder, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
38};
39use crate::core::compiler::Compiler;
40use crate::core::config::{GccCiMode, TargetSelection};
41use crate::core::session::{DependencyType, FileType, Mode};
42use crate::trace;
43use crate::utils::build_stamp::{self, BuildStamp};
44use crate::utils::channel::{self, Info};
45use crate::utils::exec::{BootstrapCommand, command};
46use crate::utils::helpers::{
47    exe, is_dylib, move_file, t, target_supports_cranelift_backend, timeit,
48};
49use crate::utils::tarball::{GeneratedTarball, OverlayKind, Tarball};
50
51pub(crate) const LLVM_TOOLS: &[&str] = &[
52    "llvm-cov",      // used to generate coverage report
53    "llvm-nm",       // used to inspect binaries; it shows symbol names, their sizes and visibility
54    "llvm-objcopy",  // used to transform ELFs into binary format which flashing tools consume
55    "llvm-objdump",  // used to disassemble programs
56    "llvm-profdata", // used to inspect and merge files generated by profiles
57    "llvm-readobj",  // used to get information from ELFs/objects that the other tools don't provide
58    "llvm-size",     // used to prints the size of the linker sections of a program
59    "llvm-strip",    // used to discard symbols from binary files to reduce their size
60    "llvm-ar",       // used for creating and modifying archive files
61    "llvm-as",       // used to convert LLVM assembly to LLVM bitcode
62    "llvm-dis",      // used to disassemble LLVM bitcode
63    "llvm-link",     // used to link LLVM bitcode
64    "llc",           // used to compile LLVM IR
65    "opt",           // used to optimize LLVM IR
66    "llubi",         // used to execute LLVM while checking for Undefined Behavior
67];
68
69/// LLD file names for all flavors.
70pub(crate) const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
71
72pub fn pkgname(builder: &Builder<'_>, component: &str) -> String {
73    format!("{}-{}", component, builder.rust_package_vers())
74}
75
76pub(crate) fn distdir(builder: &Builder<'_>) -> PathBuf {
77    builder.out.join("dist")
78}
79
80pub fn tmpdir(builder: &Builder<'_>) -> PathBuf {
81    builder.out.join("tmp/dist")
82}
83
84fn should_build_extended_tool(builder: &Builder<'_>, tool: &str) -> bool {
85    if !builder.config.extended {
86        return false;
87    }
88    builder.config.tools.as_ref().is_none_or(|tools| tools.contains(tool))
89}
90
91#[derive(Debug, Clone, Hash, PartialEq, Eq)]
92pub struct Docs {
93    pub host: TargetSelection,
94}
95
96impl CommandLineStep for Docs {
97    type Output = Option<GeneratedTarball>;
98
99    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
100        run.alias("rust-docs")
101    }
102
103    fn is_default_step(builder: &Builder<'_>) -> bool {
104        builder.config.docs
105    }
106
107    fn make_run(run: RunConfig<'_>) {
108        run.builder.ensure(Docs { host: run.target });
109    }
110
111    /// Builds the `rust-docs` installer component.
112    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
113        let host = self.host;
114        // FIXME: explicitly enumerate the steps that should be executed here, and gather their
115        // documentation, rather than running all default steps and then read their output
116        // from a shared directory.
117        builder.run_default_doc_steps();
118
119        // In case no default doc steps are run for host, it is possible that `<host>/doc` directory
120        // is never created.
121        if !builder.config.dry_run() {
122            t!(fs::create_dir_all(builder.doc_out(host)));
123        }
124
125        let dest = "share/doc/rust/html";
126
127        let mut tarball = Tarball::new(builder, "rust-docs", &host.triple);
128        tarball.set_product_name("Rust Documentation");
129        tarball.add_bulk_dir(builder.doc_out(host), dest);
130        tarball.add_file(builder.src.join("src/doc/robots.txt"), dest, FileType::Regular);
131        tarball.add_file(builder.src.join("src/doc/sitemap.txt"), dest, FileType::Regular);
132        Some(tarball.generate())
133    }
134
135    fn metadata(&self) -> Option<StepMetadata> {
136        Some(StepMetadata::dist("docs", self.host))
137    }
138}
139
140/// Builds the `rust-docs-json` installer component.
141/// It contains the documentation of the standard library in JSON format.
142#[derive(Debug, Clone, Hash, PartialEq, Eq)]
143pub struct JsonDocs {
144    build_compiler: Compiler,
145    target: TargetSelection,
146}
147
148impl CommandLineStep for JsonDocs {
149    type Output = Option<GeneratedTarball>;
150
151    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
152        run.alias("rust-docs-json")
153    }
154
155    fn is_default_step(builder: &Builder<'_>) -> bool {
156        builder.config.docs
157    }
158
159    fn make_run(run: RunConfig<'_>) {
160        run.builder.ensure(JsonDocs {
161            build_compiler: run.builder.compiler_for_std(run.builder.top_stage),
162            target: run.target,
163        });
164    }
165
166    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
167        let target = self.target;
168        let directory = builder.ensure(crate::core::build_steps::doc::Std::from_build_compiler(
169            self.build_compiler,
170            target,
171            DocumentationFormat::Json,
172        ));
173
174        let dest = "share/doc/rust/json";
175
176        let mut tarball = Tarball::new(builder, "rust-docs-json", &target.triple);
177        tarball.set_product_name("Rust Documentation In JSON Format");
178        tarball.is_preview(true);
179        tarball.add_bulk_dir(directory, dest);
180        Some(tarball.generate())
181    }
182
183    fn metadata(&self) -> Option<StepMetadata> {
184        Some(StepMetadata::dist("json-docs", self.target).built_by(self.build_compiler))
185    }
186}
187
188/// Builds the `rustc-docs` component.
189/// Apart from the documentation of the `rustc_*` crates, it also includes the documentation of
190/// various in-tree helper tools (bootstrap, build_helper, tidy),
191/// and also rustc_private tools like rustdoc, clippy, miri or rustfmt.
192///
193/// It is currently hosted at <https://doc.rust-lang.org/nightly/nightly-rustc>.
194#[derive(Debug, Clone, Hash, PartialEq, Eq)]
195pub struct RustcDocs {
196    target: TargetSelection,
197}
198
199impl CommandLineStep for RustcDocs {
200    type Output = GeneratedTarball;
201    const IS_HOST: bool = true;
202
203    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
204        run.alias("rustc-docs")
205    }
206
207    fn is_default_step(builder: &Builder<'_>) -> bool {
208        builder.config.compiler_docs
209    }
210
211    fn make_run(run: RunConfig<'_>) {
212        run.builder.ensure(RustcDocs { target: run.target });
213    }
214
215    fn run(self, builder: &Builder<'_>) -> Self::Output {
216        let target = self.target;
217        let combined_docs =
218            builder.ensure(CompilerWithTools::for_stage(builder, builder.top_stage, self.target));
219
220        let mut tarball = Tarball::new(builder, "rustc-docs", &target.triple);
221        tarball.set_product_name("Rustc Documentation");
222        tarball.add_bulk_dir(combined_docs, "share/doc/rust/html/rustc-docs");
223        tarball.generate()
224    }
225}
226
227fn find_files(files: &[&str], path: &[PathBuf]) -> Vec<PathBuf> {
228    let mut found = Vec::with_capacity(files.len());
229
230    for file in files {
231        let file_path = path.iter().map(|dir| dir.join(file)).find(|p| p.exists());
232
233        if let Some(file_path) = file_path {
234            found.push(file_path);
235        } else {
236            panic!("Could not find '{file}' in {path:?}");
237        }
238    }
239
240    found
241}
242
243fn make_win_dist(plat_root: &Path, target: TargetSelection, builder: &Builder<'_>) {
244    if builder.config.dry_run() {
245        return;
246    }
247
248    let (bin_path, lib_path) = get_cc_search_dirs(target, builder);
249
250    let compiler = if target == "i686-pc-windows-gnu" {
251        "i686-w64-mingw32-gcc.exe"
252    } else if target == "x86_64-pc-windows-gnu" {
253        "x86_64-w64-mingw32-gcc.exe"
254    } else {
255        "gcc.exe"
256    };
257    let target_tools = [compiler, "ld.exe", "dlltool.exe", "libwinpthread-1.dll"];
258
259    // Libraries necessary to link the windows-gnu toolchains.
260    // System libraries will be preferred if they are available (see #67429).
261    let target_libs = [
262        //MinGW libs
263        "libgcc.a",
264        "libgcc_eh.a",
265        "libgcc_s.a",
266        "libm.a",
267        "libmingw32.a",
268        "libmingwex.a",
269        "libstdc++.a",
270        "libiconv.a",
271        "libmoldname.a",
272        "libpthread.a",
273        // Windows import libs
274        // This *should* contain only the set of libraries necessary to link the standard library,
275        // however we've had problems with people accidentally depending on extra libs being here,
276        // so we can't easily remove entries.
277        "libadvapi32.a",
278        "libbcrypt.a",
279        "libcomctl32.a",
280        "libcomdlg32.a",
281        "libcredui.a",
282        "libcrypt32.a",
283        "libdbghelp.a",
284        "libgdi32.a",
285        "libimagehlp.a",
286        "libiphlpapi.a",
287        "libkernel32.a",
288        "libmsimg32.a",
289        "libmsvcrt.a",
290        "libntdll.a",
291        "libodbc32.a",
292        "libole32.a",
293        "liboleaut32.a",
294        "libopengl32.a",
295        "libpsapi.a",
296        "librpcrt4.a",
297        "libsecur32.a",
298        "libsetupapi.a",
299        "libshell32.a",
300        "libsynchronization.a",
301        "libuser32.a",
302        "libuserenv.a",
303        "libuuid.a",
304        "libwinhttp.a",
305        "libwinmm.a",
306        "libwinspool.a",
307        "libws2_32.a",
308        "libwsock32.a",
309    ];
310
311    //Find mingw artifacts we want to bundle
312    let target_tools = find_files(&target_tools, &bin_path);
313    let target_libs = find_files(&target_libs, &lib_path);
314
315    //Copy platform tools to platform-specific bin directory
316    let plat_target_bin_self_contained_dir =
317        plat_root.join("lib/rustlib").join(target).join("bin/self-contained");
318    fs::create_dir_all(&plat_target_bin_self_contained_dir)
319        .expect("creating plat_target_bin_self_contained_dir failed");
320    for src in target_tools {
321        builder.copy_link_to_folder(&src, &plat_target_bin_self_contained_dir);
322    }
323
324    // Warn windows-gnu users that the bundled GCC cannot compile C files
325    builder.create(
326        &plat_target_bin_self_contained_dir.join("GCC-WARNING.txt"),
327        "gcc.exe contained in this folder cannot be used for compiling C files - it is only \
328         used as a linker. In order to be able to compile projects containing C code use \
329         the GCC provided by MinGW or Cygwin.",
330    );
331
332    //Copy platform libs to platform-specific lib directory
333    let plat_target_lib_self_contained_dir =
334        plat_root.join("lib/rustlib").join(target).join("lib/self-contained");
335    fs::create_dir_all(&plat_target_lib_self_contained_dir)
336        .expect("creating plat_target_lib_self_contained_dir failed");
337    for src in target_libs {
338        builder.copy_link_to_folder(&src, &plat_target_lib_self_contained_dir);
339    }
340}
341
342fn make_win_llvm_dist(plat_root: &Path, target: TargetSelection, builder: &Builder<'_>) {
343    if builder.config.dry_run() {
344        return;
345    }
346
347    let (_, lib_path) = get_cc_search_dirs(target, builder);
348
349    // Libraries necessary to link the windows-gnullvm toolchains.
350    // System libraries will be preferred if they are available (see #67429).
351    let target_libs = [
352        // MinGW libs
353        "libunwind.a",
354        "libmingw32.a",
355        "libmingwex.a",
356        "libmsvcrt.a",
357        // Windows import libs, remove them once std transitions to raw-dylib
358        "libdbghelp.a",
359        "libkernel32.a",
360        "libntdll.a",
361        "libsynchronization.a",
362        "libuser32.a",
363        "libuserenv.a",
364        "libws2_32.a",
365    ];
366
367    //Find mingw artifacts we want to bundle
368    let target_libs = find_files(&target_libs, &lib_path);
369
370    //Copy platform libs to platform-specific lib directory
371    let plat_target_lib_self_contained_dir =
372        plat_root.join("lib/rustlib").join(target).join("lib/self-contained");
373    fs::create_dir_all(&plat_target_lib_self_contained_dir)
374        .expect("creating plat_target_lib_self_contained_dir failed");
375    for src in target_libs {
376        builder.copy_link_to_folder(&src, &plat_target_lib_self_contained_dir);
377    }
378}
379
380fn runtime_dll_dist(rust_root: &Path, target: TargetSelection, builder: &Builder<'_>) {
381    if builder.config.dry_run() {
382        return;
383    }
384
385    let (bin_path, _) = get_cc_search_dirs(target, builder);
386
387    let mut rustc_dlls = vec![];
388    // windows-gnu and windows-gnullvm require different runtime libs
389    if target.is_windows_gnu() {
390        rustc_dlls.push("libwinpthread-1.dll");
391        if target.starts_with("i686-") {
392            rustc_dlls.push("libgcc_s_dw2-1.dll");
393        } else {
394            rustc_dlls.push("libgcc_s_seh-1.dll");
395        }
396    } else if target.is_windows_gnullvm() {
397        rustc_dlls.push("libunwind.dll");
398    } else {
399        panic!("Vendoring of runtime DLLs for `{target}` is not supported`");
400    }
401    let rustc_dlls = find_files(&rustc_dlls, &bin_path);
402
403    // Copy runtime dlls next to rustc.exe
404    let rust_bin_dir = rust_root.join("bin/");
405    fs::create_dir_all(&rust_bin_dir).expect("creating rust_bin_dir failed");
406    for src in &rustc_dlls {
407        builder.copy_link_to_folder(src, &rust_bin_dir);
408    }
409
410    if builder.config.lld_enabled {
411        // rust-lld.exe also needs runtime dlls
412        let rust_target_bin_dir = rust_root.join("lib/rustlib").join(target).join("bin");
413        fs::create_dir_all(&rust_target_bin_dir).expect("creating rust_target_bin_dir failed");
414        for src in &rustc_dlls {
415            builder.copy_link_to_folder(src, &rust_target_bin_dir);
416        }
417    }
418}
419
420fn get_cc_search_dirs(
421    target: TargetSelection,
422    builder: &Builder<'_>,
423) -> (Vec<PathBuf>, Vec<PathBuf>) {
424    //Ask gcc where it keeps its stuff
425    let mut cmd = command(builder.cc(target));
426    cmd.arg("-print-search-dirs");
427    let gcc_out = cmd.run_capture_stdout(builder).stdout();
428
429    let mut bin_path: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect();
430    let mut lib_path = Vec::new();
431
432    for line in gcc_out.lines() {
433        let idx = line.find(':').unwrap();
434        let key = &line[..idx];
435        let trim_chars: &[_] = &[' ', '='];
436        let value = env::split_paths(line[(idx + 1)..].trim_start_matches(trim_chars));
437
438        if key == "programs" {
439            bin_path.extend(value);
440        } else if key == "libraries" {
441            lib_path.extend(value);
442        }
443    }
444    (bin_path, lib_path)
445}
446
447/// Builds the `rust-mingw` installer component.
448///
449/// This contains all the bits and pieces to run the MinGW Windows targets
450/// without any extra installed software (e.g., we bundle gcc, libraries, etc.).
451#[derive(Debug, Clone, Hash, PartialEq, Eq)]
452pub struct Mingw {
453    target: TargetSelection,
454}
455
456impl CommandLineStep for Mingw {
457    type Output = Option<GeneratedTarball>;
458
459    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
460        run.alias("rust-mingw")
461    }
462
463    fn is_default_step(_builder: &Builder<'_>) -> bool {
464        true
465    }
466
467    fn make_run(run: RunConfig<'_>) {
468        run.builder.ensure(Mingw { target: run.target });
469    }
470
471    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
472        let target = self.target;
473        if !target.contains("pc-windows-gnu") || !builder.config.dist_include_mingw_linker {
474            return None;
475        }
476
477        let mut tarball = Tarball::new(builder, "rust-mingw", &target.triple);
478        tarball.set_product_name("Rust MinGW");
479
480        if target.ends_with("pc-windows-gnu") {
481            make_win_dist(tarball.image_dir(), target, builder);
482        } else if target.ends_with("pc-windows-gnullvm") {
483            make_win_llvm_dist(tarball.image_dir(), target, builder);
484        } else {
485            unreachable!();
486        }
487
488        Some(tarball.generate())
489    }
490
491    fn metadata(&self) -> Option<StepMetadata> {
492        Some(StepMetadata::dist("mingw", self.target))
493    }
494}
495
496/// Creates the `rustc` installer component.
497///
498/// This includes:
499/// - The compiler and LLVM.
500/// - Debugger scripts.
501/// - Various helper tools, e.g. LLD or Rust Analyzer proc-macro server (if enabled).
502/// - The licenses of all code used by the compiler.
503///
504/// It does not include any standard library.
505#[derive(Debug, Clone, Hash, PartialEq, Eq)]
506pub struct Rustc {
507    /// This is the compiler that we will *ship* in this dist step.
508    pub target_compiler: Compiler,
509}
510
511impl CommandLineStep for Rustc {
512    type Output = GeneratedTarball;
513    const IS_HOST: bool = true;
514
515    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
516        run.alias("rustc")
517    }
518
519    fn is_default_step(_builder: &Builder<'_>) -> bool {
520        true
521    }
522
523    fn make_run(run: RunConfig<'_>) {
524        run.builder.ensure(Rustc {
525            target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
526        });
527    }
528
529    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
530        let target_compiler = self.target_compiler;
531        let target = self.target_compiler.host;
532
533        let tarball = Tarball::new(builder, "rustc", &target.triple);
534
535        // Prepare the rustc "image", what will actually end up getting installed
536        prepare_image(builder, target_compiler, tarball.image_dir());
537
538        // On MinGW we've got a few runtime DLL dependencies that we need to
539        // include.
540        // On 32-bit MinGW we're always including a DLL which needs some extra
541        // licenses to distribute. On 64-bit MinGW we don't actually distribute
542        // anything requiring us to distribute a license, but it's likely the
543        // install will *also* include the rust-mingw package, which also needs
544        // licenses, so to be safe we just include it here in all MinGW packages.
545        if target.contains("pc-windows-gnu") && builder.config.dist_include_mingw_linker {
546            runtime_dll_dist(tarball.image_dir(), target, builder);
547            tarball.add_dir(builder.src.join("src/etc/third-party"), "share/doc");
548        }
549
550        return tarball.generate();
551
552        fn prepare_image(builder: &Builder<'_>, target_compiler: Compiler, image: &Path) {
553            let target = target_compiler.host;
554            let src = builder.sysroot(target_compiler);
555
556            // Copy rustc binary
557            t!(fs::create_dir_all(image.join("bin")));
558            builder.cp_link_r(&src.join("bin"), &image.join("bin"));
559
560            // If enabled, copy rustdoc binary
561            if builder
562                .config
563                .tools
564                .as_ref()
565                .is_none_or(|tools| tools.iter().any(|tool| tool == "rustdoc"))
566            {
567                let rustdoc = builder.rustdoc_for_compiler(target_compiler);
568                builder.install(&rustdoc, &image.join("bin"), FileType::Executable);
569            }
570
571            let compilers = RustcPrivateCompilers::from_target_compiler(builder, target_compiler);
572
573            if let Some(ra_proc_macro_srv) = builder.ensure_if_default(
574                tool::RustAnalyzerProcMacroSrv::from_compilers(compilers),
575                builder.kind,
576            ) {
577                let dst = image.join("libexec");
578                builder.install(&ra_proc_macro_srv.tool_path, &dst, FileType::Executable);
579            }
580
581            let libdir_relative = builder.libdir_relative(target_compiler);
582
583            // Copy runtime DLLs needed by the compiler
584            if libdir_relative.to_str() != Some("bin") {
585                let libdir = builder.rustc_libdir(target_compiler);
586                for entry in builder.read_dir(&libdir) {
587                    // A safeguard that we will not ship libgccjit.so from the libdir, in case the
588                    // GCC codegen backend is enabled by default.
589                    // Long-term we should probably split the config options for:
590                    // - Include cg_gcc in the rustc sysroot by default
591                    // - Run dist of a specific codegen backend in `x dist` by default
592                    if is_dylib(&entry.path())
593                        && !entry
594                            .path()
595                            .file_name()
596                            .and_then(|n| n.to_str())
597                            .map(|n| n.contains("libgccjit"))
598                            .unwrap_or(false)
599                    {
600                        // Don't use custom libdir here because ^lib/ will be resolved again
601                        // with installer
602                        builder.install(&entry.path(), &image.join("lib"), FileType::NativeLibrary);
603                    }
604                }
605            }
606
607            // Copy libLLVM.so to the lib dir as well, if needed. While not
608            // technically needed by rustc itself it's needed by lots of other
609            // components like the llvm tools and LLD. LLD is included below and
610            // tools/LLDB come later, so let's just throw it in the rustc
611            // component for now.
612            maybe_install_llvm_runtime(builder, target, image);
613
614            let dst_dir = image.join("lib/rustlib").join(target).join("bin");
615            t!(fs::create_dir_all(&dst_dir));
616
617            // Copy over lld if it's there
618            if builder.config.lld_enabled {
619                let src_dir = builder.sysroot_target_bindir(target_compiler, target);
620                let rust_lld = exe("rust-lld", target_compiler.host);
621                builder.copy_link(
622                    &src_dir.join(&rust_lld),
623                    &dst_dir.join(&rust_lld),
624                    FileType::Executable,
625                );
626                let self_contained_lld_src_dir = src_dir.join("gcc-ld");
627                let self_contained_lld_dst_dir = dst_dir.join("gcc-ld");
628                t!(fs::create_dir(&self_contained_lld_dst_dir));
629                for name in LLD_FILE_NAMES {
630                    let exe_name = exe(name, target_compiler.host);
631                    builder.copy_link(
632                        &self_contained_lld_src_dir.join(&exe_name),
633                        &self_contained_lld_dst_dir.join(&exe_name),
634                        FileType::Executable,
635                    );
636                }
637            }
638
639            if builder.config.llvm_enabled(target_compiler.host)
640                && builder.config.llvm_tools_enabled
641            {
642                let src_dir = builder.sysroot_target_bindir(target_compiler, target);
643                let llvm_objcopy = exe("llvm-objcopy", target_compiler.host);
644                let rust_objcopy = exe("rust-objcopy", target_compiler.host);
645                builder.copy_link(
646                    &src_dir.join(&llvm_objcopy),
647                    &dst_dir.join(&rust_objcopy),
648                    FileType::Executable,
649                );
650            }
651
652            if builder.tool_enabled("wasm-component-ld") {
653                let src_dir = builder.sysroot_target_bindir(target_compiler, target);
654                let ld = exe("wasm-component-ld", target_compiler.host);
655                builder.copy_link(&src_dir.join(&ld), &dst_dir.join(&ld), FileType::Executable);
656            }
657
658            // Man pages
659            t!(fs::create_dir_all(image.join("share/man/man1")));
660            let man_src = builder.src.join("src/doc/man");
661            let man_dst = image.join("share/man/man1");
662
663            // don't use our `bootstrap::{copy_internal, cp_r}`, because those try
664            // to hardlink, and we don't want to edit the source templates
665            for file_entry in builder.read_dir(&man_src) {
666                let page_src = file_entry.path();
667                let page_dst = man_dst.join(file_entry.file_name());
668                let src_text = t!(std::fs::read_to_string(&page_src));
669                let version = builder.rust_info().version(builder.sess, &builder.version);
670                let new_text = src_text.replace("<INSERT VERSION HERE>", &version);
671                t!(std::fs::write(&page_dst, &new_text));
672            }
673
674            // Debugger scripts
675            builder.ensure(DebuggerScripts { sysroot: image.to_owned(), target });
676
677            generate_target_spec_json_schema(builder, image);
678
679            // HTML copyright files
680            let file_list = builder.ensure(super::run::GenerateCopyright);
681            for file in file_list {
682                builder.install(&file, &image.join("share/doc/rust"), FileType::Regular);
683            }
684
685            // README
686            builder.install(
687                &builder.src.join("README.md"),
688                &image.join("share/doc/rust"),
689                FileType::Regular,
690            );
691
692            // The REUSE-managed license files
693            let license = |path: &Path| {
694                builder.install(path, &image.join("share/doc/rust/licenses"), FileType::Regular);
695            };
696            for entry in t!(std::fs::read_dir(builder.src.join("LICENSES"))).flatten() {
697                license(&entry.path());
698            }
699        }
700    }
701
702    fn metadata(&self) -> Option<StepMetadata> {
703        Some(StepMetadata::dist("rustc", self.target_compiler.host))
704    }
705}
706
707fn generate_target_spec_json_schema(builder: &Builder<'_>, sysroot: &Path) {
708    // Since we run rustc in bootstrap, we need to ensure that we use the host compiler.
709    // We do this by using the stage 1 compiler, which is always compiled for the host,
710    // even in a cross build.
711    let stage1_host = builder.compiler(1, builder.host_target);
712    let mut rustc = builder.rustc_cmd(stage1_host).fail_fast();
713    rustc
714        .env("RUSTC_BOOTSTRAP", "1")
715        .args(["--print=target-spec-json-schema", "-Zunstable-options"]);
716    let schema = rustc.run_capture(builder).stdout();
717
718    let schema_dir = tmpdir(builder);
719    t!(fs::create_dir_all(&schema_dir));
720    let schema_file = schema_dir.join("target-spec-json-schema.json");
721    t!(std::fs::write(&schema_file, schema));
722
723    let dst = sysroot.join("etc");
724    t!(fs::create_dir_all(&dst));
725
726    builder.install(&schema_file, &dst, FileType::Regular);
727}
728
729/// Copies debugger scripts for `target` into the given compiler `sysroot`.
730#[derive(Debug, Clone, Hash, PartialEq, Eq)]
731pub struct DebuggerScripts {
732    /// Sysroot of a compiler into which will the debugger scripts be copied to.
733    pub sysroot: PathBuf,
734    pub target: TargetSelection,
735}
736
737impl Step for DebuggerScripts {
738    type Output = ();
739
740    fn run(self, builder: &Builder<'_>) {
741        let target = self.target;
742        let sysroot = self.sysroot;
743        let dst = sysroot.join("lib/rustlib/etc");
744        t!(fs::create_dir_all(&dst));
745        let cp_debugger_script = |file: &str| {
746            builder.install(&builder.src.join("src/etc/").join(file), &dst, FileType::Regular);
747        };
748        if target.contains("windows-msvc") {
749            // windbg debugger scripts
750            builder.install(
751                &builder.src.join("src/etc/rust-windbg.cmd"),
752                &sysroot.join("bin"),
753                FileType::Script,
754            );
755
756            cp_debugger_script("natvis/intrinsic.natvis");
757            cp_debugger_script("natvis/liballoc.natvis");
758            cp_debugger_script("natvis/libcore.natvis");
759            cp_debugger_script("natvis/libstd.natvis");
760        }
761
762        cp_debugger_script("rust_types.py");
763
764        // gdb debugger scripts
765        builder.install(
766            &builder.src.join("src/etc/rust-gdb"),
767            &sysroot.join("bin"),
768            FileType::Script,
769        );
770        builder.install(
771            &builder.src.join("src/etc/rust-gdbgui"),
772            &sysroot.join("bin"),
773            FileType::Script,
774        );
775
776        cp_debugger_script("gdb_load_rust_pretty_printers.py");
777        cp_debugger_script("gdb_lookup.py");
778        cp_debugger_script("gdb_providers.py");
779        if builder.sess.unstable_features() {
780            cp_debugger_script("gdb_trim_paths.py");
781        }
782
783        // lldb debugger scripts
784        builder.install(
785            &builder.src.join("src/etc/rust-lldb"),
786            &sysroot.join("bin"),
787            FileType::Script,
788        );
789
790        cp_debugger_script("lldb_lookup.py");
791        cp_debugger_script("lldb_providers.py");
792        if builder.sess.unstable_features() {
793            cp_debugger_script("lldb_trim_paths.py");
794        }
795    }
796}
797
798fn skip_host_target_lib(builder: &Builder<'_>, compiler: Compiler) -> bool {
799    // The only true set of target libraries came from the build triple, so
800    // let's reduce redundant work by only producing archives from that host.
801    if !builder.config.is_host_target(compiler.host) {
802        builder.info("\tskipping, not a build host");
803        true
804    } else {
805        false
806    }
807}
808
809/// Check that all objects in rlibs for UEFI targets are COFF. This
810/// ensures that the C compiler isn't producing ELF objects, which would
811/// not link correctly with the COFF objects.
812fn verify_uefi_rlib_format(builder: &Builder<'_>, target: TargetSelection, stamp: &BuildStamp) {
813    if !target.ends_with("-uefi") {
814        return;
815    }
816
817    for (path, _) in builder.read_stamp_file(stamp) {
818        if path.extension() != Some(OsStr::new("rlib")) {
819            continue;
820        }
821
822        let data = t!(fs::read(&path));
823        let data = data.as_slice();
824        let archive = t!(ArchiveFile::parse(data));
825        for member in archive.members() {
826            let member = t!(member);
827            let member_data = t!(member.data(data));
828
829            let is_coff = match object::File::parse(member_data) {
830                Ok(member_file) => member_file.format() == BinaryFormat::Coff,
831                Err(_) => false,
832            };
833
834            if !is_coff {
835                let member_name = String::from_utf8_lossy(member.name());
836                panic!("member {} in {} is not COFF", member_name, path.display());
837            }
838        }
839    }
840}
841
842/// Copy stamped files into an image's `target/lib` directory.
843fn copy_target_libs(
844    builder: &Builder<'_>,
845    target: TargetSelection,
846    image: &Path,
847    stamp: &BuildStamp,
848) {
849    let dst = image.join("lib/rustlib").join(target).join("lib");
850    let self_contained_dst = dst.join("self-contained");
851    t!(fs::create_dir_all(&dst));
852    t!(fs::create_dir_all(&self_contained_dst));
853    for (path, dependency_type) in builder.read_stamp_file(stamp) {
854        if dependency_type == DependencyType::TargetSelfContained {
855            builder.copy_link(
856                &path,
857                &self_contained_dst.join(path.file_name().unwrap()),
858                FileType::NativeLibrary,
859            );
860        } else if matches!(dependency_type, DependencyType::Target { .. })
861            || builder.config.is_host_target(target)
862        {
863            builder.copy_link(&path, &dst.join(path.file_name().unwrap()), FileType::NativeLibrary);
864        }
865    }
866}
867
868/// Builds the standard library (`rust-std`) dist component for a given `target`.
869/// This includes the standard library dynamic library file (e.g. .so/.dll), along with stdlib
870/// .rlibs.
871///
872/// Note that due to uplifting, we actually ship the stage 1 library
873/// (built using the stage1 compiler) even with a stage 2 dist, unless `full-bootstrap` is enabled.
874#[derive(Debug, Clone, Hash, PartialEq, Eq)]
875pub struct Std {
876    /// Compiler that will build the standard library.
877    pub build_compiler: Compiler,
878    pub target: TargetSelection,
879}
880
881impl Std {
882    pub fn new(builder: &Builder<'_>, target: TargetSelection) -> Self {
883        Std { build_compiler: builder.compiler_for_std(builder.top_stage), target }
884    }
885}
886
887impl CommandLineStep for Std {
888    type Output = Option<GeneratedTarball>;
889
890    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
891        run.alias("rust-std")
892    }
893
894    fn is_default_step(_builder: &Builder<'_>) -> bool {
895        true
896    }
897
898    fn make_run(run: RunConfig<'_>) {
899        run.builder.ensure(Std::new(run.builder, run.target));
900    }
901
902    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
903        let build_compiler = self.build_compiler;
904        let target = self.target;
905
906        if skip_host_target_lib(builder, build_compiler) {
907            return None;
908        }
909
910        // It's possible that std was uplifted and thus built with a different build compiler
911        // So we need to read the stamp that was actually generated when std was built
912        let stamp =
913            builder.std(build_compiler, target).expect("Standard library has to be built for dist");
914
915        let mut tarball = Tarball::new(builder, "rust-std", &target.triple);
916        tarball.include_target_in_component_name(true);
917
918        verify_uefi_rlib_format(builder, target, &stamp);
919        copy_target_libs(builder, target, tarball.image_dir(), &stamp);
920
921        Some(tarball.generate())
922    }
923
924    fn metadata(&self) -> Option<StepMetadata> {
925        Some(StepMetadata::dist("std", self.target).built_by(self.build_compiler))
926    }
927}
928
929/// Tarball containing the compiler that gets downloaded and used by
930/// `rust.download-rustc`.
931///
932/// (Don't confuse this with [`RustDev`], without the `c`!)
933#[derive(Debug, Clone, Hash, PartialEq, Eq)]
934pub struct RustcDev {
935    /// The compiler that will build rustc which will be shipped in this component.
936    pub build_compiler: Compiler,
937    pub target: TargetSelection,
938}
939
940impl RustcDev {
941    pub fn new(builder: &Builder<'_>, target: TargetSelection) -> Self {
942        Self {
943            // We currently always ship a stage 2 rustc-dev component, so we build it with the
944            // stage 1 compiler. This might change in the future.
945            // The precise stage used here is important, so we hard-code it.
946            build_compiler: builder.compiler(1, builder.config.host_target),
947            target,
948        }
949    }
950}
951
952impl CommandLineStep for RustcDev {
953    type Output = Option<GeneratedTarball>;
954    const IS_HOST: bool = true;
955
956    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
957        run.alias("rustc-dev")
958    }
959
960    fn is_default_step(_builder: &Builder<'_>) -> bool {
961        true
962    }
963
964    fn make_run(run: RunConfig<'_>) {
965        run.builder.ensure(RustcDev::new(run.builder, run.target));
966    }
967
968    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
969        let build_compiler = self.build_compiler;
970        let target = self.target;
971        if skip_host_target_lib(builder, build_compiler) {
972            return None;
973        }
974
975        // Build the compiler that we will ship
976        builder.ensure(compile::Rustc::new(build_compiler, target));
977
978        let tarball = Tarball::new(builder, "rustc-dev", &target.triple);
979
980        let stamp = build_stamp::librustc_stamp(builder, build_compiler, target);
981        copy_target_libs(builder, target, tarball.image_dir(), &stamp);
982
983        let src_files = &["Cargo.lock"];
984        // This is the reduced set of paths which will become the rustc-dev component
985        // (essentially the compiler crates and all of their path dependencies).
986        copy_src_dirs(
987            builder,
988            &builder.src,
989            // The compiler has a path dependency on proc_macro, so make sure to include it.
990            &["compiler", "library/proc_macro"],
991            &[],
992            &tarball.image_dir().join("lib/rustlib/rustc-src/rust"),
993        );
994        for file in src_files {
995            tarball.add_file(
996                builder.src.join(file),
997                "lib/rustlib/rustc-src/rust",
998                FileType::Regular,
999            );
1000        }
1001
1002        Some(tarball.generate())
1003    }
1004
1005    fn metadata(&self) -> Option<StepMetadata> {
1006        Some(StepMetadata::dist("rustc-dev", self.target).built_by(self.build_compiler))
1007    }
1008}
1009
1010/// The `rust-analysis` component used to create a tarball of save-analysis metadata.
1011///
1012/// This component has been deprecated and its contents now only include a warning about
1013/// its non-availability.
1014#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1015pub struct Analysis {
1016    build_compiler: Compiler,
1017    target: TargetSelection,
1018}
1019
1020impl CommandLineStep for Analysis {
1021    type Output = Option<GeneratedTarball>;
1022
1023    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1024        run.alias("rust-analysis")
1025    }
1026
1027    fn is_default_step(builder: &Builder<'_>) -> bool {
1028        should_build_extended_tool(builder, "analysis")
1029    }
1030
1031    fn make_run(run: RunConfig<'_>) {
1032        // The step just produces a deprecation notice, so we just hardcode stage 1
1033        run.builder.ensure(Analysis {
1034            build_compiler: run.builder.compiler(1, run.builder.config.host_target),
1035            target: run.target,
1036        });
1037    }
1038
1039    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1040        let compiler = self.build_compiler;
1041        let target = self.target;
1042        if skip_host_target_lib(builder, compiler) {
1043            return None;
1044        }
1045
1046        let src = builder
1047            .stage_out(compiler, Mode::Std)
1048            .join(target)
1049            .join(builder.cargo_dir(Mode::Std))
1050            .join("deps")
1051            .join("save-analysis");
1052
1053        // Write a file indicating that this component has been removed.
1054        t!(std::fs::create_dir_all(&src));
1055        let mut removed = src.clone();
1056        removed.push("removed.json");
1057        let mut f = t!(std::fs::File::create(removed));
1058        t!(write!(f, r#"{{ "warning": "The `rust-analysis` component has been removed." }}"#));
1059
1060        let mut tarball = Tarball::new(builder, "rust-analysis", &target.triple);
1061        tarball.include_target_in_component_name(true);
1062        tarball.add_dir(src, format!("lib/rustlib/{}/analysis", target.triple));
1063        Some(tarball.generate())
1064    }
1065
1066    fn metadata(&self) -> Option<StepMetadata> {
1067        Some(StepMetadata::dist("analysis", self.target).built_by(self.build_compiler))
1068    }
1069}
1070
1071/// Use the `builder` to make a filtered copy of `base`/X for X in (`src_dirs` - `exclude_dirs`) to
1072/// `dst_dir`.
1073fn copy_src_dirs(
1074    builder: &Builder<'_>,
1075    base: &Path,
1076    src_dirs: &[&str],
1077    exclude_dirs: &[&str],
1078    dst_dir: &Path,
1079) {
1080    // The src directories should be relative to `base`, we depend on them not being absolute
1081    // paths below.
1082    for src_dir in src_dirs {
1083        assert!(Path::new(src_dir).is_relative());
1084    }
1085
1086    // Iterating, filtering and copying a large number of directories can be quite slow.
1087    // Avoid doing it in dry run (and thus also tests).
1088    if builder.config.dry_run() {
1089        return;
1090    }
1091
1092    fn filter_fn(exclude_dirs: &[&str], dir: &str, path: &Path) -> bool {
1093        // The paths are relative, e.g. `llvm-project/...`.
1094        let spath = match path.to_str() {
1095            Some(path) => path,
1096            None => return false,
1097        };
1098        if spath.ends_with('~') || spath.ends_with(".pyc") {
1099            return false;
1100        }
1101        // Normalize slashes
1102        let spath = spath.replace("\\", "/");
1103
1104        static LLVM_PROJECTS: &[&str] = &[
1105            "llvm-project/clang",
1106            "llvm-project/libc",
1107            "llvm-project/libunwind",
1108            "llvm-project/lld",
1109            "llvm-project/lldb",
1110            "llvm-project/llvm",
1111            "llvm-project/compiler-rt",
1112            "llvm-project/cmake",
1113            "llvm-project/runtimes",
1114            "llvm-project/third-party",
1115        ];
1116        if spath.starts_with("llvm-project") && spath != "llvm-project" {
1117            if !LLVM_PROJECTS.iter().any(|path| spath.starts_with(path)) {
1118                return false;
1119            }
1120
1121            // Keep siphash third-party dependency
1122            if spath.starts_with("llvm-project/third-party")
1123                && spath != "llvm-project/third-party"
1124                && !spath.starts_with("llvm-project/third-party/siphash")
1125            {
1126                return false;
1127            }
1128
1129            if spath.starts_with("llvm-project/llvm/test")
1130                && (spath.ends_with(".ll") || spath.ends_with(".td") || spath.ends_with(".s"))
1131            {
1132                return false;
1133            }
1134        }
1135
1136        // Cargo tests use some files like `.gitignore` that we would otherwise exclude.
1137        if spath.starts_with("tools/cargo/tests") {
1138            return true;
1139        }
1140
1141        if !exclude_dirs.is_empty() {
1142            let full_path = Path::new(dir).join(path);
1143            if exclude_dirs.iter().any(|excl| full_path == Path::new(excl)) {
1144                return false;
1145            }
1146        }
1147
1148        static EXCLUDES: &[&str] = &[
1149            "CVS",
1150            "RCS",
1151            "SCCS",
1152            ".git",
1153            ".gitignore",
1154            ".gitmodules",
1155            ".gitattributes",
1156            ".cvsignore",
1157            ".svn",
1158            ".arch-ids",
1159            "{arch}",
1160            "=RELEASE-ID",
1161            "=meta-update",
1162            "=update",
1163            ".bzr",
1164            ".bzrignore",
1165            ".bzrtags",
1166            ".hg",
1167            ".hgignore",
1168            ".hgrags",
1169            "_darcs",
1170        ];
1171
1172        // We want to check if any component of `path` doesn't contain the strings in `EXCLUDES`.
1173        // However, since we traverse directories top-down in `Builder::cp_link_filtered`,
1174        // it is enough to always check only the last component:
1175        // - If the path is a file, we will iterate to it and then check it's filename
1176        // - If the path is a dir, if it's dir name contains an excluded string, we will not even
1177        //   recurse into it.
1178        let last_component = path.iter().next_back().map(|s| s.to_str().unwrap()).unwrap();
1179        !EXCLUDES.contains(&last_component)
1180    }
1181
1182    // Copy the directories using our filter
1183    for item in src_dirs {
1184        let dst = &dst_dir.join(item);
1185        t!(fs::create_dir_all(dst));
1186        builder
1187            .cp_link_filtered(&base.join(item), dst, &|path| filter_fn(exclude_dirs, item, path));
1188    }
1189}
1190
1191#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1192pub struct Src;
1193
1194impl CommandLineStep for Src {
1195    /// The output path of the src installer tarball
1196    type Output = GeneratedTarball;
1197    const IS_HOST: bool = true;
1198
1199    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1200        run.alias("rust-src")
1201    }
1202
1203    fn is_default_step(_builder: &Builder<'_>) -> bool {
1204        true
1205    }
1206
1207    fn make_run(run: RunConfig<'_>) {
1208        run.builder.ensure(Src);
1209    }
1210
1211    /// Creates the `rust-src` installer component
1212    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
1213        if !builder.config.dry_run() {
1214            builder.require_submodule("src/llvm-project", None);
1215        }
1216
1217        let tarball = Tarball::new_targetless(builder, "rust-src");
1218
1219        // A lot of tools expect the rust-src component to be entirely in this directory, so if you
1220        // change that (e.g. by adding another directory `lib/rustlib/src/foo` or
1221        // `lib/rustlib/src/rust/foo`), you will need to go around hunting for implicit assumptions
1222        // and fix them...
1223        //
1224        // NOTE: if you update the paths here, you also should update the "virtual" path
1225        // translation code in `imported_source_files` in `src/librustc_metadata/rmeta/decoder.rs`
1226        let dst_src = tarball.image_dir().join("lib/rustlib/src/rust");
1227
1228        // This is the reduced set of paths which will become the rust-src component
1229        // (essentially libstd and all of its path dependencies).
1230        copy_src_dirs(
1231            builder,
1232            &builder.src,
1233            &["library", "src/llvm-project/libunwind"],
1234            &[
1235                // not needed and contains symlinks which rustup currently
1236                // chokes on when unpacking.
1237                "library/backtrace/crates",
1238            ],
1239            &dst_src,
1240        );
1241
1242        // Vendor all Cargo dependencies
1243        let vendor = builder.ensure(Vendor {
1244            sync_args: vec![],
1245            versioned_dirs: true,
1246            root_dir: dst_src.clone(),
1247            output_dir: None,
1248            only_library_workspace: true,
1249        });
1250
1251        let library_cargo_config_dir = dst_src.join("library").join(".cargo");
1252        builder.create_dir(&library_cargo_config_dir);
1253        builder.create(&library_cargo_config_dir.join("config.toml"), &vendor.config_library);
1254
1255        tarball.generate()
1256    }
1257
1258    fn metadata(&self) -> Option<StepMetadata> {
1259        Some(StepMetadata::dist("src", TargetSelection::default()))
1260    }
1261}
1262
1263/// Tarball for people who want to build rustc and other components from the source.
1264/// Does not contain GPL code, which is separated into `PlainSourceTarballGpl`
1265/// for licensing reasons.
1266#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1267pub struct PlainSourceTarball;
1268
1269impl CommandLineStep for PlainSourceTarball {
1270    /// Produces the location of the tarball generated
1271    type Output = GeneratedTarball;
1272    const IS_HOST: bool = true;
1273
1274    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1275        run.alias("rustc-src")
1276    }
1277
1278    fn is_default_step(builder: &Builder<'_>) -> bool {
1279        builder.config.rust_dist_src
1280    }
1281
1282    fn make_run(run: RunConfig<'_>) {
1283        run.builder.ensure(PlainSourceTarball);
1284    }
1285
1286    /// Creates the plain source tarball
1287    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
1288        let tarball = prepare_source_tarball(
1289            builder,
1290            "src",
1291            &[
1292                // We don't currently use the GCC source code for building any official components,
1293                // it is very big, and has unclear licensing implications due to being GPL licensed.
1294                // We thus exclude it from the source tarball from now.
1295                "src/gcc",
1296            ],
1297        );
1298
1299        let plain_dst_src = tarball.image_dir();
1300        // We keep something in src/gcc because it is a registered submodule,
1301        // and if it misses completely it can cause issues elsewhere
1302        // (see https://github.com/rust-lang/rust/issues/137332).
1303        // We can also let others know why is the source code missing.
1304        if !builder.config.dry_run() {
1305            builder.create_dir(&plain_dst_src.join("src/gcc"));
1306            t!(std::fs::write(
1307                plain_dst_src.join("src/gcc/notice.txt"),
1308                "The GCC source code is not included due to unclear licensing implications\n"
1309            ));
1310        }
1311        tarball.bare()
1312    }
1313}
1314
1315/// Tarball with *all* source code for source builds, including GPL-licensed code.
1316#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1317pub struct PlainSourceTarballGpl;
1318
1319impl CommandLineStep for PlainSourceTarballGpl {
1320    /// Produces the location of the tarball generated
1321    type Output = GeneratedTarball;
1322    const IS_HOST: bool = true;
1323
1324    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1325        run.alias("rustc-src-gpl")
1326    }
1327
1328    fn is_default_step(builder: &Builder<'_>) -> bool {
1329        builder.config.rust_dist_src
1330    }
1331
1332    fn make_run(run: RunConfig<'_>) {
1333        run.builder.ensure(PlainSourceTarballGpl);
1334    }
1335
1336    /// Creates the plain source tarball
1337    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
1338        let tarball = prepare_source_tarball(builder, "src-gpl", &[]);
1339        tarball.bare()
1340    }
1341}
1342
1343fn prepare_source_tarball<'a>(
1344    builder: &'a Builder<'a>,
1345    name: &str,
1346    exclude_dirs: &[&str],
1347) -> Tarball<'a> {
1348    // NOTE: This is a strange component in a lot of ways. It uses `src` as the target, which
1349    // means neither rustup nor rustup-toolchain-install-master know how to download it.
1350    // It also contains symbolic links, unlike other any other dist tarball.
1351    // It's used for distros building rustc from source in a pre-vendored environment.
1352    let mut tarball = Tarball::new(builder, "rustc", name);
1353    tarball.permit_symlinks(true);
1354    let plain_dst_src = tarball.image_dir();
1355
1356    // This is the set of root paths which will become part of the source package
1357    let src_files = [
1358        // tidy-alphabetical-start
1359        ".gitmodules",
1360        "CONTRIBUTING.md",
1361        "COPYRIGHT",
1362        "Cargo.lock",
1363        "Cargo.toml",
1364        "LICENSE-APACHE",
1365        "LICENSE-MIT",
1366        "README.md",
1367        "RELEASES.md",
1368        "REUSE.toml",
1369        "bootstrap.example.toml",
1370        "configure",
1371        "license-metadata.json",
1372        "package.json",
1373        "x",
1374        "x.ps1",
1375        "x.py",
1376        "yarn.lock",
1377        // tidy-alphabetical-end
1378    ];
1379    let src_dirs = ["src", "compiler", "library", "tests", "LICENSES"];
1380
1381    copy_src_dirs(builder, &builder.src, &src_dirs, exclude_dirs, plain_dst_src);
1382
1383    // Copy the files normally
1384    for item in &src_files {
1385        builder.copy_link(&builder.src.join(item), &plain_dst_src.join(item), FileType::Regular);
1386    }
1387
1388    // Create the version file
1389    builder.create(&plain_dst_src.join("version"), &builder.rust_version());
1390
1391    // Create the files containing git info, to ensure --version outputs the same.
1392    let write_git_info = |info: Option<&Info>, path: &Path| {
1393        if let Some(info) = info {
1394            t!(std::fs::create_dir_all(path));
1395            channel::write_commit_hash_file(path, &info.sha);
1396            channel::write_commit_info_file(path, info);
1397        }
1398    };
1399    write_git_info(builder.rust_info().info(), plain_dst_src);
1400    write_git_info(builder.cargo_info.info(), &plain_dst_src.join("./src/tools/cargo"));
1401
1402    if builder.config.dist_vendor {
1403        builder.require_and_update_all_submodules();
1404
1405        // Vendor packages that are required by opt-dist to collect PGO profiles.
1406        let pkgs_for_pgo_training = build_helper::BACKEND_PGO_CRATES
1407            .iter()
1408            .chain(build_helper::RUSTC_PGO_CRATES)
1409            .map(|pkg| {
1410                let mut manifest_path =
1411                    builder.src.join("./src/tools/rustc-perf/collector/compile-benchmarks");
1412                manifest_path.push(pkg);
1413                manifest_path.push("Cargo.toml");
1414                manifest_path
1415            });
1416
1417        // Vendor all Cargo dependencies
1418        let vendor = builder.ensure(Vendor {
1419            sync_args: pkgs_for_pgo_training.collect(),
1420            versioned_dirs: true,
1421            root_dir: plain_dst_src.into(),
1422            output_dir: None,
1423            only_library_workspace: false,
1424        });
1425
1426        let cargo_config_dir = plain_dst_src.join(".cargo");
1427        builder.create_dir(&cargo_config_dir);
1428        builder.create(&cargo_config_dir.join("config.toml"), &vendor.config);
1429
1430        let library_cargo_config_dir = plain_dst_src.join("library").join(".cargo");
1431        builder.create_dir(&library_cargo_config_dir);
1432        builder.create(&library_cargo_config_dir.join("config.toml"), &vendor.config_library);
1433    }
1434
1435    // Delete extraneous directories
1436    // FIXME: if we're managed by git, we should probably instead ask git if the given path
1437    // is managed by it?
1438    for entry in walkdir::WalkDir::new(tarball.image_dir())
1439        .follow_links(true)
1440        .into_iter()
1441        .filter_map(|e| e.ok())
1442    {
1443        if entry.path().is_dir() && entry.path().file_name() == Some(OsStr::new("__pycache__")) {
1444            t!(fs::remove_dir_all(entry.path()));
1445        }
1446    }
1447    tarball
1448}
1449
1450#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1451pub struct Cargo {
1452    pub build_compiler: Compiler,
1453    pub target: TargetSelection,
1454}
1455
1456impl CommandLineStep for Cargo {
1457    type Output = Option<GeneratedTarball>;
1458    const IS_HOST: bool = true;
1459
1460    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1461        run.alias("cargo")
1462    }
1463
1464    fn is_default_step(builder: &Builder<'_>) -> bool {
1465        should_build_extended_tool(builder, "cargo")
1466    }
1467
1468    fn make_run(run: RunConfig<'_>) {
1469        run.builder.ensure(Cargo {
1470            build_compiler: get_tool_target_compiler(
1471                run.builder,
1472                ToolTargetBuildMode::Build(run.target),
1473            ),
1474            target: run.target,
1475        });
1476    }
1477
1478    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1479        let build_compiler = self.build_compiler;
1480        let target = self.target;
1481
1482        let cargo = builder.ensure(tool::Cargo::from_build_compiler(build_compiler, target));
1483        let src = builder.src.join("src/tools/cargo");
1484        let etc = src.join("etc");
1485
1486        // Prepare the image directory
1487        let mut tarball = Tarball::new(builder, "cargo", &target.triple);
1488        tarball.set_overlay(OverlayKind::Cargo);
1489
1490        tarball.add_file(&cargo.tool_path, "bin", FileType::Executable);
1491        tarball.add_file(etc.join("_cargo"), "share/zsh/site-functions", FileType::Regular);
1492        tarball.add_renamed_file(
1493            etc.join("cargo.bashcomp.sh"),
1494            "etc/bash_completion.d",
1495            "cargo",
1496            FileType::Regular,
1497        );
1498        tarball.add_dir(etc.join("man"), "share/man/man1");
1499        tarball.add_legal_and_readme_to("share/doc/cargo");
1500
1501        Some(tarball.generate())
1502    }
1503
1504    fn metadata(&self) -> Option<StepMetadata> {
1505        Some(StepMetadata::dist("cargo", self.target).built_by(self.build_compiler))
1506    }
1507}
1508
1509/// Distribute the rust-analyzer component, which is used as a LSP by various IDEs.
1510#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1511pub struct RustAnalyzer {
1512    pub compilers: RustcPrivateCompilers,
1513    pub target: TargetSelection,
1514}
1515
1516impl CommandLineStep for RustAnalyzer {
1517    type Output = Option<GeneratedTarball>;
1518    const IS_HOST: bool = true;
1519
1520    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1521        run.alias("rust-analyzer")
1522    }
1523
1524    fn is_default_step(builder: &Builder<'_>) -> bool {
1525        should_build_extended_tool(builder, "rust-analyzer")
1526    }
1527
1528    fn make_run(run: RunConfig<'_>) {
1529        run.builder.ensure(RustAnalyzer {
1530            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1531            target: run.target,
1532        });
1533    }
1534
1535    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1536        let target = self.target;
1537        let rust_analyzer = builder.ensure(tool::RustAnalyzer::from_compilers(self.compilers));
1538
1539        let mut tarball = Tarball::new(builder, "rust-analyzer", &target.triple);
1540        tarball.set_overlay(OverlayKind::RustAnalyzer);
1541        tarball.is_preview(true);
1542        tarball.add_file(&rust_analyzer.tool_path, "bin", FileType::Executable);
1543        tarball.add_legal_and_readme_to("share/doc/rust-analyzer");
1544        Some(tarball.generate())
1545    }
1546
1547    fn metadata(&self) -> Option<StepMetadata> {
1548        Some(
1549            StepMetadata::dist("rust-analyzer", self.target)
1550                .built_by(self.compilers.build_compiler()),
1551        )
1552    }
1553}
1554
1555#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1556pub struct Clippy {
1557    pub compilers: RustcPrivateCompilers,
1558    pub target: TargetSelection,
1559}
1560
1561impl CommandLineStep for Clippy {
1562    type Output = Option<GeneratedTarball>;
1563    const IS_HOST: bool = true;
1564
1565    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1566        run.alias("clippy")
1567    }
1568
1569    fn is_default_step(builder: &Builder<'_>) -> bool {
1570        should_build_extended_tool(builder, "clippy")
1571    }
1572
1573    fn make_run(run: RunConfig<'_>) {
1574        run.builder.ensure(Clippy {
1575            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1576            target: run.target,
1577        });
1578    }
1579
1580    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1581        let target = self.target;
1582
1583        // Prepare the image directory
1584        // We expect clippy to build, because we've exited this step above if tool
1585        // state for clippy isn't testing.
1586        let clippy = builder.ensure(tool::Clippy::from_compilers(self.compilers));
1587        let cargoclippy = builder.ensure(tool::CargoClippy::from_compilers(self.compilers));
1588
1589        let mut tarball = Tarball::new(builder, "clippy", &target.triple);
1590        tarball.set_overlay(OverlayKind::Clippy);
1591        tarball.is_preview(true);
1592        tarball.add_file(&clippy.tool_path, "bin", FileType::Executable);
1593        tarball.add_file(&cargoclippy.tool_path, "bin", FileType::Executable);
1594        tarball.add_legal_and_readme_to("share/doc/clippy");
1595        Some(tarball.generate())
1596    }
1597
1598    fn metadata(&self) -> Option<StepMetadata> {
1599        Some(StepMetadata::dist("clippy", self.target).built_by(self.compilers.build_compiler()))
1600    }
1601}
1602
1603#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1604pub struct Miri {
1605    pub compilers: RustcPrivateCompilers,
1606    pub target: TargetSelection,
1607}
1608
1609impl CommandLineStep for Miri {
1610    type Output = Option<GeneratedTarball>;
1611    const IS_HOST: bool = true;
1612
1613    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1614        run.alias("miri")
1615    }
1616
1617    fn is_default_step(builder: &Builder<'_>) -> bool {
1618        should_build_extended_tool(builder, "miri")
1619    }
1620
1621    fn make_run(run: RunConfig<'_>) {
1622        run.builder.ensure(Miri {
1623            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1624            target: run.target,
1625        });
1626    }
1627
1628    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1629        // This prevents miri from being built for "dist" or "install"
1630        // on the stable/beta channels. It is a nightly-only tool and should
1631        // not be included.
1632        if !builder.sess.unstable_features() {
1633            return None;
1634        }
1635
1636        let miri = builder.ensure(tool::Miri::from_compilers(self.compilers));
1637        let cargomiri = builder.ensure(tool::CargoMiri::from_compilers(self.compilers));
1638
1639        let mut tarball = Tarball::new(builder, "miri", &self.target.triple);
1640        tarball.set_overlay(OverlayKind::Miri);
1641        tarball.is_preview(true);
1642        tarball.add_file(&miri.tool_path, "bin", FileType::Executable);
1643        tarball.add_file(&cargomiri.tool_path, "bin", FileType::Executable);
1644        tarball.add_legal_and_readme_to("share/doc/miri");
1645        Some(tarball.generate())
1646    }
1647
1648    fn metadata(&self) -> Option<StepMetadata> {
1649        Some(StepMetadata::dist("miri", self.target).built_by(self.compilers.build_compiler()))
1650    }
1651}
1652
1653#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1654pub struct CraneliftCodegenBackend {
1655    pub compilers: RustcPrivateCompilers,
1656    pub target: TargetSelection,
1657}
1658
1659impl CommandLineStep for CraneliftCodegenBackend {
1660    type Output = Option<GeneratedTarball>;
1661    const IS_HOST: bool = true;
1662
1663    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1664        run.alias("rustc_codegen_cranelift")
1665    }
1666
1667    fn is_default_step(builder: &Builder<'_>) -> bool {
1668        // We only want to build the cranelift backend in `x dist` if the backend was enabled
1669        // in rust.codegen-backends.
1670        // Sadly, we don't have access to the actual target for which we're disting clif here..
1671        // So we just use the host target.
1672        builder
1673            .config
1674            .enabled_codegen_backends(builder.host_target)
1675            .contains(&CodegenBackendKind::Cranelift)
1676    }
1677
1678    fn make_run(run: RunConfig<'_>) {
1679        run.builder.ensure(CraneliftCodegenBackend {
1680            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1681            target: run.target,
1682        });
1683    }
1684
1685    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1686        // This prevents rustc_codegen_cranelift from being built for "dist"
1687        // or "install" on the stable/beta channels. It is not yet stable and
1688        // should not be included.
1689        if !builder.sess.unstable_features() {
1690            return None;
1691        }
1692
1693        let target = self.target;
1694        if !target_supports_cranelift_backend(target) {
1695            builder.info("target not supported by rustc_codegen_cranelift. skipping");
1696            return None;
1697        }
1698
1699        let mut tarball = Tarball::new(builder, "rustc-codegen-cranelift", &target.triple);
1700        tarball.set_overlay(OverlayKind::RustcCodegenCranelift);
1701        tarball.is_preview(true);
1702        tarball.add_legal_and_readme_to("share/doc/rustc_codegen_cranelift");
1703
1704        let compilers = self.compilers;
1705        let stamp = builder.ensure(compile::CraneliftCodegenBackend { compilers });
1706
1707        if builder.config.dry_run() {
1708            return None;
1709        }
1710
1711        add_codegen_backend_to_tarball(builder, &tarball, compilers.target_compiler(), &stamp);
1712
1713        Some(tarball.generate())
1714    }
1715
1716    fn metadata(&self) -> Option<StepMetadata> {
1717        Some(
1718            StepMetadata::dist("rustc_codegen_cranelift", self.target)
1719                .built_by(self.compilers.build_compiler()),
1720        )
1721    }
1722}
1723
1724/// Builds a dist component containing the GCC codegen backend.
1725/// Note that for this backend to work, it must have a set of libgccjit dylibs available
1726/// at runtime.
1727#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1728pub struct GccCodegenBackend {
1729    pub compilers: RustcPrivateCompilers,
1730    pub target: TargetSelection,
1731}
1732
1733impl CommandLineStep for GccCodegenBackend {
1734    type Output = Option<GeneratedTarball>;
1735    const IS_HOST: bool = true;
1736
1737    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1738        run.alias("rustc_codegen_gcc")
1739    }
1740
1741    fn is_default_step(builder: &Builder<'_>) -> bool {
1742        // We only want to build the gcc backend in `x dist` if the backend was enabled
1743        // in rust.codegen-backends.
1744        // Sadly, we don't have access to the actual target for which we're disting gcc here..
1745        // So we just use the host target.
1746        builder
1747            .config
1748            .enabled_codegen_backends(builder.host_target)
1749            .contains(&CodegenBackendKind::Gcc)
1750    }
1751
1752    fn make_run(run: RunConfig<'_>) {
1753        run.builder.ensure(GccCodegenBackend {
1754            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1755            target: run.target,
1756        });
1757    }
1758
1759    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1760        // This prevents rustc_codegen_gcc from being built for "dist"
1761        // or "install" on the stable/beta channels. It is not yet stable and
1762        // should not be included.
1763        if !builder.sess.unstable_features() {
1764            return None;
1765        }
1766
1767        let target = self.target;
1768        if target != "x86_64-unknown-linux-gnu" {
1769            builder
1770                .info(&format!("target `{target}` not supported by rustc_codegen_gcc. skipping"));
1771            return None;
1772        }
1773
1774        let mut tarball = Tarball::new(builder, "rustc-codegen-gcc", &target.triple);
1775        tarball.set_overlay(OverlayKind::RustcCodegenGcc);
1776        tarball.is_preview(true);
1777        tarball.add_legal_and_readme_to("share/doc/rustc_codegen_gcc");
1778
1779        let compilers = self.compilers;
1780        let backend = builder.ensure(compile::GccCodegenBackend::for_target(compilers, target));
1781
1782        if builder.config.dry_run() {
1783            return None;
1784        }
1785
1786        add_codegen_backend_to_tarball(
1787            builder,
1788            &tarball,
1789            compilers.target_compiler(),
1790            backend.stamp(),
1791        );
1792
1793        Some(tarball.generate())
1794    }
1795
1796    fn metadata(&self) -> Option<StepMetadata> {
1797        Some(
1798            StepMetadata::dist("rustc_codegen_gcc", self.target)
1799                .built_by(self.compilers.build_compiler()),
1800        )
1801    }
1802}
1803
1804/// Add a codegen backend built for `compiler`, with its artifacts stored in `stamp`, to the given
1805/// `tarball` at the correct place.
1806fn add_codegen_backend_to_tarball(
1807    builder: &Builder<'_>,
1808    tarball: &Tarball<'_>,
1809    compiler: Compiler,
1810    stamp: &BuildStamp,
1811) {
1812    // Get the relative path of where the codegen backend should be stored.
1813    let backends_dst = builder.sysroot_codegen_backends(compiler);
1814    let backends_rel = backends_dst
1815        .strip_prefix(builder.sysroot(compiler))
1816        .unwrap()
1817        .strip_prefix(builder.sysroot_libdir_relative(compiler))
1818        .unwrap();
1819    // Don't use custom libdir here because ^lib/ will be resolved again with installer
1820    let backends_dst = PathBuf::from("lib").join(backends_rel);
1821
1822    let codegen_backend_dylib = get_codegen_backend_file(stamp);
1823    tarball.add_renamed_file(
1824        &codegen_backend_dylib,
1825        &backends_dst,
1826        &normalize_codegen_backend_name(builder, &codegen_backend_dylib),
1827        FileType::NativeLibrary,
1828    );
1829}
1830
1831#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1832pub struct Rustfmt {
1833    pub compilers: RustcPrivateCompilers,
1834    pub target: TargetSelection,
1835}
1836
1837impl CommandLineStep for Rustfmt {
1838    type Output = Option<GeneratedTarball>;
1839    const IS_HOST: bool = true;
1840
1841    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1842        run.alias("rustfmt")
1843    }
1844
1845    fn is_default_step(builder: &Builder<'_>) -> bool {
1846        should_build_extended_tool(builder, "rustfmt")
1847    }
1848
1849    fn make_run(run: RunConfig<'_>) {
1850        run.builder.ensure(Rustfmt {
1851            compilers: RustcPrivateCompilers::new(run.builder, run.builder.top_stage, run.target),
1852            target: run.target,
1853        });
1854    }
1855
1856    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1857        let rustfmt = builder.ensure(tool::Rustfmt::from_compilers(self.compilers));
1858        let cargofmt = builder.ensure(tool::Cargofmt::from_compilers(self.compilers));
1859
1860        let mut tarball = Tarball::new(builder, "rustfmt", &self.target.triple);
1861        tarball.set_overlay(OverlayKind::Rustfmt);
1862        tarball.is_preview(true);
1863        tarball.add_file(&rustfmt.tool_path, "bin", FileType::Executable);
1864        tarball.add_file(&cargofmt.tool_path, "bin", FileType::Executable);
1865        tarball.add_legal_and_readme_to("share/doc/rustfmt");
1866        Some(tarball.generate())
1867    }
1868
1869    fn metadata(&self) -> Option<StepMetadata> {
1870        Some(StepMetadata::dist("rustfmt", self.target).built_by(self.compilers.build_compiler()))
1871    }
1872}
1873
1874/// Extended archive that contains the compiler, standard library and a bunch of tools.
1875#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1876pub struct Extended {
1877    build_compiler: Compiler,
1878    target: TargetSelection,
1879}
1880
1881impl CommandLineStep for Extended {
1882    type Output = ();
1883    const IS_HOST: bool = true;
1884
1885    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1886        run.alias("extended")
1887    }
1888
1889    fn is_default_step(builder: &Builder<'_>) -> bool {
1890        builder.config.extended
1891    }
1892
1893    fn make_run(run: RunConfig<'_>) {
1894        run.builder.ensure(Extended {
1895            build_compiler: run
1896                .builder
1897                .compiler(run.builder.top_stage - 1, run.builder.host_target),
1898            target: run.target,
1899        });
1900    }
1901
1902    /// Creates a combined installer for the specified target in the provided stage.
1903    fn run(self, builder: &Builder<'_>) {
1904        let target = self.target;
1905        builder.info(&format!("Dist extended stage{} ({target})", builder.top_stage));
1906
1907        let mut tarballs = Vec::new();
1908        let mut built_tools = HashSet::new();
1909        macro_rules! add_component {
1910            ($name:expr => $step:expr) => {
1911                if let Some(Some(tarball)) = builder.ensure_if_default($step, Kind::Dist) {
1912                    tarballs.push(tarball);
1913                    built_tools.insert($name);
1914                }
1915            };
1916        }
1917
1918        let rustc_private_compilers =
1919            RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, target);
1920        let build_compiler = rustc_private_compilers.build_compiler();
1921        let target_compiler = rustc_private_compilers.target_compiler();
1922
1923        // When rust-std package split from rustc, we needed to ensure that during
1924        // upgrades rustc was upgraded before rust-std. To avoid rustc clobbering
1925        // the std files during uninstall. To do this ensure that rustc comes
1926        // before rust-std in the list below.
1927        tarballs.push(builder.ensure(Rustc { target_compiler }));
1928        tarballs.push(builder.ensure(Std { build_compiler, target }).expect("missing std"));
1929
1930        if target.is_windows_gnu() || target.is_windows_gnullvm() {
1931            tarballs.push(builder.ensure(Mingw { target }).expect("missing mingw"));
1932        }
1933
1934        add_component!("rust-docs" => Docs { host: target });
1935        // Std stage N is documented with compiler stage N
1936        add_component!("rust-json-docs" => JsonDocs { build_compiler: target_compiler, target });
1937        add_component!("cargo" => Cargo { build_compiler, target });
1938        add_component!("rustfmt" => Rustfmt { compilers: rustc_private_compilers, target });
1939        add_component!("rust-analyzer" => RustAnalyzer { compilers: rustc_private_compilers, target });
1940        add_component!("llvm-components" => LlvmTools { target });
1941        add_component!("clippy" => Clippy { compilers: rustc_private_compilers, target });
1942        add_component!("miri" => Miri { compilers: rustc_private_compilers, target });
1943        add_component!("analysis" => Analysis { build_compiler, target });
1944        add_component!("rustc-codegen-cranelift" => CraneliftCodegenBackend {
1945            compilers: rustc_private_compilers,
1946            target
1947        });
1948        add_component!("llvm-bitcode-linker" => LlvmBitcodeLinker {
1949            build_compiler,
1950            target
1951        });
1952
1953        let etc = builder.src.join("src/etc/installer");
1954
1955        // Avoid producing tarballs during a dry run.
1956        if builder.config.dry_run() {
1957            return;
1958        }
1959
1960        let tarball = Tarball::new(builder, "rust", &target.triple);
1961        let generated = tarball.combine(&tarballs);
1962
1963        let tmp = tmpdir(builder).join("combined-tarball");
1964        let work = generated.work_dir();
1965
1966        let mut license = String::new();
1967        license += &builder.read(&builder.src.join("COPYRIGHT"));
1968        license += &builder.read(&builder.src.join("LICENSE-APACHE"));
1969        license += &builder.read(&builder.src.join("LICENSE-MIT"));
1970        license.push('\n');
1971        license.push('\n');
1972
1973        let rtf = r"{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Arial;}}\nowwrap\fs18";
1974        let mut rtf = rtf.to_string();
1975        rtf.push('\n');
1976        for line in license.lines() {
1977            rtf.push_str(line);
1978            rtf.push_str("\\line ");
1979        }
1980        rtf.push('}');
1981
1982        fn filter(contents: &str, marker: &str) -> String {
1983            let start = format!("tool-{marker}-start");
1984            let end = format!("tool-{marker}-end");
1985            let mut lines = Vec::new();
1986            let mut omitted = false;
1987            for line in contents.lines() {
1988                if line.contains(&start) {
1989                    omitted = true;
1990                } else if line.contains(&end) {
1991                    omitted = false;
1992                } else if !omitted {
1993                    lines.push(line);
1994                }
1995            }
1996
1997            lines.join("\n")
1998        }
1999
2000        let xform = |p: &Path| {
2001            let mut contents = t!(fs::read_to_string(p));
2002            for tool in &["miri", "rust-docs"] {
2003                if !built_tools.contains(tool) {
2004                    contents = filter(&contents, tool);
2005                }
2006            }
2007            let ret = tmp.join(p.file_name().unwrap());
2008            t!(fs::write(&ret, &contents));
2009            ret
2010        };
2011
2012        if target.contains("apple-darwin") {
2013            builder.info("building pkg installer");
2014            let pkg = tmp.join("pkg");
2015            let _ = fs::remove_dir_all(&pkg);
2016
2017            let pkgbuild = |component: &str| {
2018                let mut cmd = command("pkgbuild");
2019                cmd.arg("--identifier")
2020                    .arg(format!("org.rust-lang.{component}"))
2021                    .arg("--scripts")
2022                    .arg(pkg.join(component))
2023                    .arg("--nopayload")
2024                    .arg(pkg.join(component).with_extension("pkg"));
2025                cmd.run(builder);
2026            };
2027
2028            let prepare = |name: &str| {
2029                builder.create_dir(&pkg.join(name));
2030                builder.cp_link_r(
2031                    &work.join(format!("{}-{}", pkgname(builder, name), target.triple)),
2032                    &pkg.join(name),
2033                );
2034                builder.install(&etc.join("pkg/postinstall"), &pkg.join(name), FileType::Script);
2035                pkgbuild(name);
2036            };
2037            prepare("rustc");
2038            prepare("cargo");
2039            prepare("rust-std");
2040            prepare("rust-analysis");
2041
2042            for tool in &[
2043                "clippy",
2044                "rustfmt",
2045                "rust-analyzer",
2046                "rust-docs",
2047                "miri",
2048                "rustc-codegen-cranelift",
2049            ] {
2050                if built_tools.contains(tool) {
2051                    prepare(tool);
2052                }
2053            }
2054            // create an 'uninstall' package
2055            builder.install(&etc.join("pkg/postinstall"), &pkg.join("uninstall"), FileType::Script);
2056            pkgbuild("uninstall");
2057
2058            builder.create_dir(&pkg.join("res"));
2059            builder.create(&pkg.join("res/LICENSE.txt"), &license);
2060            builder.install(&etc.join("gfx/rust-logo.png"), &pkg.join("res"), FileType::Regular);
2061            let mut cmd = command("productbuild");
2062            cmd.arg("--distribution")
2063                .arg(xform(&etc.join("pkg/Distribution.xml")))
2064                .arg("--resources")
2065                .arg(pkg.join("res"))
2066                .arg(distdir(builder).join(format!(
2067                    "{}-{}.pkg",
2068                    pkgname(builder, "rust"),
2069                    target.triple
2070                )))
2071                .arg("--package-path")
2072                .arg(&pkg);
2073            let _time = timeit(builder);
2074            cmd.run(builder);
2075        }
2076
2077        if target.is_windows() {
2078            let exe = tmp.join("exe");
2079            let _ = fs::remove_dir_all(&exe);
2080
2081            let prepare = |name: &str| {
2082                builder.create_dir(&exe.join(name));
2083                let dir = if name == "rust-std" || name == "rust-analysis" {
2084                    format!("{}-{}", name, target.triple)
2085                } else if name == "rust-analyzer" {
2086                    "rust-analyzer-preview".to_string()
2087                } else if name == "clippy" {
2088                    "clippy-preview".to_string()
2089                } else if name == "rustfmt" {
2090                    "rustfmt-preview".to_string()
2091                } else if name == "miri" {
2092                    "miri-preview".to_string()
2093                } else if name == "rustc-codegen-cranelift" {
2094                    // FIXME add installer support for cg_clif once it is ready to be distributed on
2095                    // windows.
2096                    unreachable!("cg_clif shouldn't be built for windows");
2097                } else {
2098                    name.to_string()
2099                };
2100                builder.cp_link_r(
2101                    &work.join(format!("{}-{}", pkgname(builder, name), target.triple)).join(dir),
2102                    &exe.join(name),
2103                );
2104                builder.remove(&exe.join(name).join("manifest.in"));
2105            };
2106            prepare("rustc");
2107            prepare("cargo");
2108            prepare("rust-analysis");
2109            prepare("rust-std");
2110            for tool in &["clippy", "rustfmt", "rust-analyzer", "rust-docs", "miri"] {
2111                if built_tools.contains(tool) {
2112                    prepare(tool);
2113                }
2114            }
2115            if target.is_windows_gnu() || target.is_windows_gnullvm() {
2116                prepare("rust-mingw");
2117            }
2118
2119            builder.install(&etc.join("gfx/rust-logo.ico"), &exe, FileType::Regular);
2120
2121            // Generate msi installer
2122            let wix_path = env::var_os("WIX")
2123                .expect("`WIX` environment variable must be set for generating MSI installer(s).");
2124            let wix = PathBuf::from(wix_path);
2125            let heat = wix.join("bin/heat.exe");
2126            let candle = wix.join("bin/candle.exe");
2127            let light = wix.join("bin/light.exe");
2128
2129            let heat_flags = ["-nologo", "-gg", "-sfrag", "-srd", "-sreg"];
2130            command(&heat)
2131                .current_dir(&exe)
2132                .arg("dir")
2133                .arg("rustc")
2134                .args(heat_flags)
2135                .arg("-cg")
2136                .arg("RustcGroup")
2137                .arg("-dr")
2138                .arg("Rustc")
2139                .arg("-var")
2140                .arg("var.RustcDir")
2141                .arg("-out")
2142                .arg(exe.join("RustcGroup.wxs"))
2143                .run(builder);
2144            if built_tools.contains("rust-docs") {
2145                command(&heat)
2146                    .current_dir(&exe)
2147                    .arg("dir")
2148                    .arg("rust-docs")
2149                    .args(heat_flags)
2150                    .arg("-cg")
2151                    .arg("DocsGroup")
2152                    .arg("-dr")
2153                    .arg("Docs")
2154                    .arg("-var")
2155                    .arg("var.DocsDir")
2156                    .arg("-out")
2157                    .arg(exe.join("DocsGroup.wxs"))
2158                    .arg("-t")
2159                    .arg(etc.join("msi/squash-components.xsl"))
2160                    .run(builder);
2161            }
2162            command(&heat)
2163                .current_dir(&exe)
2164                .arg("dir")
2165                .arg("cargo")
2166                .args(heat_flags)
2167                .arg("-cg")
2168                .arg("CargoGroup")
2169                .arg("-dr")
2170                .arg("Cargo")
2171                .arg("-var")
2172                .arg("var.CargoDir")
2173                .arg("-out")
2174                .arg(exe.join("CargoGroup.wxs"))
2175                .arg("-t")
2176                .arg(etc.join("msi/remove-duplicates.xsl"))
2177                .run(builder);
2178            command(&heat)
2179                .current_dir(&exe)
2180                .arg("dir")
2181                .arg("rust-std")
2182                .args(heat_flags)
2183                .arg("-cg")
2184                .arg("StdGroup")
2185                .arg("-dr")
2186                .arg("Std")
2187                .arg("-var")
2188                .arg("var.StdDir")
2189                .arg("-out")
2190                .arg(exe.join("StdGroup.wxs"))
2191                .run(builder);
2192            if built_tools.contains("rust-analyzer") {
2193                command(&heat)
2194                    .current_dir(&exe)
2195                    .arg("dir")
2196                    .arg("rust-analyzer")
2197                    .args(heat_flags)
2198                    .arg("-cg")
2199                    .arg("RustAnalyzerGroup")
2200                    .arg("-dr")
2201                    .arg("RustAnalyzer")
2202                    .arg("-var")
2203                    .arg("var.RustAnalyzerDir")
2204                    .arg("-out")
2205                    .arg(exe.join("RustAnalyzerGroup.wxs"))
2206                    .arg("-t")
2207                    .arg(etc.join("msi/remove-duplicates.xsl"))
2208                    .run(builder);
2209            }
2210            if built_tools.contains("clippy") {
2211                command(&heat)
2212                    .current_dir(&exe)
2213                    .arg("dir")
2214                    .arg("clippy")
2215                    .args(heat_flags)
2216                    .arg("-cg")
2217                    .arg("ClippyGroup")
2218                    .arg("-dr")
2219                    .arg("Clippy")
2220                    .arg("-var")
2221                    .arg("var.ClippyDir")
2222                    .arg("-out")
2223                    .arg(exe.join("ClippyGroup.wxs"))
2224                    .arg("-t")
2225                    .arg(etc.join("msi/remove-duplicates.xsl"))
2226                    .run(builder);
2227            }
2228            if built_tools.contains("rustfmt") {
2229                command(&heat)
2230                    .current_dir(&exe)
2231                    .arg("dir")
2232                    .arg("rustfmt")
2233                    .args(heat_flags)
2234                    .arg("-cg")
2235                    .arg("RustFmtGroup")
2236                    .arg("-dr")
2237                    .arg("RustFmt")
2238                    .arg("-var")
2239                    .arg("var.RustFmtDir")
2240                    .arg("-out")
2241                    .arg(exe.join("RustFmtGroup.wxs"))
2242                    .arg("-t")
2243                    .arg(etc.join("msi/remove-duplicates.xsl"))
2244                    .run(builder);
2245            }
2246            if built_tools.contains("miri") {
2247                command(&heat)
2248                    .current_dir(&exe)
2249                    .arg("dir")
2250                    .arg("miri")
2251                    .args(heat_flags)
2252                    .arg("-cg")
2253                    .arg("MiriGroup")
2254                    .arg("-dr")
2255                    .arg("Miri")
2256                    .arg("-var")
2257                    .arg("var.MiriDir")
2258                    .arg("-out")
2259                    .arg(exe.join("MiriGroup.wxs"))
2260                    .arg("-t")
2261                    .arg(etc.join("msi/remove-duplicates.xsl"))
2262                    .run(builder);
2263            }
2264            command(&heat)
2265                .current_dir(&exe)
2266                .arg("dir")
2267                .arg("rust-analysis")
2268                .args(heat_flags)
2269                .arg("-cg")
2270                .arg("AnalysisGroup")
2271                .arg("-dr")
2272                .arg("Analysis")
2273                .arg("-var")
2274                .arg("var.AnalysisDir")
2275                .arg("-out")
2276                .arg(exe.join("AnalysisGroup.wxs"))
2277                .arg("-t")
2278                .arg(etc.join("msi/remove-duplicates.xsl"))
2279                .run(builder);
2280            if target.is_windows_gnu() || target.is_windows_gnullvm() {
2281                command(&heat)
2282                    .current_dir(&exe)
2283                    .arg("dir")
2284                    .arg("rust-mingw")
2285                    .args(heat_flags)
2286                    .arg("-cg")
2287                    .arg("GccGroup")
2288                    .arg("-dr")
2289                    .arg("Gcc")
2290                    .arg("-var")
2291                    .arg("var.GccDir")
2292                    .arg("-out")
2293                    .arg(exe.join("GccGroup.wxs"))
2294                    .run(builder);
2295            }
2296
2297            let candle = |input: &Path| {
2298                let output = exe.join(input.file_stem().unwrap()).with_extension("wixobj");
2299                let arch = if target.contains("x86_64") { "x64" } else { "x86" };
2300                let mut cmd = command(&candle);
2301                cmd.current_dir(&exe)
2302                    .arg("-nologo")
2303                    .arg("-dRustcDir=rustc")
2304                    .arg("-dCargoDir=cargo")
2305                    .arg("-dStdDir=rust-std")
2306                    .arg("-dAnalysisDir=rust-analysis")
2307                    .arg("-arch")
2308                    .arg(arch)
2309                    .arg("-out")
2310                    .arg(&output)
2311                    .arg(input);
2312                add_env(builder, &mut cmd, target, &built_tools);
2313
2314                if built_tools.contains("clippy") {
2315                    cmd.arg("-dClippyDir=clippy");
2316                }
2317                if built_tools.contains("rustfmt") {
2318                    cmd.arg("-dRustFmtDir=rustfmt");
2319                }
2320                if built_tools.contains("rust-docs") {
2321                    cmd.arg("-dDocsDir=rust-docs");
2322                }
2323                if built_tools.contains("rust-analyzer") {
2324                    cmd.arg("-dRustAnalyzerDir=rust-analyzer");
2325                }
2326                if built_tools.contains("miri") {
2327                    cmd.arg("-dMiriDir=miri");
2328                }
2329                if target.is_windows_gnu() || target.is_windows_gnullvm() {
2330                    cmd.arg("-dGccDir=rust-mingw");
2331                }
2332                cmd.run(builder);
2333            };
2334            candle(&xform(&etc.join("msi/rust.wxs")));
2335            candle(&etc.join("msi/ui.wxs"));
2336            candle(&etc.join("msi/rustwelcomedlg.wxs"));
2337            candle("RustcGroup.wxs".as_ref());
2338            if built_tools.contains("rust-docs") {
2339                candle("DocsGroup.wxs".as_ref());
2340            }
2341            candle("CargoGroup.wxs".as_ref());
2342            candle("StdGroup.wxs".as_ref());
2343            if built_tools.contains("clippy") {
2344                candle("ClippyGroup.wxs".as_ref());
2345            }
2346            if built_tools.contains("rustfmt") {
2347                candle("RustFmtGroup.wxs".as_ref());
2348            }
2349            if built_tools.contains("miri") {
2350                candle("MiriGroup.wxs".as_ref());
2351            }
2352            if built_tools.contains("rust-analyzer") {
2353                candle("RustAnalyzerGroup.wxs".as_ref());
2354            }
2355            candle("AnalysisGroup.wxs".as_ref());
2356
2357            if target.is_windows_gnu() || target.is_windows_gnullvm() {
2358                candle("GccGroup.wxs".as_ref());
2359            }
2360
2361            builder.create(&exe.join("LICENSE.rtf"), &rtf);
2362            builder.install(&etc.join("gfx/banner.bmp"), &exe, FileType::Regular);
2363            builder.install(&etc.join("gfx/dialogbg.bmp"), &exe, FileType::Regular);
2364
2365            builder.info(&format!("building `msi` installer with {light:?}"));
2366            let filename = format!("{}-{}.msi", pkgname(builder, "rust"), target.triple);
2367            let mut cmd = command(&light);
2368            cmd.arg("-nologo")
2369                .arg("-ext")
2370                .arg("WixUIExtension")
2371                .arg("-ext")
2372                .arg("WixUtilExtension")
2373                .arg("-out")
2374                .arg(exe.join(&filename))
2375                .arg("rust.wixobj")
2376                .arg("ui.wixobj")
2377                .arg("rustwelcomedlg.wixobj")
2378                .arg("RustcGroup.wixobj")
2379                .arg("CargoGroup.wixobj")
2380                .arg("StdGroup.wixobj")
2381                .arg("AnalysisGroup.wixobj")
2382                .current_dir(&exe);
2383
2384            if built_tools.contains("clippy") {
2385                cmd.arg("ClippyGroup.wixobj");
2386            }
2387            if built_tools.contains("rustfmt") {
2388                cmd.arg("RustFmtGroup.wixobj");
2389            }
2390            if built_tools.contains("miri") {
2391                cmd.arg("MiriGroup.wixobj");
2392            }
2393            if built_tools.contains("rust-analyzer") {
2394                cmd.arg("RustAnalyzerGroup.wixobj");
2395            }
2396            if built_tools.contains("rust-docs") {
2397                cmd.arg("DocsGroup.wixobj");
2398            }
2399
2400            if target.is_windows_gnu() || target.is_windows_gnullvm() {
2401                cmd.arg("GccGroup.wixobj");
2402            }
2403            // ICE57 wrongly complains about the shortcuts
2404            cmd.arg("-sice:ICE57");
2405
2406            let _time = timeit(builder);
2407            cmd.run(builder);
2408
2409            if !builder.config.dry_run() {
2410                t!(move_file(exe.join(&filename), distdir(builder).join(&filename)));
2411            }
2412        }
2413    }
2414
2415    fn metadata(&self) -> Option<StepMetadata> {
2416        Some(StepMetadata::dist("extended", self.target).built_by(self.build_compiler))
2417    }
2418}
2419
2420fn add_env(
2421    builder: &Builder<'_>,
2422    cmd: &mut BootstrapCommand,
2423    target: TargetSelection,
2424    built_tools: &HashSet<&'static str>,
2425) {
2426    let mut parts = builder.version.split('.');
2427    cmd.env("CFG_RELEASE_INFO", builder.rust_version())
2428        .env("CFG_RELEASE_NUM", &builder.version)
2429        .env("CFG_RELEASE", builder.rust_release())
2430        .env("CFG_VER_MAJOR", parts.next().unwrap())
2431        .env("CFG_VER_MINOR", parts.next().unwrap())
2432        .env("CFG_VER_PATCH", parts.next().unwrap())
2433        .env("CFG_VER_BUILD", "0") // just needed to build
2434        .env("CFG_PACKAGE_VERS", builder.rust_package_vers())
2435        .env("CFG_PACKAGE_NAME", pkgname(builder, "rust"))
2436        .env("CFG_BUILD", target.triple)
2437        .env("CFG_CHANNEL", &builder.config.channel);
2438
2439    if target.is_windows_gnullvm() {
2440        cmd.env("CFG_MINGW", "1").env("CFG_ABI", "LLVM");
2441    } else if target.is_windows_gnu() {
2442        cmd.env("CFG_MINGW", "1").env("CFG_ABI", "GNU");
2443    } else {
2444        cmd.env("CFG_MINGW", "0").env("CFG_ABI", "MSVC");
2445    }
2446
2447    // ensure these variables are defined
2448    let mut define_optional_tool = |tool_name: &str, env_name: &str| {
2449        cmd.env(env_name, if built_tools.contains(tool_name) { "1" } else { "0" });
2450    };
2451    define_optional_tool("rustfmt", "CFG_RUSTFMT");
2452    define_optional_tool("clippy", "CFG_CLIPPY");
2453    define_optional_tool("miri", "CFG_MIRI");
2454    define_optional_tool("rust-analyzer", "CFG_RA");
2455}
2456
2457fn install_llvm_file(
2458    builder: &Builder<'_>,
2459    source: &Path,
2460    destination: &Path,
2461    install_symlink: bool,
2462) {
2463    if builder.config.dry_run() {
2464        return;
2465    }
2466
2467    if source.is_symlink() {
2468        // If we have a symlink like libLLVM-18.so -> libLLVM.so.18.1, install the target of the
2469        // symlink, which is what will actually get loaded at runtime.
2470        builder.install(&t!(fs::canonicalize(source)), destination, FileType::NativeLibrary);
2471
2472        let full_dest = destination.join(source.file_name().unwrap());
2473        if install_symlink {
2474            // For download-ci-llvm, also install the symlink, to match what LLVM does. Using a
2475            // symlink is fine here, as this is not a rustup component.
2476            builder.copy_link(source, &full_dest, FileType::NativeLibrary);
2477        } else {
2478            // Otherwise, replace the symlink with an equivalent linker script. This is used when
2479            // projects like miri link against librustc_driver.so. We don't use a symlink, as
2480            // these are not allowed inside rustup components.
2481            let link = t!(fs::read_link(source));
2482            let mut linker_script = t!(fs::File::create(full_dest));
2483            t!(write!(linker_script, "INPUT({})\n", link.display()));
2484
2485            // We also want the linker script to have the same mtime as the source, otherwise it
2486            // can trigger rebuilds.
2487            let meta = t!(fs::metadata(source));
2488            if let Ok(mtime) = meta.modified() {
2489                t!(linker_script.set_modified(mtime));
2490            }
2491        }
2492    } else {
2493        builder.install(source, destination, FileType::NativeLibrary);
2494    }
2495}
2496
2497/// Maybe add LLVM object files to the given destination lib-dir. Allows either static or dynamic linking.
2498///
2499/// Returns whether the files were actually copied.
2500#[cfg_attr(
2501    feature = "tracing",
2502    instrument(
2503        level = "trace",
2504        name = "maybe_install_llvm",
2505        skip_all,
2506        fields(target = ?target, dst_libdir = ?dst_libdir, install_symlink = install_symlink),
2507    ),
2508)]
2509fn maybe_install_llvm(
2510    builder: &Builder<'_>,
2511    llvm: &LlvmBuildStatus,
2512    target: TargetSelection,
2513    dst_libdir: &Path,
2514    install_symlink: bool,
2515) -> bool {
2516    // If the LLVM was externally provided, then we don't currently copy
2517    // artifacts into the sysroot. This is not necessarily the right
2518    // choice (in particular, it will require the LLVM dylib to be in
2519    // the linker's load path at runtime), but the common use case for
2520    // external LLVMs is distribution provided LLVMs, and in that case
2521    // they're usually in the standard search path (e.g., /usr/lib) and
2522    // copying them here is going to cause problems as we may end up
2523    // with the wrong files and isn't what distributions want.
2524    //
2525    // This behavior may be revisited in the future though.
2526    //
2527    // NOTE: this intentionally doesn't use `is_rust_llvm`; whether this is patched or not doesn't matter,
2528    // we only care if the shared object itself is managed by bootstrap.
2529    //
2530    // If the LLVM is coming from ourselves (just from CI) though, we
2531    // still want to install it, as it otherwise won't be available.
2532
2533    let is_system_llvm = llvm.llvm_output().kind() == LlvmKind::External;
2534    if is_system_llvm {
2535        trace!("system LLVM requested, no install");
2536        return false;
2537    }
2538
2539    // On macOS, rustc (and LLVM tools) link to an unversioned libLLVM.dylib
2540    // instead of libLLVM-11-rust-....dylib, as on linux. It's not entirely
2541    // clear why this is the case, though. llvm-config will emit the versioned
2542    // paths and we don't want those in the sysroot (as we're expecting
2543    // unversioned paths).
2544    if target.contains("apple-darwin") && llvm.llvm_output().link_shared() {
2545        let src_libdir = llvm.llvm_output().root_dir().join("lib");
2546        let llvm_dylib_path = src_libdir.join("libLLVM.dylib");
2547        if llvm_dylib_path.exists() {
2548            builder.install(&llvm_dylib_path, dst_libdir, FileType::NativeLibrary);
2549
2550            if install_symlink {
2551                let major = llvm::get_llvm_version_major(builder, &builder.host_llvm_config());
2552                let versioned_name = match &builder.config.llvm_version_suffix {
2553                    Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.dylib"),
2554                    None => {
2555                        // dev builds use `-rust-dev`, while release-channel builds include the Rust version.
2556                        if builder.config.channel == "dev" {
2557                            format!("libLLVM-{major}-rust-dev.dylib")
2558                        } else {
2559                            format!(
2560                                "libLLVM-{major}-rust-{}-{}.dylib",
2561                                builder.version, builder.config.channel
2562                            )
2563                        }
2564                    }
2565                };
2566                t!(builder.symlink_file("libLLVM.dylib", dst_libdir.join(versioned_name)));
2567            }
2568        }
2569        !builder.config.dry_run()
2570    } else if let llvm::LlvmBuildStatus::AlreadyBuilt(llvm_output) = llvm {
2571        trace!("LLVM already built, installing LLVM files");
2572
2573        let host_llvm = builder.ensure(llvm::Llvm { target: builder.host_target });
2574        let mut cmd = command(host_llvm.llvm_config());
2575        cmd.cached();
2576        cmd.arg("--libfiles");
2577        builder.do_if_verbose(|| println!("running {cmd:?}"));
2578        let files = cmd.run_capture_stdout(builder).stdout();
2579        let build_llvm_out = host_llvm.root_dir();
2580        let target_llvm_out = llvm_output.root_dir();
2581        for file in files.trim_end().split(' ') {
2582            // If we're not using a custom LLVM, make sure we package for the target.
2583            let file = if let Ok(relative_path) = Path::new(file).strip_prefix(build_llvm_out) {
2584                target_llvm_out.join(relative_path)
2585            } else {
2586                PathBuf::from(file)
2587            };
2588            install_llvm_file(builder, &file, dst_libdir, install_symlink);
2589        }
2590        !builder.config.dry_run()
2591    } else {
2592        false
2593    }
2594}
2595
2596/// Maybe add libLLVM.so to the target lib-dir for linking.
2597#[cfg_attr(
2598    feature = "tracing",
2599    instrument(
2600        level = "trace",
2601        name = "maybe_install_llvm_target",
2602        skip_all,
2603        fields(
2604            target = ?target,
2605            sysroot = ?sysroot,
2606        ),
2607    ),
2608)]
2609pub fn maybe_install_llvm_target(builder: &Builder<'_>, target: TargetSelection, sysroot: &Path) {
2610    let dst_libdir = sysroot.join("lib/rustlib").join(target).join("lib");
2611
2612    // We need to figure out the link mode from a LLVM, if it is provided, but without forcing it
2613    // to be built if it isn't.
2614    let config = get_llvm_build_status(builder, target);
2615
2616    // We do not need to copy LLVM files into the sysroot if it is not
2617    // dynamically linked; it is already included into librustc_llvm
2618    // statically.
2619    if config.llvm_output().link_shared() {
2620        maybe_install_llvm(builder, &config, target, &dst_libdir, false);
2621    }
2622}
2623
2624/// Maybe add libLLVM.so to the runtime lib-dir for rustc itself.
2625#[cfg_attr(
2626    feature = "tracing",
2627    instrument(
2628        level = "trace",
2629        name = "maybe_install_llvm_runtime",
2630        skip_all,
2631        fields(
2632            target = ?target,
2633            sysroot = ?sysroot,
2634        ),
2635    ),
2636)]
2637pub fn maybe_install_llvm_runtime(builder: &Builder<'_>, target: TargetSelection, sysroot: &Path) {
2638    let dst_libdir = sysroot.join(builder.libdir_relative(Compiler::new(1, target)));
2639
2640    // We need to figure out the link mode from a LLVM, if it is provided, but without forcing it
2641    // to be built if it isn't.
2642    let config = get_llvm_build_status(builder, target);
2643
2644    // We do not need to copy LLVM files into the sysroot if it is not
2645    // dynamically linked; it is already included into librustc_llvm
2646    // statically.
2647    if config.llvm_output().link_shared() {
2648        maybe_install_llvm(builder, &config, target, &dst_libdir, false);
2649
2650        // To workaround lack of rpath on Windows, we bundle another copy of
2651        // the LLVM DLL to make rust-lld and llvm-tools work when `sysroot/bin`
2652        //  is missing from PATH, i.e. when they not launched by rustc.
2653        if target.triple.contains("windows") {
2654            let dst_libdir = sysroot.join("lib/rustlib").join(target).join("bin");
2655            maybe_install_llvm(builder, &config, target, &dst_libdir, false);
2656        }
2657    }
2658}
2659
2660#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2661pub struct LlvmTools {
2662    pub target: TargetSelection,
2663}
2664
2665impl CommandLineStep for LlvmTools {
2666    type Output = Option<GeneratedTarball>;
2667    const IS_HOST: bool = true;
2668
2669    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2670        let mut run = run.alias("llvm-tools");
2671        for tool in LLVM_TOOLS {
2672            run = run.alias(tool);
2673        }
2674
2675        run
2676    }
2677
2678    fn is_default_step(builder: &Builder<'_>) -> bool {
2679        should_build_extended_tool(builder, "llvm-tools")
2680    }
2681
2682    fn make_run(run: RunConfig<'_>) {
2683        run.builder.ensure(LlvmTools { target: run.target });
2684    }
2685
2686    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2687        fn tools_to_install(paths: &[PathBuf]) -> Vec<&'static str> {
2688            let mut tools = vec![];
2689
2690            for path in paths {
2691                let path = path.to_str().unwrap();
2692
2693                // Include all tools if path is 'llvm-tools'.
2694                if path == "llvm-tools" {
2695                    return LLVM_TOOLS.to_owned();
2696                }
2697
2698                for tool in LLVM_TOOLS {
2699                    if path == *tool {
2700                        tools.push(*tool);
2701                    }
2702                }
2703            }
2704
2705            // If no specific tool is requested, include all tools.
2706            if tools.is_empty() {
2707                tools = LLVM_TOOLS.to_owned();
2708            }
2709
2710            tools
2711        }
2712
2713        let target = self.target;
2714
2715        let llvm_output = builder.ensure(crate::core::build_steps::llvm::Llvm { target });
2716
2717        // Run only if a custom llvm-config is not used
2718        if llvm_output.kind() == LlvmKind::External {
2719            builder.info(&format!("Skipping LlvmTools ({target}): external LLVM"));
2720            return None;
2721        }
2722
2723        if !builder.config.dry_run() {
2724            builder.require_submodule("src/llvm-project", None);
2725        }
2726
2727        let mut tarball = Tarball::new(builder, "llvm-tools", &target.triple);
2728        tarball.set_overlay(OverlayKind::Llvm);
2729        tarball.is_preview(true);
2730
2731        if builder.config.llvm_tools_enabled {
2732            // Prepare the image directory
2733            let src_bindir = llvm_output.root_dir().join("bin");
2734            let dst_bindir = format!("lib/rustlib/{}/bin", target.triple);
2735            for tool in tools_to_install(&builder.paths) {
2736                let exe = src_bindir.join(exe(tool, target));
2737                // When using `download-ci-llvm`, some of the tools may not exist, so skip trying to copy them.
2738                if !exe.exists() && llvm_output.kind() == LlvmKind::DownloadedFromCi {
2739                    eprintln!("{} does not exist; skipping copy", exe.display());
2740                    continue;
2741                }
2742
2743                tarball.add_file(&exe, &dst_bindir, FileType::Executable);
2744            }
2745        }
2746
2747        // Copy libLLVM.so to the target lib dir as well, so the RPATH like
2748        // `$ORIGIN/../lib` can find it. It may also be used as a dependency
2749        // of `rustc-dev` to support the inherited `-lLLVM` when using the
2750        // compiler libraries.
2751        maybe_install_llvm_target(builder, target, tarball.image_dir());
2752
2753        Some(tarball.generate())
2754    }
2755}
2756
2757/// Distributes the `llvm-bitcode-linker` tool so that it can be used by a compiler whose host
2758/// is `target`.
2759#[derive(Debug, Clone, Hash, PartialEq, Eq)]
2760pub struct LlvmBitcodeLinker {
2761    /// The linker will be compiled by this compiler.
2762    pub build_compiler: Compiler,
2763    /// The linker will by usable by rustc on this host.
2764    pub target: TargetSelection,
2765}
2766
2767impl CommandLineStep for LlvmBitcodeLinker {
2768    type Output = Option<GeneratedTarball>;
2769    const IS_HOST: bool = true;
2770
2771    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2772        run.alias("llvm-bitcode-linker")
2773    }
2774
2775    fn is_default_step(builder: &Builder<'_>) -> bool {
2776        should_build_extended_tool(builder, "llvm-bitcode-linker")
2777    }
2778
2779    fn make_run(run: RunConfig<'_>) {
2780        run.builder.ensure(LlvmBitcodeLinker {
2781            build_compiler: tool::LlvmBitcodeLinker::get_build_compiler_for_target(
2782                run.builder,
2783                run.target,
2784            ),
2785            target: run.target,
2786        });
2787    }
2788
2789    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2790        let target = self.target;
2791
2792        let llbc_linker = builder
2793            .ensure(tool::LlvmBitcodeLinker::from_build_compiler(self.build_compiler, target));
2794
2795        let self_contained_bin_dir = format!("lib/rustlib/{}/bin/self-contained", target.triple);
2796
2797        // Prepare the image directory
2798        let mut tarball = Tarball::new(builder, "llvm-bitcode-linker", &target.triple);
2799        tarball.set_overlay(OverlayKind::LlvmBitcodeLinker);
2800        tarball.is_preview(true);
2801
2802        tarball.add_file(&llbc_linker.tool_path, self_contained_bin_dir, FileType::Executable);
2803
2804        Some(tarball.generate())
2805    }
2806}
2807
2808/// Distributes the `enzyme` library so that it can be used by a compiler whose host
2809/// is `target`.
2810#[derive(Debug, Clone, Hash, PartialEq, Eq)]
2811pub struct Enzyme {
2812    /// Enzyme will by usable by rustc on this host.
2813    pub target: TargetSelection,
2814}
2815
2816impl CommandLineStep for Enzyme {
2817    type Output = Option<GeneratedTarball>;
2818    const IS_HOST: bool = true;
2819
2820    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2821        run.alias("enzyme")
2822    }
2823
2824    fn is_default_step(builder: &Builder<'_>) -> bool {
2825        builder.config.llvm_enzyme
2826    }
2827
2828    fn make_run(run: RunConfig<'_>) {
2829        run.builder.ensure(Enzyme { target: run.target });
2830    }
2831
2832    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2833        // This prevents Enzyme from being built for "dist"
2834        // or "install" on the stable/beta channels. It is not yet stable and
2835        // should not be included.
2836        if !builder.sess.unstable_features() {
2837            return None;
2838        }
2839
2840        let target = self.target;
2841
2842        let enzyme = builder.ensure(llvm::Enzyme { target });
2843
2844        let target_libdir = format!("lib/rustlib/{}/lib", target.triple);
2845
2846        // Prepare the image directory
2847        let mut tarball = Tarball::new(builder, "enzyme", &target.triple);
2848        tarball.set_overlay(OverlayKind::Enzyme);
2849        tarball.is_preview(true);
2850
2851        tarball.add_file(enzyme.enzyme_path(), target_libdir, FileType::NativeLibrary);
2852
2853        Some(tarball.generate())
2854    }
2855}
2856
2857#[derive(Debug, Clone, Hash, PartialEq, Eq)]
2858pub struct Offload {
2859    pub target: TargetSelection,
2860}
2861
2862impl CommandLineStep for Offload {
2863    type Output = Option<GeneratedTarball>;
2864    const IS_HOST: bool = true;
2865
2866    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2867        run.alias("offload")
2868    }
2869
2870    fn is_default_step(builder: &Builder<'_>) -> bool {
2871        builder.config.llvm_offload
2872    }
2873
2874    fn make_run(run: RunConfig<'_>) {
2875        run.builder.ensure(Offload { target: run.target });
2876    }
2877
2878    fn run(self, builder: &Builder<'_>) -> Self::Output {
2879        if !builder.unstable_features() {
2880            return None;
2881        }
2882
2883        let target = self.target;
2884
2885        let omp_offload = builder.ensure(llvm::OmpOffload { target });
2886        let rust_offload = builder.ensure(llvm::RustOffload { target });
2887
2888        if builder.config.dry_run() {
2889            return None;
2890        }
2891
2892        let target_libdir = PathBuf::from(format!("lib/rustlib/{}/lib", target.triple));
2893
2894        let mut tarball = Tarball::new(builder, "offload", &target.triple);
2895        tarball.set_overlay(OverlayKind::Offload);
2896        tarball.is_preview(true);
2897
2898        let omp_offload_libdir = omp_offload.lib_dir();
2899
2900        for path in omp_offload.artifact_paths_with_symlink_targets() {
2901            let relative = t!(path.strip_prefix(omp_offload_libdir));
2902            let destdir = target_libdir.join(relative.parent().unwrap());
2903
2904            tarball.add_file(path, destdir, FileType::NativeLibrary);
2905        }
2906
2907        tarball.add_file(rust_offload.rust_offload_path(), target_libdir, FileType::NativeLibrary);
2908
2909        Some(tarball.generate())
2910    }
2911}
2912
2913/// Tarball intended for internal consumption to ease rustc/std development.
2914///
2915/// Should not be considered stable by end users.
2916///
2917/// In practice, this is the tarball that gets downloaded and used by
2918/// `llvm.download-ci-llvm`.
2919///
2920/// (Don't confuse this with [`RustcDev`], with a `c`!)
2921#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2922pub struct RustDev {
2923    pub target: TargetSelection,
2924}
2925
2926impl CommandLineStep for RustDev {
2927    type Output = Option<GeneratedTarball>;
2928    const IS_HOST: bool = true;
2929
2930    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2931        run.alias("rust-dev")
2932    }
2933
2934    fn is_default_step(_builder: &Builder<'_>) -> bool {
2935        true
2936    }
2937
2938    fn make_run(run: RunConfig<'_>) {
2939        run.builder.ensure(RustDev { target: run.target });
2940    }
2941
2942    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2943        let target = self.target;
2944
2945        /* run only if llvm-config isn't used */
2946        if let Some(config) = builder.config.target_config.get(&target)
2947            && let Some(ref _s) = config.llvm_config
2948        {
2949            builder.info(&format!("Skipping RustDev ({target}): external LLVM"));
2950            return None;
2951        }
2952
2953        if !builder.config.dry_run() {
2954            builder.require_submodule("src/llvm-project", None);
2955        }
2956
2957        let mut tarball = Tarball::new(builder, "rust-dev", &target.triple);
2958        tarball.set_overlay(OverlayKind::Llvm);
2959        // LLVM requires a shared object symlink to exist on some platforms.
2960        tarball.permit_symlinks(true);
2961
2962        let llvm_output = builder.ensure(crate::core::build_steps::llvm::Llvm { target });
2963
2964        let src_bindir = llvm_output.root_dir().join("bin");
2965        // If updating this, you likely want to change
2966        // src/bootstrap/download-ci-llvm-stamp as well, otherwise local users
2967        // will not pick up the extra file until LLVM gets bumped.
2968        // We should include all the build artifacts obtained from a source build,
2969        // so that you can use the downloadable LLVM as if you’ve just run a full source build.
2970        if src_bindir.exists() {
2971            for entry in walkdir::WalkDir::new(&src_bindir) {
2972                let entry = t!(entry);
2973                if entry.file_type().is_file() && !entry.path_is_symlink() {
2974                    let name = entry.file_name().to_str().unwrap();
2975                    tarball.add_file(src_bindir.join(name), "bin", FileType::Executable);
2976                }
2977            }
2978        }
2979
2980        if builder.config.lld_enabled {
2981            // We want to package `lld` to use it with `download-ci-llvm`.
2982            let lld_out = builder.ensure(crate::core::build_steps::llvm::Lld { target });
2983
2984            // We don't build LLD on some platforms, so only add it if it exists
2985            let lld_path = lld_out.join("bin").join(exe("lld", target));
2986            if lld_path.exists() {
2987                tarball.add_file(&lld_path, "bin", FileType::Executable);
2988            }
2989        }
2990
2991        let filecheck = builder.ensure(llvm::FileCheck { target });
2992        tarball.add_file(filecheck, "bin", FileType::Executable);
2993
2994        // Copy the include directory as well; needed mostly to build
2995        // librustc_llvm properly (e.g., llvm-config.h is in here). But also
2996        // just broadly useful to be able to link against the bundled LLVM.
2997        tarball.add_dir(llvm_output.root_dir().join("include"), "include");
2998
2999        // Copy libLLVM.so to the target lib dir as well, so the RPATH like
3000        // `$ORIGIN/../lib` can find it. It may also be used as a dependency
3001        // of `rustc-dev` to support the inherited `-lLLVM` when using the
3002        // compiler libraries.
3003        let dst_libdir = tarball.image_dir().join("lib");
3004
3005        let config = get_llvm_build_status(builder, target);
3006        maybe_install_llvm(builder, &config, target, &dst_libdir, true);
3007
3008        // Store the link type, so that it can be read by bootstrap after the archive is downloaded
3009        let link_type = if llvm_output.link_shared() { "dynamic" } else { "static" };
3010        t!(std::fs::write(tarball.image_dir().join(LLVM_CI_LINK_TYPE_PATH), link_type), dst_libdir);
3011
3012        // Copy the `compiler-rt` source, so that `library/profiler_builtins`
3013        // can potentially use it to build the profiler runtime without needing
3014        // to check out the LLVM submodule.
3015        copy_src_dirs(
3016            builder,
3017            &builder.src.join("src").join("llvm-project"),
3018            &["compiler-rt"],
3019            // The test subdirectory is much larger than the rest of the source,
3020            // and we currently don't use these test files anyway.
3021            &["compiler-rt/test"],
3022            tarball.image_dir(),
3023        );
3024
3025        Some(tarball.generate())
3026    }
3027}
3028
3029/// Tarball intended for internal consumption to ease rustc/std development.
3030///
3031/// It only packages the binaries that were already compiled when bootstrap itself was built.
3032///
3033/// Should not be considered stable by end users.
3034#[derive(Clone, Debug, Eq, Hash, PartialEq)]
3035pub struct Bootstrap {
3036    target: TargetSelection,
3037}
3038
3039impl CommandLineStep for Bootstrap {
3040    type Output = Option<GeneratedTarball>;
3041
3042    const IS_HOST: bool = true;
3043
3044    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3045        run.alias("bootstrap")
3046    }
3047
3048    fn make_run(run: RunConfig<'_>) {
3049        run.builder.ensure(Bootstrap { target: run.target });
3050    }
3051
3052    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
3053        let target = self.target;
3054
3055        let tarball = Tarball::new(builder, "bootstrap", &target.triple);
3056
3057        let bootstrap_outdir = &builder.bootstrap_out;
3058        for file in &["bootstrap", "rustc", "rustdoc"] {
3059            tarball.add_file(
3060                bootstrap_outdir.join(exe(file, target)),
3061                "bootstrap/bin",
3062                FileType::Executable,
3063            );
3064        }
3065
3066        Some(tarball.generate())
3067    }
3068
3069    fn metadata(&self) -> Option<StepMetadata> {
3070        Some(StepMetadata::dist("bootstrap", self.target))
3071    }
3072}
3073
3074/// Tarball containing a prebuilt version of the build-manifest tool, intended to be used by the
3075/// release process to avoid cloning the monorepo and building stuff.
3076///
3077/// Should not be considered stable by end users.
3078#[derive(Clone, Debug, Eq, Hash, PartialEq)]
3079pub struct BuildManifest {
3080    target: TargetSelection,
3081}
3082
3083impl CommandLineStep for BuildManifest {
3084    type Output = GeneratedTarball;
3085
3086    const IS_HOST: bool = true;
3087
3088    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3089        run.alias("build-manifest")
3090    }
3091
3092    fn make_run(run: RunConfig<'_>) {
3093        run.builder.ensure(BuildManifest { target: run.target });
3094    }
3095
3096    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
3097        // FIXME: Should BuildManifest actually be built for `self.target`?
3098        // Today CI only builds this step where that matches the host_target so it doesn't matter
3099        // today.
3100        let build_manifest =
3101            builder.ensure(tool::BuildManifest::new(builder, builder.config.host_target));
3102
3103        let tarball = Tarball::new(builder, "build-manifest", &self.target.triple);
3104        tarball.add_file(&build_manifest.tool_path, "bin", FileType::Executable);
3105        tarball.generate()
3106    }
3107
3108    fn metadata(&self) -> Option<StepMetadata> {
3109        Some(StepMetadata::dist("build-manifest", self.target))
3110    }
3111}
3112
3113/// Tarball containing artifacts necessary to reproduce the build of rustc.
3114///
3115/// Currently this is the PGO (and possibly BOLT) profile data.
3116///
3117/// Should not be considered stable by end users.
3118#[derive(Clone, Debug, Eq, Hash, PartialEq)]
3119pub struct ReproducibleArtifacts {
3120    target: TargetSelection,
3121}
3122
3123impl CommandLineStep for ReproducibleArtifacts {
3124    type Output = Option<GeneratedTarball>;
3125    const IS_HOST: bool = true;
3126
3127    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3128        run.alias("reproducible-artifacts")
3129    }
3130
3131    fn is_default_step(_builder: &Builder<'_>) -> bool {
3132        true
3133    }
3134
3135    fn make_run(run: RunConfig<'_>) {
3136        run.builder.ensure(ReproducibleArtifacts { target: run.target });
3137    }
3138
3139    fn run(self, builder: &Builder<'_>) -> Self::Output {
3140        let mut added_anything = false;
3141        let tarball = Tarball::new(builder, "reproducible-artifacts", &self.target.triple);
3142
3143        let pgo_profiles = [
3144            &builder.config.rust_pgo.use_profile,
3145            &builder.config.llvm_pgo.use_profile,
3146            &builder.config.rustdoc_pgo.use_profile,
3147            &builder.config.cargo_pgo.use_profile,
3148            &builder.config.clippy_pgo.use_profile,
3149            &builder.config.cranelift_pgo.use_profile,
3150        ];
3151        for profile in pgo_profiles {
3152            if let Some(path) = profile.as_ref() {
3153                tarball.add_file(path, ".", FileType::Regular);
3154                added_anything = true;
3155            }
3156        }
3157        for profile in &builder.config.reproducible_artifacts {
3158            tarball.add_file(profile, ".", FileType::Regular);
3159            added_anything = true;
3160        }
3161        if added_anything { Some(tarball.generate()) } else { None }
3162    }
3163
3164    fn metadata(&self) -> Option<StepMetadata> {
3165        Some(StepMetadata::dist("reproducible-artifacts", self.target))
3166    }
3167}
3168
3169/// Tarball containing a prebuilt version of the libgccjit library,
3170/// needed as a dependency for the GCC codegen backend (similarly to the LLVM
3171/// backend needing a prebuilt libLLVM).
3172///
3173/// This component is used for `download-ci-gcc`.
3174#[derive(Clone, Debug, Eq, Hash, PartialEq)]
3175pub struct GccDev {
3176    target: TargetSelection,
3177}
3178
3179impl CommandLineStep for GccDev {
3180    type Output = GeneratedTarball;
3181
3182    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3183        run.alias("gcc-dev")
3184    }
3185
3186    fn make_run(run: RunConfig<'_>) {
3187        run.builder.ensure(GccDev { target: run.target });
3188    }
3189
3190    fn run(self, builder: &Builder<'_>) -> Self::Output {
3191        let tarball = Tarball::new(builder, "gcc-dev", &self.target.triple);
3192        let output = builder
3193            .ensure(super::gcc::Gcc { target_pair: GccTargetPair::for_native_build(self.target) });
3194        tarball.add_file(output.libgccjit(), "lib", FileType::NativeLibrary);
3195        tarball.generate()
3196    }
3197
3198    fn metadata(&self) -> Option<StepMetadata> {
3199        Some(StepMetadata::dist("gcc-dev", self.target))
3200    }
3201}
3202
3203/// Tarball containing a libgccjit dylib,
3204/// needed as a dependency for the GCC codegen backend (similarly to the LLVM
3205/// backend needing a prebuilt libLLVM).
3206///
3207/// This component is used for distribution through rustup.
3208#[derive(Clone, Debug, Eq, Hash, PartialEq)]
3209pub struct Gcc {
3210    host: TargetSelection,
3211    target: TargetSelection,
3212}
3213
3214impl CommandLineStep for Gcc {
3215    type Output = Option<GeneratedTarball>;
3216
3217    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3218        run.alias("gcc")
3219    }
3220
3221    fn make_run(run: RunConfig<'_>) {
3222        // GCC is always built for a target pair, (host, target).
3223        // We do not yet support cross-compilation here, so the host target is always inferred to
3224        // be the bootstrap host target.
3225        run.builder.ensure(Gcc { host: run.builder.host_target, target: run.target });
3226    }
3227
3228    fn run(self, builder: &Builder<'_>) -> Self::Output {
3229        // This prevents gcc from being built for "dist"
3230        // or "install" on the stable/beta channels. It is not yet stable and
3231        // should not be included.
3232        if !builder.sess.unstable_features() {
3233            return None;
3234        }
3235
3236        let host = self.host;
3237        let target = self.target;
3238        if host != "x86_64-unknown-linux-gnu" {
3239            builder.info(&format!("host target `{host}` not supported by gcc. skipping"));
3240            return None;
3241        }
3242
3243        if builder.config.is_running_on_ci() {
3244            assert_eq!(
3245                builder.config.gcc_ci_mode,
3246                GccCiMode::BuildLocally,
3247                "Cannot use gcc.download-ci-gcc when distributing GCC on CI"
3248            );
3249        }
3250
3251        // We need the GCC sources to build GCC and also to add its license and README
3252        // files to the tarball
3253        builder.require_submodule(
3254            "src/gcc",
3255            Some("The src/gcc submodule is required for disting libgccjit"),
3256        );
3257
3258        let target_pair = GccTargetPair::for_target_pair(host, target);
3259        let libgccjit = builder.ensure(super::gcc::Gcc { target_pair });
3260
3261        // We have to include the target name in the component name, so that rustup can somehow
3262        // distinguish that there are multiple gcc components on a given host target.
3263        // So the tarball includes the target name.
3264        let mut tarball = Tarball::new(builder, &format!("gcc-{target}"), &host.triple);
3265        tarball.set_overlay(OverlayKind::Gcc);
3266        tarball.is_preview(true);
3267        tarball.add_legal_and_readme_to("share/doc/gcc");
3268
3269        // The path where to put libgccjit is determined by GccDylibSet.
3270        // However, it requires a Compiler to figure out the path to the codegen backend sysroot.
3271        // We don't really have any compiler here, because we just build libgccjit.
3272        // So we duplicate the logic for determining the CG sysroot here.
3273        let cg_dir = PathBuf::from(format!("lib/rustlib/{host}/codegen-backends"));
3274
3275        // This returns the path to the actual file, but here we need its parent
3276        let rel_libgccjit_path = libgccjit_path_relative_to_cg_dir(&target_pair, &libgccjit);
3277        let path = cg_dir.join(rel_libgccjit_path.parent().unwrap());
3278
3279        tarball.add_file(libgccjit.libgccjit(), path, FileType::NativeLibrary);
3280        Some(tarball.generate())
3281    }
3282
3283    fn metadata(&self) -> Option<StepMetadata> {
3284        Some(StepMetadata::dist(
3285            "gcc",
3286            TargetSelection::from_user(&format!("({}, {})", self.host, self.target)),
3287        ))
3288    }
3289}