Skip to main content

crate_plugin_kit/
loader.rs

1//! 泛型 `dlopen` 加载。
2//!
3//! # 这里没有类型擦除
4//!
5//! `T` 是**宿主自己的 `#[repr(C)]` 入口结构体**(对 bmux 来说就是 `BmuxPluginV1`)。
6//! `load()` 返回的是 `*const T` —— **瘦指针**,不是 `dyn Trait`,所以不存在
7//! "两个不同 vtable 的 fat pointer 互转"那种 UB。
8//!
9//! 本 crate **不知道也不需要知道** `T` 里有什么字段;它只负责把符号地址取出来
10//! 并 cast 成 `*const T`。怎么安全地读那些字段是宿主契约 crate 的事。
11//!
12//! # 调用方必须保证的事
13//!
14//! 1. `T` 与插件实际导出的结构体**布局一致**(靠宿主的 `abi_version` 字段兜底);
15//! 2. 每一次读 `T` 的字段之前,要自己包 [`crate::panic::guard`]。
16
17use std::path::{Path, PathBuf};
18
19use libloading::Library;
20
21use crate::error::{KitError, KitResult};
22
23/// 一个已加载的插件。
24///
25/// 持有 `Library` 句柄 —— **drop 掉这个结构体会把插件卸载**。
26/// 所以只要还想用它导出的东西,就得让它活着。
27pub struct LoadedPlugin<T> {
28    /// 必须持有。字段名以下划线开头是刻意的:它唯一的职责就是活到结构体被 drop。
29    _lib: Library,
30    entry: *const T,
31    path: PathBuf,
32}
33
34impl<T> LoadedPlugin<T> {
35    /// 入口结构体的指针。
36    ///
37    /// # Safety
38    ///
39    /// 调用方保证 `T` 的布局与插件导出的结构体一致。本 crate 无法验证这一点 ——
40    /// 那是宿主 `abi_version` 字段的职责。
41    pub fn entry(&self) -> *const T {
42        self.entry
43    }
44
45    /// 动态库文件路径。
46    pub fn path(&self) -> &Path {
47        &self.path
48    }
49}
50
51// 刻意**不**实现 `Send` / `Sync`:`T` 里装的是裸函数指针,它指向的代码是否线程安全
52// 本 crate 无从得知。需要跨线程传递的宿主应该自己用 `unsafe impl` 明确表态。
53
54/// 打开一个 cdylib 并调用它的入口函数。
55///
56/// # Safety
57///
58/// - `path` 指向的必须是本 kit 装出来的插件(或布局等价的动态库);
59/// - `T` 必须与那个插件导出的结构体布局一致。
60///
61/// # Errors
62///
63/// - [`KitError::LibraryLoad`]:`dlopen` 失败。
64/// - [`KitError::SymbolMissing`]:没有 `symbol` 这个导出符号。
65/// - [`KitError::NullEntry`]:入口函数返回了空指针。
66pub unsafe fn open<T>(path: &Path, symbol: &[u8]) -> KitResult<LoadedPlugin<T>> {
67    let lib = Library::new(path).map_err(|source| KitError::LibraryLoad {
68        path: path.to_path_buf(),
69        source: Box::new(source),
70    })?;
71
72    let entry = {
73        let f: libloading::Symbol<'_, unsafe extern "C" fn() -> *const T> =
74            lib.get(symbol).map_err(|source| {
75                if is_symbol_not_found(&source) {
76                    // 「库里没有这个符号」是常见情况(装错了东西 / 装的是别的插件),
77                    // 单独报比笼统的"加载失败"好读得多。
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/// `libloading` 表示"库里没有这个符号"的错误,**在各平台的变体名不一样**:
103///
104/// | 平台 | 变体 |
105/// | ---- | ---- |
106/// | Unix | `DlSym` / `DlSymUnknown` |
107/// | Windows | `GetProcAddress` / `GetProcAddressUnknown` |
108///
109/// 不区分平台地 match 是编译不过的(变体只在对应平台存在),所以按 `cfg` 拆开。
110fn is_symbol_not_found(e: &libloading::Error) -> bool {
111    #[cfg(unix)]
112    {
113        matches!(
114            e,
115            libloading::Error::DlSym { .. } | libloading::Error::DlSymUnknown
116        )
117    }
118
119    #[cfg(windows)]
120    {
121        matches!(
122            e,
123            libloading::Error::GetProcAddress { .. } | libloading::Error::GetProcAddressUnknown
124        )
125    }
126
127    #[cfg(not(any(unix, windows)))]
128    {
129        let _ = e;
130        false
131    }
132}
133
134/// 按平台给出 cdylib 文件名的候选列表,**按优先级排列**。
135///
136/// 会顺带列出别的平台的命名 —— 万一安装目录里躺着一个错平台的产物,
137/// 报错信息里能看见"试过哪些"比只说"找不到"有用。
138pub fn library_candidates(stem: &str) -> Vec<String> {
139    let mut out = Vec::new();
140
141    match std::env::consts::OS {
142        "windows" => out.push(format!("{stem}.dll")),
143        "macos" => out.push(format!("lib{stem}.dylib")),
144        _ => out.push(format!("lib{stem}.so")),
145    }
146
147    // 兜底:有些构建系统(或手工打包)不带 lib 前缀 / 扩展名不一致。
148    for ext in ["so", "dylib", "dll"] {
149        for name in [format!("lib{stem}.{ext}"), format!("{stem}.{ext}")] {
150            if !out.contains(&name) {
151                out.push(name);
152            }
153        }
154    }
155
156    out
157}
158
159/// 在一个目录里按候选列表找 cdylib,返回第一个存在的。
160pub fn find_library(dir: &Path, stem: &str) -> KitResult<PathBuf> {
161    let candidates = library_candidates(stem);
162
163    for name in &candidates {
164        let p = dir.join(name);
165        if p.is_file() {
166            return Ok(p);
167        }
168    }
169
170    Err(KitError::LibraryNotFound {
171        name: stem.to_string(),
172        tried: candidates.join(", "),
173    })
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    /// 当前平台该找的文件名必须排在候选列表第一位 —— 否则会优先命中错平台的产物。
181    #[test]
182    fn the_current_platform_name_comes_first() {
183        let c = library_candidates("myapp_plugin_foo");
184        let first = c.first().expect("候选列表不该为空");
185
186        let expected = match std::env::consts::OS {
187            "windows" => "myapp_plugin_foo.dll",
188            "macos" => "libmyapp_plugin_foo.dylib",
189            _ => "libmyapp_plugin_foo.so",
190        };
191        assert_eq!(first, expected);
192    }
193
194    /// 兜底项要覆盖所有平台命名 —— 这样"目录里躺着一个错平台的产物"时,
195    /// 报错信息里的"试过哪些"才有意义。
196    #[test]
197    fn candidates_cover_every_platform_spelling() {
198        let c = library_candidates("stem");
199        for name in [
200            "stem.dll",
201            "libstem.dylib",
202            "libstem.so",
203            "stem.so",
204            "stem.dylib",
205            "libstem.dll",
206        ] {
207            assert!(c.iter().any(|x| x == name), "候选里缺 {name}:{c:?}");
208        }
209    }
210
211    #[test]
212    fn candidates_have_no_duplicates() {
213        let c = library_candidates("stem");
214        let mut sorted = c.clone();
215        sorted.sort();
216        sorted.dedup();
217        assert_eq!(sorted.len(), c.len(), "候选里有重复:{c:?}");
218    }
219
220    #[test]
221    fn find_library_picks_the_matching_file() {
222        let dir = tempfile::tempdir().unwrap();
223        std::fs::write(dir.path().join("unrelated.txt"), b"x").unwrap();
224
225        let want = library_candidates("myapp_plugin_foo")[0].clone();
226        std::fs::write(dir.path().join(&want), b"not really a library").unwrap();
227
228        let found = find_library(dir.path(), "myapp_plugin_foo").expect("应当找到");
229        assert_eq!(found.file_name().unwrap().to_string_lossy(), want);
230    }
231
232    #[test]
233    fn find_library_reports_what_it_tried() {
234        let dir = tempfile::tempdir().unwrap();
235
236        let err = find_library(dir.path(), "myapp_plugin_foo");
237        match err {
238            Err(KitError::LibraryNotFound { name, tried }) => {
239                assert_eq!(name, "myapp_plugin_foo");
240                assert!(tried.contains("myapp_plugin_foo"), "tried = {tried}");
241            }
242            other => panic!("期望 LibraryNotFound,得到 {other:?}"),
243        }
244    }
245
246    /// 目录里的同名**目录**不算命中 —— 只有文件才算。
247    #[test]
248    fn find_library_ignores_a_directory_with_the_right_name() {
249        let dir = tempfile::tempdir().unwrap();
250        let want = &library_candidates("myapp_plugin_foo")[0];
251        std::fs::create_dir(dir.path().join(want)).unwrap();
252
253        assert!(find_library(dir.path(), "myapp_plugin_foo").is_err());
254    }
255
256    /// 打开一个根本不是动态库的文件,要报 `LibraryLoad` 而不是 panic。
257    #[test]
258    fn opening_a_non_library_reports_an_error() {
259        let dir = tempfile::tempdir().unwrap();
260        let path = dir.path().join("garbage.bin");
261        std::fs::write(&path, b"this is not a shared object").unwrap();
262
263        // SAFETY: 这里就是要它失败,不涉及任何布局假设。
264        let got = unsafe { open::<u32>(&path, b"whatever") };
265        assert!(
266            matches!(got, Err(KitError::LibraryLoad { .. })),
267            "期望 LibraryLoad,得到 {:?}",
268            got.err()
269        );
270    }
271}