Skip to main content

nativeview_engine/loader/
mod.rs

1//! Tier-2 modular `nv_get_interface` `cdylib` hot-swap loader.
2//!
3//! Resolves the single `nv_get_interface` entry point once at load time, caches the small
4//! `const` interface tables (`NvSurfaceApi`, plus optional `NvLayoutApi`, `NvComponentApi`,
5//! `NvDevApi`), and exposes direct zero-cost calls + state-preserving generation reloads.
6
7mod staging;
8
9use std::path::{Path, PathBuf};
10
11use nativeview_abi::{
12    slab_ptr, DispatchResult, HostServiceId, NvAppHandle, NvBufferSlice, NvComponentApi, NvDevApi,
13    NvDirectHostApi, NvDirectHostEnv, NvGestureDisposition, NvHostApi, NvHostCallbacks,
14    NvIntrinsicSize, NvLayoutApi, NvMapEntry, NvPointerApi, NvSizeConstraints, NvSurfaceApi,
15    SurfaceId, ValidatedEvents, NV_IFACE_COMPONENT, NV_IFACE_DEV, NV_IFACE_DIRECT_HOST,
16    NV_IFACE_HOST, NV_IFACE_LAYOUT, NV_IFACE_POINTER, NV_IFACE_SURFACE,
17};
18
19use crate::tracker::PointerCaptureRequest;
20
21pub use staging::{
22    MODULE_STAGE_DIR_ENV, STAGES_PRIVATE_COPY, StagedDylib, is_valid_nv_interface_symbol,
23    resolve_in_process_symbol, staging_dir,
24};
25
26use crate::app_module::NvAppModule;
27
28#[derive(Debug)]
29pub enum LoaderError {
30    /// The library could not be staged (missing / unreadable source, temp dir failure).
31    Io(std::io::Error),
32    /// The OS loader rejected the staged copy (`dlopen` / `LoadLibraryW`).
33    Load(libloading::Error),
34    /// The requested symbol does not match `nv_get_interface` or `nv_get_interface_[A-Za-z0-9_]+`.
35    InvalidSymbol,
36    /// The library loaded but exports no matching `nv_get_interface` entry point.
37    MissingEntry(libloading::Error),
38    /// The process image does not export the requested `nv_get_interface*` symbol.
39    MissingSymbol,
40    MissingSurfaceInterface,
41    NullHandle,
42    /// Loading in place (no staging root) a file whose bytes changed since this process already
43    /// loaded that inode or canonical path in place: the OS loader would hand back the mapped
44    /// image, silently running the old code.
45    AlreadyLoadedInPlace(PathBuf),
46}
47
48impl std::fmt::Display for LoaderError {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(f, "{self:?}")
51    }
52}
53
54impl std::error::Error for LoaderError {}
55
56
57/// Summary returned after a successful transactional [`HotAppInstance::reload`].
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct ReloadOutcome {
60    pub previous_generation: u64,
61    pub generation: u64,
62    pub preserved_state_bytes: usize,
63}
64
65pub struct HotAppInstance {
66    module: Option<NvAppModule>,
67    surface: NvSurfaceApi,
68    layout: Option<NvLayoutApi>,
69    component: Option<NvComponentApi>,
70    dev: Option<NvDevApi>,
71    host: Option<NvHostApi>,
72    direct_host: Option<NvDirectHostApi>,
73    pointer: Option<NvPointerApi>,
74    bound_host: Option<NvHostCallbacks>,
75    bound_direct_host: Option<NvDirectHostEnv>,
76    handle: NvAppHandle,
77    surface_id: SurfaceId,
78    generation: u64,
79    /// `NV_DISPATCH_RESULT_CLOSE_REQUEST` of the last `dispatch_events`, until taken.
80    close_request: bool,
81    /// `NV_DISPATCH_RESULT_UNCONSUMED_KEY` of the last `dispatch_events`, until taken.
82    unconsumed_key: bool,
83}
84
85impl HotAppInstance {
86    /// Loads a compiled app `cdylib` via a unique staged filename so `dlopen` never returns
87    /// a stale cached image (and Windows never hits DLL lock collisions during hot-swap),
88    /// resolves `nv_get_interface`, and optionally restores state.
89    pub fn load(
90        dylib_path: &Path,
91        surface_id: SurfaceId,
92        generation: u64,
93        prior_state: Option<&[u8]>,
94    ) -> Result<Self, LoaderError> {
95        let module = NvAppModule::load_generation(dylib_path, "nv-hotswap", generation)?;
96        Self::from_module(&module, surface_id, prior_state)
97    }
98
99    /// Instantiates a surface handle backed by a shared [`NvAppModule`] without staging or
100    /// `dlopen`ing the library again (`[INV:multi-surface-shared-dylib]`).
101    pub fn from_module(
102        module: &NvAppModule,
103        surface_id: SurfaceId,
104        prior_state: Option<&[u8]>,
105    ) -> Result<Self, LoaderError> {
106        let get_iface = module.get_interface();
107
108        // SAFETY: `get_iface` returns static, properly aligned NV C-ABI vtable pointers (or null)
109        // that remain valid while `module` keeps the dylib loaded; `surface.create` / `restore_state`
110        // obey the NV surface/dev C ABI contract.
111        let (surface, layout, component, dev, host, direct_host, handle) = unsafe {
112            let surface_ptr = get_iface(NV_IFACE_SURFACE) as *const NvSurfaceApi;
113            if surface_ptr.is_null() {
114                return Err(LoaderError::MissingSurfaceInterface);
115            }
116            let surface = *surface_ptr;
117
118            let layout_ptr = get_iface(NV_IFACE_LAYOUT) as *const NvLayoutApi;
119            let layout = (!layout_ptr.is_null()).then(|| *layout_ptr);
120
121            let component_ptr = get_iface(NV_IFACE_COMPONENT) as *const NvComponentApi;
122            let component = (!component_ptr.is_null()).then(|| *component_ptr);
123
124            let dev_ptr = get_iface(NV_IFACE_DEV) as *const NvDevApi;
125            let dev = (!dev_ptr.is_null()).then(|| *dev_ptr);
126
127            let host_ptr = get_iface(NV_IFACE_HOST) as *const NvHostApi;
128            let host = (!host_ptr.is_null()).then(|| *host_ptr);
129
130            let direct_host_ptr = get_iface(NV_IFACE_DIRECT_HOST) as *const NvDirectHostApi;
131            let direct_host = (!direct_host_ptr.is_null()).then(|| *direct_host_ptr);
132
133            let handle = (surface.create)(surface_id);
134            if handle.is_null() {
135                return Err(LoaderError::NullHandle);
136            }
137            if let (Some(dev_api), Some(state)) = (dev, prior_state)
138                && !state.is_empty()
139            {
140                (dev_api.restore_state)(handle, NvBufferSlice::from_slice(state));
141            }
142            (surface, layout, component, dev, host, direct_host, handle)
143        };
144        // SAFETY: As above (a static `NvPointerApi` or NULL).
145        let pointer = unsafe { (get_iface(NV_IFACE_POINTER) as *const NvPointerApi).as_ref().copied() };
146
147        Ok(Self {
148            module: Some(module.clone()),
149            surface,
150            layout,
151            component,
152            dev,
153            host,
154            direct_host,
155            pointer,
156            bound_host: None,
157            bound_direct_host: None,
158            handle,
159            surface_id,
160            generation: module.generation(),
161            close_request: false,
162            unconsumed_key: false,
163        })
164    }
165
166    /// Borrows the shared [`NvAppModule`] backing this surface instance.
167    #[inline]
168    pub fn module(&self) -> Option<&NvAppModule> {
169        self.module.as_ref()
170    }
171
172    pub fn surface_id(&self) -> SurfaceId {
173        self.surface_id
174    }
175
176    pub fn generation(&self) -> u64 {
177        self.generation
178    }
179
180    pub fn loaded_copy_path(&self) -> &Path {
181        self.module
182            .as_ref()
183            .and_then(NvAppModule::loaded_copy_path)
184            .unwrap_or_else(|| Path::new(""))
185    }
186
187    /// Renders a frame and borrows the binary `NV02` wire frame slice directly from the loaded
188    /// app module's internal frame buffer (zero heap allocation / zero `.to_vec()` copy per frame).
189    ///
190    /// The borrowed slice remains valid until the next `&mut self` call on this [`HotAppInstance`].
191    pub fn render(&mut self, frame_id: nativeview_abi::FrameId) -> &[u8] {
192        // SAFETY: `self.handle` is live while `self` owns it; returned buffer stays valid until next `&mut self` call.
193        unsafe { (self.surface.render)(self.handle, frame_id).as_slice() }
194    }
195
196    /// Forwards a validated zero-copy event batch directly across the C FFI boundary; returns
197    /// `NV_DISPATCH_RESULT_DIRTY` and latches `NV_DISPATCH_RESULT_CLOSE_REQUEST` for
198    /// [`Self::take_close_request`].
199    pub fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> bool {
200        // SAFETY: `self.handle` is live and `events` stays valid for the synchronous FFI call.
201        let raw = unsafe { (self.surface.dispatch_events)(self.handle, events.as_raw_batch()) };
202        let result = DispatchResult::from_bits_truncate(raw);
203        self.close_request = result.is_close_request();
204        self.unconsumed_key = result.is_unconsumed_key();
205        result.is_dirty()
206    }
207
208    /// Takes the close request of the last [`Self::dispatch_events`].
209    pub fn take_close_request(&mut self) -> bool {
210        std::mem::take(&mut self.close_request)
211    }
212
213    /// Takes whether the last [`Self::dispatch_events`] left a `KeyDown` unconsumed.
214    pub fn take_unconsumed_key(&mut self) -> bool {
215        std::mem::take(&mut self.unconsumed_key)
216    }
217
218    /// Drains the pointer-capture requests of the last [`Self::dispatch_events`] (`NvPointerApi`).
219    pub fn drain_pointer_capture_requests(&mut self, sink: &mut dyn FnMut(PointerCaptureRequest)) {
220        if let Some(api) = self.pointer {
221            // SAFETY: `self.handle` is live and `api` was resolved from the same loaded dylib.
222            unsafe { crate::app::pointer::drain_capture_requests(api, self.handle, sink) };
223        }
224    }
225
226    pub fn measure(&mut self, constraints: NvSizeConstraints) -> Option<NvIntrinsicSize> {
227        self.layout.map(|api| {
228            // SAFETY: `self.handle` is live and `api` was resolved from the same loaded dylib.
229            unsafe { (api.measure)(self.handle, constraints) }
230        })
231    }
232
233    pub fn hit_test(&mut self, x: f32, y: f32, pointer_phase: u8) -> NvGestureDisposition {
234        match self.layout {
235            Some(api) => {
236                // SAFETY: `self.handle` is live and `api` was resolved from the same loaded dylib.
237                NvGestureDisposition::from_u8(unsafe {
238                    (api.hit_test)(self.handle, x, y, pointer_phase)
239                })
240            }
241            None => NvGestureDisposition::PassThrough,
242        }
243    }
244
245    pub fn set_props(&mut self, entries: &[NvMapEntry]) -> bool {
246        match self.component {
247            // SAFETY: `self.handle` is live and `entries` stays valid for the synchronous FFI call.
248            Some(api) => unsafe {
249                (api.set_props)(
250                    self.handle,
251                    entries.as_ptr(),
252                    entries.len().min(u32::MAX as usize) as u32,
253                ) != 0
254            },
255            None => false,
256        }
257    }
258
259    /// Drains outbound component events as an ingress-validated zero-copy [`ValidatedEvents`].
260    pub fn drain_emitted_events(&mut self) -> ValidatedEvents<'_> {
261        match self.component {
262            // SAFETY: `self.handle` is live; returned batch borrows from the module's buffer until next `&mut self` call.
263            Some(api) => unsafe {
264                ValidatedEvents::from_raw((api.drain_emitted_events)(self.handle))
265            },
266            None => ValidatedEvents::EMPTY,
267        }
268    }
269
270    /// Forwards one binary `NV_HOT_PATCH` frame (as received from `nv dev`) to the module.
271    pub fn apply_hot_patch(&mut self, patch: &[u8]) -> bool {
272        match self.dev {
273            // SAFETY: `self.handle` is live and `patch` stays valid for the synchronous FFI call.
274            Some(api) => unsafe {
275                (api.apply_hot_patch)(self.handle, NvBufferSlice::from_slice(patch)) != 0
276            },
277            None => false,
278        }
279    }
280
281    /// Captures serialized app state and borrows the slice directly from the loaded app module's
282    /// internal snapshot buffer without copying.
283    pub fn snapshot_state(&mut self) -> &[u8] {
284        match self.dev {
285            // SAFETY: `self.handle` is live; returned slice stays valid until the next `&mut self` call.
286            Some(api) => unsafe { (api.snapshot_state)(self.handle).as_slice() },
287            None => &[],
288        }
289    }
290
291    pub fn has_host_interface(&self) -> bool {
292        self.host.is_some()
293    }
294
295    /// Binds (or unbinds when `None`) host capability callbacks via `NV_IFACE_HOST = 5`.
296    /// Returns `true` if the loaded module exposes `NvHostApi`.
297    pub fn bind_host(&mut self, callbacks: Option<NvHostCallbacks>) -> bool {
298        self.bound_host = callbacks;
299        match self.host {
300            Some(api) => {
301                let ptr = callbacks
302                    .as_ref()
303                    .map_or(std::ptr::null(), |cb| cb as *const NvHostCallbacks);
304                // SAFETY: `self.handle` is live and `ptr` is null or points to the valid `NvHostCallbacks` copy.
305                unsafe { (api.bind_host)(self.handle, ptr) };
306                true
307            }
308            None => false,
309        }
310    }
311
312    /// Dispatches a host-event payload buffer via `NvHostApi::dispatch_host_events`.
313    pub fn dispatch_host_events(&mut self, batch: &[u8]) -> bool {
314        match self.host {
315            // SAFETY: `self.handle` is live and `batch` stays valid for the synchronous FFI call.
316            Some(api) => unsafe {
317                (api.dispatch_host_events)(self.handle, NvBufferSlice::from_slice(batch)) != 0
318            },
319            None => false,
320        }
321    }
322
323    /// Returns `true` if the loaded module exports `NV_IFACE_DIRECT_HOST = 6`.
324    pub fn has_direct_host_interface(&self) -> bool {
325        self.direct_host.is_some()
326    }
327
328    /// Binds (or unbinds when `None`) the non-reloaded Direct-First host environment via
329    /// `NV_IFACE_DIRECT_HOST = 6`. Returns `true` if the loaded module exposes `NvDirectHostApi`.
330    pub fn bind_direct_host(&mut self, env: Option<NvDirectHostEnv>) -> bool {
331        self.bound_direct_host = env;
332        match self.direct_host {
333            Some(api) => {
334                let ptr = env
335                    .as_ref()
336                    .map_or(std::ptr::null(), |e| e as *const NvDirectHostEnv);
337                // SAFETY: `self.handle` is live and `ptr` is null or points to the valid `NvDirectHostEnv`.
338                unsafe { (api.bind_direct_host)(self.handle, ptr) };
339                true
340            }
341            None => false,
342        }
343    }
344
345    /// Dispatches one completed direct-FFI async reply on the owner thread via
346    /// `NvDirectHostApi::dispatch_direct_completion`.
347    pub fn dispatch_direct_completion(
348        &mut self,
349        local_req_id: u64,
350        status: i32,
351        payload: &[u8],
352    ) -> bool {
353        match self.direct_host {
354            // SAFETY: `self.handle` is live and `payload` stays borrowed for this synchronous FFI call.
355            Some(api) => unsafe {
356                (api.dispatch_direct_completion)(
357                    self.handle,
358                    local_req_id,
359                    status,
360                    slab_ptr(payload),
361                    payload.len(),
362                ) != 0
363            },
364            None => false,
365        }
366    }
367
368    /// Dispatches one direct-FFI push event on the owner thread via
369    /// `NvDirectHostApi::dispatch_direct_event`.
370    pub fn dispatch_direct_event(
371        &mut self,
372        service_id: HostServiceId,
373        event_id: u32,
374        flags: u32,
375        payload: &[u8],
376    ) -> bool {
377        match self.direct_host {
378            // SAFETY: `self.handle` is live and `payload` stays borrowed for this synchronous FFI call.
379            Some(api) => unsafe {
380                (api.dispatch_direct_event)(
381                    self.handle,
382                    service_id,
383                    event_id,
384                    flags,
385                    slab_ptr(payload),
386                    payload.len(),
387                ) != 0
388            },
389            None => false,
390        }
391    }
392
393    /// Transactionally hot-swaps this live instance to a freshly compiled dylib while preserving
394    /// app state.
395    ///
396    /// Snapshots state from the live app, then stages (under a unique filename to avoid Windows
397    /// DLL lock collisions), loads, validates (`nv_get_interface` + `NV_IFACE_SURFACE`),
398    /// instantiates, and restores state on the candidate dylib BEFORE swapping out and unloading
399    /// the existing instance. If any step fails, `self` stays 100% alive and untouched.
400    pub fn reload(&mut self, new_dylib_path: &Path) -> Result<ReloadOutcome, LoaderError> {
401        let bound_host = self.bound_host;
402        let bound_direct = self.bound_direct_host;
403        self.reload_with_hosts(new_dylib_path, bound_host, bound_direct)
404    }
405
406    /// Transactional reload binding `next_host` onto the candidate dylib **once** before swapping
407    /// out and unbinding the previous generation (so a failed reload leaves generation N untouched,
408    /// generation N is unbound BEFORE `destroy`, and generation N+1 is never double-bound).
409    pub fn reload_with_host(
410        &mut self,
411        new_dylib_path: &Path,
412        next_host: Option<NvHostCallbacks>,
413    ) -> Result<ReloadOutcome, LoaderError> {
414        let bound_direct = self.bound_direct_host;
415        self.reload_with_hosts(new_dylib_path, next_host, bound_direct)
416    }
417
418    /// Transactional reload binding both `next_host` (`NV_IFACE_HOST = 5`) and `next_direct`
419    /// (`NV_IFACE_DIRECT_HOST = 6`) onto the candidate dylib once before swapping out old gen.
420    pub fn reload_with_hosts(
421        &mut self,
422        new_dylib_path: &Path,
423        next_host: Option<NvHostCallbacks>,
424        next_direct: Option<NvDirectHostEnv>,
425    ) -> Result<ReloadOutcome, LoaderError> {
426        let surface_id = self.surface_id;
427        let next_gen = self.generation + 1;
428        let (candidate, preserved_state_bytes) = {
429            let saved = self.snapshot_state();
430            let len = saved.len();
431            let prior = (!saved.is_empty()).then_some(saved);
432            (Self::load(new_dylib_path, surface_id, next_gen, prior)?, len)
433        };
434        Ok(self.commit_reloaded_candidate(
435            candidate,
436            next_host,
437            next_direct,
438            preserved_state_bytes,
439            || {},
440            || {},
441        ))
442    }
443
444    /// Transactional reload using caller-captured `prior_state` (avoiding redundant double
445    /// `snapshot_state()` calls) and invoking `on_old_unbound` strictly AFTER `old.bind_host(None)`
446    /// and BEFORE `old`'s `destroy` runs.
447    pub fn reload_with_host_and_state(
448        &mut self,
449        new_dylib_path: &Path,
450        next_host: Option<NvHostCallbacks>,
451        prior_state: Option<&[u8]>,
452        on_old_unbound: impl FnOnce(),
453    ) -> Result<ReloadOutcome, LoaderError> {
454        let next_direct = self.bound_direct_host;
455        self.reload_with_hosts_and_state(
456            new_dylib_path,
457            next_host,
458            next_direct,
459            prior_state,
460            || {},
461            on_old_unbound,
462        )
463    }
464
465    /// Full transactional reload binding both lean `next_host` and `next_direct` onto the candidate
466    /// dylib once, invoking `on_old_direct_deactivate` (deactivating old `DirectSurfaceBinding` and
467    /// cancelling in-flight direct async calls) strictly BEFORE `old.bind_direct_host(None)`,
468    /// invoking `on_old_unbound` strictly AFTER unbinding and BEFORE `old`'s `destroy` + `dlclose`.
469    pub fn reload_with_hosts_and_state(
470        &mut self,
471        new_dylib_path: &Path,
472        next_host: Option<NvHostCallbacks>,
473        next_direct: Option<NvDirectHostEnv>,
474        prior_state: Option<&[u8]>,
475        on_old_direct_deactivate: impl FnOnce(),
476        on_old_unbound: impl FnOnce(),
477    ) -> Result<ReloadOutcome, LoaderError> {
478        let len = prior_state.map_or(0, <[u8]>::len);
479        let candidate =
480            Self::load(new_dylib_path, self.surface_id, self.generation + 1, prior_state)?;
481        Ok(self.commit_reloaded_candidate(
482            candidate,
483            next_host,
484            next_direct,
485            len,
486            on_old_direct_deactivate,
487            on_old_unbound,
488        ))
489    }
490
491    fn commit_reloaded_candidate(
492        &mut self,
493        mut candidate: Self,
494        next_host: Option<NvHostCallbacks>,
495        next_direct: Option<NvDirectHostEnv>,
496        preserved_state_bytes: usize,
497        on_old_direct_deactivate: impl FnOnce(),
498        on_old_unbound: impl FnOnce(),
499    ) -> ReloadOutcome {
500        let previous_generation = self.generation;
501        let next_gen = candidate.generation;
502        if let Some(cb) = next_host {
503            candidate.bind_host(Some(cb));
504        }
505        if let Some(env) = next_direct {
506            candidate.bind_direct_host(Some(env));
507        }
508        let mut old = std::mem::replace(self, candidate);
509        on_old_direct_deactivate();
510        if old.bound_direct_host.is_some() {
511            let _ = old.bind_direct_host(None);
512        }
513        if old.bound_host.is_some() {
514            let _ = old.bind_host(None);
515        }
516        on_old_unbound();
517        drop(old);
518        ReloadOutcome {
519            previous_generation,
520            generation: next_gen,
521            preserved_state_bytes,
522        }
523    }
524}
525
526impl Drop for HotAppInstance {
527    fn drop(&mut self) {
528        if !self.handle.is_null() {
529            if self.bound_direct_host.is_some() {
530                let _ = self.bind_direct_host(None);
531            }
532            if self.bound_host.is_some() {
533                let _ = self.bind_host(None);
534            }
535            // SAFETY: `self.handle` was created by `self.surface.create` and is destroyed once before unloading `module`.
536            unsafe { (self.surface.destroy)(self.handle) };
537            self.handle = std::ptr::null_mut();
538        }
539        drop(self.module.take());
540    }
541}
542