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#[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
108thread_local! {
109 static GROUP_SLOTS: RefCell<Option<Vec<FilledSlot>>> = const { RefCell::new(None) };
115}
116
117pub(crate) fn group_opened() {
119 GROUP_SLOTS.with(|slots| *slots.borrow_mut() = Some(Vec::new()));
120}
121
122pub(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
142fn claiming() -> *mut AnvilChange {
144 NonNull::<AnvilChange>::dangling().as_ptr()
145}
146
147pub(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 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
193pub 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 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 pub fn next(&self) -> Option<F> {
231 let raw = self.next.load(Ordering::Acquire);
232 (!raw.is_null()).then(|| unsafe { F::from_raw(raw) })
234 }
235
236 pub fn is_active(&self) -> bool {
238 !self.change.load(Ordering::Acquire).is_null()
239 }
240
241 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 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 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
297pub struct PointerSwap {
301 previous: AtomicPtr<c_void>,
302 change: AtomicPtr<AnvilChange>,
303}
304
305impl PointerSwap {
306 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 pub fn previous(&self) -> *mut c_void {
317 self.previous.load(Ordering::Acquire)
318 }
319
320 pub fn is_active(&self) -> bool {
322 !self.change.load(Ordering::Acquire).is_null()
323 }
324
325 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}