use std::{ffi::CString, path::Path};
use crate::{
error::{Error, Result},
lto::{
api::{InputFile, LDPS_OK},
plugin::Plugin,
session::{self, Claimed},
},
};
pub struct Claimer<'p> {
plugin: &'p Plugin,
}
#[derive(Debug, Eq, PartialEq)]
pub enum Offer {
Claimed { handle: usize, symbols: usize },
Declined,
}
impl<'p> Claimer<'p> {
pub const fn new(plugin: &'p Plugin) -> Self {
Self { plugin }
}
pub fn offer(&self, path: &Path, bytes: Vec<u8>) -> Result<Offer> {
let Some(claim) = self.plugin.hooks().claim_file else {
return Ok(Offer::Declined);
};
let name = CString::new(path.to_string_lossy().into_owned()).map_err(
|_| {
Error::CommandLine("input path contains a NUL byte".to_string())
},
)?;
let size = i64::try_from(bytes.len())
.map_err(|_| Error::OutOfRange("LTO input size"))?;
let handle = register(path, bytes)?;
let file = InputFile {
name: name.as_ptr(),
fd: -1,
offset: 0,
filesize: size,
handle: std::ptr::without_provenance_mut(handle),
};
let mut claimed: std::ffi::c_int = 0;
let status = unsafe { claim(&raw const file, &raw mut claimed) };
if status != LDPS_OK {
forget(handle);
return Err(Error::CommandLine(format!(
"LTO plugin {} failed to read {}: the bitcode may have been \
written by a different LLVM version",
self.plugin.path().display(),
path.display()
)));
}
if claimed == 0 {
forget(handle);
return Ok(Offer::Declined);
}
Ok(Offer::Claimed {
handle,
symbols: symbol_count(handle),
})
}
}
fn register(path: &Path, bytes: Vec<u8>) -> Result<usize> {
let mut state = session::session()
.lock()
.map_err(|_| Error::Format("LTO session lock was poisoned"))?;
let handle = state.reserve();
state.claimed.push(Claimed {
handle,
path: path.to_path_buf(),
bytes,
symbols: Vec::new(),
});
Ok(handle)
}
fn forget(handle: usize) {
if let Ok(mut state) = session::session().lock() {
state.claimed.retain(|file| file.handle != handle);
}
}
fn symbol_count(handle: usize) -> usize {
session::session().lock().map_or(0, |state| {
state
.claimed
.iter()
.find(|file| file.handle == handle)
.map_or(0, |file| file.symbols.len())
})
}