Skip to main content

wasmtime/runtime/rr/
enabled.rs

1use crate::prelude::*;
2use crate::runtime::vm::VMFuncRef;
3use crate::store::StoreOpaque;
4use crate::{AsContextMut, Engine, Func, Memory, Store, ValRaw};
5use core::ops::Range;
6use core::ptr::NonNull;
7use wasmtime_environ::RrCallKind;
8
9mod codec;
10mod init;
11mod objects;
12
13use codec::{Kind, Reader};
14use objects::{Objects, RecordedCall, RecordedFunc, RecordedMemory};
15
16/// The call ID with which `rr_enter` reports a call that is not recorded.
17const NOT_RECORDED: u32 = u32::MAX;
18
19/// The SHA-256 checksum of a core module's bytecode, by which traces
20/// identify the modules they instantiate.
21pub type Checksum = [u8; 32];
22
23/// Returns the core modules that `engine` compiles from `wasm`, with their
24/// checksums. `wasm` is a core module, in the binary or (with the `wat`
25/// feature) text format, which is returned as is.
26///
27/// A trace refers to the modules it instantiates by these checksums, so this
28/// can be used to find or package the bytecode that replaying it requires.
29pub fn core_modules(engine: &crate::Engine, wasm: &[u8]) -> Result<Vec<(Checksum, Vec<u8>)>> {
30    #[cfg(feature = "wat")]
31    let parsed = wat::parse_bytes(wasm).map_err(|e| format_err!("{e}"))?;
32    #[cfg(feature = "wat")]
33    let wasm = &*parsed;
34    let checksum = |wasm: &[u8]| *wasmtime_environ::WasmChecksum::from_binary(wasm, true);
35    if !wasmparser::Parser::is_component(wasm) {
36        return Ok(vec![(checksum(wasm), wasm.to_vec())]);
37    }
38    let _ = engine;
39    bail!("record/replay does not support components")
40}
41
42/// Formats a checksum as hexadecimal, as in file names and messages.
43pub fn checksum_hex(checksum: &Checksum) -> String {
44    checksum.iter().map(|b| format!("{b:02x}")).collect()
45}
46
47/// A complete execution trace, including object construction and startup.
48///
49/// Traces refer to the modules they instantiate only by [`Checksum`]; see
50/// [`Trace::module_checksums`].
51pub struct Trace {
52    bytes: Vec<u8>,
53}
54
55impl Trace {
56    /// Returns the serialized trace.
57    pub fn as_bytes(&self) -> &[u8] {
58        &self.bytes
59    }
60
61    /// Takes ownership of a serialized trace, checking its version. Its
62    /// contents are checked as they are read, such as during replay.
63    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
64        let mut reader = Reader::new(&bytes);
65        ensure!(
66            reader.take(codec::MAGIC.len())? == codec::MAGIC,
67            "unsupported record/replay trace version"
68        );
69        Ok(Self { bytes })
70    }
71
72    /// Returns the checksums of the core modules that the trace instantiates,
73    /// in the order in which they are first instantiated, without duplicates.
74    /// Replaying the trace requires their bytecode.
75    ///
76    /// This reads the whole trace, and fails if it is truncated or otherwise
77    /// malformed.
78    pub fn module_checksums(&self) -> Result<Vec<Checksum>> {
79        let mut reader = Reader::new(&self.bytes);
80        reader.take(codec::MAGIC.len())?;
81        let mut checksums = Vec::new();
82        loop {
83            let (tag, mut body) = reader.record()?;
84            match tag {
85                codec::END => {
86                    body.end()?;
87                    reader.end()?;
88                    return Ok(checksums);
89                }
90                codec::MODULE => {
91                    body.u32()?;
92                    let checksum = body.checksum()?;
93                    if !checksums.contains(&checksum) {
94                        checksums.push(checksum);
95                    }
96                }
97                _ => {}
98            }
99        }
100    }
101}
102
103#[derive(Default)]
104pub(crate) struct State {
105    session: Option<Box<Session>>,
106}
107
108struct Session {
109    objects: Objects,
110    mode: Mode,
111    /// Memory ranges that the host may have written since the last flush.
112    dirty_ranges: TryVec<DirtyRange>,
113    failure: Option<Error>,
114}
115
116/// A range of a memory that the host may have written, through the memory
117/// APIs, since the last flush.
118///
119/// The APIs hand out `&mut [u8]` slices, so individual writes are invisible to
120/// the recorder: it notes the ranges that were made writable instead, and at
121/// the next point at which the guest could observe memory (see
122/// `StoreOpaque::rr_flush`) records their contents at that point.
123struct DirtyRange {
124    memory: RecordedMemory,
125    /// The byte range within that memory.
126    bytes: Range<usize>,
127}
128
129enum Mode {
130    Recording {
131        bytes: TryVec<u8>,
132        // Calls, and the called functions, that have not yet returned.
133        outstanding: TryVec<(RecordedCall, RecordedFunc)>,
134        next_call: u32,
135    },
136}
137
138impl State {
139    pub(crate) fn active(&self) -> bool {
140        self.session.is_some()
141    }
142
143    pub(crate) fn recording(&self) -> bool {
144        matches!(
145            self.session.as_deref().map(|s| &s.mode),
146            Some(Mode::Recording { .. })
147        )
148    }
149
150    /// Records that an active session cannot represent `operation`, which
151    /// still takes place. The recording can then only be discarded.
152    pub(crate) fn poison(&mut self, operation: &'static str) {
153        if let Some(session) = &mut self.session {
154            session.fail(format_err!("record/replay does not support {operation}"));
155        }
156    }
157
158    /// Like `poison`, but also fails the operation.
159    pub(crate) fn reject(&mut self, operation: &'static str) -> Result<()> {
160        if self.active() {
161            self.poison(operation);
162            bail!("record/replay does not support {operation}");
163        }
164        Ok(())
165    }
166}
167
168impl Session {
169    /// Keeps the first failure of a session; later ones are its consequences.
170    fn fail(&mut self, error: Error) {
171        self.failure.get_or_insert(error);
172    }
173
174    /// Appends a complete record when recording.
175    fn append(&mut self, tag: u8, body: &[u8]) -> Result<()> {
176        let Mode::Recording { bytes, .. } = &mut self.mode;
177        codec::record(bytes, tag, body.len())?;
178        bytes.extend_from_slice(body)?;
179        Ok(())
180    }
181}
182
183fn validate_recording_engine(engine: &Engine) -> Result<()> {
184    ensure!(
185        engine.is_recording(),
186        "recording requires RrConfig::Recording"
187    );
188    // A debug handler could run arbitrary host code that the trace does not
189    // record.
190    ensure!(
191        !engine.tunables().debug_guest,
192        "record/replay does not support recording with guest debugging"
193    );
194    ensure!(
195        !engine
196            .features()
197            .contains(wasmparser::WasmFeatures::STACK_SWITCHING),
198        "record/replay does not support Wasm stack switching"
199    );
200    Ok(())
201}
202
203impl<T: 'static> Store<T> {
204    /// Creates a store that records its execution, including object
205    /// construction and startup, until [`Store::finish_recording`].
206    ///
207    /// See [`crate::rr`] for the restrictions on the recorded execution.
208    ///
209    /// # Errors
210    ///
211    /// Returns an error if `engine` is not configured with
212    /// [`crate::RrConfig::Recording`], if its configuration is incompatible
213    /// with recording, or on allocation failure.
214    pub fn new_recording(engine: &Engine, data: T) -> Result<Self> {
215        validate_recording_engine(engine)?;
216        let mut bytes = TryVec::new();
217        bytes.extend_from_slice(codec::MAGIC)?;
218        let session = try_new::<Box<_>>(Session {
219            objects: Objects::default(),
220            mode: Mode::Recording {
221                bytes,
222                outstanding: TryVec::new(),
223                next_call: 0,
224            },
225            dirty_ranges: TryVec::new(),
226            failure: None,
227        })?;
228        let mut this = Store::try_new(engine, data)?;
229        let store = this.as_context_mut().0;
230        store.rr.session = Some(session);
231        store.vm_store_context_mut().recording = 1;
232        Ok(this)
233    }
234
235    /// Finishes a recording, flushing pending memory writes. Returns an error
236    /// for a poisoned recording; such a trace cannot be replayed. A failed
237    /// recording is discarded and recording is disabled on the store.
238    ///
239    /// A recording may end while guest calls are unfinished, for example
240    /// after a host panic.
241    pub fn finish_recording(&mut self) -> Result<Trace> {
242        let store = self.as_context_mut().0;
243        ensure!(store.rr.recording(), "store is not recording");
244        let flushed = store.rr_flush();
245        let session = store.rr.session.take().unwrap();
246        store.vm_store_context_mut().recording = 0;
247        if let Some(e) = session.failure {
248            return Err(e);
249        }
250        flushed?;
251        let Mode::Recording { mut bytes, .. } = session.mode;
252        codec::record(&mut bytes, codec::END, 0)?;
253        Ok(Trace {
254            bytes: bytes.into(),
255        })
256    }
257}
258
259impl StoreOpaque {
260    fn rr_session(&mut self) -> &mut Session {
261        self.rr.session.as_deref_mut().unwrap()
262    }
263
264    /// Poisons an active session if recording failed, so that the trace can
265    /// never be finalized with a partial record or a missing effect.
266    fn rr_poison_on_err<R>(&mut self, result: Result<R>) -> Result<R> {
267        if let (Err(e), Some(session)) = (&result, &mut self.rr.session) {
268            session.fail(format_err!("failed to record execution: {e}"));
269        }
270        result
271    }
272
273    /// The ID of a memory written by the host, poisoning the recording if
274    /// the memory was never registered.
275    fn rr_memory_id(&mut self, memory: Memory) -> Option<RecordedMemory> {
276        let id = self
277            .rr
278            .session
279            .as_ref()
280            .unwrap()
281            .objects
282            .find_memory(self, memory);
283        if id.is_none() {
284            self.rr_session()
285                .fail(format_err!("host modified an unregistered memory"));
286        }
287        id
288    }
289
290    pub(crate) fn rr_memory_grown(&mut self, memory: Memory) -> Result<()> {
291        if !self.rr.recording() {
292            return Ok(());
293        }
294        let Some(id) = self.rr_memory_id(memory) else {
295            bail!("host grew an unregistered memory");
296        };
297        let new_size = memory.internal_data_size(self);
298        let result = (|| {
299            let mut body = [0; 12];
300            body[..4].copy_from_slice(&id.as_u32().to_le_bytes());
301            body[4..].copy_from_slice(&u64::try_from(new_size)?.to_le_bytes());
302            self.rr_session().append(codec::RESIZE, &body)
303        })();
304        self.rr_poison_on_err(result)
305    }
306
307    fn rr_check(&self) -> Result<()> {
308        if let Some(session) = &self.rr.session {
309            ensure!(
310                session.failure.is_none(),
311                "recording has failed; discard it with finish_recording"
312            );
313        }
314        Ok(())
315    }
316
317    /// Records the contents of the memory ranges that the host may have
318    /// written since the last flush (including through forgotten guards).
319    ///
320    /// This runs while the store is exclusively borrowed and before the guest
321    /// can observe memory again: at every call or return between the host and
322    /// Wasm, and when the recording finishes.
323    pub(crate) fn rr_flush(&mut self) -> Result<()> {
324        self.rr_check()?;
325        if !self.rr.recording() {
326            return Ok(());
327        }
328        let result = self.rr_flush_writes();
329        self.rr_poison_on_err(result)
330    }
331
332    fn rr_flush_writes(&mut self) -> Result<()> {
333        // Detach the dirty ranges and the trace while reading memories; this
334        // never runs guest or embedder code.
335        let session = self.rr_session();
336        let mut dirty = core::mem::take(&mut session.dirty_ranges);
337        let Mode::Recording { bytes, .. } = &mut session.mode;
338        let mut bytes = core::mem::take(bytes);
339        // Merge overlapping and adjacent ranges, so that each byte is recorded
340        // once. Sorting enables the merge and does not change the trace's
341        // meaning: the merged ranges are disjoint, and each record carries the
342        // range's current contents.
343        dirty.sort_unstable_by_key(|r| (r.memory, r.bytes.start));
344        dirty.dedup_by(|next, prev| {
345            let overlaps = next.memory == prev.memory && next.bytes.start <= prev.bytes.end;
346            if overlaps {
347                prev.bytes.end = prev.bytes.end.max(next.bytes.end);
348            }
349            overlaps
350        });
351        let result = (|| {
352            for DirtyRange {
353                memory: id,
354                bytes: range,
355            } in &dirty
356            {
357                let memory = self.rr.session.as_ref().unwrap().objects.memories[*id];
358                let data = memory
359                    .data_in_store(self)
360                    .get(range.clone())
361                    .ok_or_else(|| format_err!("tracked memory range is no longer valid"))?;
362                let len = 12usize
363                    .checked_add(data.len())
364                    .ok_or_else(|| format_err!("memory record too large"))?;
365                codec::record(&mut bytes, codec::WRITE, len)?;
366                bytes.extend_from_slice(&id.as_u32().to_le_bytes())?;
367                bytes.extend_from_slice(&u64::try_from(range.start)?.to_le_bytes())?;
368                bytes.extend_from_slice(data)?;
369            }
370            Ok(())
371        })();
372        dirty.clear();
373        let session = self.rr_session();
374        session.dirty_ranges = dirty;
375        let Mode::Recording { bytes: trace, .. } = &mut session.mode;
376        *trace = bytes;
377        result
378    }
379
380    pub(crate) fn rr_track_memory(&mut self, memory: Memory, range: Range<usize>) {
381        if !self.rr.recording() || range.is_empty() {
382            return;
383        }
384        let Some(id) = self.rr_memory_id(memory) else {
385            return;
386        };
387        let session = self.rr_session();
388        // Writes are usually sequential, so coalesce with the previous range
389        // here, in constant time; the flush merges any other overlaps.
390        if let Some(last) = session.dirty_ranges.last_mut()
391            && last.memory == id
392            && range.start <= last.bytes.end
393            && last.bytes.start <= range.end
394        {
395            last.bytes.start = last.bytes.start.min(range.start);
396            last.bytes.end = last.bytes.end.max(range.end);
397            return;
398        }
399        if let Err(oom) = session.dirty_ranges.push(DirtyRange {
400            memory: id,
401            bytes: range,
402        }) {
403            session.fail(oom.into());
404        }
405    }
406
407    /// Registers the function references among a call's parameters or
408    /// `results`, so that they can be encoded.
409    ///
410    /// # Safety
411    ///
412    /// `raw` must point to initialized slots of the parameter or result types
413    /// of `func`, whose function references this store owns.
414    unsafe fn rr_boundary_refs(
415        &mut self,
416        func: RecordedFunc,
417        raw: *const ValRaw,
418        results: bool,
419    ) -> Result<()> {
420        let bound = &self.rr_session().objects.funcs[func];
421        let count = if results {
422            bound.results.len()
423        } else {
424            bound.params.len()
425        };
426        for i in 0..count {
427            let bound = &self.rr_session().objects.funcs[func];
428            let kind = if results {
429                bound.results[i]
430            } else {
431                bound.params[i]
432            };
433            if let Kind::FuncRef { .. } = kind {
434                // SAFETY: the slot is initialized and has funcref type.
435                if let Some(ptr) = NonNull::new(unsafe { (*raw.add(i)).get_funcref() }) {
436                    // SAFETY: this store owns the reference.
437                    unsafe { self.rr_register_func_reference(ptr.cast())? };
438                }
439            }
440        }
441        Ok(())
442    }
443
444    /// The `rr_enter` builtin, which the trampolines of record/replay engines
445    /// call while the store records. Returns the call's ID, or
446    /// [`NOT_RECORDED`].
447    ///
448    /// # Safety
449    ///
450    /// `func` must be a valid function reference that this store owns, and
451    /// `raw` must point to initialized slots of its parameter types, whose
452    /// function references this store owns.
453    pub(crate) unsafe fn rr_enter(
454        &mut self,
455        func: NonNull<VMFuncRef>,
456        raw: *const ValRaw,
457        kind: RrCallKind,
458    ) -> Result<u32> {
459        if !self.rr.recording() {
460            return Ok(NOT_RECORDED);
461        }
462        // SAFETY: inherited from this function's contract.
463        let result = unsafe { self.rr_record_enter(func, raw, kind) };
464        self.rr_poison_on_err(result)
465    }
466
467    /// # Safety
468    ///
469    /// As for [`StoreOpaque::rr_enter`].
470    unsafe fn rr_record_enter(
471        &mut self,
472        func: NonNull<VMFuncRef>,
473        raw: *const ValRaw,
474        kind: RrCallKind,
475    ) -> Result<u32> {
476        self.rr_flush()?;
477        // SAFETY: inherited from this function's contract.
478        let func = unsafe { func.as_ref() };
479        let id = self.rr_session().objects.find_func_ref(func)?;
480        // SAFETY: inherited from this function's contract.
481        unsafe {
482            self.rr_boundary_refs(id, raw, false)?;
483        }
484        let session = self.rr_session();
485        let bound = &session.objects.funcs[id];
486        let Mode::Recording {
487            bytes,
488            outstanding,
489            next_call,
490        } = &mut session.mode;
491        let call = *next_call;
492        *next_call = next_call
493            .checked_add(1)
494            .filter(|c| *c != NOT_RECORDED)
495            .ok_or_else(|| format_err!("too many recorded calls"))?;
496        let tag = match kind {
497            RrCallKind::WasmToHost => codec::ENTER_HOST,
498            RrCallKind::HostToWasm => codec::ENTER_WASM,
499        };
500        codec::record(bytes, tag, 8 + codec::values_len(&bound.params))?;
501        bytes.extend_from_slice(&id.as_u32().to_le_bytes())?;
502        bytes.extend_from_slice(&call.to_le_bytes())?;
503        // SAFETY: inherited from this function's contract.
504        unsafe {
505            codec::values(bytes, &bound.params, raw, |ptr| {
506                session.objects.encode_ref(ptr)
507            })?
508        };
509        outstanding.push((RecordedCall::from_u32(call), id))?;
510        Ok(call)
511    }
512
513    /// The `rr_leave` builtin, which records the return of `call` from
514    /// [`StoreOpaque::rr_enter`]. If not `succeeded` then the call fails with
515    /// the error that is being raised.
516    ///
517    /// # Safety
518    ///
519    /// `call` must be what `rr_enter` returned for this call in this store. If
520    /// `succeeded` then `raw` must point to initialized slots of the result
521    /// types of the function that was passed to `rr_enter`, whose function
522    /// references this store owns.
523    pub(crate) unsafe fn rr_leave(
524        &mut self,
525        call: u32,
526        raw: *const ValRaw,
527        kind: RrCallKind,
528        succeeded: bool,
529    ) -> Result<()> {
530        if call == NOT_RECORDED {
531            return Ok(());
532        }
533        let result = if succeeded {
534            Ok(())
535        } else {
536            match crate::runtime::vm::pending_unwind_error() {
537                Some(error) => Err(error),
538                // A host panic is not recorded; it propagates through the
539                // recording.
540                None => return Ok(()),
541            }
542        };
543        // SAFETY: inherited from this function's contract.
544        let recorded =
545            unsafe { self.rr_record_leave(RecordedCall::from_u32(call), raw, &result, kind) };
546        let recorded = self.rr_poison_on_err(recorded);
547        // A failing call keeps its own error; the poisoned recording reports
548        // this one.
549        if succeeded { recorded } else { Ok(()) }
550    }
551
552    /// # Safety
553    ///
554    /// As for [`StoreOpaque::rr_leave`], where the call succeeded if `result`
555    /// is `Ok`.
556    unsafe fn rr_record_leave(
557        &mut self,
558        call: RecordedCall,
559        raw: *const ValRaw,
560        result: &Result<()>,
561        kind: RrCallKind,
562    ) -> Result<()> {
563        // The recording may have ended while this call was unfinished.
564        if !self.rr.recording() {
565            return Ok(());
566        }
567        self.rr_flush()?;
568        let Mode::Recording { outstanding, .. } = &self.rr_session().mode;
569        let position = outstanding
570            .iter()
571            .position(|(c, _)| *c == call)
572            .ok_or_else(|| format_err!("return without recorded call"))?;
573        let func = outstanding[position].1;
574        if result.is_ok() {
575            // SAFETY: inherited from this function's contract, as `func` is
576            // the function that was passed to `rr_enter`.
577            unsafe {
578                self.rr_boundary_refs(func, raw, true)?;
579            }
580        }
581        let session = self.rr_session();
582        let Mode::Recording {
583            bytes, outstanding, ..
584        } = &mut session.mode;
585        let tag = match kind {
586            RrCallKind::WasmToHost => codec::LEAVE_HOST,
587            RrCallKind::HostToWasm => codec::LEAVE_WASM,
588        };
589        let results = &session.objects.funcs[func].results;
590        // SAFETY: inherited from this function's contract.
591        unsafe {
592            codec::outcome(bytes, tag, call, result, results, raw, |ptr| {
593                session.objects.encode_ref(ptr)
594            })?;
595        }
596        outstanding.swap_remove(position);
597        Ok(())
598    }
599}