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