1use std::collections::{HashMap, HashSet};
2use std::path::Path;
3
4use eyre::{Context as _, ContextCompat as _};
5use wasm_encoder::{
6 CodeSection, DataCountSection, DataSection, ElementSection, EntityType, ExportKind,
7 ExportSection, Function, FunctionSection, GlobalSection, ImportSection, MemorySection, Module,
8 TableSection, TagSection, TypeSection,
9};
10use wasmparser::{ExternalKind, Payload, TypeRef};
11
12use crate::unique_name::UniqueName;
13use crate::wasm_stream::translator::{self, Rebind};
14
15pub struct MergeInput<'a> {
17 pub alias: String,
19 pub path: &'a Path,
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24#[repr(usize)]
25enum IndexKind {
26 Func,
27 Table,
28 Memory,
29 Global,
30 Tag,
31}
32
33const INDEX_KIND_COUNT: usize = 5;
34const INDEX_KINDS: [IndexKind; INDEX_KIND_COUNT] = [
35 IndexKind::Func,
36 IndexKind::Table,
37 IndexKind::Memory,
38 IndexKind::Global,
39 IndexKind::Tag,
40];
41
42impl IndexKind {
43 fn idx(self) -> usize {
44 self as usize
45 }
46
47 fn from_type_ref(ty: TypeRef) -> Self {
48 match ty {
49 TypeRef::Func(_) | TypeRef::FuncExact(_) => Self::Func,
50 TypeRef::Table(_) => Self::Table,
51 TypeRef::Memory(_) => Self::Memory,
52 TypeRef::Global(_) => Self::Global,
53 TypeRef::Tag(_) => Self::Tag,
54 }
55 }
56
57 fn from_external(kind: ExternalKind) -> Self {
58 match kind {
59 ExternalKind::Func | ExternalKind::FuncExact => Self::Func,
60 ExternalKind::Table => Self::Table,
61 ExternalKind::Memory => Self::Memory,
62 ExternalKind::Global => Self::Global,
63 ExternalKind::Tag => Self::Tag,
64 }
65 }
66
67 fn export_kind(self) -> ExportKind {
68 match self {
69 Self::Func => ExportKind::Func,
70 Self::Table => ExportKind::Table,
71 Self::Memory => ExportKind::Memory,
72 Self::Global => ExportKind::Global,
73 Self::Tag => ExportKind::Tag,
74 }
75 }
76}
77
78#[derive(Clone, Copy, Debug)]
79struct ExportRef {
80 module: usize,
81 kind: IndexKind,
82 index: u32,
83}
84
85#[derive(Clone, Debug)]
86struct ExportInfo {
87 name: String,
88 kind: ExternalKind,
89 index: u32,
90}
91
92impl ExportInfo {
93 fn index_kind(&self) -> IndexKind {
94 IndexKind::from_external(self.kind)
95 }
96}
97
98#[derive(Clone, Debug)]
99struct ImportInfo {
100 module: String,
101 name: String,
102 ty: TypeRef,
103 kind: IndexKind,
104 old_index: u32,
105 resolved: Option<ExportRef>,
106 final_index: Option<u32>,
107}
108
109#[derive(Default, Clone, Copy, Debug)]
110struct Counts {
111 types: u32,
112 func_imports: u32,
113 table_imports: u32,
114 memory_imports: u32,
115 global_imports: u32,
116 tag_imports: u32,
117 funcs: u32,
118 tables: u32,
119 memories: u32,
120 globals: u32,
121 tags: u32,
122 elems: u32,
123 data: u32,
124}
125
126impl Counts {
127 fn first_defined_offsets(self) -> Offsets {
128 Offsets {
129 funcs: self.imported(IndexKind::Func),
130 tables: self.imported(IndexKind::Table),
131 memories: self.imported(IndexKind::Memory),
132 globals: self.imported(IndexKind::Global),
133 tags: self.imported(IndexKind::Tag),
134 ..Offsets::default()
135 }
136 }
137
138 fn imported(self, kind: IndexKind) -> u32 {
139 match kind {
140 IndexKind::Func => self.func_imports,
141 IndexKind::Table => self.table_imports,
142 IndexKind::Memory => self.memory_imports,
143 IndexKind::Global => self.global_imports,
144 IndexKind::Tag => self.tag_imports,
145 }
146 }
147
148 fn defined(self, kind: IndexKind) -> u32 {
149 match kind {
150 IndexKind::Func => self.funcs,
151 IndexKind::Table => self.tables,
152 IndexKind::Memory => self.memories,
153 IndexKind::Global => self.globals,
154 IndexKind::Tag => self.tags,
155 }
156 }
157
158 fn next_import_index(&mut self, kind: IndexKind) -> u32 {
159 let counter = match kind {
160 IndexKind::Func => &mut self.func_imports,
161 IndexKind::Table => &mut self.table_imports,
162 IndexKind::Memory => &mut self.memory_imports,
163 IndexKind::Global => &mut self.global_imports,
164 IndexKind::Tag => &mut self.tag_imports,
165 };
166 let idx = *counter;
167 *counter += 1;
168 idx
169 }
170}
171
172#[derive(Default, Clone, Copy, Debug)]
173struct Offsets {
174 types: u32,
175 funcs: u32,
176 tables: u32,
177 memories: u32,
178 globals: u32,
179 tags: u32,
180 elems: u32,
181 data: u32,
182}
183
184impl Offsets {
185 fn get(self, kind: IndexKind) -> u32 {
186 match kind {
187 IndexKind::Func => self.funcs,
188 IndexKind::Table => self.tables,
189 IndexKind::Memory => self.memories,
190 IndexKind::Global => self.globals,
191 IndexKind::Tag => self.tags,
192 }
193 }
194
195 fn assign_defined_indices(&mut self, module: &mut ParsedModule) {
196 module.offsets.funcs = self.funcs;
197 self.funcs += module.counts.funcs;
198 module.offsets.tables = self.tables;
199 self.tables += module.counts.tables;
200 module.offsets.memories = self.memories;
201 self.memories += module.counts.memories;
202 module.offsets.globals = self.globals;
203 self.globals += module.counts.globals;
204 module.offsets.tags = self.tags;
205 self.tags += module.counts.tags;
206 module.offsets.elems = self.elems;
207 self.elems += module.counts.elems;
208 module.offsets.data = self.data;
209 self.data += module.counts.data;
210 }
211}
212
213#[derive(Debug)]
214struct ParsedModule {
215 alias: String,
216 bytes: Vec<u8>,
217 imports: Vec<ImportInfo>,
218 exports: Vec<ExportInfo>,
219 counts: Counts,
220 offsets: Offsets,
221 has_data_count: bool,
222}
223
224type AliasMap = HashMap<String, usize>;
225type ExportKey = (String, String, IndexKind);
226type ExportMap = HashMap<ExportKey, ExportRef>;
227
228#[derive(Clone, Copy)]
229struct ResolvedIndex {
230 value: u32,
231 resolving: bool,
232}
233
234impl ResolvedIndex {
235 const UNRESOLVED: Self = Self {
236 value: u32::MAX,
237 resolving: false,
238 };
239
240 fn is_resolved(self) -> bool {
241 self.value != u32::MAX
242 }
243}
244
245struct IndexMaps {
246 values: [Vec<Vec<ResolvedIndex>>; INDEX_KIND_COUNT],
247}
248
249impl IndexMaps {
250 fn new(modules: &[ParsedModule]) -> Self {
251 Self {
252 values: INDEX_KINDS.map(|kind| allocate_maps(modules, kind)),
253 }
254 }
255
256 fn get(&self, kind: IndexKind) -> &[Vec<ResolvedIndex>] {
257 &self.values[kind.idx()]
258 }
259
260 fn get_mut(&mut self, kind: IndexKind) -> &mut [Vec<ResolvedIndex>] {
261 &mut self.values[kind.idx()]
262 }
263
264 fn value(&self, kind: IndexKind, module: usize, index: u32) -> u32 {
265 self.get(kind)[module][index as usize].value
266 }
267}
268
269struct MergeRebinder<'a> {
270 module: usize,
271 modules: &'a [ParsedModule],
272 maps: &'a IndexMaps,
273}
274
275struct EmitContext<'a> {
276 modules: &'a [ParsedModule],
277 maps: &'a IndexMaps,
278}
279
280impl<'a> EmitContext<'a> {
281 fn rebinder(&self, module: usize) -> MergeRebinder<'a> {
282 MergeRebinder {
283 module,
284 modules: self.modules,
285 maps: self.maps,
286 }
287 }
288}
289
290impl Rebind for MergeRebinder<'_> {
291 fn function(&self, index: u32) -> u32 {
292 self.maps.value(IndexKind::Func, self.module, index)
293 }
294
295 fn global(&self, index: u32) -> u32 {
296 self.maps.value(IndexKind::Global, self.module, index)
297 }
298
299 fn memory(&self, index: u32) -> u32 {
300 self.maps.value(IndexKind::Memory, self.module, index)
301 }
302
303 fn table(&self, index: u32) -> u32 {
304 self.maps.value(IndexKind::Table, self.module, index)
305 }
306
307 fn ty(&self, index: u32) -> u32 {
308 self.modules[self.module].offsets.types + index
309 }
310
311 fn data(&self, index: u32) -> u32 {
312 self.modules[self.module].offsets.data + index
313 }
314
315 fn elem(&self, index: u32) -> u32 {
316 self.modules[self.module].offsets.elems + index
317 }
318
319 fn tag(&self, index: u32) -> u32 {
320 self.maps.value(IndexKind::Tag, self.module, index)
321 }
322}
323
324pub fn merge_modules(
326 inputs: &[MergeInput<'_>],
327 output: impl AsRef<Path>,
328 dwarf: bool,
329) -> eyre::Result<()> {
330 let mut modules = inputs
331 .iter()
332 .map(parse_module)
333 .collect::<eyre::Result<Vec<_>>>()?;
334
335 resolve_imports(&mut modules)?;
336 deduplicate_unresolved_function_imports(&mut modules);
337 assign_offsets(&mut modules);
338 let maps = build_index_maps(&modules)?;
339 let bytes = emit_merged_module(&modules, &maps, dwarf)?;
340 std::fs::write(output, bytes).wrap_err("Failed to write merged Wasm")?;
341 Ok(())
342}
343
344fn parse_module(input: &MergeInput<'_>) -> eyre::Result<ParsedModule> {
345 let bytes = std::fs::read(input.path)
346 .wrap_err_with(|| format!("Failed to read Wasm module {}", input.path.display()))?;
347 let mut counts = Counts::default();
348 let mut imports = Vec::new();
349 let mut exports = Vec::new();
350 let mut has_data_count = false;
351
352 for payload in parse_payloads(&bytes) {
353 match payload.wrap_err_with(|| format!("Failed to parse {}", input.path.display()))? {
354 Payload::TypeSection(section) => {
355 for ty in section {
356 counts.types += ty?.into_types().count() as u32;
357 }
358 }
359 Payload::ImportSection(section) => {
360 for group in section {
361 for item in group?.into_iter() {
362 let (_, import) = item?;
363 let kind = IndexKind::from_type_ref(import.ty);
364 let old_index = counts.next_import_index(kind);
365 imports.push(ImportInfo {
366 module: import.module.to_string(),
367 name: import.name.to_string(),
368 ty: import.ty,
369 kind,
370 old_index,
371 resolved: None,
372 final_index: None,
373 });
374 }
375 }
376 }
377 Payload::FunctionSection(section) => counts.funcs = section.count(),
378 Payload::TableSection(section) => counts.tables = section.count(),
379 Payload::MemorySection(section) => counts.memories = section.count(),
380 Payload::GlobalSection(section) => counts.globals = section.count(),
381 Payload::TagSection(section) => counts.tags = section.count(),
382 Payload::ElementSection(section) => counts.elems = section.count(),
383 Payload::DataSection(section) => counts.data = section.count(),
384 Payload::DataCountSection { count, .. } => {
385 counts.data = counts.data.max(count);
386 has_data_count = true;
387 }
388 Payload::ExportSection(section) => {
389 for export in section {
390 let export = export?;
391 exports.push(ExportInfo {
392 name: export.name.to_string(),
393 kind: export.kind,
394 index: export.index,
395 });
396 }
397 }
398 Payload::StartSection { .. } => {
399 eyre::bail!(
400 "Prepared module `{}` still has a start section; expected StartsPreStreamPass output",
401 input.alias
402 );
403 }
404 _ => {}
405 }
406 }
407
408 Ok(ParsedModule {
409 alias: input.alias.clone(),
410 bytes,
411 imports,
412 exports,
413 counts,
414 offsets: Offsets::default(),
415 has_data_count,
416 })
417}
418
419fn parse_payloads(bytes: &[u8]) -> impl Iterator<Item = wasmparser::Result<Payload<'_>>> {
420 wasmparser::Parser::new(0).parse_all(bytes)
421}
422
423fn resolve_imports(modules: &mut [ParsedModule]) -> eyre::Result<()> {
424 let alias_to_module = build_alias_map(modules);
425 let exports = build_export_map(modules);
426
427 for module_idx in 0..modules.len() {
428 let importing_alias = modules[module_idx].alias.clone();
429 for import in &mut modules[module_idx].imports {
430 resolve_import(
431 &importing_alias,
432 module_idx,
433 import,
434 &alias_to_module,
435 &exports,
436 )?;
437 }
438 }
439
440 Ok(())
441}
442
443fn deduplicate_unresolved_function_imports(modules: &mut [ParsedModule]) {
444 for (module_idx, module) in modules.iter_mut().enumerate() {
445 let mut first_imports = HashMap::new();
446
447 for import in &mut module.imports {
448 if import.resolved.is_some() {
449 continue;
450 }
451
452 let type_key = match import.ty {
453 TypeRef::Func(type_idx) => (false, type_idx),
454 TypeRef::FuncExact(type_idx) => (true, type_idx),
455 _ => continue,
456 };
457 let key = (import.module.clone(), import.name.clone(), type_key);
458
459 if let Some(&first_old_index) = first_imports.get(&key) {
460 import.resolved = Some(ExportRef {
461 module: module_idx,
462 kind: IndexKind::Func,
463 index: first_old_index,
464 });
465 } else {
466 first_imports.insert(key, import.old_index);
467 }
468 }
469 }
470}
471
472fn build_alias_map(modules: &[ParsedModule]) -> AliasMap {
473 modules
474 .iter()
475 .enumerate()
476 .map(|(idx, module)| (module.alias.clone(), idx))
477 .collect()
478}
479
480fn build_export_map(modules: &[ParsedModule]) -> ExportMap {
481 let mut exports = ExportMap::new();
482 for (module_idx, module) in modules.iter().enumerate() {
483 for export in &module.exports {
484 let kind = export.index_kind();
485 let export_ref = ExportRef {
486 module: module_idx,
487 kind,
488 index: export.index,
489 };
490 for export_name in alias_export_names(&module.alias, &export.name) {
491 exports
492 .entry((module.alias.clone(), export_name, kind))
493 .or_insert(export_ref);
494 }
495 }
496 }
497 exports
498}
499
500fn resolve_import(
501 importing_alias: &str,
502 module_idx: usize,
503 import: &mut ImportInfo,
504 alias_to_module: &AliasMap,
505 exports: &ExportMap,
506) -> eyre::Result<()> {
507 let Some(&target_module_idx) = alias_to_module.get(&import.module) else {
508 return Ok(());
509 };
510
511 let key = (import.module.clone(), import.name.clone(), import.kind);
512 if let Some(export) = exports.get(&key).copied() {
513 import.resolved = Some(export);
514 } else if target_module_idx == module_idx && importing_alias == UniqueName::WASIP1_ABI_MODULE {
515 import.module = "__wasip1_vfs-host".to_string();
516 import.name = format!("__wasip1_vfs___self_{}", import.name);
517 } else {
518 eyre::bail!(
519 "Module `{}` imports `{}::{}` from merge alias `{}`, but no matching export exists",
520 importing_alias,
521 import.module,
522 import.name,
523 import.module
524 );
525 }
526
527 Ok(())
528}
529
530fn assign_offsets(modules: &mut [ParsedModule]) {
531 let mut type_offset = 0;
532 for module in modules.iter_mut() {
533 module.offsets.types = type_offset;
534 type_offset += module.counts.types;
535 }
536
537 let mut unresolved = Counts::default();
538 for module in modules.iter_mut() {
539 for import in &mut module.imports {
540 if import.resolved.is_some() {
541 continue;
542 }
543 let final_index = unresolved.next_import_index(import.kind);
544 import.final_index = Some(final_index);
545 }
546 }
547
548 let mut offsets = unresolved.first_defined_offsets();
549
550 for module in modules.iter_mut() {
551 offsets.assign_defined_indices(module);
552 }
553}
554
555fn build_index_maps(modules: &[ParsedModule]) -> eyre::Result<IndexMaps> {
556 let mut maps = IndexMaps::new(modules);
557
558 for module_idx in 0..modules.len() {
559 for kind in INDEX_KINDS {
560 fill_direct_map(modules, &mut maps, module_idx, kind);
561 }
562 }
563
564 for module_idx in 0..modules.len() {
565 for kind in INDEX_KINDS {
566 resolve_all_kind(modules, &mut maps, module_idx, kind)?;
567 }
568 }
569
570 Ok(maps)
571}
572
573fn allocate_maps(modules: &[ParsedModule], kind: IndexKind) -> Vec<Vec<ResolvedIndex>> {
574 modules
575 .iter()
576 .map(|module| {
577 let len = module.counts.imported(kind) + module.counts.defined(kind);
578 vec![ResolvedIndex::UNRESOLVED; len as usize]
579 })
580 .collect()
581}
582
583fn fill_direct_map(
584 modules: &[ParsedModule],
585 maps: &mut IndexMaps,
586 module_idx: usize,
587 kind: IndexKind,
588) {
589 let module = &modules[module_idx];
590 for import in module.imports.iter().filter(|import| import.kind == kind) {
591 if let Some(final_index) = import.final_index {
592 maps.get_mut(kind)[module_idx][import.old_index as usize].value = final_index;
593 }
594 }
595
596 let import_count = module.counts.imported(kind);
597 let def_offset = module.offsets.get(kind);
598 for local_idx in 0..module.counts.defined(kind) {
599 maps.get_mut(kind)[module_idx][(import_count + local_idx) as usize].value =
600 def_offset + local_idx;
601 }
602}
603
604fn resolve_all_kind(
605 modules: &[ParsedModule],
606 maps: &mut IndexMaps,
607 module_idx: usize,
608 kind: IndexKind,
609) -> eyre::Result<()> {
610 let len = maps.get(kind)[module_idx].len();
611 for index in 0..len {
612 resolve_index(modules, maps, module_idx, kind, index as u32)?;
613 }
614 Ok(())
615}
616
617fn resolve_index(
618 modules: &[ParsedModule],
619 maps: &mut IndexMaps,
620 module_idx: usize,
621 kind: IndexKind,
622 index: u32,
623) -> eyre::Result<u32> {
624 let slot = &maps.get(kind)[module_idx][index as usize];
625 if slot.is_resolved() {
626 return Ok(slot.value);
627 }
628 if slot.resolving {
629 eyre::bail!(
630 "Cyclic merge import resolution for module `{}` index {:?} {}",
631 modules[module_idx].alias,
632 kind,
633 index
634 );
635 }
636 maps.get_mut(kind)[module_idx][index as usize].resolving = true;
637
638 let import = modules[module_idx]
639 .imports
640 .iter()
641 .find(|import| import.kind == kind && import.old_index == index)
642 .with_context(|| {
643 format!(
644 "Missing merge import mapping for module `{}` index {:?} {}",
645 modules[module_idx].alias, kind, index
646 )
647 })?;
648 let resolved = import
649 .resolved
650 .with_context(|| format!("Unresolved import `{}` has no final index", import.name))?;
651 let value = resolve_index(
652 modules,
653 maps,
654 resolved.module,
655 resolved.kind,
656 resolved.index,
657 )?;
658 let slot = &mut maps.get_mut(kind)[module_idx][index as usize];
659 slot.value = value;
660 slot.resolving = false;
661 Ok(value)
662}
663
664fn emit_merged_module(
665 modules: &[ParsedModule],
666 maps: &IndexMaps,
667 dwarf: bool,
668) -> eyre::Result<Vec<u8>> {
669 let ctx = EmitContext { modules, maps };
670 let mut module = Module::new();
671 emit_type_section(&ctx, &mut module)?;
672 emit_import_section(&ctx, &mut module)?;
673 emit_function_section(&ctx, &mut module)?;
674 emit_table_section(&ctx, &mut module)?;
675 emit_memory_section(&ctx, &mut module)?;
676 emit_tag_section(&ctx, &mut module)?;
677 emit_global_section(&ctx, &mut module)?;
678 emit_export_section(&ctx, &mut module)?;
679 emit_element_section(&ctx, &mut module)?;
680
681 let has_data_count = ctx.modules.iter().any(|m| m.has_data_count);
682 let total_data = ctx.modules.iter().map(|m| m.counts.data).sum::<u32>();
683 if has_data_count {
684 module.section(&DataCountSection { count: total_data });
685 }
686
687 emit_code_section(&ctx, &mut module)?;
688 emit_data_section(&ctx, &mut module)?;
689 emit_custom_sections(&ctx, dwarf, &mut module)?;
690
691 Ok(module.finish())
692}
693
694fn emit_type_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
695 let mut section = TypeSection::new();
696 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
697 let rebinder = ctx.rebinder(module_idx);
698 for payload in parse_payloads(&parsed.bytes) {
699 if let Payload::TypeSection(types) = payload? {
700 for ty in types {
701 let ty = ty?;
702 if ty.is_explicit_rec_group() {
703 let rec_types = ty
704 .into_types()
705 .map(|sub_ty| translator::translate_sub_type(&sub_ty, &rebinder))
706 .collect::<Vec<_>>();
707 section.ty().rec(rec_types);
708 } else {
709 for sub_ty in ty.into_types() {
710 section
711 .ty()
712 .subtype(&translator::translate_sub_type(&sub_ty, &rebinder));
713 }
714 }
715 }
716 }
717 }
718 }
719 if !section.is_empty() {
720 module.section(§ion);
721 }
722 Ok(())
723}
724
725fn emit_import_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
726 let mut section = ImportSection::new();
727 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
728 let rebinder = ctx.rebinder(module_idx);
729 for import in parsed
730 .imports
731 .iter()
732 .filter(|import| import.resolved.is_none())
733 {
734 section.import(
735 &import.module,
736 &import.name,
737 translate_type_ref(import.ty, &rebinder),
738 );
739 }
740 }
741 if !section.is_empty() {
742 module.section(§ion);
743 }
744 Ok(())
745}
746
747fn emit_function_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
748 let mut section = FunctionSection::new();
749 for parsed in ctx.modules {
750 for payload in parse_payloads(&parsed.bytes) {
751 if let Payload::FunctionSection(functions) = payload? {
752 for ty in functions {
753 section.function(parsed.offsets.types + ty?);
754 }
755 }
756 }
757 }
758 if !section.is_empty() {
759 module.section(§ion);
760 }
761 Ok(())
762}
763
764fn emit_table_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
765 let mut section = TableSection::new();
766 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
767 let rebinder = ctx.rebinder(module_idx);
768 for payload in parse_payloads(&parsed.bytes) {
769 if let Payload::TableSection(tables) = payload? {
770 for table in tables {
771 section.table(translator::translate_table_type(table?.ty, &rebinder));
772 }
773 }
774 }
775 }
776 if !section.is_empty() {
777 module.section(§ion);
778 }
779 Ok(())
780}
781
782fn emit_memory_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
783 let mut section = MemorySection::new();
784 for parsed in ctx.modules {
785 for payload in parse_payloads(&parsed.bytes) {
786 if let Payload::MemorySection(memories) = payload? {
787 for memory in memories {
788 section.memory(translator::translate_memory_type(memory?));
789 }
790 }
791 }
792 }
793 if !section.is_empty() {
794 module.section(§ion);
795 }
796 Ok(())
797}
798
799fn emit_tag_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
800 let mut section = TagSection::new();
801 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
802 let rebinder = ctx.rebinder(module_idx);
803 for payload in parse_payloads(&parsed.bytes) {
804 if let Payload::TagSection(tags) = payload? {
805 for tag in tags {
806 let tag = translator::translate_tag_type(tag?);
807 section.tag(wasm_encoder::TagType {
808 kind: tag.kind,
809 func_type_idx: rebinder.ty(tag.func_type_idx),
810 });
811 }
812 }
813 }
814 }
815 if !section.is_empty() {
816 module.section(§ion);
817 }
818 Ok(())
819}
820
821fn emit_global_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
822 let mut section = GlobalSection::new();
823 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
824 let rebinder = ctx.rebinder(module_idx);
825 for payload in parse_payloads(&parsed.bytes) {
826 if let Payload::GlobalSection(globals) = payload? {
827 for global in globals {
828 let global = global?;
829 let init = translate_const_expr_extended(&global.init_expr, &rebinder)?;
830 section.global(
831 translator::translate_global_type(global.ty, &rebinder),
832 &init,
833 );
834 }
835 }
836 }
837 }
838 if !section.is_empty() {
839 module.section(§ion);
840 }
841 Ok(())
842}
843
844fn emit_export_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
845 let mut section = ExportSection::new();
846 let mut used_names = HashSet::new();
847 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
848 let rebinder = ctx.rebinder(module_idx);
849 for export in &parsed.exports {
850 let final_index = rebind_external_index(export.kind, export.index, &rebinder);
851 let export_name = unique_export_name(&mut used_names, &parsed.alias, &export.name);
852 section.export(&export_name, export.index_kind().export_kind(), final_index);
853 }
854 }
855 if !section.is_empty() {
856 module.section(§ion);
857 }
858 Ok(())
859}
860
861fn emit_element_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
862 let mut section = ElementSection::new();
863 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
864 let rebinder = ctx.rebinder(module_idx);
865 for payload in parse_payloads(&parsed.bytes) {
866 if let Payload::ElementSection(elements) = payload? {
867 for elem in elements {
868 let elem = elem?;
869 let elements = translate_elements(elem.items, &rebinder)?;
870 match elem.kind {
871 wasmparser::ElementKind::Passive => {
872 section.passive(elements);
873 }
874 wasmparser::ElementKind::Active {
875 table_index,
876 offset_expr,
877 } => {
878 let table = Some(rebinder.table(table_index.unwrap_or(0)));
879 let offset = translate_const_expr_extended(&offset_expr, &rebinder)?;
880 section.active(table, &offset, elements);
881 }
882 wasmparser::ElementKind::Declared => {
883 section.declared(elements);
884 }
885 }
886 }
887 }
888 }
889 }
890 if !section.is_empty() {
891 module.section(§ion);
892 }
893 Ok(())
894}
895
896fn emit_code_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
897 let mut section = CodeSection::new();
898 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
899 let rebinder = ctx.rebinder(module_idx);
900 for payload in parse_payloads(&parsed.bytes) {
901 if let Payload::CodeSectionEntry(body) = payload? {
902 let mut locals = Vec::new();
903 for local in body.get_locals_reader()? {
904 let local = local?;
905 locals.push((local.0, translator::translate_val_type(local.1, &rebinder)));
906 }
907 let mut func = Function::new(locals);
908 for op in body.get_operators_reader()? {
909 let op = op?;
910 func.instruction(&translator::translate(&op, &rebinder));
911 }
912 section.function(&func);
913 }
914 }
915 }
916 if !section.is_empty() {
917 module.section(§ion);
918 }
919 Ok(())
920}
921
922fn emit_data_section(ctx: &EmitContext<'_>, module: &mut Module) -> eyre::Result<()> {
923 let mut section = DataSection::new();
924 for (module_idx, parsed) in ctx.modules.iter().enumerate() {
925 let rebinder = ctx.rebinder(module_idx);
926 for payload in parse_payloads(&parsed.bytes) {
927 if let Payload::DataSection(data_section) = payload? {
928 for data in data_section {
929 let data = data?;
930 match data.kind {
931 wasmparser::DataKind::Passive => {
932 section.passive(data.data.iter().copied());
933 }
934 wasmparser::DataKind::Active {
935 memory_index,
936 offset_expr,
937 } => {
938 let offset = translate_const_expr_extended(&offset_expr, &rebinder)?;
939 section.active(
940 rebinder.memory(memory_index),
941 &offset,
942 data.data.iter().copied(),
943 );
944 }
945 }
946 }
947 }
948 }
949 }
950 if !section.is_empty() {
951 module.section(§ion);
952 }
953 Ok(())
954}
955
956fn emit_custom_sections(
957 ctx: &EmitContext<'_>,
958 dwarf: bool,
959 module: &mut Module,
960) -> eyre::Result<()> {
961 for parsed in ctx.modules {
962 for payload in parse_payloads(&parsed.bytes) {
963 if let Payload::CustomSection(custom) = payload? {
964 if !dwarf && (custom.name() == "name" || custom.name().starts_with(".debug_")) {
965 continue;
966 }
967 module.section(&wasm_encoder::CustomSection {
968 name: custom.name().into(),
969 data: std::borrow::Cow::Borrowed(custom.data()),
970 });
971 }
972 }
973 }
974 Ok(())
975}
976
977fn translate_elements<'a>(
978 items: wasmparser::ElementItems<'a>,
979 rebinder: &impl Rebind,
980) -> eyre::Result<wasm_encoder::Elements<'a>> {
981 match items {
982 wasmparser::ElementItems::Functions(functions) => {
983 let funcs = functions
984 .into_iter()
985 .map(|idx| Ok(rebinder.function(idx?)))
986 .collect::<eyre::Result<Vec<_>>>()?;
987 Ok(wasm_encoder::Elements::Functions(std::borrow::Cow::Owned(
988 funcs,
989 )))
990 }
991 wasmparser::ElementItems::Expressions(ty, expressions) => {
992 let ty = translator::translate_ref_type(ty, rebinder);
993 let expressions = expressions
994 .into_iter()
995 .map(|expr| translate_const_expr_extended(&expr?, rebinder))
996 .collect::<eyre::Result<Vec<_>>>()?;
997 Ok(wasm_encoder::Elements::Expressions(
998 ty,
999 std::borrow::Cow::Owned(expressions),
1000 ))
1001 }
1002 }
1003}
1004
1005fn translate_const_expr_extended(
1006 expr: &wasmparser::ConstExpr,
1007 rebinder: &impl Rebind,
1008) -> eyre::Result<wasm_encoder::ConstExpr> {
1009 let mut instrs = Vec::new();
1010 for op in expr.get_operators_reader() {
1011 let op = op?;
1012 if matches!(op, wasmparser::Operator::End) {
1013 continue;
1014 }
1015 let instr = match op {
1016 wasmparser::Operator::RefNull { hty } => {
1017 wasm_encoder::Instruction::RefNull(translator::translate_heap_type(hty, rebinder))
1018 }
1019 _ => translator::translate(&op, rebinder),
1020 };
1021 instrs.push(instr);
1022 }
1023 Ok(wasm_encoder::ConstExpr::extended(instrs))
1024}
1025
1026fn translate_type_ref(ty: TypeRef, rebinder: &impl Rebind) -> EntityType {
1027 match ty {
1028 TypeRef::Func(idx) => EntityType::Function(rebinder.ty(idx)),
1029 TypeRef::FuncExact(idx) => EntityType::FunctionExact(rebinder.ty(idx)),
1030 TypeRef::Table(table) => {
1031 EntityType::Table(translator::translate_table_type(table, rebinder))
1032 }
1033 TypeRef::Memory(memory) => EntityType::Memory(translator::translate_memory_type(memory)),
1034 TypeRef::Global(global) => {
1035 EntityType::Global(translator::translate_global_type(global, rebinder))
1036 }
1037 TypeRef::Tag(tag) => EntityType::Tag(wasm_encoder::TagType {
1038 kind: match tag.kind {
1039 wasmparser::TagKind::Exception => wasm_encoder::TagKind::Exception,
1040 },
1041 func_type_idx: rebinder.ty(tag.func_type_idx),
1042 }),
1043 }
1044}
1045
1046fn rebind_external_index(kind: ExternalKind, index: u32, rebinder: &impl Rebind) -> u32 {
1047 match kind {
1048 ExternalKind::Func | ExternalKind::FuncExact => rebinder.function(index),
1049 ExternalKind::Table => rebinder.table(index),
1050 ExternalKind::Memory => rebinder.memory(index),
1051 ExternalKind::Global => rebinder.global(index),
1052 ExternalKind::Tag => rebinder.tag(index),
1053 }
1054}
1055
1056fn alias_export_names(alias: &str, export_name: &str) -> Vec<String> {
1057 let mut names = vec![export_name.to_string()];
1058
1059 if alias == UniqueName::WASIP1_ABI_MODULE {
1060 for prefix in ["__wasip1_vfs___self_", "__wasip1_vfs_self_"] {
1061 if let Some(name) = export_name.strip_prefix(prefix) {
1062 names.push(name.to_string());
1063 }
1064 }
1065 }
1066
1067 if let Some(target_name) = alias.strip_prefix("wasip1_vfs_") {
1068 let normalized_prefix = format!("__wasip1_vfs_{target_name}_");
1069 if let Some(name) = export_name.strip_prefix(&normalized_prefix) {
1070 names.push(name.to_string());
1071 }
1072 }
1073
1074 names
1075}
1076
1077fn unique_export_name(used: &mut HashSet<String>, alias: &str, name: &str) -> String {
1078 if used.insert(name.to_string()) {
1079 return name.to_string();
1080 }
1081 let mut candidate = format!("__{alias}_{name}");
1082 let mut suffix = 1;
1083 while !used.insert(candidate.clone()) {
1084 candidate = format!("__{alias}_{name}_{suffix}");
1085 suffix += 1;
1086 }
1087 candidate
1088}
1089
1090#[cfg(test)]
1091mod tests {
1092 use tempfile::tempdir;
1093 use wasm_encoder::{
1094 CodeSection, ExportKind, ExportSection, Function, FunctionSection, ImportSection,
1095 Instruction, Module, TypeSection,
1096 };
1097
1098 use super::*;
1099
1100 #[test]
1101 fn resolves_cross_module_function_import() -> eyre::Result<()> {
1102 let dir = tempdir()?;
1103 let a = dir.path().join("a.wasm");
1104 let b = dir.path().join("b.wasm");
1105 let out = dir.path().join("merged.wasm");
1106
1107 std::fs::write(&a, exported_const_module("answer", 7))?;
1108 std::fs::write(&b, importing_module("a", "answer"))?;
1109
1110 merge_modules(
1111 &[
1112 MergeInput {
1113 alias: "a".to_string(),
1114 path: &a,
1115 },
1116 MergeInput {
1117 alias: "b".to_string(),
1118 path: &b,
1119 },
1120 ],
1121 &out,
1122 false,
1123 )?;
1124
1125 let bytes = std::fs::read(out)?;
1126 let mut import_count = 0;
1127 let mut has_call = false;
1128 for payload in parse_payloads(&bytes) {
1129 match payload? {
1130 Payload::ImportSection(section) => import_count += section.count(),
1131 Payload::CodeSectionEntry(body) => {
1132 for op in body.get_operators_reader()? {
1133 if matches!(op?, wasmparser::Operator::Call { function_index: 0 }) {
1134 has_call = true;
1135 }
1136 }
1137 }
1138 _ => {}
1139 }
1140 }
1141 assert_eq!(import_count, 0);
1142 assert!(has_call);
1143 Ok(())
1144 }
1145
1146 #[test]
1147 fn deduplicates_identical_external_function_imports() -> eyre::Result<()> {
1148 let dir = tempdir()?;
1149 let input = dir.path().join("input.wasm");
1150 let out = dir.path().join("merged.wasm");
1151
1152 std::fs::write(&input, duplicate_importing_module("host", "run"))?;
1153 merge_modules(
1154 &[MergeInput {
1155 alias: "input".to_string(),
1156 path: &input,
1157 }],
1158 &out,
1159 false,
1160 )?;
1161
1162 let bytes = std::fs::read(out)?;
1163 let mut import_count = 0;
1164 let mut calls = Vec::new();
1165 for payload in parse_payloads(&bytes) {
1166 match payload? {
1167 Payload::ImportSection(section) => import_count += section.count(),
1168 Payload::CodeSectionEntry(body) => {
1169 for op in body.get_operators_reader()? {
1170 if let wasmparser::Operator::Call { function_index } = op? {
1171 calls.push(function_index);
1172 }
1173 }
1174 }
1175 _ => {}
1176 }
1177 }
1178
1179 assert_eq!(import_count, 1);
1180 assert_eq!(calls, vec![0, 0]);
1181 Ok(())
1182 }
1183
1184 fn exported_const_module(export: &str, value: i32) -> Vec<u8> {
1185 let mut module = Module::new();
1186 let mut types = TypeSection::new();
1187 types.ty().function([], [wasm_encoder::ValType::I32]);
1188 module.section(&types);
1189 let mut funcs = FunctionSection::new();
1190 funcs.function(0);
1191 module.section(&funcs);
1192 let mut exports = ExportSection::new();
1193 exports.export(export, ExportKind::Func, 0);
1194 module.section(&exports);
1195 let mut code = CodeSection::new();
1196 let mut func = Function::new([]);
1197 func.instruction(&Instruction::I32Const(value));
1198 func.instruction(&Instruction::End);
1199 code.function(&func);
1200 module.section(&code);
1201 module.finish()
1202 }
1203
1204 fn importing_module(module_name: &str, name: &str) -> Vec<u8> {
1205 let mut module = Module::new();
1206 let mut types = TypeSection::new();
1207 types.ty().function([], [wasm_encoder::ValType::I32]);
1208 module.section(&types);
1209 let mut imports = ImportSection::new();
1210 imports.import(module_name, name, EntityType::Function(0));
1211 module.section(&imports);
1212 let mut funcs = FunctionSection::new();
1213 funcs.function(0);
1214 module.section(&funcs);
1215 let mut code = CodeSection::new();
1216 let mut func = Function::new([]);
1217 func.instruction(&Instruction::Call(0));
1218 func.instruction(&Instruction::Drop);
1219 func.instruction(&Instruction::End);
1220 code.function(&func);
1221 module.section(&code);
1222 module.finish()
1223 }
1224
1225 fn duplicate_importing_module(module_name: &str, name: &str) -> Vec<u8> {
1226 let mut module = Module::new();
1227 let mut types = TypeSection::new();
1228 types.ty().function([], []);
1229 module.section(&types);
1230
1231 let mut imports = ImportSection::new();
1232 imports.import(module_name, name, EntityType::Function(0));
1233 imports.import(module_name, name, EntityType::Function(0));
1234 module.section(&imports);
1235
1236 let mut funcs = FunctionSection::new();
1237 funcs.function(0);
1238 module.section(&funcs);
1239
1240 let mut code = CodeSection::new();
1241 let mut func = Function::new([]);
1242 func.instruction(&Instruction::Call(0));
1243 func.instruction(&Instruction::Call(1));
1244 func.instruction(&Instruction::End);
1245 code.function(&func);
1246 module.section(&code);
1247 module.finish()
1248 }
1249}