use core::fmt;
use core::cell::{Cell, UnsafeCell};
use core::marker::PhantomData;
#[cfg(crossheap)]
use core::num::{NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8};
use core::ops::Deref;
use core::ptr::{NonNull, null_mut};
use core::sync::atomic::{AtomicPtr, AtomicU64, AtomicUsize, Ordering};
#[cfg(crossheap)]
use core::sync::atomic::{AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicU16, AtomicU32, AtomicU8};
use std::sync::Arc;
use crate::{Heap, Mutator, Trace, Tracer};
use crate::heap::{HeapInternal, MutatorInternal};
#[cfg(crossheap)]
use crate::heap::{Inner, CrossHeap, CrossHeapInternal, CrossHeapMutator, CrossHeapMutatorInternal};
use crate::layout::Header;
#[cfg(crossheap)]
use crate::layout::{GRANULE, PHeader};
use crate::mark::TracerInternal;
#[cfg(crossheap)]
use crate::shm::{REGION, Region};
use crate::sync::{PushList, SegVec};
pub type Invariant<'gc> = PhantomData<Cell<&'gc ()>>;
type GcBrand<'gc, T> = PhantomData<(&'gc T, fn(&'gc ()) -> &'gc ())>;
#[repr(transparent)]
pub struct Gc<'gc, T> {
ptr: NonNull<T>,
_brand: GcBrand<'gc, T>,
}
unsafe impl<T: Send + Sync> Send for Gc<'_, T> {}
unsafe impl<T: Send + Sync> Sync for Gc<'_, T> {}
impl<T> Clone for Gc<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Gc<'_, T> {}
pub trait GcInternal {
type Data;
unsafe fn from_data(ptr: *mut Self::Data) -> Self;
fn header(self) -> *const Header;
}
impl<T> GcInternal for Gc<'_, T> {
type Data = T;
unsafe fn from_data(ptr: *mut T) -> Self {
Self { ptr: unsafe { NonNull::new_unchecked(ptr) }, _brand: PhantomData }
}
fn header(self) -> *const Header {
Header::of(self.ptr.as_ptr().cast())
}
}
impl<'gc, T> Gc<'gc, T> {
pub fn as_ptr(self) -> *const T {
self.ptr.as_ptr()
}
pub unsafe fn from_raw(ptr: *const T) -> Self {
unsafe { Self::from_data(ptr.cast_mut()) }
}
pub fn get(self) -> &'gc T {
unsafe { self.ptr.as_ref() }
}
pub fn ptr_eq(a: Self, b: Self) -> bool {
a.ptr == b.ptr
}
}
impl<T> Deref for Gc<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
}
impl<T: fmt::Debug> fmt::Debug for Gc<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[repr(C)]
pub struct Slot<'gc, T> {
word: AtomicU64,
counted: AtomicUsize,
_brand: PhantomData<Gc<'gc, T>>,
}
pub const UNCOUNTED: usize = usize::MAX;
pub const PROMOTED: usize = usize::MAX - 1;
pub const LOGGED: usize = 1;
pub const WORD_POINTER_MIN: u64 = 0xFFF8 << 48;
pub const WORD_PAYLOAD: u64 = (1 << 48) - 1;
pub const RAW_TAG: u64 = 0xFFFF << 48;
#[inline]
pub fn word_pointer(word: u64) -> Option<*mut u8> {
(word >= WORD_POINTER_MIN).then(|| core::ptr::with_exposed_provenance_mut((word & WORD_PAYLOAD) as usize))
}
#[inline]
fn word_with_pointer(word: u64, data: *const u8) -> u64 {
debug_assert!(word >= WORD_POINTER_MIN, "only pointer words are rewritten");
(word & !WORD_PAYLOAD) | data.expose_provenance() as u64
}
#[repr(C)]
pub struct RawSlot {
pub word: AtomicU64,
pub counted: AtomicUsize,
}
impl RawSlot {
fn header(word: u64) -> Option<*const Header> {
Self::private(word_pointer(word)).map(|p| Header::of(p))
}
#[cfg(crossheap)]
fn private(p: Option<*mut u8>) -> Option<*mut u8> {
p.filter(|p| !Region::holds_fixed(p.addr()))
}
#[cfg(not(crossheap))]
fn private(p: Option<*mut u8>) -> Option<*mut u8> {
p
}
#[cfg(crossheap)]
pub fn cross(&self) -> Option<*mut u8> {
word_pointer(self.word.load(Ordering::Acquire)).filter(|p| Region::holds_fixed(p.addr()))
}
pub fn relocate(&self, to: *const Header) {
let w = self.word.load(Ordering::Acquire);
self.word.store(word_with_pointer(w, Header::data(to)), Ordering::Release);
}
fn uncounted(c: usize) -> bool {
c >= PROMOTED
}
fn from_counted(c: usize) -> Option<*const Header> {
(!Self::uncounted(c) && c & !LOGGED != 0).then(|| Header::of(core::ptr::with_exposed_provenance::<u8>(c & !LOGGED)))
}
pub fn log(&self) -> bool {
let c = self.counted.load(Ordering::Relaxed);
!Self::uncounted(c) && c & LOGGED == 0 && self.counted.compare_exchange(c, c | LOGGED, Ordering::AcqRel, Ordering::Relaxed).is_ok()
}
pub fn is_young(&self) -> bool {
self.counted.load(Ordering::Relaxed) == UNCOUNTED
}
pub fn promote(&self) {
let _ = self.counted.compare_exchange(UNCOUNTED, PROMOTED, Ordering::Relaxed, Ordering::Relaxed);
}
pub fn unlog(&self) {
self.counted.fetch_and(!LOGGED, Ordering::AcqRel);
}
pub fn recount(&self) -> (Option<*const Header>, Option<*const Header>) {
let p = Self::private(word_pointer(self.word.load(Ordering::Acquire)));
let prev = self.counted.swap(p.map_or(0, <*mut u8>::expose_provenance), Ordering::AcqRel);
(p.map(|p| Header::of(p.cast_const())), Self::from_counted(prev))
}
pub fn current(&self) -> Option<*const Header> {
Self::header(self.word.load(Ordering::Acquire))
}
pub fn counted(&self) -> Option<*const Header> {
Self::from_counted(self.counted.load(Ordering::Acquire))
}
}
impl<T> Default for Slot<'_, T> {
fn default() -> Self {
Self { word: AtomicU64::new(0), counted: AtomicUsize::new(UNCOUNTED), _brand: PhantomData }
}
}
impl<'gc, T> From<Option<Gc<'gc, T>>> for Slot<'gc, T> {
fn from(v: Option<Gc<'gc, T>>) -> Self {
Self { word: AtomicU64::new(Self::raw(v)), counted: AtomicUsize::new(UNCOUNTED), _brand: PhantomData }
}
}
impl<'gc, T> From<Gc<'gc, T>> for Slot<'gc, T> {
fn from(v: Gc<'gc, T>) -> Self {
Some(v).into()
}
}
impl<'gc, T> Slot<'gc, T> {
fn raw(v: Option<Gc<'gc, T>>) -> u64 {
v.map_or(0, |g| RAW_TAG | g.ptr.as_ptr().expose_provenance() as u64)
}
fn wrap(word: u64) -> Option<Gc<'gc, T>> {
word_pointer(word).map(|p| unsafe { Gc::from_data(p.cast()) })
}
pub fn get(&self) -> Option<Gc<'gc, T>> {
Self::wrap(self.word.load(Ordering::Acquire))
}
pub fn set(&self, m: &Mutator<'gc>, v: Option<Gc<'gc, T>>) {
self.swap(m, v);
}
pub fn swap(&self, m: &Mutator<'gc>, v: Option<Gc<'gc, T>>) -> Option<Gc<'gc, T>> {
let new = Self::raw(v);
let old = self.word.swap(new, Ordering::AcqRel);
m.written(self.raw_slot(), RawSlot::header(old), RawSlot::header(new));
Self::wrap(old)
}
pub fn compare_exchange(&self, m: &Mutator<'gc>, current: Option<Gc<'gc, T>>, new: Option<Gc<'gc, T>>) -> Result<Option<Gc<'gc, T>>, Option<Gc<'gc, T>>> {
let new = Self::raw(new);
let done = self.word.compare_exchange(Self::raw(current), new, Ordering::AcqRel, Ordering::Acquire);
if let Ok(old) = done {
m.written(self.raw_slot(), RawSlot::header(old), RawSlot::header(new));
}
done.map(Self::wrap).map_err(Self::wrap)
}
}
#[repr(C)]
pub struct WordSlot<'gc> {
word: AtomicU64,
counted: AtomicUsize,
_brand: PhantomData<Gc<'gc, ()>>,
}
impl WordSlot<'_> {
pub fn new(word: u64) -> Self {
Self { word: AtomicU64::new(word), counted: AtomicUsize::new(UNCOUNTED), _brand: PhantomData }
}
#[inline]
pub fn get(&self) -> u64 {
self.word.load(Ordering::Acquire)
}
#[inline]
pub fn set(&self, m: &Mutator<'_>, word: u64) {
let old = self.word.load(Ordering::Relaxed);
self.word.store(word, Ordering::Release);
let (o, n) = (RawSlot::header(old), RawSlot::header(word));
if o != n {
m.written(self.raw_slot(), o, n);
}
}
pub fn set_mut(&mut self, word: u64) {
*self.word.get_mut() = word;
}
fn raw_slot(&self) -> &RawSlot {
unsafe { &*(&raw const *self).cast::<RawSlot>() }
}
}
impl fmt::Debug for WordSlot<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "WordSlot({:#x})", self.get())
}
}
pub trait WordSlotInternal {
fn raw(&self) -> &RawSlot;
}
impl WordSlotInternal for WordSlot<'_> {
fn raw(&self) -> &RawSlot {
self.raw_slot()
}
}
pub trait SlotInternal<'gc> {
type Data;
fn raw_slot(&self) -> &RawSlot;
}
impl<'gc, T> SlotInternal<'gc> for Slot<'gc, T> {
type Data = T;
fn raw_slot(&self) -> &RawSlot {
unsafe { &*(&raw const *self).cast::<RawSlot>() }
}
}
impl<T: fmt::Debug> fmt::Debug for Slot<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Slot").field(&self.get()).finish()
}
}
pub trait Brand {
type Of<'gc>: Trace + 'gc;
}
#[macro_export]
macro_rules! brand {
($(#[$meta:meta])* $vis:vis $name:ident = for<$l:lifetime> $ty:ty) => {
$(#[$meta])*
$vis struct $name;
impl $crate::Brand for $name {
type Of<$l> = $ty;
}
};
}
#[derive(Default)]
pub struct Entry {
ptr: AtomicPtr<Header>,
holder: AtomicUsize,
}
pub const NO_HOLDER: usize = 0;
impl Entry {
pub fn load(&self) -> *mut Header {
self.ptr.load(Ordering::Acquire)
}
pub fn store(&self, header: *mut Header) {
self.ptr.store(header, Ordering::Release);
}
}
#[derive(Default)]
pub struct RootTable {
slots: SegVec<Entry>,
returned: PushList<usize>,
ready: UnsafeCell<Vec<usize>>,
cursor: AtomicUsize,
}
unsafe impl Sync for RootTable {}
unsafe impl Send for RootTable {}
impl RootTable {
#[cfg(crossheap)]
fn crossed(p: *const Header) -> bool {
Region::holds_fixed(p.addr())
}
#[cfg(not(crossheap))]
fn crossed(_: *const Header) -> bool {
false
}
#[cfg(crossheap)]
pub unsafe fn crossing(&self, mut f: impl FnMut(*mut u8)) {
for slot in self.slots.iter() {
let p = slot.load();
if !p.is_null() && Self::crossed(p) {
f(Header::data(p));
}
}
}
#[cfg(crossheap)]
pub unsafe fn clear_crossed(&self, alive: impl Fn(*mut u8) -> bool) {
for slot in self.slots.iter() {
let p = slot.load();
if !p.is_null() && Self::crossed(p) && !alive(Header::data(p)) {
let _ = slot.ptr.compare_exchange(p, null_mut(), Ordering::AcqRel, Ordering::Relaxed);
}
}
}
pub fn claim(&self, header: *const Header, holder: usize) -> usize {
let ready = unsafe { &*self.ready.get() };
let i = self.cursor.fetch_add(1, Ordering::AcqRel);
match ready.get(i).and_then(|&slot| self.slots.get(slot).map(|s| (slot, s))) {
Some((slot, s)) => {
s.holder.store(holder, Ordering::Relaxed);
s.store(header.cast_mut());
slot
}
None => self.slots.push(Entry { ptr: AtomicPtr::new(header.cast_mut()), holder: AtomicUsize::new(holder) }),
}
}
pub fn slot(&self, i: usize) -> &Entry {
self.slots.get(i).expect("root slot indexes come from claim")
}
pub fn release(&self, i: usize) {
self.slot(i).store(null_mut());
self.returned.push(i);
}
pub fn relocate(&self, mut f: impl FnMut(*const Header) -> *const Header) {
for slot in self.slots.iter() {
let old = slot.load();
if old.is_null() || Self::crossed(old) {
continue;
}
let new = f(old.cast_const());
if !core::ptr::eq(old, new) {
let _ = slot.ptr.compare_exchange(old, new.cast_mut(), Ordering::AcqRel, Ordering::Acquire);
}
}
}
pub unsafe fn pinned(&self, mut f: impl FnMut(*const Header)) {
for slot in self.slots.iter() {
let p = slot.load();
if !p.is_null() && !Self::crossed(p) && slot.holder.load(Ordering::Relaxed) != NO_HOLDER {
f(p.cast_const());
}
}
}
pub unsafe fn settle(&self) -> Vec<*const Header> {
unsafe { self.settle_outside(|_| false) }
}
pub unsafe fn settle_outside(&self, inside: impl Fn(usize) -> bool) -> Vec<*const Header> {
unsafe { self.recycle() };
self.slots
.iter()
.filter_map(|s| {
let p = s.load();
(!p.is_null() && !Self::crossed(p) && !inside(s.holder.load(Ordering::Relaxed))).then_some(p.cast_const())
})
.collect()
}
unsafe fn recycle(&self) {
let ready = unsafe { &mut *self.ready.get() };
let used = self.cursor.swap(0, Ordering::AcqRel).min(ready.len());
ready.drain(..used);
ready.extend(self.returned.take());
}
pub unsafe fn clear_unreached(&self, epoch: u32, parity: bool) {
unsafe { self.recycle() };
for slot in self.slots.iter() {
let old = slot.load();
if old.is_null() || Self::crossed(old) {
continue;
}
let new = Header::survivor(old, epoch);
if let Some(new) = new {
unsafe { &*new }.rc_stick(parity);
}
let new = new.map_or(null_mut(), <*const Header>::cast_mut);
if !core::ptr::eq(old, new) {
let _ = slot.ptr.compare_exchange(old, new, Ordering::AcqRel, Ordering::Acquire);
}
}
}
pub unsafe fn clear_dead(&self, inside: impl Fn(usize) -> bool, epoch: u32) {
for slot in self.slots.iter() {
let p = slot.load();
if !p.is_null() && !Self::crossed(p) && inside(slot.holder.load(Ordering::Relaxed)) && !unsafe { &*p }.is_marked(epoch) {
let _ = slot.ptr.compare_exchange(p, null_mut(), Ordering::AcqRel, Ordering::Relaxed);
}
}
}
}
pub struct Root<B: Brand> {
table: Arc<RootTable>,
slot: usize,
_brand: PhantomData<fn() -> B>,
}
impl<B: Brand> Drop for Root<B> {
fn drop(&mut self) {
self.table.release(self.slot);
}
}
unsafe impl<B: Brand> Trace for Root<B> {
const NO_EDGES: bool = true;
fn trace(&self, _: &mut crate::Tracer<'_>) {}
}
impl<'gc> Mutator<'gc> {
pub fn root<B: Brand>(&self, gc: Gc<'gc, B::Of<'gc>>) -> Root<B> {
let table = self.heap().roots().clone();
let slot = table.claim(gc.header(), NO_HOLDER);
Root { table, slot, _brand: PhantomData }
}
pub fn get<B: Brand>(&self, root: &Root<B>) -> Gc<'gc, B::Of<'gc>> {
assert!(Arc::ptr_eq(&root.table, self.heap().roots()), "this Root does not belong to this heap");
let header = root.table.slot(root.slot).load();
unsafe { Gc::from_data(Header::data(header).cast()) }
}
pub fn set<B: Brand>(&self, root: &Root<B>, gc: Gc<'gc, B::Of<'gc>>) {
assert!(Arc::ptr_eq(&root.table, self.heap().roots()), "this Root does not belong to this heap");
root.table.slot(root.slot).store(gc.header().cast_mut());
}
}
pub struct Weak<B: Brand> {
table: Arc<RootTable>,
slot: usize,
_brand: PhantomData<fn() -> B>,
}
impl<B: Brand> Weak<B> {
pub fn is_cleared(&self) -> bool {
self.table.slot(self.slot).load().is_null()
}
}
impl<B: Brand> Drop for Weak<B> {
fn drop(&mut self) {
self.table.release(self.slot);
}
}
unsafe impl<B: Brand> Trace for Weak<B> {
const NO_EDGES: bool = true;
fn trace(&self, _: &mut crate::Tracer<'_>) {}
}
impl<'gc> Mutator<'gc> {
pub fn weak<B: Brand>(&self, gc: Gc<'gc, B::Of<'gc>>) -> Weak<B> {
let table = self.heap().weaks().clone();
let slot = table.claim(gc.header(), NO_HOLDER);
Weak { table, slot, _brand: PhantomData }
}
pub fn upgrade<B: Brand>(&self, weak: &Weak<B>) -> Option<Gc<'gc, B::Of<'gc>>> {
assert!(Arc::ptr_eq(&weak.table, self.heap().weaks()), "this Weak does not belong to this heap");
let header = weak.table.slot(weak.slot).load();
if header.is_null() {
return None;
}
self.reached(header);
Some(unsafe { Gc::from_data(Header::data(header).cast()) })
}
}
pub struct Far<'a, B: Brand> {
table: Arc<RootTable>,
slot: usize,
ptr: NonNull<Header>,
_brand: PhantomData<(Invariant<'a>, fn() -> B)>,
}
unsafe impl<B: Brand> Send for Far<'_, B> {}
unsafe impl<B: Brand> Sync for Far<'_, B> {}
impl<'a, B: Brand> Far<'a, B> {
pub fn new<'b>(holder: &Mutator<'a>, target: &Mutator<'b>, gc: Gc<'b, B::Of<'b>>) -> Self {
assert!(!core::ptr::eq(holder.heap(), target.heap()), "edges within one heap use Slot, not Far");
let table = target.heap().roots().clone();
let slot = table.claim(gc.header(), holder.heap().id());
let ptr = unsafe { NonNull::new_unchecked(gc.header().cast_mut()) };
Self { table, slot, ptr, _brand: PhantomData }
}
pub fn get<'b>(&self, m: &Mutator<'b>) -> Gc<'b, B::Of<'b>> {
assert!(Arc::ptr_eq(&self.table, m.heap().roots()), "this Far does not point into this heap");
unsafe { Gc::from_data(Header::data(self.ptr.as_ptr()).cast()) }
}
pub fn points_into(&self, heap: &Heap) -> bool {
Arc::ptr_eq(&self.table, heap.roots())
}
fn report(&self, t: &mut Tracer<'_>) {
t.far(Arc::as_ptr(&self.table).addr(), self.ptr.as_ptr());
}
}
impl<B: Brand> Drop for Far<'_, B> {
fn drop(&mut self) {
self.table.release(self.slot);
}
}
unsafe impl<B: Brand> Trace for Far<'_, B> {
fn trace(&self, t: &mut Tracer<'_>) {
self.report(t);
}
fn relocate(&mut self, t: &mut Tracer<'_>) {
self.report(t);
}
}
#[cfg(crossheap)]
pub unsafe trait Shared: Send + Sync {
const NO_EDGES: bool = false;
fn edges(map: &mut EdgeMap, at: u32);
}
#[cfg(crossheap)]
pub const FAR_EDGE: u32 = 1 << 31;
#[cfg(crossheap)]
pub const WORD_EDGE: u32 = 1 << 30;
#[cfg(crossheap)]
pub const PTR_EDGE: u32 = 1 << 29;
#[cfg(crossheap)]
pub const EDGE_KINDS: u32 = FAR_EDGE | WORD_EDGE | PTR_EDGE;
#[derive(Default)]
#[cfg(crossheap)]
pub struct EdgeMap(Vec<u32>);
#[cfg(crossheap)]
impl EdgeMap {
pub fn edge(&mut self, at: u32) {
self.0.push(at);
}
pub fn far(&mut self, at: u32) {
self.0.push(at | FAR_EDGE);
}
pub fn word(&mut self, at: u32) {
self.0.push(at | WORD_EDGE);
}
pub fn ptr(&mut self, at: u32) {
self.0.push(at | PTR_EDGE);
}
pub fn as_slice(&self) -> &[u32] {
&self.0
}
pub fn offset(bytes: usize) -> u32 {
u32::try_from(bytes).ok().filter(|&b| b & EDGE_KINDS == 0).expect("public heap objects are at most 512 MiB")
}
}
#[cfg(crossheap)]
unsafe impl<T: Send + Sync> Shared for Gc<'_, T> {
fn edges(map: &mut EdgeMap, at: u32) {
map.ptr(at);
}
}
#[cfg(crossheap)]
unsafe impl<T: Send + Sync> Shared for Option<Gc<'_, T>> {
fn edges(map: &mut EdgeMap, at: u32) {
map.ptr(at);
}
}
#[cfg(crossheap)]
unsafe impl<T: Send + Sync> Shared for Slot<'_, T> {
fn edges(map: &mut EdgeMap, at: u32) {
map.word(at);
}
}
#[cfg(crossheap)]
unsafe impl Shared for WordSlot<'_> {
fn edges(map: &mut EdgeMap, at: u32) {
map.word(at);
}
}
#[cfg(crossheap)]
macro_rules! shared_leaf {
($($ty:ty),* $(,)?) => {$(
unsafe impl Shared for $ty {
const NO_EDGES: bool = true;
fn edges(_: &mut EdgeMap, _: u32) {}
}
)*};
}
#[cfg(crossheap)]
shared_leaf!(
(), bool, char, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64,
NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64,
AtomicBool, AtomicU8, AtomicU16, AtomicU32, AtomicU64, AtomicI8, AtomicI16, AtomicI32, AtomicI64,
);
#[cfg(crossheap)]
unsafe impl<T: ?Sized + Send + Sync> Shared for PhantomData<T> {
const NO_EDGES: bool = true;
fn edges(_: &mut EdgeMap, _: u32) {}
}
#[cfg(crossheap)]
unsafe impl<T: Shared, const N: usize> Shared for [T; N] {
const NO_EDGES: bool = T::NO_EDGES;
fn edges(map: &mut EdgeMap, at: u32) {
if !T::NO_EDGES {
for i in 0..N {
T::edges(map, at + EdgeMap::offset(i * size_of::<T>()));
}
}
}
}
#[cfg(crossheap)]
pub struct CrossHeapGc<'p, T> {
ptr: NonNull<T>,
_brand: PhantomData<(&'p T, Invariant<'p>)>,
}
#[cfg(crossheap)]
unsafe impl<T: Send + Sync> Send for CrossHeapGc<'_, T> {}
#[cfg(crossheap)]
unsafe impl<T: Send + Sync> Sync for CrossHeapGc<'_, T> {}
#[cfg(crossheap)]
impl<T> Clone for CrossHeapGc<'_, T> {
fn clone(&self) -> Self {
*self
}
}
#[cfg(crossheap)]
impl<T> Copy for CrossHeapGc<'_, T> {}
#[cfg(crossheap)]
impl<'p, T> CrossHeapGc<'p, T> {
pub fn as_ptr(self) -> *const T {
self.ptr.as_ptr()
}
pub fn get(self) -> &'p T {
unsafe { self.ptr.as_ref() }
}
pub fn ptr_eq(a: Self, b: Self) -> bool {
a.ptr == b.ptr
}
}
#[cfg(crossheap)]
pub trait CrossHeapGcInternal {
unsafe fn from_data(ptr: *mut u8) -> Self;
fn offset(self) -> u64;
}
#[cfg(crossheap)]
impl<T> CrossHeapGcInternal for CrossHeapGc<'_, T> {
unsafe fn from_data(ptr: *mut u8) -> Self {
Self { ptr: unsafe { NonNull::new_unchecked(ptr.cast()) }, _brand: PhantomData }
}
fn offset(self) -> u64 {
let addr = self.ptr.as_ptr().addr();
(addr - Region::base_of(addr)) as u64
}
}
#[cfg(crossheap)]
impl<T> Deref for CrossHeapGc<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
}
#[cfg(crossheap)]
impl<T: fmt::Debug> fmt::Debug for CrossHeapGc<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[repr(transparent)]
#[cfg(crossheap)]
pub struct CrossHeapSlot<'p, T> {
off: AtomicU64,
_brand: PhantomData<CrossHeapGc<'p, T>>,
}
#[cfg(crossheap)]
impl<T> Default for CrossHeapSlot<'_, T> {
fn default() -> Self {
Self { off: AtomicU64::new(0), _brand: PhantomData }
}
}
#[cfg(crossheap)]
impl<'p, T> From<Option<CrossHeapGc<'p, T>>> for CrossHeapSlot<'p, T> {
fn from(v: Option<CrossHeapGc<'p, T>>) -> Self {
Self { off: AtomicU64::new(Self::raw(v)), _brand: PhantomData }
}
}
#[cfg(crossheap)]
impl<'p, T> From<CrossHeapGc<'p, T>> for CrossHeapSlot<'p, T> {
fn from(v: CrossHeapGc<'p, T>) -> Self {
Some(v).into()
}
}
#[cfg(crossheap)]
impl<'p, T> CrossHeapSlot<'p, T> {
fn raw(v: Option<CrossHeapGc<'p, T>>) -> u64 {
v.map_or(0, CrossHeapGc::offset)
}
fn wrap(m: &CrossHeapMutator<'p>, off: u64) -> Option<CrossHeapGc<'p, T>> {
(off != 0).then(|| unsafe { CrossHeapGc::from_data(m.at(off)) })
}
pub fn get(&self, m: &CrossHeapMutator<'p>) -> Option<CrossHeapGc<'p, T>> {
Self::wrap(m, self.off.load(Ordering::Acquire))
}
pub fn set(&self, m: &CrossHeapMutator<'p>, v: Option<CrossHeapGc<'p, T>>) {
self.swap(m, v);
}
pub fn swap(&self, m: &CrossHeapMutator<'p>, v: Option<CrossHeapGc<'p, T>>) -> Option<CrossHeapGc<'p, T>> {
Self::wrap(m, self.off.swap(Self::raw(v), Ordering::AcqRel))
}
pub fn compare_exchange(&self, m: &CrossHeapMutator<'p>, current: Option<CrossHeapGc<'p, T>>, new: Option<CrossHeapGc<'p, T>>) -> Result<Option<CrossHeapGc<'p, T>>, Option<CrossHeapGc<'p, T>>> {
self.off
.compare_exchange(Self::raw(current), Self::raw(new), Ordering::AcqRel, Ordering::Acquire)
.map(|o| Self::wrap(m, o))
.map_err(|o| Self::wrap(m, o))
}
}
#[cfg(crossheap)]
unsafe impl<T: Send + Sync> Shared for CrossHeapSlot<'_, T> {
fn edges(map: &mut EdgeMap, at: u32) {
map.edge(at);
}
}
#[repr(C)]
#[cfg(crossheap)]
pub struct CrossHeapRef<'a, B: CrossHeapBrand> {
off: AtomicU64,
incarnation: AtomicU64,
_brand: PhantomData<(HolderBrand<'a>, fn() -> B)>,
}
#[cfg(crossheap)]
type HolderBrand<'a> = fn(&'a ()) -> &'a ();
#[cfg(crossheap)]
impl<B: CrossHeapBrand> Default for CrossHeapRef<'_, B> {
fn default() -> Self {
Self { off: AtomicU64::new(0), incarnation: AtomicU64::new(0), _brand: PhantomData }
}
}
#[cfg(crossheap)]
impl<'a, B: CrossHeapBrand> CrossHeapRef<'a, B> {
pub fn to<'b>(holder: &CrossHeapMutator<'a>, target: &CrossHeapMutator<'b>, gc: CrossHeapGc<'b, B::Of<'b>>) -> Self {
let r = Self::default();
r.set(holder, target, Some(gc));
r
}
pub fn set<'b>(&self, holder: &CrossHeapMutator<'a>, target: &CrossHeapMutator<'b>, v: Option<CrossHeapGc<'b, B::Of<'b>>>) {
assert!(holder.index() != target.index(), "edges within one public heap use CrossHeapSlot");
let off = v.map_or(0, CrossHeapGc::offset);
if off != 0 {
target.register(off, holder);
}
self.incarnation.store(target.incarnation(), Ordering::Release);
self.off.store(off, Ordering::Release);
}
pub fn get<'b>(&self, target: &CrossHeapMutator<'b>) -> Option<CrossHeapGc<'b, B::Of<'b>>> {
let off = self.off.load(Ordering::Acquire);
if off == 0 || Inner::heap_of(off) != Some(target.index()) || self.incarnation.load(Ordering::Acquire) != target.incarnation() {
return None;
}
Some(unsafe { CrossHeapGc::from_data(target.at(off)) })
}
pub fn points_into(&self, heap: &CrossHeap) -> bool {
Inner::heap_of(self.off.load(Ordering::Acquire)) == Some(heap.id()) && self.incarnation.load(Ordering::Acquire) == heap.incarnation()
}
}
#[cfg(crossheap)]
unsafe impl<B: CrossHeapBrand> Shared for CrossHeapRef<'_, B> {
fn edges(map: &mut EdgeMap, at: u32) {
map.far(at);
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg(crossheap)]
pub struct WeakWord(u64);
#[cfg(crossheap)]
const OFF_SHIFT: u32 = GRANULE.trailing_zeros();
#[cfg(crossheap)]
const OFF_BITS: u32 = REGION.trailing_zeros() - OFF_SHIFT;
#[cfg(crossheap)]
const STAMP_BITS: u32 = if u64::BITS - OFF_BITS < u32::BITS { u64::BITS - OFF_BITS } else { u32::BITS };
#[cfg(crossheap)]
pub const STAMP_MASK: u32 = u32::MAX >> (u32::BITS - STAMP_BITS);
#[cfg(crossheap)]
impl From<(u64, u32)> for WeakWord {
fn from((off, stamp): (u64, u32)) -> Self {
Self(((off >> OFF_SHIFT) << STAMP_BITS) | u64::from(stamp & STAMP_MASK))
}
}
#[cfg(crossheap)]
impl From<u64> for WeakWord {
fn from(raw: u64) -> Self {
Self(raw)
}
}
#[cfg(crossheap)]
impl From<WeakWord> for u64 {
fn from(w: WeakWord) -> Self {
w.0
}
}
#[cfg(crossheap)]
impl<T> From<CrossHeapGc<'_, T>> for WeakWord {
fn from(gc: CrossHeapGc<'_, T>) -> Self {
let stamp = unsafe { (*PHeader::of(gc.as_ptr().cast())).stamp };
(gc.offset(), stamp).into()
}
}
#[cfg(crossheap)]
impl WeakWord {
pub fn offset(self) -> u64 {
(self.0 >> STAMP_BITS) << OFF_SHIFT
}
pub fn stamp(self) -> u32 {
u32::try_from(self.0 & u64::from(STAMP_MASK)).expect("the stamp fits in the low 32 bits")
}
pub fn heap(self) -> Option<usize> {
(self.0 != 0).then(|| Inner::heap_of(self.offset())).flatten()
}
}
#[repr(transparent)]
#[cfg(crossheap)]
pub struct CrossHeapWeak<B: CrossHeapBrand> {
word: AtomicU64,
_brand: PhantomData<fn() -> B>,
}
#[cfg(crossheap)]
impl<B: CrossHeapBrand> Default for CrossHeapWeak<B> {
fn default() -> Self {
Self { word: AtomicU64::new(0), _brand: PhantomData }
}
}
#[cfg(crossheap)]
impl<B: CrossHeapBrand> From<Option<CrossHeapGc<'_, B::Of<'_>>>> for CrossHeapWeak<B> {
fn from(v: Option<CrossHeapGc<'_, B::Of<'_>>>) -> Self {
Self { word: AtomicU64::new(v.map_or(0, |gc| WeakWord::from(gc).into())), _brand: PhantomData }
}
}
#[cfg(crossheap)]
impl<B: CrossHeapBrand> From<CrossHeapGc<'_, B::Of<'_>>> for CrossHeapWeak<B> {
fn from(gc: CrossHeapGc<'_, B::Of<'_>>) -> Self {
Some(gc).into()
}
}
#[cfg(crossheap)]
impl<B: CrossHeapBrand> CrossHeapWeak<B> {
pub fn set(&self, v: Option<CrossHeapGc<'_, B::Of<'_>>>) {
self.word.store(v.map_or(0, |gc| WeakWord::from(gc).into()), Ordering::Release);
}
pub fn get<'b>(&self, target: &CrossHeapMutator<'b>) -> Option<CrossHeapGc<'b, B::Of<'b>>> {
let data = target.locate(self.word.load(Ordering::Acquire).into())?;
target.is_type::<B::Of<'b>>(data).then(|| unsafe { CrossHeapGc::from_data(data) })
}
pub fn heap(&self) -> Option<usize> {
WeakWord::from(self.word.load(Ordering::Acquire)).heap()
}
pub fn word(&self) -> u64 {
self.word.load(Ordering::Acquire)
}
pub fn from_word(word: u64) -> Self {
Self { word: AtomicU64::new(word), _brand: PhantomData }
}
}
#[cfg(crossheap)]
unsafe impl<B: CrossHeapBrand> Shared for CrossHeapWeak<B> {
const NO_EDGES: bool = true;
fn edges(_: &mut EdgeMap, _: u32) {}
}
#[cfg(crossheap)]
unsafe impl<B: CrossHeapBrand> Trace for CrossHeapWeak<B> {
const NO_EDGES: bool = true;
fn trace(&self, _: &mut Tracer<'_>) {}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg(crossheap)]
pub struct Signature {
word: WeakWord,
incarnation: u64,
key: [u64; 2],
}
#[cfg(crossheap)]
pub const SIGNATURE_BYTES: usize = 32;
#[cfg(crossheap)]
impl Signature {
pub fn heap(&self) -> Option<usize> {
self.word.heap()
}
pub fn incarnation(&self) -> u64 {
self.incarnation
}
pub fn key(&self) -> [u64; 2] {
self.key
}
}
#[cfg(crossheap)]
impl From<(WeakWord, u64, [u64; 2])> for Signature {
fn from((word, incarnation, key): (WeakWord, u64, [u64; 2])) -> Self {
Self { word, incarnation, key }
}
}
#[cfg(crossheap)]
impl From<&Signature> for WeakWord {
fn from(s: &Signature) -> Self {
s.word
}
}
#[cfg(crossheap)]
impl From<Signature> for [u8; SIGNATURE_BYTES] {
fn from(s: Signature) -> Self {
let mut out = [0; SIGNATURE_BYTES];
for (chunk, v) in out.as_chunks_mut::<{ size_of::<u64>() }>().0.iter_mut().zip([s.word.into(), s.incarnation, s.key[0], s.key[1]]) {
chunk.copy_from_slice(&u64::to_le_bytes(v));
}
out
}
}
#[cfg(crossheap)]
impl From<&[u8; SIGNATURE_BYTES]> for Signature {
fn from(bytes: &[u8; SIGNATURE_BYTES]) -> Self {
let mut words = bytes.as_chunks::<{ size_of::<u64>() }>().0.iter().map(|c| u64::from_le_bytes(*c));
let mut next = || words.next().expect("4 words");
Self { word: next().into(), incarnation: next(), key: [next(), next()] }
}
}
#[cfg(crossheap)]
pub trait CrossHeapBrand {
type Of<'p>: Shared + 'p;
}
#[cfg(crossheap)]
#[macro_export]
macro_rules! cross_heap_brand {
($(#[$meta:meta])* $vis:vis $name:ident = for<$l:lifetime> $ty:ty) => {
$(#[$meta])*
$vis struct $name;
impl $crate::CrossHeapBrand for $name {
type Of<$l> = $ty;
}
};
}
#[cfg(crossheap)]
pub struct CrossHeapRoot<B: CrossHeapBrand> {
heap: Arc<Inner>,
entry: u32,
data: NonNull<u8>,
_brand: PhantomData<fn() -> B>,
}
#[cfg(crossheap)]
unsafe impl<B: CrossHeapBrand> Send for CrossHeapRoot<B> {}
#[cfg(crossheap)]
unsafe impl<B: CrossHeapBrand> Sync for CrossHeapRoot<B> {}
#[cfg(crossheap)]
impl<B: CrossHeapBrand> CrossHeapRoot<B> {
pub fn get<'p>(&self, m: &CrossHeapMutator<'p>) -> CrossHeapGc<'p, B::Of<'p>> {
assert!(m.is(&self.heap), "this CrossHeapRoot does not point into this heap");
unsafe { CrossHeapGc::from_data(self.data.as_ptr()) }
}
pub fn points_into(&self, heap: &CrossHeap) -> bool {
heap.is(&self.heap)
}
pub fn index(&self) -> u32 {
self.entry
}
pub fn persist(self) -> u32 {
let me = core::mem::ManuallyDrop::new(self);
me.heap.disown_entry(me.entry);
let entry = me.entry;
drop(unsafe { core::ptr::read(&raw const me.heap) });
entry
}
}
#[cfg(crossheap)]
pub trait CrossHeapRootInternal {
fn new(heap: Arc<Inner>, entry: u32, data: NonNull<u8>) -> Self;
}
#[cfg(crossheap)]
impl<B: CrossHeapBrand> CrossHeapRootInternal for CrossHeapRoot<B> {
fn new(heap: Arc<Inner>, entry: u32, data: NonNull<u8>) -> Self {
Self { heap, entry, data, _brand: PhantomData }
}
}
#[cfg(crossheap)]
impl<B: CrossHeapBrand> Drop for CrossHeapRoot<B> {
fn drop(&mut self) {
self.heap.release_entry(self.entry);
}
}
#[cfg(crossheap)]
unsafe impl<B: CrossHeapBrand> Trace for CrossHeapRoot<B> {
const NO_EDGES: bool = true;
fn trace(&self, _: &mut Tracer<'_>) {}
}