1use crate::module::{
2 FuncRefIndex, Initializer, MemoryInitialization, MemoryInitializer, Module, TableSegment,
3 TableSegmentElements,
4};
5use crate::prelude::*;
6use crate::{
7 ConstExpr, ConstOp, DataIndex, DefinedFuncIndex, ElemIndex, EngineOrModuleTypeIndex,
8 EntityIndex, EntityType, FuncIndex, FuncKey, GlobalIndex, IndexType, InitMemory, MemoryIndex,
9 ModuleInternedTypeIndex, ModuleTypesBuilder, PrimaryMap, SizeOverflow, StaticMemoryInitializer,
10 StaticModuleIndex, TableIndex, TableInitialValue, Tag, TagIndex, Tunables, TypeConvert,
11 TypeIndex, WasmError, WasmHeapTopType, WasmHeapType, WasmResult, WasmValType,
12 WasmparserTypeConverter,
13};
14use anyhow::{Result, bail};
15use cranelift_entity::SecondaryMap;
16use cranelift_entity::packed_option::ReservedValue;
17use std::borrow::Cow;
18use std::collections::HashMap;
19use std::mem;
20use std::path::PathBuf;
21use std::sync::Arc;
22use wasmparser::{
23 CustomSectionReader, DataKind, ElementItems, ElementKind, Encoding, ExternalKind,
24 FuncToValidate, FunctionBody, KnownCustom, NameSectionReader, Naming, Parser, Payload, TypeRef,
25 Validator, ValidatorResources, types::Types,
26};
27
28pub struct ModuleEnvironment<'a, 'data> {
30 result: ModuleTranslation<'data>,
32
33 types: &'a mut ModuleTypesBuilder,
35
36 validator: &'a mut Validator,
38 tunables: &'a Tunables,
39}
40
41pub struct ModuleTranslation<'data> {
46 pub module: Module,
48
49 pub wasm: &'data [u8],
55
56 pub function_body_inputs: PrimaryMap<DefinedFuncIndex, FunctionBodyData<'data>>,
58
59 pub known_imported_functions: SecondaryMap<FuncIndex, Option<FuncKey>>,
68
69 pub exported_signatures: Vec<ModuleInternedTypeIndex>,
73
74 pub debuginfo: DebugInfoData<'data>,
76
77 pub has_unparsed_debuginfo: bool,
80
81 pub data: Vec<Cow<'data, [u8]>>,
87
88 pub data_align: Option<u64>,
95
96 total_data: u32,
98
99 pub passive_data: Vec<&'data [u8]>,
102
103 total_passive_data: u32,
105
106 code_index: u32,
109
110 types: Option<Types>,
113}
114
115impl<'data> ModuleTranslation<'data> {
116 pub fn new(module_index: StaticModuleIndex) -> Self {
118 Self {
119 module: Module::new(module_index),
120 wasm: &[],
121 function_body_inputs: PrimaryMap::default(),
122 known_imported_functions: SecondaryMap::default(),
123 exported_signatures: Vec::default(),
124 debuginfo: DebugInfoData::default(),
125 has_unparsed_debuginfo: false,
126 data: Vec::default(),
127 data_align: None,
128 total_data: 0,
129 passive_data: Vec::default(),
130 total_passive_data: 0,
131 code_index: 0,
132 types: None,
133 }
134 }
135
136 pub fn get_types(&self) -> &Types {
138 self.types
139 .as_ref()
140 .expect("module type information to be available")
141 }
142
143 pub fn module_index(&self) -> StaticModuleIndex {
145 self.module.module_index
146 }
147}
148
149pub struct FunctionBodyData<'a> {
151 pub body: FunctionBody<'a>,
153 pub validator: FuncToValidate<ValidatorResources>,
155}
156
157#[derive(Debug, Default)]
158#[expect(missing_docs, reason = "self-describing fields")]
159pub struct DebugInfoData<'a> {
160 pub dwarf: Dwarf<'a>,
161 pub name_section: NameSection<'a>,
162 pub wasm_file: WasmFileInfo,
163 pub debug_loc: gimli::DebugLoc<Reader<'a>>,
164 pub debug_loclists: gimli::DebugLocLists<Reader<'a>>,
165 pub debug_ranges: gimli::DebugRanges<Reader<'a>>,
166 pub debug_rnglists: gimli::DebugRngLists<Reader<'a>>,
167 pub debug_cu_index: gimli::DebugCuIndex<Reader<'a>>,
168 pub debug_tu_index: gimli::DebugTuIndex<Reader<'a>>,
169}
170
171#[expect(missing_docs, reason = "self-describing")]
172pub type Dwarf<'input> = gimli::Dwarf<Reader<'input>>;
173
174type Reader<'input> = gimli::EndianSlice<'input, gimli::LittleEndian>;
175
176#[derive(Debug, Default)]
177#[expect(missing_docs, reason = "self-describing fields")]
178pub struct NameSection<'a> {
179 pub module_name: Option<&'a str>,
180 pub func_names: HashMap<FuncIndex, &'a str>,
181 pub locals_names: HashMap<FuncIndex, HashMap<u32, &'a str>>,
182}
183
184#[derive(Debug, Default)]
185#[expect(missing_docs, reason = "self-describing fields")]
186pub struct WasmFileInfo {
187 pub path: Option<PathBuf>,
188 pub code_section_offset: u64,
189 pub imported_func_count: u32,
190 pub funcs: Vec<FunctionMetadata>,
191}
192
193#[derive(Debug)]
194#[expect(missing_docs, reason = "self-describing fields")]
195pub struct FunctionMetadata {
196 pub params: Box<[WasmValType]>,
197 pub locals: Box<[(u32, WasmValType)]>,
198}
199
200impl<'a, 'data> ModuleEnvironment<'a, 'data> {
201 pub fn new(
203 tunables: &'a Tunables,
204 validator: &'a mut Validator,
205 types: &'a mut ModuleTypesBuilder,
206 module_index: StaticModuleIndex,
207 ) -> Self {
208 Self {
209 result: ModuleTranslation::new(module_index),
210 types,
211 tunables,
212 validator,
213 }
214 }
215
216 pub fn translate(
225 mut self,
226 parser: Parser,
227 data: &'data [u8],
228 ) -> Result<ModuleTranslation<'data>> {
229 self.result.wasm = data;
230
231 for payload in parser.parse_all(data) {
232 self.translate_payload(payload?)?;
233 }
234
235 Ok(self.result)
236 }
237
238 fn translate_payload(&mut self, payload: Payload<'data>) -> Result<()> {
239 match payload {
240 Payload::Version {
241 num,
242 encoding,
243 range,
244 } => {
245 self.validator.version(num, encoding, &range)?;
246 match encoding {
247 Encoding::Module => {}
248 Encoding::Component => {
249 bail!("expected a WebAssembly module but was given a WebAssembly component")
250 }
251 }
252 }
253
254 Payload::End(offset) => {
255 self.result.types = Some(self.validator.end(offset)?);
256
257 self.result.exported_signatures = self
261 .result
262 .module
263 .functions
264 .iter()
265 .filter_map(|(_, func)| {
266 if func.is_escaping() {
267 Some(func.signature.unwrap_module_type_index())
268 } else {
269 None
270 }
271 })
272 .collect();
273 self.result.exported_signatures.sort_unstable();
274 self.result.exported_signatures.dedup();
275 }
276
277 Payload::TypeSection(types) => {
278 self.validator.type_section(&types)?;
279
280 let count = self.validator.types(0).unwrap().core_type_count_in_module();
281 log::trace!("interning {count} Wasm types");
282
283 let capacity = usize::try_from(count).unwrap();
284 self.result.module.types.reserve(capacity);
285 self.types.reserve_wasm_signatures(capacity);
286
287 let mut type_index = 0;
297 while type_index < count {
298 let validator_types = self.validator.types(0).unwrap();
299
300 log::trace!("looking up wasmparser type for index {type_index}");
303 let core_type_id = validator_types.core_type_at_in_module(type_index);
304 log::trace!(
305 " --> {core_type_id:?} = {:?}",
306 validator_types[core_type_id],
307 );
308 let rec_group_id = validator_types.rec_group_id_of(core_type_id);
309 debug_assert_eq!(
310 validator_types
311 .rec_group_elements(rec_group_id)
312 .position(|id| id == core_type_id),
313 Some(0)
314 );
315
316 let interned = self.types.intern_rec_group(validator_types, rec_group_id)?;
319 let elems = self.types.rec_group_elements(interned);
320 let len = elems.len();
321 self.result.module.types.reserve(len);
322 for ty in elems {
323 self.result.module.types.push(ty.into());
324 }
325
326 type_index += u32::try_from(len).unwrap();
328 }
329 }
330
331 Payload::ImportSection(imports) => {
332 self.validator.import_section(&imports)?;
333
334 let cnt = usize::try_from(imports.count()).unwrap();
335 self.result.module.initializers.reserve(cnt);
336
337 for entry in imports {
338 let import = entry?;
339 let ty = match import.ty {
340 TypeRef::Func(index) => {
341 let index = TypeIndex::from_u32(index);
342 let interned_index = self.result.module.types[index];
343 self.result.module.num_imported_funcs += 1;
344 self.result.debuginfo.wasm_file.imported_func_count += 1;
345 EntityType::Function(interned_index)
346 }
347 TypeRef::Memory(ty) => {
348 self.result.module.num_imported_memories += 1;
349 EntityType::Memory(ty.into())
350 }
351 TypeRef::Global(ty) => {
352 self.result.module.num_imported_globals += 1;
353 EntityType::Global(self.convert_global_type(&ty)?)
354 }
355 TypeRef::Table(ty) => {
356 self.result.module.num_imported_tables += 1;
357 EntityType::Table(self.convert_table_type(&ty)?)
358 }
359 TypeRef::Tag(ty) => {
360 let index = TypeIndex::from_u32(ty.func_type_idx);
361 let signature = self.result.module.types[index];
362 let exception = self.types.define_exception_type_for_tag(
363 signature.unwrap_module_type_index(),
364 );
365 let tag = Tag {
366 signature,
367 exception: EngineOrModuleTypeIndex::Module(exception),
368 };
369 self.result.module.num_imported_tags += 1;
370 EntityType::Tag(tag)
371 }
372 };
373 self.declare_import(import.module, import.name, ty);
374 }
375 }
376
377 Payload::FunctionSection(functions) => {
378 self.validator.function_section(&functions)?;
379
380 let cnt = usize::try_from(functions.count()).unwrap();
381 self.result.module.functions.reserve_exact(cnt);
382
383 for entry in functions {
384 let sigindex = entry?;
385 let ty = TypeIndex::from_u32(sigindex);
386 let interned_index = self.result.module.types[ty];
387 self.result.module.push_function(interned_index);
388 }
389 }
390
391 Payload::TableSection(tables) => {
392 self.validator.table_section(&tables)?;
393 let cnt = usize::try_from(tables.count()).unwrap();
394 self.result.module.tables.reserve_exact(cnt);
395
396 for entry in tables {
397 let wasmparser::Table { ty, init } = entry?;
398 let table = self.convert_table_type(&ty)?;
399 self.result.module.needs_gc_heap |= table.ref_type.is_vmgcref_type();
400 self.result.module.tables.push(table);
401 let init = match init {
402 wasmparser::TableInit::RefNull => TableInitialValue::Null {
403 precomputed: Vec::new(),
404 },
405 wasmparser::TableInit::Expr(expr) => {
406 let (init, escaped) = ConstExpr::from_wasmparser(self, expr)?;
407 for f in escaped {
408 self.flag_func_escaped(f);
409 }
410 TableInitialValue::Expr(init)
411 }
412 };
413 self.result
414 .module
415 .table_initialization
416 .initial_values
417 .push(init);
418 }
419 }
420
421 Payload::MemorySection(memories) => {
422 self.validator.memory_section(&memories)?;
423
424 let cnt = usize::try_from(memories.count()).unwrap();
425 self.result.module.memories.reserve_exact(cnt);
426
427 for entry in memories {
428 let memory = entry?;
429 self.result.module.memories.push(memory.into());
430 }
431 }
432
433 Payload::TagSection(tags) => {
434 self.validator.tag_section(&tags)?;
435
436 for entry in tags {
437 let sigindex = entry?.func_type_idx;
438 let ty = TypeIndex::from_u32(sigindex);
439 let interned_index = self.result.module.types[ty];
440 let exception = self
441 .types
442 .define_exception_type_for_tag(interned_index.unwrap_module_type_index());
443 self.result.module.push_tag(interned_index, exception);
444 }
445 }
446
447 Payload::GlobalSection(globals) => {
448 self.validator.global_section(&globals)?;
449
450 let cnt = usize::try_from(globals.count()).unwrap();
451 self.result.module.globals.reserve_exact(cnt);
452
453 for entry in globals {
454 let wasmparser::Global { ty, init_expr } = entry?;
455 let (initializer, escaped) = ConstExpr::from_wasmparser(self, init_expr)?;
456 for f in escaped {
457 self.flag_func_escaped(f);
458 }
459 let ty = self.convert_global_type(&ty)?;
460 self.result.module.globals.push(ty);
461 self.result.module.global_initializers.push(initializer);
462 }
463 }
464
465 Payload::ExportSection(exports) => {
466 self.validator.export_section(&exports)?;
467
468 let cnt = usize::try_from(exports.count()).unwrap();
469 self.result.module.exports.reserve(cnt);
470
471 for entry in exports {
472 let wasmparser::Export { name, kind, index } = entry?;
473 let entity = match kind {
474 ExternalKind::Func => {
475 let index = FuncIndex::from_u32(index);
476 self.flag_func_escaped(index);
477 EntityIndex::Function(index)
478 }
479 ExternalKind::Table => EntityIndex::Table(TableIndex::from_u32(index)),
480 ExternalKind::Memory => EntityIndex::Memory(MemoryIndex::from_u32(index)),
481 ExternalKind::Global => EntityIndex::Global(GlobalIndex::from_u32(index)),
482 ExternalKind::Tag => EntityIndex::Tag(TagIndex::from_u32(index)),
483 };
484 self.result
485 .module
486 .exports
487 .insert(String::from(name), entity);
488 }
489 }
490
491 Payload::StartSection { func, range } => {
492 self.validator.start_section(func, &range)?;
493
494 let func_index = FuncIndex::from_u32(func);
495 self.flag_func_escaped(func_index);
496 debug_assert!(self.result.module.start_func.is_none());
497 self.result.module.start_func = Some(func_index);
498 }
499
500 Payload::ElementSection(elements) => {
501 self.validator.element_section(&elements)?;
502
503 for (index, entry) in elements.into_iter().enumerate() {
504 let wasmparser::Element {
505 kind,
506 items,
507 range: _,
508 } = entry?;
509
510 let elements = match items {
516 ElementItems::Functions(funcs) => {
517 let mut elems =
518 Vec::with_capacity(usize::try_from(funcs.count()).unwrap());
519 for func in funcs {
520 let func = FuncIndex::from_u32(func?);
521 self.flag_func_escaped(func);
522 elems.push(func);
523 }
524 TableSegmentElements::Functions(elems.into())
525 }
526 ElementItems::Expressions(_ty, items) => {
527 let mut exprs =
528 Vec::with_capacity(usize::try_from(items.count()).unwrap());
529 for expr in items {
530 let (expr, escaped) = ConstExpr::from_wasmparser(self, expr?)?;
531 exprs.push(expr);
532 for func in escaped {
533 self.flag_func_escaped(func);
534 }
535 }
536 TableSegmentElements::Expressions(exprs.into())
537 }
538 };
539
540 match kind {
541 ElementKind::Active {
542 table_index,
543 offset_expr,
544 } => {
545 let table_index = TableIndex::from_u32(table_index.unwrap_or(0));
546 let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?;
547 debug_assert!(escaped.is_empty());
548
549 self.result
550 .module
551 .table_initialization
552 .segments
553 .push(TableSegment {
554 table_index,
555 offset,
556 elements,
557 });
558 }
559
560 ElementKind::Passive => {
561 let elem_index = ElemIndex::from_u32(index as u32);
562 let index = self.result.module.passive_elements.len();
563 self.result.module.passive_elements.push(elements);
564 self.result
565 .module
566 .passive_elements_map
567 .insert(elem_index, index);
568 }
569
570 ElementKind::Declared => {}
571 }
572 }
573 }
574
575 Payload::CodeSectionStart { count, range, .. } => {
576 self.validator.code_section_start(&range)?;
577 let cnt = usize::try_from(count).unwrap();
578 self.result.function_body_inputs.reserve_exact(cnt);
579 self.result.debuginfo.wasm_file.code_section_offset = range.start as u64;
580 }
581
582 Payload::CodeSectionEntry(body) => {
583 let validator = self.validator.code_section_entry(&body)?;
584 let func_index =
585 self.result.code_index + self.result.module.num_imported_funcs as u32;
586 let func_index = FuncIndex::from_u32(func_index);
587
588 if self.tunables.debug_native {
589 let sig_index = self.result.module.functions[func_index]
590 .signature
591 .unwrap_module_type_index();
592 let sig = self.types[sig_index].unwrap_func();
593 let mut locals = Vec::new();
594 for pair in body.get_locals_reader()? {
595 let (cnt, ty) = pair?;
596 let ty = self.convert_valtype(ty)?;
597 locals.push((cnt, ty));
598 }
599 self.result
600 .debuginfo
601 .wasm_file
602 .funcs
603 .push(FunctionMetadata {
604 locals: locals.into_boxed_slice(),
605 params: sig.params().into(),
606 });
607 }
608 self.result
609 .function_body_inputs
610 .push(FunctionBodyData { validator, body });
611 self.result.code_index += 1;
612 }
613
614 Payload::DataSection(data) => {
615 self.validator.data_section(&data)?;
616
617 let initializers = match &mut self.result.module.memory_initialization {
618 MemoryInitialization::Segmented(i) => i,
619 _ => unreachable!(),
620 };
621
622 let cnt = usize::try_from(data.count()).unwrap();
623 initializers.reserve_exact(cnt);
624 self.result.data.reserve_exact(cnt);
625
626 for (index, entry) in data.into_iter().enumerate() {
627 let wasmparser::Data {
628 kind,
629 data,
630 range: _,
631 } = entry?;
632 let mk_range = |total: &mut u32| -> Result<_, WasmError> {
633 let range = u32::try_from(data.len())
634 .ok()
635 .and_then(|size| {
636 let start = *total;
637 let end = start.checked_add(size)?;
638 Some(start..end)
639 })
640 .ok_or_else(|| {
641 WasmError::Unsupported(format!(
642 "more than 4 gigabytes of data in wasm module",
643 ))
644 })?;
645 *total += range.end - range.start;
646 Ok(range)
647 };
648 match kind {
649 DataKind::Active {
650 memory_index,
651 offset_expr,
652 } => {
653 let range = mk_range(&mut self.result.total_data)?;
654 let memory_index = MemoryIndex::from_u32(memory_index);
655 let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?;
656 debug_assert!(escaped.is_empty());
657
658 let initializers = match &mut self.result.module.memory_initialization {
659 MemoryInitialization::Segmented(i) => i,
660 _ => unreachable!(),
661 };
662 initializers.push(MemoryInitializer {
663 memory_index,
664 offset,
665 data: range,
666 });
667 self.result.data.push(data.into());
668 }
669 DataKind::Passive => {
670 let data_index = DataIndex::from_u32(index as u32);
671 let range = mk_range(&mut self.result.total_passive_data)?;
672 self.result.passive_data.push(data);
673 self.result
674 .module
675 .passive_data_map
676 .insert(data_index, range);
677 }
678 }
679 }
680 }
681
682 Payload::DataCountSection { count, range } => {
683 self.validator.data_count_section(count, &range)?;
684
685 }
691
692 Payload::CustomSection(s)
693 if s.name() == "webidl-bindings" || s.name() == "wasm-interface-types" =>
694 {
695 bail!(
696 "\
697Support for interface types has temporarily been removed from `wasmtime`.
698
699For more information about this temporary change you can read on the issue online:
700
701 https://github.com/bytecodealliance/wasmtime/issues/1271
702
703and for re-adding support for interface types you can see this issue:
704
705 https://github.com/bytecodealliance/wasmtime/issues/677
706"
707 )
708 }
709
710 Payload::CustomSection(s) => {
711 self.register_custom_section(&s);
712 }
713
714 other => {
719 self.validator.payload(&other)?;
720 panic!("unimplemented section in wasm file {other:?}");
721 }
722 }
723 Ok(())
724 }
725
726 fn register_custom_section(&mut self, section: &CustomSectionReader<'data>) {
727 match section.as_known() {
728 KnownCustom::Name(name) => {
729 let result = self.name_section(name);
730 if let Err(e) = result {
731 log::warn!("failed to parse name section {e:?}");
732 }
733 }
734 _ => {
735 let name = section.name().trim_end_matches(".dwo");
736 if name.starts_with(".debug_") {
737 self.dwarf_section(name, section);
738 }
739 }
740 }
741 }
742
743 fn dwarf_section(&mut self, name: &str, section: &CustomSectionReader<'data>) {
744 if !self.tunables.debug_native && !self.tunables.parse_wasm_debuginfo {
745 self.result.has_unparsed_debuginfo = true;
746 return;
747 }
748 let info = &mut self.result.debuginfo;
749 let dwarf = &mut info.dwarf;
750 let endian = gimli::LittleEndian;
751 let data = section.data();
752 let slice = gimli::EndianSlice::new(data, endian);
753
754 match name {
755 ".debug_abbrev" => dwarf.debug_abbrev = gimli::DebugAbbrev::new(data, endian),
757 ".debug_addr" => dwarf.debug_addr = gimli::DebugAddr::from(slice),
758 ".debug_info" => {
759 dwarf.debug_info = gimli::DebugInfo::new(data, endian);
760 }
761 ".debug_line" => dwarf.debug_line = gimli::DebugLine::new(data, endian),
762 ".debug_line_str" => dwarf.debug_line_str = gimli::DebugLineStr::from(slice),
763 ".debug_str" => dwarf.debug_str = gimli::DebugStr::new(data, endian),
764 ".debug_str_offsets" => dwarf.debug_str_offsets = gimli::DebugStrOffsets::from(slice),
765 ".debug_str_sup" => {
766 let mut dwarf_sup: Dwarf<'data> = Default::default();
767 dwarf_sup.debug_str = gimli::DebugStr::from(slice);
768 dwarf.sup = Some(Arc::new(dwarf_sup));
769 }
770 ".debug_types" => dwarf.debug_types = gimli::DebugTypes::from(slice),
771
772 ".debug_loc" => info.debug_loc = gimli::DebugLoc::from(slice),
774 ".debug_loclists" => info.debug_loclists = gimli::DebugLocLists::from(slice),
775 ".debug_ranges" => info.debug_ranges = gimli::DebugRanges::new(data, endian),
776 ".debug_rnglists" => info.debug_rnglists = gimli::DebugRngLists::new(data, endian),
777
778 ".debug_cu_index" => info.debug_cu_index = gimli::DebugCuIndex::new(data, endian),
780 ".debug_tu_index" => info.debug_tu_index = gimli::DebugTuIndex::new(data, endian),
781
782 ".debug_aranges" | ".debug_pubnames" | ".debug_pubtypes" => return,
784 other => {
785 log::warn!("unknown debug section `{other}`");
786 return;
787 }
788 }
789
790 dwarf.ranges = gimli::RangeLists::new(info.debug_ranges, info.debug_rnglists);
791 dwarf.locations = gimli::LocationLists::new(info.debug_loc, info.debug_loclists);
792 }
793
794 fn declare_import(&mut self, module: &'data str, field: &'data str, ty: EntityType) {
807 let index = self.push_type(ty);
808 self.result.module.initializers.push(Initializer::Import {
809 name: module.to_owned(),
810 field: field.to_owned(),
811 index,
812 });
813 }
814
815 fn push_type(&mut self, ty: EntityType) -> EntityIndex {
816 match ty {
817 EntityType::Function(ty) => EntityIndex::Function({
818 let func_index = self
819 .result
820 .module
821 .push_function(ty.unwrap_module_type_index());
822 self.flag_func_escaped(func_index);
825 func_index
826 }),
827 EntityType::Table(ty) => EntityIndex::Table(self.result.module.tables.push(ty)),
828 EntityType::Memory(ty) => EntityIndex::Memory(self.result.module.memories.push(ty)),
829 EntityType::Global(ty) => EntityIndex::Global(self.result.module.globals.push(ty)),
830 EntityType::Tag(ty) => EntityIndex::Tag(self.result.module.tags.push(ty)),
831 }
832 }
833
834 fn flag_func_escaped(&mut self, func: FuncIndex) {
835 let ty = &mut self.result.module.functions[func];
836 if ty.is_escaping() {
838 return;
839 }
840 let index = self.result.module.num_escaped_funcs as u32;
841 ty.func_ref = FuncRefIndex::from_u32(index);
842 self.result.module.num_escaped_funcs += 1;
843 }
844
845 fn name_section(&mut self, names: NameSectionReader<'data>) -> WasmResult<()> {
847 for subsection in names {
848 match subsection? {
849 wasmparser::Name::Function(names) => {
850 for name in names {
851 let Naming { index, name } = name?;
852 if (index as usize) >= self.result.module.functions.len() {
855 continue;
856 }
857
858 let index = FuncIndex::from_u32(index);
863 self.result
864 .debuginfo
865 .name_section
866 .func_names
867 .insert(index, name);
868 }
869 }
870 wasmparser::Name::Module { name, .. } => {
871 self.result.module.name = Some(name.to_string());
872 if self.tunables.debug_native {
873 self.result.debuginfo.name_section.module_name = Some(name);
874 }
875 }
876 wasmparser::Name::Local(reader) => {
877 if !self.tunables.debug_native {
878 continue;
879 }
880 for f in reader {
881 let f = f?;
882 if (f.index as usize) >= self.result.module.functions.len() {
885 continue;
886 }
887 for name in f.names {
888 let Naming { index, name } = name?;
889
890 self.result
891 .debuginfo
892 .name_section
893 .locals_names
894 .entry(FuncIndex::from_u32(f.index))
895 .or_insert(HashMap::new())
896 .insert(index, name);
897 }
898 }
899 }
900 wasmparser::Name::Label(_)
901 | wasmparser::Name::Type(_)
902 | wasmparser::Name::Table(_)
903 | wasmparser::Name::Global(_)
904 | wasmparser::Name::Memory(_)
905 | wasmparser::Name::Element(_)
906 | wasmparser::Name::Data(_)
907 | wasmparser::Name::Tag(_)
908 | wasmparser::Name::Field(_)
909 | wasmparser::Name::Unknown { .. } => {}
910 }
911 }
912 Ok(())
913 }
914}
915
916impl TypeConvert for ModuleEnvironment<'_, '_> {
917 fn lookup_heap_type(&self, index: wasmparser::UnpackedIndex) -> WasmHeapType {
918 WasmparserTypeConverter::new(&self.types, |idx| {
919 self.result.module.types[idx].unwrap_module_type_index()
920 })
921 .lookup_heap_type(index)
922 }
923
924 fn lookup_type_index(&self, index: wasmparser::UnpackedIndex) -> EngineOrModuleTypeIndex {
925 WasmparserTypeConverter::new(&self.types, |idx| {
926 self.result.module.types[idx].unwrap_module_type_index()
927 })
928 .lookup_type_index(index)
929 }
930}
931
932impl ModuleTranslation<'_> {
933 pub fn try_static_init(&mut self, page_size: u64, max_image_size_always_allowed: u64) {
964 if !self.module.memory_initialization.is_segmented() {
967 return;
968 }
969
970 struct Memory {
974 data_size: u64,
975 min_addr: u64,
976 max_addr: u64,
977 segments: Vec<(usize, StaticMemoryInitializer)>,
981 }
982 let mut info = PrimaryMap::with_capacity(self.module.memories.len());
983 for _ in 0..self.module.memories.len() {
984 info.push(Memory {
985 data_size: 0,
986 min_addr: u64::MAX,
987 max_addr: 0,
988 segments: Vec::new(),
989 });
990 }
991
992 struct InitMemoryAtCompileTime<'a> {
993 module: &'a Module,
994 info: &'a mut PrimaryMap<MemoryIndex, Memory>,
995 idx: usize,
996 }
997 impl InitMemory for InitMemoryAtCompileTime<'_> {
998 fn memory_size_in_bytes(
999 &mut self,
1000 memory_index: MemoryIndex,
1001 ) -> Result<u64, SizeOverflow> {
1002 self.module.memories[memory_index].minimum_byte_size()
1003 }
1004
1005 fn eval_offset(&mut self, memory_index: MemoryIndex, expr: &ConstExpr) -> Option<u64> {
1006 match (expr.ops(), self.module.memories[memory_index].idx_type) {
1007 (&[ConstOp::I32Const(offset)], IndexType::I32) => {
1008 Some(offset.cast_unsigned().into())
1009 }
1010 (&[ConstOp::I64Const(offset)], IndexType::I64) => Some(offset.cast_unsigned()),
1011 _ => None,
1012 }
1013 }
1014
1015 fn write(&mut self, memory: MemoryIndex, init: &StaticMemoryInitializer) -> bool {
1016 if self.module.defined_memory_index(memory).is_none() {
1021 return false;
1022 };
1023 let info = &mut self.info[memory];
1024 let data_len = u64::from(init.data.end - init.data.start);
1025 if data_len > 0 {
1026 info.data_size += data_len;
1027 info.min_addr = info.min_addr.min(init.offset);
1028 info.max_addr = info.max_addr.max(init.offset + data_len);
1029 info.segments.push((self.idx, init.clone()));
1030 }
1031 self.idx += 1;
1032 true
1033 }
1034 }
1035 let ok = self
1036 .module
1037 .memory_initialization
1038 .init_memory(&mut InitMemoryAtCompileTime {
1039 idx: 0,
1040 module: &self.module,
1041 info: &mut info,
1042 });
1043 if !ok {
1044 return;
1045 }
1046
1047 for (i, info) in info.iter().filter(|(_, info)| info.data_size > 0) {
1050 let image_size = info.max_addr - info.min_addr;
1051
1052 if self.module.memories[i].page_size() < page_size {
1060 return;
1061 }
1062
1063 if image_size < info.data_size.saturating_mul(2) {
1070 continue;
1071 }
1072
1073 if image_size < max_image_size_always_allowed {
1077 continue;
1078 }
1079
1080 return;
1084 }
1085
1086 let data = mem::replace(&mut self.data, Vec::new());
1090 let mut map = PrimaryMap::with_capacity(info.len());
1091 let mut module_data_size = 0u32;
1092 for (memory, info) in info.iter() {
1093 let extent = if info.segments.len() > 0 {
1096 (info.max_addr - info.min_addr) as usize
1097 } else {
1098 0
1099 };
1100 let mut image = Vec::with_capacity(extent);
1101 for (idx, init) in info.segments.iter() {
1102 let data = &data[*idx];
1103 assert_eq!(data.len(), init.data.len());
1104 let offset = usize::try_from(init.offset - info.min_addr).unwrap();
1105 if image.len() < offset {
1106 image.resize(offset, 0u8);
1107 image.extend_from_slice(data);
1108 } else {
1109 image.splice(
1110 offset..(offset + data.len()).min(image.len()),
1111 data.iter().copied(),
1112 );
1113 }
1114 }
1115 assert_eq!(image.len(), extent);
1116 assert_eq!(image.capacity(), extent);
1117 let mut offset = if info.segments.len() > 0 {
1118 info.min_addr
1119 } else {
1120 0
1121 };
1122
1123 if let Some(i) = image.iter().rposition(|i| *i != 0) {
1127 image.truncate(i + 1);
1128 }
1129
1130 if let Some(i) = image.iter().position(|i| *i != 0) {
1132 offset += i as u64;
1133 image.drain(..i);
1134 }
1135 let mut len = u64::try_from(image.len()).unwrap();
1136
1137 if offset % page_size != 0 {
1142 let zero_padding = offset % page_size;
1143 self.data.push(vec![0; zero_padding as usize].into());
1144 offset -= zero_padding;
1145 len += zero_padding;
1146 }
1147 self.data.push(image.into());
1148 if len % page_size != 0 {
1149 let zero_padding = page_size - (len % page_size);
1150 self.data.push(vec![0; zero_padding as usize].into());
1151 len += zero_padding;
1152 }
1153
1154 assert!(offset % page_size == 0);
1156 assert!(len % page_size == 0);
1157
1158 let len = u32::try_from(len).unwrap();
1166 let init = if len > 0 {
1167 Some(StaticMemoryInitializer {
1168 offset,
1169 data: module_data_size..module_data_size + len,
1170 })
1171 } else {
1172 None
1173 };
1174 let idx = map.push(init);
1175 assert_eq!(idx, memory);
1176 module_data_size += len;
1177 }
1178 self.data_align = Some(page_size);
1179 self.module.memory_initialization = MemoryInitialization::Static { map };
1180 }
1181
1182 pub fn try_func_table_init(&mut self) {
1187 const MAX_FUNC_TABLE_SIZE: u64 = 1024 * 1024;
1191
1192 for ((_, init), (_, table)) in self
1195 .module
1196 .table_initialization
1197 .initial_values
1198 .iter_mut()
1199 .zip(
1200 self.module
1201 .tables
1202 .iter()
1203 .skip(self.module.num_imported_tables),
1204 )
1205 {
1206 let table_size = table.limits.min;
1207 if table_size > MAX_FUNC_TABLE_SIZE {
1208 continue;
1209 }
1210 if let TableInitialValue::Expr(expr) = init {
1211 if let [ConstOp::RefFunc(f)] = expr.ops() {
1212 *init = TableInitialValue::Null {
1213 precomputed: vec![*f; table_size as usize],
1214 };
1215 }
1216 }
1217 }
1218
1219 let mut segments = mem::take(&mut self.module.table_initialization.segments)
1220 .into_iter()
1221 .peekable();
1222
1223 while let Some(segment) = segments.peek() {
1235 let defined_index = match self.module.defined_table_index(segment.table_index) {
1236 Some(index) => index,
1237 None => break,
1241 };
1242
1243 let offset = match segment.offset.ops() {
1247 &[ConstOp::I32Const(offset)] => u64::from(offset.cast_unsigned()),
1248 &[ConstOp::I64Const(offset)] => offset.cast_unsigned(),
1249 _ => break,
1250 };
1251
1252 let top = match offset.checked_add(segment.elements.len()) {
1256 Some(top) => top,
1257 None => break,
1258 };
1259 let table_size = self.module.tables[segment.table_index].limits.min;
1260 if top > table_size || top > MAX_FUNC_TABLE_SIZE {
1261 break;
1262 }
1263
1264 match self.module.tables[segment.table_index]
1265 .ref_type
1266 .heap_type
1267 .top()
1268 {
1269 WasmHeapTopType::Func => {}
1270 WasmHeapTopType::Any
1276 | WasmHeapTopType::Extern
1277 | WasmHeapTopType::Cont
1278 | WasmHeapTopType::Exn => break,
1279 }
1280
1281 let function_elements = match &segment.elements {
1284 TableSegmentElements::Functions(indices) => indices,
1285 TableSegmentElements::Expressions(_) => break,
1286 };
1287
1288 let precomputed =
1289 match &mut self.module.table_initialization.initial_values[defined_index] {
1290 TableInitialValue::Null { precomputed } => precomputed,
1291
1292 TableInitialValue::Expr(_) => break,
1299 };
1300
1301 if precomputed.len() < top as usize {
1307 precomputed.resize(top as usize, FuncIndex::reserved_value());
1308 }
1309 let dst = &mut precomputed[offset as usize..top as usize];
1310 dst.copy_from_slice(&function_elements);
1311
1312 let _ = segments.next();
1314 }
1315 self.module.table_initialization.segments = segments.collect();
1316 }
1317}