nativeview_engine/loader/
staging.rs1use std::io::Read;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6use std::sync::atomic::{AtomicU64, Ordering};
7
8use libloading::Library;
9use nativeview_abi::{NvGetInterfaceFn, Xxh64Hasher};
10
11use super::LoaderError;
12
13static STAGED_COPY_SEQ: AtomicU64 = AtomicU64::new(1);
14static TOTAL_STAGED_LOADS: AtomicU64 = AtomicU64::new(0);
15
16pub const STAGES_PRIVATE_COPY: bool = !cfg!(any(target_os = "android", target_os = "ios"));
24
25pub const MODULE_STAGE_DIR_ENV: &str = "NV_MODULE_STAGE_DIR";
28
29fn stage_root() -> Option<PathBuf> {
32 match std::env::var_os(MODULE_STAGE_DIR_ENV).filter(|v| !v.is_empty()) {
33 Some(root) => Some(PathBuf::from(root)),
34 None => STAGES_PRIVATE_COPY.then(std::env::temp_dir),
35 }
36}
37
38pub(crate) fn is_macos_app_bundle_frameworks_path(path: &Path) -> bool {
41 use std::ffi::OsStr;
42 use std::path::Component;
43
44 let mut normals: Vec<&OsStr> = Vec::new();
45 let mut ends_with_normal = false;
46 for comp in path.components() {
47 match comp {
48 Component::Normal(s) => {
49 normals.push(s);
50 ends_with_normal = true;
51 }
52 Component::CurDir => {}
53 Component::ParentDir => {
54 normals.pop();
55 ends_with_normal = false;
56 }
57 Component::RootDir | Component::Prefix(_) => {
58 normals.clear();
59 ends_with_normal = false;
60 }
61 }
62 }
63 if !ends_with_normal || normals.len() < 4 {
64 return false;
65 }
66 let parent = &normals[..normals.len() - 1];
67 parent.windows(3).any(|w| {
68 let app_ok = w[0].to_str().is_some_and(|s| {
69 s.len() > 4 && s.as_bytes()[s.len() - 4..].eq_ignore_ascii_case(b".app")
70 });
71 app_ok && w[1] == OsStr::new("Contents") && w[2] == OsStr::new("Frameworks")
72 })
73}
74
75enum LoadStrategy {
76 StageCopy(PathBuf),
77 InPlace { resolved: Option<PathBuf> },
78}
79
80fn resolve_load_strategy(dylib_path: &Path, env_stage_dir: Option<&std::ffi::OsStr>) -> LoadStrategy {
84 if let Some(root) = env_stage_dir.filter(|v| !v.is_empty()) {
85 return LoadStrategy::StageCopy(PathBuf::from(root));
86 }
87 if cfg!(target_os = "macos") {
88 let resolved = std::fs::canonicalize(dylib_path).ok();
89 let check_path = resolved.as_deref().unwrap_or(dylib_path);
90 if is_macos_app_bundle_frameworks_path(check_path) {
91 return LoadStrategy::InPlace { resolved };
92 }
93 }
94 match STAGES_PRIVATE_COPY.then(std::env::temp_dir) {
95 Some(root) => LoadStrategy::StageCopy(root),
96 None => LoadStrategy::InPlace { resolved: None },
97 }
98}
99
100pub fn staging_dir(subdir: &str) -> Option<PathBuf> {
104 stage_root().map(|root| staging_dir_in(&root, subdir))
105}
106
107fn staging_dir_in(root: &Path, subdir: &str) -> PathBuf {
108 #[cfg(unix)]
109 return root.join(format!("{subdir}-{}", unsafe { libc::geteuid() }));
111 #[cfg(not(unix))]
112 return root.join(subdir);
113}
114
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117struct FileDigest {
118 len: u64,
119 xxh64: u64,
120}
121
122fn hash_open_file(file: &mut std::fs::File) -> std::io::Result<FileDigest> {
123 let mut hasher = Xxh64Hasher::new(0);
124 let mut buf = [0u8; 16 * 1024];
125 let mut len = 0u64;
126 loop {
127 match file.read(&mut buf) {
128 Ok(0) => break,
129 Ok(n) => {
130 len = len.saturating_add(n as u64);
131 hasher.update(&buf[..n]);
132 }
133 Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
134 Err(err) => return Err(err),
135 }
136 }
137 Ok(FileDigest { len, xxh64: hasher.digest() })
138}
139
140struct InPlaceEntry {
141 inode: Option<(u64, u64)>,
143 resolved_path: PathBuf,
145 digest: FileDigest,
146 pending: usize,
148 sealed: bool,
150}
151
152static IN_PLACE_FILES: Mutex<Vec<InPlaceEntry>> = Mutex::new(Vec::new());
158
159struct InPlaceClaim {
163 inode: Option<(u64, u64)>,
164 resolved_path: PathBuf,
165 digest: FileDigest,
166 sealed: bool,
167}
168
169impl InPlaceClaim {
170 #[cfg(all(test, unix))]
171 fn new(path: &Path) -> Result<Self, LoaderError> {
172 Self::new_with_resolved(path, None)
173 }
174
175 fn new_with_resolved(path: &Path, pre_resolved: Option<PathBuf>) -> Result<Self, LoaderError> {
176 let resolved_path = pre_resolved.unwrap_or_else(|| {
177 std::fs::canonicalize(path)
178 .or_else(|_| std::path::absolute(path))
179 .unwrap_or_else(|_| path.to_path_buf())
180 });
181 let mut file = std::fs::File::open(&resolved_path).map_err(LoaderError::Io)?;
182 let meta = file.metadata().map_err(LoaderError::Io)?;
183 #[cfg(unix)]
184 let inode = {
185 use std::os::unix::fs::MetadataExt;
186 Some((meta.dev(), meta.ino()))
187 };
188 #[cfg(not(unix))]
189 let inode = {
190 let _ = meta;
191 None
192 };
193 let digest = hash_open_file(&mut file).map_err(LoaderError::Io)?;
194
195 let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
196 for entry in loaded.iter() {
197 let same_inode = inode.is_some() && entry.inode == inode;
198 let same_path = entry.resolved_path == resolved_path;
199 if (same_inode || same_path) && entry.digest != digest {
200 return Err(LoaderError::AlreadyLoadedInPlace(resolved_path));
201 }
202 }
203 if let Some(existing) = loaded.iter_mut().find(|e| {
204 e.inode == inode && e.resolved_path == resolved_path && e.digest == digest
205 }) {
206 existing.pending += 1;
207 } else {
208 loaded.push(InPlaceEntry {
209 inode,
210 resolved_path: resolved_path.clone(),
211 digest,
212 pending: 1,
213 sealed: false,
214 });
215 }
216 Ok(Self { inode, resolved_path, digest, sealed: false })
217 }
218
219 fn resolved_path(&self) -> &Path {
220 &self.resolved_path
221 }
222
223 fn seal(&mut self) {
225 if self.sealed {
226 return;
227 }
228 self.sealed = true;
229 let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
230 if let Some(entry) = loaded.iter_mut().find(|e| {
231 e.inode == self.inode
232 && e.resolved_path == self.resolved_path
233 && e.digest == self.digest
234 }) {
235 entry.sealed = true;
236 entry.pending = entry.pending.saturating_sub(1);
237 }
238 }
239}
240
241impl Drop for InPlaceClaim {
242 fn drop(&mut self) {
243 if self.sealed {
244 return;
245 }
246 let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
247 if let Some(at) = loaded.iter().position(|e| {
248 e.inode == self.inode
249 && e.resolved_path == self.resolved_path
250 && e.digest == self.digest
251 }) {
252 loaded[at].pending = loaded[at].pending.saturating_sub(1);
253 if !loaded[at].sealed && loaded[at].pending == 0 {
254 loaded.swap_remove(at);
255 }
256 }
257 }
258}
259
260pub struct StagedDylib {
267 lib: Option<Library>,
268 get_interface: NvGetInterfaceFn,
269 loaded_path: PathBuf,
270 owns_copy: bool,
272 _in_place: Option<InPlaceClaim>,
274}
275
276pub fn is_valid_nv_interface_symbol(symbol: &str) -> bool {
279 if symbol == "nv_get_interface" {
280 return true;
281 }
282 let Some(suffix) = symbol.strip_prefix("nv_get_interface_") else {
283 return false;
284 };
285 !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
286}
287
288fn symbol_c_bytes(symbol: &str) -> Vec<u8> {
289 let mut bytes = Vec::with_capacity(symbol.len() + 1);
290 bytes.extend_from_slice(symbol.as_bytes());
291 bytes.push(0);
292 bytes
293}
294
295pub fn resolve_in_process_symbol(symbol: &str) -> Result<NvGetInterfaceFn, LoaderError> {
297 if !is_valid_nv_interface_symbol(symbol) {
298 return Err(LoaderError::InvalidSymbol);
299 }
300 let sym_nul = symbol_c_bytes(symbol);
301 #[cfg(unix)]
302 {
303 let ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, sym_nul.as_ptr().cast()) };
305 if ptr.is_null() {
306 return Err(LoaderError::MissingSymbol);
307 }
308 const {
309 assert!(
310 core::mem::size_of::<*mut libc::c_void>()
311 == core::mem::size_of::<NvGetInterfaceFn>()
312 );
313 }
314 Ok(unsafe { core::mem::transmute::<*mut libc::c_void, NvGetInterfaceFn>(ptr) })
316 }
317 #[cfg(windows)]
318 {
319 let lib = libloading::os::windows::Library::this().map_err(LoaderError::Load)?;
320 let sym = unsafe { lib.get::<NvGetInterfaceFn>(sym_nul.as_slice()) }
322 .map_err(LoaderError::MissingEntry)?;
323 Ok(*sym)
324 }
325 #[cfg(not(any(unix, windows)))]
326 {
327 let _ = sym_nul;
328 Err(LoaderError::MissingSymbol)
329 }
330}
331
332impl StagedDylib {
333 pub fn load(dylib_path: &Path, subdir: &str, label: &str) -> Result<Self, LoaderError> {
334 Self::load_symbol(dylib_path, "nv_get_interface", subdir, label)
335 }
336
337 pub fn load_symbol(
338 dylib_path: &Path,
339 symbol: &str,
340 subdir: &str,
341 label: &str,
342 ) -> Result<Self, LoaderError> {
343 if !is_valid_nv_interface_symbol(symbol) {
344 return Err(LoaderError::InvalidSymbol);
345 }
346 let env_dir = std::env::var_os(MODULE_STAGE_DIR_ENV);
347 Self::load_with_strategy(
348 dylib_path,
349 symbol,
350 resolve_load_strategy(dylib_path, env_dir.as_deref()),
351 subdir,
352 label,
353 )
354 }
355
356 #[cfg(all(test, unix))]
357 fn load_with_root(
358 dylib_path: &Path,
359 root: Option<&Path>,
360 subdir: &str,
361 label: &str,
362 ) -> Result<Self, LoaderError> {
363 let strategy = match root {
364 Some(r) => LoadStrategy::StageCopy(r.to_path_buf()),
365 None => LoadStrategy::InPlace { resolved: None },
366 };
367 Self::load_with_strategy(dylib_path, "nv_get_interface", strategy, subdir, label)
368 }
369
370 fn load_with_strategy(
371 dylib_path: &Path,
372 symbol: &str,
373 strategy: LoadStrategy,
374 subdir: &str,
375 label: &str,
376 ) -> Result<Self, LoaderError> {
377 let sym_nul = symbol_c_bytes(symbol);
378 let (loaded_path, owns_copy, mut in_place) = match strategy {
379 LoadStrategy::StageCopy(root) => {
380 (stage_private_copy(&root, dylib_path, subdir, label)?, true, None)
381 }
382 LoadStrategy::InPlace { resolved } => {
383 let claim = InPlaceClaim::new_with_resolved(dylib_path, resolved)?;
384 (claim.resolved_path().to_path_buf(), false, Some(claim))
385 }
386 };
387 let discard = |path: &Path| {
388 if owns_copy {
389 let _ = std::fs::remove_file(path);
390 }
391 };
392 let lib = match unsafe { Library::new(&loaded_path) } {
394 Ok(lib) => {
395 if let Some(claim) = in_place.as_mut() {
398 claim.seal();
399 }
400 lib
401 }
402 Err(err) => {
403 discard(&loaded_path);
404 return Err(LoaderError::Load(err));
405 }
406 };
407 let get_interface: NvGetInterfaceFn = match unsafe {
409 lib.get::<NvGetInterfaceFn>(sym_nul.as_slice())
410 } {
411 Ok(sym) => *sym,
412 Err(err) => {
413 drop(lib);
414 discard(&loaded_path);
415 return Err(LoaderError::MissingEntry(err));
416 }
417 };
418 TOTAL_STAGED_LOADS.fetch_add(1, Ordering::Relaxed);
419 Ok(Self {
420 lib: Some(lib),
421 get_interface,
422 loaded_path,
423 owns_copy,
424 _in_place: in_place,
425 })
426 }
427
428 #[inline]
432 pub fn total_staged_loads() -> u64 {
433 TOTAL_STAGED_LOADS.load(Ordering::Relaxed)
434 }
435
436 pub fn get_interface(&self) -> NvGetInterfaceFn {
437 self.get_interface
438 }
439
440 pub fn loaded_copy_path(&self) -> &Path {
442 &self.loaded_path
443 }
444}
445
446impl Drop for StagedDylib {
447 fn drop(&mut self) {
448 drop(self.lib.take());
451 if self.owns_copy {
452 let _ = std::fs::remove_file(&self.loaded_path);
453 }
454 }
455}
456
457fn stage_private_copy(
464 root: &Path,
465 dylib_path: &Path,
466 subdir: &str,
467 label: &str,
468) -> Result<PathBuf, LoaderError> {
469 const MAX_NAME_ATTEMPTS: u32 = 16;
471 let ext = dylib_path
472 .extension()
473 .and_then(|e| e.to_str())
474 .unwrap_or(std::env::consts::DLL_EXTENSION);
475 let stem = dylib_path
476 .file_stem()
477 .and_then(|s| s.to_str())
478 .unwrap_or("nv_app");
479 let dir = staging_dir_in(root, subdir);
480 let mut src = std::fs::File::open(dylib_path).map_err(LoaderError::Io)?;
481
482 #[cfg(unix)]
483 {
484 use std::ffi::CString;
485 use std::os::fd::{AsRawFd, FromRawFd};
486
487 let dir_fd = open_private_dir(&dir).map_err(LoaderError::Io)?;
488 let mut attempt = 0u32;
489 let (file_name, c_name, mut dst) = loop {
490 let seq = STAGED_COPY_SEQ.fetch_add(1, Ordering::Relaxed);
491 let file_name = format!("{stem}_{label}_{}_{seq}.{ext}", std::process::id());
492 if file_name.contains('/') {
493 return Err(LoaderError::Io(std::io::Error::new(
494 std::io::ErrorKind::InvalidInput,
495 format!("staged library filename contains path separator: {file_name}"),
496 )));
497 }
498 let c_name = CString::new(file_name.as_str()).map_err(|_| {
499 LoaderError::Io(std::io::Error::new(
500 std::io::ErrorKind::InvalidInput,
501 "staged library filename contains interior NUL",
502 ))
503 })?;
504 let fd = unsafe {
507 libc::openat(
508 dir_fd.as_raw_fd(),
509 c_name.as_ptr(),
510 libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
511 0o600 as libc::c_uint,
512 )
513 };
514 if fd >= 0 {
515 let file = unsafe { std::fs::File::from_raw_fd(fd) };
517 break (file_name, c_name, file);
518 }
519 let err = std::io::Error::last_os_error();
520 if err.kind() == std::io::ErrorKind::AlreadyExists && attempt + 1 < MAX_NAME_ATTEMPTS {
521 attempt += 1;
522 } else {
523 return Err(LoaderError::Io(err));
524 }
525 };
526 if let Err(err) = std::io::copy(&mut src, &mut dst).and_then(|_| dst.sync_all()) {
527 drop(dst);
528 let _ = unsafe { libc::unlinkat(dir_fd.as_raw_fd(), c_name.as_ptr(), 0) };
530 return Err(LoaderError::Io(err));
531 }
532 Ok(dir.join(file_name))
533 }
534
535 #[cfg(not(unix))]
536 {
537 let dir = ensure_private_dir_non_unix(dir).map_err(LoaderError::Io)?;
538 let mut options = std::fs::OpenOptions::new();
539 options.write(true).create_new(true);
540 let mut attempt = 0u32;
541 let (copy, mut dst) = loop {
542 let seq = STAGED_COPY_SEQ.fetch_add(1, Ordering::Relaxed);
543 let copy = dir.join(format!("{stem}_{label}_{}_{seq}.{ext}", std::process::id()));
544 match options.open(©) {
545 Ok(file) => break (copy, file),
546 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists && attempt + 1 < MAX_NAME_ATTEMPTS => {
547 attempt += 1;
548 }
549 Err(err) => return Err(LoaderError::Io(err)),
550 }
551 };
552 if let Err(err) = std::io::copy(&mut src, &mut dst).and_then(|_| dst.sync_all()) {
553 drop(dst);
554 let _ = std::fs::remove_file(©);
555 return Err(LoaderError::Io(err));
556 }
557 Ok(copy)
558 }
559}
560
561#[cfg(unix)]
565fn open_private_dir(dir: &Path) -> std::io::Result<std::os::fd::OwnedFd> {
566 use std::ffi::CString;
567 use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
568 use std::os::unix::ffi::OsStrExt;
569
570 let c_dir = CString::new(dir.as_os_str().as_bytes()).map_err(|_| {
571 std::io::Error::new(std::io::ErrorKind::InvalidInput, "staging dir contains interior NUL")
572 })?;
573 if unsafe { libc::mkdir(c_dir.as_ptr(), 0o700) } != 0 {
575 let err = std::io::Error::last_os_error();
576 if err.kind() != std::io::ErrorKind::AlreadyExists {
577 return Err(err);
578 }
579 }
580 let fd = unsafe {
582 libc::open(
583 c_dir.as_ptr(),
584 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
585 )
586 };
587 if fd < 0 {
588 return Err(std::io::Error::last_os_error());
589 }
590 let dir_fd = unsafe { OwnedFd::from_raw_fd(fd) };
592
593 let mut st = std::mem::MaybeUninit::<libc::stat>::uninit();
594 if unsafe { libc::fstat(dir_fd.as_raw_fd(), st.as_mut_ptr()) } != 0 {
596 return Err(std::io::Error::last_os_error());
597 }
598 let st = unsafe { st.assume_init() };
600 #[allow(clippy::useless_conversion)]
602 let is_dir = (u32::from(st.st_mode) & u32::from(libc::S_IFMT)) == u32::from(libc::S_IFDIR);
603 if !is_dir {
604 return Err(std::io::Error::other(format!(
605 "staging path {} is not a directory",
606 dir.display()
607 )));
608 }
609 let euid = unsafe { libc::geteuid() };
611 if st.st_uid != euid {
612 return Err(std::io::Error::new(
613 std::io::ErrorKind::PermissionDenied,
614 format!("staging dir {} is owned by uid {}, not {euid}", dir.display(), st.st_uid),
615 ));
616 }
617 if unsafe { libc::fchmod(dir_fd.as_raw_fd(), 0o700) } != 0 {
619 return Err(std::io::Error::last_os_error());
620 }
621 Ok(dir_fd)
622}
623
624#[cfg(not(unix))]
625fn ensure_private_dir_non_unix(dir: PathBuf) -> std::io::Result<PathBuf> {
626 match std::fs::DirBuilder::new().create(&dir) {
627 Ok(()) => return Ok(dir),
628 Err(err) if err.kind() != std::io::ErrorKind::AlreadyExists => return Err(err),
629 Err(_) => {}
630 }
631 let meta = std::fs::symlink_metadata(&dir)?;
632 if !meta.file_type().is_dir() {
633 return Err(std::io::Error::other(format!(
634 "staging path {} is not a directory",
635 dir.display()
636 )));
637 }
638 Ok(dir)
639}
640
641#[cfg(all(test, unix))]
642#[path = "staging_tests.rs"]
643mod staging_tests;