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 build_helper::stage0_parser::VersionMetadata;
12use xz2::bufread::XzDecoder;
13
14use crate::core::build_steps::llvm::detect_llvm_freshness;
15use crate::core::config::toml::llvm::check_incompatible_options_for_ci_llvm;
16use crate::core::config::{BUILDER_CONFIG_FILENAME, TargetSelection};
17use crate::utils::build_stamp::BuildStamp;
18use crate::utils::exec::{ExecutionContext, command};
19use crate::utils::helpers::{exe, hex_encode, move_file};
20use crate::{Config, exit, t};
21
22static SHOULD_FIX_BINS_AND_DYLIBS: OnceLock<bool> = OnceLock::new();
23
24fn extract_curl_version(out: String) -> semver::Version {
25 out.lines()
27 .next()
28 .and_then(|line| line.split(" ").nth(1))
29 .and_then(|version| semver::Version::parse(version).ok())
30 .unwrap_or(semver::Version::new(1, 0, 0))
31}
32
33impl Config {
35 pub fn is_verbose(&self) -> bool {
36 self.exec_ctx.is_verbose()
37 }
38
39 pub(crate) fn create<P: AsRef<Path>>(&self, path: P, s: &str) {
40 if self.dry_run() {
41 return;
42 }
43 t!(fs::write(path, s));
44 }
45
46 pub(crate) fn remove(&self, f: &Path) {
47 remove(&self.exec_ctx, f);
48 }
49
50 pub(crate) fn tempdir(&self) -> PathBuf {
55 let tmp = self.out.join("tmp");
56 t!(fs::create_dir_all(&tmp));
57 tmp
58 }
59
60 fn should_fix_bins_and_dylibs(&self) -> bool {
63 should_fix_bins_and_dylibs(self.patch_binaries_for_nix, &self.exec_ctx)
64 }
65
66 fn fix_bin_or_dylib(&self, fname: &Path) {
74 fix_bin_or_dylib(&self.out, fname, &self.exec_ctx);
75 }
76
77 fn download_file(&self, url: &str, dest_path: &Path, help_on_error: &str) {
78 let dwn_ctx: DownloadContext<'_> = self.into();
79 download_file(dwn_ctx, &self.out, url, dest_path, help_on_error);
80 }
81
82 fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) {
83 unpack(&self.exec_ctx, tarball, dst, pattern);
84 }
85
86 #[cfg(test)]
88 pub(crate) fn verify(&self, path: &Path, expected: &str) -> bool {
89 verify(&self.exec_ctx, path, expected)
90 }
91}
92
93fn recorded_entries(dst: &Path, pattern: &str) -> Option<BufWriter<File>> {
94 let name = if pattern == "rustc-dev" {
95 ".rustc-dev-contents"
96 } else if pattern.starts_with("rust-std") {
97 ".rust-std-contents"
98 } else {
99 return None;
100 };
101 Some(BufWriter::new(t!(File::create(dst.join(name)))))
102}
103
104#[derive(Clone)]
105enum DownloadSource {
106 CI,
107 Dist,
108}
109
110impl Config {
112 pub(crate) fn download_clippy(&self) -> PathBuf {
113 self.do_if_verbose(|| println!("downloading stage0 clippy artifacts"));
114
115 let date = &self.stage0_metadata.compiler.date;
116 let version = &self.stage0_metadata.compiler.version;
117 let host = self.host_target;
118
119 let clippy_stamp =
120 BuildStamp::new(&self.initial_sysroot).with_prefix("clippy").add_stamp(date);
121 let cargo_clippy = self.initial_sysroot.join("bin").join(exe("cargo-clippy", host));
122 if cargo_clippy.exists() && clippy_stamp.is_up_to_date() {
123 return cargo_clippy;
124 }
125
126 let filename = format!("clippy-{version}-{host}.tar.xz");
127 self.download_component(DownloadSource::Dist, filename, "clippy-preview", date, "stage0");
128 if self.should_fix_bins_and_dylibs() {
129 self.fix_bin_or_dylib(&cargo_clippy);
130 self.fix_bin_or_dylib(&cargo_clippy.with_file_name(exe("clippy-driver", host)));
131 }
132
133 t!(clippy_stamp.write());
134 cargo_clippy
135 }
136
137 pub(crate) fn ci_rust_std_contents(&self) -> Vec<String> {
138 self.ci_component_contents(".rust-std-contents")
139 }
140
141 pub(crate) fn ci_rustc_dev_contents(&self) -> Vec<String> {
142 self.ci_component_contents(".rustc-dev-contents")
143 }
144
145 fn ci_component_contents(&self, stamp_file: &str) -> Vec<String> {
146 assert!(self.download_rustc());
147 if self.dry_run() {
148 return vec![];
149 }
150
151 let ci_rustc_dir = self.ci_rustc_dir();
152 let stamp_file = ci_rustc_dir.join(stamp_file);
153 let contents_file = t!(File::open(&stamp_file), stamp_file.display().to_string());
154 t!(BufReader::new(contents_file).lines().collect())
155 }
156
157 pub(crate) fn download_ci_rustc(&self, commit: &str) {
158 self.do_if_verbose(|| {
159 println!("using downloaded stage2 artifacts from CI (commit {commit})")
160 });
161
162 let version = self.artifact_version_part(commit);
163 let extra_components = ["rustc-dev"];
166
167 self.download_toolchain(
168 &version,
169 "ci-rustc",
170 &format!("{commit}-{}", self.llvm_assertions),
171 &extra_components,
172 Self::download_ci_component,
173 );
174 }
175
176 fn download_toolchain(
177 &self,
178 version: &str,
179 sysroot: &str,
180 stamp_key: &str,
181 extra_components: &[&str],
182 download_component: fn(&Config, String, &str, &str),
183 ) {
184 let host = self.host_target.triple;
185 let bin_root = self.out.join(host).join(sysroot);
186 let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
187
188 if !bin_root.join("bin").join(exe("rustc", self.host_target)).exists()
189 || !rustc_stamp.is_up_to_date()
190 {
191 if bin_root.exists() {
192 t!(fs::remove_dir_all(&bin_root));
193 }
194 let filename = format!("rust-std-{version}-{host}.tar.xz");
195 let pattern = format!("rust-std-{host}");
196 download_component(self, filename, &pattern, stamp_key);
197 let filename = format!("rustc-{version}-{host}.tar.xz");
198 download_component(self, filename, "rustc", stamp_key);
199
200 for component in extra_components {
201 let filename = format!("{component}-{version}-{host}.tar.xz");
202 download_component(self, filename, component, stamp_key);
203 }
204
205 if self.should_fix_bins_and_dylibs() {
206 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustc"));
207 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustdoc"));
208 self.fix_bin_or_dylib(
209 &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
210 );
211 let lib_dir = bin_root.join("lib");
212 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
213 let lib = t!(lib);
214 if path_is_dylib(&lib.path()) {
215 self.fix_bin_or_dylib(&lib.path());
216 }
217 }
218 }
219
220 t!(rustc_stamp.write());
221 }
222 }
223
224 fn download_ci_component(&self, filename: String, prefix: &str, commit_with_assertions: &str) {
227 Self::download_component(
228 self,
229 DownloadSource::CI,
230 filename,
231 prefix,
232 commit_with_assertions,
233 "ci-rustc",
234 )
235 }
236
237 fn download_component(
238 &self,
239 mode: DownloadSource,
240 filename: String,
241 prefix: &str,
242 key: &str,
243 destination: &str,
244 ) {
245 let dwn_ctx: DownloadContext<'_> = self.into();
246 download_component(dwn_ctx, &self.out, mode, filename, prefix, key, destination);
247 }
248
249 pub(crate) fn maybe_download_ci_llvm(&self) {
250 if cfg!(test) {
252 return;
253 }
254
255 if !self.llvm_from_ci {
256 return;
257 }
258
259 let llvm_root = self.ci_llvm_root();
260 let llvm_freshness =
261 detect_llvm_freshness(self, self.rust_info.is_managed_git_subrepository());
262 self.do_if_verbose(|| {
263 eprintln!("LLVM freshness: {llvm_freshness:?}");
264 });
265 let llvm_sha = match llvm_freshness {
266 PathFreshness::LastModifiedUpstream { upstream } => upstream,
267 PathFreshness::HasLocalModifications { upstream, modifications: _ } => upstream,
268 PathFreshness::MissingUpstream => {
269 eprintln!("error: could not find commit hash for downloading LLVM");
270 eprintln!("HELP: maybe your repository history is too shallow?");
271 eprintln!("HELP: consider disabling `download-ci-llvm`");
272 eprintln!("HELP: or fetch enough history to include one upstream commit");
273 crate::exit!(1);
274 }
275 };
276 let stamp_key = format!("{}{}", llvm_sha, self.llvm_assertions);
277 let llvm_stamp = BuildStamp::new(&llvm_root).with_prefix("llvm").add_stamp(stamp_key);
278 if !llvm_stamp.is_up_to_date() && !self.dry_run() {
279 self.download_ci_llvm(&llvm_sha);
280
281 if self.should_fix_bins_and_dylibs() {
282 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
283 self.fix_bin_or_dylib(&t!(entry).path());
284 }
285 }
286
287 let now = std::time::SystemTime::now();
296 let file_times = fs::FileTimes::new().set_accessed(now).set_modified(now);
297
298 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", self.host_target));
299 t!(crate::utils::helpers::set_file_times(llvm_config, file_times));
300
301 if self.should_fix_bins_and_dylibs() {
302 let llvm_lib = llvm_root.join("lib");
303 for entry in t!(fs::read_dir(llvm_lib)) {
304 let lib = t!(entry).path();
305 if path_is_dylib(&lib) {
306 self.fix_bin_or_dylib(&lib);
307 }
308 }
309 }
310
311 t!(llvm_stamp.write());
312 }
313
314 if let Some(config_path) = &self.config {
315 let current_config_toml = Self::get_toml(config_path).unwrap();
316
317 match self.get_builder_toml("ci-llvm") {
318 Ok(ci_config_toml) => {
319 t!(check_incompatible_options_for_ci_llvm(current_config_toml, ci_config_toml));
320 }
321 Err(e) if e.to_string().contains("unknown field") => {
322 println!(
323 "WARNING: CI LLVM has some fields that are no longer supported in bootstrap; download-ci-llvm will be disabled."
324 );
325 println!("HELP: Consider rebasing to a newer commit if available.");
326 }
327 Err(e) => {
328 eprintln!("ERROR: Failed to parse CI LLVM bootstrap.toml: {e}");
329 exit!(2);
330 }
331 };
332 };
333 }
334
335 fn download_ci_llvm(&self, llvm_sha: &str) {
336 assert!(cfg!(not(test)), "unit tests shouldn't be downloading CI LLVM");
338
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
414pub(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 path.to_str().is_some_and(|path| path.contains(".so"))
460}
461
462pub(crate) fn is_download_ci_available(target_triple: &str, llvm_assertions: bool) -> bool {
464 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
506pub(crate) fn maybe_download_rustfmt<'a>(
509 dwn_ctx: impl AsRef<DownloadContext<'a>>,
510 out: &Path,
511) -> Option<PathBuf> {
512 if cfg!(test) {
514 return Some(PathBuf::new());
515 }
516
517 let dwn_ctx = dwn_ctx.as_ref();
518
519 if dwn_ctx.exec_ctx.dry_run() {
520 return Some(PathBuf::new());
521 }
522
523 let VersionMetadata { date, version, .. } = dwn_ctx.stage0_metadata.rustfmt.as_ref()?;
524 let channel = format!("{version}-{date}");
525
526 let host = dwn_ctx.host_target;
527 let bin_root = out.join(host).join("rustfmt");
528 let rustfmt_path = bin_root.join("bin").join(exe("rustfmt", host));
529 let rustfmt_stamp = BuildStamp::new(&bin_root).with_prefix("rustfmt").add_stamp(channel);
530 if rustfmt_path.exists() && rustfmt_stamp.is_up_to_date() {
531 return Some(rustfmt_path);
532 }
533
534 download_component(
535 dwn_ctx,
536 out,
537 DownloadSource::Dist,
538 format!("rustfmt-{version}-{build}.tar.xz", build = host.triple),
539 "rustfmt-preview",
540 date,
541 "rustfmt",
542 );
543
544 download_component(
545 dwn_ctx,
546 out,
547 DownloadSource::Dist,
548 format!("rustc-{version}-{build}.tar.xz", build = host.triple),
549 "rustc",
550 date,
551 "rustfmt",
552 );
553
554 if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
555 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustfmt"), dwn_ctx.exec_ctx);
556 fix_bin_or_dylib(out, &bin_root.join("bin").join("cargo-fmt"), dwn_ctx.exec_ctx);
557 let lib_dir = bin_root.join("lib");
558 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
559 let lib = t!(lib);
560 if path_is_dylib(&lib.path()) {
561 fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
562 }
563 }
564 }
565
566 t!(rustfmt_stamp.write());
567 Some(rustfmt_path)
568}
569
570pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef<DownloadContext<'a>>, out: &Path) {
571 if cfg!(test) {
573 return;
574 }
575
576 let dwn_ctx = dwn_ctx.as_ref();
577 dwn_ctx.exec_ctx.do_if_verbose(|| {
578 println!("downloading stage0 beta artifacts");
579 });
580
581 let date = dwn_ctx.stage0_metadata.compiler.date.clone();
582 let version = dwn_ctx.stage0_metadata.compiler.version.clone();
583 let extra_components = ["cargo"];
584 let sysroot = "stage0";
585 download_toolchain(
586 dwn_ctx,
587 out,
588 &version,
589 sysroot,
590 &date,
591 &extra_components,
592 "stage0",
593 DownloadSource::Dist,
594 );
595}
596
597#[allow(clippy::too_many_arguments)]
598fn download_toolchain<'a>(
599 dwn_ctx: impl AsRef<DownloadContext<'a>>,
600 out: &Path,
601 version: &str,
602 sysroot: &str,
603 stamp_key: &str,
604 extra_components: &[&str],
605 destination: &str,
606 mode: DownloadSource,
607) {
608 assert!(cfg!(not(test)), "unit tests shouldn't be downloading a toolchain");
609
610 let dwn_ctx = dwn_ctx.as_ref();
611 let host = dwn_ctx.host_target.triple;
612 let bin_root = out.join(host).join(sysroot);
613 let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
614
615 if !bin_root.join("bin").join(exe("rustc", dwn_ctx.host_target)).exists()
616 || !rustc_stamp.is_up_to_date()
617 {
618 if bin_root.exists() {
619 t!(fs::remove_dir_all(&bin_root));
620 }
621 let filename = format!("rust-std-{version}-{host}.tar.xz");
622 let pattern = format!("rust-std-{host}");
623 download_component(dwn_ctx, out, mode.clone(), filename, &pattern, stamp_key, destination);
624 let filename = format!("rustc-{version}-{host}.tar.xz");
625 download_component(dwn_ctx, out, mode.clone(), filename, "rustc", stamp_key, destination);
626
627 for component in extra_components {
628 let filename = format!("{component}-{version}-{host}.tar.xz");
629 download_component(
630 dwn_ctx,
631 out,
632 mode.clone(),
633 filename,
634 component,
635 stamp_key,
636 destination,
637 );
638 }
639
640 if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
641 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustc"), dwn_ctx.exec_ctx);
642 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustdoc"), dwn_ctx.exec_ctx);
643 fix_bin_or_dylib(
644 out,
645 &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
646 dwn_ctx.exec_ctx,
647 );
648 let lib_dir = bin_root.join("lib");
649 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
650 let lib = t!(lib);
651 if path_is_dylib(&lib.path()) {
652 fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
653 }
654 }
655 }
656
657 t!(rustc_stamp.write());
658 }
659}
660
661pub(crate) fn remove(exec_ctx: &ExecutionContext, f: &Path) {
662 if exec_ctx.dry_run() {
663 return;
664 }
665 fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}"));
666}
667
668fn fix_bin_or_dylib(out: &Path, fname: &Path, exec_ctx: &ExecutionContext) {
669 assert_eq!(SHOULD_FIX_BINS_AND_DYLIBS.get(), Some(&true));
670 println!("attempting to patch {}", fname.display());
671
672 static NIX_DEPS_DIR: OnceLock<PathBuf> = OnceLock::new();
674 let mut nix_build_succeeded = true;
675 let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
676 let nix_deps_dir = out.join(".nix-deps");
691 const NIX_EXPR: &str = "
692 with (import <nixpkgs> {});
693 symlinkJoin {
694 name = \"rust-stage0-dependencies\";
695 paths = [
696 zlib
697 zstd.out
698 patchelf
699 stdenv.cc.bintools
700 stdenv.cc.cc.lib
701 ];
702 }
703 ";
704 nix_build_succeeded = command("nix-build")
705 .allow_failure()
706 .args([Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir])
707 .run_capture_stdout(exec_ctx)
708 .is_success();
709 nix_deps_dir
710 });
711 if !nix_build_succeeded {
712 return;
713 }
714
715 let mut patchelf = command(nix_deps_dir.join("bin/patchelf"));
716 patchelf.args(&[
717 OsString::from("--add-rpath"),
718 OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")),
719 ]);
720 if !path_is_dylib(fname) {
721 let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
723 let dynamic_linker = t!(fs::read_to_string(dynamic_linker_path));
724 patchelf.args(["--set-interpreter", dynamic_linker.trim_end()]);
725 }
726 patchelf.arg(fname);
727 let _ = patchelf.allow_failure().run_capture_stdout(exec_ctx);
728}
729
730fn should_fix_bins_and_dylibs(
731 patch_binaries_for_nix: Option<bool>,
732 exec_ctx: &ExecutionContext,
733) -> bool {
734 let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| {
735 let uname = command("uname").allow_failure().arg("-s").run_capture_stdout(exec_ctx);
736 if uname.is_failure() {
737 return false;
738 }
739 let output = uname.stdout();
740 if !output.starts_with("Linux") {
741 return false;
742 }
743 if let Some(explicit_value) = patch_binaries_for_nix {
749 return explicit_value;
750 }
751
752 let is_nixos = match File::open("/etc/os-release") {
755 Err(e) if e.kind() == ErrorKind::NotFound => false,
756 Err(e) => panic!("failed to access /etc/os-release: {e}"),
757 Ok(os_release) => BufReader::new(os_release).lines().any(|l| {
758 let l = l.expect("reading /etc/os-release");
759 matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"")
760 }),
761 };
762 if !is_nixos {
763 let in_nix_shell = env::var("IN_NIX_SHELL");
764 if let Ok(in_nix_shell) = in_nix_shell {
765 eprintln!(
766 "The IN_NIX_SHELL environment variable is `{in_nix_shell}`; \
767 you may need to set `patch-binaries-for-nix=true` in bootstrap.toml"
768 );
769 }
770 }
771 is_nixos
772 });
773 if val {
774 eprintln!("INFO: You seem to be using Nix.");
775 }
776 val
777}
778
779fn download_component<'a>(
780 dwn_ctx: impl AsRef<DownloadContext<'a>>,
781 out: &Path,
782 mode: DownloadSource,
783 filename: String,
784 prefix: &str,
785 key: &str,
786 destination: &str,
787) {
788 let dwn_ctx = dwn_ctx.as_ref();
789
790 if dwn_ctx.exec_ctx.dry_run() {
791 return;
792 }
793
794 let cache_dst =
795 dwn_ctx.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| out.join("cache"));
796
797 let cache_dir = cache_dst.join(key);
798 if !cache_dir.exists() {
799 t!(fs::create_dir_all(&cache_dir));
800 }
801
802 let bin_root = out.join(dwn_ctx.host_target).join(destination);
803 let tarball = cache_dir.join(&filename);
804 let (base_url, url, should_verify) = match mode {
805 DownloadSource::CI => {
806 let dist_server = if dwn_ctx.llvm_assertions {
807 dwn_ctx.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone()
808 } else {
809 dwn_ctx.stage0_metadata.config.artifacts_server.clone()
810 };
811 let url = format!(
812 "{}/{filename}",
813 key.strip_suffix(&format!("-{}", dwn_ctx.llvm_assertions)).unwrap()
814 );
815 (dist_server, url, false)
816 }
817 DownloadSource::Dist => {
818 let dist_server = env::var("RUSTUP_DIST_SERVER")
819 .unwrap_or(dwn_ctx.stage0_metadata.config.dist_server.to_string());
820 (dist_server, format!("dist/{key}/{filename}"), true)
822 }
823 };
824
825 let checksum = if should_verify {
827 let error = format!(
828 "src/stage0 doesn't contain a checksum for {url}. \
829 Pre-built artifacts might not be available for this \
830 target at this time, see https://doc.rust-lang.org/nightly\
831 /rustc/platform-support.html for more information."
832 );
833 let sha256 = dwn_ctx.stage0_metadata.checksums_sha256.get(&url).expect(&error);
834 if tarball.exists() {
835 if verify(dwn_ctx.exec_ctx, &tarball, sha256) {
836 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
837 return;
838 } else {
839 dwn_ctx.exec_ctx.do_if_verbose(|| {
840 println!(
841 "ignoring cached file {} due to failed verification",
842 tarball.display()
843 )
844 });
845 remove(dwn_ctx.exec_ctx, &tarball);
846 }
847 }
848 Some(sha256)
849 } else if tarball.exists() {
850 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
851 return;
852 } else {
853 None
854 };
855
856 let mut help_on_error = "";
857 if destination == "ci-rustc" {
858 help_on_error = "ERROR: failed to download pre-built rustc from CI
859
860NOTE: old builds get deleted after a certain time
861HELP: if trying to compile an old commit of rustc, disable `download-rustc` in bootstrap.toml:
862
863[rust]
864download-rustc = false
865";
866 }
867 download_file(dwn_ctx, out, &format!("{base_url}/{url}"), &tarball, help_on_error);
868 if let Some(sha256) = checksum
869 && !verify(dwn_ctx.exec_ctx, &tarball, sha256)
870 {
871 panic!("failed to verify {}", tarball.display());
872 }
873
874 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
875}
876
877pub(crate) fn verify(exec_ctx: &ExecutionContext, path: &Path, expected: &str) -> bool {
878 use sha2::Digest;
879
880 exec_ctx.do_if_verbose(|| {
881 println!("verifying {}", path.display());
882 });
883
884 if exec_ctx.dry_run() {
885 return false;
886 }
887
888 let mut hasher = sha2::Sha256::new();
889
890 let file = t!(File::open(path));
891 let mut reader = BufReader::new(file);
892
893 loop {
894 let buffer = t!(reader.fill_buf());
895 let l = buffer.len();
896 if l == 0 {
898 break;
899 }
900 hasher.update(buffer);
901 reader.consume(l);
902 }
903
904 let checksum = hex_encode(hasher.finalize().as_slice());
905 let verified = checksum == expected;
906
907 if !verified {
908 println!(
909 "invalid checksum: \n\
910 found: {checksum}\n\
911 expected: {expected}",
912 );
913 }
914
915 verified
916}
917
918fn unpack(exec_ctx: &ExecutionContext, tarball: &Path, dst: &Path, pattern: &str) {
919 eprintln!("extracting {} to {}", tarball.display(), dst.display());
920 if !dst.exists() {
921 t!(fs::create_dir_all(dst));
922 }
923
924 let uncompressed_filename =
927 Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
928 let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
929
930 let data = t!(File::open(tarball), format!("file {} not found", tarball.display()));
932 let decompressor = XzDecoder::new(BufReader::new(data));
933
934 let mut tar = tar::Archive::new(decompressor);
935
936 let is_ci_rustc = dst.ends_with("ci-rustc");
937 let is_ci_llvm = dst.ends_with("ci-llvm");
938
939 let mut recorded_entries = if is_ci_rustc { recorded_entries(dst, pattern) } else { None };
943
944 for member in t!(tar.entries()) {
945 let mut member = t!(member);
946 let original_path = t!(member.path()).into_owned();
947 if original_path == directory_prefix {
949 continue;
950 }
951 let mut short_path = t!(original_path.strip_prefix(directory_prefix));
952 let is_builder_config = short_path.to_str() == Some(BUILDER_CONFIG_FILENAME);
953
954 if !(short_path.starts_with(pattern) || ((is_ci_rustc || is_ci_llvm) && is_builder_config))
955 {
956 continue;
957 }
958 short_path = short_path.strip_prefix(pattern).unwrap_or(short_path);
959 let dst_path = dst.join(short_path);
960
961 exec_ctx.do_if_verbose(|| {
962 println!("extracting {} to {}", original_path.display(), dst.display());
963 });
964
965 if !t!(member.unpack_in(dst)) {
966 panic!("path traversal attack ??");
967 }
968 if let Some(record) = &mut recorded_entries {
969 t!(writeln!(record, "{}", short_path.to_str().unwrap()));
970 }
971 let src_path = dst.join(original_path);
972 if src_path.is_dir() && dst_path.exists() {
973 continue;
974 }
975 t!(move_file(src_path, dst_path));
976 }
977 let dst_dir = dst.join(directory_prefix);
978 if dst_dir.exists() {
979 t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display()));
980 }
981}
982
983fn download_file<'a>(
984 dwn_ctx: impl AsRef<DownloadContext<'a>>,
985 out: &Path,
986 url: &str,
987 dest_path: &Path,
988 help_on_error: &str,
989) {
990 let dwn_ctx = dwn_ctx.as_ref();
991
992 dwn_ctx.exec_ctx.do_if_verbose(|| {
993 println!("download {url}");
994 });
995 let tempfile = tempdir(out).join(dest_path.file_name().unwrap());
997 match url.split_once("://").map(|(proto, _)| proto) {
1001 Some("http") | Some("https") => download_http_with_retries(
1002 dwn_ctx.host_target,
1003 dwn_ctx.is_running_on_ci(),
1004 dwn_ctx.exec_ctx,
1005 &tempfile,
1006 url,
1007 help_on_error,
1008 ),
1009 Some(other) => panic!("unsupported protocol {other} in {url}"),
1010 None => panic!("no protocol in {url}"),
1011 }
1012 t!(move_file(&tempfile, dest_path), format!("failed to rename {tempfile:?} to {dest_path:?}"));
1013}
1014
1015pub(crate) fn tempdir(out: &Path) -> PathBuf {
1020 let tmp = out.join("tmp");
1021 t!(fs::create_dir_all(&tmp));
1022 tmp
1023}
1024
1025fn download_http_with_retries(
1026 host_target: TargetSelection,
1027 is_running_on_ci: bool,
1028 exec_ctx: &ExecutionContext,
1029 tempfile: &Path,
1030 url: &str,
1031 help_on_error: &str,
1032) {
1033 println!("downloading {url}");
1034 assert!(cfg!(not(test)), "unit tests shouldn't be downloading things: {url:?}");
1035
1036 let mut curl = command("curl").allow_failure();
1041 curl.args([
1042 "--location",
1044 "--speed-time",
1046 "30",
1047 "--speed-limit",
1048 "10",
1049 "--connect-timeout",
1051 "30",
1052 "--output",
1054 tempfile.to_str().unwrap(),
1055 "--continue-at",
1058 "-",
1059 "--retry",
1062 "3",
1063 "--show-error",
1065 "--remote-time",
1067 "--fail",
1069 ]);
1070 if is_running_on_ci {
1072 curl.arg("--silent");
1073 } else {
1074 curl.arg("--progress-bar");
1075 }
1076 if curl_version(exec_ctx) >= semver::Version::new(7, 71, 0) {
1078 curl.arg("--retry-all-errors");
1079 }
1080 curl.arg(url);
1081 if !curl.run(exec_ctx) {
1082 if host_target.contains("windows-msvc") {
1083 eprintln!("Fallback to PowerShell");
1084 for _ in 0..3 {
1085 let powershell = command("PowerShell.exe").allow_failure().args([
1086 "/nologo",
1087 "-Command",
1088 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
1089 &format!(
1090 "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
1091 url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
1092 ),
1093 ]).run_capture_stdout(exec_ctx);
1094
1095 if powershell.is_success() {
1096 return;
1097 }
1098
1099 eprintln!("\nspurious failure, trying again");
1100 }
1101 }
1102 if !help_on_error.is_empty() {
1103 eprintln!("{help_on_error}");
1104 }
1105 crate::exit!(1);
1106 }
1107}
1108
1109fn curl_version(exec_ctx: &ExecutionContext) -> semver::Version {
1110 let mut curl = command("curl");
1111 curl.arg("-V");
1112 let curl = curl.run_capture_stdout(exec_ctx);
1113 if curl.is_failure() {
1114 return semver::Version::new(1, 0, 0);
1115 }
1116 let output = curl.stdout();
1117 extract_curl_version(output)
1118}