A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Add a reusable `StringPool` for interning strings (#12536)
Nick Fitzgerald0c673b703282
diff --git a/crates/core/src/alloc.rs b/crates/core/src/alloc.rsindex eb690047bb..90db484d1e 100644--- a/crates/core/src/alloc.rs+++ b/crates/core/src/alloc.rs@@ -91,3 +91,24 @@ impl<T> PanicOnOom for Result<T, OutOfMemory> {}}}++/// Create a `*mut str` from a pointer and length pair.+///+/// NB: This function is safe, but dereferencing it or otherwise using the+/// resulting `str` pointer's contents is unsafe and requires that the pointer+/// be valid for accessing and points to a valid utf8 sequence of `len` bytes.+fn str_ptr_from_raw_parts(ptr: *mut u8, len: usize) -> *mut str {+ let ptr: *mut [u8] = core::ptr::slice_from_raw_parts_mut(ptr, len);+ str_ptr_from_slice_ptr(ptr)+}++/// Create a `*mut str` from a slice pointer.+///+/// NB: This function is safe, but dereferencing it or otherwise using the+/// resulting `str` pointer's contents is unsafe and requires that the pointer+/// be valid for accessing and points to a valid utf8 sequence of `len` bytes.+fn str_ptr_from_slice_ptr(ptr: *mut [u8]) -> *mut str {+ // SAFETY: `str` is a newtype of `[u8]`.+ let ptr: *mut str = unsafe { core::mem::transmute(ptr) };+ ptr+}diff --git a/crates/core/src/alloc/boxed.rs b/crates/core/src/alloc/boxed.rsindex f7a273a6ab..478b1d97cf 100644--- a/crates/core/src/alloc/boxed.rs+++ b/crates/core/src/alloc/boxed.rs@@ -1,5 +1,5 @@use super::{TryClone, TryNew, Vec, try_alloc};-use crate::error::OutOfMemory;+use crate::{alloc::str_ptr_from_slice_ptr, error::OutOfMemory};use core::{alloc::Layout,mem::{self, MaybeUninit},@@ -67,6 +67,23 @@ where}}+impl TryClone for Box<str> {+ fn try_clone(&self) -> Result<Self, OutOfMemory> {+ let mut builder = BoxedSliceBuilder::new(self.len())?;+ for b in self.as_bytes() {+ builder.push(*b).expect("reserved capacity");+ }+ debug_assert_eq!(builder.init_len(), builder.capacity());+ let boxed = builder.finish();+ let ptr = Box::into_raw(boxed);+ let ptr = str_ptr_from_slice_ptr(ptr);+ // SAFETY: the pointer is allocated with the global allocator and points+ // to a valid utf8 sequence.+ let boxed = unsafe { Box::from_raw(ptr) };+ Ok(boxed)+ }+}+/// Allocate a new `Box<[MaybeUninit<T>]>` of the given length with/// uninitialized contents, returning `Err(OutOfMemory)` on allocation failure.///diff --git a/crates/core/src/alloc/string.rs b/crates/core/src/alloc/string.rsindex 79f2b32299..4212ce0feb 100644--- a/crates/core/src/alloc/string.rs+++ b/crates/core/src/alloc/string.rs@@ -1,10 +1,13 @@-use super::TryClone;-use crate::error::OutOfMemory;-use core::{fmt, ops};-use std_alloc::string as inner;+use crate::{+ alloc::{TryClone, str_ptr_from_raw_parts, try_realloc},+ error::OutOfMemory,+};+use core::{fmt, mem, ops};+use std_alloc::{alloc::Layout, boxed::Box, string as inner};/// A newtype wrapper around [`std::string::String`] that only exposes/// fallible-allocation methods.+#[derive(Default)]pub struct String {inner: inner::String,}@@ -70,6 +73,12 @@ impl String {Ok(s)}+ /// Same as [`std::string::String::capacity`].+ #[inline]+ pub fn capacity(&self) -> usize {+ self.inner.capacity()+ }+/// Same as [`std::string::String::reserve`] but returns an error on/// allocation failure.#[inline]@@ -105,4 +114,105 @@ impl String {self.inner.push_str(s);Ok(())}++ /// Same as [`std::string::String::into_raw_parts`].+ pub fn into_raw_parts(mut self) -> (*mut u8, usize, usize) {+ // NB: Can't use `String::into_raw_parts` until our MSRV is >= 1.93.+ #[cfg(not(miri))]+ {+ let ptr = self.as_mut_ptr();+ let len = self.len();+ let cap = self.capacity();+ mem::forget(self);+ (ptr, len, cap)+ }+ // NB: Miri requires using `into_raw_parts`, but always run on nightly,+ // so it's fine to use there.+ #[cfg(miri)]+ {+ let _ = &mut self;+ self.inner.into_raw_parts()+ }+ }++ /// Same as [`std::string::String::from_raw_parts`].+ pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> Self {+ Self {+ // Safety: Same as our unsafe contract.+ inner: unsafe { inner::String::from_raw_parts(buf, length, capacity) },+ }+ }++ /// Same as [`std::string::String::shrink_to_fit`] but returns an error on+ /// allocation failure.+ pub fn shrink_to_fit(&mut self) -> Result<(), OutOfMemory> {+ // If our length is already equal to our capacity, then there is nothing+ // to shrink.+ if self.len() == self.capacity() {+ return Ok(());+ }++ // `realloc` requires a non-zero original layout as well as a non-zero+ // destination layout, so this guard ensures that the sizes below are+ // all nonzero. This handles a couple cases:+ //+ // * If `len == cap == 0` then no allocation has ever been made.+ // * If `len == 0` and `cap != 0` then this function effectively frees+ // the memory.+ //+ // In both of these cases delegate to the standard library's+ // `shrink_to_fit` which is guaranteed to not perform a `realloc`.+ if self.is_empty() {+ self.inner.shrink_to_fit();+ return Ok(());+ }++ let (ptr, len, cap) = mem::take(self).into_raw_parts();+ debug_assert!(!ptr.is_null());+ debug_assert!(len > 0);+ debug_assert!(cap > len);+ let old_layout = Layout::array::<u8>(cap).unwrap();+ debug_assert_eq!(old_layout.size(), cap);+ let new_layout = Layout::array::<u8>(len).unwrap();+ debug_assert_eq!(old_layout.align(), new_layout.align());+ debug_assert_eq!(new_layout.size(), len);++ // SAFETY: `ptr` was previously allocated in the global allocator,+ // `layout` has a nonzero size and matches the current allocation of+ // `ptr`, `len` is nonzero, and `len` is a valid array size+ // for `len` elements given its constructor.+ let result = unsafe { try_realloc(ptr, old_layout, len) };++ match result {+ Ok(ptr) => {+ // SAFETY: `result` is allocated with the global allocator and+ // has room for exactly `[u8; len]`.+ *self = unsafe { Self::from_raw_parts(ptr.as_ptr(), len, len) };+ Ok(())+ }+ Err(oom) => {+ // SAFETY: If reallocation fails then it's guaranteed that the+ // original allocation is not tampered with, so it's safe to+ // reassemble the original vector.+ *self = unsafe { Self::from_raw_parts(ptr, len, cap) };+ Err(oom)+ }+ }+ }++ /// Same as [`std::string::String::into_boxed_str`] but returns an error on+ /// allocation failure.+ pub fn into_boxed_str(mut self) -> Result<Box<str>, OutOfMemory> {+ self.shrink_to_fit()?;++ let (ptr, len, cap) = self.into_raw_parts();+ debug_assert_eq!(len, cap);+ let ptr = str_ptr_from_raw_parts(ptr, len);++ // SAFETY: The `ptr` is allocated with the global allocator and points+ // to a valid block of utf8.+ let boxed = unsafe { Box::from_raw(ptr) };++ Ok(boxed)+ }}diff --git a/crates/core/src/alloc/try_clone.rs b/crates/core/src/alloc/try_clone.rsindex 98c4d61343..09d03975bb 100644--- a/crates/core/src/alloc/try_clone.rs+++ b/crates/core/src/alloc/try_clone.rs@@ -1,4 +1,5 @@use crate::error::OutOfMemory;+use core::mem;/// A trait for values that can be cloned, but contain owned, heap-allocated/// values whose allocations may fail during cloning.@@ -8,14 +9,30 @@ pub trait TryClone: Sized {fn try_clone(&self) -> Result<Self, OutOfMemory>;}-impl<T> TryClone for *mut T {+impl<T> TryClone for *mut T+where+ T: ?Sized,+{#[inline]fn try_clone(&self) -> Result<Self, OutOfMemory> {Ok(*self)}}-impl<T> TryClone for core::ptr::NonNull<T> {+impl<T> TryClone for core::ptr::NonNull<T>+where+ T: ?Sized,+{+ #[inline]+ fn try_clone(&self) -> Result<Self, OutOfMemory> {+ Ok(*self)+ }+}++impl<'a, T> TryClone for &'a T+where+ T: ?Sized,+{#[inline]fn try_clone(&self) -> Result<Self, OutOfMemory> {Ok(*self)@@ -73,6 +90,15 @@ tuples! {A, B, C, D, E, F, G, H, I, J;}+impl<T> TryClone for mem::ManuallyDrop<T>+where+ T: TryClone,+{+ fn try_clone(&self) -> Result<Self, OutOfMemory> {+ Ok(mem::ManuallyDrop::new((**self).try_clone()?))+ }+}+#[cfg(feature = "std")]impl_try_clone_via_clone! {std::hash::RandomStatediff --git a/crates/core/src/alloc/vec.rs b/crates/core/src/alloc/vec.rsindex 5c9f4366e2..835bdaaa06 100644--- a/crates/core/src/alloc/vec.rs+++ b/crates/core/src/alloc/vec.rs@@ -140,57 +140,67 @@ impl<T> Vec<T> {self.inner.drain(range)}- /// Same as [`std::vec::Vec::into_boxed_slice`].- pub fn into_boxed_slice(self) -> Result<Box<[T]>, OutOfMemory> {+ /// Same as [`std::vec::Vec::shrink_to_fit`] but returns an error on+ /// allocation failure.+ pub fn shrink_to_fit(&mut self) -> Result<(), OutOfMemory> {+ // If our length is already equal to our capacity, then there is nothing+ // to shrink.+ if self.len() == self.capacity() {+ return Ok(());+ }+// `realloc` requires a non-zero original layout as well as a non-zero// destination layout, so this guard ensures that the sizes below are- // all nonzero. This handles a few case:+ // all nonzero. This handles a few cases://// * If `len == cap == 0` then no allocation has ever been made.// * If `len == 0` and `cap != 0` then this function effectively frees// the memory.// * If `T` is a zero-sized type then nothing's been allocated either.- // * If `len == cap` then the allocation doesn't need to be shrunken.//// In all of these cases delegate to the standard library's- // `into_boxed_slice` which is guaranteed to not perform a `realloc`.- if self.is_empty() || mem::size_of::<T>() == 0 || self.inner.len() == self.inner.capacity()- {- return Ok(self.inner.into_boxed_slice());+ // `shrink_to_fit` which is guaranteed to not perform a `realloc`.+ if self.is_empty() || mem::size_of::<T>() == 0 {+ self.inner.shrink_to_fit();+ return Ok(());}- let (ptr, len, cap) = self.into_raw_parts();+ let (ptr, len, cap) = mem::take(self).into_raw_parts();let layout = Layout::array::<T>(cap).unwrap();- let new_len = Layout::array::<T>(len).unwrap().size();+ let new_size = Layout::array::<T>(len).unwrap().size();// SAFETY: `ptr` was previously allocated in the global allocator,// `layout` has a nonzero size and matches the current allocation of// `ptr`, `new_size` is nonzero, and `new_size` is a valid array size// for `len` elements given its constructor.- let result = unsafe { try_realloc(ptr.cast(), layout, new_len) };+ let result = unsafe { try_realloc(ptr.cast(), layout, new_size) };match result {Ok(ptr) => {- // SAFETY: `result` is allocated with the global allocator with- // an appropriate size/align to create this `Box` with.- unsafe {- Ok(Box::from_raw(core::ptr::slice_from_raw_parts_mut(- ptr.as_ptr().cast(),- len,- )))- }+ // SAFETY: `result` is allocated with the global allocator and+ // has room for exactly `[T; len]`.+ *self = unsafe { Self::from_raw_parts(ptr.cast::<T>().as_ptr(), len, len) };+ Ok(())}Err(oom) => {// SAFETY: If reallocation fails then it's guaranteed that the// original allocation is not tampered with, so it's safe to- // reassemble it back into the original vector.- unsafe {- let _ = Vec::from_raw_parts(ptr, len, cap);- }+ // reassemble the original vector.+ *self = unsafe { Vec::from_raw_parts(ptr, len, cap) };Err(oom)}}}++ /// Same as [`std::vec::Vec::into_boxed_slice`] but returns an error on+ /// allocation failure.+ pub fn into_boxed_slice(mut self) -> Result<Box<[T]>, OutOfMemory> {+ self.shrink_to_fit()?;++ // Once we've shrunken the allocation to just the actual length, we can+ // use `std`'s `into_boxed_slice` without fear of `realloc`.+ Ok(self.inner.into_boxed_slice())+ }}impl<T> Deref for Vec<T> {diff --git a/crates/fuzzing/tests/oom.rs b/crates/fuzzing/tests/oom.rsindex 8631965a41..8f25dcd7b8 100644--- a/crates/fuzzing/tests/oom.rs+++ b/crates/fuzzing/tests/oom.rs@@ -298,6 +298,60 @@ fn string_push_str() -> Result<()> {})}+#[test]+fn string_shrink_to_fit() -> Result<()> {+ OomTest::new().test(|| {+ // len == cap == 0+ let mut s = String::new();+ s.shrink_to_fit()?;++ // len == 0 < cap+ let mut s = String::with_capacity(4)?;+ s.shrink_to_fit()?;++ // 0 < len < cap+ let mut s = String::with_capacity(4)?;+ s.push('a')?;+ s.shrink_to_fit()?;++ // 0 < len == cap+ let mut s = String::new();+ s.reserve_exact(2)?;+ s.push('a')?;+ s.push('a')?;+ s.shrink_to_fit()?;++ Ok(())+ })+}++#[test]+fn string_into_boxed_str() -> Result<()> {+ OomTest::new().test(|| {+ // len == cap == 0+ let s = String::new();+ let _ = s.into_boxed_str()?;++ // len == 0 < cap+ let s = String::with_capacity(4)?;+ let _ = s.into_boxed_str()?;++ // 0 < len < cap+ let mut s = String::with_capacity(4)?;+ s.push('a')?;+ let _ = s.into_boxed_str()?;++ // 0 < len == cap+ let mut s = String::new();+ s.reserve_exact(2)?;+ s.push('a')?;+ s.push('a')?;+ let _ = s.into_boxed_str()?;++ Ok(())+ })+}+#[test]fn config_new() -> Result<()> {OomTest::new().test(|| {@@ -535,6 +589,47 @@ fn vec_and_boxed_slice() -> Result<()> {})}+#[test]+fn vec_shrink_to_fit() -> Result<()> {+ use wasmtime_core::alloc::Vec;++ #[derive(Default)]+ struct ZeroSized;++ #[derive(Default)]+ struct NonZeroSized {+ _unused: usize,+ }++ fn do_test<T: Default>() -> Result<()> {+ // len == cap == 0+ let mut v = Vec::<T>::new();+ v.shrink_to_fit()?;++ // len == 0 < cap+ let mut v = Vec::<T>::with_capacity(4)?;+ v.shrink_to_fit()?;++ // 0 < len < cap+ let mut v = Vec::with_capacity(4)?;+ v.push(T::default())?;+ v.shrink_to_fit()?;++ // 0 < len == cap+ let mut v = Vec::new();+ v.reserve_exact(2)?;+ v.push(T::default())?;+ v.push(T::default())?;+ v.shrink_to_fit()?;++ Ok(())+ }++ OomTest::new().test(|| do_test::<ZeroSized>())?;+ OomTest::new().test(|| do_test::<NonZeroSized>())?;+ Ok(())+}+#[test]fn vec_try_collect() -> Result<()> {OomTest::new().test(|| {diff --git a/crates/wasmtime/src/runtime.rs b/crates/wasmtime/src/runtime.rsindex e9417931a2..471e0daf46 100644--- a/crates/wasmtime/src/runtime.rs+++ b/crates/wasmtime/src/runtime.rs@@ -49,6 +49,7 @@ pub(crate) mod module;pub(crate) mod native_debug;pub(crate) mod resources;pub(crate) mod store;+pub(crate) mod string_pool;pub(crate) mod trampoline;pub(crate) mod trap;pub(crate) mod type_registry;diff --git a/crates/wasmtime/src/runtime/string_pool.rs b/crates/wasmtime/src/runtime/string_pool.rsnew file mode 100644index 0000000000..30db692127--- /dev/null+++ b/crates/wasmtime/src/runtime/string_pool.rs@@ -0,0 +1,237 @@+//! Simple string interning.++#![allow(unused, reason = "used in follow up commits")]++use crate::{error::OutOfMemory, prelude::*};+use core::{fmt, mem, num::NonZeroU32};+use wasmtime_core::alloc::TryClone;+use wasmtime_environ::collections::{HashMap, String, Vec};++/// A pool of interned strings.+///+/// Insert new strings with [`StringPool::insert`] to get an `Atom` that is+/// unique per string within the context of the associated pool.+///+/// Once you have interned a string into the pool and have its `Atom`, you can+/// get the interned string slice via `&pool[atom]` or `pool.get(atom)`.+///+/// In general, there are no correctness protections against indexing into a+/// different `StringPool` from the one that the `Atom` was not allocated+/// inside. Doing so is memory safe but may panic or otherwise return incorrect+/// results.+#[derive(Default)]+pub struct StringPool {+ /// A map from each string in this pool (as an unsafe borrow from+ /// `self.strings`) to its `Atom`.+ map: mem::ManuallyDrop<HashMap<&'static str, Atom>>,++ /// Strings in this pool. These must never be mutated or reallocated once+ /// inserted.+ strings: mem::ManuallyDrop<Vec<Box<str>>>,+}++impl Drop for StringPool {+ fn drop(&mut self) {+ // Ensure that `self.map` is dropped before `self.strings`, since+ // `self.map` borrows from `self.strings`.+ //+ // Safety: Neither field will be used again.+ unsafe {+ mem::ManuallyDrop::drop(&mut self.map);+ mem::ManuallyDrop::drop(&mut self.strings);+ }+ }+}++/// An interned string associated with a particular string in a `StringPool`.+///+/// Allows for $O(1)$ equality tests, $O(1)$ hashing, and $O(1)$+/// arbitrary-but-stable ordering.+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct Atom {+ index: NonZeroU32,+}++impl fmt::Debug for StringPool {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ struct Strings<'a>(&'a StringPool);+ impl fmt::Debug for Strings<'_> {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_map()+ .entries(+ self.0+ .strings+ .iter()+ .enumerate()+ .map(|(i, s)| (Atom::new(i), s)),+ )+ .finish()+ }+ }++ f.debug_struct("StringPool")+ .field("strings", &Strings(self))+ .finish()+ }+}++impl TryClone for StringPool {+ fn try_clone(&self) -> Result<Self, OutOfMemory> {+ Ok(StringPool {+ map: self.map.try_clone()?,+ strings: self.strings.try_clone()?,+ })+ }+}++impl TryClone for Atom {+ fn try_clone(&self) -> Result<Self, OutOfMemory> {+ Ok(*self)+ }+}++impl core::ops::Index<Atom> for StringPool {+ type Output = str;++ #[inline]+ #[track_caller]+ fn index(&self, atom: Atom) -> &Self::Output {+ self.get(atom).unwrap()+ }+}++impl StringPool {+ /// Create a new, empty pool.+ pub fn new() -> Self {+ Self::default()+ }++ /// Insert a new string into this pool.+ pub fn insert(&mut self, s: &str) -> Result<Atom, OutOfMemory> {+ if let Some(atom) = self.map.get(s) {+ return Ok(*atom);+ }++ self.map.reserve(1)?;+ self.strings.reserve(1)?;++ let mut owned = String::new();+ owned.reserve_exact(s.len())?;+ owned.push_str(s).expect("reserved capacity");+ let owned = owned+ .into_boxed_str()+ .expect("reserved exact capacity, so shouldn't need to realloc");++ let index = self.strings.len();+ let atom = Atom::new(index);+ self.strings.push(owned).expect("reserved capacity");++ // SAFETY: We never expose this borrow and never mutate or reallocate+ // strings once inserted into the pool.+ let s = unsafe { mem::transmute::<&str, &'static str>(&self.strings[index]) };++ let old = self.map.insert(s, atom).expect("reserved capacity");+ debug_assert!(old.is_none());++ Ok(atom)+ }++ /// Get the `Atom` for the given string, if it has already been inserted+ /// into this pool.+ pub fn get_atom(&self, s: &str) -> Option<Atom> {+ self.map.get(s).copied()+ }++ /// Does this pool contain the given `atom`?+ #[inline]+ pub fn contains(&self, atom: Atom) -> bool {+ atom.index() < self.strings.len()+ }++ /// Get the string associated with the given `atom`, if the pool contains+ /// the atom.+ #[inline]+ pub fn get(&self, atom: Atom) -> Option<&str> {+ if self.contains(atom) {+ Some(&self.strings[atom.index()])+ } else {+ None+ }+ }+}++impl fmt::Debug for Atom {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("Atom")+ .field("index", &self.index())+ .finish()+ }+}++impl Atom {+ fn new(index: usize) -> Self {+ assert!(index < usize::try_from(u32::MAX).unwrap());+ let index = u32::try_from(index).unwrap();+ let index = NonZeroU32::new(index + 1).unwrap();+ Self { index }+ }++ /// Get this atom's index in its pool.+ pub fn index(&self) -> usize {+ let index = self.index.get() - 1;+ usize::try_from(index).unwrap()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn basic() -> Result<()> {+ let mut pool = StringPool::new();++ let a = pool.insert("a")?;+ assert_eq!(&pool[a], "a");+ assert_eq!(pool.get_atom("a"), Some(a));++ let a2 = pool.insert("a")?;+ assert_eq!(a, a2);+ assert_eq!(&pool[a2], "a");++ let b = pool.insert("b")?;+ assert_eq!(&pool[b], "b");+ assert_ne!(a, b);+ assert_eq!(pool.get_atom("b"), Some(b));++ assert!(pool.get_atom("zzz").is_none());++ let mut pool2 = StringPool::new();+ let c = pool2.insert("c")?;+ assert_eq!(&pool2[c], "c");+ assert_eq!(a, c);+ assert_eq!(&pool2[a], "c");+ assert!(!pool2.contains(b));+ assert!(pool2.get(b).is_none());++ Ok(())+ }++ #[test]+ fn stress() -> Result<()> {+ let mut pool = StringPool::new();++ let n = if cfg!(miri) { 100 } else { 10_000 };++ for _ in 0..2 {+ let atoms: Vec<_> = (0..n).map(|i| pool.insert(&i.to_string())).try_collect()?;++ for atom in atoms {+ assert!(pool.contains(atom));+ assert_eq!(&pool[atom], atom.index().to_string());+ }+ }++ Ok(())+ }+}