]> git.lizzy.rs Git - rust.git/blob - src/build_helper/lib.rs
Rollup merge of #65112 - jack-t:type-parens-lint, r=varkor
[rust.git] / src / build_helper / lib.rs
1 use std::fs::File;
2 use std::path::{Path, PathBuf};
3 use std::process::{Command, Stdio};
4 use std::time::{SystemTime, UNIX_EPOCH};
5 use std::{env, fs};
6 use std::thread;
7
8 /// A helper macro to `unwrap` a result except also print out details like:
9 ///
10 /// * The file/line of the panic
11 /// * The expression that failed
12 /// * The error itself
13 ///
14 /// This is currently used judiciously throughout the build system rather than
15 /// using a `Result` with `try!`, but this may change one day...
16 #[macro_export]
17 macro_rules! t {
18     ($e:expr) => {
19         match $e {
20             Ok(e) => e,
21             Err(e) => panic!("{} failed with {}", stringify!($e), e),
22         }
23     };
24     // it can show extra info in the second parameter
25     ($e:expr, $extra:expr) => {
26         match $e {
27             Ok(e) => e,
28             Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
29         }
30     };
31 }
32
33 // Because Cargo adds the compiler's dylib path to our library search path, llvm-config may
34 // break: the dylib path for the compiler, as of this writing, contains a copy of the LLVM
35 // shared library, which means that when our freshly built llvm-config goes to load it's
36 // associated LLVM, it actually loads the compiler's LLVM. In particular when building the first
37 // compiler (i.e., in stage 0) that's a problem, as the compiler's LLVM is likely different from
38 // the one we want to use. As such, we restore the environment to what bootstrap saw. This isn't
39 // perfect -- we might actually want to see something from Cargo's added library paths -- but
40 // for now it works.
41 pub fn restore_library_path() {
42     println!("cargo:rerun-if-env-changed=REAL_LIBRARY_PATH_VAR");
43     println!("cargo:rerun-if-env-changed=REAL_LIBRARY_PATH");
44     let key = env::var_os("REAL_LIBRARY_PATH_VAR").expect("REAL_LIBRARY_PATH_VAR");
45     if let Some(env) = env::var_os("REAL_LIBRARY_PATH") {
46         env::set_var(&key, &env);
47     } else {
48         env::remove_var(&key);
49     }
50 }
51
52 /// Run the command, printing what we are running.
53 pub fn run_verbose(cmd: &mut Command) {
54     println!("running: {:?}", cmd);
55     run(cmd);
56 }
57
58 pub fn run(cmd: &mut Command) {
59     if !try_run(cmd) {
60         std::process::exit(1);
61     }
62 }
63
64 pub fn try_run(cmd: &mut Command) -> bool {
65     let status = match cmd.status() {
66         Ok(status) => status,
67         Err(e) => fail(&format!(
68             "failed to execute command: {:?}\nerror: {}",
69             cmd, e
70         )),
71     };
72     if !status.success() {
73         println!(
74             "\n\ncommand did not execute successfully: {:?}\n\
75              expected success, got: {}\n\n",
76             cmd, status
77         );
78     }
79     status.success()
80 }
81
82 pub fn run_suppressed(cmd: &mut Command) {
83     if !try_run_suppressed(cmd) {
84         std::process::exit(1);
85     }
86 }
87
88 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
89     let output = match cmd.output() {
90         Ok(status) => status,
91         Err(e) => fail(&format!(
92             "failed to execute command: {:?}\nerror: {}",
93             cmd, e
94         )),
95     };
96     if !output.status.success() {
97         println!(
98             "\n\ncommand did not execute successfully: {:?}\n\
99              expected success, got: {}\n\n\
100              stdout ----\n{}\n\
101              stderr ----\n{}\n\n",
102             cmd,
103             output.status,
104             String::from_utf8_lossy(&output.stdout),
105             String::from_utf8_lossy(&output.stderr)
106         );
107     }
108     output.status.success()
109 }
110
111 pub fn gnu_target(target: &str) -> &str {
112     match target {
113         "i686-pc-windows-msvc" => "i686-pc-win32",
114         "x86_64-pc-windows-msvc" => "x86_64-pc-win32",
115         "i686-pc-windows-gnu" => "i686-w64-mingw32",
116         "x86_64-pc-windows-gnu" => "x86_64-w64-mingw32",
117         s => s,
118     }
119 }
120
121 pub fn make(host: &str) -> PathBuf {
122     if host.contains("dragonfly") || host.contains("freebsd")
123         || host.contains("netbsd") || host.contains("openbsd")
124     {
125         PathBuf::from("gmake")
126     } else {
127         PathBuf::from("make")
128     }
129 }
130
131 pub fn output(cmd: &mut Command) -> String {
132     let output = match cmd.stderr(Stdio::inherit()).output() {
133         Ok(status) => status,
134         Err(e) => fail(&format!(
135             "failed to execute command: {:?}\nerror: {}",
136             cmd, e
137         )),
138     };
139     if !output.status.success() {
140         panic!(
141             "command did not execute successfully: {:?}\n\
142              expected success, got: {}",
143             cmd, output.status
144         );
145     }
146     String::from_utf8(output.stdout).unwrap()
147 }
148
149 pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
150     let mut stack = dir.read_dir()
151         .unwrap()
152         .map(|e| e.unwrap())
153         .filter(|e| &*e.file_name() != ".git")
154         .collect::<Vec<_>>();
155     while let Some(entry) = stack.pop() {
156         let path = entry.path();
157         if entry.file_type().unwrap().is_dir() {
158             stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
159         } else {
160             println!("cargo:rerun-if-changed={}", path.display());
161         }
162     }
163 }
164
165 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
166 pub fn mtime(path: &Path) -> SystemTime {
167     fs::metadata(path)
168         .and_then(|f| f.modified())
169         .unwrap_or(UNIX_EPOCH)
170 }
171
172 /// Returns `true` if `dst` is up to date given that the file or files in `src`
173 /// are used to generate it.
174 ///
175 /// Uses last-modified time checks to verify this.
176 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
177     if !dst.exists() {
178         return false;
179     }
180     let threshold = mtime(dst);
181     let meta = match fs::metadata(src) {
182         Ok(meta) => meta,
183         Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
184     };
185     if meta.is_dir() {
186         dir_up_to_date(src, threshold)
187     } else {
188         meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
189     }
190 }
191
192 #[must_use]
193 pub struct NativeLibBoilerplate {
194     pub src_dir: PathBuf,
195     pub out_dir: PathBuf,
196 }
197
198 impl NativeLibBoilerplate {
199     /// On macOS we don't want to ship the exact filename that compiler-rt builds.
200     /// This conflicts with the system and ours is likely a wildly different
201     /// version, so they can't be substituted.
202     ///
203     /// As a result, we rename it here but we need to also use
204     /// `install_name_tool` on macOS to rename the commands listed inside of it to
205     /// ensure it's linked against correctly.
206     pub fn fixup_sanitizer_lib_name(&self, sanitizer_name: &str) {
207         if env::var("TARGET").unwrap() != "x86_64-apple-darwin" {
208             return
209         }
210
211         let dir = self.out_dir.join("build/lib/darwin");
212         let name = format!("clang_rt.{}_osx_dynamic", sanitizer_name);
213         let src = dir.join(&format!("lib{}.dylib", name));
214         let new_name = format!("lib__rustc__{}.dylib", name);
215         let dst = dir.join(&new_name);
216
217         println!("{} => {}", src.display(), dst.display());
218         fs::rename(&src, &dst).unwrap();
219         let status = Command::new("install_name_tool")
220             .arg("-id")
221             .arg(format!("@rpath/{}", new_name))
222             .arg(&dst)
223             .status()
224             .expect("failed to execute `install_name_tool`");
225         assert!(status.success());
226     }
227 }
228
229 impl Drop for NativeLibBoilerplate {
230     fn drop(&mut self) {
231         if !thread::panicking() {
232             t!(File::create(self.out_dir.join("rustbuild.timestamp")));
233         }
234     }
235 }
236
237 // Perform standard preparations for native libraries that are build only once for all stages.
238 // Emit rerun-if-changed and linking attributes for Cargo, check if any source files are
239 // updated, calculate paths used later in actual build with CMake/make or C/C++ compiler.
240 // If Err is returned, then everything is up-to-date and further build actions can be skipped.
241 // Timestamps are created automatically when the result of `native_lib_boilerplate` goes out
242 // of scope, so all the build actions should be completed until then.
243 pub fn native_lib_boilerplate(
244     src_dir: &Path,
245     out_name: &str,
246     link_name: &str,
247     search_subdir: &str,
248 ) -> Result<NativeLibBoilerplate, ()> {
249     rerun_if_changed_anything_in_dir(src_dir);
250
251     let out_dir = env::var_os("RUSTBUILD_NATIVE_DIR").unwrap_or_else(||
252         env::var_os("OUT_DIR").unwrap());
253     let out_dir = PathBuf::from(out_dir).join(out_name);
254     t!(fs::create_dir_all(&out_dir));
255     if link_name.contains('=') {
256         println!("cargo:rustc-link-lib={}", link_name);
257     } else {
258         println!("cargo:rustc-link-lib=static={}", link_name);
259     }
260     println!(
261         "cargo:rustc-link-search=native={}",
262         out_dir.join(search_subdir).display()
263     );
264
265     let timestamp = out_dir.join("rustbuild.timestamp");
266     if !up_to_date(Path::new("build.rs"), &timestamp) || !up_to_date(src_dir, &timestamp) {
267         Ok(NativeLibBoilerplate {
268             src_dir: src_dir.to_path_buf(),
269             out_dir,
270         })
271     } else {
272         Err(())
273     }
274 }
275
276 pub fn sanitizer_lib_boilerplate(sanitizer_name: &str)
277     -> Result<(NativeLibBoilerplate, String), ()>
278 {
279     let (link_name, search_path, apple) = match &*env::var("TARGET").unwrap() {
280         "x86_64-unknown-linux-gnu" => (
281             format!("clang_rt.{}-x86_64", sanitizer_name),
282             "build/lib/linux",
283             false,
284         ),
285         "x86_64-apple-darwin" => (
286             format!("clang_rt.{}_osx_dynamic", sanitizer_name),
287             "build/lib/darwin",
288             true,
289         ),
290         _ => return Err(()),
291     };
292     let to_link = if apple {
293         format!("dylib=__rustc__{}", link_name)
294     } else {
295         format!("static={}", link_name)
296     };
297     // This env var is provided by rustbuild to tell us where `compiler-rt`
298     // lives.
299     let dir = env::var_os("RUST_COMPILER_RT_ROOT").unwrap();
300     let lib = native_lib_boilerplate(
301         dir.as_ref(),
302         sanitizer_name,
303         &to_link,
304         search_path,
305     )?;
306     Ok((lib, link_name))
307 }
308
309 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
310     t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
311         let meta = t!(e.metadata());
312         if meta.is_dir() {
313             dir_up_to_date(&e.path(), threshold)
314         } else {
315             meta.modified().unwrap_or(UNIX_EPOCH) < threshold
316         }
317     })
318 }
319
320 fn fail(s: &str) -> ! {
321     println!("\n\n{}\n\n", s);
322     std::process::exit(1);
323 }