2 use std::path::{Path, PathBuf};
3 use std::process::{Command, Stdio};
4 use std::time::{SystemTime, UNIX_EPOCH};
8 /// A helper macro to `unwrap` a result except also print out details like:
10 /// * The file/line of the panic
11 /// * The expression that failed
12 /// * The error itself
14 /// This is currently used judiciously throughout the build system rather than
15 /// using a `Result` with `try!`, but this may change one day...
21 Err(e) => panic!("{} failed with {}", stringify!($e), e),
24 // it can show extra info in the second parameter
25 ($e:expr, $extra:expr) => {
28 Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
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
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);
48 env::remove_var(&key);
52 /// Run the command, printing what we are running.
53 pub fn run_verbose(cmd: &mut Command) {
54 println!("running: {:?}", cmd);
58 pub fn run(cmd: &mut Command) {
60 std::process::exit(1);
64 pub fn try_run(cmd: &mut Command) -> bool {
65 let status = match cmd.status() {
67 Err(e) => fail(&format!(
68 "failed to execute command: {:?}\nerror: {}",
72 if !status.success() {
74 "\n\ncommand did not execute successfully: {:?}\n\
75 expected success, got: {}\n\n",
82 pub fn run_suppressed(cmd: &mut Command) {
83 if !try_run_suppressed(cmd) {
84 std::process::exit(1);
88 pub fn try_run_suppressed(cmd: &mut Command) -> bool {
89 let output = match cmd.output() {
91 Err(e) => fail(&format!(
92 "failed to execute command: {:?}\nerror: {}",
96 if !output.status.success() {
98 "\n\ncommand did not execute successfully: {:?}\n\
99 expected success, got: {}\n\n\
101 stderr ----\n{}\n\n",
104 String::from_utf8_lossy(&output.stdout),
105 String::from_utf8_lossy(&output.stderr)
108 output.status.success()
111 pub fn gnu_target(target: &str) -> &str {
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",
121 pub fn make(host: &str) -> PathBuf {
122 if host.contains("dragonfly") || host.contains("freebsd")
123 || host.contains("netbsd") || host.contains("openbsd")
125 PathBuf::from("gmake")
127 PathBuf::from("make")
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: {}",
139 if !output.status.success() {
141 "command did not execute successfully: {:?}\n\
142 expected success, got: {}",
146 String::from_utf8(output.stdout).unwrap()
149 pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
150 let mut stack = dir.read_dir()
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()));
160 println!("cargo:rerun-if-changed={}", path.display());
165 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
166 pub fn mtime(path: &Path) -> SystemTime {
168 .and_then(|f| f.modified())
169 .unwrap_or(UNIX_EPOCH)
172 /// Returns `true` if `dst` is up to date given that the file or files in `src`
173 /// are used to generate it.
175 /// Uses last-modified time checks to verify this.
176 pub fn up_to_date(src: &Path, dst: &Path) -> bool {
180 let threshold = mtime(dst);
181 let meta = match fs::metadata(src) {
183 Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
186 dir_up_to_date(src, threshold)
188 meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
193 pub struct NativeLibBoilerplate {
194 pub src_dir: PathBuf,
195 pub out_dir: PathBuf,
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.
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" {
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);
217 println!("{} => {}", src.display(), dst.display());
218 fs::rename(&src, &dst).unwrap();
219 let status = Command::new("install_name_tool")
221 .arg(format!("@rpath/{}", new_name))
224 .expect("failed to execute `install_name_tool`");
225 assert!(status.success());
229 impl Drop for NativeLibBoilerplate {
231 if !thread::panicking() {
232 t!(File::create(self.out_dir.join("rustbuild.timestamp")));
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(
248 ) -> Result<NativeLibBoilerplate, ()> {
249 rerun_if_changed_anything_in_dir(src_dir);
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);
258 println!("cargo:rustc-link-lib=static={}", link_name);
261 "cargo:rustc-link-search=native={}",
262 out_dir.join(search_subdir).display()
265 let timestamp = out_dir.join("rustbuild.timestamp");
266 if !up_to_date(Path::new("build.rs"), ×tamp) || !up_to_date(src_dir, ×tamp) {
267 Ok(NativeLibBoilerplate {
268 src_dir: src_dir.to_path_buf(),
276 pub fn sanitizer_lib_boilerplate(sanitizer_name: &str)
277 -> Result<(NativeLibBoilerplate, String), ()>
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),
285 "x86_64-apple-darwin" => (
286 format!("clang_rt.{}_osx_dynamic", sanitizer_name),
292 let to_link = if apple {
293 format!("dylib=__rustc__{}", link_name)
295 format!("static={}", link_name)
297 // This env var is provided by rustbuild to tell us where `compiler-rt`
299 let dir = env::var_os("RUST_COMPILER_RT_ROOT").unwrap();
300 let lib = native_lib_boilerplate(
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());
313 dir_up_to_date(&e.path(), threshold)
315 meta.modified().unwrap_or(UNIX_EPOCH) < threshold
320 fn fail(s: &str) -> ! {
321 println!("\n\n{}\n\n", s);
322 std::process::exit(1);