crates/edge/cli/src/templates/library/ffi.rs.in 4.8 KiB 145 lines Raw
1 //! The foreign-library boundary.2 //!3 //! Every `unsafe` block in this bundle is here. A real bundle replaces the4 //! placeholder exports in `engine/engine.c` with a thin C adapter over the5 //! library it hosts.6 //! The Rust side stays one safe `Plugin` and never sees a namespace of the7 //! engine's internals.8 9 use std::ffi::{CStr, CString};10 use std::os::fd::{AsRawFd, OwnedFd};11 use std::os::raw::{c_char, c_int, c_void};12 use std::path::Path;13 14 #[link(name = "dl")]15 unsafe extern "C" {16     fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void;17     fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;18     fn dlclose(handle: *mut c_void) -> c_int;19     fn dlerror() -> *mut c_char;20 }21 22 const RTLD_NOW: c_int = 2;23 const RTLD_LOCAL: c_int = 0;24 const ABI_VERSION: u32 = 1;25 26 type Abi = unsafe extern "C" fn() -> u32;27 type OpenFromFd = unsafe extern "C" fn(c_int) -> *mut c_void;28 type Generate = unsafe extern "C" fn(*mut c_void, *const u8, usize, *mut u8, usize) -> isize;29 type Close = unsafe extern "C" fn(*mut c_void);30 31 /// One loaded engine. The C handle is opaque here.32 pub struct Native {33     lib: *mut c_void,34     handle: *mut c_void,35     generate: Generate,36     close: Close,37 }38 39 // The engine is used under the plugin mutex and `max_inflight` is one. The40 // raw pointer never escapes this struct.41 unsafe impl Send for Native {}42 43 impl Native {44     /// Loads the library and opens an engine over the first granted weight45     /// descriptor. The C side takes ownership of a duplicate of that fd.46     pub fn open(path: &Path, weight: Option<&OwnedFd>) -> Result<Native, String> {47         let name = CString::new(path.as_os_str().as_encoded_bytes().to_vec())48             .map_err(|_| "the library path contains a NUL".to_string())?;49         // SAFETY: `name` is NUL-terminated and lives for the call. The handle50         // is closed by `Drop`.51         unsafe {52             let lib = dlopen(name.as_ptr(), RTLD_NOW | RTLD_LOCAL);53             if lib.is_null() {54                 return Err(last_error());55             }56             match Native::from_lib(lib, weight) {57                 Ok(native) => Ok(native),58                 Err(why) => {59                     let _ = dlclose(lib);60                     Err(why)61                 }62             }63         }64     }65 66     unsafe fn from_lib(lib: *mut c_void, weight: Option<&OwnedFd>) -> Result<Native, String> {67         let abi: Abi = unsafe { symbol(lib, b"inf3r_engine_abi\0")? };68         let open_from_fd: OpenFromFd = unsafe { symbol(lib, b"inf3r_engine_open_fd\0")? };69         let generate: Generate = unsafe { symbol(lib, b"inf3r_engine_generate\0")? };70         let close: Close = unsafe { symbol(lib, b"inf3r_engine_close\0")? };71         if unsafe { abi() } != ABI_VERSION {72             return Err(format!("the engine ABI is not {ABI_VERSION}"));73         }74 75         let owned = match weight {76             Some(fd) => Some(fd.try_clone().map_err(|why| why.to_string())?),77             None => None,78         };79         let raw = owned.as_ref().map_or(-1, AsRawFd::as_raw_fd);80         let handle = unsafe { open_from_fd(raw) };81         if handle.is_null() {82             return Err("the engine refused the weight descriptor".to_string());83         }84         if let Some(owned) = owned {85             // The C side closes its duplicate in `inf3r_engine_close`.86             std::mem::forget(owned);87         }88         Ok(Native {89             lib,90             handle,91             generate,92             close,93         })94     }95 96     pub fn generate(&self, prompt: &[u8]) -> Result<Vec<u8>, String> {97         let mut out = vec![0u8; 1 << 16];98         let n = unsafe {99             (self.generate)(100                 self.handle,101                 prompt.as_ptr(),102                 prompt.len(),103                 out.as_mut_ptr(),104                 out.len(),105             )106         };107         if n < 0 {108             return Err("the engine failed to generate".to_string());109         }110         out.truncate(n as usize);111         Ok(out)112     }113 }114 115 impl Drop for Native {116     fn drop(&mut self) {117         if !self.handle.is_null() {118             unsafe { (self.close)(self.handle) };119         }120         unsafe {121             let _ = dlclose(self.lib);122         }123     }124 }125 126 /// One exported symbol, with the exact type that the C header promises.127 unsafe fn symbol<T: Copy>(lib: *mut c_void, name: &[u8]) -> Result<T, String> {128     let raw = unsafe { dlsym(lib, name.as_ptr().cast()) };129     if raw.is_null() {130         return Err(unsafe { last_error() });131     }132     // SAFETY: the caller names the symbol and its type together. The type is133     // a function pointer of the same size as the loader's pointer.134     Ok(unsafe { std::mem::transmute_copy(&raw) })135 }136 137 unsafe fn last_error() -> String {138     let why = unsafe { dlerror() };139     if why.is_null() {140         return "the loader gave no reason".to_string();141     }142     unsafe { CStr::from_ptr(why) }143         .to_string_lossy()144         .into_owned()145 }