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