mirust 1.2.0

Write mIRC and AdiIRC DLLs in safe, idiomatic Rust.
Documentation
//! Glue called by the code that [`config!`](crate::config) and [`export!`](crate::export)
//! generate, and by the entry points in `entry`. Not public API.

use core::ffi::c_void;
use std::panic::{self, AssertUnwindSafe};

use crate::canvas::{self, Draw, IntoUpdate};
use crate::{
    Call, Config, IntoResponse, Response, WindowHandle, delivery, encoding, entry, host, worker,
};

/// Longest input mirust will read, in code units. Current mIRC passes at most about 10,400.
const MAX_INPUT_UNITS: usize = 1 << 16;

/// The signature mIRC calls exported functions with.
pub type ExportFn = unsafe extern "system" fn(
    main_window: *mut c_void,
    active_window: *mut c_void,
    data: *mut c_void,
    parms: *mut c_void,
    show: i32,
    no_pause: i32,
) -> i32;

/// Passed as `show` (with a null main window) when mirust asks the `config!` export for
/// the configuration. mIRC only ever passes 0 or 1.
pub const CONFIG_MARKER: i32 = 0x6D69_7275; // "miru"

/// Body of the export generated by [`config!`](crate::config).
///
/// When called by mirust itself, recognised by the null main window and [`CONFIG_MARKER`],
/// it writes `config` into `*data` and answers with the marker. When called any other way,
/// for example by a script running `/dll <file> __mirust_config`, it does nothing and
/// returns 1 (continue).
///
/// # Safety
///
/// The arguments must be those of an exported-function call: from mIRC, or from mirust with
/// `data` pointing to a `*const Config`.
pub unsafe fn provide_config(
    main_window: *mut c_void,
    data: *mut c_void,
    show: i32,
    config: &'static Config,
) -> i32 {
    if main_window.is_null() && show == CONFIG_MARKER && !data.is_null() {
        // SAFETY: mirust's own call passes a pointer to a `*const Config`.
        unsafe { data.cast::<*const Config>().write(config) };
        CONFIG_MARKER
    } else {
        1
    }
}

/// Body of every exported function.
///
/// # Safety
///
/// The arguments must be those mIRC passed to the exported function: `data` and `parms`
/// null or pointing to buffers of at least [`Host::capacity`](crate::Host::capacity) units.
pub unsafe fn dispatch<F, R>(
    main_window: *mut c_void,
    active_window: *mut c_void,
    data: *mut c_void,
    parms: *mut c_void,
    show: i32,
    no_pause: i32,
    f: F,
) -> i32
where
    F: FnOnce(Call) -> R,
    R: IntoResponse,
{
    let main_window = WindowHandle::from_raw(main_window);
    // mIRC 5.6 – 5.71 never call `LoadDll`/`UnloadDll`; act as they would around the call.
    // Dropped last, after the response has been written.
    let legacy = entry::begin_legacy_call(main_window);
    let host = host::host();
    let (capacity, encoding) = (host.capacity(), host.encoding());
    let is_dllcall = !main_window.is_current_thread();
    // Counts a `$dllcall()` for the exit grace period until the call has finished.
    let guard = worker::begin_call(is_dllcall);

    let call = Call {
        // SAFETY: mIRC always passes a NUL-terminated string in `data`. The input can be
        // longer than `capacity` (which is conservative, and limits what we write), so read
        // up to the terminator; the larger limit only guards against a missing one.
        data: unsafe { encoding::read(data, capacity.max(MAX_INPUT_UNITS), encoding) },
        main_window,
        active_window: WindowHandle::from_raw(active_window),
        show: show != 0,
        no_pause: no_pause != 0,
        is_dllcall,
        stop: guard.token.clone(),
        host,
    };

    // Unwinding into mIRC is undefined behaviour. Halt the script instead.
    let response =
        panic::catch_unwind(AssertUnwindSafe(|| f(call).into_response())).unwrap_or(Response::Halt);

    // mIRC can overwrite a `$dllcall()`'s pending command before running it, so queue it
    // and hand mIRC a delivery command instead (see `delivery`). Not possible when mIRC
    // unloads the DLL after every call: the queue wouldn't survive until delivery.
    let response = if is_dllcall && host.keep_loaded() {
        delivery::intercept(response)
    } else {
        response
    };

    // SAFETY: both buffers are writable for `capacity` units.
    unsafe {
        match &response {
            Response::Halt | Response::Continue => {}
            Response::Return(value) => encoding::write(value, data, capacity, encoding),
            Response::Command {
                command,
                parms: args,
            } => {
                encoding::write(command, data, capacity, encoding);
                encoding::write(args, parms, capacity, encoding);
            }
        }
    }
    drop(guard);
    drop(legacy);
    response.code()
}

/// Body of every export generated by [`export_draw!`](crate::export_draw): a function mIRC
/// calls with `/drawdll`.
///
/// Returns 3 with the update reply in `data`, which is what `/drawdll` expects. If mIRC
/// didn't call it through `/drawdll` (a script used `/dll` on it, say), there is no bitmap,
/// so it does nothing and returns 1 (continue).
///
/// # Safety
///
/// The arguments must be those mIRC passed to the exported function.
pub unsafe fn dispatch_draw<F, R>(
    main_window: *mut c_void,
    active_window: *mut c_void,
    data: *mut c_void,
    _parms: *mut c_void,
    _show: i32,
    _no_pause: i32,
    f: F,
) -> i32
where
    F: FnOnce(Draw) -> R,
    R: IntoUpdate,
{
    let host = host::host();
    let (capacity, encoding) = (host.capacity(), host.encoding());
    // SAFETY: as in `dispatch`, `data` holds a NUL-terminated string.
    let text = unsafe { encoding::read(data, capacity.max(MAX_INPUT_UNITS), encoding) };
    let Some(draw) = canvas::prepare(
        &text,
        WindowHandle::from_raw(main_window),
        WindowHandle::from_raw(active_window),
        host,
    ) else {
        return Response::Continue.code();
    };
    let update = match panic::catch_unwind(AssertUnwindSafe(|| f(draw).into_update())) {
        Ok(update) => update,
        Err(_) => return Response::Halt.code(),
    };
    // SAFETY: `data` is writable for `capacity` units.
    unsafe { encoding::write(&update.reply(), data, capacity, encoding) };
    Response::Return(String::new()).code()
}

/// Body of the `__mirust_deliver` export, which mIRC calls (through `/dll`, on its UI
/// thread) to deliver queued `$dllcall()` commands.
pub fn deliver(call: Call) -> Response {
    delivery::deliver(call.max_response_len())
}

/// Body of the `__mirust_run` export: runs the oldest queued command.
pub fn run_next(_: Call) -> Response {
    delivery::run_next()
}