1use std::path::{Path, PathBuf};
20
21use libloading::Library;
22
23use crate::error::{KitError, KitResult};
24
25pub struct LoadedPlugin<T> {
30 _lib: Library,
33 entry: *const T,
34 path: PathBuf,
35}
36
37impl<T> LoadedPlugin<T> {
38 pub fn entry(&self) -> *const T {
46 self.entry
47 }
48
49 pub fn path(&self) -> &Path {
51 &self.path
52 }
53}
54
55pub 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 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
111fn 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
144pub 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
160fn 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
168pub 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 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
189pub fn library_candidates(stem: &str) -> Vec<String> {
191 library_candidates_for_target(stem, crate::TARGET_TRIPLE)
192}
193
194pub fn find_library(dir: &Path, stem: &str) -> KitResult<PathBuf> {
197 find_library_for_target(dir, stem, crate::TARGET_TRIPLE)
198}
199
200pub 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 #[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 #[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 #[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 #[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 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 #[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 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 #[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 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}