Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Add fallible allocation methods to `cranelift_bitset::CompoundBitSet` (#12381)

Nick Fitzgerald233f1875e0ff
diff --git a/Cargo.lock b/Cargo.lock
index 238789180c..345059d465 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -743,6 +743,8 @@ dependencies = [
"arbitrary",
"serde",
"serde_derive",
+ "wasmtime-internal-core",
+ "wasmtime-internal-error",
]
[[package]]
@@ -4714,6 +4716,7 @@ dependencies = [
"wasmparser 0.244.0",
"wasmprinter",
"wasmtime-internal-component-util",
+ "wasmtime-internal-core",
"wasmtime-internal-error",
"wat",
]
@@ -4770,6 +4773,7 @@ version = "0.0.0"
dependencies = [
"arbitrary",
"backtrace",
+ "cranelift-bitset",
"env_logger 0.11.5",
"futures",
"indexmap 2.11.4",
@@ -4855,6 +4859,13 @@ dependencies = [
name = "wasmtime-internal-component-util"
version = "42.0.0"
+[[package]]
+name = "wasmtime-internal-core"
+version = "42.0.0"
+dependencies = [
+ "wasmtime-internal-error",
+]
+
[[package]]
name = "wasmtime-internal-cranelift"
version = "42.0.0"
diff --git a/Cargo.toml b/Cargo.toml
index 4d5d30807f..387c14ba6e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -158,6 +158,7 @@ members = [
"cranelift/serde",
"crates/bench-api",
"crates/c-api/artifact",
+ "crates/core",
"crates/environ/fuzz",
"crates/error",
"crates/misc/component-async-tests",
@@ -263,6 +264,7 @@ wasmtime-wast = { path = "crates/wast", version = "=42.0.0" }
# that these are internal unsupported crates for external use. These exist as
# part of the project organization of other public crates in Wasmtime and are
# otherwise not supported in terms of CVEs for example.
+wasmtime-core = { path = "crates/core", version = "=42.0.0", package = 'wasmtime-internal-core' }
wasmtime-error = { path = "crates/error", version = "=42.0.0", package = 'wasmtime-internal-error' }
wasmtime-wmemcheck = { path = "crates/wmemcheck", version = "=42.0.0", package = 'wasmtime-internal-wmemcheck' }
wasmtime-c-api-macros = { path = "crates/c-api-macros", version = "=42.0.0", package = 'wasmtime-internal-c-api-macros' }
diff --git a/cranelift/bitset/Cargo.toml b/cranelift/bitset/Cargo.toml
index d70c7408e4..10dabbab6c 100644
--- a/cranelift/bitset/Cargo.toml
+++ b/cranelift/bitset/Cargo.toml
@@ -16,6 +16,8 @@ workspace = true
arbitrary = { workspace = true, optional = true }
serde = { workspace = true, optional = true }
serde_derive = { workspace = true, optional = true }
+wasmtime-error = { workspace = true }
+wasmtime-core = { workspace = true }
[features]
enable-serde = ["dep:serde", "dep:serde_derive"]
diff --git a/cranelift/bitset/src/compound.rs b/cranelift/bitset/src/compound.rs
index 508a80126f..93a000d8bc 100644
--- a/cranelift/bitset/src/compound.rs
+++ b/cranelift/bitset/src/compound.rs
@@ -3,6 +3,7 @@
use crate::scalar::{self, ScalarBitSet, ScalarBitSetStorage};
use alloc::boxed::Box;
use core::{cmp, iter, mem};
+use wasmtime_error::OutOfMemory;
/// A large bit set backed by dynamically-sized storage.
///
@@ -83,6 +84,11 @@ impl<T: ScalarBitSetStorage> CompoundBitSet<T> {
///
/// The actual capacity reserved may be greater than that requested.
///
+ /// # Panics
+ ///
+ /// Panics on allocation failure. Use [`CompoundBitSet::try_with_capacity`]
+ /// to handle allocation failure.
+ ///
/// # Example
///
/// ```
@@ -95,9 +101,16 @@ impl<T: ScalarBitSetStorage> CompoundBitSet<T> {
/// ```
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
+ Self::try_with_capacity(capacity).unwrap()
+ }
+
+ /// Like [`CompoundBitSet::with_capacity`] but returns an error on
+ /// allocation failure.
+ #[inline]
+ pub fn try_with_capacity(capacity: usize) -> Result<Self, OutOfMemory> {
let mut bitset = Self::default();
- bitset.ensure_capacity(capacity);
- bitset
+ bitset.try_ensure_capacity(capacity)?;
+ Ok(bitset)
}
/// Get the number of elements in this bitset.
@@ -221,6 +234,11 @@ impl<T: ScalarBitSetStorage> CompoundBitSet<T> {
/// where `i < n` is guaranteed to succeed without growing the bitset's
/// backing storage.
///
+ /// # Panics
+ ///
+ /// Panics on allocation failure. Use
+ /// [`CompoundBitSet::try_ensure_capacity`] to handle allocation failure.
+ ///
/// # Example
///
/// ```
@@ -243,31 +261,53 @@ impl<T: ScalarBitSetStorage> CompoundBitSet<T> {
/// ```
#[inline]
pub fn ensure_capacity(&mut self, n: usize) {
+ self.try_ensure_capacity(n).unwrap()
+ }
+
+ /// Like [`CompoundBitSet::ensure_capacity`] but returns an error on
+ /// allocation failure.
+ #[inline]
+ pub fn try_ensure_capacity(&mut self, n: usize) -> Result<(), OutOfMemory> {
// Subtract one from the capacity to get the maximum bit that we might
// set. If `n` is 0 then nothing need be done as no capacity needs to be
// allocated.
let (word, _bit) = Self::word_and_bit(match n.checked_sub(1) {
- None => return,
+ None => return Ok(()),
Some(n) => n,
});
- if word >= self.elems.len() {
- assert!(word < usize::try_from(isize::MAX).unwrap());
- let delta = word - self.elems.len();
- let to_grow = delta + 1;
+ if word < self.elems.len() {
+ // Already have capacity.
+ return Ok(());
+ }
+
+ // Need to allocate additional capacity.
+
+ assert!(word < usize::try_from(isize::MAX).unwrap());
- // Amortize the cost of growing.
- let to_grow = cmp::max(to_grow, self.elems.len() * 2);
- // Don't make ridiculously small allocations.
- let to_grow = cmp::max(to_grow, 4);
+ let delta = word - self.elems.len();
+ let to_grow = delta + 1;
- let new_elems = self
- .elems
+ // Amortize the cost of growing by at least growing another
+ // `self.elems.len()`, so the new length is double the old length.
+ let to_grow = cmp::max(to_grow, self.elems.len());
+ // Don't make ridiculously small allocations.
+ let to_grow = cmp::max(to_grow, 4);
+
+ let new_len = self.elems.len() + to_grow;
+ match wasmtime_core::alloc::new_boxed_slice_from_iter(
+ new_len,
+ self.elems
.iter()
.copied()
- .chain(iter::repeat(ScalarBitSet::new()).take(to_grow))
- .collect::<Box<[_]>>();
- self.elems = new_elems;
+ .chain(iter::repeat(ScalarBitSet::new())),
+ ) {
+ Ok(new_elems) => {
+ self.elems = new_elems;
+ Ok(())
+ }
+ Err(wasmtime_core::alloc::BoxedSliceFromIterError::Oom(oom)) => Err(oom),
+ Err(wasmtime_core::alloc::BoxedSliceFromIterError::TooFewItems) => unreachable!(),
}
}
diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml
new file mode 100644
index 0000000000..baf65f36d2
--- /dev/null
+++ b/crates/core/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+authors.workspace = true
+description = "INTERNAL: Wasmtime's core utilities and helpers with minimal dependencies"
+edition.workspace = true
+license = "Apache-2.0 WITH LLVM-exception"
+name = "wasmtime-internal-core"
+rust-version.workspace = true
+version.workspace = true
+
+[dependencies]
+# This crate should have *very* minimal dependencies! Don't add new ones
+# lightly.
+wasmtime-error = { workspace = true }
+
+[lints]
+workspace = true
+
+[features]
diff --git a/crates/environ/build.rs b/crates/core/build.rs
similarity index 100%
rename from crates/environ/build.rs
rename to crates/core/build.rs
diff --git a/crates/core/src/alloc.rs b/crates/core/src/alloc.rs
new file mode 100644
index 0000000000..dbaad07fa5
--- /dev/null
+++ b/crates/core/src/alloc.rs
@@ -0,0 +1,30 @@
+//! Low-level allocation and OOM-handling utilities.
+
+mod arc;
+mod boxed;
+mod try_new;
+
+pub use boxed::{BoxedSliceFromIterError, new_boxed_slice_from_iter};
+pub use try_new::{TryNew, try_new};
+
+use core::{alloc::Layout, ptr::NonNull};
+use wasmtime_error::OutOfMemory;
+
+/// Try to allocate a block of memory that fits the given layout, or return an
+/// `OutOfMemory` error.
+///
+/// # Safety
+///
+/// Same as `alloc::alloc::alloc`: layout must have non-zero size.
+#[inline]
+unsafe fn try_alloc(layout: Layout) -> Result<NonNull<u8>, OutOfMemory> {
+ // Safety: same as our safety conditions.
+ debug_assert!(layout.size() > 0);
+ let ptr = unsafe { std_alloc::alloc::alloc(layout) };
+
+ if let Some(ptr) = NonNull::new(ptr) {
+ Ok(ptr)
+ } else {
+ Err(OutOfMemory::new(layout.size()))
+ }
+}
diff --git a/crates/core/src/alloc/arc.rs b/crates/core/src/alloc/arc.rs
new file mode 100644
index 0000000000..021a487ea2
--- /dev/null
+++ b/crates/core/src/alloc/arc.rs
@@ -0,0 +1,28 @@
+use super::TryNew;
+use std_alloc::sync::Arc;
+use wasmtime_error::OutOfMemory;
+
+/// XXX: Stable Rust doesn't actually give us any method to build fallible
+/// allocation for `Arc<T>`, so this is only actually fallible when using
+/// nightly Rust and setting `RUSTFLAGS="--cfg arc_try_new"`.
+impl<T> TryNew for Arc<T> {
+ type Value = T;
+
+ #[inline]
+ fn try_new(value: T) -> Result<Self, OutOfMemory>
+ where
+ Self: Sized,
+ {
+ #[cfg(arc_try_new)]
+ return Arc::try_new(value).map_err(|_| {
+ // We don't have access to the exact size of the inner `Arc`
+ // allocation, but (at least at one point) it was made up of a
+ // strong ref count, a weak ref count, and the inner value.
+ let bytes = core::mem::size_of::<(usize, usize, T)>();
+ OutOfMemory::new(bytes)
+ });
+
+ #[cfg(not(arc_try_new))]
+ return Ok(Arc::new(value));
+ }
+}
diff --git a/crates/core/src/alloc/boxed.rs b/crates/core/src/alloc/boxed.rs
new file mode 100644
index 0000000000..94f6db6e32
--- /dev/null
+++ b/crates/core/src/alloc/boxed.rs
@@ -0,0 +1,236 @@
+use super::{TryNew, try_alloc};
+use core::{alloc::Layout, mem::MaybeUninit};
+use std_alloc::boxed::Box;
+use wasmtime_error::OutOfMemory;
+
+/// Allocate an `Box<MaybeUninit<T>>` with uninitialized contents, returning
+/// `Err(OutOfMemory)` on allocation failure.
+///
+/// You can initialize the resulting box's value via [`Box::write`].
+#[inline]
+fn new_uninit_box<T>() -> Result<Box<MaybeUninit<T>>, OutOfMemory> {
+ let layout = Layout::new::<MaybeUninit<T>>();
+
+ if layout.size() == 0 {
+ // NB: no actual allocation takes place when boxing zero-sized
+ // types.
+ return Ok(Box::new(MaybeUninit::uninit()));
+ }
+
+ // Safety: layout size is non-zero.
+ let ptr = unsafe { try_alloc(layout)? };
+
+ let ptr = ptr.cast::<MaybeUninit<T>>();
+
+ // Safety: The pointer's memory block was allocated by the global allocator.
+ Ok(unsafe { Box::from_raw(ptr.as_ptr()) })
+}
+
+impl<T> TryNew for Box<T> {
+ type Value = T;
+
+ #[inline]
+ fn try_new(value: T) -> Result<Self, OutOfMemory>
+ where
+ Self: Sized,
+ {
+ let boxed = new_uninit_box::<T>()?;
+ Ok(Box::write(boxed, value))
+ }
+}
+
+fn new_uninit_boxed_slice<T>(len: usize) -> Result<Box<[MaybeUninit<T>]>, OutOfMemory> {
+ let layout = Layout::array::<MaybeUninit<T>>(len)
+ .map_err(|_| OutOfMemory::new(len.saturating_mul(core::mem::size_of::<T>())))?;
+
+ if layout.size() == 0 {
+ // NB: no actual allocation takes place when boxing zero-sized
+ // types.
+ return Ok(Box::new_uninit_slice(len));
+ }
+
+ // Safety: we just ensured that the new length is non-zero.
+ debug_assert_ne!(layout.size(), 0);
+ let ptr = unsafe { try_alloc(layout)? };
+
+ let ptr = ptr.cast::<MaybeUninit<T>>().as_ptr();
+ let ptr = core::ptr::slice_from_raw_parts_mut(ptr, len);
+
+ // Safety: `ptr` points to a memory block that is valid for
+ // `[MaybeUninit<T>; len]` and which was allocated by the global memory
+ // allocator.
+ let boxed = unsafe { Box::from_raw(ptr) };
+ Ok(boxed)
+}
+
+/// An error returned by [`new_boxed_slice_from_iter`].
+#[derive(Debug)]
+pub enum BoxedSliceFromIterError {
+ /// The iterator did not yield enough items to fill the boxed slice.
+ TooFewItems,
+ /// Failed to allocate space for the boxed slice.
+ Oom(OutOfMemory),
+}
+
+impl From<OutOfMemory> for BoxedSliceFromIterError {
+ fn from(oom: OutOfMemory) -> Self {
+ Self::Oom(oom)
+ }
+}
+
+impl core::fmt::Display for BoxedSliceFromIterError {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ match self {
+ BoxedSliceFromIterError::TooFewItems => {
+ f.write_str("The iterator did not yield enough items to fill the boxed slice")
+ }
+ BoxedSliceFromIterError::Oom(_) => {
+ f.write_str("Failed to allocate space for the boxed slice")
+ }
+ }
+ }
+}
+
+impl core::error::Error for BoxedSliceFromIterError {
+ fn cause(&self) -> Option<&dyn core::error::Error> {
+ match self {
+ BoxedSliceFromIterError::TooFewItems => None,
+ BoxedSliceFromIterError::Oom(oom) => Some(oom),
+ }
+ }
+}
+
+/// Create a `Box<[T]>` of length `len` from the given iterator's elements.
+///
+/// Returns an error on allocation failure, or if `iter` yields fewer than `len`
+/// elements.
+///
+/// The iterator is dropped after `len` elements have been yielded, this
+/// function does not check that the iterator yields exactly `len` elements.
+pub fn new_boxed_slice_from_iter<T>(
+ len: usize,
+ iter: impl IntoIterator<Item = T>,
+) -> Result<Box<[T]>, BoxedSliceFromIterError> {
+ /// RAII guard to handle dropping the initialized elements of the boxed
+ /// slice in the cases where we get too few items or the iterator panics.
+ struct DropGuard<T> {
+ boxed: Box<[MaybeUninit<T>]>,
+ init_len: usize,
+ }
+
+ impl<T> Drop for DropGuard<T> {
+ fn drop(&mut self) {
+ debug_assert!(self.init_len <= self.boxed.len());
+
+ if !core::mem::needs_drop::<T>() {
+ return;
+ }
+
+ for elem in self.boxed.iter_mut().take(self.init_len) {
+ // Safety: the elements in `self.boxed[..self.init_len]` are
+ // valid and initialized and will not be used again.
+ unsafe {
+ core::ptr::drop_in_place(elem.as_mut_ptr());
+ }
+ }
+ }
+ }
+
+ let mut guard = DropGuard {
+ boxed: new_uninit_boxed_slice(len)?,
+ init_len: 0,
+ };
+ assert_eq!(len, guard.boxed.len());
+
+ for (i, elem) in iter.into_iter().enumerate().take(len) {
+ debug_assert!(i < len);
+ debug_assert_eq!(guard.init_len, i);
+ guard.boxed[i].write(elem);
+ guard.init_len += 1;
+ }
+
+ debug_assert!(guard.init_len <= guard.boxed.len());
+
+ if guard.init_len < guard.boxed.len() {
+ return Err(BoxedSliceFromIterError::TooFewItems);
+ }
+
+ debug_assert_eq!(guard.init_len, guard.boxed.len());
+
+ // Take the boxed slice out of the guard.
+ let boxed = {
+ guard.init_len = 0;
+ let boxed = core::mem::take(&mut guard.boxed);
+ core::mem::forget(guard);
+ boxed
+ };
+
+ // Safety: we initialized all elements.
+ let boxed = unsafe { boxed.assume_init() };
+
+ Ok(boxed)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use core::cell::Cell;
+ use std_alloc::rc::Rc;
+
+ struct SetFlagOnDrop(Rc<Cell<bool>>);
+
+ impl Drop for SetFlagOnDrop {
+ fn drop(&mut self) {
+ let old_value = self.0.replace(true);
+ assert_eq!(old_value, false);
+ }
+ }
+
+ impl SetFlagOnDrop {
+ fn new() -> (Rc<Cell<bool>>, Self) {
+ let flag = Rc::new(Cell::new(false));
+ (flag.clone(), SetFlagOnDrop(flag))
+ }
+ }
+
+ #[test]
+ fn new_boxed_slice_from_iter_smoke_test() {
+ let slice = new_boxed_slice_from_iter(3, [42, 36, 1337]).unwrap();
+ assert_eq!(&*slice, &[42, 36, 1337]);
+ }
+
+ #[test]
+ fn new_boxed_slice_from_iter_with_too_few_elems() {
+ let (a_dropped, a) = SetFlagOnDrop::new();
+ let (b_dropped, b) = SetFlagOnDrop::new();
+ let (c_dropped, c) = SetFlagOnDrop::new();
+
+ match new_boxed_slice_from_iter(4, [a, b, c]) {
+ Err(BoxedSliceFromIterError::TooFewItems) => {}
+ Ok(_) | Err(BoxedSliceFromIterError::Oom(_)) => unreachable!(),
+ }
+
+ assert!(a_dropped.get());
+ assert!(b_dropped.get());
+ assert!(c_dropped.get());
+ }
+
+ #[test]
+ fn new_boxed_slice_from_iter_with_too_many_elems() {
+ let (a_dropped, a) = SetFlagOnDrop::new();
+ let (b_dropped, b) = SetFlagOnDrop::new();
+ let (c_dropped, c) = SetFlagOnDrop::new();
+
+ let slice = new_boxed_slice_from_iter(2, [a, b, c]).unwrap();
+
+ assert!(!a_dropped.get());
+ assert!(!b_dropped.get());
+ assert!(c_dropped.get());
+
+ drop(slice);
+
+ assert!(a_dropped.get());
+ assert!(b_dropped.get());
+ assert!(c_dropped.get());
+ }
+}
diff --git a/crates/core/src/alloc/try_new.rs b/crates/core/src/alloc/try_new.rs
new file mode 100644
index 0000000000..9c3487e37e
--- /dev/null
+++ b/crates/core/src/alloc/try_new.rs
@@ -0,0 +1,35 @@
+use wasmtime_error::OutOfMemory;
+
+/// Helper function to invoke `<T as TryNew>::try_new`.
+///
+/// # Example
+///
+/// ```
+/// # use wasmtime_internal_core::alloc::*;
+/// # use wasmtime_error::Result;
+/// # fn _foo() -> Result<()> {
+/// let boxed = try_new::<Box<u32>>(36)?;
+/// assert_eq!(*boxed, 36);
+/// # Ok(())
+/// # }
+/// ```
+#[inline]
+pub fn try_new<T>(value: T::Value) -> Result<T, OutOfMemory>
+where
+ T: TryNew,
+{
+ TryNew::try_new(value)
+}
+
+/// Extension trait providing fallible allocation for types like `Arc<T>` and
+/// `Box<T>.
+pub trait TryNew {
+ /// The inner `T` type that is getting wrapped into an `Arc<T>` or `Box<T>`.
+ type Value;
+
+ /// Allocate a new `Self`, returning `Err(OutOfMemory)` on allocation
+ /// failure.
+ fn try_new(value: Self::Value) -> Result<Self, OutOfMemory>
+ where
+ Self: Sized;
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
new file mode 100644
index 0000000000..be9b081271
--- /dev/null
+++ b/crates/core/src/lib.rs
@@ -0,0 +1,15 @@
+//! > **⚠️ Warning ⚠️**: this crate is an internal-only crate for the Wasmtime
+//! > project and is not intended for general use. APIs are not strictly
+//! > reviewed for safety and usage outside of Wasmtime may have bugs. If
+//! > you're interested in using this feel free to file an issue on the
+//! > Wasmtime repository to start a discussion about doing so, but otherwise
+//! > be aware that your usage of this crate is not supported.
+
+#![no_std]
+#![deny(missing_docs)]
+#![cfg_attr(arc_try_new, allow(unstable_features))]
+#![cfg_attr(arc_try_new, feature(allocator_api))]
+
+extern crate alloc as std_alloc;
+
+pub mod alloc;
diff --git a/crates/environ/Cargo.toml b/crates/environ/Cargo.toml
index 6ef18c016f..1cccb96322 100644
--- a/crates/environ/Cargo.toml
+++ b/crates/environ/Cargo.toml
@@ -35,6 +35,7 @@ target-lexicon = { workspace = true }
wasm-encoder = { workspace = true, optional = true }
wasmprinter = { workspace = true, optional = true }
wasmtime-component-util = { workspace = true, optional = true }
+wasmtime-core = { workspace = true }
wasmtime-error = { workspace = true }
semver = { workspace = true, optional = true, features = ['serde'] }
smallvec = { workspace = true, features = ['serde'] }
diff --git a/crates/environ/src/collections.rs b/crates/environ/src/collections.rs
index af750772b5..50dae01cab 100644
--- a/crates/environ/src/collections.rs
+++ b/crates/environ/src/collections.rs
@@ -1,120 +1,3 @@
//! Fallible, OOM-handling collections.
-use crate::error::OutOfMemory;
-use alloc::{boxed::Box, sync::Arc};
-use core::{alloc::Layout, mem::MaybeUninit, ptr::NonNull};
-
-/// Helper function to invoke `<T as TryNew>::try_new`.
-///
-/// # Example
-///
-/// ```
-/// # use wasmtime_environ::prelude::*;
-/// # fn _foo() -> Result<()> {
-/// use wasmtime_environ::collections::try_new;
-///
-/// let boxed = try_new::<Box<u32>>(36)?;
-/// assert_eq!(*boxed, 36);
-/// # Ok(())
-/// # }
-/// ```
-#[inline]
-pub fn try_new<T>(value: T::Value) -> Result<T, OutOfMemory>
-where
- T: TryNew,
-{
- TryNew::try_new(value)
-}
-
-/// Extension trait providing fallible allocation for types like `Arc<T>` and
-/// `Box<T>.
-pub trait TryNew {
- /// The inner `T` type that is getting wrapped into an `Arc<T>` or `Box<T>`.
- type Value;
-
- /// Allocate a new `Self`, returning `Err(OutOfMemory)` on allocation
- /// failure.
- fn try_new(value: Self::Value) -> Result<Self, OutOfMemory>
- where
- Self: Sized;
-}
-
-/// Try to allocate a block of memory that fits the given layout, or return an
-/// `OutOfMemory` error.
-///
-/// # Safety
-///
-/// Same as `alloc::alloc::alloc`: layout must have non-zero size.
-#[inline]
-unsafe fn try_alloc(layout: Layout) -> Result<NonNull<u8>, OutOfMemory> {
- // Safety: same as our safety conditions.
- debug_assert!(layout.size() > 0);
- let ptr = unsafe { alloc::alloc::alloc(layout) };
-
- if let Some(ptr) = NonNull::new(ptr) {
- Ok(ptr)
- } else {
- Err(OutOfMemory::new(layout.size()))
- }
-}
-
-/// Allocate an `Box<MaybeUninit<T>>` with uninitialized contents, returning
-/// `Err(OutOfMemory)` on allocation failure.
-///
-/// You can initialize the resulting box's value via [`Box::write`].
-#[inline]
-fn new_uninit_box<T>() -> Result<Box<MaybeUninit<T>>, OutOfMemory> {
- let layout = alloc::alloc::Layout::new::<MaybeUninit<T>>();
-
- if layout.size() == 0 {
- // NB: no actual allocation takes place when boxing zero-sized
- // types.
- return Ok(Box::new(MaybeUninit::uninit()));
- }
-
- // Safety: layout size is non-zero.
- let ptr = unsafe { try_alloc(layout)? };
-
- let ptr = ptr.cast::<MaybeUninit<T>>();
-
- // Safety: The pointer's memory block was allocated by the global allocator.
- Ok(unsafe { Box::from_raw(ptr.as_ptr()) })
-}
-
-impl<T> TryNew for Box<T> {
- type Value = T;
-
- #[inline]
- fn try_new(value: T) -> Result<Self, OutOfMemory>
- where
- Self: Sized,
- {
- let boxed = new_uninit_box::<T>()?;
- Ok(Box::write(boxed, value))
- }
-}
-
-/// XXX: Stable Rust doesn't actually give us any method to build fallible
-/// allocation for `Arc<T>`, so this is only actually fallible when using
-/// nightly Rust and setting `RUSTFLAGS="--cfg arc_try_new"`.
-impl<T> TryNew for Arc<T> {
- type Value = T;
-
- #[inline]
- fn try_new(value: T) -> Result<Self, OutOfMemory>
- where
- Self: Sized,
- {
- #[cfg(arc_try_new)]
- return Arc::try_new(value).map_err(|_| {
- // We don't have access to the exact size of the inner `Arc`
- // allocation, but (at least at one point) it was made up of a
- // strong ref count, a weak ref count, and the inner value.
- let bytes = core::mem::size_of::<(usize, usize, T)>();
- OutOfMemory::new(bytes)
- });
-
- #[cfg(not(arc_try_new))]
- return Ok(Arc::new(value));
- }
-}
+pub use wasmtime_core::alloc::{TryNew, try_new};
diff --git a/crates/environ/src/lib.rs b/crates/environ/src/lib.rs
index 0c3e155352..2694f78b6b 100644
--- a/crates/environ/src/lib.rs
+++ b/crates/environ/src/lib.rs
@@ -10,8 +10,6 @@
#![deny(missing_docs)]
#![warn(clippy::cast_sign_loss)]
#![no_std]
-#![cfg_attr(arc_try_new, allow(unstable_features))]
-#![cfg_attr(arc_try_new, feature(allocator_api))]
#[cfg(feature = "std")]
#[macro_use]
diff --git a/crates/fuzzing/Cargo.toml b/crates/fuzzing/Cargo.toml
index 94984817f1..ad631c6cc4 100644
--- a/crates/fuzzing/Cargo.toml
+++ b/crates/fuzzing/Cargo.toml
@@ -71,6 +71,7 @@ v8 = "139.0.0"
wat = { workspace = true }
rand = { version = "0.8.0", features = ["small_rng"] }
wasmtime-environ = { workspace = true }
+cranelift-bitset = { workspace = true }
# Only enable the `build-libinterpret` feature when fuzzing is enabled, enabling
# commands like `cargo test --workspace` or similar to not need an ocaml
diff --git a/crates/fuzzing/tests/oom.rs b/crates/fuzzing/tests/oom.rs
index b5ddb62905..1ba6b91b0b 100644
--- a/crates/fuzzing/tests/oom.rs
+++ b/crates/fuzzing/tests/oom.rs
@@ -1,3 +1,4 @@
+use cranelift_bitset::CompoundBitSet;
use std::{
alloc::{Layout, alloc},
fmt::{self, Write},
@@ -50,6 +51,23 @@ fn try_new_box() -> Result<()> {
})
}
+#[test]
+fn compound_bit_set_try_with_capacity() -> Result<()> {
+ OomTest::new().test(|| {
+ let _bitset = CompoundBitSet::<usize>::try_with_capacity(32)?;
+ Ok(())
+ })
+}
+
+#[test]
+fn compound_bit_set_try_ensure_capacity() -> Result<()> {
+ OomTest::new().test(|| {
+ let mut bitset = CompoundBitSet::new();
+ bitset.try_ensure_capacity(100)?;
+ Ok(())
+ })
+}
+
#[test]
fn config_new() -> Result<()> {
OomTest::new().test(|| {
diff --git a/scripts/publish.rs b/scripts/publish.rs
index c418760cf3..91c94ee21f 100644
--- a/scripts/publish.rs
+++ b/scripts/publish.rs
@@ -18,6 +18,8 @@ use std::time::Duration;
// note that this list must be topologically sorted by dependencies
const CRATES_TO_PUBLISH: &[&str] = &[
// pulley
+ "wasmtime-internal-error",
+ "wasmtime-internal-core",
"cranelift-bitset",
"wasmtime-internal-math",
"pulley-macros",
@@ -40,7 +42,6 @@ const CRATES_TO_PUBLISH: &[&str] = &[
"cranelift-native",
"cranelift-object",
"cranelift-interpreter",
- "wasmtime-internal-error",
"wasmtime-internal-component-util",
"wasmtime-environ",
"wasmtime-internal-jit-icache-coherence",