Skip to main content

anvil/
host.rs

1use std::ffi::{c_char, c_void, CStr};
2use std::fmt::{self, Display, Write as _};
3use std::mem::{offset_of, size_of};
4use std::path::PathBuf;
5use std::ptr::{self, NonNull};
6use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
7
8use crate::change::{Change, FunctionHook, PointerSwap};
9use crate::cpu::Cpu;
10use crate::error::{check, Result};
11use crate::event::{Event, Payload};
12use crate::fnptr::{FnPtr, FnSymbol};
13use crate::panic::{catch_raw, resume, run_callback};
14use crate::sys::{
15    AnvilChange, AnvilCpuCallback, AnvilCpuContext, AnvilHost, AnvilLogLevel, AnvilPlugin,
16    AnvilResult, AnvilSetting, AnvilSymbol, ANVIL_LOG_DEBUG, ANVIL_LOG_ERROR, ANVIL_LOG_INFO,
17    ANVIL_LOG_WARNING,
18};
19use crate::table::Table;
20use crate::text::{c_string, owned_string, static_str};
21
22static TABLE: AtomicPtr<AnvilHost> = AtomicPtr::new(ptr::null_mut());
23static PLUGIN: AtomicPtr<AnvilPlugin> = AtomicPtr::new(ptr::null_mut());
24
25/// Whether the table has every function of API 2.0 (up to `publish`).
26pub(crate) fn covers_api_2_0(table: Table<AnvilHost>) -> bool {
27    table.size() as usize
28        >= offset_of!(AnvilHost, publish) + size_of::<Option<unsafe extern "C" fn()>>()
29}
30
31/// Keeps the host table and the plugin's handle for every later call; Anvil
32/// keeps both for the process.
33pub(crate) fn install(table: Table<AnvilHost>, plugin: *mut AnvilPlugin) {
34    PLUGIN.store(plugin, Ordering::Release);
35    TABLE.store(table.as_ptr().cast_mut(), Ordering::Release);
36}
37
38/// A log level of `anvil.log`.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub enum LogLevel {
41    /// Debug.
42    Debug,
43    /// Information.
44    Info,
45    /// Warning.
46    Warning,
47    /// Error.
48    Error,
49}
50
51impl LogLevel {
52    const fn raw(self) -> AnvilLogLevel {
53        match self {
54            Self::Debug => ANVIL_LOG_DEBUG,
55            Self::Info => ANVIL_LOG_INFO,
56            Self::Warning => ANVIL_LOG_WARNING,
57            Self::Error => ANVIL_LOG_ERROR,
58        }
59    }
60}
61
62/// The running game executable.
63#[derive(Clone, Copy, Debug)]
64pub struct GameInfo {
65    /// `eu4-1.37.5-steam-win64`; `None` when unknown.
66    pub build_id: Option<&'static str>,
67    /// Where eu4.exe is in memory.
68    pub image_base: usize,
69    /// The size of the image.
70    pub image_size: u32,
71    /// The SHA-256 of eu4.exe, upper-case hex; `None` until Anvil verified
72    /// it off the critical path.
73    pub sha256: Option<&'static str>,
74}
75
76/// A key binding (settings.toml type `key`): the Windows virtual-key code in
77/// bits 0-7 with the modifiers above it; 0 is no binding.
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
79pub struct Key(pub i64);
80
81impl Key {
82    /// Shift.
83    pub const SHIFT: i64 = 0x100;
84    /// Ctrl.
85    pub const CTRL: i64 = 0x200;
86    /// Alt.
87    pub const ALT: i64 = 0x400;
88
89    /// The virtual-key code.
90    pub const fn vk(self) -> u8 {
91        (self.0 & 0xFF) as u8
92    }
93    /// Whether Shift is part of it.
94    pub const fn shift(self) -> bool {
95        self.0 & Self::SHIFT != 0
96    }
97    /// Whether Ctrl is part of it.
98    pub const fn ctrl(self) -> bool {
99        self.0 & Self::CTRL != 0
100    }
101    /// Whether Alt is part of it.
102    pub const fn alt(self) -> bool {
103        self.0 & Self::ALT != 0
104    }
105    /// Whether a key is bound.
106    pub const fn is_bound(self) -> bool {
107        self.0 != 0
108    }
109}
110
111/// The host: Anvil's table and this plugin's handle. It is `Copy`: capture it
112/// in callbacks, or get it anywhere with [`Host::current`] once the plugin is
113/// loading.
114///
115/// Logging never fails. Every other call returns the [`Error`](crate::Error)
116/// Anvil answered with.
117#[derive(Clone, Copy)]
118pub struct Host {
119    table: Table<AnvilHost>,
120    plugin: *mut AnvilPlugin,
121}
122
123// SAFETY: Anvil's host functions may be called from any thread; the handle is an id.
124unsafe impl Send for Host {}
125// SAFETY: as above.
126unsafe impl Sync for Host {}
127
128impl fmt::Debug for Host {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        f.debug_struct("Host")
131            .field("anvil_version", &self.anvil_version())
132            .finish_non_exhaustive()
133    }
134}
135
136/// The adapter of a mid hook or block replacement; never freed (a game
137/// thread may still run it after the change is removed).
138struct CpuAdapter<F> {
139    callback: F,
140    what: String,
141    panicked: AtomicBool,
142}
143
144unsafe extern "C" fn cpu_adapter<F: Fn(&mut Cpu) + Send + Sync + 'static>(
145    cpu: *mut AnvilCpuContext,
146    user: *mut c_void,
147) {
148    // SAFETY: `user` is the adapter this crate registered with the change.
149    let adapter = unsafe { &*user.cast::<CpuAdapter<F>>() };
150    // SAFETY: the context Anvil passes, valid during the callback.
151    let Some(cpu) = (unsafe { Cpu::from_raw(cpu) }) else {
152        return;
153    };
154    run_callback(&adapter.what, &adapter.panicked, (), || {
155        (adapter.callback)(cpu)
156    });
157}
158
159struct EventAdapter<P, F> {
160    handler: F,
161    what: String,
162    panicked: AtomicBool,
163    _payload: std::marker::PhantomData<fn() -> P>,
164}
165
166unsafe extern "C" fn event_adapter<P: Payload, F: Fn(&P) + Send + Sync + 'static>(
167    _event: *const c_char,
168    payload: *const c_void,
169    context: *mut c_void,
170) {
171    // SAFETY: `context` is the adapter this crate subscribed with.
172    let adapter = unsafe { &*context.cast::<EventAdapter<P, F>>() };
173    run_callback(&adapter.what, &adapter.panicked, (), || {
174        // SAFETY: the Event<P> promises that P reads this event's payloads.
175        if let Some(payload) = unsafe { P::read(payload) } {
176            (adapter.handler)(&payload);
177        }
178    });
179}
180
181struct RawEventAdapter<F> {
182    handler: F,
183    what: String,
184    panicked: AtomicBool,
185}
186
187unsafe extern "C" fn raw_event_adapter<F: Fn(&str, *const c_void) + Send + Sync + 'static>(
188    event: *const c_char,
189    payload: *const c_void,
190    context: *mut c_void,
191) {
192    // SAFETY: `context` is the adapter this crate subscribed with.
193    let adapter = unsafe { &*context.cast::<RawEventAdapter<F>>() };
194    run_callback(&adapter.what, &adapter.panicked, (), || {
195        // SAFETY: the event name Anvil passes, valid during the call.
196        let name = unsafe { owned_string(event) };
197        (adapter.handler)(&name, payload);
198    });
199}
200
201struct SettingAdapter<F> {
202    handler: F,
203    what: String,
204    panicked: AtomicBool,
205}
206
207unsafe extern "C" fn setting_adapter<F: Fn() + Send + Sync + 'static>(
208    _setting: AnvilSetting,
209    context: *mut c_void,
210) {
211    // SAFETY: `context` is the adapter this crate subscribed with.
212    let adapter = unsafe { &*context.cast::<SettingAdapter<F>>() };
213    run_callback(&adapter.what, &adapter.panicked, (), || (adapter.handler)());
214}
215
216/// Writes one log line through the host; never fails.
217fn write_log(
218    table: Table<AnvilHost>,
219    plugin: *mut AnvilPlugin,
220    level: LogLevel,
221    message: &dyn Display,
222) {
223    let Some(log) = field!(table, AnvilHost, log).flatten() else {
224        return;
225    };
226    let mut text = String::new();
227    if write!(text, "{message}").is_err() {
228        text = "(a log line could not be formatted)".to_owned();
229    }
230    let text = c_string(&text);
231    // SAFETY: the host's own function with this plugin and a NUL-terminated UTF-8 line.
232    unsafe { log(plugin, level.raw(), text.as_ptr()) };
233}
234
235pub(crate) fn wide_path(text: *const u16) -> PathBuf {
236    if text.is_null() {
237        return PathBuf::new();
238    }
239    // SAFETY: a NUL-terminated wide string the host keeps.
240    let units = unsafe {
241        let mut length = 0;
242        while *text.add(length) != 0 {
243            length += 1;
244        }
245        std::slice::from_raw_parts(text, length)
246    };
247    #[cfg(windows)]
248    {
249        use std::os::windows::ffi::OsStringExt;
250        PathBuf::from(std::ffi::OsString::from_wide(units))
251    }
252    #[cfg(not(windows))]
253    {
254        PathBuf::from(String::from_utf16_lossy(units))
255    }
256}
257
258impl Host {
259    pub(crate) fn from_parts(table: Table<AnvilHost>, plugin: *mut AnvilPlugin) -> Self {
260        Self { table, plugin }
261    }
262
263    /// The host of this plugin; `None` before Anvil called `anvil_plugin_load`.
264    pub fn current() -> Option<Self> {
265        let table = TABLE.load(Ordering::Acquire);
266        let plugin = PLUGIN.load(Ordering::Acquire);
267        // SAFETY: install() stored Anvil's table, which lives for the process.
268        unsafe { Table::from_raw(table) }.map(|table| Self { table, plugin })
269    }
270
271    /// Anvil's C table, for what this crate does not wrap.
272    pub fn c_api(&self) -> Table<AnvilHost> {
273        self.table
274    }
275
276    /// This plugin's handle, the `self` of every C host call.
277    pub fn raw_plugin(&self) -> *mut AnvilPlugin {
278        self.plugin
279    }
280
281    /// The host of module `name`, which `plugin.toml` declares in
282    /// `[[modules]]` (Anvil 1.22.0; ADR 0011). Every call on
283    /// the returned `Host` acts for the module: Anvil suspends its changes by
284    /// the module's own `affects_gameplay`, `allow_ironman` and
285    /// `allow_multiplayer`, `anvil.suspended` reaches what it subscribes, and a
286    /// service that checks its caller sees the module. Settings, symbols,
287    /// folders and the names of services and events stay the plugin's.
288    ///
289    /// [`ErrorCode::Disabled`](crate::ErrorCode::Disabled) when the player
290    /// turned the module off (its code should not run then),
291    /// [`ErrorCode::NotDeclared`](crate::ErrorCode::NotDeclared) for a name
292    /// `plugin.toml` does not declare or when `self` is a module already, and
293    /// [`ErrorCode::Unsupported`](crate::ErrorCode::Unsupported) from an Anvil
294    /// without modules.
295    pub fn module(&self, name: &str) -> Result<Host> {
296        let module = function!(self.table, AnvilHost, module)?;
297        let text = c_string(name);
298        let mut out: *mut AnvilPlugin = ptr::null_mut();
299        // SAFETY: the host's function with this plugin, a NUL-terminated name
300        // and a place for the handle; the table is long enough (checked above).
301        let result = unsafe { module(self.plugin, text.as_ptr(), &mut out) };
302        check(result, || format!("module {name}"))?;
303        Ok(Self {
304            table: self.table,
305            plugin: out,
306        })
307    }
308
309    /// Anvil's version (SemVer).
310    pub fn anvil_version(&self) -> &'static str {
311        let version = field!(self.table, AnvilHost, anvil_version).unwrap_or(ptr::null());
312        // SAFETY: the host fills it for the process.
313        unsafe { static_str(version) }.unwrap_or("")
314    }
315
316    /// Whether a failed request leaves a hook's `next` cell as it was: Anvil
317    /// after 1.25.0 puts the cell's value back for every kind of change;
318    /// 1.25.0 and older write NULL into it for a function hook, call redirect
319    /// or import replacement.
320    pub(crate) fn restores_next(&self) -> bool {
321        restores_next(self.anvil_version())
322    }
323
324    /// The running game executable.
325    pub fn game(&self) -> GameInfo {
326        let game = field!(self.table, AnvilHost, game).unwrap_or(ptr::null());
327        if game.is_null() {
328            return GameInfo {
329                build_id: None,
330                image_base: 0,
331                image_size: 0,
332                sha256: None,
333            };
334        }
335        // SAFETY: the host's game info lives for the process. Only sha256
336        // changes after load: the core stores it atomically once the hash is
337        // verified, on another thread, so it is read atomically through a raw
338        // pointer (a reference to the struct would claim it does not change).
339        let sha256 = unsafe {
340            AtomicPtr::from_ptr(
341                ptr::addr_of!((*game).sha256)
342                    .cast_mut()
343                    .cast::<*mut c_char>(),
344            )
345            .load(Ordering::Acquire)
346        };
347        // SAFETY: as above; the other fields are set before any plugin loads.
348        let (build_id, image_base, image_size) =
349            unsafe { ((*game).build_id, (*game).image_base, (*game).image_size) };
350        GameInfo {
351            // SAFETY: as above; build_id and sha256 may be null.
352            build_id: unsafe { static_str(build_id) },
353            image_base,
354            image_size,
355            // SAFETY: as above.
356            sha256: unsafe { static_str(sha256.cast_const()) },
357        }
358    }
359
360    /// The plugin's folder (read-only).
361    pub fn plugin_dir(&self) -> PathBuf {
362        // SAFETY: the host's function with this plugin.
363        field!(self.table, AnvilHost, plugin_dir)
364            .flatten()
365            .map_or_else(PathBuf::new, |f| wide_path(unsafe { f(self.plugin) }))
366    }
367
368    /// The plugin's writable `anvil/data/<id>/`, created on the first call.
369    pub fn data_dir(&self) -> PathBuf {
370        // SAFETY: the host's function with this plugin.
371        field!(self.table, AnvilHost, data_dir)
372            .flatten()
373            .map_or_else(PathBuf::new, |f| wide_path(unsafe { f(self.plugin) }))
374    }
375
376    // --- log -------------------------------------------------------------------
377
378    /// One line of `anvil.log`, under the plugin's id: `host.log(level, "text")`
379    /// or `host.log(level, format_args!(…))`.
380    pub fn log(&self, level: LogLevel, message: impl Display) {
381        write_log(self.table, self.plugin, level, &message);
382    }
383
384    /// A debug line.
385    pub fn debug(&self, message: impl Display) {
386        self.log(LogLevel::Debug, message);
387    }
388
389    /// An information line.
390    pub fn info(&self, message: impl Display) {
391        self.log(LogLevel::Info, message);
392    }
393
394    /// A warning.
395    pub fn warn(&self, message: impl Display) {
396        self.log(LogLevel::Warning, message);
397    }
398
399    /// An error line.
400    pub fn error(&self, message: impl Display) {
401        self.log(LogLevel::Error, message);
402    }
403
404    // --- changes on declared symbols ------------------------------------------------
405
406    /// Hooks a function symbol: the game calls `detour`, which passes on
407    /// through `hook.next()`. With `hook` and `detour` of the symbol's
408    /// generated type (`sym::<Name>Fn`), a detour of another shape does not
409    /// compile; but the symbol id is a plain `u32`, so nothing ties `F` to
410    /// `symbol` but the caller. [`hook_symbol`](Self::hook_symbol) is the safe
411    /// form, with the typed symbols of `anvil gen --lang rust-sdk`.
412    ///
413    /// During `load` the change is staged and enabled with the others when
414    /// load returns; later it is enabled at once (or with its group).
415    ///
416    /// # Safety
417    /// `symbol` is a function symbol whose declared signature `F` is: the
418    /// `sym::<Name>Fn` that `anvil gen --lang rust` writes for the same
419    /// symbol as `sym::<NAME>`. The game calls `detour` with the arguments
420    /// of that signature, and the hook's `next` is the game's function of it.
421    pub unsafe fn hook<F: FnPtr>(
422        &self,
423        hook: &'static FunctionHook<F>,
424        symbol: AnvilSymbol,
425        detour: F,
426    ) -> Result<()> {
427        let _gate = crate::change::request_gate();
428        let claim = hook.claim("hook_function")?;
429        let call = function!(self.table, AnvilHost, hook_function)?;
430        let mut change: *mut AnvilChange = ptr::null_mut();
431        let mut next: *mut c_void = ptr::null_mut();
432        let cell = hook.next_cell(&mut next, self.restores_next());
433        // SAFETY: Anvil writes `cell` (the hook's own cell or a local) during the call only; the caller vouches that the
434        // detour has the symbol's declared type.
435        let result = unsafe { call(self.plugin, symbol, detour.into_raw(), cell, &mut change) };
436        check(result, || format!("hook_function symbol {symbol}"))?;
437        hook.finish(claim, cell, next, change, self.plugin);
438        Ok(())
439    }
440
441    /// [`hook`](Self::hook) without `unsafe`: the symbol comes with its type,
442    /// `sym::typed::<NAME>` from `anvil gen --lang rust-sdk`, so `hook` and
443    /// `detour` must be of the symbol's own `sym::<Name>Fn` and a detour of
444    /// another shape does not compile.
445    ///
446    /// ```ignore
447    /// static SPEED_OBJECT: FunctionHook<sym::SpeedObjectFn> = FunctionHook::new();
448    /// host.hook_symbol(&SPEED_OBJECT, sym::typed::SPEED_OBJECT, on_speed_object)?;
449    /// ```
450    pub fn hook_symbol<F: FnPtr>(
451        &self,
452        hook: &'static FunctionHook<F>,
453        symbol: FnSymbol<F>,
454        detour: F,
455    ) -> Result<()> {
456        // SAFETY: FnSymbol::new's contract ties `F` to the symbol's declared
457        // signature, which is what `hook` asks of its caller.
458        unsafe { self.hook(hook, symbol.id(), detour) }
459    }
460
461    /// A mid hook: `callback` runs when the game reaches the site (a function
462    /// or site symbol with at least 5 declared bytes), before the code there.
463    /// It may run on several game threads at once. A panic in it is logged
464    /// once and the game carries on.
465    pub fn mid_hook<F>(&self, site: AnvilSymbol, callback: F) -> Result<Change>
466    where
467        F: Fn(&mut Cpu) + Send + Sync + 'static,
468    {
469        let call = function!(self.table, AnvilHost, mid_hook)?;
470        let what = format!("mid_hook symbol {site}");
471        self.cpu_change(what, callback, |function, user, out| {
472            // SAFETY: a declared symbol; the adapter is never freed and never unwinds.
473            unsafe { call(self.plugin, site, function, user, out) }
474        })
475    }
476
477    /// A block replacement: the symbol's declared bytes never run; `callback`
478    /// runs instead and the game resumes at the block's `resume` or end
479    /// (unless the callback writes `rip` with [`Cpu::regs_mut`]).
480    pub fn replace_block<F>(&self, block: AnvilSymbol, callback: F) -> Result<Change>
481    where
482        F: Fn(&mut Cpu) + Send + Sync + 'static,
483    {
484        let call = function!(self.table, AnvilHost, replace_block)?;
485        let what = format!("replace_block symbol {block}");
486        self.cpu_change(what, callback, |function, user, out| {
487            // SAFETY: as in mid_hook.
488            unsafe { call(self.plugin, block, function, user, out) }
489        })
490    }
491
492    /// A call redirect at a `call rel32` site symbol: `target` gets the call,
493    /// `hook.next()` is the previous target.
494    ///
495    /// # Safety
496    /// A call site declares no signature: `F` must be the type of the
497    /// function the site calls.
498    pub unsafe fn redirect_call<F: FnPtr>(
499        &self,
500        hook: &'static FunctionHook<F>,
501        call_site: AnvilSymbol,
502        target: F,
503    ) -> Result<()> {
504        let _gate = crate::change::request_gate();
505        let claim = hook.claim("redirect_call")?;
506        let call = function!(self.table, AnvilHost, redirect_call)?;
507        let mut change: *mut AnvilChange = ptr::null_mut();
508        let mut next: *mut c_void = ptr::null_mut();
509        let cell = hook.next_cell(&mut next, self.restores_next());
510        // SAFETY: a declared symbol; the caller vouches for the type.
511        let result = unsafe { call(self.plugin, call_site, target.into_raw(), cell, &mut change) };
512        check(result, || format!("redirect_call symbol {call_site}"))?;
513        hook.finish(claim, cell, next, change, self.plugin);
514        Ok(())
515    }
516
517    /// A byte patch within the symbol's declared bytes.
518    ///
519    /// # Safety
520    /// The bytes become the game's code or data at the site: they must be
521    /// what the game can run or read there.
522    pub unsafe fn patch_bytes(&self, site: AnvilSymbol, bytes: &[u8]) -> Result<Change> {
523        let call = function!(self.table, AnvilHost, patch_bytes)?;
524        let mut change: *mut AnvilChange = ptr::null_mut();
525        // SAFETY: Anvil copies the bytes during the call; the caller vouches for them.
526        let result = unsafe {
527            call(
528                self.plugin,
529                site,
530                bytes.as_ptr().cast(),
531                bytes.len(),
532                &mut change,
533            )
534        };
535        check(result, || format!("patch_bytes symbol {site}"))?;
536        Ok(Change::from_raw(change))
537    }
538
539    /// A pointer swap on a slot symbol (`points_to`): the slot holds `value`,
540    /// `swap.previous()` the rest of the chain.
541    ///
542    /// # Safety
543    /// The game uses `value` as the slot's pointer: it must be what the slot
544    /// points to (a function of the vtable entry's type, an object), for as
545    /// long as the change lives.
546    pub unsafe fn swap_pointer(
547        &self,
548        swap: &'static PointerSwap,
549        slot: AnvilSymbol,
550        value: *mut c_void,
551    ) -> Result<()> {
552        let _gate = crate::change::request_gate();
553        let claim = swap.claim()?;
554        let call = function!(self.table, AnvilHost, swap_pointer)?;
555        let mut change: *mut AnvilChange = ptr::null_mut();
556        // SAFETY: `previous` lives in a static and is 8-byte aligned; the caller vouches for `value`.
557        let result = unsafe { call(self.plugin, slot, value, swap.previous_slot(), &mut change) };
558        check(result, || format!("swap_pointer symbol {slot}"))?;
559        claim.finish(change, self.plugin);
560        Ok(())
561    }
562
563    /// Replaces an import of eu4.exe, e.g. `("KERNEL32.dll", "GetTickCount")`
564    /// (the module ignores case).
565    ///
566    /// # Safety
567    /// `F` must be the type of the imported function.
568    pub unsafe fn replace_import<F: FnPtr>(
569        &self,
570        hook: &'static FunctionHook<F>,
571        module: &str,
572        function: &str,
573        replacement: F,
574    ) -> Result<()> {
575        let _gate = crate::change::request_gate();
576        let claim = hook.claim("replace_import")?;
577        let call = function!(self.table, AnvilHost, replace_import)?;
578        let (module_c, function_c) = (c_string(module), c_string(function));
579        let mut change: *mut AnvilChange = ptr::null_mut();
580        let mut next: *mut c_void = ptr::null_mut();
581        let cell = hook.next_cell(&mut next, self.restores_next());
582        // SAFETY: NUL-terminated names; the caller vouches for the type.
583        let result = unsafe {
584            call(
585                self.plugin,
586                module_c.as_ptr(),
587                function_c.as_ptr(),
588                replacement.into_raw(),
589                cell,
590                &mut change,
591            )
592        };
593        check(result, || format!("replace_import {module}!{function}"))?;
594        hook.finish(claim, cell, next, change, self.plugin);
595        Ok(())
596    }
597
598    /// A function hook at a raw address outside the eu4.exe image (e.g. a
599    /// Direct3D 9 vtable entry); `expected_prologue` may be empty.
600    ///
601    /// # Safety
602    /// `address` is the start of a function of type `F` that lives while the
603    /// change does.
604    pub unsafe fn hook_at<F: FnPtr>(
605        &self,
606        hook: &'static FunctionHook<F>,
607        address: NonNull<c_void>,
608        expected_prologue: &[u8],
609        detour: F,
610    ) -> Result<()> {
611        let _gate = crate::change::request_gate();
612        let claim = hook.claim("hook_function_at")?;
613        let call = function!(self.table, AnvilHost, hook_function_at)?;
614        let mut change: *mut AnvilChange = ptr::null_mut();
615        let mut next: *mut c_void = ptr::null_mut();
616        let cell = hook.next_cell(&mut next, self.restores_next());
617        // SAFETY: the caller's contract; the bytes are read during the call.
618        let result = unsafe {
619            call(
620                self.plugin,
621                address.as_ptr(),
622                bytes_or_null(expected_prologue),
623                expected_prologue.len(),
624                detour.into_raw(),
625                cell,
626                &mut change,
627            )
628        };
629        check(result, || {
630            format!("hook_function_at {:p}", address.as_ptr())
631        })?;
632        hook.finish(claim, cell, next, change, self.plugin);
633        Ok(())
634    }
635
636    /// A mid hook at a raw address outside the eu4.exe image; `expected` may
637    /// be empty.
638    ///
639    /// # Safety
640    /// `address` is the start of an instruction that lives while the change does.
641    pub unsafe fn mid_hook_at<F>(
642        &self,
643        address: NonNull<c_void>,
644        expected: &[u8],
645        callback: F,
646    ) -> Result<Change>
647    where
648        F: Fn(&mut Cpu) + Send + Sync + 'static,
649    {
650        let call = function!(self.table, AnvilHost, mid_hook_at)?;
651        let what = format!("mid_hook_at {:p}", address.as_ptr());
652        self.cpu_change(what, callback, |function, user, out| {
653            // SAFETY: the caller's contract; the adapter never unwinds.
654            unsafe {
655                call(
656                    self.plugin,
657                    address.as_ptr(),
658                    bytes_or_null(expected),
659                    expected.len(),
660                    function,
661                    user,
662                    out,
663                )
664            }
665        })
666    }
667
668    /// After load: the changes `body` requests are enabled together, or none
669    /// when it returns an error or panics (the panic goes on, logged as
670    /// `panic: …` unless an adapter of this crate catches it further out,
671    /// which logs it itself). Inside `load`
672    /// the load itself is the group: `WrongPhase`.
673    ///
674    /// The group is this host's (the plugin's, or the module's for a
675    /// [`module`](Self::module) host), not this thread's: a request on this
676    /// host from any thread while it is open (a panel click, a thread `body`
677    /// started) joins it, is enabled only with the commit and dropped with an
678    /// abort. A request on another host (a module inside the plugin's group)
679    /// is not part of it.
680    ///
681    /// When the group's changes are dropped (an error, a panic, or a commit
682    /// Anvil refuses), the [`FunctionHook`]s and [`PointerSwap`]s filled in
683    /// the group, on any thread, are free again: `is_active` is false and
684    /// they take a new request.
685    pub fn group<R>(&self, body: impl FnOnce() -> Result<R>) -> Result<R> {
686        let begin = function!(self.table, AnvilHost, begin_group)?;
687        let commit = function!(self.table, AnvilHost, commit_group)?;
688        let abort = function!(self.table, AnvilHost, abort_group)?;
689        {
690            let _gate = crate::change::group_gate();
691            // SAFETY: the host's functions with this plugin.
692            check(unsafe { begin(self.plugin) }, || "begin_group")?;
693            crate::change::group_opened(self.plugin);
694        }
695        let outcome = catch_raw(body);
696        let gate = crate::change::group_gate();
697        match outcome {
698            Ok(Ok(value)) => {
699                // SAFETY: as above.
700                let committed = check(unsafe { commit(self.plugin) }, || "commit_group");
701                crate::change::group_closed(self.plugin, committed.is_err());
702                drop(gate);
703                committed?;
704                Ok(value)
705            }
706            Ok(Err(error)) => {
707                // SAFETY: as above.
708                unsafe { abort(self.plugin) };
709                crate::change::group_closed(self.plugin, true);
710                Err(error)
711            }
712            Err(panic) => {
713                // SAFETY: as above.
714                unsafe { abort(self.plugin) };
715                crate::change::group_closed(self.plugin, true);
716                drop(gate);
717                // Logged here when no adapter of this thread catches it further out.
718                resume(panic)
719            }
720        }
721    }
722
723    fn cpu_change<F>(
724        &self,
725        what: String,
726        callback: F,
727        request: impl FnOnce(AnvilCpuCallback, *mut c_void, *mut *mut AnvilChange) -> AnvilResult,
728    ) -> Result<Change>
729    where
730        F: Fn(&mut Cpu) + Send + Sync + 'static,
731    {
732        let adapter: &'static CpuAdapter<F> = Box::leak(Box::new(CpuAdapter {
733            callback,
734            what,
735            panicked: AtomicBool::new(false),
736        }));
737        let mut change: *mut AnvilChange = ptr::null_mut();
738        let result = request(
739            Some(cpu_adapter::<F>),
740            ptr::from_ref(adapter).cast_mut().cast(),
741            &mut change,
742        );
743        check(result, || adapter.what.clone())?;
744        Ok(Change::from_raw(change))
745    }
746
747    // --- addresses -------------------------------------------------------------------
748
749    /// The verified address of a symbol; `None` for an unknown one, or one
750    /// symbols.toml declares `absent` on the running game build.
751    pub fn address(&self, symbol: AnvilSymbol) -> Option<NonNull<c_void>> {
752        // SAFETY: the host's function with this plugin.
753        field!(self.table, AnvilHost, address_of)
754            .flatten()
755            .and_then(|f| NonNull::new(unsafe { f(self.plugin, symbol) }))
756    }
757
758    /// Whether the symbol is there on the running game build: check it before
759    /// using a symbol symbols.toml may declare `absent`.
760    pub fn present(&self, symbol: AnvilSymbol) -> bool {
761        self.address(symbol).is_some()
762    }
763
764    /// The game function of a function symbol, to call.
765    ///
766    /// # Safety
767    /// `F` is the symbol's generated type (`sym::<Name>Fn`).
768    pub unsafe fn function<F: FnPtr>(&self, symbol: AnvilSymbol) -> Option<F> {
769        // SAFETY: a verified function of the caller's type.
770        self.address(symbol)
771            .map(|address| unsafe { F::from_raw(address.as_ptr()) })
772    }
773
774    /// The game's data at a data symbol, for the life of the process.
775    ///
776    /// # Safety
777    /// The symbol's memory holds a `T`, and nothing writes it while the
778    /// reference is used (data the game never changes, or read only on the
779    /// thread that writes it).
780    pub unsafe fn data<T>(&self, symbol: AnvilSymbol) -> Option<&'static T> {
781        // SAFETY: the caller's contract.
782        self.address(symbol)
783            .map(|address| unsafe { address.cast::<T>().as_ref() })
784    }
785
786    /// A value of symbols.toml `values` (a `rip_relative` value is an RVA).
787    pub fn value(&self, symbol: AnvilSymbol, name: &str) -> Result<u64> {
788        let call = function!(self.table, AnvilHost, symbol_value)?;
789        let name_c = c_string(name);
790        let mut out = 0u64;
791        // SAFETY: the host's function with a NUL-terminated name.
792        let result = unsafe { call(self.plugin, symbol, name_c.as_ptr(), &mut out) };
793        check(result, || format!("symbol_value symbol {symbol}.{name}"))?;
794        Ok(out)
795    }
796
797    // --- settings (settings.gen.rs) -----------------------------------------------------
798
799    /// A bool setting (false for an unknown one or one of another type).
800    pub fn setting_bool(&self, setting: AnvilSetting) -> bool {
801        // SAFETY: the host's function with this plugin.
802        field!(self.table, AnvilHost, setting_bool)
803            .flatten()
804            .is_some_and(|f| unsafe { f(self.plugin, setting) } != 0)
805    }
806
807    /// An int, bool, enum index (`<NAME>_<OPTION>`) or key code.
808    pub fn setting_int(&self, setting: AnvilSetting) -> i64 {
809        // SAFETY: as above.
810        field!(self.table, AnvilHost, setting_int)
811            .flatten()
812            .map_or(0, |f| unsafe { f(self.plugin, setting) })
813    }
814
815    /// A float or int setting.
816    pub fn setting_float(&self, setting: AnvilSetting) -> f64 {
817        // SAFETY: as above.
818        field!(self.table, AnvilHost, setting_float)
819            .flatten()
820            .map_or(0.0, |f| unsafe { f(self.plugin, setting) })
821    }
822
823    /// A string, an enum option's name or a key ("Ctrl+F12").
824    pub fn setting_string(&self, setting: AnvilSetting) -> String {
825        // SAFETY: valid until the next change of the setting; copied at once.
826        field!(self.table, AnvilHost, setting_string)
827            .flatten()
828            .map_or_else(String::new, |f| unsafe {
829                owned_string(f(self.plugin, setting))
830            })
831    }
832
833    /// A key setting.
834    pub fn setting_key(&self, setting: AnvilSetting) -> Key {
835        Key(self.setting_int(setting))
836    }
837
838    /// `handler` runs after a `restart = false` setting changes (in the
839    /// overlay), on the thread that changed it; kept for the process.
840    pub fn subscribe_setting<F>(&self, setting: AnvilSetting, handler: F) -> Result<()>
841    where
842        F: Fn() + Send + Sync + 'static,
843    {
844        let call = function!(self.table, AnvilHost, subscribe_setting)?;
845        let what = format!("setting {setting} handler");
846        let adapter: &'static SettingAdapter<F> = Box::leak(Box::new(SettingAdapter {
847            handler,
848            what,
849            panicked: AtomicBool::new(false),
850        }));
851        // SAFETY: the adapter is never freed and never unwinds.
852        let result = unsafe {
853            call(
854                self.plugin,
855                setting,
856                Some(setting_adapter::<F>),
857                ptr::from_ref(adapter).cast_mut().cast(),
858            )
859        };
860        check(result, || format!("subscribe_setting setting {setting}"))
861    }
862
863    // --- events ----------------------------------------------------------------------
864
865    /// `handler(&payload)` runs for each `event`, synchronously on the
866    /// publishing thread; kept for the process.
867    pub fn subscribe<P, F>(&self, event: Event<P>, handler: F) -> Result<()>
868    where
869        P: Payload,
870        F: Fn(&P) + Send + Sync + 'static,
871    {
872        let call = function!(self.table, AnvilHost, subscribe)?;
873        let name = event.name();
874        let what = format!("{} handler", name.to_string_lossy());
875        let adapter: &'static EventAdapter<P, F> = Box::leak(Box::new(EventAdapter {
876            handler,
877            what,
878            panicked: AtomicBool::new(false),
879            _payload: std::marker::PhantomData,
880        }));
881        // SAFETY: a NUL-terminated name; the adapter is never freed and never unwinds.
882        let result = unsafe {
883            call(
884                self.plugin,
885                name.as_ptr(),
886                Some(event_adapter::<P, F>),
887                ptr::from_ref(adapter).cast_mut().cast(),
888            )
889        };
890        check(result, || format!("subscribe {}", name.to_string_lossy()))
891    }
892
893    /// `handler(name, payload)` for any event name, with the publisher's raw
894    /// payload pointer (valid during the handler).
895    pub fn subscribe_raw<F>(&self, event: &str, handler: F) -> Result<()>
896    where
897        F: Fn(&str, *const c_void) + Send + Sync + 'static,
898    {
899        let call = function!(self.table, AnvilHost, subscribe)?;
900        let name = c_string(event);
901        let what = format!("{event} handler");
902        let adapter: &'static RawEventAdapter<F> = Box::leak(Box::new(RawEventAdapter {
903            handler,
904            what,
905            panicked: AtomicBool::new(false),
906        }));
907        // SAFETY: as in subscribe.
908        let result = unsafe {
909            call(
910                self.plugin,
911                name.as_ptr(),
912                Some(raw_event_adapter::<F>),
913                ptr::from_ref(adapter).cast_mut().cast(),
914            )
915        };
916        check(result, || format!("subscribe {event}"))
917    }
918
919    /// Publishes `<plugin-id>.<name>` with no payload (NULL), which every
920    /// [`Payload::read`](crate::Payload::read) answers without reading.
921    pub fn publish(&self, event: &str) -> Result<()> {
922        // SAFETY: a NULL payload, which no subscriber reads.
923        unsafe { self.publish_raw(event, ptr::null()) }
924    }
925
926    /// Publishes `<plugin-id>.<name>` with a payload its subscribers read
927    /// during the call: synchronously, on this thread, before it returns.
928    ///
929    /// # Safety
930    /// `payload` is null or points to a value of the layout this event's
931    /// subscribers read it as: the payload type its documentation (or C
932    /// header) names, which every [`Event`] of that name declares with
933    /// [`Event::new`]. For a type that starts with `uint32_t size`, the
934    /// `size` is the value's own and at least that many bytes are readable.
935    /// It stays valid and unchanged until the call returns.
936    pub unsafe fn publish_raw(&self, event: &str, payload: *const c_void) -> Result<()> {
937        let call = function!(self.table, AnvilHost, publish)?;
938        let name = c_string(event);
939        // SAFETY: a NUL-terminated name; the caller vouches for the payload.
940        check(unsafe { call(self.plugin, name.as_ptr(), payload) }, || {
941            format!("publish {event}")
942        })
943    }
944
945    // --- services ----------------------------------------------------------------------
946
947    /// Registers a service `<plugin-id>.<service>` of major `version`.
948    ///
949    /// # Safety
950    /// `service` is a `#[repr(C)]` struct whose first field is `u32 size`
951    /// (its size), followed by `extern "C"` functions that never unwind, as
952    /// the service's C header describes it.
953    pub unsafe fn register_service<T: Sync>(
954        &self,
955        name: &str,
956        version: u32,
957        service: &'static T,
958    ) -> Result<()> {
959        let call = function!(self.table, AnvilHost, register_service)?;
960        let name_c = c_string(name);
961        // SAFETY: the service lives for the process; the caller vouches for its layout.
962        let result = unsafe {
963            call(
964                self.plugin,
965                name_c.as_ptr(),
966                version,
967                ptr::from_ref(service).cast(),
968            )
969        };
970        check(result, || format!("register_service {name} v{version}"))
971    }
972
973    /// A service by name and major version, as a [`Table`]; the typed
974    /// wrappers ([`game::Game`](crate::game::Game),
975    /// [`world::World`](crate::world::World),
976    /// [`panel::Panels`](crate::panel::Panels),
977    /// [`benchmark::Benchmark`](crate::benchmark::Benchmark)) use it. Only the
978    /// table's `size` is read here: a provider older than `T` has a shorter
979    /// table, and [`Table`] reads a field only when that size covers it.
980    ///
981    /// # Safety
982    /// `T` is the service's table type for that version (or a newer
983    /// release of the same version): a `#[repr(C)]` struct whose first field
984    /// is `u32 size`.
985    pub unsafe fn service<T>(&self, name: &CStr, version: u32) -> Option<Table<T>> {
986        let call = field!(self.table, AnvilHost, get_service).flatten()?;
987        // SAFETY: a NUL-terminated name; a service's table starts with its
988        // size, has that many bytes and lives for the process (ADR 0001);
989        // the caller vouches for T.
990        unsafe { Table::from_raw(call(self.plugin, name.as_ptr(), version).cast::<T>()) }
991    }
992}
993
994fn bytes_or_null(bytes: &[u8]) -> *const c_void {
995    if bytes.is_empty() {
996        ptr::null()
997    } else {
998        bytes.as_ptr().cast()
999    }
1000}
1001
1002/// See [`Host::restores_next`]: a version above 1.25.0 (a prerelease of a
1003/// later version counts as that version).
1004pub(crate) fn restores_next(version: &str) -> bool {
1005    let mut parts = version.splitn(3, '.');
1006    let mut number = || -> Option<u64> {
1007        let part = parts.next()?;
1008        let digits = part
1009            .find(|c: char| !c.is_ascii_digit())
1010            .unwrap_or(part.len());
1011        if digits == 0 || digits > 7 {
1012            return None;
1013        }
1014        part[..digits].parse().ok()
1015    };
1016    let (Some(major), Some(minor), Some(patch)) = (number(), number(), number()) else {
1017        return false;
1018    };
1019    (major, minor, patch) > (1, 25, 0)
1020}