Skip to main content

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 extension implied by a target triple.
145///
146/// Derived from the triple rather than from the running host: the same function names
147/// the assets a release publishes (`install::prebuilt` looks them up) and the artifact a
148/// local build produced (`crate::pack`), and those two must agree even when the build
149/// targets a triple other than the host's.
150pub fn lib_ext_for_target(target: &str) -> &'static str {
151    if target.contains("windows") {
152        "dll"
153    } else if target.contains("apple") || target.contains("darwin") {
154        "dylib"
155    } else {
156        "so"
157    }
158}
159
160/// The file name a cdylib has on the platform of `target`.
161fn lib_file_name_for_target(stem: &str, target: &str) -> String {
162    match lib_ext_for_target(target) {
163        "dll" => format!("{stem}.dll"),
164        ext => format!("lib{stem}.{ext}"),
165    }
166}
167
168/// The cdylib file name candidates for `target`, in priority order.
169///
170/// Other platforms' spellings are listed as well, so that when a wrong-platform
171/// artifact sits in the install dir the error message can show what was tried
172/// instead of only saying "not found".
173pub fn library_candidates_for_target(stem: &str, target: &str) -> Vec<String> {
174    let mut out = vec![lib_file_name_for_target(stem, target)];
175
176    // Fallbacks: some build systems (or hand-made archives) omit the `lib` prefix
177    // or use a different extension.
178    for ext in ["so", "dylib", "dll"] {
179        for name in [format!("lib{stem}.{ext}"), format!("{stem}.{ext}")] {
180            if !out.contains(&name) {
181                out.push(name);
182            }
183        }
184    }
185
186    out
187}
188
189/// The cdylib file name candidates for this build's target, in priority order.
190pub fn library_candidates(stem: &str) -> Vec<String> {
191    library_candidates_for_target(stem, crate::TARGET_TRIPLE)
192}
193
194/// Finds a cdylib in a directory by walking the candidate list, returning the first
195/// one that exists.
196pub fn find_library(dir: &Path, stem: &str) -> KitResult<PathBuf> {
197    find_library_for_target(dir, stem, crate::TARGET_TRIPLE)
198}
199
200/// [`find_library`], for a specific target triple.
201pub fn find_library_for_target(dir: &Path, stem: &str, target: &str) -> KitResult<PathBuf> {
202    let candidates = library_candidates_for_target(stem, target);
203
204    for name in &candidates {
205        let p = dir.join(name);
206        if p.is_file() {
207            return Ok(p);
208        }
209    }
210
211    Err(KitError::LibraryNotFound {
212        name: stem.to_string(),
213        tried: candidates.join(", "),
214    })
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    /// This platform's file name must come first in the candidate list, otherwise a
222    /// wrong-platform artifact would win.
223    #[test]
224    fn the_current_platform_name_comes_first() {
225        let c = library_candidates("myapp_plugin_foo");
226        let first = c.first().expect("candidate list must not be empty");
227
228        let expected = match std::env::consts::OS {
229            "windows" => "myapp_plugin_foo.dll",
230            "macos" => "libmyapp_plugin_foo.dylib",
231            _ => "libmyapp_plugin_foo.so",
232        };
233        assert_eq!(first, expected);
234    }
235
236    /// The fallback entries must cover every platform spelling — that is what makes
237    /// the "tried" list in the error meaningful when a wrong-platform artifact is
238    /// sitting in the directory.
239    #[test]
240    fn candidates_cover_every_platform_spelling() {
241        let c = library_candidates("stem");
242        for name in [
243            "stem.dll",
244            "libstem.dylib",
245            "libstem.so",
246            "stem.so",
247            "stem.dylib",
248            "libstem.dll",
249        ] {
250            assert!(
251                c.iter().any(|x| x == name),
252                "candidate missing {name}: {c:?}"
253            );
254        }
255    }
256
257    #[test]
258    fn candidates_have_no_duplicates() {
259        let c = library_candidates("stem");
260        let mut sorted = c.clone();
261        sorted.sort();
262        sorted.dedup();
263        assert_eq!(sorted.len(), c.len(), "duplicate candidates: {c:?}");
264    }
265
266    #[test]
267    fn find_library_picks_the_matching_file() {
268        let dir = tempfile::tempdir().unwrap();
269        std::fs::write(dir.path().join("unrelated.txt"), b"x").unwrap();
270
271        let want = library_candidates("myapp_plugin_foo")[0].clone();
272        std::fs::write(dir.path().join(&want), b"not really a library").unwrap();
273
274        let found = find_library(dir.path(), "myapp_plugin_foo").expect("should be found");
275        assert_eq!(found.file_name().unwrap().to_string_lossy(), want);
276    }
277
278    #[test]
279    fn find_library_reports_what_it_tried() {
280        let dir = tempfile::tempdir().unwrap();
281
282        let err = find_library(dir.path(), "myapp_plugin_foo");
283        match err {
284            Err(KitError::LibraryNotFound { name, tried }) => {
285                assert_eq!(name, "myapp_plugin_foo");
286                assert!(tried.contains("myapp_plugin_foo"), "tried = {tried}");
287            }
288            other => panic!("expected LibraryNotFound, got {other:?}"),
289        }
290    }
291
292    /// A directory with the right name does not count as a hit — only files do.
293    #[test]
294    fn find_library_ignores_a_directory_with_the_right_name() {
295        let dir = tempfile::tempdir().unwrap();
296        let want = &library_candidates("myapp_plugin_foo")[0];
297        std::fs::create_dir(dir.path().join(want)).unwrap();
298
299        assert!(find_library(dir.path(), "myapp_plugin_foo").is_err());
300    }
301
302    /// The extension is a property of the target, not of whatever machine happens to be
303    /// running: `pack` names assets for the triple it built, and `prebuilt` looks them up
304    /// by the triple it was compiled for.
305    #[test]
306    fn the_extension_follows_the_target() {
307        assert_eq!(lib_ext_for_target("x86_64-unknown-linux-gnu"), "so");
308        assert_eq!(lib_ext_for_target("aarch64-unknown-linux-musl"), "so");
309        assert_eq!(lib_ext_for_target("x86_64-pc-windows-msvc"), "dll");
310        assert_eq!(lib_ext_for_target("aarch64-pc-windows-msvc"), "dll");
311        assert_eq!(lib_ext_for_target("x86_64-apple-darwin"), "dylib");
312        assert_eq!(lib_ext_for_target("aarch64-apple-darwin"), "dylib");
313    }
314
315    #[test]
316    fn candidates_are_ordered_for_the_target_not_the_host() {
317        // A Windows target on any host: the `.dll` spelling has to come first, otherwise
318        // an artifact from a previous build of another platform could win.
319        let c = library_candidates_for_target("stem", "x86_64-pc-windows-msvc");
320        assert_eq!(c.first().map(String::as_str), Some("stem.dll"));
321
322        let c = library_candidates_for_target("stem", "x86_64-apple-darwin");
323        assert_eq!(c.first().map(String::as_str), Some("libstem.dylib"));
324
325        let c = library_candidates_for_target("stem", "x86_64-unknown-linux-gnu");
326        assert_eq!(c.first().map(String::as_str), Some("libstem.so"));
327    }
328
329    /// Every platform's spelling is still reachable, so a wrong-platform artifact in the
330    /// directory produces a useful error rather than "not found".
331    #[test]
332    fn target_candidates_keep_every_fallback() {
333        let c = library_candidates_for_target("stem", "x86_64-pc-windows-msvc");
334        for name in ["stem.dll", "libstem.dylib", "libstem.so", "stem.so"] {
335            assert!(c.iter().any(|x| x == name), "missing {name}: {c:?}");
336        }
337    }
338
339    #[test]
340    fn find_library_for_target_finds_another_platforms_artifact() {
341        let dir = tempfile::tempdir().unwrap();
342        // A Linux artifact, looked up for a Linux target: the `lib` prefix is what the
343        // build actually produces there.
344        std::fs::write(dir.path().join("libstem.so"), b"x").unwrap();
345
346        let found = find_library_for_target(dir.path(), "stem", "x86_64-unknown-linux-gnu")
347            .expect("should be found");
348        assert_eq!(found.file_name().unwrap().to_string_lossy(), "libstem.so");
349    }
350
351    /// Opening a file that is not a dynamic library at all must report
352    /// `LibraryLoad`, not panic.
353    #[test]
354    fn opening_a_non_library_reports_an_error() {
355        let dir = tempfile::tempdir().unwrap();
356        let path = dir.path().join("garbage.bin");
357        std::fs::write(&path, b"this is not a shared object").unwrap();
358
359        // SAFETY: the point here is to make it fail; no layout assumption is involved.
360        let got = unsafe { open::<u32>(&path, b"whatever") };
361        assert!(
362            matches!(got, Err(KitError::LibraryLoad { .. })),
363            "expected LibraryLoad, got {:?}",
364            got.err()
365        );
366    }
367}