-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtest_parser.cpp
5978 lines (5511 loc) · 289 KB
/
test_parser.cpp
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
#include "gtest/gtest.h"
#include "pochivm/common.h"
#include "pochivm/error_context.h"
#include "pochivm/codegen_arena_allocator.h"
#include "fastinterp/fastinterp_helper.h"
#include "fastinterp/fastinterp_codegen_helper.h"
#include "fastinterp/wasm_memory_ptr.h"
#include "wasi_impl.h"
#include <unistd.h>
#include <asm/prctl.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
namespace PochiVM
{
class ShallowStream
{
public:
// Read a directly-encoded integer or floating point value
// This function assumes that the binary is well-formatted (i.e. the module has passed validation).
//
template<typename T>
T WARN_UNUSED ReadScalar()
{
static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "T must be integral or floating point");
assert(m_current + sizeof(T) <= m_end);
T result;
memcpy(&result, reinterpret_cast<void*>(m_current), sizeof(T));
m_current += sizeof(T);
return result;
}
template<typename T>
T WARN_UNUSED PeekScalar()
{
static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "T must be integral or floating point");
assert(m_current + sizeof(T) <= m_end);
T result;
memcpy(&result, reinterpret_cast<void*>(m_current), sizeof(T));
return result;
}
// Read a LEB-encoded integer value
// This function assumes that the binary is well-formatted (i.e. the module has passed validation).
//
template<typename T>
T WARN_UNUSED ReadIntLeb()
{
static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "T must be integral");
using U = typename std::make_unsigned<T>::type;
uint32_t shift = 0;
U result = 0;
while (true)
{
assert(shift < sizeof(T) * 8);
uint8_t value = *reinterpret_cast<uint8_t*>(m_current);
result |= static_cast<U>(value & 0x7f) << shift;
shift += 7;
m_current++;
if ((value & 0x80) == 0)
{
// If the type is signed and the value is negative, do sign extension
//
if constexpr(std::is_signed<T>::value)
{
if ((value & 0x40) && shift < sizeof(T) * 8)
{
result |= (~static_cast<U>(0)) << shift;
}
}
break;
}
}
assert(m_current <= m_end);
return static_cast<T>(result);
}
// Read a wasm string. The string is shallow (not copied).
// This function assumes that the binary is well-formatted (i.e. the module has passed validation).
//
std::pair<uint32_t, const char*> WARN_UNUSED ReadShallowString()
{
uint32_t length = ReadIntLeb<uint32_t>();
const char* s = reinterpret_cast<const char*>(m_current);
m_current += length;
assert(m_current <= m_end);
return std::make_pair(length, s);
}
#ifndef NDEBUG
bool WARN_UNUSED HasMore() const
{
return m_current < m_end;
}
#endif
void SkipBytes(size_t numBytes)
{
m_current += numBytes;
assert(m_current <= m_end);
}
ShallowStream GetShallowStreamFromNow(size_t length)
{
assert(m_current + length <= m_end);
return ShallowStream(m_current, length);
}
friend class MemoryMappedFile;
private:
ShallowStream(uintptr_t start, size_t DEBUG_ONLY(length))
: m_current(start)
#ifndef NDEBUG
, m_end(start + length)
#endif
{ }
uintptr_t m_current;
#ifndef NDEBUG
uintptr_t m_end;
#endif
};
class MemoryMappedFile : NonCopyable, NonMovable
{
public:
MemoryMappedFile()
: m_fd(-1), m_file(nullptr)
{ }
~MemoryMappedFile()
{
if (m_fd != -1 || m_file != nullptr)
{
munmap(reinterpret_cast<void*>(m_start), m_length);
if (m_fd != -1)
{
close(m_fd);
m_fd = -1;
}
if (m_file != nullptr)
{
fclose(m_file);
}
}
}
bool WARN_UNUSED IsInitalized() const { return m_fd != -1 || m_file != nullptr; }
bool WARN_UNUSED Open(const char* file)
{
assert(!IsInitalized());
//#define INPUT_USE_MMAP
#ifdef INPUT_USE_MMAP
bool success = false;
m_fd = open(file, O_RDONLY);
if (m_fd == -1)
{
int err = errno;
REPORT_ERR("Failed to open file '%s' for mmap, error %d(%s).", file, err, strerror(err));
return false;
}
Auto(
if (!success) { close(m_fd); m_fd = -1; }
);
{
struct stat s;
int status = fstat(m_fd, &s);
if (status != 0)
{
assert(status == -1);
int err = errno;
REPORT_ERR("Failed to fstat file '%s', error %d(%s).", file, err, strerror(err));
return false;
}
m_length = static_cast<size_t>(s.st_size);
}
void* result = mmap(nullptr, m_length, PROT_READ, MAP_PRIVATE, m_fd, 0 /*offset*/);
if (result == MAP_FAILED)
{
int err = errno;
REPORT_ERR("Failed to mmap file '%s', error %d(%s).", file, err, strerror(err));
return false;
}
assert(result != nullptr);
m_start = reinterpret_cast<uintptr_t>(result);
success = true;
return true;
#else
bool success = false;
m_file = fopen(file, "r");
if (m_file == nullptr)
{
int err = errno;
REPORT_ERR("Failed to open file '%s' for mmap, error %d(%s).", file, err, strerror(err));
return false;
}
Auto(
if (!success) { fclose(m_file); m_file = nullptr; }
);
fseek(m_file, 0, SEEK_END);
m_length = static_cast<size_t>(ftell(m_file));
fseek(m_file, 0, SEEK_SET);
void* result = mmap(nullptr, m_length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
if (result == MAP_FAILED)
{
ReleaseAssert(false && "Out Of Memory");
}
assert(result != nullptr);
fread(result, 1, m_length, m_file);
m_start = reinterpret_cast<uintptr_t>(result);
success = true;
return true;
#endif
}
ShallowStream GetShallowStream()
{
return ShallowStream(m_start, m_length);
}
bool WARN_UNUSED HasMore(const ShallowStream& s)
{
assert(m_start <= s.m_current && s.m_current <= m_start + m_length);
assert(s.m_end == m_start + m_length);
return s.m_current < m_start + m_length;
}
private:
int m_fd;
FILE* m_file;
uintptr_t m_start;
size_t m_length;
};
// Order is hardcoded!
//
enum class WasmValueType : uint8_t
{
I32,
I64,
F32,
F64,
X_END_OF_ENUM
};
struct WasmValueTypeHelper
{
static WasmValueType ALWAYS_INLINE WARN_UNUSED Parse(ShallowStream& reader)
{
// valtype::= 0x7F => i32, 0x7E => i64, 0x7D => f32, 0x7C => f64
//
uint8_t value = reader.ReadScalar<uint8_t>();
value ^= 0x7f;
assert(value < 4);
return static_cast<WasmValueType>(value);
}
static bool IsIntegral(WasmValueType t)
{
assert(t < WasmValueType::X_END_OF_ENUM);
return t <= WasmValueType::I64;
}
static bool IsFloatingPoint(WasmValueType t)
{
return !IsIntegral(t);
}
};
struct WasmFunctionType
{
void ALWAYS_INLINE Parse(TempArenaAllocator& alloc, ShallowStream& reader)
{
// https://webassembly.github.io/spec/core/binary/types.html#binary-functype
// Function types are encoded by the byte 0x60 followed by the respective vectors of parameter and result types.
//
uint8_t magic = reader.ReadScalar<uint8_t>();
assert(magic == 0x60);
std::ignore = magic;
m_numParams = reader.ReadIntLeb<uint32_t>();
m_numIntParams = 0;
m_numFloatParams = 0;
WasmValueType* tmp = reinterpret_cast<WasmValueType*>(alloca(sizeof(WasmValueType) * m_numParams));
for (uint32_t i = 0; i < m_numParams; i++)
{
tmp[i] = WasmValueTypeHelper::Parse(reader);
if (tmp[i] == WasmValueType::I32 || tmp[i] == WasmValueType::I64)
{
m_numIntParams++;
}
else
{
m_numFloatParams++;
}
}
m_numReturns = reader.ReadIntLeb<uint32_t>();
if (m_numReturns > 1)
{
TestAssert(false && "multiple-value extension is currently not supported");
}
m_types = new (std::align_val_t(1), alloc) WasmValueType[m_numParams + m_numReturns];
memcpy(m_types, tmp, sizeof(WasmValueType) * m_numParams);
for (uint32_t i = 0; i < m_numReturns; i++)
{
m_types[m_numParams + i] = WasmValueTypeHelper::Parse(reader);
}
}
WasmValueType GetParamType(uint32_t i) const
{
assert(i < m_numParams);
return m_types[i];
}
WasmValueType GetReturnType(uint32_t i) const
{
assert(i < m_numReturns);
return m_types[m_numParams + i];
}
uint32_t m_numParams;
uint32_t m_numReturns;
uint32_t m_numIntParams;
uint32_t m_numFloatParams;
WasmValueType* m_types;
};
class WasmFunctionTypeSection
{
public:
WasmFunctionTypeSection()
: m_numFunctionTypes(0)
, m_functionTypes(nullptr)
{ }
// Parse the function types section.
// 'reader' should be the exact range of this section.
//
void ParseSection(TempArenaAllocator& alloc, ShallowStream reader)
{
// https://webassembly.github.io/spec/core/binary/modules.html#binary-typesec
// The type section has the id 1. It decodes into a vector of function types that represent the types component of a module.
//
m_numFunctionTypes = reader.ReadIntLeb<uint32_t>();
m_functionTypes = new (alloc) WasmFunctionType[m_numFunctionTypes];
for (uint32_t i = 0; i < m_numFunctionTypes; i++)
{
m_functionTypes[i].Parse(alloc, reader);
}
assert(!reader.HasMore());
}
uint32_t GetNumFunctionTypes() const
{
return m_numFunctionTypes;
}
WasmFunctionType GetFunctionTypeFromIdx(uint32_t typeIdx)
{
assert(typeIdx < m_numFunctionTypes);
return m_functionTypes[typeIdx];
}
private:
uint32_t m_numFunctionTypes;
WasmFunctionType* m_functionTypes;
};
struct WasmImportedEntityName
{
uint32_t m_lv1NameLen;
uint32_t m_lv2NameLen;
const char* m_lv1Name;
const char* m_lv2Name;
void ALWAYS_INLINE Parse(ShallowStream& reader)
{
// https://webassembly.github.io/spec/core/binary/modules.html#binary-import
//
std::tie(m_lv1NameLen, m_lv1Name) = reader.ReadShallowString();
std::tie(m_lv2NameLen, m_lv2Name) = reader.ReadShallowString();
}
};
struct WasmTableOrMemoryLimit
{
uint32_t m_minSize;
uint32_t m_maxSize;
WasmTableOrMemoryLimit()
: m_minSize(0)
, m_maxSize(std::numeric_limits<uint32_t>::max())
{ }
void ALWAYS_INLINE Parse(ShallowStream& reader)
{
// https://webassembly.github.io/spec/core/binary/types.html#binary-limits
//
uint8_t kind = reader.ReadScalar<uint8_t>();
m_minSize = reader.ReadIntLeb<uint32_t>();
if (kind == 0)
{
m_maxSize = std::numeric_limits<uint32_t>::max();
}
else
{
assert(kind == 1);
m_maxSize = reader.ReadIntLeb<uint32_t>();
assert(m_minSize <= m_maxSize);
}
}
};
struct WasmGlobal
{
void ALWAYS_INLINE Parse(ShallowStream& reader)
{
m_valueType = WasmValueTypeHelper::Parse(reader);
uint8_t isMut = reader.ReadScalar<uint8_t>();
assert(isMut == 0 || isMut == 1);
m_isMutable = isMut;
}
WasmValueType m_valueType;
bool m_isMutable;
};
class WasmImportSection
{
public:
WasmImportSection()
: m_numImportedFunctions(0)
, m_numImportedGlobals(0)
, m_totalImports(0)
, m_isTableImported(false)
, m_isMemoryImported(false)
{ }
void ParseSection(TempArenaAllocator& alloc, ShallowStream reader)
{
// https://webassembly.github.io/spec/core/binary/modules.html#binary-importsec
//
uint32_t totalImports = reader.ReadIntLeb<uint32_t>();
m_totalImports = totalImports;
m_numImportedFunctions = 0;
m_numImportedGlobals = 0;
m_importNames = new (alloc) WasmImportedEntityName[totalImports + 2];
m_importedFunctionTypes = new (alloc) uint32_t[totalImports];
m_importedGlobalTypes = new (alloc) WasmGlobal[totalImports];
for (uint32_t i = 0; i < totalImports; i++)
{
WasmImportedEntityName name;
name.Parse(reader);
uint8_t importType = reader.ReadScalar<uint8_t>();
if (importType == 0)
{
// function type
//
m_importedFunctionTypes[m_numImportedFunctions] = reader.ReadIntLeb<uint32_t>();
m_importNames[m_numImportedFunctions] = name;
m_numImportedFunctions++;
}
else if (importType == 3)
{
// global type
//
m_importNames[m_totalImports - 1 - m_numImportedGlobals] = name;
m_importedGlobalTypes[m_numImportedGlobals].Parse(reader);
m_numImportedGlobals++;
}
else if (importType == 1)
{
// table type
//
assert(!m_isTableImported);
m_isTableImported = true;
m_importNames[m_totalImports] = name;
uint8_t magic;
magic = reader.ReadScalar<uint8_t>();
assert(magic == 0x70);
std::ignore = magic;
m_importedTableLimit.Parse(reader);
}
else if (importType == 2)
{
// memory type
//
assert(!m_isMemoryImported);
m_isMemoryImported = true;
m_importNames[m_totalImports + 1] = name;
m_importedMemoryLimit.Parse(reader);
}
else
{
assert(false);
}
}
assert(!reader.HasMore());
}
bool IsTableImported() const { return m_isTableImported; }
bool IsMemoryImported() const { return m_isMemoryImported; }
WasmImportedEntityName GetImportedTableName() const { assert(IsTableImported()); return m_importNames[m_totalImports]; }
WasmTableOrMemoryLimit GetImportedTableLimit() const { assert(IsTableImported()); return m_importedTableLimit; }
WasmImportedEntityName GetImportedMemoryName() const { assert(IsMemoryImported()); return m_importNames[m_totalImports + 1]; }
WasmTableOrMemoryLimit GetImportedMemoryLimit() const { assert(IsMemoryImported()); return m_importedMemoryLimit; }
WasmImportedEntityName GetImportedFunctionName(uint32_t funcIdx) const
{
assert(funcIdx < m_numImportedFunctions);
return m_importNames[funcIdx];
}
uint32_t GetImportedFunctionType(uint32_t funcIdx) const
{
assert(funcIdx < m_numImportedFunctions);
return m_importedFunctionTypes[funcIdx];
}
WasmImportedEntityName GetImportedGlobalName(uint32_t globalIdx) const
{
assert(globalIdx < m_numImportedGlobals);
return m_importNames[m_totalImports - 1 - globalIdx];
}
WasmGlobal GetImportedGlobalType(uint32_t globalIdx) const
{
assert(globalIdx < m_numImportedGlobals);
return m_importedGlobalTypes[globalIdx];
}
uint32_t GetNumImportedFunctions() const { return m_numImportedFunctions; }
uint32_t* GetImportedFunctionTypesArray() const { return m_importedFunctionTypes; }
uint32_t GetNumImportedGlobals() const { return m_numImportedGlobals; }
WasmGlobal* GetImportedGlobalTypesArray() const { return m_importedGlobalTypes; }
private:
// Imports may show up in any order, but we don't want to use std::vector for dynamic-length array for performance reasons.
// So internally, we layout the entities as
// [imported functions] [padding] [imported globals in reverse order] [imported table] [imported memory]
// imported table is always at #numImports and importedMemory is always at #numImports+1
//
uint32_t m_numImportedFunctions;
uint32_t m_numImportedGlobals;
WasmImportedEntityName* m_importNames;
uint32_t* m_importedFunctionTypes;
WasmGlobal* m_importedGlobalTypes;
// WASM spec atm only allows up to 1 memory/table
//
WasmTableOrMemoryLimit m_importedTableLimit;
WasmTableOrMemoryLimit m_importedMemoryLimit;
uint32_t m_totalImports;
bool m_isTableImported;
bool m_isMemoryImported;
};
struct WasmFunctionDeclarationSection
{
void ParseEmptySection(WasmImportSection* imports)
{
m_numImportedFunctions = imports->GetNumImportedFunctions();
m_numFunctions = m_numImportedFunctions;
m_functionDeclarations = imports->GetImportedFunctionTypesArray();
}
void ParseSection(TempArenaAllocator& alloc, ShallowStream reader, WasmImportSection* imports)
{
uint32_t numInternalFuncs = reader.ReadIntLeb<uint32_t>();
m_numImportedFunctions = imports->GetNumImportedFunctions();
m_numFunctions = m_numImportedFunctions + numInternalFuncs;
m_functionDeclarations = new (alloc) uint32_t[m_numFunctions];
m_functionStackSize = new (alloc) uint32_t[m_numFunctions];
m_functionEntryPoint = new (alloc) uint8_t*[m_numFunctions];
memcpy(m_functionDeclarations, imports->GetImportedFunctionTypesArray(), sizeof(uint32_t) * m_numImportedFunctions);
for (uint32_t i = m_numImportedFunctions; i < m_numFunctions; i++)
{
m_functionDeclarations[i] = reader.ReadIntLeb<uint32_t>();
}
assert(!reader.HasMore());
}
bool IsFunctionIdxImported(uint32_t functionIdx) const
{
assert(functionIdx < m_numFunctions);
return functionIdx < m_numImportedFunctions;
}
uint32_t GetFunctionTypeIdxFromFunctionIdx(uint32_t functionIdx) const
{
assert(functionIdx < m_numFunctions);
return m_functionDeclarations[functionIdx];
}
uint32_t m_numFunctions;
uint32_t m_numImportedFunctions;
// m_functionDeclarations[i] is the function type index of function i
// [0, m_numImportedFunctions) are imported functions
//
uint32_t* m_functionDeclarations;
uint32_t* m_functionStackSize;
uint8_t** m_functionEntryPoint;
};
struct WasmTableSection
{
WasmTableSection()
: m_hasTable(false)
{ }
void ParseSection(ShallowStream reader)
{
uint32_t numTables = reader.ReadIntLeb<uint32_t>();
// current WASM spec allows up to 1 table.
//
assert(numTables <= 1);
if (numTables == 1)
{
m_hasTable = true;
uint8_t magic;
magic = reader.ReadScalar<uint8_t>();
assert(magic == 0x70);
std::ignore = magic;
m_limit.Parse(reader);
assert(m_limit.m_minSize == m_limit.m_maxSize);
}
assert(!reader.HasMore());
}
WasmTableOrMemoryLimit m_limit;
bool m_hasTable;
};
struct WasmMemorySection
{
WasmMemorySection()
: m_hasMemory(false)
{ }
void ParseSection(ShallowStream reader)
{
uint32_t numMemories = reader.ReadIntLeb<uint32_t>();
// current WASM spec allows up to 1 memory
//
assert(numMemories <= 1);
if (numMemories == 1)
{
m_hasMemory = true;
m_limit.Parse(reader);
}
assert(!reader.HasMore());
}
WasmTableOrMemoryLimit m_limit;
bool m_hasMemory;
};
class WasmConstantExpression
{
public:
void ALWAYS_INLINE Parse(ShallowStream& reader
#ifndef NDEBUG
, WasmValueType valueType
, uint32_t globalLimit
#endif
)
{
uint8_t opcode = reader.ReadScalar<uint8_t>();
if (opcode == 0x23)
{
// global.get
//
m_isInitByGlobal = true;
m_globalIdx = reader.ReadIntLeb<uint32_t>();
assert(m_globalIdx < globalLimit);
}
else
{
// must be a 't.const' matching expected type
//
assert(opcode == 0x41 + static_cast<uint8_t>(valueType));
WasmValueType globalType = static_cast<WasmValueType>(opcode - 0x41);
m_isInitByGlobal = false;
// For integers, the operand is encoded as *signed* integers
//
if (globalType == WasmValueType::I32)
{
int32_t value = reader.ReadIntLeb<int32_t>();
memcpy(m_initRawBytes, &value, 4);
}
else if (globalType == WasmValueType::I64)
{
int64_t value = reader.ReadIntLeb<int64_t>();
memcpy(m_initRawBytes, &value, 8);
}
else if (globalType == WasmValueType::F32)
{
static_assert(sizeof(float) == 4);
float value = reader.ReadScalar<float>();
memcpy(m_initRawBytes, &value, 4);
}
else
{
assert(globalType == WasmValueType::F64);
static_assert(sizeof(double) == 8);
double value = reader.ReadScalar<double>();
memcpy(m_initRawBytes, &value, 8);
}
}
// The next opcode must be an 'end' opcode
//
{
uint8_t endOpcode = reader.ReadScalar<uint8_t>();
assert(endOpcode == 0x0B);
std::ignore = endOpcode;
}
}
// https://webassembly.github.io/spec/core/valid/instructions.html#valid-constant
// A WASM constant expression must be either a 't.const c' or a 'global.get x'
//
// Whether this constant is initialized by a global
//
bool m_isInitByGlobal;
// If yes, the idx of the global
//
uint32_t m_globalIdx;
// Otherwise, the constant bytes to initialize this value
//
char m_initRawBytes[8];
};
struct WasmGlobalSection
{
void ParseEmptySection(WasmImportSection* imports)
{
m_numImportedGlobals = imports->GetNumImportedGlobals();
m_numGlobals = m_numImportedGlobals;
m_globals = imports->GetImportedGlobalTypesArray();
m_initExprs = nullptr;
}
void ParseSection(TempArenaAllocator& alloc, ShallowStream reader, WasmImportSection* imports)
{
uint32_t numInternalGlobals = reader.ReadIntLeb<uint32_t>();
m_numImportedGlobals = imports->GetNumImportedGlobals();
m_numGlobals = m_numImportedGlobals + numInternalGlobals;
m_globals = new (alloc) WasmGlobal[m_numGlobals];
memcpy(m_globals, imports->GetImportedGlobalTypesArray(), sizeof(WasmGlobal) * m_numImportedGlobals);
m_initExprs = new (alloc) WasmConstantExpression[numInternalGlobals];
for (uint32_t i = 0; i < numInternalGlobals; i++)
{
m_globals[m_numImportedGlobals + i].Parse(reader);
// https://webassembly.github.io/spec/core/valid/instructions.html#expressions
// Currently, constant expressions occurring as initializers of globals are further constrained
// in that contained global.get instructions are only allowed to refer to imported globals.
//
m_initExprs[i].Parse(reader
#ifndef NDEBUG
, m_globals[m_numImportedGlobals + i].m_valueType
, m_numImportedGlobals /*globalLimit*/
#endif
);
}
assert(!reader.HasMore());
}
uint32_t m_numGlobals;
uint32_t m_numImportedGlobals;
WasmGlobal* m_globals;
// init expressions for each non-imported global
//
WasmConstantExpression* m_initExprs;
};
struct WasmExportedEntity
{
uint32_t m_entityIdx;
uint32_t m_length;
const char* m_name;
};
struct WasmExportSection
{
WasmExportSection()
: m_numFunctionsExported(0)
, m_numGlobalsExported(0)
, m_exportedFunctions(nullptr)
, m_exportedGlobals(nullptr)
, m_exportedTable(nullptr)
, m_exportedMemory(nullptr)
{ }
void ParseSection(TempArenaAllocator& alloc, ShallowStream reader)
{
uint32_t totalExports = reader.ReadIntLeb<uint32_t>();
m_exportedFunctions = new (alloc) WasmExportedEntity[totalExports];
m_exportedFunctionAddresses = new (alloc) uint8_t*[totalExports];
m_exportedGlobals = new (alloc) WasmExportedEntity[totalExports];
for (uint32_t i = 0; i < totalExports; i++)
{
WasmExportedEntity entity;
std::tie(entity.m_length, entity.m_name) = reader.ReadShallowString();
uint8_t exportType = reader.ReadScalar<uint8_t>();
entity.m_entityIdx = reader.ReadIntLeb<uint32_t>();
if (exportType == 0)
{
// function export
//
m_exportedFunctions[m_numFunctionsExported] = entity;
m_numFunctionsExported++;
}
else if (exportType == 3)
{
// global export
//
m_exportedGlobals[m_numGlobalsExported] = entity;
m_numGlobalsExported++;
}
else if (exportType == 1)
{
// table export
//
assert(entity.m_entityIdx == 0 && m_exportedTable == nullptr);
m_exportedTable = new (alloc) WasmExportedEntity;
*m_exportedTable = entity;
}
else
{
assert(exportType == 2);
// memory export
//
assert(entity.m_entityIdx == 0 && m_exportedMemory == nullptr);
m_exportedMemory = new (alloc) WasmExportedEntity;
*m_exportedMemory = entity;
}
}
assert(!reader.HasMore());
}
bool IsTableExported() const { return m_exportedTable != nullptr; }
bool IsMemoryExported() const { return m_exportedMemory != nullptr; }
WasmExportedEntity GetExportedTable() const { assert(IsTableExported()); return *m_exportedTable; }
WasmExportedEntity GetExportedMemory() const { assert(IsMemoryExported()); return *m_exportedMemory; }
uint32_t m_numFunctionsExported;
uint32_t m_numGlobalsExported;
WasmExportedEntity* m_exportedFunctions;
uint8_t** m_exportedFunctionAddresses;
WasmExportedEntity* m_exportedGlobals;
WasmExportedEntity* m_exportedTable;
WasmExportedEntity* m_exportedMemory;
};
struct WasmStartSection
{
WasmStartSection()
: m_hasStartFunction(false)
{ }
void ParseSection(ShallowStream reader)
{
m_hasStartFunction = true;
m_startFunctionIdx = reader.ReadIntLeb<uint32_t>();
assert(!reader.HasMore());
}
bool m_hasStartFunction;
uint32_t m_startFunctionIdx;
};
struct WasmElementRecord
{
void Parse(TempArenaAllocator& alloc, ShallowStream& reader)
{
uint32_t tableIdx = reader.ReadIntLeb<uint32_t>();
assert(tableIdx == 0);
std::ignore = tableIdx;
m_offset.Parse(reader
#ifndef NDEBUG
, WasmValueType::I32 /*valueType*/
, static_cast<uint32_t>(-1) /*globalLimit*/
#endif
);
uint32_t length = reader.ReadIntLeb<uint32_t>();
m_length = length;
m_contents = new (alloc) uint32_t[length];
for (uint32_t i = 0; i < length; i++)
{
m_contents[i] = reader.ReadIntLeb<uint32_t>();
}
}
WasmConstantExpression m_offset;
uint32_t m_length;
uint32_t* m_contents;
};
struct WasmElementSection
{
WasmElementSection()
: m_numRecords(0)
{ }
void ParseSection(TempArenaAllocator& alloc, ShallowStream reader)
{
m_numRecords = reader.ReadIntLeb<uint32_t>();
m_records = new (alloc) WasmElementRecord[m_numRecords];
for (uint32_t i = 0; i < m_numRecords; i++)
{
m_records[i].Parse(alloc, reader);
}
assert(!reader.HasMore());
}
uint32_t m_numRecords;
WasmElementRecord* m_records;
};
struct WasmDataRecord
{
void Parse(ShallowStream& reader)
{
uint32_t memoryIdx = reader.ReadIntLeb<uint32_t>();
assert(memoryIdx == 0);
std::ignore = memoryIdx;
m_offset.Parse(reader
#ifndef NDEBUG
, WasmValueType::I32 /*valueType*/
, static_cast<uint32_t>(-1) /*globalLimit*/
#endif
);
std::tie(m_length, m_contents) = reader.ReadShallowString();
}
WasmConstantExpression m_offset;
uint32_t m_length;
const char* m_contents;
};
enum class WasmSectionId
{
CUSTOM_SECTION = 0,
TYPE_SECTION = 1,
IMPORT_SECTION = 2,
FUNCTION_SECTION = 3,
TABLE_SECTION = 4,
MEMORY_SECTION = 5,
GLOBAL_SECTION = 6,
EXPORT_SECTION = 7,
START_SECTION = 8,
ELEMENT_SECTION = 9,
CODE_SECTION = 10,
DATA_SECTION = 11,
X_END_OF_ENUM = 12
};
enum class WasmOpcodeOperandKind : uint8_t
{
NONE, // has no operands
U32, // one u32
MEM_U32_U32, // two u32, but only second operand is useful
CONST, // t.const
BLOCKTYPE, // one s33
SPECIAL
};
struct alignas(8) WasmOpcodeInfo
{
constexpr WasmOpcodeInfo()
: m_isValid(false), m_isSpecial(false), m_numIntConsumes(0)
, m_numFloatConsumes(0), m_hasOutput(false), m_isOutputIntegral(false)
, m_outputType(WasmValueType::I32), m_operandKind(WasmOpcodeOperandKind::NONE)
{ }
constexpr WasmOpcodeInfo(bool isValid, bool isSpecial, uint8_t numIntConsumes,
uint8_t numFloatConsumes, bool hasOutput, bool isOutputIntegral,
WasmValueType outputType, WasmOpcodeOperandKind operandKind)
: m_isValid(isValid), m_isSpecial(isSpecial), m_numIntConsumes(numIntConsumes)
, m_numFloatConsumes(numFloatConsumes), m_hasOutput(hasOutput), m_isOutputIntegral(isOutputIntegral)
, m_outputType(outputType), m_operandKind(operandKind)