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 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
30impl 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 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 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 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 #[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
107impl 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 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 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 } => 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 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}
403
404pub(crate) struct DownloadContext<'a> {
406 pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
407 pub src: &'a Path,
408 pub submodules: &'a Option<bool>,
409 pub host_target: TargetSelection,
410 pub patch_binaries_for_nix: Option<bool>,
411 pub exec_ctx: &'a ExecutionContext,
412 pub stage0_metadata: &'a build_helper::stage0_parser::Stage0,
413 pub llvm_assertions: bool,
414 pub bootstrap_cache_path: &'a Option<PathBuf>,
415 pub ci_env: CiEnv,
416}
417
418impl<'a> DownloadContext<'a> {
419 pub fn is_running_on_ci(&self) -> bool {
420 self.ci_env.is_running_in_ci()
421 }
422}
423
424impl<'a> AsRef<DownloadContext<'a>> for DownloadContext<'a> {
425 fn as_ref(&self) -> &DownloadContext<'a> {
426 self
427 }
428}
429
430impl<'a> From<&'a Config> for DownloadContext<'a> {
431 fn from(value: &'a Config) -> Self {
432 DownloadContext {
433 path_modification_cache: value.path_modification_cache.clone(),
434 src: &value.src,
435 host_target: value.host_target,
436 submodules: &value.submodules,
437 patch_binaries_for_nix: value.patch_binaries_for_nix,
438 exec_ctx: &value.exec_ctx,
439 stage0_metadata: &value.stage0_metadata,
440 llvm_assertions: value.llvm_assertions,
441 bootstrap_cache_path: &value.bootstrap_cache_path,
442 ci_env: value.ci_env,
443 }
444 }
445}
446
447fn path_is_dylib(path: &Path) -> bool {
448 path.to_str().is_some_and(|path| path.contains(".so"))
450}
451
452pub(crate) fn is_download_ci_available(target_triple: &str, llvm_assertions: bool) -> bool {
454 const SUPPORTED_PLATFORMS: &[&str] = &[
456 "aarch64-apple-darwin",
457 "aarch64-pc-windows-gnullvm",
458 "aarch64-pc-windows-msvc",
459 "aarch64-unknown-linux-gnu",
460 "aarch64-unknown-linux-musl",
461 "arm-unknown-linux-gnueabi",
462 "arm-unknown-linux-gnueabihf",
463 "armv7-unknown-linux-gnueabihf",
464 "i686-pc-windows-gnu",
465 "i686-pc-windows-msvc",
466 "i686-unknown-linux-gnu",
467 "loongarch64-unknown-linux-gnu",
468 "powerpc-unknown-linux-gnu",
469 "powerpc64-unknown-linux-gnu",
470 "powerpc64-unknown-linux-musl",
471 "powerpc64le-unknown-linux-gnu",
472 "powerpc64le-unknown-linux-musl",
473 "riscv64gc-unknown-linux-gnu",
474 "s390x-unknown-linux-gnu",
475 "x86_64-apple-darwin",
476 "x86_64-pc-windows-gnu",
477 "x86_64-pc-windows-gnullvm",
478 "x86_64-pc-windows-msvc",
479 "x86_64-unknown-freebsd",
480 "x86_64-unknown-illumos",
481 "x86_64-unknown-linux-gnu",
482 "x86_64-unknown-linux-musl",
483 "x86_64-unknown-netbsd",
484 ];
485
486 const SUPPORTED_PLATFORMS_WITH_ASSERTIONS: &[&str] =
487 &["x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"];
488
489 if llvm_assertions {
490 SUPPORTED_PLATFORMS_WITH_ASSERTIONS.contains(&target_triple)
491 } else {
492 SUPPORTED_PLATFORMS.contains(&target_triple)
493 }
494}
495
496#[cfg(test)]
497pub(crate) fn maybe_download_rustfmt<'a>(
498 dwn_ctx: impl AsRef<DownloadContext<'a>>,
499 out: &Path,
500) -> Option<PathBuf> {
501 Some(PathBuf::new())
502}
503
504#[cfg(not(test))]
507pub(crate) fn maybe_download_rustfmt<'a>(
508 dwn_ctx: impl AsRef<DownloadContext<'a>>,
509 out: &Path,
510) -> Option<PathBuf> {
511 use build_helper::stage0_parser::VersionMetadata;
512
513 let dwn_ctx = dwn_ctx.as_ref();
514
515 if dwn_ctx.exec_ctx.dry_run() {
516 return Some(PathBuf::new());
517 }
518
519 let VersionMetadata { date, version, .. } = dwn_ctx.stage0_metadata.rustfmt.as_ref()?;
520 let channel = format!("{version}-{date}");
521
522 let host = dwn_ctx.host_target;
523 let bin_root = out.join(host).join("rustfmt");
524 let rustfmt_path = bin_root.join("bin").join(exe("rustfmt", host));
525 let rustfmt_stamp = BuildStamp::new(&bin_root).with_prefix("rustfmt").add_stamp(channel);
526 if rustfmt_path.exists() && rustfmt_stamp.is_up_to_date() {
527 return Some(rustfmt_path);
528 }
529
530 download_component(
531 dwn_ctx,
532 out,
533 DownloadSource::Dist,
534 format!("rustfmt-{version}-{build}.tar.xz", build = host.triple),
535 "rustfmt-preview",
536 date,
537 "rustfmt",
538 );
539
540 download_component(
541 dwn_ctx,
542 out,
543 DownloadSource::Dist,
544 format!("rustc-{version}-{build}.tar.xz", build = host.triple),
545 "rustc",
546 date,
547 "rustfmt",
548 );
549
550 if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
551 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustfmt"), dwn_ctx.exec_ctx);
552 fix_bin_or_dylib(out, &bin_root.join("bin").join("cargo-fmt"), dwn_ctx.exec_ctx);
553 let lib_dir = bin_root.join("lib");
554 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
555 let lib = t!(lib);
556 if path_is_dylib(&lib.path()) {
557 fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
558 }
559 }
560 }
561
562 t!(rustfmt_stamp.write());
563 Some(rustfmt_path)
564}
565
566#[cfg(test)]
567pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef<DownloadContext<'a>>, out: &Path) {}
568
569#[cfg(not(test))]
570pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef<DownloadContext<'a>>, out: &Path) {
571 let dwn_ctx = dwn_ctx.as_ref();
572 dwn_ctx.exec_ctx.do_if_verbose(|| {
573 println!("downloading stage0 beta artifacts");
574 });
575
576 let date = dwn_ctx.stage0_metadata.compiler.date.clone();
577 let version = dwn_ctx.stage0_metadata.compiler.version.clone();
578 let extra_components = ["cargo"];
579 let sysroot = "stage0";
580 download_toolchain(
581 dwn_ctx,
582 out,
583 &version,
584 sysroot,
585 &date,
586 &extra_components,
587 "stage0",
588 DownloadSource::Dist,
589 );
590}
591
592#[allow(clippy::too_many_arguments)]
593fn download_toolchain<'a>(
594 dwn_ctx: impl AsRef<DownloadContext<'a>>,
595 out: &Path,
596 version: &str,
597 sysroot: &str,
598 stamp_key: &str,
599 extra_components: &[&str],
600 destination: &str,
601 mode: DownloadSource,
602) {
603 let dwn_ctx = dwn_ctx.as_ref();
604 let host = dwn_ctx.host_target.triple;
605 let bin_root = out.join(host).join(sysroot);
606 let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
607
608 if !bin_root.join("bin").join(exe("rustc", dwn_ctx.host_target)).exists()
609 || !rustc_stamp.is_up_to_date()
610 {
611 if bin_root.exists() {
612 t!(fs::remove_dir_all(&bin_root));
613 }
614 let filename = format!("rust-std-{version}-{host}.tar.xz");
615 let pattern = format!("rust-std-{host}");
616 download_component(dwn_ctx, out, mode.clone(), filename, &pattern, stamp_key, destination);
617 let filename = format!("rustc-{version}-{host}.tar.xz");
618 download_component(dwn_ctx, out, mode.clone(), filename, "rustc", stamp_key, destination);
619
620 for component in extra_components {
621 let filename = format!("{component}-{version}-{host}.tar.xz");
622 download_component(
623 dwn_ctx,
624 out,
625 mode.clone(),
626 filename,
627 component,
628 stamp_key,
629 destination,
630 );
631 }
632
633 if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
634 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustc"), dwn_ctx.exec_ctx);
635 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustdoc"), dwn_ctx.exec_ctx);
636 fix_bin_or_dylib(
637 out,
638 &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
639 dwn_ctx.exec_ctx,
640 );
641 let lib_dir = bin_root.join("lib");
642 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
643 let lib = t!(lib);
644 if path_is_dylib(&lib.path()) {
645 fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
646 }
647 }
648 }
649
650 t!(rustc_stamp.write());
651 }
652}
653
654pub(crate) fn remove(exec_ctx: &ExecutionContext, f: &Path) {
655 if exec_ctx.dry_run() {
656 return;
657 }
658 fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}"));
659}
660
661fn fix_bin_or_dylib(out: &Path, fname: &Path, exec_ctx: &ExecutionContext) {
662 assert_eq!(SHOULD_FIX_BINS_AND_DYLIBS.get(), Some(&true));
663 println!("attempting to patch {}", fname.display());
664
665 static NIX_DEPS_DIR: OnceLock<PathBuf> = OnceLock::new();
667 let mut nix_build_succeeded = true;
668 let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
669 let nix_deps_dir = out.join(".nix-deps");
681 const NIX_EXPR: &str = "
682 with (import <nixpkgs> {});
683 symlinkJoin {
684 name = \"rust-stage0-dependencies\";
685 paths = [
686 zlib
687 patchelf
688 stdenv.cc.bintools
689 ];
690 }
691 ";
692 nix_build_succeeded = command("nix-build")
693 .allow_failure()
694 .args([Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir])
695 .run_capture_stdout(exec_ctx)
696 .is_success();
697 nix_deps_dir
698 });
699 if !nix_build_succeeded {
700 return;
701 }
702
703 let mut patchelf = command(nix_deps_dir.join("bin/patchelf"));
704 patchelf.args(&[
705 OsString::from("--add-rpath"),
706 OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")),
707 ]);
708 if !path_is_dylib(fname) {
709 let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
711 let dynamic_linker = t!(fs::read_to_string(dynamic_linker_path));
712 patchelf.args(["--set-interpreter", dynamic_linker.trim_end()]);
713 }
714 patchelf.arg(fname);
715 let _ = patchelf.allow_failure().run_capture_stdout(exec_ctx);
716}
717
718fn should_fix_bins_and_dylibs(
719 patch_binaries_for_nix: Option<bool>,
720 exec_ctx: &ExecutionContext,
721) -> bool {
722 let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| {
723 let uname = command("uname").allow_failure().arg("-s").run_capture_stdout(exec_ctx);
724 if uname.is_failure() {
725 return false;
726 }
727 let output = uname.stdout();
728 if !output.starts_with("Linux") {
729 return false;
730 }
731 if let Some(explicit_value) = patch_binaries_for_nix {
737 return explicit_value;
738 }
739
740 let is_nixos = match File::open("/etc/os-release") {
743 Err(e) if e.kind() == ErrorKind::NotFound => false,
744 Err(e) => panic!("failed to access /etc/os-release: {e}"),
745 Ok(os_release) => BufReader::new(os_release).lines().any(|l| {
746 let l = l.expect("reading /etc/os-release");
747 matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"")
748 }),
749 };
750 if !is_nixos {
751 let in_nix_shell = env::var("IN_NIX_SHELL");
752 if let Ok(in_nix_shell) = in_nix_shell {
753 eprintln!(
754 "The IN_NIX_SHELL environment variable is `{in_nix_shell}`; \
755 you may need to set `patch-binaries-for-nix=true` in bootstrap.toml"
756 );
757 }
758 }
759 is_nixos
760 });
761 if val {
762 eprintln!("INFO: You seem to be using Nix.");
763 }
764 val
765}
766
767fn download_component<'a>(
768 dwn_ctx: impl AsRef<DownloadContext<'a>>,
769 out: &Path,
770 mode: DownloadSource,
771 filename: String,
772 prefix: &str,
773 key: &str,
774 destination: &str,
775) {
776 let dwn_ctx = dwn_ctx.as_ref();
777
778 if dwn_ctx.exec_ctx.dry_run() {
779 return;
780 }
781
782 let cache_dst =
783 dwn_ctx.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| out.join("cache"));
784
785 let cache_dir = cache_dst.join(key);
786 if !cache_dir.exists() {
787 t!(fs::create_dir_all(&cache_dir));
788 }
789
790 let bin_root = out.join(dwn_ctx.host_target).join(destination);
791 let tarball = cache_dir.join(&filename);
792 let (base_url, url, should_verify) = match mode {
793 DownloadSource::CI => {
794 let dist_server = if dwn_ctx.llvm_assertions {
795 dwn_ctx.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone()
796 } else {
797 dwn_ctx.stage0_metadata.config.artifacts_server.clone()
798 };
799 let url = format!(
800 "{}/{filename}",
801 key.strip_suffix(&format!("-{}", dwn_ctx.llvm_assertions)).unwrap()
802 );
803 (dist_server, url, false)
804 }
805 DownloadSource::Dist => {
806 let dist_server = env::var("RUSTUP_DIST_SERVER")
807 .unwrap_or(dwn_ctx.stage0_metadata.config.dist_server.to_string());
808 (dist_server, format!("dist/{key}/{filename}"), true)
810 }
811 };
812
813 let checksum = if should_verify {
815 let error = format!(
816 "src/stage0 doesn't contain a checksum for {url}. \
817 Pre-built artifacts might not be available for this \
818 target at this time, see https://doc.rust-lang.org/nightly\
819 /rustc/platform-support.html for more information."
820 );
821 let sha256 = dwn_ctx.stage0_metadata.checksums_sha256.get(&url).expect(&error);
822 if tarball.exists() {
823 if verify(dwn_ctx.exec_ctx, &tarball, sha256) {
824 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
825 return;
826 } else {
827 dwn_ctx.exec_ctx.do_if_verbose(|| {
828 println!(
829 "ignoring cached file {} due to failed verification",
830 tarball.display()
831 )
832 });
833 remove(dwn_ctx.exec_ctx, &tarball);
834 }
835 }
836 Some(sha256)
837 } else if tarball.exists() {
838 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
839 return;
840 } else {
841 None
842 };
843
844 let mut help_on_error = "";
845 if destination == "ci-rustc" {
846 help_on_error = "ERROR: failed to download pre-built rustc from CI
847
848NOTE: old builds get deleted after a certain time
849HELP: if trying to compile an old commit of rustc, disable `download-rustc` in bootstrap.toml:
850
851[rust]
852download-rustc = false
853";
854 }
855 download_file(dwn_ctx, out, &format!("{base_url}/{url}"), &tarball, help_on_error);
856 if let Some(sha256) = checksum
857 && !verify(dwn_ctx.exec_ctx, &tarball, sha256)
858 {
859 panic!("failed to verify {}", tarball.display());
860 }
861
862 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
863}
864
865pub(crate) fn verify(exec_ctx: &ExecutionContext, path: &Path, expected: &str) -> bool {
866 use sha2::Digest;
867
868 exec_ctx.do_if_verbose(|| {
869 println!("verifying {}", path.display());
870 });
871
872 if exec_ctx.dry_run() {
873 return false;
874 }
875
876 let mut hasher = sha2::Sha256::new();
877
878 let file = t!(File::open(path));
879 let mut reader = BufReader::new(file);
880
881 loop {
882 let buffer = t!(reader.fill_buf());
883 let l = buffer.len();
884 if l == 0 {
886 break;
887 }
888 hasher.update(buffer);
889 reader.consume(l);
890 }
891
892 let checksum = hex_encode(hasher.finalize().as_slice());
893 let verified = checksum == expected;
894
895 if !verified {
896 println!(
897 "invalid checksum: \n\
898 found: {checksum}\n\
899 expected: {expected}",
900 );
901 }
902
903 verified
904}
905
906fn unpack(exec_ctx: &ExecutionContext, tarball: &Path, dst: &Path, pattern: &str) {
907 eprintln!("extracting {} to {}", tarball.display(), dst.display());
908 if !dst.exists() {
909 t!(fs::create_dir_all(dst));
910 }
911
912 let uncompressed_filename =
915 Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
916 let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
917
918 let data = t!(File::open(tarball), format!("file {} not found", tarball.display()));
920 let decompressor = XzDecoder::new(BufReader::new(data));
921
922 let mut tar = tar::Archive::new(decompressor);
923
924 let is_ci_rustc = dst.ends_with("ci-rustc");
925 let is_ci_llvm = dst.ends_with("ci-llvm");
926
927 let mut recorded_entries = if is_ci_rustc { recorded_entries(dst, pattern) } else { None };
931
932 for member in t!(tar.entries()) {
933 let mut member = t!(member);
934 let original_path = t!(member.path()).into_owned();
935 if original_path == directory_prefix {
937 continue;
938 }
939 let mut short_path = t!(original_path.strip_prefix(directory_prefix));
940 let is_builder_config = short_path.to_str() == Some(BUILDER_CONFIG_FILENAME);
941
942 if !(short_path.starts_with(pattern) || ((is_ci_rustc || is_ci_llvm) && is_builder_config))
943 {
944 continue;
945 }
946 short_path = short_path.strip_prefix(pattern).unwrap_or(short_path);
947 let dst_path = dst.join(short_path);
948
949 exec_ctx.do_if_verbose(|| {
950 println!("extracting {} to {}", original_path.display(), dst.display());
951 });
952
953 if !t!(member.unpack_in(dst)) {
954 panic!("path traversal attack ??");
955 }
956 if let Some(record) = &mut recorded_entries {
957 t!(writeln!(record, "{}", short_path.to_str().unwrap()));
958 }
959 let src_path = dst.join(original_path);
960 if src_path.is_dir() && dst_path.exists() {
961 continue;
962 }
963 t!(move_file(src_path, dst_path));
964 }
965 let dst_dir = dst.join(directory_prefix);
966 if dst_dir.exists() {
967 t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display()));
968 }
969}
970
971fn download_file<'a>(
972 dwn_ctx: impl AsRef<DownloadContext<'a>>,
973 out: &Path,
974 url: &str,
975 dest_path: &Path,
976 help_on_error: &str,
977) {
978 let dwn_ctx = dwn_ctx.as_ref();
979
980 dwn_ctx.exec_ctx.do_if_verbose(|| {
981 println!("download {url}");
982 });
983 let tempfile = tempdir(out).join(dest_path.file_name().unwrap());
985 match url.split_once("://").map(|(proto, _)| proto) {
989 Some("http") | Some("https") => download_http_with_retries(
990 dwn_ctx.host_target,
991 dwn_ctx.is_running_on_ci(),
992 dwn_ctx.exec_ctx,
993 &tempfile,
994 url,
995 help_on_error,
996 ),
997 Some(other) => panic!("unsupported protocol {other} in {url}"),
998 None => panic!("no protocol in {url}"),
999 }
1000 t!(move_file(&tempfile, dest_path), format!("failed to rename {tempfile:?} to {dest_path:?}"));
1001}
1002
1003pub(crate) fn tempdir(out: &Path) -> PathBuf {
1008 let tmp = out.join("tmp");
1009 t!(fs::create_dir_all(&tmp));
1010 tmp
1011}
1012
1013fn download_http_with_retries(
1014 host_target: TargetSelection,
1015 is_running_on_ci: bool,
1016 exec_ctx: &ExecutionContext,
1017 tempfile: &Path,
1018 url: &str,
1019 help_on_error: &str,
1020) {
1021 println!("downloading {url}");
1022 let mut curl = command("curl").allow_failure();
1027 curl.args([
1028 "--location",
1030 "--speed-time",
1032 "30",
1033 "--speed-limit",
1034 "10",
1035 "--connect-timeout",
1037 "30",
1038 "--output",
1040 tempfile.to_str().unwrap(),
1041 "--continue-at",
1044 "-",
1045 "--retry",
1048 "3",
1049 "--show-error",
1051 "--remote-time",
1053 "--fail",
1055 ]);
1056 if is_running_on_ci {
1058 curl.arg("--silent");
1059 } else {
1060 curl.arg("--progress-bar");
1061 }
1062 if curl_version(exec_ctx) >= semver::Version::new(7, 71, 0) {
1064 curl.arg("--retry-all-errors");
1065 }
1066 curl.arg(url);
1067 if !curl.run(exec_ctx) {
1068 if host_target.contains("windows-msvc") {
1069 eprintln!("Fallback to PowerShell");
1070 for _ in 0..3 {
1071 let powershell = command("PowerShell.exe").allow_failure().args([
1072 "/nologo",
1073 "-Command",
1074 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
1075 &format!(
1076 "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
1077 url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
1078 ),
1079 ]).run_capture_stdout(exec_ctx);
1080
1081 if powershell.is_failure() {
1082 return;
1083 }
1084
1085 eprintln!("\nspurious failure, trying again");
1086 }
1087 }
1088 if !help_on_error.is_empty() {
1089 eprintln!("{help_on_error}");
1090 }
1091 crate::exit!(1);
1092 }
1093}
1094
1095fn curl_version(exec_ctx: &ExecutionContext) -> semver::Version {
1096 let mut curl = command("curl");
1097 curl.arg("-V");
1098 let curl = curl.run_capture_stdout(exec_ctx);
1099 if curl.is_failure() {
1100 return semver::Version::new(1, 0, 0);
1101 }
1102 let output = curl.stdout();
1103 extract_curl_version(output)
1104}