use std::cell::RefCell;
use std::collections::hash_map::{Entry, HashMap};
use std::env;
use std::path::PathBuf;
use std::str::{self, FromStr};
use crate::core::compiler::CompileKind;
use crate::core::TargetKind;
use crate::util::config::StringList;
use crate::util::{CargoResult, CargoResultExt, Config, ProcessBuilder, Rustc};
use cargo_platform::{Cfg, CfgExpr};
#[derive(Clone)]
pub struct TargetInfo {
crate_type_process: ProcessBuilder,
crate_types: RefCell<HashMap<String, Option<(String, String)>>>,
cfg: Vec<Cfg>,
pub sysroot_host_libdir: PathBuf,
pub sysroot_target_libdir: PathBuf,
pub rustflags: Vec<String>,
pub rustdocflags: Vec<String>,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum FileFlavor {
Normal,
Auxiliary,
Linkable { rmeta: bool },
DebugInfo,
}
pub struct FileType {
pub flavor: FileFlavor,
suffix: String,
prefix: String,
should_replace_hyphens: bool,
}
impl FileType {
pub fn filename(&self, stem: &str) -> String {
let stem = if self.should_replace_hyphens {
stem.replace("-", "_")
} else {
stem.to_string()
};
format!("{}{}{}", self.prefix, stem, self.suffix)
}
}
impl TargetInfo {
pub fn new(
config: &Config,
requested_kind: CompileKind,
rustc: &Rustc,
kind: CompileKind,
) -> CargoResult<TargetInfo> {
let rustflags = env_args(config, requested_kind, &rustc.host, None, kind, "RUSTFLAGS")?;
let mut process = rustc.process();
process
.arg("-")
.arg("--crate-name")
.arg("___")
.arg("--print=file-names")
.args(&rustflags)
.env_remove("RUSTC_LOG");
if let CompileKind::Target(target) = kind {
process.arg("--target").arg(target.rustc_target());
}
let crate_type_process = process.clone();
const KNOWN_CRATE_TYPES: &[&str] =
&["bin", "rlib", "dylib", "cdylib", "staticlib", "proc-macro"];
for crate_type in KNOWN_CRATE_TYPES.iter() {
process.arg("--crate-type").arg(crate_type);
}
process.arg("--print=sysroot");
process.arg("--print=cfg");
let (output, error) = rustc
.cached_output(&process)
.chain_err(|| "failed to run `rustc` to learn about target-specific information")?;
let mut lines = output.lines();
let mut map = HashMap::new();
for crate_type in KNOWN_CRATE_TYPES {
let out = parse_crate_type(crate_type, &process, &output, &error, &mut lines)?;
map.insert(crate_type.to_string(), out);
}
let line = match lines.next() {
Some(line) => line,
None => failure::bail!(
"output of --print=sysroot missing when learning about \
target-specific information from rustc\n{}",
output_err_info(&process, &output, &error)
),
};
let mut sysroot_host_libdir = PathBuf::from(line);
if cfg!(windows) {
sysroot_host_libdir.push("bin");
} else {
sysroot_host_libdir.push("lib");
}
let mut sysroot_target_libdir = PathBuf::from(line);
sysroot_target_libdir.push("lib");
sysroot_target_libdir.push("rustlib");
sysroot_target_libdir.push(match &kind {
CompileKind::Host => rustc.host.as_str(),
CompileKind::Target(target) => target.short_name(),
});
sysroot_target_libdir.push("lib");
let cfg = lines
.map(|line| Ok(Cfg::from_str(line)?))
.collect::<CargoResult<Vec<_>>>()
.chain_err(|| {
format!(
"failed to parse the cfg from `rustc --print=cfg`, got:\n{}",
output
)
})?;
Ok(TargetInfo {
crate_type_process,
crate_types: RefCell::new(map),
sysroot_host_libdir,
sysroot_target_libdir,
rustflags: env_args(
config,
requested_kind,
&rustc.host,
Some(&cfg),
kind,
"RUSTFLAGS",
)?,
rustdocflags: env_args(
config,
requested_kind,
&rustc.host,
Some(&cfg),
kind,
"RUSTDOCFLAGS",
)?,
cfg,
})
}
pub fn cfg(&self) -> &[Cfg] {
&self.cfg
}
pub fn file_types(
&self,
crate_type: &str,
flavor: FileFlavor,
kind: &TargetKind,
target_triple: &str,
) -> CargoResult<Option<Vec<FileType>>> {
let mut crate_types = self.crate_types.borrow_mut();
let entry = crate_types.entry(crate_type.to_string());
let crate_type_info = match entry {
Entry::Occupied(o) => &*o.into_mut(),
Entry::Vacant(v) => {
let value = self.discover_crate_type(v.key())?;
&*v.insert(value)
}
};
let (prefix, suffix) = match *crate_type_info {
Some((ref prefix, ref suffix)) => (prefix, suffix),
None => return Ok(None),
};
let mut ret = vec![FileType {
suffix: suffix.clone(),
prefix: prefix.clone(),
flavor,
should_replace_hyphens: false,
}];
if target_triple.ends_with("pc-windows-msvc")
&& crate_type.ends_with("dylib")
&& suffix == ".dll"
{
ret.push(FileType {
suffix: ".dll.lib".to_string(),
prefix: prefix.clone(),
flavor: FileFlavor::Normal,
should_replace_hyphens: false,
})
}
if target_triple.starts_with("wasm32-") && crate_type == "bin" && suffix == ".js" {
ret.push(FileType {
suffix: ".wasm".to_string(),
prefix: prefix.clone(),
flavor: FileFlavor::Auxiliary,
should_replace_hyphens: true,
})
}
let is_apple = target_triple.contains("-apple-");
if *kind == TargetKind::Bin || (*kind == TargetKind::ExampleBin && is_apple) {
if is_apple {
ret.push(FileType {
suffix: ".dSYM".to_string(),
prefix: prefix.clone(),
flavor: FileFlavor::DebugInfo,
should_replace_hyphens: false,
})
} else if target_triple.ends_with("-msvc") {
ret.push(FileType {
suffix: ".pdb".to_string(),
prefix: prefix.clone(),
flavor: FileFlavor::DebugInfo,
should_replace_hyphens: false,
})
}
}
Ok(Some(ret))
}
fn discover_crate_type(&self, crate_type: &str) -> CargoResult<Option<(String, String)>> {
let mut process = self.crate_type_process.clone();
process.arg("--crate-type").arg(crate_type);
let output = process.exec_with_output().chain_err(|| {
format!(
"failed to run `rustc` to learn about crate-type {} information",
crate_type
)
})?;
let error = str::from_utf8(&output.stderr).unwrap();
let output = str::from_utf8(&output.stdout).unwrap();
Ok(parse_crate_type(
crate_type,
&process,
output,
error,
&mut output.lines(),
)?)
}
}
fn parse_crate_type(
crate_type: &str,
cmd: &ProcessBuilder,
output: &str,
error: &str,
lines: &mut str::Lines<'_>,
) -> CargoResult<Option<(String, String)>> {
let not_supported = error.lines().any(|line| {
(line.contains("unsupported crate type") || line.contains("unknown crate type"))
&& line.contains(&format!("crate type `{}`", crate_type))
});
if not_supported {
return Ok(None);
}
let line = match lines.next() {
Some(line) => line,
None => failure::bail!(
"malformed output when learning about crate-type {} information\n{}",
crate_type,
output_err_info(cmd, output, error)
),
};
let mut parts = line.trim().split("___");
let prefix = parts.next().unwrap();
let suffix = match parts.next() {
Some(part) => part,
None => failure::bail!(
"output of --print=file-names has changed in the compiler, cannot parse\n{}",
output_err_info(cmd, output, error)
),
};
Ok(Some((prefix.to_string(), suffix.to_string())))
}
fn output_err_info(cmd: &ProcessBuilder, stdout: &str, stderr: &str) -> String {
let mut result = format!("command was: {}\n", cmd);
if !stdout.is_empty() {
result.push_str("\n--- stdout\n");
result.push_str(stdout);
}
if !stderr.is_empty() {
result.push_str("\n--- stderr\n");
result.push_str(stderr);
}
if stdout.is_empty() && stderr.is_empty() {
result.push_str("(no output received)");
}
result
}
fn env_args(
config: &Config,
requested_kind: CompileKind,
host_triple: &str,
target_cfg: Option<&[Cfg]>,
kind: CompileKind,
name: &str,
) -> CargoResult<Vec<String>> {
if !requested_kind.is_host() && kind.is_host() {
return Ok(Vec::new());
}
if let Ok(a) = env::var(name) {
let args = a
.split(' ')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string);
return Ok(args.collect());
}
let mut rustflags = Vec::new();
let name = name
.chars()
.flat_map(|c| c.to_lowercase())
.collect::<String>();
let target = match &kind {
CompileKind::Host => host_triple,
CompileKind::Target(target) => target.short_name(),
};
let key = format!("target.{}.{}", target, name);
if let Some(args) = config.get::<Option<StringList>>(&key)? {
rustflags.extend(args.as_slice().iter().cloned());
}
if let Some(target_cfg) = target_cfg {
if let Some(table) = config.get_table("target")? {
let cfgs = table
.val
.keys()
.filter(|key| CfgExpr::matches_key(key, target_cfg));
let mut cfgs = cfgs.collect::<Vec<_>>();
cfgs.sort();
for n in cfgs {
let key = format!("target.{}.{}", n, name);
if let Some(args) = config.get::<Option<StringList>>(&key)? {
rustflags.extend(args.as_slice().iter().cloned());
}
}
}
}
if !rustflags.is_empty() {
return Ok(rustflags);
}
let build = config.build_config()?;
let list = if name == "rustflags" {
&build.rustflags
} else {
&build.rustdocflags
};
if let Some(list) = list {
return Ok(list.as_slice().to_vec());
}
Ok(Vec::new())
}