crate_plugin_kit/loader.rs
1//! Generic `dlopen` loading.
2//!
3//! # No type erasure here
4//!
5//! `T` is the host's own `#[repr(C)]` entry struct (for bmux, that is
6//! `BmuxPluginV1`). `load()` returns a `*const T` — a thin pointer, not a `dyn Trait`
7//! — so there is no "convert a fat pointer between two different vtables" UB.
8//!
9//! This crate neither knows nor needs to know which fields `T` has; it only reads
10//! the symbol address and casts it to `*const T`. Reading those fields safely is the
11//! host contract crate's job.
12//!
13//! # What the caller has to guarantee
14//!
15//! 1. `T` and the struct the plugin actually exports have the same layout (backed by
16//! the host's `abi_version` field);
17//! 2. every read of a field of `T` is wrapped in [`crate::panic::guard`].
18
19use std::path::{Path, PathBuf};
20
21use libloading::Library;
22
23use crate::error::{KitError, KitResult};
24
25/// A loaded plugin.
26///
27/// Holds the `Library` handle — dropping this struct unloads the plugin. So keep it
28/// alive for as long as anything exported by it is still in use.
29pub struct LoadedPlugin<T> {
30 /// Must be held. The field exists to keep the library alive until the struct is
31 /// dropped.
32 _lib: Library,
33 entry: *const T,
34 path: PathBuf,
35}
36
37impl<T> LoadedPlugin<T> {
38 /// Pointer to the entry struct.
39 ///
40 /// # Safety
41 ///
42 /// The caller guarantees that the layout of `T` matches the struct exported by
43 /// the plugin. This crate cannot verify that — it is the job of the host's
44 /// `abi_version` field.
45 pub fn entry(&self) -> *const T {
46 self.entry
47 }
48
49 /// Dynamic library file path.
50 pub fn path(&self) -> &Path {
51 &self.path
52 }
53}
54
55// `Send` / `Sync` are deliberately not implemented: `T` holds raw function pointers,
56// and this crate has no way to know whether the code they point to is thread-safe.
57// A host that needs to pass one across threads should say so explicitly with
58// `unsafe impl`.
59
60/// Opens a cdylib and calls its entry function.
61///
62/// # Safety
63///
64/// - `path` must point at a plugin installed by this kit (or a layout-equivalent
65/// dynamic library);
66/// - `T` must have the same layout as the struct that plugin exports.
67///
68/// # Errors
69///
70/// - [`KitError::LibraryLoad`]: `dlopen` failed.
71/// - [`KitError::SymbolMissing`]: there is no exported symbol named `symbol`.
72/// - [`KitError::NullEntry`]: the entry function returned a null pointer.
73pub unsafe fn open<T>(path: &Path, symbol: &[u8]) -> KitResult<LoadedPlugin<T>> {
74 let lib = Library::new(path).map_err(|source| KitError::LibraryLoad {
75 path: path.to_path_buf(),
76 source: Box::new(source),
77 })?;
78
79 let entry = {
80 let f: libloading::Symbol<'_, unsafe extern "C" fn() -> *const T> =
81 lib.get(symbol).map_err(|source| {
82 if is_symbol_not_found(&source) {
83 // "The library does not have this symbol" is a common case (the
84 // wrong thing was installed, or a different plugin was), and
85 // reporting it separately reads much better than a vague "load
86 // failed".
87 KitError::SymbolMissing {
88 symbol: String::from_utf8_lossy(symbol).into_owned(),
89 }
90 } else {
91 KitError::LibraryLoad {
92 path: path.to_path_buf(),
93 source: Box::new(source),
94 }
95 }
96 })?;
97 f()
98 };
99
100 if entry.is_null() {
101 return Err(KitError::NullEntry);
102 }
103
104 Ok(LoadedPlugin {
105 _lib: lib,
106 entry,
107 path: path.to_path_buf(),
108 })
109}
110
111/// The `libloading` errors that mean "the library does not have this symbol"; the
112/// variant names differ per platform:
113///
114/// | Platform | Variants |
115/// | ---- | ---- |
116/// | Unix | `DlSym` / `DlSymUnknown` |
117/// | Windows | `GetProcAddress` / `GetProcAddressUnknown` |
118///
119/// The variants only exist on their own platform, so the match is split by `cfg`.
120fn is_symbol_not_found(e: &libloading::Error) -> bool {
121 #[cfg(unix)]
122 {
123 matches!(
124 e,
125 libloading::Error::DlSym { .. } | libloading::Error::DlSymUnknown
126 )
127 }
128
129 #[cfg(windows)]
130 {
131 matches!(
132 e,
133 libloading::Error::GetProcAddress { .. } | libloading::Error::GetProcAddressUnknown
134 )
135 }
136
137 #[cfg(not(any(unix, windows)))]
138 {
139 let _ = e;
140 false
141 }
142}
143
144/// The cdylib file name candidates for this platform, in priority order.
145///
146/// Other platforms' spellings are listed as well, so that when a wrong-platform
147/// artifact sits in the install dir the error message can show what was tried
148/// instead of only saying "not found".
149pub fn library_candidates(stem: &str) -> Vec<String> {
150 let mut out = Vec::new();
151
152 match std::env::consts::OS {
153 "windows" => out.push(format!("{stem}.dll")),
154 "macos" => out.push(format!("lib{stem}.dylib")),
155 _ => out.push(format!("lib{stem}.so")),
156 }
157
158 // Fallbacks: some build systems (or hand-made archives) omit the `lib` prefix
159 // or use a different extension.
160 for ext in ["so", "dylib", "dll"] {
161 for name in [format!("lib{stem}.{ext}"), format!("{stem}.{ext}")] {
162 if !out.contains(&name) {
163 out.push(name);
164 }
165 }
166 }
167
168 out
169}
170
171/// Finds a cdylib in a directory by walking the candidate list, returning the first
172/// one that exists.
173pub fn find_library(dir: &Path, stem: &str) -> KitResult<PathBuf> {
174 let candidates = library_candidates(stem);
175
176 for name in &candidates {
177 let p = dir.join(name);
178 if p.is_file() {
179 return Ok(p);
180 }
181 }
182
183 Err(KitError::LibraryNotFound {
184 name: stem.to_string(),
185 tried: candidates.join(", "),
186 })
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 /// This platform's file name must come first in the candidate list, otherwise a
194 /// wrong-platform artifact would win.
195 #[test]
196 fn the_current_platform_name_comes_first() {
197 let c = library_candidates("myapp_plugin_foo");
198 let first = c.first().expect("candidate list must not be empty");
199
200 let expected = match std::env::consts::OS {
201 "windows" => "myapp_plugin_foo.dll",
202 "macos" => "libmyapp_plugin_foo.dylib",
203 _ => "libmyapp_plugin_foo.so",
204 };
205 assert_eq!(first, expected);
206 }
207
208 /// The fallback entries must cover every platform spelling — that is what makes
209 /// the "tried" list in the error meaningful when a wrong-platform artifact is
210 /// sitting in the directory.
211 #[test]
212 fn candidates_cover_every_platform_spelling() {
213 let c = library_candidates("stem");
214 for name in [
215 "stem.dll",
216 "libstem.dylib",
217 "libstem.so",
218 "stem.so",
219 "stem.dylib",
220 "libstem.dll",
221 ] {
222 assert!(
223 c.iter().any(|x| x == name),
224 "candidate missing {name}: {c:?}"
225 );
226 }
227 }
228
229 #[test]
230 fn candidates_have_no_duplicates() {
231 let c = library_candidates("stem");
232 let mut sorted = c.clone();
233 sorted.sort();
234 sorted.dedup();
235 assert_eq!(sorted.len(), c.len(), "duplicate candidates: {c:?}");
236 }
237
238 #[test]
239 fn find_library_picks_the_matching_file() {
240 let dir = tempfile::tempdir().unwrap();
241 std::fs::write(dir.path().join("unrelated.txt"), b"x").unwrap();
242
243 let want = library_candidates("myapp_plugin_foo")[0].clone();
244 std::fs::write(dir.path().join(&want), b"not really a library").unwrap();
245
246 let found = find_library(dir.path(), "myapp_plugin_foo").expect("should be found");
247 assert_eq!(found.file_name().unwrap().to_string_lossy(), want);
248 }
249
250 #[test]
251 fn find_library_reports_what_it_tried() {
252 let dir = tempfile::tempdir().unwrap();
253
254 let err = find_library(dir.path(), "myapp_plugin_foo");
255 match err {
256 Err(KitError::LibraryNotFound { name, tried }) => {
257 assert_eq!(name, "myapp_plugin_foo");
258 assert!(tried.contains("myapp_plugin_foo"), "tried = {tried}");
259 }
260 other => panic!("expected LibraryNotFound, got {other:?}"),
261 }
262 }
263
264 /// A directory with the right name does not count as a hit — only files do.
265 #[test]
266 fn find_library_ignores_a_directory_with_the_right_name() {
267 let dir = tempfile::tempdir().unwrap();
268 let want = &library_candidates("myapp_plugin_foo")[0];
269 std::fs::create_dir(dir.path().join(want)).unwrap();
270
271 assert!(find_library(dir.path(), "myapp_plugin_foo").is_err());
272 }
273
274 /// Opening a file that is not a dynamic library at all must report
275 /// `LibraryLoad`, not panic.
276 #[test]
277 fn opening_a_non_library_reports_an_error() {
278 let dir = tempfile::tempdir().unwrap();
279 let path = dir.path().join("garbage.bin");
280 std::fs::write(&path, b"this is not a shared object").unwrap();
281
282 // SAFETY: the point here is to make it fail; no layout assumption is involved.
283 let got = unsafe { open::<u32>(&path, b"whatever") };
284 assert!(
285 matches!(got, Err(KitError::LibraryLoad { .. })),
286 "expected LibraryLoad, got {:?}",
287 got.err()
288 );
289 }
290}