wasmtime_internal_core/error/oom.rs
1use crate::error::{Error, OomOrDynError};
2use core::{fmt, mem, ptr::NonNull};
3
4/// An out-of-memory (OOM) error.
5///
6/// This error is the sentinel for allocation failure due to memory exhaustion.
7///
8/// Constructing an [`Error`] from an `OutOfMemory` does not allocate.
9///
10/// Allocation failure inside any `Error` method that must allocate
11/// (e.g. [`Error::context`]) will propagate an `OutOfMemory` error.
12///
13/// # Out-of-Memory Handling in Wasmtime
14///
15/// Wasmtime performs out-of-memory (OOM) error handling on a **best-effort
16/// basis**. OOM handling does _not_ have [tier 1
17/// support](https://docs.wasmtime.dev/stability-tiers.html) at this time and,
18/// therefore, while failure to handle OOM at some allocation site may be
19/// considered a bug, and might be a potential denial-of-service vector, it
20/// would not be considered a security vulnerability.[^limits]
21///
22/// [^limits]: Note that unconstrained guest-controlled resource usage is still
23/// considered a vulnerability. Wasmtime has tier 1 support for limiting guest
24/// resources, but not for handling OOMs within those limits.
25///
26/// ## Where Wasmtime Attempts to Handle OOM
27///
28/// It is important to note that **not all portions of Wasmtime attempt to
29/// handle out-of-memory errors**. Notably, Wasmtime only ever attempts to
30/// handle OOM in the core *runtime* and never in the *compiler*. No attempt is
31/// made to handle allocation failure in the middle of compiling new `Module`s
32/// or `Component`s from Wasm to machine code (or Pulley bytecode). However,
33/// Wasmtime will attempt to handle OOM when running *pre-compiled* Wasm code
34/// (loaded via `Module::deserialize` or `Component::deserialize`).
35///
36/// Wasmtime's interfaces allow *you* to handle OOM in your own embedding's WASI
37/// implementations and host APIs, but Wasmtime's provided WASI implementations
38/// (e.g. `wasmtime_wasi_http`) will generally not attempt to handle OOM (as
39/// they often depend on third-party crates that do not attempt to handle OOM).
40///
41/// The API documentation for individual functions and methods that handle OOM
42/// should generally document this fact by listing `OutOfMemory` as one of the
43/// potential errors returned.
44///
45/// | **Where** | **Handles OOM?** |
46/// |---------------------------------------------------|---------------------------------|
47/// | **Compiler** | **No** |
48/// |  `wasmtime::Module::new` | No |
49/// |  `wasmtime::Component::new` | No |
50/// |  `wasmtime::CodeBuilder` | No |
51/// |  Other compilation APIs... | No |
52/// | **Runtime** | **Yes** |
53/// |  `wasmtime::Store` | Yes |
54/// |  `wasmtime::Linker` | Yes |
55/// |  `wasmtime::Module::deserialize` | Yes |
56/// |  `wasmtime::Instance` | Yes |
57/// |  `wasmtime::Func::call` | Yes |
58/// |  Wasm execution | Yes |
59/// |  Garbage collector and related APIs | Not yet |
60/// |  Component Model concurrency/async APIs | Not yet |
61/// |  Other instantiation and execution APIs... | Yes |
62/// | **WASI Implementations and Host APIs** | **Depends** |
63/// |  `wasmtime_wasi` | No |
64/// |  `wasmtime_wasi_http` | No |
65/// |  `wasmtime_wasi_*` | No |
66/// |  Your embedding's APIs / WASI implementation | If *you* implement OOM handling |
67///
68/// If you encounter an unhandled OOM inside Wasmtime, and it is within a
69/// portion of code where it should be handled, then please [file an
70/// issue](https://github.com/bytecodealliance/wasmtime/issues/new/choose).
71///
72/// ## Handling More OOMs with Rust Nightly APIs
73///
74/// Rust's standard library provides fallible allocation APIs, or the necessary
75/// building blocks for making our own fallible allocation APIs, for some of its
76/// types and collections. For example, it provides `Vec::try_reserve` which can
77/// be used to build a fallible version of `Vec::push` and fallible `Box`
78/// allocation can be built upon raw allocations from the global allocator and
79/// `Box::from_raw`.
80///
81/// However, the standard library does not provide these things for all the
82/// types and collections that Wasmtime uses. Some of these APIs are completely
83/// missing (such as a fallible version of
84/// `std::collections::hash_map::VacantEntry::insert`) and some APIs exist but
85/// are feature-gated on unstable, nightly-only Rust features. The most relevant
86/// API from this latter category is
87/// [`Arc::try_new`](https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.try_new),
88/// as Wasmtime's runtime uses a number of `Arc`s under the covers.
89///
90/// If handling OOMs is important for your Wasmtime embedding, then you should
91/// compile Wasmtime from source using a Nightly Rust toolchain and with the
92/// `RUSTFLAGS="--cfg arc_try_new"` environment variable set. This unlocks
93/// Wasmtime's internal usage of `Arc::try_new`, making more OOM handling at
94/// more allocation sites possible.
95#[derive(Clone, Copy)]
96// NB: `OutOfMemory`'s representation must be the same as `OomOrDynError`
97// (and therefore also `Error`).
98#[repr(transparent)]
99pub struct OutOfMemory {
100 inner: NonNull<u8>,
101}
102
103// Safety: The `inner` pointer is not a real pointer, it is just bitpacked size
104// data.
105unsafe impl Send for OutOfMemory {}
106
107// Safety: The `inner` pointer is not a real pointer, it is just bitpacked size
108// data.
109unsafe impl Sync for OutOfMemory {}
110
111impl fmt::Debug for OutOfMemory {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 f.debug_struct("OutOfMemory")
114 .field(
115 "requested_allocation_size",
116 &self.requested_allocation_size(),
117 )
118 .finish()
119 }
120}
121
122impl fmt::Display for OutOfMemory {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 write!(
125 f,
126 "out of memory (failed to allocate {} bytes)",
127 self.requested_allocation_size()
128 )
129 }
130}
131
132impl core::error::Error for OutOfMemory {
133 #[inline]
134 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
135 None
136 }
137}
138
139impl OutOfMemory {
140 // NB: `OutOfMemory`'s representation must be the same as `OomOrDynError`
141 // (and therefore also `Error`).
142 const _SAME_SIZE_AS_OOM_OR_DYN_ERROR: () =
143 assert!(mem::size_of::<OutOfMemory>() == mem::size_of::<OomOrDynError>());
144 const _SAME_ALIGN_AS_OOM_OR_DYN_ERROR: () =
145 assert!(mem::align_of::<OutOfMemory>() == mem::align_of::<OomOrDynError>());
146 const _SAME_SIZE_AS_ERROR: () =
147 assert!(mem::size_of::<OutOfMemory>() == mem::size_of::<Error>());
148 const _SAME_ALIGN_AS_ERROR: () =
149 assert!(mem::align_of::<OutOfMemory>() == mem::align_of::<Error>());
150
151 /// Construct a new `OutOfMemory` error.
152 ///
153 /// The `requested_allocation_size` argument should be the size (in bytes)
154 /// of the associated allocation that was attempted and failed.
155 ///
156 /// This operation does not allocate.
157 ///
158 /// # Example
159 ///
160 /// ```rust
161 /// # use wasmtime_internal_core::error::OutOfMemory;
162 /// # extern crate alloc;
163 /// use alloc::alloc::{Layout, alloc};
164 /// use core::ptr::NonNull;
165 ///
166 /// /// Attempt to allocate a block of memory from the global allocator,
167 /// /// returning an `OutOfMemory` error on failure.
168 /// fn try_global_alloc(layout: Layout) -> Result<NonNull<u8>, OutOfMemory> {
169 /// if layout.size() == 0 {
170 /// return Ok(NonNull::dangling());
171 /// }
172 ///
173 /// // Safety: the layout's size is non-zero.
174 /// let ptr = unsafe { alloc(layout) };
175 ///
176 /// if let Some(ptr) = NonNull::new(ptr) {
177 /// Ok(ptr)
178 /// } else {
179 /// // The allocation failed, so return an `OutOfMemory` error,
180 /// // passing the attempted allocation's size into the `OutOfMemory`
181 /// // constructor.
182 /// Err(OutOfMemory::new(layout.size()))
183 /// }
184 /// }
185 /// ```
186 #[inline]
187 pub const fn new(requested_allocation_size: usize) -> Self {
188 Self {
189 inner: OomOrDynError::new_oom_ptr(requested_allocation_size),
190 }
191 }
192
193 /// Get the size (in bytes) of the associated allocation that was attempted
194 /// and which failed.
195 ///
196 /// Very large allocation sizes (near `isize::MAX` and larger) may be capped
197 /// to a maximum value.
198 ///
199 /// # Example
200 ///
201 /// ```rust
202 /// # use wasmtime_internal_core::error::OutOfMemory;
203 /// let oom = OutOfMemory::new(8192);
204 /// assert_eq!(oom.requested_allocation_size(), 8192);
205 /// ```
206 #[inline]
207 pub fn requested_allocation_size(&self) -> usize {
208 OomOrDynError::oom_size(self.inner)
209 }
210}
211
212impl From<OutOfMemory> for OomOrDynError {
213 fn from(oom: OutOfMemory) -> Self {
214 OomOrDynError::new_oom(oom.inner)
215 }
216}