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");
682 const NIX_EXPR: &str = "
683 with (import <nixpkgs> {});
684 symlinkJoin {
685 name = \"rust-stage0-dependencies\";
686 paths = [
687 zlib
688 patchelf
689 stdenv.cc.bintools
690 stdenv.cc.cc.lib
691 ];
692 }
693 ";
694 nix_build_succeeded = command("nix-build")
695 .allow_failure()
696 .args([Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir])
697 .run_capture_stdout(exec_ctx)
698 .is_success();
699 nix_deps_dir
700 });
701 if !nix_build_succeeded {
702 return;
703 }
704
705 let mut patchelf = command(nix_deps_dir.join("bin/patchelf"));
706 patchelf.args(&[
707 OsString::from("--add-rpath"),
708 OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")),
709 ]);
710 if !path_is_dylib(fname) {
711 let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
713 let dynamic_linker = t!(fs::read_to_string(dynamic_linker_path));
714 patchelf.args(["--set-interpreter", dynamic_linker.trim_end()]);
715 }
716 patchelf.arg(fname);
717 let _ = patchelf.allow_failure().run_capture_stdout(exec_ctx);
718}
719
720fn should_fix_bins_and_dylibs(
721 patch_binaries_for_nix: Option<bool>,
722 exec_ctx: &ExecutionContext,
723) -> bool {
724 let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| {
725 let uname = command("uname").allow_failure().arg("-s").run_capture_stdout(exec_ctx);
726 if uname.is_failure() {
727 return false;
728 }
729 let output = uname.stdout();
730 if !output.starts_with("Linux") {
731 return false;
732 }
733 if let Some(explicit_value) = patch_binaries_for_nix {
739 return explicit_value;
740 }
741
742 let is_nixos = match File::open("/etc/os-release") {
745 Err(e) if e.kind() == ErrorKind::NotFound => false,
746 Err(e) => panic!("failed to access /etc/os-release: {e}"),
747 Ok(os_release) => BufReader::new(os_release).lines().any(|l| {
748 let l = l.expect("reading /etc/os-release");
749 matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"")
750 }),
751 };
752 if !is_nixos {
753 let in_nix_shell = env::var("IN_NIX_SHELL");
754 if let Ok(in_nix_shell) = in_nix_shell {
755 eprintln!(
756 "The IN_NIX_SHELL environment variable is `{in_nix_shell}`; \
757 you may need to set `patch-binaries-for-nix=true` in bootstrap.toml"
758 );
759 }
760 }
761 is_nixos
762 });
763 if val {
764 eprintln!("INFO: You seem to be using Nix.");
765 }
766 val
767}
768
769fn download_component<'a>(
770 dwn_ctx: impl AsRef<DownloadContext<'a>>,
771 out: &Path,
772 mode: DownloadSource,
773 filename: String,
774 prefix: &str,
775 key: &str,
776 destination: &str,
777) {
778 let dwn_ctx = dwn_ctx.as_ref();
779
780 if dwn_ctx.exec_ctx.dry_run() {
781 return;
782 }
783
784 let cache_dst =
785 dwn_ctx.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| out.join("cache"));
786
787 let cache_dir = cache_dst.join(key);
788 if !cache_dir.exists() {
789 t!(fs::create_dir_all(&cache_dir));
790 }
791
792 let bin_root = out.join(dwn_ctx.host_target).join(destination);
793 let tarball = cache_dir.join(&filename);
794 let (base_url, url, should_verify) = match mode {
795 DownloadSource::CI => {
796 let dist_server = if dwn_ctx.llvm_assertions {
797 dwn_ctx.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone()
798 } else {
799 dwn_ctx.stage0_metadata.config.artifacts_server.clone()
800 };
801 let url = format!(
802 "{}/{filename}",
803 key.strip_suffix(&format!("-{}", dwn_ctx.llvm_assertions)).unwrap()
804 );
805 (dist_server, url, false)
806 }
807 DownloadSource::Dist => {
808 let dist_server = env::var("RUSTUP_DIST_SERVER")
809 .unwrap_or(dwn_ctx.stage0_metadata.config.dist_server.to_string());
810 (dist_server, format!("dist/{key}/{filename}"), true)
812 }
813 };
814
815 let checksum = if should_verify {
817 let error = format!(
818 "src/stage0 doesn't contain a checksum for {url}. \
819 Pre-built artifacts might not be available for this \
820 target at this time, see https://doc.rust-lang.org/nightly\
821 /rustc/platform-support.html for more information."
822 );
823 let sha256 = dwn_ctx.stage0_metadata.checksums_sha256.get(&url).expect(&error);
824 if tarball.exists() {
825 if verify(dwn_ctx.exec_ctx, &tarball, sha256) {
826 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
827 return;
828 } else {
829 dwn_ctx.exec_ctx.do_if_verbose(|| {
830 println!(
831 "ignoring cached file {} due to failed verification",
832 tarball.display()
833 )
834 });
835 remove(dwn_ctx.exec_ctx, &tarball);
836 }
837 }
838 Some(sha256)
839 } else if tarball.exists() {
840 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
841 return;
842 } else {
843 None
844 };
845
846 let mut help_on_error = "";
847 if destination == "ci-rustc" {
848 help_on_error = "ERROR: failed to download pre-built rustc from CI
849
850NOTE: old builds get deleted after a certain time
851HELP: if trying to compile an old commit of rustc, disable `download-rustc` in bootstrap.toml:
852
853[rust]
854download-rustc = false
855";
856 }
857 download_file(dwn_ctx, out, &format!("{base_url}/{url}"), &tarball, help_on_error);
858 if let Some(sha256) = checksum
859 && !verify(dwn_ctx.exec_ctx, &tarball, sha256)
860 {
861 panic!("failed to verify {}", tarball.display());
862 }
863
864 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
865}
866
867pub(crate) fn verify(exec_ctx: &ExecutionContext, path: &Path, expected: &str) -> bool {
868 use sha2::Digest;
869
870 exec_ctx.do_if_verbose(|| {
871 println!("verifying {}", path.display());
872 });
873
874 if exec_ctx.dry_run() {
875 return false;
876 }
877
878 let mut hasher = sha2::Sha256::new();
879
880 let file = t!(File::open(path));
881 let mut reader = BufReader::new(file);
882
883 loop {
884 let buffer = t!(reader.fill_buf());
885 let l = buffer.len();
886 if l == 0 {
888 break;
889 }
890 hasher.update(buffer);
891 reader.consume(l);
892 }
893
894 let checksum = hex_encode(hasher.finalize().as_slice());
895 let verified = checksum == expected;
896
897 if !verified {
898 println!(
899 "invalid checksum: \n\
900 found: {checksum}\n\
901 expected: {expected}",
902 );
903 }
904
905 verified
906}
907
908fn unpack(exec_ctx: &ExecutionContext, tarball: &Path, dst: &Path, pattern: &str) {
909 eprintln!("extracting {} to {}", tarball.display(), dst.display());
910 if !dst.exists() {
911 t!(fs::create_dir_all(dst));
912 }
913
914 let uncompressed_filename =
917 Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
918 let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
919
920 let data = t!(File::open(tarball), format!("file {} not found", tarball.display()));
922 let decompressor = XzDecoder::new(BufReader::new(data));
923
924 let mut tar = tar::Archive::new(decompressor);
925
926 let is_ci_rustc = dst.ends_with("ci-rustc");
927 let is_ci_llvm = dst.ends_with("ci-llvm");
928
929 let mut recorded_entries = if is_ci_rustc { recorded_entries(dst, pattern) } else { None };
933
934 for member in t!(tar.entries()) {
935 let mut member = t!(member);
936 let original_path = t!(member.path()).into_owned();
937 if original_path == directory_prefix {
939 continue;
940 }
941 let mut short_path = t!(original_path.strip_prefix(directory_prefix));
942 let is_builder_config = short_path.to_str() == Some(BUILDER_CONFIG_FILENAME);
943
944 if !(short_path.starts_with(pattern) || ((is_ci_rustc || is_ci_llvm) && is_builder_config))
945 {
946 continue;
947 }
948 short_path = short_path.strip_prefix(pattern).unwrap_or(short_path);
949 let dst_path = dst.join(short_path);
950
951 exec_ctx.do_if_verbose(|| {
952 println!("extracting {} to {}", original_path.display(), dst.display());
953 });
954
955 if !t!(member.unpack_in(dst)) {
956 panic!("path traversal attack ??");
957 }
958 if let Some(record) = &mut recorded_entries {
959 t!(writeln!(record, "{}", short_path.to_str().unwrap()));
960 }
961 let src_path = dst.join(original_path);
962 if src_path.is_dir() && dst_path.exists() {
963 continue;
964 }
965 t!(move_file(src_path, dst_path));
966 }
967 let dst_dir = dst.join(directory_prefix);
968 if dst_dir.exists() {
969 t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display()));
970 }
971}
972
973fn download_file<'a>(
974 dwn_ctx: impl AsRef<DownloadContext<'a>>,
975 out: &Path,
976 url: &str,
977 dest_path: &Path,
978 help_on_error: &str,
979) {
980 let dwn_ctx = dwn_ctx.as_ref();
981
982 dwn_ctx.exec_ctx.do_if_verbose(|| {
983 println!("download {url}");
984 });
985 let tempfile = tempdir(out).join(dest_path.file_name().unwrap());
987 match url.split_once("://").map(|(proto, _)| proto) {
991 Some("http") | Some("https") => download_http_with_retries(
992 dwn_ctx.host_target,
993 dwn_ctx.is_running_on_ci(),
994 dwn_ctx.exec_ctx,
995 &tempfile,
996 url,
997 help_on_error,
998 ),
999 Some(other) => panic!("unsupported protocol {other} in {url}"),
1000 None => panic!("no protocol in {url}"),
1001 }
1002 t!(move_file(&tempfile, dest_path), format!("failed to rename {tempfile:?} to {dest_path:?}"));
1003}
1004
1005pub(crate) fn tempdir(out: &Path) -> PathBuf {
1010 let tmp = out.join("tmp");
1011 t!(fs::create_dir_all(&tmp));
1012 tmp
1013}
1014
1015fn download_http_with_retries(
1016 host_target: TargetSelection,
1017 is_running_on_ci: bool,
1018 exec_ctx: &ExecutionContext,
1019 tempfile: &Path,
1020 url: &str,
1021 help_on_error: &str,
1022) {
1023 println!("downloading {url}");
1024 let mut curl = command("curl").allow_failure();
1029 curl.args([
1030 "--location",
1032 "--speed-time",
1034 "30",
1035 "--speed-limit",
1036 "10",
1037 "--connect-timeout",
1039 "30",
1040 "--output",
1042 tempfile.to_str().unwrap(),
1043 "--continue-at",
1046 "-",
1047 "--retry",
1050 "3",
1051 "--show-error",
1053 "--remote-time",
1055 "--fail",
1057 ]);
1058 if is_running_on_ci {
1060 curl.arg("--silent");
1061 } else {
1062 curl.arg("--progress-bar");
1063 }
1064 if curl_version(exec_ctx) >= semver::Version::new(7, 71, 0) {
1066 curl.arg("--retry-all-errors");
1067 }
1068 curl.arg(url);
1069 if !curl.run(exec_ctx) {
1070 if host_target.contains("windows-msvc") {
1071 eprintln!("Fallback to PowerShell");
1072 for _ in 0..3 {
1073 let powershell = command("PowerShell.exe").allow_failure().args([
1074 "/nologo",
1075 "-Command",
1076 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
1077 &format!(
1078 "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
1079 url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
1080 ),
1081 ]).run_capture_stdout(exec_ctx);
1082
1083 if powershell.is_failure() {
1084 return;
1085 }
1086
1087 eprintln!("\nspurious failure, trying again");
1088 }
1089 }
1090 if !help_on_error.is_empty() {
1091 eprintln!("{help_on_error}");
1092 }
1093 crate::exit!(1);
1094 }
1095}
1096
1097fn curl_version(exec_ctx: &ExecutionContext) -> semver::Version {
1098 let mut curl = command("curl");
1099 curl.arg("-V");
1100 let curl = curl.run_capture_stdout(exec_ctx);
1101 if curl.is_failure() {
1102 return semver::Version::new(1, 0, 0);
1103 }
1104 let output = curl.stdout();
1105 extract_curl_version(output)
1106}