bootstrap/core/
download.rs

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