Coverage Report

Created: 2026-08-28 08:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wasm-tools/crates/wasmparser/src/validator.rs
Line
Count
Source
1
/* Copyright 2018 Mozilla Foundation
2
 *
3
 * Licensed under the Apache License, Version 2.0 (the "License");
4
 * you may not use this file except in compliance with the License.
5
 * You may obtain a copy of the License at
6
 *
7
 *     http://www.apache.org/licenses/LICENSE-2.0
8
 *
9
 * Unless required by applicable law or agreed to in writing, software
10
 * distributed under the License is distributed on an "AS IS" BASIS,
11
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
 * See the License for the specific language governing permissions and
13
 * limitations under the License.
14
 */
15
16
use crate::prelude::*;
17
use crate::{
18
    AbstractHeapType, Encoding, Error, FromReader, FunctionBody, HeapType, Parser, Payload,
19
    RefType, Result, SectionLimited, ValType, WASM_MODULE_VERSION, WasmFeatures, limits::*,
20
    require_feature,
21
};
22
use ::core::mem;
23
use ::core::ops::Range;
24
use ::core::sync::atomic::{AtomicUsize, Ordering};
25
use alloc::sync::Arc;
26
27
/// Test whether the given buffer contains a valid WebAssembly module or component,
28
/// analogous to [`WebAssembly.validate`][js] in the JS API.
29
///
30
/// This functions requires the bytes to validate are entirely resident in memory.
31
/// Additionally this validates the given bytes with the default set of WebAssembly
32
/// features implemented by `wasmparser`.
33
///
34
/// For more fine-tuned control over validation it's recommended to review the
35
/// documentation of [`Validator`].
36
///
37
/// Upon success, the type information for the top-level module or component will
38
/// be returned.
39
///
40
/// [js]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate
41
1
pub fn validate(bytes: &[u8]) -> Result<Types> {
42
1
    Validator::new().validate_all(bytes)
43
1
}
44
45
#[test]
46
fn test_validate() {
47
    assert!(validate(&[0x0, 0x61, 0x73, 0x6d, 0x1, 0x0, 0x0, 0x0]).is_ok());
48
    assert!(validate(&[0x0, 0x61, 0x73, 0x6d, 0x2, 0x0, 0x0, 0x0]).is_err());
49
}
50
51
#[cfg(feature = "component-model")]
52
mod component;
53
#[cfg(feature = "component-model")]
54
pub mod component_types;
55
mod core;
56
mod func;
57
#[cfg(feature = "component-model")]
58
pub mod names;
59
mod operators;
60
pub mod types;
61
62
#[cfg(feature = "component-model")]
63
use self::component::*;
64
pub use self::core::ValidatorResources;
65
use self::core::*;
66
use self::types::{TypeAlloc, Types, TypesRef};
67
pub use func::{FuncToValidate, FuncValidator, FuncValidatorAllocations};
68
pub use operators::Frame;
69
70
1.10M
fn check_max(cur_len: usize, amt_added: u32, max: usize, desc: &str, offset: u64) -> Result<()> {
71
1.10M
    if max
72
1.10M
        .checked_sub(cur_len)
73
1.10M
        .and_then(|amt| amt.checked_sub(amt_added as usize))
74
1.10M
        .is_none()
75
    {
76
0
        if max == 1 {
77
0
            bail!(offset, "multiple {desc}");
78
0
        }
79
80
0
        bail!(offset, "{desc} count exceeds limit of {max}");
81
1.10M
    }
82
83
1.10M
    Ok(())
84
1.10M
}
85
86
688k
fn combine_type_sizes(a: u32, b: u32, offset: u64) -> Result<u32> {
87
688k
    match a.checked_add(b) {
88
688k
        Some(sum) if sum < MAX_WASM_TYPE_SIZE => Ok(sum),
89
0
        _ => Err(format_err!(
90
0
            offset,
91
0
            "effective type size exceeds the limit of {MAX_WASM_TYPE_SIZE}",
92
0
        )),
93
    }
94
688k
}
95
96
/// A unique identifier for a particular `Validator`.
97
///
98
/// Allows you to save the `ValidatorId` of the [`Validator`][crate::Validator]
99
/// you get identifiers out of (e.g. [`CoreTypeId`][crate::types::CoreTypeId])
100
/// and then later assert that you are pairing those identifiers with the same
101
/// `Validator` instance when accessing the identifier's associated data.
102
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
103
pub struct ValidatorId(usize);
104
105
impl Default for ValidatorId {
106
    #[inline]
107
8.40k
    fn default() -> Self {
108
        static ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
109
8.40k
        ValidatorId(ID_COUNTER.fetch_add(1, Ordering::AcqRel))
110
8.40k
    }
111
}
112
113
/// Validator for a WebAssembly binary module or component.
114
///
115
/// This structure encapsulates state necessary to validate a WebAssembly
116
/// binary. This implements validation as defined by the [core
117
/// specification][core]. A `Validator` is designed, like
118
/// [`Parser`], to accept incremental input over time.
119
/// Additionally a `Validator` is also designed for parallel validation of
120
/// functions as they are received.
121
///
122
/// It's expected that you'll be using a [`Parser`] in tandem with a
123
/// `Validator`. As each [`Payload`](crate::Payload) is received from a
124
/// [`Parser`] you'll pass it into a `Validator` to test the validity of the
125
/// payload. Note that all payloads received from a [`Parser`] are expected to
126
/// be passed to a [`Validator`]. For example if you receive
127
/// [`Payload::TypeSection`](crate::Payload) you'll call
128
/// [`Validator::type_section`] to validate this.
129
///
130
/// The design of [`Validator`] is intended that you'll interleave, in your own
131
/// application's processing, calls to validation. Each variant, after it's
132
/// received, will be validated and then your application would proceed as
133
/// usual. At all times, however, you'll have access to the [`Validator`] and
134
/// the validation context up to that point. This enables applications to check
135
/// the types of functions and learn how many globals there are, for example.
136
///
137
/// [core]: https://webassembly.github.io/spec/core/valid/index.html
138
#[derive(Default)]
139
pub struct Validator {
140
    id: ValidatorId,
141
142
    /// The current state of the validator.
143
    state: State,
144
145
    /// The global type space used by the validator and any sub-validators.
146
    types: TypeAlloc,
147
148
    /// The module state when parsing a WebAssembly module.
149
    module: Option<ModuleState>,
150
151
    /// With the component model enabled, this stores the pushed component states.
152
    /// The top of the stack is the current component state.
153
    #[cfg(feature = "component-model")]
154
    components: Vec<ComponentState>,
155
156
    /// Enabled WebAssembly feature flags, dictating what's valid and what
157
    /// isn't.
158
    features: WasmFeatures,
159
}
160
161
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
162
enum State {
163
    /// A header has not yet been parsed.
164
    ///
165
    /// The value is the expected encoding for the header.
166
    Unparsed(Option<Encoding>),
167
    /// A module header has been parsed.
168
    ///
169
    /// The associated module state is available via [`Validator::module`].
170
    Module,
171
    /// A component header has been parsed.
172
    ///
173
    /// The associated component state exists at the top of the
174
    /// validator's [`Validator::components`] stack.
175
    #[cfg(feature = "component-model")]
176
    Component,
177
    /// The parse has completed and no more data is expected.
178
    End,
179
}
180
181
impl State {
182
498k
    fn ensure_parsable(&self, offset: u64) -> Result<()> {
183
498k
        match self {
184
386k
            Self::Module => Ok(()),
185
            #[cfg(feature = "component-model")]
186
112k
            Self::Component => Ok(()),
187
0
            Self::Unparsed(_) => Err(Error::new(
188
0
                "unexpected section before header was parsed",
189
0
                offset,
190
0
            )),
191
0
            Self::End => Err(Error::new(
192
0
                "unexpected section after parsing has completed",
193
0
                offset,
194
0
            )),
195
        }
196
498k
    }
197
198
386k
    fn ensure_module(&self, section: &str, offset: u64) -> Result<()> {
199
386k
        self.ensure_parsable(offset)?;
200
386k
        let _ = section;
201
202
386k
        match self {
203
386k
            Self::Module => Ok(()),
204
            #[cfg(feature = "component-model")]
205
0
            Self::Component => Err(format_err!(
206
0
                offset,
207
0
                "unexpected module {section} section while parsing a component",
208
0
            )),
209
0
            _ => unreachable!(),
210
        }
211
386k
    }
212
213
    #[cfg(feature = "component-model")]
214
112k
    fn ensure_component(&self, section: &str, offset: u64) -> Result<()> {
215
112k
        self.ensure_parsable(offset)?;
216
217
112k
        match self {
218
112k
            Self::Component => Ok(()),
219
0
            Self::Module => Err(format_err!(
220
0
                offset,
221
0
                "unexpected component {section} section while parsing a module",
222
0
            )),
223
0
            _ => unreachable!(),
224
        }
225
112k
    }
226
}
227
228
impl Default for State {
229
8.40k
    fn default() -> Self {
230
8.40k
        Self::Unparsed(None)
231
8.40k
    }
232
}
233
234
impl WasmFeatures {
235
    /// NOTE: This only checks that the value type corresponds to the feature set!!
236
    ///
237
    /// To check that reference types are valid, we need access to the module
238
    /// types. Use module.check_value_type.
239
12.6M
    pub(crate) fn check_value_type(&self, ty: ValType, offset: u64) -> Result<()> {
240
12.6M
        match ty {
241
4.79M
            ValType::I32 | ValType::I64 => Ok(()),
242
            ValType::F32 | ValType::F64 => {
243
5.85M
                require_feature::floats(*self, "floating-point support is disabled", offset)
244
            }
245
1.94M
            ValType::Ref(r) => self.check_ref_type(r, offset),
246
48.5k
            ValType::V128 => require_feature::simd(*self, "SIMD support is not enabled", offset),
247
        }
248
12.6M
    }
249
250
2.76M
    pub(crate) fn check_ref_type(&self, r: RefType, offset: u64) -> Result<()> {
251
2.76M
        require_feature::reference_types(*self, "reference types support is not enabled", offset)?;
252
2.76M
        match r.heap_type() {
253
            HeapType::Concrete(_) => {
254
                // Note that `self.gc_types()` is not checked here because
255
                // concrete pointers to function types are allowed. GC types
256
                // are disallowed by instead rejecting the definition of
257
                // array/struct types and only allowing the definition of
258
                // function types.
259
260
                // Indexed types require either the function-references or gc
261
                // proposal as gc implies function references here.
262
136k
                if self.gc() {
263
136k
                    Ok(())
264
                } else {
265
0
                    require_feature::function_references(
266
0
                        *self,
267
                        "function references required for index reference types",
268
0
                        offset,
269
                    )
270
                }
271
            }
272
            HeapType::Exact(_) => {
273
                // Exact types were introduced with the custom descriptors
274
                // proposal.
275
0
                require_feature::custom_descriptors(
276
0
                    *self,
277
                    "custom descriptors required for exact reference types",
278
0
                    offset,
279
                )
280
            }
281
2.62M
            HeapType::Abstract { shared, ty } => {
282
                use AbstractHeapType::*;
283
2.62M
                if shared {
284
10.2k
                    require_feature::shared_everything_threads(
285
10.2k
                        *self,
286
                        "shared reference types require the shared-everything-threads proposal",
287
10.2k
                        offset,
288
0
                    )?;
289
2.61M
                }
290
291
                // Apply the "gc-types" feature which disallows all heap types
292
                // except exnref/funcref.
293
2.62M
                if ty != Func && ty != Exn {
294
635k
                    require_feature::gc_types(
295
635k
                        *self,
296
                        "gc types are disallowed but found type which requires gc",
297
635k
                        offset,
298
0
                    )?;
299
1.99M
                }
300
301
2.62M
                match (ty, r.is_nullable()) {
302
                    // funcref/externref only require `reference-types`.
303
2.23M
                    (Func, true) | (Extern, true) => Ok(()),
304
305
                    // Non-nullable func/extern references requires the
306
                    // `function-references` proposal.
307
0
                    (Func | Extern, false) => require_feature::function_references(
308
0
                        *self,
309
                        "function references required for non-nullable types",
310
0
                        offset,
311
                    ),
312
313
                    // These types were added in the gc proposal.
314
                    (Any | None | Eq | Struct | Array | I31 | NoExtern | NoFunc, _) => {
315
171k
                        require_feature::gc(
316
171k
                            *self,
317
                            "heap types not supported without the gc feature",
318
171k
                            offset,
319
                        )
320
                    }
321
322
                    // These types were added in the exception-handling proposal.
323
223k
                    (Exn | NoExn, _) => require_feature::exceptions(
324
223k
                        *self,
325
                        "exception refs not supported without the exception handling feature",
326
223k
                        offset,
327
                    ),
328
329
                    // These types were added in the stack switching proposal.
330
0
                    (Cont | NoCont, _) => require_feature::stack_switching(
331
0
                        *self,
332
                        "continuation refs not supported without the stack switching feature",
333
0
                        offset,
334
                    ),
335
                }
336
            }
337
        }
338
2.76M
    }
339
}
340
341
/// Possible return values from [`Validator::payload`].
342
#[allow(clippy::large_enum_variant)]
343
pub enum ValidPayload<'a> {
344
    /// The payload validated, no further action need be taken.
345
    Ok,
346
    /// The payload validated, but it started a nested module or component.
347
    ///
348
    /// This result indicates that the specified parser should be used instead
349
    /// of the currently-used parser until this returned one ends.
350
    Parser(Parser),
351
    /// A function was found to be validated.
352
    Func(FuncToValidate<ValidatorResources>, FunctionBody<'a>),
353
    /// The end payload was validated and the types known to the validator
354
    /// are provided.
355
    End(Types),
356
}
357
358
impl Validator {
359
    /// Creates a new [`Validator`] ready to validate a WebAssembly module
360
    /// or component.
361
    ///
362
    /// The new validator will receive payloads parsed from
363
    /// [`Parser`], and expects the first payload received to be
364
    /// the version header from the parser.
365
8.40k
    pub fn new() -> Validator {
366
8.40k
        Validator::default()
367
8.40k
    }
368
369
    /// Creates a new [`Validator`] which has the specified set of wasm
370
    /// features activated for validation.
371
    ///
372
    /// This function is the same as [`Validator::new`] except it also allows
373
    /// you to customize the active wasm features in use for validation. This
374
    /// can allow enabling experimental proposals or also turning off
375
    /// on-by-default wasm proposals.
376
8.39k
    pub fn new_with_features(features: WasmFeatures) -> Validator {
377
8.39k
        let mut ret = Validator::new();
378
8.39k
        ret.features = features;
379
8.39k
        ret
380
8.39k
    }
381
382
    /// Returns the wasm features used for this validator.
383
0
    pub fn features(&self) -> &WasmFeatures {
384
0
        &self.features
385
0
    }
386
387
    /// Reset this validator's state such that it is ready to validate a new
388
    /// Wasm module or component.
389
    ///
390
    /// This does *not* clear or reset the internal state keeping track of
391
    /// validated (and deduplicated and canonicalized) types, allowing you to
392
    /// use the same type identifiers (such as
393
    /// [`CoreTypeId`][crate::types::CoreTypeId]) for the same types that are
394
    /// defined multiple times across different modules and components.
395
    ///
396
    /// # Panics
397
    ///
398
    /// This function will panic if the validator was mid-way through
399
    /// validating a binary. Validation must complete entirely or not have
400
    /// started at all for this method to be called.
401
    ///
402
    /// # Examples
403
    ///
404
    /// ```
405
    /// fn foo() -> anyhow::Result<()> {
406
    /// use wasmparser::Validator;
407
    ///
408
    /// let mut validator = Validator::default();
409
    ///
410
    /// // Two wasm modules, both of which define the same type, but at
411
    /// // different indices in their respective types index spaces.
412
    /// let wasm1 = wat::parse_str("
413
    ///     (module
414
    ///         (type $same_type (func (param i32) (result f64)))
415
    ///     )
416
    /// ")?;
417
    /// let wasm2 = wat::parse_str("
418
    ///     (module
419
    ///         (type $different_type (func))
420
    ///         (type $same_type (func (param i32) (result f64)))
421
    ///     )
422
    /// ")?;
423
    ///
424
    /// // Validate the first Wasm module and get the ID of its type.
425
    /// let types = validator.validate_all(&wasm1)?;
426
    /// let id1 = types.as_ref().core_type_at_in_module(0);
427
    ///
428
    /// // Reset the validator so we can parse the second wasm module inside
429
    /// // this validator's same context.
430
    /// validator.reset();
431
    ///
432
    /// // Validate the second Wasm module and get the ID of its second type,
433
    /// // which is the same type as the first Wasm module's only type.
434
    /// let types = validator.validate_all(&wasm2)?;
435
    /// let id2 = types.as_ref().core_type_at_in_module(1);
436
    ///
437
    /// // Because both modules were processed in the same `Validator`, they
438
    /// // share the same types context and therefore the same type defined
439
    /// // multiple times across different modules will be deduplicated and
440
    /// // assigned the same identifier!
441
    /// assert_eq!(id1, id2);
442
    /// assert_eq!(types[id1], types[id2]);
443
    /// # Ok(())
444
    /// # }
445
    /// # foo().unwrap()
446
    /// ```
447
0
    pub fn reset(&mut self) {
448
        let Validator {
449
            // Not changing the identifier; users should be able to observe that
450
            // they are using the same validation context, even after resetting.
451
            id: _,
452
453
            // Don't mess with `types`, we specifically want to reuse canonicalization.
454
            types: _,
455
456
            // Also leave features as they are. While this is perhaps not
457
            // strictly necessary, it helps us avoid weird bugs where we have
458
            // different views of what is or is not a valid type at different
459
            // times, despite using the same `TypeList` and hash consing
460
            // context, and therefore there could be moments in time where we
461
            // have "invalid" types inside our current types list.
462
            features: _,
463
464
0
            state,
465
0
            module,
466
            #[cfg(feature = "component-model")]
467
0
            components,
468
0
        } = self;
469
470
0
        assert!(
471
0
            matches!(state, State::End) || matches!(state, State::Unparsed(None)),
472
            "cannot reset a validator that did not successfully complete validation"
473
        );
474
0
        assert!(module.is_none());
475
        #[cfg(feature = "component-model")]
476
0
        assert!(components.is_empty());
477
478
0
        *state = State::default();
479
0
    }
480
481
    /// Get this validator's unique identifier.
482
    ///
483
    /// Allows you to assert that you are always working with the same
484
    /// `Validator` instance, when you can't otherwise statically ensure that
485
    /// property by e.g. storing a reference to the validator inside your
486
    /// structure.
487
0
    pub fn id(&self) -> ValidatorId {
488
0
        self.id
489
0
    }
490
491
    /// Validates an entire in-memory module or component with this validator.
492
    ///
493
    /// This function will internally create a [`Parser`] to parse the `bytes`
494
    /// provided. The entire module or component specified by `bytes` will be
495
    /// parsed and validated.
496
    ///
497
    /// Upon success, the type information for the top-level module or component
498
    /// will be returned.
499
5.33k
    pub fn validate_all(&mut self, bytes: &[u8]) -> Result<Types> {
500
5.33k
        let mut functions_to_validate = Vec::new();
501
5.33k
        let mut last_types = None;
502
5.33k
        let mut parser = Parser::new(0);
503
5.33k
        let _ = &mut parser;
504
        #[cfg(feature = "features")]
505
5.33k
        parser.set_features(self.features);
506
405k
        for payload in parser.parse_all(bytes) {
507
405k
            match self.payload(&payload?)? {
508
312k
                ValidPayload::Func(a, b) => {
509
312k
                    functions_to_validate.push((a, b));
510
312k
                }
511
7.88k
                ValidPayload::End(types) => {
512
7.88k
                    // Only the last (top-level) type information will be returned
513
7.88k
                    last_types = Some(types);
514
7.88k
                }
515
85.2k
                _ => {}
516
            }
517
        }
518
519
5.32k
        let mut allocs = FuncValidatorAllocations::default();
520
312k
        for (func, body) in functions_to_validate {
521
312k
            let mut validator = func.into_validator(allocs);
522
312k
            validator.validate(&body)?;
523
312k
            allocs = validator.into_allocations();
524
        }
525
526
5.32k
        Ok(last_types.unwrap())
527
5.33k
    }
528
529
    /// Gets the types known by the validator so far within the
530
    /// module/component `level` modules/components up from the
531
    /// module/component currently being parsed.
532
    ///
533
    /// For instance, calling `validator.types(0)` will get the types of the
534
    /// module/component currently being parsed, and `validator.types(1)` will
535
    /// get the types of the component containing that module/component.
536
    ///
537
    /// Returns `None` if there is no module/component that many levels up.
538
18.3k
    pub fn types(&self, mut level: usize) -> Option<TypesRef<'_>> {
539
18.3k
        if let Some(module) = &self.module {
540
9.95k
            if level == 0 {
541
9.95k
                return Some(TypesRef::from_module(self.id, &self.types, &module.module));
542
0
            } else {
543
0
                level -= 1;
544
0
                let _ = level;
545
0
            }
546
8.39k
        }
547
548
        #[cfg(feature = "component-model")]
549
8.39k
        return self
550
8.39k
            .components
551
8.39k
            .iter()
552
8.39k
            .nth_back(level)
553
8.39k
            .map(|component| TypesRef::from_component(self.id, &self.types, component));
554
        #[cfg(not(feature = "component-model"))]
555
        return None;
556
18.3k
    }
557
558
    /// Convenience function to validate a single [`Payload`].
559
    ///
560
    /// This function is intended to be used as a convenience. It will
561
    /// internally perform any validation necessary to validate the [`Payload`]
562
    /// provided. The convenience part is that you're likely already going to
563
    /// be matching on [`Payload`] in your application, at which point it's more
564
    /// appropriate to call the individual methods on [`Validator`] per-variant
565
    /// in [`Payload`], such as [`Validator::type_section`].
566
    ///
567
    /// This function returns a [`ValidPayload`] variant on success, indicating
568
    /// one of a few possible actions that need to be taken after a payload is
569
    /// validated. For example function contents are not validated here, they're
570
    /// returned through [`ValidPayload`] for validation by the caller.
571
543k
    pub fn payload<'a>(&mut self, payload: &Payload<'a>) -> Result<ValidPayload<'a>> {
572
        use crate::Payload::*;
573
543k
        match payload {
574
            Version {
575
16.0k
                num,
576
16.0k
                encoding,
577
16.0k
                range,
578
16.0k
            } => self.version(*num, *encoding, range)?,
579
580
            // Module sections
581
8.79k
            TypeSection(s) => self.type_section(s)?,
582
6.16k
            ImportSection(s) => self.import_section(s)?,
583
6.47k
            FunctionSection(s) => self.function_section(s)?,
584
2.49k
            TableSection(s) => self.table_section(s)?,
585
4.61k
            MemorySection(s) => self.memory_section(s)?,
586
259
            TagSection(s) => self.tag_section(s)?,
587
4.19k
            GlobalSection(s) => self.global_section(s)?,
588
5.53k
            ExportSection(s) => self.export_section(s)?,
589
1.96k
            StartSection { func, range } => self.start_section(*func, range)?,
590
2.22k
            ElementSection(s) => self.element_section(s)?,
591
1.16k
            DataCountSection { count, range } => self.data_count_section(*count, range)?,
592
            CodeSectionStart {
593
                count: _,
594
6.47k
                range,
595
                size: _,
596
6.47k
            } => self.code_section_start(range)?,
597
334k
            CodeSectionEntry(body) => {
598
334k
                let func_validator = self.code_section_entry(body)?;
599
334k
                return Ok(ValidPayload::Func(func_validator, body.clone()));
600
            }
601
1.67k
            DataSection(s) => self.data_section(s)?,
602
603
            // Component sections
604
            #[cfg(feature = "component-model")]
605
            ModuleSection {
606
4.27k
                parser,
607
4.27k
                unchecked_range: range,
608
                ..
609
            } => {
610
4.27k
                self.module_section(range)?;
611
4.27k
                return Ok(ValidPayload::Parser(parser.clone()));
612
            }
613
            #[cfg(feature = "component-model")]
614
5.45k
            InstanceSection(s) => self.instance_section(s)?,
615
            #[cfg(feature = "component-model")]
616
0
            CoreTypeSection(s) => self.core_type_section(s)?,
617
            #[cfg(feature = "component-model")]
618
            ComponentSection {
619
3.41k
                parser,
620
3.41k
                unchecked_range: range,
621
                ..
622
            } => {
623
3.41k
                self.component_section(range)?;
624
3.41k
                return Ok(ValidPayload::Parser(parser.clone()));
625
            }
626
            #[cfg(feature = "component-model")]
627
3.41k
            ComponentInstanceSection(s) => self.component_instance_section(s)?,
628
            #[cfg(feature = "component-model")]
629
11.0k
            ComponentAliasSection(s) => self.component_alias_section(s)?,
630
            #[cfg(feature = "component-model")]
631
36.5k
            ComponentTypeSection(s) => self.component_type_section(s)?,
632
            #[cfg(feature = "component-model")]
633
10.9k
            ComponentCanonicalSection(s) => self.component_canonical_section(s)?,
634
            #[cfg(feature = "component-model")]
635
0
            ComponentStartSection { start, range } => self.component_start_section(start, range)?,
636
            #[cfg(feature = "component-model")]
637
6.63k
            ComponentImportSection(s) => self.component_import_section(s)?,
638
            #[cfg(feature = "component-model")]
639
30.8k
            ComponentExportSection(s) => self.component_export_section(s)?,
640
641
16.0k
            End(offset) => return Ok(ValidPayload::End(self.end(*offset)?)),
642
643
12.9k
            CustomSection { .. } => {} // no validation for custom sections
644
0
            UnknownSection { id, range, .. } => self.unknown_section(*id, range)?,
645
        }
646
186k
        Ok(ValidPayload::Ok)
647
543k
    }
648
649
    /// Validates [`Payload::Version`](crate::Payload).
650
16.0k
    pub fn version(&mut self, num: u16, encoding: Encoding, range: &Range<u64>) -> Result<()> {
651
16.0k
        match &self.state {
652
16.0k
            State::Unparsed(expected) => {
653
16.0k
                if let Some(expected) = expected {
654
7.68k
                    if *expected != encoding {
655
0
                        bail!(
656
0
                            range.start,
657
                            "expected a version header for a {}",
658
0
                            match expected {
659
0
                                Encoding::Module => "module",
660
0
                                Encoding::Component => "component",
661
                            }
662
                        );
663
7.68k
                    }
664
8.40k
                }
665
            }
666
            _ => {
667
0
                return Err(Error::new("wasm version header out of order", range.start));
668
            }
669
        }
670
671
16.0k
        self.state = match encoding {
672
            Encoding::Module => {
673
9.24k
                if num == WASM_MODULE_VERSION {
674
9.24k
                    assert!(self.module.is_none());
675
9.24k
                    self.module = Some(ModuleState::new(self.features));
676
9.24k
                    State::Module
677
                } else {
678
0
                    bail!(range.start, "unknown binary version: {num:#x}");
679
                }
680
            }
681
            Encoding::Component => {
682
6.83k
                require_feature::component_model(
683
6.83k
                    self.features,
684
6.83k
                    format_args!(
685
                        "unknown binary version and encoding combination: {num:#x} and 0x1, \
686
                        note: encoded as a component but the WebAssembly component model feature \
687
                        is not enabled - enable the feature to allow component validation",
688
                    ),
689
6.83k
                    range.start,
690
0
                )?;
691
                #[cfg(feature = "component-model")]
692
6.83k
                if num == crate::WASM_COMPONENT_VERSION {
693
6.83k
                    self.components
694
6.83k
                        .push(ComponentState::new(ComponentKind::Component, self.features));
695
6.83k
                    State::Component
696
0
                } else if num < crate::WASM_COMPONENT_VERSION {
697
0
                    bail!(range.start, "unsupported component version: {num:#x}");
698
                } else {
699
0
                    bail!(range.start, "unknown component version: {num:#x}");
700
                }
701
                #[cfg(not(feature = "component-model"))]
702
                bail!(
703
                    range.start,
704
                    "component model validation support disabled \
705
                     at compile time"
706
                );
707
            }
708
        };
709
710
16.0k
        Ok(())
711
16.0k
    }
712
713
    /// Validates [`Payload::TypeSection`](crate::Payload).
714
8.79k
    pub fn type_section(&mut self, section: &crate::TypeSectionReader<'_>) -> Result<()> {
715
8.79k
        self.process_module_section(
716
8.79k
            section,
717
8.79k
            "type",
718
8.79k
            |state, _types, count, offset| {
719
8.79k
                check_max(
720
8.79k
                    state.module.types.len(),
721
8.79k
                    count,
722
                    MAX_WASM_TYPES,
723
8.79k
                    "types",
724
8.79k
                    offset,
725
0
                )?;
726
8.79k
                state.module.assert_mut().types.reserve(count as usize);
727
8.79k
                Ok(())
728
8.79k
            },
729
158k
            |state, types, rec_group, offset| {
730
158k
                state
731
158k
                    .module
732
158k
                    .assert_mut()
733
158k
                    .add_types(rec_group, types, offset, true)?;
734
158k
                Ok(())
735
158k
            },
736
        )
737
8.79k
    }
738
739
    /// Validates [`Payload::ImportSection`](crate::Payload).
740
    ///
741
    /// This method should only be called when parsing a module.
742
6.16k
    pub fn import_section(&mut self, section: &crate::ImportSectionReader<'_>) -> Result<()> {
743
6.16k
        self.process_module_section(
744
6.16k
            section,
745
6.16k
            "import",
746
6.16k
            |state, _, count, offset| {
747
6.16k
                check_max(
748
6.16k
                    state.module.imports.len(),
749
6.16k
                    count,
750
                    MAX_WASM_IMPORTS,
751
6.16k
                    "imports",
752
6.16k
                    offset,
753
0
                )?;
754
6.16k
                state.module.assert_mut().imports.reserve(count as usize);
755
6.16k
                Ok(())
756
6.16k
            },
757
45.3k
            |state, types, imports, _offset| {
758
45.3k
                let state = state.module.assert_mut();
759
106k
                for import_and_offset in imports {
760
106k
                    let (offset, import) = import_and_offset?;
761
106k
                    state.add_import(import, types, offset)?;
762
                }
763
45.3k
                Ok(())
764
45.3k
            },
765
        )
766
6.16k
    }
767
768
    /// Validates [`Payload::FunctionSection`](crate::Payload).
769
    ///
770
    /// This method should only be called when parsing a module.
771
6.47k
    pub fn function_section(&mut self, section: &crate::FunctionSectionReader<'_>) -> Result<()> {
772
6.47k
        self.process_module_section(
773
6.47k
            section,
774
6.47k
            "function",
775
6.47k
            |state, _, count, offset| {
776
6.47k
                check_max(
777
6.47k
                    state.module.functions.len(),
778
6.47k
                    count,
779
                    MAX_WASM_FUNCTIONS,
780
6.47k
                    "functions",
781
6.47k
                    offset,
782
0
                )?;
783
6.47k
                state.module.assert_mut().functions.reserve(count as usize);
784
6.47k
                Ok(())
785
6.47k
            },
786
334k
            |state, types, ty, offset| state.module.assert_mut().add_function(ty, types, offset),
787
        )
788
6.47k
    }
789
790
    /// Validates [`Payload::TableSection`](crate::Payload).
791
    ///
792
    /// This method should only be called when parsing a module.
793
2.49k
    pub fn table_section(&mut self, section: &crate::TableSectionReader<'_>) -> Result<()> {
794
2.49k
        self.process_module_section(
795
2.49k
            section,
796
2.49k
            "table",
797
2.49k
            |state, _, count, offset| {
798
2.49k
                check_max(
799
2.49k
                    state.module.tables.len(),
800
2.49k
                    count,
801
2.49k
                    state.module.max_tables(),
802
2.49k
                    "tables",
803
2.49k
                    offset,
804
0
                )?;
805
2.49k
                state.module.assert_mut().tables.reserve(count as usize);
806
2.49k
                Ok(())
807
2.49k
            },
808
17.1k
            |state, types, table, offset| state.add_table(table, types, offset),
809
        )
810
2.49k
    }
811
812
    /// Validates [`Payload::MemorySection`](crate::Payload).
813
    ///
814
    /// This method should only be called when parsing a module.
815
4.61k
    pub fn memory_section(&mut self, section: &crate::MemorySectionReader<'_>) -> Result<()> {
816
4.61k
        self.process_module_section(
817
4.61k
            section,
818
4.61k
            "memory",
819
4.61k
            |state, _, count, offset| {
820
4.61k
                check_max(
821
4.61k
                    state.module.memories.len(),
822
4.61k
                    count,
823
4.61k
                    state.module.max_memories(),
824
4.61k
                    "memories",
825
4.61k
                    offset,
826
0
                )?;
827
4.61k
                state.module.assert_mut().memories.reserve(count as usize);
828
4.61k
                Ok(())
829
4.61k
            },
830
22.5k
            |state, _, ty, offset| state.module.assert_mut().add_memory(ty, offset),
831
        )
832
4.61k
    }
833
834
    /// Validates [`Payload::TagSection`](crate::Payload).
835
    ///
836
    /// This method should only be called when parsing a module.
837
259
    pub fn tag_section(&mut self, section: &crate::TagSectionReader<'_>) -> Result<()> {
838
259
        require_feature::exceptions(
839
259
            self.features,
840
            "exceptions proposal not enabled",
841
259
            section.range().start,
842
0
        )?;
843
259
        self.process_module_section(
844
259
            section,
845
259
            "tag",
846
259
            |state, _, count, offset| {
847
259
                check_max(
848
259
                    state.module.tags.len(),
849
259
                    count,
850
                    MAX_WASM_TAGS,
851
259
                    "tags",
852
259
                    offset,
853
0
                )?;
854
259
                state.module.assert_mut().tags.reserve(count as usize);
855
259
                Ok(())
856
259
            },
857
8.27k
            |state, types, ty, offset| state.module.assert_mut().add_tag(ty, types, offset),
858
        )
859
259
    }
860
861
    /// Validates [`Payload::GlobalSection`](crate::Payload).
862
    ///
863
    /// This method should only be called when parsing a module.
864
4.19k
    pub fn global_section(&mut self, section: &crate::GlobalSectionReader<'_>) -> Result<()> {
865
4.19k
        self.process_module_section(
866
4.19k
            section,
867
4.19k
            "global",
868
4.19k
            |state, _, count, offset| {
869
4.19k
                check_max(
870
4.19k
                    state.module.globals.len(),
871
4.19k
                    count,
872
                    MAX_WASM_GLOBALS,
873
4.19k
                    "globals",
874
4.19k
                    offset,
875
0
                )?;
876
4.19k
                state.module.assert_mut().globals.reserve(count as usize);
877
4.19k
                Ok(())
878
4.19k
            },
879
146k
            |state, types, global, offset| state.add_global(global, types, offset),
880
        )
881
4.19k
    }
882
883
    /// Validates [`Payload::ExportSection`](crate::Payload).
884
    ///
885
    /// This method should only be called when parsing a module.
886
5.53k
    pub fn export_section(&mut self, section: &crate::ExportSectionReader<'_>) -> Result<()> {
887
5.53k
        self.process_module_section(
888
5.53k
            section,
889
5.53k
            "export",
890
5.53k
            |state, _, count, offset| {
891
5.53k
                check_max(
892
5.53k
                    state.module.exports.len(),
893
5.53k
                    count,
894
                    MAX_WASM_EXPORTS,
895
5.53k
                    "exports",
896
5.53k
                    offset,
897
0
                )?;
898
5.53k
                state.module.assert_mut().exports.reserve(count as usize);
899
5.53k
                Ok(())
900
5.53k
            },
901
69.4k
            |state, types, e, offset| {
902
69.4k
                let state = state.module.assert_mut();
903
69.4k
                let ty = state.export_to_entity_type(&e, offset)?;
904
69.4k
                state.add_export(e.name, ty, offset, false /* checked above */, types)
905
69.4k
            },
906
        )
907
5.53k
    }
908
909
    /// Validates [`Payload::StartSection`](crate::Payload).
910
    ///
911
    /// This method should only be called when parsing a module.
912
1.96k
    pub fn start_section(&mut self, func: u32, range: &Range<u64>) -> Result<()> {
913
1.96k
        let offset = range.start;
914
1.96k
        self.state.ensure_module("start", offset)?;
915
1.96k
        let state = self.module.as_mut().unwrap();
916
917
1.96k
        let ty = state.module.get_func_type(func, &self.types, offset)?;
918
1.96k
        if !ty.params().is_empty() || !ty.results().is_empty() {
919
0
            return Err(Error::new("invalid start function type", offset));
920
1.96k
        }
921
922
1.96k
        Ok(())
923
1.96k
    }
924
925
    /// Validates [`Payload::ElementSection`](crate::Payload).
926
    ///
927
    /// This method should only be called when parsing a module.
928
2.22k
    pub fn element_section(&mut self, section: &crate::ElementSectionReader<'_>) -> Result<()> {
929
2.22k
        self.process_module_section(
930
2.22k
            section,
931
2.22k
            "element",
932
2.22k
            |state, _, count, offset| {
933
2.22k
                check_max(
934
2.22k
                    state.module.element_types.len(),
935
2.22k
                    count,
936
                    MAX_WASM_ELEMENT_SEGMENTS,
937
2.22k
                    "element segments",
938
2.22k
                    offset,
939
0
                )?;
940
2.22k
                state
941
2.22k
                    .module
942
2.22k
                    .assert_mut()
943
2.22k
                    .element_types
944
2.22k
                    .reserve(count as usize);
945
2.22k
                Ok(())
946
2.22k
            },
947
38.9k
            |state, types, e, offset| state.add_element_segment(e, types, offset),
948
        )
949
2.22k
    }
950
951
    /// Validates [`Payload::DataCountSection`](crate::Payload).
952
    ///
953
    /// This method should only be called when parsing a module.
954
1.16k
    pub fn data_count_section(&mut self, count: u32, range: &Range<u64>) -> Result<()> {
955
1.16k
        let offset = range.start;
956
1.16k
        self.state.ensure_module("data count", offset)?;
957
958
1.16k
        let state = self.module.as_mut().unwrap();
959
960
1.16k
        if count > MAX_WASM_DATA_SEGMENTS as u32 {
961
0
            return Err(Error::new(
962
0
                "data count section specifies too many data segments",
963
0
                offset,
964
0
            ));
965
1.16k
        }
966
967
1.16k
        state.module.assert_mut().data_count = Some(count);
968
1.16k
        Ok(())
969
1.16k
    }
970
971
    /// Validates [`Payload::CodeSectionStart`](crate::Payload).
972
    ///
973
    /// This method should only be called when parsing a module.
974
6.47k
    pub fn code_section_start(&mut self, range: &Range<u64>) -> Result<()> {
975
6.47k
        let offset = range.start;
976
6.47k
        self.state.ensure_module("code", offset)?;
977
978
6.47k
        let state = self.module.as_mut().unwrap();
979
980
        // Take a snapshot of the types when we start the code section.
981
6.47k
        state.module.assert_mut().snapshot = Some(Arc::new(self.types.commit()));
982
983
6.47k
        Ok(())
984
6.47k
    }
985
986
    /// Validates [`Payload::CodeSectionEntry`](crate::Payload).
987
    ///
988
    /// This function will prepare a [`FuncToValidate`] which can be used to
989
    /// create a [`FuncValidator`] to validate the function. The function body
990
    /// provided will not be parsed or validated by this function.
991
    ///
992
    /// Note that the returned [`FuncToValidate`] is "connected" to this
993
    /// [`Validator`] in that it uses the internal context of this validator for
994
    /// validating the function. The [`FuncToValidate`] can be sent to another
995
    /// thread, for example, to offload actual processing of functions
996
    /// elsewhere.
997
    ///
998
    /// This method should only be called when parsing a module.
999
334k
    pub fn code_section_entry(
1000
334k
        &mut self,
1001
334k
        body: &crate::FunctionBody,
1002
334k
    ) -> Result<FuncToValidate<ValidatorResources>> {
1003
334k
        let offset = body.range().start;
1004
334k
        self.state.ensure_module("code", offset)?;
1005
334k
        check_max(
1006
            0,
1007
334k
            u32::try_from(body.range().end - body.range().start)
1008
334k
                .expect("body length already validated to u32 during section-length decoding"),
1009
            MAX_WASM_FUNCTION_SIZE,
1010
334k
            "function body size",
1011
334k
            offset,
1012
0
        )?;
1013
1014
334k
        let state = self.module.as_mut().unwrap();
1015
1016
334k
        let (index, ty) = state.next_code_index_and_type();
1017
334k
        Ok(FuncToValidate {
1018
334k
            index,
1019
334k
            ty,
1020
334k
            resources: ValidatorResources(state.module.arc().clone()),
1021
334k
            features: self.features,
1022
334k
        })
1023
334k
    }
1024
1025
    /// Validates [`Payload::DataSection`](crate::Payload).
1026
    ///
1027
    /// This method should only be called when parsing a module.
1028
1.67k
    pub fn data_section(&mut self, section: &crate::DataSectionReader<'_>) -> Result<()> {
1029
1.67k
        self.process_module_section(
1030
1.67k
            section,
1031
1.67k
            "data",
1032
1.67k
            |_, _, count, offset| {
1033
1.67k
                check_max(0, count, MAX_WASM_DATA_SEGMENTS, "data segments", offset)
1034
1.67k
            },
1035
30.4k
            |state, types, d, offset| state.add_data_segment(d, types, offset),
1036
        )
1037
1.67k
    }
1038
1039
    /// Validates [`Payload::ModuleSection`](crate::Payload).
1040
    ///
1041
    /// This method should only be called when parsing a component.
1042
    #[cfg(feature = "component-model")]
1043
4.27k
    pub fn module_section(&mut self, range: &Range<u64>) -> Result<()> {
1044
4.27k
        self.state.ensure_component("module", range.start)?;
1045
1046
4.27k
        let current = self.components.last_mut().unwrap();
1047
4.27k
        check_max(
1048
4.27k
            current.core_modules.len(),
1049
            1,
1050
            MAX_WASM_MODULES,
1051
4.27k
            "modules",
1052
4.27k
            range.start,
1053
0
        )?;
1054
1055
4.27k
        match mem::replace(&mut self.state, State::Unparsed(Some(Encoding::Module))) {
1056
4.27k
            State::Component => {}
1057
0
            _ => unreachable!(),
1058
        }
1059
1060
4.27k
        Ok(())
1061
4.27k
    }
1062
1063
    /// Validates [`Payload::InstanceSection`](crate::Payload).
1064
    ///
1065
    /// This method should only be called when parsing a component.
1066
    #[cfg(feature = "component-model")]
1067
5.45k
    pub fn instance_section(&mut self, section: &crate::InstanceSectionReader) -> Result<()> {
1068
5.45k
        self.process_component_section(
1069
5.45k
            section,
1070
5.45k
            "core instance",
1071
5.45k
            |components, _, count, offset| {
1072
5.45k
                let current = components.last_mut().unwrap();
1073
5.45k
                check_max(
1074
5.45k
                    current.instance_count(),
1075
5.45k
                    count,
1076
                    MAX_WASM_INSTANCES,
1077
5.45k
                    "instances",
1078
5.45k
                    offset,
1079
0
                )?;
1080
5.45k
                current.core_instances.reserve(count as usize);
1081
5.45k
                Ok(())
1082
5.45k
            },
1083
7.08k
            |components, types, _features, instance, offset| {
1084
7.08k
                components
1085
7.08k
                    .last_mut()
1086
7.08k
                    .unwrap()
1087
7.08k
                    .add_core_instance(instance, types, offset)
1088
7.08k
            },
1089
        )
1090
5.45k
    }
1091
1092
    /// Validates [`Payload::CoreTypeSection`](crate::Payload).
1093
    ///
1094
    /// This method should only be called when parsing a component.
1095
    #[cfg(feature = "component-model")]
1096
0
    pub fn core_type_section(&mut self, section: &crate::CoreTypeSectionReader<'_>) -> Result<()> {
1097
0
        self.process_component_section(
1098
0
            section,
1099
0
            "core type",
1100
0
            |components, _types, count, offset| {
1101
0
                let current = components.last_mut().unwrap();
1102
0
                check_max(current.type_count(), count, MAX_WASM_TYPES, "types", offset)?;
1103
0
                current.core_types.reserve(count as usize);
1104
0
                Ok(())
1105
0
            },
1106
0
            |components, types, _features, ty, offset| {
1107
0
                ComponentState::add_core_type(
1108
0
                    components, ty, types, offset, false, /* checked above */
1109
                )
1110
0
            },
1111
        )
1112
0
    }
1113
1114
    /// Validates [`Payload::ComponentSection`](crate::Payload).
1115
    ///
1116
    /// This method should only be called when parsing a component.
1117
    #[cfg(feature = "component-model")]
1118
3.41k
    pub fn component_section(&mut self, range: &Range<u64>) -> Result<()> {
1119
3.41k
        self.state.ensure_component("component", range.start)?;
1120
1121
3.41k
        let current = self.components.last_mut().unwrap();
1122
3.41k
        check_max(
1123
3.41k
            current.components.len(),
1124
            1,
1125
            MAX_WASM_COMPONENTS,
1126
3.41k
            "components",
1127
3.41k
            range.start,
1128
0
        )?;
1129
1130
3.41k
        match mem::replace(&mut self.state, State::Unparsed(Some(Encoding::Component))) {
1131
3.41k
            State::Component => {}
1132
0
            _ => unreachable!(),
1133
        }
1134
1135
3.41k
        Ok(())
1136
3.41k
    }
1137
1138
    /// Validates [`Payload::ComponentInstanceSection`](crate::Payload).
1139
    ///
1140
    /// This method should only be called when parsing a component.
1141
    #[cfg(feature = "component-model")]
1142
3.41k
    pub fn component_instance_section(
1143
3.41k
        &mut self,
1144
3.41k
        section: &crate::ComponentInstanceSectionReader,
1145
3.41k
    ) -> Result<()> {
1146
3.41k
        self.process_component_section(
1147
3.41k
            section,
1148
3.41k
            "instance",
1149
3.41k
            |components, _, count, offset| {
1150
3.41k
                let current = components.last_mut().unwrap();
1151
3.41k
                check_max(
1152
3.41k
                    current.instance_count(),
1153
3.41k
                    count,
1154
                    MAX_WASM_INSTANCES,
1155
3.41k
                    "instances",
1156
3.41k
                    offset,
1157
0
                )?;
1158
3.41k
                current.instances.reserve(count as usize);
1159
3.41k
                Ok(())
1160
3.41k
            },
1161
3.41k
            |components, types, _features, instance, offset| {
1162
3.41k
                components
1163
3.41k
                    .last_mut()
1164
3.41k
                    .unwrap()
1165
3.41k
                    .add_instance(instance, types, offset)
1166
3.41k
            },
1167
        )
1168
3.41k
    }
1169
1170
    /// Validates [`Payload::ComponentAliasSection`](crate::Payload).
1171
    ///
1172
    /// This method should only be called when parsing a component.
1173
    #[cfg(feature = "component-model")]
1174
11.0k
    pub fn component_alias_section(
1175
11.0k
        &mut self,
1176
11.0k
        section: &crate::ComponentAliasSectionReader<'_>,
1177
11.0k
    ) -> Result<()> {
1178
11.0k
        self.process_component_section(
1179
11.0k
            section,
1180
11.0k
            "alias",
1181
11.0k
            |_, _, _, _| Ok(()), // maximums checked via `add_alias`
1182
18.6k
            |components, types, _features, alias, offset| -> Result<(), Error> {
1183
18.6k
                ComponentState::add_alias(components, alias, types, offset)
1184
18.6k
            },
1185
        )
1186
11.0k
    }
1187
1188
    /// Validates [`Payload::ComponentTypeSection`](crate::Payload).
1189
    ///
1190
    /// This method should only be called when parsing a component.
1191
    #[cfg(feature = "component-model")]
1192
36.5k
    pub fn component_type_section(
1193
36.5k
        &mut self,
1194
36.5k
        section: &crate::ComponentTypeSectionReader,
1195
36.5k
    ) -> Result<()> {
1196
36.5k
        self.process_component_section(
1197
36.5k
            section,
1198
36.5k
            "type",
1199
36.5k
            |components, _types, count, offset| {
1200
36.5k
                let current = components.last_mut().unwrap();
1201
36.5k
                check_max(current.type_count(), count, MAX_WASM_TYPES, "types", offset)?;
1202
36.5k
                current.types.reserve(count as usize);
1203
36.5k
                Ok(())
1204
36.5k
            },
1205
85.3k
            |components, types, _features, ty, offset| {
1206
85.3k
                ComponentState::add_type(
1207
85.3k
                    components, ty, types, offset, false, /* checked above */
1208
                )
1209
85.3k
            },
1210
        )
1211
36.5k
    }
1212
1213
    /// Validates [`Payload::ComponentCanonicalSection`](crate::Payload).
1214
    ///
1215
    /// This method should only be called when parsing a component.
1216
    #[cfg(feature = "component-model")]
1217
10.9k
    pub fn component_canonical_section(
1218
10.9k
        &mut self,
1219
10.9k
        section: &crate::ComponentCanonicalSectionReader,
1220
10.9k
    ) -> Result<()> {
1221
10.9k
        self.process_component_section(
1222
10.9k
            section,
1223
10.9k
            "function",
1224
10.9k
            |components, _, count, offset| {
1225
10.9k
                let current = components.last_mut().unwrap();
1226
10.9k
                check_max(
1227
10.9k
                    current.function_count(),
1228
10.9k
                    count,
1229
                    MAX_WASM_FUNCTIONS,
1230
10.9k
                    "functions",
1231
10.9k
                    offset,
1232
0
                )?;
1233
10.9k
                current.funcs.reserve(count as usize);
1234
10.9k
                Ok(())
1235
10.9k
            },
1236
20.0k
            |components, types, _features, func, offset| {
1237
20.0k
                let current = components.last_mut().unwrap();
1238
20.0k
                current.canonical_function(func, types, offset)
1239
20.0k
            },
1240
        )
1241
10.9k
    }
1242
1243
    /// Validates [`Payload::ComponentStartSection`](crate::Payload).
1244
    ///
1245
    /// This method should only be called when parsing a component.
1246
    #[cfg(feature = "component-model")]
1247
0
    pub fn component_start_section(
1248
0
        &mut self,
1249
0
        f: &crate::ComponentStartFunction,
1250
0
        range: &Range<u64>,
1251
0
    ) -> Result<()> {
1252
0
        self.state.ensure_component("start", range.start)?;
1253
1254
0
        self.components.last_mut().unwrap().add_start(
1255
0
            f.func_index,
1256
0
            &f.arguments,
1257
0
            f.results,
1258
0
            &mut self.types,
1259
0
            range.start,
1260
        )
1261
0
    }
1262
1263
    /// Validates [`Payload::ComponentImportSection`](crate::Payload).
1264
    ///
1265
    /// This method should only be called when parsing a component.
1266
    #[cfg(feature = "component-model")]
1267
6.63k
    pub fn component_import_section(
1268
6.63k
        &mut self,
1269
6.63k
        section: &crate::ComponentImportSectionReader,
1270
6.63k
    ) -> Result<()> {
1271
6.63k
        self.process_component_section(
1272
6.63k
            section,
1273
6.63k
            "import",
1274
6.63k
            |_, _, _, _| Ok(()), // add_import will check limits
1275
9.50k
            |components, types, _features, import, offset| {
1276
9.50k
                components
1277
9.50k
                    .last_mut()
1278
9.50k
                    .unwrap()
1279
9.50k
                    .add_import(import, types, offset)
1280
9.50k
            },
1281
        )
1282
6.63k
    }
1283
1284
    /// Validates [`Payload::ComponentExportSection`](crate::Payload).
1285
    ///
1286
    /// This method should only be called when parsing a component.
1287
    #[cfg(feature = "component-model")]
1288
30.8k
    pub fn component_export_section(
1289
30.8k
        &mut self,
1290
30.8k
        section: &crate::ComponentExportSectionReader,
1291
30.8k
    ) -> Result<()> {
1292
30.8k
        self.process_component_section(
1293
30.8k
            section,
1294
30.8k
            "export",
1295
30.8k
            |components, _, count, offset| {
1296
30.8k
                let current = components.last_mut().unwrap();
1297
30.8k
                check_max(
1298
30.8k
                    current.exports.len(),
1299
30.8k
                    count,
1300
                    MAX_WASM_EXPORTS,
1301
30.8k
                    "exports",
1302
30.8k
                    offset,
1303
0
                )?;
1304
30.8k
                current.exports.reserve(count as usize);
1305
30.8k
                Ok(())
1306
30.8k
            },
1307
33.6k
            |components, types, _features, export, offset| {
1308
33.6k
                let current = components.last_mut().unwrap();
1309
33.6k
                let ty = current.export_to_entity_type(&export, types, offset)?;
1310
33.6k
                current.add_export(
1311
33.6k
                    export.name,
1312
33.6k
                    ty,
1313
33.6k
                    types,
1314
33.6k
                    offset,
1315
                    false, /* checked above */
1316
                )
1317
33.6k
            },
1318
        )
1319
30.8k
    }
1320
1321
    /// Validates [`Payload::UnknownSection`](crate::Payload).
1322
    ///
1323
    /// Currently always returns an error.
1324
0
    pub fn unknown_section(&mut self, id: u8, range: &Range<u64>) -> Result<()> {
1325
0
        Err(format_err!(range.start, "malformed section id: {id}"))
1326
0
    }
1327
1328
    /// Validates [`Payload::End`](crate::Payload).
1329
    ///
1330
    /// Returns the types known to the validator for the module or component.
1331
16.0k
    pub fn end(&mut self, offset: u64) -> Result<Types> {
1332
16.0k
        match mem::replace(&mut self.state, State::End) {
1333
0
            State::Unparsed(_) => Err(Error::new(
1334
0
                "cannot call `end` before a header has been parsed",
1335
0
                offset,
1336
0
            )),
1337
0
            State::End => Err(Error::new(
1338
0
                "cannot call `end` after parsing has completed",
1339
0
                offset,
1340
0
            )),
1341
            State::Module => {
1342
9.24k
                let mut state = self.module.take().unwrap();
1343
1344
                // If there's a parent component, we'll add a module to the parent state
1345
                // and continue to validate the component
1346
                #[cfg(feature = "component-model")]
1347
9.24k
                if let Some(parent) = self.components.last_mut() {
1348
4.27k
                    parent.add_core_module(&state.module, &mut self.types, offset)?;
1349
4.27k
                    self.state = State::Component;
1350
4.97k
                }
1351
1352
9.24k
                Ok(Types::from_module(
1353
9.24k
                    self.id,
1354
9.24k
                    self.types.commit(),
1355
9.24k
                    state.module.arc().clone(),
1356
9.24k
                ))
1357
            }
1358
            #[cfg(feature = "component-model")]
1359
            State::Component => {
1360
6.82k
                let mut component = self.components.pop().unwrap();
1361
1362
                // Validate that all values were used for the component
1363
6.82k
                if let Some(index) = component.values.iter().position(|(_, used)| !*used) {
1364
0
                    bail!(
1365
0
                        offset,
1366
                        "value index {index} was not used as part of an \
1367
                         instantiation, start function, or export"
1368
                    );
1369
6.82k
                }
1370
1371
                // If there's a parent component, pop the stack, add it to the parent,
1372
                // and continue to validate the component
1373
6.82k
                let ty = component.finish(&self.types, offset)?;
1374
6.82k
                if let Some(parent) = self.components.last_mut() {
1375
3.41k
                    parent.add_component(ty, &mut self.types)?;
1376
3.41k
                    self.state = State::Component;
1377
3.41k
                }
1378
1379
6.82k
                Ok(Types::from_component(
1380
6.82k
                    self.id,
1381
6.82k
                    self.types.commit(),
1382
6.82k
                    component,
1383
6.82k
                ))
1384
            }
1385
        }
1386
16.0k
    }
1387
1388
42.4k
    fn process_module_section<'a, T>(
1389
42.4k
        &mut self,
1390
42.4k
        section: &SectionLimited<'a, T>,
1391
42.4k
        name: &str,
1392
42.4k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
42.4k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
42.4k
    ) -> Result<()>
1395
42.4k
    where
1396
42.4k
        T: FromReader<'a>,
1397
    {
1398
42.4k
        let offset = section.range().start;
1399
42.4k
        self.state.ensure_module(name, offset)?;
1400
1401
42.4k
        let state = self.module.as_mut().unwrap();
1402
1403
42.4k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
871k
        for item in section.clone().into_iter_with_offsets() {
1406
871k
            let (offset, item) = item?;
1407
871k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
42.4k
        Ok(())
1411
42.4k
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::data::Data, <wasmparser::validator::Validator>::data_section::{closure#0}, <wasmparser::validator::Validator>::data_section::{closure#1}>
Line
Count
Source
1388
1.67k
    fn process_module_section<'a, T>(
1389
1.67k
        &mut self,
1390
1.67k
        section: &SectionLimited<'a, T>,
1391
1.67k
        name: &str,
1392
1.67k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
1.67k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
1.67k
    ) -> Result<()>
1395
1.67k
    where
1396
1.67k
        T: FromReader<'a>,
1397
    {
1398
1.67k
        let offset = section.range().start;
1399
1.67k
        self.state.ensure_module(name, offset)?;
1400
1401
1.67k
        let state = self.module.as_mut().unwrap();
1402
1403
1.67k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
30.4k
        for item in section.clone().into_iter_with_offsets() {
1406
30.4k
            let (offset, item) = item?;
1407
30.4k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
1.67k
        Ok(())
1411
1.67k
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::types::MemoryType, <wasmparser::validator::Validator>::memory_section::{closure#0}, <wasmparser::validator::Validator>::memory_section::{closure#1}>
Line
Count
Source
1388
4.61k
    fn process_module_section<'a, T>(
1389
4.61k
        &mut self,
1390
4.61k
        section: &SectionLimited<'a, T>,
1391
4.61k
        name: &str,
1392
4.61k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
4.61k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
4.61k
    ) -> Result<()>
1395
4.61k
    where
1396
4.61k
        T: FromReader<'a>,
1397
    {
1398
4.61k
        let offset = section.range().start;
1399
4.61k
        self.state.ensure_module(name, offset)?;
1400
1401
4.61k
        let state = self.module.as_mut().unwrap();
1402
1403
4.61k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
22.5k
        for item in section.clone().into_iter_with_offsets() {
1406
22.5k
            let (offset, item) = item?;
1407
22.5k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
4.61k
        Ok(())
1411
4.61k
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::types::TagType, <wasmparser::validator::Validator>::tag_section::{closure#0}, <wasmparser::validator::Validator>::tag_section::{closure#1}>
Line
Count
Source
1388
259
    fn process_module_section<'a, T>(
1389
259
        &mut self,
1390
259
        section: &SectionLimited<'a, T>,
1391
259
        name: &str,
1392
259
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
259
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
259
    ) -> Result<()>
1395
259
    where
1396
259
        T: FromReader<'a>,
1397
    {
1398
259
        let offset = section.range().start;
1399
259
        self.state.ensure_module(name, offset)?;
1400
1401
259
        let state = self.module.as_mut().unwrap();
1402
1403
259
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
8.27k
        for item in section.clone().into_iter_with_offsets() {
1406
8.27k
            let (offset, item) = item?;
1407
8.27k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
259
        Ok(())
1411
259
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::types::RecGroup, <wasmparser::validator::Validator>::type_section::{closure#0}, <wasmparser::validator::Validator>::type_section::{closure#1}>
Line
Count
Source
1388
8.79k
    fn process_module_section<'a, T>(
1389
8.79k
        &mut self,
1390
8.79k
        section: &SectionLimited<'a, T>,
1391
8.79k
        name: &str,
1392
8.79k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
8.79k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
8.79k
    ) -> Result<()>
1395
8.79k
    where
1396
8.79k
        T: FromReader<'a>,
1397
    {
1398
8.79k
        let offset = section.range().start;
1399
8.79k
        self.state.ensure_module(name, offset)?;
1400
1401
8.79k
        let state = self.module.as_mut().unwrap();
1402
1403
8.79k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
158k
        for item in section.clone().into_iter_with_offsets() {
1406
158k
            let (offset, item) = item?;
1407
158k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
8.79k
        Ok(())
1411
8.79k
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::tables::Table, <wasmparser::validator::Validator>::table_section::{closure#0}, <wasmparser::validator::Validator>::table_section::{closure#1}>
Line
Count
Source
1388
2.49k
    fn process_module_section<'a, T>(
1389
2.49k
        &mut self,
1390
2.49k
        section: &SectionLimited<'a, T>,
1391
2.49k
        name: &str,
1392
2.49k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
2.49k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
2.49k
    ) -> Result<()>
1395
2.49k
    where
1396
2.49k
        T: FromReader<'a>,
1397
    {
1398
2.49k
        let offset = section.range().start;
1399
2.49k
        self.state.ensure_module(name, offset)?;
1400
1401
2.49k
        let state = self.module.as_mut().unwrap();
1402
1403
2.49k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
17.1k
        for item in section.clone().into_iter_with_offsets() {
1406
17.1k
            let (offset, item) = item?;
1407
17.1k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
2.49k
        Ok(())
1411
2.49k
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::exports::Export, <wasmparser::validator::Validator>::export_section::{closure#0}, <wasmparser::validator::Validator>::export_section::{closure#1}>
Line
Count
Source
1388
5.53k
    fn process_module_section<'a, T>(
1389
5.53k
        &mut self,
1390
5.53k
        section: &SectionLimited<'a, T>,
1391
5.53k
        name: &str,
1392
5.53k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
5.53k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
5.53k
    ) -> Result<()>
1395
5.53k
    where
1396
5.53k
        T: FromReader<'a>,
1397
    {
1398
5.53k
        let offset = section.range().start;
1399
5.53k
        self.state.ensure_module(name, offset)?;
1400
1401
5.53k
        let state = self.module.as_mut().unwrap();
1402
1403
5.53k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
69.4k
        for item in section.clone().into_iter_with_offsets() {
1406
69.4k
            let (offset, item) = item?;
1407
69.4k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
5.53k
        Ok(())
1411
5.53k
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::globals::Global, <wasmparser::validator::Validator>::global_section::{closure#0}, <wasmparser::validator::Validator>::global_section::{closure#1}>
Line
Count
Source
1388
4.19k
    fn process_module_section<'a, T>(
1389
4.19k
        &mut self,
1390
4.19k
        section: &SectionLimited<'a, T>,
1391
4.19k
        name: &str,
1392
4.19k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
4.19k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
4.19k
    ) -> Result<()>
1395
4.19k
    where
1396
4.19k
        T: FromReader<'a>,
1397
    {
1398
4.19k
        let offset = section.range().start;
1399
4.19k
        self.state.ensure_module(name, offset)?;
1400
1401
4.19k
        let state = self.module.as_mut().unwrap();
1402
1403
4.19k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
146k
        for item in section.clone().into_iter_with_offsets() {
1406
146k
            let (offset, item) = item?;
1407
146k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
4.19k
        Ok(())
1411
4.19k
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::imports::Imports, <wasmparser::validator::Validator>::import_section::{closure#0}, <wasmparser::validator::Validator>::import_section::{closure#1}>
Line
Count
Source
1388
6.16k
    fn process_module_section<'a, T>(
1389
6.16k
        &mut self,
1390
6.16k
        section: &SectionLimited<'a, T>,
1391
6.16k
        name: &str,
1392
6.16k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
6.16k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
6.16k
    ) -> Result<()>
1395
6.16k
    where
1396
6.16k
        T: FromReader<'a>,
1397
    {
1398
6.16k
        let offset = section.range().start;
1399
6.16k
        self.state.ensure_module(name, offset)?;
1400
1401
6.16k
        let state = self.module.as_mut().unwrap();
1402
1403
6.16k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
45.3k
        for item in section.clone().into_iter_with_offsets() {
1406
45.3k
            let (offset, item) = item?;
1407
45.3k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
6.16k
        Ok(())
1411
6.16k
    }
<wasmparser::validator::Validator>::process_module_section::<wasmparser::readers::core::elements::Element, <wasmparser::validator::Validator>::element_section::{closure#0}, <wasmparser::validator::Validator>::element_section::{closure#1}>
Line
Count
Source
1388
2.22k
    fn process_module_section<'a, T>(
1389
2.22k
        &mut self,
1390
2.22k
        section: &SectionLimited<'a, T>,
1391
2.22k
        name: &str,
1392
2.22k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
2.22k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
2.22k
    ) -> Result<()>
1395
2.22k
    where
1396
2.22k
        T: FromReader<'a>,
1397
    {
1398
2.22k
        let offset = section.range().start;
1399
2.22k
        self.state.ensure_module(name, offset)?;
1400
1401
2.22k
        let state = self.module.as_mut().unwrap();
1402
1403
2.22k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
38.9k
        for item in section.clone().into_iter_with_offsets() {
1406
38.9k
            let (offset, item) = item?;
1407
38.9k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
2.22k
        Ok(())
1411
2.22k
    }
<wasmparser::validator::Validator>::process_module_section::<u32, <wasmparser::validator::Validator>::function_section::{closure#0}, <wasmparser::validator::Validator>::function_section::{closure#1}>
Line
Count
Source
1388
6.47k
    fn process_module_section<'a, T>(
1389
6.47k
        &mut self,
1390
6.47k
        section: &SectionLimited<'a, T>,
1391
6.47k
        name: &str,
1392
6.47k
        validate_section: impl FnOnce(&mut ModuleState, &mut TypeAlloc, u32, u64) -> Result<()>,
1393
6.47k
        mut validate_item: impl FnMut(&mut ModuleState, &mut TypeAlloc, T, u64) -> Result<()>,
1394
6.47k
    ) -> Result<()>
1395
6.47k
    where
1396
6.47k
        T: FromReader<'a>,
1397
    {
1398
6.47k
        let offset = section.range().start;
1399
6.47k
        self.state.ensure_module(name, offset)?;
1400
1401
6.47k
        let state = self.module.as_mut().unwrap();
1402
1403
6.47k
        validate_section(state, &mut self.types, section.count(), offset)?;
1404
1405
334k
        for item in section.clone().into_iter_with_offsets() {
1406
334k
            let (offset, item) = item?;
1407
334k
            validate_item(state, &mut self.types, item, offset)?;
1408
        }
1409
1410
6.47k
        Ok(())
1411
6.47k
    }
1412
1413
    #[cfg(feature = "component-model")]
1414
104k
    fn process_component_section<'a, T>(
1415
104k
        &mut self,
1416
104k
        section: &SectionLimited<'a, T>,
1417
104k
        name: &str,
1418
104k
        validate_section: impl FnOnce(&mut Vec<ComponentState>, &mut TypeAlloc, u32, u64) -> Result<()>,
1419
104k
        mut validate_item: impl FnMut(
1420
104k
            &mut Vec<ComponentState>,
1421
104k
            &mut TypeAlloc,
1422
104k
            &WasmFeatures,
1423
104k
            T,
1424
104k
            u64,
1425
104k
        ) -> Result<()>,
1426
104k
    ) -> Result<()>
1427
104k
    where
1428
104k
        T: FromReader<'a>,
1429
    {
1430
104k
        let offset = section.range().start;
1431
1432
104k
        self.state.ensure_component(name, offset)?;
1433
104k
        validate_section(
1434
104k
            &mut self.components,
1435
104k
            &mut self.types,
1436
104k
            section.count(),
1437
104k
            offset,
1438
104k
        )?;
1439
1440
177k
        for item in section.clone().into_iter_with_offsets() {
1441
177k
            let (offset, item) = item?;
1442
177k
            validate_item(
1443
177k
                &mut self.components,
1444
177k
                &mut self.types,
1445
177k
                &self.features,
1446
177k
                item,
1447
177k
                offset,
1448
177k
            )?;
1449
        }
1450
1451
104k
        Ok(())
1452
104k
    }
<wasmparser::validator::Validator>::process_component_section::<wasmparser::readers::component::canonicals::CanonicalFunction, <wasmparser::validator::Validator>::component_canonical_section::{closure#0}, <wasmparser::validator::Validator>::component_canonical_section::{closure#1}>
Line
Count
Source
1414
10.9k
    fn process_component_section<'a, T>(
1415
10.9k
        &mut self,
1416
10.9k
        section: &SectionLimited<'a, T>,
1417
10.9k
        name: &str,
1418
10.9k
        validate_section: impl FnOnce(&mut Vec<ComponentState>, &mut TypeAlloc, u32, u64) -> Result<()>,
1419
10.9k
        mut validate_item: impl FnMut(
1420
10.9k
            &mut Vec<ComponentState>,
1421
10.9k
            &mut TypeAlloc,
1422
10.9k
            &WasmFeatures,
1423
10.9k
            T,
1424
10.9k
            u64,
1425
10.9k
        ) -> Result<()>,
1426
10.9k
    ) -> Result<()>
1427
10.9k
    where
1428
10.9k
        T: FromReader<'a>,
1429
    {
1430
10.9k
        let offset = section.range().start;
1431
1432
10.9k
        self.state.ensure_component(name, offset)?;
1433
10.9k
        validate_section(
1434
10.9k
            &mut self.components,
1435
10.9k
            &mut self.types,
1436
10.9k
            section.count(),
1437
10.9k
            offset,
1438
10.9k
        )?;
1439
1440
20.0k
        for item in section.clone().into_iter_with_offsets() {
1441
20.0k
            let (offset, item) = item?;
1442
20.0k
            validate_item(
1443
20.0k
                &mut self.components,
1444
20.0k
                &mut self.types,
1445
20.0k
                &self.features,
1446
20.0k
                item,
1447
20.0k
                offset,
1448
20.0k
            )?;
1449
        }
1450
1451
10.9k
        Ok(())
1452
10.9k
    }
<wasmparser::validator::Validator>::process_component_section::<wasmparser::readers::component::types::ComponentType, <wasmparser::validator::Validator>::component_type_section::{closure#0}, <wasmparser::validator::Validator>::component_type_section::{closure#1}>
Line
Count
Source
1414
36.5k
    fn process_component_section<'a, T>(
1415
36.5k
        &mut self,
1416
36.5k
        section: &SectionLimited<'a, T>,
1417
36.5k
        name: &str,
1418
36.5k
        validate_section: impl FnOnce(&mut Vec<ComponentState>, &mut TypeAlloc, u32, u64) -> Result<()>,
1419
36.5k
        mut validate_item: impl FnMut(
1420
36.5k
            &mut Vec<ComponentState>,
1421
36.5k
            &mut TypeAlloc,
1422
36.5k
            &WasmFeatures,
1423
36.5k
            T,
1424
36.5k
            u64,
1425
36.5k
        ) -> Result<()>,
1426
36.5k
    ) -> Result<()>
1427
36.5k
    where
1428
36.5k
        T: FromReader<'a>,
1429
    {
1430
36.5k
        let offset = section.range().start;
1431
1432
36.5k
        self.state.ensure_component(name, offset)?;
1433
36.5k
        validate_section(
1434
36.5k
            &mut self.components,
1435
36.5k
            &mut self.types,
1436
36.5k
            section.count(),
1437
36.5k
            offset,
1438
36.5k
        )?;
1439
1440
85.3k
        for item in section.clone().into_iter_with_offsets() {
1441
85.3k
            let (offset, item) = item?;
1442
85.3k
            validate_item(
1443
85.3k
                &mut self.components,
1444
85.3k
                &mut self.types,
1445
85.3k
                &self.features,
1446
85.3k
                item,
1447
85.3k
                offset,
1448
85.3k
            )?;
1449
        }
1450
1451
36.5k
        Ok(())
1452
36.5k
    }
Unexecuted instantiation: <wasmparser::validator::Validator>::process_component_section::<wasmparser::readers::component::types::CoreType, <wasmparser::validator::Validator>::core_type_section::{closure#0}, <wasmparser::validator::Validator>::core_type_section::{closure#1}>
<wasmparser::validator::Validator>::process_component_section::<wasmparser::readers::component::aliases::ComponentAlias, <wasmparser::validator::Validator>::component_alias_section::{closure#0}, <wasmparser::validator::Validator>::component_alias_section::{closure#1}>
Line
Count
Source
1414
11.0k
    fn process_component_section<'a, T>(
1415
11.0k
        &mut self,
1416
11.0k
        section: &SectionLimited<'a, T>,
1417
11.0k
        name: &str,
1418
11.0k
        validate_section: impl FnOnce(&mut Vec<ComponentState>, &mut TypeAlloc, u32, u64) -> Result<()>,
1419
11.0k
        mut validate_item: impl FnMut(
1420
11.0k
            &mut Vec<ComponentState>,
1421
11.0k
            &mut TypeAlloc,
1422
11.0k
            &WasmFeatures,
1423
11.0k
            T,
1424
11.0k
            u64,
1425
11.0k
        ) -> Result<()>,
1426
11.0k
    ) -> Result<()>
1427
11.0k
    where
1428
11.0k
        T: FromReader<'a>,
1429
    {
1430
11.0k
        let offset = section.range().start;
1431
1432
11.0k
        self.state.ensure_component(name, offset)?;
1433
11.0k
        validate_section(
1434
11.0k
            &mut self.components,
1435
11.0k
            &mut self.types,
1436
11.0k
            section.count(),
1437
11.0k
            offset,
1438
11.0k
        )?;
1439
1440
18.6k
        for item in section.clone().into_iter_with_offsets() {
1441
18.6k
            let (offset, item) = item?;
1442
18.6k
            validate_item(
1443
18.6k
                &mut self.components,
1444
18.6k
                &mut self.types,
1445
18.6k
                &self.features,
1446
18.6k
                item,
1447
18.6k
                offset,
1448
18.6k
            )?;
1449
        }
1450
1451
11.0k
        Ok(())
1452
11.0k
    }
<wasmparser::validator::Validator>::process_component_section::<wasmparser::readers::component::exports::ComponentExport, <wasmparser::validator::Validator>::component_export_section::{closure#0}, <wasmparser::validator::Validator>::component_export_section::{closure#1}>
Line
Count
Source
1414
30.8k
    fn process_component_section<'a, T>(
1415
30.8k
        &mut self,
1416
30.8k
        section: &SectionLimited<'a, T>,
1417
30.8k
        name: &str,
1418
30.8k
        validate_section: impl FnOnce(&mut Vec<ComponentState>, &mut TypeAlloc, u32, u64) -> Result<()>,
1419
30.8k
        mut validate_item: impl FnMut(
1420
30.8k
            &mut Vec<ComponentState>,
1421
30.8k
            &mut TypeAlloc,
1422
30.8k
            &WasmFeatures,
1423
30.8k
            T,
1424
30.8k
            u64,
1425
30.8k
        ) -> Result<()>,
1426
30.8k
    ) -> Result<()>
1427
30.8k
    where
1428
30.8k
        T: FromReader<'a>,
1429
    {
1430
30.8k
        let offset = section.range().start;
1431
1432
30.8k
        self.state.ensure_component(name, offset)?;
1433
30.8k
        validate_section(
1434
30.8k
            &mut self.components,
1435
30.8k
            &mut self.types,
1436
30.8k
            section.count(),
1437
30.8k
            offset,
1438
30.8k
        )?;
1439
1440
33.6k
        for item in section.clone().into_iter_with_offsets() {
1441
33.6k
            let (offset, item) = item?;
1442
33.6k
            validate_item(
1443
33.6k
                &mut self.components,
1444
33.6k
                &mut self.types,
1445
33.6k
                &self.features,
1446
33.6k
                item,
1447
33.6k
                offset,
1448
33.6k
            )?;
1449
        }
1450
1451
30.8k
        Ok(())
1452
30.8k
    }
<wasmparser::validator::Validator>::process_component_section::<wasmparser::readers::component::imports::ComponentImport, <wasmparser::validator::Validator>::component_import_section::{closure#0}, <wasmparser::validator::Validator>::component_import_section::{closure#1}>
Line
Count
Source
1414
6.63k
    fn process_component_section<'a, T>(
1415
6.63k
        &mut self,
1416
6.63k
        section: &SectionLimited<'a, T>,
1417
6.63k
        name: &str,
1418
6.63k
        validate_section: impl FnOnce(&mut Vec<ComponentState>, &mut TypeAlloc, u32, u64) -> Result<()>,
1419
6.63k
        mut validate_item: impl FnMut(
1420
6.63k
            &mut Vec<ComponentState>,
1421
6.63k
            &mut TypeAlloc,
1422
6.63k
            &WasmFeatures,
1423
6.63k
            T,
1424
6.63k
            u64,
1425
6.63k
        ) -> Result<()>,
1426
6.63k
    ) -> Result<()>
1427
6.63k
    where
1428
6.63k
        T: FromReader<'a>,
1429
    {
1430
6.63k
        let offset = section.range().start;
1431
1432
6.63k
        self.state.ensure_component(name, offset)?;
1433
6.63k
        validate_section(
1434
6.63k
            &mut self.components,
1435
6.63k
            &mut self.types,
1436
6.63k
            section.count(),
1437
6.63k
            offset,
1438
6.63k
        )?;
1439
1440
9.50k
        for item in section.clone().into_iter_with_offsets() {
1441
9.50k
            let (offset, item) = item?;
1442
9.50k
            validate_item(
1443
9.50k
                &mut self.components,
1444
9.50k
                &mut self.types,
1445
9.50k
                &self.features,
1446
9.50k
                item,
1447
9.50k
                offset,
1448
9.50k
            )?;
1449
        }
1450
1451
6.63k
        Ok(())
1452
6.63k
    }
<wasmparser::validator::Validator>::process_component_section::<wasmparser::readers::component::instances::ComponentInstance, <wasmparser::validator::Validator>::component_instance_section::{closure#0}, <wasmparser::validator::Validator>::component_instance_section::{closure#1}>
Line
Count
Source
1414
3.41k
    fn process_component_section<'a, T>(
1415
3.41k
        &mut self,
1416
3.41k
        section: &SectionLimited<'a, T>,
1417
3.41k
        name: &str,
1418
3.41k
        validate_section: impl FnOnce(&mut Vec<ComponentState>, &mut TypeAlloc, u32, u64) -> Result<()>,
1419
3.41k
        mut validate_item: impl FnMut(
1420
3.41k
            &mut Vec<ComponentState>,
1421
3.41k
            &mut TypeAlloc,
1422
3.41k
            &WasmFeatures,
1423
3.41k
            T,
1424
3.41k
            u64,
1425
3.41k
        ) -> Result<()>,
1426
3.41k
    ) -> Result<()>
1427
3.41k
    where
1428
3.41k
        T: FromReader<'a>,
1429
    {
1430
3.41k
        let offset = section.range().start;
1431
1432
3.41k
        self.state.ensure_component(name, offset)?;
1433
3.41k
        validate_section(
1434
3.41k
            &mut self.components,
1435
3.41k
            &mut self.types,
1436
3.41k
            section.count(),
1437
3.41k
            offset,
1438
3.41k
        )?;
1439
1440
3.41k
        for item in section.clone().into_iter_with_offsets() {
1441
3.41k
            let (offset, item) = item?;
1442
3.41k
            validate_item(
1443
3.41k
                &mut self.components,
1444
3.41k
                &mut self.types,
1445
3.41k
                &self.features,
1446
3.41k
                item,
1447
3.41k
                offset,
1448
3.41k
            )?;
1449
        }
1450
1451
3.41k
        Ok(())
1452
3.41k
    }
<wasmparser::validator::Validator>::process_component_section::<wasmparser::readers::component::instances::Instance, <wasmparser::validator::Validator>::instance_section::{closure#0}, <wasmparser::validator::Validator>::instance_section::{closure#1}>
Line
Count
Source
1414
5.45k
    fn process_component_section<'a, T>(
1415
5.45k
        &mut self,
1416
5.45k
        section: &SectionLimited<'a, T>,
1417
5.45k
        name: &str,
1418
5.45k
        validate_section: impl FnOnce(&mut Vec<ComponentState>, &mut TypeAlloc, u32, u64) -> Result<()>,
1419
5.45k
        mut validate_item: impl FnMut(
1420
5.45k
            &mut Vec<ComponentState>,
1421
5.45k
            &mut TypeAlloc,
1422
5.45k
            &WasmFeatures,
1423
5.45k
            T,
1424
5.45k
            u64,
1425
5.45k
        ) -> Result<()>,
1426
5.45k
    ) -> Result<()>
1427
5.45k
    where
1428
5.45k
        T: FromReader<'a>,
1429
    {
1430
5.45k
        let offset = section.range().start;
1431
1432
5.45k
        self.state.ensure_component(name, offset)?;
1433
5.45k
        validate_section(
1434
5.45k
            &mut self.components,
1435
5.45k
            &mut self.types,
1436
5.45k
            section.count(),
1437
5.45k
            offset,
1438
5.45k
        )?;
1439
1440
7.08k
        for item in section.clone().into_iter_with_offsets() {
1441
7.08k
            let (offset, item) = item?;
1442
7.08k
            validate_item(
1443
7.08k
                &mut self.components,
1444
7.08k
                &mut self.types,
1445
7.08k
                &self.features,
1446
7.08k
                item,
1447
7.08k
                offset,
1448
7.08k
            )?;
1449
        }
1450
1451
5.45k
        Ok(())
1452
5.45k
    }
1453
}
1454
1455
#[cfg(test)]
1456
mod tests {
1457
    use crate::{GlobalType, MemoryType, RefType, TableType, ValType, Validator, WasmFeatures};
1458
    use anyhow::Result;
1459
1460
    #[test]
1461
    fn test_module_type_information() -> Result<()> {
1462
        let bytes = wat::parse_str(
1463
            r#"
1464
            (module
1465
                (type (func (param i32 i64) (result i32)))
1466
                (memory 1 5)
1467
                (table 10 funcref)
1468
                (global (mut i32) (i32.const 0))
1469
                (func (type 0) (i32.const 0))
1470
                (tag (param i64 i32))
1471
                (elem funcref (ref.func 0))
1472
            )
1473
        "#,
1474
        )?;
1475
1476
        let mut validator =
1477
            Validator::new_with_features(WasmFeatures::default() | WasmFeatures::EXCEPTIONS);
1478
1479
        let types = validator.validate_all(&bytes)?;
1480
        let types = types.as_ref();
1481
1482
        assert_eq!(types.core_type_count_in_module(), 2);
1483
        assert_eq!(types.memory_count(), 1);
1484
        assert_eq!(types.table_count(), 1);
1485
        assert_eq!(types.global_count(), 1);
1486
        assert_eq!(types.function_count(), 1);
1487
        assert_eq!(types.tag_count(), 1);
1488
        assert_eq!(types.element_count(), 1);
1489
        assert_eq!(types.module_count(), 0);
1490
        assert_eq!(types.component_count(), 0);
1491
        assert_eq!(types.core_instance_count(), 0);
1492
        assert_eq!(types.value_count(), 0);
1493
1494
        let id = types.core_type_at_in_module(0);
1495
        let ty = types[id].unwrap_func();
1496
        assert_eq!(ty.params(), [ValType::I32, ValType::I64]);
1497
        assert_eq!(ty.results(), [ValType::I32]);
1498
1499
        let id = types.core_type_at_in_module(1);
1500
        let ty = types[id].unwrap_func();
1501
        assert_eq!(ty.params(), [ValType::I64, ValType::I32]);
1502
        assert_eq!(ty.results(), []);
1503
1504
        assert_eq!(
1505
            types.memory_at(0),
1506
            MemoryType {
1507
                memory64: false,
1508
                shared: false,
1509
                initial: 1,
1510
                maximum: Some(5),
1511
                page_size_log2: None,
1512
            }
1513
        );
1514
1515
        assert_eq!(
1516
            types.table_at(0),
1517
            TableType {
1518
                initial: 10,
1519
                maximum: None,
1520
                element_type: RefType::FUNCREF,
1521
                table64: false,
1522
                shared: false,
1523
            }
1524
        );
1525
1526
        assert_eq!(
1527
            types.global_at(0),
1528
            GlobalType {
1529
                content_type: ValType::I32,
1530
                mutable: true,
1531
                shared: false
1532
            }
1533
        );
1534
1535
        let id = types.core_function_at(0);
1536
        let ty = types[id].unwrap_func();
1537
        assert_eq!(ty.params(), [ValType::I32, ValType::I64]);
1538
        assert_eq!(ty.results(), [ValType::I32]);
1539
1540
        let ty = types.tag_at(0);
1541
        let ty = types[ty].unwrap_func();
1542
        assert_eq!(ty.params(), [ValType::I64, ValType::I32]);
1543
        assert_eq!(ty.results(), []);
1544
1545
        assert_eq!(types.element_at(0), RefType::FUNCREF);
1546
1547
        Ok(())
1548
    }
1549
1550
    #[test]
1551
    fn test_type_id_aliasing() -> Result<()> {
1552
        let bytes = wat::parse_str(
1553
            r#"
1554
            (component
1555
              (type $T (list string))
1556
              (alias outer 0 $T (type $A1))
1557
              (alias outer 0 $T (type $A2))
1558
            )
1559
        "#,
1560
        )?;
1561
1562
        let mut validator =
1563
            Validator::new_with_features(WasmFeatures::default() | WasmFeatures::COMPONENT_MODEL);
1564
1565
        let types = validator.validate_all(&bytes)?;
1566
        let types = types.as_ref();
1567
1568
        let t_id = types.component_defined_type_at(0);
1569
        let a1_id = types.component_defined_type_at(1);
1570
        let a2_id = types.component_defined_type_at(2);
1571
1572
        // The ids should all be the same
1573
        assert!(t_id == a1_id);
1574
        assert!(t_id == a2_id);
1575
        assert!(a1_id == a2_id);
1576
1577
        // However, they should all point to the same type
1578
        assert!(std::ptr::eq(&types[t_id], &types[a1_id],));
1579
        assert!(std::ptr::eq(&types[t_id], &types[a2_id],));
1580
1581
        Ok(())
1582
    }
1583
1584
    #[test]
1585
    fn test_type_id_exports() -> Result<()> {
1586
        let bytes = wat::parse_str(
1587
            r#"
1588
            (component
1589
              (type $T (list string))
1590
              (export $A1 "A1" (type $T))
1591
              (export $A2 "A2" (type $T))
1592
            )
1593
        "#,
1594
        )?;
1595
1596
        let mut validator =
1597
            Validator::new_with_features(WasmFeatures::default() | WasmFeatures::COMPONENT_MODEL);
1598
1599
        let types = validator.validate_all(&bytes)?;
1600
        let types = types.as_ref();
1601
1602
        let t_id = types.component_defined_type_at(0);
1603
        let a1_id = types.component_defined_type_at(1);
1604
        let a2_id = types.component_defined_type_at(2);
1605
1606
        // The ids should all be the same
1607
        assert!(t_id != a1_id);
1608
        assert!(t_id != a2_id);
1609
        assert!(a1_id != a2_id);
1610
1611
        // However, they should all point to the same type
1612
        assert!(std::ptr::eq(&types[t_id], &types[a1_id],));
1613
        assert!(std::ptr::eq(&types[t_id], &types[a2_id],));
1614
1615
        Ok(())
1616
    }
1617
1618
    #[test]
1619
    fn reset_fresh_validator() {
1620
        Validator::new().reset();
1621
    }
1622
1623
    #[cfg(feature = "features")]
1624
    #[test]
1625
    fn test_validate_missing_wasm_feature_exceptions_disabled() {
1626
        let bytes = wat::parse_str(
1627
            r#"
1628
            (module
1629
                (func (throw 0))
1630
            )
1631
        "#,
1632
        )
1633
        .unwrap();
1634
1635
        let mut validator =
1636
            Validator::new_with_features(WasmFeatures::default() & !WasmFeatures::EXCEPTIONS);
1637
        let Err(err) = validator.validate_all(&bytes) else {
1638
            panic!("should fail validation");
1639
        };
1640
        assert_eq!(err.missing_wasm_feature(), Some(WasmFeatures::EXCEPTIONS));
1641
    }
1642
}