1use crate::wasm_op::WasmOp;
7use anyhow::{Context, Result};
8use std::collections::HashMap;
9use wasmparser::{ExternalKind, Parser, Payload};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum ImportKind {
14 Function(u32),
16 Memory,
18 Table,
20 Global,
22}
23
24#[derive(Debug, Clone)]
26pub struct ImportEntry {
27 pub module: String,
29 pub name: String,
31 pub kind: ImportKind,
33 pub index: u32,
35}
36
37#[derive(Debug, Clone)]
39pub struct WasmMemory {
40 pub index: u32,
42 pub initial_pages: u32,
44 pub max_pages: Option<u32>,
46 pub shared: bool,
48}
49
50#[derive(Debug, Clone)]
56pub struct WasmGlobal {
57 pub index: u32,
59 pub init_i32: Option<i32>,
61 pub mutable: bool,
63}
64
65impl WasmMemory {
66 pub fn initial_bytes(&self) -> u32 {
68 self.initial_pages * 65536
69 }
70
71 pub fn max_bytes(&self) -> u32 {
73 self.max_pages.unwrap_or(self.initial_pages) * 65536
74 }
75}
76
77#[derive(Debug, Clone)]
79pub struct DecodedModule {
80 pub functions: Vec<FunctionOps>,
82 pub memories: Vec<WasmMemory>,
84 pub data_segments: Vec<(u32, Vec<u8>)>,
86 pub imports: Vec<ImportEntry>,
88 pub num_imported_funcs: u32,
90 pub func_arg_counts: Vec<u32>,
96 pub type_arg_counts: Vec<u32>,
100 pub func_ret_i64: Vec<bool>,
104 pub type_ret_i64: Vec<bool>,
106 pub func_params_i64: Vec<Vec<bool>>,
111 pub globals: Vec<WasmGlobal>,
116 pub elem_func_indices: Vec<u32>,
123}
124
125pub fn decode_wasm_module(wasm_bytes: &[u8]) -> Result<DecodedModule> {
127 let mut functions = Vec::new();
128 let mut memories = Vec::new();
129 let mut data_segments = Vec::new();
130 let mut globals: Vec<WasmGlobal> = Vec::new();
131 let mut imports = Vec::new();
132 let mut func_index = 0u32;
133 let mut num_imported_funcs = 0u32;
134 let mut export_names: HashMap<u32, String> = HashMap::new();
135 let mut type_arg_counts: Vec<u32> = Vec::new();
138 let mut func_arg_counts: Vec<u32> = Vec::new();
139 let mut type_ret_i64: Vec<bool> = Vec::new();
140 let mut func_ret_i64: Vec<bool> = Vec::new();
141 let mut type_params_i64: Vec<Vec<bool>> = Vec::new();
143 let mut func_params_i64: Vec<Vec<bool>> = Vec::new();
144 let mut elem_func_indices: Vec<u32> = Vec::new();
145
146 for payload in Parser::new(0).parse_all(wasm_bytes) {
147 let payload = payload.context("Failed to parse WASM payload")?;
148
149 match payload {
150 Payload::TypeSection(reader) => {
151 for rec_group in reader {
154 let rec_group = rec_group.context("Failed to parse type")?;
155 for sub_ty in rec_group.types() {
156 let (count, ret_i64, params_i64) = match &sub_ty.composite_type.inner {
157 wasmparser::CompositeInnerType::Func(func_ty) => (
158 func_ty.params().len() as u32,
159 func_ty
160 .results()
161 .first()
162 .is_some_and(|t| *t == wasmparser::ValType::I64),
163 func_ty
168 .params()
169 .iter()
170 .map(|t| {
171 matches!(
172 t,
173 wasmparser::ValType::I64 | wasmparser::ValType::F64
174 )
175 })
176 .collect::<Vec<bool>>(),
177 ),
178 _ => (0, false, Vec::new()),
179 };
180 type_arg_counts.push(count);
181 type_ret_i64.push(ret_i64);
182 type_params_i64.push(params_i64);
183 }
184 }
185 }
186 Payload::ImportSection(reader) => {
187 for import in reader.into_imports() {
193 let import = import.context("Failed to parse import")?;
194 let (kind, idx) = match import.ty {
195 wasmparser::TypeRef::Func(type_idx) => {
196 let idx = num_imported_funcs;
197 num_imported_funcs += 1;
198 func_arg_counts
201 .push(type_arg_counts.get(type_idx as usize).copied().unwrap_or(0));
202 func_ret_i64.push(
203 type_ret_i64
204 .get(type_idx as usize)
205 .copied()
206 .unwrap_or(false),
207 );
208 func_params_i64.push(
209 type_params_i64
210 .get(type_idx as usize)
211 .cloned()
212 .unwrap_or_default(),
213 );
214 (ImportKind::Function(type_idx), idx)
215 }
216 wasmparser::TypeRef::Memory(_) => (ImportKind::Memory, 0),
217 wasmparser::TypeRef::Table(_) => (ImportKind::Table, 0),
218 wasmparser::TypeRef::Global(_) => (ImportKind::Global, 0),
219 _ => continue,
220 };
221 imports.push(ImportEntry {
222 module: import.module.to_string(),
223 name: import.name.to_string(),
224 kind,
225 index: idx,
226 });
227 }
228 }
229 Payload::FunctionSection(reader) => {
230 for ty in reader {
235 let type_idx = ty.context("Failed to parse function type index")?;
236 func_arg_counts
237 .push(type_arg_counts.get(type_idx as usize).copied().unwrap_or(0));
238 func_ret_i64.push(
239 type_ret_i64
240 .get(type_idx as usize)
241 .copied()
242 .unwrap_or(false),
243 );
244 func_params_i64.push(
245 type_params_i64
246 .get(type_idx as usize)
247 .cloned()
248 .unwrap_or_default(),
249 );
250 }
251 }
252 Payload::MemorySection(reader) => {
253 for (idx, memory) in reader.into_iter().enumerate() {
254 let mem = memory.context("Failed to parse memory")?;
255 memories.push(WasmMemory {
256 index: idx as u32,
257 initial_pages: mem.initial as u32,
258 max_pages: mem.maximum.map(|m| m as u32),
259 shared: mem.shared,
260 });
261 }
262 }
263 Payload::GlobalSection(reader) => {
264 for (idx, global) in reader.into_iter().enumerate() {
270 let global = global.context("Failed to parse global")?;
271 let mut init_i32 = None;
272 let mut ops = global.init_expr.get_operators_reader();
273 if let Ok(wasmparser::Operator::I32Const { value }) = ops.read() {
274 init_i32 = Some(value);
275 }
276 globals.push(WasmGlobal {
277 index: idx as u32,
278 init_i32,
279 mutable: global.ty.mutable,
280 });
281 }
282 }
283 Payload::DataSection(reader) => {
284 for data in reader {
285 let data = data.context("Failed to parse data segment")?;
286 if let wasmparser::DataKind::Active {
287 memory_index: 0,
288 offset_expr,
289 } = data.kind
290 {
291 let mut ops = offset_expr.get_operators_reader();
292 if let Ok(wasmparser::Operator::I32Const { value }) = ops.read() {
293 data_segments.push((value as u32, data.data.to_vec()));
294 }
295 }
296 }
297 }
298 Payload::ElementSection(reader) => {
299 for elem in reader {
306 let elem = elem.context("Failed to parse element segment")?;
307 match elem.items {
308 wasmparser::ElementItems::Functions(funcs) => {
309 for f in funcs {
310 elem_func_indices
311 .push(f.context("Failed to parse element func index")?);
312 }
313 }
314 wasmparser::ElementItems::Expressions(_, exprs) => {
315 for expr in exprs {
316 let expr = expr.context("Failed to parse element expr")?;
317 for op in expr.get_operators_reader() {
318 if let wasmparser::Operator::RefFunc { function_index } =
319 op.context("Failed to parse element op")?
320 {
321 elem_func_indices.push(function_index);
322 }
323 }
324 }
325 }
326 }
327 }
328 }
329 Payload::ExportSection(exports) => {
330 for export in exports {
331 let export = export.context("Failed to parse export")?;
332 if export.kind == ExternalKind::Func {
333 export_names.insert(export.index, export.name.to_string());
334 }
335 }
336 }
337 Payload::CodeSectionEntry(body) => {
338 let (ops, unsupported) = decode_function_body(&body)?;
339 let actual_index = num_imported_funcs + func_index;
340 let export_name = export_names.get(&actual_index).cloned();
341
342 functions.push(FunctionOps {
343 index: actual_index,
344 export_name,
345 ops,
346 unsupported,
347 });
348 func_index += 1;
349 }
350 _ => {}
351 }
352 }
353
354 Ok(DecodedModule {
355 functions,
356 memories,
357 data_segments,
358 imports,
359 num_imported_funcs,
360 func_arg_counts,
361 type_arg_counts,
362 func_ret_i64,
363 type_ret_i64,
364 func_params_i64,
365 globals,
366 elem_func_indices,
367 })
368}
369
370pub fn decode_wasm_functions(wasm_bytes: &[u8]) -> Result<Vec<FunctionOps>> {
372 let mut functions = Vec::new();
373 let mut func_index = 0u32;
374 let mut num_imported_funcs = 0u32;
375 let mut export_names: HashMap<u32, String> = HashMap::new();
376
377 for payload in Parser::new(0).parse_all(wasm_bytes) {
378 let payload = payload.context("Failed to parse WASM payload")?;
379
380 match payload {
381 Payload::ImportSection(imports) => {
382 for import in imports.into_imports() {
385 let import = import.context("Failed to parse import")?;
386 if matches!(import.ty, wasmparser::TypeRef::Func(_)) {
387 num_imported_funcs += 1;
388 }
389 }
390 }
391 Payload::ExportSection(exports) => {
392 for export in exports {
393 let export = export.context("Failed to parse export")?;
394 if export.kind == ExternalKind::Func {
395 export_names.insert(export.index, export.name.to_string());
396 }
397 }
398 }
399 Payload::CodeSectionEntry(body) => {
400 let (ops, unsupported) = decode_function_body(&body)?;
401 let actual_index = num_imported_funcs + func_index;
402 let export_name = export_names.get(&actual_index).cloned();
403
404 functions.push(FunctionOps {
405 index: actual_index,
406 export_name,
407 ops,
408 unsupported,
409 });
410 func_index += 1;
411 }
412 _ => {}
413 }
414 }
415
416 Ok(functions)
417}
418
419#[derive(Debug, Clone)]
421pub struct FunctionOps {
422 pub index: u32,
424 pub export_name: Option<String>,
426 pub ops: Vec<WasmOp>,
428 pub unsupported: Option<String>,
438}
439
440fn decode_function_body(body: &wasmparser::FunctionBody) -> Result<(Vec<WasmOp>, Option<String>)> {
446 let mut ops = Vec::new();
447 let mut unsupported: Option<String> = None;
448
449 let ops_reader = body.get_operators_reader()?;
450 for op_result in ops_reader {
451 let op = op_result.context("Failed to read operator")?;
452
453 if let Some(wasm_op) = convert_operator(&op) {
454 ops.push(wasm_op);
455 } else if unsupported.is_none() && !is_intentionally_ignored(&op) {
456 unsupported = Some(format!("{op:?}"));
460 }
461 }
462
463 Ok((ops, unsupported))
464}
465
466fn is_intentionally_ignored(op: &wasmparser::Operator) -> bool {
471 use wasmparser::Operator::*;
472 matches!(op, Nop | Unreachable)
473}
474
475fn convert_operator(op: &wasmparser::Operator) -> Option<WasmOp> {
477 use wasmparser::Operator::*;
478
479 match op {
480 I32Const { value } => Some(WasmOp::I32Const(*value)),
482
483 I32Add => Some(WasmOp::I32Add),
485 I32Sub => Some(WasmOp::I32Sub),
486 I32Mul => Some(WasmOp::I32Mul),
487 I32DivS => Some(WasmOp::I32DivS),
488 I32DivU => Some(WasmOp::I32DivU),
489 I32RemS => Some(WasmOp::I32RemS),
490 I32RemU => Some(WasmOp::I32RemU),
491
492 I64Const { value } => Some(WasmOp::I64Const(*value)),
494
495 I64Add => Some(WasmOp::I64Add),
497 I64Sub => Some(WasmOp::I64Sub),
498 I64Mul => Some(WasmOp::I64Mul),
499 I64DivS => Some(WasmOp::I64DivS),
500 I64DivU => Some(WasmOp::I64DivU),
501 I64RemS => Some(WasmOp::I64RemS),
502 I64RemU => Some(WasmOp::I64RemU),
503
504 I64And => Some(WasmOp::I64And),
506 I64Or => Some(WasmOp::I64Or),
507 I64Xor => Some(WasmOp::I64Xor),
508 I64Shl => Some(WasmOp::I64Shl),
509 I64ShrS => Some(WasmOp::I64ShrS),
510 I64ShrU => Some(WasmOp::I64ShrU),
511 I64Rotl => Some(WasmOp::I64Rotl),
512 I64Rotr => Some(WasmOp::I64Rotr),
513 I64Clz => Some(WasmOp::I64Clz),
514 I64Ctz => Some(WasmOp::I64Ctz),
515 I64Popcnt => Some(WasmOp::I64Popcnt),
516 I64Extend8S => Some(WasmOp::I64Extend8S),
517 I64Extend16S => Some(WasmOp::I64Extend16S),
518 I64Extend32S => Some(WasmOp::I64Extend32S),
519 I64ExtendI32U => Some(WasmOp::I64ExtendI32U),
525 I64ExtendI32S => Some(WasmOp::I64ExtendI32S),
526 I32WrapI64 => Some(WasmOp::I32WrapI64),
527
528 I64Eqz => Some(WasmOp::I64Eqz),
530 I64Eq => Some(WasmOp::I64Eq),
531 I64Ne => Some(WasmOp::I64Ne),
532 I64LtS => Some(WasmOp::I64LtS),
533 I64LtU => Some(WasmOp::I64LtU),
534 I64LeS => Some(WasmOp::I64LeS),
535 I64LeU => Some(WasmOp::I64LeU),
536 I64GtS => Some(WasmOp::I64GtS),
537 I64GtU => Some(WasmOp::I64GtU),
538 I64GeS => Some(WasmOp::I64GeS),
539 I64GeU => Some(WasmOp::I64GeU),
540
541 I32And => Some(WasmOp::I32And),
543 I32Or => Some(WasmOp::I32Or),
544 I32Xor => Some(WasmOp::I32Xor),
545 I32Shl => Some(WasmOp::I32Shl),
546 I32ShrS => Some(WasmOp::I32ShrS),
547 I32ShrU => Some(WasmOp::I32ShrU),
548 I32Rotl => Some(WasmOp::I32Rotl),
549 I32Rotr => Some(WasmOp::I32Rotr),
550 I32Clz => Some(WasmOp::I32Clz),
551 I32Ctz => Some(WasmOp::I32Ctz),
552 I32Popcnt => Some(WasmOp::I32Popcnt),
553 I32Extend8S => Some(WasmOp::I32Extend8S),
554 I32Extend16S => Some(WasmOp::I32Extend16S),
555
556 I32Eqz => Some(WasmOp::I32Eqz),
558 I32Eq => Some(WasmOp::I32Eq),
559 I32Ne => Some(WasmOp::I32Ne),
560 I32LtS => Some(WasmOp::I32LtS),
561 I32LtU => Some(WasmOp::I32LtU),
562 I32LeS => Some(WasmOp::I32LeS),
563 I32LeU => Some(WasmOp::I32LeU),
564 I32GtS => Some(WasmOp::I32GtS),
565 I32GtU => Some(WasmOp::I32GtU),
566 I32GeS => Some(WasmOp::I32GeS),
567 I32GeU => Some(WasmOp::I32GeU),
568
569 I32Load { memarg } => Some(WasmOp::I32Load {
571 offset: memarg.offset as u32,
572 align: memarg.align as u32,
573 }),
574 I32Store { memarg } => Some(WasmOp::I32Store {
575 offset: memarg.offset as u32,
576 align: memarg.align as u32,
577 }),
578 I64Load { memarg } => Some(WasmOp::I64Load {
585 offset: memarg.offset as u32,
586 align: memarg.align as u32,
587 }),
588 I64Store { memarg } => Some(WasmOp::I64Store {
589 offset: memarg.offset as u32,
590 align: memarg.align as u32,
591 }),
592
593 I32Load8S { memarg } => Some(WasmOp::I32Load8S {
595 offset: memarg.offset as u32,
596 align: memarg.align as u32,
597 }),
598 I32Load8U { memarg } => Some(WasmOp::I32Load8U {
599 offset: memarg.offset as u32,
600 align: memarg.align as u32,
601 }),
602 I32Load16S { memarg } => Some(WasmOp::I32Load16S {
603 offset: memarg.offset as u32,
604 align: memarg.align as u32,
605 }),
606 I32Load16U { memarg } => Some(WasmOp::I32Load16U {
607 offset: memarg.offset as u32,
608 align: memarg.align as u32,
609 }),
610
611 I32Store8 { memarg } => Some(WasmOp::I32Store8 {
613 offset: memarg.offset as u32,
614 align: memarg.align as u32,
615 }),
616 I32Store16 { memarg } => Some(WasmOp::I32Store16 {
617 offset: memarg.offset as u32,
618 align: memarg.align as u32,
619 }),
620
621 LocalGet { local_index } => Some(WasmOp::LocalGet(*local_index)),
623 LocalSet { local_index } => Some(WasmOp::LocalSet(*local_index)),
624 LocalTee { local_index } => Some(WasmOp::LocalTee(*local_index)),
625 GlobalGet { global_index } => Some(WasmOp::GlobalGet(*global_index)),
626 GlobalSet { global_index } => Some(WasmOp::GlobalSet(*global_index)),
627
628 Block { .. } => Some(WasmOp::Block),
630 Loop { .. } => Some(WasmOp::Loop),
631 Br { relative_depth } => Some(WasmOp::Br(*relative_depth)),
632 BrIf { relative_depth } => Some(WasmOp::BrIf(*relative_depth)),
633 BrTable { targets } => {
639 let default = targets.default();
640 let tgts: Vec<u32> = targets.targets().filter_map(Result::ok).collect();
641 Some(WasmOp::BrTable {
642 targets: tgts,
643 default,
644 })
645 }
646 Return => Some(WasmOp::Return),
647 Call { function_index } => Some(WasmOp::Call(*function_index)),
648 CallIndirect {
649 type_index,
650 table_index,
651 ..
652 } => Some(WasmOp::CallIndirect {
653 type_index: *type_index,
654 table_index: *table_index,
655 }),
656
657 End => Some(WasmOp::End),
659
660 Nop | Unreachable => None,
662
663 Drop => Some(WasmOp::Drop),
665
666 Select => Some(WasmOp::Select),
668
669 If { .. } => Some(WasmOp::If),
671 Else => Some(WasmOp::Else),
672
673 I64Load8S { memarg } => Some(WasmOp::I64Load8S {
675 offset: memarg.offset as u32,
676 align: memarg.align as u32,
677 }),
678 I64Load8U { memarg } => Some(WasmOp::I64Load8U {
679 offset: memarg.offset as u32,
680 align: memarg.align as u32,
681 }),
682 I64Load16S { memarg } => Some(WasmOp::I64Load16S {
683 offset: memarg.offset as u32,
684 align: memarg.align as u32,
685 }),
686 I64Load16U { memarg } => Some(WasmOp::I64Load16U {
687 offset: memarg.offset as u32,
688 align: memarg.align as u32,
689 }),
690 I64Load32S { memarg } => Some(WasmOp::I64Load32S {
691 offset: memarg.offset as u32,
692 align: memarg.align as u32,
693 }),
694 I64Load32U { memarg } => Some(WasmOp::I64Load32U {
695 offset: memarg.offset as u32,
696 align: memarg.align as u32,
697 }),
698
699 I64Store8 { memarg } => Some(WasmOp::I64Store8 {
701 offset: memarg.offset as u32,
702 align: memarg.align as u32,
703 }),
704 I64Store16 { memarg } => Some(WasmOp::I64Store16 {
705 offset: memarg.offset as u32,
706 align: memarg.align as u32,
707 }),
708 I64Store32 { memarg } => Some(WasmOp::I64Store32 {
709 offset: memarg.offset as u32,
710 align: memarg.align as u32,
711 }),
712
713 MemorySize { mem, .. } => Some(WasmOp::MemorySize(*mem)),
715 MemoryGrow { mem, .. } => Some(WasmOp::MemoryGrow(*mem)),
716
717 V128Const { value } => {
721 let mut bytes = [0u8; 16];
722 bytes.copy_from_slice(value.bytes());
723 Some(WasmOp::V128Const(bytes))
724 }
725 V128Load { memarg } => Some(WasmOp::V128Load {
726 offset: memarg.offset as u32,
727 align: memarg.align as u32,
728 }),
729 V128Store { memarg } => Some(WasmOp::V128Store {
730 offset: memarg.offset as u32,
731 align: memarg.align as u32,
732 }),
733
734 V128And => Some(WasmOp::V128And),
736 V128Or => Some(WasmOp::V128Or),
737 V128Xor => Some(WasmOp::V128Xor),
738 V128Not => Some(WasmOp::V128Not),
739 V128AndNot => Some(WasmOp::V128AndNot),
740
741 I8x16Add => Some(WasmOp::I8x16Add),
743 I8x16Sub => Some(WasmOp::I8x16Sub),
744 I8x16Neg => Some(WasmOp::I8x16Neg),
745 I8x16Eq => Some(WasmOp::I8x16Eq),
746 I8x16Ne => Some(WasmOp::I8x16Ne),
747 I8x16LtS => Some(WasmOp::I8x16LtS),
748 I8x16LtU => Some(WasmOp::I8x16LtU),
749 I8x16GtS => Some(WasmOp::I8x16GtS),
750 I8x16GtU => Some(WasmOp::I8x16GtU),
751 I8x16LeS => Some(WasmOp::I8x16LeS),
752 I8x16LeU => Some(WasmOp::I8x16LeU),
753 I8x16GeS => Some(WasmOp::I8x16GeS),
754 I8x16GeU => Some(WasmOp::I8x16GeU),
755 I8x16Splat => Some(WasmOp::I8x16Splat),
756 I8x16ExtractLaneS { lane } => Some(WasmOp::I8x16ExtractLaneS(*lane)),
757 I8x16ExtractLaneU { lane } => Some(WasmOp::I8x16ExtractLaneU(*lane)),
758 I8x16ReplaceLane { lane } => Some(WasmOp::I8x16ReplaceLane(*lane)),
759 I8x16Shuffle { lanes } => Some(WasmOp::I8x16Shuffle(*lanes)),
760 I8x16Swizzle => Some(WasmOp::I8x16Swizzle),
761
762 I16x8Add => Some(WasmOp::I16x8Add),
764 I16x8Sub => Some(WasmOp::I16x8Sub),
765 I16x8Mul => Some(WasmOp::I16x8Mul),
766 I16x8Neg => Some(WasmOp::I16x8Neg),
767 I16x8Eq => Some(WasmOp::I16x8Eq),
768 I16x8Ne => Some(WasmOp::I16x8Ne),
769 I16x8LtS => Some(WasmOp::I16x8LtS),
770 I16x8LtU => Some(WasmOp::I16x8LtU),
771 I16x8GtS => Some(WasmOp::I16x8GtS),
772 I16x8GtU => Some(WasmOp::I16x8GtU),
773 I16x8LeS => Some(WasmOp::I16x8LeS),
774 I16x8LeU => Some(WasmOp::I16x8LeU),
775 I16x8GeS => Some(WasmOp::I16x8GeS),
776 I16x8GeU => Some(WasmOp::I16x8GeU),
777 I16x8Splat => Some(WasmOp::I16x8Splat),
778 I16x8ExtractLaneS { lane } => Some(WasmOp::I16x8ExtractLaneS(*lane)),
779 I16x8ExtractLaneU { lane } => Some(WasmOp::I16x8ExtractLaneU(*lane)),
780 I16x8ReplaceLane { lane } => Some(WasmOp::I16x8ReplaceLane(*lane)),
781
782 I32x4Add => Some(WasmOp::I32x4Add),
784 I32x4Sub => Some(WasmOp::I32x4Sub),
785 I32x4Mul => Some(WasmOp::I32x4Mul),
786 I32x4Neg => Some(WasmOp::I32x4Neg),
787 I32x4Eq => Some(WasmOp::I32x4Eq),
788 I32x4Ne => Some(WasmOp::I32x4Ne),
789 I32x4LtS => Some(WasmOp::I32x4LtS),
790 I32x4LtU => Some(WasmOp::I32x4LtU),
791 I32x4GtS => Some(WasmOp::I32x4GtS),
792 I32x4GtU => Some(WasmOp::I32x4GtU),
793 I32x4LeS => Some(WasmOp::I32x4LeS),
794 I32x4LeU => Some(WasmOp::I32x4LeU),
795 I32x4GeS => Some(WasmOp::I32x4GeS),
796 I32x4GeU => Some(WasmOp::I32x4GeU),
797 I32x4Splat => Some(WasmOp::I32x4Splat),
798 I32x4ExtractLane { lane } => Some(WasmOp::I32x4ExtractLane(*lane)),
799 I32x4ReplaceLane { lane } => Some(WasmOp::I32x4ReplaceLane(*lane)),
800
801 I64x2Add => Some(WasmOp::I64x2Add),
803 I64x2Sub => Some(WasmOp::I64x2Sub),
804 I64x2Mul => Some(WasmOp::I64x2Mul),
805 I64x2Neg => Some(WasmOp::I64x2Neg),
806 I64x2Eq => Some(WasmOp::I64x2Eq),
807 I64x2Ne => Some(WasmOp::I64x2Ne),
808 I64x2LtS => Some(WasmOp::I64x2LtS),
809 I64x2GtS => Some(WasmOp::I64x2GtS),
810 I64x2LeS => Some(WasmOp::I64x2LeS),
811 I64x2GeS => Some(WasmOp::I64x2GeS),
812 I64x2Splat => Some(WasmOp::I64x2Splat),
813 I64x2ExtractLane { lane } => Some(WasmOp::I64x2ExtractLane(*lane)),
814 I64x2ReplaceLane { lane } => Some(WasmOp::I64x2ReplaceLane(*lane)),
815
816 F32x4Add => Some(WasmOp::F32x4Add),
818 F32x4Sub => Some(WasmOp::F32x4Sub),
819 F32x4Mul => Some(WasmOp::F32x4Mul),
820 F32x4Div => Some(WasmOp::F32x4Div),
821 F32x4Abs => Some(WasmOp::F32x4Abs),
822 F32x4Neg => Some(WasmOp::F32x4Neg),
823 F32x4Sqrt => Some(WasmOp::F32x4Sqrt),
824 F32x4Eq => Some(WasmOp::F32x4Eq),
825 F32x4Ne => Some(WasmOp::F32x4Ne),
826 F32x4Lt => Some(WasmOp::F32x4Lt),
827 F32x4Le => Some(WasmOp::F32x4Le),
828 F32x4Gt => Some(WasmOp::F32x4Gt),
829 F32x4Ge => Some(WasmOp::F32x4Ge),
830 F32x4Splat => Some(WasmOp::F32x4Splat),
831 F32x4ExtractLane { lane } => Some(WasmOp::F32x4ExtractLane(*lane)),
832 F32x4ReplaceLane { lane } => Some(WasmOp::F32x4ReplaceLane(*lane)),
833
834 _ => None,
836 }
837}
838
839#[cfg(test)]
840mod tests {
841 use super::*;
842
843 #[test]
844 fn test_decode_simple_add() {
845 let wat = r#"
846 (module
847 (func (export "add") (param i32 i32) (result i32)
848 local.get 0
849 local.get 1
850 i32.add
851 )
852 )
853 "#;
854
855 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
856 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
857
858 assert_eq!(functions.len(), 1);
859 assert_eq!(functions[0].index, 0);
860 assert_eq!(functions[0].export_name, Some("add".to_string()));
861 assert_eq!(
862 functions[0].ops,
863 vec![
864 WasmOp::LocalGet(0),
865 WasmOp::LocalGet(1),
866 WasmOp::I32Add,
867 WasmOp::End
868 ]
869 );
870 }
871
872 #[test]
878 fn test_decode_i64_i32_width_conversions() {
879 let wat = r#"
880 (module
881 (func (export "conv") (param i32 i64) (result i32)
882 local.get 0
883 i64.extend_i32_u
884 local.get 0
885 i64.extend_i32_s
886 i64.add
887 local.get 1
888 i64.add
889 i32.wrap_i64
890 )
891 )
892 "#;
893 let wasm = wat::parse_str(wat).expect("parse");
894 let functions = decode_wasm_functions(&wasm).expect("decode");
895 let ops = &functions[0].ops;
896 assert!(
897 ops.contains(&WasmOp::I64ExtendI32U),
898 "i64.extend_i32_u must decode (not be dropped): {ops:?}"
899 );
900 assert!(
901 ops.contains(&WasmOp::I64ExtendI32S),
902 "i64.extend_i32_s must decode (not be dropped): {ops:?}"
903 );
904 assert!(
905 ops.contains(&WasmOp::I32WrapI64),
906 "i32.wrap_i64 must decode (not be dropped): {ops:?}"
907 );
908 }
909
910 #[test]
915 fn test_decode_br_table() {
916 let wat = r#"
917 (module
918 (func (export "bt") (param i32) (result i32)
919 (block (block (block
920 local.get 0
921 br_table 2 0 1 2)
922 i32.const 30 return)
923 i32.const 20 return)
924 i32.const 10))
925 "#;
926 let wasm = wat::parse_str(wat).expect("parse");
927 let functions = decode_wasm_functions(&wasm).expect("decode");
928 let bt = functions[0]
929 .ops
930 .iter()
931 .find_map(|o| match o {
932 WasmOp::BrTable { targets, default } => Some((targets.clone(), *default)),
933 _ => None,
934 })
935 .expect("br_table must decode (not be dropped)");
936 assert_eq!(bt.0, vec![2, 0, 1], "br_table targets preserved in order");
937 assert_eq!(bt.1, 2, "br_table default preserved");
938 }
939
940 #[test]
941 fn test_decode_arithmetic() {
942 let wat = r#"
943 (module
944 (func (export "calc") (result i32)
945 i32.const 5
946 i32.const 3
947 i32.mul
948 i32.const 2
949 i32.add
950 )
951 )
952 "#;
953
954 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
955 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
956
957 assert_eq!(functions.len(), 1);
958 assert_eq!(functions[0].export_name, Some("calc".to_string()));
959 assert_eq!(
960 functions[0].ops,
961 vec![
962 WasmOp::I32Const(5),
963 WasmOp::I32Const(3),
964 WasmOp::I32Mul,
965 WasmOp::I32Const(2),
966 WasmOp::I32Add,
967 WasmOp::End,
968 ]
969 );
970 }
971
972 #[test]
973 fn test_decode_multi_function_module() {
974 let wat = r#"
975 (module
976 (func $helper)
977 (func (export "add") (param i32 i32) (result i32)
978 local.get 0
979 local.get 1
980 i32.add
981 )
982 (func (export "sub") (param i32 i32) (result i32)
983 local.get 0
984 local.get 1
985 i32.sub
986 )
987 )
988 "#;
989
990 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
991 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
992
993 assert_eq!(functions.len(), 3);
994 assert_eq!(functions[0].index, 0);
995 assert_eq!(functions[0].export_name, None);
996 assert_eq!(functions[1].index, 1);
997 assert_eq!(functions[1].export_name, Some("add".to_string()));
998 assert_eq!(functions[2].index, 2);
999 assert_eq!(functions[2].export_name, Some("sub".to_string()));
1000 }
1001
1002 #[test]
1003 fn test_decode_module_with_imports() {
1004 let wat = r#"
1005 (module
1006 (import "env" "log" (func $log (param i32)))
1007 (import "env" "memory" (memory 1))
1008 (func (export "run") (param i32)
1009 local.get 0
1010 call 0
1011 )
1012 )
1013 "#;
1014
1015 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1016 let module = decode_wasm_module(&wasm).expect("Failed to decode");
1017
1018 assert_eq!(module.imports.len(), 2);
1020 assert_eq!(module.num_imported_funcs, 1);
1021
1022 assert_eq!(module.imports[0].module, "env");
1024 assert_eq!(module.imports[0].name, "log");
1025 assert!(matches!(module.imports[0].kind, ImportKind::Function(_)));
1026
1027 assert_eq!(module.imports[1].module, "env");
1029 assert_eq!(module.imports[1].name, "memory");
1030 assert_eq!(module.imports[1].kind, ImportKind::Memory);
1031
1032 assert_eq!(module.functions.len(), 1);
1034 assert_eq!(module.functions[0].index, 1);
1035 assert_eq!(module.functions[0].export_name, Some("run".to_string()));
1036 }
1037
1038 #[test]
1039 fn test_find_function_by_export_name() {
1040 let wat = r#"
1041 (module
1042 (func $helper)
1043 (func (export "add") (param i32 i32) (result i32)
1044 local.get 0
1045 local.get 1
1046 i32.add
1047 )
1048 )
1049 "#;
1050
1051 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1052 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1053
1054 let add_func = functions
1055 .iter()
1056 .find(|f| f.export_name.as_deref() == Some("add"))
1057 .expect("Should find 'add' function");
1058
1059 assert_eq!(add_func.index, 1);
1060 assert!(add_func.ops.contains(&WasmOp::I32Add));
1061 }
1062
1063 #[test]
1064 fn test_decode_subword_loads() {
1065 let wat = r#"
1066 (module
1067 (memory 1)
1068 (func (export "test") (param i32) (result i32)
1069 local.get 0
1070 i32.load8_u
1071 )
1072 )
1073 "#;
1074
1075 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1076 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1077
1078 assert_eq!(functions.len(), 1);
1079 assert!(functions[0].ops.contains(&WasmOp::I32Load8U {
1080 offset: 0,
1081 align: 0,
1082 }));
1083 }
1084
1085 #[test]
1086 fn test_decode_subword_stores() {
1087 let wat = r#"
1088 (module
1089 (memory 1)
1090 (func (export "test") (param i32 i32)
1091 local.get 0
1092 local.get 1
1093 i32.store8
1094 )
1095 )
1096 "#;
1097
1098 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1099 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1100
1101 assert_eq!(functions.len(), 1);
1102 assert!(functions[0].ops.contains(&WasmOp::I32Store8 {
1103 offset: 0,
1104 align: 0,
1105 }));
1106 }
1107
1108 #[test]
1109 fn test_decode_memory_size_grow() {
1110 let wat = r#"
1111 (module
1112 (memory 1)
1113 (func (export "test") (result i32)
1114 memory.size
1115 )
1116 )
1117 "#;
1118
1119 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1120 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1121
1122 assert_eq!(functions.len(), 1);
1123 assert!(functions[0].ops.contains(&WasmOp::MemorySize(0)));
1124 }
1125
1126 #[test]
1127 fn test_decode_memory_grow() {
1128 let wat = r#"
1129 (module
1130 (memory 1)
1131 (func (export "test") (param i32) (result i32)
1132 local.get 0
1133 memory.grow
1134 )
1135 )
1136 "#;
1137
1138 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1139 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1140
1141 assert_eq!(functions.len(), 1);
1142 assert!(functions[0].ops.contains(&WasmOp::MemoryGrow(0)));
1143 }
1144
1145 #[test]
1146 fn test_decode_i64_subword_loads() {
1147 let wat = r#"
1148 (module
1149 (memory 1)
1150 (func (export "test") (param i32) (result i64)
1151 local.get 0
1152 i64.load8_s
1153 )
1154 )
1155 "#;
1156
1157 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1158 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1159
1160 assert_eq!(functions.len(), 1);
1161 assert!(functions[0].ops.contains(&WasmOp::I64Load8S {
1162 offset: 0,
1163 align: 0,
1164 }));
1165 }
1166
1167 #[test]
1168 fn test_decode_all_subword_memory_ops() {
1169 let wat = r#"
1171 (module
1172 (memory 1)
1173 (func (export "test") (param i32)
1174 ;; i32 sub-word loads
1175 local.get 0
1176 i32.load8_s
1177 drop
1178 local.get 0
1179 i32.load8_u
1180 drop
1181 local.get 0
1182 i32.load16_s
1183 drop
1184 local.get 0
1185 i32.load16_u
1186 drop
1187
1188 ;; i32 sub-word stores
1189 local.get 0
1190 i32.const 42
1191 i32.store8
1192 local.get 0
1193 i32.const 42
1194 i32.store16
1195
1196 ;; i64 sub-word loads
1197 local.get 0
1198 i64.load8_s
1199 drop
1200 local.get 0
1201 i64.load8_u
1202 drop
1203 local.get 0
1204 i64.load16_s
1205 drop
1206 local.get 0
1207 i64.load16_u
1208 drop
1209 local.get 0
1210 i64.load32_s
1211 drop
1212 local.get 0
1213 i64.load32_u
1214 drop
1215
1216 ;; i64 sub-word stores
1217 local.get 0
1218 i64.const 42
1219 i64.store8
1220 local.get 0
1221 i64.const 42
1222 i64.store16
1223 local.get 0
1224 i64.const 42
1225 i64.store32
1226 )
1227 )
1228 "#;
1229
1230 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1231 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1232
1233 assert_eq!(functions.len(), 1);
1234 let ops = &functions[0].ops;
1235
1236 assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Load8S { .. })));
1238 assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Load8U { .. })));
1239 assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Load16S { .. })));
1240 assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Load16U { .. })));
1241 assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Store8 { .. })));
1242 assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Store16 { .. })));
1243
1244 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load8S { .. })));
1246 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load8U { .. })));
1247 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load16S { .. })));
1248 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load16U { .. })));
1249 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load32S { .. })));
1250 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load32U { .. })));
1251 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Store8 { .. })));
1252 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Store16 { .. })));
1253 assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Store32 { .. })));
1254 }
1255
1256 #[test]
1257 fn test_decode_simd_i32x4_add() {
1258 let wat = r#"
1259 (module
1260 (func (export "add_v128") (param v128 v128) (result v128)
1261 local.get 0
1262 local.get 1
1263 i32x4.add
1264 )
1265 )
1266 "#;
1267
1268 let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1269 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1270
1271 assert_eq!(functions.len(), 1);
1272 assert!(
1273 functions[0].ops.contains(&WasmOp::I32x4Add),
1274 "Should decode i32x4.add: {:?}",
1275 functions[0].ops
1276 );
1277 }
1278
1279 #[test]
1280 fn test_decode_simd_v128_const() {
1281 let wat = r#"
1282 (module
1283 (func (export "const_v128") (result v128)
1284 v128.const i32x4 1 2 3 4
1285 )
1286 )
1287 "#;
1288
1289 let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1290 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1291
1292 assert_eq!(functions.len(), 1);
1293 assert!(
1294 functions[0]
1295 .ops
1296 .iter()
1297 .any(|o| matches!(o, WasmOp::V128Const(_))),
1298 "Should decode v128.const: {:?}",
1299 functions[0].ops
1300 );
1301 }
1302
1303 #[test]
1304 fn test_decode_simd_v128_load_store() {
1305 let wat = r#"
1306 (module
1307 (memory 1)
1308 (func (export "load_store") (param i32)
1309 local.get 0
1310 v128.load
1311 local.get 0
1312 v128.store
1313 )
1314 )
1315 "#;
1316
1317 let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1318 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1319
1320 assert_eq!(functions.len(), 1);
1321 let ops = &functions[0].ops;
1322 assert!(
1323 ops.iter().any(|o| matches!(o, WasmOp::V128Load { .. })),
1324 "Should decode v128.load"
1325 );
1326 assert!(
1327 ops.iter().any(|o| matches!(o, WasmOp::V128Store { .. })),
1328 "Should decode v128.store"
1329 );
1330 }
1331
1332 #[test]
1333 fn test_decode_simd_bitwise_ops() {
1334 let wat = r#"
1335 (module
1336 (func (export "bitwise") (param v128 v128) (result v128)
1337 local.get 0
1338 local.get 1
1339 v128.and
1340 )
1341 )
1342 "#;
1343
1344 let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1345 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1346
1347 assert_eq!(functions.len(), 1);
1348 assert!(functions[0].ops.contains(&WasmOp::V128And));
1349 }
1350
1351 #[test]
1352 fn test_decode_simd_splat() {
1353 let wat = r#"
1354 (module
1355 (func (export "splat") (param i32) (result v128)
1356 local.get 0
1357 i32x4.splat
1358 )
1359 )
1360 "#;
1361
1362 let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1363 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1364
1365 assert_eq!(functions.len(), 1);
1366 assert!(functions[0].ops.contains(&WasmOp::I32x4Splat));
1367 }
1368
1369 #[test]
1370 fn test_decode_simd_extract_lane() {
1371 let wat = r#"
1372 (module
1373 (func (export "extract") (param v128) (result i32)
1374 local.get 0
1375 i32x4.extract_lane 2
1376 )
1377 )
1378 "#;
1379
1380 let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1381 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1382
1383 assert_eq!(functions.len(), 1);
1384 assert!(
1385 functions[0].ops.contains(&WasmOp::I32x4ExtractLane(2)),
1386 "Should decode i32x4.extract_lane 2"
1387 );
1388 }
1389
1390 #[test]
1391 fn test_decode_simd_f32x4_arithmetic() {
1392 let wat = r#"
1393 (module
1394 (func (export "f32x4_add") (param v128 v128) (result v128)
1395 local.get 0
1396 local.get 1
1397 f32x4.add
1398 )
1399 )
1400 "#;
1401
1402 let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1403 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1404
1405 assert_eq!(functions.len(), 1);
1406 assert!(functions[0].ops.contains(&WasmOp::F32x4Add));
1407 }
1408
1409 #[test]
1410 fn test_369_scalar_float_op_flags_function_unsupported_not_dropped() {
1411 let wat = r#"
1415 (module
1416 (func (export "fadd") (param f32 f32) (result f32)
1417 local.get 0 local.get 1 f32.add)
1418 (func (export "iadd") (param i32 i32) (result i32)
1419 local.get 0 local.get 1 i32.add))
1420 "#;
1421 let wasm = wat::parse_str(wat).expect("parse");
1422 let functions = decode_wasm_functions(&wasm).expect("decode");
1423 let fadd = functions
1424 .iter()
1425 .find(|f| f.export_name.as_deref() == Some("fadd"))
1426 .unwrap();
1427 let iadd = functions
1428 .iter()
1429 .find(|f| f.export_name.as_deref() == Some("iadd"))
1430 .unwrap();
1431 assert!(
1432 fadd.unsupported.is_some(),
1433 "f32.add must flag the function unsupported (loud-skip), got {:?}",
1434 fadd.unsupported
1435 );
1436 assert!(
1437 fadd.unsupported.as_deref().unwrap().contains("F32Add"),
1438 "diagnostic should name the op: {:?}",
1439 fadd.unsupported
1440 );
1441 assert!(
1442 iadd.unsupported.is_none(),
1443 "a pure-integer function must NOT be flagged: {:?}",
1444 iadd.unsupported
1445 );
1446 }
1447
1448 #[test]
1449 fn test_decode_simd_multiple_ops() {
1450 let wat = r#"
1451 (module
1452 (func (export "simd_ops") (param v128 v128 v128) (result v128)
1453 ;; (a + b) * c
1454 local.get 0
1455 local.get 1
1456 i32x4.add
1457 local.get 2
1458 i32x4.mul
1459 )
1460 )
1461 "#;
1462
1463 let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1464 let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1465
1466 assert_eq!(functions.len(), 1);
1467 let ops = &functions[0].ops;
1468 assert!(ops.contains(&WasmOp::I32x4Add));
1469 assert!(ops.contains(&WasmOp::I32x4Mul));
1470 }
1471
1472 #[test]
1475 fn test_decode_captures_global_initializer() {
1476 let wat = r#"
1477 (module
1478 (memory 2)
1479 (global $__stack_pointer (mut i32) (i32.const 65536))
1480 (global $immutable_const i32 (i32.const 7))
1481 (func (export "f") (result i32) global.get 0)
1482 )
1483 "#;
1484 let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1485 let module = decode_wasm_module(&wasm).expect("Failed to decode");
1486
1487 assert_eq!(module.globals.len(), 2, "both globals captured");
1488 let sp = &module.globals[0];
1489 assert_eq!(sp.index, 0);
1490 assert_eq!(sp.init_i32, Some(65536), "stack-pointer init captured");
1491 assert!(sp.mutable, "stack pointer is mutable");
1492 let c = &module.globals[1];
1493 assert_eq!(c.init_i32, Some(7));
1494 assert!(!c.mutable, "second global is immutable");
1495 }
1496}