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#[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
24unsafe impl Send for Change {}
26unsafe 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 pub fn as_raw(&self) -> *mut AnvilChange {
38 self.handle.map_or(ptr::null_mut(), NonNull::as_ptr)
39 }
40
41 pub fn remove(mut self) -> Result<()> {
44 remove_handle(self.handle.take())
45 }
46
47 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 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
80fn 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
105type FilledSlot = (&'static AtomicPtr<AnvilChange>, usize);
107
108static OPEN_GROUPS: Mutex<Vec<(usize, Vec<FilledSlot>)>> = Mutex::new(Vec::new());
117
118static GROUP_GATE: RwLock<()> = RwLock::new(());
122
123pub(crate) fn request_gate() -> RwLockReadGuard<'static, ()> {
125 GROUP_GATE.read().unwrap_or_else(|e| e.into_inner())
126}
127
128pub(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
137pub(crate) fn group_opened(owner: *mut AnvilPlugin) {
139 open_groups().push((owner as usize, Vec::new()));
140}
141
142pub(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
166fn claiming() -> *mut AnvilChange {
168 NonNull::<AnvilChange>::dangling().as_ptr()
169}
170
171pub(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 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
217pub 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 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 pub fn next(&self) -> Option<F> {
256 let raw = self.next.load(Ordering::Acquire);
257 (!raw.is_null()).then(|| unsafe { F::from_raw(raw) })
259 }
260
261 pub fn is_active(&self) -> bool {
263 !self.change.load(Ordering::Acquire).is_null()
264 }
265
266 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 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 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
324pub struct PointerSwap {
328 previous: AtomicPtr<c_void>,
329 change: AtomicPtr<AnvilChange>,
330}
331
332impl PointerSwap {
333 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 pub fn previous(&self) -> *mut c_void {
344 self.previous.load(Ordering::Acquire)
345 }
346
347 pub fn is_active(&self) -> bool {
349 !self.change.load(Ordering::Acquire).is_null()
350 }
351
352 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}