3 ffi::{OsStr, OsString},
5 io::{BufRead, BufReader, ErrorKind},
7 process::{Command, Stdio},
10 use once_cell::sync::OnceCell;
11 use xz2::bufread::XzDecoder;
14 config::RustfmtMetadata,
15 native::detect_llvm_sha,
17 util::{check_run, exe, program_out_of_date, try_run},
21 /// Generic helpers that are useful anywhere in bootstrap.
23 pub fn is_verbose(&self) -> bool {
27 pub(crate) fn create(&self, path: &Path, s: &str) {
31 t!(fs::write(path, s));
34 pub(crate) fn remove(&self, f: &Path) {
38 fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {:?}", f));
41 /// Create a temporary directory in `out` and return its path.
43 /// NOTE: this temporary directory is shared between all steps;
44 /// if you need an empty directory, create a new subdirectory inside it.
45 pub(crate) fn tempdir(&self) -> PathBuf {
46 let tmp = self.out.join("tmp");
47 t!(fs::create_dir_all(&tmp));
51 /// Runs a command, printing out nice contextual information if it fails.
52 /// Exits if the command failed to execute at all, otherwise returns its
53 /// `status.success()`.
54 pub(crate) fn try_run(&self, cmd: &mut Command) -> bool {
58 self.verbose(&format!("running: {:?}", cmd));
59 try_run(cmd, self.is_verbose())
62 /// Runs a command, printing out nice contextual information if it fails.
63 /// Returns false if do not execute at all, otherwise returns its
64 /// `status.success()`.
65 pub(crate) fn check_run(&self, cmd: &mut Command) -> bool {
69 self.verbose(&format!("running: {:?}", cmd));
70 check_run(cmd, self.is_verbose())
73 /// Modifies the interpreter section of 'fname' to fix the dynamic linker,
74 /// or the RPATH section, to fix the dynamic library search path
76 /// This is only required on NixOS and uses the PatchELF utility to
77 /// change the interpreter/RPATH of ELF executables.
79 /// Please see https://nixos.org/patchelf.html for more information
80 fn fix_bin_or_dylib(&self, fname: &Path) {
81 // FIXME: cache NixOS detection?
82 match Command::new("uname").arg("-s").stderr(Stdio::inherit()).output() {
84 Ok(output) if !output.status.success() => return,
86 let mut s = output.stdout;
87 if s.last() == Some(&b'\n') {
96 // If the user has asked binaries to be patched for Nix, then
97 // don't check for NixOS or `/lib`, just continue to the patching.
98 // NOTE: this intentionally comes after the Linux check:
99 // - patchelf only works with ELF files, so no need to run it on Mac or Windows
100 // - On other Unix systems, there is no stable syscall interface, so Nix doesn't manage the global libc.
101 if !self.patch_binaries_for_nix {
102 // Use `/etc/os-release` instead of `/etc/NIXOS`.
103 // The latter one does not exist on NixOS when using tmpfs as root.
104 const NIX_IDS: &[&str] = &["ID=nixos", "ID='nixos'", "ID=\"nixos\""];
105 let os_release = match File::open("/etc/os-release") {
106 Err(e) if e.kind() == ErrorKind::NotFound => return,
107 Err(e) => panic!("failed to access /etc/os-release: {}", e),
110 if !BufReader::new(os_release).lines().any(|l| NIX_IDS.contains(&t!(l).trim())) {
113 if Path::new("/lib").exists() {
118 // At this point we're pretty sure the user is running NixOS or using Nix
119 println!("info: you seem to be using Nix. Attempting to patch {}", fname.display());
121 // Only build `.nix-deps` once.
122 static NIX_DEPS_DIR: OnceCell<PathBuf> = OnceCell::new();
123 let mut nix_build_succeeded = true;
124 let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
125 // Run `nix-build` to "build" each dependency (which will likely reuse
126 // the existing `/nix/store` copy, or at most download a pre-built copy).
128 // Importantly, we create a gc-root called `.nix-deps` in the `build/`
129 // directory, but still reference the actual `/nix/store` path in the rpath
130 // as it makes it significantly more robust against changes to the location of
131 // the `.nix-deps` location.
133 // bintools: Needed for the path of `ld-linux.so` (via `nix-support/dynamic-linker`).
134 // zlib: Needed as a system dependency of `libLLVM-*.so`.
135 // patchelf: Needed for patching ELF binaries (see doc comment above).
136 let nix_deps_dir = self.out.join(".nix-deps");
137 const NIX_EXPR: &str = "
138 with (import <nixpkgs> {});
140 name = \"rust-stage0-dependencies\";
148 nix_build_succeeded = self.try_run(Command::new("nix-build").args(&[
156 if !nix_build_succeeded {
160 let mut patchelf = Command::new(nix_deps_dir.join("bin/patchelf"));
161 let rpath_entries = {
162 // ORIGIN is a relative default, all binary and dynamic libraries we ship
163 // appear to have this (even when `../lib` is redundant).
164 // NOTE: there are only two paths here, delimited by a `:`
165 let mut entries = OsString::from("$ORIGIN/../lib:");
166 entries.push(t!(fs::canonicalize(nix_deps_dir)));
167 entries.push("/lib");
170 patchelf.args(&[OsString::from("--set-rpath"), rpath_entries]);
171 if !fname.extension().map_or(false, |ext| ext == "so") {
172 // Finally, set the correct .interp for binaries
173 let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
174 // FIXME: can we support utf8 here? `args` doesn't accept Vec<u8>, only OsString ...
175 let dynamic_linker = t!(String::from_utf8(t!(fs::read(dynamic_linker_path))));
176 patchelf.args(&["--set-interpreter", dynamic_linker.trim_end()]);
179 self.try_run(patchelf.arg(fname));
182 fn download_file(&self, url: &str, dest_path: &Path, help_on_error: &str) {
183 self.verbose(&format!("download {url}"));
184 // Use a temporary file in case we crash while downloading, to avoid a corrupt download in cache/.
185 let tempfile = self.tempdir().join(dest_path.file_name().unwrap());
186 // While bootstrap itself only supports http and https downloads, downstream forks might
187 // need to download components from other protocols. The match allows them adding more
188 // protocols without worrying about merge conflicts if we change the HTTP implementation.
189 match url.split_once("://").map(|(proto, _)| proto) {
190 Some("http") | Some("https") => {
191 self.download_http_with_retries(&tempfile, url, help_on_error)
193 Some(other) => panic!("unsupported protocol {other} in {url}"),
194 None => panic!("no protocol in {url}"),
196 t!(std::fs::rename(&tempfile, dest_path));
199 fn download_http_with_retries(&self, tempfile: &Path, url: &str, help_on_error: &str) {
200 println!("downloading {}", url);
201 // Try curl. If that fails and we are on windows, fallback to PowerShell.
202 let mut curl = Command::new("curl");
208 "10", // timeout if speed is < 10 bytes/sec for > 30 seconds
210 "30", // timeout if cannot connect within 30 seconds
218 if !self.check_run(&mut curl) {
219 if self.build.contains("windows-msvc") {
220 println!("Fallback to PowerShell");
222 if self.try_run(Command::new("PowerShell.exe").args(&[
225 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
227 "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
228 url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
233 println!("\nspurious failure, trying again");
236 if !help_on_error.is_empty() {
237 eprintln!("{}", help_on_error);
239 crate::detail_exit(1);
243 fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) {
244 println!("extracting {} to {}", tarball.display(), dst.display());
246 t!(fs::create_dir_all(dst));
249 // `tarball` ends with `.tar.xz`; strip that suffix
250 // example: `rust-dev-nightly-x86_64-unknown-linux-gnu`
251 let uncompressed_filename =
252 Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
253 let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
255 // decompress the file
256 let data = t!(File::open(tarball));
257 let decompressor = XzDecoder::new(BufReader::new(data));
259 let mut tar = tar::Archive::new(decompressor);
260 for member in t!(tar.entries()) {
261 let mut member = t!(member);
262 let original_path = t!(member.path()).into_owned();
263 // skip the top-level directory
264 if original_path == directory_prefix {
267 let mut short_path = t!(original_path.strip_prefix(directory_prefix));
268 if !short_path.starts_with(pattern) {
271 short_path = t!(short_path.strip_prefix(pattern));
272 let dst_path = dst.join(short_path);
273 self.verbose(&format!("extracting {} to {}", original_path.display(), dst.display()));
274 if !t!(member.unpack_in(dst)) {
275 panic!("path traversal attack ??");
277 let src_path = dst.join(original_path);
278 if src_path.is_dir() && dst_path.exists() {
281 t!(fs::rename(src_path, dst_path));
283 t!(fs::remove_dir_all(dst.join(directory_prefix)));
286 /// Returns whether the SHA256 checksum of `path` matches `expected`.
287 fn verify(&self, path: &Path, expected: &str) -> bool {
290 self.verbose(&format!("verifying {}", path.display()));
291 let mut hasher = sha2::Sha256::new();
292 // FIXME: this is ok for rustfmt (4.1 MB large at time of writing), but it seems memory-intensive for rustc and larger components.
293 // Consider using streaming IO instead?
294 let contents = if self.dry_run() { vec![] } else { t!(fs::read(path)) };
295 hasher.update(&contents);
296 let found = hex::encode(hasher.finalize().as_slice());
297 let verified = found == expected;
298 if !verified && !self.dry_run() {
300 "invalid checksum: \n\
302 expected: {expected}",
309 enum DownloadSource {
314 /// Functions that are only ever called once, but named for clarify and to avoid thousand-line functions.
316 pub(crate) fn maybe_download_rustfmt(&self) -> Option<PathBuf> {
317 let RustfmtMetadata { date, version } = self.stage0_metadata.rustfmt.as_ref()?;
318 let channel = format!("{version}-{date}");
320 let host = self.build;
321 let rustfmt_path = self.initial_rustc.with_file_name(exe("rustfmt", host));
322 let bin_root = self.out.join(host.triple).join("stage0");
323 let rustfmt_stamp = bin_root.join(".rustfmt-stamp");
324 if rustfmt_path.exists() && !program_out_of_date(&rustfmt_stamp, &channel) {
325 return Some(rustfmt_path);
328 let filename = format!("rustfmt-{version}-{build}.tar.xz", build = host.triple);
329 self.download_component(DownloadSource::Dist, filename, "rustfmt-preview", &date, "stage0");
331 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustfmt"));
332 self.fix_bin_or_dylib(&bin_root.join("bin").join("cargo-fmt"));
334 self.create(&rustfmt_stamp, &channel);
338 pub(crate) fn download_ci_rustc(&self, commit: &str) {
339 self.verbose(&format!("using downloaded stage2 artifacts from CI (commit {commit})"));
340 let version = self.artifact_version_part(commit);
341 let host = self.build.triple;
342 let bin_root = self.out.join(host).join("ci-rustc");
343 let rustc_stamp = bin_root.join(".rustc-stamp");
345 if !bin_root.join("bin").join("rustc").exists() || program_out_of_date(&rustc_stamp, commit)
347 if bin_root.exists() {
348 t!(fs::remove_dir_all(&bin_root));
350 let filename = format!("rust-std-{version}-{host}.tar.xz");
351 let pattern = format!("rust-std-{host}");
352 self.download_ci_component(filename, &pattern, commit);
353 let filename = format!("rustc-{version}-{host}.tar.xz");
354 self.download_ci_component(filename, "rustc", commit);
355 // download-rustc doesn't need its own cargo, it can just use beta's.
356 let filename = format!("rustc-dev-{version}-{host}.tar.xz");
357 self.download_ci_component(filename, "rustc-dev", commit);
358 let filename = format!("rust-src-{version}.tar.xz");
359 self.download_ci_component(filename, "rust-src", commit);
361 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustc"));
362 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustdoc"));
363 self.fix_bin_or_dylib(&bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"));
364 let lib_dir = bin_root.join("lib");
365 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
367 if lib.path().extension() == Some(OsStr::new("so")) {
368 self.fix_bin_or_dylib(&lib.path());
371 t!(fs::write(rustc_stamp, commit));
375 /// Download a single component of a CI-built toolchain (not necessarily a published nightly).
376 // NOTE: intentionally takes an owned string to avoid downloading multiple times by accident
377 fn download_ci_component(&self, filename: String, prefix: &str, commit: &str) {
378 Self::download_component(self, DownloadSource::CI, filename, prefix, commit, "ci-rustc")
381 fn download_component(
383 mode: DownloadSource,
389 let cache_dst = self.out.join("cache");
390 let cache_dir = cache_dst.join(key);
391 if !cache_dir.exists() {
392 t!(fs::create_dir_all(&cache_dir));
395 let bin_root = self.out.join(self.build.triple).join(destination);
396 let tarball = cache_dir.join(&filename);
397 let (base_url, url, should_verify) = match mode {
398 DownloadSource::CI => (
399 self.stage0_metadata.config.artifacts_server.clone(),
400 format!("{key}/{filename}"),
403 DownloadSource::Dist => {
404 let dist_server = env::var("RUSTUP_DIST_SERVER")
405 .unwrap_or(self.stage0_metadata.config.dist_server.to_string());
406 // NOTE: make `dist` part of the URL because that's how it's stored in src/stage0.json
407 (dist_server, format!("dist/{key}/{filename}"), true)
411 // For the beta compiler, put special effort into ensuring the checksums are valid.
412 // FIXME: maybe we should do this for download-rustc as well? but it would be a pain to update
413 // this on each and every nightly ...
414 let checksum = if should_verify {
416 "src/stage0.json doesn't contain a checksum for {url}. \
417 Pre-built artifacts might not be available for this \
418 target at this time, see https://doc.rust-lang.org/nightly\
419 /rustc/platform-support.html for more information."
421 let sha256 = self.stage0_metadata.checksums_sha256.get(&url).expect(&error);
422 if tarball.exists() {
423 if self.verify(&tarball, sha256) {
424 self.unpack(&tarball, &bin_root, prefix);
427 self.verbose(&format!(
428 "ignoring cached file {} due to failed verification",
431 self.remove(&tarball);
435 } else if tarball.exists() {
436 self.unpack(&tarball, &bin_root, prefix);
442 self.download_file(&format!("{base_url}/{url}"), &tarball, "");
443 if let Some(sha256) = checksum {
444 if !self.verify(&tarball, sha256) {
445 panic!("failed to verify {}", tarball.display());
449 self.unpack(&tarball, &bin_root, prefix);
452 pub(crate) fn maybe_download_ci_llvm(&self) {
453 if !self.llvm_from_ci {
456 let llvm_root = self.ci_llvm_root();
457 let llvm_stamp = llvm_root.join(".llvm-stamp");
458 let llvm_sha = detect_llvm_sha(&self, self.rust_info.is_managed_git_subrepository());
459 let key = format!("{}{}", llvm_sha, self.llvm_assertions);
460 if program_out_of_date(&llvm_stamp, &key) && !self.dry_run() {
461 self.download_ci_llvm(&llvm_sha);
462 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
463 self.fix_bin_or_dylib(&t!(entry).path());
466 // Update the timestamp of llvm-config to force rustc_llvm to be
467 // rebuilt. This is a hacky workaround for a deficiency in Cargo where
468 // the rerun-if-changed directive doesn't handle changes very well.
469 // https://github.com/rust-lang/cargo/issues/10791
470 // Cargo only compares the timestamp of the file relative to the last
471 // time `rustc_llvm` build script ran. However, the timestamps of the
472 // files in the tarball are in the past, so it doesn't trigger a
474 let now = filetime::FileTime::from_system_time(std::time::SystemTime::now());
475 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", self.build));
476 t!(filetime::set_file_times(&llvm_config, now, now));
478 let llvm_lib = llvm_root.join("lib");
479 for entry in t!(fs::read_dir(&llvm_lib)) {
480 let lib = t!(entry).path();
481 if lib.extension().map_or(false, |ext| ext == "so") {
482 self.fix_bin_or_dylib(&lib);
485 t!(fs::write(llvm_stamp, key));
489 fn download_ci_llvm(&self, llvm_sha: &str) {
490 let llvm_assertions = self.llvm_assertions;
492 let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
493 let cache_dst = self.out.join("cache");
494 let rustc_cache = cache_dst.join(cache_prefix);
495 if !rustc_cache.exists() {
496 t!(fs::create_dir_all(&rustc_cache));
498 let base = if llvm_assertions {
499 &self.stage0_metadata.config.artifacts_with_llvm_assertions_server
501 &self.stage0_metadata.config.artifacts_server
503 let version = self.artifact_version_part(llvm_sha);
504 let filename = format!("rust-dev-{}-{}.tar.xz", version, self.build.triple);
505 let tarball = rustc_cache.join(&filename);
506 if !tarball.exists() {
507 let help_on_error = "error: failed to download llvm from ci
509 help: old builds get deleted after a certain time
510 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
513 download-ci-llvm = false
515 self.download_file(&format!("{base}/{llvm_sha}/{filename}"), &tarball, help_on_error);
517 let llvm_root = self.ci_llvm_root();
518 self.unpack(&tarball, &llvm_root, "rust-dev");