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, Config, TargetSelection};
17use crate::exit;
18use crate::utils::build_stamp::BuildStamp;
19use crate::utils::exec::{ExecutionContext, command};
20use crate::utils::helpers::{exe, hex_encode, move_file, 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 pub(crate) fn download_std_json_docs(
177 &self,
178 target: TargetSelection,
179 commit: &str,
180 ) -> Option<PathBuf> {
181 if self.dry_run() {
182 return None;
183 }
184
185 self.do_if_verbose(|| println!("using downloaded std json docs from CI (commit {commit})"));
186
187 let version = self.artifact_version_part(commit);
188 download_component(
189 DownloadContext::from(self),
190 &self.out,
191 DownloadSource::CI,
192 format!("rust-docs-json-{version}-{target}.tar.xz"),
193 "rust-docs-json-preview",
194 &format!("{commit}-{}", self.llvm_assertions),
196 "ci-docs-json",
197 )
198 }
199
200 fn download_toolchain(
201 &self,
202 version: &str,
203 sysroot: &str,
204 stamp_key: &str,
205 extra_components: &[&str],
206 download_component: fn(&Config, String, &str, &str),
207 ) {
208 let host = self.host_target.triple;
209 let bin_root = self.out.join(host).join(sysroot);
210 let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
211
212 if !bin_root.join("bin").join(exe("rustc", self.host_target)).exists()
213 || !rustc_stamp.is_up_to_date()
214 {
215 if bin_root.exists() {
216 t!(fs::remove_dir_all(&bin_root));
217 }
218 let filename = format!("rust-std-{version}-{host}.tar.xz");
219 let pattern = format!("rust-std-{host}");
220 download_component(self, filename, &pattern, stamp_key);
221 let filename = format!("rustc-{version}-{host}.tar.xz");
222 download_component(self, filename, "rustc", stamp_key);
223
224 for component in extra_components {
225 let filename = format!("{component}-{version}-{host}.tar.xz");
226 download_component(self, filename, component, stamp_key);
227 }
228
229 if self.should_fix_bins_and_dylibs() {
230 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustc"));
231 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustdoc"));
232 self.fix_bin_or_dylib(
233 &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
234 );
235 let lib_dir = bin_root.join("lib");
236 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
237 let lib = t!(lib);
238 if path_is_dylib(&lib.path()) {
239 self.fix_bin_or_dylib(&lib.path());
240 }
241 }
242 }
243
244 t!(rustc_stamp.write());
245 }
246 }
247
248 fn download_ci_component(&self, filename: String, prefix: &str, commit_with_assertions: &str) {
251 Self::download_component(
252 self,
253 DownloadSource::CI,
254 filename,
255 prefix,
256 commit_with_assertions,
257 "ci-rustc",
258 )
259 }
260
261 fn download_component(
262 &self,
263 mode: DownloadSource,
264 filename: String,
265 prefix: &str,
266 key: &str,
267 destination: &str,
268 ) {
269 let dwn_ctx: DownloadContext<'_> = self.into();
270 download_component(dwn_ctx, &self.out, mode, filename, prefix, key, destination);
271 }
272
273 pub(crate) fn maybe_download_ci_llvm(&self) {
274 if cfg!(test) {
276 return;
277 }
278
279 if !self.llvm_from_ci {
280 return;
281 }
282
283 let llvm_root = self.ci_llvm_root();
284 let llvm_freshness =
285 detect_llvm_freshness(self, self.rust_info.is_managed_git_subrepository());
286 self.do_if_verbose(|| {
287 eprintln!("LLVM freshness: {llvm_freshness:?}");
288 });
289 let llvm_sha = match llvm_freshness {
290 PathFreshness::LastModifiedUpstream { upstream } => upstream,
291 PathFreshness::HasLocalModifications { upstream, modifications: _ } => upstream,
292 PathFreshness::MissingUpstream => {
293 eprintln!("error: could not find commit hash for downloading LLVM");
294 eprintln!("HELP: maybe your repository history is too shallow?");
295 eprintln!("HELP: consider disabling `download-ci-llvm`");
296 eprintln!("HELP: or fetch enough history to include one upstream commit");
297 crate::exit!(1);
298 }
299 };
300 let stamp_key = format!("{}{}", llvm_sha, self.llvm_assertions);
301 let llvm_stamp = BuildStamp::new(&llvm_root).with_prefix("llvm").add_stamp(stamp_key);
302 if !llvm_stamp.is_up_to_date() && !self.dry_run() {
303 self.download_ci_llvm(&llvm_sha);
304
305 if self.should_fix_bins_and_dylibs() {
306 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
307 self.fix_bin_or_dylib(&t!(entry).path());
308 }
309 }
310
311 let now = std::time::SystemTime::now();
320 let file_times = fs::FileTimes::new().set_accessed(now).set_modified(now);
321
322 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", self.host_target));
323 t!(crate::utils::helpers::set_file_times(llvm_config, file_times));
324
325 if self.should_fix_bins_and_dylibs() {
326 let llvm_lib = llvm_root.join("lib");
327 for entry in t!(fs::read_dir(llvm_lib)) {
328 let lib = t!(entry).path();
329 if path_is_dylib(&lib) {
330 self.fix_bin_or_dylib(&lib);
331 }
332 }
333 }
334
335 t!(llvm_stamp.write());
336 }
337
338 if let Some(config_path) = &self.config {
339 let current_config_toml = Self::get_toml(config_path).unwrap();
340
341 match self.get_builder_toml("ci-llvm") {
342 Ok(ci_config_toml) => {
343 t!(check_incompatible_options_for_ci_llvm(current_config_toml, ci_config_toml));
344 }
345 Err(e) if e.to_string().contains("unknown field") => {
346 println!(
347 "WARNING: CI LLVM has some fields that are no longer supported in bootstrap; download-ci-llvm will be disabled."
348 );
349 println!("HELP: Consider rebasing to a newer commit if available.");
350 }
351 Err(e) => {
352 eprintln!("ERROR: Failed to parse CI LLVM bootstrap.toml: {e}");
353 exit!(2);
354 }
355 };
356 };
357 }
358
359 fn download_ci_llvm(&self, llvm_sha: &str) {
360 assert!(cfg!(not(test)), "unit tests shouldn't be downloading CI LLVM");
362
363 let llvm_assertions = self.llvm_assertions;
364
365 let cache_prefix = format!("llvm-{llvm_sha}-{llvm_assertions}");
366 let cache_dst =
367 self.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| self.out.join("cache"));
368
369 let rustc_cache = cache_dst.join(cache_prefix);
370 if !rustc_cache.exists() {
371 t!(fs::create_dir_all(&rustc_cache));
372 }
373 let base = if llvm_assertions {
374 &self.stage0_metadata.config.artifacts_with_llvm_assertions_server
375 } else {
376 &self.stage0_metadata.config.artifacts_server
377 };
378 let version = self.artifact_version_part(llvm_sha);
379 let filename = format!("rust-dev-{}-{}.tar.xz", version, self.host_target.triple);
380 let tarball = rustc_cache.join(&filename);
381 if !tarball.exists() {
382 let help_on_error = "ERROR: failed to download llvm from ci
383
384 HELP: There could be two reasons behind this:
385 1) The host triple is not supported for `download-ci-llvm`.
386 2) Old builds get deleted after a certain time.
387 HELP: In either case, disable `download-ci-llvm` in your bootstrap.toml:
388
389 [llvm]
390 download-ci-llvm = false
391 ";
392 self.download_file(&format!("{base}/{llvm_sha}/{filename}"), &tarball, help_on_error);
393 }
394 let llvm_root = self.ci_llvm_root();
395 self.unpack(&tarball, &llvm_root, "rust-dev");
396 }
397
398 pub fn download_ci_gcc(&self, gcc_sha: &str, root_dir: &Path) {
399 let cache_prefix = format!("gcc-{gcc_sha}");
400 let cache_dst =
401 self.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| self.out.join("cache"));
402
403 let gcc_cache = cache_dst.join(cache_prefix);
404 if !gcc_cache.exists() {
405 t!(fs::create_dir_all(&gcc_cache));
406 }
407 let base = &self.stage0_metadata.config.artifacts_server;
408 let version = self.artifact_version_part(gcc_sha);
409 let filename = format!("gcc-dev-{version}-{}.tar.xz", self.host_target.triple);
410 let tarball = gcc_cache.join(&filename);
411 if !tarball.exists() {
412 let help_on_error = "ERROR: failed to download gcc from ci
413
414 HELP: There could be two reasons behind this:
415 1) The host triple is not supported for `download-ci-gcc`.
416 2) Old builds get deleted after a certain time.
417 HELP: In either case, disable `download-ci-gcc` in your bootstrap.toml:
418
419 [gcc]
420 download-ci-gcc = false
421 ";
422 self.download_file(&format!("{base}/{gcc_sha}/{filename}"), &tarball, help_on_error);
423 }
424 self.unpack(&tarball, root_dir, "gcc-dev");
425
426 if self.should_fix_bins_and_dylibs() {
427 let lib_dir = root_dir.join("lib");
428 for entry in t!(fs::read_dir(lib_dir)) {
429 let lib = t!(entry).path();
430 if path_is_dylib(&lib) {
431 self.fix_bin_or_dylib(&lib);
432 }
433 }
434 }
435 }
436}
437
438pub(crate) struct DownloadContext<'a> {
440 pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
441 pub src: &'a Path,
442 pub submodules: &'a Option<bool>,
443 pub host_target: TargetSelection,
444 pub patch_binaries_for_nix: Option<bool>,
445 pub exec_ctx: &'a ExecutionContext,
446 pub stage0_metadata: &'a build_helper::stage0_parser::Stage0,
447 pub llvm_assertions: bool,
448 pub bootstrap_cache_path: &'a Option<PathBuf>,
449 pub ci_env: CiEnv,
450}
451
452impl<'a> DownloadContext<'a> {
453 pub fn is_running_on_ci(&self) -> bool {
454 self.ci_env.is_running_in_ci()
455 }
456}
457
458impl<'a> AsRef<DownloadContext<'a>> for DownloadContext<'a> {
459 fn as_ref(&self) -> &DownloadContext<'a> {
460 self
461 }
462}
463
464impl<'a> From<&'a Config> for DownloadContext<'a> {
465 fn from(value: &'a Config) -> Self {
466 DownloadContext {
467 path_modification_cache: value.path_modification_cache.clone(),
468 src: &value.src,
469 host_target: value.host_target,
470 submodules: &value.submodules,
471 patch_binaries_for_nix: value.patch_binaries_for_nix,
472 exec_ctx: &value.exec_ctx,
473 stage0_metadata: &value.stage0_metadata,
474 llvm_assertions: value.llvm_assertions,
475 bootstrap_cache_path: &value.bootstrap_cache_path,
476 ci_env: value.ci_env,
477 }
478 }
479}
480
481fn path_is_dylib(path: &Path) -> bool {
482 path.to_str().is_some_and(|path| path.contains(".so"))
484}
485
486pub(crate) fn is_download_ci_available(target_triple: &str, llvm_assertions: bool) -> bool {
488 const SUPPORTED_PLATFORMS: &[&str] = &[
490 "aarch64-apple-darwin",
491 "aarch64-pc-windows-gnullvm",
492 "aarch64-pc-windows-msvc",
493 "aarch64-unknown-linux-gnu",
494 "aarch64-unknown-linux-musl",
495 "arm-unknown-linux-gnueabi",
496 "arm-unknown-linux-gnueabihf",
497 "armv7-unknown-linux-gnueabihf",
498 "i686-pc-windows-gnu",
499 "i686-pc-windows-msvc",
500 "i686-unknown-linux-gnu",
501 "loongarch64-unknown-linux-gnu",
502 "powerpc-unknown-linux-gnu",
503 "powerpc64-unknown-linux-gnu",
504 "powerpc64-unknown-linux-musl",
505 "powerpc64le-unknown-linux-gnu",
506 "powerpc64le-unknown-linux-musl",
507 "riscv64gc-unknown-linux-gnu",
508 "riscv64gc-unknown-linux-musl",
509 "s390x-unknown-linux-gnu",
510 "x86_64-apple-darwin",
511 "x86_64-pc-windows-gnu",
512 "x86_64-pc-windows-gnullvm",
513 "x86_64-pc-windows-msvc",
514 "x86_64-unknown-freebsd",
515 "x86_64-unknown-illumos",
516 "x86_64-unknown-linux-gnu",
517 "x86_64-unknown-linux-musl",
518 "x86_64-unknown-netbsd",
519 ];
520
521 const SUPPORTED_PLATFORMS_WITH_ASSERTIONS: &[&str] =
522 &["x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"];
523
524 if llvm_assertions {
525 SUPPORTED_PLATFORMS_WITH_ASSERTIONS.contains(&target_triple)
526 } else {
527 SUPPORTED_PLATFORMS.contains(&target_triple)
528 }
529}
530
531pub(crate) fn maybe_download_rustfmt(config: &Config, out: &Path) -> Option<PathBuf> {
534 if cfg!(test) {
536 return Some(PathBuf::new());
537 }
538
539 if config.dry_run() {
540 return Some(PathBuf::new());
541 }
542
543 let VersionMetadata { date, version, .. } = config.stage0_metadata.rustfmt.as_ref()?;
544 let channel = format!("{version}-{date}");
545
546 let host = config.host_target;
547 let bin_root = out.join(host).join("rustfmt");
548 let rustfmt_path = bin_root.join("bin").join(exe("rustfmt", host));
549 let rustfmt_stamp = BuildStamp::new(&bin_root).with_prefix("rustfmt").add_stamp(channel);
550 if rustfmt_path.exists() && rustfmt_stamp.is_up_to_date() {
551 return Some(rustfmt_path);
552 }
553
554 download_component(
555 DownloadContext::from(config),
556 out,
557 DownloadSource::Dist,
558 format!("rustfmt-{version}-{build}.tar.xz", build = host.triple),
559 "rustfmt-preview",
560 date,
561 "rustfmt",
562 );
563
564 download_component(
565 DownloadContext::from(config),
566 out,
567 DownloadSource::Dist,
568 format!("rustc-{version}-{build}.tar.xz", build = host.triple),
569 "rustc",
570 date,
571 "rustfmt",
572 );
573
574 if should_fix_bins_and_dylibs(config.patch_binaries_for_nix, &config.exec_ctx) {
575 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustfmt"), &config.exec_ctx);
576 fix_bin_or_dylib(out, &bin_root.join("bin").join("cargo-fmt"), &config.exec_ctx);
577 let lib_dir = bin_root.join("lib");
578 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
579 let lib = t!(lib);
580 if path_is_dylib(&lib.path()) {
581 fix_bin_or_dylib(out, &lib.path(), &config.exec_ctx);
582 }
583 }
584 }
585
586 t!(rustfmt_stamp.write());
587 Some(rustfmt_path)
588}
589
590pub(crate) fn download_beta_toolchain<'a>(dwn_ctx: impl AsRef<DownloadContext<'a>>, out: &Path) {
591 if cfg!(test) {
593 return;
594 }
595
596 let dwn_ctx = dwn_ctx.as_ref();
597 dwn_ctx.exec_ctx.do_if_verbose(|| {
598 println!("downloading stage0 beta artifacts");
599 });
600
601 let date = dwn_ctx.stage0_metadata.compiler.date.clone();
602 let version = dwn_ctx.stage0_metadata.compiler.version.clone();
603 let extra_components = ["cargo"];
604 let sysroot = "stage0";
605 download_toolchain(
606 dwn_ctx,
607 out,
608 &version,
609 sysroot,
610 &date,
611 &extra_components,
612 "stage0",
613 DownloadSource::Dist,
614 );
615}
616
617#[allow(clippy::too_many_arguments)]
618fn download_toolchain<'a>(
619 dwn_ctx: impl AsRef<DownloadContext<'a>>,
620 out: &Path,
621 version: &str,
622 sysroot: &str,
623 stamp_key: &str,
624 extra_components: &[&str],
625 destination: &str,
626 mode: DownloadSource,
627) {
628 assert!(cfg!(not(test)), "unit tests shouldn't be downloading a toolchain");
629
630 let dwn_ctx = dwn_ctx.as_ref();
631 let host = dwn_ctx.host_target.triple;
632 let bin_root = out.join(host).join(sysroot);
633 let rustc_stamp = BuildStamp::new(&bin_root).with_prefix("rustc").add_stamp(stamp_key);
634
635 if !bin_root.join("bin").join(exe("rustc", dwn_ctx.host_target)).exists()
636 || !rustc_stamp.is_up_to_date()
637 {
638 if bin_root.exists() {
639 t!(fs::remove_dir_all(&bin_root));
640 }
641 let filename = format!("rust-std-{version}-{host}.tar.xz");
642 let pattern = format!("rust-std-{host}");
643 download_component(dwn_ctx, out, mode.clone(), filename, &pattern, stamp_key, destination);
644 let filename = format!("rustc-{version}-{host}.tar.xz");
645 download_component(dwn_ctx, out, mode.clone(), filename, "rustc", stamp_key, destination);
646
647 for component in extra_components {
648 let filename = format!("{component}-{version}-{host}.tar.xz");
649 download_component(
650 dwn_ctx,
651 out,
652 mode.clone(),
653 filename,
654 component,
655 stamp_key,
656 destination,
657 );
658 }
659
660 if should_fix_bins_and_dylibs(dwn_ctx.patch_binaries_for_nix, dwn_ctx.exec_ctx) {
661 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustc"), dwn_ctx.exec_ctx);
662 fix_bin_or_dylib(out, &bin_root.join("bin").join("rustdoc"), dwn_ctx.exec_ctx);
663 fix_bin_or_dylib(
664 out,
665 &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
666 dwn_ctx.exec_ctx,
667 );
668 let lib_dir = bin_root.join("lib");
669 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
670 let lib = t!(lib);
671 if path_is_dylib(&lib.path()) {
672 fix_bin_or_dylib(out, &lib.path(), dwn_ctx.exec_ctx);
673 }
674 }
675 }
676
677 t!(rustc_stamp.write());
678 }
679}
680
681pub(crate) fn remove(exec_ctx: &ExecutionContext, f: &Path) {
682 if exec_ctx.dry_run() {
683 return;
684 }
685 fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}"));
686}
687
688fn fix_bin_or_dylib(out: &Path, fname: &Path, exec_ctx: &ExecutionContext) {
689 assert_eq!(SHOULD_FIX_BINS_AND_DYLIBS.get(), Some(&true));
690 println!("attempting to patch {}", fname.display());
691
692 static NIX_DEPS_DIR: OnceLock<PathBuf> = OnceLock::new();
694 let mut nix_build_succeeded = true;
695 let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
696 let nix_deps_dir = out.join(".nix-deps");
711 const NIX_EXPR: &str = "
712 with (import <nixpkgs> {});
713 symlinkJoin {
714 name = \"rust-stage0-dependencies\";
715 paths = [
716 zlib
717 zstd.out
718 patchelf
719 stdenv.cc.bintools
720 stdenv.cc.cc.lib
721 ];
722 }
723 ";
724 nix_build_succeeded = command("nix-build")
725 .allow_failure()
726 .args([Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir])
727 .run_capture_stdout(exec_ctx)
728 .is_success();
729 nix_deps_dir
730 });
731 if !nix_build_succeeded {
732 return;
733 }
734
735 let mut patchelf = command(nix_deps_dir.join("bin/patchelf"));
736 patchelf.args(&[
737 OsString::from("--add-rpath"),
738 OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")),
739 ]);
740 if !path_is_dylib(fname) {
741 let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
743 let dynamic_linker = t!(fs::read_to_string(dynamic_linker_path));
744 patchelf.args(["--set-interpreter", dynamic_linker.trim_end()]);
745 }
746 patchelf.arg(fname);
747 let _ = patchelf.allow_failure().run_capture_stdout(exec_ctx);
748}
749
750fn should_fix_bins_and_dylibs(
751 patch_binaries_for_nix: Option<bool>,
752 exec_ctx: &ExecutionContext,
753) -> bool {
754 let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| {
755 let uname = command("uname").allow_failure().arg("-s").run_capture_stdout(exec_ctx);
756 if uname.is_failure() {
757 return false;
758 }
759 let output = uname.stdout();
760 if !output.starts_with("Linux") {
761 return false;
762 }
763 if let Some(explicit_value) = patch_binaries_for_nix {
769 return explicit_value;
770 }
771
772 let is_nixos = match File::open("/etc/os-release") {
775 Err(e) if e.kind() == ErrorKind::NotFound => false,
776 Err(e) => panic!("failed to access /etc/os-release: {e}"),
777 Ok(os_release) => BufReader::new(os_release).lines().any(|l| {
778 let l = l.expect("reading /etc/os-release");
779 matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"")
780 }),
781 };
782 if !is_nixos {
783 let in_nix_shell = env::var("IN_NIX_SHELL");
784 if let Ok(in_nix_shell) = in_nix_shell {
785 eprintln!(
786 "The IN_NIX_SHELL environment variable is `{in_nix_shell}`; \
787 you may need to set `patch-binaries-for-nix=true` in bootstrap.toml"
788 );
789 }
790 }
791 is_nixos
792 });
793 if val {
794 eprintln!("INFO: You seem to be using Nix.");
795 }
796 val
797}
798
799fn download_component<'a>(
800 dwn_ctx: impl AsRef<DownloadContext<'a>>,
801 out: &Path,
802 mode: DownloadSource,
803 filename: String,
804 prefix: &str,
805 key: &str,
806 destination: &str,
807) -> Option<PathBuf> {
808 let dwn_ctx = dwn_ctx.as_ref();
809
810 if dwn_ctx.exec_ctx.dry_run() {
811 return None;
812 }
813
814 let cache_dst =
815 dwn_ctx.bootstrap_cache_path.as_ref().cloned().unwrap_or_else(|| out.join("cache"));
816
817 let cache_dir = cache_dst.join(key);
818 if !cache_dir.exists() {
819 t!(fs::create_dir_all(&cache_dir));
820 }
821
822 let bin_root = out.join(dwn_ctx.host_target).join(destination);
823 let tarball = cache_dir.join(&filename);
824 let (base_url, url, should_verify) = match mode {
825 DownloadSource::CI => {
826 let dist_server = if dwn_ctx.llvm_assertions {
827 dwn_ctx.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone()
828 } else {
829 dwn_ctx.stage0_metadata.config.artifacts_server.clone()
830 };
831 let url = format!(
832 "{}/{filename}",
833 key.strip_suffix(&format!("-{}", dwn_ctx.llvm_assertions)).unwrap()
834 );
835 (dist_server, url, false)
836 }
837 DownloadSource::Dist => {
838 let dist_server = env::var("RUSTUP_DIST_SERVER")
839 .unwrap_or(dwn_ctx.stage0_metadata.config.dist_server.to_string());
840 (dist_server, format!("dist/{key}/{filename}"), true)
842 }
843 };
844
845 let checksum = if should_verify {
847 let error = format!(
848 "src/stage0 doesn't contain a checksum for {url}. \
849 Pre-built artifacts might not be available for this \
850 target at this time, see https://doc.rust-lang.org/nightly\
851 /rustc/platform-support.html for more information."
852 );
853 let sha256 = dwn_ctx.stage0_metadata.checksums_sha256.get(&url).expect(&error);
854 if tarball.exists() {
855 if verify(dwn_ctx.exec_ctx, &tarball, sha256) {
856 return Some(unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix));
857 } else {
858 dwn_ctx.exec_ctx.do_if_verbose(|| {
859 println!(
860 "ignoring cached file {} due to failed verification",
861 tarball.display()
862 )
863 });
864 remove(dwn_ctx.exec_ctx, &tarball);
865 }
866 }
867 Some(sha256)
868 } else if tarball.exists() {
869 return Some(unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix));
870 } else {
871 None
872 };
873
874 let mut help_on_error = "";
875 if destination == "ci-rustc" {
876 help_on_error = "ERROR: failed to download pre-built rustc from CI
877
878NOTE: old builds get deleted after a certain time
879HELP: if trying to compile an old commit of rustc, disable `download-rustc` in bootstrap.toml:
880
881[rust]
882download-rustc = false
883";
884 }
885 download_file(dwn_ctx, out, &format!("{base_url}/{url}"), &tarball, help_on_error);
886 if let Some(sha256) = checksum
887 && !verify(dwn_ctx.exec_ctx, &tarball, sha256)
888 {
889 panic!("failed to verify {}", tarball.display());
890 }
891
892 Some(unpack(dwn_ctx.exec_ctx, &tarball, &bin_root, prefix))
893}
894
895pub(crate) fn verify(exec_ctx: &ExecutionContext, path: &Path, expected: &str) -> bool {
896 use sha2::Digest;
897
898 exec_ctx.do_if_verbose(|| {
899 println!("verifying {}", path.display());
900 });
901
902 if exec_ctx.dry_run() {
903 return false;
904 }
905
906 let mut hasher = sha2::Sha256::new();
907
908 let file = t!(File::open(path));
909 let mut reader = BufReader::new(file);
910
911 loop {
912 let buffer = t!(reader.fill_buf());
913 let l = buffer.len();
914 if l == 0 {
916 break;
917 }
918 hasher.update(buffer);
919 reader.consume(l);
920 }
921
922 let checksum = hex_encode(hasher.finalize().as_slice());
923 let verified = checksum == expected;
924
925 if !verified {
926 println!(
927 "invalid checksum: \n\
928 found: {checksum}\n\
929 expected: {expected}",
930 );
931 }
932
933 verified
934}
935
936fn unpack(exec_ctx: &ExecutionContext, tarball: &Path, dst: &Path, pattern: &str) -> PathBuf {
937 eprintln!("extracting {} to {}", tarball.display(), dst.display());
938 if !dst.exists() {
939 t!(fs::create_dir_all(dst));
940 }
941
942 let uncompressed_filename =
945 Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
946 let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
947
948 let data = t!(File::open(tarball), format!("file {} not found", tarball.display()));
950 let decompressor = XzDecoder::new(BufReader::new(data));
951
952 let mut tar = tar::Archive::new(decompressor);
953
954 let is_ci_rustc = dst.ends_with("ci-rustc");
955 let is_ci_llvm = dst.ends_with("ci-llvm");
956
957 let mut recorded_entries = if is_ci_rustc { recorded_entries(dst, pattern) } else { None };
961
962 for member in t!(tar.entries()) {
963 let mut member = t!(member);
964 let original_path = t!(member.path()).into_owned();
965 if original_path == directory_prefix {
967 continue;
968 }
969 let mut short_path = t!(original_path.strip_prefix(directory_prefix));
970 let is_builder_config = short_path.to_str() == Some(BUILDER_CONFIG_FILENAME);
971
972 if !(short_path.starts_with(pattern) || ((is_ci_rustc || is_ci_llvm) && is_builder_config))
973 {
974 continue;
975 }
976 short_path = short_path.strip_prefix(pattern).unwrap_or(short_path);
977 let dst_path = dst.join(short_path);
978
979 exec_ctx.do_if_verbose(|| {
980 println!("extracting {} to {}", original_path.display(), dst.display());
981 });
982
983 if !t!(member.unpack_in(dst)) {
984 panic!("path traversal attack ??");
985 }
986 if let Some(record) = &mut recorded_entries {
987 t!(writeln!(record, "{}", short_path.to_str().unwrap()));
988 }
989 let src_path = dst.join(original_path);
990 if src_path.is_dir() && dst_path.exists() {
991 continue;
992 }
993 t!(move_file(src_path, dst_path));
994 }
995 let dst_dir = dst.join(directory_prefix);
996 if dst_dir.exists() {
997 t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display()));
998 }
999 dst.to_path_buf()
1000}
1001
1002fn download_file<'a>(
1003 dwn_ctx: impl AsRef<DownloadContext<'a>>,
1004 out: &Path,
1005 url: &str,
1006 dest_path: &Path,
1007 help_on_error: &str,
1008) {
1009 let dwn_ctx = dwn_ctx.as_ref();
1010
1011 dwn_ctx.exec_ctx.do_if_verbose(|| {
1012 println!("download {url}");
1013 });
1014 let tempfile = tempdir(out).join(dest_path.file_name().unwrap());
1016 match url.split_once("://").map(|(proto, _)| proto) {
1020 Some("http") | Some("https") => download_http_with_retries(
1021 dwn_ctx.host_target,
1022 dwn_ctx.is_running_on_ci(),
1023 dwn_ctx.exec_ctx,
1024 &tempfile,
1025 url,
1026 help_on_error,
1027 ),
1028 Some(other) => panic!("unsupported protocol {other} in {url}"),
1029 None => panic!("no protocol in {url}"),
1030 }
1031 t!(move_file(&tempfile, dest_path), format!("failed to rename {tempfile:?} to {dest_path:?}"));
1032}
1033
1034pub(crate) fn tempdir(out: &Path) -> PathBuf {
1039 let tmp = out.join("tmp");
1040 t!(fs::create_dir_all(&tmp));
1041 tmp
1042}
1043
1044fn download_http_with_retries(
1045 host_target: TargetSelection,
1046 is_running_on_ci: bool,
1047 exec_ctx: &ExecutionContext,
1048 tempfile: &Path,
1049 url: &str,
1050 help_on_error: &str,
1051) {
1052 println!("downloading {url}");
1053 assert!(cfg!(not(test)), "unit tests shouldn't be downloading things: {url:?}");
1054
1055 let mut curl = command("curl").allow_failure();
1060 curl.args([
1061 "--location",
1063 "--speed-time",
1065 "30",
1066 "--speed-limit",
1067 "10",
1068 "--connect-timeout",
1070 "30",
1071 "--output",
1073 tempfile.to_str().unwrap(),
1074 "--continue-at",
1077 "-",
1078 "--retry",
1081 "3",
1082 "--show-error",
1084 "--remote-time",
1086 "--fail",
1088 ]);
1089 if is_running_on_ci {
1091 curl.arg("--silent");
1092 } else {
1093 curl.arg("--progress-bar");
1094 }
1095 if curl_version(exec_ctx) >= semver::Version::new(7, 71, 0) {
1097 curl.arg("--retry-all-errors");
1098 }
1099 curl.arg(url);
1100 if !curl.run(exec_ctx) {
1101 if host_target.contains("windows-msvc") {
1102 eprintln!("Fallback to PowerShell");
1103 for _ in 0..3 {
1104 let powershell = command("PowerShell.exe").allow_failure().args([
1105 "/nologo",
1106 "-Command",
1107 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
1108 &format!(
1109 "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
1110 url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
1111 ),
1112 ]).run_capture_stdout(exec_ctx);
1113
1114 if powershell.is_success() {
1115 return;
1116 }
1117
1118 eprintln!("\nspurious failure, trying again");
1119 }
1120 }
1121 if !help_on_error.is_empty() {
1122 eprintln!("{help_on_error}");
1123 }
1124 crate::exit!(1);
1125 }
1126}
1127
1128fn curl_version(exec_ctx: &ExecutionContext) -> semver::Version {
1129 let mut curl = command("curl");
1130 curl.arg("-V");
1131 let curl = curl.run_capture_stdout(exec_ctx);
1132 if curl.is_failure() {
1133 return semver::Version::new(1, 0, 0);
1134 }
1135 let output = curl.stdout();
1136 extract_curl_version(output)
1137}