use crate::error::{Error, Result};
use crate::namespace::Namespace;
use crate::vfs::VirtualFs;
use std::path::PathBuf;
use std::sync::Arc;
#[cfg(hookfs_backend)]
use crate::dispatch::{self, Sym};
#[cfg(hookfs_backend)]
use crate::router::Engine;
#[cfg(hookfs_backend)]
use std::sync::Mutex;
#[derive(Debug, Clone)]
pub enum Scope {
Module(usize),
AllModules,
Only(Vec<String>),
Exclude(Vec<String>),
}
enum Matcher {
Namespace(Namespace),
Predicate(Box<dyn Fn(&std::path::Path) -> bool + Send + Sync>),
}
pub struct Options {
scope: Scope,
allow_writes: bool,
auto_rescan: bool,
matcher: Option<Matcher>,
}
impl std::fmt::Debug for Options {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Options")
.field("scope", &self.scope)
.field("allow_writes", &self.allow_writes)
.field("auto_rescan", &self.auto_rescan)
.field("custom_matcher", &self.matcher.is_some())
.finish()
}
}
impl Default for Options {
fn default() -> Self {
Self {
scope: Scope::AllModules,
allow_writes: false,
auto_rescan: false,
matcher: None,
}
}
}
impl Options {
#[must_use]
pub fn for_module(address: *const core::ffi::c_void) -> Self {
Self {
scope: Scope::Module(address as usize),
..Self::default()
}
}
#[must_use]
pub fn for_prefix(prefix: impl Into<PathBuf>) -> Self {
Self {
matcher: Some(Matcher::Namespace(Namespace::for_prefix(prefix))),
..Self::default()
}
}
#[must_use]
pub fn scope(mut self, scope: Scope) -> Self {
self.scope = scope;
self
}
#[must_use]
pub fn allow_writes(mut self, allow: bool) -> Self {
self.allow_writes = allow;
self
}
#[must_use]
pub fn auto_rescan(mut self, enable: bool) -> Self {
self.auto_rescan = enable;
self
}
#[must_use]
pub fn is_virtual(
mut self,
predicate: impl Fn(&std::path::Path) -> bool + Send + Sync + 'static,
) -> Self {
self.matcher = Some(Matcher::Predicate(Box::new(predicate)));
self
}
pub(crate) fn into_parts(self) -> (Scope, bool, bool) {
(self.scope, self.allow_writes, self.auto_rescan)
}
}
pub fn install(vfs: Arc<dyn VirtualFs>, opts: Options) -> Result<InstallGuard> {
let namespace = match opts.matcher {
Some(Matcher::Namespace(ns)) => ns,
Some(Matcher::Predicate(pred)) => Namespace::with_predicate(pred),
None => Namespace::reserved(),
};
install_with_namespace(
vfs,
namespace,
opts.scope,
opts.allow_writes,
opts.auto_rescan,
)
}
#[cfg(hookfs_backend)]
pub(crate) fn install_with_namespace(
vfs: Arc<dyn VirtualFs>,
namespace: Namespace,
scope: Scope,
allow_writes: bool,
auto_rescan: bool,
) -> Result<InstallGuard> {
let modules = resolve_modules(&scope)?;
if modules.is_empty() {
return Err(Error::NoTargetModule("scope matched no loaded module"));
}
let engine = Arc::new(Engine::new(vfs, namespace, allow_writes));
let install_id = dispatch::try_activate(engine.clone()).ok_or(Error::AlreadyInstalled)?;
preresolve_originals();
let replacements = build_replacements(auto_rescan);
let sdk_dir = anchor_dir(&scope);
let installer = Arc::new(Installer {
scope,
sdk_dir,
auto_rescan,
install_id,
guards: Mutex::new(Vec::new()),
hooked_bases: Mutex::new(std::collections::HashSet::new()),
_engine: engine,
});
for module in &modules {
match plthook::install(module, &replacements) {
Ok(guard) => {
refresh_originals(&guard);
installer
.hooked_bases
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(module.base() as usize);
installer
.guards
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(guard);
}
Err(err) => {
installer.uninstall_all();
dispatch::deactivate(install_id);
return Err(Error::Engine(err));
}
}
}
if auto_rescan {
let installer_for_cb = installer.clone();
dispatch::set_rescan(Arc::new(move || {
let _ = installer_for_cb.rescan();
}));
}
Ok(InstallGuard { installer })
}
#[cfg(hookfs_backend)]
struct Installer {
scope: Scope,
sdk_dir: Option<String>,
auto_rescan: bool,
install_id: u64,
guards: Mutex<Vec<plthook::HookGuard>>,
hooked_bases: Mutex<std::collections::HashSet<usize>>,
_engine: Arc<Engine>,
}
#[cfg(hookfs_backend)]
impl Installer {
fn rescan(&self) -> Result<usize> {
let replacements = build_replacements(self.auto_rescan);
let modules = plthook::Module::enumerate().map_err(Error::Engine)?;
let mut count = 0;
for module in modules {
let base = module.base() as usize;
if !self.should_rescan_hook(&module) {
continue;
}
{
let mut bases = self
.hooked_bases
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if bases.contains(&base) {
continue;
}
bases.insert(base);
}
if let Ok(guard) = plthook::install(&module, &replacements) {
refresh_originals(&guard);
self.guards
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(guard);
count += 1;
}
}
Ok(count)
}
fn should_rescan_hook(&self, module: &plthook::Module) -> bool {
match &self.scope {
Scope::Module(_) => self
.sdk_dir
.as_deref()
.is_some_and(|dir| module_dir_key(module) == dir),
Scope::AllModules => true,
Scope::Only(names) => names.iter().any(|n| name_eq(module.name(), n)),
Scope::Exclude(names) => !names.iter().any(|n| name_eq(module.name(), n)),
}
}
fn uninstall_all(&self) {
let guards = std::mem::take(
&mut *self
.guards
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
);
for guard in guards {
let _ = guard.uninstall();
}
}
}
#[cfg(hookfs_backend)]
pub struct InstallGuard {
installer: Arc<Installer>,
}
#[cfg(hookfs_backend)]
impl std::fmt::Debug for InstallGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let hooked = self.installer.hooked_bases.lock().map_or(0, |b| b.len());
f.debug_struct("InstallGuard")
.field("hooked_modules", &hooked)
.finish()
}
}
#[cfg(hookfs_backend)]
impl InstallGuard {
pub fn rescan(&self) -> Result<usize> {
self.installer.rescan()
}
#[must_use]
pub fn hooked_module_count(&self) -> usize {
self.installer.hooked_bases.lock().map_or(0, |b| b.len())
}
}
#[cfg(hookfs_backend)]
impl Drop for InstallGuard {
fn drop(&mut self) {
dispatch::clear_rescan();
self.installer.uninstall_all();
dispatch::deactivate(self.installer.install_id);
}
}
#[cfg(windows)]
fn build_replacements(auto_rescan: bool) -> Vec<plthook::Replacement> {
use crate::shims::windows::shim_address;
dispatch::ALL
.iter()
.filter(|&&sym| auto_rescan || !matches!(sym, Sym::LoadLibraryExW | Sym::LoadLibraryA))
.map(|&sym| {
plthook::Replacement::by_name("KERNEL32.dll", sym.name(), shim_address(sym)).optional()
})
.collect()
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "ios"))]
fn build_replacements(auto_rescan: bool) -> Vec<plthook::Replacement> {
use crate::shims::unix::shim_address;
dispatch::ALL
.iter()
.filter(|&&sym| auto_rescan || !matches!(sym, Sym::Dlopen | Sym::Dlclose))
.map(|&sym| plthook::Replacement::by_symbol(sym.name(), shim_address(sym)).optional())
.collect()
}
#[cfg(hookfs_backend)]
fn resolve_modules(scope: &Scope) -> Result<Vec<plthook::Module>> {
match scope {
Scope::Module(addr) => {
let module =
unsafe { plthook::Module::from_address(*addr as *const core::ffi::c_void) }
.map_err(Error::Engine)?;
Ok(vec![module])
}
Scope::AllModules => plthook::Module::enumerate().map_err(Error::Engine),
Scope::Only(names) => Ok(plthook::Module::enumerate()
.map_err(Error::Engine)?
.into_iter()
.filter(|m| names.iter().any(|n| name_eq(m.name(), n)))
.collect()),
Scope::Exclude(names) => Ok(plthook::Module::enumerate()
.map_err(Error::Engine)?
.into_iter()
.filter(|m| !names.iter().any(|n| name_eq(m.name(), n)))
.collect()),
}
}
#[cfg(hookfs_backend)]
fn anchor_dir(scope: &Scope) -> Option<String> {
match scope {
Scope::Module(addr) => {
let module =
unsafe { plthook::Module::from_address(*addr as *const core::ffi::c_void) }.ok()?;
Some(module_dir_key(&module))
}
_ => None,
}
}
#[cfg(hookfs_backend)]
fn module_dir_key(module: &plthook::Module) -> String {
let path = std::path::Path::new(module.path());
let dir = path.parent().unwrap_or(path);
crate::namespace::normalize_key(dir)
}
#[cfg(hookfs_backend)]
fn name_eq(actual: &str, wanted: &str) -> bool {
actual.eq_ignore_ascii_case(wanted)
}
#[cfg(windows)]
fn preresolve_originals() {
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
let kernel32: Vec<u16> = "kernel32.dll\0".encode_utf16().collect();
let module = unsafe { GetModuleHandleW(kernel32.as_ptr()) };
if module.is_null() {
return;
}
for sym in dispatch::ALL {
let mut cname: Vec<u8> = sym.name().as_bytes().to_vec();
cname.push(0);
if let Some(proc) = unsafe { GetProcAddress(module, cname.as_ptr()) } {
dispatch::set_original(sym.name(), proc as usize);
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "ios"))]
fn preresolve_originals() {
for sym in dispatch::ALL {
let mut cname: Vec<u8> = sym.name().as_bytes().to_vec();
cname.push(0);
let proc = unsafe {
libc::dlsym(
libc::RTLD_DEFAULT,
cname.as_ptr().cast::<core::ffi::c_char>(),
)
};
if !proc.is_null() {
dispatch::set_original(sym.name(), proc as usize);
}
}
}
#[cfg(hookfs_backend)]
fn refresh_originals(guard: &plthook::HookGuard) {
for hook in guard.installed() {
dispatch::set_original(&hook.symbol().describe(), hook.original() as usize);
}
}
#[cfg(all(windows, test))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
use crate::providers::MemoryFs;
use crate::vfs::VirtualFs;
fn self_scope() -> Scope {
Scope::Module(self_scope as *const core::ffi::c_void as usize)
}
#[test]
fn second_install_is_rejected_until_the_first_guard_drops() {
let _serial = dispatch::GLOBAL_STATE_TEST_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let vfs: Arc<dyn VirtualFs> = MemoryFs::new();
let first = install(vfs.clone(), Options::default().scope(self_scope()))
.expect("first install should succeed");
let err = install(vfs.clone(), Options::default().scope(self_scope()))
.expect_err("second install must be rejected while one is active");
assert!(
matches!(err, Error::AlreadyInstalled),
"unexpected error: {err:?}"
);
drop(first);
let second = install(vfs, Options::default().scope(self_scope()))
.expect("install should succeed again after teardown");
drop(second);
}
}
#[cfg(not(hookfs_backend))]
pub(crate) fn install_with_namespace(
_vfs: Arc<dyn VirtualFs>,
_namespace: Namespace,
_scope: Scope,
_allow_writes: bool,
_auto_rescan: bool,
) -> Result<InstallGuard> {
Err(Error::UnsupportedPlatform)
}
#[cfg(not(hookfs_backend))]
#[derive(Debug)]
pub struct InstallGuard {
_private: (),
}
#[cfg(not(hookfs_backend))]
impl InstallGuard {
pub fn rescan(&self) -> Result<usize> {
Err(Error::UnsupportedPlatform)
}
}