#![doc(html_root_url = "https://docs.rs/cc/1.0")]
#![cfg_attr(test, deny(warnings))]
#![allow(deprecated)]
#![deny(missing_docs)]
use std::collections::HashMap;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fmt::{self, Display};
use std::fs;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
#[cfg(windows)]
mod registry;
#[cfg(windows)]
#[macro_use]
mod winapi;
#[cfg(windows)]
mod com;
#[cfg(windows)]
mod setup_config;
pub mod windows_registry;
#[derive(Clone, Debug)]
pub struct Build {
include_directories: Vec<PathBuf>,
definitions: Vec<(String, Option<String>)>,
objects: Vec<PathBuf>,
flags: Vec<String>,
flags_supported: Vec<String>,
known_flag_support_status: Arc<Mutex<HashMap<String, bool>>>,
ar_flags: Vec<String>,
no_default_flags: bool,
files: Vec<PathBuf>,
cpp: bool,
cpp_link_stdlib: Option<Option<String>>,
cpp_set_stdlib: Option<String>,
cuda: bool,
target: Option<String>,
host: Option<String>,
out_dir: Option<PathBuf>,
opt_level: Option<String>,
debug: Option<bool>,
force_frame_pointer: Option<bool>,
env: Vec<(OsString, OsString)>,
compiler: Option<PathBuf>,
archiver: Option<PathBuf>,
cargo_metadata: bool,
pic: Option<bool>,
use_plt: Option<bool>,
static_crt: Option<bool>,
shared_flag: Option<bool>,
static_flag: Option<bool>,
warnings_into_errors: bool,
warnings: Option<bool>,
extra_warnings: Option<bool>,
env_cache: Arc<Mutex<HashMap<String, Option<String>>>>,
}
#[derive(Clone, Debug)]
enum ErrorKind {
IOError,
ArchitectureInvalid,
EnvVarNotFound,
ToolExecError,
ToolNotFound,
}
#[derive(Clone, Debug)]
pub struct Error {
kind: ErrorKind,
message: String,
}
impl Error {
fn new(kind: ErrorKind, message: &str) -> Error {
Error {
kind: kind,
message: message.to_owned(),
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::new(ErrorKind::IOError, &format!("{}", e))
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}: {}", self.kind, self.message)
}
}
impl std::error::Error for Error {}
#[derive(Clone, Debug)]
pub struct Tool {
path: PathBuf,
cc_wrapper_path: Option<PathBuf>,
cc_wrapper_args: Vec<OsString>,
args: Vec<OsString>,
env: Vec<(OsString, OsString)>,
family: ToolFamily,
cuda: bool,
removed_args: Vec<OsString>,
}
#[derive(Copy, Clone, Debug, PartialEq)]
enum ToolFamily {
Gnu,
Clang,
Msvc { clang_cl: bool },
}
impl ToolFamily {
fn add_debug_flags(&self, cmd: &mut Tool) {
match *self {
ToolFamily::Msvc { .. } => {
cmd.push_cc_arg("-Z7".into());
}
ToolFamily::Gnu | ToolFamily::Clang => {
cmd.push_cc_arg("-g".into());
}
}
}
fn add_force_frame_pointer(&self, cmd: &mut Tool) {
match *self {
ToolFamily::Gnu | ToolFamily::Clang => {
cmd.push_cc_arg("-fno-omit-frame-pointer".into());
}
_ => (),
}
}
fn warnings_flags(&self) -> &'static str {
match *self {
ToolFamily::Msvc { .. } => "-W4",
ToolFamily::Gnu | ToolFamily::Clang => "-Wall",
}
}
fn extra_warnings_flags(&self) -> Option<&'static str> {
match *self {
ToolFamily::Msvc { .. } => None,
ToolFamily::Gnu | ToolFamily::Clang => Some("-Wextra"),
}
}
fn warnings_to_errors_flag(&self) -> &'static str {
match *self {
ToolFamily::Msvc { .. } => "-WX",
ToolFamily::Gnu | ToolFamily::Clang => "-Werror",
}
}
fn verbose_stderr(&self) -> bool {
*self == ToolFamily::Clang
}
}
#[derive(Clone, Debug)]
struct Object {
src: PathBuf,
dst: PathBuf,
}
impl Object {
fn new(src: PathBuf, dst: PathBuf) -> Object {
Object { src: src, dst: dst }
}
}
impl Build {
pub fn new() -> Build {
Build {
include_directories: Vec::new(),
definitions: Vec::new(),
objects: Vec::new(),
flags: Vec::new(),
flags_supported: Vec::new(),
known_flag_support_status: Arc::new(Mutex::new(HashMap::new())),
ar_flags: Vec::new(),
no_default_flags: false,
files: Vec::new(),
shared_flag: None,
static_flag: None,
cpp: false,
cpp_link_stdlib: None,
cpp_set_stdlib: None,
cuda: false,
target: None,
host: None,
out_dir: None,
opt_level: None,
debug: None,
force_frame_pointer: None,
env: Vec::new(),
compiler: None,
archiver: None,
cargo_metadata: true,
pic: None,
use_plt: None,
static_crt: None,
warnings: None,
extra_warnings: None,
warnings_into_errors: false,
env_cache: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Build {
self.include_directories.push(dir.as_ref().to_path_buf());
self
}
pub fn define<'a, V: Into<Option<&'a str>>>(&mut self, var: &str, val: V) -> &mut Build {
self.definitions
.push((var.to_string(), val.into().map(|s| s.to_string())));
self
}
pub fn object<P: AsRef<Path>>(&mut self, obj: P) -> &mut Build {
self.objects.push(obj.as_ref().to_path_buf());
self
}
pub fn flag(&mut self, flag: &str) -> &mut Build {
self.flags.push(flag.to_string());
self
}
pub fn ar_flag(&mut self, flag: &str) -> &mut Build {
self.ar_flags.push(flag.to_string());
self
}
fn ensure_check_file(&self) -> Result<PathBuf, Error> {
let out_dir = self.get_out_dir()?;
let src = if self.cuda {
assert!(self.cpp);
out_dir.join("flag_check.cu")
} else if self.cpp {
out_dir.join("flag_check.cpp")
} else {
out_dir.join("flag_check.c")
};
if !src.exists() {
let mut f = fs::File::create(&src)?;
write!(f, "int main(void) {{ return 0; }}")?;
}
Ok(src)
}
pub fn is_flag_supported(&self, flag: &str) -> Result<bool, Error> {
let mut known_status = self.known_flag_support_status.lock().unwrap();
if let Some(is_supported) = known_status.get(flag).cloned() {
return Ok(is_supported);
}
let out_dir = self.get_out_dir()?;
let src = self.ensure_check_file()?;
let obj = out_dir.join("flag_check");
let target = self.get_target()?;
let host = self.get_host()?;
let mut cfg = Build::new();
cfg.flag(flag)
.target(&target)
.opt_level(0)
.host(&host)
.debug(false)
.cpp(self.cpp)
.cuda(self.cuda);
let mut compiler = cfg.try_get_compiler()?;
if compiler.family.verbose_stderr() {
compiler.remove_arg("-v".into());
}
let mut cmd = compiler.to_command();
let is_arm = target.contains("aarch64") || target.contains("arm");
command_add_output_file(
&mut cmd,
&obj,
self.cuda,
target.contains("msvc"),
false,
is_arm,
);
if target.contains("msvc") && !self.cuda {
cmd.arg("-c");
}
cmd.arg(&src);
let output = cmd.output()?;
let is_supported = output.stderr.is_empty();
known_status.insert(flag.to_owned(), is_supported);
Ok(is_supported)
}
pub fn flag_if_supported(&mut self, flag: &str) -> &mut Build {
self.flags_supported.push(flag.to_string());
self
}
pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build {
self.shared_flag = Some(shared_flag);
self
}
pub fn static_flag(&mut self, static_flag: bool) -> &mut Build {
self.static_flag = Some(static_flag);
self
}
pub fn no_default_flags(&mut self, no_default_flags: bool) -> &mut Build {
self.no_default_flags = no_default_flags;
self
}
pub fn file<P: AsRef<Path>>(&mut self, p: P) -> &mut Build {
self.files.push(p.as_ref().to_path_buf());
self
}
pub fn files<P>(&mut self, p: P) -> &mut Build
where
P: IntoIterator,
P::Item: AsRef<Path>,
{
for file in p.into_iter() {
self.file(file);
}
self
}
pub fn cpp(&mut self, cpp: bool) -> &mut Build {
self.cpp = cpp;
self
}
pub fn cuda(&mut self, cuda: bool) -> &mut Build {
self.cuda = cuda;
if cuda {
self.cpp = true;
}
self
}
pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build {
self.warnings_into_errors = warnings_into_errors;
self
}
pub fn warnings(&mut self, warnings: bool) -> &mut Build {
self.warnings = Some(warnings);
self.extra_warnings = Some(warnings);
self
}
pub fn extra_warnings(&mut self, warnings: bool) -> &mut Build {
self.extra_warnings = Some(warnings);
self
}
pub fn cpp_link_stdlib<'a, V: Into<Option<&'a str>>>(
&mut self,
cpp_link_stdlib: V,
) -> &mut Build {
self.cpp_link_stdlib = Some(cpp_link_stdlib.into().map(|s| s.into()));
self
}
pub fn cpp_set_stdlib<'a, V: Into<Option<&'a str>>>(
&mut self,
cpp_set_stdlib: V,
) -> &mut Build {
let cpp_set_stdlib = cpp_set_stdlib.into();
self.cpp_set_stdlib = cpp_set_stdlib.map(|s| s.into());
self.cpp_link_stdlib(cpp_set_stdlib);
self
}
pub fn target(&mut self, target: &str) -> &mut Build {
self.target = Some(target.to_string());
self
}
pub fn host(&mut self, host: &str) -> &mut Build {
self.host = Some(host.to_string());
self
}
pub fn opt_level(&mut self, opt_level: u32) -> &mut Build {
self.opt_level = Some(opt_level.to_string());
self
}
pub fn opt_level_str(&mut self, opt_level: &str) -> &mut Build {
self.opt_level = Some(opt_level.to_string());
self
}
pub fn debug(&mut self, debug: bool) -> &mut Build {
self.debug = Some(debug);
self
}
pub fn force_frame_pointer(&mut self, force: bool) -> &mut Build {
self.force_frame_pointer = Some(force);
self
}
pub fn out_dir<P: AsRef<Path>>(&mut self, out_dir: P) -> &mut Build {
self.out_dir = Some(out_dir.as_ref().to_owned());
self
}
pub fn compiler<P: AsRef<Path>>(&mut self, compiler: P) -> &mut Build {
self.compiler = Some(compiler.as_ref().to_owned());
self
}
pub fn archiver<P: AsRef<Path>>(&mut self, archiver: P) -> &mut Build {
self.archiver = Some(archiver.as_ref().to_owned());
self
}
pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build {
self.cargo_metadata = cargo_metadata;
self
}
pub fn pic(&mut self, pic: bool) -> &mut Build {
self.pic = Some(pic);
self
}
pub fn use_plt(&mut self, use_plt: bool) -> &mut Build {
self.use_plt = Some(use_plt);
self
}
pub fn static_crt(&mut self, static_crt: bool) -> &mut Build {
self.static_crt = Some(static_crt);
self
}
#[doc(hidden)]
pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build
where
A: AsRef<OsStr>,
B: AsRef<OsStr>,
{
self.env
.push((a.as_ref().to_owned(), b.as_ref().to_owned()));
self
}
pub fn try_compile(&self, output: &str) -> Result<(), Error> {
let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") {
(&output[3..output.len() - 2], output.to_owned())
} else {
let mut gnu = String::with_capacity(5 + output.len());
gnu.push_str("lib");
gnu.push_str(&output);
gnu.push_str(".a");
(output, gnu)
};
let dst = self.get_out_dir()?;
let mut objects = Vec::new();
for file in self.files.iter() {
let obj = dst.join(file).with_extension("o");
let obj = if !obj.starts_with(&dst) {
dst.join(obj.file_name().ok_or_else(|| {
Error::new(ErrorKind::IOError, "Getting object file details failed.")
})?)
} else {
obj
};
match obj.parent() {
Some(s) => fs::create_dir_all(s)?,
None => {
return Err(Error::new(
ErrorKind::IOError,
"Getting object file details failed.",
));
}
};
objects.push(Object::new(file.to_path_buf(), obj));
}
self.compile_objects(&objects)?;
self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?;
if self.get_target()?.contains("msvc") {
let compiler = self.get_base_compiler()?;
let atlmfc_lib = compiler
.env()
.iter()
.find(|&&(ref var, _)| var.as_os_str() == OsStr::new("LIB"))
.and_then(|&(_, ref lib_paths)| {
env::split_paths(lib_paths).find(|path| {
let sub = Path::new("atlmfc/lib");
path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub))
})
});
if let Some(atlmfc_lib) = atlmfc_lib {
self.print(&format!(
"cargo:rustc-link-search=native={}",
atlmfc_lib.display()
));
}
}
self.print(&format!("cargo:rustc-link-lib=static={}", lib_name));
self.print(&format!("cargo:rustc-link-search=native={}", dst.display()));
if self.cpp {
if let Some(stdlib) = self.get_cpp_link_stdlib()? {
self.print(&format!("cargo:rustc-link-lib={}", stdlib));
}
}
Ok(())
}
pub fn compile(&self, output: &str) {
if let Err(e) = self.try_compile(output) {
fail(&e.message);
}
}
#[cfg(feature = "parallel")]
fn compile_objects<'me>(&'me self, objs: &[Object]) -> Result<(), Error> {
use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
use std::sync::Once;
let server = jobserver();
let reacquire = server.release_raw().is_ok();
let error = AtomicBool::new(false);
let mut threads = Vec::new();
for obj in objs {
if error.load(SeqCst) {
break;
}
let token = server.acquire()?;
let state = State {
build: self,
obj,
error: &error,
};
let state = unsafe { std::mem::transmute::<State, State<'static>>(state) };
let thread = thread::spawn(|| {
let state: State<'me> = state;
let result = state.build.compile_object(state.obj);
if result.is_err() {
state.error.store(true, SeqCst);
}
drop(token);
return result;
});
threads.push(JoinOnDrop(Some(thread)));
}
for mut thread in threads {
if let Some(thread) = thread.0.take() {
thread.join().expect("thread should not panic")?;
}
}
if reacquire {
server.acquire_raw()?;
}
return Ok(());
struct State<'a> {
build: &'a Build,
obj: &'a Object,
error: &'a AtomicBool,
}
fn jobserver() -> &'static jobserver::Client {
static INIT: Once = Once::new();
static mut JOBSERVER: Option<jobserver::Client> = None;
fn _assert_sync<T: Sync>() {}
_assert_sync::<jobserver::Client>();
unsafe {
INIT.call_once(|| {
let server = default_jobserver();
JOBSERVER = Some(server);
});
JOBSERVER.as_ref().unwrap()
}
}
unsafe fn default_jobserver() -> jobserver::Client {
if let Some(client) = jobserver::Client::from_env() {
return client;
}
let mut parallelism = 4;
if let Ok(amt) = env::var("NUM_JOBS") {
if let Ok(amt) = amt.parse() {
parallelism = amt;
}
}
let client = jobserver::Client::new(parallelism).expect("failed to create jobserver");
client.acquire_raw().expect("failed to acquire initial");
return client;
}
struct JoinOnDrop(Option<thread::JoinHandle<Result<(), Error>>>);
impl Drop for JoinOnDrop {
fn drop(&mut self) {
if let Some(thread) = self.0.take() {
drop(thread.join());
}
}
}
}
#[cfg(not(feature = "parallel"))]
fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> {
for obj in objs {
self.compile_object(obj)?;
}
Ok(())
}
fn compile_object(&self, obj: &Object) -> Result<(), Error> {
let is_asm = obj.src.extension().and_then(|s| s.to_str()) == Some("asm");
let target = self.get_target()?;
let msvc = target.contains("msvc");
let (mut cmd, name) = if msvc && is_asm {
self.msvc_macro_assembler()?
} else {
let compiler = self.try_get_compiler()?;
let mut cmd = compiler.to_command();
for &(ref a, ref b) in self.env.iter() {
cmd.env(a, b);
}
(
cmd,
compiler
.path
.file_name()
.ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))?
.to_string_lossy()
.into_owned(),
)
};
let is_arm = target.contains("aarch64") || target.contains("arm");
command_add_output_file(&mut cmd, &obj.dst, self.cuda, msvc, is_asm, is_arm);
if !msvc || !is_asm || !is_arm {
cmd.arg("-c");
}
cmd.arg(&obj.src);
run(&mut cmd, &name)?;
Ok(())
}
pub fn try_expand(&self) -> Result<Vec<u8>, Error> {
let compiler = self.try_get_compiler()?;
let mut cmd = compiler.to_command();
for &(ref a, ref b) in self.env.iter() {
cmd.env(a, b);
}
cmd.arg("-E");
assert!(
self.files.len() <= 1,
"Expand may only be called for a single file"
);
for file in self.files.iter() {
cmd.arg(file);
}
let name = compiler
.path
.file_name()
.ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))?
.to_string_lossy()
.into_owned();
Ok(run_output(&mut cmd, &name)?)
}
pub fn expand(&self) -> Vec<u8> {
match self.try_expand() {
Err(e) => fail(&e.message),
Ok(v) => v,
}
}
pub fn get_compiler(&self) -> Tool {
match self.try_get_compiler() {
Ok(tool) => tool,
Err(e) => fail(&e.message),
}
}
pub fn try_get_compiler(&self) -> Result<Tool, Error> {
let opt_level = self.get_opt_level()?;
let target = self.get_target()?;
let mut cmd = self.get_base_compiler()?;
let envflags = self.envflags(if self.cpp { "CXXFLAGS" } else { "CFLAGS" });
let no_defaults = self.no_default_flags || self.getenv("CRATE_CC_NO_DEFAULTS").is_some();
if !no_defaults {
self.add_default_flags(&mut cmd, &target, &opt_level)?;
} else {
println!("Info: default compiler flags are disabled");
}
for arg in envflags {
cmd.push_cc_arg(arg.into());
}
for directory in self.include_directories.iter() {
cmd.args.push("-I".into());
cmd.args.push(directory.into());
}
if self
.warnings
.unwrap_or(if self.has_flags() { false } else { true })
{
let wflags = cmd.family.warnings_flags().into();
cmd.push_cc_arg(wflags);
}
if self
.extra_warnings
.unwrap_or(if self.has_flags() { false } else { true })
{
if let Some(wflags) = cmd.family.extra_warnings_flags() {
cmd.push_cc_arg(wflags.into());
}
}
for flag in self.flags.iter() {
cmd.args.push(flag.into());
}
for flag in self.flags_supported.iter() {
if self.is_flag_supported(flag).unwrap_or(false) {
cmd.push_cc_arg(flag.into());
}
}
for &(ref key, ref value) in self.definitions.iter() {
if let Some(ref value) = *value {
cmd.args.push(format!("-D{}={}", key, value).into());
} else {
cmd.args.push(format!("-D{}", key).into());
}
}
if self.warnings_into_errors {
let warnings_to_errors_flag = cmd.family.warnings_to_errors_flag().into();
cmd.push_cc_arg(warnings_to_errors_flag);
}
Ok(cmd)
}
fn add_default_flags(
&self,
cmd: &mut Tool,
target: &str,
opt_level: &str,
) -> Result<(), Error> {
match cmd.family {
ToolFamily::Msvc { .. } => {
cmd.push_cc_arg("-nologo".into());
let crt_flag = match self.static_crt {
Some(true) => "-MT",
Some(false) => "-MD",
None => {
let features = self
.getenv("CARGO_CFG_TARGET_FEATURE")
.unwrap_or(String::new());
if features.contains("crt-static") {
"-MT"
} else {
"-MD"
}
}
};
cmd.push_cc_arg(crt_flag.into());
match &opt_level[..] {
"z" | "s" | "1" => cmd.push_opt_unless_duplicate("-O1".into()),
"2" | "3" => cmd.push_opt_unless_duplicate("-O2".into()),
_ => {}
}
}
ToolFamily::Gnu | ToolFamily::Clang => {
if opt_level == "z" && cmd.family != ToolFamily::Clang {
cmd.push_opt_unless_duplicate("-Os".into());
} else {
cmd.push_opt_unless_duplicate(format!("-O{}", opt_level).into());
}
if !target.contains("-ios") {
cmd.push_cc_arg("-ffunction-sections".into());
cmd.push_cc_arg("-fdata-sections".into());
}
if self.pic.unwrap_or(
!target.contains("windows-gnu")
&& !(target.contains("riscv") && target.contains("-none-")),
) {
cmd.push_cc_arg("-fPIC".into());
if target.contains("linux") && !self.use_plt.unwrap_or(true) {
cmd.push_cc_arg("-fno-plt".into());
}
}
}
}
if self.get_debug() {
if self.cuda {
cmd.args.push("-G".into());
}
let family = cmd.family;
family.add_debug_flags(cmd);
}
if self.get_force_frame_pointer() {
let family = cmd.family;
family.add_force_frame_pointer(cmd);
}
match cmd.family {
ToolFamily::Clang => {
cmd.args.push(format!("--target={}", target).into());
}
ToolFamily::Msvc { clang_cl } => {
cmd.args.push("-Brepro".into());
if clang_cl {
if target.contains("x86_64") {
cmd.args.push("-m64".into());
} else if target.contains("86") {
cmd.args.push("-m32".into());
cmd.push_cc_arg("-arch:IA32".into());
} else {
cmd.push_cc_arg(format!("--target={}", target).into());
}
} else {
if target.contains("i586") {
cmd.push_cc_arg("-arch:IA32".into());
}
}
if target.contains("arm") || target.contains("thumb") {
cmd.args
.push("-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1".into());
}
}
ToolFamily::Gnu => {
if target.contains("i686") || target.contains("i586") {
cmd.args.push("-m32".into());
} else if target == "x86_64-unknown-linux-gnux32" {
cmd.args.push("-mx32".into());
} else if target.contains("x86_64") || target.contains("powerpc64") {
cmd.args.push("-m64".into());
}
if self.static_flag.is_none() {
let features = self
.getenv("CARGO_CFG_TARGET_FEATURE")
.unwrap_or(String::new());
if features.contains("crt-static") {
cmd.args.push("-static".into());
}
}
if (target.starts_with("armv7") || target.starts_with("thumbv7"))
&& target.contains("-linux-")
{
cmd.args.push("-march=armv7-a".into());
}
if target.contains("-androideabi") && target.contains("v7") {
cmd.args.push("-mthumb".into());
if !target.contains("neon") {
cmd.args.push("-mfpu=vfpv3-d16".into());
}
cmd.args.push("-mfloat-abi=softfp".into());
}
if target.contains("neon") {
cmd.args.push("-mfpu=neon-vfpv4".into());
}
if target.starts_with("armv4t-unknown-linux-") {
cmd.args.push("-march=armv4t".into());
cmd.args.push("-marm".into());
cmd.args.push("-mfloat-abi=soft".into());
}
if target.starts_with("armv5te-unknown-linux-") {
cmd.args.push("-march=armv5te".into());
cmd.args.push("-marm".into());
cmd.args.push("-mfloat-abi=soft".into());
}
if target.starts_with("arm-unknown-linux-") {
cmd.args.push("-march=armv6".into());
cmd.args.push("-marm".into());
if target.ends_with("hf") {
cmd.args.push("-mfpu=vfp".into());
} else {
cmd.args.push("-mfloat-abi=soft".into());
}
}
if target.starts_with("arm-frc-") {
cmd.args.push("-march=armv7-a".into());
cmd.args.push("-mcpu=cortex-a9".into());
cmd.args.push("-mfpu=vfpv3".into());
cmd.args.push("-mfloat-abi=softfp".into());
cmd.args.push("-marm".into());
}
if target.starts_with("i586-unknown-linux-") {
cmd.args.push("-march=pentium".into());
}
if target.starts_with("i686-unknown-linux-") {
cmd.args.push("-march=i686".into());
}
if target == "i686-unknown-linux-musl" || target == "i586-unknown-linux-musl" {
cmd.args.push("-Wl,-melf_i386".into());
}
if target.starts_with("thumb") {
cmd.args.push("-mthumb".into());
if target.ends_with("eabihf") {
cmd.args.push("-mfloat-abi=hard".into())
}
}
if target.starts_with("thumbv6m") {
cmd.args.push("-march=armv6s-m".into());
}
if target.starts_with("thumbv7em") {
cmd.args.push("-march=armv7e-m".into());
if target.ends_with("eabihf") {
cmd.args.push("-mfpu=fpv4-sp-d16".into())
}
}
if target.starts_with("thumbv7m") {
cmd.args.push("-march=armv7-m".into());
}
if target.starts_with("thumbv8m.base") {
cmd.args.push("-march=armv8-m.base".into());
}
if target.starts_with("thumbv8m.main") {
cmd.args.push("-march=armv8-m.main".into());
if target.ends_with("eabihf") {
cmd.args.push("-mfpu=fpv5-sp-d16".into())
}
}
if target.starts_with("armebv7r") | target.starts_with("armv7r") {
if target.starts_with("armeb") {
cmd.args.push("-mbig-endian".into());
} else {
cmd.args.push("-mlittle-endian".into());
}
cmd.args.push("-marm".into());
cmd.args.push("-march=armv7-r".into());
if target.ends_with("eabihf") {
cmd.args.push("-mfloat-abi=hard".into());
cmd.args.push("-mfpu=vfpv3-d16".into())
} else {
cmd.args.push("-mfloat-abi=soft".into());
}
}
if target.starts_with("riscv32") || target.starts_with("riscv64") {
let mut parts = target.split('-');
if let Some(arch) = parts.next() {
let arch = &arch[5..];
cmd.args.push(("-march=rv".to_owned() + arch).into());
if target.contains("linux") && arch.starts_with("64") {
cmd.args.push("-mabi=lp64d".into());
} else if target.contains("linux") && arch.starts_with("32") {
cmd.args.push("-mabi=ilp32d".into());
} else if arch.starts_with("64") {
cmd.args.push("-mabi=lp64".into());
} else {
cmd.args.push("-mabi=ilp32".into());
}
}
}
}
}
if target.contains("-ios") {
self.ios_flags(cmd)?;
}
if self.static_flag.unwrap_or(false) {
cmd.args.push("-static".into());
}
if self.shared_flag.unwrap_or(false) {
cmd.args.push("-shared".into());
}
if self.cpp {
match (self.cpp_set_stdlib.as_ref(), cmd.family) {
(None, _) => {}
(Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang) => {
cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into());
}
_ => {
println!(
"cargo:warning=cpp_set_stdlib is specified, but the {:?} compiler \
does not support this option, ignored",
cmd.family
);
}
}
}
Ok(())
}
fn has_flags(&self) -> bool {
let flags_env_var_name = if self.cpp { "CXXFLAGS" } else { "CFLAGS" };
let flags_env_var_value = self.get_var(flags_env_var_name);
if let Ok(_) = flags_env_var_value {
true
} else {
false
}
}
fn msvc_macro_assembler(&self) -> Result<(Command, String), Error> {
let target = self.get_target()?;
let tool = if target.contains("x86_64") {
"ml64.exe"
} else if target.contains("arm") {
"armasm.exe"
} else if target.contains("aarch64") {
"armasm64.exe"
} else {
"ml.exe"
};
let mut cmd = windows_registry::find(&target, tool).unwrap_or_else(|| self.cmd(tool));
for directory in self.include_directories.iter() {
cmd.arg("-I").arg(directory);
}
for &(ref key, ref value) in self.definitions.iter() {
if let Some(ref value) = *value {
cmd.arg(&format!("-D{}={}", key, value));
} else {
cmd.arg(&format!("-D{}", key));
}
}
if target.contains("i686") || target.contains("i586") {
cmd.arg("-safeseh");
}
for flag in self.flags.iter() {
cmd.arg(flag);
}
Ok((cmd, tool.to_string()))
}
fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> {
let _ = fs::remove_file(&dst);
let objects: Vec<_> = objs.iter().map(|obj| obj.dst.clone()).collect();
let target = self.get_target()?;
if target.contains("msvc") {
let (mut cmd, program) = self.get_ar()?;
let mut out = OsString::from("-out:");
out.push(dst);
cmd.arg(out).arg("-nologo");
for flag in self.ar_flags.iter() {
cmd.arg(flag);
}
let estimated_command_line_len = objects
.iter()
.chain(&self.objects)
.map(|a| a.as_os_str().len())
.sum::<usize>();
if estimated_command_line_len > 1024 * 6 {
let mut args = String::from("\u{FEFF}");
for arg in objects.iter().chain(&self.objects) {
args.push('"');
for c in arg.to_str().unwrap().chars() {
if c == '"' {
args.push('\\')
}
args.push(c)
}
args.push('"');
args.push('\n');
}
let mut utf16le = Vec::new();
for code_unit in args.encode_utf16() {
utf16le.push(code_unit as u8);
utf16le.push((code_unit >> 8) as u8);
}
let mut args_file = OsString::from(dst);
args_file.push(".args");
fs::File::create(&args_file)
.unwrap()
.write_all(&utf16le)
.unwrap();
let mut args_file_arg = OsString::from("@");
args_file_arg.push(args_file);
cmd.arg(args_file_arg);
} else {
cmd.args(&objects).args(&self.objects);
}
run(&mut cmd, &program)?;
let lib_dst = dst.with_file_name(format!("{}.lib", lib_name));
let _ = fs::remove_file(&lib_dst);
match fs::hard_link(&dst, &lib_dst).or_else(|_| {
fs::copy(&dst, &lib_dst).map(|_| ())
}) {
Ok(_) => (),
Err(_) => {
return Err(Error::new(
ErrorKind::IOError,
"Could not copy or create a hard-link to the generated lib file.",
));
}
};
} else {
let (mut ar, cmd) = self.get_ar()?;
ar.env("ZERO_AR_DATE", "1");
for flag in self.ar_flags.iter() {
ar.arg(flag);
}
run(
ar.arg("crs").arg(dst).args(&objects).args(&self.objects),
&cmd,
)?;
}
Ok(())
}
fn ios_flags(&self, cmd: &mut Tool) -> Result<(), Error> {
enum ArchSpec {
Device(&'static str),
Simulator(&'static str),
}
let target = self.get_target()?;
let arch = target.split('-').nth(0).ok_or_else(|| {
Error::new(
ErrorKind::ArchitectureInvalid,
"Unknown architecture for iOS target.",
)
})?;
let arch = match arch {
"arm" | "armv7" | "thumbv7" => ArchSpec::Device("armv7"),
"armv7s" | "thumbv7s" => ArchSpec::Device("armv7s"),
"arm64" | "aarch64" => ArchSpec::Device("arm64"),
"i386" | "i686" => ArchSpec::Simulator("-m32"),
"x86_64" => ArchSpec::Simulator("-m64"),
_ => {
return Err(Error::new(
ErrorKind::ArchitectureInvalid,
"Unknown architecture for iOS target.",
));
}
};
let min_version =
std::env::var("IPHONEOS_DEPLOYMENT_TARGET").unwrap_or_else(|_| "7.0".into());
let sdk = match arch {
ArchSpec::Device(arch) => {
cmd.args.push("-arch".into());
cmd.args.push(arch.into());
cmd.args
.push(format!("-miphoneos-version-min={}", min_version).into());
"iphoneos"
}
ArchSpec::Simulator(arch) => {
cmd.args.push(arch.into());
cmd.args
.push(format!("-mios-simulator-version-min={}", min_version).into());
"iphonesimulator"
}
};
self.print(&format!("Detecting iOS SDK path for {}", sdk));
let sdk_path = self
.cmd("xcrun")
.arg("--show-sdk-path")
.arg("--sdk")
.arg(sdk)
.stderr(Stdio::inherit())
.output()?
.stdout;
let sdk_path = match String::from_utf8(sdk_path) {
Ok(p) => p,
Err(_) => {
return Err(Error::new(
ErrorKind::IOError,
"Unable to determine iOS SDK path.",
));
}
};
cmd.args.push("-isysroot".into());
cmd.args.push(sdk_path.trim().into());
cmd.args.push("-fembed-bitcode".into());
Ok(())
}
fn cmd<P: AsRef<OsStr>>(&self, prog: P) -> Command {
let mut cmd = Command::new(prog);
for &(ref a, ref b) in self.env.iter() {
cmd.env(a, b);
}
cmd
}
fn get_base_compiler(&self) -> Result<Tool, Error> {
if let Some(ref c) = self.compiler {
return Ok(Tool::new(c.clone()));
}
let host = self.get_host()?;
let target = self.get_target()?;
let (env, msvc, gnu, traditional, clang) = if self.cpp {
("CXX", "cl.exe", "g++", "c++", "clang++")
} else {
("CC", "cl.exe", "gcc", "cc", "clang")
};
let default = if host.contains("solaris") {
gnu
} else {
traditional
};
let cl_exe = windows_registry::find_tool(&target, "cl.exe");
let tool_opt: Option<Tool> = self
.env_tool(env)
.map(|(tool, wrapper, args)| {
const DRIVER_MODE: &str = "--driver-mode=";
let driver_mode = args
.iter()
.find(|a| a.starts_with(DRIVER_MODE))
.map(|a| &a[DRIVER_MODE.len()..]);
let mut t = Tool::with_clang_driver(PathBuf::from(tool.trim()), driver_mode);
if let Some(cc) = wrapper {
t.cc_wrapper_path = Some(PathBuf::from(cc));
}
for arg in args {
t.cc_wrapper_args.push(arg.into());
}
t
})
.or_else(|| {
if target.contains("emscripten") {
let tool = if self.cpp { "em++" } else { "emcc" };
if cfg!(windows) {
let mut t = Tool::new(PathBuf::from("cmd"));
t.args.push("/c".into());
t.args.push(format!("{}.bat", tool).into());
Some(t)
} else {
Some(Tool::new(PathBuf::from(tool)))
}
} else {
None
}
})
.or_else(|| cl_exe.clone());
let tool = match tool_opt {
Some(t) => t,
None => {
let compiler = if host.contains("windows") && target.contains("windows") {
if target.contains("msvc") {
msvc.to_string()
} else {
format!("{}.exe", gnu)
}
} else if target.contains("android") {
let target = target
.replace("armv7neon", "arm")
.replace("armv7", "arm")
.replace("thumbv7neon", "arm")
.replace("thumbv7", "arm");
let gnu_compiler = format!("{}-{}", target, gnu);
let clang_compiler = format!("{}-{}", target, clang);
if Command::new(&gnu_compiler).spawn().is_ok() {
gnu_compiler
} else {
clang_compiler
}
} else if target.contains("cloudabi") {
format!("{}-{}", target, traditional)
} else if target == "wasm32-wasi"
|| target == "wasm32-unknown-wasi"
|| target == "wasm32-unknown-unknown"
{
"clang".to_string()
} else if target.contains("vxworks") {
"wr-c++".to_string()
} else if self.get_host()? != target {
let cc_env = self.getenv("CROSS_COMPILE");
let cross_compile = cc_env.as_ref().map(|s| s.trim_right_matches('-'));
let prefix = cross_compile.or(match &target[..] {
"aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"),
"aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"),
"aarch64-unknown-netbsd" => Some("aarch64--netbsd"),
"arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
"armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
"armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"),
"arm-frc-linux-gnueabi" => Some("arm-frc-linux-gnueabi"),
"arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
"arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"),
"arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
"arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"),
"armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"),
"armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
"armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
"armv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
"armv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
"thumbv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
"thumbv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
"thumbv7neon-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"),
"thumbv7neon-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"),
"armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"),
"i586-unknown-linux-musl" => Some("musl"),
"i686-pc-windows-gnu" => Some("i686-w64-mingw32"),
"i686-uwp-windows-gnu" => Some("i686-w64-mingw32"),
"i686-unknown-linux-musl" => Some("musl"),
"i686-unknown-netbsd" => Some("i486--netbsdelf"),
"mips-unknown-linux-gnu" => Some("mips-linux-gnu"),
"mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"),
"mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"),
"mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"),
"mipsisa32r6-unknown-linux-gnu" => Some("mipsisa32r6-linux-gnu"),
"mipsisa32r6el-unknown-linux-gnu" => Some("mipsisa32r6el-linux-gnu"),
"mipsisa64r6-unknown-linux-gnuabi64" => Some("mipsisa64r6-linux-gnuabi64"),
"mipsisa64r6el-unknown-linux-gnuabi64" => {
Some("mipsisa64r6el-linux-gnuabi64")
}
"powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
"powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"),
"powerpc-unknown-netbsd" => Some("powerpc--netbsd"),
"powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"),
"powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"),
"riscv32i-unknown-none-elf" => Some("riscv32-unknown-elf"),
"riscv32imac-unknown-none-elf" => Some("riscv32-unknown-elf"),
"riscv32imc-unknown-none-elf" => Some("riscv32-unknown-elf"),
"riscv64gc-unknown-none-elf" => Some("riscv64-unknown-elf"),
"riscv64imac-unknown-none-elf" => Some("riscv64-unknown-elf"),
"riscv64gc-unknown-linux-gnu" => Some("riscv64-linux-gnu"),
"s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"),
"sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"),
"sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"),
"sparc64-unknown-netbsd" => Some("sparc64--netbsd"),
"sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"),
"armebv7r-none-eabi" => Some("arm-none-eabi"),
"armebv7r-none-eabihf" => Some("arm-none-eabi"),
"armv7r-none-eabi" => Some("arm-none-eabi"),
"armv7r-none-eabihf" => Some("arm-none-eabi"),
"thumbv6m-none-eabi" => Some("arm-none-eabi"),
"thumbv7em-none-eabi" => Some("arm-none-eabi"),
"thumbv7em-none-eabihf" => Some("arm-none-eabi"),
"thumbv7m-none-eabi" => Some("arm-none-eabi"),
"thumbv8m.base-none-eabi" => Some("arm-none-eabi"),
"thumbv8m.main-none-eabi" => Some("arm-none-eabi"),
"thumbv8m.main-none-eabihf" => Some("arm-none-eabi"),
"x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"),
"x86_64-uwp-windows-gnu" => Some("x86_64-w64-mingw32"),
"x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"),
"x86_64-unknown-linux-musl" => Some("musl"),
"x86_64-unknown-netbsd" => Some("x86_64--netbsd"),
_ => None,
});
match prefix {
Some(prefix) => format!("{}-{}", prefix, gnu),
None => default.to_string(),
}
} else {
default.to_string()
};
Tool::new(PathBuf::from(compiler))
}
};
let mut tool = if self.cuda {
assert!(
tool.args.is_empty(),
"CUDA compilation currently assumes empty pre-existing args"
);
let nvcc = match self.get_var("NVCC") {
Err(_) => "nvcc".into(),
Ok(nvcc) => nvcc,
};
let mut nvcc_tool = Tool::with_features(PathBuf::from(nvcc), None, self.cuda);
nvcc_tool
.args
.push(format!("-ccbin={}", tool.path.display()).into());
nvcc_tool.family = tool.family;
nvcc_tool
} else {
tool
};
if let Some(cl_exe) = cl_exe {
if tool.family == (ToolFamily::Msvc { clang_cl: true })
&& tool.env.len() == 0
&& target.contains("msvc")
{
for &(ref k, ref v) in cl_exe.env.iter() {
tool.env.push((k.to_owned(), v.to_owned()));
}
}
}
Ok(tool)
}
fn get_var(&self, var_base: &str) -> Result<String, Error> {
let target = self.get_target()?;
let host = self.get_host()?;
let kind = if host == target { "HOST" } else { "TARGET" };
let target_u = target.replace("-", "_");
let res = self
.getenv(&format!("{}_{}", var_base, target))
.or_else(|| self.getenv(&format!("{}_{}", var_base, target_u)))
.or_else(|| self.getenv(&format!("{}_{}", kind, var_base)))
.or_else(|| self.getenv(var_base));
match res {
Some(res) => Ok(res),
None => Err(Error::new(
ErrorKind::EnvVarNotFound,
&format!("Could not find environment variable {}.", var_base),
)),
}
}
fn envflags(&self, name: &str) -> Vec<String> {
self.get_var(name)
.unwrap_or(String::new())
.split(|c: char| c.is_whitespace())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect()
}
fn env_tool(&self, name: &str) -> Option<(String, Option<String>, Vec<String>)> {
let tool = match self.get_var(name) {
Ok(tool) => tool,
Err(_) => return None,
};
if Path::new(&tool).exists() {
return Some((tool, None, Vec::new()));
}
let known_wrappers = ["ccache", "distcc", "sccache", "icecc"];
let mut parts = tool.split_whitespace();
let maybe_wrapper = match parts.next() {
Some(s) => s,
None => return None,
};
let file_stem = Path::new(maybe_wrapper)
.file_stem()
.unwrap()
.to_str()
.unwrap();
if known_wrappers.contains(&file_stem) {
if let Some(compiler) = parts.next() {
return Some((
compiler.to_string(),
Some(maybe_wrapper.to_string()),
parts.map(|s| s.to_string()).collect(),
));
}
}
Some((
maybe_wrapper.to_string(),
None,
parts.map(|s| s.to_string()).collect(),
))
}
fn get_cpp_link_stdlib(&self) -> Result<Option<String>, Error> {
match self.cpp_link_stdlib.clone() {
Some(s) => Ok(s),
None => {
if let Ok(stdlib) = self.get_var("CXXSTDLIB") {
if stdlib.is_empty() {
Ok(None)
} else {
Ok(Some(stdlib))
}
} else {
let target = self.get_target()?;
if target.contains("msvc") {
Ok(None)
} else if target.contains("apple") {
Ok(Some("c++".to_string()))
} else if target.contains("freebsd") {
Ok(Some("c++".to_string()))
} else if target.contains("openbsd") {
Ok(Some("c++".to_string()))
} else {
Ok(Some("stdc++".to_string()))
}
}
}
}
}
fn get_ar(&self) -> Result<(Command, String), Error> {
if let Some(ref p) = self.archiver {
let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("ar");
return Ok((self.cmd(p), name.to_string()));
}
if let Ok(p) = self.get_var("AR") {
return Ok((self.cmd(&p), p));
}
let target = self.get_target()?;
let program = if target.contains("android") {
format!("{}-ar", target.replace("armv7", "arm"))
} else if target.contains("emscripten") {
if cfg!(windows) {
let mut cmd = self.cmd("cmd");
cmd.arg("/c").arg("emar.bat");
return Ok((cmd, "emar.bat".to_string()));
}
"emar".to_string()
} else if target.contains("msvc") {
match windows_registry::find(&target, "lib.exe") {
Some(t) => return Ok((t, "lib.exe".to_string())),
None => "lib.exe".to_string(),
}
} else {
"ar".to_string()
};
Ok((self.cmd(&program), program))
}
fn get_target(&self) -> Result<String, Error> {
match self.target.clone() {
Some(t) => Ok(t),
None => Ok(self.getenv_unwrap("TARGET")?),
}
}
fn get_host(&self) -> Result<String, Error> {
match self.host.clone() {
Some(h) => Ok(h),
None => Ok(self.getenv_unwrap("HOST")?),
}
}
fn get_opt_level(&self) -> Result<String, Error> {
match self.opt_level.as_ref().cloned() {
Some(ol) => Ok(ol),
None => Ok(self.getenv_unwrap("OPT_LEVEL")?),
}
}
fn get_debug(&self) -> bool {
self.debug.unwrap_or_else(|| match self.getenv("DEBUG") {
Some(s) => s != "false",
None => false,
})
}
fn get_force_frame_pointer(&self) -> bool {
self.force_frame_pointer.unwrap_or_else(|| self.get_debug())
}
fn get_out_dir(&self) -> Result<PathBuf, Error> {
match self.out_dir.clone() {
Some(p) => Ok(p),
None => Ok(env::var_os("OUT_DIR").map(PathBuf::from).ok_or_else(|| {
Error::new(
ErrorKind::EnvVarNotFound,
"Environment variable OUT_DIR not defined.",
)
})?),
}
}
fn getenv(&self, v: &str) -> Option<String> {
let mut cache = self.env_cache.lock().unwrap();
if let Some(val) = cache.get(v) {
return val.clone();
}
let r = env::var(v).ok();
self.print(&format!("{} = {:?}", v, r));
cache.insert(v.to_string(), r.clone());
r
}
fn getenv_unwrap(&self, v: &str) -> Result<String, Error> {
match self.getenv(v) {
Some(s) => Ok(s),
None => Err(Error::new(
ErrorKind::EnvVarNotFound,
&format!("Environment variable {} not defined.", v.to_string()),
)),
}
}
fn print(&self, s: &str) {
if self.cargo_metadata {
println!("{}", s);
}
}
}
impl Default for Build {
fn default() -> Build {
Build::new()
}
}
impl Tool {
fn new(path: PathBuf) -> Self {
Tool::with_features(path, None, false)
}
fn with_clang_driver(path: PathBuf, clang_driver: Option<&str>) -> Self {
Self::with_features(path, clang_driver, false)
}
fn with_features(path: PathBuf, clang_driver: Option<&str>, cuda: bool) -> Self {
let family = if let Some(fname) = path.file_name().and_then(|p| p.to_str()) {
if fname.contains("clang-cl") {
ToolFamily::Msvc { clang_cl: true }
} else if fname.contains("cl")
&& !fname.contains("cloudabi")
&& !fname.contains("uclibc")
&& !fname.contains("clang")
{
ToolFamily::Msvc { clang_cl: false }
} else if fname.contains("clang") {
match clang_driver {
Some("cl") => ToolFamily::Msvc { clang_cl: true },
_ => ToolFamily::Clang,
}
} else {
ToolFamily::Gnu
}
} else {
ToolFamily::Gnu
};
Tool {
path: path,
cc_wrapper_path: None,
cc_wrapper_args: Vec::new(),
args: Vec::new(),
env: Vec::new(),
family: family,
cuda: cuda,
removed_args: Vec::new(),
}
}
fn remove_arg(&mut self, flag: OsString) {
self.removed_args.push(flag);
}
fn push_cc_arg(&mut self, flag: OsString) {
if self.cuda {
self.args.push("-Xcompiler".into());
}
self.args.push(flag);
}
fn is_duplicate_opt_arg(&self, flag: &OsString) -> bool {
let flag = flag.to_str().unwrap();
let mut chars = flag.chars();
if self.is_like_msvc() {
if chars.next() != Some('/') {
return false;
}
} else if self.is_like_gnu() || self.is_like_clang() {
if chars.next() != Some('-') {
return false;
}
}
if chars.next() == Some('O') {
return self
.args()
.iter()
.any(|ref a| a.to_str().unwrap_or("").chars().nth(1) == Some('O'));
}
return false;
}
fn push_opt_unless_duplicate(&mut self, flag: OsString) {
if self.is_duplicate_opt_arg(&flag) {
println!("Info: Ignoring duplicate arg {:?}", &flag);
} else {
self.push_cc_arg(flag);
}
}
pub fn to_command(&self) -> Command {
let mut cmd = match self.cc_wrapper_path {
Some(ref cc_wrapper_path) => {
let mut cmd = Command::new(&cc_wrapper_path);
cmd.arg(&self.path);
cmd
}
None => Command::new(&self.path),
};
cmd.args(&self.cc_wrapper_args);
let value = self
.args
.iter()
.filter(|a| !self.removed_args.contains(a))
.collect::<Vec<_>>();
cmd.args(&value);
for &(ref k, ref v) in self.env.iter() {
cmd.env(k, v);
}
cmd
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn args(&self) -> &[OsString] {
&self.args
}
pub fn env(&self) -> &[(OsString, OsString)] {
&self.env
}
pub fn cc_env(&self) -> OsString {
match self.cc_wrapper_path {
Some(ref cc_wrapper_path) => {
let mut cc_env = cc_wrapper_path.as_os_str().to_owned();
cc_env.push(" ");
cc_env.push(self.path.to_path_buf().into_os_string());
for arg in self.cc_wrapper_args.iter() {
cc_env.push(" ");
cc_env.push(arg);
}
cc_env
}
None => OsString::from(""),
}
}
pub fn cflags_env(&self) -> OsString {
let mut flags = OsString::new();
for (i, arg) in self.args.iter().enumerate() {
if i > 0 {
flags.push(" ");
}
flags.push(arg);
}
flags
}
pub fn is_like_gnu(&self) -> bool {
self.family == ToolFamily::Gnu
}
pub fn is_like_clang(&self) -> bool {
self.family == ToolFamily::Clang
}
pub fn is_like_msvc(&self) -> bool {
match self.family {
ToolFamily::Msvc { .. } => true,
_ => false,
}
}
}
fn run(cmd: &mut Command, program: &str) -> Result<(), Error> {
let (mut child, print) = spawn(cmd, program)?;
let status = match child.wait() {
Ok(s) => s,
Err(_) => {
return Err(Error::new(
ErrorKind::ToolExecError,
&format!(
"Failed to wait on spawned child process, command {:?} with args {:?}.",
cmd, program
),
));
}
};
print.join().unwrap();
println!("{}", status);
if status.success() {
Ok(())
} else {
Err(Error::new(
ErrorKind::ToolExecError,
&format!(
"Command {:?} with args {:?} did not execute successfully (status code {}).",
cmd, program, status
),
))
}
}
fn run_output(cmd: &mut Command, program: &str) -> Result<Vec<u8>, Error> {
cmd.stdout(Stdio::piped());
let (mut child, print) = spawn(cmd, program)?;
let mut stdout = vec![];
child
.stdout
.take()
.unwrap()
.read_to_end(&mut stdout)
.unwrap();
let status = match child.wait() {
Ok(s) => s,
Err(_) => {
return Err(Error::new(
ErrorKind::ToolExecError,
&format!(
"Failed to wait on spawned child process, command {:?} with args {:?}.",
cmd, program
),
));
}
};
print.join().unwrap();
println!("{}", status);
if status.success() {
Ok(stdout)
} else {
Err(Error::new(
ErrorKind::ToolExecError,
&format!(
"Command {:?} with args {:?} did not execute successfully (status code {}).",
cmd, program, status
),
))
}
}
fn spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error> {
println!("running: {:?}", cmd);
match cmd.stderr(Stdio::piped()).spawn() {
Ok(mut child) => {
let stderr = BufReader::new(child.stderr.take().unwrap());
let print = thread::spawn(move || {
for line in stderr.split(b'\n').filter_map(|l| l.ok()) {
print!("cargo:warning=");
std::io::stdout().write_all(&line).unwrap();
println!("");
}
});
Ok((child, print))
}
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
let extra = if cfg!(windows) {
" (see https://github.com/alexcrichton/cc-rs#compile-time-requirements \
for help)"
} else {
""
};
Err(Error::new(
ErrorKind::ToolNotFound,
&format!("Failed to find tool. Is `{}` installed?{}", program, extra),
))
}
Err(_) => Err(Error::new(
ErrorKind::ToolExecError,
&format!("Command {:?} with args {:?} failed to start.", cmd, program),
)),
}
}
fn fail(s: &str) -> ! {
let _ = writeln!(io::stderr(), "\n\nerror occurred: {}\n\n", s);
std::process::exit(1);
}
fn command_add_output_file(
cmd: &mut Command,
dst: &Path,
cuda: bool,
msvc: bool,
is_asm: bool,
is_arm: bool,
) {
if msvc && !cuda && !(is_asm && is_arm) {
let mut s = OsString::from("-Fo");
s.push(&dst);
cmd.arg(s);
} else {
cmd.arg("-o").arg(&dst);
}
}