Skip to main content

anvil/
change.rs

1use std::cell::RefCell;
2use std::ffi::c_void;
3use std::fmt;
4use std::marker::PhantomData;
5use std::ptr::{self, NonNull};
6use std::sync::atomic::{AtomicPtr, Ordering};
7
8use crate::error::{check, Error, ErrorCode, Result};
9use crate::fnptr::FnPtr;
10use crate::host::Host;
11use crate::sys::AnvilChange;
12
13/// A change's handle: dropping it removes the change; [`keep`](Change::keep)
14/// keeps the change for the rest of the process.
15///
16/// Anvil never frees its own stubs, so a game thread still inside a removed
17/// change finishes safely; what the change runs (an adapter of this crate)
18/// is never freed either.
19#[must_use = "dropping a Change removes the change; keep it in the plugin, or call keep()"]
20pub struct Change {
21    handle: Option<NonNull<AnvilChange>>,
22}
23
24// SAFETY: the handle is an opaque id; Anvil's remove may be called from any thread.
25unsafe impl Send for Change {}
26// SAFETY: as above; &Change only reads the id.
27unsafe impl Sync for Change {}
28
29impl Change {
30    pub(crate) fn from_raw(handle: *mut AnvilChange) -> Self {
31        Self {
32            handle: NonNull::new(handle),
33        }
34    }
35
36    /// The raw handle, for `AnvilHost::remove`.
37    pub fn as_raw(&self) -> *mut AnvilChange {
38        self.handle.map_or(ptr::null_mut(), NonNull::as_ptr)
39    }
40
41    /// Removes the change now. A change that is already gone (e.g. rolled
42    /// back after a failed load) is no error.
43    pub fn remove(mut self) -> Result<()> {
44        remove_handle(self.handle.take())
45    }
46
47    /// Keeps the change for the rest of the process.
48    pub fn keep(mut self) {
49        self.handle = None;
50    }
51}
52
53impl Drop for Change {
54    fn drop(&mut self) {
55        let _ = remove_handle(self.handle.take());
56    }
57}
58
59impl fmt::Debug for Change {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.debug_tuple("Change").field(&self.as_raw()).finish()
62    }
63}
64
65fn remove_handle(handle: Option<NonNull<AnvilChange>>) -> Result<()> {
66    let (Some(handle), Some(host)) = (handle, Host::current()) else {
67        return Ok(());
68    };
69    let Some(remove) = field!(host.c_api(), crate::sys::AnvilHost, remove).flatten() else {
70        return Ok(());
71    };
72    // SAFETY: a handle Anvil gave this plugin; Anvil answers NOT_FOUND for one that is gone.
73    let result = unsafe { remove(host.raw_plugin(), handle.as_ptr()) };
74    match check(result, || "remove") {
75        Err(error) if error.code() == ErrorCode::NotFound => Ok(()),
76        other => other,
77    }
78}
79
80/// Takes the change out of `slot` and removes it. A slot another thread is
81/// filling (a request on it still runs) is left to that thread.
82fn remove_slot(slot: &AtomicPtr<AnvilChange>, what: &str) -> Result<()> {
83    loop {
84        let current = slot.load(Ordering::Acquire);
85        if current == claiming() {
86            return Err(Error::new(
87                ErrorCode::InvalidArgument,
88                format!("{what}: another thread is installing a change on it; remove() after that returns"),
89            ));
90        }
91        if slot
92            .compare_exchange_weak(
93                current,
94                ptr::null_mut(),
95                Ordering::AcqRel,
96                Ordering::Acquire,
97            )
98            .is_ok()
99        {
100            return remove_handle(NonNull::new(current));
101        }
102    }
103}
104
105/// A slot filled in a group, and the handle (as an address) it got.
106type FilledSlot = (&'static AtomicPtr<AnvilChange>, usize);
107
108thread_local! {
109    /// The hook and swap slots this thread filled inside its open
110    /// [`Host::group`](crate::Host::group), each with the handle it got. A
111    /// group that aborts or whose commit Anvil refuses removes those changes,
112    /// so the slots are emptied again (else `is_active` stays true and the
113    /// next request on the hook answers "already holds a change").
114    static GROUP_SLOTS: RefCell<Option<Vec<FilledSlot>>> = const { RefCell::new(None) };
115}
116
117/// A group opened on this thread: slots filled from now on are recorded.
118pub(crate) fn group_opened() {
119    GROUP_SLOTS.with(|slots| *slots.borrow_mut() = Some(Vec::new()));
120}
121
122/// The group ended. When Anvil removed its changes (`discarded`), each slot
123/// still holding the handle it got in the group is emptied; a slot that has
124/// moved on (removed, or filled again) is left as it is.
125pub(crate) fn group_closed(discarded: bool) {
126    let Some(filled) = GROUP_SLOTS.with(|slots| slots.borrow_mut().take()) else {
127        return;
128    };
129    if !discarded {
130        return;
131    }
132    for (slot, handle) in filled {
133        let _ = slot.compare_exchange(
134            handle as *mut AnvilChange,
135            ptr::null_mut(),
136            Ordering::AcqRel,
137            Ordering::Acquire,
138        );
139    }
140}
141
142/// What a hook's or swap's `change` holds while a request on it runs.
143fn claiming() -> *mut AnvilChange {
144    NonNull::<AnvilChange>::dangling().as_ptr()
145}
146
147/// The `change` slot of a hook or swap, taken for one request with a
148/// compare-exchange: two threads requesting a change on one static cannot both
149/// get through (the later handle would overwrite the earlier one, which could
150/// then never be removed). Dropped without [`finish`](Claim::finish) (the
151/// request failed), the slot is empty again.
152pub(crate) struct Claim {
153    slot: &'static AtomicPtr<AnvilChange>,
154}
155
156impl Claim {
157    fn take(slot: &'static AtomicPtr<AnvilChange>, what: &str) -> Result<Self> {
158        slot.compare_exchange(
159            ptr::null_mut(),
160            claiming(),
161            Ordering::AcqRel,
162            Ordering::Acquire,
163        )
164        .map(|_| Self { slot })
165        .map_err(|_| {
166            Error::new(
167                ErrorCode::InvalidArgument,
168                format!("{what} already holds a change; remove() it first"),
169            )
170        })
171    }
172
173    /// The request succeeded: the slot holds its handle.
174    pub(crate) fn finish(self, change: *mut AnvilChange) {
175        self.slot.store(change, Ordering::Release);
176        if !change.is_null() {
177            GROUP_SLOTS.with(|slots| {
178                if let Some(filled) = slots.borrow_mut().as_mut() {
179                    filled.push((self.slot, change as usize));
180                }
181            });
182        }
183        std::mem::forget(self);
184    }
185}
186
187impl Drop for Claim {
188    fn drop(&mut self) {
189        self.slot.store(ptr::null_mut(), Ordering::Release);
190    }
191}
192
193/// A function hook, call redirect or import replacement, and the rest of its
194/// chain. It lives in a `static`, so the detour (a plain function the game
195/// calls) reaches `next`, and Anvil can write `next` into it before the change
196/// is enabled:
197///
198/// ```ignore
199/// static SPEED_OBJECT: anvil::FunctionHook<sym::SpeedObjectFn> = anvil::FunctionHook::new();
200///
201/// unsafe extern "C" fn on_speed_object(session: *mut c_void) -> *mut c_void {
202///     let Some(next) = SPEED_OBJECT.next() else { return std::ptr::null_mut() };
203///     // SAFETY: the game's own function, called as it declares.
204///     unsafe { next(session) }
205/// }
206/// ```
207///
208/// A detour is called by the game directly, with no adapter between: it must
209/// not panic (a panic out of an `extern "C"` function aborts the process).
210/// Wrap fallible work in [`catch_panic`](crate::catch_panic).
211pub struct FunctionHook<F: FnPtr> {
212    next: AtomicPtr<c_void>,
213    change: AtomicPtr<AnvilChange>,
214    _function: PhantomData<F>,
215}
216
217impl<F: FnPtr> FunctionHook<F> {
218    /// An unused hook.
219    pub const fn new() -> Self {
220        Self {
221            next: AtomicPtr::new(ptr::null_mut()),
222            change: AtomicPtr::new(ptr::null_mut()),
223            _function: PhantomData,
224        }
225    }
226
227    /// The rest of the chain: the next plugin's detour or the game's code;
228    /// `None` before Anvil wrote it. It stays valid after the change is
229    /// removed, for a thread still inside the detour.
230    pub fn next(&self) -> Option<F> {
231        let raw = self.next.load(Ordering::Acquire);
232        // SAFETY: Anvil wrote a function of the declared type (or nothing).
233        (!raw.is_null()).then(|| unsafe { F::from_raw(raw) })
234    }
235
236    /// Whether the hook holds a change (or another thread is installing one).
237    pub fn is_active(&self) -> bool {
238        !self.change.load(Ordering::Acquire).is_null()
239    }
240
241    /// Removes the change; nothing when there is none. The hook can then take
242    /// a new change; until it does, `next` keeps the removed change's chain
243    /// for a thread still inside the detour.
244    pub fn remove(&self) -> Result<()> {
245        remove_slot(&self.change, "the hook object")
246    }
247
248    pub(crate) fn claim(&'static self, call: &'static str) -> Result<Claim> {
249        Claim::take(&self.change, &format!("{call}: the hook object"))
250    }
251
252    /// Where Anvil writes `next` during a request (it writes it before it
253    /// enables the change, and a failed request writes NULL): the hook's own
254    /// cell while it is empty, so a detour the game enters as soon as the
255    /// change is enabled finds `next`; on a reused hook `local`, so a failed
256    /// request leaves the removed change's chain for a thread still inside
257    /// its detour.
258    pub(crate) fn next_cell(&self, local: &mut *mut c_void) -> *mut *mut c_void {
259        if self.next.load(Ordering::Acquire).is_null() {
260            self.next.as_ptr()
261        } else {
262            local
263        }
264    }
265
266    /// A request that succeeded: Anvil wrote `next` into `cell` during the
267    /// call (and never changes it afterwards); a local is copied in only now.
268    pub(crate) fn finish(
269        &self,
270        claim: Claim,
271        cell: *mut *mut c_void,
272        local: *mut c_void,
273        change: *mut AnvilChange,
274    ) {
275        if cell != self.next.as_ptr() {
276            self.next.store(local, Ordering::Release);
277        }
278        claim.finish(change);
279    }
280}
281
282impl<F: FnPtr> Default for FunctionHook<F> {
283    fn default() -> Self {
284        Self::new()
285    }
286}
287
288impl<F: FnPtr> fmt::Debug for FunctionHook<F> {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        f.debug_struct("FunctionHook")
291            .field("next", &self.next.load(Ordering::Relaxed))
292            .field("active", &self.is_active())
293            .finish()
294    }
295}
296
297/// A pointer swap on a slot symbol, and the rest of its chain. Anvil rewrites
298/// [`previous`](PointerSwap::previous) whenever the chain changes, so it lives
299/// in a `static`.
300pub struct PointerSwap {
301    previous: AtomicPtr<c_void>,
302    change: AtomicPtr<AnvilChange>,
303}
304
305impl PointerSwap {
306    /// An unused swap.
307    pub const fn new() -> Self {
308        Self {
309            previous: AtomicPtr::new(ptr::null_mut()),
310            change: AtomicPtr::new(ptr::null_mut()),
311        }
312    }
313
314    /// The rest of the chain, read on each use: another plugin's value or the
315    /// slot's original pointer.
316    pub fn previous(&self) -> *mut c_void {
317        self.previous.load(Ordering::Acquire)
318    }
319
320    /// Whether the swap holds a change.
321    pub fn is_active(&self) -> bool {
322        !self.change.load(Ordering::Acquire).is_null()
323    }
324
325    /// Removes the change; nothing when there is none.
326    pub fn remove(&self) -> Result<()> {
327        remove_slot(&self.change, "the swap object")
328    }
329
330    pub(crate) fn claim(&'static self) -> Result<Claim> {
331        Claim::take(&self.change, "swap_pointer: the swap object")
332    }
333
334    pub(crate) fn previous_slot(&self) -> *mut *mut c_void {
335        self.previous.as_ptr()
336    }
337}
338
339impl Default for PointerSwap {
340    fn default() -> Self {
341        Self::new()
342    }
343}
344
345impl fmt::Debug for PointerSwap {
346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347        f.debug_struct("PointerSwap")
348            .field("previous", &self.previous())
349            .field("active", &self.is_active())
350            .finish()
351    }
352}