use std::env;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=RUSTC_LINKER");
println!("cargo:rustc-check-cfg=cfg(blots_pools)");
let os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let vendor = env::var("CARGO_CFG_TARGET_VENDOR").unwrap_or_default();
let libc = env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
if os == "linux"
&& libc == "gnu"
&& static_unwinder().is_some_and(|path| runs_on_any_glibc(&path))
{
println!("cargo:rustc-link-lib=static=gcc_eh");
}
if has_native_thread_locals(&os, &vendor, &libc) {
println!("cargo:rustc-cfg=blots_pools");
}
}
fn has_native_thread_locals(os: &str, vendor: &str, libc: &str) -> bool {
match os {
"linux" | "freebsd" | "netbsd" | "dragonfly" => true,
"windows" => libc == "msvc",
_ => vendor == "apple",
}
}
fn linker() -> Option<OsString> {
env::var_os("RUSTC_LINKER")
.or_else(|| (env::var("HOST").ok()? == env::var("TARGET").ok()?).then(|| "cc".into()))
}
fn static_unwinder() -> Option<PathBuf> {
let output = Command::new(linker()?)
.arg("-print-file-name=libgcc_eh.a")
.output()
.ok()?;
let path = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
(output.status.success() && path.is_absolute() && path.is_file()).then_some(path)
}
fn runs_on_any_glibc(path: &Path) -> bool {
const NEWER: &[u8] = b"_dl_find_object";
fs::read(path).is_ok_and(|archive| !archive.windows(NEWER.len()).any(|name| name == NEWER))
}