use crate::driver::{ape, ARCHES};
use crate::sha256::Sha256;
use crate::toolchain::run;
use std::env::consts::EXE_SUFFIX;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
const SPEC_X86: &str = include_str!("../assets/x86_64-unknown-cosmo.json");
const SPEC_ARM: &str = include_str!("../assets/aarch64-unknown-cosmo.json");
const SHIM: &str = include_str!("../assets/shim.rs");
pub const WRAP_LIST: &str = include_str!("../assets/wrap.txt");
pub const CHANNEL: &str = include_str!("../assets/channel.txt");
pub struct Cache {
pub root: PathBuf,
pub cosmocc: PathBuf,
pub gen: PathBuf,
}
pub struct Glue {
pub specs: [PathBuf; 2],
pub tools: PathBuf,
}
impl Glue {
pub fn tool(&self, name: &str) -> PathBuf {
self.tools.join(format!("{name}{EXE_SUFFIX}"))
}
}
impl Cache {
pub fn locate() -> Result<Cache, String> {
let root = match std::env::var_os("COSMO_HOME") {
Some(d) => PathBuf::from(d),
None => base_cache_dir()?.join("cargo-cosmo"),
};
Ok(Cache {
cosmocc: root.join("cosmocc"),
gen: root.join(concat!("v", env!("CARGO_PKG_VERSION"))),
root,
})
}
pub fn bin(&self, name: &str) -> PathBuf {
self.cosmocc.join("bin").join(name)
}
pub fn materialize(&self) -> Result<Glue, String> {
fs::create_dir_all(&self.gen).map_err(|e| format!("{}: {e}", self.gen.display()))?;
let wraps: Vec<&str> = WRAP_LIST
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.collect();
let libcosmo = self.unwrapped_libcosmo(&wraps)?;
let tools = self.drivers(&wraps, &libcosmo)?;
let glue = Glue { specs: [PathBuf::new(), PathBuf::new()], tools };
let mut specs = Vec::new();
for (arch, spec) in [("x86_64", SPEC_X86), ("aarch64", SPEC_ARM)] {
let ld = glue.tool(&format!("cosmo-ld-{arch}"));
let path = self.gen.join(format!("{arch}-unknown-cosmo.json"));
let text = spec.replace("@COSMO_LD@", &escape_json(&ld.to_string_lossy()));
if fs::read_to_string(&path).ok().as_deref() != Some(text.as_str()) {
fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
}
specs.push(path);
}
Ok(Glue { specs: [specs.remove(0), specs.remove(0)], ..glue })
}
fn unwrapped_libcosmo(&self, wraps: &[&str]) -> Result<PathBuf, String> {
let dir = self.gen.join(format!("libcosmo-{}", short_hash(&[&wraps.join(" ")])));
if wraps.is_empty() {
return Ok(dir);
}
for arch in ARCHES {
let out = dir.join(format!("{arch}.a"));
if out.is_file() {
continue;
}
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let pid = std::process::id();
let syms = dir.join(format!("{arch}.syms.{pid}"));
let tmp = dir.join(format!("{arch}.a.{pid}"));
let text: String = wraps.iter().map(|s| format!("{s} __cosmo_real_{s}\n")).collect();
fs::write(&syms, text).map_err(|e| format!("{}: {e}", syms.display()))?;
let lib = self.cosmocc.join(format!("{arch}-linux-cosmo")).join("lib").join("libcosmo.a");
let r = run(
ape(&self.bin(&format!("{arch}-linux-cosmo-objcopy")))
.arg(format!("--redefine-syms={}", syms.display()))
.arg(&lib)
.arg(&tmp),
);
let _ = fs::remove_file(&syms);
r?;
settle(&tmp, &out)?;
}
Ok(dir)
}
fn drivers(&self, wraps: &[&str], libcosmo: &Path) -> Result<PathBuf, String> {
let cosmocc = self.cosmocc.to_string_lossy();
let libcosmo = libcosmo.to_string_lossy();
let wraps = wraps.join(" ");
let key = short_hash(&[SHIM, &cosmocc, &libcosmo, &wraps]);
let dir = self.gen.join(format!("tools-{key}"));
if dir.is_dir() {
return Ok(dir);
}
let tmp = self.gen.join(format!("tools-{key}.{}", std::process::id()));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let src = tmp.join("cosmo-shim.rs");
fs::write(&src, SHIM).map_err(|e| format!("{}: {e}", src.display()))?;
let exe = tmp.join(format!("cosmo-shim{EXE_SUFFIX}"));
let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
run(Command::new(rustc)
.args(["--edition", "2021", "-O", "--crate-name", "cosmo_shim", "-o"])
.arg(&exe)
.arg(&src)
.env("COSMO_SHIM_COSMOCC", &*cosmocc)
.env("COSMO_SHIM_LIBCOSMO", &*libcosmo)
.env("COSMO_SHIM_WRAPS", &wraps))?;
for arch in ARCHES {
for name in [
format!("cosmo-ld-{arch}"),
format!("{arch}-unknown-cosmo-cc"),
format!("{arch}-unknown-cosmo-c++"),
format!("{arch}-unknown-cosmo-ar"),
] {
let link = tmp.join(format!("{name}{EXE_SUFFIX}"));
fs::hard_link(&exe, &link)
.or_else(|_| fs::copy(&exe, &link).map(|_| ()))
.map_err(|e| format!("{}: {e}", link.display()))?;
}
}
match fs::rename(&tmp, &dir) {
Ok(()) => Ok(dir),
Err(_) if dir.is_dir() => {
let _ = fs::remove_dir_all(&tmp);
Ok(dir)
}
Err(e) => Err(format!("{} -> {}: {e}", tmp.display(), dir.display())),
}
}
}
fn settle(tmp: &Path, out: &Path) -> Result<(), String> {
match fs::rename(tmp, out) {
Ok(()) => Ok(()),
Err(_) if out.is_file() => {
let _ = fs::remove_file(tmp);
Ok(())
}
Err(e) => Err(format!("{} -> {}: {e}", tmp.display(), out.display())),
}
}
fn short_hash(parts: &[&str]) -> String {
let mut h = Sha256::new();
for p in parts {
h.update(p.as_bytes());
h.update(&[0]);
}
h.finalize()[..8].iter().map(|b| format!("{b:02x}")).collect()
}
fn base_cache_dir() -> Result<PathBuf, String> {
if let Some(d) = std::env::var_os("XDG_CACHE_HOME") {
return Ok(PathBuf::from(d));
}
if cfg!(windows) {
if let Some(d) = std::env::var_os("LOCALAPPDATA") {
return Ok(PathBuf::from(d));
}
}
match std::env::var_os("HOME") {
Some(h) => Ok(PathBuf::from(h).join(".cache")),
None => Err("none of COSMO_HOME, XDG_CACHE_HOME, LOCALAPPDATA or HOME is set".into()),
}
}
fn escape_json(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"")
}
pub fn set_exec(path: &Path) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perm = fs::metadata(path)
.map_err(|e| format!("{}: {e}", path.display()))?
.permissions();
perm.set_mode(perm.mode() | 0o755);
fs::set_permissions(path, perm).map_err(|e| format!("{}: {e}", path.display()))?;
}
let _ = path;
Ok(())
}