bootstrap/utils/
tarball.rs

1//! Facilitates the management and generation of tarballs.
2//!
3//! Tarballs efficiently hold Rust compiler build artifacts and
4//! capture a snapshot of each bootstrap stage.
5//! In uplifting, a tarball from Stage N captures essential components
6//! to assemble Stage N + 1 compiler.
7
8use std::path::{Path, PathBuf};
9
10use crate::FileType;
11use crate::core::build_steps::dist::distdir;
12use crate::core::builder::{Builder, Kind};
13use crate::core::config::BUILDER_CONFIG_FILENAME;
14use crate::utils::exec::BootstrapCommand;
15use crate::utils::helpers::{move_file, t};
16use crate::utils::{channel, helpers};
17
18#[derive(Copy, Clone)]
19pub(crate) enum OverlayKind {
20    Rust,
21    Llvm,
22    Cargo,
23    Clippy,
24    Miri,
25    Rustfmt,
26    RustAnalyzer,
27    RustcCodegenCranelift,
28    RustcCodegenGcc,
29    Gcc,
30    LlvmBitcodeLinker,
31}
32
33impl OverlayKind {
34    fn legal_and_readme(&self) -> &[&str] {
35        match self {
36            OverlayKind::Rust => &["COPYRIGHT", "LICENSE-APACHE", "LICENSE-MIT", "README.md"],
37            OverlayKind::Llvm => {
38                &["src/llvm-project/llvm/LICENSE.TXT", "src/llvm-project/llvm/README.txt"]
39            }
40            OverlayKind::Cargo => &[
41                "src/tools/cargo/README.md",
42                "src/tools/cargo/LICENSE-MIT",
43                "src/tools/cargo/LICENSE-APACHE",
44                "src/tools/cargo/LICENSE-THIRD-PARTY",
45            ],
46            OverlayKind::Clippy => &[
47                "src/tools/clippy/README.md",
48                "src/tools/clippy/LICENSE-APACHE",
49                "src/tools/clippy/LICENSE-MIT",
50            ],
51            OverlayKind::Miri => &[
52                "src/tools/miri/README.md",
53                "src/tools/miri/LICENSE-APACHE",
54                "src/tools/miri/LICENSE-MIT",
55            ],
56            OverlayKind::Rustfmt => &[
57                "src/tools/rustfmt/README.md",
58                "src/tools/rustfmt/LICENSE-APACHE",
59                "src/tools/rustfmt/LICENSE-MIT",
60            ],
61            OverlayKind::RustAnalyzer => &[
62                "src/tools/rust-analyzer/README.md",
63                "src/tools/rust-analyzer/LICENSE-APACHE",
64                "src/tools/rust-analyzer/LICENSE-MIT",
65            ],
66            OverlayKind::RustcCodegenCranelift => &[
67                "compiler/rustc_codegen_cranelift/Readme.md",
68                "compiler/rustc_codegen_cranelift/LICENSE-APACHE",
69                "compiler/rustc_codegen_cranelift/LICENSE-MIT",
70            ],
71            OverlayKind::RustcCodegenGcc => &[
72                "compiler/rustc_codegen_gcc/Readme.md",
73                "compiler/rustc_codegen_gcc/LICENSE-APACHE",
74                "compiler/rustc_codegen_gcc/LICENSE-MIT",
75            ],
76            OverlayKind::LlvmBitcodeLinker => &[
77                "COPYRIGHT",
78                "LICENSE-APACHE",
79                "LICENSE-MIT",
80                "src/tools/llvm-bitcode-linker/README.md",
81            ],
82            OverlayKind::Gcc => &[
83                "src/gcc/README",
84                "src/gcc/COPYING",
85                "src/gcc/COPYING.LIB",
86                "src/gcc/COPYING.RUNTIME",
87                "src/gcc/COPYING3",
88                "src/gcc/COPYING3.LIB",
89            ],
90        }
91    }
92
93    fn version(&self, builder: &Builder<'_>) -> String {
94        match self {
95            OverlayKind::Rust => builder.rust_version(),
96            OverlayKind::Llvm => builder.rust_version(),
97            OverlayKind::Cargo => {
98                builder.cargo_info.version(builder, &builder.release_num("cargo"))
99            }
100            OverlayKind::Clippy => {
101                builder.clippy_info.version(builder, &builder.release_num("clippy"))
102            }
103            OverlayKind::Miri => builder.miri_info.version(builder, &builder.release_num("miri")),
104            OverlayKind::Rustfmt => {
105                builder.rustfmt_info.version(builder, &builder.release_num("rustfmt"))
106            }
107            OverlayKind::RustAnalyzer => builder
108                .rust_analyzer_info
109                .version(builder, &builder.release_num("rust-analyzer/crates/rust-analyzer")),
110            OverlayKind::RustcCodegenCranelift => builder.rust_version(),
111            OverlayKind::RustcCodegenGcc => builder.rust_version(),
112            OverlayKind::LlvmBitcodeLinker => builder.rust_version(),
113            OverlayKind::Gcc => builder.rust_version(),
114        }
115    }
116}
117
118pub(crate) struct Tarball<'a> {
119    builder: &'a Builder<'a>,
120
121    pkgname: String,
122    component: String,
123    target: Option<String>,
124    product_name: String,
125    overlay: OverlayKind,
126
127    temp_dir: PathBuf,
128    image_dir: PathBuf,
129    overlay_dir: PathBuf,
130    bulk_dirs: Vec<PathBuf>,
131
132    include_target_in_component_name: bool,
133    is_preview: bool,
134    permit_symlinks: bool,
135}
136
137impl<'a> Tarball<'a> {
138    pub(crate) fn new(builder: &'a Builder<'a>, component: &str, target: &str) -> Self {
139        Self::new_inner(builder, component, Some(target.into()))
140    }
141
142    pub(crate) fn new_targetless(builder: &'a Builder<'a>, component: &str) -> Self {
143        Self::new_inner(builder, component, None)
144    }
145
146    fn new_inner(builder: &'a Builder<'a>, component: &str, target: Option<String>) -> Self {
147        let pkgname = crate::core::build_steps::dist::pkgname(builder, component);
148
149        let mut temp_dir = builder.out.join("tmp").join("tarball").join(component);
150        if let Some(target) = &target {
151            temp_dir = temp_dir.join(target);
152        }
153        let _ = std::fs::remove_dir_all(&temp_dir);
154
155        let image_dir = temp_dir.join("image");
156        let overlay_dir = temp_dir.join("overlay");
157
158        Self {
159            builder,
160
161            pkgname,
162            component: component.into(),
163            target,
164            product_name: "Rust".into(),
165            overlay: OverlayKind::Rust,
166
167            temp_dir,
168            image_dir,
169            overlay_dir,
170            bulk_dirs: Vec::new(),
171
172            include_target_in_component_name: false,
173            is_preview: false,
174            permit_symlinks: false,
175        }
176    }
177
178    pub(crate) fn set_overlay(&mut self, overlay: OverlayKind) {
179        self.overlay = overlay;
180    }
181
182    pub(crate) fn set_product_name(&mut self, name: &str) {
183        self.product_name = name.into();
184    }
185
186    pub(crate) fn include_target_in_component_name(&mut self, include: bool) {
187        self.include_target_in_component_name = include;
188    }
189
190    pub(crate) fn is_preview(&mut self, is: bool) {
191        self.is_preview = is;
192    }
193
194    pub(crate) fn permit_symlinks(&mut self, flag: bool) {
195        self.permit_symlinks = flag;
196    }
197
198    pub(crate) fn image_dir(&self) -> &Path {
199        t!(std::fs::create_dir_all(&self.image_dir));
200        &self.image_dir
201    }
202
203    pub(crate) fn add_file(
204        &self,
205        src: impl AsRef<Path>,
206        destdir: impl AsRef<Path>,
207        file_type: FileType,
208    ) {
209        // create_dir_all fails to create `foo/bar/.`, so when the destination is "." this simply
210        // uses the base directory as the destination directory.
211        let destdir = if destdir.as_ref() == Path::new(".") {
212            self.image_dir.clone()
213        } else {
214            self.image_dir.join(destdir.as_ref())
215        };
216
217        t!(std::fs::create_dir_all(&destdir));
218        self.builder.install(src.as_ref(), &destdir, file_type);
219    }
220
221    pub(crate) fn add_renamed_file(
222        &self,
223        src: impl AsRef<Path>,
224        destdir: impl AsRef<Path>,
225        new_name: &str,
226        file_type: FileType,
227    ) {
228        let destdir = self.image_dir.join(destdir.as_ref());
229        t!(std::fs::create_dir_all(&destdir));
230        self.builder.copy_link(src.as_ref(), &destdir.join(new_name), file_type);
231    }
232
233    pub(crate) fn add_legal_and_readme_to(&self, destdir: impl AsRef<Path>) {
234        for file in self.overlay.legal_and_readme() {
235            self.add_file(self.builder.src.join(file), destdir.as_ref(), FileType::Regular);
236        }
237    }
238
239    pub(crate) fn add_dir(&self, src: impl AsRef<Path>, dest: impl AsRef<Path>) {
240        let dest = self.image_dir.join(dest.as_ref());
241
242        t!(std::fs::create_dir_all(&dest));
243        self.builder.cp_link_r(src.as_ref(), &dest);
244    }
245
246    pub(crate) fn add_bulk_dir(&mut self, src: impl AsRef<Path>, dest: impl AsRef<Path>) {
247        self.bulk_dirs.push(dest.as_ref().to_path_buf());
248        self.add_dir(src, dest);
249    }
250
251    pub(crate) fn generate(self) -> GeneratedTarball {
252        let mut component_name = self.component.clone();
253        if self.is_preview {
254            component_name.push_str("-preview");
255        }
256        if self.include_target_in_component_name {
257            component_name.push('-');
258            component_name.push_str(
259                self.target
260                    .as_ref()
261                    .expect("include_target_in_component_name used in a targetless tarball"),
262            );
263        }
264
265        self.run(|this, cmd| {
266            cmd.arg("generate")
267                .arg("--image-dir")
268                .arg(&this.image_dir)
269                .arg(format!("--component-name={component_name}"));
270
271            if let Some((dir, dirs)) = this.bulk_dirs.split_first() {
272                let mut arg = dir.as_os_str().to_os_string();
273                for dir in dirs {
274                    arg.push(",");
275                    arg.push(dir);
276                }
277                cmd.arg("--bulk-dirs").arg(&arg);
278            }
279
280            this.non_bare_args(cmd);
281        })
282    }
283
284    pub(crate) fn combine(self, tarballs: &[GeneratedTarball]) -> GeneratedTarball {
285        let mut input_tarballs = tarballs[0].path.as_os_str().to_os_string();
286        for tarball in &tarballs[1..] {
287            input_tarballs.push(",");
288            input_tarballs.push(&tarball.path);
289        }
290
291        self.run(|this, cmd| {
292            cmd.arg("combine").arg("--input-tarballs").arg(input_tarballs);
293            this.non_bare_args(cmd);
294        })
295    }
296
297    pub(crate) fn bare(self) -> GeneratedTarball {
298        // Bare tarballs should have the top level directory match the package
299        // name, not "image". We rename the image directory just before passing
300        // into rust-installer.
301        let dest = self.temp_dir.join(self.package_name());
302        t!(move_file(&self.image_dir, &dest));
303
304        self.run(|this, cmd| {
305            let distdir = distdir(this.builder);
306            t!(std::fs::create_dir_all(&distdir));
307            cmd.arg("tarball")
308                .arg("--input")
309                .arg(&dest)
310                .arg("--output")
311                .arg(distdir.join(this.package_name()));
312        })
313    }
314
315    fn package_name(&self) -> String {
316        if let Some(target) = &self.target {
317            format!("{}-{}", self.pkgname, target)
318        } else {
319            self.pkgname.clone()
320        }
321    }
322
323    fn non_bare_args(&self, cmd: &mut BootstrapCommand) {
324        cmd.arg("--rel-manifest-dir=rustlib")
325            .arg("--legacy-manifest-dirs=rustlib,cargo")
326            .arg(format!("--product-name={}", self.product_name))
327            .arg(format!("--success-message={} installed.", self.component))
328            .arg(format!("--package-name={}", self.package_name()))
329            .arg("--non-installed-overlay")
330            .arg(&self.overlay_dir)
331            .arg("--output-dir")
332            .arg(distdir(self.builder));
333    }
334
335    fn run(self, build_cli: impl FnOnce(&Tarball<'a>, &mut BootstrapCommand)) -> GeneratedTarball {
336        t!(std::fs::create_dir_all(&self.overlay_dir));
337        self.builder.create(&self.overlay_dir.join("version"), &self.overlay.version(self.builder));
338        if let Some(info) = self.builder.rust_info().info() {
339            channel::write_commit_hash_file(&self.overlay_dir, &info.sha);
340            channel::write_commit_info_file(&self.overlay_dir, info);
341        }
342
343        // Add config file if present.
344        if let Some(config) = &self.builder.config.config {
345            self.add_renamed_file(
346                config,
347                &self.overlay_dir,
348                BUILDER_CONFIG_FILENAME,
349                FileType::Regular,
350            );
351        }
352
353        for file in self.overlay.legal_and_readme() {
354            self.builder.install(
355                &self.builder.src.join(file),
356                &self.overlay_dir,
357                FileType::Regular,
358            );
359        }
360
361        let mut cmd = self.builder.tool_cmd(crate::core::build_steps::tool::Tool::RustInstaller);
362
363        let package_name = self.package_name();
364        self.builder.info(&format!("Dist {package_name}"));
365        let _time = crate::utils::helpers::timeit(self.builder);
366
367        build_cli(&self, &mut cmd);
368        cmd.arg("--work-dir").arg(&self.temp_dir);
369        if let Some(formats) = &self.builder.config.dist_compression_formats {
370            assert!(!formats.is_empty(), "dist.compression-formats can't be empty");
371            cmd.arg("--compression-formats").arg(formats.join(","));
372        }
373
374        // For `x install` tarball files aren't needed, so we can speed up the process by not producing them.
375        let compression_profile = if self.builder.kind == Kind::Install {
376            self.builder.do_if_verbose(|| {
377                println!("Forcing dist.compression-profile = 'no-op' for `x install`.")
378            });
379            // "no-op" indicates that the rust-installer won't produce compressed tarball sources.
380            "no-op"
381        } else {
382            assert!(
383                self.builder.config.dist_compression_profile != "no-op",
384                "dist.compression-profile = 'no-op' can only be used for `x install`"
385            );
386
387            &self.builder.config.dist_compression_profile
388        };
389
390        cmd.args(["--compression-profile", compression_profile]);
391
392        // We want to use a pinned modification time for files in the archive
393        // to achieve better reproducibility. However, using the same mtime for all
394        // releases is not ideal, because it can break e.g. Cargo mtime checking
395        // (https://github.com/rust-lang/rust/issues/125578).
396        // Therefore, we set mtime to the date of the latest commit (if we're managed
397        // by git). In this way, the archive will still be always the same for a given commit
398        // (achieving reproducibility), but it will also change between different commits and
399        // Rust versions, so that it won't break mtime-based caches.
400        //
401        // Note that this only overrides the mtime of files, not directories, due to the
402        // limitations of the tarballer tool. Directories will have their mtime set to 2006.
403
404        // Get the UTC timestamp of the last git commit, if we're under git.
405        // We need to use UTC, so that anyone who tries to rebuild from the same commit
406        // gets the same timestamp.
407        if self.builder.rust_info().is_managed_git_subrepository() {
408            // %ct means committer date
409            let timestamp = helpers::git(Some(&self.builder.src))
410                .arg("log")
411                .arg("-1")
412                .arg("--format=%ct")
413                .run_capture_stdout(self.builder)
414                .stdout();
415            cmd.args(["--override-file-mtime", timestamp.trim()]);
416        }
417
418        cmd.run(self.builder);
419
420        // Ensure there are no symbolic links in the tarball. In particular,
421        // rustup-toolchain-install-master and most versions of Windows can't handle symbolic links.
422        let decompressed_output = self.temp_dir.join(&package_name);
423        if !self.builder.config.dry_run() && !self.permit_symlinks {
424            for entry in walkdir::WalkDir::new(&decompressed_output) {
425                let entry = t!(entry);
426                if entry.path_is_symlink() {
427                    panic!("generated a symlink in a tarball: {}", entry.path().display());
428                }
429            }
430        }
431
432        // Use either the first compression format defined, or "gz" as the default.
433        let ext = self
434            .builder
435            .config
436            .dist_compression_formats
437            .as_ref()
438            .and_then(|formats| formats.first())
439            .map(|s| s.as_str())
440            .unwrap_or("gz");
441
442        GeneratedTarball {
443            path: distdir(self.builder).join(format!("{package_name}.tar.{ext}")),
444            decompressed_output,
445            work: self.temp_dir,
446        }
447    }
448}
449
450#[derive(Debug, Clone)]
451pub struct GeneratedTarball {
452    path: PathBuf,
453    decompressed_output: PathBuf,
454    work: PathBuf,
455}
456
457impl GeneratedTarball {
458    pub(crate) fn tarball(&self) -> &Path {
459        &self.path
460    }
461
462    pub(crate) fn decompressed_output(&self) -> &Path {
463        &self.decompressed_output
464    }
465
466    pub(crate) fn work_dir(&self) -> &Path {
467        &self.work
468    }
469}