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::git::PathFreshness;
10use xz2::bufread::XzDecoder;
11
12use crate::core::config::{BUILDER_CONFIG_FILENAME, TargetSelection};
13use crate::utils::build_stamp::BuildStamp;
14use crate::utils::exec::{ExecutionContext, command};
15use crate::utils::helpers::{exe, hex_encode, move_file};
16use crate::{Config, t};
17
18static SHOULD_FIX_BINS_AND_DYLIBS: OnceLock<bool> = OnceLock::new();
19
20fn extract_curl_version(out: String) -> semver::Version {
21 out.lines()
23 .next()
24 .and_then(|line| line.split(" ").nth(1))
25 .and_then(|version| semver::Version::parse(version).ok())
26 .unwrap_or(semver::Version::new(1, 0, 0))
27}
28
29impl Config {
31 pub fn is_verbose(&self) -> bool {
32 self.exec_ctx.is_verbose()
33 }
34
35 pub(crate) fn create<P: AsRef<Path>>(&self, path: P, s: &str) {
36 if self.dry_run() {
37 return;
38 }
39 t!(fs::write(path, s));
40 }
41
42 pub(crate) fn remove(&self, f: &Path) {
43 remove(&self.exec_ctx, f);
44 }
45
46 pub(crate) fn tempdir(&self) -> PathBuf {
51 let tmp = self.out.join("tmp");
52 t!(fs::create_dir_all(&tmp));
53 tmp
54 }
55
56 fn should_fix_bins_and_dylibs(&self) -> bool {
59 should_fix_bins_and_dylibs(self.patch_binaries_for_nix, &self.exec_ctx)
60 }
61
62 fn fix_bin_or_dylib(&self, fname: &Path) {
70 fix_bin_or_dylib(&self.out, fname, &self.exec_ctx);
71 }
72
73 fn download_file(&self, url: &str, dest_path: &Path, help_on_error: &str) {
74 let dwn_ctx: DownloadContext<'_> = self.into();
75 download_file(dwn_ctx, &self.out, url, dest_path, help_on_error);
76 }
77
78 fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) {
79 unpack(&self.exec_ctx, tarball, dst, pattern);
80 }
81
82 #[cfg(test)]
84 pub(crate) fn verify(&self, path: &Path, expected: &str) -> bool {
85 verify(&self.exec_ctx, path, expected)
86 }
87}
88
89fn recorded_entries(dst: &Path, pattern: &str) -> Option<BufWriter<File>> {
90 let name = if pattern == "rustc-dev" {
91 ".rustc-dev-contents"
92 } else if pattern.starts_with("rust-std") {
93 ".rust-std-contents"
94 } else {
95 return None;
96 };
97 Some(BufWriter::new(t!(File::create(dst.join(name)))))
98}
99
100#[derive(Clone)]
101enum DownloadSource {
102 CI,
103 Dist,
104}
105
106impl Config {
108 pub(crate) fn download_clippy(&self) -> PathBuf {
109 self.do_if_verbose(|| println!("downloading stage0 clippy artifacts"));
110
111 let date = &self.stage0_metadata.compiler.date;
112 let version = &self.stage0_metadata.compiler.version;
113 let host = self.host_target;
114
115 let clippy_stamp =
116 BuildStamp::new(&self.initial_sysroot).with_prefix("clippy").add_stamp(date);
117 let cargo_clippy = self.initial_sysroot.join("bin").join(exe("cargo-clippy", host));
118 if cargo_clippy.exists() && clippy_stamp.is_up_to_date() {
119 return cargo_clippy;
120 }
121
122 let filename = format!("clippy-{version}-{host}.tar.xz");
123 self.download_component(DownloadSource::Dist, filename, "clippy-preview", date, "stage0");
124 if self.should_fix_bins_and_dylibs() {
125 self.fix_bin_or_dylib(&cargo_clippy);
126 self.fix_bin_or_dylib(&cargo_clippy.with_file_name(exe("clippy-driver", host)));
127 }
128
129 t!(clippy_stamp.write());
130 cargo_clippy
131 }
132
133 pub(crate) fn ci_rust_std_contents(&self) -> Vec<String> {
134 self.ci_component_contents(".rust-std-contents")
135 }
136
137 pub(crate) fn ci_rustc_dev_contents(&self) -> Vec<String> {
138 self.ci_component_contents(".rustc-dev-contents")
139 }
140
141 fn ci_component_contents(&self, stamp_file: &str) -> Vec<String> {
142 assert!(self.download_rustc());
143 if self.dry_run() {
144 return vec![];
145 }
146
147 let ci_rustc_dir = self.ci_rustc_dir();
148 let stamp_file = ci_rustc_dir.join(stamp_file);
149 let contents_file = t!(File::open(&stamp_file), stamp_file.display().to_string());
150 t!(BufReader::new(contents_file).lines().collect())
151 }
152
153 pub(crate) fn download_ci_rustc(&self, commit: &str) {
154 self.do_if_verbose(|| {
155 println!("using downloaded stage2 artifacts from CI (commit {commit})")
156 });
157
158 let version = self.artifact_version_part(commit);
159 let extra_components = ["rustc-dev"];
162
163 self.download_toolchain(
164 &version,
165 "ci-rustc",
166 &format!("{commit}-{}", self.llvm_assertions),
167 &extra_components,
168 Self::download_ci_component,
169 );
170 }
171
172 fn download_toolchain(
173 &self,
174 version: &str,
175 sysroot: &str,
176 stamp_key: &str,
177 extra_components: &[&str],
178 download_component: fn(&Config, String, &str, &str),
179 ) {
180 let host = self.host_target.triple;
181 let bin_root = self.out.join(host).join(sysroot);
182 let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
183
184 if !bin_root.join("bin").join(exe("rustc", self.host_target)).exists()
185 || !rustc_stamp.is_up_to_date()
186 {
187 if bin_root.exists() {
188 t!(fs::remove_dir_all(&bin_root));
189 }
190 let filename = format!("rust-std-{version}-{host}.tar.xz");
191 let pattern = format!("rust-std-{host}");
192 download_component(self, filename, &pattern, stamp_key);
193 let filename = format!("rustc-{version}-{host}.tar.xz");
194 download_component(self, filename, "rustc", stamp_key);
195
196 for component in extra_components {
197 let filename = format!("{component}-{version}-{host}.tar.xz");
198 download_component(self, filename, component, stamp_key);
199 }
200
201 if self.should_fix_bins_and_dylibs() {
202 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustc"));
203 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustdoc"));
204 self.fix_bin_or_dylib(
205 &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
206 );
207 let lib_dir = bin_root.join("lib");
208 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
209 let lib = t!(lib);
210 if path_is_dylib(&lib.path()) {
211 self.fix_bin_or_dylib(&lib.path());
212 }
213 }
214 }
215
216 t!(rustc_stamp.write());
217 }
218 }
219
220 fn download_ci_component(&self, filename: String, prefix: &str, commit_with_assertions: &str) {
223 Self::download_component(
224 self,
225 DownloadSource::CI,
226 filename,
227 prefix,
228 commit_with_assertions,
229 "ci-rustc",
230 )
231 }
232
233 fn download_component(
234 &self,
235 mode: DownloadSource,
236 filename: String,
237 prefix: &str,
238 key: &str,
239 destination: &str,
240 ) {
241 let dwn_ctx: DownloadContext<'_> = self.into();
242 download_component(dwn_ctx, &self.out, mode, filename, prefix, key, destination);
243 }
244
245 #[cfg(test)]
246 pub(crate) fn maybe_download_ci_llvm(&self) {}
247
248 #[cfg(not(test))]
249 pub(crate) fn maybe_download_ci_llvm(&self) {
250 use build_helper::exit;
251 use build_helper::git::PathFreshness;
252
253 use crate::core::build_steps::llvm::detect_llvm_freshness;
254 use crate::core::config::toml::llvm::check_incompatible_options_for_ci_llvm;
255
256 if !self.llvm_from_ci {
257 return;
258 }
259
260 let llvm_root = self.ci_llvm_root();
261 let llvm_freshness =
262 detect_llvm_freshness(self, self.rust_info.is_managed_git_subrepository());
263 self.do_if_verbose(|| {
264 eprintln!("LLVM freshness: {llvm_freshness:?}");
265 });
266 let llvm_sha = match llvm_freshness {
267 PathFreshness::LastModifiedUpstream { upstream } => upstream,
268 PathFreshness::HasLocalModifications { upstream } => upstream,
269 PathFreshness::MissingUpstream => {
270 eprintln!("error: could not find commit hash for downloading LLVM");
271 eprintln!("HELP: maybe your repository history is too shallow?");
272 eprintln!("HELP: consider disabling `download-ci-llvm`");
273 eprintln!("HELP: or fetch enough history to include one upstream commit");
274 crate::exit!(1);
275 }
276 };
277 let stamp_key = format!("{}{}", llvm_sha, self.llvm_assertions);
278 let llvm_stamp = BuildStamp::new(&llvm_root).with_prefix("llvm").add_stamp(stamp_key);
279 if !llvm_stamp.is_up_to_date() && !self.dry_run() {
280 self.download_ci_llvm(&llvm_sha);
281
282 if self.should_fix_bins_and_dylibs() {
283 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
284 self.fix_bin_or_dylib(&t!(entry).path());
285 }
286 }
287
288 let now = std::time::SystemTime::now();
297 let file_times = fs::FileTimes::new().set_accessed(now).set_modified(now);
298
299 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", self.host_target));
300 t!(crate::utils::helpers::set_file_times(llvm_config, file_times));
301
302 if self.should_fix_bins_and_dylibs() {
303 let llvm_lib = llvm_root.join("lib");
304 for entry in t!(fs::read_dir(llvm_lib)) {
305 let lib = t!(entry).path();
306 if path_is_dylib(&lib) {
307 self.fix_bin_or_dylib(&lib);
308 }
309 }
310 }
311
312 t!(llvm_stamp.write());
313 }
314
315 if let Some(config_path) = &self.config {
316 let current_config_toml = Self::get_toml(config_path).unwrap();
317
318 match self.get_builder_toml("ci-llvm") {
319 Ok(ci_config_toml) => {
320 t!(check_incompatible_options_for_ci_llvm(current_config_toml, ci_config_toml));
321 }
322 Err(e) if e.to_string().contains("unknown field") => {
323 println!(
324 "WARNING: CI LLVM has some fields that are no longer supported in bootstrap; download-ci-llvm will be disabled."
325 );
326 println!("HELP: Consider rebasing to a newer commit if available.");
327 }
328 Err(e) => {
329 eprintln!("ERROR: Failed to parse CI LLVM bootstrap.toml: {e}");
330 exit!(2);
331 }
332 };
333 };
334 }
335
336 #[cfg(not(test))]
337 fn download_ci_llvm(&self, llvm_sha: &str) {
338 let llvm_assertions = self.llvm_assertions;
339
340 let cache_prefix = format!("llvm-{llvm_sha}-{llvm_assertions}");
341 let cache_dst =
342 self.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| self.out.join("cache"));
343
344 let rustc_cache = cache_dst.join(cache_prefix);
345 if !rustc_cache.exists() {
346 t!(fs::create_dir_all(&rustc_cache));
347 }
348 let base = if llvm_assertions {
349 &self.stage0_metadata.config.artifacts_with_llvm_assertions_server
350 } else {
351 &self.stage0_metadata.config.artifacts_server
352 };
353 let version = self.artifact_version_part(llvm_sha);
354 let filename = format!("rust-dev-{}-{}.tar.xz", version, self.host_target.triple);
355 let tarball = rustc_cache.join(&filename);
356 if !tarball.exists() {
357 let help_on_error = "ERROR: failed to download llvm from ci
358
359 HELP: There could be two reasons behind this:
360 1) The host triple is not supported for `download-ci-llvm`.
361 2) Old builds get deleted after a certain time.
362 HELP: In either case, disable `download-ci-llvm` in your bootstrap.toml:
363
364 [llvm]
365 download-ci-llvm = false
366 ";
367 self.download_file(&format!("{base}/{llvm_sha}/{filename}"), &tarball, help_on_error);
368 }
369 let llvm_root = self.ci_llvm_root();
370 self.unpack(&tarball, &llvm_root, "rust-dev");
371 }
372
373 pub fn download_ci_gcc(&self, gcc_sha: &str, root_dir: &Path) {
374 let cache_prefix = format!("gcc-{gcc_sha}");
375 let cache_dst =
376 self.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| self.out.join("cache"));
377
378 let gcc_cache = cache_dst.join(cache_prefix);
379 if !gcc_cache.exists() {
380 t!(fs::create_dir_all(&gcc_cache));
381 }
382 let base = &self.stage0_metadata.config.artifacts_server;
383 let version = self.artifact_version_part(gcc_sha);
384 let filename = format!("gcc-dev-{version}-{}.tar.xz", self.host_target.triple);
385 let tarball = gcc_cache.join(&filename);
386 if !tarball.exists() {
387 let help_on_error = "ERROR: failed to download gcc from ci
388
389 HELP: There could be two reasons behind this:
390 1) The host triple is not supported for `download-ci-gcc`.
391 2) Old builds get deleted after a certain time.
392 HELP: In either case, disable `download-ci-gcc` in your bootstrap.toml:
393
394 [gcc]
395 download-ci-gcc = false
396 ";
397 self.download_file(&format!("{base}/{gcc_sha}/{filename}"), &tarball, help_on_error);
398 }
399 self.unpack(&tarball, root_dir, "gcc-dev");
400 }
401}
402
403pub(crate) struct DownloadContext<'a> {
405 pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
406 pub src: &'a Path,
407 pub submodules: &'a Option<bool>,
408 pub host_target: TargetSelection,
409 pub patch_binaries_for_nix: Option<bool>,
410 pub exec_ctx: &'a ExecutionContext,
411 pub stage0_metadata: &'a build_helper::stage0_parser::Stage0,
412 pub llvm_assertions: bool,
413 pub bootstrap_cache_path: &'a Option<PathBuf>,
414 pub is_running_on_ci: bool,
415}
416
417impl<'a> AsRef<DownloadContext<'a>> for DownloadContext<'a> {
418 fn as_ref(&self) -> &DownloadContext<'a> {
419 self
420 }
421}
422
423impl<'a> From<&'a Config> for DownloadContext<'a> {
424 fn from(value: &'a Config) -> Self {
425 DownloadContext {
426 path_modification_cache: value.path_modification_cache.clone(),
427 src: &value.src,
428 host_target: value.host_target,
429 submodules: &value.submodules,
430 patch_binaries_for_nix: value.patch_binaries_for_nix,
431 exec_ctx: &value.exec_ctx,
432 stage0_metadata: &value.stage0_metadata,
433 llvm_assertions: value.llvm_assertions,
434 bootstrap_cache_path: &value.bootstrap_cache_path,
435 is_running_on_ci: value.is_running_on_ci,
436 }
437 }
438}
439
440fn path_is_dylib(path: &Path) -> bool {
441 path.to_str().is_some_and(|path| path.contains(".so"))
443}
444
445pub(crate) fn is_download_ci_available(target_triple: &str, llvm_assertions: bool) -> bool {
447 const SUPPORTED_PLATFORMS: &[&str] = &[
449 "aarch64-apple-darwin",
450 "aarch64-pc-windows-gnullvm",
451 "aarch64-pc-windows-msvc",
452 "aarch64-unknown-linux-gnu",
453 "aarch64-unknown-linux-musl",
454 "arm-unknown-linux-gnueabi",
455 "arm-unknown-linux-gnueabihf",
456 "armv7-unknown-linux-gnueabihf",
457 "i686-pc-windows-gnu",
458 "i686-pc-windows-msvc",
459 "i686-unknown-linux-gnu",
460 "loongarch64-unknown-linux-gnu",
461 "powerpc-unknown-linux-gnu",
462 "powerpc64-unknown-linux-gnu",
463 "powerpc64-unknown-linux-musl",
464 "powerpc64le-unknown-linux-gnu",
465 "powerpc64le-unknown-linux-musl",
466 "riscv64gc-unknown-linux-gnu",
467 "s390x-unknown-linux-gnu",
468 "x86_64-apple-darwin",
469 "x86_64-pc-windows-gnu",
470 "x86_64-pc-windows-gnullvm",
471 "x86_64-pc-windows-msvc",
472 "x86_64-unknown-freebsd",
473 "x86_64-unknown-illumos",
474 "x86_64-unknown-linux-gnu",
475 "x86_64-unknown-linux-musl",
476 "x86_64-unknown-netbsd",
477 ];
478
479 const SUPPORTED_PLATFORMS_WITH_ASSERTIONS: &[&str] =
480 &["x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"];
481
482 if llvm_assertions {
483 SUPPORTED_PLATFORMS_WITH_ASSERTIONS.contains(&target_triple)
484 } else {
485 SUPPORTED_PLATFORMS.contains(&target_triple)
486 }
487}
488
489#[cfg(test)]
490pub(crate) fn maybe_download_rustfmt<'a>(
491 dwn_ctx: impl AsRef<DownloadContext<'a>>,
492 out: &Path,
493) -> Option<PathBuf> {
494 Some(PathBuf::new())
495}
496
497#[cfg(not(test))]
500pub(crate) fn maybe_download_rustfmt<'a>(
501 dwn_ctx: impl AsRef<DownloadContext<'a>>,
502 out: &Path,
503) -> Option<PathBuf> {
504 use build_helper::stage0_parser::VersionMetadata;
505
506 let dwn_ctx = dwn_ctx.as_ref();
507
508 if dwn_ctx.exec_ctx.dry_run() {
509 return Some(PathBuf::new());
510 }
511
512 let VersionMetadata { date, version, .. } = dwn_ctx.stage0_metadata.rustfmt.as_ref()?;
513 let channel = format!("{version}-{date}");
514
515 let host = dwn_ctx.host_target;
516 let bin_root = out.join(host).join("rustfmt");
517 let rustfmt_path = bin_root.join("bin").join(exe("rustfmt", host));
518 let rustfmt_stamp = BuildStamp::new(&bin_root).with_prefix("rustfmt").add_stamp(channel);
519 if rustfmt_path.exists() && rustfmt_stamp.is_up_to_date() {
520 return Some(rustfmt_path);
521 }
522
523 download_component(
524 dwn_ctx,
525 out,
526 DownloadSource::Dist,
527 format!("rustfmt-{version}-{build}.tar.xz", build = host.triple),
528 "rustfmt-preview",
529 date,
530 "rustfmt",
531 );
532
533 download_component(
534 dwn_ctx,
535 out,
536 DownloadSource::Dist,
537 format!("rustc-{version}-{build}.tar.xz", build = host.triple),
538 "rustc",
539 date,
540 "rustfmt",
541 );
542
543 if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
544 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustfmt"), dwn_ctx.exec_ctx);
545 fix_bin_or_dylib(out, &bin_root.join("bin").join("cargo-fmt"), dwn_ctx.exec_ctx);
546 let lib_dir = bin_root.join("lib");
547 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
548 let lib = t!(lib);
549 if path_is_dylib(&lib.path()) {
550 fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
551 }
552 }
553 }
554
555 t!(rustfmt_stamp.write());
556 Some(rustfmt_path)
557}
558
559#[cfg(test)]
560pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef<DownloadContext<'a>>, out: &Path) {}
561
562#[cfg(not(test))]
563pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef<DownloadContext<'a>>, out: &Path) {
564 let dwn_ctx = dwn_ctx.as_ref();
565 dwn_ctx.exec_ctx.do_if_verbose(|| {
566 println!("downloading stage0 beta artifacts");
567 });
568
569 let date = dwn_ctx.stage0_metadata.compiler.date.clone();
570 let version = dwn_ctx.stage0_metadata.compiler.version.clone();
571 let extra_components = ["cargo"];
572 let sysroot = "stage0";
573 download_toolchain(
574 dwn_ctx,
575 out,
576 &version,
577 sysroot,
578 &date,
579 &extra_components,
580 "stage0",
581 DownloadSource::Dist,
582 );
583}
584
585#[allow(clippy::too_many_arguments)]
586fn download_toolchain<'a>(
587 dwn_ctx: impl AsRef<DownloadContext<'a>>,
588 out: &Path,
589 version: &str,
590 sysroot: &str,
591 stamp_key: &str,
592 extra_components: &[&str],
593 destination: &str,
594 mode: DownloadSource,
595) {
596 let dwn_ctx = dwn_ctx.as_ref();
597 let host = dwn_ctx.host_target.triple;
598 let bin_root = out.join(host).join(sysroot);
599 let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
600
601 if !bin_root.join("bin").join(exe("rustc", dwn_ctx.host_target)).exists()
602 || !rustc_stamp.is_up_to_date()
603 {
604 if bin_root.exists() {
605 t!(fs::remove_dir_all(&bin_root));
606 }
607 let filename = format!("rust-std-{version}-{host}.tar.xz");
608 let pattern = format!("rust-std-{host}");
609 download_component(dwn_ctx, out, mode.clone(), filename, &pattern, stamp_key, destination);
610 let filename = format!("rustc-{version}-{host}.tar.xz");
611 download_component(dwn_ctx, out, mode.clone(), filename, "rustc", stamp_key, destination);
612
613 for component in extra_components {
614 let filename = format!("{component}-{version}-{host}.tar.xz");
615 download_component(
616 dwn_ctx,
617 out,
618 mode.clone(),
619 filename,
620 component,
621 stamp_key,
622 destination,
623 );
624 }
625
626 if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
627 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustc"), dwn_ctx.exec_ctx);
628 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustdoc"), dwn_ctx.exec_ctx);
629 fix_bin_or_dylib(
630 out,
631 &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
632 dwn_ctx.exec_ctx,
633 );
634 let lib_dir = bin_root.join("lib");
635 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
636 let lib = t!(lib);
637 if path_is_dylib(&lib.path()) {
638 fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
639 }
640 }
641 }
642
643 t!(rustc_stamp.write());
644 }
645}
646
647pub(crate) fn remove(exec_ctx: &ExecutionContext, f: &Path) {
648 if exec_ctx.dry_run() {
649 return;
650 }
651 fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}"));
652}
653
654fn fix_bin_or_dylib(out: &Path, fname: &Path, exec_ctx: &ExecutionContext) {
655 assert_eq!(SHOULD_FIX_BINS_AND_DYLIBS.get(), Some(&true));
656 println!("attempting to patch {}", fname.display());
657
658 static NIX_DEPS_DIR: OnceLock<PathBuf> = OnceLock::new();
660 let mut nix_build_succeeded = true;
661 let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
662 let nix_deps_dir = out.join(".nix-deps");
674 const NIX_EXPR: &str = "
675 with (import <nixpkgs> {});
676 symlinkJoin {
677 name = \"rust-stage0-dependencies\";
678 paths = [
679 zlib
680 patchelf
681 stdenv.cc.bintools
682 ];
683 }
684 ";
685 nix_build_succeeded = command("nix-build")
686 .allow_failure()
687 .args([Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir])
688 .run_capture_stdout(exec_ctx)
689 .is_success();
690 nix_deps_dir
691 });
692 if !nix_build_succeeded {
693 return;
694 }
695
696 let mut patchelf = command(nix_deps_dir.join("bin/patchelf"));
697 patchelf.args(&[
698 OsString::from("--add-rpath"),
699 OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")),
700 ]);
701 if !path_is_dylib(fname) {
702 let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
704 let dynamic_linker = t!(fs::read_to_string(dynamic_linker_path));
705 patchelf.args(["--set-interpreter", dynamic_linker.trim_end()]);
706 }
707 patchelf.arg(fname);
708 let _ = patchelf.allow_failure().run_capture_stdout(exec_ctx);
709}
710
711fn should_fix_bins_and_dylibs(
712 patch_binaries_for_nix: Option<bool>,
713 exec_ctx: &ExecutionContext,
714) -> bool {
715 let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| {
716 let uname = command("uname").allow_failure().arg("-s").run_capture_stdout(exec_ctx);
717 if uname.is_failure() {
718 return false;
719 }
720 let output = uname.stdout();
721 if !output.starts_with("Linux") {
722 return false;
723 }
724 if let Some(explicit_value) = patch_binaries_for_nix {
730 return explicit_value;
731 }
732
733 let is_nixos = match File::open("/etc/os-release") {
736 Err(e) if e.kind() == ErrorKind::NotFound => false,
737 Err(e) => panic!("failed to access /etc/os-release: {e}"),
738 Ok(os_release) => BufReader::new(os_release).lines().any(|l| {
739 let l = l.expect("reading /etc/os-release");
740 matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"")
741 }),
742 };
743 if !is_nixos {
744 let in_nix_shell = env::var("IN_NIX_SHELL");
745 if let Ok(in_nix_shell) = in_nix_shell {
746 eprintln!(
747 "The IN_NIX_SHELL environment variable is `{in_nix_shell}`; \
748 you may need to set `patch-binaries-for-nix=true` in bootstrap.toml"
749 );
750 }
751 }
752 is_nixos
753 });
754 if val {
755 eprintln!("INFO: You seem to be using Nix.");
756 }
757 val
758}
759
760fn download_component<'a>(
761 dwn_ctx: impl AsRef<DownloadContext<'a>>,
762 out: &Path,
763 mode: DownloadSource,
764 filename: String,
765 prefix: &str,
766 key: &str,
767 destination: &str,
768) {
769 let dwn_ctx = dwn_ctx.as_ref();
770
771 if dwn_ctx.exec_ctx.dry_run() {
772 return;
773 }
774
775 let cache_dst =
776 dwn_ctx.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| out.join("cache"));
777
778 let cache_dir = cache_dst.join(key);
779 if !cache_dir.exists() {
780 t!(fs::create_dir_all(&cache_dir));
781 }
782
783 let bin_root = out.join(dwn_ctx.host_target).join(destination);
784 let tarball = cache_dir.join(&filename);
785 let (base_url, url, should_verify) = match mode {
786 DownloadSource::CI => {
787 let dist_server = if dwn_ctx.llvm_assertions {
788 dwn_ctx.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone()
789 } else {
790 dwn_ctx.stage0_metadata.config.artifacts_server.clone()
791 };
792 let url = format!(
793 "{}/{filename}",
794 key.strip_suffix(&format!("-{}", dwn_ctx.llvm_assertions)).unwrap()
795 );
796 (dist_server, url, false)
797 }
798 DownloadSource::Dist => {
799 let dist_server = env::var("RUSTUP_DIST_SERVER")
800 .unwrap_or(dwn_ctx.stage0_metadata.config.dist_server.to_string());
801 (dist_server, format!("dist/{key}/{filename}"), true)
803 }
804 };
805
806 let checksum = if should_verify {
808 let error = format!(
809 "src/stage0 doesn't contain a checksum for {url}. \
810 Pre-built artifacts might not be available for this \
811 target at this time, see https://doc.rust-lang.org/nightly\
812 /rustc/platform-support.html for more information."
813 );
814 let sha256 = dwn_ctx.stage0_metadata.checksums_sha256.get(&url).expect(&error);
815 if tarball.exists() {
816 if verify(dwn_ctx.exec_ctx, &tarball, sha256) {
817 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
818 return;
819 } else {
820 dwn_ctx.exec_ctx.do_if_verbose(|| {
821 println!(
822 "ignoring cached file {} due to failed verification",
823 tarball.display()
824 )
825 });
826 remove(dwn_ctx.exec_ctx, &tarball);
827 }
828 }
829 Some(sha256)
830 } else if tarball.exists() {
831 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
832 return;
833 } else {
834 None
835 };
836
837 let mut help_on_error = "";
838 if destination == "ci-rustc" {
839 help_on_error = "ERROR: failed to download pre-built rustc from CI
840
841NOTE: old builds get deleted after a certain time
842HELP: if trying to compile an old commit of rustc, disable `download-rustc` in bootstrap.toml:
843
844[rust]
845download-rustc = false
846";
847 }
848 download_file(dwn_ctx, out, &format!("{base_url}/{url}"), &tarball, help_on_error);
849 if let Some(sha256) = checksum
850 && !verify(dwn_ctx.exec_ctx, &tarball, sha256)
851 {
852 panic!("failed to verify {}", tarball.display());
853 }
854
855 unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix);
856}
857
858pub(crate) fn verify(exec_ctx: &ExecutionContext, path: &Path, expected: &str) -> bool {
859 use sha2::Digest;
860
861 exec_ctx.do_if_verbose(|| {
862 println!("verifying {}", path.display());
863 });
864
865 if exec_ctx.dry_run() {
866 return false;
867 }
868
869 let mut hasher = sha2::Sha256::new();
870
871 let file = t!(File::open(path));
872 let mut reader = BufReader::new(file);
873
874 loop {
875 let buffer = t!(reader.fill_buf());
876 let l = buffer.len();
877 if l == 0 {
879 break;
880 }
881 hasher.update(buffer);
882 reader.consume(l);
883 }
884
885 let checksum = hex_encode(hasher.finalize().as_slice());
886 let verified = checksum == expected;
887
888 if !verified {
889 println!(
890 "invalid checksum: \n\
891 found: {checksum}\n\
892 expected: {expected}",
893 );
894 }
895
896 verified
897}
898
899fn unpack(exec_ctx: &ExecutionContext, tarball: &Path, dst: &Path, pattern: &str) {
900 eprintln!("extracting {} to {}", tarball.display(), dst.display());
901 if !dst.exists() {
902 t!(fs::create_dir_all(dst));
903 }
904
905 let uncompressed_filename =
908 Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
909 let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
910
911 let data = t!(File::open(tarball), format!("file {} not found", tarball.display()));
913 let decompressor = XzDecoder::new(BufReader::new(data));
914
915 let mut tar = tar::Archive::new(decompressor);
916
917 let is_ci_rustc = dst.ends_with("ci-rustc");
918 let is_ci_llvm = dst.ends_with("ci-llvm");
919
920 let mut recorded_entries = if is_ci_rustc { recorded_entries(dst, pattern) } else { None };
924
925 for member in t!(tar.entries()) {
926 let mut member = t!(member);
927 let original_path = t!(member.path()).into_owned();
928 if original_path == directory_prefix {
930 continue;
931 }
932 let mut short_path = t!(original_path.strip_prefix(directory_prefix));
933 let is_builder_config = short_path.to_str() == Some(BUILDER_CONFIG_FILENAME);
934
935 if !(short_path.starts_with(pattern) || ((is_ci_rustc || is_ci_llvm) && is_builder_config))
936 {
937 continue;
938 }
939 short_path = short_path.strip_prefix(pattern).unwrap_or(short_path);
940 let dst_path = dst.join(short_path);
941
942 exec_ctx.do_if_verbose(|| {
943 println!("extracting {} to {}", original_path.display(), dst.display());
944 });
945
946 if !t!(member.unpack_in(dst)) {
947 panic!("path traversal attack ??");
948 }
949 if let Some(record) = &mut recorded_entries {
950 t!(writeln!(record, "{}", short_path.to_str().unwrap()));
951 }
952 let src_path = dst.join(original_path);
953 if src_path.is_dir() && dst_path.exists() {
954 continue;
955 }
956 t!(move_file(src_path, dst_path));
957 }
958 let dst_dir = dst.join(directory_prefix);
959 if dst_dir.exists() {
960 t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display()));
961 }
962}
963
964fn download_file<'a>(
965 dwn_ctx: impl AsRef<DownloadContext<'a>>,
966 out: &Path,
967 url: &str,
968 dest_path: &Path,
969 help_on_error: &str,
970) {
971 let dwn_ctx = dwn_ctx.as_ref();
972
973 dwn_ctx.exec_ctx.do_if_verbose(|| {
974 println!("download {url}");
975 });
976 let tempfile = tempdir(out).join(dest_path.file_name().unwrap());
978 match url.split_once("://").map(|(proto, _)| proto) {
982 Some("http") | Some("https") => download_http_with_retries(
983 dwn_ctx.host_target,
984 dwn_ctx.is_running_on_ci,
985 dwn_ctx.exec_ctx,
986 &tempfile,
987 url,
988 help_on_error,
989 ),
990 Some(other) => panic!("unsupported protocol {other} in {url}"),
991 None => panic!("no protocol in {url}"),
992 }
993 t!(move_file(&tempfile, dest_path), format!("failed to rename {tempfile:?} to {dest_path:?}"));
994}
995
996pub(crate) fn tempdir(out: &Path) -> PathBuf {
1001 let tmp = out.join("tmp");
1002 t!(fs::create_dir_all(&tmp));
1003 tmp
1004}
1005
1006fn download_http_with_retries(
1007 host_target: TargetSelection,
1008 is_running_on_ci: bool,
1009 exec_ctx: &ExecutionContext,
1010 tempfile: &Path,
1011 url: &str,
1012 help_on_error: &str,
1013) {
1014 println!("downloading {url}");
1015 let mut curl = command("curl").allow_failure();
1020 curl.args([
1021 "--location",
1023 "--speed-time",
1025 "30",
1026 "--speed-limit",
1027 "10",
1028 "--connect-timeout",
1030 "30",
1031 "--output",
1033 tempfile.to_str().unwrap(),
1034 "--continue-at",
1037 "-",
1038 "--retry",
1041 "3",
1042 "--show-error",
1044 "--remote-time",
1046 "--fail",
1048 ]);
1049 if is_running_on_ci {
1051 curl.arg("--silent");
1052 } else {
1053 curl.arg("--progress-bar");
1054 }
1055 if curl_version(exec_ctx) >= semver::Version::new(7, 71, 0) {
1057 curl.arg("--retry-all-errors");
1058 }
1059 curl.arg(url);
1060 if !curl.run(exec_ctx) {
1061 if host_target.contains("windows-msvc") {
1062 eprintln!("Fallback to PowerShell");
1063 for _ in 0..3 {
1064 let powershell = command("PowerShell.exe").allow_failure().args([
1065 "/nologo",
1066 "-Command",
1067 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
1068 &format!(
1069 "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
1070 url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
1071 ),
1072 ]).run_capture_stdout(exec_ctx);
1073
1074 if powershell.is_failure() {
1075 return;
1076 }
1077
1078 eprintln!("\nspurious failure, trying again");
1079 }
1080 }
1081 if !help_on_error.is_empty() {
1082 eprintln!("{help_on_error}");
1083 }
1084 crate::exit!(1);
1085 }
1086}
1087
1088fn curl_version(exec_ctx: &ExecutionContext) -> semver::Version {
1089 let mut curl = command("curl");
1090 curl.arg("-V");
1091 let curl = curl.run_capture_stdout(exec_ctx);
1092 if curl.is_failure() {
1093 return semver::Version::new(1, 0, 0);
1094 }
1095 let output = curl.stdout();
1096 extract_curl_version(output)
1097}