audio-plugin-bsd 0.1.0

Dynamic .so audio-plugin loader with ABI verification and FreeBSD Capsicum/pdfork per-process sandboxing for real-time audio in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Dynamic plugin loader: [`PluginLoader`], [`LoadedPlugin`], and [`PluginId`].
//!
//! [`PluginLoader`] owns every loaded `cdylib` (`libloading::Library`) and
//! hands out [`PluginId`]s that reference them. Unloading a plugin removes its
//! entry, which drops the `Library` and runs `dlclose` — guaranteeing no
//! outstanding [`AudioNode`](audio_core_bsd::AudioNode) instance can outlive
//! the library it came from (the adapter is dropped first, releasing the
//! opaque handle, and only then the library is closed).
//!
//! # Real-time safety boundary
//!
//! `load` / `unload` / `instantiate` run on a **non-RT** (setup) thread. Only
//! the [`AudioNode`](audio_core_bsd::AudioNode) returned from
//! [`PluginLoader::instantiate`] ever touches the RT thread.

use std::collections::HashMap;
use std::path::Path;

use audio_core_bsd::AudioNode;
use libloading::Library;

use crate::abi::{is_abi_compatible, AUDIO_PLUGIN_ABI_MAGIC, AUDIO_PLUGIN_ABI_VERSION};
use crate::error::{PluginError, Result};
use crate::metadata::PluginMetadata;
use crate::plugin::{HostPlugin, Plugin};
use crate::symbols::{
    raw_to_metadata, AbiMagicFn, AbiVersionFn, CreateFn, DestroyFn, MetadataFn,
    AUDIO_PLUGIN_ABI_MAGIC_SYMBOL, AUDIO_PLUGIN_ABI_VERSION_SYMBOL, AUDIO_PLUGIN_CREATE_SYMBOL,
    AUDIO_PLUGIN_DESTROY_SYMBOL, AUDIO_PLUGIN_METADATA_SYMBOL,
};

/// Opaque, copyable handle identifying one loaded plugin inside a
/// [`PluginLoader`].
///
/// IDs are assigned monotonically starting at 0 and are unique within a single
/// loader instance until `u32::MAX` is reached (after which they wrap). In
/// practice the wrap is unreachable; it is handled without panicking for
/// robustness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PluginId(u32);

/// A successfully loaded plugin: its library, metadata, host adapter, and id.
///
/// The library is owned here so that dropping a `LoadedPlugin` runs `dlclose`
/// after the adapter (and any instantiated node) has been released, preventing
/// use-after-unload.
pub struct LoadedPlugin {
    /// The opened `cdylib`; never read directly — its sole purpose is to be
    /// dropped (running `dlclose`) when the `LoadedPlugin` is removed, so the
    /// plugin's symbols stay mapped for the adapter's lifetime.
    #[allow(dead_code)]
    library: Library,
    /// Owned metadata copied out of the plugin at load time.
    metadata: PluginMetadata,
    /// Host adapter bridging the plugin's C symbols to [`Plugin`].
    plugin: Box<dyn Plugin>,
    /// The loader-assigned id.
    id: PluginId,
}

impl LoadedPlugin {
    /// Static metadata for this plugin.
    #[must_use]
    pub fn metadata(&self) -> &PluginMetadata {
        &self.metadata
    }

    /// The id under which this plugin is registered.
    #[must_use]
    pub fn id(&self) -> PluginId {
        self.id
    }
}

/// Owner of all loaded plugin `cdylib`s.
///
/// See the [module docs](self) for the lifetime / RT-safety contract.
pub struct PluginLoader {
    plugins: HashMap<PluginId, LoadedPlugin>,
    next_id: u32,
}

impl PluginLoader {
    /// Construct an empty loader.
    #[must_use]
    pub fn new() -> Self {
        Self {
            plugins: HashMap::new(),
            next_id: 0,
        }
    }

    /// Load and ABI-verify a plugin `cdylib`, returning its assigned id.
    ///
    /// # Steps
    ///
    /// 1. Validate the path (must be an existing, readable file).
    /// 2. `dlopen` the library.
    /// 3. Look up and call `audio_plugin_abi_magic`; require
    ///    [`AUDIO_PLUGIN_ABI_MAGIC`].
    /// 4. Look up and call `audio_plugin_abi_version`; require a
    ///    **major** match (see [`is_abi_compatible`]).
    /// 5. Look up `audio_plugin_metadata` and copy out an owned
    ///    [`PluginMetadata`].
    /// 6. Look up `audio_plugin_create` (required) and `audio_plugin_destroy`
    ///    (optional).
    /// 7. Register the plugin under a fresh [`PluginId`].
    ///
    /// Loading the same path twice is permitted: each call receives its own id
    /// and its own `dlopen` handle.
    ///
    /// # Errors
    ///
    /// - [`PluginError::InvalidPath`] — missing file or non-UTF-8 path.
    /// - [`PluginError::LibraryLoad`] — `dlopen` failed.
    /// - [`PluginError::SymbolMissing`] — a required symbol is absent.
    /// - [`PluginError::InvalidMetadata`] — magic mismatch or bad metadata.
    /// - [`PluginError::AbiVersionMismatch`] — ABI major differs.
    pub fn load(&mut self, path: &Path) -> Result<PluginId> {
        // 1. Path validation: must exist and be a file. UTF-8 is required so
        //    that error messages can embed the path (see InvalidPath doc).
        if !path.is_file() {
            return Err(PluginError::InvalidPath(format!(
                "{}: not an existing file",
                path.display()
            )));
        }
        if path.to_str().is_none() {
            return Err(PluginError::InvalidPath(format!(
                "{}: path is not valid UTF-8",
                path.display()
            )));
        }

        // 2. dlopen.
        let library = unsafe { Library::new(path) }
            .map_err(|e| PluginError::LibraryLoad(format!("{}: {e}", path.display())))?;

        // 3. ABI magic.
        let plugin_magic = unsafe {
            let sym: libloading::Symbol<AbiMagicFn> = library
                .get(AUDIO_PLUGIN_ABI_MAGIC_SYMBOL.as_bytes())
                .map_err(|e| {
                    PluginError::SymbolMissing(format!("{AUDIO_PLUGIN_ABI_MAGIC_SYMBOL}: {e}"))
                })?;
            sym()
        };
        if plugin_magic != AUDIO_PLUGIN_ABI_MAGIC {
            return Err(PluginError::InvalidMetadata(format!(
                "ABI magic mismatch: expected {AUDIO_PLUGIN_ABI_MAGIC:#010x}, got {plugin_magic:#010x}"
            )));
        }

        // 4. ABI version (major must match host).
        let plugin_version = unsafe {
            let sym: libloading::Symbol<AbiVersionFn> = library
                .get(AUDIO_PLUGIN_ABI_VERSION_SYMBOL.as_bytes())
                .map_err(|e| {
                    PluginError::SymbolMissing(format!("{AUDIO_PLUGIN_ABI_VERSION_SYMBOL}: {e}"))
                })?;
            sym()
        };
        if !is_abi_compatible(AUDIO_PLUGIN_ABI_VERSION, plugin_version) {
            return Err(PluginError::AbiVersionMismatch {
                host: AUDIO_PLUGIN_ABI_VERSION,
                plugin: plugin_version,
            });
        }

        // 5. Metadata (copy strings into owned memory).
        let metadata = unsafe {
            let sym: libloading::Symbol<MetadataFn> = library
                .get(AUDIO_PLUGIN_METADATA_SYMBOL.as_bytes())
                .map_err(|e| {
                    PluginError::SymbolMissing(format!("{AUDIO_PLUGIN_METADATA_SYMBOL}: {e}"))
                })?;
            let raw_ptr = sym();
            // SAFETY: `raw_ptr` is the plugin's `'static` metadata pointer;
            // the library (and therefore the plugin's data segment) is alive
            // because `library` is still in scope.
            raw_to_metadata(raw_ptr)?
        };

        // 6. create (required) + destroy (optional).
        let create_fn: CreateFn = unsafe {
            let sym: libloading::Symbol<CreateFn> = library
                .get(AUDIO_PLUGIN_CREATE_SYMBOL.as_bytes())
                .map_err(|e| {
                    PluginError::SymbolMissing(format!("{AUDIO_PLUGIN_CREATE_SYMBOL}: {e}"))
                })?;
            *sym
        };
        let destroy_fn: Option<DestroyFn> = unsafe {
            library
                .get::<DestroyFn>(AUDIO_PLUGIN_DESTROY_SYMBOL.as_bytes())
                .ok()
                // SAFETY: `Symbol<DestroyFn>` derefs to `&DestroyFn`; copying
                // the plain function pointer out releases the library borrow.
                .map(|sym| *sym)
        };

        // 7. Register.
        let plugin: Box<dyn Plugin> =
            Box::new(HostPlugin::new(metadata.clone(), create_fn, destroy_fn));
        let id = self.fresh_id();
        self.plugins.insert(
            id,
            LoadedPlugin {
                library,
                metadata,
                plugin,
                id,
            },
        );
        Ok(id)
    }

    /// Unload a plugin, dropping its library (`dlclose`).
    ///
    /// The caller must ensure no [`AudioNode`](audio_core_bsd::AudioNode)
    /// instantiated from this plugin is still alive — the adapter owns an
    /// opaque handle into the plugin's memory and calling it after `dlclose`
    /// is undefined behaviour.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::NotLoaded`] when `id` is not registered.
    pub fn unload(&mut self, id: PluginId) -> Result<()> {
        if self.plugins.remove(&id).is_some() {
            Ok(())
        } else {
            Err(PluginError::NotLoaded)
        }
    }

    /// Borrow a loaded plugin by id.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::NotLoaded`] when `id` is not registered.
    pub fn get(&self, id: PluginId) -> Result<&LoadedPlugin> {
        self.plugins.get(&id).ok_or(PluginError::NotLoaded)
    }

    /// Mutably borrow a loaded plugin by id.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::NotLoaded`] when `id` is not registered.
    pub fn get_mut(&mut self, id: PluginId) -> Result<&mut LoadedPlugin> {
        self.plugins.get_mut(&id).ok_or(PluginError::NotLoaded)
    }

    /// Metadata for a loaded plugin.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::NotLoaded`] when `id` is not registered.
    pub fn metadata(&self, id: PluginId) -> Result<&PluginMetadata> {
        Ok(self.get(id)?.metadata())
    }

    /// Instantiate a fresh [`AudioNode`] from a loaded plugin.
    ///
    /// Runs on the setup thread; the returned node is then moved onto the RT
    /// thread by the caller.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::NotLoaded`] when `id` is not registered.
    pub fn instantiate(&mut self, id: PluginId) -> Result<Box<dyn AudioNode>> {
        let loaded = self.get_mut(id)?;
        Ok(loaded.plugin.instantiate())
    }

    /// `true` when `id` is currently loaded.
    #[must_use]
    pub fn is_loaded(&self, id: PluginId) -> bool {
        self.plugins.contains_key(&id)
    }

    /// Number of plugins currently loaded.
    #[must_use]
    pub fn len(&self) -> usize {
        self.plugins.len()
    }

    /// `true` when no plugins are loaded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.plugins.is_empty()
    }

    /// All currently-registered plugin ids.
    ///
    /// The order is unspecified (iteration order of the internal map).
    #[must_use]
    pub fn ids(&self) -> Vec<PluginId> {
        self.plugins.keys().copied().collect()
    }

    /// Allocate a fresh, never-zero id. Wraps at `u32::MAX` without panicking.
    fn fresh_id(&mut self) -> PluginId {
        let id = PluginId(self.next_id);
        self.next_id = self.next_id.wrapping_add(1);
        id
    }
}

impl Default for PluginLoader {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn plugin_id_is_copy_eq_hash_debug() {
        let a = PluginId(7);
        let b = a; // Copy
        assert_eq!(a, b);
        assert_eq!(format!("{a:?}"), "PluginId(7)");

        // Hash + Eq usable in a HashSet.
        let mut set = std::collections::HashSet::new();
        set.insert(a);
        assert!(set.contains(&b));
        assert!(!set.contains(&PluginId(8)));
    }

    #[test]
    fn new_loader_is_empty() {
        let loader = PluginLoader::new();
        assert!(loader.is_empty());
        assert_eq!(loader.len(), 0);
        assert!(loader.ids().is_empty());
    }

    #[test]
    fn default_equals_new() {
        let d = PluginLoader::default();
        assert!(d.is_empty());
        assert_eq!(d.len(), 0);
    }

    #[test]
    fn unload_unknown_id_is_not_loaded_err() {
        let mut loader = PluginLoader::new();
        let err = loader.unload(PluginId(0)).unwrap_err();
        assert_eq!(err, PluginError::NotLoaded);
    }

    #[test]
    fn get_unknown_id_is_not_loaded_err() {
        let loader = PluginLoader::new();
        // Map the `Ok(&LoadedPlugin)` to `Ok(())` so `unwrap_err` only needs
        // `(): Debug` (LoadedPlugin intentionally does not impl Debug).
        let err = loader.get(PluginId(42)).map(|_| ()).unwrap_err();
        assert_eq!(err, PluginError::NotLoaded);
    }

    #[test]
    fn get_mut_unknown_id_is_not_loaded_err() {
        let mut loader = PluginLoader::new();
        let err = loader.get_mut(PluginId(99)).map(|_| ()).unwrap_err();
        assert_eq!(err, PluginError::NotLoaded);
    }

    #[test]
    fn metadata_unknown_id_is_not_loaded_err() {
        let loader = PluginLoader::new();
        let err = loader.metadata(PluginId(5)).unwrap_err();
        assert_eq!(err, PluginError::NotLoaded);
    }

    #[test]
    fn instantiate_unknown_id_is_not_loaded_err() {
        let mut loader = PluginLoader::new();
        // Map the `Ok(Box<dyn AudioNode>)` to `Ok(())` so `unwrap_err` only
        // needs `(): Debug` (dyn AudioNode does not impl Debug).
        let err = loader.instantiate(PluginId(3)).map(|_| ()).unwrap_err();
        assert_eq!(err, PluginError::NotLoaded);
    }

    #[test]
    fn is_loaded_unknown_id_is_false() {
        let loader = PluginLoader::new();
        assert!(!loader.is_loaded(PluginId(0)));
        assert!(!loader.is_loaded(PluginId(u32::MAX)));
    }

    #[test]
    fn load_missing_file_is_invalid_path_err() {
        let mut loader = PluginLoader::new();
        let err = loader
            .load(Path::new("/nonexistent/path/does-not-exist.so"))
            .unwrap_err();
        assert!(matches!(err, PluginError::InvalidPath(_)));
        assert!(err.to_string().contains("not an existing file"));
    }

    #[test]
    fn load_directory_is_invalid_path_err() {
        let mut loader = PluginLoader::new();
        // The crate's own parent directory definitely exists as a non-file.
        let dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let err = loader.load(dir).unwrap_err();
        assert!(matches!(err, PluginError::InvalidPath(_)));
        assert!(err.to_string().contains("not an existing file"));
    }

    #[test]
    fn fresh_id_is_monotonic_and_does_not_panic_at_max() {
        // Simulate the wrap directly: jump next_id to MAX and observe that the
        // next allocation returns MAX and wraps to 0 without panicking.
        let mut loader = PluginLoader::new();
        loader.next_id = u32::MAX;
        let first = loader.fresh_id();
        assert_eq!(first, PluginId(u32::MAX));
        // Wrapping add — no panic.
        let second = loader.fresh_id();
        assert_eq!(second, PluginId(0));
    }
}