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 static SHOULD_FIX_BINS_AND_DYLIBS: OnceCell<bool> = OnceCell::new();
23 /// Generic helpers that are useful anywhere in bootstrap.
25 pub fn is_verbose(&self) -> bool {
29 pub(crate) fn create(&self, path: &Path, s: &str) {
33 t!(fs::write(path, s));
36 pub(crate) fn remove(&self, f: &Path) {
40 fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {:?}", f));
43 /// Create a temporary directory in `out` and return its path.
45 /// NOTE: this temporary directory is shared between all steps;
46 /// if you need an empty directory, create a new subdirectory inside it.
47 pub(crate) fn tempdir(&self) -> PathBuf {
48 let tmp = self.out.join("tmp");
49 t!(fs::create_dir_all(&tmp));
53 /// Runs a command, printing out nice contextual information if it fails.
54 /// Exits if the command failed to execute at all, otherwise returns its
55 /// `status.success()`.
56 pub(crate) fn try_run(&self, cmd: &mut Command) -> bool {
60 self.verbose(&format!("running: {:?}", cmd));
61 try_run(cmd, self.is_verbose())
64 /// Runs a command, printing out nice contextual information if it fails.
65 /// Returns false if do not execute at all, otherwise returns its
66 /// `status.success()`.
67 pub(crate) fn check_run(&self, cmd: &mut Command) -> bool {
71 self.verbose(&format!("running: {:?}", cmd));
72 check_run(cmd, self.is_verbose())
75 /// Whether or not `fix_bin_or_dylib` needs to be run; can only be true
77 fn should_fix_bins_and_dylibs(&self) -> bool {
78 let val = *SHOULD_FIX_BINS_AND_DYLIBS.get_or_init(|| {
79 match Command::new("uname").arg("-s").stderr(Stdio::inherit()).output() {
80 Err(_) => return false,
81 Ok(output) if !output.status.success() => return false,
83 let mut os_name = output.stdout;
84 if os_name.last() == Some(&b'\n') {
87 if os_name != b"Linux" {
93 // If the user has asked binaries to be patched for Nix, then
94 // don't check for NixOS or `/lib`.
95 // NOTE: this intentionally comes after the Linux check:
96 // - patchelf only works with ELF files, so no need to run it on Mac or Windows
97 // - On other Unix systems, there is no stable syscall interface, so Nix doesn't manage the global libc.
98 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 let is_nixos = match File::open("/etc/os-release") {
105 Err(e) if e.kind() == ErrorKind::NotFound => false,
106 Err(e) => panic!("failed to access /etc/os-release: {}", e),
107 Ok(os_release) => BufReader::new(os_release).lines().any(|l| {
108 let l = l.expect("reading /etc/os-release");
109 matches!(l.trim(), "ID=nixos" | "ID='nixos'" | "ID=\"nixos\"")
112 is_nixos && !Path::new("/lib").exists()
115 println!("info: You seem to be using Nix.");
120 /// Modifies the interpreter section of 'fname' to fix the dynamic linker,
121 /// or the RPATH section, to fix the dynamic library search path
123 /// This is only required on NixOS and uses the PatchELF utility to
124 /// change the interpreter/RPATH of ELF executables.
126 /// Please see https://nixos.org/patchelf.html for more information
127 fn fix_bin_or_dylib(&self, fname: &Path) {
128 assert_eq!(SHOULD_FIX_BINS_AND_DYLIBS.get(), Some(&true));
129 println!("attempting to patch {}", fname.display());
131 // Only build `.nix-deps` once.
132 static NIX_DEPS_DIR: OnceCell<PathBuf> = OnceCell::new();
133 let mut nix_build_succeeded = true;
134 let nix_deps_dir = NIX_DEPS_DIR.get_or_init(|| {
135 // Run `nix-build` to "build" each dependency (which will likely reuse
136 // the existing `/nix/store` copy, or at most download a pre-built copy).
138 // Importantly, we create a gc-root called `.nix-deps` in the `build/`
139 // directory, but still reference the actual `/nix/store` path in the rpath
140 // as it makes it significantly more robust against changes to the location of
141 // the `.nix-deps` location.
143 // bintools: Needed for the path of `ld-linux.so` (via `nix-support/dynamic-linker`).
144 // zlib: Needed as a system dependency of `libLLVM-*.so`.
145 // patchelf: Needed for patching ELF binaries (see doc comment above).
146 let nix_deps_dir = self.out.join(".nix-deps");
147 const NIX_EXPR: &str = "
148 with (import <nixpkgs> {});
150 name = \"rust-stage0-dependencies\";
158 nix_build_succeeded = self.try_run(Command::new("nix-build").args(&[
166 if !nix_build_succeeded {
170 let mut patchelf = Command::new(nix_deps_dir.join("bin/patchelf"));
171 let rpath_entries = {
172 // ORIGIN is a relative default, all binary and dynamic libraries we ship
173 // appear to have this (even when `../lib` is redundant).
174 // NOTE: there are only two paths here, delimited by a `:`
175 let mut entries = OsString::from("$ORIGIN/../lib:");
176 entries.push(t!(fs::canonicalize(nix_deps_dir)));
177 entries.push("/lib");
180 patchelf.args(&[OsString::from("--set-rpath"), rpath_entries]);
181 if !fname.extension().map_or(false, |ext| ext == "so") {
182 // Finally, set the correct .interp for binaries
183 let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker");
184 // FIXME: can we support utf8 here? `args` doesn't accept Vec<u8>, only OsString ...
185 let dynamic_linker = t!(String::from_utf8(t!(fs::read(dynamic_linker_path))));
186 patchelf.args(&["--set-interpreter", dynamic_linker.trim_end()]);
189 self.try_run(patchelf.arg(fname));
192 fn download_file(&self, url: &str, dest_path: &Path, help_on_error: &str) {
193 self.verbose(&format!("download {url}"));
194 // Use a temporary file in case we crash while downloading, to avoid a corrupt download in cache/.
195 let tempfile = self.tempdir().join(dest_path.file_name().unwrap());
196 // While bootstrap itself only supports http and https downloads, downstream forks might
197 // need to download components from other protocols. The match allows them adding more
198 // protocols without worrying about merge conflicts if we change the HTTP implementation.
199 match url.split_once("://").map(|(proto, _)| proto) {
200 Some("http") | Some("https") => {
201 self.download_http_with_retries(&tempfile, url, help_on_error)
203 Some(other) => panic!("unsupported protocol {other} in {url}"),
204 None => panic!("no protocol in {url}"),
206 t!(std::fs::rename(&tempfile, dest_path));
209 fn download_http_with_retries(&self, tempfile: &Path, url: &str, help_on_error: &str) {
210 println!("downloading {}", url);
211 // Try curl. If that fails and we are on windows, fallback to PowerShell.
212 let mut curl = Command::new("curl");
218 "10", // timeout if speed is < 10 bytes/sec for > 30 seconds
220 "30", // timeout if cannot connect within 30 seconds
228 if !self.check_run(&mut curl) {
229 if self.build.contains("windows-msvc") {
230 println!("Fallback to PowerShell");
232 if self.try_run(Command::new("PowerShell.exe").args(&[
235 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
237 "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
238 url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
243 println!("\nspurious failure, trying again");
246 if !help_on_error.is_empty() {
247 eprintln!("{}", help_on_error);
249 crate::detail_exit(1);
253 fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) {
254 println!("extracting {} to {}", tarball.display(), dst.display());
256 t!(fs::create_dir_all(dst));
259 // `tarball` ends with `.tar.xz`; strip that suffix
260 // example: `rust-dev-nightly-x86_64-unknown-linux-gnu`
261 let uncompressed_filename =
262 Path::new(tarball.file_name().expect("missing tarball filename")).file_stem().unwrap();
263 let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap());
265 // decompress the file
266 let data = t!(File::open(tarball));
267 let decompressor = XzDecoder::new(BufReader::new(data));
269 let mut tar = tar::Archive::new(decompressor);
270 for member in t!(tar.entries()) {
271 let mut member = t!(member);
272 let original_path = t!(member.path()).into_owned();
273 // skip the top-level directory
274 if original_path == directory_prefix {
277 let mut short_path = t!(original_path.strip_prefix(directory_prefix));
278 if !short_path.starts_with(pattern) {
281 short_path = t!(short_path.strip_prefix(pattern));
282 let dst_path = dst.join(short_path);
283 self.verbose(&format!("extracting {} to {}", original_path.display(), dst.display()));
284 if !t!(member.unpack_in(dst)) {
285 panic!("path traversal attack ??");
287 let src_path = dst.join(original_path);
288 if src_path.is_dir() && dst_path.exists() {
291 t!(fs::rename(src_path, dst_path));
293 t!(fs::remove_dir_all(dst.join(directory_prefix)));
296 /// Returns whether the SHA256 checksum of `path` matches `expected`.
297 fn verify(&self, path: &Path, expected: &str) -> bool {
300 self.verbose(&format!("verifying {}", path.display()));
301 let mut hasher = sha2::Sha256::new();
302 // FIXME: this is ok for rustfmt (4.1 MB large at time of writing), but it seems memory-intensive for rustc and larger components.
303 // Consider using streaming IO instead?
304 let contents = if self.dry_run() { vec![] } else { t!(fs::read(path)) };
305 hasher.update(&contents);
306 let found = hex::encode(hasher.finalize().as_slice());
307 let verified = found == expected;
308 if !verified && !self.dry_run() {
310 "invalid checksum: \n\
312 expected: {expected}",
319 enum DownloadSource {
324 /// Functions that are only ever called once, but named for clarify and to avoid thousand-line functions.
326 pub(crate) fn maybe_download_rustfmt(&self) -> Option<PathBuf> {
327 let RustfmtMetadata { date, version } = self.stage0_metadata.rustfmt.as_ref()?;
328 let channel = format!("{version}-{date}");
330 let host = self.build;
331 let bin_root = self.out.join(host.triple).join("rustfmt");
332 let rustfmt_path = bin_root.join("bin").join(exe("rustfmt", host));
333 let rustfmt_stamp = bin_root.join(".rustfmt-stamp");
334 if rustfmt_path.exists() && !program_out_of_date(&rustfmt_stamp, &channel) {
335 return Some(rustfmt_path);
338 self.download_component(
339 DownloadSource::Dist,
340 format!("rustfmt-{version}-{build}.tar.xz", build = host.triple),
345 self.download_component(
346 DownloadSource::Dist,
347 format!("rustc-{version}-{build}.tar.xz", build = host.triple),
353 if self.should_fix_bins_and_dylibs() {
354 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustfmt"));
355 self.fix_bin_or_dylib(&bin_root.join("bin").join("cargo-fmt"));
358 self.create(&rustfmt_stamp, &channel);
362 pub(crate) fn download_ci_rustc(&self, commit: &str) {
363 self.verbose(&format!("using downloaded stage2 artifacts from CI (commit {commit})"));
364 let version = self.artifact_version_part(commit);
365 let host = self.build.triple;
366 let bin_root = self.out.join(host).join("ci-rustc");
367 let rustc_stamp = bin_root.join(".rustc-stamp");
369 if !bin_root.join("bin").join("rustc").exists() || program_out_of_date(&rustc_stamp, commit)
371 if bin_root.exists() {
372 t!(fs::remove_dir_all(&bin_root));
374 let filename = format!("rust-std-{version}-{host}.tar.xz");
375 let pattern = format!("rust-std-{host}");
376 self.download_ci_component(filename, &pattern, commit);
377 let filename = format!("rustc-{version}-{host}.tar.xz");
378 self.download_ci_component(filename, "rustc", commit);
379 // download-rustc doesn't need its own cargo, it can just use beta's.
380 let filename = format!("rustc-dev-{version}-{host}.tar.xz");
381 self.download_ci_component(filename, "rustc-dev", commit);
382 let filename = format!("rust-src-{version}.tar.xz");
383 self.download_ci_component(filename, "rust-src", commit);
385 if self.should_fix_bins_and_dylibs() {
386 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustc"));
387 self.fix_bin_or_dylib(&bin_root.join("bin").join("rustdoc"));
388 self.fix_bin_or_dylib(
389 &bin_root.join("libexec").join("rust-analyzer-proc-macro-srv"),
391 let lib_dir = bin_root.join("lib");
392 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
394 if lib.path().extension() == Some(OsStr::new("so")) {
395 self.fix_bin_or_dylib(&lib.path());
400 t!(fs::write(rustc_stamp, commit));
404 /// Download a single component of a CI-built toolchain (not necessarily a published nightly).
405 // NOTE: intentionally takes an owned string to avoid downloading multiple times by accident
406 fn download_ci_component(&self, filename: String, prefix: &str, commit: &str) {
407 Self::download_component(self, DownloadSource::CI, filename, prefix, commit, "ci-rustc")
410 fn download_component(
412 mode: DownloadSource,
418 let cache_dst = self.out.join("cache");
419 let cache_dir = cache_dst.join(key);
420 if !cache_dir.exists() {
421 t!(fs::create_dir_all(&cache_dir));
424 let bin_root = self.out.join(self.build.triple).join(destination);
425 let tarball = cache_dir.join(&filename);
426 let (base_url, url, should_verify) = match mode {
427 DownloadSource::CI => (
428 self.stage0_metadata.config.artifacts_server.clone(),
429 format!("{key}/{filename}"),
432 DownloadSource::Dist => {
433 let dist_server = env::var("RUSTUP_DIST_SERVER")
434 .unwrap_or(self.stage0_metadata.config.dist_server.to_string());
435 // NOTE: make `dist` part of the URL because that's how it's stored in src/stage0.json
436 (dist_server, format!("dist/{key}/{filename}"), true)
440 // For the beta compiler, put special effort into ensuring the checksums are valid.
441 // FIXME: maybe we should do this for download-rustc as well? but it would be a pain to update
442 // this on each and every nightly ...
443 let checksum = if should_verify {
445 "src/stage0.json doesn't contain a checksum for {url}. \
446 Pre-built artifacts might not be available for this \
447 target at this time, see https://doc.rust-lang.org/nightly\
448 /rustc/platform-support.html for more information."
450 let sha256 = self.stage0_metadata.checksums_sha256.get(&url).expect(&error);
451 if tarball.exists() {
452 if self.verify(&tarball, sha256) {
453 self.unpack(&tarball, &bin_root, prefix);
456 self.verbose(&format!(
457 "ignoring cached file {} due to failed verification",
460 self.remove(&tarball);
464 } else if tarball.exists() {
465 self.unpack(&tarball, &bin_root, prefix);
471 self.download_file(&format!("{base_url}/{url}"), &tarball, "");
472 if let Some(sha256) = checksum {
473 if !self.verify(&tarball, sha256) {
474 panic!("failed to verify {}", tarball.display());
478 self.unpack(&tarball, &bin_root, prefix);
481 pub(crate) fn maybe_download_ci_llvm(&self) {
482 if !self.llvm_from_ci {
485 let llvm_root = self.ci_llvm_root();
486 let llvm_stamp = llvm_root.join(".llvm-stamp");
487 let llvm_sha = detect_llvm_sha(&self, self.rust_info.is_managed_git_subrepository());
488 let key = format!("{}{}", llvm_sha, self.llvm_assertions);
489 if program_out_of_date(&llvm_stamp, &key) && !self.dry_run() {
490 self.download_ci_llvm(&llvm_sha);
491 if self.should_fix_bins_and_dylibs() {
492 for entry in t!(fs::read_dir(llvm_root.join("bin"))) {
493 self.fix_bin_or_dylib(&t!(entry).path());
497 // Update the timestamp of llvm-config to force rustc_llvm to be
498 // rebuilt. This is a hacky workaround for a deficiency in Cargo where
499 // the rerun-if-changed directive doesn't handle changes very well.
500 // https://github.com/rust-lang/cargo/issues/10791
501 // Cargo only compares the timestamp of the file relative to the last
502 // time `rustc_llvm` build script ran. However, the timestamps of the
503 // files in the tarball are in the past, so it doesn't trigger a
505 let now = filetime::FileTime::from_system_time(std::time::SystemTime::now());
506 let llvm_config = llvm_root.join("bin").join(exe("llvm-config", self.build));
507 t!(filetime::set_file_times(&llvm_config, now, now));
509 if self.should_fix_bins_and_dylibs() {
510 let llvm_lib = llvm_root.join("lib");
511 for entry in t!(fs::read_dir(&llvm_lib)) {
512 let lib = t!(entry).path();
513 if lib.extension().map_or(false, |ext| ext == "so") {
514 self.fix_bin_or_dylib(&lib);
519 t!(fs::write(llvm_stamp, key));
523 fn download_ci_llvm(&self, llvm_sha: &str) {
524 let llvm_assertions = self.llvm_assertions;
526 let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
527 let cache_dst = self.out.join("cache");
528 let rustc_cache = cache_dst.join(cache_prefix);
529 if !rustc_cache.exists() {
530 t!(fs::create_dir_all(&rustc_cache));
532 let base = if llvm_assertions {
533 &self.stage0_metadata.config.artifacts_with_llvm_assertions_server
535 &self.stage0_metadata.config.artifacts_server
537 let version = self.artifact_version_part(llvm_sha);
538 let filename = format!("rust-dev-{}-{}.tar.xz", version, self.build.triple);
539 let tarball = rustc_cache.join(&filename);
540 if !tarball.exists() {
541 let help_on_error = "error: failed to download llvm from ci
543 help: old builds get deleted after a certain time
544 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
547 download-ci-llvm = false
549 self.download_file(&format!("{base}/{llvm_sha}/{filename}"), &tarball, help_on_error);
551 let llvm_root = self.ci_llvm_root();
552 self.unpack(&tarball, &llvm_root, "rust-dev");