crate_plugin_kit/loader/open.rs
1//! Opening a cdylib and resolving its entry symbol.
2//!
3//! The whole `dlopen` surface: a `Library` handle that is kept alive by the returned
4//! [`LoadedPlugin`], the entry function looked up by name, and the platform-specific
5//! "there is no such symbol" error turned into its own variant.
6//!
7//! All of it is unsafe by nature — the file being opened, and the layout of `T`, are
8//! both assumptions this crate cannot check.
9
10use std::path::{Path, PathBuf};
11
12use libloading::Library;
13
14use crate::error::{KitError, KitResult};
15
16/// A loaded plugin.
17///
18/// Holds the `Library` handle — dropping this struct unloads the plugin. So keep it
19/// alive for as long as anything exported by it is still in use.
20pub struct LoadedPlugin<T> {
21 /// Must be held. The field exists to keep the library alive until the struct is
22 /// dropped.
23 _lib: Library,
24 entry: *const T,
25 path: PathBuf,
26}
27
28impl<T> LoadedPlugin<T> {
29 /// Pointer to the entry struct.
30 ///
31 /// # Safety
32 ///
33 /// The caller guarantees that the layout of `T` matches the struct exported by
34 /// the plugin. This crate cannot verify that — it is the job of the host's
35 /// `abi_version` field.
36 pub fn entry(&self) -> *const T {
37 self.entry
38 }
39
40 /// Dynamic library file path.
41 pub fn path(&self) -> &Path {
42 &self.path
43 }
44}
45
46// `Send` / `Sync` are deliberately not implemented: `T` holds raw function pointers,
47// and this crate has no way to know whether the code they point to is thread-safe.
48// A host that needs to pass one across threads should say so explicitly with
49// `unsafe impl`.
50
51/// Opens a cdylib and calls its entry function.
52///
53/// # Safety
54///
55/// - `path` must point at a plugin installed by this kit (or a layout-equivalent
56/// dynamic library);
57/// - `T` must have the same layout as the struct that plugin exports.
58///
59/// # Errors
60///
61/// - [`KitError::LibraryLoad`]: `dlopen` failed.
62/// - [`KitError::SymbolMissing`]: there is no exported symbol named `symbol`.
63/// - [`KitError::NullEntry`]: the entry function returned a null pointer.
64pub unsafe fn open<T>(path: &Path, symbol: &[u8]) -> KitResult<LoadedPlugin<T>> {
65 let lib = Library::new(path).map_err(|source| KitError::LibraryLoad {
66 path: path.to_path_buf(),
67 source: Box::new(source),
68 })?;
69
70 let entry = {
71 let f: libloading::Symbol<'_, unsafe extern "C" fn() -> *const T> =
72 lib.get(symbol).map_err(|source| {
73 if is_symbol_not_found(&source) {
74 // "The library does not have this symbol" is a common case (the
75 // wrong thing was installed, or a different plugin was), and
76 // reporting it separately reads much better than a vague "load
77 // failed".
78 KitError::SymbolMissing {
79 symbol: String::from_utf8_lossy(symbol).into_owned(),
80 }
81 } else {
82 KitError::LibraryLoad {
83 path: path.to_path_buf(),
84 source: Box::new(source),
85 }
86 }
87 })?;
88 f()
89 };
90
91 if entry.is_null() {
92 return Err(KitError::NullEntry);
93 }
94
95 Ok(LoadedPlugin {
96 _lib: lib,
97 entry,
98 path: path.to_path_buf(),
99 })
100}
101
102/// The `libloading` errors that mean "the library does not have this symbol"; the
103/// variant names differ per platform:
104///
105/// | Platform | Variants |
106/// | ---- | ---- |
107/// | Unix | `DlSym` / `DlSymUnknown` |
108/// | Windows | `GetProcAddress` / `GetProcAddressUnknown` |
109///
110/// The variants only exist on their own platform, so the match is split by `cfg`.
111fn is_symbol_not_found(e: &libloading::Error) -> bool {
112 #[cfg(unix)]
113 {
114 matches!(
115 e,
116 libloading::Error::DlSym { .. } | libloading::Error::DlSymUnknown
117 )
118 }
119
120 #[cfg(windows)]
121 {
122 matches!(
123 e,
124 libloading::Error::GetProcAddress { .. } | libloading::Error::GetProcAddressUnknown
125 )
126 }
127
128 #[cfg(not(any(unix, windows)))]
129 {
130 let _ = e;
131 false
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 /// Opening a file that is not a dynamic library at all must report
140 /// `LibraryLoad`, not panic.
141 #[test]
142 fn opening_a_non_library_reports_an_error() {
143 let dir = tempfile::tempdir().unwrap();
144 let path = dir.path().join("garbage.bin");
145 std::fs::write(&path, b"this is not a shared object").unwrap();
146
147 // SAFETY: the point here is to make it fail; no layout assumption is involved.
148 let got = unsafe { open::<u32>(&path, b"whatever") };
149 assert!(
150 matches!(got, Err(KitError::LibraryLoad { .. })),
151 "expected LibraryLoad, got {:?}",
152 got.err()
153 );
154 }
155}