]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/build_system/utils.rs
Merge commit '7d53619064ab7045c383644cb445052d2a3d46db' into sync_cg_clif-2023-02-09
[rust.git] / compiler / rustc_codegen_cranelift / build_system / utils.rs
1 use std::env;
2 use std::fs;
3 use std::io::{self, Write};
4 use std::path::{Path, PathBuf};
5 use std::process::{self, Command, Stdio};
6
7 use super::path::{Dirs, RelPath};
8 use super::rustc_info::{get_cargo_path, get_rustc_path, get_rustdoc_path};
9
10 #[derive(Clone, Debug)]
11 pub(crate) struct Compiler {
12     pub(crate) cargo: PathBuf,
13     pub(crate) rustc: PathBuf,
14     pub(crate) rustdoc: PathBuf,
15     pub(crate) rustflags: String,
16     pub(crate) rustdocflags: String,
17     pub(crate) triple: String,
18     pub(crate) runner: Vec<String>,
19 }
20
21 impl Compiler {
22     pub(crate) fn bootstrap_with_triple(triple: String) -> Compiler {
23         Compiler {
24             cargo: get_cargo_path(),
25             rustc: get_rustc_path(),
26             rustdoc: get_rustdoc_path(),
27             rustflags: String::new(),
28             rustdocflags: String::new(),
29             triple,
30             runner: vec![],
31         }
32     }
33
34     pub(crate) fn set_cross_linker_and_runner(&mut self) {
35         match self.triple.as_str() {
36             "aarch64-unknown-linux-gnu" => {
37                 // We are cross-compiling for aarch64. Use the correct linker and run tests in qemu.
38                 self.rustflags += " -Clinker=aarch64-linux-gnu-gcc";
39                 self.rustdocflags += " -Clinker=aarch64-linux-gnu-gcc";
40                 self.runner = vec![
41                     "qemu-aarch64".to_owned(),
42                     "-L".to_owned(),
43                     "/usr/aarch64-linux-gnu".to_owned(),
44                 ];
45             }
46             "s390x-unknown-linux-gnu" => {
47                 // We are cross-compiling for s390x. Use the correct linker and run tests in qemu.
48                 self.rustflags += " -Clinker=s390x-linux-gnu-gcc";
49                 self.rustdocflags += " -Clinker=s390x-linux-gnu-gcc";
50                 self.runner = vec![
51                     "qemu-s390x".to_owned(),
52                     "-L".to_owned(),
53                     "/usr/s390x-linux-gnu".to_owned(),
54                 ];
55             }
56             "x86_64-pc-windows-gnu" => {
57                 // We are cross-compiling for Windows. Run tests in wine.
58                 self.runner = vec!["wine".to_owned()];
59             }
60             _ => {
61                 println!("Unknown non-native platform");
62             }
63         }
64     }
65 }
66
67 pub(crate) struct CargoProject {
68     source: &'static RelPath,
69     target: &'static str,
70 }
71
72 impl CargoProject {
73     pub(crate) const fn new(path: &'static RelPath, target: &'static str) -> CargoProject {
74         CargoProject { source: path, target }
75     }
76
77     pub(crate) fn source_dir(&self, dirs: &Dirs) -> PathBuf {
78         self.source.to_path(dirs)
79     }
80
81     pub(crate) fn manifest_path(&self, dirs: &Dirs) -> PathBuf {
82         self.source_dir(dirs).join("Cargo.toml")
83     }
84
85     pub(crate) fn target_dir(&self, dirs: &Dirs) -> PathBuf {
86         RelPath::BUILD.join(self.target).to_path(dirs)
87     }
88
89     #[must_use]
90     fn base_cmd(&self, command: &str, cargo: &Path, dirs: &Dirs) -> Command {
91         let mut cmd = Command::new(cargo);
92
93         cmd.arg(command)
94             .arg("--manifest-path")
95             .arg(self.manifest_path(dirs))
96             .arg("--target-dir")
97             .arg(self.target_dir(dirs))
98             .arg("--frozen");
99
100         cmd
101     }
102
103     #[must_use]
104     fn build_cmd(&self, command: &str, compiler: &Compiler, dirs: &Dirs) -> Command {
105         let mut cmd = self.base_cmd(command, &compiler.cargo, dirs);
106
107         cmd.arg("--target").arg(&compiler.triple);
108
109         cmd.env("RUSTC", &compiler.rustc);
110         cmd.env("RUSTDOC", &compiler.rustdoc);
111         cmd.env("RUSTFLAGS", &compiler.rustflags);
112         cmd.env("RUSTDOCFLAGS", &compiler.rustdocflags);
113         if !compiler.runner.is_empty() {
114             cmd.env(
115                 format!("CARGO_TARGET_{}_RUNNER", compiler.triple.to_uppercase().replace('-', "_")),
116                 compiler.runner.join(" "),
117             );
118         }
119
120         cmd
121     }
122
123     #[must_use]
124     pub(crate) fn fetch(
125         &self,
126         cargo: impl AsRef<Path>,
127         rustc: impl AsRef<Path>,
128         dirs: &Dirs,
129     ) -> Command {
130         let mut cmd = Command::new(cargo.as_ref());
131
132         cmd.env("RUSTC", rustc.as_ref())
133             .arg("fetch")
134             .arg("--manifest-path")
135             .arg(self.manifest_path(dirs));
136
137         cmd
138     }
139
140     pub(crate) fn clean(&self, dirs: &Dirs) {
141         let _ = fs::remove_dir_all(self.target_dir(dirs));
142     }
143
144     #[must_use]
145     pub(crate) fn build(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
146         self.build_cmd("build", compiler, dirs)
147     }
148
149     #[must_use]
150     pub(crate) fn test(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
151         self.build_cmd("test", compiler, dirs)
152     }
153
154     #[must_use]
155     pub(crate) fn run(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
156         self.build_cmd("run", compiler, dirs)
157     }
158 }
159
160 #[must_use]
161 pub(crate) fn hyperfine_command(
162     warmup: u64,
163     runs: u64,
164     prepare: Option<&str>,
165     a: &str,
166     b: &str,
167 ) -> Command {
168     let mut bench = Command::new("hyperfine");
169
170     if warmup != 0 {
171         bench.arg("--warmup").arg(warmup.to_string());
172     }
173
174     if runs != 0 {
175         bench.arg("--runs").arg(runs.to_string());
176     }
177
178     if let Some(prepare) = prepare {
179         bench.arg("--prepare").arg(prepare);
180     }
181
182     bench.arg(a).arg(b);
183
184     bench
185 }
186
187 #[must_use]
188 pub(crate) fn git_command<'a>(repo_dir: impl Into<Option<&'a Path>>, cmd: &str) -> Command {
189     let mut git_cmd = Command::new("git");
190     git_cmd
191         .arg("-c")
192         .arg("user.name=Dummy")
193         .arg("-c")
194         .arg("user.email=dummy@example.com")
195         .arg("-c")
196         .arg("core.autocrlf=false")
197         .arg(cmd);
198     if let Some(repo_dir) = repo_dir.into() {
199         git_cmd.current_dir(repo_dir);
200     }
201     git_cmd
202 }
203
204 #[track_caller]
205 pub(crate) fn try_hard_link(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
206     let src = src.as_ref();
207     let dst = dst.as_ref();
208     if let Err(_) = fs::hard_link(src, dst) {
209         fs::copy(src, dst).unwrap(); // Fallback to copying if hardlinking failed
210     }
211 }
212
213 #[track_caller]
214 pub(crate) fn spawn_and_wait(mut cmd: Command) {
215     if !cmd.spawn().unwrap().wait().unwrap().success() {
216         process::exit(1);
217     }
218 }
219
220 // Based on the retry function in rust's src/ci/shared.sh
221 #[track_caller]
222 pub(crate) fn retry_spawn_and_wait(tries: u64, mut cmd: Command) {
223     for i in 1..tries + 1 {
224         if i != 1 {
225             println!("Command failed. Attempt {i}/{tries}:");
226         }
227         if cmd.spawn().unwrap().wait().unwrap().success() {
228             return;
229         }
230         std::thread::sleep(std::time::Duration::from_secs(i * 5));
231     }
232     println!("The command has failed after {tries} attempts.");
233     process::exit(1);
234 }
235
236 #[track_caller]
237 pub(crate) fn spawn_and_wait_with_input(mut cmd: Command, input: String) -> String {
238     let mut child = cmd
239         .stdin(Stdio::piped())
240         .stdout(Stdio::piped())
241         .spawn()
242         .expect("Failed to spawn child process");
243
244     let mut stdin = child.stdin.take().expect("Failed to open stdin");
245     std::thread::spawn(move || {
246         stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
247     });
248
249     let output = child.wait_with_output().expect("Failed to read stdout");
250     if !output.status.success() {
251         process::exit(1);
252     }
253
254     String::from_utf8(output.stdout).unwrap()
255 }
256
257 pub(crate) fn remove_dir_if_exists(path: &Path) {
258     match fs::remove_dir_all(&path) {
259         Ok(()) => {}
260         Err(err) if err.kind() == io::ErrorKind::NotFound => {}
261         Err(err) => panic!("Failed to remove {path}: {err}", path = path.display()),
262     }
263 }
264
265 pub(crate) fn copy_dir_recursively(from: &Path, to: &Path) {
266     for entry in fs::read_dir(from).unwrap() {
267         let entry = entry.unwrap();
268         let filename = entry.file_name();
269         if filename == "." || filename == ".." {
270             continue;
271         }
272         if entry.metadata().unwrap().is_dir() {
273             fs::create_dir(to.join(&filename)).unwrap();
274             copy_dir_recursively(&from.join(&filename), &to.join(&filename));
275         } else {
276             fs::copy(from.join(&filename), to.join(&filename)).unwrap();
277         }
278     }
279 }
280
281 pub(crate) fn is_ci() -> bool {
282     env::var("CI").is_ok()
283 }
284
285 pub(crate) fn is_ci_opt() -> bool {
286     env::var("CI_OPT").is_ok()
287 }