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