forked from bytecodealliance/wasm-tools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
3501 lines (3239 loc) · 136 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A crate to convert a WebAssembly binary to its textual representation in the
//! WebAssembly Text Format (WAT).
//!
//! This crate is intended for developer toolchains and debugging, supporting
//! human-readable versions of a wasm binary. This can also be useful when
//! developing wasm toolchain support in Rust for various purposes like testing
//! and debugging and such.
#![deny(missing_docs)]
use anyhow::{anyhow, bail, Context, Result};
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Write};
use std::mem;
use std::path::Path;
use wasmparser::*;
const MAX_LOCALS: u32 = 50000;
const MAX_NESTING_TO_PRINT: u32 = 50;
const MAX_WASM_FUNCTIONS: u32 = 1_000_000;
/// Reads a WebAssembly `file` from the filesystem and then prints it into an
/// in-memory `String`.
pub fn print_file(file: impl AsRef<Path>) -> Result<String> {
let file = file.as_ref();
let contents = std::fs::read(file).context(format!("failed to read `{}`", file.display()))?;
Printer::new().print(&contents)
}
/// Prints an in-memory `wasm` binary blob into an in-memory `String` which is
/// its textual representation.
pub fn print_bytes(wasm: impl AsRef<[u8]>) -> Result<String> {
Printer::new().print(wasm.as_ref())
}
/// Context used for printing a WebAssembly binary.
///
/// This is largely only required if you'd like to register custom printers for
/// custom sections in a wasm binary.
#[derive(Default)]
pub struct Printer {
printers: HashMap<String, Box<dyn FnMut(&mut Printer, usize, &[u8]) -> Result<()>>>,
result: String,
nesting: u32,
line: usize,
group_lines: Vec<usize>,
}
enum TypeDef<'a> {
// A core function type.
// The inner type is `None` for core functions in a component's function
// index space.
Func(Option<FuncType>),
Module,
// Stores a map between export name and index into the global type list.
// The exports are a subset of those exports relevant to the printer's state.
Component(HashMap<String, usize>),
// Stores a map between export name and index into the global type list.
// The exports are a subset of those exports relevant to the printer's state.
Instance(HashMap<String, usize>),
ComponentFunc(ComponentFuncType<'a>),
Value,
Interface,
}
#[derive(Debug, Clone, Copy)]
enum InstanceIndexType {
Module,
// Stores an index into the global type list.
// The expected type is an instance type (for imports or
// an instance from exported items) or a component type
// for component instantiations.
Component(usize),
}
struct State {
encoding: Encoding,
memories: u32,
tags: u32,
globals: u32,
tables: u32,
labels: u32,
values: u32,
modules: u32,
// Stores indexes into global type list.
types: Vec<usize>,
// Stores indexes into global type list (core or component function type).
functions: Vec<usize>,
instances: Vec<InstanceIndexType>,
// Stores indexes into global type list (component type).
components: Vec<usize>,
// Stores export names to index into global type list.
// This is populated only for components and only relevant exports are inserted.
exports: HashMap<String, usize>,
function_names: HashMap<u32, Naming>,
local_names: HashMap<(u32, u32), Naming>,
label_names: HashMap<(u32, u32), Naming>,
type_names: HashMap<u32, Naming>,
table_names: HashMap<u32, Naming>,
memory_names: HashMap<u32, Naming>,
global_names: HashMap<u32, Naming>,
element_names: HashMap<u32, Naming>,
data_names: HashMap<u32, Naming>,
module_names: HashMap<u32, Naming>,
component_names: HashMap<u32, Naming>,
instance_names: HashMap<u32, Naming>,
value_names: HashMap<u32, Naming>,
name: Option<Naming>,
}
impl State {
fn new(encoding: Encoding) -> Self {
Self {
encoding,
memories: 0,
tags: 0,
globals: 0,
tables: 0,
labels: 0,
values: 0,
modules: 0,
types: Vec::new(),
functions: Vec::new(),
instances: Vec::new(),
components: Vec::new(),
exports: HashMap::new(),
function_names: HashMap::new(),
local_names: HashMap::new(),
label_names: HashMap::new(),
type_names: HashMap::new(),
table_names: HashMap::new(),
memory_names: HashMap::new(),
global_names: HashMap::new(),
element_names: HashMap::new(),
data_names: HashMap::new(),
module_names: HashMap::new(),
component_names: HashMap::new(),
instance_names: HashMap::new(),
value_names: HashMap::new(),
name: None,
}
}
fn export(&mut self, name: &str, ty: usize) -> Result<()> {
if self.exports.insert(name.to_string(), ty).is_some() {
bail!(
"duplicate export name `{}` in export or type definition",
name
);
}
Ok(())
}
fn ty(&self, index: u32) -> Result<usize> {
self.types
.get(index as usize)
.copied()
.ok_or_else(|| anyhow!("type index {} out of bounds", index))
}
fn function(&self, index: u32) -> Result<usize> {
self.functions
.get(index as usize)
.copied()
.ok_or_else(|| anyhow!("function index {} out of bounds", index))
}
fn instance(&self, index: u32) -> Result<InstanceIndexType> {
self.instances
.get(index as usize)
.copied()
.ok_or_else(|| anyhow!("instance index {} out of bounds", index))
}
fn component(&self, index: u32) -> Result<usize> {
self.components
.get(index as usize)
.copied()
.ok_or_else(|| anyhow!("component index {} out of bounds", index))
}
fn instance_export(&self, types: &[TypeDef], instance: u32, name: &str) -> Result<usize> {
match self.instance(instance)? {
InstanceIndexType::Module => unreachable!(),
InstanceIndexType::Component(ty) => match &types[ty] {
TypeDef::Component(exports) | TypeDef::Instance(exports) => {
exports.get(name).copied().ok_or_else(|| {
anyhow!(
"no export named `{}` for instance with index {}",
name,
instance
)
})
}
_ => unreachable!(),
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OuterAliasKind {
Type,
Module,
Component,
}
struct Naming {
identifier: Option<String>,
name: String,
}
impl Printer {
/// Creates a new `Printer` object that's ready to start printing wasm
/// binaries to strings.
pub fn new() -> Self {
Self::default()
}
/// Registers a custom `printer` function to get invoked whenever a custom
/// section of name `section` is seen.
///
/// This can be used to register printers into a textual format for custom
/// sections, such as by emitting annotations and/or other textual
/// references (maybe comments!)
///
/// By default all custom sections are ignored for the text format.
///
/// The `printer` function provided takes three arguments:
///
/// * A `&mut Printer`, or where to print results to
/// * A `usize` offset which is the start of the offset for the custom
/// section
/// * A byte slice which is the actual contents of the custom section.
pub fn add_custom_section_printer(
&mut self,
section: &str,
printer: impl FnMut(&mut Printer, usize, &[u8]) -> Result<()> + 'static,
) {
self.printers.insert(section.to_string(), Box::new(printer));
}
/// Gets the output result of this `Printer`, or where all output is going.
pub fn result_mut(&mut self) -> &mut String {
&mut self.result
}
/// Prints a WebAssembly binary into a `String`
///
/// This function takes an entire `wasm` binary blob and will print it to
/// the WebAssembly Text Format and return the result as a `String`.
pub fn print(&mut self, wasm: &[u8]) -> Result<String> {
self.print_contents(wasm)?;
Ok(mem::take(&mut self.result))
}
fn read_names_and_code<'a>(
&mut self,
mut bytes: &'a [u8],
mut parser: Parser,
state: &mut State,
code: &mut Vec<FunctionBody<'a>>,
) -> Result<()> {
loop {
let payload = match parser.parse(bytes, true)? {
Chunk::NeedMoreData(_) => unreachable!(),
Chunk::Parsed { payload, consumed } => {
bytes = &bytes[consumed..];
payload
}
};
match payload {
Payload::FunctionSection(s) => {
if s.get_count() > MAX_WASM_FUNCTIONS {
bail!(
"module contains {} functions which exceeds the limit of {}",
s.get_count(),
MAX_WASM_FUNCTIONS
);
}
code.reserve(s.get_count() as usize);
}
Payload::CodeSectionEntry(f) => {
code.push(f);
}
Payload::ModuleSection { range, .. } | Payload::ComponentSection { range, .. } => {
let offset = range.end - range.start;
if offset > bytes.len() {
bail!("invalid module or component section range");
}
bytes = &bytes[offset..];
}
Payload::CustomSection(c) if c.name() == "name" => {
let reader = NameSectionReader::new(c.data(), c.data_offset())?;
// Ignore any error associated with the name section.
drop(self.register_names(state, reader));
}
Payload::End(_) => break,
_ => {}
}
}
Ok(())
}
fn ensure_module(states: &[State]) -> Result<()> {
if !matches!(states.last().unwrap().encoding, Encoding::Module) {
bail!("unexpected section found when parsing a module");
}
Ok(())
}
fn ensure_component(states: &[State]) -> Result<()> {
if !matches!(states.last().unwrap().encoding, Encoding::Component) {
bail!("unexpected section found when parsing a component");
}
Ok(())
}
fn print_contents(&mut self, mut bytes: &[u8]) -> Result<()> {
let mut expected = None;
let mut types = Vec::new();
let mut states: Vec<State> = Vec::new();
let mut parser = Parser::new(0);
let mut parsers = Vec::new();
let mut code = Vec::new();
let mut code_printed = false;
loop {
let payload = match parser.parse(bytes, true)? {
Chunk::NeedMoreData(_) => unreachable!(),
Chunk::Parsed { payload, consumed } => {
bytes = &bytes[consumed..];
payload
}
};
match payload {
Payload::Version { encoding, .. } => {
if let Some(e) = expected {
if encoding != e {
bail!("incorrect encoding for nested module or component");
}
expected = None;
}
assert!(states.last().map(|s| s.encoding) != Some(Encoding::Module));
match encoding {
Encoding::Module => {
states.push(State::new(Encoding::Module));
self.start_group("module");
if states.len() > 1 {
let parent = &states[states.len() - 2];
self.result.push(' ');
self.print_name(&parent.module_names, parent.modules)?;
}
}
Encoding::Component => {
states.push(State::new(Encoding::Component));
self.start_group("component");
if states.len() > 1 {
let parent = &states[states.len() - 2];
self.result.push(' ');
self.print_name(
&parent.component_names,
parent.components.len() as u32,
)?;
}
}
}
let state = states.last_mut().unwrap();
// First up try to find the `name` subsection which we'll use to print
// pretty names everywhere. Also look for the `code` section so we can
// print out functions as soon as we hit the function section.
code.clear();
code_printed = false;
self.read_names_and_code(bytes, parser.clone(), state, &mut code)?;
if let Some(name) = state.name.as_ref() {
self.result.push(' ');
name.write(&mut self.result);
}
}
Payload::CustomSection(c) => {
let mut printers = mem::take(&mut self.printers);
if let Some(printer) = printers.get_mut(c.name()) {
printer(self, c.data_offset(), c.data())?;
}
self.printers = printers;
}
Payload::TypeSection(s) => {
Self::ensure_module(&states)?;
self.print_types(states.last_mut().unwrap(), &mut types, s)?
}
Payload::ImportSection(s) => {
Self::ensure_module(&states)?;
self.print_imports(states.last_mut().unwrap(), &types, s)?
}
Payload::FunctionSection(reader) => {
Self::ensure_module(&states)?;
if mem::replace(&mut code_printed, true) {
bail!("function section appeared twice in module");
}
if reader.get_count() == 0 {
continue;
}
self.print_code(states.last_mut().unwrap(), &types, &code, reader)?;
}
Payload::TableSection(s) => {
Self::ensure_module(&states)?;
self.print_tables(states.last_mut().unwrap(), s)?
}
Payload::MemorySection(s) => {
Self::ensure_module(&states)?;
self.print_memories(states.last_mut().unwrap(), s)?
}
Payload::TagSection(s) => {
Self::ensure_module(&states)?;
self.print_tags(states.last_mut().unwrap(), &types, s)?
}
Payload::GlobalSection(s) => {
Self::ensure_module(&states)?;
self.print_globals(states.last_mut().unwrap(), &types, s)?
}
Payload::ExportSection(s) => {
Self::ensure_module(&states)?;
self.print_exports(states.last().unwrap(), s)?
}
Payload::StartSection { func, .. } => {
Self::ensure_module(&states)?;
self.newline();
self.start_group("start ");
self.print_idx(&states.last().unwrap().function_names, func)?;
self.end_group();
}
Payload::ElementSection(s) => {
Self::ensure_module(&states)?;
self.print_elems(states.last_mut().unwrap(), &types, s)?;
}
// printed with the `Function` section, so we
// skip this section
Payload::CodeSectionStart { size, .. } => {
Self::ensure_module(&states)?;
bytes = &bytes[size as usize..];
parser.skip_section();
}
Payload::CodeSectionEntry(_) => unreachable!(),
Payload::DataCountSection { .. } => {
Self::ensure_module(&states)?;
// not part of the text format
}
Payload::DataSection(s) => {
Self::ensure_module(&states)?;
self.print_data(states.last_mut().unwrap(), &types, s)?;
}
Payload::ComponentTypeSection(s) => {
Self::ensure_component(&states)?;
self.print_component_types(&mut states, &mut types, s)?;
}
Payload::ComponentImportSection(s) => {
Self::ensure_component(&states)?;
self.print_component_imports(states.last_mut().unwrap(), &types, s)?;
}
Payload::ComponentFunctionSection(s) => {
Self::ensure_component(&states)?;
self.print_component_functions(states.last_mut().unwrap(), &mut types, s)?;
}
Payload::ModuleSection { parser: inner, .. } => {
Self::ensure_component(&states)?;
expected = Some(Encoding::Module);
parsers.push(parser);
parser = inner;
self.newline();
}
Payload::ComponentSection { parser: inner, .. } => {
Self::ensure_component(&states)?;
expected = Some(Encoding::Component);
parsers.push(parser);
parser = inner;
self.newline();
}
Payload::InstanceSection(s) => {
Self::ensure_component(&states)?;
self.print_instances(states.last_mut().unwrap(), &mut types, s)?;
}
Payload::ComponentExportSection(s) => {
Self::ensure_component(&states)?;
self.print_component_exports(states.last_mut().unwrap(), s)?;
}
Payload::ComponentStartSection(s) => {
Self::ensure_component(&states)?;
self.print_component_start(states.last_mut().unwrap(), &types, s)?;
}
Payload::AliasSection(s) => {
Self::ensure_component(&states)?;
self.print_aliases(&mut states, &mut types, s)?;
}
Payload::End(_) => {
self.end_group(); // close the `module` or `component` group
let state = states.pop().unwrap();
if let Some(parent) = states.last_mut() {
match state.encoding {
Encoding::Module => {
parent.modules += 1;
}
Encoding::Component => {
parent.components.push(types.len());
types.push(TypeDef::Component(state.exports));
}
}
parser = parsers.pop().unwrap();
} else {
break;
}
}
Payload::UnknownSection { id, .. } => bail!("found unknown section `{}`", id),
}
}
Ok(())
}
fn start_group(&mut self, name: &str) {
self.result.push('(');
self.result.push_str(name);
self.nesting += 1;
self.group_lines.push(self.line);
}
fn end_group(&mut self) {
self.nesting -= 1;
if let Some(line) = self.group_lines.pop() {
if line != self.line {
self.newline();
}
}
self.result.push(')');
}
fn register_names(&mut self, state: &mut State, names: NameSectionReader<'_>) -> Result<()> {
fn name_map(into: &mut HashMap<u32, Naming>, names: NameMap<'_>, name: &str) -> Result<()> {
let mut used = HashSet::new();
let mut map = names.get_map()?;
for _ in 0..map.get_count() {
let naming = map.read()?;
into.insert(
naming.index,
Naming::new(naming.name, naming.index, name, &mut used),
);
}
Ok(())
}
fn indirect_name_map(
into: &mut HashMap<(u32, u32), Naming>,
names: IndirectNameMap<'_>,
name: &str,
) -> Result<()> {
let mut outer_map = names.get_indirect_map()?;
for _ in 0..outer_map.get_indirect_count() {
let mut used = HashSet::new();
let outer = outer_map.read()?;
let mut inner_map = outer.get_map()?;
for _ in 0..inner_map.get_count() {
let inner = inner_map.read()?;
into.insert(
(outer.indirect_index, inner.index),
Naming::new(inner.name, inner.index, name, &mut used),
);
}
}
Ok(())
}
for section in names {
match section? {
Name::Module(n) => {
let name = Naming::new(n.get_name()?, 0, "module", &mut HashSet::new());
state.name = Some(name);
}
Name::Function(n) => name_map(&mut state.function_names, n, "func")?,
Name::Local(n) => indirect_name_map(&mut state.local_names, n, "local")?,
Name::Label(n) => indirect_name_map(&mut state.label_names, n, "label")?,
Name::Type(n) => name_map(&mut state.type_names, n, "type")?,
Name::Table(n) => name_map(&mut state.table_names, n, "table")?,
Name::Memory(n) => name_map(&mut state.memory_names, n, "memory")?,
Name::Global(n) => name_map(&mut state.global_names, n, "global")?,
Name::Element(n) => name_map(&mut state.element_names, n, "elem")?,
Name::Data(n) => name_map(&mut state.data_names, n, "data")?,
Name::Unknown { .. } => (),
}
}
Ok(())
}
fn print_type(&mut self, state: &State, ty: &wasmparser::TypeDef) -> Result<()> {
self.start_group("type ");
self.print_name(&state.type_names, state.types.len() as u32)?;
self.result.push(' ');
match ty {
wasmparser::TypeDef::Func(ty) => {
self.start_group("func");
self.print_func_type(state, ty, None)?;
}
}
self.end_group(); // inner type
self.end_group(); // `type` itself
Ok(())
}
fn print_types(
&mut self,
state: &mut State,
types: &mut Vec<TypeDef>,
parser: TypeSectionReader<'_>,
) -> Result<()> {
for ty in parser {
let ty = ty?;
self.newline();
self.print_type(state, &ty)?;
match ty {
wasmparser::TypeDef::Func(ty) => {
state.types.push(types.len());
types.push(TypeDef::Func(Some(ty)));
}
}
}
Ok(())
}
fn print_functype_idx(
&mut self,
state: &State,
types: &[TypeDef],
idx: u32,
always_print_type: bool,
names_for: Option<u32>,
) -> Result<Option<u32>> {
if always_print_type {
self.print_type_ref(state, idx)?;
}
match &types[state.ty(idx)?] {
TypeDef::Func(Some(ty)) => self.print_func_type(state, ty, names_for).map(Some),
_ => unreachable!(),
}
}
/// Returns the number of parameters, useful for local index calculations
/// later.
fn print_func_type(
&mut self,
state: &State,
ty: &FuncType,
names_for: Option<u32>,
) -> Result<u32> {
if ty.params.len() > 0 {
self.result.push(' ');
}
let mut params = NamedLocalPrinter::new("param");
// Note that named parameters must be alone in a `param` block, so
// we need to be careful to terminate previous param blocks and open
// a new one if that's the case with a named parameter.
for (i, param) in ty.params.iter().enumerate() {
let name = names_for.and_then(|n| state.local_names.get(&(n, i as u32)));
params.start_local(name, &mut self.result);
self.print_valtype(*param)?;
params.end_local(&mut self.result);
}
params.finish(&mut self.result);
if ty.returns.len() > 0 {
self.result.push_str(" (result");
for result in ty.returns.iter() {
self.result.push(' ');
self.print_valtype(*result)?;
}
self.result.push(')');
}
Ok(ty.params.len() as u32)
}
fn print_valtype(&mut self, ty: Type) -> Result<()> {
match ty {
Type::I32 => self.result.push_str("i32"),
Type::I64 => self.result.push_str("i64"),
Type::F32 => self.result.push_str("f32"),
Type::F64 => self.result.push_str("f64"),
Type::V128 => self.result.push_str("v128"),
Type::FuncRef => self.result.push_str("funcref"),
Type::ExternRef => self.result.push_str("externref"),
}
Ok(())
}
fn print_reftype(&mut self, ty: Type) -> Result<()> {
match ty {
Type::FuncRef => self.result.push_str("func"),
Type::ExternRef => self.result.push_str("extern"),
_ => bail!("invalid reference type {:?}", ty),
}
Ok(())
}
fn print_imports(
&mut self,
state: &mut State,
types: &[TypeDef],
parser: ImportSectionReader<'_>,
) -> Result<()> {
for import in parser {
let import = import?;
self.newline();
self.print_import(state, types, &import, true)?;
match import.ty {
TypeRef::Func(index) => {
let ty = state.ty(index)?;
match &types[ty] {
TypeDef::Func(_) => {
state.functions.push(ty);
}
_ => bail!("index is not a function type"),
}
}
TypeRef::Table(_) => state.tables += 1,
TypeRef::Memory(_) => state.memories += 1,
TypeRef::Tag(_) => state.tags += 1,
TypeRef::Global(_) => state.globals += 1,
}
}
Ok(())
}
fn print_import(
&mut self,
state: &State,
types: &[TypeDef],
import: &Import<'_>,
index: bool,
) -> Result<()> {
self.start_group("import ");
self.print_str(import.module)?;
self.result.push(' ');
self.print_str(import.name)?;
self.result.push(' ');
self.print_import_ty(state, types, &import.ty, index)?;
self.end_group();
Ok(())
}
fn print_import_ty(
&mut self,
state: &State,
types: &[TypeDef],
ty: &TypeRef,
index: bool,
) -> Result<()> {
use TypeRef::*;
match ty {
Func(f) => {
self.start_group("func");
if index {
self.result.push(' ');
self.print_name(&state.function_names, state.functions.len() as u32)?;
}
self.print_type_ref(state, *f)?;
}
Table(f) => self.print_table_type(state, f, index)?,
Memory(f) => self.print_memory_type(state, f, index)?,
Tag(f) => self.print_tag_type(state, types, f, index)?,
Global(f) => self.print_global_type(state, f, index)?,
}
self.end_group();
Ok(())
}
fn print_table_type(&mut self, state: &State, ty: &TableType, index: bool) -> Result<()> {
self.start_group("table ");
if index {
self.print_name(&state.table_names, state.tables)?;
self.result.push(' ');
}
self.print_limits(ty.initial, ty.maximum)?;
self.result.push(' ');
self.print_valtype(ty.element_type)?;
Ok(())
}
fn print_memory_type(&mut self, state: &State, ty: &MemoryType, index: bool) -> Result<()> {
self.start_group("memory ");
if index {
self.print_name(&state.memory_names, state.memories)?;
self.result.push(' ');
}
if ty.memory64 {
self.result.push_str("i64 ");
}
self.print_limits(ty.initial, ty.maximum)?;
if ty.shared {
self.result.push_str(" shared");
}
Ok(())
}
fn print_tag_type(
&mut self,
state: &State,
types: &[TypeDef],
ty: &TagType,
index: bool,
) -> Result<()> {
self.start_group("tag ");
if index {
write!(self.result, "(;{};)", state.tags)?;
}
self.print_functype_idx(state, types, ty.func_type_idx, true, None)?;
Ok(())
}
fn print_limits<T>(&mut self, initial: T, maximum: Option<T>) -> Result<()>
where
T: fmt::Display,
{
write!(self.result, "{}", initial)?;
if let Some(max) = maximum {
write!(self.result, " {}", max)?;
}
Ok(())
}
fn print_global_type(&mut self, state: &State, ty: &GlobalType, index: bool) -> Result<()> {
self.start_group("global ");
if index {
self.print_name(&state.global_names, state.globals)?;
self.result.push(' ');
}
if ty.mutable {
self.result.push_str("(mut ");
self.print_valtype(ty.content_type)?;
self.result.push(')');
} else {
self.print_valtype(ty.content_type)?;
}
Ok(())
}
fn print_tables(&mut self, state: &mut State, parser: TableSectionReader<'_>) -> Result<()> {
for table in parser {
let table = table?;
self.newline();
self.print_table_type(state, &table, true)?;
self.end_group();
state.tables += 1;
}
Ok(())
}
fn print_memories(&mut self, state: &mut State, parser: MemorySectionReader<'_>) -> Result<()> {
for memory in parser {
let memory = memory?;
self.newline();
self.print_memory_type(state, &memory, true)?;
self.end_group();
state.memories += 1;
}
Ok(())
}
fn print_tags(
&mut self,
state: &mut State,
types: &[TypeDef],
parser: TagSectionReader<'_>,
) -> Result<()> {
for tag in parser {
let tag = tag?;
self.newline();
self.print_tag_type(state, types, &tag, true)?;
self.end_group();
state.tags += 1;
}
Ok(())
}
fn print_globals(
&mut self,
state: &mut State,
types: &[TypeDef],
parser: GlobalSectionReader<'_>,
) -> Result<()> {
for global in parser {
let global = global?;
self.newline();
self.print_global_type(state, &global.ty, true)?;
self.result.push(' ');
self.print_init_expr(state, types, &global.init_expr)?;
self.end_group();
state.globals += 1;
}
Ok(())
}
fn print_code(
&mut self,
state: &mut State,
types: &[TypeDef],
code: &[FunctionBody<'_>],
mut funcs: FunctionSectionReader<'_>,
) -> Result<()> {
if funcs.get_count() != code.len() as u32 {
bail!("mismatch in function and code section counts");
}
for body in code {
let ty = funcs.read()?;
self.newline();
self.start_group("func ");
let func_idx = state.functions.len() as u32;
self.print_name(&state.function_names, func_idx)?;
let params = self
.print_functype_idx(state, types, ty, true, Some(func_idx))?
.unwrap_or(0);
let mut first = true;
let mut local_idx = 0;
let mut locals = NamedLocalPrinter::new("local");
for local in body.get_locals_reader()? {
let (cnt, ty) = local?;
if MAX_LOCALS
.checked_sub(local_idx)
.and_then(|s| s.checked_sub(cnt))
.is_none()
{
bail!("function exceeds the maximum number of locals that can be printed");
}
for _ in 0..cnt {
if first {
self.newline();
first = false;
}
let name = state.local_names.get(&(func_idx, params + local_idx));
locals.start_local(name, &mut self.result);
self.print_valtype(ty)?;
locals.end_local(&mut self.result);
local_idx += 1;
}
}
locals.finish(&mut self.result);
state.labels = 0;
let nesting_start = self.nesting;
let mut reader = body.get_operators_reader()?;
reader.allow_memarg64(true);
while !reader.eof() {
let operator = reader.read()?;
match operator {
// The final `end` in a reader is not printed, it's implied
// in the text format.
Operator::End if reader.eof() => break,
// When we start a block we newline to the current
// indentation, then we increase the indentation so further
// instructions are tabbed over.
Operator::If { .. }
| Operator::Block { .. }
| Operator::Loop { .. }
| Operator::Try { .. } => {
self.newline();
self.nesting += 1;
}
// `else`/`catch` are special in that it's printed at
// the previous indentation, but it doesn't actually change
// our nesting level.
Operator::Else | Operator::Catch { .. } | Operator::CatchAll => {
self.nesting -= 1;
self.newline();
self.nesting += 1;
}
// Exiting a block prints `end` at the previous indentation
// level. `delegate` also ends a block like `end` for `try`.
Operator::End | Operator::Delegate { .. } if self.nesting > nesting_start => {
self.nesting -= 1;
self.newline();
}