use std::ffi::{CStr, CString, c_void};
use std::marker::PhantomData;
use std::ops::Deref;
use std::path::PathBuf;
use std::ptr::NonNull;
use crate::error::{Error, Result};
use crate::loader;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OpenFlags(pub i32);
impl OpenFlags {
pub const LAZY: Self = Self(0x1);
pub const NOW: Self = Self(0x2);
pub const NOLOAD: Self = Self(0x4);
pub const LOCAL: Self = Self(0x0);
pub const GLOBAL: Self = Self(0x100);
pub const NODELETE: Self = Self(0x1000);
}
impl std::ops::BitOr for OpenFlags {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
#[derive(Default)]
pub struct ContextBuilder {
interpreter: Option<PathBuf>,
env: Option<Vec<CString>>,
}
impl ContextBuilder {
pub fn interpreter(mut self, path: impl Into<PathBuf>) -> Self {
self.interpreter = Some(path.into());
self
}
pub fn env(mut self, env: impl IntoIterator<Item = CString>) -> Self {
self.env = Some(env.into_iter().collect());
self
}
pub fn build(self) -> Result<Context> {
let interpreter = match self.interpreter {
Some(path) => path,
None => loader::find_interpreter()?,
};
let _ = (interpreter, self.env);
Err(Error::Unimplemented("loader bootstrap"))
}
}
pub struct Context {
_private: (),
}
impl Context {
pub fn new() -> Result<Self> {
Self::builder().build()
}
pub fn builder() -> ContextBuilder {
ContextBuilder::default()
}
pub fn open(&self, name: &CStr, flags: OpenFlags) -> Result<Library<'_>> {
let handle = self.open_raw(Some(name), flags)?;
Ok(Library { ctx: self, handle })
}
pub fn open_raw(&self, name: Option<&CStr>, flags: OpenFlags) -> Result<NonNull<c_void>> {
let _ = (name, flags);
Err(Error::Unimplemented("dlopen"))
}
pub fn symbol_raw(&self, handle: NonNull<c_void>, name: &CStr) -> Result<NonNull<c_void>> {
let _ = (handle, name);
Err(Error::Unimplemented("dlsym"))
}
pub fn close_raw(&self, handle: NonNull<c_void>) -> Result<()> {
let _ = handle;
Err(Error::Unimplemented("dlclose"))
}
}
pub struct Library<'ctx> {
ctx: &'ctx Context,
handle: NonNull<c_void>,
}
impl<'ctx> Library<'ctx> {
pub unsafe fn symbol<T: Copy>(&self, name: &CStr) -> Result<Symbol<'_, T>> {
const { assert!(size_of::<T>() == size_of::<*mut c_void>()) };
let ptr = self.ctx.symbol_raw(self.handle, name)?;
let value = unsafe { std::mem::transmute_copy::<NonNull<c_void>, T>(&ptr) };
Ok(Symbol {
value,
_lib: PhantomData,
})
}
pub fn as_raw(&self) -> NonNull<c_void> {
self.handle
}
}
impl Drop for Library<'_> {
fn drop(&mut self) {
let _ = self.ctx.close_raw(self.handle);
}
}
pub struct Symbol<'lib, T> {
value: T,
_lib: PhantomData<&'lib ()>,
}
impl<T> Deref for Symbol<'_, T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}