Skip to main content

tilo_process/
library.rs

1//! Libraries this process opens at run time: code beside the runtime that only some processes
2//! need, reached through one exported entry whose type the caller defines.
3
4use std::fmt;
5
6/// Why a library's entry could not be reached.
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub enum LoadError {
9    /// The loader could not open the library (it is missing from the
10    /// runtime bundle, or does not link against this runtime).
11    Open { library: String, reason: String },
12    /// The library has no such entry.
13    Missing { library: String, symbol: String },
14    /// This target opens no libraries at run time.
15    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
30/// The entry `symbol` of library `library` (its file name, as the dynamic loader finds it),
31/// opening the library the first time. A library opened here is never closed: what it hands out
32/// lives as long as the process.
33///
34/// # Errors
35///
36/// [`LoadError`] when the library does not open or lacks the entry, and for
37/// a `T` that is not the size of a function pointer.
38///
39/// # Safety
40///
41/// `T` must be the type of the function `symbol` names: a `fn` pointer type,
42/// spelled from the same definition the library's entry is checked against,
43/// in a library built with this runtime.
44pub 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    // SAFETY: the caller guarantees `T` is the entry's function pointer
53    // type, which has the size checked above; `address` is that function.
54    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    /// An open library. Never closed: the process uses what it handed out.
65    struct Handle(*mut c_void);
66
67    // SAFETY: a `dlopen` handle may be used from any thread.
68    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            // SAFETY: `name` is a C string. Local symbols: the engine's
86            // own crates bind inside it (it links with -Bsymbolic), and
87            // nothing later resolves against them by accident.
88            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        // SAFETY: `handle` is an open library (never closed) and
100        // `symbol_name` a C string.
101        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        // SAFETY: dlerror returns null or a C string valid until the next
113        // dl* call on this thread, copied out at once.
114        let error = unsafe { libc::dlerror() };
115        if error.is_null() {
116            return "unknown error".to_owned();
117        }
118        // SAFETY: non-null, nul-terminated, see above.
119        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        // SAFETY: nothing is called through the result.
141        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        // SAFETY: as above.
147        let absent = unsafe { entry::<fn()>("libc.so.6", "tilo_no_such_entry") };
148        assert!(
149            matches!(absent, Err(LoadError::Missing { .. })),
150            "{absent:?}"
151        );
152        // A real function of it is found, opened once however often asked.
153        for _ in 0..2 {
154            // SAFETY: `getpid` has this C signature.
155            let getpid =
156                unsafe { entry::<unsafe extern "C" fn() -> libc::pid_t>("libc.so.6", "getpid") }
157                    .expect("libc has getpid");
158            // SAFETY: getpid has no preconditions.
159            assert_eq!(
160                unsafe { getpid() },
161                i32::try_from(std::process::id()).unwrap()
162            );
163        }
164    }
165}