bootstrap/core/
download.rs

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