Skip to main content

nativeview_engine/app/
module.rs

1//! Shared, ref-counted app module handle ([`NvAppModule`]) for multi-surface execution.
2//!
3//! Opening N surfaces for the same app `cdylib` stages and `dlopen`s the library **once per reload
4//! generation** (`staged_loads == 1`) so every surface shares the exact same Rust `static`s,
5//! `SharedAtom<T>`s, and allocator while unloading cleanly once the last surface detaches.
6
7#[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
8use std::path::Path;
9#[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
10use std::sync::Arc;
11
12use nativeview_abi::NvGetInterfaceFn;
13
14#[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
15use crate::loader::{LoaderError, StagedDylib};
16
17#[derive(Clone)]
18enum ModuleBacking {
19    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
20    Dylib(Arc<StagedDylib>),
21    Static(NvGetInterfaceFn),
22}
23
24/// Ref-counted handle to one loaded app module generation (`Arc<StagedDylib>` or static
25/// `NvGetInterfaceFn`).
26///
27/// Cloning is an O(1) atomic refcount bump that shares the single mapped `cdylib` across all
28/// surfaces attached to the same generation (`[INV:multi-surface-shared-dylib]`).
29#[derive(Clone)]
30pub struct NvAppModule {
31    backing: ModuleBacking,
32    generation: u64,
33    staged_loads: u64,
34}
35
36impl NvAppModule {
37    /// Stages and `dlopen`s `dylib_path` **once** (generation 1) into a shared [`NvAppModule`].
38    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
39    pub fn load(dylib_path: &Path, subdir: &str, label: &str) -> Result<Self, LoaderError> {
40        let staged = StagedDylib::load(dylib_path, subdir, label)?;
41        Ok(Self::from_staged_dylib(Arc::new(staged), 1))
42    }
43
44    /// Stages and `dlopen`s `dylib_path` **once** for reload `generation` into a shared
45    /// [`NvAppModule`].
46    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
47    pub fn load_generation(
48        dylib_path: &Path,
49        subdir: &str,
50        generation: u64,
51    ) -> Result<Self, LoaderError> {
52        let staged = StagedDylib::load(dylib_path, subdir, &format!("gen{generation}"))?;
53        Ok(Self::from_staged_dylib(Arc::new(staged), generation))
54    }
55
56    /// Wraps an already-loaded [`StagedDylib`] as generation `generation` (`staged_loads == 1`).
57    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
58    pub fn from_staged_dylib(staged: Arc<StagedDylib>, generation: u64) -> Self {
59        Self {
60            backing: ModuleBacking::Dylib(staged),
61            generation,
62            staged_loads: 1,
63        }
64    }
65
66    /// Wraps a statically linked or in-process `nv_get_interface` entry point (zero dylib
67    /// staging; works on every target including `wasm32`).
68    #[inline]
69    pub fn from_get_interface(get_interface: NvGetInterfaceFn) -> Self {
70        Self::from_get_interface_generation(get_interface, 1)
71    }
72
73    /// Wraps a statically linked `nv_get_interface` entry point tagged with `generation`.
74    #[inline]
75    pub fn from_get_interface_generation(
76        get_interface: NvGetInterfaceFn,
77        generation: u64,
78    ) -> Self {
79        Self {
80            backing: ModuleBacking::Static(get_interface),
81            generation,
82            staged_loads: 0,
83        }
84    }
85
86    /// Returns the resolved `nv_get_interface` entry point backed by this module.
87    #[inline]
88    pub fn get_interface(&self) -> NvGetInterfaceFn {
89        match &self.backing {
90            #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
91            ModuleBacking::Dylib(staged) => staged.get_interface(),
92            ModuleBacking::Static(f) => *f,
93        }
94    }
95
96    /// Reload generation of this module (`1` for initial load, incremented per atomic reload).
97    #[inline]
98    pub fn generation(&self) -> u64 {
99        self.generation
100    }
101
102    /// Number of staged `cdylib` loads performed to produce this generation (`1` for dylib loads,
103    /// `0` for statically linked `nv_get_interface`).
104    #[inline]
105    pub fn staged_loads(&self) -> u64 {
106        self.staged_loads
107    }
108
109    /// Path of the private staged copy (or resolved in-place file on mobile), or `None` for
110    /// statically linked modules.
111    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
112    pub fn loaded_copy_path(&self) -> Option<&Path> {
113        match &self.backing {
114            ModuleBacking::Dylib(staged) => Some(staged.loaded_copy_path()),
115            ModuleBacking::Static(_) => None,
116        }
117    }
118
119    /// Strong reference count of the underlying `Arc<StagedDylib>` (`1` for static modules).
120    #[inline]
121    pub fn strong_count(&self) -> usize {
122        match &self.backing {
123            #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
124            ModuleBacking::Dylib(staged) => Arc::strong_count(staged),
125            ModuleBacking::Static(_) => 1,
126        }
127    }
128
129    /// Returns `true` when both handles share the exact same underlying mapped `StagedDylib`
130    /// allocation (or identical static `nv_get_interface` function pointer).
131    #[inline]
132    pub fn same_backing(&self, other: &Self) -> bool {
133        match (&self.backing, &other.backing) {
134            #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
135            (ModuleBacking::Dylib(a), ModuleBacking::Dylib(b)) => Arc::ptr_eq(a, b),
136            (ModuleBacking::Static(a), ModuleBacking::Static(b)) => {
137                std::ptr::fn_addr_eq(*a, *b)
138            }
139            #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
140            _ => false,
141        }
142    }
143}
144
145impl std::fmt::Debug for NvAppModule {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        let mut s = f.debug_struct("NvAppModule");
148        s.field("generation", &self.generation)
149            .field("staged_loads", &self.staged_loads)
150            .field("strong_count", &self.strong_count());
151        #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
152        s.field("loaded_copy_path", &self.loaded_copy_path());
153        s.finish()
154    }
155}