Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

4.6 KB
Raw Blame
//! Keeps every module the process has loaded in memory until it exits, so that a shell extension a right-click menu loaded is never
//! unloaded while something of it is still in use.
//!
//! Why (issues 396 and 605): a context menu handler that says it can be unloaded (`DllCanUnloadNow`) while an object of its own is
//! still held by the shell is unloaded by COM, and the next time Windows calls that object (`shcore.dll`, from a message on the shell
//! thread) it reads code or a vtable that is no longer there and the whole process ends with an access violation. Two crash dumps
//! from issue 605 show exactly that: the read address is inside `FolderColorShlExt.dll` (a folder colouring extension), at the same
//! offset in both, and that DLL is in the dump's list of UNLOADED modules. The bug is the extension's, but it ends rustyfiles.
//! Explorer is spared because it keeps such handlers loaded; we do the same by pinning (`GET_MODULE_HANDLE_EX_FLAG_PIN`): a pinned
//! module stays until the process ends, whatever its reference count says. The cost is only that the memory of an extension that was
//! used once stays mapped.
//!
//! [`pin_loaded`] pins every module loaded at the moment that is not pinned yet (cheap: one module list and a set lookup each); the
//! shell menu code calls it after it has asked the handlers for their items and after it ran a command.

use std::collections::HashSet;
use std::sync::Mutex;

use windows::Win32::Foundation::HMODULE;
use windows::Win32::System::LibraryLoader::{GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_PIN, GetModuleHandleExW};
use windows::Win32::System::ProcessStatus::{EnumProcessModulesEx, LIST_MODULES_ALL};
use windows::Win32::System::Threading::GetCurrentProcess;
use windows::core::PCWSTR;

/// The bases of the modules pinned so far. A pinned module can never be unloaded, so its base can never be taken by another one.
static PINNED: Mutex<Option<HashSet<usize>>> = Mutex::new(None);

/// The modules loaded in this process now.
fn loaded() -> Vec<HMODULE> {
    let size = std::mem::size_of::<HMODULE>();
    let mut mods = vec![HMODULE::default(); 512];
    unsafe {
        let p = GetCurrentProcess();
        loop {
            let mut need = 0u32;
            if EnumProcessModulesEx(p, mods.as_mut_ptr(), (mods.len() * size) as u32, &mut need, LIST_MODULES_ALL).is_err() {
                return Vec::new();
            }
            let n = need as usize / size;
            if n <= mods.len() {
                mods.truncate(n);
                return mods;
            }
            mods = vec![HMODULE::default(); n + 64];
        }
    }
}

/// Pins every module loaded now that was not pinned before, and says how many it pinned.
pub fn pin_loaded() -> usize {
    let mods = loaded();
    let mut guard = PINNED.lock().unwrap_or_else(|e| e.into_inner());
    let pinned = guard.get_or_insert_with(HashSet::new);
    let mut newly = 0;
    for m in mods {
        let base = m.0 as usize;
        if base == 0 || !pinned.insert(base) {
            continue;
        }
        let mut out = HMODULE::default();
        // by address: the base is inside the module; a module that went away since the list was taken just fails here
        let ok = unsafe { GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, PCWSTR(base as *const u16), &mut out) }.is_ok();
        if ok {
            newly += 1;
        } else {
            pinned.remove(&base);
        }
    }
    if newly > 0 {
        log::debug!("extpin: {newly} module(s) kept loaded");
    }
    newly
}

#[cfg(test)]
mod tests {
    use super::pin_loaded;
    use windows::Win32::Foundation::FreeLibrary;
    use windows::Win32::System::LibraryLoader::{GetModuleHandleW, LoadLibraryW};
    use windows::core::w;

    #[test]
    fn a_pinned_module_stays_loaded_after_its_last_free_library() {
        unsafe {
            // a system DLL a test process has no other use for (the same one twice: its count is 2 before the pin)
            let m = LoadLibraryW(w!("mscms.dll")).expect("mscms.dll loads");
            let _ = LoadLibraryW(w!("mscms.dll"));
            assert!(pin_loaded() > 0 || GetModuleHandleW(w!("mscms.dll")).is_ok());
            // pinning again finds nothing new to pin among the same modules
            let again = pin_loaded();
            assert!(again <= 2, "only modules loaded in between: {again}");
            // every FreeLibrary the loads asked for, and one more: the module is still there
            let _ = FreeLibrary(m);
            let _ = FreeLibrary(m);
            let _ = FreeLibrary(m);
            assert!(GetModuleHandleW(w!("mscms.dll")).is_ok(), "pinned: never unloaded");
        }
    }
}