use build_helper::util::{fail, try_run};
use std::env;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::str;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use crate::builder::Builder;
use crate::config::{Config, TargetSelection};
use crate::OnceCell;
#[macro_export]
macro_rules! t {
($e:expr) => {
match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {}", stringify!($e), e),
}
};
($e:expr, $extra:expr) => {
match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
}
};
}
pub use t;
pub fn exe(name: &str, target: TargetSelection) -> String {
if target.contains("windows") {
format!("{name}.exe")
} else if target.contains("uefi") {
format!("{name}.efi")
} else {
name.to_string()
}
}
pub fn is_dylib(name: &str) -> bool {
name.ends_with(".dylib") || name.ends_with(".so") || name.ends_with(".dll")
}
pub fn is_debug_info(name: &str) -> bool {
name.ends_with(".pdb")
}
pub fn libdir(target: TargetSelection) -> &'static str {
if target.contains("windows") { "bin" } else { "lib" }
}
pub fn add_dylib_path(path: Vec<PathBuf>, cmd: &mut Command) {
let mut list = dylib_path();
for path in path {
list.insert(0, path);
}
cmd.env(dylib_path_var(), t!(env::join_paths(list)));
}
include!("dylib_util.rs");
pub fn add_link_lib_path(path: Vec<PathBuf>, cmd: &mut Command) {
let mut list = link_lib_path();
for path in path {
list.insert(0, path);
}
cmd.env(link_lib_path_var(), t!(env::join_paths(list)));
}
fn link_lib_path_var() -> &'static str {
if cfg!(target_env = "msvc") { "LIB" } else { "LIBRARY_PATH" }
}
fn link_lib_path() -> Vec<PathBuf> {
let var = match env::var_os(link_lib_path_var()) {
Some(v) => v,
None => return vec![],
};
env::split_paths(&var).collect()
}
pub struct TimeIt(bool, Instant);
pub fn timeit(builder: &Builder<'_>) -> TimeIt {
TimeIt(builder.config.dry_run(), Instant::now())
}
impl Drop for TimeIt {
fn drop(&mut self) {
let time = self.1.elapsed();
if !self.0 {
println!("\tfinished in {}.{:03} seconds", time.as_secs(), time.subsec_millis());
}
}
}
pub(crate) fn program_out_of_date(stamp: &Path, key: &str) -> bool {
if !stamp.exists() {
return true;
}
t!(fs::read_to_string(stamp)) != key
}
pub fn symlink_dir(config: &Config, original: &Path, link: &Path) -> io::Result<()> {
if config.dry_run() {
return Ok(());
}
let _ = fs::remove_dir(link);
return symlink_dir_inner(original, link);
#[cfg(not(windows))]
fn symlink_dir_inner(original: &Path, link: &Path) -> io::Result<()> {
use std::os::unix::fs;
fs::symlink(original, link)
}
#[cfg(windows)]
fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
junction::create(&target, &junction)
}
}
pub fn forcing_clang_based_tests() -> bool {
if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") {
match &var.to_string_lossy().to_lowercase()[..] {
"1" | "yes" | "on" => true,
"0" | "no" | "off" => false,
other => {
panic!(
"Unrecognized option '{other}' set in \
RUSTBUILD_FORCE_CLANG_BASED_TESTS"
)
}
}
} else {
false
}
}
pub fn use_host_linker(target: TargetSelection) -> bool {
!(target.contains("emscripten")
|| target.contains("wasm32")
|| target.contains("nvptx")
|| target.contains("fortanix")
|| target.contains("fuchsia")
|| target.contains("bpf")
|| target.contains("switch"))
}
pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>(
path: &'a Path,
suite_path: P,
builder: &Builder<'_>,
) -> Option<&'a str> {
let suite_path = suite_path.as_ref();
let path = match path.strip_prefix(".") {
Ok(p) => p,
Err(_) => path,
};
if !path.starts_with(suite_path) {
return None;
}
let abs_path = builder.src.join(path);
let exists = abs_path.is_dir() || abs_path.is_file();
if !exists {
panic!(
"Invalid test suite filter \"{}\": file or directory does not exist",
abs_path.display()
);
}
match path.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
Some(s) if !s.is_empty() => Some(s),
_ => None,
}
}
pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) {
if try_run(cmd, print_cmd_on_fail).is_err() {
crate::exit!(1);
}
}
pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool {
let status = match cmd.status() {
Ok(status) => status,
Err(e) => {
println!("failed to execute command: {cmd:?}\nerror: {e}");
return false;
}
};
if !status.success() && print_cmd_on_fail {
println!(
"\n\ncommand did not execute successfully: {cmd:?}\n\
expected success, got: {status}\n\n"
);
}
status.success()
}
pub fn run_suppressed(cmd: &mut Command) {
if !try_run_suppressed(cmd) {
crate::exit!(1);
}
}
pub fn try_run_suppressed(cmd: &mut Command) -> bool {
let output = match cmd.output() {
Ok(status) => status,
Err(e) => fail(&format!("failed to execute command: {cmd:?}\nerror: {e}")),
};
if !output.status.success() {
println!(
"\n\ncommand did not execute successfully: {:?}\n\
expected success, got: {}\n\n\
stdout ----\n{}\n\
stderr ----\n{}\n\n",
cmd,
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
output.status.success()
}
pub fn make(host: &str) -> PathBuf {
if host.contains("dragonfly")
|| host.contains("freebsd")
|| host.contains("netbsd")
|| host.contains("openbsd")
{
PathBuf::from("gmake")
} else {
PathBuf::from("make")
}
}
#[track_caller]
pub fn output(cmd: &mut Command) -> String {
let output = match cmd.stderr(Stdio::inherit()).output() {
Ok(status) => status,
Err(e) => fail(&format!("failed to execute command: {cmd:?}\nerror: {e}")),
};
if !output.status.success() {
panic!(
"command did not execute successfully: {:?}\n\
expected success, got: {}",
cmd, output.status
);
}
String::from_utf8(output.stdout).unwrap()
}
pub fn output_result(cmd: &mut Command) -> Result<String, String> {
let output = match cmd.stderr(Stdio::inherit()).output() {
Ok(status) => status,
Err(e) => return Err(format!("failed to run command: {cmd:?}: {e}")),
};
if !output.status.success() {
return Err(format!(
"command did not execute successfully: {:?}\n\
expected success, got: {}\n{}",
cmd,
output.status,
String::from_utf8(output.stderr).map_err(|err| format!("{err:?}"))?
));
}
Ok(String::from_utf8(output.stdout).map_err(|err| format!("{err:?}"))?)
}
pub fn mtime(path: &Path) -> SystemTime {
fs::metadata(path).and_then(|f| f.modified()).unwrap_or(UNIX_EPOCH)
}
pub fn up_to_date(src: &Path, dst: &Path) -> bool {
if !dst.exists() {
return false;
}
let threshold = mtime(dst);
let meta = match fs::metadata(src) {
Ok(meta) => meta,
Err(e) => panic!("source {src:?} failed to get metadata: {e}"),
};
if meta.is_dir() {
dir_up_to_date(src, threshold)
} else {
meta.modified().unwrap_or(UNIX_EPOCH) <= threshold
}
}
fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool {
t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
let meta = t!(e.metadata());
if meta.is_dir() {
dir_up_to_date(&e.path(), threshold)
} else {
meta.modified().unwrap_or(UNIX_EPOCH) < threshold
}
})
}
pub(crate) fn absolute(path: &Path) -> PathBuf {
if path.as_os_str().is_empty() {
panic!("can't make empty path absolute");
}
#[cfg(unix)]
{
t!(absolute_unix(path), format!("could not make path absolute: {}", path.display()))
}
#[cfg(windows)]
{
t!(absolute_windows(path), format!("could not make path absolute: {}", path.display()))
}
#[cfg(not(any(unix, windows)))]
{
println!("warning: bootstrap is not supported on non-unix platforms");
t!(std::fs::canonicalize(t!(std::env::current_dir()))).join(path)
}
}
#[cfg(unix)]
fn absolute_unix(path: &Path) -> io::Result<PathBuf> {
use std::os::unix::prelude::OsStrExt;
let mut components = path.components();
let path_os = path.as_os_str().as_bytes();
let mut normalized = if path.is_absolute() {
if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
components.next();
PathBuf::from("//")
} else {
PathBuf::new()
}
} else {
env::current_dir()?
};
normalized.extend(components);
if path_os.ends_with(b"/") {
normalized.push("");
}
Ok(normalized)
}
#[cfg(windows)]
fn absolute_windows(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
use std::ffi::OsString;
use std::io::Error;
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::ptr::null_mut;
#[link(name = "kernel32")]
extern "system" {
fn GetFullPathNameW(
lpFileName: *const u16,
nBufferLength: u32,
lpBuffer: *mut u16,
lpFilePart: *mut *const u16,
) -> u32;
}
unsafe {
let path: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
let mut buffer = Vec::new();
loop {
let len = GetFullPathNameW(
path.as_ptr(),
buffer.len().try_into().unwrap(),
buffer.as_mut_ptr(),
null_mut(),
);
match len as usize {
0 => return Err(Error::last_os_error()),
len if len > buffer.len() => buffer.resize(len, 0),
len => {
buffer.truncate(len);
return Ok(OsString::from_wide(&buffer).into());
}
}
}
}
}
pub fn get_clang_cl_resource_dir(clang_cl_path: &str) -> PathBuf {
let mut builtins_locator = Command::new(clang_cl_path);
builtins_locator.args(&["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]);
let clang_rt_builtins = output(&mut builtins_locator);
let clang_rt_builtins = Path::new(clang_rt_builtins.trim());
assert!(
clang_rt_builtins.exists(),
"`clang-cl` must correctly locate the library runtime directory"
);
let clang_rt_dir = clang_rt_builtins.parent().expect("The clang lib folder should exist");
clang_rt_dir.to_path_buf()
}
pub fn lld_flag_no_threads(is_windows: bool) -> &'static str {
static LLD_NO_THREADS: OnceCell<(&'static str, &'static str)> = OnceCell::new();
let (windows, other) = LLD_NO_THREADS.get_or_init(|| {
let out = output(Command::new("lld").arg("-flavor").arg("ld").arg("--version"));
let newer = match (out.find(char::is_numeric), out.find('.')) {
(Some(b), Some(e)) => out.as_str()[b..e].parse::<i32>().ok().unwrap_or(14) > 10,
_ => true,
};
if newer { ("/threads:1", "--threads=1") } else { ("/no-threads", "--no-threads") }
});
if is_windows { windows } else { other }
}
pub fn dir_is_empty(dir: &Path) -> bool {
t!(std::fs::read_dir(dir)).next().is_none()
}