1 #![deny(rust_2018_idioms)]
4 use std::path::{Path, PathBuf};
5 use std::process::{Command, Stdio};
6 use std::time::{SystemTime, UNIX_EPOCH};
10 /// A helper macro to `unwrap` a result except also print out details like:
12 /// * The file/line of the panic
13 /// * The expression that failed
14 /// * The error itself
16 /// This is currently used judiciously throughout the build system rather than
17 /// using a `Result` with `try!`, but this may change one day...
23 Err(e) => panic!("{} failed with {}", stringify!($e), e),
28 // Because Cargo adds the compiler's dylib path to our library search path, llvm-config may
29 // break: the dylib path for the compiler, as of this writing, contains a copy of the LLVM
30 // shared library, which means that when our freshly built llvm-config goes to load it's
31 // associated LLVM, it actually loads the compiler's LLVM. In particular when building the first
32 // compiler (i.e., in stage 0) that's a problem, as the compiler's LLVM is likely different from
33 // the one we want to use. As such, we restore the environment to what bootstrap saw. This isn't
34 // perfect -- we might actually want to see something from Cargo's added library paths -- but
36 pub fn restore_library_path() {
37 println!("cargo:rerun-if-env-changed=REAL_LIBRARY_PATH_VAR");
38 println!("cargo:rerun-if-env-changed=REAL_LIBRARY_PATH");
39 let key = env::var_os("REAL_LIBRARY_PATH_VAR").expect("REAL_LIBRARY_PATH_VAR");
40 if let Some(env) = env::var_os("REAL_LIBRARY_PATH") {
41 env::set_var(&key, &env);
43 env::remove_var(&key);
47 pub fn run(cmd: &mut Command) {
48 println!("running: {:?}", cmd);
52 pub fn run_silent(cmd: &mut Command) {
53 if !try_run_silent(cmd) {
54 std::process::exit(1);
58 pub fn try_run_silent(cmd: &mut Command) -> bool {
59 let status = match cmd.status() {
61 Err(e) => fail(&format!(
62 "failed to execute command: {:?}\nerror: {}",
66 if !status.success() {
68 "\n\ncommand did not execute successfully: {:?}\n\
69 expected success, got: {}\n\n",
76 pub fn run_suppressed(cmd: &mut Command) {
77 if !try_run_suppressed(cmd) {
78 std::process::exit(1);
82 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
83 let output = match cmd.output() {
85 Err(e) => fail(&format!(
86 "failed to execute command: {:?}\nerror: {}",
90 if !output.status.success() {
92 "\n\ncommand did not execute successfully: {:?}\n\
93 expected success, got: {}\n\n\
98 String::from_utf8_lossy(&output.stdout),
99 String::from_utf8_lossy(&output.stderr)
102 output.status.success()
105 pub fn gnu_target(target: &str) -> &str {
107 "i686-pc-windows-msvc" => "i686-pc-win32",
108 "x86_64-pc-windows-msvc" => "x86_64-pc-win32",
109 "i686-pc-windows-gnu" => "i686-w64-mingw32",
110 "x86_64-pc-windows-gnu" => "x86_64-w64-mingw32",
115 pub fn make(host: &str) -> PathBuf {
116 if host.contains("dragonfly") || host.contains("freebsd")
117 || host.contains("netbsd") || host.contains("openbsd")
119 PathBuf::from("gmake")
121 PathBuf::from("make")
125 pub fn output(cmd: &mut Command) -> String {
126 let output = match cmd.stderr(Stdio::inherit()).output() {
127 Ok(status) => status,
128 Err(e) => fail(&format!(
129 "failed to execute command: {:?}\nerror: {}",
133 if !output.status.success() {
135 "command did not execute successfully: {:?}\n\
136 expected success, got: {}",
140 String::from_utf8(output.stdout).unwrap()
143 pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
144 let mut stack = dir.read_dir()
147 .filter(|e| &*e.file_name() != ".git")
148 .collect::<Vec<_>>();
149 while let Some(entry) = stack.pop() {
150 let path = entry.path();
151 if entry.file_type().unwrap().is_dir() {
152 stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
154 println!("cargo:rerun-if-changed={}", path.display());
159 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
160 pub fn mtime(path: &Path) -> SystemTime {
162 .and_then(|f| f.modified())
163 .unwrap_or(UNIX_EPOCH)
166 /// Returns `true` if `dst` is up to date given that the file or files in `src`
167 /// are used to generate it.
169 /// Uses last-modified time checks to verify this.
170 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
174 let threshold = mtime(dst);
175 let meta = match fs::metadata(src) {
177 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
180 dir_up_to_date(src, threshold)
182 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
187 pub struct NativeLibBoilerplate {
188 pub src_dir: PathBuf,
189 pub out_dir: PathBuf,
192 impl NativeLibBoilerplate {
193 /// On macOS we don't want to ship the exact filename that compiler-rt builds.
194 /// This conflicts with the system and ours is likely a wildly different
195 /// version, so they can't be substituted.
197 /// As a result, we rename it here but we need to also use
198 /// `install_name_tool` on macOS to rename the commands listed inside of it to
199 /// ensure it's linked against correctly.
200 pub fn fixup_sanitizer_lib_name(&self, sanitizer_name: &str) {
201 if env::var("TARGET").unwrap() != "x86_64-apple-darwin" {
205 let dir = self.out_dir.join("build/lib/darwin");
206 let name = format!("clang_rt.{}_osx_dynamic", sanitizer_name);
207 let src = dir.join(&format!("lib{}.dylib", name));
208 let new_name = format!("lib__rustc__{}.dylib", name);
209 let dst = dir.join(&new_name);
211 println!("{} => {}", src.display(), dst.display());
212 fs::rename(&src, &dst).unwrap();
213 let status = Command::new("install_name_tool")
215 .arg(format!("@rpath/{}", new_name))
218 .expect("failed to execute `install_name_tool`");
219 assert!(status.success());
223 impl Drop for NativeLibBoilerplate {
225 if !thread::panicking() {
226 t!(File::create(self.out_dir.join("rustbuild.timestamp")));
231 // Perform standard preparations for native libraries that are build only once for all stages.
232 // Emit rerun-if-changed and linking attributes for Cargo, check if any source files are
233 // updated, calculate paths used later in actual build with CMake/make or C/C++ compiler.
234 // If Err is returned, then everything is up-to-date and further build actions can be skipped.
235 // Timestamps are created automatically when the result of `native_lib_boilerplate` goes out
236 // of scope, so all the build actions should be completed until then.
237 pub fn native_lib_boilerplate(
242 ) -> Result<NativeLibBoilerplate, ()> {
243 rerun_if_changed_anything_in_dir(src_dir);
245 let out_dir = env::var_os("RUSTBUILD_NATIVE_DIR").unwrap_or_else(||
246 env::var_os("OUT_DIR").unwrap());
247 let out_dir = PathBuf::from(out_dir).join(out_name);
248 t!(fs::create_dir_all(&out_dir));
249 if link_name.contains('=') {
250 println!("cargo:rustc-link-lib={}", link_name);
252 println!("cargo:rustc-link-lib=static={}", link_name);
255 "cargo:rustc-link-search=native={}",
256 out_dir.join(search_subdir).display()
259 let timestamp = out_dir.join("rustbuild.timestamp");
260 if !up_to_date(Path::new("build.rs"), ×tamp) || !up_to_date(src_dir, ×tamp) {
261 Ok(NativeLibBoilerplate {
262 src_dir: src_dir.to_path_buf(),
270 pub fn sanitizer_lib_boilerplate(sanitizer_name: &str)
271 -> Result<(NativeLibBoilerplate, String), ()>
273 let (link_name, search_path, apple) = match &*env::var("TARGET").unwrap() {
274 "x86_64-unknown-linux-gnu" => (
275 format!("clang_rt.{}-x86_64", sanitizer_name),
279 "x86_64-apple-darwin" => (
280 format!("clang_rt.{}_osx_dynamic", sanitizer_name),
286 let to_link = if apple {
287 format!("dylib=__rustc__{}", link_name)
289 format!("static={}", link_name)
291 // This env var is provided by rustbuild to tell us where `compiler-rt`
293 let dir = env::var_os("RUST_COMPILER_RT_ROOT").unwrap();
294 let lib = native_lib_boilerplate(
303 fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
304 t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
305 let meta = t!(e.metadata());
307 dir_up_to_date(&e.path(), threshold)
309 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
314 fn fail(s: &str) -> ! {
315 println!("\n\n{}\n\n", s);
316 std::process::exit(1);