use std::{
ffi::{CStr, c_char, c_int, c_uint, c_void},
path::PathBuf,
sync::{Mutex, OnceLock},
};
use crate::lto::api::{
self, InputFile, LDPR_UNKNOWN, LDPS_ERR, LDPS_OK, Status, Symbol,
};
pub struct PluginSymbol {
pub name: Vec<u8>,
pub kind: c_uint,
pub visibility: c_uint,
pub size: u64,
pub comdat: Option<Vec<u8>>,
pub resolution: c_int,
}
pub struct Claimed {
pub handle: usize,
pub path: PathBuf,
pub bytes: Vec<u8>,
pub symbols: Vec<PluginSymbol>,
}
#[derive(Default)]
pub struct State {
pub claimed: Vec<Claimed>,
pub next_handle: usize,
pub added: Vec<PathBuf>,
pub library_paths: Vec<PathBuf>,
}
impl State {
pub fn reserve(&mut self) -> usize {
self.next_handle = self.next_handle.saturating_add(1);
self.next_handle
}
fn find(&mut self, handle: usize) -> Option<&mut Claimed> {
self.claimed.iter_mut().find(|file| file.handle == handle)
}
}
static SESSION: OnceLock<Mutex<State>> = OnceLock::new();
pub fn session() -> &'static Mutex<State> {
SESSION.get_or_init(|| Mutex::new(State::default()))
}
fn with_state(body: impl FnOnce(&mut State) -> Status) -> Status {
session()
.lock()
.map_or(LDPS_ERR, |mut state| body(&mut state))
}
fn copy_c_str(ptr: *const c_char) -> Option<Vec<u8>> {
if ptr.is_null() {
return None;
}
Some(unsafe { CStr::from_ptr(ptr) }.to_bytes().to_vec())
}
pub unsafe extern "C" fn message(level: c_int, format: *const c_char, _: ...) {
let text = copy_c_str(format).map_or_else(
|| "(no message)".to_string(),
|bytes| String::from_utf8_lossy(&bytes).into_owned(),
);
let severity = match level {
api::LDPL_INFO => "info",
api::LDPL_WARNING => "warning",
api::LDPL_FATAL => "fatal",
_ => "error",
};
eprintln!("xold: LTO plugin {severity}: {text}");
}
pub unsafe extern "C" fn add_symbols(
handle: *mut c_void,
count: c_int,
syms: *const Symbol,
) -> Status {
let Ok(count) = usize::try_from(count) else {
return LDPS_ERR;
};
if syms.is_null() && count != 0 {
return LDPS_ERR;
}
let handle = handle as usize;
with_state(|state| {
let mut collected = Vec::with_capacity(count);
for index in 0..count {
let sym = unsafe { &*syms.add(index) };
let Some(name) = copy_c_str(sym.name) else {
return LDPS_ERR;
};
collected.push(PluginSymbol {
name,
kind: c_uint::try_from(sym.def).unwrap_or(api::LDPK_UNDEF),
visibility: sym.visibility,
size: sym.size,
comdat: copy_c_str(sym.comdat_key),
resolution: LDPR_UNKNOWN.cast_signed(),
});
}
let Some(file) = state.find(handle) else {
return LDPS_ERR;
};
file.symbols = collected;
LDPS_OK
})
}
pub unsafe extern "C" fn get_symbols(
handle: *const c_void,
count: c_int,
syms: *mut Symbol,
) -> Status {
let Ok(count) = usize::try_from(count) else {
return LDPS_ERR;
};
if syms.is_null() && count != 0 {
return LDPS_ERR;
}
let handle = handle as usize;
with_state(|state| {
let Some(file) = state.find(handle) else {
return LDPS_ERR;
};
if file.symbols.len() != count {
return LDPS_ERR;
}
for (index, sym) in file.symbols.iter().enumerate() {
unsafe { (*syms.add(index)).resolution = sym.resolution };
}
LDPS_OK
})
}
pub unsafe extern "C" fn add_input_file(path: *const c_char) -> Status {
let Some(bytes) = copy_c_str(path) else {
return LDPS_ERR;
};
with_state(|state| {
state
.added
.push(PathBuf::from(String::from_utf8_lossy(&bytes).into_owned()));
LDPS_OK
})
}
pub unsafe extern "C" fn set_extra_library_path(path: *const c_char) -> Status {
let Some(bytes) = copy_c_str(path) else {
return LDPS_ERR;
};
with_state(|state| {
state
.library_paths
.push(PathBuf::from(String::from_utf8_lossy(&bytes).into_owned()));
LDPS_OK
})
}
pub unsafe extern "C" fn get_input_file(
handle: *const c_void,
file: *mut InputFile,
) -> Status {
if file.is_null() {
return LDPS_ERR;
}
let handle = handle as usize;
with_state(|state| {
let Some(claimed) = state.find(handle) else {
return LDPS_ERR;
};
let Ok(size) = i64::try_from(claimed.bytes.len()) else {
return LDPS_ERR;
};
unsafe {
(*file).name = std::ptr::null();
(*file).fd = -1;
(*file).offset = 0;
(*file).filesize = size;
(*file).handle = handle as *mut c_void;
}
LDPS_OK
})
}
pub unsafe extern "C" fn release_input_file(_handle: *const c_void) -> Status {
LDPS_OK
}
pub unsafe extern "C" fn get_view(
handle: *const c_void,
view: *mut *mut c_void,
) -> Status {
if view.is_null() {
return LDPS_ERR;
}
let handle = handle as usize;
with_state(|state| {
let Some(claimed) = state.find(handle) else {
return LDPS_ERR;
};
let ptr = claimed.bytes.as_ptr().cast::<c_void>().cast_mut();
unsafe { *view = ptr };
LDPS_OK
})
}