pub struct Module {
Show 19 fields pub name: Option<String>, pub initializers: Vec<Initializer>, pub exports: IndexMap<String, EntityIndex>, pub start_func: Option<FuncIndex>, pub table_initialization: TableInitialization, pub memory_initialization: MemoryInitialization, pub passive_elements: Vec<Box<[FuncIndex]>>, pub passive_elements_map: BTreeMap<ElemIndex, usize>, pub passive_data_map: BTreeMap<DataIndex, Range<u32>>, pub types: PrimaryMap<TypeIndex, ModuleType>, pub num_imported_funcs: usize, pub num_imported_tables: usize, pub num_imported_memories: usize, pub num_imported_globals: usize, pub num_escaped_funcs: usize, pub functions: PrimaryMap<FuncIndex, FunctionType>, pub table_plans: PrimaryMap<TableIndex, TablePlan>, pub memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, pub globals: PrimaryMap<GlobalIndex, Global>,
}
Expand description

A translated WebAssembly module, excluding the function bodies and memory initializers.

Fields§

§name: Option<String>

The name of this wasm module, often found in the wasm file.

§initializers: Vec<Initializer>

All import records, in the order they are declared in the module.

§exports: IndexMap<String, EntityIndex>

Exported entities.

§start_func: Option<FuncIndex>

The module “start” function, if present.

§table_initialization: TableInitialization

WebAssembly table initialization data, per table.

§memory_initialization: MemoryInitialization

WebAssembly linear memory initializer.

§passive_elements: Vec<Box<[FuncIndex]>>

WebAssembly passive elements.

§passive_elements_map: BTreeMap<ElemIndex, usize>

The map from passive element index (element segment index space) to index in passive_elements.

§passive_data_map: BTreeMap<DataIndex, Range<u32>>

The map from passive data index (data segment index space) to index in passive_data.

§types: PrimaryMap<TypeIndex, ModuleType>

Types declared in the wasm module.

§num_imported_funcs: usize

Number of imported or aliased functions in the module.

§num_imported_tables: usize

Number of imported or aliased tables in the module.

§num_imported_memories: usize

Number of imported or aliased memories in the module.

§num_imported_globals: usize

Number of imported or aliased globals in the module.

§num_escaped_funcs: usize

Number of functions that “escape” from this module may need to have a VMCallerCheckedAnyfunc constructed for them.

This is also the number of functions in the functions array below with an anyfunc index (and is the maximum anyfunc index).

§functions: PrimaryMap<FuncIndex, FunctionType>

Types of functions, imported and local.

§table_plans: PrimaryMap<TableIndex, TablePlan>

WebAssembly tables.

§memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>

WebAssembly linear memory plans.

§globals: PrimaryMap<GlobalIndex, Global>

WebAssembly global variables.

Implementations§

Allocates the module data structures.

Convert a DefinedFuncIndex into a FuncIndex.

Convert a FuncIndex into a DefinedFuncIndex. Returns None if the index is an imported function.

Test whether the given function index is for an imported function.

Convert a DefinedTableIndex into a TableIndex.

Convert a TableIndex into a DefinedTableIndex. Returns None if the index is an imported table.

Examples found in repository?
src/module.rs (line 422)
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    pub fn try_func_table_init(&mut self) {
        // This should be large enough to support very large Wasm
        // modules with huge funcref tables, but small enough to avoid
        // OOMs or DoS on truly sparse tables.
        const MAX_FUNC_TABLE_SIZE: u32 = 1024 * 1024;

        let segments = match &self.module.table_initialization {
            TableInitialization::Segments { segments } => segments,
            TableInitialization::FuncTable { .. } => {
                // Already done!
                return;
            }
        };

        // Build the table arrays per-table.
        let mut tables = PrimaryMap::with_capacity(self.module.table_plans.len());
        // Keep the "leftovers" for eager init.
        let mut leftovers = vec![];

        for segment in segments {
            // Skip imported tables: we can't provide a preconstructed
            // table for them, because their values depend on the
            // imported table overlaid with whatever segments we have.
            if self
                .module
                .defined_table_index(segment.table_index)
                .is_none()
            {
                leftovers.push(segment.clone());
                continue;
            }

            // If this is not a funcref table, then we can't support a
            // pre-computed table of function indices.
            if self.module.table_plans[segment.table_index].table.wasm_ty != WasmType::FuncRef {
                leftovers.push(segment.clone());
                continue;
            }

            // If the base of this segment is dynamic, then we can't
            // include it in the statically-built array of initial
            // contents.
            if segment.base.is_some() {
                leftovers.push(segment.clone());
                continue;
            }

            // Get the end of this segment. If out-of-bounds, or too
            // large for our dense table representation, then skip the
            // segment.
            let top = match segment.offset.checked_add(segment.elements.len() as u32) {
                Some(top) => top,
                None => {
                    leftovers.push(segment.clone());
                    continue;
                }
            };
            let table_size = self.module.table_plans[segment.table_index].table.minimum;
            if top > table_size || top > MAX_FUNC_TABLE_SIZE {
                leftovers.push(segment.clone());
                continue;
            }

            // We can now incorporate this segment into the initializers array.
            while tables.len() <= segment.table_index.index() {
                tables.push(vec![]);
            }
            let elements = &mut tables[segment.table_index];
            if elements.is_empty() {
                elements.resize(table_size as usize, FuncIndex::reserved_value());
            }

            let dst = &mut elements[(segment.offset as usize)..(top as usize)];
            dst.copy_from_slice(&segment.elements[..]);
        }

        self.module.table_initialization = TableInitialization::FuncTable {
            tables,
            segments: leftovers,
        };
    }

Test whether the given table index is for an imported table.

Convert a DefinedMemoryIndex into a MemoryIndex.

Convert a MemoryIndex into a DefinedMemoryIndex. Returns None if the index is an imported memory.

Examples found in repository?
src/module.rs (line 250)
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    pub fn try_static_init(&mut self, page_size: u64, max_image_size_always_allowed: u64) {
        // This method only attempts to transform a `Segmented` memory init
        // into a `Static` one, no other state.
        if !self.module.memory_initialization.is_segmented() {
            return;
        }

        // First a dry run of memory initialization is performed. This
        // collects information about the extent of memory initialized for each
        // memory as well as the size of all data segments being copied in.
        struct Memory {
            data_size: u64,
            min_addr: u64,
            max_addr: u64,
            // The `usize` here is a pointer into `self.data` which is the list
            // of data segments corresponding to what was found in the original
            // wasm module.
            segments: Vec<(usize, StaticMemoryInitializer)>,
        }
        let mut info = PrimaryMap::with_capacity(self.module.memory_plans.len());
        for _ in 0..self.module.memory_plans.len() {
            info.push(Memory {
                data_size: 0,
                min_addr: u64::MAX,
                max_addr: 0,
                segments: Vec::new(),
            });
        }
        let mut idx = 0;
        let ok = self.module.memory_initialization.init_memory(
            InitMemory::CompileTime(&self.module),
            &mut |memory, init| {
                // Currently `Static` only applies to locally-defined memories,
                // so if a data segment references an imported memory then
                // transitioning to a `Static` memory initializer is not
                // possible.
                if self.module.defined_memory_index(memory).is_none() {
                    return false;
                };
                let info = &mut info[memory];
                let data_len = u64::from(init.data.end - init.data.start);
                if data_len > 0 {
                    info.data_size += data_len;
                    info.min_addr = info.min_addr.min(init.offset);
                    info.max_addr = info.max_addr.max(init.offset + data_len);
                    info.segments.push((idx, init.clone()));
                }
                idx += 1;
                true
            },
        );
        if !ok {
            return;
        }

        // Validate that the memory information collected is indeed valid for
        // static memory initialization.
        for info in info.values().filter(|i| i.data_size > 0) {
            let image_size = info.max_addr - info.min_addr;

            // If the range of memory being initialized is less than twice the
            // total size of the data itself then it's assumed that static
            // initialization is ok. This means we'll at most double memory
            // consumption during the memory image creation process, which is
            // currently assumed to "probably be ok" but this will likely need
            // tweaks over time.
            if image_size < info.data_size.saturating_mul(2) {
                continue;
            }

            // If the memory initialization image is larger than the size of all
            // data, then we still allow memory initialization if the image will
            // be of a relatively modest size, such as 1MB here.
            if image_size < max_image_size_always_allowed {
                continue;
            }

            // At this point memory initialization is concluded to be too
            // expensive to do at compile time so it's entirely deferred to
            // happen at runtime.
            return;
        }

        // Here's where we've now committed to changing to static memory. The
        // memory initialization image is built here from the page data and then
        // it's converted to a single initializer.
        let data = mem::replace(&mut self.data, Vec::new());
        let mut map = PrimaryMap::with_capacity(info.len());
        let mut module_data_size = 0u32;
        for (memory, info) in info.iter() {
            // Create the in-memory `image` which is the initialized contents of
            // this linear memory.
            let extent = if info.segments.len() > 0 {
                (info.max_addr - info.min_addr) as usize
            } else {
                0
            };
            let mut image = Vec::with_capacity(extent);
            for (idx, init) in info.segments.iter() {
                let data = &data[*idx];
                assert_eq!(data.len(), init.data.len());
                let offset = usize::try_from(init.offset - info.min_addr).unwrap();
                if image.len() < offset {
                    image.resize(offset, 0u8);
                    image.extend_from_slice(data);
                } else {
                    image.splice(
                        offset..(offset + data.len()).min(image.len()),
                        data.iter().copied(),
                    );
                }
            }
            assert_eq!(image.len(), extent);
            assert_eq!(image.capacity(), extent);
            let mut offset = if info.segments.len() > 0 {
                info.min_addr
            } else {
                0
            };

            // Chop off trailing zeros from the image as memory is already
            // zero-initialized. Note that `i` is the position of a nonzero
            // entry here, so to not lose it we truncate to `i + 1`.
            if let Some(i) = image.iter().rposition(|i| *i != 0) {
                image.truncate(i + 1);
            }

            // Also chop off leading zeros, if any.
            if let Some(i) = image.iter().position(|i| *i != 0) {
                offset += i as u64;
                image.drain(..i);
            }
            let mut len = u64::try_from(image.len()).unwrap();

            // The goal is to enable mapping this image directly into memory, so
            // the offset into linear memory must be a multiple of the page
            // size. If that's not already the case then the image is padded at
            // the front and back with extra zeros as necessary
            if offset % page_size != 0 {
                let zero_padding = offset % page_size;
                self.data.push(vec![0; zero_padding as usize].into());
                offset -= zero_padding;
                len += zero_padding;
            }
            self.data.push(image.into());
            if len % page_size != 0 {
                let zero_padding = page_size - (len % page_size);
                self.data.push(vec![0; zero_padding as usize].into());
                len += zero_padding;
            }

            // Offset/length should now always be page-aligned.
            assert!(offset % page_size == 0);
            assert!(len % page_size == 0);

            // Create the `StaticMemoryInitializer` which describes this image,
            // only needed if the image is actually present and has a nonzero
            // length. The `offset` has been calculates above, originally
            // sourced from `info.min_addr`. The `data` field is the extent
            // within the final data segment we'll emit to an ELF image, which
            // is the concatenation of `self.data`, so here it's the size of
            // the section-so-far plus the current segment we're appending.
            let len = u32::try_from(len).unwrap();
            let init = if len > 0 {
                Some(StaticMemoryInitializer {
                    offset,
                    data: module_data_size..module_data_size + len,
                })
            } else {
                None
            };
            let idx = map.push(init);
            assert_eq!(idx, memory);
            module_data_size += len;
        }
        self.data_align = Some(page_size);
        self.module.memory_initialization = MemoryInitialization::Static { map };
    }

Convert a DefinedMemoryIndex into an OwnedMemoryIndex. Returns None if the index is an imported memory.

Test whether the given memory index is for an imported memory.

Convert a DefinedGlobalIndex into a GlobalIndex.

Convert a GlobalIndex into a DefinedGlobalIndex. Returns None if the index is an imported global.

Test whether the given global index is for an imported global.

Returns an iterator of all the imports in this module, along with their module name, field name, and type that’s being imported.

Returns the type of an item based on its index

Examples found in repository?
src/module.rs (line 980)
977
978
979
980
981
982
983
    pub fn imports(&self) -> impl ExactSizeIterator<Item = (&str, &str, EntityType)> {
        self.initializers.iter().map(move |i| match i {
            Initializer::Import { name, field, index } => {
                (name.as_str(), field.as_str(), self.type_of(*index))
            }
        })
    }

Appends a new function to this module with the given type information, used for functions that either don’t escape or aren’t certain whether they escape yet.

Examples found in repository?
src/module_environ.rs (line 294)
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
    fn translate_payload(&mut self, payload: Payload<'data>) -> WasmResult<()> {
        match payload {
            Payload::Version {
                num,
                encoding,
                range,
            } => {
                self.validator.version(num, encoding, &range)?;
                match encoding {
                    Encoding::Module => {}
                    Encoding::Component => {
                        return Err(WasmError::Unsupported(format!("component model")));
                    }
                }
            }

            Payload::End(offset) => {
                self.result.types = Some(self.validator.end(offset)?);

                // With the `escaped_funcs` set of functions finished
                // we can calculate the set of signatures that are exported as
                // the set of exported functions' signatures.
                self.result.exported_signatures = self
                    .result
                    .module
                    .functions
                    .iter()
                    .filter_map(|(_, func)| {
                        if func.is_escaping() {
                            Some(func.signature)
                        } else {
                            None
                        }
                    })
                    .collect();
                self.result.exported_signatures.sort_unstable();
                self.result.exported_signatures.dedup();
            }

            Payload::TypeSection(types) => {
                self.validator.type_section(&types)?;
                let num = usize::try_from(types.get_count()).unwrap();
                self.result.module.types.reserve(num);
                self.types.reserve_wasm_signatures(num);

                for ty in types {
                    match ty? {
                        Type::Func(wasm_func_ty) => {
                            self.declare_type_func(wasm_func_ty.try_into()?)?;
                        }
                    }
                }
            }

            Payload::ImportSection(imports) => {
                self.validator.import_section(&imports)?;

                let cnt = usize::try_from(imports.get_count()).unwrap();
                self.result.module.initializers.reserve(cnt);

                for entry in imports {
                    let import = entry?;
                    let ty = match import.ty {
                        TypeRef::Func(index) => {
                            let index = TypeIndex::from_u32(index);
                            let sig_index = self.result.module.types[index].unwrap_function();
                            self.result.module.num_imported_funcs += 1;
                            self.result.debuginfo.wasm_file.imported_func_count += 1;
                            EntityType::Function(sig_index)
                        }
                        TypeRef::Memory(ty) => {
                            self.result.module.num_imported_memories += 1;
                            EntityType::Memory(ty.into())
                        }
                        TypeRef::Global(ty) => {
                            self.result.module.num_imported_globals += 1;
                            EntityType::Global(Global::new(ty, GlobalInit::Import)?)
                        }
                        TypeRef::Table(ty) => {
                            self.result.module.num_imported_tables += 1;
                            EntityType::Table(ty.try_into()?)
                        }

                        // doesn't get past validation
                        TypeRef::Tag(_) => unreachable!(),
                    };
                    self.declare_import(import.module, import.name, ty);
                }
            }

            Payload::FunctionSection(functions) => {
                self.validator.function_section(&functions)?;

                let cnt = usize::try_from(functions.get_count()).unwrap();
                self.result.module.functions.reserve_exact(cnt);

                for entry in functions {
                    let sigindex = entry?;
                    let ty = TypeIndex::from_u32(sigindex);
                    let sig_index = self.result.module.types[ty].unwrap_function();
                    self.result.module.push_function(sig_index);
                }
            }

            Payload::TableSection(tables) => {
                self.validator.table_section(&tables)?;
                let cnt = usize::try_from(tables.get_count()).unwrap();
                self.result.module.table_plans.reserve_exact(cnt);

                for entry in tables {
                    let table = entry?.try_into()?;
                    let plan = TablePlan::for_table(table, &self.tunables);
                    self.result.module.table_plans.push(plan);
                }
            }

            Payload::MemorySection(memories) => {
                self.validator.memory_section(&memories)?;

                let cnt = usize::try_from(memories.get_count()).unwrap();
                self.result.module.memory_plans.reserve_exact(cnt);

                for entry in memories {
                    let memory = entry?;
                    let plan = MemoryPlan::for_memory(memory.into(), &self.tunables);
                    self.result.module.memory_plans.push(plan);
                }
            }

            Payload::TagSection(tags) => {
                self.validator.tag_section(&tags)?;

                // This feature isn't enabled at this time, so we should
                // never get here.
                unreachable!();
            }

            Payload::GlobalSection(globals) => {
                self.validator.global_section(&globals)?;

                let cnt = usize::try_from(globals.get_count()).unwrap();
                self.result.module.globals.reserve_exact(cnt);

                for entry in globals {
                    let wasmparser::Global { ty, init_expr } = entry?;
                    let mut init_expr_reader = init_expr.get_binary_reader();
                    let initializer = match init_expr_reader.read_operator()? {
                        Operator::I32Const { value } => GlobalInit::I32Const(value),
                        Operator::I64Const { value } => GlobalInit::I64Const(value),
                        Operator::F32Const { value } => GlobalInit::F32Const(value.bits()),
                        Operator::F64Const { value } => GlobalInit::F64Const(value.bits()),
                        Operator::V128Const { value } => {
                            GlobalInit::V128Const(u128::from_le_bytes(*value.bytes()))
                        }
                        Operator::RefNull { ty: _ } => GlobalInit::RefNullConst,
                        Operator::RefFunc { function_index } => {
                            let index = FuncIndex::from_u32(function_index);
                            self.flag_func_escaped(index);
                            GlobalInit::RefFunc(index)
                        }
                        Operator::GlobalGet { global_index } => {
                            GlobalInit::GetGlobal(GlobalIndex::from_u32(global_index))
                        }
                        s => {
                            return Err(WasmError::Unsupported(format!(
                                "unsupported init expr in global section: {:?}",
                                s
                            )));
                        }
                    };
                    let ty = Global::new(ty, initializer)?;
                    self.result.module.globals.push(ty);
                }
            }

            Payload::ExportSection(exports) => {
                self.validator.export_section(&exports)?;

                let cnt = usize::try_from(exports.get_count()).unwrap();
                self.result.module.exports.reserve(cnt);

                for entry in exports {
                    let wasmparser::Export { name, kind, index } = entry?;
                    let entity = match kind {
                        ExternalKind::Func => {
                            let index = FuncIndex::from_u32(index);
                            self.flag_func_escaped(index);
                            EntityIndex::Function(index)
                        }
                        ExternalKind::Table => EntityIndex::Table(TableIndex::from_u32(index)),
                        ExternalKind::Memory => EntityIndex::Memory(MemoryIndex::from_u32(index)),
                        ExternalKind::Global => EntityIndex::Global(GlobalIndex::from_u32(index)),

                        // this never gets past validation
                        ExternalKind::Tag => unreachable!(),
                    };
                    self.result
                        .module
                        .exports
                        .insert(String::from(name), entity);
                }
            }

            Payload::StartSection { func, range } => {
                self.validator.start_section(func, &range)?;

                let func_index = FuncIndex::from_u32(func);
                self.flag_func_escaped(func_index);
                debug_assert!(self.result.module.start_func.is_none());
                self.result.module.start_func = Some(func_index);
            }

            Payload::ElementSection(elements) => {
                self.validator.element_section(&elements)?;

                for (index, entry) in elements.into_iter().enumerate() {
                    let wasmparser::Element {
                        kind,
                        items,
                        ty: _,
                        range: _,
                    } = entry?;

                    // Build up a list of `FuncIndex` corresponding to all the
                    // entries listed in this segment. Note that it's not
                    // possible to create anything other than a `ref.null
                    // extern` for externref segments, so those just get
                    // translated to the reserved value of `FuncIndex`.
                    let items_reader = items.get_items_reader()?;
                    let mut elements =
                        Vec::with_capacity(usize::try_from(items_reader.get_count()).unwrap());
                    for item in items_reader {
                        let func = match item? {
                            ElementItem::Func(f) => Some(f),
                            ElementItem::Expr(init) => {
                                match init.get_binary_reader().read_operator()? {
                                    Operator::RefNull { .. } => None,
                                    Operator::RefFunc { function_index } => Some(function_index),
                                    s => {
                                        return Err(WasmError::Unsupported(format!(
                                            "unsupported init expr in element section: {:?}",
                                            s
                                        )));
                                    }
                                }
                            }
                        };
                        elements.push(match func {
                            Some(f) => {
                                let f = FuncIndex::from_u32(f);
                                self.flag_func_escaped(f);
                                f
                            }
                            None => FuncIndex::reserved_value(),
                        });
                    }

                    match kind {
                        ElementKind::Active {
                            table_index,
                            offset_expr,
                        } => {
                            let table_index = TableIndex::from_u32(table_index);
                            let mut offset_expr_reader = offset_expr.get_binary_reader();
                            let (base, offset) = match offset_expr_reader.read_operator()? {
                                Operator::I32Const { value } => (None, value as u32),
                                Operator::GlobalGet { global_index } => {
                                    (Some(GlobalIndex::from_u32(global_index)), 0)
                                }
                                ref s => {
                                    return Err(WasmError::Unsupported(format!(
                                        "unsupported init expr in element section: {:?}",
                                        s
                                    )));
                                }
                            };

                            let table_segments = match &mut self.result.module.table_initialization
                            {
                                TableInitialization::Segments { segments } => segments,
                                TableInitialization::FuncTable { .. } => unreachable!(),
                            };
                            table_segments.push(TableInitializer {
                                table_index,
                                base,
                                offset,
                                elements: elements.into(),
                            });
                        }

                        ElementKind::Passive => {
                            let elem_index = ElemIndex::from_u32(index as u32);
                            let index = self.result.module.passive_elements.len();
                            self.result.module.passive_elements.push(elements.into());
                            self.result
                                .module
                                .passive_elements_map
                                .insert(elem_index, index);
                        }

                        ElementKind::Declared => {}
                    }
                }
            }

            Payload::CodeSectionStart { count, range, .. } => {
                self.validator.code_section_start(count, &range)?;
                let cnt = usize::try_from(count).unwrap();
                self.result.function_body_inputs.reserve_exact(cnt);
                self.result.debuginfo.wasm_file.code_section_offset = range.start as u64;
            }

            Payload::CodeSectionEntry(mut body) => {
                let validator = self.validator.code_section_entry(&body)?;
                let func_index =
                    self.result.code_index + self.result.module.num_imported_funcs as u32;
                let func_index = FuncIndex::from_u32(func_index);

                if self.tunables.generate_native_debuginfo {
                    let sig_index = self.result.module.functions[func_index].signature;
                    let sig = &self.types[sig_index];
                    let mut locals = Vec::new();
                    for pair in body.get_locals_reader()? {
                        locals.push(pair?);
                    }
                    self.result
                        .debuginfo
                        .wasm_file
                        .funcs
                        .push(FunctionMetadata {
                            locals: locals.into_boxed_slice(),
                            params: sig.params().iter().cloned().map(|i| i.into()).collect(),
                        });
                }
                body.allow_memarg64(self.validator.features().memory64);
                self.result
                    .function_body_inputs
                    .push(FunctionBodyData { validator, body });
                self.result.code_index += 1;
            }

            Payload::DataSection(data) => {
                self.validator.data_section(&data)?;

                let initializers = match &mut self.result.module.memory_initialization {
                    MemoryInitialization::Segmented(i) => i,
                    _ => unreachable!(),
                };

                let cnt = usize::try_from(data.get_count()).unwrap();
                initializers.reserve_exact(cnt);
                self.result.data.reserve_exact(cnt);

                for (index, entry) in data.into_iter().enumerate() {
                    let wasmparser::Data {
                        kind,
                        data,
                        range: _,
                    } = entry?;
                    let mk_range = |total: &mut u32| -> Result<_, WasmError> {
                        let range = u32::try_from(data.len())
                            .ok()
                            .and_then(|size| {
                                let start = *total;
                                let end = start.checked_add(size)?;
                                Some(start..end)
                            })
                            .ok_or_else(|| {
                                WasmError::Unsupported(format!(
                                    "more than 4 gigabytes of data in wasm module",
                                ))
                            })?;
                        *total += range.end - range.start;
                        Ok(range)
                    };
                    match kind {
                        DataKind::Active {
                            memory_index,
                            offset_expr,
                        } => {
                            let range = mk_range(&mut self.result.total_data)?;
                            let memory_index = MemoryIndex::from_u32(memory_index);
                            let mut offset_expr_reader = offset_expr.get_binary_reader();
                            let (base, offset) = match offset_expr_reader.read_operator()? {
                                Operator::I32Const { value } => (None, value as u64),
                                Operator::I64Const { value } => (None, value as u64),
                                Operator::GlobalGet { global_index } => {
                                    (Some(GlobalIndex::from_u32(global_index)), 0)
                                }
                                s => {
                                    return Err(WasmError::Unsupported(format!(
                                        "unsupported init expr in data section: {:?}",
                                        s
                                    )));
                                }
                            };

                            initializers.push(MemoryInitializer {
                                memory_index,
                                base,
                                offset,
                                data: range,
                            });
                            self.result.data.push(data.into());
                        }
                        DataKind::Passive => {
                            let data_index = DataIndex::from_u32(index as u32);
                            let range = mk_range(&mut self.result.total_passive_data)?;
                            self.result.passive_data.push(data);
                            self.result
                                .module
                                .passive_data_map
                                .insert(data_index, range);
                        }
                    }
                }
            }

            Payload::DataCountSection { count, range } => {
                self.validator.data_count_section(count, &range)?;

                // Note: the count passed in here is the *total* segment count
                // There is no way to reserve for just the passive segments as
                // they are discovered when iterating the data section entries
                // Given that the total segment count might be much larger than
                // the passive count, do not reserve anything here.
            }

            Payload::CustomSection(s) if s.name() == "name" => {
                let result = NameSectionReader::new(s.data(), s.data_offset())
                    .map_err(|e| e.into())
                    .and_then(|s| self.name_section(s));
                if let Err(e) = result {
                    log::warn!("failed to parse name section {:?}", e);
                }
            }

            Payload::CustomSection(s)
                if s.name() == "webidl-bindings" || s.name() == "wasm-interface-types" =>
            {
                return Err(WasmError::Unsupported(
                    "\
Support for interface types has temporarily been removed from `wasmtime`.

For more information about this temporary change you can read on the issue online:

    https://github.com/bytecodealliance/wasmtime/issues/1271

and for re-adding support for interface types you can see this issue:

    https://github.com/bytecodealliance/wasmtime/issues/677
"
                    .to_string(),
                ))
            }

            Payload::CustomSection(s) => {
                self.register_dwarf_section(&s);
            }

            // It's expected that validation will probably reject other
            // payloads such as `UnknownSection` or those related to the
            // component model. If, however, something gets past validation then
            // that's a bug in Wasmtime as we forgot to implement something.
            other => {
                self.validator.payload(&other)?;
                panic!("unimplemented section in wasm file {:?}", other);
            }
        }
        Ok(())
    }

    fn register_dwarf_section(&mut self, section: &CustomSectionReader<'data>) {
        let name = section.name();
        if !name.starts_with(".debug_") {
            return;
        }
        if !self.tunables.generate_native_debuginfo && !self.tunables.parse_wasm_debuginfo {
            self.result.has_unparsed_debuginfo = true;
            return;
        }
        let info = &mut self.result.debuginfo;
        let dwarf = &mut info.dwarf;
        let endian = gimli::LittleEndian;
        let data = section.data();
        let slice = gimli::EndianSlice::new(data, endian);

        match name {
            // `gimli::Dwarf` fields.
            ".debug_abbrev" => dwarf.debug_abbrev = gimli::DebugAbbrev::new(data, endian),
            ".debug_addr" => dwarf.debug_addr = gimli::DebugAddr::from(slice),
            ".debug_info" => dwarf.debug_info = gimli::DebugInfo::new(data, endian),
            ".debug_line" => dwarf.debug_line = gimli::DebugLine::new(data, endian),
            ".debug_line_str" => dwarf.debug_line_str = gimli::DebugLineStr::from(slice),
            ".debug_str" => dwarf.debug_str = gimli::DebugStr::new(data, endian),
            ".debug_str_offsets" => dwarf.debug_str_offsets = gimli::DebugStrOffsets::from(slice),
            ".debug_str_sup" => {
                let mut dwarf_sup: Dwarf<'data> = Default::default();
                dwarf_sup.debug_str = gimli::DebugStr::from(slice);
                dwarf.sup = Some(Arc::new(dwarf_sup));
            }
            ".debug_types" => dwarf.debug_types = gimli::DebugTypes::from(slice),

            // Additional fields.
            ".debug_loc" => info.debug_loc = gimli::DebugLoc::from(slice),
            ".debug_loclists" => info.debug_loclists = gimli::DebugLocLists::from(slice),
            ".debug_ranges" => info.debug_ranges = gimli::DebugRanges::new(data, endian),
            ".debug_rnglists" => info.debug_rnglists = gimli::DebugRngLists::new(data, endian),

            // We don't use these at the moment.
            ".debug_aranges" | ".debug_pubnames" | ".debug_pubtypes" => return,

            other => {
                log::warn!("unknown debug section `{}`", other);
                return;
            }
        }

        dwarf.ranges = gimli::RangeLists::new(info.debug_ranges, info.debug_rnglists);
        dwarf.locations = gimli::LocationLists::new(info.debug_loc, info.debug_loclists);
    }

    /// Declares a new import with the `module` and `field` names, importing the
    /// `ty` specified.
    ///
    /// Note that this method is somewhat tricky due to the implementation of
    /// the module linking proposal. In the module linking proposal two-level
    /// imports are recast as single-level imports of instances. That recasting
    /// happens here by recording an import of an instance for the first time
    /// we see a two-level import.
    ///
    /// When the module linking proposal is disabled, however, disregard this
    /// logic and instead work directly with two-level imports since no
    /// instances are defined.
    fn declare_import(&mut self, module: &'data str, field: &'data str, ty: EntityType) {
        let index = self.push_type(ty);
        self.result.module.initializers.push(Initializer::Import {
            name: module.to_owned(),
            field: field.to_owned(),
            index,
        });
    }

    fn push_type(&mut self, ty: EntityType) -> EntityIndex {
        match ty {
            EntityType::Function(ty) => EntityIndex::Function(self.result.module.push_function(ty)),
            EntityType::Table(ty) => {
                let plan = TablePlan::for_table(ty, &self.tunables);
                EntityIndex::Table(self.result.module.table_plans.push(plan))
            }
            EntityType::Memory(ty) => {
                let plan = MemoryPlan::for_memory(ty, &self.tunables);
                EntityIndex::Memory(self.result.module.memory_plans.push(plan))
            }
            EntityType::Global(ty) => EntityIndex::Global(self.result.module.globals.push(ty)),
            EntityType::Tag(_) => unimplemented!(),
        }
    }

Appends a new function to this module with the given type information.

Trait Implementations§

Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Deserialize this value from the given Serde deserializer. Read more
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.