use std::alloc::Layout;
use std::any::Any;
use std::cell::UnsafeCell;
use std::cmp;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops::Deref;
use std::ptr::{self, NonNull};
use std::sync::atomic::{self, AtomicUsize, Ordering};
use wasmtime_environ::StackMap;
use crate::Backtrace;
#[derive(Debug)]
#[repr(transparent)]
pub struct VMExternRef(NonNull<VMExternData>);
impl std::fmt::Pointer for VMExternRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Pointer::fmt(&self.0, f)
}
}
unsafe impl Send for VMExternRef {}
unsafe impl Sync for VMExternRef {}
#[repr(C)]
pub(crate) struct VMExternData {
ref_count: AtomicUsize,
value_ptr: NonNull<dyn Any + Send + Sync>,
}
impl Clone for VMExternRef {
#[inline]
fn clone(&self) -> VMExternRef {
self.extern_data().increment_ref_count();
VMExternRef(self.0)
}
}
impl Drop for VMExternRef {
#[inline]
fn drop(&mut self) {
let data = self.extern_data();
if data.ref_count.fetch_sub(1, Ordering::Release) != 1 {
return;
}
atomic::fence(Ordering::Acquire);
drop(data);
unsafe {
VMExternData::drop_and_dealloc(self.0);
}
}
}
impl VMExternData {
unsafe fn layout_for(value_size: usize, value_align: usize) -> (Layout, usize) {
let extern_data_size = mem::size_of::<VMExternData>();
let extern_data_align = mem::align_of::<VMExternData>();
let value_and_padding_size = round_up_to_align(value_size, extern_data_align).unwrap();
let alloc_align = std::cmp::max(value_align, extern_data_align);
let alloc_size = value_and_padding_size + extern_data_size;
debug_assert!(
Layout::from_size_align(alloc_size, alloc_align).is_ok(),
"should create a `Layout` for size={} and align={} okay",
alloc_size,
alloc_align,
);
(
Layout::from_size_align_unchecked(alloc_size, alloc_align),
value_and_padding_size,
)
}
pub(crate) unsafe fn drop_and_dealloc(mut data: NonNull<VMExternData>) {
log::trace!("Dropping externref data @ {:p}", data);
let (alloc_ptr, layout) = {
let data = data.as_mut();
debug_assert_eq!(data.ref_count.load(Ordering::SeqCst), 0);
let (layout, _) = {
let value = data.value_ptr.as_ref();
Self::layout_for(mem::size_of_val(value), mem::align_of_val(value))
};
ptr::drop_in_place(data.value_ptr.as_ptr());
let alloc_ptr = data.value_ptr.cast::<u8>();
(alloc_ptr, layout)
};
ptr::drop_in_place(data.as_ptr());
std::alloc::dealloc(alloc_ptr.as_ptr(), layout);
}
#[inline]
fn increment_ref_count(&self) {
self.ref_count.fetch_add(1, Ordering::Relaxed);
}
}
#[inline]
fn round_up_to_align(n: usize, align: usize) -> Option<usize> {
debug_assert!(align.is_power_of_two());
let align_minus_one = align - 1;
Some(n.checked_add(align_minus_one)? & !align_minus_one)
}
impl VMExternRef {
pub fn new<T>(value: T) -> VMExternRef
where
T: 'static + Any + Send + Sync,
{
VMExternRef::new_with(|| value)
}
pub fn new_with<T>(make_value: impl FnOnce() -> T) -> VMExternRef
where
T: 'static + Any + Send + Sync,
{
unsafe {
let (layout, footer_offset) =
VMExternData::layout_for(mem::size_of::<T>(), mem::align_of::<T>());
let alloc_ptr = std::alloc::alloc(layout);
let alloc_ptr = NonNull::new(alloc_ptr).unwrap_or_else(|| {
std::alloc::handle_alloc_error(layout);
});
let value_ptr = alloc_ptr.cast::<T>();
ptr::write(value_ptr.as_ptr(), make_value());
let extern_data_ptr =
alloc_ptr.cast::<u8>().as_ptr().add(footer_offset) as *mut VMExternData;
ptr::write(
extern_data_ptr,
VMExternData {
ref_count: AtomicUsize::new(1),
value_ptr: NonNull::new_unchecked(value_ptr.as_ptr()),
},
);
log::trace!("New externref data @ {:p}", extern_data_ptr);
VMExternRef(NonNull::new_unchecked(extern_data_ptr))
}
}
#[inline]
pub fn as_raw(&self) -> *mut u8 {
let ptr = self.0.cast::<u8>().as_ptr();
ptr
}
pub unsafe fn into_raw(self) -> *mut u8 {
let ptr = self.0.cast::<u8>().as_ptr();
std::mem::forget(self);
ptr
}
pub unsafe fn from_raw(ptr: *mut u8) -> Self {
debug_assert!(!ptr.is_null());
VMExternRef(NonNull::new_unchecked(ptr).cast())
}
pub unsafe fn clone_from_raw(ptr: *mut u8) -> Self {
debug_assert!(!ptr.is_null());
let x = VMExternRef(NonNull::new_unchecked(ptr).cast());
x.extern_data().increment_ref_count();
x
}
pub fn strong_count(&self) -> usize {
self.extern_data().ref_count.load(Ordering::SeqCst)
}
#[inline]
fn extern_data(&self) -> &VMExternData {
unsafe { self.0.as_ref() }
}
}
impl VMExternRef {
#[inline]
pub fn eq(a: &Self, b: &Self) -> bool {
ptr::eq(a.0.as_ptr(), b.0.as_ptr())
}
#[inline]
pub fn hash<H>(externref: &Self, hasher: &mut H)
where
H: Hasher,
{
ptr::hash(externref.0.as_ptr(), hasher);
}
#[inline]
pub fn cmp(a: &Self, b: &Self) -> cmp::Ordering {
let a = a.0.as_ptr() as usize;
let b = b.0.as_ptr() as usize;
a.cmp(&b)
}
}
impl Deref for VMExternRef {
type Target = dyn Any;
fn deref(&self) -> &dyn Any {
unsafe { self.extern_data().value_ptr.as_ref() }
}
}
#[derive(Clone, Debug)]
struct VMExternRefWithTraits(VMExternRef);
impl Hash for VMExternRefWithTraits {
fn hash<H>(&self, hasher: &mut H)
where
H: Hasher,
{
VMExternRef::hash(&self.0, hasher)
}
}
impl PartialEq for VMExternRefWithTraits {
fn eq(&self, other: &Self) -> bool {
VMExternRef::eq(&self.0, &other.0)
}
}
impl Eq for VMExternRefWithTraits {}
type TableElem = UnsafeCell<Option<VMExternRef>>;
#[repr(C)] pub struct VMExternRefActivationsTable {
alloc: VMExternRefTableAlloc,
over_approximated_stack_roots: HashSet<VMExternRefWithTraits>,
precise_stack_roots: HashSet<VMExternRefWithTraits>,
#[cfg(debug_assertions)]
gc_okay: bool,
}
#[repr(C)] struct VMExternRefTableAlloc {
next: UnsafeCell<NonNull<TableElem>>,
end: NonNull<TableElem>,
chunk: Box<[TableElem]>,
}
unsafe impl Send for VMExternRefTableAlloc {}
unsafe impl Sync for VMExternRefTableAlloc {}
fn _assert_send_sync() {
fn _assert<T: Send + Sync>() {}
_assert::<VMExternRefActivationsTable>();
_assert::<VMExternRef>();
}
impl VMExternRefActivationsTable {
const CHUNK_SIZE: usize = 4096 / mem::size_of::<usize>();
pub fn new() -> Self {
let mut chunk: Box<[TableElem]> = Box::new([]);
let next = chunk.as_mut_ptr();
let end = unsafe { next.add(chunk.len()) };
VMExternRefActivationsTable {
alloc: VMExternRefTableAlloc {
next: UnsafeCell::new(NonNull::new(next).unwrap()),
end: NonNull::new(end).unwrap(),
chunk,
},
over_approximated_stack_roots: HashSet::new(),
precise_stack_roots: HashSet::new(),
#[cfg(debug_assertions)]
gc_okay: true,
}
}
fn new_chunk(size: usize) -> Box<[UnsafeCell<Option<VMExternRef>>]> {
assert!(size >= Self::CHUNK_SIZE);
(0..size).map(|_| UnsafeCell::new(None)).collect()
}
#[inline]
pub fn bump_capacity_remaining(&self) -> usize {
let end = self.alloc.end.as_ptr() as usize;
let next = unsafe { *self.alloc.next.get() };
end - next.as_ptr() as usize
}
#[inline]
pub fn try_insert(&mut self, externref: VMExternRef) -> Result<(), VMExternRef> {
unsafe {
let next = *self.alloc.next.get();
if next == self.alloc.end {
return Err(externref);
}
debug_assert!(
(*next.as_ref().get()).is_none(),
"slots >= the `next` bump finger are always `None`"
);
ptr::write(next.as_ptr(), UnsafeCell::new(Some(externref)));
let next = NonNull::new_unchecked(next.as_ptr().add(1));
debug_assert!(next <= self.alloc.end);
*self.alloc.next.get() = next;
Ok(())
}
}
#[inline]
pub unsafe fn insert_with_gc(
&mut self,
externref: VMExternRef,
module_info_lookup: &dyn ModuleInfoLookup,
) {
#[cfg(debug_assertions)]
assert!(self.gc_okay);
if let Err(externref) = self.try_insert(externref) {
self.gc_and_insert_slow(externref, module_info_lookup);
}
}
#[inline(never)]
unsafe fn gc_and_insert_slow(
&mut self,
externref: VMExternRef,
module_info_lookup: &dyn ModuleInfoLookup,
) {
gc(module_info_lookup, self);
self.over_approximated_stack_roots
.insert(VMExternRefWithTraits(externref));
}
#[inline]
pub fn insert_without_gc(&mut self, externref: VMExternRef) {
if let Err(externref) = self.try_insert(externref) {
self.insert_slow_without_gc(externref);
}
}
#[inline(never)]
fn insert_slow_without_gc(&mut self, externref: VMExternRef) {
self.over_approximated_stack_roots
.insert(VMExternRefWithTraits(externref));
}
fn num_filled_in_bump_chunk(&self) -> usize {
let next = unsafe { *self.alloc.next.get() };
let bytes_unused = (self.alloc.end.as_ptr() as usize) - (next.as_ptr() as usize);
let slots_unused = bytes_unused / mem::size_of::<TableElem>();
self.alloc.chunk.len().saturating_sub(slots_unused)
}
fn elements(&self, mut f: impl FnMut(&VMExternRef)) {
for elem in self.over_approximated_stack_roots.iter() {
f(&elem.0);
}
let num_filled = self.num_filled_in_bump_chunk();
for slot in self.alloc.chunk.iter().take(num_filled) {
if let Some(elem) = unsafe { &*slot.get() } {
f(elem);
}
}
}
fn insert_precise_stack_root(
precise_stack_roots: &mut HashSet<VMExternRefWithTraits>,
root: NonNull<VMExternData>,
) {
let root = unsafe { VMExternRef::clone_from_raw(root.as_ptr().cast()) };
log::trace!("Found externref on stack: {:p}", root);
precise_stack_roots.insert(VMExternRefWithTraits(root));
}
fn sweep(&mut self) {
log::trace!("begin GC sweep");
let num_filled = self.num_filled_in_bump_chunk();
unsafe {
*self.alloc.next.get() = self.alloc.end;
}
for slot in self.alloc.chunk.iter().take(num_filled) {
unsafe {
*slot.get() = None;
}
}
debug_assert!(
self.alloc
.chunk
.iter()
.all(|slot| unsafe { (*slot.get()).as_ref().is_none() }),
"after sweeping the bump chunk, all slots should be `None`"
);
if self.alloc.chunk.is_empty() {
self.alloc.chunk = Self::new_chunk(Self::CHUNK_SIZE);
self.alloc.end =
NonNull::new(unsafe { self.alloc.chunk.as_mut_ptr().add(self.alloc.chunk.len()) })
.unwrap();
}
unsafe {
let next = self.alloc.chunk.as_mut_ptr();
debug_assert!(!next.is_null());
*self.alloc.next.get() = NonNull::new_unchecked(next);
}
mem::swap(
&mut self.precise_stack_roots,
&mut self.over_approximated_stack_roots,
);
self.precise_stack_roots.clear();
log::trace!("end GC sweep");
}
#[inline]
pub fn set_gc_okay(&mut self, okay: bool) -> bool {
#[cfg(debug_assertions)]
{
return std::mem::replace(&mut self.gc_okay, okay);
}
#[cfg(not(debug_assertions))]
{
let _ = okay;
return true;
}
}
}
pub trait ModuleInfoLookup {
fn lookup(&self, pc: usize) -> Option<&dyn ModuleInfo>;
}
pub trait ModuleInfo {
fn lookup_stack_map(&self, pc: usize) -> Option<&StackMap>;
}
#[derive(Debug, Default)]
struct DebugOnly<T> {
inner: T,
}
impl<T> std::ops::Deref for DebugOnly<T> {
type Target = T;
fn deref(&self) -> &T {
if cfg!(debug_assertions) {
&self.inner
} else {
panic!(
"only deref `DebugOnly` when `cfg(debug_assertions)` or \
inside a `debug_assert!(..)`"
)
}
}
}
impl<T> std::ops::DerefMut for DebugOnly<T> {
fn deref_mut(&mut self) -> &mut T {
if cfg!(debug_assertions) {
&mut self.inner
} else {
panic!(
"only deref `DebugOnly` when `cfg(debug_assertions)` or \
inside a `debug_assert!(..)`"
)
}
}
}
pub unsafe fn gc(
module_info_lookup: &dyn ModuleInfoLookup,
externref_activations_table: &mut VMExternRefActivationsTable,
) {
log::debug!("start GC");
#[cfg(debug_assertions)]
assert!(externref_activations_table.gc_okay);
debug_assert!({
externref_activations_table.precise_stack_roots.is_empty()
});
let mut activations_table_set: DebugOnly<HashSet<_>> = Default::default();
if cfg!(debug_assertions) {
externref_activations_table.elements(|elem| {
activations_table_set.insert(elem.as_raw() as *mut VMExternData);
});
}
log::trace!("begin GC trace");
Backtrace::trace(|frame| {
let pc = frame.pc();
debug_assert!(pc != 0, "we should always get a valid PC for Wasm frames");
let fp = frame.fp();
debug_assert!(
fp != 0,
"we should always get a valid frame pointer for Wasm frames"
);
let module_info = module_info_lookup
.lookup(pc)
.expect("should have module info for Wasm frame");
let stack_map = match module_info.lookup_stack_map(pc) {
Some(sm) => sm,
None => {
log::trace!("No stack map for this Wasm frame");
return std::ops::ControlFlow::Continue(());
}
};
log::trace!(
"We have a stack map that maps {} words in this Wasm frame",
stack_map.mapped_words()
);
let sp = fp - stack_map.mapped_words() as usize * mem::size_of::<usize>();
for i in 0..(stack_map.mapped_words() as usize) {
let stack_slot = sp + i * mem::size_of::<usize>();
if !stack_map.get_bit(i) {
log::trace!(
"Stack slot @ {:p} does not contain externrefs",
stack_slot as *const (),
);
continue;
}
let stack_slot = stack_slot as *const *mut VMExternData;
let r = std::ptr::read(stack_slot);
log::trace!("Stack slot @ {:p} = {:p}", stack_slot, r);
debug_assert!(
r.is_null() || activations_table_set.contains(&r),
"every on-stack externref inside a Wasm frame should \
have an entry in the VMExternRefActivationsTable; \
{:?} is not in the table",
r
);
if let Some(r) = NonNull::new(r) {
VMExternRefActivationsTable::insert_precise_stack_root(
&mut externref_activations_table.precise_stack_roots,
r,
);
}
}
std::ops::ControlFlow::Continue(())
});
log::trace!("end GC trace");
externref_activations_table.sweep();
log::debug!("end GC");
}
#[cfg(test)]
mod tests {
use super::*;
use std::convert::TryInto;
#[test]
fn extern_ref_is_pointer_sized_and_aligned() {
assert_eq!(mem::size_of::<VMExternRef>(), mem::size_of::<*mut ()>());
assert_eq!(mem::align_of::<VMExternRef>(), mem::align_of::<*mut ()>());
assert_eq!(
mem::size_of::<Option<VMExternRef>>(),
mem::size_of::<*mut ()>()
);
assert_eq!(
mem::align_of::<Option<VMExternRef>>(),
mem::align_of::<*mut ()>()
);
}
#[test]
fn ref_count_is_at_correct_offset() {
let s = "hi";
let s: &(dyn Any + Send + Sync) = &s as _;
let s: *const (dyn Any + Send + Sync) = s as _;
let s: *mut (dyn Any + Send + Sync) = s as _;
let extern_data = VMExternData {
ref_count: AtomicUsize::new(0),
value_ptr: NonNull::new(s).unwrap(),
};
let extern_data_ptr = &extern_data as *const _;
let ref_count_ptr = &extern_data.ref_count as *const _;
let actual_offset = (ref_count_ptr as usize) - (extern_data_ptr as usize);
let offsets = wasmtime_environ::VMOffsets::from(wasmtime_environ::VMOffsetsFields {
ptr: 8,
num_imported_functions: 0,
num_imported_tables: 0,
num_imported_memories: 0,
num_imported_globals: 0,
num_defined_tables: 0,
num_defined_memories: 0,
num_owned_memories: 0,
num_defined_globals: 0,
num_escaped_funcs: 0,
});
assert_eq!(
offsets.vm_extern_data_ref_count(),
actual_offset.try_into().unwrap(),
);
}
#[test]
fn table_next_is_at_correct_offset() {
let table = VMExternRefActivationsTable::new();
let table_ptr = &table as *const _;
let next_ptr = &table.alloc.next as *const _;
let actual_offset = (next_ptr as usize) - (table_ptr as usize);
let offsets = wasmtime_environ::VMOffsets::from(wasmtime_environ::VMOffsetsFields {
ptr: 8,
num_imported_functions: 0,
num_imported_tables: 0,
num_imported_memories: 0,
num_imported_globals: 0,
num_defined_tables: 0,
num_defined_memories: 0,
num_owned_memories: 0,
num_defined_globals: 0,
num_escaped_funcs: 0,
});
assert_eq!(
offsets.vm_extern_ref_activation_table_next() as usize,
actual_offset
);
}
#[test]
fn table_end_is_at_correct_offset() {
let table = VMExternRefActivationsTable::new();
let table_ptr = &table as *const _;
let end_ptr = &table.alloc.end as *const _;
let actual_offset = (end_ptr as usize) - (table_ptr as usize);
let offsets = wasmtime_environ::VMOffsets::from(wasmtime_environ::VMOffsetsFields {
ptr: 8,
num_imported_functions: 0,
num_imported_tables: 0,
num_imported_memories: 0,
num_imported_globals: 0,
num_defined_tables: 0,
num_defined_memories: 0,
num_owned_memories: 0,
num_defined_globals: 0,
num_escaped_funcs: 0,
});
assert_eq!(
offsets.vm_extern_ref_activation_table_end() as usize,
actual_offset
);
}
}