Skip to main content

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