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 TypeRef::FuncExact(_) => {
373 bail!("custom-descriptors proposal not implemented yet");
374 }
375 };
376 self.declare_import(import.module, import.name, ty);
377 }
378 }
379
380 Payload::FunctionSection(functions) => {
381 self.validator.function_section(&functions)?;
382
383 let cnt = usize::try_from(functions.count()).unwrap();
384 self.result.module.functions.reserve_exact(cnt);
385
386 for entry in functions {
387 let sigindex = entry?;
388 let ty = TypeIndex::from_u32(sigindex);
389 let interned_index = self.result.module.types[ty];
390 self.result.module.push_function(interned_index);
391 }
392 }
393
394 Payload::TableSection(tables) => {
395 self.validator.table_section(&tables)?;
396 let cnt = usize::try_from(tables.count()).unwrap();
397 self.result.module.tables.reserve_exact(cnt);
398
399 for entry in tables {
400 let wasmparser::Table { ty, init } = entry?;
401 let table = self.convert_table_type(&ty)?;
402 self.result.module.needs_gc_heap |= table.ref_type.is_vmgcref_type();
403 self.result.module.tables.push(table);
404 let init = match init {
405 wasmparser::TableInit::RefNull => TableInitialValue::Null {
406 precomputed: Vec::new(),
407 },
408 wasmparser::TableInit::Expr(expr) => {
409 let (init, escaped) = ConstExpr::from_wasmparser(self, expr)?;
410 for f in escaped {
411 self.flag_func_escaped(f);
412 }
413 TableInitialValue::Expr(init)
414 }
415 };
416 self.result
417 .module
418 .table_initialization
419 .initial_values
420 .push(init);
421 }
422 }
423
424 Payload::MemorySection(memories) => {
425 self.validator.memory_section(&memories)?;
426
427 let cnt = usize::try_from(memories.count()).unwrap();
428 self.result.module.memories.reserve_exact(cnt);
429
430 for entry in memories {
431 let memory = entry?;
432 self.result.module.memories.push(memory.into());
433 }
434 }
435
436 Payload::TagSection(tags) => {
437 self.validator.tag_section(&tags)?;
438
439 for entry in tags {
440 let sigindex = entry?.func_type_idx;
441 let ty = TypeIndex::from_u32(sigindex);
442 let interned_index = self.result.module.types[ty];
443 let exception = self
444 .types
445 .define_exception_type_for_tag(interned_index.unwrap_module_type_index());
446 self.result.module.push_tag(interned_index, exception);
447 }
448 }
449
450 Payload::GlobalSection(globals) => {
451 self.validator.global_section(&globals)?;
452
453 let cnt = usize::try_from(globals.count()).unwrap();
454 self.result.module.globals.reserve_exact(cnt);
455
456 for entry in globals {
457 let wasmparser::Global { ty, init_expr } = entry?;
458 let (initializer, escaped) = ConstExpr::from_wasmparser(self, init_expr)?;
459 for f in escaped {
460 self.flag_func_escaped(f);
461 }
462 let ty = self.convert_global_type(&ty)?;
463 self.result.module.globals.push(ty);
464 self.result.module.global_initializers.push(initializer);
465 }
466 }
467
468 Payload::ExportSection(exports) => {
469 self.validator.export_section(&exports)?;
470
471 let cnt = usize::try_from(exports.count()).unwrap();
472 self.result.module.exports.reserve(cnt);
473
474 for entry in exports {
475 let wasmparser::Export { name, kind, index } = entry?;
476 let entity = match kind {
477 ExternalKind::Func | ExternalKind::FuncExact => {
478 let index = FuncIndex::from_u32(index);
479 self.flag_func_escaped(index);
480 EntityIndex::Function(index)
481 }
482 ExternalKind::Table => EntityIndex::Table(TableIndex::from_u32(index)),
483 ExternalKind::Memory => EntityIndex::Memory(MemoryIndex::from_u32(index)),
484 ExternalKind::Global => EntityIndex::Global(GlobalIndex::from_u32(index)),
485 ExternalKind::Tag => EntityIndex::Tag(TagIndex::from_u32(index)),
486 };
487 self.result
488 .module
489 .exports
490 .insert(String::from(name), entity);
491 }
492 }
493
494 Payload::StartSection { func, range } => {
495 self.validator.start_section(func, &range)?;
496
497 let func_index = FuncIndex::from_u32(func);
498 self.flag_func_escaped(func_index);
499 debug_assert!(self.result.module.start_func.is_none());
500 self.result.module.start_func = Some(func_index);
501 }
502
503 Payload::ElementSection(elements) => {
504 self.validator.element_section(&elements)?;
505
506 for (index, entry) in elements.into_iter().enumerate() {
507 let wasmparser::Element {
508 kind,
509 items,
510 range: _,
511 } = entry?;
512
513 let elements = match items {
519 ElementItems::Functions(funcs) => {
520 let mut elems =
521 Vec::with_capacity(usize::try_from(funcs.count()).unwrap());
522 for func in funcs {
523 let func = FuncIndex::from_u32(func?);
524 self.flag_func_escaped(func);
525 elems.push(func);
526 }
527 TableSegmentElements::Functions(elems.into())
528 }
529 ElementItems::Expressions(_ty, items) => {
530 let mut exprs =
531 Vec::with_capacity(usize::try_from(items.count()).unwrap());
532 for expr in items {
533 let (expr, escaped) = ConstExpr::from_wasmparser(self, expr?)?;
534 exprs.push(expr);
535 for func in escaped {
536 self.flag_func_escaped(func);
537 }
538 }
539 TableSegmentElements::Expressions(exprs.into())
540 }
541 };
542
543 match kind {
544 ElementKind::Active {
545 table_index,
546 offset_expr,
547 } => {
548 let table_index = TableIndex::from_u32(table_index.unwrap_or(0));
549 let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?;
550 debug_assert!(escaped.is_empty());
551
552 self.result
553 .module
554 .table_initialization
555 .segments
556 .push(TableSegment {
557 table_index,
558 offset,
559 elements,
560 });
561 }
562
563 ElementKind::Passive => {
564 let elem_index = ElemIndex::from_u32(index as u32);
565 let index = self.result.module.passive_elements.len();
566 self.result.module.passive_elements.push(elements);
567 self.result
568 .module
569 .passive_elements_map
570 .insert(elem_index, index);
571 }
572
573 ElementKind::Declared => {}
574 }
575 }
576 }
577
578 Payload::CodeSectionStart { count, range, .. } => {
579 self.validator.code_section_start(&range)?;
580 let cnt = usize::try_from(count).unwrap();
581 self.result.function_body_inputs.reserve_exact(cnt);
582 self.result.debuginfo.wasm_file.code_section_offset = range.start as u64;
583 }
584
585 Payload::CodeSectionEntry(body) => {
586 let validator = self.validator.code_section_entry(&body)?;
587 let func_index =
588 self.result.code_index + self.result.module.num_imported_funcs as u32;
589 let func_index = FuncIndex::from_u32(func_index);
590
591 if self.tunables.debug_native {
592 let sig_index = self.result.module.functions[func_index]
593 .signature
594 .unwrap_module_type_index();
595 let sig = self.types[sig_index].unwrap_func();
596 let mut locals = Vec::new();
597 for pair in body.get_locals_reader()? {
598 let (cnt, ty) = pair?;
599 let ty = self.convert_valtype(ty)?;
600 locals.push((cnt, ty));
601 }
602 self.result
603 .debuginfo
604 .wasm_file
605 .funcs
606 .push(FunctionMetadata {
607 locals: locals.into_boxed_slice(),
608 params: sig.params().into(),
609 });
610 }
611 self.result
612 .function_body_inputs
613 .push(FunctionBodyData { validator, body });
614 self.result.code_index += 1;
615 }
616
617 Payload::DataSection(data) => {
618 self.validator.data_section(&data)?;
619
620 let initializers = match &mut self.result.module.memory_initialization {
621 MemoryInitialization::Segmented(i) => i,
622 _ => unreachable!(),
623 };
624
625 let cnt = usize::try_from(data.count()).unwrap();
626 initializers.reserve_exact(cnt);
627 self.result.data.reserve_exact(cnt);
628
629 for (index, entry) in data.into_iter().enumerate() {
630 let wasmparser::Data {
631 kind,
632 data,
633 range: _,
634 } = entry?;
635 let mk_range = |total: &mut u32| -> Result<_, WasmError> {
636 let range = u32::try_from(data.len())
637 .ok()
638 .and_then(|size| {
639 let start = *total;
640 let end = start.checked_add(size)?;
641 Some(start..end)
642 })
643 .ok_or_else(|| {
644 WasmError::Unsupported(format!(
645 "more than 4 gigabytes of data in wasm module",
646 ))
647 })?;
648 *total += range.end - range.start;
649 Ok(range)
650 };
651 match kind {
652 DataKind::Active {
653 memory_index,
654 offset_expr,
655 } => {
656 let range = mk_range(&mut self.result.total_data)?;
657 let memory_index = MemoryIndex::from_u32(memory_index);
658 let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?;
659 debug_assert!(escaped.is_empty());
660
661 let initializers = match &mut self.result.module.memory_initialization {
662 MemoryInitialization::Segmented(i) => i,
663 _ => unreachable!(),
664 };
665 initializers.push(MemoryInitializer {
666 memory_index,
667 offset,
668 data: range,
669 });
670 self.result.data.push(data.into());
671 }
672 DataKind::Passive => {
673 let data_index = DataIndex::from_u32(index as u32);
674 let range = mk_range(&mut self.result.total_passive_data)?;
675 self.result.passive_data.push(data);
676 self.result
677 .module
678 .passive_data_map
679 .insert(data_index, range);
680 }
681 }
682 }
683 }
684
685 Payload::DataCountSection { count, range } => {
686 self.validator.data_count_section(count, &range)?;
687
688 }
694
695 Payload::CustomSection(s)
696 if s.name() == "webidl-bindings" || s.name() == "wasm-interface-types" =>
697 {
698 bail!(
699 "\
700Support for interface types has temporarily been removed from `wasmtime`.
701
702For more information about this temporary change you can read on the issue online:
703
704 https://github.com/bytecodealliance/wasmtime/issues/1271
705
706and for re-adding support for interface types you can see this issue:
707
708 https://github.com/bytecodealliance/wasmtime/issues/677
709"
710 )
711 }
712
713 Payload::CustomSection(s) => {
714 self.register_custom_section(&s);
715 }
716
717 other => {
722 self.validator.payload(&other)?;
723 panic!("unimplemented section in wasm file {other:?}");
724 }
725 }
726 Ok(())
727 }
728
729 fn register_custom_section(&mut self, section: &CustomSectionReader<'data>) {
730 match section.as_known() {
731 KnownCustom::Name(name) => {
732 let result = self.name_section(name);
733 if let Err(e) = result {
734 log::warn!("failed to parse name section {e:?}");
735 }
736 }
737 _ => {
738 let name = section.name().trim_end_matches(".dwo");
739 if name.starts_with(".debug_") {
740 self.dwarf_section(name, section);
741 }
742 }
743 }
744 }
745
746 fn dwarf_section(&mut self, name: &str, section: &CustomSectionReader<'data>) {
747 if !self.tunables.debug_native && !self.tunables.parse_wasm_debuginfo {
748 self.result.has_unparsed_debuginfo = true;
749 return;
750 }
751 let info = &mut self.result.debuginfo;
752 let dwarf = &mut info.dwarf;
753 let endian = gimli::LittleEndian;
754 let data = section.data();
755 let slice = gimli::EndianSlice::new(data, endian);
756
757 match name {
758 ".debug_abbrev" => dwarf.debug_abbrev = gimli::DebugAbbrev::new(data, endian),
760 ".debug_addr" => dwarf.debug_addr = gimli::DebugAddr::from(slice),
761 ".debug_info" => {
762 dwarf.debug_info = gimli::DebugInfo::new(data, endian);
763 }
764 ".debug_line" => dwarf.debug_line = gimli::DebugLine::new(data, endian),
765 ".debug_line_str" => dwarf.debug_line_str = gimli::DebugLineStr::from(slice),
766 ".debug_str" => dwarf.debug_str = gimli::DebugStr::new(data, endian),
767 ".debug_str_offsets" => dwarf.debug_str_offsets = gimli::DebugStrOffsets::from(slice),
768 ".debug_str_sup" => {
769 let mut dwarf_sup: Dwarf<'data> = Default::default();
770 dwarf_sup.debug_str = gimli::DebugStr::from(slice);
771 dwarf.sup = Some(Arc::new(dwarf_sup));
772 }
773 ".debug_types" => dwarf.debug_types = gimli::DebugTypes::from(slice),
774
775 ".debug_loc" => info.debug_loc = gimli::DebugLoc::from(slice),
777 ".debug_loclists" => info.debug_loclists = gimli::DebugLocLists::from(slice),
778 ".debug_ranges" => info.debug_ranges = gimli::DebugRanges::new(data, endian),
779 ".debug_rnglists" => info.debug_rnglists = gimli::DebugRngLists::new(data, endian),
780
781 ".debug_cu_index" => info.debug_cu_index = gimli::DebugCuIndex::new(data, endian),
783 ".debug_tu_index" => info.debug_tu_index = gimli::DebugTuIndex::new(data, endian),
784
785 ".debug_aranges" | ".debug_pubnames" | ".debug_pubtypes" => return,
787 other => {
788 log::warn!("unknown debug section `{other}`");
789 return;
790 }
791 }
792
793 dwarf.ranges = gimli::RangeLists::new(info.debug_ranges, info.debug_rnglists);
794 dwarf.locations = gimli::LocationLists::new(info.debug_loc, info.debug_loclists);
795 }
796
797 fn declare_import(&mut self, module: &'data str, field: &'data str, ty: EntityType) {
810 let index = self.push_type(ty);
811 self.result.module.initializers.push(Initializer::Import {
812 name: module.to_owned(),
813 field: field.to_owned(),
814 index,
815 });
816 }
817
818 fn push_type(&mut self, ty: EntityType) -> EntityIndex {
819 match ty {
820 EntityType::Function(ty) => EntityIndex::Function({
821 let func_index = self
822 .result
823 .module
824 .push_function(ty.unwrap_module_type_index());
825 self.flag_func_escaped(func_index);
828 func_index
829 }),
830 EntityType::Table(ty) => EntityIndex::Table(self.result.module.tables.push(ty)),
831 EntityType::Memory(ty) => EntityIndex::Memory(self.result.module.memories.push(ty)),
832 EntityType::Global(ty) => EntityIndex::Global(self.result.module.globals.push(ty)),
833 EntityType::Tag(ty) => EntityIndex::Tag(self.result.module.tags.push(ty)),
834 }
835 }
836
837 fn flag_func_escaped(&mut self, func: FuncIndex) {
838 let ty = &mut self.result.module.functions[func];
839 if ty.is_escaping() {
841 return;
842 }
843 let index = self.result.module.num_escaped_funcs as u32;
844 ty.func_ref = FuncRefIndex::from_u32(index);
845 self.result.module.num_escaped_funcs += 1;
846 }
847
848 fn name_section(&mut self, names: NameSectionReader<'data>) -> WasmResult<()> {
850 for subsection in names {
851 match subsection? {
852 wasmparser::Name::Function(names) => {
853 for name in names {
854 let Naming { index, name } = name?;
855 if (index as usize) >= self.result.module.functions.len() {
858 continue;
859 }
860
861 let index = FuncIndex::from_u32(index);
866 self.result
867 .debuginfo
868 .name_section
869 .func_names
870 .insert(index, name);
871 }
872 }
873 wasmparser::Name::Module { name, .. } => {
874 self.result.module.name = Some(name.to_string());
875 if self.tunables.debug_native {
876 self.result.debuginfo.name_section.module_name = Some(name);
877 }
878 }
879 wasmparser::Name::Local(reader) => {
880 if !self.tunables.debug_native {
881 continue;
882 }
883 for f in reader {
884 let f = f?;
885 if (f.index as usize) >= self.result.module.functions.len() {
888 continue;
889 }
890 for name in f.names {
891 let Naming { index, name } = name?;
892
893 self.result
894 .debuginfo
895 .name_section
896 .locals_names
897 .entry(FuncIndex::from_u32(f.index))
898 .or_insert(HashMap::new())
899 .insert(index, name);
900 }
901 }
902 }
903 wasmparser::Name::Label(_)
904 | wasmparser::Name::Type(_)
905 | wasmparser::Name::Table(_)
906 | wasmparser::Name::Global(_)
907 | wasmparser::Name::Memory(_)
908 | wasmparser::Name::Element(_)
909 | wasmparser::Name::Data(_)
910 | wasmparser::Name::Tag(_)
911 | wasmparser::Name::Field(_)
912 | wasmparser::Name::Unknown { .. } => {}
913 }
914 }
915 Ok(())
916 }
917}
918
919impl TypeConvert for ModuleEnvironment<'_, '_> {
920 fn lookup_heap_type(&self, index: wasmparser::UnpackedIndex) -> WasmHeapType {
921 WasmparserTypeConverter::new(&self.types, |idx| {
922 self.result.module.types[idx].unwrap_module_type_index()
923 })
924 .lookup_heap_type(index)
925 }
926
927 fn lookup_type_index(&self, index: wasmparser::UnpackedIndex) -> EngineOrModuleTypeIndex {
928 WasmparserTypeConverter::new(&self.types, |idx| {
929 self.result.module.types[idx].unwrap_module_type_index()
930 })
931 .lookup_type_index(index)
932 }
933}
934
935impl ModuleTranslation<'_> {
936 pub fn try_static_init(&mut self, page_size: u64, max_image_size_always_allowed: u64) {
967 if !self.module.memory_initialization.is_segmented() {
970 return;
971 }
972
973 struct Memory {
977 data_size: u64,
978 min_addr: u64,
979 max_addr: u64,
980 segments: Vec<(usize, StaticMemoryInitializer)>,
984 }
985 let mut info = PrimaryMap::with_capacity(self.module.memories.len());
986 for _ in 0..self.module.memories.len() {
987 info.push(Memory {
988 data_size: 0,
989 min_addr: u64::MAX,
990 max_addr: 0,
991 segments: Vec::new(),
992 });
993 }
994
995 struct InitMemoryAtCompileTime<'a> {
996 module: &'a Module,
997 info: &'a mut PrimaryMap<MemoryIndex, Memory>,
998 idx: usize,
999 }
1000 impl InitMemory for InitMemoryAtCompileTime<'_> {
1001 fn memory_size_in_bytes(
1002 &mut self,
1003 memory_index: MemoryIndex,
1004 ) -> Result<u64, SizeOverflow> {
1005 self.module.memories[memory_index].minimum_byte_size()
1006 }
1007
1008 fn eval_offset(&mut self, memory_index: MemoryIndex, expr: &ConstExpr) -> Option<u64> {
1009 match (expr.ops(), self.module.memories[memory_index].idx_type) {
1010 (&[ConstOp::I32Const(offset)], IndexType::I32) => {
1011 Some(offset.cast_unsigned().into())
1012 }
1013 (&[ConstOp::I64Const(offset)], IndexType::I64) => Some(offset.cast_unsigned()),
1014 _ => None,
1015 }
1016 }
1017
1018 fn write(&mut self, memory: MemoryIndex, init: &StaticMemoryInitializer) -> bool {
1019 if self.module.defined_memory_index(memory).is_none() {
1024 return false;
1025 };
1026 let info = &mut self.info[memory];
1027 let data_len = u64::from(init.data.end - init.data.start);
1028 if data_len > 0 {
1029 info.data_size += data_len;
1030 info.min_addr = info.min_addr.min(init.offset);
1031 info.max_addr = info.max_addr.max(init.offset + data_len);
1032 info.segments.push((self.idx, init.clone()));
1033 }
1034 self.idx += 1;
1035 true
1036 }
1037 }
1038 let ok = self
1039 .module
1040 .memory_initialization
1041 .init_memory(&mut InitMemoryAtCompileTime {
1042 idx: 0,
1043 module: &self.module,
1044 info: &mut info,
1045 });
1046 if !ok {
1047 return;
1048 }
1049
1050 for (i, info) in info.iter().filter(|(_, info)| info.data_size > 0) {
1053 let image_size = info.max_addr - info.min_addr;
1054
1055 if self.module.memories[i].page_size() < page_size {
1063 return;
1064 }
1065
1066 if image_size < info.data_size.saturating_mul(2) {
1073 continue;
1074 }
1075
1076 if image_size < max_image_size_always_allowed {
1080 continue;
1081 }
1082
1083 return;
1087 }
1088
1089 let data = mem::replace(&mut self.data, Vec::new());
1093 let mut map = PrimaryMap::with_capacity(info.len());
1094 let mut module_data_size = 0u32;
1095 for (memory, info) in info.iter() {
1096 let extent = if info.segments.len() > 0 {
1099 (info.max_addr - info.min_addr) as usize
1100 } else {
1101 0
1102 };
1103 let mut image = Vec::with_capacity(extent);
1104 for (idx, init) in info.segments.iter() {
1105 let data = &data[*idx];
1106 assert_eq!(data.len(), init.data.len());
1107 let offset = usize::try_from(init.offset - info.min_addr).unwrap();
1108 if image.len() < offset {
1109 image.resize(offset, 0u8);
1110 image.extend_from_slice(data);
1111 } else {
1112 image.splice(
1113 offset..(offset + data.len()).min(image.len()),
1114 data.iter().copied(),
1115 );
1116 }
1117 }
1118 assert_eq!(image.len(), extent);
1119 assert_eq!(image.capacity(), extent);
1120 let mut offset = if info.segments.len() > 0 {
1121 info.min_addr
1122 } else {
1123 0
1124 };
1125
1126 if let Some(i) = image.iter().rposition(|i| *i != 0) {
1130 image.truncate(i + 1);
1131 }
1132
1133 if let Some(i) = image.iter().position(|i| *i != 0) {
1135 offset += i as u64;
1136 image.drain(..i);
1137 }
1138 let mut len = u64::try_from(image.len()).unwrap();
1139
1140 if offset % page_size != 0 {
1145 let zero_padding = offset % page_size;
1146 self.data.push(vec![0; zero_padding as usize].into());
1147 offset -= zero_padding;
1148 len += zero_padding;
1149 }
1150 self.data.push(image.into());
1151 if len % page_size != 0 {
1152 let zero_padding = page_size - (len % page_size);
1153 self.data.push(vec![0; zero_padding as usize].into());
1154 len += zero_padding;
1155 }
1156
1157 assert!(offset % page_size == 0);
1159 assert!(len % page_size == 0);
1160
1161 let len = u32::try_from(len).unwrap();
1169 let init = if len > 0 {
1170 Some(StaticMemoryInitializer {
1171 offset,
1172 data: module_data_size..module_data_size + len,
1173 })
1174 } else {
1175 None
1176 };
1177 let idx = map.push(init);
1178 assert_eq!(idx, memory);
1179 module_data_size += len;
1180 }
1181 self.data_align = Some(page_size);
1182 self.module.memory_initialization = MemoryInitialization::Static { map };
1183 }
1184
1185 pub fn try_func_table_init(&mut self) {
1190 const MAX_FUNC_TABLE_SIZE: u64 = 1024 * 1024;
1194
1195 for ((_, init), (_, table)) in self
1198 .module
1199 .table_initialization
1200 .initial_values
1201 .iter_mut()
1202 .zip(
1203 self.module
1204 .tables
1205 .iter()
1206 .skip(self.module.num_imported_tables),
1207 )
1208 {
1209 let table_size = table.limits.min;
1210 if table_size > MAX_FUNC_TABLE_SIZE {
1211 continue;
1212 }
1213 if let TableInitialValue::Expr(expr) = init {
1214 if let [ConstOp::RefFunc(f)] = expr.ops() {
1215 *init = TableInitialValue::Null {
1216 precomputed: vec![*f; table_size as usize],
1217 };
1218 }
1219 }
1220 }
1221
1222 let mut segments = mem::take(&mut self.module.table_initialization.segments)
1223 .into_iter()
1224 .peekable();
1225
1226 while let Some(segment) = segments.peek() {
1238 let defined_index = match self.module.defined_table_index(segment.table_index) {
1239 Some(index) => index,
1240 None => break,
1244 };
1245
1246 let offset = match segment.offset.ops() {
1250 &[ConstOp::I32Const(offset)] => u64::from(offset.cast_unsigned()),
1251 &[ConstOp::I64Const(offset)] => offset.cast_unsigned(),
1252 _ => break,
1253 };
1254
1255 let top = match offset.checked_add(segment.elements.len()) {
1259 Some(top) => top,
1260 None => break,
1261 };
1262 let table_size = self.module.tables[segment.table_index].limits.min;
1263 if top > table_size || top > MAX_FUNC_TABLE_SIZE {
1264 break;
1265 }
1266
1267 match self.module.tables[segment.table_index]
1268 .ref_type
1269 .heap_type
1270 .top()
1271 {
1272 WasmHeapTopType::Func => {}
1273 WasmHeapTopType::Any
1279 | WasmHeapTopType::Extern
1280 | WasmHeapTopType::Cont
1281 | WasmHeapTopType::Exn => break,
1282 }
1283
1284 let function_elements = match &segment.elements {
1287 TableSegmentElements::Functions(indices) => indices,
1288 TableSegmentElements::Expressions(_) => break,
1289 };
1290
1291 let precomputed =
1292 match &mut self.module.table_initialization.initial_values[defined_index] {
1293 TableInitialValue::Null { precomputed } => precomputed,
1294
1295 TableInitialValue::Expr(_) => break,
1302 };
1303
1304 if precomputed.len() < top as usize {
1310 precomputed.resize(top as usize, FuncIndex::reserved_value());
1311 }
1312 let dst = &mut precomputed[offset as usize..top as usize];
1313 dst.copy_from_slice(&function_elements);
1314
1315 let _ = segments.next();
1317 }
1318 self.module.table_initialization.segments = segments.collect();
1319 }
1320}