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