extern crate anyhow;
extern crate cc;
#[macro_use]
extern crate lazy_static;
extern crate regex_lite;
extern crate semver;
use std::env;
use std::ffi::OsStr;
use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use anyhow::Context as _;
use regex_lite::Regex;
use semver::Version;
lazy_static! {
static ref ENV_LLVM_PREFIX: String =
format!("LLVM_SYS_{}_PREFIX", env!("CARGO_PKG_VERSION_MAJOR"));
static ref ENV_IGNORE_BLOCKLIST: String =
format!("LLVM_SYS_{}_IGNORE_BLOCKLIST", env!("CARGO_PKG_VERSION_MAJOR"));
static ref ENV_STRICT_VERSIONING: String =
format!("LLVM_SYS_{}_STRICT_VERSIONING", env!("CARGO_PKG_VERSION_MAJOR"));
static ref ENV_NO_CLEAN_CFLAGS: String =
format!("LLVM_SYS_{}_NO_CLEAN_CFLAGS", env!("CARGO_PKG_VERSION_MAJOR"));
static ref ENV_USE_DEBUG_MSVCRT: String =
format!("LLVM_SYS_{}_USE_DEBUG_MSVCRT", env!("CARGO_PKG_VERSION_MAJOR"));
static ref ENV_FORCE_FFI: String =
format!("LLVM_SYS_{}_FFI_WORKAROUND", env!("CARGO_PKG_VERSION_MAJOR"));
}
lazy_static! {
static ref CRATE_VERSION: Version = {
let crate_version = Version::parse(env!("CARGO_PKG_VERSION"))
.expect("Crate version is somehow not valid semver");
Version {
major: crate_version.major / 10,
minor: crate_version.major % 10,
.. crate_version
}
};
}
fn target_env_is(name: &str) -> bool {
match env::var_os("CARGO_CFG_TARGET_ENV") {
Some(s) => s == name,
None => false,
}
}
fn target_os_is(name: &str) -> bool {
match env::var_os("CARGO_CFG_TARGET_OS") {
Some(s) => s == name,
None => false,
}
}
fn locate_llvm_config() -> Option<PathBuf> {
let prefix = env::var_os(&*ENV_LLVM_PREFIX)
.map(|p| PathBuf::from(p).join("bin"))
.unwrap_or_else(PathBuf::new);
if let Some(x) = llvm_compatible_binary_name(&prefix) {
return Some(x);
}
if target_os_is("macos") {
if let Some(p) = homebrew_prefix(Some(&format!("llvm@{}", CRATE_VERSION.major)))
.or_else(|| homebrew_prefix(Some("llvm")))
{
return llvm_compatible_binary_name(&PathBuf::from(p).join("bin"));
}
}
None
}
fn llvm_compatible_binary_name(prefix: &Path) -> Option<PathBuf> {
for binary_name in llvm_config_binary_names() {
let binary_name = prefix.join(binary_name);
match llvm_version(&binary_name) {
Ok(version) => {
if is_compatible_llvm(&version) {
return Some(binary_name);
}
println!(
"found LLVM version {} on PATH, but need {}",
version, *CRATE_VERSION
);
}
Err(e) => {
if e.downcast_ref::<io::Error>()
.map_or(false, |e| e.kind() == ErrorKind::NotFound)
{
} else {
panic!("Failed to search PATH for llvm-config: {}", e)
}
}
}
}
None
}
fn llvm_config_binary_names() -> impl Iterator<Item = String> {
let base_names = [
"llvm-config".into(),
format!("llvm-config-{}", CRATE_VERSION.major),
format!("llvm-config{}", CRATE_VERSION.major),
format!("llvm{}-config", CRATE_VERSION.major),
format!(
"llvm-config-{}.{}",
CRATE_VERSION.major, CRATE_VERSION.minor
),
format!("llvm-config{}{}", CRATE_VERSION.major, CRATE_VERSION.minor),
];
if target_os_is("windows") {
IntoIterator::into_iter(base_names)
.flat_map(|name| [format!("{}.exe", name), name])
.collect::<Vec<_>>()
} else {
base_names.to_vec()
}
.into_iter()
}
fn is_blocklisted_llvm(llvm_version: &Version) -> Option<&'static str> {
static BLOCKLIST: &'static [(u64, u64, u64, &'static str)] = &[];
if let Some(x) = env::var_os(&*ENV_IGNORE_BLOCKLIST) {
if &x == "YES" {
println!(
"cargo:warning=ignoring blocklist entry for LLVM {}",
llvm_version
);
return None;
} else {
println!(
"cargo:warning={} is set but not exactly \"YES\"; blocklist is still honored",
*ENV_IGNORE_BLOCKLIST
);
}
}
for &(major, minor, patch, reason) in BLOCKLIST.iter() {
let bad_version = Version {
major: major,
minor: minor,
patch: patch,
pre: semver::Prerelease::EMPTY,
build: semver::BuildMetadata::EMPTY,
};
if &bad_version == llvm_version {
return Some(reason);
}
}
None
}
fn is_compatible_llvm(llvm_version: &Version) -> bool {
if let Some(reason) = is_blocklisted_llvm(llvm_version) {
println!(
"found LLVM {}, which is blocklisted: {}",
llvm_version, reason
);
return false;
}
let strict =
env::var_os(&*ENV_STRICT_VERSIONING).is_some() || cfg!(feature = "strict-versioning");
if strict {
llvm_version.major == CRATE_VERSION.major && llvm_version.minor == CRATE_VERSION.minor
} else {
llvm_version.major >= CRATE_VERSION.major
|| (llvm_version.major == CRATE_VERSION.major
&& llvm_version.minor >= CRATE_VERSION.minor)
}
}
fn llvm_config<I, S>(binary: &Path, args: I) -> String
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
llvm_config_ex(binary, args).expect("Surprising failure from llvm-config")
}
fn llvm_config_ex<I, S>(binary: &Path, args: I) -> anyhow::Result<String>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut cmd = Command::new(binary);
(|| {
let Output {
status,
stdout,
stderr,
} = cmd.args(args).output()?;
let stdout = String::from_utf8(stdout).context("stdout")?;
let stderr = String::from_utf8(stderr).context("stderr")?;
if status.success() {
Ok(stdout)
} else {
Err(anyhow::anyhow!(
"status={status}\nstdout={}\nstderr={}",
stdout.trim(),
stderr.trim()
))
}
})()
.with_context(|| format!("{cmd:?}"))
}
fn llvm_version(binary: &Path) -> anyhow::Result<Version> {
let version_str = llvm_config_ex(binary, ["--version"])?;
let re = Regex::new(r"^(?P<major>\d+)\.(?P<minor>\d+)(?:\.(?P<patch>\d+))??").unwrap();
let c = re.captures(&version_str).ok_or_else(|| {
anyhow::anyhow!(
"could not determine LLVM version from llvm-config. Version string: {version_str}"
)
})?;
let major = c.name("major").unwrap().as_str().parse().context("major")?;
let minor = c.name("minor").unwrap().as_str().parse().context("minor")?;
let patch = match c.name("patch") {
None => 0,
Some(patch) => patch.as_str().parse().context("patch")?,
};
Ok(Version::new(major, minor, patch))
}
fn get_system_libraries(llvm_config_path: &Path, kind: LibraryKind) -> Vec<String> {
let link_arg = match kind {
LibraryKind::Static => "--link-static",
LibraryKind::Dynamic => "--link-shared",
};
llvm_config(llvm_config_path, ["--system-libs", link_arg])
.split(&[' ', '\n'] as &[char])
.filter(|s| !s.is_empty())
.map(|flag| {
if target_env_is("msvc") {
flag.strip_suffix(".lib").unwrap_or_else(|| {
panic!(
"system library '{}' does not appear to be a MSVC library file",
flag
)
})
} else {
if let Some(flag) = flag.strip_prefix("-l") {
if target_os_is("macos") {
if let Some(flag) = flag
.strip_prefix("lib")
.and_then(|flag| flag.strip_suffix(".tbd"))
{
return flag;
}
}
if let Some(i) = flag.find(".so.") {
return &flag[..i];
}
return flag;
}
let maybe_lib = Path::new(flag);
if maybe_lib.is_file() {
println!(
"cargo:rustc-link-search={}",
maybe_lib.parent().unwrap().display()
);
let soname = maybe_lib
.file_name()
.unwrap()
.to_str()
.expect("Shared library path must be a valid string");
let (stem, _rest) = soname
.rsplit_once(target_dylib_extension())
.expect("Shared library should be a .so file");
stem.strip_prefix("lib").unwrap_or_else(|| {
panic!("system library '{}' does not have a 'lib' prefix", soname)
})
} else {
panic!(
"Unable to parse result of llvm-config --system-libs: {}",
flag
)
}
}
})
.chain(get_system_libcpp())
.map(str::to_owned)
.collect()
}
fn get_system_library_dirs() -> impl IntoIterator<Item = String> {
let mut system_library_dirs = Vec::new();
if let Some(dirs) = option_env!("LLVM_SYS_SYSTEM_LIBRARY_DIRS") {
system_library_dirs.extend(dirs.split(':').map(|s| s.to_string()));
}
if target_os_is("openbsd") || target_os_is("freebsd") {
system_library_dirs.push("/usr/local/lib".to_string());
} else if target_os_is("macos") {
if let Some(p) = homebrew_prefix(None) {
system_library_dirs.push(format!("{}/lib", p));
}
} else if target_os_is("linux") && cfg!(target_feature = "crt-static") {
#[cfg(any(
target_arch = "x86_64",
target_arch = "powerpc64",
target_arch = "aarch64"
))]
{
system_library_dirs.push("/lib64".to_string());
system_library_dirs.push("/usr/lib64".to_string());
system_library_dirs.push("/usr/local/lib64".to_string());
}
system_library_dirs.push("/lib".to_string());
system_library_dirs.push("/usr/lib".to_string());
system_library_dirs.push("/usr/local/lib".to_string());
}
system_library_dirs
}
fn homebrew_prefix(name: Option<&str>) -> Option<String> {
let mut cmd = Command::new("brew");
cmd.arg("--prefix");
if let Some(name) = name {
cmd.arg(name);
}
cmd.output()
.ok()
.filter(|o| !o.stdout.is_empty())
.and_then(|out| String::from_utf8(out.stdout).ok())
.map(|val| val.trim().to_string())
}
fn target_dylib_extension() -> &'static str {
if target_os_is("macos") {
".dylib"
} else {
".so"
}
}
fn get_system_libcpp() -> Option<&'static str> {
if let Some(libcpp) = option_env!("LLVM_SYS_LIBCPP") {
Some(libcpp)
} else if target_env_is("msvc") {
None
} else if target_os_is("macos") {
Some("c++")
} else if target_os_is("freebsd") || target_os_is("openbsd") {
Some("c++")
} else {
Some("stdc++")
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum LibraryKind {
Static,
Dynamic,
}
impl LibraryKind {
pub fn string(&self) -> &'static str {
match self {
LibraryKind::Static => "static",
LibraryKind::Dynamic => "dylib",
}
}
}
fn get_link_libraries(
llvm_config_path: &Path,
preferences: &LinkingPreferences,
) -> (LibraryKind, Vec<String>) {
fn get_link_libraries_impl(
llvm_config_path: &Path,
kind: LibraryKind,
) -> anyhow::Result<String> {
if target_env_is("msvc") && kind == LibraryKind::Dynamic {
anyhow::bail!("Dynamic linking to LLVM is not supported on Windows");
}
let link_arg = match kind {
LibraryKind::Static => "--link-static",
LibraryKind::Dynamic => "--link-shared",
};
llvm_config_ex(llvm_config_path, ["--libnames", link_arg])
}
let LinkingPreferences {
prefer_static,
force,
} = preferences;
let one = [*prefer_static];
let both = [*prefer_static, !*prefer_static];
let preferences = if *force { &one[..] } else { &both[..] }
.iter()
.map(|is_static| {
if *is_static {
LibraryKind::Static
} else {
LibraryKind::Dynamic
}
});
for kind in preferences {
match get_link_libraries_impl(llvm_config_path, kind) {
Ok(s) => return (kind, extract_library(&s, kind)),
Err(err) => {
println!(
"failed to get {} libraries from llvm-config: {err:?}",
kind.string()
)
}
}
}
panic!("failed to get linking libraries from llvm-config",);
}
fn extract_library(s: &str, kind: LibraryKind) -> Vec<String> {
s.split(&[' ', '\n'] as &[char])
.filter(|s| !s.is_empty())
.map(|name| {
match kind {
LibraryKind::Static => {
if let Some(name) = name
.strip_prefix("lib")
.and_then(|name| name.strip_suffix(".a"))
{
name
} else if let Some(name) = name.strip_suffix(".lib") {
name
} else {
panic!("'{}' does not look like a static library name", name)
}
}
LibraryKind::Dynamic => {
if let Some(name) = name
.strip_prefix("lib")
.and_then(|name| name.strip_suffix(".dylib"))
{
name
} else if let Some(name) = name
.strip_prefix("lib")
.and_then(|name| name.strip_suffix(".so"))
{
name
} else if let Some(name) = IntoIterator::into_iter([".dll", ".lib"])
.find_map(|suffix| name.strip_suffix(suffix))
{
name
} else {
panic!("'{}' does not look like a shared library name", name)
}
}
}
.to_string()
})
.collect::<Vec<String>>()
}
#[derive(Debug, Clone, Copy)]
struct LinkingPreferences {
prefer_static: bool,
force: bool,
}
impl LinkingPreferences {
fn init() -> LinkingPreferences {
let prefer_static = cfg!(feature = "prefer-static");
let prefer_dynamic = cfg!(feature = "prefer-dynamic");
let force_static = cfg!(feature = "force-static");
let force_dynamic = cfg!(feature = "force-dynamic");
if [prefer_static, prefer_dynamic, force_static, force_dynamic]
.iter()
.filter(|&&x| x)
.count()
> 1
{
panic!(
"Only one of the features `prefer-static`, `prefer-dynamic`, `force-static`, \
`force-dynamic` can be enabled at once"
);
}
let prefer_static = prefer_static || !(prefer_dynamic || force_static || force_dynamic);
LinkingPreferences {
prefer_static: force_static || prefer_static,
force: force_static || force_dynamic,
}
}
}
fn get_llvm_cflags(llvm_config_path: &Path) -> String {
let output = llvm_config(llvm_config_path, ["--cflags"]);
let no_clean = env::var_os(&*ENV_NO_CLEAN_CFLAGS).is_some();
if no_clean || target_env_is("msvc") {
return output;
}
output
.split(&[' ', '\n'][..])
.filter(|word| !word.starts_with("-W"))
.collect::<Vec<_>>()
.join(" ")
}
fn is_llvm_debug(llvm_config_path: &Path) -> bool {
llvm_config(llvm_config_path, ["--build-mode"]).contains("Debug")
}
fn main() {
println!("cargo:rerun-if-env-changed={}", &*ENV_LLVM_PREFIX);
if let Ok(path) = env::var(&*ENV_LLVM_PREFIX) {
println!("cargo:rerun-if-changed={}", path);
}
println!("cargo:rerun-if-env-changed={}", &*ENV_IGNORE_BLOCKLIST);
println!("cargo:rerun-if-env-changed={}", &*ENV_STRICT_VERSIONING);
println!("cargo:rerun-if-env-changed={}", &*ENV_NO_CLEAN_CFLAGS);
println!("cargo:rerun-if-env-changed={}", &*ENV_USE_DEBUG_MSVCRT);
println!("cargo:rerun-if-env-changed={}", &*ENV_FORCE_FFI);
if cfg!(feature = "no-llvm-linking") && cfg!(feature = "disable-alltargets-init") {
return;
}
let llvm_config_path = match locate_llvm_config() {
None => {
println!("cargo:rustc-cfg=LLVM_SYS_NOT_FOUND");
return;
}
Some(llvm_config_path) => llvm_config_path,
};
if !cfg!(feature = "disable-alltargets-init") {
std::env::set_var("CFLAGS", get_llvm_cflags(&llvm_config_path));
cc::Build::new()
.file("wrappers/target.c")
.compile("targetwrappers");
}
if cfg!(feature = "no-llvm-linking") {
return;
}
let libdir = llvm_config(&llvm_config_path, ["--libdir"]);
println!("cargo:config_path={}", llvm_config_path.display()); println!("cargo:libdir={}", libdir);
let preferences = LinkingPreferences::init();
println!("cargo:rustc-link-search=native={}", libdir);
for link_search_dir in get_system_library_dirs() {
println!("cargo:rustc-link-search=native={}", link_search_dir);
}
let (kind, libs) = get_link_libraries(&llvm_config_path, &preferences);
for name in libs {
println!("cargo:rustc-link-lib={}={}", kind.string(), name);
}
let sys_lib_kind = if cfg!(target_feature = "crt-static") {
LibraryKind::Static
} else {
LibraryKind::Dynamic
};
for name in get_system_libraries(&llvm_config_path, kind) {
println!("cargo:rustc-link-lib={}={}", sys_lib_kind.string(), name);
}
let use_debug_msvcrt = env::var_os(&*ENV_USE_DEBUG_MSVCRT).is_some();
if target_env_is("msvc") && (use_debug_msvcrt || is_llvm_debug(&llvm_config_path)) {
println!("cargo:rustc-link-lib={}", "msvcrtd");
}
let force_ffi = env::var_os(&*ENV_FORCE_FFI).is_some();
if force_ffi {
println!("cargo:rustc-link-lib=dylib={}", "ffi");
}
}