]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/build_system/utils.rs
Auto merge of #106938 - GuillaumeGomez:normalize-projection-field-ty, r=oli-obk
[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(&self, cargo: impl AsRef<Path>, dirs: &Dirs) -> Command {
125         let mut cmd = Command::new(cargo.as_ref());
126
127         cmd.arg("fetch").arg("--manifest-path").arg(self.manifest_path(dirs));
128
129         cmd
130     }
131
132     pub(crate) fn clean(&self, dirs: &Dirs) {
133         let _ = fs::remove_dir_all(self.target_dir(dirs));
134     }
135
136     #[must_use]
137     pub(crate) fn build(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
138         self.build_cmd("build", compiler, dirs)
139     }
140
141     #[must_use]
142     pub(crate) fn test(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
143         self.build_cmd("test", compiler, dirs)
144     }
145
146     #[must_use]
147     pub(crate) fn run(&self, compiler: &Compiler, dirs: &Dirs) -> Command {
148         self.build_cmd("run", compiler, dirs)
149     }
150 }
151
152 #[must_use]
153 pub(crate) fn hyperfine_command(
154     warmup: u64,
155     runs: u64,
156     prepare: Option<&str>,
157     a: &str,
158     b: &str,
159 ) -> Command {
160     let mut bench = Command::new("hyperfine");
161
162     if warmup != 0 {
163         bench.arg("--warmup").arg(warmup.to_string());
164     }
165
166     if runs != 0 {
167         bench.arg("--runs").arg(runs.to_string());
168     }
169
170     if let Some(prepare) = prepare {
171         bench.arg("--prepare").arg(prepare);
172     }
173
174     bench.arg(a).arg(b);
175
176     bench
177 }
178
179 #[must_use]
180 pub(crate) fn git_command<'a>(repo_dir: impl Into<Option<&'a Path>>, cmd: &str) -> Command {
181     let mut git_cmd = Command::new("git");
182     git_cmd
183         .arg("-c")
184         .arg("user.name=Dummy")
185         .arg("-c")
186         .arg("user.email=dummy@example.com")
187         .arg("-c")
188         .arg("core.autocrlf=false")
189         .arg(cmd);
190     if let Some(repo_dir) = repo_dir.into() {
191         git_cmd.current_dir(repo_dir);
192     }
193     git_cmd
194 }
195
196 #[track_caller]
197 pub(crate) fn try_hard_link(src: impl AsRef<Path>, dst: impl AsRef<Path>) {
198     let src = src.as_ref();
199     let dst = dst.as_ref();
200     if let Err(_) = fs::hard_link(src, dst) {
201         fs::copy(src, dst).unwrap(); // Fallback to copying if hardlinking failed
202     }
203 }
204
205 #[track_caller]
206 pub(crate) fn spawn_and_wait(mut cmd: Command) {
207     if !cmd.spawn().unwrap().wait().unwrap().success() {
208         process::exit(1);
209     }
210 }
211
212 // Based on the retry function in rust's src/ci/shared.sh
213 #[track_caller]
214 pub(crate) fn retry_spawn_and_wait(tries: u64, mut cmd: Command) {
215     for i in 1..tries + 1 {
216         if i != 1 {
217             println!("Command failed. Attempt {i}/{tries}:");
218         }
219         if cmd.spawn().unwrap().wait().unwrap().success() {
220             return;
221         }
222         std::thread::sleep(std::time::Duration::from_secs(i * 5));
223     }
224     println!("The command has failed after {tries} attempts.");
225     process::exit(1);
226 }
227
228 #[track_caller]
229 pub(crate) fn spawn_and_wait_with_input(mut cmd: Command, input: String) -> String {
230     let mut child = cmd
231         .stdin(Stdio::piped())
232         .stdout(Stdio::piped())
233         .spawn()
234         .expect("Failed to spawn child process");
235
236     let mut stdin = child.stdin.take().expect("Failed to open stdin");
237     std::thread::spawn(move || {
238         stdin.write_all(input.as_bytes()).expect("Failed to write to stdin");
239     });
240
241     let output = child.wait_with_output().expect("Failed to read stdout");
242     if !output.status.success() {
243         process::exit(1);
244     }
245
246     String::from_utf8(output.stdout).unwrap()
247 }
248
249 pub(crate) fn remove_dir_if_exists(path: &Path) {
250     match fs::remove_dir_all(&path) {
251         Ok(()) => {}
252         Err(err) if err.kind() == io::ErrorKind::NotFound => {}
253         Err(err) => panic!("Failed to remove {path}: {err}", path = path.display()),
254     }
255 }
256
257 pub(crate) fn copy_dir_recursively(from: &Path, to: &Path) {
258     for entry in fs::read_dir(from).unwrap() {
259         let entry = entry.unwrap();
260         let filename = entry.file_name();
261         if filename == "." || filename == ".." {
262             continue;
263         }
264         if entry.metadata().unwrap().is_dir() {
265             fs::create_dir(to.join(&filename)).unwrap();
266             copy_dir_recursively(&from.join(&filename), &to.join(&filename));
267         } else {
268             fs::copy(from.join(&filename), to.join(&filename)).unwrap();
269         }
270     }
271 }
272
273 pub(crate) fn is_ci() -> bool {
274     env::var("CI").as_deref() == Ok("true")
275 }