bootstrap/core/
download.rs

1use std::collections::HashMap;
2use std::env;
3use std::ffi::OsString;
4use std::fs::{self, File};
5use std::io::{BufRead, BufReader, BufWriter, ErrorKind, Write};
6use std::path::{Path, PathBuf};
7use std::sync::{Arc, Mutex, OnceLock};
8
9use build_helper::git::PathFreshness;
10use xz2::bufread::XzDecoder;
11
12use crate::core::config::{BUILDER_CONFIG_FILENAME, TargetSelection};
13use crate::utils::build_stamp::BuildStamp;
14use crate::utils::exec::{ExecutionContext, command};
15use crate::utils::helpers::{exe, hex_encode, move_file};
16use crate::{Config, t};
17
18static SHOULD_FIX_BINS_AND_DYLIBS: OnceLock<bool> = OnceLock::new();
19
20fn extract_curl_version(out: String) -> semver::Version {
21    // The output should look like this: "curl <major>.<minor>.<patch> ..."
22    out.lines()
23        .next()
24        .and_then(|line| line.split(" ").nth(1))
25        .and_then(|version| semver::Version::parse(version).ok())
26        .unwrap_or(semver::Version::new(1, 0, 0))
27}
28
29/// Generic helpers that are useful anywhere in bootstrap.
30impl Config {
31    pub fn is_verbose(&self) -> bool {
32        self.exec_ctx.is_verbose()
33    }
34
35    pub(crate) fn create<P: AsRef<Path>>(&self, path: P, s: &str) {
36        if self.dry_run() {
37            return;
38        }
39        t!(fs::write(path, s));
40    }
41
42    pub(crate) fn remove(&self, f: &Path) {
43        remove(&self.exec_ctx, f);
44    }
45
46    /// Create a temporary directory in `out` and return its path.
47    ///
48    /// NOTE: this temporary directory is shared between all steps;
49    /// if you need an empty directory, create a new subdirectory inside it.
50    pub(crate) fn tempdir(&self) -> PathBuf {
51        let tmp = self.out.join("tmp");
52        t!(fs::create_dir_all(&tmp));
53        tmp
54    }
55
56    /// Whether or not `fix_bin_or_dylib` needs to be run; can only be true
57    /// on NixOS
58    fn should_fix_bins_and_dylibs(&self) -> bool {
59        should_fix_bins_and_dylibs(self.patch_binaries_for_nix, &self.exec_ctx)
60    }
61
62    /// Modifies the interpreter section of 'fname' to fix the dynamic linker,
63    /// or the RPATH section, to fix the dynamic library search path
64    ///
65    /// This is only required on NixOS and uses the PatchELF utility to
66    /// change the interpreter/RPATH of ELF executables.
67    ///
68    /// Please see <https://nixos.org/patchelf.html> for more information
69    fn fix_bin_or_dylib(&self, fname: &Path) {
70        fix_bin_or_dylib(&self.out, fname, &self.exec_ctx);
71    }
72
73    fn download_file(&self, url: &str, dest_path: &Path, help_on_error: &str) {
74        let dwn_ctx: DownloadContext<'_> = self.into();
75        download_file(dwn_ctx, &self.out, url, dest_path, help_on_error);
76    }
77
78    fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) {
79        unpack(&self.exec_ctx, tarball, dst, pattern);
80    }
81
82    /// Returns whether the SHA256 checksum of `path` matches `expected`.
83    #[cfg(test)]
84    pub(crate) fn verify(&self, path: &Path, expected: &str) -> bool {
85        verify(&self.exec_ctx, path, expected)
86    }
87}
88
89fn recorded_entries(dst: &Path, pattern: &str) -> Option<BufWriter<File>> {
90    let name = if pattern == "rustc-dev" {
91        ".rustc-dev-contents"
92    } else if pattern.starts_with("rust-std") {
93        ".rust-std-contents"
94    } else {
95        return None;
96    };
97    Some(BufWriter::new(t!(File::create(dst.join(name)))))
98}
99
100#[derive(Clone)]
101enum DownloadSource {
102    CI,
103    Dist,
104}
105
106/// Functions that are only ever called once, but named for clarity and to avoid thousand-line functions.
107impl Config {
108    pub(crate) fn download_clippy(&self) -> PathBuf {
109        self.do_if_verbose(|| println!("downloading stage0 clippy artifacts"));
110
111        let date = &self.stage0_metadata.compiler.date;
112        let version = &self.stage0_metadata.compiler.version;
113        let host = self.host_target;
114
115        let clippy_stamp =
116            BuildStamp::new(&self.initial_sysroot).with_prefix("clippy").add_stamp(date);
117        let cargo_clippy = self.initial_sysroot.join("bin").join(exe("cargo-clippy", host));
118        if cargo_clippy.exists() && clippy_stamp.is_up_to_date() {
119            return cargo_clippy;
120        }
121
122        let filename = format!("clippy-{version}-{host}.tar.xz");
123        self.download_component(DownloadSource::Dist, filename, "clippy-preview", date, "stage0");
124        if self.should_fix_bins_and_dylibs() {
125            self.fix_bin_or_dylib(&cargo_clippy);
126            self.fix_bin_or_dylib(&cargo_clippy.with_file_name(exe("clippy-driver", host)));
127        }
128
129        t!(clippy_stamp.write());
130        cargo_clippy
131    }
132
133    pub(crate) fn ci_rust_std_contents(&self) -> Vec<String> {
134        self.ci_component_contents(".rust-std-contents")
135    }
136
137    pub(crate) fn ci_rustc_dev_contents(&self) -> Vec<String> {
138        self.ci_component_contents(".rustc-dev-contents")
139    }
140
141    fn ci_component_contents(&self, stamp_file: &str) -> Vec<String> {
142        assert!(self.download_rustc());
143        if self.dry_run() {
144            return vec![];
145        }
146
147        let ci_rustc_dir = self.ci_rustc_dir();
148        let stamp_file = ci_rustc_dir.join(stamp_file);
149        let contents_file = t!(File::open(&stamp_file), stamp_file.display().to_string());
150        t!(BufReader::new(contents_file).lines().collect())
151    }
152
153    pub(crate) fn download_ci_rustc(&self, commit: &str) {
154        self.do_if_verbose(|| {
155            println!("using downloaded stage2 artifacts from CI (commit {commit})")
156        });
157
158        let version = self.artifact_version_part(commit);
159        // download-rustc doesn't need its own cargo, it can just use beta's. But it does need the
160        // `rustc_private` crates for tools.
161        let extra_components = ["rustc-dev"];
162
163        self.download_toolchain(
164            &version,
165            "ci-rustc",
166            &format!("{commit}-{}", self.llvm_assertions),
167            &extra_components,
168            Self::download_ci_component,
169        );
170    }
171
172    fn download_toolchain(
173        &self,
174        version: &str,
175        sysroot: &str,
176        stamp_key: &str,
177        extra_components: &[&str],
178        download_component: fn(&Config, String, &str, &str),
179    ) {
180        let host = self.host_target.triple;
181        let bin_root = self.out.join(host).join(sysroot);
182        let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
183
184        if !bin_root.join("bin").join(exe("rustc", self.host_target)).exists()
185            || !rustc_stamp.is_up_to_date()
186        {
187            if bin_root.exists() {
188                t!(fs::remove_dir_all(&bin_root));
189            }
190            let filename = format!("rust-std-{version}-{host}.tar.xz");
191            let pattern = format!("rust-std-{host}");
192            download_component(self, filename, &pattern, stamp_key);
193            let filename = format!("rustc-{version}-{host}.tar.xz");
194            download_component(self, filename, "rustc", stamp_key);
195
196            for component in extra_components {
197                let filename = format!("{component}-{version}-{host}.tar.xz");
198                download_component(self, filename, component, stamp_key);
199            }
200
201            if self.should_fix_bins_and_dylibs() {
202                self.fix_bin_or_dylib(&bin_root.join("bin").join("rustc"));
203                self.fix_bin_or_dylib(&bin_root.join("bin").join("rustdoc"));
204                self.fix_bin_or_dylib(
205                    &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
206                );
207                let lib_dir = bin_root.join("lib");
208                for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
209                    let lib = t!(lib);
210                    if path_is_dylib(&lib.path()) {
211                        self.fix_bin_or_dylib(&lib.path());
212                    }
213                }
214            }
215
216            t!(rustc_stamp.write());
217        }
218    }
219
220    /// Download a single component of a CI-built toolchain (not necessarily a published nightly).
221    // NOTE: intentionally takes an owned string to avoid downloading multiple times by accident
222    fn download_ci_component(&self, filename: String, prefix: &str, commit_with_assertions: &str) {
223        Self::download_component(
224            self,
225            DownloadSource::CI,
226            filename,
227            prefix,
228            commit_with_assertions,
229            "ci-rustc",
230        )
231    }
232
233    fn download_component(
234        &self,
235        mode: DownloadSource,
236        filename: String,
237        prefix: &str,
238        key: &str,
239        destination: &str,
240    ) {
241        let dwn_ctx: DownloadContext<'_> = self.into();
242        download_component(dwn_ctx, &self.out, mode, filename, prefix, key, destination);
243    }
244
245    #[cfg(test)]
246    pub(crate) fn maybe_download_ci_llvm(&self) {}
247
248    #[cfg(not(test))]
249    pub(crate) fn maybe_download_ci_llvm(&self) {
250        use build_helper::exit;
251        use build_helper::git::PathFreshness;
252
253        use crate::core::build_steps::llvm::detect_llvm_freshness;
254        use crate::core::config::toml::llvm::check_incompatible_options_for_ci_llvm;
255
256        if !self.llvm_from_ci {
257            return;
258        }
259
260        let llvm_root = self.ci_llvm_root();
261        let llvm_freshness =
262            detect_llvm_freshness(self, self.rust_info.is_managed_git_subrepository());
263        self.do_if_verbose(|| {
264            eprintln!("LLVM freshness: {llvm_freshness:?}");
265        });
266        let llvm_sha = match llvm_freshness {
267            PathFreshness::LastModifiedUpstream { upstream } => upstream,
268            PathFreshness::HasLocalModifications { upstream } => upstream,
269            PathFreshness::MissingUpstream => {
270                eprintln!("error: could not find commit hash for downloading LLVM");
271                eprintln!("HELP: maybe your repository history is too shallow?");
272                eprintln!("HELP: consider disabling `download-ci-llvm`");
273                eprintln!("HELP: or fetch enough history to include one upstream commit");
274                crate::exit!(1);
275            }
276        };
277        let stamp_key = format!("{}{}", llvm_sha, self.llvm_assertions);
278        let llvm_stamp = BuildStamp::new(&llvm_root).with_prefix("llvm").add_stamp(stamp_key);
279        if !llvm_stamp.is_up_to_date() && !self.dry_run() {
280            self.download_ci_llvm(&llvm_sha);
281
282            if self.should_fix_bins_and_dylibs() {
283                for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
284                    self.fix_bin_or_dylib(&t!(entry).path());
285                }
286            }
287
288            // Update the timestamp of llvm-config to force rustc_llvm to be
289            // rebuilt. This is a hacky workaround for a deficiency in Cargo where
290            // the rerun-if-changed directive doesn't handle changes very well.
291            // https://github.com/rust-lang/cargo/issues/10791
292            // Cargo only compares the timestamp of the file relative to the last
293            // time `rustc_llvm` build script ran. However, the timestamps of the
294            // files in the tarball are in the past, so it doesn't trigger a
295            // rebuild.
296            let now = std::time::SystemTime::now();
297            let file_times = fs::FileTimes::new().set_accessed(now).set_modified(now);
298
299            let llvm_config = llvm_root.join("bin").join(exe("llvm-config", self.host_target));
300            t!(crate::utils::helpers::set_file_times(llvm_config, file_times));
301
302            if self.should_fix_bins_and_dylibs() {
303                let llvm_lib = llvm_root.join("lib");
304                for entry in t!(fs::read_dir(llvm_lib)) {
305                    let lib = t!(entry).path();
306                    if path_is_dylib(&lib) {
307                        self.fix_bin_or_dylib(&lib);
308                    }
309                }
310            }
311
312            t!(llvm_stamp.write());
313        }
314
315        if let Some(config_path) = &self.config {
316            let current_config_toml = Self::get_toml(config_path).unwrap();
317
318            match self.get_builder_toml("ci-llvm") {
319                Ok(ci_config_toml) => {
320                    t!(check_incompatible_options_for_ci_llvm(current_config_toml, ci_config_toml));
321                }
322                Err(e) if e.to_string().contains("unknown field") => {
323                    println!(
324                        "WARNING: CI LLVM has some fields that are no longer supported in bootstrap; download-ci-llvm will be disabled."
325                    );
326                    println!("HELP: Consider rebasing to a newer commit if available.");
327                }
328                Err(e) => {
329                    eprintln!("ERROR: Failed to parse CI LLVM bootstrap.toml: {e}");
330                    exit!(2);
331                }
332            };
333        };
334    }
335
336    #[cfg(not(test))]
337    fn download_ci_llvm(&self, llvm_sha: &str) {
338        let llvm_assertions = self.llvm_assertions;
339
340        let cache_prefix = format!("llvm-{llvm_sha}-{llvm_assertions}");
341        let cache_dst =
342            self.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| self.out.join("cache"));
343
344        let rustc_cache = cache_dst.join(cache_prefix);
345        if !rustc_cache.exists() {
346            t!(fs::create_dir_all(&rustc_cache));
347        }
348        let base = if llvm_assertions {
349            &self.stage0_metadata.config.artifacts_with_llvm_assertions_server
350        } else {
351            &self.stage0_metadata.config.artifacts_server
352        };
353        let version = self.artifact_version_part(llvm_sha);
354        let filename = format!("rust-dev-{}-{}.tar.xz", version, self.host_target.triple);
355        let tarball = rustc_cache.join(&filename);
356        if !tarball.exists() {
357            let help_on_error = "ERROR: failed to download llvm from ci
358
359    HELP: There could be two reasons behind this:
360        1) The host triple is not supported for `download-ci-llvm`.
361        2) Old builds get deleted after a certain time.
362    HELP: In either case, disable `download-ci-llvm` in your bootstrap.toml:
363
364    [llvm]
365    download-ci-llvm = false
366    ";
367            self.download_file(&format!("{base}/{llvm_sha}/{filename}"), &tarball, help_on_error);
368        }
369        let llvm_root = self.ci_llvm_root();
370        self.unpack(&tarball, &llvm_root, "rust-dev");
371    }
372
373    pub fn download_ci_gcc(&self, gcc_sha: &str, root_dir: &Path) {
374        let cache_prefix = format!("gcc-{gcc_sha}");
375        let cache_dst =
376            self.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| self.out.join("cache"));
377
378        let gcc_cache = cache_dst.join(cache_prefix);
379        if !gcc_cache.exists() {
380            t!(fs::create_dir_all(&gcc_cache));
381        }
382        let base = &self.stage0_metadata.config.artifacts_server;
383        let version = self.artifact_version_part(gcc_sha);
384        let filename = format!("gcc-{version}-{}.tar.xz", self.host_target.triple);
385        let tarball = gcc_cache.join(&filename);
386        if !tarball.exists() {
387            let help_on_error = "ERROR: failed to download gcc from ci
388
389    HELP: There could be two reasons behind this:
390        1) The host triple is not supported for `download-ci-gcc`.
391        2) Old builds get deleted after a certain time.
392    HELP: In either case, disable `download-ci-gcc` in your bootstrap.toml:
393
394    [gcc]
395    download-ci-gcc = false
396    ";
397            self.download_file(&format!("{base}/{gcc_sha}/{filename}"), &tarball, help_on_error);
398        }
399        self.unpack(&tarball, root_dir, "gcc");
400    }
401}
402
403/// Only should be used for pre config initialization downloads.
404pub(crate) struct DownloadContext<'a> {
405    pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
406    pub src: &'a Path,
407    pub submodules: &'a Option<bool>,
408    pub host_target: TargetSelection,
409    pub patch_binaries_for_nix: Option<bool>,
410    pub exec_ctx: &'a ExecutionContext,
411    pub stage0_metadata: &'a build_helper::stage0_parser::Stage0,
412    pub llvm_assertions: bool,
413    pub bootstrap_cache_path: &'a Option<PathBuf>,
414    pub is_running_on_ci: bool,
415}
416
417impl<'a> AsRef<DownloadContext<'a>> for DownloadContext<'a> {
418    fn as_ref(&self) -> &DownloadContext<'a> {
419        self
420    }
421}
422
423impl<'a> From<&'a Config> for DownloadContext<'a> {
424    fn from(value: &'a Config) -> Self {
425        DownloadContext {
426            path_modification_cache: value.path_modification_cache.clone(),
427            src: &value.src,
428            host_target: value.host_target,
429            submodules: &value.submodules,
430            patch_binaries_for_nix: value.patch_binaries_for_nix,
431            exec_ctx: &value.exec_ctx,
432            stage0_metadata: &value.stage0_metadata,
433            llvm_assertions: value.llvm_assertions,
434            bootstrap_cache_path: &value.bootstrap_cache_path,
435            is_running_on_ci: value.is_running_on_ci,
436        }
437    }
438}
439
440fn path_is_dylib(path: &Path) -> bool {
441    // The .so is not necessarily the extension, it might be libLLVM.so.18.1
442    path.to_str().is_some_and(|path| path.contains(".so"))
443}
444
445/// Checks whether the CI rustc is available for the given target triple.
446pub(crate) fn is_download_ci_available(target_triple: &str, llvm_assertions: bool) -> bool {
447    // All tier 1 targets and tier 2 targets with host tools.
448    const SUPPORTED_PLATFORMS: &[&str] = &[
449        "aarch64-apple-darwin",
450        "aarch64-pc-windows-msvc",
451        "aarch64-unknown-linux-gnu",
452        "aarch64-unknown-linux-musl",
453        "arm-unknown-linux-gnueabi",
454        "arm-unknown-linux-gnueabihf",
455        "armv7-unknown-linux-gnueabihf",
456        "i686-pc-windows-gnu",
457        "i686-pc-windows-msvc",
458        "i686-unknown-linux-gnu",
459        "loongarch64-unknown-linux-gnu",
460        "powerpc-unknown-linux-gnu",
461        "powerpc64-unknown-linux-gnu",
462        "powerpc64le-unknown-linux-gnu",
463        "powerpc64le-unknown-linux-musl",
464        "riscv64gc-unknown-linux-gnu",
465        "s390x-unknown-linux-gnu",
466        "x86_64-apple-darwin",
467        "x86_64-pc-windows-gnu",
468        "x86_64-pc-windows-msvc",
469        "x86_64-unknown-freebsd",
470        "x86_64-unknown-illumos",
471        "x86_64-unknown-linux-gnu",
472        "x86_64-unknown-linux-musl",
473        "x86_64-unknown-netbsd",
474    ];
475
476    const SUPPORTED_PLATFORMS_WITH_ASSERTIONS: &[&str] =
477        &["x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"];
478
479    if llvm_assertions {
480        SUPPORTED_PLATFORMS_WITH_ASSERTIONS.contains(&target_triple)
481    } else {
482        SUPPORTED_PLATFORMS.contains(&target_triple)
483    }
484}
485
486#[cfg(test)]
487pub(crate) fn maybe_download_rustfmt<'a>(
488    dwn_ctx: impl AsRef<DownloadContext<'a>>,
489    out: &Path,
490) -> Option<PathBuf> {
491    Some(PathBuf::new())
492}
493
494/// NOTE: rustfmt is a completely different toolchain than the bootstrap compiler, so it can't
495/// reuse target directories or artifacts
496#[cfg(not(test))]
497pub(crate) fn maybe_download_rustfmt<'a>(
498    dwn_ctx: impl AsRef<DownloadContext<'a>>,
499    out: &Path,
500) -> Option<PathBuf> {
501    use build_helper::stage0_parser::VersionMetadata;
502
503    let dwn_ctx = dwn_ctx.as_ref();
504
505    if dwn_ctx.exec_ctx.dry_run() {
506        return Some(PathBuf::new());
507    }
508
509    let VersionMetadata { date, version, .. } = dwn_ctx.stage0_metadata.rustfmt.as_ref()?;
510    let channel = format!("{version}-{date}");
511
512    let host = dwn_ctx.host_target;
513    let bin_root = out.join(host).join("rustfmt");
514    let rustfmt_path = bin_root.join("bin").join(exe("rustfmt", host));
515    let rustfmt_stamp = BuildStamp::new(&bin_root).with_prefix("rustfmt").add_stamp(channel);
516    if rustfmt_path.exists() && rustfmt_stamp.is_up_to_date() {
517        return Some(rustfmt_path);
518    }
519
520    download_component(
521        dwn_ctx,
522        out,
523        DownloadSource::Dist,
524        format!("rustfmt-{version}-{build}.tar.xz", build = host.triple),
525        "rustfmt-preview",
526        date,
527        "rustfmt",
528    );
529
530    download_component(
531        dwn_ctx,
532        out,
533        DownloadSource::Dist,
534        format!("rustc-{version}-{build}.tar.xz", build = host.triple),
535        "rustc",
536        date,
537        "rustfmt",
538    );
539
540    if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
541        fix_bin_or_dylib(out, &bin_root.join("bin").join("rustfmt"), dwn_ctx.exec_ctx);
542        fix_bin_or_dylib(out, &bin_root.join("bin").join("cargo-fmt"), dwn_ctx.exec_ctx);
543        let lib_dir = bin_root.join("lib");
544        for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
545            let lib = t!(lib);
546            if path_is_dylib(&lib.path()) {
547                fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
548            }
549        }
550    }
551
552    t!(rustfmt_stamp.write());
553    Some(rustfmt_path)
554}
555
556#[cfg(test)]
557pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef<DownloadContext<'a>>, out: &Path) {}
558
559#[cfg(not(test))]
560pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef<DownloadContext<'a>>, out: &Path) {
561    let dwn_ctx = dwn_ctx.as_ref();
562    dwn_ctx.exec_ctx.do_if_verbose(|| {
563        println!("downloading stage0 beta artifacts");
564    });
565
566    let date = dwn_ctx.stage0_metadata.compiler.date.clone();
567    let version = dwn_ctx.stage0_metadata.compiler.version.clone();
568    let extra_components = ["cargo"];
569    let sysroot = "stage0";
570    download_toolchain(
571        dwn_ctx,
572        out,
573        &version,
574        sysroot,
575        &date,
576        &extra_components,
577        "stage0",
578        DownloadSource::Dist,
579    );
580}
581
582#[allow(clippy::too_many_arguments)]
583fn download_toolchain<'a>(
584    dwn_ctx: impl AsRef<DownloadContext<'a>>,
585    out: &Path,
586    version: &str,
587    sysroot: &str,
588    stamp_key: &str,
589    extra_components: &[&str],
590    destination: &str,
591    mode: DownloadSource,
592) {
593    let dwn_ctx = dwn_ctx.as_ref();
594    let host = dwn_ctx.host_target.triple;
595    let bin_root = out.join(host).join(sysroot);
596    let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
597
598    if !bin_root.join("bin").join(exe("rustc", dwn_ctx.host_target)).exists()
599        || !rustc_stamp.is_up_to_date()
600    {
601        if bin_root.exists() {
602            t!(fs::remove_dir_all(&bin_root));
603        }
604        let filename = format!("rust-std-{version}-{host}.tar.xz");
605        let pattern = format!("rust-std-{host}");
606        download_component(dwn_ctx, out, mode.clone(), filename, &pattern, stamp_key, destination);
607        let filename = format!("rustc-{version}-{host}.tar.xz");
608        download_component(dwn_ctx, out, mode.clone(), filename, "rustc", stamp_key, destination);
609
610        for component in extra_components {
611            let filename = format!("{component}-{version}-{host}.tar.xz");
612            download_component(
613                dwn_ctx,
614                out,
615                mode.clone(),
616                filename,
617                component,
618                stamp_key,
619                destination,
620            );
621        }
622
623        if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
624            fix_bin_or_dylib(out, &bin_root.join("bin").join("rustc"), dwn_ctx.exec_ctx);
625            fix_bin_or_dylib(out, &bin_root.join("bin").join("rustdoc"), dwn_ctx.exec_ctx);
626            fix_bin_or_dylib(
627                out,
628                &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
629                dwn_ctx.exec_ctx,
630            );
631            let lib_dir = bin_root.join("lib");
632            for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
633                let lib = t!(lib);
634                if path_is_dylib(&lib.path()) {
635                    fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
636                }
637            }
638        }
639
640        t!(rustc_stamp.write());
641    }
642}
643
644pub(crate) fn remove(exec_ctx: &ExecutionContext, f: &Path) {
645    if exec_ctx.dry_run() {
646        return;
647    }
648    fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}"));
649}
650
651fn fix_bin_or_dylib(out: &Path, fname: &Path, exec_ctx: &ExecutionContext) {
652    assert_eq!(SHOULD_FIX_BINS_AND_DYLIBS.get(), Some(&true));
653    println!("attempting to patch {}", fname.display());
654
655    // Only build `.nix-deps` once.
656    static NIX_DEPS_DIR: OnceLock<PathBuf> = OnceLock::new();
657    let mut nix_build_succeeded = true;
658    let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
659        // Run `nix-build` to "build" each dependency (which will likely reuse
660        // the existing `/nix/store` copy, or at most download a pre-built copy).
661        //
662        // Importantly, we create a gc-root called `.nix-deps` in the `build/`
663        // directory, but still reference the actual `/nix/store` path in the rpath
664        // as it makes it significantly more robust against changes to the location of
665        // the `.nix-deps` location.
666        //
667        // bintools: Needed for the path of `ld-linux.so` (via `nix-support/dynamic-linker`).
668        // zlib: Needed as a system dependency of `libLLVM-*.so`.
669        // patchelf: Needed for patching ELF binaries (see doc comment above).
670        let nix_deps_dir = out.join(".nix-deps");
671        const NIX_EXPR: &str = "
672        with (import <nixpkgs> {});
673        symlinkJoin {
674            name = \"rust-stage0-dependencies\";
675            paths = [
676                zlib
677                patchelf
678                stdenv.cc.bintools
679            ];
680        }
681        ";
682        nix_build_succeeded = command("nix-build")
683            .allow_failure()
684            .args([Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir])
685            .run_capture_stdout(exec_ctx)
686            .is_success();
687        nix_deps_dir
688    });
689    if !nix_build_succeeded {
690        return;
691    }
692
693    let mut patchelf = command(nix_deps_dir.join("bin/patchelf"));
694    patchelf.args(&[
695        OsString::from("--add-rpath"),
696        OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")),
697    ]);
698    if !path_is_dylib(fname) {
699        // Finally, set the correct .interp for binaries
700        let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
701        let dynamic_linker = t!(fs::read_to_string(dynamic_linker_path));
702        patchelf.args(["--set-interpreter", dynamic_linker.trim_end()]);
703    }
704    patchelf.arg(fname);
705    let _ = patchelf.allow_failure().run_capture_stdout(exec_ctx);
706}
707
708fn should_fix_bins_and_dylibs(
709    patch_binaries_for_nix: Option<bool>,
710    exec_ctx: &ExecutionContext,
711) -> bool {
712    let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| {
713        let uname = command("uname").allow_failure().arg("-s").run_capture_stdout(exec_ctx);
714        if uname.is_failure() {
715            return false;
716        }
717        let output = uname.stdout();
718        if !output.starts_with("Linux") {
719            return false;
720        }
721        // If the user has asked binaries to be patched for Nix, then
722        // don't check for NixOS or `/lib`.
723        // NOTE: this intentionally comes after the Linux check:
724        // - patchelf only works with ELF files, so no need to run it on Mac or Windows
725        // - On other Unix systems, there is no stable syscall interface, so Nix doesn't manage the global libc.
726        if let Some(explicit_value) = patch_binaries_for_nix {
727            return explicit_value;
728        }
729
730        // Use `/etc/os-release` instead of `/etc/NIXOS`.
731        // The latter one does not exist on NixOS when using tmpfs as root.
732        let is_nixos = match File::open("/etc/os-release") {
733            Err(e) if e.kind() == ErrorKind::NotFound => false,
734            Err(e) => panic!("failed to access /etc/os-release: {e}"),
735            Ok(os_release) => BufReader::new(os_release).lines().any(|l| {
736                let l = l.expect("reading /etc/os-release");
737                matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"")
738            }),
739        };
740        if !is_nixos {
741            let in_nix_shell = env::var("IN_NIX_SHELL");
742            if let Ok(in_nix_shell) = in_nix_shell {
743                eprintln!(
744                    "The IN_NIX_SHELL environment variable is `{in_nix_shell}`; \
745                     you may need to set `patch-binaries-for-nix=true` in bootstrap.toml"
746                );
747            }
748        }
749        is_nixos
750    });
751    if val {
752        eprintln!("INFO: You seem to be using Nix.");
753    }
754    val
755}
756
757fn download_component<'a>(
758    dwn_ctx: impl AsRef<DownloadContext<'a>>,
759    out: &Path,
760    mode: DownloadSource,
761    filename: String,
762    prefix: &str,
763    key: &str,
764    destination: &str,
765) {
766    let dwn_ctx = dwn_ctx.as_ref();
767
768    if dwn_ctx.exec_ctx.dry_run() {
769        return;
770    }
771
772    let cache_dst =
773        dwn_ctx.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| out.join("cache"));
774
775    let cache_dir = cache_dst.join(key);
776    if !cache_dir.exists() {
777        t!(fs::create_dir_all(&cache_dir));
778    }
779
780    let bin_root = out.join(dwn_ctx.host_target).join(destination);
781    let tarball = cache_dir.join(&filename);
782    let (base_url, url, should_verify) = match mode {
783        DownloadSource::CI => {
784            let dist_server = if dwn_ctx.llvm_assertions {
785                dwn_ctx.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone()
786            } else {
787                dwn_ctx.stage0_metadata.config.artifacts_server.clone()
788            };
789            let url = format!(
790                "{}/{filename}",
791                key.strip_suffix(&format!("-{}", dwn_ctx.llvm_assertions)).unwrap()
792            );
793            (dist_server, url, false)
794        }
795        DownloadSource::Dist => {
796            let dist_server = env::var("RUSTUP_DIST_SERVER")
797                .unwrap_or(dwn_ctx.stage0_metadata.config.dist_server.to_string());
798            // NOTE: make `dist` part of the URL because that's how it's stored in src/stage0
799            (dist_server, format!("dist/{key}/{filename}"), true)
800        }
801    };
802
803    // For the stage0 compiler, put special effort into ensuring the checksums are valid.
804    let checksum = if should_verify {
805        let error = format!(
806            "src/stage0 doesn't contain a checksum for {url}. \
807            Pre-built artifacts might not be available for this \
808            target at this time, see https://doc.rust-lang.org/nightly\
809            /rustc/platform-support.html for more information."
810        );
811        let sha256 = dwn_ctx.stage0_metadata.checksums_sha256.get(&url).expect(&error);
812        if tarball.exists() {
813            if verify(dwn_ctx.exec_ctx, &tarball, sha256) {
814                unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
815                return;
816            } else {
817                dwn_ctx.exec_ctx.do_if_verbose(|| {
818                    println!(
819                        "ignoring cached file {} due to failed verification",
820                        tarball.display()
821                    )
822                });
823                remove(dwn_ctx.exec_ctx, &tarball);
824            }
825        }
826        Some(sha256)
827    } else if tarball.exists() {
828        unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
829        return;
830    } else {
831        None
832    };
833
834    let mut help_on_error = "";
835    if destination == "ci-rustc" {
836        help_on_error = "ERROR: failed to download pre-built rustc from CI
837
838NOTE: old builds get deleted after a certain time
839HELP: if trying to compile an old commit of rustc, disable `download-rustc` in bootstrap.toml:
840
841[rust]
842download-rustc = false
843";
844    }
845    download_file(dwn_ctx, out, &format!("{base_url}/{url}"), &tarball, help_on_error);
846    if let Some(sha256) = checksum
847        && !verify(dwn_ctx.exec_ctx, &tarball, sha256)
848    {
849        panic!("failed to verify {}", tarball.display());
850    }
851
852    unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
853}
854
855pub(crate) fn verify(exec_ctx: &ExecutionContext, path: &Path, expected: &str) -> bool {
856    use sha2::Digest;
857
858    exec_ctx.do_if_verbose(|| {
859        println!("verifying {}", path.display());
860    });
861
862    if exec_ctx.dry_run() {
863        return false;
864    }
865
866    let mut hasher = sha2::Sha256::new();
867
868    let file = t!(File::open(path));
869    let mut reader = BufReader::new(file);
870
871    loop {
872        let buffer = t!(reader.fill_buf());
873        let l = buffer.len();
874        // break if EOF
875        if l == 0 {
876            break;
877        }
878        hasher.update(buffer);
879        reader.consume(l);
880    }
881
882    let checksum = hex_encode(hasher.finalize().as_slice());
883    let verified = checksum == expected;
884
885    if !verified {
886        println!(
887            "invalid checksum: \n\
888            found:    {checksum}\n\
889            expected: {expected}",
890        );
891    }
892
893    verified
894}
895
896fn unpack(exec_ctx: &ExecutionContext, tarball: &Path, dst: &Path, pattern: &str) {
897    eprintln!("extracting {} to {}", tarball.display(), dst.display());
898    if !dst.exists() {
899        t!(fs::create_dir_all(dst));
900    }
901
902    // `tarball` ends with `.tar.xz`; strip that suffix
903    // example: `rust-dev-nightly-x86_64-unknown-linux-gnu`
904    let uncompressed_filename =
905        Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
906    let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
907
908    // decompress the file
909    let data = t!(File::open(tarball), format!("file {} not found", tarball.display()));
910    let decompressor = XzDecoder::new(BufReader::new(data));
911
912    let mut tar = tar::Archive::new(decompressor);
913
914    let is_ci_rustc = dst.ends_with("ci-rustc");
915    let is_ci_llvm = dst.ends_with("ci-llvm");
916
917    // `compile::Sysroot` needs to know the contents of the `rustc-dev` tarball to avoid adding
918    // it to the sysroot unless it was explicitly requested. But parsing the 100 MB tarball is slow.
919    // Cache the entries when we extract it so we only have to read it once.
920    let mut recorded_entries = if is_ci_rustc { recorded_entries(dst, pattern) } else { None };
921
922    for member in t!(tar.entries()) {
923        let mut member = t!(member);
924        let original_path = t!(member.path()).into_owned();
925        // skip the top-level directory
926        if original_path == directory_prefix {
927            continue;
928        }
929        let mut short_path = t!(original_path.strip_prefix(directory_prefix));
930        let is_builder_config = short_path.to_str() == Some(BUILDER_CONFIG_FILENAME);
931
932        if !(short_path.starts_with(pattern) || ((is_ci_rustc || is_ci_llvm) && is_builder_config))
933        {
934            continue;
935        }
936        short_path = short_path.strip_prefix(pattern).unwrap_or(short_path);
937        let dst_path = dst.join(short_path);
938
939        exec_ctx.do_if_verbose(|| {
940            println!("extracting {} to {}", original_path.display(), dst.display());
941        });
942
943        if !t!(member.unpack_in(dst)) {
944            panic!("path traversal attack ??");
945        }
946        if let Some(record) = &mut recorded_entries {
947            t!(writeln!(record, "{}", short_path.to_str().unwrap()));
948        }
949        let src_path = dst.join(original_path);
950        if src_path.is_dir() && dst_path.exists() {
951            continue;
952        }
953        t!(move_file(src_path, dst_path));
954    }
955    let dst_dir = dst.join(directory_prefix);
956    if dst_dir.exists() {
957        t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display()));
958    }
959}
960
961fn download_file<'a>(
962    dwn_ctx: impl AsRef<DownloadContext<'a>>,
963    out: &Path,
964    url: &str,
965    dest_path: &Path,
966    help_on_error: &str,
967) {
968    let dwn_ctx = dwn_ctx.as_ref();
969
970    dwn_ctx.exec_ctx.do_if_verbose(|| {
971        println!("download {url}");
972    });
973    // Use a temporary file in case we crash while downloading, to avoid a corrupt download in cache/.
974    let tempfile = tempdir(out).join(dest_path.file_name().unwrap());
975    // While bootstrap itself only supports http and https downloads, downstream forks might
976    // need to download components from other protocols. The match allows them adding more
977    // protocols without worrying about merge conflicts if we change the HTTP implementation.
978    match url.split_once("://").map(|(proto, _)| proto) {
979        Some("http") | Some("https") => download_http_with_retries(
980            dwn_ctx.host_target,
981            dwn_ctx.is_running_on_ci,
982            dwn_ctx.exec_ctx,
983            &tempfile,
984            url,
985            help_on_error,
986        ),
987        Some(other) => panic!("unsupported protocol {other} in {url}"),
988        None => panic!("no protocol in {url}"),
989    }
990    t!(move_file(&tempfile, dest_path), format!("failed to rename {tempfile:?} to {dest_path:?}"));
991}
992
993/// Create a temporary directory in `out` and return its path.
994///
995/// NOTE: this temporary directory is shared between all steps;
996/// if you need an empty directory, create a new subdirectory inside it.
997pub(crate) fn tempdir(out: &Path) -> PathBuf {
998    let tmp = out.join("tmp");
999    t!(fs::create_dir_all(&tmp));
1000    tmp
1001}
1002
1003fn download_http_with_retries(
1004    host_target: TargetSelection,
1005    is_running_on_ci: bool,
1006    exec_ctx: &ExecutionContext,
1007    tempfile: &Path,
1008    url: &str,
1009    help_on_error: &str,
1010) {
1011    println!("downloading {url}");
1012    // Try curl. If that fails and we are on windows, fallback to PowerShell.
1013    // options should be kept in sync with
1014    // src/bootstrap/src/core/download.rs
1015    // for consistency
1016    let mut curl = command("curl").allow_failure();
1017    curl.args([
1018        // follow redirect
1019        "--location",
1020        // timeout if speed is < 10 bytes/sec for > 30 seconds
1021        "--speed-time",
1022        "30",
1023        "--speed-limit",
1024        "10",
1025        // timeout if cannot connect within 30 seconds
1026        "--connect-timeout",
1027        "30",
1028        // output file
1029        "--output",
1030        tempfile.to_str().unwrap(),
1031        // if there is an error, don't restart the download,
1032        // instead continue where it left off.
1033        "--continue-at",
1034        "-",
1035        // retry up to 3 times.  note that this means a maximum of 4
1036        // attempts will be made, since the first attempt isn't a *re*try.
1037        "--retry",
1038        "3",
1039        // show errors, even if --silent is specified
1040        "--show-error",
1041        // set timestamp of downloaded file to that of the server
1042        "--remote-time",
1043        // fail on non-ok http status
1044        "--fail",
1045    ]);
1046    // Don't print progress in CI; the \r wrapping looks bad and downloads don't take long enough for progress to be useful.
1047    if is_running_on_ci {
1048        curl.arg("--silent");
1049    } else {
1050        curl.arg("--progress-bar");
1051    }
1052    // --retry-all-errors was added in 7.71.0, don't use it if curl is old.
1053    if curl_version(exec_ctx) >= semver::Version::new(7, 71, 0) {
1054        curl.arg("--retry-all-errors");
1055    }
1056    curl.arg(url);
1057    if !curl.run(exec_ctx) {
1058        if host_target.contains("windows-msvc") {
1059            eprintln!("Fallback to PowerShell");
1060            for _ in 0..3 {
1061                let powershell = command("PowerShell.exe").allow_failure().args([
1062                    "/nologo",
1063                    "-Command",
1064                    "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
1065                    &format!(
1066                        "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
1067                        url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
1068                    ),
1069                ]).run_capture_stdout(exec_ctx);
1070
1071                if powershell.is_failure() {
1072                    return;
1073                }
1074
1075                eprintln!("\nspurious failure, trying again");
1076            }
1077        }
1078        if !help_on_error.is_empty() {
1079            eprintln!("{help_on_error}");
1080        }
1081        crate::exit!(1);
1082    }
1083}
1084
1085fn curl_version(exec_ctx: &ExecutionContext) -> semver::Version {
1086    let mut curl = command("curl");
1087    curl.arg("-V");
1088    let curl = curl.run_capture_stdout(exec_ctx);
1089    if curl.is_failure() {
1090        return semver::Version::new(1, 0, 0);
1091    }
1092    let output = curl.stdout();
1093    extract_curl_version(output)
1094}