1use std::fmt;
5
6#[derive(Clone, Debug, PartialEq, Eq)]
8pub enum LoadError {
9 Open { library: String, reason: String },
12 Missing { library: String, symbol: String },
14 Unsupported,
16}
17
18impl fmt::Display for LoadError {
19 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20 match self {
21 Self::Open { library, reason } => write!(formatter, "opening {library}: {reason}"),
22 Self::Missing { library, symbol } => write!(formatter, "{library} has no {symbol}"),
23 Self::Unsupported => formatter.write_str("this target loads no libraries"),
24 }
25 }
26}
27
28impl std::error::Error for LoadError {}
29
30pub unsafe fn entry<T: Copy>(library: &str, symbol: &str) -> Result<T, LoadError> {
45 let address = imp::open(library, symbol)?;
46 if size_of::<T>() != size_of::<*const ()>() {
47 return Err(LoadError::Missing {
48 library: library.to_owned(),
49 symbol: format!("{symbol} as a {}-byte entry", size_of::<T>()),
50 });
51 }
52 Ok(unsafe { std::mem::transmute_copy::<*const (), T>(&address) })
55}
56
57#[cfg(unix)]
58mod imp {
59 use std::ffi::{CStr, CString, c_void};
60 use std::sync::{Mutex, PoisonError};
61
62 use super::LoadError;
63
64 struct Handle(*mut c_void);
66
67 unsafe impl Send for Handle {}
69
70 static OPEN: Mutex<Vec<(String, Handle)>> = Mutex::new(Vec::new());
71
72 pub(super) fn open(library: &str, symbol: &str) -> Result<*const (), LoadError> {
73 let symbol_name = CString::new(symbol).map_err(|_| LoadError::Missing {
74 library: library.to_owned(),
75 symbol: symbol.to_owned(),
76 })?;
77 let mut open = OPEN.lock().unwrap_or_else(PoisonError::into_inner);
78 let handle = if let Some((_, handle)) = open.iter().find(|(name, _)| name == library) {
79 handle.0
80 } else {
81 let name = CString::new(library).map_err(|_| LoadError::Open {
82 library: library.to_owned(),
83 reason: "the name holds a nul".to_owned(),
84 })?;
85 let handle = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
89 if handle.is_null() {
90 return Err(LoadError::Open {
91 library: library.to_owned(),
92 reason: last_error(),
93 });
94 }
95 open.push((library.to_owned(), Handle(handle)));
96 handle
97 };
98 drop(open);
99 let address = unsafe { libc::dlsym(handle, symbol_name.as_ptr()) };
102 if address.is_null() {
103 return Err(LoadError::Missing {
104 library: library.to_owned(),
105 symbol: symbol.to_owned(),
106 });
107 }
108 Ok(address.cast_const().cast::<()>())
109 }
110
111 fn last_error() -> String {
112 let error = unsafe { libc::dlerror() };
115 if error.is_null() {
116 return "unknown error".to_owned();
117 }
118 unsafe { CStr::from_ptr(error) }
120 .to_string_lossy()
121 .into_owned()
122 }
123}
124
125#[cfg(not(unix))]
126mod imp {
127 use super::LoadError;
128
129 pub(super) fn open(_library: &str, _symbol: &str) -> Result<*const (), LoadError> {
130 Err(LoadError::Unsupported)
131 }
132}
133
134#[cfg(all(test, unix))]
135mod tests {
136 use super::*;
137
138 #[test]
139 fn a_missing_library_or_entry_is_an_error_not_a_crash() {
140 let missing = unsafe { entry::<fn()>("libtilo_no_such_engine.so", "tilo_no_such_entry") };
142 assert!(
143 matches!(missing, Err(LoadError::Open { ref library, .. }) if library == "libtilo_no_such_engine.so"),
144 "{missing:?}"
145 );
146 let absent = unsafe { entry::<fn()>("libc.so.6", "tilo_no_such_entry") };
148 assert!(
149 matches!(absent, Err(LoadError::Missing { .. })),
150 "{absent:?}"
151 );
152 for _ in 0..2 {
154 let getpid =
156 unsafe { entry::<unsafe extern "C" fn() -> libc::pid_t>("libc.so.6", "getpid") }
157 .expect("libc has getpid");
158 assert_eq!(
160 unsafe { getpid() },
161 i32::try_from(std::process::id()).unwrap()
162 );
163 }
164 }
165}