use std::{
ffi::{CString, OsStr, c_int, c_void},
path::{Path, PathBuf},
ptr,
};
use crate::{
error::{Error, Result},
lto::{
api::{
AllSymbolsRead, ClaimFile, Cleanup, LDPO_DYN, LDPO_EXEC, LDPO_PIE,
LDPO_REL, LDPS_OK, LDPT_ADD_INPUT_FILE, LDPT_ADD_SYMBOLS,
LDPT_API_VERSION, LDPT_GET_INPUT_FILE, LDPT_GET_SYMBOLS_V2,
LDPT_GET_VIEW, LDPT_LINKER_OUTPUT, LDPT_MESSAGE, LDPT_NULL,
LDPT_OPTION, LDPT_OUTPUT_NAME, LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK,
LDPT_REGISTER_CLAIM_FILE_HOOK, LDPT_REGISTER_CLEANUP_HOOK,
LDPT_RELEASE_INPUT_FILE, LDPT_SET_EXTRA_LIBRARY_PATH, OnLoad,
Status, Value,
},
dynlib::Library,
session,
},
};
#[derive(Clone, Copy)]
pub enum Output {
Relocatable,
Executable,
Pie,
Shared,
}
impl Output {
const fn tag(self) -> c_int {
match self {
Self::Relocatable => LDPO_REL,
Self::Executable => LDPO_EXEC,
Self::Pie => LDPO_PIE,
Self::Shared => LDPO_DYN,
}
}
}
const PLUGIN_DIRS: &[&str] =
&["/usr/lib64/bfd-plugins", "/usr/lib/bfd-plugins"];
const PLUGIN_NAME: &str = "LLVMgold.so";
#[derive(Default, Clone, Copy)]
pub struct Hooks {
pub claim_file: Option<ClaimFile>,
pub all_symbols_read: Option<AllSymbolsRead>,
pub cleanup: Option<Cleanup>,
}
static mut REGISTERED: Hooks = Hooks {
claim_file: None,
all_symbols_read: None,
cleanup: None,
};
unsafe extern "C" fn register_claim_file(hook: ClaimFile) -> Status {
unsafe { REGISTERED.claim_file = Some(hook) };
LDPS_OK
}
unsafe extern "C" fn register_all_symbols_read(hook: AllSymbolsRead) -> Status {
unsafe { REGISTERED.all_symbols_read = Some(hook) };
LDPS_OK
}
unsafe extern "C" fn register_cleanup(hook: Cleanup) -> Status {
unsafe { REGISTERED.cleanup = Some(hook) };
LDPS_OK
}
pub struct Plugin {
#[allow(dead_code)]
library: Library,
hooks: Hooks,
path: PathBuf,
#[allow(dead_code)]
strings: Vec<CString>,
}
impl Plugin {
pub fn load(
path: &Path,
output: &Path,
kind: Output,
options: &[String],
) -> Result<Self> {
let library = Library::open(path).map_err(|why| {
Error::CommandLine(format!(
"cannot load LTO plugin {}: {why}",
path.display()
))
})?;
let onload = entry(&library, path)?;
let name = output.to_str().ok_or_else(|| {
Error::CommandLine(
"output path is not valid UTF-8, which the LTO plugin \
interface cannot carry"
.to_string(),
)
})?;
let mut strings = Vec::with_capacity(options.len().saturating_add(1));
strings.push(CString::new(name).map_err(|_| {
Error::CommandLine("output path contains a NUL byte".to_string())
})?);
for opt in options {
strings.push(CString::new(opt.as_str()).map_err(|_| {
Error::CommandLine(format!(
"-plugin-opt={opt} contains a NUL byte"
))
})?);
}
let hooks = call_onload(onload, path, kind, &strings)?;
Ok(Self {
library,
hooks,
path: path.to_path_buf(),
strings,
})
}
pub const fn hooks(&self) -> Hooks {
self.hooks
}
pub fn path(&self) -> &Path {
&self.path
}
}
fn entry(library: &Library, path: &Path) -> Result<OnLoad> {
let sym = library.symbol("onload").ok_or_else(|| {
Error::CommandLine(format!(
"{} is not an LTO plugin: it exports no `onload`",
path.display()
))
})?;
Ok(unsafe { std::mem::transmute::<*mut c_void, OnLoad>(sym) })
}
fn call_onload(
onload: OnLoad,
path: &Path,
output: Output,
strings: &[CString],
) -> Result<Hooks> {
let Some((output_name, opts)) = strings.split_first() else {
return Err(Error::Format("LTO plugin strings were not built"));
};
let mut tv: Vec<Value> = vec![
Value {
tag: LDPT_API_VERSION,
payload: ptr::without_provenance_mut(
usize::try_from(crate::lto::api::API_VERSION).unwrap_or(1),
),
},
Value {
tag: LDPT_REGISTER_CLAIM_FILE_HOOK,
payload: register_claim_file as *mut c_void,
},
Value {
tag: LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK,
payload: register_all_symbols_read as *mut c_void,
},
Value {
tag: LDPT_REGISTER_CLEANUP_HOOK,
payload: register_cleanup as *mut c_void,
},
Value {
tag: LDPT_ADD_SYMBOLS,
payload: session::add_symbols as *mut c_void,
},
Value {
tag: LDPT_GET_SYMBOLS_V2,
payload: session::get_symbols as *mut c_void,
},
Value {
tag: LDPT_ADD_INPUT_FILE,
payload: session::add_input_file as *mut c_void,
},
Value {
tag: LDPT_GET_INPUT_FILE,
payload: session::get_input_file as *mut c_void,
},
Value {
tag: LDPT_RELEASE_INPUT_FILE,
payload: session::release_input_file as *mut c_void,
},
Value {
tag: LDPT_GET_VIEW,
payload: session::get_view as *mut c_void,
},
Value {
tag: LDPT_SET_EXTRA_LIBRARY_PATH,
payload: session::set_extra_library_path as *mut c_void,
},
Value {
tag: LDPT_MESSAGE,
payload: session::message as *mut c_void,
},
Value {
tag: LDPT_LINKER_OUTPUT,
payload: ptr::without_provenance_mut(
usize::try_from(output.tag()).unwrap_or(0),
),
},
Value {
tag: LDPT_OUTPUT_NAME,
payload: output_name.as_ptr().cast::<c_void>().cast_mut(),
},
];
for opt in opts {
tv.push(Value {
tag: LDPT_OPTION,
payload: opt.as_ptr().cast::<c_void>().cast_mut(),
});
}
tv.push(Value {
tag: LDPT_NULL,
payload: ptr::null_mut(),
});
unsafe {
REGISTERED = Hooks::default();
}
let status = unsafe { onload(tv.as_mut_ptr()) };
if status != LDPS_OK {
return Err(Error::CommandLine(format!(
"LTO plugin {} refused to load (status {status})",
path.display()
)));
}
let hooks = unsafe { REGISTERED };
if hooks.claim_file.is_none() {
return Err(Error::CommandLine(format!(
"LTO plugin {} registered no claim-file hook, so it can read no \
bitcode",
path.display()
)));
}
Ok(hooks)
}
pub fn resolve(named: Option<&Path>) -> Option<PathBuf> {
if let Some(path) = named {
return Some(path.to_path_buf());
}
for dir in PLUGIN_DIRS {
let candidate = Path::new(OsStr::new(dir)).join(PLUGIN_NAME);
if candidate.is_file() {
return Some(candidate);
}
}
None
}
pub const fn ok(status: c_int) -> bool {
status == LDPS_OK
}