-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
1959 lines (1637 loc) · 82.6 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Wasm.Model;
using ModuleSaw;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
namespace WasmStrip {
class ReferenceComparer<T> : IEqualityComparer<T> {
bool IEqualityComparer<T>.Equals (T x, T y) {
return object.ReferenceEquals(x, y);
}
int IEqualityComparer<T>.GetHashCode (T obj) {
return obj.GetHashCode();
}
}
class Config {
public string ModulePath;
public string ReportPath;
public string GraphPath;
public List<Regex> GraphRegexes = new List<Regex>();
public string DiffAgainst;
public string DiffPath;
public string StripOutputPath;
public string StripRetainListPath;
public string StripListPath;
public List<Regex> StripRetainRegexes = new List<Regex>();
public List<Regex> StripRegexes = new List<Regex>();
public string StripReportPath;
public bool VerifyOutput = true;
public string DumpSectionsPath;
public List<Regex> DumpSectionRegexes = new List<Regex>();
public bool DumpFunctions = true, DisassembleFunctions = true;
public string DumpFunctionsPath;
public List<Regex> DumpFunctionRegexes = new List<Regex>();
public string WhatIs;
}
class NamespaceInfo {
public static readonly ReferenceComparer<NamespaceInfo> Comparer = new ReferenceComparer<NamespaceInfo>();
public int Index;
public string Name;
public uint FunctionCount;
public uint SizeBytes;
public HashSet<NamespaceInfo> ChildNamespaces = new HashSet<NamespaceInfo>(Comparer);
}
class FunctionInfoComparer : IEqualityComparer<FunctionInfo> {
public bool Equals (FunctionInfo x, FunctionInfo y) {
return (x.Index == y.Index);
}
public int GetHashCode (FunctionInfo obj) {
unchecked { return (int)obj.Index; }
}
}
class FunctionInfo {
public static readonly FunctionInfoComparer Comparer = new FunctionInfoComparer();
public uint Index;
public uint TypeIndex;
public func_type Type;
public function_body Body;
public string Name;
public int LocalsSize;
public int NumLocals;
}
class Program {
public static Thread MainThread;
public static int Main (string[] _args) {
MainThread = Thread.CurrentThread;
var execStarted = false;
try {
var args = new List<string> (_args);
var config = new Config();
var argErrorCount = 0;
for (int i = 0; i < args.Count; i++) {
var arg = args[i];
if (arg[0] == '@') {
try {
ParseResponseFile(arg.Substring(1), args);
} catch (Exception exc) {
Console.Error.WriteLine($"Error parsing response file '{arg}': {exc}");
argErrorCount++;
}
args.RemoveAt(i--);
} else if (arg.StartsWith("--")) {
if (arg == "--")
break;
ParseOption(arg.Substring(2), config);
args.RemoveAt(i--);
} else {
if (arg.StartsWith('"') && arg.EndsWith('"')) {
arg = arg.Substring(1, arg.Length - 2);
args[i] = arg;
}
try {
if (!File.Exists(arg))
throw new FileNotFoundException(arg);
} catch (Exception exc) {
Console.Error.WriteLine($"Argument error for '{arg}': {exc}");
argErrorCount++;
}
}
}
if (argErrorCount > 0)
return 2;
if (args.Count != 1)
return 1;
config.ModulePath = args[0];
if (string.IsNullOrWhiteSpace(config.ModulePath) || !File.Exists(config.ModulePath)) {
Console.Error.WriteLine($"File not found: '{config.ModulePath}'");
return 3;
}
execStarted = true;
Console.WriteLine($"Processing module {config.ModulePath}...");
var wasmStream = ReadModule(config.ModulePath, out byte[] wasmBytes);
var functions = new Dictionary<uint, FunctionInfo>();
WasmReader wasmReader;
using (wasmStream) {
wasmReader = new WasmReader(wasmStream);
wasmReader.FunctionBodyCallback = (fb, br) => {
var info = ProcessFunctionBody(wasmReader, fb, br, config);
functions[info.Index] = info;
};
Console.Write("Reading module...");
wasmReader.Read();
AssignFunctionNames(functions, wasmReader);
AssignImportNames(wasmReader);
ClearLine("Dumping sections...");
if (config.DumpSectionsPath != null)
DumpSections(config, wasmBytes, wasmReader);
if (!string.IsNullOrEmpty(config.WhatIs)) {
int index = 0;
bool isIndex = false;
if (config.WhatIs.StartsWith("0x"))
isIndex = int.TryParse(config.WhatIs.Substring(2), System.Globalization.NumberStyles.HexNumber, null, out index);
else
isIndex = int.TryParse(config.WhatIs, out index);
if (isIndex) {
var biasedIndex = index - wasmReader.FunctionIndexOffset;
if (functions.TryGetValue((uint)biasedIndex, out var fi))
Console.WriteLine($"table entry {index} = #{fi.Index} {fi.Name}");
else
Console.WriteLine($"No table entry for {index}");
} else {
var fi = functions.Values.FirstOrDefault(f => f.Name.Equals(config.WhatIs, StringComparison.OrdinalIgnoreCase));
if (fi != null)
Console.WriteLine($"#{fi.Index} {fi.Name}");
else
Console.WriteLine($"No functions named {config.WhatIs}");
}
}
ClearLine("Analyzing module.");
AnalysisData data = null;
if ((config.ReportPath != null) || (config.GraphPath != null)) {
var functionArray = new FunctionInfo[functions.Count];
functions.Values.CopyTo(functionArray, 0);
data = new AnalysisData(config, wasmBytes, wasmStream, wasmReader, functionArray);
}
ClearLine("Generating reports...");
if (config.ReportPath != null) {
try {
GenerateReport(config, wasmStream, wasmReader, data, config.ReportPath);
} catch (Exception exc) {
ClearLine();
Console.Error.WriteLine("Failed to generate report:{1}{0}", exc, Environment.NewLine);
Console.WriteLine();
}
}
if (config.GraphPath != null) {
try {
GenerateGraph(config, wasmStream, wasmReader, data, config.GraphPath);
} catch (Exception exc) {
ClearLine();
Console.Error.WriteLine("Failed to generate graph:{1}{0}", exc, Environment.NewLine);
Console.WriteLine();
}
}
ClearLine("Dumping functions... ");
if (config.DumpFunctionsPath != null)
DumpFunctions(config, wasmBytes, wasmReader, functions);
ClearLine("Stripping methods...");
if (config.StripOutputPath != null) {
GenerateStrippedModule(config, wasmBytes, wasmStream, wasmReader, functions);
var shouldReadOutput = config.VerifyOutput || (config.StripReportPath != null);
if (shouldReadOutput) {
var resultFunctions = new Dictionary<uint, FunctionInfo>();
using (var resultReader = ReadModule(config.StripOutputPath, out _)) {
ClearLine("Reading stripped module...");
var resultWasmReader = new WasmReader(resultReader);
resultWasmReader.FunctionBodyCallback = (fb, br) => {
var info = ProcessFunctionBody(resultWasmReader, fb, br, config);
resultFunctions[info.Index] = info;
};
resultWasmReader.Read();
AssignFunctionNames(resultFunctions, resultWasmReader);
if (config.StripReportPath != null) {
ClearLine("Analyzing stripped module.");
var resultArray = new FunctionInfo[resultFunctions.Count];
resultFunctions.Values.CopyTo(resultArray, 0);
var newData = new AnalysisData(config, wasmBytes, resultReader, resultWasmReader, resultArray);
GenerateReport(config, resultReader, resultWasmReader, newData, config.StripReportPath);
}
}
}
}
ClearLine("OK.");
Console.WriteLine();
}
} finally {
if (!execStarted) {
Console.Error.WriteLine("Usage: WasmStrip module.wasm [--option ...] [@response.rsp]");
Console.Error.WriteLine(" --report-out=filename.xml");
Console.Error.WriteLine(" --graph-out=filename.dot");
Console.Error.WriteLine(" --graph-filter=regex [...]");
Console.Error.WriteLine(" --diff-against=oldmodule.wasm --diff-out=filename.csv");
Console.Error.WriteLine(" --dump-sections[=regex] --dump-sections-to=outdir/");
Console.Error.WriteLine(" --dump-functions=regex --dump-functions-to=outdir/");
Console.Error.WriteLine(" --disassemble-only");
Console.Error.WriteLine(" --dump-only");
Console.Error.WriteLine(" --strip-out=newmodule.wasm");
Console.Error.WriteLine(" --strip-section=regex [...]");
Console.Error.WriteLine(" --strip=regex [...]");
Console.Error.WriteLine(" --strip-list=regexes.txt");
Console.Error.WriteLine(" --retain=regex [...]");
Console.Error.WriteLine(" --retain-list=regexes.txt");
Console.Error.WriteLine(" --whatis=(func-index)|0x(hex-func-index)|(func-name)");
}
if (Debugger.IsAttached) {
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
return 0;
}
private static void AssignImportNames (WasmReader wasmReader) {
var imports = wasmReader.Imports.entries;
for (int i = 0; i < imports.Length; i++) {
var import = imports[i];
if (import.kind != external_kind.Function)
continue;
if (wasmReader.FunctionNames.TryGetValue((uint)i, out var s) && !string.IsNullOrWhiteSpace(s))
continue;
wasmReader.FunctionNames[(uint)i] = $"{import.module}.{import.field}";
}
}
private static void AssignFunctionNames (Dictionary<uint, FunctionInfo> functions, WasmReader wasmReader) {
var offset = wasmReader.FunctionIndexOffset;
foreach (var kvp in wasmReader.FunctionNames) {
// FIXME
if (kvp.Key < offset)
continue;
var biasedIndex = kvp.Key - offset;
functions[(uint)biasedIndex].Name = kvp.Value;
}
}
private static BinaryReader ReadModule (string path, out byte[] wasmBytes) {
wasmBytes = File.ReadAllBytes(path);
var stream = new MemoryStream(wasmBytes, false);
return new BinaryReader(stream, Encoding.UTF8, false);
}
private static void ClearLine (string newText = null) {
Console.CursorLeft = 0;
Console.Write(new string(' ', 50));
Console.CursorLeft = 0;
if (newText != null)
Console.Write(newText);
}
private static void EnsureValidPath (string filename) {
var directoryName = Path.GetDirectoryName(filename);
Directory.CreateDirectory(directoryName);
}
private static Stream GetSectionStream (byte[] bytes, SectionHeader header, bool includeHeader) {
var startOffset = includeHeader ? header.StreamHeaderStart - 1 : header.StreamPayloadStart;
var size = (int)(header.StreamPayloadEnd - startOffset);
return new MemoryStream(bytes, (int)startOffset, size, false);
}
private static void GenerateStrippedModule (
Config config, byte[] wasmBytes, BinaryReader wasmStream, WasmReader wasmReader,
Dictionary<uint, FunctionInfo> functions
) {
EnsureValidPath(config.StripOutputPath);
using (var o = new BinaryWriter(File.OpenWrite(config.StripOutputPath), Encoding.UTF8, false)) {
o.BaseStream.SetLength(0);
o.Write((uint)0x6d736100);
o.Write((uint)1);
foreach (var sh in wasmReader.SectionHeaders) {
switch (sh.id) {
case SectionTypes.Code:
using (var sectionScratch = new MemoryStream(1024 * 1024))
using (var sectionScratchWriter = new BinaryWriter(sectionScratch, Encoding.UTF8, true)) {
GenerateStrippedCodeSection(config, wasmBytes, wasmStream, wasmReader, functions, sh, sectionScratchWriter);
sectionScratchWriter.Flush();
o.Write((sbyte)sh.id);
o.WriteLEB((uint)sectionScratch.Length);
o.Flush();
sectionScratch.Position = 0;
sectionScratch.CopyTo(o.BaseStream);
}
break;
default:
using (var ss = GetSectionStream(wasmBytes, sh, true)) {
o.Flush();
ss.Position = 0;
ss.CopyTo(o.BaseStream);
}
break;
}
}
}
}
private static void GenerateStrippedCodeSection (Config config, byte[] wasmBytes, BinaryReader wasmStream, WasmReader wasmReader, Dictionary<uint, FunctionInfo> functions, SectionHeader sh, BinaryWriter output) {
output.WriteLEB((uint)wasmReader.Code.bodies.Length);
var scratchBuffer = new MemoryStream(102400);
foreach (var body in wasmReader.Code.bodies) {
scratchBuffer.Position = 0;
scratchBuffer.SetLength(0);
using (var scratch = new BinaryWriter(scratchBuffer, Encoding.UTF8, true)) {
var fi = functions[body.Index];
var name = fi.Name ?? $"#{body.Index}";
var retain = config.StripRetainRegexes.Any(r => r.IsMatch(name));
var strip = config.StripRegexes.Any(r => r.IsMatch(name));
if (strip && !retain) {
Console.WriteLine($"// Stripping {name}");
GenerateStrippedFunctionBody(body, scratch);
} else {
CopyExistingFunctionBody(wasmBytes, body, scratch);
}
scratch.Flush();
output.WriteLEB((uint)scratchBuffer.Position);
output.Write(scratchBuffer.GetBuffer(), 0, (int)scratchBuffer.Position);
}
}
}
private static void EmitExpression (
BinaryWriter writer, ref Expression e
) {
writer.Write((byte)e.Opcode);
switch (e.Body.Type & ~ExpressionBody.Types.children) {
case ExpressionBody.Types.none:
break;
case ExpressionBody.Types.u32:
writer.WriteLEB(e.Body.U.u32);
break;
case ExpressionBody.Types.u1:
writer.Write((byte)e.Body.U.u32);
break;
case ExpressionBody.Types.i64:
writer.WriteLEB(e.Body.U.i64);
break;
case ExpressionBody.Types.i32:
writer.WriteLEB(e.Body.U.i32);
break;
case ExpressionBody.Types.f64:
writer.Write(e.Body.U.f64);
break;
case ExpressionBody.Types.f32:
writer.Write(e.Body.U.f32);
break;
case ExpressionBody.Types.memory:
writer.WriteLEB(e.Body.U.memory.alignment_exponent);
writer.WriteLEB(e.Body.U.memory.offset);
break;
case ExpressionBody.Types.type:
writer.Write((byte)e.Body.U.type);
break;
case ExpressionBody.Types.br_table:
writer.WriteLEB((uint)e.Body.br_table.target_table.Length);
foreach (var t in e.Body.br_table.target_table)
writer.WriteLEB(t);
writer.WriteLEB(e.Body.br_table.default_target);
break;
default:
throw new NotImplementedException();
}
if (e.Opcode == Opcodes.call_indirect)
throw new NotImplementedException();
if (e.Body.children != null) {
Expression c;
for (int i = 0; i < e.Body.children.Count; i++) {
c = e.Body.children[i];
EmitExpression(writer, ref c);
}
}
}
private static void GenerateStrippedFunctionBody (function_body body, BinaryWriter output) {
output.WriteLEB((uint)0);
var expr = new Expression {
Opcode = Opcodes.unreachable,
State = ExpressionState.Initialized
};
EmitExpression(output, ref expr);
expr.Opcode = Opcodes.end;
EmitExpression(output, ref expr);
}
private static void CopyExistingFunctionBody (byte[] bytes, function_body body, BinaryWriter output) {
using (var fb = GetFunctionBodyStream(bytes, body)) {
output.WriteLEB((uint)body.locals.Length);
foreach (var l in body.locals) {
output.WriteLEB(l.count);
output.Write((byte)l.type);
}
output.Flush();
fb.CopyTo(output.BaseStream);
}
}
private static void DumpSections (Config config, byte[] wasmBytes, WasmReader wasmReader) {
Directory.CreateDirectory(config.DumpSectionsPath);
for (int i = 0; i < wasmReader.SectionHeaders.Count; i++) {
var sh = wasmReader.SectionHeaders[i];
var id = $"{i:00} {sh.id.ToString()} {sh.name ?? ""}".Trim();
var path = Path.Combine(config.DumpSectionsPath, id);
if (config.DumpSectionRegexes.Count > 0) {
if (!config.DumpSectionRegexes.Any((re) => {
if (sh.name != null)
if (re.IsMatch(sh.name))
return true;
return re.IsMatch(sh.id.ToString());
}))
continue;
}
try {
using (var outStream = File.OpenWrite(path)) {
outStream.SetLength(0);
using (var sw = GetSectionStream(wasmBytes, sh, false))
sw.CopyTo(outStream);
}
} catch (Exception exc) {
Console.Error.WriteLine($"Failed to dump section {id}: {exc}");
}
}
}
private static void DumpFunctions (Config config, byte[] wasmBytes, WasmReader wasmReader, Dictionary<uint, FunctionInfo> functions) {
Directory.CreateDirectory(config.DumpFunctionsPath);
int count = 0;
Parallel.ForEach(wasmReader.Code.bodies, (body) => {
var i = Interlocked.Increment(ref count);
if (((i % 5000) == 0) && (i > 0)) {
ClearLine($"Dumping functions... {i}/{functions.Count}");
}
var fi = functions[body.Index];
var indexStr = $"#{body.Index:00000}";
var name = fi.Name ?? indexStr;
if (config.DumpFunctionRegexes.Count > 0) {
if (!config.DumpFunctionRegexes.Any((re) => re.IsMatch(name) || re.IsMatch(indexStr)))
return;
}
var fileName = name.Replace(":", "_").Replace("\\", "_").Replace("/", "_").Replace("<", "(").Replace(">", ")").Replace("?", "_").Replace("*", "_");
if (fileName.Length > 127)
fileName = fileName.Substring(0, 127) + name.GetHashCode().ToString("X8");
var path = Path.Combine(config.DumpFunctionsPath, fileName);
var inBytes = new ArraySegment<byte>(wasmBytes, (int)body.StreamOffset, (int)(body.StreamEnd - body.StreamOffset));
using (var fb = GetFunctionBodyStream(wasmBytes, body)) {
try {
if (config.DumpFunctions)
using (var outStream = File.OpenWrite(path)) {
outStream.SetLength(0);
fb.Position = 0;
fb.CopyTo(outStream);
}
} catch (Exception exc) {
Console.Error.WriteLine($"Failed to dump function {name}: {exc}");
}
path = Path.Combine(config.DumpFunctionsPath, fileName + ".dis");
try {
if (config.DisassembleFunctions)
using (var outStream = File.OpenWrite(path)) {
outStream.SetLength(0);
fb.Position = 0;
DisassembleFunctionBody(
name, fb, fi, inBytes, outStream, wasmReader.FunctionNames, functions,
wasmReader.ImportedFunctionCount, wasmReader.Types.entries
);
}
} catch (Exception exc) {
Console.Error.WriteLine($"Failed to dump function {name}: {exc.Message}");
}
}
});
}
private class DisassembleListener : ExpressionReaderListener {
const int BytesWidth = 16;
int Depth;
public Opcodes LastSeenOpcode;
readonly uint FunctionIndexOffset;
readonly FunctionInfo Function;
readonly func_type[] Types;
readonly Dictionary<uint, string> FunctionNames;
readonly Dictionary<uint, FunctionInfo> Functions;
readonly Stack<long> StartOffsets = new Stack<long>();
readonly Stream Input;
readonly ArraySegment<byte> InputBytes;
readonly StreamWriter Output;
public DisassembleListener (
Stream input, ArraySegment<byte> inputBytes, StreamWriter output, FunctionInfo function,
Dictionary<uint, string> functionNames, Dictionary<uint, FunctionInfo> functions,
uint functionIndexOffset, func_type[] types
) {
FunctionIndexOffset = functionIndexOffset;
Function = function;
FunctionNames = functionNames;
Functions = functions;
Types = types;
Input = input;
InputBytes = inputBytes;
Output = output;
Depth = 0;
}
private string GetIndent (int offset, int depth) {
const int threshold = 24;
if (depth < threshold) {
return new string('.', (Depth * 2) + offset);
} else {
var counter = $"{depth} > ";
return new string('.', (threshold * 2) + offset - counter.Length) + counter;
}
}
private void WriteIndented (int offset, string text) {
Output.Write("{0}{1}", GetIndent(offset, Depth), text);
}
private void WriteIndented (int offset, string format, params object[] args) {
WriteIndented(offset, string.Format(format, args));
}
public void BeginBody (ref Expression expression, bool readingChildNodes) {
if (readingChildNodes) {
Output.WriteLine();
WriteHeader(ref expression);
Output.WriteLine("(");
}
}
public void BeginHeader () {
StartOffsets.Push(Input.Position);
}
static string[] ByteStrings = new string[256];
static DisassembleListener () {
for (int i = 0; i < 256; i++)
ByteStrings[i] = i.ToString("X2");
}
char[] RangeBuffer = new char[10240];
StringBuilder RangeBuilder = new StringBuilder();
private void RangeToBytes (long startOffset, long endOffset, StreamWriter output) {
var sb = RangeBuilder;
sb.Clear();
var position = Input.Position;
var count = (int)(endOffset - startOffset);
sb.AppendFormat("{0:0000} ", startOffset + InputBytes.Offset);
int lineOffset = 0;
for (int i = 0; i < count; i++) {
var b = InputBytes.Array[startOffset + i + InputBytes.Offset];
if (sb.Length - lineOffset >= BytesWidth) {
sb.AppendLine(" ...");
lineOffset = sb.Length;
}
sb.Append(ByteStrings[b]);
}
// HACK
while (sb.Length - lineOffset < BytesWidth)
sb.Append(' ');
sb.CopyTo(0, RangeBuffer, 0, sb.Length);
output.Write(RangeBuffer, 0, sb.Length);
}
private void WriteHeader (ref Expression expression) {
Depth -= 1;
LastSeenOpcode = expression.Opcode;
var startOffset = StartOffsets.Pop();
var endOffset = Input.Position;
RangeToBytes(startOffset, endOffset, Output);
WriteIndented(0, expression.Opcode.ToString() + " ");
if ((expression.Body.Type & ExpressionBody.Types.type) == ExpressionBody.Types.type)
Output.Write($"{expression.Body.U.type} ");
Depth += 1;
}
private Wasm.Model.LanguageTypes GetTypeOfLocal (uint index) {
if (index < Function.Type.param_types.Length)
return Function.Type.param_types[index];
index -= (uint)Function.Type.param_types.Length;
foreach (var l in Function.Body.locals) {
if (index < l.count)
return l.type;
index -= l.count;
}
return LanguageTypes.INVALID;
}
private string GetNameOfLocal (uint index) {
if (index < Function.Type.param_types.Length) {
return $"arg{index}";
}
index -= (uint)Function.Type.param_types.Length;
return $"local{index}";
}
public void EndBody (ref Expression expression, bool readChildNodes, bool successful) {
if (!readChildNodes)
WriteHeader(ref expression);
if (!successful) {
Output.Write("<error>");
Depth -= 1;
} else if (readChildNodes) {
Depth -= 1;
WriteIndented(16, ")");
Output.WriteLine();
Output.WriteLine();
} else {
switch (expression.Opcode) {
case Opcodes.call:
if (expression.Body.U.u32 >= FunctionIndexOffset) {
var funcIndex = expression.Body.U.u32 - FunctionIndexOffset;
if (!Functions.TryGetValue(funcIndex, out FunctionInfo func)) {
Output.WriteLine($"<invalid #{funcIndex}>");
} else {
Output.Write(func.Name ?? $"#{expression.Body.U.u32}");
Output.Write(' ');
Output.WriteLine(GetSignatureForType(func.Type));
}
} else {
FunctionNames.TryGetValue(expression.Body.U.u32, out var importName);
Output.WriteLine(importName ?? $"<import #{expression.Body.U.u32}>");
}
break;
case Opcodes.call_indirect:
var imm = expression.Body.U.call_indirect;
Output.WriteLine($"tables[{imm.table_index}] {GetSignatureForType(Types[imm.sig_index])}");
break;
case Opcodes.get_local:
case Opcodes.set_local:
case Opcodes.tee_local:
Output.WriteLine($"{GetTypeOfLocal(expression.Body.U.u32)} {GetNameOfLocal(expression.Body.U.u32)}");
break;
default:
switch (expression.Body.Type) {
case ExpressionBody.Types.u1:
Output.WriteLine(expression.Body.U.u32);
break;
case ExpressionBody.Types.u32:
if (expression.Body.U.u32 >= 10)
Output.WriteLine($"0x{expression.Body.U.u32:X8} {expression.Body.U.u32}");
else
Output.WriteLine(expression.Body.U.u32);
break;
case ExpressionBody.Types.i64:
Output.WriteLine($"0x{expression.Body.U.i64:X16} {expression.Body.U.i64}");
break;
case ExpressionBody.Types.i32:
if (expression.Body.U.u32 >= 10)
Output.WriteLine($"0x{expression.Body.U.u32:X8} {expression.Body.U.i32}");
else
Output.WriteLine(expression.Body.U.i32);
break;
case ExpressionBody.Types.f64:
Output.WriteLine($"0x{expression.Body.U.u32:X16} {expression.Body.U.f64}");
break;
case ExpressionBody.Types.f32:
Output.WriteLine($"0x{expression.Body.U.u32:X8} {expression.Body.U.f32}");
break;
case ExpressionBody.Types.memory:
if (expression.Body.U.memory.alignment_exponent != 0)
Output.WriteLine($"[{1 << (int)expression.Body.U.memory.alignment_exponent}] +{expression.Body.U.memory.offset}");
else
Output.WriteLine($"+{expression.Body.U.memory.offset}");
break;
case ExpressionBody.Types.type:
break;
case ExpressionBody.Types.br_table:
Output.WriteLine("...");
break;
default:
Output.WriteLine();
break;
}
break;
}
Depth -= 1;
}
}
public void EndHeader (ref Expression expression, bool successful) {
if (!successful) {
StartOffsets.Pop();
if (Depth == 0)
WriteIndented(0, "<eof>" + Environment.NewLine);
else
WriteIndented(Depth, "<error>" + Environment.NewLine);
} else {
Depth += 1;
}
}
}
private static void DisassembleFunctionBody (
string name, Stream stream, FunctionInfo function, ArraySegment<byte> inputBytes, FileStream outStream,
Dictionary<uint, string> functionNames, Dictionary<uint, FunctionInfo> functions, uint functionIndexOffset, func_type[] types
) {
var body = function.Body;
var outWriter = new StreamWriter(outStream, Encoding.UTF8);
outWriter.WriteLine($"{name} ( {string.Join(", ", function.Type.param_types)} ) -> {function.Type.return_type} ({function.Body.body_size} byte(s))");
if (body.locals.Length > 0) {
outWriter.WriteLine($"{body.locals.Sum(l => l.count)} local(s)");
foreach (var l in body.locals)
outWriter.WriteLine($" {l.type} x{l.count}");
}
outWriter.WriteLine();
try {
var fbr = new BinaryReader(stream, Encoding.UTF8, true);
var er = new ExpressionReader(fbr);
var listener = new DisassembleListener(stream, inputBytes, outWriter, function, functionNames, functions, functionIndexOffset, types);
while (true) {
Expression expr;
if (!er.TryReadExpression(out expr, listener))
break;
if (!er.TryReadExpressionBody(ref expr, listener))
break;
}
if (listener.LastSeenOpcode != Opcodes.end)
outWriter.WriteLine("ERROR: Function body did not end with an 'end' opcode");
outWriter.Flush();
} catch (Exception exc) {
outWriter.WriteLine();
outWriter.WriteLine("ERROR: Exception while disassembling function");
outWriter.WriteLine(exc);
outWriter.Flush();
throw;
}
}
private class AnalysisData {
public readonly FunctionInfo[] Functions;
public readonly Dictionary<string, NamespaceInfo> Namespaces;
public readonly Dictionary<FunctionInfo, FunctionInfo[]> DirectDependencies;
public readonly DependencyGraphNode[] DependencyGraph;
public readonly int[] OpcodeCounts = new int[0xFFFF];
public readonly Dictionary<string, object> RawData;
public AnalysisData (Config config, byte[] wasmBytes, BinaryReader wasmStream, WasmReader wasmReader, FunctionInfo[] functions) {
Functions = functions;
Namespaces = ComputeNamespaceSizes(this);
Console.Write(".");
DirectDependencies = ComputeDirectDependencies(config, wasmBytes, wasmStream, wasmReader, this);
Console.Write(".");
DependencyGraph = ComputeDependencyGraph(config, wasmStream, wasmReader, this);
Console.Write(".");
RawData = ComputeRawData(config, wasmBytes, wasmStream, wasmReader, this);
}
public bool TryGetFunction (uint index, out FunctionInfo result) {
result = default(FunctionInfo);
if ((index < 0) || (index >= Functions.Length))
return false;
result = Functions[index];
return true;
}
private class RawDataListener : ExpressionReaderListener {
public int[] OpcodeCounts;
public int[] SmallBlockCounts = new int[8];
public int AverageBlockLengthSum, BlockCount;
public int GetLocalRuns, SetLocalRuns, DupCandidates, MaxRunSize, RunCount, AverageRunLengthSum;
public int SimpleI32Memops;
int CurrentRunSize;
Expression PreviousExpression = default(Expression);
public RawDataListener () {
}
public void BeginBody (ref Expression expression, bool readingChildNodes) {
}
public void BeginHeader () {
}
private void WriteHeader (ref Expression expression) {
}
private void ResetRun () {
if (CurrentRunSize != 0) {
AverageRunLengthSum += CurrentRunSize;
RunCount++;
}
CurrentRunSize = 0;
}
public void EndBody (ref Expression expression, bool readChildNodes, bool successful) {
OpcodeCounts[(int)expression.Opcode]++;
if (expression.Body.Type == ExpressionBody.Types.children) {
var count = expression.Body.children?.Count ?? 0;
BlockCount++;
if (count < SmallBlockCounts.Length)
SmallBlockCounts[count]++;
AverageBlockLengthSum += count;
}
var isLoad = (expression.Opcode >= OpcodesInfo.FirstLoad) && (expression.Opcode <= OpcodesInfo.LastLoad);
var isStore = (expression.Opcode >= OpcodesInfo.FirstStore) && (expression.Opcode <= OpcodesInfo.LastStore);
if (expression.Opcode == PreviousExpression.Opcode) {
if (expression.Opcode == Opcodes.get_local) {
GetLocalRuns++;
CurrentRunSize++;
} else if (expression.Opcode == Opcodes.set_local) {
SetLocalRuns++;
CurrentRunSize++;
} else {
ResetRun();
}
} else if (
(
// FIXME: Inaccurate
(expression.Opcode == Opcodes.get_local) ||
(expression.Opcode == Opcodes.get_global)
) &&
(
(PreviousExpression.Opcode == Opcodes.set_local) ||
(PreviousExpression.Opcode == Opcodes.tee_local) ||
(PreviousExpression.Opcode == Opcodes.set_global)
)
) {
ResetRun();
if (expression.Body.U.i32 == PreviousExpression.Body.U.i32)
DupCandidates++;
} else if (
(
(expression.Opcode == Opcodes.i32_load) ||
(expression.Opcode == Opcodes.i32_store)
) &&
(
(PreviousExpression.Opcode == Opcodes.get_local) ||
(PreviousExpression.Opcode == Opcodes.tee_local) ||
(PreviousExpression.Opcode == Opcodes.get_global)
)
) {
ResetRun();
SimpleI32Memops++;
} else {
ResetRun();
}
MaxRunSize = Math.Max(MaxRunSize, CurrentRunSize);
PreviousExpression = expression;
}
public void EndHeader (ref Expression expression, bool successful) {
}
}
private Dictionary<string, object> ComputeRawData (Config config, byte[] wasmBytes, BinaryReader wasmStream, WasmReader wasmReader, AnalysisData analysisData) {
var listener = new RawDataListener {
OpcodeCounts = analysisData.OpcodeCounts
};