wasm/core/decoding/modules/
custom_section.rs

1use crate::{
2    core::decoding::reader::{span::Span, WasmDecoder},
3    DecodingError, ValidationError,
4};
5
6#[derive(Debug, Clone)]
7pub struct CustomSection<'wasm> {
8    pub name: &'wasm str,
9    pub contents: &'wasm [u8],
10}
11
12impl<'wasm> CustomSection<'wasm> {
13    // TODO this should return a Result<_, DecodingError>
14    pub(crate) fn decode(
15        wasm: &mut WasmDecoder<'wasm>,
16        section_contents: Span,
17    ) -> Result<CustomSection<'wasm>, ValidationError> {
18        // customsec ::= section_0(custom)
19        // custom ::= name byte*
20        // name ::= b*:vec(byte) => name (if utf8(name) = b*)
21        // vec(B) ::= n:u32 (x:B)^n => x^n
22        let name = wasm.decode_name()?;
23
24        let section_start = wasm.pc;
25        let section_end = section_contents
26            .from()
27            .checked_add(section_contents.len())
28            .ok_or(DecodingError::SectionSizeMismatch)?;
29
30        let contents = wasm
31            .full_wasm_binary
32            .get(section_start..section_end)
33            .ok_or(DecodingError::SectionSizeMismatch)?;
34
35        let section_len = section_end
36            .checked_sub(section_start)
37            .expect("section start <= section end always");
38
39        wasm.skip(section_len)?;
40
41        Ok(CustomSection { name, contents })
42    }
43}