wasm/validation/
globals.rs

1use alloc::collections::btree_set::BTreeSet;
2use alloc::vec::Vec;
3
4use crate::core::indices::FuncIdx;
5use crate::core::reader::section_header::{SectionHeader, SectionTy};
6use crate::core::reader::types::global::{Global, GlobalType};
7use crate::core::reader::{WasmReadable, WasmReader};
8use crate::read_constant_expression::read_constant_expression;
9use crate::validation_stack::ValidationStack;
10use crate::Result;
11
12/// Validate the global section.
13///
14/// The global section is a vector of global variables. Each [Global] variable is composed of a [GlobalType] and an
15/// initialization expression represented by a constant expression.
16///
17/// See [`read_constant_expression`] for more information.
18pub(super) fn validate_global_section(
19    wasm: &mut WasmReader,
20    section_header: SectionHeader,
21    imported_global_types: &[GlobalType],
22    validation_context_refs: &mut BTreeSet<FuncIdx>,
23    num_funcs: usize,
24) -> Result<Vec<Global>> {
25    assert_eq!(section_header.ty, SectionTy::Global);
26
27    wasm.read_vec(|wasm| {
28        let ty = GlobalType::read(wasm)?;
29        let stack = &mut ValidationStack::new();
30        let (init_expr, seen_func_idxs) =
31            read_constant_expression(wasm, stack, imported_global_types, num_funcs)?;
32
33        stack.assert_val_types(&[ty.ty], true)?;
34        validation_context_refs.extend(seen_func_idxs);
35
36        Ok(Global { ty, init_expr })
37    })
38}