Skip to main content

bootstrap/core/
download.rs

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