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
20use crate::core::build_steps::doc::DocumentationFormat;
21use crate::core::build_steps::tool::{self, Tool};
22use crate::core::build_steps::vendor::default_paths_to_vendor;
23use crate::core::build_steps::{compile, llvm};
24use crate::core::builder::{Builder, Kind, RunConfig, ShouldRun, Step};
25use crate::core::config::TargetSelection;
26use crate::utils::build_stamp::{self, BuildStamp};
27use crate::utils::channel::{self, Info};
28use crate::utils::exec::{BootstrapCommand, command};
29use crate::utils::helpers::{
30    exe, is_dylib, move_file, t, target_supports_cranelift_backend, timeit,
31};
32use crate::utils::tarball::{GeneratedTarball, OverlayKind, Tarball};
33use crate::{Compiler, DependencyType, LLVM_TOOLS, Mode};
34
35pub fn pkgname(builder: &Builder<'_>, component: &str) -> String {
36    format!("{}-{}", component, builder.rust_package_vers())
37}
38
39pub(crate) fn distdir(builder: &Builder<'_>) -> PathBuf {
40    builder.out.join("dist")
41}
42
43pub fn tmpdir(builder: &Builder<'_>) -> PathBuf {
44    builder.out.join("tmp/dist")
45}
46
47fn should_build_extended_tool(builder: &Builder<'_>, tool: &str) -> bool {
48    if !builder.config.extended {
49        return false;
50    }
51    builder.config.tools.as_ref().is_none_or(|tools| tools.contains(tool))
52}
53
54#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
55pub struct Docs {
56    pub host: TargetSelection,
57}
58
59impl Step for Docs {
60    type Output = Option<GeneratedTarball>;
61    const DEFAULT: bool = true;
62
63    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
64        let default = run.builder.config.docs;
65        run.alias("rust-docs").default_condition(default)
66    }
67
68    fn make_run(run: RunConfig<'_>) {
69        run.builder.ensure(Docs { host: run.target });
70    }
71
72    /// Builds the `rust-docs` installer component.
73    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
74        let host = self.host;
75        builder.default_doc(&[]);
76
77        let dest = "share/doc/rust/html";
78
79        let mut tarball = Tarball::new(builder, "rust-docs", &host.triple);
80        tarball.set_product_name("Rust Documentation");
81        tarball.add_bulk_dir(builder.doc_out(host), dest);
82        tarball.add_file(builder.src.join("src/doc/robots.txt"), dest, 0o644);
83        Some(tarball.generate())
84    }
85}
86
87#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
88pub struct JsonDocs {
89    pub host: TargetSelection,
90}
91
92impl Step for JsonDocs {
93    type Output = Option<GeneratedTarball>;
94    const DEFAULT: bool = true;
95
96    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
97        let default = run.builder.config.docs;
98        run.alias("rust-docs-json").default_condition(default)
99    }
100
101    fn make_run(run: RunConfig<'_>) {
102        run.builder.ensure(JsonDocs { host: run.target });
103    }
104
105    /// Builds the `rust-docs-json` installer component.
106    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
107        let host = self.host;
108        builder.ensure(crate::core::build_steps::doc::Std::new(
109            builder.top_stage,
110            host,
111            DocumentationFormat::Json,
112        ));
113
114        let dest = "share/doc/rust/json";
115
116        let mut tarball = Tarball::new(builder, "rust-docs-json", &host.triple);
117        tarball.set_product_name("Rust Documentation In JSON Format");
118        tarball.is_preview(true);
119        tarball.add_bulk_dir(builder.json_doc_out(host), dest);
120        Some(tarball.generate())
121    }
122}
123
124#[derive(Debug, Clone, Hash, PartialEq, Eq)]
125pub struct RustcDocs {
126    pub host: TargetSelection,
127}
128
129impl Step for RustcDocs {
130    type Output = Option<GeneratedTarball>;
131    const DEFAULT: bool = true;
132    const ONLY_HOSTS: bool = true;
133
134    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
135        let builder = run.builder;
136        run.alias("rustc-docs").default_condition(builder.config.compiler_docs)
137    }
138
139    fn make_run(run: RunConfig<'_>) {
140        run.builder.ensure(RustcDocs { host: run.target });
141    }
142
143    /// Builds the `rustc-docs` installer component.
144    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
145        let host = self.host;
146        builder.default_doc(&[]);
147
148        let mut tarball = Tarball::new(builder, "rustc-docs", &host.triple);
149        tarball.set_product_name("Rustc Documentation");
150        tarball.add_bulk_dir(builder.compiler_doc_out(host), "share/doc/rust/html/rustc");
151        Some(tarball.generate())
152    }
153}
154
155fn find_files(files: &[&str], path: &[PathBuf]) -> Vec<PathBuf> {
156    let mut found = Vec::with_capacity(files.len());
157
158    for file in files {
159        let file_path = path.iter().map(|dir| dir.join(file)).find(|p| p.exists());
160
161        if let Some(file_path) = file_path {
162            found.push(file_path);
163        } else {
164            panic!("Could not find '{file}' in {path:?}");
165        }
166    }
167
168    found
169}
170
171fn make_win_dist(
172    rust_root: &Path,
173    plat_root: &Path,
174    target: TargetSelection,
175    builder: &Builder<'_>,
176) {
177    if builder.config.dry_run() {
178        return;
179    }
180
181    //Ask gcc where it keeps its stuff
182    let mut cmd = command(builder.cc(target));
183    cmd.arg("-print-search-dirs");
184    let gcc_out = cmd.run_capture_stdout(builder).stdout();
185
186    let mut bin_path: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect();
187    let mut lib_path = Vec::new();
188
189    for line in gcc_out.lines() {
190        let idx = line.find(':').unwrap();
191        let key = &line[..idx];
192        let trim_chars: &[_] = &[' ', '='];
193        let value = env::split_paths(line[(idx + 1)..].trim_start_matches(trim_chars));
194
195        if key == "programs" {
196            bin_path.extend(value);
197        } else if key == "libraries" {
198            lib_path.extend(value);
199        }
200    }
201
202    let compiler = if target == "i686-pc-windows-gnu" {
203        "i686-w64-mingw32-gcc.exe"
204    } else if target == "x86_64-pc-windows-gnu" {
205        "x86_64-w64-mingw32-gcc.exe"
206    } else {
207        "gcc.exe"
208    };
209    let target_tools = [compiler, "ld.exe", "dlltool.exe", "libwinpthread-1.dll"];
210    let mut rustc_dlls = vec!["libwinpthread-1.dll"];
211    if target.starts_with("i686-") {
212        rustc_dlls.push("libgcc_s_dw2-1.dll");
213    } else {
214        rustc_dlls.push("libgcc_s_seh-1.dll");
215    }
216
217    // Libraries necessary to link the windows-gnu toolchains.
218    // System libraries will be preferred if they are available (see #67429).
219    let target_libs = [
220        //MinGW libs
221        "libgcc.a",
222        "libgcc_eh.a",
223        "libgcc_s.a",
224        "libm.a",
225        "libmingw32.a",
226        "libmingwex.a",
227        "libstdc++.a",
228        "libiconv.a",
229        "libmoldname.a",
230        "libpthread.a",
231        //Windows import libs
232        //This should contain only the set of libraries necessary to link the standard library.
233        "libadvapi32.a",
234        "libbcrypt.a",
235        "libcomctl32.a",
236        "libcomdlg32.a",
237        "libcredui.a",
238        "libcrypt32.a",
239        "libdbghelp.a",
240        "libgdi32.a",
241        "libimagehlp.a",
242        "libiphlpapi.a",
243        "libkernel32.a",
244        "libmsimg32.a",
245        "libmsvcrt.a",
246        "libntdll.a",
247        "libodbc32.a",
248        "libole32.a",
249        "liboleaut32.a",
250        "libopengl32.a",
251        "libpsapi.a",
252        "librpcrt4.a",
253        "libsecur32.a",
254        "libsetupapi.a",
255        "libshell32.a",
256        "libsynchronization.a",
257        "libuser32.a",
258        "libuserenv.a",
259        "libuuid.a",
260        "libwinhttp.a",
261        "libwinmm.a",
262        "libwinspool.a",
263        "libws2_32.a",
264        "libwsock32.a",
265    ];
266
267    //Find mingw artifacts we want to bundle
268    let target_tools = find_files(&target_tools, &bin_path);
269    let rustc_dlls = find_files(&rustc_dlls, &bin_path);
270    let target_libs = find_files(&target_libs, &lib_path);
271
272    // Copy runtime dlls next to rustc.exe
273    let rust_bin_dir = rust_root.join("bin/");
274    fs::create_dir_all(&rust_bin_dir).expect("creating rust_bin_dir failed");
275    for src in &rustc_dlls {
276        builder.copy_link_to_folder(src, &rust_bin_dir);
277    }
278
279    if builder.config.lld_enabled {
280        // rust-lld.exe also needs runtime dlls
281        let rust_target_bin_dir = rust_root.join("lib/rustlib").join(target).join("bin");
282        fs::create_dir_all(&rust_target_bin_dir).expect("creating rust_target_bin_dir failed");
283        for src in &rustc_dlls {
284            builder.copy_link_to_folder(src, &rust_target_bin_dir);
285        }
286    }
287
288    //Copy platform tools to platform-specific bin directory
289    let plat_target_bin_self_contained_dir =
290        plat_root.join("lib/rustlib").join(target).join("bin/self-contained");
291    fs::create_dir_all(&plat_target_bin_self_contained_dir)
292        .expect("creating plat_target_bin_self_contained_dir failed");
293    for src in target_tools {
294        builder.copy_link_to_folder(&src, &plat_target_bin_self_contained_dir);
295    }
296
297    // Warn windows-gnu users that the bundled GCC cannot compile C files
298    builder.create(
299        &plat_target_bin_self_contained_dir.join("GCC-WARNING.txt"),
300        "gcc.exe contained in this folder cannot be used for compiling C files - it is only \
301         used as a linker. In order to be able to compile projects containing C code use \
302         the GCC provided by MinGW or Cygwin.",
303    );
304
305    //Copy platform libs to platform-specific lib directory
306    let plat_target_lib_self_contained_dir =
307        plat_root.join("lib/rustlib").join(target).join("lib/self-contained");
308    fs::create_dir_all(&plat_target_lib_self_contained_dir)
309        .expect("creating plat_target_lib_self_contained_dir failed");
310    for src in target_libs {
311        builder.copy_link_to_folder(&src, &plat_target_lib_self_contained_dir);
312    }
313}
314
315#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
316pub struct Mingw {
317    pub host: TargetSelection,
318}
319
320impl Step for Mingw {
321    type Output = Option<GeneratedTarball>;
322    const DEFAULT: bool = true;
323
324    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
325        run.alias("rust-mingw")
326    }
327
328    fn make_run(run: RunConfig<'_>) {
329        run.builder.ensure(Mingw { host: run.target });
330    }
331
332    /// Builds the `rust-mingw` installer component.
333    ///
334    /// This contains all the bits and pieces to run the MinGW Windows targets
335    /// without any extra installed software (e.g., we bundle gcc, libraries, etc).
336    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
337        let host = self.host;
338        if !host.ends_with("pc-windows-gnu") || !builder.config.dist_include_mingw_linker {
339            return None;
340        }
341
342        let mut tarball = Tarball::new(builder, "rust-mingw", &host.triple);
343        tarball.set_product_name("Rust MinGW");
344
345        // The first argument is a "temporary directory" which is just
346        // thrown away (this contains the runtime DLLs included in the rustc package
347        // above) and the second argument is where to place all the MinGW components
348        // (which is what we want).
349        make_win_dist(&tmpdir(builder), tarball.image_dir(), host, builder);
350
351        Some(tarball.generate())
352    }
353}
354
355#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
356pub struct Rustc {
357    pub compiler: Compiler,
358}
359
360impl Step for Rustc {
361    type Output = GeneratedTarball;
362    const DEFAULT: bool = true;
363    const ONLY_HOSTS: bool = true;
364
365    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
366        run.alias("rustc")
367    }
368
369    fn make_run(run: RunConfig<'_>) {
370        run.builder
371            .ensure(Rustc { compiler: run.builder.compiler(run.builder.top_stage, run.target) });
372    }
373
374    /// Creates the `rustc` installer component.
375    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
376        let compiler = self.compiler;
377        let host = self.compiler.host;
378
379        let tarball = Tarball::new(builder, "rustc", &host.triple);
380
381        // Prepare the rustc "image", what will actually end up getting installed
382        prepare_image(builder, compiler, tarball.image_dir());
383
384        // On MinGW we've got a few runtime DLL dependencies that we need to
385        // include. The first argument to this script is where to put these DLLs
386        // (the image we're creating), and the second argument is a junk directory
387        // to ignore all other MinGW stuff the script creates.
388        //
389        // On 32-bit MinGW we're always including a DLL which needs some extra
390        // licenses to distribute. On 64-bit MinGW we don't actually distribute
391        // anything requiring us to distribute a license, but it's likely the
392        // install will *also* include the rust-mingw package, which also needs
393        // licenses, so to be safe we just include it here in all MinGW packages.
394        if host.ends_with("pc-windows-gnu") && builder.config.dist_include_mingw_linker {
395            make_win_dist(tarball.image_dir(), &tmpdir(builder), host, builder);
396            tarball.add_dir(builder.src.join("src/etc/third-party"), "share/doc");
397        }
398
399        return tarball.generate();
400
401        fn prepare_image(builder: &Builder<'_>, compiler: Compiler, image: &Path) {
402            let host = compiler.host;
403            let src = builder.sysroot(compiler);
404
405            // Copy rustc binary
406            t!(fs::create_dir_all(image.join("bin")));
407            builder.cp_link_r(&src.join("bin"), &image.join("bin"));
408
409            // If enabled, copy rustdoc binary
410            if builder
411                .config
412                .tools
413                .as_ref()
414                .is_none_or(|tools| tools.iter().any(|tool| tool == "rustdoc"))
415            {
416                let rustdoc = builder.rustdoc(compiler);
417                builder.install(&rustdoc, &image.join("bin"), 0o755);
418            }
419
420            if let Some(ra_proc_macro_srv) = builder.ensure_if_default(
421                tool::RustAnalyzerProcMacroSrv {
422                    compiler: builder.compiler_for(
423                        compiler.stage,
424                        builder.config.build,
425                        compiler.host,
426                    ),
427                    target: compiler.host,
428                },
429                builder.kind,
430            ) {
431                builder.install(&ra_proc_macro_srv, &image.join("libexec"), 0o755);
432            }
433
434            let libdir_relative = builder.libdir_relative(compiler);
435
436            // Copy runtime DLLs needed by the compiler
437            if libdir_relative.to_str() != Some("bin") {
438                let libdir = builder.rustc_libdir(compiler);
439                for entry in builder.read_dir(&libdir) {
440                    if is_dylib(&entry.path()) {
441                        // Don't use custom libdir here because ^lib/ will be resolved again
442                        // with installer
443                        builder.install(&entry.path(), &image.join("lib"), 0o644);
444                    }
445                }
446            }
447
448            // Copy libLLVM.so to the lib dir as well, if needed. While not
449            // technically needed by rustc itself it's needed by lots of other
450            // components like the llvm tools and LLD. LLD is included below and
451            // tools/LLDB come later, so let's just throw it in the rustc
452            // component for now.
453            maybe_install_llvm_runtime(builder, host, image);
454
455            let dst_dir = image.join("lib/rustlib").join(host).join("bin");
456            t!(fs::create_dir_all(&dst_dir));
457
458            // Copy over lld if it's there
459            if builder.config.lld_enabled {
460                let src_dir = builder.sysroot_target_bindir(compiler, host);
461                let rust_lld = exe("rust-lld", compiler.host);
462                builder.copy_link(&src_dir.join(&rust_lld), &dst_dir.join(&rust_lld));
463                let self_contained_lld_src_dir = src_dir.join("gcc-ld");
464                let self_contained_lld_dst_dir = dst_dir.join("gcc-ld");
465                t!(fs::create_dir(&self_contained_lld_dst_dir));
466                for name in crate::LLD_FILE_NAMES {
467                    let exe_name = exe(name, compiler.host);
468                    builder.copy_link(
469                        &self_contained_lld_src_dir.join(&exe_name),
470                        &self_contained_lld_dst_dir.join(&exe_name),
471                    );
472                }
473            }
474
475            if builder.config.llvm_enabled(compiler.host) && builder.config.llvm_tools_enabled {
476                let src_dir = builder.sysroot_target_bindir(compiler, host);
477                let llvm_objcopy = exe("llvm-objcopy", compiler.host);
478                let rust_objcopy = exe("rust-objcopy", compiler.host);
479                builder.copy_link(&src_dir.join(&llvm_objcopy), &dst_dir.join(&rust_objcopy));
480            }
481
482            if builder.tool_enabled("wasm-component-ld") {
483                let src_dir = builder.sysroot_target_bindir(compiler, host);
484                let ld = exe("wasm-component-ld", compiler.host);
485                builder.copy_link(&src_dir.join(&ld), &dst_dir.join(&ld));
486            }
487
488            // Man pages
489            t!(fs::create_dir_all(image.join("share/man/man1")));
490            let man_src = builder.src.join("src/doc/man");
491            let man_dst = image.join("share/man/man1");
492
493            // don't use our `bootstrap::{copy_internal, cp_r}`, because those try
494            // to hardlink, and we don't want to edit the source templates
495            for file_entry in builder.read_dir(&man_src) {
496                let page_src = file_entry.path();
497                let page_dst = man_dst.join(file_entry.file_name());
498                let src_text = t!(std::fs::read_to_string(&page_src));
499                let new_text = src_text.replace("<INSERT VERSION HERE>", &builder.version);
500                t!(std::fs::write(&page_dst, &new_text));
501                t!(fs::copy(&page_src, &page_dst));
502            }
503
504            // Debugger scripts
505            builder.ensure(DebuggerScripts { sysroot: image.to_owned(), host });
506
507            // HTML copyright files
508            let file_list = builder.ensure(super::run::GenerateCopyright);
509            for file in file_list {
510                builder.install(&file, &image.join("share/doc/rust"), 0o644);
511            }
512
513            // README
514            builder.install(&builder.src.join("README.md"), &image.join("share/doc/rust"), 0o644);
515
516            // The REUSE-managed license files
517            let license = |path: &Path| {
518                builder.install(path, &image.join("share/doc/rust/licences"), 0o644);
519            };
520            for entry in t!(std::fs::read_dir(builder.src.join("LICENSES"))).flatten() {
521                license(&entry.path());
522            }
523        }
524    }
525}
526
527#[derive(Debug, Clone, Hash, PartialEq, Eq)]
528pub struct DebuggerScripts {
529    pub sysroot: PathBuf,
530    pub host: TargetSelection,
531}
532
533impl Step for DebuggerScripts {
534    type Output = ();
535
536    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
537        run.never()
538    }
539
540    /// Copies debugger scripts for `target` into the `sysroot` specified.
541    fn run(self, builder: &Builder<'_>) {
542        let host = self.host;
543        let sysroot = self.sysroot;
544        let dst = sysroot.join("lib/rustlib/etc");
545        t!(fs::create_dir_all(&dst));
546        let cp_debugger_script = |file: &str| {
547            builder.install(&builder.src.join("src/etc/").join(file), &dst, 0o644);
548        };
549        if host.contains("windows-msvc") {
550            // windbg debugger scripts
551            builder.install(
552                &builder.src.join("src/etc/rust-windbg.cmd"),
553                &sysroot.join("bin"),
554                0o755,
555            );
556
557            cp_debugger_script("natvis/intrinsic.natvis");
558            cp_debugger_script("natvis/liballoc.natvis");
559            cp_debugger_script("natvis/libcore.natvis");
560            cp_debugger_script("natvis/libstd.natvis");
561        }
562
563        cp_debugger_script("rust_types.py");
564
565        // gdb debugger scripts
566        builder.install(&builder.src.join("src/etc/rust-gdb"), &sysroot.join("bin"), 0o755);
567        builder.install(&builder.src.join("src/etc/rust-gdbgui"), &sysroot.join("bin"), 0o755);
568
569        cp_debugger_script("gdb_load_rust_pretty_printers.py");
570        cp_debugger_script("gdb_lookup.py");
571        cp_debugger_script("gdb_providers.py");
572
573        // lldb debugger scripts
574        builder.install(&builder.src.join("src/etc/rust-lldb"), &sysroot.join("bin"), 0o755);
575
576        cp_debugger_script("lldb_lookup.py");
577        cp_debugger_script("lldb_providers.py");
578        cp_debugger_script("lldb_commands")
579    }
580}
581
582fn skip_host_target_lib(builder: &Builder<'_>, compiler: Compiler) -> bool {
583    // The only true set of target libraries came from the build triple, so
584    // let's reduce redundant work by only producing archives from that host.
585    if !builder.is_builder_target(&compiler.host) {
586        builder.info("\tskipping, not a build host");
587        true
588    } else {
589        false
590    }
591}
592
593/// Check that all objects in rlibs for UEFI targets are COFF. This
594/// ensures that the C compiler isn't producing ELF objects, which would
595/// not link correctly with the COFF objects.
596fn verify_uefi_rlib_format(builder: &Builder<'_>, target: TargetSelection, stamp: &BuildStamp) {
597    if !target.ends_with("-uefi") {
598        return;
599    }
600
601    for (path, _) in builder.read_stamp_file(stamp) {
602        if path.extension() != Some(OsStr::new("rlib")) {
603            continue;
604        }
605
606        let data = t!(fs::read(&path));
607        let data = data.as_slice();
608        let archive = t!(ArchiveFile::parse(data));
609        for member in archive.members() {
610            let member = t!(member);
611            let member_data = t!(member.data(data));
612
613            let is_coff = match object::File::parse(member_data) {
614                Ok(member_file) => member_file.format() == BinaryFormat::Coff,
615                Err(_) => false,
616            };
617
618            if !is_coff {
619                let member_name = String::from_utf8_lossy(member.name());
620                panic!("member {} in {} is not COFF", member_name, path.display());
621            }
622        }
623    }
624}
625
626/// Copy stamped files into an image's `target/lib` directory.
627fn copy_target_libs(
628    builder: &Builder<'_>,
629    target: TargetSelection,
630    image: &Path,
631    stamp: &BuildStamp,
632) {
633    let dst = image.join("lib/rustlib").join(target).join("lib");
634    let self_contained_dst = dst.join("self-contained");
635    t!(fs::create_dir_all(&dst));
636    t!(fs::create_dir_all(&self_contained_dst));
637    for (path, dependency_type) in builder.read_stamp_file(stamp) {
638        if dependency_type == DependencyType::TargetSelfContained {
639            builder.copy_link(&path, &self_contained_dst.join(path.file_name().unwrap()));
640        } else if dependency_type == DependencyType::Target || builder.is_builder_target(&target) {
641            builder.copy_link(&path, &dst.join(path.file_name().unwrap()));
642        }
643    }
644}
645
646#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
647pub struct Std {
648    pub compiler: Compiler,
649    pub target: TargetSelection,
650}
651
652impl Step for Std {
653    type Output = Option<GeneratedTarball>;
654    const DEFAULT: bool = true;
655
656    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
657        run.alias("rust-std")
658    }
659
660    fn make_run(run: RunConfig<'_>) {
661        run.builder.ensure(Std {
662            compiler: run.builder.compiler_for(
663                run.builder.top_stage,
664                run.builder.config.build,
665                run.target,
666            ),
667            target: run.target,
668        });
669    }
670
671    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
672        let compiler = self.compiler;
673        let target = self.target;
674
675        if skip_host_target_lib(builder, compiler) {
676            return None;
677        }
678
679        builder.ensure(compile::Std::new(compiler, target));
680
681        let mut tarball = Tarball::new(builder, "rust-std", &target.triple);
682        tarball.include_target_in_component_name(true);
683
684        let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
685        let stamp = build_stamp::libstd_stamp(builder, compiler_to_use, target);
686        verify_uefi_rlib_format(builder, target, &stamp);
687        copy_target_libs(builder, target, tarball.image_dir(), &stamp);
688
689        Some(tarball.generate())
690    }
691}
692
693/// Tarball containing the compiler that gets downloaded and used by
694/// `rust.download-rustc`.
695///
696/// (Don't confuse this with [`RustDev`], without the `c`!)
697#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
698pub struct RustcDev {
699    pub compiler: Compiler,
700    pub target: TargetSelection,
701}
702
703impl Step for RustcDev {
704    type Output = Option<GeneratedTarball>;
705    const DEFAULT: bool = true;
706    const ONLY_HOSTS: bool = true;
707
708    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
709        run.alias("rustc-dev")
710    }
711
712    fn make_run(run: RunConfig<'_>) {
713        run.builder.ensure(RustcDev {
714            compiler: run.builder.compiler_for(
715                run.builder.top_stage,
716                run.builder.config.build,
717                run.target,
718            ),
719            target: run.target,
720        });
721    }
722
723    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
724        let compiler = self.compiler;
725        let target = self.target;
726        if skip_host_target_lib(builder, compiler) {
727            return None;
728        }
729
730        builder.ensure(compile::Rustc::new(compiler, target));
731
732        let tarball = Tarball::new(builder, "rustc-dev", &target.triple);
733
734        let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
735        let stamp = build_stamp::librustc_stamp(builder, compiler_to_use, target);
736        copy_target_libs(builder, target, tarball.image_dir(), &stamp);
737
738        let src_files = &["Cargo.lock"];
739        // This is the reduced set of paths which will become the rustc-dev component
740        // (essentially the compiler crates and all of their path dependencies).
741        copy_src_dirs(
742            builder,
743            &builder.src,
744            &["compiler"],
745            &[],
746            &tarball.image_dir().join("lib/rustlib/rustc-src/rust"),
747        );
748        for file in src_files {
749            tarball.add_file(builder.src.join(file), "lib/rustlib/rustc-src/rust", 0o644);
750        }
751
752        Some(tarball.generate())
753    }
754}
755
756#[derive(Debug, Clone, Hash, PartialEq, Eq)]
757pub struct Analysis {
758    pub compiler: Compiler,
759    pub target: TargetSelection,
760}
761
762impl Step for Analysis {
763    type Output = Option<GeneratedTarball>;
764    const DEFAULT: bool = true;
765
766    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
767        let default = should_build_extended_tool(run.builder, "analysis");
768        run.alias("rust-analysis").default_condition(default)
769    }
770
771    fn make_run(run: RunConfig<'_>) {
772        run.builder.ensure(Analysis {
773            // Find the actual compiler (handling the full bootstrap option) which
774            // produced the save-analysis data because that data isn't copied
775            // through the sysroot uplifting.
776            compiler: run.builder.compiler_for(
777                run.builder.top_stage,
778                run.builder.config.build,
779                run.target,
780            ),
781            target: run.target,
782        });
783    }
784
785    /// Creates a tarball of (degenerate) save-analysis metadata, if available.
786    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
787        let compiler = self.compiler;
788        let target = self.target;
789        if !builder.is_builder_target(&compiler.host) {
790            return None;
791        }
792
793        let src = builder
794            .stage_out(compiler, Mode::Std)
795            .join(target)
796            .join(builder.cargo_dir())
797            .join("deps")
798            .join("save-analysis");
799
800        // Write a file indicating that this component has been removed.
801        t!(std::fs::create_dir_all(&src));
802        let mut removed = src.clone();
803        removed.push("removed.json");
804        let mut f = t!(std::fs::File::create(removed));
805        t!(write!(f, r#"{{ "warning": "The `rust-analysis` component has been removed." }}"#));
806
807        let mut tarball = Tarball::new(builder, "rust-analysis", &target.triple);
808        tarball.include_target_in_component_name(true);
809        tarball.add_dir(src, format!("lib/rustlib/{}/analysis", target.triple));
810        Some(tarball.generate())
811    }
812}
813
814/// Use the `builder` to make a filtered copy of `base`/X for X in (`src_dirs` - `exclude_dirs`) to
815/// `dst_dir`.
816fn copy_src_dirs(
817    builder: &Builder<'_>,
818    base: &Path,
819    src_dirs: &[&str],
820    exclude_dirs: &[&str],
821    dst_dir: &Path,
822) {
823    fn filter_fn(exclude_dirs: &[&str], dir: &str, path: &Path) -> bool {
824        let spath = match path.to_str() {
825            Some(path) => path,
826            None => return false,
827        };
828        if spath.ends_with('~') || spath.ends_with(".pyc") {
829            return false;
830        }
831
832        const LLVM_PROJECTS: &[&str] = &[
833            "llvm-project/clang",
834            "llvm-project\\clang",
835            "llvm-project/libunwind",
836            "llvm-project\\libunwind",
837            "llvm-project/lld",
838            "llvm-project\\lld",
839            "llvm-project/lldb",
840            "llvm-project\\lldb",
841            "llvm-project/llvm",
842            "llvm-project\\llvm",
843            "llvm-project/compiler-rt",
844            "llvm-project\\compiler-rt",
845            "llvm-project/cmake",
846            "llvm-project\\cmake",
847            "llvm-project/runtimes",
848            "llvm-project\\runtimes",
849        ];
850        if spath.contains("llvm-project")
851            && !spath.ends_with("llvm-project")
852            && !LLVM_PROJECTS.iter().any(|path| spath.contains(path))
853        {
854            return false;
855        }
856
857        const LLVM_TEST: &[&str] = &["llvm-project/llvm/test", "llvm-project\\llvm\\test"];
858        if LLVM_TEST.iter().any(|path| spath.contains(path))
859            && (spath.ends_with(".ll") || spath.ends_with(".td") || spath.ends_with(".s"))
860        {
861            return false;
862        }
863
864        // Cargo tests use some files like `.gitignore` that we would otherwise exclude.
865        const CARGO_TESTS: &[&str] = &["tools/cargo/tests", "tools\\cargo\\tests"];
866        if CARGO_TESTS.iter().any(|path| spath.contains(path)) {
867            return true;
868        }
869
870        let full_path = Path::new(dir).join(path);
871        if exclude_dirs.iter().any(|excl| full_path == Path::new(excl)) {
872            return false;
873        }
874
875        let excludes = [
876            "CVS",
877            "RCS",
878            "SCCS",
879            ".git",
880            ".gitignore",
881            ".gitmodules",
882            ".gitattributes",
883            ".cvsignore",
884            ".svn",
885            ".arch-ids",
886            "{arch}",
887            "=RELEASE-ID",
888            "=meta-update",
889            "=update",
890            ".bzr",
891            ".bzrignore",
892            ".bzrtags",
893            ".hg",
894            ".hgignore",
895            ".hgrags",
896            "_darcs",
897        ];
898        !path.iter().map(|s| s.to_str().unwrap()).any(|s| excludes.contains(&s))
899    }
900
901    // Copy the directories using our filter
902    for item in src_dirs {
903        let dst = &dst_dir.join(item);
904        t!(fs::create_dir_all(dst));
905        builder
906            .cp_link_filtered(&base.join(item), dst, &|path| filter_fn(exclude_dirs, item, path));
907    }
908}
909
910#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
911pub struct Src;
912
913impl Step for Src {
914    /// The output path of the src installer tarball
915    type Output = GeneratedTarball;
916    const DEFAULT: bool = true;
917    const ONLY_HOSTS: bool = true;
918
919    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
920        run.alias("rust-src")
921    }
922
923    fn make_run(run: RunConfig<'_>) {
924        run.builder.ensure(Src);
925    }
926
927    /// Creates the `rust-src` installer component
928    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
929        if !builder.config.dry_run() {
930            builder.require_submodule("src/llvm-project", None);
931        }
932
933        let tarball = Tarball::new_targetless(builder, "rust-src");
934
935        // A lot of tools expect the rust-src component to be entirely in this directory, so if you
936        // change that (e.g. by adding another directory `lib/rustlib/src/foo` or
937        // `lib/rustlib/src/rust/foo`), you will need to go around hunting for implicit assumptions
938        // and fix them...
939        //
940        // NOTE: if you update the paths here, you also should update the "virtual" path
941        // translation code in `imported_source_files` in `src/librustc_metadata/rmeta/decoder.rs`
942        let dst_src = tarball.image_dir().join("lib/rustlib/src/rust");
943
944        // This is the reduced set of paths which will become the rust-src component
945        // (essentially libstd and all of its path dependencies).
946        copy_src_dirs(
947            builder,
948            &builder.src,
949            &["library", "src/llvm-project/libunwind"],
950            &[
951                // not needed and contains symlinks which rustup currently
952                // chokes on when unpacking.
953                "library/backtrace/crates",
954                // these are 30MB combined and aren't necessary for building
955                // the standard library.
956                "library/stdarch/Cargo.toml",
957                "library/stdarch/crates/stdarch-verify",
958                "library/stdarch/crates/intrinsic-test",
959            ],
960            &dst_src,
961        );
962
963        tarball.generate()
964    }
965}
966
967#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
968pub struct PlainSourceTarball;
969
970impl Step for PlainSourceTarball {
971    /// Produces the location of the tarball generated
972    type Output = GeneratedTarball;
973    const DEFAULT: bool = true;
974    const ONLY_HOSTS: bool = true;
975
976    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
977        let builder = run.builder;
978        run.alias("rustc-src").default_condition(builder.config.rust_dist_src)
979    }
980
981    fn make_run(run: RunConfig<'_>) {
982        run.builder.ensure(PlainSourceTarball);
983    }
984
985    /// Creates the plain source tarball
986    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
987        // NOTE: This is a strange component in a lot of ways. It uses `src` as the target, which
988        // means neither rustup nor rustup-toolchain-install-master know how to download it.
989        // It also contains symbolic links, unlike other any other dist tarball.
990        // It's used for distros building rustc from source in a pre-vendored environment.
991        let mut tarball = Tarball::new(builder, "rustc", "src");
992        tarball.permit_symlinks(true);
993        let plain_dst_src = tarball.image_dir();
994
995        // This is the set of root paths which will become part of the source package
996        let src_files = [
997            // tidy-alphabetical-start
998            ".gitmodules",
999            "Cargo.lock",
1000            "Cargo.toml",
1001            "config.example.toml",
1002            "configure",
1003            "CONTRIBUTING.md",
1004            "COPYRIGHT",
1005            "LICENSE-APACHE",
1006            "license-metadata.json",
1007            "LICENSE-MIT",
1008            "README.md",
1009            "RELEASES.md",
1010            "REUSE.toml",
1011            "x",
1012            "x.ps1",
1013            "x.py",
1014            // tidy-alphabetical-end
1015        ];
1016        let src_dirs = ["src", "compiler", "library", "tests", "LICENSES"];
1017
1018        copy_src_dirs(
1019            builder,
1020            &builder.src,
1021            &src_dirs,
1022            &[
1023                // We don't currently use the GCC source code for building any official components,
1024                // it is very big, and has unclear licensing implications due to being GPL licensed.
1025                // We thus exclude it from the source tarball from now.
1026                "src/gcc",
1027            ],
1028            plain_dst_src,
1029        );
1030
1031        // Copy the files normally
1032        for item in &src_files {
1033            builder.copy_link(&builder.src.join(item), &plain_dst_src.join(item));
1034        }
1035
1036        // Create the version file
1037        builder.create(&plain_dst_src.join("version"), &builder.rust_version());
1038
1039        // Create the files containing git info, to ensure --version outputs the same.
1040        let write_git_info = |info: Option<&Info>, path: &Path| {
1041            if let Some(info) = info {
1042                t!(std::fs::create_dir_all(path));
1043                channel::write_commit_hash_file(path, &info.sha);
1044                channel::write_commit_info_file(path, info);
1045            }
1046        };
1047        write_git_info(builder.rust_info().info(), plain_dst_src);
1048        write_git_info(builder.cargo_info.info(), &plain_dst_src.join("./src/tools/cargo"));
1049
1050        if builder.config.dist_vendor {
1051            builder.require_and_update_all_submodules();
1052
1053            // Vendor all Cargo dependencies
1054            let mut cmd = command(&builder.initial_cargo);
1055            cmd.arg("vendor").arg("--versioned-dirs");
1056
1057            for (p, _) in default_paths_to_vendor(builder) {
1058                cmd.arg("--sync").arg(p);
1059            }
1060
1061            cmd
1062                // Will read the libstd Cargo.toml which uses the unstable `public-dependency` feature.
1063                .env("RUSTC_BOOTSTRAP", "1")
1064                .current_dir(plain_dst_src);
1065
1066            // Vendor packages that are required by opt-dist to collect PGO profiles.
1067            let pkgs_for_pgo_training = build_helper::LLVM_PGO_CRATES
1068                .iter()
1069                .chain(build_helper::RUSTC_PGO_CRATES)
1070                .map(|pkg| {
1071                    let mut manifest_path =
1072                        builder.src.join("./src/tools/rustc-perf/collector/compile-benchmarks");
1073                    manifest_path.push(pkg);
1074                    manifest_path.push("Cargo.toml");
1075                    manifest_path
1076                });
1077            for manifest_path in pkgs_for_pgo_training {
1078                cmd.arg("--sync").arg(manifest_path);
1079            }
1080
1081            let config = cmd.run_capture(builder).stdout();
1082
1083            let cargo_config_dir = plain_dst_src.join(".cargo");
1084            builder.create_dir(&cargo_config_dir);
1085            builder.create(&cargo_config_dir.join("config.toml"), &config);
1086        }
1087
1088        // Delete extraneous directories
1089        // FIXME: if we're managed by git, we should probably instead ask git if the given path
1090        // is managed by it?
1091        for entry in walkdir::WalkDir::new(tarball.image_dir())
1092            .follow_links(true)
1093            .into_iter()
1094            .filter_map(|e| e.ok())
1095        {
1096            if entry.path().is_dir() && entry.path().file_name() == Some(OsStr::new("__pycache__"))
1097            {
1098                t!(fs::remove_dir_all(entry.path()));
1099            }
1100        }
1101
1102        tarball.bare()
1103    }
1104}
1105
1106#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
1107pub struct Cargo {
1108    pub compiler: Compiler,
1109    pub target: TargetSelection,
1110}
1111
1112impl Step for Cargo {
1113    type Output = Option<GeneratedTarball>;
1114    const DEFAULT: bool = true;
1115    const ONLY_HOSTS: bool = true;
1116
1117    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1118        let default = should_build_extended_tool(run.builder, "cargo");
1119        run.alias("cargo").default_condition(default)
1120    }
1121
1122    fn make_run(run: RunConfig<'_>) {
1123        run.builder.ensure(Cargo {
1124            compiler: run.builder.compiler_for(
1125                run.builder.top_stage,
1126                run.builder.config.build,
1127                run.target,
1128            ),
1129            target: run.target,
1130        });
1131    }
1132
1133    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1134        let compiler = self.compiler;
1135        let target = self.target;
1136
1137        let cargo = builder.ensure(tool::Cargo { compiler, target });
1138        let src = builder.src.join("src/tools/cargo");
1139        let etc = src.join("src/etc");
1140
1141        // Prepare the image directory
1142        let mut tarball = Tarball::new(builder, "cargo", &target.triple);
1143        tarball.set_overlay(OverlayKind::Cargo);
1144
1145        tarball.add_file(cargo, "bin", 0o755);
1146        tarball.add_file(etc.join("_cargo"), "share/zsh/site-functions", 0o644);
1147        tarball.add_renamed_file(etc.join("cargo.bashcomp.sh"), "etc/bash_completion.d", "cargo");
1148        tarball.add_dir(etc.join("man"), "share/man/man1");
1149        tarball.add_legal_and_readme_to("share/doc/cargo");
1150
1151        Some(tarball.generate())
1152    }
1153}
1154
1155#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
1156pub struct Rls {
1157    pub compiler: Compiler,
1158    pub target: TargetSelection,
1159}
1160
1161impl Step for Rls {
1162    type Output = Option<GeneratedTarball>;
1163    const ONLY_HOSTS: bool = true;
1164    const DEFAULT: bool = true;
1165
1166    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1167        let default = should_build_extended_tool(run.builder, "rls");
1168        run.alias("rls").default_condition(default)
1169    }
1170
1171    fn make_run(run: RunConfig<'_>) {
1172        run.builder.ensure(Rls {
1173            compiler: run.builder.compiler_for(
1174                run.builder.top_stage,
1175                run.builder.config.build,
1176                run.target,
1177            ),
1178            target: run.target,
1179        });
1180    }
1181
1182    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1183        let compiler = self.compiler;
1184        let target = self.target;
1185
1186        let rls = builder.ensure(tool::Rls { compiler, target });
1187
1188        let mut tarball = Tarball::new(builder, "rls", &target.triple);
1189        tarball.set_overlay(OverlayKind::Rls);
1190        tarball.is_preview(true);
1191        tarball.add_file(rls, "bin", 0o755);
1192        tarball.add_legal_and_readme_to("share/doc/rls");
1193        Some(tarball.generate())
1194    }
1195}
1196
1197#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
1198pub struct RustAnalyzer {
1199    pub compiler: Compiler,
1200    pub target: TargetSelection,
1201}
1202
1203impl Step for RustAnalyzer {
1204    type Output = Option<GeneratedTarball>;
1205    const DEFAULT: bool = true;
1206    const ONLY_HOSTS: bool = true;
1207
1208    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1209        let default = should_build_extended_tool(run.builder, "rust-analyzer");
1210        run.alias("rust-analyzer").default_condition(default)
1211    }
1212
1213    fn make_run(run: RunConfig<'_>) {
1214        run.builder.ensure(RustAnalyzer {
1215            compiler: run.builder.compiler_for(
1216                run.builder.top_stage,
1217                run.builder.config.build,
1218                run.target,
1219            ),
1220            target: run.target,
1221        });
1222    }
1223
1224    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1225        let compiler = self.compiler;
1226        let target = self.target;
1227
1228        let rust_analyzer = builder.ensure(tool::RustAnalyzer { compiler, target });
1229
1230        let mut tarball = Tarball::new(builder, "rust-analyzer", &target.triple);
1231        tarball.set_overlay(OverlayKind::RustAnalyzer);
1232        tarball.is_preview(true);
1233        tarball.add_file(rust_analyzer, "bin", 0o755);
1234        tarball.add_legal_and_readme_to("share/doc/rust-analyzer");
1235        Some(tarball.generate())
1236    }
1237}
1238
1239#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
1240pub struct Clippy {
1241    pub compiler: Compiler,
1242    pub target: TargetSelection,
1243}
1244
1245impl Step for Clippy {
1246    type Output = Option<GeneratedTarball>;
1247    const DEFAULT: bool = true;
1248    const ONLY_HOSTS: bool = true;
1249
1250    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1251        let default = should_build_extended_tool(run.builder, "clippy");
1252        run.alias("clippy").default_condition(default)
1253    }
1254
1255    fn make_run(run: RunConfig<'_>) {
1256        run.builder.ensure(Clippy {
1257            compiler: run.builder.compiler_for(
1258                run.builder.top_stage,
1259                run.builder.config.build,
1260                run.target,
1261            ),
1262            target: run.target,
1263        });
1264    }
1265
1266    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1267        let compiler = self.compiler;
1268        let target = self.target;
1269
1270        // Prepare the image directory
1271        // We expect clippy to build, because we've exited this step above if tool
1272        // state for clippy isn't testing.
1273        let clippy = builder.ensure(tool::Clippy { compiler, target });
1274        let cargoclippy = builder.ensure(tool::CargoClippy { compiler, target });
1275
1276        let mut tarball = Tarball::new(builder, "clippy", &target.triple);
1277        tarball.set_overlay(OverlayKind::Clippy);
1278        tarball.is_preview(true);
1279        tarball.add_file(clippy, "bin", 0o755);
1280        tarball.add_file(cargoclippy, "bin", 0o755);
1281        tarball.add_legal_and_readme_to("share/doc/clippy");
1282        Some(tarball.generate())
1283    }
1284}
1285
1286#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
1287pub struct Miri {
1288    pub compiler: Compiler,
1289    pub target: TargetSelection,
1290}
1291
1292impl Step for Miri {
1293    type Output = Option<GeneratedTarball>;
1294    const DEFAULT: bool = true;
1295    const ONLY_HOSTS: bool = true;
1296
1297    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1298        let default = should_build_extended_tool(run.builder, "miri");
1299        run.alias("miri").default_condition(default)
1300    }
1301
1302    fn make_run(run: RunConfig<'_>) {
1303        run.builder.ensure(Miri {
1304            compiler: run.builder.compiler_for(
1305                run.builder.top_stage,
1306                run.builder.config.build,
1307                run.target,
1308            ),
1309            target: run.target,
1310        });
1311    }
1312
1313    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1314        // This prevents miri from being built for "dist" or "install"
1315        // on the stable/beta channels. It is a nightly-only tool and should
1316        // not be included.
1317        if !builder.build.unstable_features() {
1318            return None;
1319        }
1320        let compiler = self.compiler;
1321        let target = self.target;
1322
1323        let miri = builder.ensure(tool::Miri { compiler, target });
1324        let cargomiri = builder.ensure(tool::CargoMiri { compiler, target });
1325
1326        let mut tarball = Tarball::new(builder, "miri", &target.triple);
1327        tarball.set_overlay(OverlayKind::Miri);
1328        tarball.is_preview(true);
1329        tarball.add_file(miri, "bin", 0o755);
1330        tarball.add_file(cargomiri, "bin", 0o755);
1331        tarball.add_legal_and_readme_to("share/doc/miri");
1332        Some(tarball.generate())
1333    }
1334}
1335
1336#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
1337pub struct CodegenBackend {
1338    pub compiler: Compiler,
1339    pub backend: String,
1340}
1341
1342impl Step for CodegenBackend {
1343    type Output = Option<GeneratedTarball>;
1344    const DEFAULT: bool = true;
1345    const ONLY_HOSTS: bool = true;
1346
1347    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1348        run.path("compiler/rustc_codegen_cranelift")
1349    }
1350
1351    fn make_run(run: RunConfig<'_>) {
1352        for backend in run.builder.config.codegen_backends(run.target) {
1353            if backend == "llvm" {
1354                continue; // Already built as part of rustc
1355            }
1356
1357            run.builder.ensure(CodegenBackend {
1358                compiler: run.builder.compiler(run.builder.top_stage, run.target),
1359                backend: backend.clone(),
1360            });
1361        }
1362    }
1363
1364    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1365        if builder.config.dry_run() {
1366            return None;
1367        }
1368
1369        // This prevents rustc_codegen_cranelift from being built for "dist"
1370        // or "install" on the stable/beta channels. It is not yet stable and
1371        // should not be included.
1372        if !builder.build.unstable_features() {
1373            return None;
1374        }
1375
1376        if !builder.config.codegen_backends(self.compiler.host).contains(&self.backend.to_string())
1377        {
1378            return None;
1379        }
1380
1381        if self.backend == "cranelift" && !target_supports_cranelift_backend(self.compiler.host) {
1382            builder.info("target not supported by rustc_codegen_cranelift. skipping");
1383            return None;
1384        }
1385
1386        let compiler = self.compiler;
1387        let backend = self.backend;
1388
1389        let mut tarball =
1390            Tarball::new(builder, &format!("rustc-codegen-{}", backend), &compiler.host.triple);
1391        if backend == "cranelift" {
1392            tarball.set_overlay(OverlayKind::RustcCodegenCranelift);
1393        } else {
1394            panic!("Unknown backend rustc_codegen_{}", backend);
1395        }
1396        tarball.is_preview(true);
1397        tarball.add_legal_and_readme_to(format!("share/doc/rustc_codegen_{}", backend));
1398
1399        let src = builder.sysroot(compiler);
1400        let backends_src = builder.sysroot_codegen_backends(compiler);
1401        let backends_rel = backends_src
1402            .strip_prefix(src)
1403            .unwrap()
1404            .strip_prefix(builder.sysroot_libdir_relative(compiler))
1405            .unwrap();
1406        // Don't use custom libdir here because ^lib/ will be resolved again with installer
1407        let backends_dst = PathBuf::from("lib").join(backends_rel);
1408
1409        let backend_name = format!("rustc_codegen_{}", backend);
1410        let mut found_backend = false;
1411        for backend in fs::read_dir(&backends_src).unwrap() {
1412            let file_name = backend.unwrap().file_name();
1413            if file_name.to_str().unwrap().contains(&backend_name) {
1414                tarball.add_file(backends_src.join(file_name), &backends_dst, 0o644);
1415                found_backend = true;
1416            }
1417        }
1418        assert!(found_backend);
1419
1420        Some(tarball.generate())
1421    }
1422}
1423
1424#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
1425pub struct Rustfmt {
1426    pub compiler: Compiler,
1427    pub target: TargetSelection,
1428}
1429
1430impl Step for Rustfmt {
1431    type Output = Option<GeneratedTarball>;
1432    const DEFAULT: bool = true;
1433    const ONLY_HOSTS: bool = true;
1434
1435    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1436        let default = should_build_extended_tool(run.builder, "rustfmt");
1437        run.alias("rustfmt").default_condition(default)
1438    }
1439
1440    fn make_run(run: RunConfig<'_>) {
1441        run.builder.ensure(Rustfmt {
1442            compiler: run.builder.compiler_for(
1443                run.builder.top_stage,
1444                run.builder.config.build,
1445                run.target,
1446            ),
1447            target: run.target,
1448        });
1449    }
1450
1451    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
1452        let compiler = self.compiler;
1453        let target = self.target;
1454
1455        let rustfmt = builder.ensure(tool::Rustfmt { compiler, target });
1456        let cargofmt = builder.ensure(tool::Cargofmt { compiler, target });
1457        let mut tarball = Tarball::new(builder, "rustfmt", &target.triple);
1458        tarball.set_overlay(OverlayKind::Rustfmt);
1459        tarball.is_preview(true);
1460        tarball.add_file(rustfmt, "bin", 0o755);
1461        tarball.add_file(cargofmt, "bin", 0o755);
1462        tarball.add_legal_and_readme_to("share/doc/rustfmt");
1463        Some(tarball.generate())
1464    }
1465}
1466
1467#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
1468pub struct Extended {
1469    stage: u32,
1470    host: TargetSelection,
1471    target: TargetSelection,
1472}
1473
1474impl Step for Extended {
1475    type Output = ();
1476    const DEFAULT: bool = true;
1477    const ONLY_HOSTS: bool = true;
1478
1479    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1480        let builder = run.builder;
1481        run.alias("extended").default_condition(builder.config.extended)
1482    }
1483
1484    fn make_run(run: RunConfig<'_>) {
1485        run.builder.ensure(Extended {
1486            stage: run.builder.top_stage,
1487            host: run.builder.config.build,
1488            target: run.target,
1489        });
1490    }
1491
1492    /// Creates a combined installer for the specified target in the provided stage.
1493    fn run(self, builder: &Builder<'_>) {
1494        let target = self.target;
1495        let stage = self.stage;
1496        let compiler = builder.compiler_for(self.stage, self.host, self.target);
1497
1498        builder.info(&format!("Dist extended stage{} ({})", compiler.stage, target));
1499
1500        let mut tarballs = Vec::new();
1501        let mut built_tools = HashSet::new();
1502        macro_rules! add_component {
1503            ($name:expr => $step:expr) => {
1504                if let Some(tarball) = builder.ensure_if_default($step, Kind::Dist) {
1505                    tarballs.push(tarball);
1506                    built_tools.insert($name);
1507                }
1508            };
1509        }
1510
1511        // When rust-std package split from rustc, we needed to ensure that during
1512        // upgrades rustc was upgraded before rust-std. To avoid rustc clobbering
1513        // the std files during uninstall. To do this ensure that rustc comes
1514        // before rust-std in the list below.
1515        tarballs.push(builder.ensure(Rustc { compiler: builder.compiler(stage, target) }));
1516        tarballs.push(builder.ensure(Std { compiler, target }).expect("missing std"));
1517
1518        if target.is_windows_gnu() {
1519            tarballs.push(builder.ensure(Mingw { host: target }).expect("missing mingw"));
1520        }
1521
1522        add_component!("rust-docs" => Docs { host: target });
1523        add_component!("rust-json-docs" => JsonDocs { host: target });
1524        add_component!("cargo" => Cargo { compiler, target });
1525        add_component!("rustfmt" => Rustfmt { compiler, target });
1526        add_component!("rls" => Rls { compiler, target });
1527        add_component!("rust-analyzer" => RustAnalyzer { compiler, target });
1528        add_component!("llvm-components" => LlvmTools { target });
1529        add_component!("clippy" => Clippy { compiler, target });
1530        add_component!("miri" => Miri { compiler, target });
1531        add_component!("analysis" => Analysis { compiler, target });
1532        add_component!("rustc-codegen-cranelift" => CodegenBackend {
1533            compiler: builder.compiler(stage, target),
1534            backend: "cranelift".to_string(),
1535        });
1536        add_component!("llvm-bitcode-linker" => LlvmBitcodeLinker {compiler, target});
1537
1538        let etc = builder.src.join("src/etc/installer");
1539
1540        // Avoid producing tarballs during a dry run.
1541        if builder.config.dry_run() {
1542            return;
1543        }
1544
1545        let tarball = Tarball::new(builder, "rust", &target.triple);
1546        let generated = tarball.combine(&tarballs);
1547
1548        let tmp = tmpdir(builder).join("combined-tarball");
1549        let work = generated.work_dir();
1550
1551        let mut license = String::new();
1552        license += &builder.read(&builder.src.join("COPYRIGHT"));
1553        license += &builder.read(&builder.src.join("LICENSE-APACHE"));
1554        license += &builder.read(&builder.src.join("LICENSE-MIT"));
1555        license.push('\n');
1556        license.push('\n');
1557
1558        let rtf = r"{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Arial;}}\nowwrap\fs18";
1559        let mut rtf = rtf.to_string();
1560        rtf.push('\n');
1561        for line in license.lines() {
1562            rtf.push_str(line);
1563            rtf.push_str("\\line ");
1564        }
1565        rtf.push('}');
1566
1567        fn filter(contents: &str, marker: &str) -> String {
1568            let start = format!("tool-{marker}-start");
1569            let end = format!("tool-{marker}-end");
1570            let mut lines = Vec::new();
1571            let mut omitted = false;
1572            for line in contents.lines() {
1573                if line.contains(&start) {
1574                    omitted = true;
1575                } else if line.contains(&end) {
1576                    omitted = false;
1577                } else if !omitted {
1578                    lines.push(line);
1579                }
1580            }
1581
1582            lines.join("\n")
1583        }
1584
1585        let xform = |p: &Path| {
1586            let mut contents = t!(fs::read_to_string(p));
1587            for tool in &["miri", "rust-docs"] {
1588                if !built_tools.contains(tool) {
1589                    contents = filter(&contents, tool);
1590                }
1591            }
1592            let ret = tmp.join(p.file_name().unwrap());
1593            t!(fs::write(&ret, &contents));
1594            ret
1595        };
1596
1597        if target.contains("apple-darwin") {
1598            builder.info("building pkg installer");
1599            let pkg = tmp.join("pkg");
1600            let _ = fs::remove_dir_all(&pkg);
1601
1602            let pkgbuild = |component: &str| {
1603                let mut cmd = command("pkgbuild");
1604                cmd.arg("--identifier")
1605                    .arg(format!("org.rust-lang.{}", component))
1606                    .arg("--scripts")
1607                    .arg(pkg.join(component))
1608                    .arg("--nopayload")
1609                    .arg(pkg.join(component).with_extension("pkg"));
1610                cmd.run(builder);
1611            };
1612
1613            let prepare = |name: &str| {
1614                builder.create_dir(&pkg.join(name));
1615                builder.cp_link_r(
1616                    &work.join(format!("{}-{}", pkgname(builder, name), target.triple)),
1617                    &pkg.join(name),
1618                );
1619                builder.install(&etc.join("pkg/postinstall"), &pkg.join(name), 0o755);
1620                pkgbuild(name);
1621            };
1622            prepare("rustc");
1623            prepare("cargo");
1624            prepare("rust-std");
1625            prepare("rust-analysis");
1626            prepare("clippy");
1627            prepare("rust-analyzer");
1628            for tool in &["rust-docs", "miri", "rustc-codegen-cranelift"] {
1629                if built_tools.contains(tool) {
1630                    prepare(tool);
1631                }
1632            }
1633            // create an 'uninstall' package
1634            builder.install(&etc.join("pkg/postinstall"), &pkg.join("uninstall"), 0o755);
1635            pkgbuild("uninstall");
1636
1637            builder.create_dir(&pkg.join("res"));
1638            builder.create(&pkg.join("res/LICENSE.txt"), &license);
1639            builder.install(&etc.join("gfx/rust-logo.png"), &pkg.join("res"), 0o644);
1640            let mut cmd = command("productbuild");
1641            cmd.arg("--distribution")
1642                .arg(xform(&etc.join("pkg/Distribution.xml")))
1643                .arg("--resources")
1644                .arg(pkg.join("res"))
1645                .arg(distdir(builder).join(format!(
1646                    "{}-{}.pkg",
1647                    pkgname(builder, "rust"),
1648                    target.triple
1649                )))
1650                .arg("--package-path")
1651                .arg(&pkg);
1652            let _time = timeit(builder);
1653            cmd.run(builder);
1654        }
1655
1656        if target.is_windows() {
1657            let exe = tmp.join("exe");
1658            let _ = fs::remove_dir_all(&exe);
1659
1660            let prepare = |name: &str| {
1661                builder.create_dir(&exe.join(name));
1662                let dir = if name == "rust-std" || name == "rust-analysis" {
1663                    format!("{}-{}", name, target.triple)
1664                } else if name == "rust-analyzer" {
1665                    "rust-analyzer-preview".to_string()
1666                } else if name == "clippy" {
1667                    "clippy-preview".to_string()
1668                } else if name == "miri" {
1669                    "miri-preview".to_string()
1670                } else if name == "rustc-codegen-cranelift" {
1671                    // FIXME add installer support for cg_clif once it is ready to be distributed on
1672                    // windows.
1673                    unreachable!("cg_clif shouldn't be built for windows");
1674                } else {
1675                    name.to_string()
1676                };
1677                builder.cp_link_r(
1678                    &work.join(format!("{}-{}", pkgname(builder, name), target.triple)).join(dir),
1679                    &exe.join(name),
1680                );
1681                builder.remove(&exe.join(name).join("manifest.in"));
1682            };
1683            prepare("rustc");
1684            prepare("cargo");
1685            prepare("rust-analysis");
1686            prepare("rust-std");
1687            for tool in &["clippy", "rust-analyzer", "rust-docs", "miri"] {
1688                if built_tools.contains(tool) {
1689                    prepare(tool);
1690                }
1691            }
1692            if target.is_windows_gnu() {
1693                prepare("rust-mingw");
1694            }
1695
1696            builder.install(&etc.join("gfx/rust-logo.ico"), &exe, 0o644);
1697
1698            // Generate msi installer
1699            let wix_path = env::var_os("WIX")
1700                .expect("`WIX` environment variable must be set for generating MSI installer(s).");
1701            let wix = PathBuf::from(wix_path);
1702            let heat = wix.join("bin/heat.exe");
1703            let candle = wix.join("bin/candle.exe");
1704            let light = wix.join("bin/light.exe");
1705
1706            let heat_flags = ["-nologo", "-gg", "-sfrag", "-srd", "-sreg"];
1707            command(&heat)
1708                .current_dir(&exe)
1709                .arg("dir")
1710                .arg("rustc")
1711                .args(heat_flags)
1712                .arg("-cg")
1713                .arg("RustcGroup")
1714                .arg("-dr")
1715                .arg("Rustc")
1716                .arg("-var")
1717                .arg("var.RustcDir")
1718                .arg("-out")
1719                .arg(exe.join("RustcGroup.wxs"))
1720                .run(builder);
1721            if built_tools.contains("rust-docs") {
1722                command(&heat)
1723                    .current_dir(&exe)
1724                    .arg("dir")
1725                    .arg("rust-docs")
1726                    .args(heat_flags)
1727                    .arg("-cg")
1728                    .arg("DocsGroup")
1729                    .arg("-dr")
1730                    .arg("Docs")
1731                    .arg("-var")
1732                    .arg("var.DocsDir")
1733                    .arg("-out")
1734                    .arg(exe.join("DocsGroup.wxs"))
1735                    .arg("-t")
1736                    .arg(etc.join("msi/squash-components.xsl"))
1737                    .run(builder);
1738            }
1739            command(&heat)
1740                .current_dir(&exe)
1741                .arg("dir")
1742                .arg("cargo")
1743                .args(heat_flags)
1744                .arg("-cg")
1745                .arg("CargoGroup")
1746                .arg("-dr")
1747                .arg("Cargo")
1748                .arg("-var")
1749                .arg("var.CargoDir")
1750                .arg("-out")
1751                .arg(exe.join("CargoGroup.wxs"))
1752                .arg("-t")
1753                .arg(etc.join("msi/remove-duplicates.xsl"))
1754                .run(builder);
1755            command(&heat)
1756                .current_dir(&exe)
1757                .arg("dir")
1758                .arg("rust-std")
1759                .args(heat_flags)
1760                .arg("-cg")
1761                .arg("StdGroup")
1762                .arg("-dr")
1763                .arg("Std")
1764                .arg("-var")
1765                .arg("var.StdDir")
1766                .arg("-out")
1767                .arg(exe.join("StdGroup.wxs"))
1768                .run(builder);
1769            if built_tools.contains("rust-analyzer") {
1770                command(&heat)
1771                    .current_dir(&exe)
1772                    .arg("dir")
1773                    .arg("rust-analyzer")
1774                    .args(heat_flags)
1775                    .arg("-cg")
1776                    .arg("RustAnalyzerGroup")
1777                    .arg("-dr")
1778                    .arg("RustAnalyzer")
1779                    .arg("-var")
1780                    .arg("var.RustAnalyzerDir")
1781                    .arg("-out")
1782                    .arg(exe.join("RustAnalyzerGroup.wxs"))
1783                    .arg("-t")
1784                    .arg(etc.join("msi/remove-duplicates.xsl"))
1785                    .run(builder);
1786            }
1787            if built_tools.contains("clippy") {
1788                command(&heat)
1789                    .current_dir(&exe)
1790                    .arg("dir")
1791                    .arg("clippy")
1792                    .args(heat_flags)
1793                    .arg("-cg")
1794                    .arg("ClippyGroup")
1795                    .arg("-dr")
1796                    .arg("Clippy")
1797                    .arg("-var")
1798                    .arg("var.ClippyDir")
1799                    .arg("-out")
1800                    .arg(exe.join("ClippyGroup.wxs"))
1801                    .arg("-t")
1802                    .arg(etc.join("msi/remove-duplicates.xsl"))
1803                    .run(builder);
1804            }
1805            if built_tools.contains("miri") {
1806                command(&heat)
1807                    .current_dir(&exe)
1808                    .arg("dir")
1809                    .arg("miri")
1810                    .args(heat_flags)
1811                    .arg("-cg")
1812                    .arg("MiriGroup")
1813                    .arg("-dr")
1814                    .arg("Miri")
1815                    .arg("-var")
1816                    .arg("var.MiriDir")
1817                    .arg("-out")
1818                    .arg(exe.join("MiriGroup.wxs"))
1819                    .arg("-t")
1820                    .arg(etc.join("msi/remove-duplicates.xsl"))
1821                    .run(builder);
1822            }
1823            command(&heat)
1824                .current_dir(&exe)
1825                .arg("dir")
1826                .arg("rust-analysis")
1827                .args(heat_flags)
1828                .arg("-cg")
1829                .arg("AnalysisGroup")
1830                .arg("-dr")
1831                .arg("Analysis")
1832                .arg("-var")
1833                .arg("var.AnalysisDir")
1834                .arg("-out")
1835                .arg(exe.join("AnalysisGroup.wxs"))
1836                .arg("-t")
1837                .arg(etc.join("msi/remove-duplicates.xsl"))
1838                .run(builder);
1839            if target.is_windows_gnu() {
1840                command(&heat)
1841                    .current_dir(&exe)
1842                    .arg("dir")
1843                    .arg("rust-mingw")
1844                    .args(heat_flags)
1845                    .arg("-cg")
1846                    .arg("GccGroup")
1847                    .arg("-dr")
1848                    .arg("Gcc")
1849                    .arg("-var")
1850                    .arg("var.GccDir")
1851                    .arg("-out")
1852                    .arg(exe.join("GccGroup.wxs"))
1853                    .run(builder);
1854            }
1855
1856            let candle = |input: &Path| {
1857                let output = exe.join(input.file_stem().unwrap()).with_extension("wixobj");
1858                let arch = if target.contains("x86_64") { "x64" } else { "x86" };
1859                let mut cmd = command(&candle);
1860                cmd.current_dir(&exe)
1861                    .arg("-nologo")
1862                    .arg("-dRustcDir=rustc")
1863                    .arg("-dCargoDir=cargo")
1864                    .arg("-dStdDir=rust-std")
1865                    .arg("-dAnalysisDir=rust-analysis")
1866                    .arg("-arch")
1867                    .arg(arch)
1868                    .arg("-out")
1869                    .arg(&output)
1870                    .arg(input);
1871                add_env(builder, &mut cmd, target);
1872
1873                if built_tools.contains("clippy") {
1874                    cmd.arg("-dClippyDir=clippy");
1875                }
1876                if built_tools.contains("rust-docs") {
1877                    cmd.arg("-dDocsDir=rust-docs");
1878                }
1879                if built_tools.contains("rust-analyzer") {
1880                    cmd.arg("-dRustAnalyzerDir=rust-analyzer");
1881                }
1882                if built_tools.contains("miri") {
1883                    cmd.arg("-dMiriDir=miri");
1884                }
1885                if target.is_windows_gnu() {
1886                    cmd.arg("-dGccDir=rust-mingw");
1887                }
1888                cmd.run(builder);
1889            };
1890            candle(&xform(&etc.join("msi/rust.wxs")));
1891            candle(&etc.join("msi/ui.wxs"));
1892            candle(&etc.join("msi/rustwelcomedlg.wxs"));
1893            candle("RustcGroup.wxs".as_ref());
1894            if built_tools.contains("rust-docs") {
1895                candle("DocsGroup.wxs".as_ref());
1896            }
1897            candle("CargoGroup.wxs".as_ref());
1898            candle("StdGroup.wxs".as_ref());
1899            if built_tools.contains("clippy") {
1900                candle("ClippyGroup.wxs".as_ref());
1901            }
1902            if built_tools.contains("miri") {
1903                candle("MiriGroup.wxs".as_ref());
1904            }
1905            if built_tools.contains("rust-analyzer") {
1906                candle("RustAnalyzerGroup.wxs".as_ref());
1907            }
1908            candle("AnalysisGroup.wxs".as_ref());
1909
1910            if target.is_windows_gnu() {
1911                candle("GccGroup.wxs".as_ref());
1912            }
1913
1914            builder.create(&exe.join("LICENSE.rtf"), &rtf);
1915            builder.install(&etc.join("gfx/banner.bmp"), &exe, 0o644);
1916            builder.install(&etc.join("gfx/dialogbg.bmp"), &exe, 0o644);
1917
1918            builder.info(&format!("building `msi` installer with {light:?}"));
1919            let filename = format!("{}-{}.msi", pkgname(builder, "rust"), target.triple);
1920            let mut cmd = command(&light);
1921            cmd.arg("-nologo")
1922                .arg("-ext")
1923                .arg("WixUIExtension")
1924                .arg("-ext")
1925                .arg("WixUtilExtension")
1926                .arg("-out")
1927                .arg(exe.join(&filename))
1928                .arg("rust.wixobj")
1929                .arg("ui.wixobj")
1930                .arg("rustwelcomedlg.wixobj")
1931                .arg("RustcGroup.wixobj")
1932                .arg("CargoGroup.wixobj")
1933                .arg("StdGroup.wixobj")
1934                .arg("AnalysisGroup.wixobj")
1935                .current_dir(&exe);
1936
1937            if built_tools.contains("clippy") {
1938                cmd.arg("ClippyGroup.wixobj");
1939            }
1940            if built_tools.contains("miri") {
1941                cmd.arg("MiriGroup.wixobj");
1942            }
1943            if built_tools.contains("rust-analyzer") {
1944                cmd.arg("RustAnalyzerGroup.wixobj");
1945            }
1946            if built_tools.contains("rust-docs") {
1947                cmd.arg("DocsGroup.wixobj");
1948            }
1949
1950            if target.is_windows_gnu() {
1951                cmd.arg("GccGroup.wixobj");
1952            }
1953            // ICE57 wrongly complains about the shortcuts
1954            cmd.arg("-sice:ICE57");
1955
1956            let _time = timeit(builder);
1957            cmd.run(builder);
1958
1959            if !builder.config.dry_run() {
1960                t!(move_file(exe.join(&filename), distdir(builder).join(&filename)));
1961            }
1962        }
1963    }
1964}
1965
1966fn add_env(builder: &Builder<'_>, cmd: &mut BootstrapCommand, target: TargetSelection) {
1967    let mut parts = builder.version.split('.');
1968    cmd.env("CFG_RELEASE_INFO", builder.rust_version())
1969        .env("CFG_RELEASE_NUM", &builder.version)
1970        .env("CFG_RELEASE", builder.rust_release())
1971        .env("CFG_VER_MAJOR", parts.next().unwrap())
1972        .env("CFG_VER_MINOR", parts.next().unwrap())
1973        .env("CFG_VER_PATCH", parts.next().unwrap())
1974        .env("CFG_VER_BUILD", "0") // just needed to build
1975        .env("CFG_PACKAGE_VERS", builder.rust_package_vers())
1976        .env("CFG_PACKAGE_NAME", pkgname(builder, "rust"))
1977        .env("CFG_BUILD", target.triple)
1978        .env("CFG_CHANNEL", &builder.config.channel);
1979
1980    if target.contains("windows-gnullvm") {
1981        cmd.env("CFG_MINGW", "1").env("CFG_ABI", "LLVM");
1982    } else if target.is_windows_gnu() {
1983        cmd.env("CFG_MINGW", "1").env("CFG_ABI", "GNU");
1984    } else {
1985        cmd.env("CFG_MINGW", "0").env("CFG_ABI", "MSVC");
1986    }
1987}
1988
1989fn install_llvm_file(
1990    builder: &Builder<'_>,
1991    source: &Path,
1992    destination: &Path,
1993    install_symlink: bool,
1994) {
1995    if builder.config.dry_run() {
1996        return;
1997    }
1998
1999    if source.is_symlink() {
2000        // If we have a symlink like libLLVM-18.so -> libLLVM.so.18.1, install the target of the
2001        // symlink, which is what will actually get loaded at runtime.
2002        builder.install(&t!(fs::canonicalize(source)), destination, 0o644);
2003
2004        let full_dest = destination.join(source.file_name().unwrap());
2005        if install_symlink {
2006            // For download-ci-llvm, also install the symlink, to match what LLVM does. Using a
2007            // symlink is fine here, as this is not a rustup component.
2008            builder.copy_link(source, &full_dest);
2009        } else {
2010            // Otherwise, replace the symlink with an equivalent linker script. This is used when
2011            // projects like miri link against librustc_driver.so. We don't use a symlink, as
2012            // these are not allowed inside rustup components.
2013            let link = t!(fs::read_link(source));
2014            let mut linker_script = t!(fs::File::create(full_dest));
2015            t!(write!(linker_script, "INPUT({})\n", link.display()));
2016
2017            // We also want the linker script to have the same mtime as the source, otherwise it
2018            // can trigger rebuilds.
2019            let meta = t!(fs::metadata(source));
2020            if let Ok(mtime) = meta.modified() {
2021                t!(linker_script.set_modified(mtime));
2022            }
2023        }
2024    } else {
2025        builder.install(source, destination, 0o644);
2026    }
2027}
2028
2029/// Maybe add LLVM object files to the given destination lib-dir. Allows either static or dynamic linking.
2030///
2031/// Returns whether the files were actually copied.
2032fn maybe_install_llvm(
2033    builder: &Builder<'_>,
2034    target: TargetSelection,
2035    dst_libdir: &Path,
2036    install_symlink: bool,
2037) -> bool {
2038    // If the LLVM was externally provided, then we don't currently copy
2039    // artifacts into the sysroot. This is not necessarily the right
2040    // choice (in particular, it will require the LLVM dylib to be in
2041    // the linker's load path at runtime), but the common use case for
2042    // external LLVMs is distribution provided LLVMs, and in that case
2043    // they're usually in the standard search path (e.g., /usr/lib) and
2044    // copying them here is going to cause problems as we may end up
2045    // with the wrong files and isn't what distributions want.
2046    //
2047    // This behavior may be revisited in the future though.
2048    //
2049    // NOTE: this intentionally doesn't use `is_rust_llvm`; whether this is patched or not doesn't matter,
2050    // we only care if the shared object itself is managed by bootstrap.
2051    //
2052    // If the LLVM is coming from ourselves (just from CI) though, we
2053    // still want to install it, as it otherwise won't be available.
2054    if builder.is_system_llvm(target) {
2055        return false;
2056    }
2057
2058    // On macOS, rustc (and LLVM tools) link to an unversioned libLLVM.dylib
2059    // instead of libLLVM-11-rust-....dylib, as on linux. It's not entirely
2060    // clear why this is the case, though. llvm-config will emit the versioned
2061    // paths and we don't want those in the sysroot (as we're expecting
2062    // unversioned paths).
2063    if target.contains("apple-darwin") && builder.llvm_link_shared() {
2064        let src_libdir = builder.llvm_out(target).join("lib");
2065        let llvm_dylib_path = src_libdir.join("libLLVM.dylib");
2066        if llvm_dylib_path.exists() {
2067            builder.install(&llvm_dylib_path, dst_libdir, 0o644);
2068        }
2069        !builder.config.dry_run()
2070    } else if let llvm::LlvmBuildStatus::AlreadyBuilt(llvm::LlvmResult { llvm_config, .. }) =
2071        llvm::prebuilt_llvm_config(builder, target, true)
2072    {
2073        let mut cmd = command(llvm_config);
2074        cmd.arg("--libfiles");
2075        builder.verbose(|| println!("running {cmd:?}"));
2076        let files = cmd.run_capture_stdout(builder).stdout();
2077        let build_llvm_out = &builder.llvm_out(builder.config.build);
2078        let target_llvm_out = &builder.llvm_out(target);
2079        for file in files.trim_end().split(' ') {
2080            // If we're not using a custom LLVM, make sure we package for the target.
2081            let file = if let Ok(relative_path) = Path::new(file).strip_prefix(build_llvm_out) {
2082                target_llvm_out.join(relative_path)
2083            } else {
2084                PathBuf::from(file)
2085            };
2086            install_llvm_file(builder, &file, dst_libdir, install_symlink);
2087        }
2088        !builder.config.dry_run()
2089    } else {
2090        false
2091    }
2092}
2093
2094/// Maybe add libLLVM.so to the target lib-dir for linking.
2095pub fn maybe_install_llvm_target(builder: &Builder<'_>, target: TargetSelection, sysroot: &Path) {
2096    let dst_libdir = sysroot.join("lib/rustlib").join(target).join("lib");
2097    // We do not need to copy LLVM files into the sysroot if it is not
2098    // dynamically linked; it is already included into librustc_llvm
2099    // statically.
2100    if builder.llvm_link_shared() {
2101        maybe_install_llvm(builder, target, &dst_libdir, false);
2102    }
2103}
2104
2105/// Maybe add libLLVM.so to the runtime lib-dir for rustc itself.
2106pub fn maybe_install_llvm_runtime(builder: &Builder<'_>, target: TargetSelection, sysroot: &Path) {
2107    let dst_libdir =
2108        sysroot.join(builder.sysroot_libdir_relative(Compiler { stage: 1, host: target }));
2109    // We do not need to copy LLVM files into the sysroot if it is not
2110    // dynamically linked; it is already included into librustc_llvm
2111    // statically.
2112    if builder.llvm_link_shared() {
2113        maybe_install_llvm(builder, target, &dst_libdir, false);
2114    }
2115}
2116
2117#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2118pub struct LlvmTools {
2119    pub target: TargetSelection,
2120}
2121
2122impl Step for LlvmTools {
2123    type Output = Option<GeneratedTarball>;
2124    const ONLY_HOSTS: bool = true;
2125    const DEFAULT: bool = true;
2126
2127    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2128        let default = should_build_extended_tool(run.builder, "llvm-tools");
2129
2130        let mut run = run.alias("llvm-tools");
2131        for tool in LLVM_TOOLS {
2132            run = run.alias(tool);
2133        }
2134
2135        run.default_condition(default)
2136    }
2137
2138    fn make_run(run: RunConfig<'_>) {
2139        run.builder.ensure(LlvmTools { target: run.target });
2140    }
2141
2142    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2143        fn tools_to_install(paths: &[PathBuf]) -> Vec<&'static str> {
2144            let mut tools = vec![];
2145
2146            for path in paths {
2147                let path = path.to_str().unwrap();
2148
2149                // Include all tools if path is 'llvm-tools'.
2150                if path == "llvm-tools" {
2151                    return LLVM_TOOLS.to_owned();
2152                }
2153
2154                for tool in LLVM_TOOLS {
2155                    if path == *tool {
2156                        tools.push(*tool);
2157                    }
2158                }
2159            }
2160
2161            // If no specific tool is requested, include all tools.
2162            if tools.is_empty() {
2163                tools = LLVM_TOOLS.to_owned();
2164            }
2165
2166            tools
2167        }
2168
2169        let target = self.target;
2170
2171        /* run only if llvm-config isn't used */
2172        if let Some(config) = builder.config.target_config.get(&target) {
2173            if let Some(ref _s) = config.llvm_config {
2174                builder.info(&format!("Skipping LlvmTools ({target}): external LLVM"));
2175                return None;
2176            }
2177        }
2178
2179        builder.ensure(crate::core::build_steps::llvm::Llvm { target });
2180
2181        let mut tarball = Tarball::new(builder, "llvm-tools", &target.triple);
2182        tarball.set_overlay(OverlayKind::Llvm);
2183        tarball.is_preview(true);
2184
2185        if builder.config.llvm_tools_enabled {
2186            // Prepare the image directory
2187            let src_bindir = builder.llvm_out(target).join("bin");
2188            let dst_bindir = format!("lib/rustlib/{}/bin", target.triple);
2189            for tool in tools_to_install(&builder.paths) {
2190                let exe = src_bindir.join(exe(tool, target));
2191                tarball.add_file(&exe, &dst_bindir, 0o755);
2192            }
2193        }
2194
2195        // Copy libLLVM.so to the target lib dir as well, so the RPATH like
2196        // `$ORIGIN/../lib` can find it. It may also be used as a dependency
2197        // of `rustc-dev` to support the inherited `-lLLVM` when using the
2198        // compiler libraries.
2199        maybe_install_llvm_target(builder, target, tarball.image_dir());
2200
2201        Some(tarball.generate())
2202    }
2203}
2204
2205#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)]
2206pub struct LlvmBitcodeLinker {
2207    pub compiler: Compiler,
2208    pub target: TargetSelection,
2209}
2210
2211impl Step for LlvmBitcodeLinker {
2212    type Output = Option<GeneratedTarball>;
2213    const DEFAULT: bool = true;
2214    const ONLY_HOSTS: bool = true;
2215
2216    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2217        let default = should_build_extended_tool(run.builder, "llvm-bitcode-linker");
2218        run.alias("llvm-bitcode-linker").default_condition(default)
2219    }
2220
2221    fn make_run(run: RunConfig<'_>) {
2222        run.builder.ensure(LlvmBitcodeLinker {
2223            compiler: run.builder.compiler_for(
2224                run.builder.top_stage,
2225                run.builder.config.build,
2226                run.target,
2227            ),
2228            target: run.target,
2229        });
2230    }
2231
2232    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2233        let compiler = self.compiler;
2234        let target = self.target;
2235
2236        let llbc_linker =
2237            builder.ensure(tool::LlvmBitcodeLinker { compiler, target, extra_features: vec![] });
2238
2239        let self_contained_bin_dir = format!("lib/rustlib/{}/bin/self-contained", target.triple);
2240
2241        // Prepare the image directory
2242        let mut tarball = Tarball::new(builder, "llvm-bitcode-linker", &target.triple);
2243        tarball.set_overlay(OverlayKind::LlvmBitcodeLinker);
2244        tarball.is_preview(true);
2245
2246        tarball.add_file(llbc_linker, self_contained_bin_dir, 0o755);
2247
2248        Some(tarball.generate())
2249    }
2250}
2251
2252/// Tarball intended for internal consumption to ease rustc/std development.
2253///
2254/// Should not be considered stable by end users.
2255///
2256/// In practice, this is the tarball that gets downloaded and used by
2257/// `llvm.download-ci-llvm`.
2258///
2259/// (Don't confuse this with [`RustcDev`], with a `c`!)
2260#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2261pub struct RustDev {
2262    pub target: TargetSelection,
2263}
2264
2265impl Step for RustDev {
2266    type Output = Option<GeneratedTarball>;
2267    const DEFAULT: bool = true;
2268    const ONLY_HOSTS: bool = true;
2269
2270    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2271        run.alias("rust-dev")
2272    }
2273
2274    fn make_run(run: RunConfig<'_>) {
2275        run.builder.ensure(RustDev { target: run.target });
2276    }
2277
2278    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2279        let target = self.target;
2280
2281        /* run only if llvm-config isn't used */
2282        if let Some(config) = builder.config.target_config.get(&target) {
2283            if let Some(ref _s) = config.llvm_config {
2284                builder.info(&format!("Skipping RustDev ({target}): external LLVM"));
2285                return None;
2286            }
2287        }
2288
2289        let mut tarball = Tarball::new(builder, "rust-dev", &target.triple);
2290        tarball.set_overlay(OverlayKind::Llvm);
2291        // LLVM requires a shared object symlink to exist on some platforms.
2292        tarball.permit_symlinks(true);
2293
2294        builder.ensure(crate::core::build_steps::llvm::Llvm { target });
2295
2296        let src_bindir = builder.llvm_out(target).join("bin");
2297        // If updating this, you likely want to change
2298        // src/bootstrap/download-ci-llvm-stamp as well, otherwise local users
2299        // will not pick up the extra file until LLVM gets bumped.
2300        // We should include all the build artifacts obtained from a source build,
2301        // so that you can use the downloadable LLVM as if you’ve just run a full source build.
2302        if src_bindir.exists() {
2303            for entry in walkdir::WalkDir::new(&src_bindir) {
2304                let entry = t!(entry);
2305                if entry.file_type().is_file() && !entry.path_is_symlink() {
2306                    let name = entry.file_name().to_str().unwrap();
2307                    tarball.add_file(src_bindir.join(name), "bin", 0o755);
2308                }
2309            }
2310        }
2311
2312        if builder.config.lld_enabled {
2313            // We want to package `lld` to use it with `download-ci-llvm`.
2314            let lld_out = builder.ensure(crate::core::build_steps::llvm::Lld { target });
2315
2316            // We don't build LLD on some platforms, so only add it if it exists
2317            let lld_path = lld_out.join("bin").join(exe("lld", target));
2318            if lld_path.exists() {
2319                tarball.add_file(lld_path, "bin", 0o755);
2320            }
2321        }
2322
2323        tarball.add_file(builder.llvm_filecheck(target), "bin", 0o755);
2324
2325        // Copy the include directory as well; needed mostly to build
2326        // librustc_llvm properly (e.g., llvm-config.h is in here). But also
2327        // just broadly useful to be able to link against the bundled LLVM.
2328        tarball.add_dir(builder.llvm_out(target).join("include"), "include");
2329
2330        // Copy libLLVM.so to the target lib dir as well, so the RPATH like
2331        // `$ORIGIN/../lib` can find it. It may also be used as a dependency
2332        // of `rustc-dev` to support the inherited `-lLLVM` when using the
2333        // compiler libraries.
2334        let dst_libdir = tarball.image_dir().join("lib");
2335        maybe_install_llvm(builder, target, &dst_libdir, true);
2336        let link_type = if builder.llvm_link_shared() { "dynamic" } else { "static" };
2337        t!(std::fs::write(tarball.image_dir().join("link-type.txt"), link_type), dst_libdir);
2338
2339        // Copy the `compiler-rt` source, so that `library/profiler_builtins`
2340        // can potentially use it to build the profiler runtime without needing
2341        // to check out the LLVM submodule.
2342        copy_src_dirs(
2343            builder,
2344            &builder.src.join("src").join("llvm-project"),
2345            &["compiler-rt"],
2346            // The test subdirectory is much larger than the rest of the source,
2347            // and we currently don't use these test files anyway.
2348            &["compiler-rt/test"],
2349            tarball.image_dir(),
2350        );
2351
2352        Some(tarball.generate())
2353    }
2354}
2355
2356/// Tarball intended for internal consumption to ease rustc/std development.
2357///
2358/// Should not be considered stable by end users.
2359#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2360pub struct Bootstrap {
2361    pub target: TargetSelection,
2362}
2363
2364impl Step for Bootstrap {
2365    type Output = Option<GeneratedTarball>;
2366    const DEFAULT: bool = false;
2367    const ONLY_HOSTS: bool = true;
2368
2369    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2370        run.alias("bootstrap")
2371    }
2372
2373    fn make_run(run: RunConfig<'_>) {
2374        run.builder.ensure(Bootstrap { target: run.target });
2375    }
2376
2377    fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> {
2378        let target = self.target;
2379
2380        let tarball = Tarball::new(builder, "bootstrap", &target.triple);
2381
2382        let bootstrap_outdir = &builder.bootstrap_out;
2383        for file in &["bootstrap", "rustc", "rustdoc", "sccache-plus-cl"] {
2384            tarball.add_file(bootstrap_outdir.join(exe(file, target)), "bootstrap/bin", 0o755);
2385        }
2386
2387        Some(tarball.generate())
2388    }
2389}
2390
2391/// Tarball containing a prebuilt version of the build-manifest tool, intended to be used by the
2392/// release process to avoid cloning the monorepo and building stuff.
2393///
2394/// Should not be considered stable by end users.
2395#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2396pub struct BuildManifest {
2397    pub target: TargetSelection,
2398}
2399
2400impl Step for BuildManifest {
2401    type Output = GeneratedTarball;
2402    const DEFAULT: bool = false;
2403    const ONLY_HOSTS: bool = true;
2404
2405    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2406        run.alias("build-manifest")
2407    }
2408
2409    fn make_run(run: RunConfig<'_>) {
2410        run.builder.ensure(BuildManifest { target: run.target });
2411    }
2412
2413    fn run(self, builder: &Builder<'_>) -> GeneratedTarball {
2414        let build_manifest = builder.tool_exe(Tool::BuildManifest);
2415
2416        let tarball = Tarball::new(builder, "build-manifest", &self.target.triple);
2417        tarball.add_file(build_manifest, "bin", 0o755);
2418        tarball.generate()
2419    }
2420}
2421
2422/// Tarball containing artifacts necessary to reproduce the build of rustc.
2423///
2424/// Currently this is the PGO profile data.
2425///
2426/// Should not be considered stable by end users.
2427#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2428pub struct ReproducibleArtifacts {
2429    pub target: TargetSelection,
2430}
2431
2432impl Step for ReproducibleArtifacts {
2433    type Output = Option<GeneratedTarball>;
2434    const DEFAULT: bool = true;
2435    const ONLY_HOSTS: bool = true;
2436
2437    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2438        run.alias("reproducible-artifacts")
2439    }
2440
2441    fn make_run(run: RunConfig<'_>) {
2442        run.builder.ensure(ReproducibleArtifacts { target: run.target });
2443    }
2444
2445    fn run(self, builder: &Builder<'_>) -> Self::Output {
2446        let mut added_anything = false;
2447        let tarball = Tarball::new(builder, "reproducible-artifacts", &self.target.triple);
2448        if let Some(path) = builder.config.rust_profile_use.as_ref() {
2449            tarball.add_file(path, ".", 0o644);
2450            added_anything = true;
2451        }
2452        if let Some(path) = builder.config.llvm_profile_use.as_ref() {
2453            tarball.add_file(path, ".", 0o644);
2454            added_anything = true;
2455        }
2456        for profile in &builder.config.reproducible_artifacts {
2457            tarball.add_file(profile, ".", 0o644);
2458            added_anything = true;
2459        }
2460        if added_anything { Some(tarball.generate()) } else { None }
2461    }
2462}