crate_plugin_kit/
loader.rs1use std::path::{Path, PathBuf};
18
19use libloading::Library;
20
21use crate::error::{KitError, KitResult};
22
23pub struct LoadedPlugin<T> {
28 _lib: Library,
30 entry: *const T,
31 path: PathBuf,
32}
33
34impl<T> LoadedPlugin<T> {
35 pub fn entry(&self) -> *const T {
42 self.entry
43 }
44
45 pub fn path(&self) -> &Path {
47 &self.path
48 }
49}
50
51pub 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 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
102fn 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
134pub 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 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
159pub 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 #[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 #[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 #[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 #[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 let got = unsafe { open::<u32>(&path, b"whatever") };
265 assert!(
266 matches!(got, Err(KitError::LibraryLoad { .. })),
267 "期望 LibraryLoad,得到 {:?}",
268 got.err()
269 );
270 }
271}