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