mirust 1.2.0

Write mIRC and AdiIRC DLLs in safe, idiomatic Rust.
Documentation
//! The DLL entry points mIRC looks for, exported by every DLL built with mirust.
//!
//! `#[no_mangle]` functions in a dependency are exported from the final `cdylib`, so users
//! don't have to generate these. The optional [`Config`] reaches them through a hidden
//! export generated by [`config!`](crate::config), looked up at load time.

use core::ffi::c_void;
use core::ptr;
use std::panic;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::{Config, Unload, UnloadReason, WindowHandle, host, runtime, sys, worker};

/// Set once mIRC has called `LoadDll`. mIRC 5.6 – 5.71 never do.
static LOADED: AtomicBool = AtomicBool::new(false);

/// Export name of the function generated by [`config!`](crate::config).
const CONFIG_EXPORT: &core::ffi::CStr = c"__mirust_config";

/// `LoadDll`: called by mIRC 5.8+ when it loads the DLL, before any other call.
///
/// # Safety
///
/// Called by mIRC with a pointer to its `LOADINFO`.
#[unsafe(no_mangle)]
unsafe extern "system" fn LoadDll(info: *mut sys::LoadInfo) {
    LOADED.store(true, Ordering::SeqCst);
    let config = config();
    if config.pin_module {
        worker::pin_module();
    }
    // SAFETY: forwarded from mIRC.
    let host = unsafe { host::init(info, config.keep_loaded, config.unicode) };
    worker::loaded(host.main_window(), config.exit_grace);
    if let Some(hook) = config.on_load {
        // Unwinding into mIRC is undefined behaviour; swallow the panic instead.
        let _ = panic::catch_unwind(|| hook(host));
    }
}

/// `UnloadDll`: called by mIRC 5.8+ before it unloads the DLL. Returns 0 to stay loaded
/// (only honoured for an idle unload), 1 to allow unloading.
#[unsafe(no_mangle)]
extern "system" fn UnloadDll(raw_reason: i32) -> i32 {
    unload(UnloadReason::from_raw(raw_reason))
}

/// What `UnloadDll` does. Returns 0 to stay loaded, 1 to allow unloading.
fn unload(reason: UnloadReason) -> i32 {
    let config = config();
    let decision = match config.on_unload {
        Some(hook) => panic::catch_unwind(|| hook(reason)).unwrap_or(Unload::Allow),
        None if config.keep_loaded => Unload::Keep,
        None => Unload::Allow,
    };
    if let (UnloadReason::Idle, Unload::Keep) = (reason, decision) {
        return 0;
    }

    // mIRC will now call FreeLibrary. Workers hold their own reference to the DLL, so
    // they only need asking to stop. Never wait here while mIRC keeps running: this is
    // its UI thread. On exit, give them a bounded chance to finish.
    worker::unloading(reason == UnloadReason::Exit);
    1
}

/// Starts a call on mIRC 5.6 – 5.71, which call exported functions without ever calling
/// `LoadDll` or `UnloadDll`, and unload the DLL after every call.
///
/// To behave as on later versions with [`Config::keep_loaded(false)`](Config::keep_loaded),
/// this does what `LoadDll` would before the call, and the returned guard does what
/// `UnloadDll` would (an [`UnloadReason::Manual`] unload) when the call ends. Returns
/// `None` on hosts that called `LoadDll`.
pub(crate) fn begin_legacy_call(main_window: WindowHandle) -> Option<LegacyCall> {
    if LOADED.load(Ordering::SeqCst) {
        return None;
    }
    let config = config();
    if config.pin_module {
        worker::pin_module();
    }
    let host = host::init_legacy(main_window);
    worker::loaded(host.main_window(), config.exit_grace);
    if let Some(hook) = config.on_load {
        let _ = panic::catch_unwind(|| hook(host));
    }
    Some(LegacyCall)
}

/// Ends a call on mIRC 5.6 – 5.71 as `UnloadDll` would; see [`begin_legacy_call`].
pub(crate) struct LegacyCall;

impl Drop for LegacyCall {
    fn drop(&mut self) {
        unload(UnloadReason::Manual);
    }
}

/// `__mirust_deliver`: runs queued `$dllcall()` commands (see `delivery`).
///
/// # Safety
///
/// Called by mIRC with the standard exported-function arguments.
#[unsafe(no_mangle)]
unsafe extern "system" fn __mirust_deliver(
    main_window: *mut c_void,
    active_window: *mut c_void,
    data: *mut c_void,
    parms: *mut c_void,
    show: i32,
    no_pause: i32,
) -> i32 {
    // SAFETY: forwarded from mIRC.
    unsafe {
        runtime::dispatch(
            main_window,
            active_window,
            data,
            parms,
            show,
            no_pause,
            runtime::deliver,
        )
    }
}

/// `__mirust_run`: runs the oldest queued `$dllcall()` command.
///
/// # Safety
///
/// Called by mIRC with the standard exported-function arguments.
#[unsafe(no_mangle)]
unsafe extern "system" fn __mirust_run(
    main_window: *mut c_void,
    active_window: *mut c_void,
    data: *mut c_void,
    parms: *mut c_void,
    show: i32,
    no_pause: i32,
) -> i32 {
    // SAFETY: forwarded from mIRC.
    unsafe {
        runtime::dispatch(
            main_window,
            active_window,
            data,
            parms,
            show,
            no_pause,
            runtime::run_next,
        )
    }
}

/// The DLL's configuration: the one given to [`config!`](crate::config), or the defaults.
fn config() -> &'static Config {
    static DEFAULT: Config = Config::new();
    static RESOLVED: OnceLock<&'static Config> = OnceLock::new();
    RESOLVED.get_or_init(|| find_user_config().unwrap_or(&DEFAULT))
}

/// Looks for the export generated by [`config!`](crate::config) and asks it for the
/// configuration.
fn find_user_config() -> Option<&'static Config> {
    let module = own_module()?;
    // SAFETY: a valid module handle and a NUL-terminated name.
    let export = unsafe { sys::GetProcAddress(module, CONFIG_EXPORT.as_ptr().cast()) };
    if export.is_null() {
        return None;
    }
    // SAFETY: `config!` generates this export with exactly this signature.
    let export: runtime::ExportFn = unsafe { core::mem::transmute(export) };
    let mut config: *const Config = ptr::null();
    // SAFETY: the null window and the marker in `show` identify mirust's own call (see
    // `runtime::provide_config`), which writes a `&'static Config` into `config`.
    let answer = unsafe {
        export(
            ptr::null_mut(),
            ptr::null_mut(),
            (&raw mut config).cast(),
            ptr::null_mut(),
            runtime::CONFIG_MARKER,
            0,
        )
    };
    // SAFETY: `provide_config` only answers the marker after writing a `&'static Config`.
    (answer == runtime::CONFIG_MARKER && !config.is_null()).then(|| unsafe { &*config })
}

/// A handle to this DLL, without changing its reference count.
pub(crate) fn own_module() -> Option<*mut c_void> {
    let mut module = ptr::null_mut();
    // SAFETY: any address inside this DLL identifies it.
    let found = unsafe {
        sys::GetModuleHandleExW(
            sys::GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
                | sys::GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
            own_module as *const u16,
            &mut module,
        )
    };
    (found != 0).then_some(module)
}