Skip to main content

wasmtime_environ/
frame_table.rs

1//! Frame-table parser and lookup logic.
2//!
3//! This module contains utilities to interpret the `.wasmtime.frame`
4//! section in a compiled artifact as produced by
5//! [`crate::compile::FrameTableBuilder`].
6
7use crate::{FuncKey, ModulePC, StaticModuleIndex};
8use alloc::vec::Vec;
9use core::ops::Range;
10use object::{Bytes, LittleEndian, U32};
11
12/// An index into the table of stack shapes.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
14pub struct FrameStackShape(pub(crate) u32);
15impl FrameStackShape {
16    pub(crate) fn index(self) -> usize {
17        usize::try_from(self.0).unwrap()
18    }
19
20    /// Get the raw stack-shape index suitable for serializing into
21    /// metadata.
22    pub fn raw(self) -> u32 {
23        self.0
24    }
25
26    /// Wrap a raw stack shape index (e.g. from debug tags) into a FrameStackShape.
27    pub fn from_raw(index: u32) -> FrameStackShape {
28        FrameStackShape(index)
29    }
30}
31
32/// An index to a frame descriptor that can be referenced from a
33/// program point descriptor.
34#[derive(Clone, Copy, Debug)]
35pub struct FrameTableDescriptorIndex(pub(crate) u32);
36impl FrameTableDescriptorIndex {
37    fn index(self) -> usize {
38        usize::try_from(self.0).unwrap()
39    }
40}
41
42/// A parser for a frame-table section.
43///
44/// This parser holds slices to the in-memory section data, and is
45/// cheap to construct: it reads some header fields but does not
46/// interpret or validate content data until queried.
47pub struct FrameTable<'a> {
48    frame_descriptor_ranges: &'a [U32<LittleEndian>],
49    frame_descriptor_data: &'a [u8],
50
51    frame_descriptor_fp_offsets: &'a [U32<LittleEndian>],
52
53    progpoint_pcs: &'a [U32<LittleEndian>],
54    progpoint_descriptor_offsets: &'a [U32<LittleEndian>],
55    progpoint_descriptor_data: &'a [U32<LittleEndian>],
56
57    breakpoint_modules: &'a [U32<LittleEndian>],
58    breakpoint_pcs: &'a [U32<LittleEndian>],
59    breakpoint_patch_offsets: &'a [U32<LittleEndian>],
60    breakpoint_patch_data_ends: &'a [U32<LittleEndian>],
61    breakpoint_patch_data: &'a [u8],
62
63    func_starts: &'a [U32<LittleEndian>],
64
65    original_text: &'a [u8],
66}
67
68impl<'a> FrameTable<'a> {
69    /// Parse a frame table section from a byte-slice as produced by
70    /// [`crate::compile::FrameTableBuilder`].
71    pub fn parse(data: &'a [u8], original_text: &'a [u8]) -> anyhow::Result<FrameTable<'a>> {
72        let mut data = Bytes(data);
73        let num_frame_descriptors = data
74            .read::<U32<LittleEndian>>()
75            .map_err(|_| anyhow::anyhow!("Unable to read frame descriptor count prefix"))?;
76        let num_frame_descriptors = usize::try_from(num_frame_descriptors.get(LittleEndian))?;
77        let num_progpoint_descriptors = data
78            .read::<U32<LittleEndian>>()
79            .map_err(|_| anyhow::anyhow!("Unable to read progpoint descriptor count prefix"))?;
80        let num_progpoint_descriptors =
81            usize::try_from(num_progpoint_descriptors.get(LittleEndian))?;
82        let num_breakpoints = data
83            .read::<U32<LittleEndian>>()
84            .map_err(|_| anyhow::anyhow!("Unable to read breakpoint count prefix"))?;
85        let num_breakpoints = usize::try_from(num_breakpoints.get(LittleEndian))?;
86        let num_funcs = data
87            .read::<U32<LittleEndian>>()
88            .map_err(|_| anyhow::anyhow!("Unable to read function count prefix"))?;
89        let num_funcs = usize::try_from(num_funcs.get(LittleEndian))?;
90
91        let frame_descriptor_pool_length = data
92            .read::<U32<LittleEndian>>()
93            .map_err(|_| anyhow::anyhow!("Unable to read frame descriptor pool length"))?;
94        let frame_descriptor_pool_length =
95            usize::try_from(frame_descriptor_pool_length.get(LittleEndian))?;
96        let progpoint_descriptor_pool_length = data
97            .read::<U32<LittleEndian>>()
98            .map_err(|_| anyhow::anyhow!("Unable to read progpoint descriptor pool length"))?;
99        let progpoint_descriptor_pool_length =
100            usize::try_from(progpoint_descriptor_pool_length.get(LittleEndian))?;
101        let breakpoint_patch_pool_length = data
102            .read::<U32<LittleEndian>>()
103            .map_err(|_| anyhow::anyhow!("Unable to read breakpoint patch pool length"))?;
104        let breakpoint_patch_pool_length =
105            usize::try_from(breakpoint_patch_pool_length.get(LittleEndian))?;
106
107        let (frame_descriptor_ranges, data) =
108            object::slice_from_bytes::<U32<LittleEndian>>(data.0, 2 * num_frame_descriptors)
109                .map_err(|_| anyhow::anyhow!("Unable to read frame descriptor ranges slice"))?;
110        let (frame_descriptor_fp_offsets, data) =
111            object::slice_from_bytes::<U32<LittleEndian>>(data, num_frame_descriptors)
112                .map_err(|_| anyhow::anyhow!("Unable to read frame descriptor FP offset slice"))?;
113
114        let (progpoint_pcs, data) =
115            object::slice_from_bytes::<U32<LittleEndian>>(data, num_progpoint_descriptors)
116                .map_err(|_| anyhow::anyhow!("Unable to read progpoint PC slice"))?;
117        let (progpoint_descriptor_offsets, data) =
118            object::slice_from_bytes::<U32<LittleEndian>>(data, num_progpoint_descriptors)
119                .map_err(|_| anyhow::anyhow!("Unable to read progpoint descriptor offset slice"))?;
120        let (breakpoint_modules, data) =
121            object::slice_from_bytes::<U32<LittleEndian>>(data, num_breakpoints)
122                .map_err(|_| anyhow::anyhow!("Unable to read breakpoint module slice"))?;
123        let (breakpoint_pcs, data) =
124            object::slice_from_bytes::<U32<LittleEndian>>(data, num_breakpoints)
125                .map_err(|_| anyhow::anyhow!("Unable to read breakpoint PC slice"))?;
126        let (breakpoint_patch_offsets, data) =
127            object::slice_from_bytes::<U32<LittleEndian>>(data, num_breakpoints)
128                .map_err(|_| anyhow::anyhow!("Unable to read breakpoint patch offsets slice"))?;
129        let (breakpoint_patch_data_ends, data) =
130            object::slice_from_bytes::<U32<LittleEndian>>(data, num_breakpoints)
131                .map_err(|_| anyhow::anyhow!("Unable to read breakpoint patch data ends slice"))?;
132        let (func_starts, data) = object::slice_from_bytes::<U32<LittleEndian>>(data, num_funcs)
133            .map_err(|_| anyhow::anyhow!("Unable to read function starts slice"))?;
134
135        let (frame_descriptor_data, data) = data
136            .split_at_checked(frame_descriptor_pool_length)
137            .ok_or_else(|| anyhow::anyhow!("Unable to read frame descriptor pool"))?;
138
139        let (progpoint_descriptor_data, data) =
140            object::slice_from_bytes::<U32<LittleEndian>>(data, progpoint_descriptor_pool_length)
141                .map_err(|_| anyhow::anyhow!("Unable to read progpoint descriptor pool"))?;
142
143        let (breakpoint_patch_data, _) = data
144            .split_at_checked(breakpoint_patch_pool_length)
145            .ok_or_else(|| anyhow::anyhow!("Unable to read breakpoint patch pool"))?;
146
147        Ok(FrameTable {
148            frame_descriptor_ranges,
149            frame_descriptor_data,
150            frame_descriptor_fp_offsets,
151            progpoint_pcs,
152            progpoint_descriptor_offsets,
153            progpoint_descriptor_data,
154            breakpoint_modules,
155            breakpoint_pcs,
156            breakpoint_patch_offsets,
157            breakpoint_patch_data_ends,
158            breakpoint_patch_data,
159            func_starts,
160            original_text,
161        })
162    }
163
164    /// Get raw frame descriptor data and slot-to-FP-offset for a
165    /// given frame descriptor.
166    pub fn frame_descriptor(
167        &self,
168        frame_descriptor: FrameTableDescriptorIndex,
169    ) -> Option<(&'a [u8], u32)> {
170        let range_start = self
171            .frame_descriptor_ranges
172            .get(frame_descriptor.index() * 2)?
173            .get(LittleEndian);
174        let range_end = self
175            .frame_descriptor_ranges
176            .get(frame_descriptor.index() * 2 + 1)?
177            .get(LittleEndian);
178        let range_start = usize::try_from(range_start).unwrap();
179        let range_end = usize::try_from(range_end).unwrap();
180        if range_end < range_start || range_end > self.frame_descriptor_data.len() {
181            return None;
182        }
183        let descriptor = &self.frame_descriptor_data[range_start..range_end];
184        let slot_to_fp_offset = self
185            .frame_descriptor_fp_offsets
186            .get(frame_descriptor.index())?
187            .get(LittleEndian);
188        Some((descriptor, slot_to_fp_offset))
189    }
190
191    /// Get frames for the program point at the PC upper-bounded by a
192    /// given search PC (offset in text section).
193    ///
194    /// The search is bounded by the start of the function containing
195    /// the search PC: if that function has no program point at or
196    /// before the search PC, `None` is returned, rather than a
197    /// program point from a preceding function.
198    pub fn find_program_point(
199        &self,
200        search_pc: u32,
201        search_pos: FrameInstPos,
202    ) -> Option<impl Iterator<Item = (ModulePC, FrameTableDescriptorIndex, FrameStackShape)>> {
203        let key = FrameInstPos::encode(search_pc, search_pos);
204        let index = match self
205            .progpoint_pcs
206            .binary_search_by_key(&key, |entry| entry.get(LittleEndian))
207        {
208            Ok(idx) => idx,
209            Err(idx) if idx > 0 => idx - 1,
210            Err(_) => return None,
211        };
212
213        // Find the start of the function containing the search
214        // point. If the result of the search above falls before the
215        // start of the function, that means that the function has no
216        // program points; so return `None`.
217        let func_start = match self.func_starts.binary_search_by_key(&key, |entry| {
218            FrameInstPos::encode(entry.get(LittleEndian), FrameInstPos::Pre)
219        }) {
220            Ok(idx) => self.func_starts[idx].get(LittleEndian),
221            Err(idx) if idx > 0 => self.func_starts[idx - 1].get(LittleEndian),
222            Err(_) => return None,
223        };
224        let func_start_key = FrameInstPos::encode(func_start, FrameInstPos::Pre);
225        if self.progpoint_pcs[index].get(LittleEndian) < func_start_key {
226            return None;
227        }
228
229        Some(self.program_point_frame_iter(index))
230    }
231
232    /// Get all program point records with iterators over
233    /// corresponding frames for each.
234    pub fn into_program_points(
235        self,
236    ) -> impl Iterator<
237        Item = (
238            u32,
239            FrameInstPos,
240            Vec<(ModulePC, FrameTableDescriptorIndex, FrameStackShape)>,
241        ),
242    > + 'a {
243        self.progpoint_pcs.iter().enumerate().map(move |(i, pc)| {
244            let pc_and_pos = pc.get(LittleEndian);
245            let (pc, pos) = FrameInstPos::decode(pc_and_pos);
246            (
247                pc,
248                pos,
249                self.program_point_frame_iter(i).collect::<Vec<_>>(),
250            )
251        })
252    }
253
254    fn program_point_frame_iter(
255        &self,
256        index: usize,
257    ) -> impl Iterator<Item = (ModulePC, FrameTableDescriptorIndex, FrameStackShape)> {
258        let offset =
259            usize::try_from(self.progpoint_descriptor_offsets[index].get(LittleEndian)).unwrap();
260        let mut data = &self.progpoint_descriptor_data[offset..];
261
262        core::iter::from_fn(move || {
263            if data.len() < 3 {
264                return None;
265            }
266            let wasm_pc_raw = data[0].get(LittleEndian);
267            let frame_descriptor = FrameTableDescriptorIndex(data[1].get(LittleEndian));
268            let stack_shape = FrameStackShape(data[2].get(LittleEndian));
269            data = &data[3..];
270            let not_last = wasm_pc_raw & 0x8000_0000 != 0;
271            let wasm_pc = ModulePC::new(wasm_pc_raw & 0x7fff_ffff);
272            if !not_last {
273                data = &[];
274            }
275            Some((wasm_pc, frame_descriptor, stack_shape))
276        })
277    }
278
279    /// For a given breakpoint index, return the patch offset in text,
280    /// the patch data, and the original data.
281    fn breakpoint_patch(&self, i: usize) -> FrameTableBreakpointData<'_> {
282        let patch_pool_start = if i == 0 {
283            0
284        } else {
285            self.breakpoint_patch_data_ends[i - 1].get(LittleEndian)
286        };
287        let patch_pool_end = self.breakpoint_patch_data_ends[i].get(LittleEndian);
288        let patch_pool_start = usize::try_from(patch_pool_start).unwrap();
289        let patch_pool_end = usize::try_from(patch_pool_end).unwrap();
290        let len = patch_pool_end - patch_pool_start;
291        let offset = self.breakpoint_patch_offsets[i].get(LittleEndian);
292        let offset = usize::try_from(offset).unwrap();
293        let original_data = &self.original_text[offset..offset + len];
294        FrameTableBreakpointData {
295            offset,
296            enable: &self.breakpoint_patch_data[patch_pool_start..patch_pool_end],
297            disable: original_data,
298        }
299    }
300
301    /// The range of breakpoint indices for the given module.
302    ///
303    /// A component's modules share one frame table, and one module's
304    /// Wasm PCs mean nothing in another, so every breakpoint lookup is
305    /// scoped to one module first.
306    fn module_breakpoints(&self, module: StaticModuleIndex) -> Range<usize> {
307        let module = module.as_u32();
308        let start = self
309            .breakpoint_modules
310            .partition_point(|m| m.get(LittleEndian) < module);
311        let end = start
312            + self.breakpoint_modules[start..].partition_point(|m| m.get(LittleEndian) == module);
313        start..end
314    }
315
316    /// Find a list of breakpoint patches for a given Wasm PC in the
317    /// given module.
318    ///
319    /// There may be more than one, as inlining can copy a Wasm PC into
320    /// several functions.
321    pub fn lookup_breakpoint_patches_by_pc(
322        &self,
323        module: StaticModuleIndex,
324        pc: ModulePC,
325    ) -> impl Iterator<Item = FrameTableBreakpointData<'_>> + '_ {
326        let range = self.module_breakpoints(module);
327        let pcs = &self.breakpoint_pcs[range.clone()];
328        let start = pcs.partition_point(|p| p.get(LittleEndian) < pc.raw());
329        let end = pcs.partition_point(|p| p.get(LittleEndian) <= pc.raw());
330        (range.start + start..range.start + end).map(|i| self.breakpoint_patch(i))
331    }
332
333    /// Find the nearest breakpoint PC at or after the given PC in the
334    /// given module.
335    pub fn nearest_breakpoint(&self, module: StaticModuleIndex, pc: ModulePC) -> Option<ModulePC> {
336        let pcs = &self.breakpoint_pcs[self.module_breakpoints(module)];
337        let i = pcs.partition_point(|p| p.get(LittleEndian) < pc.raw());
338        pcs.get(i).map(|p| ModulePC::new(p.get(LittleEndian)))
339    }
340
341    /// Return an iterator over all breakpoint patches for Wasm code
342    /// from the given module, wherever it was compiled (including
343    /// copies inlined into other modules' functions).
344    ///
345    /// Returned tuples are (module-relative Wasm PC, breakpoint data).
346    pub fn breakpoint_patches(
347        &self,
348        module: StaticModuleIndex,
349    ) -> impl Iterator<Item = (ModulePC, FrameTableBreakpointData<'_>)> + '_ {
350        self.module_breakpoints(module).map(|i| {
351            let wasm_pc = ModulePC::new(self.breakpoint_pcs[i].get(LittleEndian));
352            (wasm_pc, self.breakpoint_patch(i))
353        })
354    }
355
356    /// Return an iterator over all breakpoint patches, for every
357    /// module.
358    ///
359    /// Returned tuples are (module, module-relative Wasm PC, breakpoint
360    /// data).
361    pub fn all_breakpoint_patches(
362        &self,
363    ) -> impl Iterator<Item = (StaticModuleIndex, ModulePC, FrameTableBreakpointData<'_>)> + '_
364    {
365        (0..self.breakpoint_pcs.len()).map(|i| {
366            let module = StaticModuleIndex::from_u32(self.breakpoint_modules[i].get(LittleEndian));
367            let wasm_pc = ModulePC::new(self.breakpoint_pcs[i].get(LittleEndian));
368            (module, wasm_pc, self.breakpoint_patch(i))
369        })
370    }
371}
372
373/// Data describing how to patch code to enable or disable one
374/// breakpoint.
375pub struct FrameTableBreakpointData<'a> {
376    /// Offset in the code image's text section.
377    pub offset: usize,
378    /// Code bytes to patch in to enable the breakpoint.
379    pub enable: &'a [u8],
380    /// Code bytes to patch in to disable the breakpoint.
381    pub disable: &'a [u8],
382}
383
384/// An instruction position for a program point.
385///
386/// We attach debug metadata to a *position* on an offset in the text
387/// (code) section, either "post" or "pre". The "post" position
388/// logically comes first, and is associated with the instruction that
389/// ends at this offset (i.e., the previous instruction). The "pre"
390/// position comes next, and is associated with the instruction that
391/// begins at this offset (i.e., the next instruction).
392///
393/// We make this distinction because metadata lookups sometimes occur
394/// with a PC that is after the instruction (e.g., the return address
395/// after a call instruction), and sometimes at the instruction (e.g.,
396/// a trapping PC address). The lookup context will know which one to
397/// use -- e.g., when walking the stack, "pre" for a trapping PC and
398/// "post" for every frame after that -- so we simply encode it as
399/// part of the position and allow searching on it.
400///
401/// The need for this distinction can be understood by way of an
402/// example; say we have:
403///
404/// ```plain
405/// call ...
406/// trapping_store ...
407/// ```
408///
409/// where both instructions have debug metadata. We might look up the
410/// PC of `trapping_store` once as we walk the stack from within the
411/// call (we will get this PC because it is the return address) and
412/// once when `trapping_store` itself traps; and we want different
413/// metadata in each case.
414///
415/// An alternative is to universally attach tags to the end offset of
416/// an instruction, which allows us to handle return addresses
417/// naturally but requires traps to adjust their PC. However, this
418/// requires trap handlers to know the length of the trapping
419/// instruction, which is not always easy -- in the most general case,
420/// on variable-length instruction sets, it requires a full
421/// instruction decoder.
422#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
423pub enum FrameInstPos {
424    /// The "post" position at an offset attaches to the instruction
425    /// that ends at this offset, i.e., came previously.
426    Post,
427    /// The "pre" position at an offset attaches to the instruction
428    /// that begins at this offset, i.e., comes next.
429    Pre,
430}
431
432impl FrameInstPos {
433    pub(crate) fn encode(pc: u32, pos: FrameInstPos) -> u32 {
434        let lsb = match pos {
435            Self::Post => 0,
436            Self::Pre => 1,
437        };
438        debug_assert!(pc < 0x8000_0000);
439        (pc << 1) | lsb
440    }
441    pub(crate) fn decode(bits: u32) -> (u32, FrameInstPos) {
442        let pos = match bits & 1 {
443            0 => Self::Post,
444            1 => Self::Pre,
445            _ => unreachable!(),
446        };
447        let pc = bits >> 1;
448        (pc, pos)
449    }
450}
451
452/// An offset into the state slot.
453#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
454pub struct FrameStateSlotOffset(pub(crate) u32);
455impl FrameStateSlotOffset {
456    #[cfg(feature = "compile")]
457    pub(crate) fn add(self, offset: u32) -> FrameStateSlotOffset {
458        FrameStateSlotOffset(self.0 + offset)
459    }
460
461    /// Get the offset into the state stackslot, suitable for use in a
462    /// `stack_store`/`stack_load` instruction.
463    pub fn offset(self) -> i32 {
464        i32::try_from(self.0).unwrap()
465    }
466}
467
468/// A type stored in a frame.
469#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
470#[allow(missing_docs, reason = "self-describing variants")]
471pub enum FrameValType {
472    I32,
473    I64,
474    F32,
475    F64,
476    V128,
477    AnyRef,
478    FuncRef,
479    ExternRef,
480    ExnRef,
481    ContRef,
482}
483
484impl FrameValType {
485    #[cfg(feature = "compile")]
486    pub(crate) fn storage_size(&self, pointer_size: u32) -> u32 {
487        match self {
488            FrameValType::I32 => 4,
489            FrameValType::I64 => 8,
490            FrameValType::F32 => 4,
491            FrameValType::F64 => 8,
492            FrameValType::V128 => 16,
493            FrameValType::AnyRef | FrameValType::ExternRef | FrameValType::ExnRef => 4,
494            FrameValType::FuncRef => pointer_size,
495            FrameValType::ContRef => 2 * pointer_size,
496        }
497    }
498}
499
500impl From<FrameValType> for u8 {
501    fn from(value: FrameValType) -> u8 {
502        match value {
503            FrameValType::I32 => 0,
504            FrameValType::I64 => 1,
505            FrameValType::F32 => 2,
506            FrameValType::F64 => 3,
507            FrameValType::V128 => 4,
508            FrameValType::AnyRef => 5,
509            FrameValType::FuncRef => 6,
510            FrameValType::ExternRef => 7,
511            FrameValType::ExnRef => 8,
512            FrameValType::ContRef => 9,
513        }
514    }
515}
516
517impl TryFrom<u8> for FrameValType {
518    type Error = anyhow::Error;
519    fn try_from(value: u8) -> anyhow::Result<Self> {
520        match value {
521            0 => Ok(Self::I32),
522            1 => Ok(Self::I64),
523            2 => Ok(Self::F32),
524            3 => Ok(Self::F64),
525            4 => Ok(Self::V128),
526            5 => Ok(Self::AnyRef),
527            6 => Ok(Self::FuncRef),
528            7 => Ok(Self::ExternRef),
529            8 => Ok(Self::ExnRef),
530            9 => Ok(Self::ContRef),
531            _ => Err(anyhow::anyhow!("Invalid type")),
532        }
533    }
534}
535
536/// Parser for a frame state slot descriptor.
537///
538/// This provides the ability to extract offsets and types for locals
539/// and for the stack given a stack shape.
540pub struct FrameStateSlot<'a> {
541    func_key: FuncKey,
542    local_offsets: &'a [U32<LittleEndian>],
543    stack_shape_parents: &'a [U32<LittleEndian>],
544    stack_shape_offsets: &'a [U32<LittleEndian>],
545    local_types: &'a [u8],
546    stack_shape_types: &'a [u8],
547}
548
549impl<'a> FrameStateSlot<'a> {
550    /// Parse a slot descriptor.
551    ///
552    /// This parses the descriptor bytes as provided by
553    /// [`FrameTable::frame_descriptor`].
554    pub fn parse(descriptor: &'a [u8]) -> anyhow::Result<FrameStateSlot<'a>> {
555        let mut data = Bytes(descriptor);
556        let func_key_namespace = data
557            .read::<U32<LittleEndian>>()
558            .map_err(|_| anyhow::anyhow!("Unable to read func key namespace"))?
559            .get(LittleEndian);
560        let func_key_index = data
561            .read::<U32<LittleEndian>>()
562            .map_err(|_| anyhow::anyhow!("Unable to read func key index"))?
563            .get(LittleEndian);
564        let func_key = FuncKey::from_raw_parts(func_key_namespace, func_key_index);
565
566        let num_locals = data
567            .read::<U32<LittleEndian>>()
568            .map_err(|_| anyhow::anyhow!("Unable to read num_locals"))?
569            .get(LittleEndian);
570        let num_locals = usize::try_from(num_locals)?;
571        let num_stack_shapes = data
572            .read::<U32<LittleEndian>>()
573            .map_err(|_| anyhow::anyhow!("Unable to read num_stack_shapes"))?
574            .get(LittleEndian);
575        let num_stack_shapes = usize::try_from(num_stack_shapes)?;
576
577        let (local_offsets, data) =
578            object::slice_from_bytes::<U32<LittleEndian>>(data.0, num_locals)
579                .map_err(|_| anyhow::anyhow!("Unable to read local_offsets slice"))?;
580        let (stack_shape_parents, data) =
581            object::slice_from_bytes::<U32<LittleEndian>>(data, num_stack_shapes)
582                .map_err(|_| anyhow::anyhow!("Unable to read stack_shape_parents slice"))?;
583        let (stack_shape_offsets, data) =
584            object::slice_from_bytes::<U32<LittleEndian>>(data, num_stack_shapes)
585                .map_err(|_| anyhow::anyhow!("Unable to read stack_shape_offsets slice"))?;
586        let (local_types, data) = data
587            .split_at_checked(num_locals)
588            .ok_or_else(|| anyhow::anyhow!("Unable to read local_types slice"))?;
589        let (stack_shape_types, _) = data
590            .split_at_checked(num_stack_shapes)
591            .ok_or_else(|| anyhow::anyhow!("Unable to read stack_shape_types slice"))?;
592
593        Ok(FrameStateSlot {
594            func_key,
595            local_offsets,
596            stack_shape_parents,
597            stack_shape_offsets,
598            local_types,
599            stack_shape_types,
600        })
601    }
602
603    /// Get the FuncKey for the function that produced this frame
604    /// slot.
605    pub fn func_key(&self) -> FuncKey {
606        self.func_key
607    }
608
609    /// Get the local offsets and types.
610    pub fn locals(&self) -> impl Iterator<Item = (FrameStateSlotOffset, FrameValType)> {
611        (0..self.num_locals()).map(|i| self.local(i).unwrap())
612    }
613
614    /// Get the type and offset for a given local.
615    pub fn local(&self, index: usize) -> Option<(FrameStateSlotOffset, FrameValType)> {
616        let offset = FrameStateSlotOffset(self.local_offsets.get(index)?.get(LittleEndian));
617        let ty = FrameValType::try_from(*self.local_types.get(index)?).expect("Invalid type");
618        Some((offset, ty))
619    }
620
621    /// Get the number of locals in the frame.
622    pub fn num_locals(&self) -> usize {
623        self.local_offsets.len()
624    }
625
626    /// Get the offsets and types for operand stack values, from top
627    /// of stack (most recently pushed) down.
628    pub fn stack(
629        &self,
630        shape: FrameStackShape,
631    ) -> impl Iterator<Item = (FrameStateSlotOffset, FrameValType)> {
632        fn unpack_option_shape(shape: FrameStackShape) -> Option<FrameStackShape> {
633            if shape.0 == u32::MAX {
634                None
635            } else {
636                Some(shape)
637            }
638        }
639
640        let mut shape = unpack_option_shape(shape);
641        core::iter::from_fn(move || {
642            shape.map(|s| {
643                let parent = FrameStackShape(self.stack_shape_parents[s.index()].get(LittleEndian));
644                let parent = unpack_option_shape(parent);
645                let offset =
646                    FrameStateSlotOffset(self.stack_shape_offsets[s.index()].get(LittleEndian));
647                let ty = FrameValType::try_from(self.stack_shape_types[s.index()])
648                    .expect("Invalid type");
649                shape = parent;
650                (offset, ty)
651            })
652        })
653    }
654
655    /// Returns an iterator over all storage in this frame.
656    pub fn stack_and_locals(
657        &self,
658        shape: FrameStackShape,
659    ) -> impl Iterator<Item = (FrameStateSlotOffset, FrameValType)> + '_ {
660        self.locals().chain(self.stack(shape))
661    }
662}