Coverage Report

Created: 2026-11-23 07:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wasm-tools/crates/wasmparser/src/validator/custom.rs
Line
Count
Source
1
use crate::types::EntityType;
2
use crate::validator::TypesRef;
3
use crate::{
4
    BranchHintSectionReader, CompositeInnerType, Encoding, FunctionBody, IndirectNameMap,
5
    KnownCustom, Name, NameMap, NameSectionReader, Operator, Payload, Result, Validator,
6
};
7
use alloc::vec;
8
use alloc::vec::Vec;
9
10
/// A validator for the contents of custom sections.
11
///
12
/// Custom sections in WebAssembly do not affect whether a module is valid, but
13
/// it can still be useful for debugging and specification purposes to know and
14
/// test whether a custom section is valid.
15
///
16
/// For known custom sections specified in the WebAssembly specification, such
17
/// as the `name` custom section or the branch-hint custom section, this
18
/// validator will ensure that those contents are valid according to the
19
/// specification.
20
///
21
/// This structure is intended to be used in parallel with a [`Validator`].
22
/// After a [`Payload`] is fed to a [`Validator`] it's then fed into this with
23
/// [`CustomSectionValidator::payload`]. Function validation then later invokes
24
/// [`CustomSectionValidator::code_section_entry`] to ensure the validity of
25
/// custom sections referring to contents of function bodies.
26
#[derive(Default)]
27
pub struct CustomSectionValidator {
28
    /// State for every module and component seen so far, indexed by the ids
29
    /// returned from `current_module_id`.
30
    states: Vec<State>,
31
    /// Stack of indices into `states` for modules/components which are
32
    /// currently being parsed, with the innermost one last.
33
    active: Vec<usize>,
34
}
35
36
#[derive(Default)]
37
struct State {
38
    is_component: bool,
39
    seen_name: bool,
40
    seen_branch_hints: bool,
41
    num_data: u32,
42
    name_local_max_per_function: Vec<NameMax>,
43
    params_per_function: Vec<u32>,
44
    name_label_max_per_function: Vec<NameMax>,
45
    per_function_hints: Vec<Vec<(u32, u64)>>,
46
}
47
48
#[derive(Copy, Clone)]
49
enum NameMax {
50
    None,
51
    EmptyList {
52
        offset_specifying_index: u64,
53
    },
54
    Index {
55
        index: u32,
56
        offset_specifying_index: u64,
57
    },
58
}
59
60
impl CustomSectionValidator {
61
    /// Creates a new validator ready for validating a component or a module.
62
0
    pub fn new() -> Self {
63
0
        Self::default()
64
0
    }
65
66
    /// Validates the `payload` provided which should already have been
67
    /// validated with the `validator` provided.
68
0
    pub fn payload(&mut self, payload: &Payload<'_>, validator: &Validator) -> Result<()> {
69
0
        match payload {
70
0
            Payload::Version { encoding, .. } => {
71
0
                self.active.push(self.states.len());
72
0
                self.states.push(State {
73
0
                    is_component: *encoding == Encoding::Component,
74
0
                    ..State::default()
75
0
                });
76
0
            }
77
0
            Payload::End(_) => {
78
0
                self.active.pop();
79
0
            }
80
0
            other => {
81
0
                if let Some(i) = self.active.last() {
82
0
                    self.states[*i].payload(other, validator)?;
83
0
                }
84
            }
85
        }
86
0
        Ok(())
87
0
    }
88
89
    /// Gets an id for the current module to pass to
90
    /// [`CustomSectionValidator::code_section_entry`] when the function
91
    /// contents are ready to be validated.
92
0
    pub fn current_module_id(&self) -> usize {
93
0
        *self.active.last().unwrap()
94
0
    }
95
96
    /// Validates the contents of `body` w.r.t. custom sections.
97
    ///
98
    /// The `module_id` should have been previously acquired from
99
    /// [`CustomSectionValidator::current_module_id`]. The `func_index` and
100
    /// `body` are specified relative to that module.
101
    ///
102
    /// This function should only be invoked after the entire module has been
103
    /// processed with [`CustomSectionValidator::payload`] to ensure that all
104
    /// data is known about all custom sections present.
105
0
    pub fn code_section_entry(
106
0
        &self,
107
0
        module_id: usize,
108
0
        func_index: u32,
109
0
        body: &FunctionBody<'_>,
110
0
    ) -> Result<()> {
111
0
        self.states[module_id].code_section_entry(func_index, body)
112
0
    }
113
}
114
115
impl State {
116
0
    fn payload(&mut self, payload: &Payload<'_>, validator: &Validator) -> Result<()> {
117
0
        match payload {
118
0
            Payload::CustomSection(s) => self.known_custom_section(s.as_known(), validator)?,
119
            _ => {
120
0
                if let Some((_id, range)) = payload.as_section() {
121
0
                    if self.seen_name {
122
0
                        bail!(range.start, "name section must come last");
123
0
                    }
124
0
                }
125
0
                if let Payload::DataSection(s) = payload {
126
0
                    self.num_data = s.count();
127
0
                }
128
            }
129
        }
130
0
        Ok(())
131
0
    }
132
133
0
    fn known_custom_section(
134
0
        &mut self,
135
0
        section: KnownCustom<'_>,
136
0
        validator: &Validator,
137
0
    ) -> Result<()> {
138
0
        match section {
139
0
            KnownCustom::Name(name) => self.name_section(name, validator),
140
0
            KnownCustom::BranchHints(hints) => self.branch_hint_section(hints, validator),
141
0
            _ => Ok(()),
142
        }
143
0
    }
144
145
0
    fn name_section(&mut self, names: NameSectionReader<'_>, validator: &Validator) -> Result<()> {
146
0
        if self.is_component {
147
0
            bail!(
148
0
                names.sections.range().start,
149
                "core module `name` section in a component"
150
            );
151
0
        }
152
0
        if self.seen_name {
153
0
            bail!(names.sections.range().start, "duplicate name section");
154
0
        }
155
0
        self.seen_name = true;
156
0
        let types = validator.types(0).unwrap();
157
0
        for name in names {
158
0
            match name? {
159
0
                Name::Module { .. } => {}
160
0
                Name::Function(s) => {
161
0
                    name_map(s, types.function_count(), "func")?;
162
                }
163
0
                Name::Type(s) => {
164
0
                    name_map(s, types.core_type_count_in_module(), "type")?;
165
                }
166
0
                Name::Table(s) => {
167
0
                    name_map(s, types.table_count(), "table")?;
168
                }
169
0
                Name::Memory(s) => {
170
0
                    name_map(s, types.memory_count(), "memory")?;
171
                }
172
0
                Name::Global(s) => {
173
0
                    name_map(s, types.global_count(), "global")?;
174
                }
175
0
                Name::Local(s) => {
176
0
                    self.name_local_max_per_function =
177
0
                        indirect_name_map(s, types.function_count(), "func", "local")?;
178
179
                    // Record the number of parameters for all functions to
180
                    // avoid needing `validator` over in function validation.
181
0
                    for i in 0..self.name_local_max_per_function.len() {
182
0
                        let i = i as u32;
183
0
                        let ty = types.core_function_at(i);
184
0
                        let params = match &types[ty].composite_type.inner {
185
0
                            CompositeInnerType::Func(ty) => ty.params().len() as u32,
186
0
                            _ => 0,
187
                        };
188
0
                        self.params_per_function.push(params);
189
                    }
190
191
                    // Imported functions only have local for their type's parameters,
192
                    // and defined functions must get validated later.
193
0
                    let imported_funcs_to_validate =
194
0
                        num_imported_functions(types).min(self.name_local_max_per_function.len());
195
0
                    validate_indirect_name_map(
196
0
                        &self.name_local_max_per_function[..imported_funcs_to_validate],
197
0
                        "local name",
198
0
                        |i, _offset| Ok(self.params_per_function[i as usize]),
199
0
                    )?;
200
                }
201
0
                Name::Label(s) => {
202
0
                    self.name_label_max_per_function =
203
0
                        indirect_name_map(s, types.function_count(), "func", "label")?;
204
205
                    // Imported functions have no labels, and defined functions
206
                    // get validated later.
207
0
                    let imported_funcs_to_validate =
208
0
                        num_imported_functions(types).min(self.name_label_max_per_function.len());
209
0
                    validate_indirect_name_map(
210
0
                        &self.name_label_max_per_function[..imported_funcs_to_validate],
211
0
                        "label name",
212
                        |_i, _offset| Ok(0),
213
0
                    )?;
214
                }
215
0
                Name::Element(s) => {
216
0
                    name_map(s, types.element_count(), "element")?;
217
                }
218
0
                Name::Data(s) => {
219
0
                    name_map(s, self.num_data, "data")?;
220
                }
221
0
                Name::Field(s) => {
222
0
                    let max =
223
0
                        indirect_name_map(s, types.core_type_count_in_module(), "type", "field")?;
224
0
                    validate_indirect_name_map(&max, "field name", |i, offset| {
225
0
                        let ty = types.core_type_at_in_module(i);
226
0
                        match &types[ty].composite_type.inner {
227
0
                            CompositeInnerType::Struct(ty) => Ok(ty.fields.len() as u32),
228
                            _ => {
229
0
                                bail!(offset, "field name specified when type {i} is not a struct")
230
                            }
231
                        }
232
0
                    })?;
233
                }
234
0
                Name::Tag(s) => {
235
0
                    name_map(s, types.tag_count(), "tag")?;
236
                }
237
0
                Name::Parameter(s) => {
238
0
                    let max =
239
0
                        indirect_name_map(s, types.core_type_count_in_module(), "type", "param")?;
240
0
                    validate_indirect_name_map(&max, "parameter name", |i, offset| {
241
0
                        let ty = types.core_type_at_in_module(i);
242
0
                        match &types[ty].composite_type.inner {
243
0
                            CompositeInnerType::Func(ty) => Ok(ty.params().len() as u32),
244
                            _ => {
245
0
                                bail!(
246
0
                                    offset,
247
                                    "parameter name specified when type {i} is not a func"
248
                                )
249
                            }
250
                        }
251
0
                    })?;
252
                }
253
0
                Name::TagParameter(s) => {
254
0
                    let max = indirect_name_map(s, types.tag_count(), "tag", "param")?;
255
0
                    validate_indirect_name_map(&max, "tag parameter name", |i, offset| {
256
0
                        let ty = types.tag_at(i);
257
0
                        match &types[ty].composite_type.inner {
258
0
                            CompositeInnerType::Func(ty) => Ok(ty.params().len() as u32),
259
0
                            _ => bail!(offset, "tag {i} not typed as a func"),
260
                        }
261
0
                    })?;
262
                }
263
0
                Name::Unknown { range, ty, .. } => {
264
0
                    bail!(range.start, "unknown name subsection: {ty}");
265
                }
266
            }
267
        }
268
0
        Ok(())
269
0
    }
270
271
0
    fn branch_hint_section(
272
0
        &mut self,
273
0
        hints: BranchHintSectionReader<'_>,
274
0
        validator: &Validator,
275
0
    ) -> Result<()> {
276
0
        if self.is_component {
277
0
            bail!(
278
0
                hints.range().start,
279
                "core module branch hint section in a component"
280
            );
281
0
        }
282
0
        if self.seen_branch_hints {
283
0
            bail!(hints.range().start, "duplicate branch hint section");
284
0
        }
285
0
        self.seen_branch_hints = true;
286
0
        let types = validator.types(0).unwrap();
287
0
        let num_imported = u32::try_from(num_imported_functions(types)).unwrap();
288
0
        let num_funcs = types.function_count();
289
0
        let mut prev = None;
290
0
        for func in hints.into_iter_with_offsets() {
291
0
            let (offset, func) = func?;
292
0
            if let Some(prev) = prev {
293
0
                if prev >= func.func {
294
0
                    bail!(offset, "branch hints must be sorted by function index");
295
0
                }
296
0
            }
297
0
            prev = Some(func.func);
298
299
            // Branch hints can only be specified for defined functions, and
300
            // only those known so far in the module.
301
0
            if func.func < num_imported || func.func >= num_funcs {
302
0
                bail!(
303
0
                    offset,
304
                    "invalid function index {} in branch hint section",
305
                    func.func
306
                );
307
0
            }
308
309
0
            while self.per_function_hints.len() <= func.func as usize {
310
0
                self.per_function_hints.push(Vec::new());
311
0
            }
312
313
0
            let hints = &mut self.per_function_hints[func.func as usize];
314
0
            let mut prev = None;
315
0
            for hint in func.hints.into_iter_with_offsets() {
316
0
                let (offset, hint) = hint?;
317
0
                if let Some(prev) = prev {
318
0
                    if prev >= hint.func_offset {
319
0
                        bail!(offset, "branch hints must be sorted by function offset");
320
0
                    }
321
0
                }
322
0
                prev = Some(hint.func_offset);
323
0
                hints.push((hint.func_offset, offset));
324
            }
325
        }
326
0
        Ok(())
327
0
    }
328
329
0
    fn code_section_entry(&self, func_index: u32, body: &FunctionBody<'_>) -> Result<()> {
330
0
        if let Some(max) = self.name_local_max_per_function.get(func_index as usize) {
331
0
            let mut locals = self.params_per_function[func_index as usize];
332
0
            for cnt in body.get_locals_reader()? {
333
0
                locals += cnt?.0;
334
            }
335
            if let NameMax::Index {
336
0
                index,
337
0
                offset_specifying_index,
338
0
            } = max
339
            {
340
0
                if *index >= locals {
341
0
                    bail!(*offset_specifying_index, "invalid local index {index}");
342
0
                }
343
0
            }
344
0
        }
345
346
0
        let mut hints = self
347
0
            .per_function_hints
348
0
            .get(func_index as usize)
349
0
            .map(|v| v.as_slice())
350
0
            .unwrap_or(&[]);
351
352
0
        let mut labels = 0;
353
0
        let mut ops = body.get_operators_reader()?;
354
0
        while !ops.eof() {
355
0
            let cur_func_offset =
356
0
                u32::try_from(ops.original_position() - body.range().start).unwrap();
357
0
            let branch_hint_offset = match hints.first() {
358
0
                Some(&(func_offset, hint_offset)) => {
359
0
                    if func_offset > cur_func_offset {
360
0
                        None
361
0
                    } else if func_offset == cur_func_offset {
362
0
                        hints = &hints[1..];
363
0
                        Some(hint_offset)
364
                    } else {
365
0
                        bail!(hint_offset, "branch hint for bytes between instructions");
366
                    }
367
                }
368
0
                None => None,
369
            };
370
371
0
            let operator = ops.read()?;
372
373
            // Keep track of the number of labels in this function to validate
374
            // the name subsection for labels.
375
0
            match &operator {
376
                Operator::If { .. }
377
                | Operator::Block { .. }
378
                | Operator::Loop { .. }
379
                | Operator::Try { .. }
380
0
                | Operator::TryTable { .. } => {
381
0
                    labels += 1;
382
0
                }
383
0
                _ => {}
384
            }
385
386
            // Validate that if this instruction has a branch hint it's allowed
387
            // to have one.
388
0
            match &operator {
389
0
                Operator::If { .. } | Operator::BrIf { .. } => {}
390
                _ => {
391
0
                    if let Some(offset) = branch_hint_offset {
392
0
                        bail!(offset, "branch hint for instruction that isn't if or br_if")
393
0
                    }
394
                }
395
            }
396
        }
397
398
0
        if let Some((_, hint_offset)) = hints.first() {
399
0
            bail!(*hint_offset, "branch hint for nonexistent instruction");
400
0
        }
401
402
0
        if let Some(max) = self.name_label_max_per_function.get(func_index as usize) {
403
            if let NameMax::Index {
404
0
                index,
405
0
                offset_specifying_index,
406
0
            } = max
407
            {
408
0
                if *index >= labels {
409
0
                    bail!(*offset_specifying_index, "invalid label index {index}");
410
0
                }
411
0
            }
412
0
        }
413
0
        Ok(())
414
0
    }
415
}
416
417
0
fn validate_indirect_name_map(
418
0
    max: &[NameMax],
419
0
    desc: &str,
420
0
    mut get_max: impl FnMut(u32, u64) -> Result<u32>,
421
0
) -> Result<()> {
422
0
    for (i, max) in max.iter().enumerate() {
423
0
        let offset = match max {
424
            NameMax::Index {
425
0
                offset_specifying_index,
426
                ..
427
            }
428
            | NameMax::EmptyList {
429
0
                offset_specifying_index,
430
0
            } => *offset_specifying_index,
431
0
            NameMax::None => continue,
432
        };
433
0
        let i = i as u32;
434
0
        let max_index = get_max(i, offset)?;
435
0
        if let NameMax::Index { index, .. } = max {
436
0
            if *index >= max_index {
437
0
                bail!(offset, "invalid {desc} index {index}");
438
0
            }
439
0
        }
440
    }
441
0
    Ok(())
442
0
}
Unexecuted instantiation: wasmparser::validator::custom::validate_indirect_name_map::<<wasmparser::validator::custom::State>::name_section::{closure#0}>
Unexecuted instantiation: wasmparser::validator::custom::validate_indirect_name_map::<<wasmparser::validator::custom::State>::name_section::{closure#2}>
Unexecuted instantiation: wasmparser::validator::custom::validate_indirect_name_map::<<wasmparser::validator::custom::State>::name_section::{closure#3}>
Unexecuted instantiation: wasmparser::validator::custom::validate_indirect_name_map::<<wasmparser::validator::custom::State>::name_section::{closure#4}>
Unexecuted instantiation: wasmparser::validator::custom::validate_indirect_name_map::<<wasmparser::validator::custom::State>::name_section::{closure#1}>
443
444
0
fn indirect_name_map(
445
0
    mut names: IndirectNameMap<'_>,
446
0
    items: u32,
447
0
    desc: &str,
448
0
    item_desc: &str,
449
0
) -> Result<Vec<NameMax>> {
450
0
    let mut max = vec![NameMax::None; items as usize];
451
    loop {
452
0
        let offset = names.names.original_position();
453
0
        let naming = match names.next() {
454
0
            Some(naming) => naming?,
455
0
            None => break,
456
        };
457
0
        if naming.index >= items {
458
0
            bail!(offset, "invalid {desc} naming index {}", naming.index);
459
0
        }
460
461
0
        max[naming.index as usize] = match name_map(naming.names, u32::MAX, item_desc)? {
462
0
            Some((i, offset)) => NameMax::Index {
463
0
                index: i,
464
0
                offset_specifying_index: offset,
465
0
            },
466
0
            None => NameMax::EmptyList {
467
0
                offset_specifying_index: offset,
468
0
            },
469
        };
470
    }
471
0
    Ok(max)
472
0
}
473
474
0
fn name_map(mut names: NameMap<'_>, items: u32, desc: &str) -> Result<Option<(u32, u64)>> {
475
0
    let mut max = None;
476
    loop {
477
0
        let offset = names.names.original_position();
478
0
        let naming = match names.next() {
479
0
            Some(naming) => naming?,
480
0
            None => break,
481
        };
482
0
        if naming.index >= items {
483
0
            bail!(offset, "invalid {desc} naming index {}", naming.index);
484
0
        }
485
0
        max = Some((naming.index, offset));
486
    }
487
0
    Ok(max)
488
0
}
489
490
0
fn num_imported_functions(types: TypesRef<'_>) -> usize {
491
0
    types
492
0
        .core_imports()
493
0
        .map(|i| {
494
0
            i.filter(|(_, _, i)| matches!(i, EntityType::Func(_) | EntityType::FuncExact(_)))
495
0
                .count()
496
0
        })
497
0
        .unwrap_or(0)
498
0
}