Skip to main content

anvil/
change.rs

1use std::ffi::c_void;
2use std::fmt;
3use std::marker::PhantomData;
4use std::ptr::{self, NonNull};
5use std::sync::atomic::{AtomicPtr, Ordering};
6use std::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
7
8use crate::error::{check, Error, ErrorCode, Result};
9use crate::fnptr::FnPtr;
10use crate::host::Host;
11use crate::sys::{AnvilChange, AnvilPlugin};
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
108/// The open [`Host::group`](crate::Host::group)s of the plugin and its
109/// modules, by owner handle (as an address), each with the hook and swap
110/// slots filled in it and the handles they got (anvil#533). A group is its
111/// owner's: a request of that owner from any thread joins it, and each module
112/// is an owner of its own. A group that aborts or whose commit Anvil refuses
113/// removes those changes, so the slots are emptied again (else `is_active`
114/// stays true and the next request on the hook answers "already holds a
115/// change").
116static OPEN_GROUPS: Mutex<Vec<(usize, Vec<FilledSlot>)>> = Mutex::new(Vec::new());
117
118/// Held shared by a request from its host call until its slot is recorded,
119/// and exclusively by `Host::group` around `begin_group` and around the
120/// commit or abort, so a request is recorded exactly when Anvil staged it.
121static GROUP_GATE: RwLock<()> = RwLock::new(());
122
123/// The shared hold of a request.
124pub(crate) fn request_gate() -> RwLockReadGuard<'static, ()> {
125    GROUP_GATE.read().unwrap_or_else(|e| e.into_inner())
126}
127
128/// The exclusive hold of a group's start and end.
129pub(crate) fn group_gate() -> RwLockWriteGuard<'static, ()> {
130    GROUP_GATE.write().unwrap_or_else(|e| e.into_inner())
131}
132
133fn open_groups() -> std::sync::MutexGuard<'static, Vec<(usize, Vec<FilledSlot>)>> {
134    OPEN_GROUPS.lock().unwrap_or_else(|e| e.into_inner())
135}
136
137/// `owner` opened a group: slots its requests fill from now on are recorded.
138pub(crate) fn group_opened(owner: *mut AnvilPlugin) {
139    open_groups().push((owner as usize, Vec::new()));
140}
141
142/// `owner`'s group ended. When Anvil removed its changes (`discarded`), each
143/// slot still holding the handle it got in the group is emptied; a slot that
144/// has moved on (removed, or filled again) is left as it is.
145pub(crate) fn group_closed(owner: *mut AnvilPlugin, discarded: bool) {
146    let filled = {
147        let mut groups = open_groups();
148        let Some(at) = groups.iter().position(|(o, _)| *o == owner as usize) else {
149            return;
150        };
151        groups.swap_remove(at).1
152    };
153    if !discarded {
154        return;
155    }
156    for (slot, handle) in filled {
157        let _ = slot.compare_exchange(
158            handle as *mut AnvilChange,
159            ptr::null_mut(),
160            Ordering::AcqRel,
161            Ordering::Acquire,
162        );
163    }
164}
165
166/// What a hook's or swap's `change` holds while a request on it runs.
167fn claiming() -> *mut AnvilChange {
168    NonNull::<AnvilChange>::dangling().as_ptr()
169}
170
171/// The `change` slot of a hook or swap, taken for one request with a
172/// compare-exchange: two threads requesting a change on one static cannot both
173/// get through (the later handle would overwrite the earlier one, which could
174/// then never be removed). Dropped without [`finish`](Claim::finish) (the
175/// request failed), the slot is empty again.
176pub(crate) struct Claim {
177    slot: &'static AtomicPtr<AnvilChange>,
178}
179
180impl Claim {
181    fn take(slot: &'static AtomicPtr<AnvilChange>, what: &str) -> Result<Self> {
182        slot.compare_exchange(
183            ptr::null_mut(),
184            claiming(),
185            Ordering::AcqRel,
186            Ordering::Acquire,
187        )
188        .map(|_| Self { slot })
189        .map_err(|_| {
190            Error::new(
191                ErrorCode::InvalidArgument,
192                format!("{what} already holds a change; remove() it first"),
193            )
194        })
195    }
196
197    /// The request of `owner` succeeded: the slot holds its handle. Called
198    /// under the request's [`request_gate`].
199    pub(crate) fn finish(self, change: *mut AnvilChange, owner: *mut AnvilPlugin) {
200        self.slot.store(change, Ordering::Release);
201        if !change.is_null() {
202            let mut groups = open_groups();
203            if let Some((_, filled)) = groups.iter_mut().find(|(o, _)| *o == owner as usize) {
204                filled.push((self.slot, change as usize));
205            }
206        }
207        std::mem::forget(self);
208    }
209}
210
211impl Drop for Claim {
212    fn drop(&mut self) {
213        self.slot.store(ptr::null_mut(), Ordering::Release);
214    }
215}
216
217/// A function hook, call redirect or import replacement, and the rest of its
218/// chain. It lives in a `static`, so the detour (a plain function the game
219/// calls) reaches `next`, and Anvil can write `next` into it before the change
220/// is enabled (on a hook reused after [`remove`](FunctionHook::remove), only
221/// on an Anvil newer than 1.25.0):
222///
223/// ```ignore
224/// static SPEED_OBJECT: anvil::FunctionHook<sym::SpeedObjectFn> = anvil::FunctionHook::new();
225///
226/// unsafe extern "C" fn on_speed_object(session: *mut c_void) -> *mut c_void {
227///     let Some(next) = SPEED_OBJECT.next() else { return std::ptr::null_mut() };
228///     // SAFETY: the game's own function, called as it declares.
229///     unsafe { next(session) }
230/// }
231/// ```
232///
233/// A detour is called by the game directly, with no adapter between: it must
234/// not panic (a panic out of an `extern "C"` function aborts the process).
235/// Wrap fallible work in [`catch_panic`](crate::catch_panic).
236pub struct FunctionHook<F: FnPtr> {
237    next: AtomicPtr<c_void>,
238    change: AtomicPtr<AnvilChange>,
239    _function: PhantomData<F>,
240}
241
242impl<F: FnPtr> FunctionHook<F> {
243    /// An unused hook.
244    pub const fn new() -> Self {
245        Self {
246            next: AtomicPtr::new(ptr::null_mut()),
247            change: AtomicPtr::new(ptr::null_mut()),
248            _function: PhantomData,
249        }
250    }
251
252    /// The rest of the chain: the next plugin's detour or the game's code;
253    /// `None` before Anvil wrote it. It stays valid after the change is
254    /// removed, for a thread still inside the detour.
255    pub fn next(&self) -> Option<F> {
256        let raw = self.next.load(Ordering::Acquire);
257        // SAFETY: Anvil wrote a function of the declared type (or nothing).
258        (!raw.is_null()).then(|| unsafe { F::from_raw(raw) })
259    }
260
261    /// Whether the hook holds a change (or another thread is installing one).
262    pub fn is_active(&self) -> bool {
263        !self.change.load(Ordering::Acquire).is_null()
264    }
265
266    /// Removes the change; nothing when there is none. The hook can then take
267    /// a new change; until it does, `next` keeps the removed change's chain
268    /// for a thread still inside the detour.
269    pub fn remove(&self) -> Result<()> {
270        remove_slot(&self.change, "the hook object")
271    }
272
273    pub(crate) fn claim(&'static self, call: &'static str) -> Result<Claim> {
274        Claim::take(&self.change, &format!("{call}: the hook object"))
275    }
276
277    /// Where Anvil writes `next` during a request (it writes it before it
278    /// enables the change): the hook's own cell, so a detour the game enters
279    /// as soon as the change is enabled finds `next`. On a reused hook that
280    /// holds to an Anvil that restores the cell when a request fails
281    /// (`restores`); an older one writes NULL there, so the reused hook gets
282    /// `local` and a failed request leaves the removed change's chain for a
283    /// thread still inside its detour.
284    pub(crate) fn next_cell(&self, local: &mut *mut c_void, restores: bool) -> *mut *mut c_void {
285        if restores || self.next.load(Ordering::Acquire).is_null() {
286            self.next.as_ptr()
287        } else {
288            local
289        }
290    }
291
292    /// A request that succeeded: Anvil wrote `next` into `cell` during the
293    /// call (and never changes it afterwards); a local is copied in only now.
294    pub(crate) fn finish(
295        &self,
296        claim: Claim,
297        cell: *mut *mut c_void,
298        local: *mut c_void,
299        change: *mut AnvilChange,
300        owner: *mut AnvilPlugin,
301    ) {
302        if cell != self.next.as_ptr() {
303            self.next.store(local, Ordering::Release);
304        }
305        claim.finish(change, owner);
306    }
307}
308
309impl<F: FnPtr> Default for FunctionHook<F> {
310    fn default() -> Self {
311        Self::new()
312    }
313}
314
315impl<F: FnPtr> fmt::Debug for FunctionHook<F> {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        f.debug_struct("FunctionHook")
318            .field("next", &self.next.load(Ordering::Relaxed))
319            .field("active", &self.is_active())
320            .finish()
321    }
322}
323
324/// A pointer swap on a slot symbol, and the rest of its chain. Anvil rewrites
325/// [`previous`](PointerSwap::previous) whenever the chain changes, so it lives
326/// in a `static`.
327pub struct PointerSwap {
328    previous: AtomicPtr<c_void>,
329    change: AtomicPtr<AnvilChange>,
330}
331
332impl PointerSwap {
333    /// An unused swap.
334    pub const fn new() -> Self {
335        Self {
336            previous: AtomicPtr::new(ptr::null_mut()),
337            change: AtomicPtr::new(ptr::null_mut()),
338        }
339    }
340
341    /// The rest of the chain, read on each use: another plugin's value or the
342    /// slot's original pointer.
343    pub fn previous(&self) -> *mut c_void {
344        self.previous.load(Ordering::Acquire)
345    }
346
347    /// Whether the swap holds a change.
348    pub fn is_active(&self) -> bool {
349        !self.change.load(Ordering::Acquire).is_null()
350    }
351
352    /// Removes the change; nothing when there is none.
353    pub fn remove(&self) -> Result<()> {
354        remove_slot(&self.change, "the swap object")
355    }
356
357    pub(crate) fn claim(&'static self) -> Result<Claim> {
358        Claim::take(&self.change, "swap_pointer: the swap object")
359    }
360
361    pub(crate) fn previous_slot(&self) -> *mut *mut c_void {
362        self.previous.as_ptr()
363    }
364}
365
366impl Default for PointerSwap {
367    fn default() -> Self {
368        Self::new()
369    }
370}
371
372impl fmt::Debug for PointerSwap {
373    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374        f.debug_struct("PointerSwap")
375            .field("previous", &self.previous())
376            .field("active", &self.is_active())
377            .finish()
378    }
379}