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