use std::ffi::{CStr, CString, c_char, c_int, c_void};
use std::marker::PhantomData;
use std::ops::Deref;
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::ptr::NonNull;
use std::sync::Mutex;
use crate::error::{Error, Result};
use crate::gate::Gate;
use crate::heap::{self, HeapUsage};
use crate::loader;
use crate::runtime::{self, Runtime};
use crate::thunk::Thunks;
type DlOpen = unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void;
type DlSym = unsafe extern "C" fn(*mut c_void, *const c_char) -> *mut c_void;
type DlClose = unsafe extern "C" fn(*mut c_void) -> c_int;
type DlError = unsafe extern "C" fn() -> *const c_char;
#[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 env = self.env.unwrap_or_else(|| {
std::env::vars_os()
.filter_map(|(k, v)| {
let mut kv = k.as_bytes().to_vec();
kv.push(b'=');
kv.extend_from_slice(v.as_bytes());
CString::new(kv).ok()
})
.collect()
});
let gate: &'static Gate = Box::leak(Box::new(Gate::new()));
let rt: &'static Runtime = Box::leak(Box::new(Runtime::new(loader::page_size())));
let mut thunks = Thunks::default();
let heap_data = &rt.heap as *const _ as usize;
let rt_data = rt as *const Runtime as usize;
let defs = heap::exports()
.into_iter()
.map(|(name, func)| (name, func, heap_data))
.chain(
runtime::exports()
.into_iter()
.map(|(name, func)| (name, func, rt_data)),
)
.map(|(name, func, data)| Ok((name, thunks.bound(func, data)?)))
.collect::<Result<Vec<_>>>()?;
let booted = loader::boot(&interpreter, env, &defs)?;
gate.boot_tp
.store(booted.foreign_tp, std::sync::atomic::Ordering::Release);
rt.heap.set_errno_location(booted.errno_location);
let mut wrap = |target: usize| thunks.outbound(gate, target);
let inner = unsafe {
Inner {
dlopen: std::mem::transmute::<usize, DlOpen>(wrap(booted.dlopen)?),
dlsym: std::mem::transmute::<usize, DlSym>(wrap(booted.dlsym)?),
dlclose: std::mem::transmute::<usize, DlClose>(wrap(booted.dlclose)?),
dlerror: std::mem::transmute::<usize, DlError>(wrap(booted.dlerror)?),
gate,
rt,
thunks: Mutex::new(thunks),
fflush: None,
booted,
}
};
let mut inner = inner;
inner.resolve_libc();
Ok(Context {
inner: Box::leak(Box::new(inner)),
})
}
}
pub struct Context {
inner: &'static Inner,
}
pub(crate) struct Inner {
pub(crate) gate: &'static Gate,
pub(crate) rt: &'static Runtime,
pub(crate) thunks: Mutex<Thunks>,
dlopen: DlOpen,
dlsym: DlSym,
dlclose: DlClose,
dlerror: DlError,
pub(crate) fflush: Option<unsafe extern "C" fn(*mut c_void) -> c_int>,
pub(crate) booted: loader::Booted,
}
impl Inner {
fn resolve_libc(&mut self) {
for lib in [c"libc.so.6", c"libpthread.so.0"] {
let handle =
unsafe { (self.dlopen)(lib.as_ptr(), OpenFlags::LAZY.0 | OpenFlags::NOLOAD.0) };
if handle.is_null() {
continue;
}
unsafe {
let create = (self.dlsym)(handle, c"pthread_create".as_ptr());
if !create.is_null() {
self.rt.set_pthread_create(create as usize);
}
let fflush = (self.dlsym)(handle, c"fflush".as_ptr());
if self.fflush.is_none() && !fflush.is_null() {
let mut thunks = self.thunks.lock().unwrap_or_else(|e| e.into_inner());
if let Ok(t) = thunks.outbound(self.gate, fflush as usize) {
self.fflush = Some(std::mem::transmute::<
usize,
unsafe extern "C" fn(*mut c_void) -> c_int,
>(t));
}
}
(self.dlclose)(handle);
}
}
}
fn last_error(&self, fallback: &str) -> Error {
let msg = unsafe { (self.dlerror)() };
if msg.is_null() {
Error::Dl(fallback.to_owned())
} else {
Error::Dl(
unsafe { CStr::from_ptr(msg) }
.to_string_lossy()
.into_owned(),
)
}
}
}
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 unload(self) -> std::result::Result<(), (Self, Error)> {
if let Err(e) = unsafe { self.inner.unload() } {
return Err((self, e));
}
unsafe {
let inner = Box::from_raw(self.inner as *const Inner as *mut Inner);
drop(Box::from_raw(inner.gate as *const Gate as *mut Gate));
drop(Box::from_raw(inner.rt as *const Runtime as *mut Runtime));
}
Ok(())
}
pub fn heap_usage(&self) -> HeapUsage {
self.inner.rt.heap.usage()
}
pub fn global(&self) -> Result<Library<'_>> {
let handle = self.open_raw(None, OpenFlags::LAZY)?;
Ok(Library { ctx: self, handle })
}
pub unsafe fn callback<F: Copy>(&self, f: F) -> Result<Callback<'_, F>> {
const { assert!(size_of::<F>() == size_of::<*mut c_void>()) };
let raw = unsafe { std::mem::transmute_copy::<F, NonNull<c_void>>(&f) };
let thunk = self.callback_raw(raw)?;
let thunk_fn = unsafe { std::mem::transmute_copy::<NonNull<c_void>, F>(&thunk) };
Ok(Callback {
ctx: self,
thunk,
thunk_fn,
})
}
pub fn callback_raw(&self, f: NonNull<c_void>) -> Result<NonNull<c_void>> {
let mut thunks = self.inner.thunks.lock().unwrap_or_else(|e| e.into_inner());
let thunk = thunks.inbound(self.inner.gate, f.as_ptr() as usize)?;
Ok(NonNull::new(thunk as *mut c_void).expect("thunk address"))
}
pub fn free_callback_raw(&self, thunk: NonNull<c_void>) {
let _ = thunk;
}
pub fn open_raw(&self, name: Option<&CStr>, flags: OpenFlags) -> Result<NonNull<c_void>> {
let name_ptr = name.map_or(std::ptr::null(), CStr::as_ptr);
self.inner.gate.with(|| {
let handle = unsafe { (self.inner.dlopen)(name_ptr, flags.0) };
NonNull::new(handle).ok_or_else(|| self.inner.last_error("dlopen failed"))
})
}
pub fn symbol_raw(&self, handle: NonNull<c_void>, name: &CStr) -> Result<NonNull<c_void>> {
let target = self.inner.gate.with(|| {
let sym = unsafe { (self.inner.dlsym)(handle.as_ptr(), name.as_ptr()) };
NonNull::new(sym).ok_or_else(|| self.inner.last_error("dlsym failed"))
})?;
let mut thunks = self.inner.thunks.lock().unwrap_or_else(|e| e.into_inner());
let thunk = thunks.outbound(self.inner.gate, target.as_ptr() as usize)?;
Ok(NonNull::new(thunk as *mut c_void).expect("thunk address"))
}
pub fn close_raw(&self, handle: NonNull<c_void>) -> Result<()> {
self.inner.gate.with(|| {
match unsafe { (self.inner.dlclose)(handle.as_ptr()) } {
0 => Ok(()),
_ => Err(self.inner.last_error("dlclose failed")),
}
})
}
}
pub struct Library<'ctx> {
ctx: &'ctx Context,
handle: NonNull<c_void>,
}
unsafe impl Send for Library<'_> {}
unsafe impl Sync for Library<'_> {}
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
}
}
pub struct Callback<'ctx, F> {
ctx: &'ctx Context,
thunk: NonNull<c_void>,
thunk_fn: F,
}
impl<F> Deref for Callback<'_, F> {
type Target = F;
fn deref(&self) -> &F {
&self.thunk_fn
}
}
impl<F> Drop for Callback<'_, F> {
fn drop(&mut self) {
self.ctx.free_callback_raw(self.thunk);
}
}
unsafe impl<F: Send> Send for Callback<'_, F> {}
unsafe impl<F: Sync> Sync for Callback<'_, F> {}