]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/download.rs
Rollup merge of #107740 - oli-obk:lock_tcx, r=petrochenkov
[rust.git] / src / bootstrap / download.rs
1 use std::{
2     env,
3     ffi::{OsStr, OsString},
4     fs::{self, File},
5     io::{BufRead, BufReader, ErrorKind},
6     path::{Path, PathBuf},
7     process::{Command, Stdio},
8 };
9
10 use once_cell::sync::OnceCell;
11 use xz2::bufread::XzDecoder;
12
13 use crate::{
14     config::RustfmtMetadata,
15     native::detect_llvm_sha,
16     t,
17     util::{check_run, exe, program_out_of_date, try_run},
18     Config,
19 };
20
21 static SHOULD_FIX_BINS_AND_DYLIBS: OnceCell<bool> = OnceCell::new();
22
23 /// Generic helpers that are useful anywhere in bootstrap.
24 impl Config {
25     pub fn is_verbose(&self) -> bool {
26         self.verbose > 0
27     }
28
29     pub(crate) fn create(&self, path: &Path, s: &str) {
30         if self.dry_run() {
31             return;
32         }
33         t!(fs::write(path, s));
34     }
35
36     pub(crate) fn remove(&self, f: &Path) {
37         if self.dry_run() {
38             return;
39         }
40         fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {:?}", f));
41     }
42
43     /// Create a temporary directory in `out` and return its path.
44     ///
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));
50         tmp
51     }
52
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 {
57         if self.dry_run() {
58             return true;
59         }
60         self.verbose(&format!("running: {:?}", cmd));
61         try_run(cmd, self.is_verbose())
62     }
63
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 {
68         if self.dry_run() {
69             return true;
70         }
71         self.verbose(&format!("running: {:?}", cmd));
72         check_run(cmd, self.is_verbose())
73     }
74
75     /// Whether or not `fix_bin_or_dylib` needs to be run; can only be true
76     /// on NixOS
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,
82                 Ok(output) => {
83                     let mut os_name = output.stdout;
84                     if os_name.last() == Some(&b'\n') {
85                         os_name.pop();
86                     }
87                     if os_name != b"Linux" {
88                         return false;
89                     }
90                 }
91             }
92
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 {
99                 return true;
100             }
101
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\"")
110                 }),
111             };
112             is_nixos && !Path::new("/lib").exists()
113         });
114         if val {
115             println!("info: You seem to be using Nix.");
116         }
117         val
118     }
119
120     /// Modifies the interpreter section of 'fname' to fix the dynamic linker,
121     /// or the RPATH section, to fix the dynamic library search path
122     ///
123     /// This is only required on NixOS and uses the PatchELF utility to
124     /// change the interpreter/RPATH of ELF executables.
125     ///
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());
130
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).
137             //
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.
142             //
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> {});
149             symlinkJoin {
150                 name = \"rust-stage0-dependencies\";
151                 paths = [
152                     zlib
153                     patchelf
154                     stdenv.cc.bintools
155                 ];
156             }
157             ";
158             nix_build_succeeded = self.try_run(Command::new("nix-build").args(&[
159                 Path::new("-E"),
160                 Path::new(NIX_EXPR),
161                 Path::new("-o"),
162                 &nix_deps_dir,
163             ]));
164             nix_deps_dir
165         });
166         if !nix_build_succeeded {
167             return;
168         }
169
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");
178             entries
179         };
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()]);
187         }
188
189         self.try_run(patchelf.arg(fname));
190     }
191
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)
202             }
203             Some(other) => panic!("unsupported protocol {other} in {url}"),
204             None => panic!("no protocol in {url}"),
205         }
206         t!(std::fs::rename(&tempfile, dest_path));
207     }
208
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");
213         curl.args(&[
214             "-#",
215             "-y",
216             "30",
217             "-Y",
218             "10", // timeout if speed is < 10 bytes/sec for > 30 seconds
219             "--connect-timeout",
220             "30", // timeout if cannot connect within 30 seconds
221             "--retry",
222             "3",
223             "-Sf",
224             "-o",
225         ]);
226         curl.arg(tempfile);
227         curl.arg(url);
228         if !self.check_run(&mut curl) {
229             if self.build.contains("windows-msvc") {
230                 println!("Fallback to PowerShell");
231                 for _ in 0..3 {
232                     if self.try_run(Command::new("PowerShell.exe").args(&[
233                         "/nologo",
234                         "-Command",
235                         "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
236                         &format!(
237                             "(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
238                             url, tempfile.to_str().expect("invalid UTF-8 not supported with powershell downloads"),
239                         ),
240                     ])) {
241                         return;
242                     }
243                     println!("\nspurious failure, trying again");
244                 }
245             }
246             if !help_on_error.is_empty() {
247                 eprintln!("{}", help_on_error);
248             }
249             crate::detail_exit(1);
250         }
251     }
252
253     fn unpack(&self, tarball: &Path, dst: &Path, pattern: &str) {
254         println!("extracting {} to {}", tarball.display(), dst.display());
255         if !dst.exists() {
256             t!(fs::create_dir_all(dst));
257         }
258
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());
264
265         // decompress the file
266         let data = t!(File::open(tarball));
267         let decompressor = XzDecoder::new(BufReader::new(data));
268
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 {
275                 continue;
276             }
277             let mut short_path = t!(original_path.strip_prefix(directory_prefix));
278             if !short_path.starts_with(pattern) {
279                 continue;
280             }
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 ??");
286             }
287             let src_path = dst.join(original_path);
288             if src_path.is_dir() && dst_path.exists() {
289                 continue;
290             }
291             t!(fs::rename(src_path, dst_path));
292         }
293         t!(fs::remove_dir_all(dst.join(directory_prefix)));
294     }
295
296     /// Returns whether the SHA256 checksum of `path` matches `expected`.
297     fn verify(&self, path: &Path, expected: &str) -> bool {
298         use sha2::Digest;
299
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() {
309             println!(
310                 "invalid checksum: \n\
311                 found:    {found}\n\
312                 expected: {expected}",
313             );
314         }
315         return verified;
316     }
317 }
318
319 enum DownloadSource {
320     CI,
321     Dist,
322 }
323
324 /// Functions that are only ever called once, but named for clarify and to avoid thousand-line functions.
325 impl Config {
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}");
329
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);
336         }
337
338         self.download_component(
339             DownloadSource::Dist,
340             format!("rustfmt-{version}-{build}.tar.xz", build = host.triple),
341             "rustfmt-preview",
342             &date,
343             "rustfmt",
344         );
345         self.download_component(
346             DownloadSource::Dist,
347             format!("rustc-{version}-{build}.tar.xz", build = host.triple),
348             "rustc",
349             &date,
350             "rustfmt",
351         );
352
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"));
356         }
357
358         self.create(&rustfmt_stamp, &channel);
359         Some(rustfmt_path)
360     }
361
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");
368
369         if !bin_root.join("bin").join("rustc").exists() || program_out_of_date(&rustc_stamp, commit)
370         {
371             if bin_root.exists() {
372                 t!(fs::remove_dir_all(&bin_root));
373             }
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);
384
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"),
390                 );
391                 let lib_dir = bin_root.join("lib");
392                 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
393                     let lib = t!(lib);
394                     if lib.path().extension() == Some(OsStr::new("so")) {
395                         self.fix_bin_or_dylib(&lib.path());
396                     }
397                 }
398             }
399
400             t!(fs::write(rustc_stamp, commit));
401         }
402     }
403
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")
408     }
409
410     fn download_component(
411         &self,
412         mode: DownloadSource,
413         filename: String,
414         prefix: &str,
415         key: &str,
416         destination: &str,
417     ) {
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));
422         }
423
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}"),
430                 false,
431             ),
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)
437             }
438         };
439
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 {
444             let error = format!(
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."
449             );
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);
454                     return;
455                 } else {
456                     self.verbose(&format!(
457                         "ignoring cached file {} due to failed verification",
458                         tarball.display()
459                     ));
460                     self.remove(&tarball);
461                 }
462             }
463             Some(sha256)
464         } else if tarball.exists() {
465             self.unpack(&tarball, &bin_root, prefix);
466             return;
467         } else {
468             None
469         };
470
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());
475             }
476         }
477
478         self.unpack(&tarball, &bin_root, prefix);
479     }
480
481     pub(crate) fn maybe_download_ci_llvm(&self) {
482         if !self.llvm_from_ci {
483             return;
484         }
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());
494                 }
495             }
496
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
504             // rebuild.
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));
508
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);
515                     }
516                 }
517             }
518
519             t!(fs::write(llvm_stamp, key));
520         }
521     }
522
523     fn download_ci_llvm(&self, llvm_sha: &str) {
524         let llvm_assertions = self.llvm_assertions;
525
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));
531         }
532         let base = if llvm_assertions {
533             &self.stage0_metadata.config.artifacts_with_llvm_assertions_server
534         } else {
535             &self.stage0_metadata.config.artifacts_server
536         };
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
542
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:
545
546     [llvm]
547     download-ci-llvm = false
548     ";
549             self.download_file(&format!("{base}/{llvm_sha}/{filename}"), &tarball, help_on_error);
550         }
551         let llvm_root = self.ci_llvm_root();
552         self.unpack(&tarball, &llvm_root, "rust-dev");
553     }
554 }