use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use libloading::Library;
use nativeview_abi::{NvGetInterfaceFn, Xxh64Hasher};
use super::LoaderError;
static STAGED_COPY_SEQ: AtomicU64 = AtomicU64::new(1);
static TOTAL_STAGED_LOADS: AtomicU64 = AtomicU64::new(0);
pub const STAGES_PRIVATE_COPY: bool = !cfg!(any(target_os = "android", target_os = "ios"));
pub const MODULE_STAGE_DIR_ENV: &str = "NV_MODULE_STAGE_DIR";
fn stage_root() -> Option<PathBuf> {
match std::env::var_os(MODULE_STAGE_DIR_ENV).filter(|v| !v.is_empty()) {
Some(root) => Some(PathBuf::from(root)),
None => STAGES_PRIVATE_COPY.then(std::env::temp_dir),
}
}
pub(crate) fn is_macos_app_bundle_frameworks_path(path: &Path) -> bool {
use std::ffi::OsStr;
use std::path::Component;
let mut normals: Vec<&OsStr> = Vec::new();
let mut ends_with_normal = false;
for comp in path.components() {
match comp {
Component::Normal(s) => {
normals.push(s);
ends_with_normal = true;
}
Component::CurDir => {}
Component::ParentDir => {
normals.pop();
ends_with_normal = false;
}
Component::RootDir | Component::Prefix(_) => {
normals.clear();
ends_with_normal = false;
}
}
}
if !ends_with_normal || normals.len() < 4 {
return false;
}
let parent = &normals[..normals.len() - 1];
parent.windows(3).any(|w| {
let app_ok = w[0].to_str().is_some_and(|s| {
s.len() > 4 && s.as_bytes()[s.len() - 4..].eq_ignore_ascii_case(b".app")
});
app_ok && w[1] == OsStr::new("Contents") && w[2] == OsStr::new("Frameworks")
})
}
enum LoadStrategy {
StageCopy(PathBuf),
InPlace { resolved: Option<PathBuf> },
}
fn resolve_load_strategy(dylib_path: &Path, env_stage_dir: Option<&std::ffi::OsStr>) -> LoadStrategy {
if let Some(root) = env_stage_dir.filter(|v| !v.is_empty()) {
return LoadStrategy::StageCopy(PathBuf::from(root));
}
if cfg!(target_os = "macos") {
let resolved = std::fs::canonicalize(dylib_path).ok();
let check_path = resolved.as_deref().unwrap_or(dylib_path);
if is_macos_app_bundle_frameworks_path(check_path) {
return LoadStrategy::InPlace { resolved };
}
}
match STAGES_PRIVATE_COPY.then(std::env::temp_dir) {
Some(root) => LoadStrategy::StageCopy(root),
None => LoadStrategy::InPlace { resolved: None },
}
}
pub fn staging_dir(subdir: &str) -> Option<PathBuf> {
stage_root().map(|root| staging_dir_in(&root, subdir))
}
fn staging_dir_in(root: &Path, subdir: &str) -> PathBuf {
#[cfg(unix)]
return root.join(format!("{subdir}-{}", unsafe { libc::geteuid() }));
#[cfg(not(unix))]
return root.join(subdir);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FileDigest {
len: u64,
xxh64: u64,
}
fn hash_open_file(file: &mut std::fs::File) -> std::io::Result<FileDigest> {
let mut hasher = Xxh64Hasher::new(0);
let mut buf = [0u8; 16 * 1024];
let mut len = 0u64;
loop {
match file.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
len = len.saturating_add(n as u64);
hasher.update(&buf[..n]);
}
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
}
}
Ok(FileDigest { len, xxh64: hasher.digest() })
}
struct InPlaceEntry {
inode: Option<(u64, u64)>,
resolved_path: PathBuf,
digest: FileDigest,
pending: usize,
sealed: bool,
}
static IN_PLACE_FILES: Mutex<Vec<InPlaceEntry>> = Mutex::new(Vec::new());
struct InPlaceClaim {
inode: Option<(u64, u64)>,
resolved_path: PathBuf,
digest: FileDigest,
sealed: bool,
}
impl InPlaceClaim {
#[cfg(all(test, unix))]
fn new(path: &Path) -> Result<Self, LoaderError> {
Self::new_with_resolved(path, None)
}
fn new_with_resolved(path: &Path, pre_resolved: Option<PathBuf>) -> Result<Self, LoaderError> {
let resolved_path = pre_resolved.unwrap_or_else(|| {
std::fs::canonicalize(path)
.or_else(|_| std::path::absolute(path))
.unwrap_or_else(|_| path.to_path_buf())
});
let mut file = std::fs::File::open(&resolved_path).map_err(LoaderError::Io)?;
let meta = file.metadata().map_err(LoaderError::Io)?;
#[cfg(unix)]
let inode = {
use std::os::unix::fs::MetadataExt;
Some((meta.dev(), meta.ino()))
};
#[cfg(not(unix))]
let inode = {
let _ = meta;
None
};
let digest = hash_open_file(&mut file).map_err(LoaderError::Io)?;
let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for entry in loaded.iter() {
let same_inode = inode.is_some() && entry.inode == inode;
let same_path = entry.resolved_path == resolved_path;
if (same_inode || same_path) && entry.digest != digest {
return Err(LoaderError::AlreadyLoadedInPlace(resolved_path));
}
}
if let Some(existing) = loaded.iter_mut().find(|e| {
e.inode == inode && e.resolved_path == resolved_path && e.digest == digest
}) {
existing.pending += 1;
} else {
loaded.push(InPlaceEntry {
inode,
resolved_path: resolved_path.clone(),
digest,
pending: 1,
sealed: false,
});
}
Ok(Self { inode, resolved_path, digest, sealed: false })
}
fn resolved_path(&self) -> &Path {
&self.resolved_path
}
fn seal(&mut self) {
if self.sealed {
return;
}
self.sealed = true;
let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(entry) = loaded.iter_mut().find(|e| {
e.inode == self.inode
&& e.resolved_path == self.resolved_path
&& e.digest == self.digest
}) {
entry.sealed = true;
entry.pending = entry.pending.saturating_sub(1);
}
}
}
impl Drop for InPlaceClaim {
fn drop(&mut self) {
if self.sealed {
return;
}
let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(at) = loaded.iter().position(|e| {
e.inode == self.inode
&& e.resolved_path == self.resolved_path
&& e.digest == self.digest
}) {
loaded[at].pending = loaded[at].pending.saturating_sub(1);
if !loaded[at].sealed && loaded[at].pending == 0 {
loaded.swap_remove(at);
}
}
}
}
pub struct StagedDylib {
lib: Option<Library>,
get_interface: NvGetInterfaceFn,
loaded_path: PathBuf,
owns_copy: bool,
_in_place: Option<InPlaceClaim>,
}
pub fn is_valid_nv_interface_symbol(symbol: &str) -> bool {
if symbol == "nv_get_interface" {
return true;
}
let Some(suffix) = symbol.strip_prefix("nv_get_interface_") else {
return false;
};
!suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
}
fn symbol_c_bytes(symbol: &str) -> Vec<u8> {
let mut bytes = Vec::with_capacity(symbol.len() + 1);
bytes.extend_from_slice(symbol.as_bytes());
bytes.push(0);
bytes
}
pub fn resolve_in_process_symbol(symbol: &str) -> Result<NvGetInterfaceFn, LoaderError> {
if !is_valid_nv_interface_symbol(symbol) {
return Err(LoaderError::InvalidSymbol);
}
let sym_nul = symbol_c_bytes(symbol);
#[cfg(unix)]
{
let ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, sym_nul.as_ptr().cast()) };
if ptr.is_null() {
return Err(LoaderError::MissingSymbol);
}
const {
assert!(
core::mem::size_of::<*mut libc::c_void>()
== core::mem::size_of::<NvGetInterfaceFn>()
);
}
Ok(unsafe { core::mem::transmute::<*mut libc::c_void, NvGetInterfaceFn>(ptr) })
}
#[cfg(windows)]
{
let lib = libloading::os::windows::Library::this().map_err(LoaderError::Load)?;
let sym = unsafe { lib.get::<NvGetInterfaceFn>(sym_nul.as_slice()) }
.map_err(LoaderError::MissingEntry)?;
Ok(*sym)
}
#[cfg(not(any(unix, windows)))]
{
let _ = sym_nul;
Err(LoaderError::MissingSymbol)
}
}
impl StagedDylib {
pub fn load(dylib_path: &Path, subdir: &str, label: &str) -> Result<Self, LoaderError> {
Self::load_symbol(dylib_path, "nv_get_interface", subdir, label)
}
pub fn load_symbol(
dylib_path: &Path,
symbol: &str,
subdir: &str,
label: &str,
) -> Result<Self, LoaderError> {
if !is_valid_nv_interface_symbol(symbol) {
return Err(LoaderError::InvalidSymbol);
}
let env_dir = std::env::var_os(MODULE_STAGE_DIR_ENV);
Self::load_with_strategy(
dylib_path,
symbol,
resolve_load_strategy(dylib_path, env_dir.as_deref()),
subdir,
label,
)
}
#[cfg(all(test, unix))]
fn load_with_root(
dylib_path: &Path,
root: Option<&Path>,
subdir: &str,
label: &str,
) -> Result<Self, LoaderError> {
let strategy = match root {
Some(r) => LoadStrategy::StageCopy(r.to_path_buf()),
None => LoadStrategy::InPlace { resolved: None },
};
Self::load_with_strategy(dylib_path, "nv_get_interface", strategy, subdir, label)
}
fn load_with_strategy(
dylib_path: &Path,
symbol: &str,
strategy: LoadStrategy,
subdir: &str,
label: &str,
) -> Result<Self, LoaderError> {
let sym_nul = symbol_c_bytes(symbol);
let (loaded_path, owns_copy, mut in_place) = match strategy {
LoadStrategy::StageCopy(root) => {
(stage_private_copy(&root, dylib_path, subdir, label)?, true, None)
}
LoadStrategy::InPlace { resolved } => {
let claim = InPlaceClaim::new_with_resolved(dylib_path, resolved)?;
(claim.resolved_path().to_path_buf(), false, Some(claim))
}
};
let discard = |path: &Path| {
if owns_copy {
let _ = std::fs::remove_file(path);
}
};
let lib = match unsafe { Library::new(&loaded_path) } {
Ok(lib) => {
if let Some(claim) = in_place.as_mut() {
claim.seal();
}
lib
}
Err(err) => {
discard(&loaded_path);
return Err(LoaderError::Load(err));
}
};
let get_interface: NvGetInterfaceFn = match unsafe {
lib.get::<NvGetInterfaceFn>(sym_nul.as_slice())
} {
Ok(sym) => *sym,
Err(err) => {
drop(lib);
discard(&loaded_path);
return Err(LoaderError::MissingEntry(err));
}
};
TOTAL_STAGED_LOADS.fetch_add(1, Ordering::Relaxed);
Ok(Self {
lib: Some(lib),
get_interface,
loaded_path,
owns_copy,
_in_place: in_place,
})
}
#[inline]
pub fn total_staged_loads() -> u64 {
TOTAL_STAGED_LOADS.load(Ordering::Relaxed)
}
pub fn get_interface(&self) -> NvGetInterfaceFn {
self.get_interface
}
pub fn loaded_copy_path(&self) -> &Path {
&self.loaded_path
}
}
impl Drop for StagedDylib {
fn drop(&mut self) {
drop(self.lib.take());
if self.owns_copy {
let _ = std::fs::remove_file(&self.loaded_path);
}
}
}
fn stage_private_copy(
root: &Path,
dylib_path: &Path,
subdir: &str,
label: &str,
) -> Result<PathBuf, LoaderError> {
const MAX_NAME_ATTEMPTS: u32 = 16;
let ext = dylib_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or(std::env::consts::DLL_EXTENSION);
let stem = dylib_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("nv_app");
let dir = staging_dir_in(root, subdir);
let mut src = std::fs::File::open(dylib_path).map_err(LoaderError::Io)?;
#[cfg(unix)]
{
use std::ffi::CString;
use std::os::fd::{AsRawFd, FromRawFd};
let dir_fd = open_private_dir(&dir).map_err(LoaderError::Io)?;
let mut attempt = 0u32;
let (file_name, c_name, mut dst) = loop {
let seq = STAGED_COPY_SEQ.fetch_add(1, Ordering::Relaxed);
let file_name = format!("{stem}_{label}_{}_{seq}.{ext}", std::process::id());
if file_name.contains('/') {
return Err(LoaderError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("staged library filename contains path separator: {file_name}"),
)));
}
let c_name = CString::new(file_name.as_str()).map_err(|_| {
LoaderError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"staged library filename contains interior NUL",
))
})?;
let fd = unsafe {
libc::openat(
dir_fd.as_raw_fd(),
c_name.as_ptr(),
libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
0o600 as libc::c_uint,
)
};
if fd >= 0 {
let file = unsafe { std::fs::File::from_raw_fd(fd) };
break (file_name, c_name, file);
}
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::AlreadyExists && attempt + 1 < MAX_NAME_ATTEMPTS {
attempt += 1;
} else {
return Err(LoaderError::Io(err));
}
};
if let Err(err) = std::io::copy(&mut src, &mut dst).and_then(|_| dst.sync_all()) {
drop(dst);
let _ = unsafe { libc::unlinkat(dir_fd.as_raw_fd(), c_name.as_ptr(), 0) };
return Err(LoaderError::Io(err));
}
Ok(dir.join(file_name))
}
#[cfg(not(unix))]
{
let dir = ensure_private_dir_non_unix(dir).map_err(LoaderError::Io)?;
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
let mut attempt = 0u32;
let (copy, mut dst) = loop {
let seq = STAGED_COPY_SEQ.fetch_add(1, Ordering::Relaxed);
let copy = dir.join(format!("{stem}_{label}_{}_{seq}.{ext}", std::process::id()));
match options.open(©) {
Ok(file) => break (copy, file),
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists && attempt + 1 < MAX_NAME_ATTEMPTS => {
attempt += 1;
}
Err(err) => return Err(LoaderError::Io(err)),
}
};
if let Err(err) = std::io::copy(&mut src, &mut dst).and_then(|_| dst.sync_all()) {
drop(dst);
let _ = std::fs::remove_file(©);
return Err(LoaderError::Io(err));
}
Ok(copy)
}
}
#[cfg(unix)]
fn open_private_dir(dir: &Path) -> std::io::Result<std::os::fd::OwnedFd> {
use std::ffi::CString;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
let c_dir = CString::new(dir.as_os_str().as_bytes()).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidInput, "staging dir contains interior NUL")
})?;
if unsafe { libc::mkdir(c_dir.as_ptr(), 0o700) } != 0 {
let err = std::io::Error::last_os_error();
if err.kind() != std::io::ErrorKind::AlreadyExists {
return Err(err);
}
}
let fd = unsafe {
libc::open(
c_dir.as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
)
};
if fd < 0 {
return Err(std::io::Error::last_os_error());
}
let dir_fd = unsafe { OwnedFd::from_raw_fd(fd) };
let mut st = std::mem::MaybeUninit::<libc::stat>::uninit();
if unsafe { libc::fstat(dir_fd.as_raw_fd(), st.as_mut_ptr()) } != 0 {
return Err(std::io::Error::last_os_error());
}
let st = unsafe { st.assume_init() };
#[allow(clippy::useless_conversion)]
let is_dir = (u32::from(st.st_mode) & u32::from(libc::S_IFMT)) == u32::from(libc::S_IFDIR);
if !is_dir {
return Err(std::io::Error::other(format!(
"staging path {} is not a directory",
dir.display()
)));
}
let euid = unsafe { libc::geteuid() };
if st.st_uid != euid {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!("staging dir {} is owned by uid {}, not {euid}", dir.display(), st.st_uid),
));
}
if unsafe { libc::fchmod(dir_fd.as_raw_fd(), 0o700) } != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(dir_fd)
}
#[cfg(not(unix))]
fn ensure_private_dir_non_unix(dir: PathBuf) -> std::io::Result<PathBuf> {
match std::fs::DirBuilder::new().create(&dir) {
Ok(()) => return Ok(dir),
Err(err) if err.kind() != std::io::ErrorKind::AlreadyExists => return Err(err),
Err(_) => {}
}
let meta = std::fs::symlink_metadata(&dir)?;
if !meta.file_type().is_dir() {
return Err(std::io::Error::other(format!(
"staging path {} is not a directory",
dir.display()
)));
}
Ok(dir)
}
#[cfg(all(test, unix))]
#[path = "staging_tests.rs"]
mod staging_tests;