use std::ffi::c_void;
use std::fmt;
use std::marker::PhantomData;
use std::ptr::{self, NonNull};
use std::sync::atomic::{AtomicPtr, Ordering};
use std::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
use crate::error::{check, Error, ErrorCode, Result};
use crate::fnptr::FnPtr;
use crate::host::Host;
use crate::sys::{AnvilChange, AnvilPlugin};
#[must_use = "dropping a Change removes the change; keep it in the plugin, or call keep()"]
pub struct Change {
handle: Option<NonNull<AnvilChange>>,
}
unsafe impl Send for Change {}
unsafe impl Sync for Change {}
impl Change {
pub(crate) fn from_raw(handle: *mut AnvilChange) -> Self {
Self {
handle: NonNull::new(handle),
}
}
pub fn as_raw(&self) -> *mut AnvilChange {
self.handle.map_or(ptr::null_mut(), NonNull::as_ptr)
}
pub fn remove(mut self) -> Result<()> {
remove_handle(self.handle.take())
}
pub fn keep(mut self) {
self.handle = None;
}
}
impl Drop for Change {
fn drop(&mut self) {
let _ = remove_handle(self.handle.take());
}
}
impl fmt::Debug for Change {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Change").field(&self.as_raw()).finish()
}
}
fn remove_handle(handle: Option<NonNull<AnvilChange>>) -> Result<()> {
let (Some(handle), Some(host)) = (handle, Host::current()) else {
return Ok(());
};
let Some(remove) = field!(host.c_api(), crate::sys::AnvilHost, remove).flatten() else {
return Ok(());
};
let result = unsafe { remove(host.raw_plugin(), handle.as_ptr()) };
match check(result, || "remove") {
Err(error) if error.code() == ErrorCode::NotFound => Ok(()),
other => other,
}
}
fn remove_slot(slot: &AtomicPtr<AnvilChange>, what: &str) -> Result<()> {
loop {
let current = slot.load(Ordering::Acquire);
if current == claiming() {
return Err(Error::new(
ErrorCode::InvalidArgument,
format!("{what}: another thread is installing a change on it; remove() after that returns"),
));
}
if slot
.compare_exchange_weak(
current,
ptr::null_mut(),
Ordering::AcqRel,
Ordering::Acquire,
)
.is_ok()
{
return remove_handle(NonNull::new(current));
}
}
}
type FilledSlot = (&'static AtomicPtr<AnvilChange>, usize);
static OPEN_GROUPS: Mutex<Vec<(usize, Vec<FilledSlot>)>> = Mutex::new(Vec::new());
static GROUP_GATE: RwLock<()> = RwLock::new(());
pub(crate) fn request_gate() -> RwLockReadGuard<'static, ()> {
GROUP_GATE.read().unwrap_or_else(|e| e.into_inner())
}
pub(crate) fn group_gate() -> RwLockWriteGuard<'static, ()> {
GROUP_GATE.write().unwrap_or_else(|e| e.into_inner())
}
fn open_groups() -> std::sync::MutexGuard<'static, Vec<(usize, Vec<FilledSlot>)>> {
OPEN_GROUPS.lock().unwrap_or_else(|e| e.into_inner())
}
pub(crate) fn group_opened(owner: *mut AnvilPlugin) {
open_groups().push((owner as usize, Vec::new()));
}
pub(crate) fn group_closed(owner: *mut AnvilPlugin, discarded: bool) {
let filled = {
let mut groups = open_groups();
let Some(at) = groups.iter().position(|(o, _)| *o == owner as usize) else {
return;
};
groups.swap_remove(at).1
};
if !discarded {
return;
}
for (slot, handle) in filled {
let _ = slot.compare_exchange(
handle as *mut AnvilChange,
ptr::null_mut(),
Ordering::AcqRel,
Ordering::Acquire,
);
}
}
fn claiming() -> *mut AnvilChange {
NonNull::<AnvilChange>::dangling().as_ptr()
}
pub(crate) struct Claim {
slot: &'static AtomicPtr<AnvilChange>,
}
impl Claim {
fn take(slot: &'static AtomicPtr<AnvilChange>, what: &str) -> Result<Self> {
slot.compare_exchange(
ptr::null_mut(),
claiming(),
Ordering::AcqRel,
Ordering::Acquire,
)
.map(|_| Self { slot })
.map_err(|_| {
Error::new(
ErrorCode::InvalidArgument,
format!("{what} already holds a change; remove() it first"),
)
})
}
pub(crate) fn finish(self, change: *mut AnvilChange, owner: *mut AnvilPlugin) {
self.slot.store(change, Ordering::Release);
if !change.is_null() {
let mut groups = open_groups();
if let Some((_, filled)) = groups.iter_mut().find(|(o, _)| *o == owner as usize) {
filled.push((self.slot, change as usize));
}
}
std::mem::forget(self);
}
}
impl Drop for Claim {
fn drop(&mut self) {
self.slot.store(ptr::null_mut(), Ordering::Release);
}
}
pub struct FunctionHook<F: FnPtr> {
next: AtomicPtr<c_void>,
change: AtomicPtr<AnvilChange>,
_function: PhantomData<F>,
}
impl<F: FnPtr> FunctionHook<F> {
pub const fn new() -> Self {
Self {
next: AtomicPtr::new(ptr::null_mut()),
change: AtomicPtr::new(ptr::null_mut()),
_function: PhantomData,
}
}
pub fn next(&self) -> Option<F> {
let raw = self.next.load(Ordering::Acquire);
(!raw.is_null()).then(|| unsafe { F::from_raw(raw) })
}
pub fn is_active(&self) -> bool {
!self.change.load(Ordering::Acquire).is_null()
}
pub fn remove(&self) -> Result<()> {
remove_slot(&self.change, "the hook object")
}
pub(crate) fn claim(&'static self, call: &'static str) -> Result<Claim> {
Claim::take(&self.change, &format!("{call}: the hook object"))
}
pub(crate) fn next_cell(&self, local: &mut *mut c_void, restores: bool) -> *mut *mut c_void {
if restores || self.next.load(Ordering::Acquire).is_null() {
self.next.as_ptr()
} else {
local
}
}
pub(crate) fn finish(
&self,
claim: Claim,
cell: *mut *mut c_void,
local: *mut c_void,
change: *mut AnvilChange,
owner: *mut AnvilPlugin,
) {
if cell != self.next.as_ptr() {
self.next.store(local, Ordering::Release);
}
claim.finish(change, owner);
}
}
impl<F: FnPtr> Default for FunctionHook<F> {
fn default() -> Self {
Self::new()
}
}
impl<F: FnPtr> fmt::Debug for FunctionHook<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FunctionHook")
.field("next", &self.next.load(Ordering::Relaxed))
.field("active", &self.is_active())
.finish()
}
}
pub struct PointerSwap {
previous: AtomicPtr<c_void>,
change: AtomicPtr<AnvilChange>,
}
impl PointerSwap {
pub const fn new() -> Self {
Self {
previous: AtomicPtr::new(ptr::null_mut()),
change: AtomicPtr::new(ptr::null_mut()),
}
}
pub fn previous(&self) -> *mut c_void {
self.previous.load(Ordering::Acquire)
}
pub fn is_active(&self) -> bool {
!self.change.load(Ordering::Acquire).is_null()
}
pub fn remove(&self) -> Result<()> {
remove_slot(&self.change, "the swap object")
}
pub(crate) fn claim(&'static self) -> Result<Claim> {
Claim::take(&self.change, "swap_pointer: the swap object")
}
pub(crate) fn previous_slot(&self) -> *mut *mut c_void {
self.previous.as_ptr()
}
}
impl Default for PointerSwap {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for PointerSwap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PointerSwap")
.field("previous", &self.previous())
.field("active", &self.is_active())
.finish()
}
}