anvil/lib.rs
1//! Safe Rust API for plugins of [Anvil](https://github.com/happy-dwarf-team/anvil),
2//! the native plugin loader for Europa Universalis IV 1.37.5.
3//!
4//! The crate sits on the raw bindings of [`anvil-sys`](sys) and adds what the C
5//! ABI leaves to every plugin:
6//!
7//! - [`plugin!`]: exports `anvil_plugin_load`, creates the plugin with
8//! [`Plugin::load`] and turns an [`Error`] or a panic into the result Anvil
9//! rolls the plugin back on.
10//! - Every callback Anvil or the game calls through an adapter of this crate
11//! (mid hooks, block replacements, events, settings, panel clicks, work for
12//! the main thread) runs under `catch_unwind`: a panic is logged once per
13//! callback and never crosses the FFI.
14//! - [`Change`] is a handle whose `Drop` removes the change.
15//! - Typed wrappers of the services Anvil ships: [`game`] (`anvil-game.game`),
16//! [`world`] (`anvil-game.world`), [`camera`] (`anvil-game.camera`),
17//! [`panel`] (`anvil-overlay.panel`),
18//! [`benchmark`] (`anvil.benchmark`), [`map`] (`anvil-map.modes`),
19//! [`script`] (`anvil-script.effects`, `anvil-script.day_end`) and
20//! [`log_throttle`] (`anvil-log-throttle.messages`).
21//!
22//! # Where `unsafe` stays
23//!
24//! Host and service calls are safe. What reaches the game's memory by address
25//! or puts raw bytes and pointers into it stays an `unsafe fn` with its
26//! contract: calling a hook's [`next`](FunctionHook::next) (the generated
27//! function types are `unsafe extern "C" fn`), [`Host::hook`] (a symbol id is
28//! a plain `u32`, so the caller ties it to its `sym::<Name>Fn`; with the
29//! [`FnSymbol`]s of `anvil gen --lang rust-sdk`, [`Host::hook_symbol`] is the
30//! safe form),
31//! [`Host::function`], [`Host::data`], writing the mid-hook context
32//! ([`Cpu::regs_mut`]), byte patches, pointer swaps, call redirects, import
33//! replacements, changes at raw addresses, and publishing a raw payload
34//! ([`Host::publish_raw`]).
35//!
36//! Service tables are [`Table`]s: a provider older than this crate has a
37//! shorter table, and the crate reads a function only when the table's `size`
38//! covers it, never through a reference to the whole table.
39//!
40//! # A plugin
41//!
42//! ```no_run
43//! use anvil::{Change, Host, Plugin};
44//!
45//! #[allow(dead_code)]
46//! mod sym {
47//! // anvil gen --lang rust symbols.toml writes this file (build.rs).
48//! pub const IDLE_EXIT: u32 = 0;
49//! }
50//!
51//! struct Hello {
52//! // Dropping a Change removes it; the plugin is kept for the process.
53//! _idle_exit: Change,
54//! }
55//!
56//! impl Plugin for Hello {
57//! fn load(host: &mut Host) -> anvil::Result<Self> {
58//! host.info(format_args!("hello from Rust on Anvil {}", host.anvil_version()));
59//! let log = *host;
60//! let idle_exit = host.mid_hook(sym::IDLE_EXIT, move |cpu| {
61//! log.info(format_args!("returning to the menu (rcx={:#x})", cpu.rcx));
62//! })?;
63//! Ok(Hello { _idle_exit: idle_exit })
64//! }
65//! }
66//!
67//! anvil::plugin!(Hello);
68//! ```
69//!
70//! Versions: this crate has its own `0.x` line; the source compatibility of
71//! Anvil's ADR 0001 covers it from its 1.0.
72#![deny(unsafe_op_in_unsafe_fn)]
73#![warn(missing_docs, clippy::undocumented_unsafe_blocks)]
74
75pub use anvil_sys as sys;
76
77/// The field `$field` of a [`Table`], when the provider's `size` covers it
78/// (the `ANVIL_*_HAS` macros of the C headers); else `None`. It reads through
79/// the table's pointer and never makes a `&$ty`.
80macro_rules! field {
81 ($table:expr, $ty:ty, $field:ident) => {{
82 let table: $crate::Table<$ty> = $table;
83 // SAFETY: the offset and the type of a field of $ty.
84 unsafe {
85 table.read_field(
86 ::core::mem::offset_of!($ty, $field),
87 $crate::table::field_type::<$ty, _>(|t| &t.$field),
88 )
89 }
90 }};
91}
92
93/// The function `$field` of a [`Table`], when the provider's `size` covers
94/// it and the function is there; else `Unsupported`.
95macro_rules! function {
96 ($table:expr, $ty:ty, $field:ident) => {{
97 $crate::error::need(field!($table, $ty, $field).flatten(), stringify!($field))
98 }};
99}
100
101mod change;
102mod cpu;
103mod error;
104mod event;
105mod fnptr;
106mod host;
107mod panic;
108pub(crate) mod table;
109mod text;
110
111pub mod benchmark;
112pub mod camera;
113pub mod commands;
114pub mod game;
115pub mod input;
116pub mod log_throttle;
117pub mod map;
118pub mod panel;
119pub mod script;
120pub mod world;
121
122#[cfg(test)]
123mod tests;
124
125pub use change::{Change, FunctionHook, PointerSwap};
126pub use cpu::Cpu;
127pub use error::{Error, ErrorCode, Result};
128pub use event::{Event, Payload, PLUGINS_LOADED, RESUMED, SUSPENDED};
129pub use fnptr::{FnPtr, FnSymbol};
130pub use host::{GameInfo, Host, Key, LogLevel};
131pub use panic::catch_panic;
132pub use table::Table;
133pub use text::Tag;
134
135/// A plugin: one value, created by [`plugin!`] when Anvil loads the DLL and
136/// kept for the life of the process.
137///
138/// Request the changes in [`load`](Plugin::load); Anvil enables them together
139/// when it returns `Ok`. Return an error (or let a host call's error propagate
140/// with `?`) to refuse loading: Anvil rolls back everything the plugin staged.
141pub trait Plugin: Sized + 'static {
142 /// Called once, in the phase `plugin.toml` names.
143 fn load(host: &mut Host) -> Result<Self>;
144}
145
146/// Exports `anvil_plugin_load` for the plugin type: `anvil::plugin!(MyPlugin);`
147/// once, at the root of the plugin's `cdylib`.
148#[macro_export]
149macro_rules! plugin {
150 ($plugin:ty) => {
151 /// The entry point Anvil calls once (generated by `anvil::plugin!`).
152 ///
153 /// # Safety
154 /// Called by Anvil with its host table and this plugin's handle.
155 #[unsafe(no_mangle)]
156 pub unsafe extern "C" fn anvil_plugin_load(
157 host: *const $crate::sys::AnvilHost,
158 plugin: *mut $crate::sys::AnvilPlugin,
159 ) -> $crate::sys::AnvilResult {
160 // SAFETY: forwarded from Anvil, which calls this export once.
161 unsafe { $crate::__private::load::<$plugin>(host, plugin) }
162 }
163
164 const _: $crate::sys::AnvilPluginLoadFn = anvil_plugin_load;
165 };
166}
167
168#[doc(hidden)]
169pub mod __private {
170 use crate::sys::{
171 AnvilHost, AnvilPlugin, AnvilResult, ANVIL_API_VERSION, ANVIL_ERROR_INTERNAL,
172 ANVIL_ERROR_INVALID_ARGUMENT, ANVIL_ERROR_UNSUPPORTED, ANVIL_OK,
173 };
174 use crate::{host, panic, Host, LogLevel, Plugin, Table};
175
176 /// What `plugin!` exports.
177 ///
178 /// # Safety
179 /// `table` is Anvil's host table (or null) and `plugin` this plugin's
180 /// handle, both valid for the life of the process.
181 pub unsafe fn load<P: Plugin>(
182 table: *const AnvilHost,
183 plugin: *mut AnvilPlugin,
184 ) -> AnvilResult {
185 // SAFETY: see the contract above; only `size` is read here, and
186 // `Table` reads no field its size does not cover.
187 let Some(table) = (unsafe { Table::from_raw(table) }) else {
188 return ANVIL_ERROR_INVALID_ARGUMENT;
189 };
190 if field!(table, AnvilHost, api_version) != Some(ANVIL_API_VERSION)
191 || !host::covers_api_2_0(table)
192 || plugin.is_null()
193 {
194 return ANVIL_ERROR_UNSUPPORTED;
195 }
196 host::install(table, plugin);
197 panic::install_hook();
198 let mut host = Host::from_parts(table, plugin);
199 match panic::catch(|| P::load(&mut host)) {
200 Ok(Ok(loaded)) => {
201 // Kept for the process, as Anvil keeps the DLL: its changes stay.
202 std::mem::forget(loaded);
203 ANVIL_OK
204 }
205 Ok(Err(error)) => {
206 host.log(LogLevel::Error, format_args!("load() failed: {error}"));
207 error.code().result()
208 }
209 Err(message) => {
210 host.log(LogLevel::Error, format_args!("load() panicked: {message}"));
211 ANVIL_ERROR_INTERNAL
212 }
213 }
214 }
215}