xref: /wasmtime-44.0.1/crates/fuzzing/src/oom.rs (revision e4e9cabe)
1 //! Utilities for testing and fuzzing out-of-memory handling.
2 //!
3 //! Inspired by SpiderMonkey's `oomTest()` helper:
4 //! https://firefox-source-docs.mozilla.org/js/hacking_tips.html#how-to-debug-oomtest-failures
5 
6 use backtrace::Backtrace;
7 use std::{alloc::GlobalAlloc, cell::Cell, mem, ptr, time};
8 use wasmtime_error::{Error, OutOfMemory, Result, bail};
9 
10 /// An allocator for use with `OomTest`.
11 #[non_exhaustive]
12 pub struct OomTestAllocator;
13 
14 impl OomTestAllocator {
15     /// Create a new OOM test allocator.
16     pub const fn new() -> Self {
17         OomTestAllocator
18     }
19 }
20 
21 #[derive(Clone, Debug, Default, PartialEq, Eq)]
22 enum OomState {
23     /// We are in code that is not part of an OOM test.
24     #[default]
25     OutsideOomTest,
26 
27     /// We are inside an OOM test and should inject an OOM when the counter
28     /// reaches zero.
29     OomOnAlloc(u32),
30 
31     /// We are inside an OOM test and we already injected an OOM.
32     DidOom,
33 }
34 
35 thread_local! {
36     static OOM_STATE: Cell<OomState> = const { Cell::new(OomState::OutsideOomTest) };
37 }
38 
39 /// Set the new OOM state, returning the old state.
40 fn set_oom_state(state: OomState) -> OomState {
41     OOM_STATE.with(|s| s.replace(state))
42 }
43 
44 /// RAII helper to set the OOM state within a block of code and reset it upon
45 /// exiting that block (even if exiting via panic unwinding).
46 struct ScopedOomState {
47     prev_state: OomState,
48 }
49 
50 impl ScopedOomState {
51     fn new(state: OomState) -> Self {
52         ScopedOomState {
53             prev_state: set_oom_state(state),
54         }
55     }
56 
57     /// Finish this OOM state scope early, resetting the OOM state to what it
58     /// was before this scope was created, and returning the previous state that
59     /// was just overwritten by the reset.
60     fn finish(&self) -> OomState {
61         set_oom_state(self.prev_state.clone())
62     }
63 }
64 
65 impl Drop for ScopedOomState {
66     fn drop(&mut self) {
67         set_oom_state(mem::take(&mut self.prev_state));
68     }
69 }
70 
71 unsafe impl GlobalAlloc for OomTestAllocator {
72     unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 {
73         let old_state = set_oom_state(OomState::OutsideOomTest);
74 
75         let new_state;
76         let ptr;
77         {
78             // NB: It's okay to log/backtrace/etc... in this block because the
79             // current state is `OutsideOomTest`, so any re-entrant allocations
80             // will be passed through to the system allocator.
81 
82             match old_state {
83                 OomState::OutsideOomTest => {
84                     new_state = OomState::OutsideOomTest;
85                     ptr = unsafe { std::alloc::System.alloc(layout) };
86                 }
87                 OomState::OomOnAlloc(0) => {
88                     log::trace!(
89                         "injecting OOM for allocation: {layout:?}\nAllocation backtrace:\n{:?}",
90                         Backtrace::new(),
91                     );
92                     new_state = OomState::DidOom;
93                     ptr = ptr::null_mut();
94                 }
95                 OomState::OomOnAlloc(c) => {
96                     new_state = OomState::OomOnAlloc(c - 1);
97                     ptr = unsafe { std::alloc::System.alloc(layout) };
98                 }
99                 OomState::DidOom => {
100                     log::trace!(
101                         "Attempt to allocate {layout:?} after OOM:\n{:?}",
102                         Backtrace::new(),
103                     );
104                     panic!("OOM test attempted to allocate after OOM: {layout:?}")
105                 }
106             }
107         }
108 
109         set_oom_state(new_state);
110         ptr
111     }
112 
113     unsafe fn dealloc(&self, ptr: *mut u8, layout: std::alloc::Layout) {
114         unsafe {
115             std::alloc::System.dealloc(ptr, layout);
116         }
117     }
118 }
119 
120 /// A test helper that checks that some code handles OOM correctly.
121 ///
122 /// `OomTest` will only work correctly when `OomTestAllocator` is configured as
123 /// the global allocator.
124 ///
125 /// `OomTest` does not support reentrancy, so you cannot run an `OomTest` within
126 /// an `OomTest`.
127 ///
128 /// # Example
129 ///
130 /// ```no_run
131 /// use std::time::Duration;
132 /// use wasmtime::Result;
133 /// use wasmtime_fuzzing::oom::{OomTest, OomTestAllocator};
134 ///
135 /// #[global_allocator]
136 /// static GLOBAL_ALOCATOR: OomTestAllocator = OomTestAllocator::new();
137 ///
138 /// #[test]
139 /// fn my_oom_test() -> Result<()> {
140 ///     OomTest::new()
141 ///         .max_iters(1_000_000)
142 ///         .max_duration(Duration::from_secs(5))
143 ///         .test(|| {
144 ///             todo!("insert code here that should handle OOM here...")
145 ///         })
146 /// }
147 /// ```
148 pub struct OomTest {
149     max_iters: Option<u32>,
150     max_duration: Option<time::Duration>,
151 }
152 
153 impl OomTest {
154     /// Create a new OOM test.
155     ///
156     /// By default there is no iteration or time limit, tests will be executed
157     /// until the pass (or fail).
158     pub fn new() -> Self {
159         let _ = env_logger::try_init();
160 
161         // NB: `std::backtrace::Backtrace` doesn't have ways to handle
162         // OOM. Ideally we would just disable the `"backtrace"` cargo feature,
163         // but workspace feature resolution doesn't play nice with that.
164         wasmtime_error::disable_backtrace();
165 
166         OomTest {
167             max_iters: None,
168             max_duration: None,
169         }
170     }
171 
172     /// Configure the maximum number of times to run an OOM test.
173     pub fn max_iters(&mut self, max_iters: u32) -> &mut Self {
174         self.max_iters = Some(max_iters);
175         self
176     }
177 
178     /// Configure the maximum duration of time to run an OOM text.
179     pub fn max_duration(&mut self, max_duration: time::Duration) -> &mut Self {
180         self.max_duration = Some(max_duration);
181         self
182     }
183 
184     /// Repeatedly run the given test function, injecting OOMs at different
185     /// times and checking that it correctly handles them.
186     ///
187     /// The test function should not use threads, or else allocations may not be
188     /// tracked correctly and OOM injection may be incorrect.
189     ///
190     /// The test function should return an `Err(_)` if and only if it encounters
191     /// an OOM.
192     ///
193     /// Returns early once the test function returns `Ok(())` before an OOM has
194     /// been injected.
195     pub fn test(&self, test_func: impl Fn() -> Result<()>) -> Result<()> {
196         let start = time::Instant::now();
197 
198         for i in 0.. {
199             if self.max_iters.is_some_and(|n| i >= n)
200                 || self.max_duration.is_some_and(|d| start.elapsed() >= d)
201             {
202                 break;
203             }
204 
205             log::trace!("=== Injecting OOM after {i} allocations ===");
206             let (result, old_state) = {
207                 let guard = ScopedOomState::new(OomState::OomOnAlloc(i));
208                 assert_eq!(guard.prev_state, OomState::OutsideOomTest);
209 
210                 let result = test_func();
211 
212                 (result, guard.finish())
213             };
214 
215             match (result, old_state) {
216                 (_, OomState::OutsideOomTest) => unreachable!(),
217 
218                 // The test function completed successfully before we ran out of
219                 // allocation fuel, so we're done.
220                 (Ok(()), OomState::OomOnAlloc(_)) => break,
221 
222                 // We injected an OOM and the test function handled it
223                 // correctly; continue to the next iteration.
224                 (Err(e), OomState::DidOom) if self.is_oom_error(&e) => {}
225 
226                 // Missed OOMs.
227                 (Ok(()), OomState::DidOom) => {
228                     bail!("OOM test function missed an OOM: returned Ok(())");
229                 }
230                 (Err(e), OomState::DidOom) => {
231                     return Err(
232                         e.context("OOM test function missed an OOM: returned non-OOM error")
233                     );
234                 }
235 
236                 // Unexpected error.
237                 (Err(e), OomState::OomOnAlloc(_)) => {
238                     return Err(
239                         e.context("OOM test function returned an error when there was no OOM")
240                     );
241                 }
242             }
243         }
244 
245         Ok(())
246     }
247 
248     fn is_oom_error(&self, e: &Error) -> bool {
249         e.is::<OutOfMemory>()
250     }
251 }
252