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    /// The running game executable.
317    pub fn game(&self) -> GameInfo {
318        let game = field!(self.table, AnvilHost, game).unwrap_or(ptr::null());
319        if game.is_null() {
320            return GameInfo {
321                build_id: None,
322                image_base: 0,
323                image_size: 0,
324                sha256: None,
325            };
326        }
327        // SAFETY: the host's game info lives for the process. Only sha256
328        // changes after load: the core stores it atomically once the hash is
329        // verified, on another thread, so it is read atomically through a raw
330        // pointer (a reference to the struct would claim it does not change).
331        let sha256 = unsafe {
332            AtomicPtr::from_ptr(
333                ptr::addr_of!((*game).sha256)
334                    .cast_mut()
335                    .cast::<*mut c_char>(),
336            )
337            .load(Ordering::Acquire)
338        };
339        // SAFETY: as above; the other fields are set before any plugin loads.
340        let (build_id, image_base, image_size) =
341            unsafe { ((*game).build_id, (*game).image_base, (*game).image_size) };
342        GameInfo {
343            // SAFETY: as above; build_id and sha256 may be null.
344            build_id: unsafe { static_str(build_id) },
345            image_base,
346            image_size,
347            // SAFETY: as above.
348            sha256: unsafe { static_str(sha256.cast_const()) },
349        }
350    }
351
352    /// The plugin's folder (read-only).
353    pub fn plugin_dir(&self) -> PathBuf {
354        // SAFETY: the host's function with this plugin.
355        field!(self.table, AnvilHost, plugin_dir)
356            .flatten()
357            .map_or_else(PathBuf::new, |f| wide_path(unsafe { f(self.plugin) }))
358    }
359
360    /// The plugin's writable `anvil/data/<id>/`, created on the first call.
361    pub fn data_dir(&self) -> PathBuf {
362        // SAFETY: the host's function with this plugin.
363        field!(self.table, AnvilHost, data_dir)
364            .flatten()
365            .map_or_else(PathBuf::new, |f| wide_path(unsafe { f(self.plugin) }))
366    }
367
368    // --- log -------------------------------------------------------------------
369
370    /// One line of `anvil.log`, under the plugin's id: `host.log(level, "text")`
371    /// or `host.log(level, format_args!(…))`.
372    pub fn log(&self, level: LogLevel, message: impl Display) {
373        write_log(self.table, self.plugin, level, &message);
374    }
375
376    /// A debug line.
377    pub fn debug(&self, message: impl Display) {
378        self.log(LogLevel::Debug, message);
379    }
380
381    /// An information line.
382    pub fn info(&self, message: impl Display) {
383        self.log(LogLevel::Info, message);
384    }
385
386    /// A warning.
387    pub fn warn(&self, message: impl Display) {
388        self.log(LogLevel::Warning, message);
389    }
390
391    /// An error line.
392    pub fn error(&self, message: impl Display) {
393        self.log(LogLevel::Error, message);
394    }
395
396    // --- changes on declared symbols ------------------------------------------------
397
398    /// Hooks a function symbol: the game calls `detour`, which passes on
399    /// through `hook.next()`. With `hook` and `detour` of the symbol's
400    /// generated type (`sym::<Name>Fn`), a detour of another shape does not
401    /// compile; but the symbol id is a plain `u32`, so nothing ties `F` to
402    /// `symbol` but the caller. [`hook_symbol`](Self::hook_symbol) is the safe
403    /// form, with the typed symbols of `anvil gen --lang rust-sdk`.
404    ///
405    /// During `load` the change is staged and enabled with the others when
406    /// load returns; later it is enabled at once (or with its group).
407    ///
408    /// # Safety
409    /// `symbol` is a function symbol whose declared signature `F` is: the
410    /// `sym::<Name>Fn` that `anvil gen --lang rust` writes for the same
411    /// symbol as `sym::<NAME>`. The game calls `detour` with the arguments
412    /// of that signature, and the hook's `next` is the game's function of it.
413    pub unsafe fn hook<F: FnPtr>(
414        &self,
415        hook: &'static FunctionHook<F>,
416        symbol: AnvilSymbol,
417        detour: F,
418    ) -> Result<()> {
419        let claim = hook.claim("hook_function")?;
420        let call = function!(self.table, AnvilHost, hook_function)?;
421        let mut change: *mut AnvilChange = ptr::null_mut();
422        let mut next: *mut c_void = ptr::null_mut();
423        let cell = hook.next_cell(&mut next);
424        // SAFETY: Anvil writes `cell` (the hook's empty cell or a local) during the call only; the caller vouches that the
425        // detour has the symbol's declared type.
426        let result = unsafe { call(self.plugin, symbol, detour.into_raw(), cell, &mut change) };
427        check(result, || format!("hook_function symbol {symbol}"))?;
428        hook.finish(claim, cell, next, change);
429        Ok(())
430    }
431
432    /// [`hook`](Self::hook) without `unsafe`: the symbol comes with its type,
433    /// `sym::typed::<NAME>` from `anvil gen --lang rust-sdk`, so `hook` and
434    /// `detour` must be of the symbol's own `sym::<Name>Fn` and a detour of
435    /// another shape does not compile.
436    ///
437    /// ```ignore
438    /// static SPEED_OBJECT: FunctionHook<sym::SpeedObjectFn> = FunctionHook::new();
439    /// host.hook_symbol(&SPEED_OBJECT, sym::typed::SPEED_OBJECT, on_speed_object)?;
440    /// ```
441    pub fn hook_symbol<F: FnPtr>(
442        &self,
443        hook: &'static FunctionHook<F>,
444        symbol: FnSymbol<F>,
445        detour: F,
446    ) -> Result<()> {
447        // SAFETY: FnSymbol::new's contract ties `F` to the symbol's declared
448        // signature, which is what `hook` asks of its caller.
449        unsafe { self.hook(hook, symbol.id(), detour) }
450    }
451
452    /// A mid hook: `callback` runs when the game reaches the site (a function
453    /// or site symbol with at least 5 declared bytes), before the code there.
454    /// It may run on several game threads at once. A panic in it is logged
455    /// once and the game carries on.
456    pub fn mid_hook<F>(&self, site: AnvilSymbol, callback: F) -> Result<Change>
457    where
458        F: Fn(&mut Cpu) + Send + Sync + 'static,
459    {
460        let call = function!(self.table, AnvilHost, mid_hook)?;
461        let what = format!("mid_hook symbol {site}");
462        self.cpu_change(what, callback, |function, user, out| {
463            // SAFETY: a declared symbol; the adapter is never freed and never unwinds.
464            unsafe { call(self.plugin, site, function, user, out) }
465        })
466    }
467
468    /// A block replacement: the symbol's declared bytes never run; `callback`
469    /// runs instead and the game resumes at the block's `resume` or end
470    /// (unless the callback writes `rip` with [`Cpu::regs_mut`]).
471    pub fn replace_block<F>(&self, block: AnvilSymbol, callback: F) -> Result<Change>
472    where
473        F: Fn(&mut Cpu) + Send + Sync + 'static,
474    {
475        let call = function!(self.table, AnvilHost, replace_block)?;
476        let what = format!("replace_block symbol {block}");
477        self.cpu_change(what, callback, |function, user, out| {
478            // SAFETY: as in mid_hook.
479            unsafe { call(self.plugin, block, function, user, out) }
480        })
481    }
482
483    /// A call redirect at a `call rel32` site symbol: `target` gets the call,
484    /// `hook.next()` is the previous target.
485    ///
486    /// # Safety
487    /// A call site declares no signature: `F` must be the type of the
488    /// function the site calls.
489    pub unsafe fn redirect_call<F: FnPtr>(
490        &self,
491        hook: &'static FunctionHook<F>,
492        call_site: AnvilSymbol,
493        target: F,
494    ) -> Result<()> {
495        let claim = hook.claim("redirect_call")?;
496        let call = function!(self.table, AnvilHost, redirect_call)?;
497        let mut change: *mut AnvilChange = ptr::null_mut();
498        let mut next: *mut c_void = ptr::null_mut();
499        let cell = hook.next_cell(&mut next);
500        // SAFETY: a declared symbol; the caller vouches for the type.
501        let result = unsafe { call(self.plugin, call_site, target.into_raw(), cell, &mut change) };
502        check(result, || format!("redirect_call symbol {call_site}"))?;
503        hook.finish(claim, cell, next, change);
504        Ok(())
505    }
506
507    /// A byte patch within the symbol's declared bytes.
508    ///
509    /// # Safety
510    /// The bytes become the game's code or data at the site: they must be
511    /// what the game can run or read there.
512    pub unsafe fn patch_bytes(&self, site: AnvilSymbol, bytes: &[u8]) -> Result<Change> {
513        let call = function!(self.table, AnvilHost, patch_bytes)?;
514        let mut change: *mut AnvilChange = ptr::null_mut();
515        // SAFETY: Anvil copies the bytes during the call; the caller vouches for them.
516        let result = unsafe {
517            call(
518                self.plugin,
519                site,
520                bytes.as_ptr().cast(),
521                bytes.len(),
522                &mut change,
523            )
524        };
525        check(result, || format!("patch_bytes symbol {site}"))?;
526        Ok(Change::from_raw(change))
527    }
528
529    /// A pointer swap on a slot symbol (`points_to`): the slot holds `value`,
530    /// `swap.previous()` the rest of the chain.
531    ///
532    /// # Safety
533    /// The game uses `value` as the slot's pointer: it must be what the slot
534    /// points to (a function of the vtable entry's type, an object), for as
535    /// long as the change lives.
536    pub unsafe fn swap_pointer(
537        &self,
538        swap: &'static PointerSwap,
539        slot: AnvilSymbol,
540        value: *mut c_void,
541    ) -> Result<()> {
542        let claim = swap.claim()?;
543        let call = function!(self.table, AnvilHost, swap_pointer)?;
544        let mut change: *mut AnvilChange = ptr::null_mut();
545        // SAFETY: `previous` lives in a static and is 8-byte aligned; the caller vouches for `value`.
546        let result = unsafe { call(self.plugin, slot, value, swap.previous_slot(), &mut change) };
547        check(result, || format!("swap_pointer symbol {slot}"))?;
548        claim.finish(change);
549        Ok(())
550    }
551
552    /// Replaces an import of eu4.exe, e.g. `("KERNEL32.dll", "GetTickCount")`
553    /// (the module ignores case).
554    ///
555    /// # Safety
556    /// `F` must be the type of the imported function.
557    pub unsafe fn replace_import<F: FnPtr>(
558        &self,
559        hook: &'static FunctionHook<F>,
560        module: &str,
561        function: &str,
562        replacement: F,
563    ) -> Result<()> {
564        let claim = hook.claim("replace_import")?;
565        let call = function!(self.table, AnvilHost, replace_import)?;
566        let (module_c, function_c) = (c_string(module), c_string(function));
567        let mut change: *mut AnvilChange = ptr::null_mut();
568        let mut next: *mut c_void = ptr::null_mut();
569        let cell = hook.next_cell(&mut next);
570        // SAFETY: NUL-terminated names; the caller vouches for the type.
571        let result = unsafe {
572            call(
573                self.plugin,
574                module_c.as_ptr(),
575                function_c.as_ptr(),
576                replacement.into_raw(),
577                cell,
578                &mut change,
579            )
580        };
581        check(result, || format!("replace_import {module}!{function}"))?;
582        hook.finish(claim, cell, next, change);
583        Ok(())
584    }
585
586    /// A function hook at a raw address outside the eu4.exe image (e.g. a
587    /// Direct3D 9 vtable entry); `expected_prologue` may be empty.
588    ///
589    /// # Safety
590    /// `address` is the start of a function of type `F` that lives while the
591    /// change does.
592    pub unsafe fn hook_at<F: FnPtr>(
593        &self,
594        hook: &'static FunctionHook<F>,
595        address: NonNull<c_void>,
596        expected_prologue: &[u8],
597        detour: F,
598    ) -> Result<()> {
599        let claim = hook.claim("hook_function_at")?;
600        let call = function!(self.table, AnvilHost, hook_function_at)?;
601        let mut change: *mut AnvilChange = ptr::null_mut();
602        let mut next: *mut c_void = ptr::null_mut();
603        let cell = hook.next_cell(&mut next);
604        // SAFETY: the caller's contract; the bytes are read during the call.
605        let result = unsafe {
606            call(
607                self.plugin,
608                address.as_ptr(),
609                bytes_or_null(expected_prologue),
610                expected_prologue.len(),
611                detour.into_raw(),
612                cell,
613                &mut change,
614            )
615        };
616        check(result, || {
617            format!("hook_function_at {:p}", address.as_ptr())
618        })?;
619        hook.finish(claim, cell, next, change);
620        Ok(())
621    }
622
623    /// A mid hook at a raw address outside the eu4.exe image; `expected` may
624    /// be empty.
625    ///
626    /// # Safety
627    /// `address` is the start of an instruction that lives while the change does.
628    pub unsafe fn mid_hook_at<F>(
629        &self,
630        address: NonNull<c_void>,
631        expected: &[u8],
632        callback: F,
633    ) -> Result<Change>
634    where
635        F: Fn(&mut Cpu) + Send + Sync + 'static,
636    {
637        let call = function!(self.table, AnvilHost, mid_hook_at)?;
638        let what = format!("mid_hook_at {:p}", address.as_ptr());
639        self.cpu_change(what, callback, |function, user, out| {
640            // SAFETY: the caller's contract; the adapter never unwinds.
641            unsafe {
642                call(
643                    self.plugin,
644                    address.as_ptr(),
645                    bytes_or_null(expected),
646                    expected.len(),
647                    function,
648                    user,
649                    out,
650                )
651            }
652        })
653    }
654
655    /// After load: the changes `body` requests are enabled together, or none
656    /// when it returns an error or panics (the panic goes on, logged as
657    /// `panic: …` unless an adapter of this crate catches it further out,
658    /// which logs it itself). Inside `load`
659    /// the load itself is the group: `WrongPhase`.
660    ///
661    /// When the group's changes are dropped (an error, a panic, or a commit
662    /// Anvil refuses), the [`FunctionHook`]s and [`PointerSwap`]s this thread
663    /// filled in `body` are free again: `is_active` is false and they take a
664    /// new request.
665    ///
666    /// The group is the plugin's, not this thread's: a request from any of
667    /// the plugin's threads while it is open (a panel click, a thread `body`
668    /// started) joins it, is enabled only with the commit and dropped with an
669    /// abort. Hook objects another thread filled keep their handles then:
670    /// `remove()` them before reusing them.
671    pub fn group<R>(&self, body: impl FnOnce() -> Result<R>) -> Result<R> {
672        let begin = function!(self.table, AnvilHost, begin_group)?;
673        let commit = function!(self.table, AnvilHost, commit_group)?;
674        let abort = function!(self.table, AnvilHost, abort_group)?;
675        // SAFETY: the host's functions with this plugin.
676        check(unsafe { begin(self.plugin) }, || "begin_group")?;
677        crate::change::group_opened();
678        match catch_raw(body) {
679            Ok(Ok(value)) => {
680                // SAFETY: as above.
681                let committed = check(unsafe { commit(self.plugin) }, || "commit_group");
682                crate::change::group_closed(committed.is_err());
683                committed?;
684                Ok(value)
685            }
686            Ok(Err(error)) => {
687                // SAFETY: as above.
688                unsafe { abort(self.plugin) };
689                crate::change::group_closed(true);
690                Err(error)
691            }
692            Err(panic) => {
693                // SAFETY: as above.
694                unsafe { abort(self.plugin) };
695                crate::change::group_closed(true);
696                // Logged here when no adapter of this thread catches it further out.
697                resume(panic)
698            }
699        }
700    }
701
702    fn cpu_change<F>(
703        &self,
704        what: String,
705        callback: F,
706        request: impl FnOnce(AnvilCpuCallback, *mut c_void, *mut *mut AnvilChange) -> AnvilResult,
707    ) -> Result<Change>
708    where
709        F: Fn(&mut Cpu) + Send + Sync + 'static,
710    {
711        let adapter: &'static CpuAdapter<F> = Box::leak(Box::new(CpuAdapter {
712            callback,
713            what,
714            panicked: AtomicBool::new(false),
715        }));
716        let mut change: *mut AnvilChange = ptr::null_mut();
717        let result = request(
718            Some(cpu_adapter::<F>),
719            ptr::from_ref(adapter).cast_mut().cast(),
720            &mut change,
721        );
722        check(result, || adapter.what.clone())?;
723        Ok(Change::from_raw(change))
724    }
725
726    // --- addresses -------------------------------------------------------------------
727
728    /// The verified address of a symbol; `None` for an unknown one, or one
729    /// symbols.toml declares `absent` on the running game build.
730    pub fn address(&self, symbol: AnvilSymbol) -> Option<NonNull<c_void>> {
731        // SAFETY: the host's function with this plugin.
732        field!(self.table, AnvilHost, address_of)
733            .flatten()
734            .and_then(|f| NonNull::new(unsafe { f(self.plugin, symbol) }))
735    }
736
737    /// Whether the symbol is there on the running game build: check it before
738    /// using a symbol symbols.toml may declare `absent`.
739    pub fn present(&self, symbol: AnvilSymbol) -> bool {
740        self.address(symbol).is_some()
741    }
742
743    /// The game function of a function symbol, to call.
744    ///
745    /// # Safety
746    /// `F` is the symbol's generated type (`sym::<Name>Fn`).
747    pub unsafe fn function<F: FnPtr>(&self, symbol: AnvilSymbol) -> Option<F> {
748        // SAFETY: a verified function of the caller's type.
749        self.address(symbol)
750            .map(|address| unsafe { F::from_raw(address.as_ptr()) })
751    }
752
753    /// The game's data at a data symbol, for the life of the process.
754    ///
755    /// # Safety
756    /// The symbol's memory holds a `T`, and nothing writes it while the
757    /// reference is used (data the game never changes, or read only on the
758    /// thread that writes it).
759    pub unsafe fn data<T>(&self, symbol: AnvilSymbol) -> Option<&'static T> {
760        // SAFETY: the caller's contract.
761        self.address(symbol)
762            .map(|address| unsafe { address.cast::<T>().as_ref() })
763    }
764
765    /// A value of symbols.toml `values` (a `rip_relative` value is an RVA).
766    pub fn value(&self, symbol: AnvilSymbol, name: &str) -> Result<u64> {
767        let call = function!(self.table, AnvilHost, symbol_value)?;
768        let name_c = c_string(name);
769        let mut out = 0u64;
770        // SAFETY: the host's function with a NUL-terminated name.
771        let result = unsafe { call(self.plugin, symbol, name_c.as_ptr(), &mut out) };
772        check(result, || format!("symbol_value symbol {symbol}.{name}"))?;
773        Ok(out)
774    }
775
776    // --- settings (settings.gen.rs) -----------------------------------------------------
777
778    /// A bool setting (false for an unknown one or one of another type).
779    pub fn setting_bool(&self, setting: AnvilSetting) -> bool {
780        // SAFETY: the host's function with this plugin.
781        field!(self.table, AnvilHost, setting_bool)
782            .flatten()
783            .is_some_and(|f| unsafe { f(self.plugin, setting) } != 0)
784    }
785
786    /// An int, bool, enum index (`<NAME>_<OPTION>`) or key code.
787    pub fn setting_int(&self, setting: AnvilSetting) -> i64 {
788        // SAFETY: as above.
789        field!(self.table, AnvilHost, setting_int)
790            .flatten()
791            .map_or(0, |f| unsafe { f(self.plugin, setting) })
792    }
793
794    /// A float or int setting.
795    pub fn setting_float(&self, setting: AnvilSetting) -> f64 {
796        // SAFETY: as above.
797        field!(self.table, AnvilHost, setting_float)
798            .flatten()
799            .map_or(0.0, |f| unsafe { f(self.plugin, setting) })
800    }
801
802    /// A string, an enum option's name or a key ("Ctrl+F12").
803    pub fn setting_string(&self, setting: AnvilSetting) -> String {
804        // SAFETY: valid until the next change of the setting; copied at once.
805        field!(self.table, AnvilHost, setting_string)
806            .flatten()
807            .map_or_else(String::new, |f| unsafe {
808                owned_string(f(self.plugin, setting))
809            })
810    }
811
812    /// A key setting.
813    pub fn setting_key(&self, setting: AnvilSetting) -> Key {
814        Key(self.setting_int(setting))
815    }
816
817    /// `handler` runs after a `restart = false` setting changes (in the
818    /// overlay), on the thread that changed it; kept for the process.
819    pub fn subscribe_setting<F>(&self, setting: AnvilSetting, handler: F) -> Result<()>
820    where
821        F: Fn() + Send + Sync + 'static,
822    {
823        let call = function!(self.table, AnvilHost, subscribe_setting)?;
824        let what = format!("setting {setting} handler");
825        let adapter: &'static SettingAdapter<F> = Box::leak(Box::new(SettingAdapter {
826            handler,
827            what,
828            panicked: AtomicBool::new(false),
829        }));
830        // SAFETY: the adapter is never freed and never unwinds.
831        let result = unsafe {
832            call(
833                self.plugin,
834                setting,
835                Some(setting_adapter::<F>),
836                ptr::from_ref(adapter).cast_mut().cast(),
837            )
838        };
839        check(result, || format!("subscribe_setting setting {setting}"))
840    }
841
842    // --- events ----------------------------------------------------------------------
843
844    /// `handler(&payload)` runs for each `event`, synchronously on the
845    /// publishing thread; kept for the process.
846    pub fn subscribe<P, F>(&self, event: Event<P>, handler: F) -> Result<()>
847    where
848        P: Payload,
849        F: Fn(&P) + Send + Sync + 'static,
850    {
851        let call = function!(self.table, AnvilHost, subscribe)?;
852        let name = event.name();
853        let what = format!("{} handler", name.to_string_lossy());
854        let adapter: &'static EventAdapter<P, F> = Box::leak(Box::new(EventAdapter {
855            handler,
856            what,
857            panicked: AtomicBool::new(false),
858            _payload: std::marker::PhantomData,
859        }));
860        // SAFETY: a NUL-terminated name; the adapter is never freed and never unwinds.
861        let result = unsafe {
862            call(
863                self.plugin,
864                name.as_ptr(),
865                Some(event_adapter::<P, F>),
866                ptr::from_ref(adapter).cast_mut().cast(),
867            )
868        };
869        check(result, || format!("subscribe {}", name.to_string_lossy()))
870    }
871
872    /// `handler(name, payload)` for any event name, with the publisher's raw
873    /// payload pointer (valid during the handler).
874    pub fn subscribe_raw<F>(&self, event: &str, handler: F) -> Result<()>
875    where
876        F: Fn(&str, *const c_void) + Send + Sync + 'static,
877    {
878        let call = function!(self.table, AnvilHost, subscribe)?;
879        let name = c_string(event);
880        let what = format!("{event} handler");
881        let adapter: &'static RawEventAdapter<F> = Box::leak(Box::new(RawEventAdapter {
882            handler,
883            what,
884            panicked: AtomicBool::new(false),
885        }));
886        // SAFETY: as in subscribe.
887        let result = unsafe {
888            call(
889                self.plugin,
890                name.as_ptr(),
891                Some(raw_event_adapter::<F>),
892                ptr::from_ref(adapter).cast_mut().cast(),
893            )
894        };
895        check(result, || format!("subscribe {event}"))
896    }
897
898    /// Publishes `<plugin-id>.<name>` with no payload (NULL), which every
899    /// [`Payload::read`](crate::Payload::read) answers without reading.
900    pub fn publish(&self, event: &str) -> Result<()> {
901        // SAFETY: a NULL payload, which no subscriber reads.
902        unsafe { self.publish_raw(event, ptr::null()) }
903    }
904
905    /// Publishes `<plugin-id>.<name>` with a payload its subscribers read
906    /// during the call: synchronously, on this thread, before it returns.
907    ///
908    /// # Safety
909    /// `payload` is null or points to a value of the layout this event's
910    /// subscribers read it as: the payload type its documentation (or C
911    /// header) names, which every [`Event`] of that name declares with
912    /// [`Event::new`]. For a type that starts with `uint32_t size`, the
913    /// `size` is the value's own and at least that many bytes are readable.
914    /// It stays valid and unchanged until the call returns.
915    pub unsafe fn publish_raw(&self, event: &str, payload: *const c_void) -> Result<()> {
916        let call = function!(self.table, AnvilHost, publish)?;
917        let name = c_string(event);
918        // SAFETY: a NUL-terminated name; the caller vouches for the payload.
919        check(unsafe { call(self.plugin, name.as_ptr(), payload) }, || {
920            format!("publish {event}")
921        })
922    }
923
924    // --- services ----------------------------------------------------------------------
925
926    /// Registers a service `<plugin-id>.<service>` of major `version`.
927    ///
928    /// # Safety
929    /// `service` is a `#[repr(C)]` struct whose first field is `u32 size`
930    /// (its size), followed by `extern "C"` functions that never unwind, as
931    /// the service's C header describes it.
932    pub unsafe fn register_service<T: Sync>(
933        &self,
934        name: &str,
935        version: u32,
936        service: &'static T,
937    ) -> Result<()> {
938        let call = function!(self.table, AnvilHost, register_service)?;
939        let name_c = c_string(name);
940        // SAFETY: the service lives for the process; the caller vouches for its layout.
941        let result = unsafe {
942            call(
943                self.plugin,
944                name_c.as_ptr(),
945                version,
946                ptr::from_ref(service).cast(),
947            )
948        };
949        check(result, || format!("register_service {name} v{version}"))
950    }
951
952    /// A service by name and major version, as a [`Table`]; the typed
953    /// wrappers ([`game::Game`](crate::game::Game),
954    /// [`world::World`](crate::world::World),
955    /// [`panel::Panels`](crate::panel::Panels),
956    /// [`benchmark::Benchmark`](crate::benchmark::Benchmark)) use it. Only the
957    /// table's `size` is read here: a provider older than `T` has a shorter
958    /// table, and [`Table`] reads a field only when that size covers it.
959    ///
960    /// # Safety
961    /// `T` is the service's table type for that version (or a newer
962    /// release of the same version): a `#[repr(C)]` struct whose first field
963    /// is `u32 size`.
964    pub unsafe fn service<T>(&self, name: &CStr, version: u32) -> Option<Table<T>> {
965        let call = field!(self.table, AnvilHost, get_service).flatten()?;
966        // SAFETY: a NUL-terminated name; a service's table starts with its
967        // size, has that many bytes and lives for the process (ADR 0001);
968        // the caller vouches for T.
969        unsafe { Table::from_raw(call(self.plugin, name.as_ptr(), version).cast::<T>()) }
970    }
971}
972
973fn bytes_or_null(bytes: &[u8]) -> *const c_void {
974    if bytes.is_empty() {
975        ptr::null()
976    } else {
977        bytes.as_ptr().cast()
978    }
979}