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
25pub(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
31pub(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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub enum LogLevel {
41 Debug,
43 Info,
45 Warning,
47 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#[derive(Clone, Copy, Debug)]
64pub struct GameInfo {
65 pub build_id: Option<&'static str>,
67 pub image_base: usize,
69 pub image_size: u32,
71 pub sha256: Option<&'static str>,
74}
75
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
79pub struct Key(pub i64);
80
81impl Key {
82 pub const SHIFT: i64 = 0x100;
84 pub const CTRL: i64 = 0x200;
86 pub const ALT: i64 = 0x400;
88
89 pub const fn vk(self) -> u8 {
91 (self.0 & 0xFF) as u8
92 }
93 pub const fn shift(self) -> bool {
95 self.0 & Self::SHIFT != 0
96 }
97 pub const fn ctrl(self) -> bool {
99 self.0 & Self::CTRL != 0
100 }
101 pub const fn alt(self) -> bool {
103 self.0 & Self::ALT != 0
104 }
105 pub const fn is_bound(self) -> bool {
107 self.0 != 0
108 }
109}
110
111#[derive(Clone, Copy)]
118pub struct Host {
119 table: Table<AnvilHost>,
120 plugin: *mut AnvilPlugin,
121}
122
123unsafe impl Send for Host {}
125unsafe 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
136struct 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 let adapter = unsafe { &*user.cast::<CpuAdapter<F>>() };
150 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 let adapter = unsafe { &*context.cast::<EventAdapter<P, F>>() };
173 run_callback(&adapter.what, &adapter.panicked, (), || {
174 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 let adapter = unsafe { &*context.cast::<RawEventAdapter<F>>() };
194 run_callback(&adapter.what, &adapter.panicked, (), || {
195 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 let adapter = unsafe { &*context.cast::<SettingAdapter<F>>() };
213 run_callback(&adapter.what, &adapter.panicked, (), || (adapter.handler)());
214}
215
216fn 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 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 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 pub fn current() -> Option<Self> {
265 let table = TABLE.load(Ordering::Acquire);
266 let plugin = PLUGIN.load(Ordering::Acquire);
267 unsafe { Table::from_raw(table) }.map(|table| Self { table, plugin })
269 }
270
271 pub fn c_api(&self) -> Table<AnvilHost> {
273 self.table
274 }
275
276 pub fn raw_plugin(&self) -> *mut AnvilPlugin {
278 self.plugin
279 }
280
281 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 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 pub fn anvil_version(&self) -> &'static str {
311 let version = field!(self.table, AnvilHost, anvil_version).unwrap_or(ptr::null());
312 unsafe { static_str(version) }.unwrap_or("")
314 }
315
316 pub(crate) fn restores_next(&self) -> bool {
321 restores_next(self.anvil_version())
322 }
323
324 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 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 let (build_id, image_base, image_size) =
349 unsafe { ((*game).build_id, (*game).image_base, (*game).image_size) };
350 GameInfo {
351 build_id: unsafe { static_str(build_id) },
353 image_base,
354 image_size,
355 sha256: unsafe { static_str(sha256.cast_const()) },
357 }
358 }
359
360 pub fn plugin_dir(&self) -> PathBuf {
362 field!(self.table, AnvilHost, plugin_dir)
364 .flatten()
365 .map_or_else(PathBuf::new, |f| wide_path(unsafe { f(self.plugin) }))
366 }
367
368 pub fn data_dir(&self) -> PathBuf {
370 field!(self.table, AnvilHost, data_dir)
372 .flatten()
373 .map_or_else(PathBuf::new, |f| wide_path(unsafe { f(self.plugin) }))
374 }
375
376 pub fn log(&self, level: LogLevel, message: impl Display) {
381 write_log(self.table, self.plugin, level, &message);
382 }
383
384 pub fn debug(&self, message: impl Display) {
386 self.log(LogLevel::Debug, message);
387 }
388
389 pub fn info(&self, message: impl Display) {
391 self.log(LogLevel::Info, message);
392 }
393
394 pub fn warn(&self, message: impl Display) {
396 self.log(LogLevel::Warning, message);
397 }
398
399 pub fn error(&self, message: impl Display) {
401 self.log(LogLevel::Error, message);
402 }
403
404 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 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 pub fn hook_symbol<F: FnPtr>(
451 &self,
452 hook: &'static FunctionHook<F>,
453 symbol: FnSymbol<F>,
454 detour: F,
455 ) -> Result<()> {
456 unsafe { self.hook(hook, symbol.id(), detour) }
459 }
460
461 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 unsafe { call(self.plugin, site, function, user, out) }
474 })
475 }
476
477 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 unsafe { call(self.plugin, block, function, user, out) }
489 })
490 }
491
492 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 unsafe { abort(self.plugin) };
709 crate::change::group_closed(self.plugin, true);
710 Err(error)
711 }
712 Err(panic) => {
713 unsafe { abort(self.plugin) };
715 crate::change::group_closed(self.plugin, true);
716 drop(gate);
717 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 pub fn address(&self, symbol: AnvilSymbol) -> Option<NonNull<c_void>> {
752 field!(self.table, AnvilHost, address_of)
754 .flatten()
755 .and_then(|f| NonNull::new(unsafe { f(self.plugin, symbol) }))
756 }
757
758 pub fn present(&self, symbol: AnvilSymbol) -> bool {
761 self.address(symbol).is_some()
762 }
763
764 pub unsafe fn function<F: FnPtr>(&self, symbol: AnvilSymbol) -> Option<F> {
769 self.address(symbol)
771 .map(|address| unsafe { F::from_raw(address.as_ptr()) })
772 }
773
774 pub unsafe fn data<T>(&self, symbol: AnvilSymbol) -> Option<&'static T> {
781 self.address(symbol)
783 .map(|address| unsafe { address.cast::<T>().as_ref() })
784 }
785
786 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 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 pub fn setting_bool(&self, setting: AnvilSetting) -> bool {
801 field!(self.table, AnvilHost, setting_bool)
803 .flatten()
804 .is_some_and(|f| unsafe { f(self.plugin, setting) } != 0)
805 }
806
807 pub fn setting_int(&self, setting: AnvilSetting) -> i64 {
809 field!(self.table, AnvilHost, setting_int)
811 .flatten()
812 .map_or(0, |f| unsafe { f(self.plugin, setting) })
813 }
814
815 pub fn setting_float(&self, setting: AnvilSetting) -> f64 {
817 field!(self.table, AnvilHost, setting_float)
819 .flatten()
820 .map_or(0.0, |f| unsafe { f(self.plugin, setting) })
821 }
822
823 pub fn setting_string(&self, setting: AnvilSetting) -> String {
825 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 pub fn setting_key(&self, setting: AnvilSetting) -> Key {
835 Key(self.setting_int(setting))
836 }
837
838 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 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 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 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 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 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 pub fn publish(&self, event: &str) -> Result<()> {
922 unsafe { self.publish_raw(event, ptr::null()) }
924 }
925
926 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 check(unsafe { call(self.plugin, name.as_ptr(), payload) }, || {
941 format!("publish {event}")
942 })
943 }
944
945 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 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 pub unsafe fn service<T>(&self, name: &CStr, version: u32) -> Option<Table<T>> {
986 let call = field!(self.table, AnvilHost, get_service).flatten()?;
987 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
1002pub(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}