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