forked from v8/v8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule-decoder.cc
More file actions
2422 lines (2193 loc) · 89.5 KB
/
module-decoder.cc
File metadata and controls
2422 lines (2193 loc) · 89.5 KB
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
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/wasm/module-decoder.h"
#include "src/base/functional.h"
#include "src/base/platform/platform.h"
#include "src/base/platform/wrappers.h"
#include "src/flags/flags.h"
#include "src/init/v8.h"
#include "src/logging/counters.h"
#include "src/logging/metrics.h"
#include "src/objects/objects-inl.h"
#include "src/utils/ostreams.h"
#include "src/wasm/decoder.h"
#include "src/wasm/function-body-decoder-impl.h"
#include "src/wasm/init-expr-interface.h"
#include "src/wasm/struct-types.h"
#include "src/wasm/wasm-constants.h"
#include "src/wasm/wasm-engine.h"
#include "src/wasm/wasm-limits.h"
#include "src/wasm/wasm-opcodes-inl.h"
namespace v8 {
namespace internal {
namespace wasm {
#define TRACE(...) \
do { \
if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
} while (false)
namespace {
constexpr char kNameString[] = "name";
constexpr char kSourceMappingURLString[] = "sourceMappingURL";
constexpr char kCompilationHintsString[] = "compilationHints";
constexpr char kBranchHintsString[] = "branchHints";
constexpr char kDebugInfoString[] = ".debug_info";
constexpr char kExternalDebugInfoString[] = "external_debug_info";
const char* ExternalKindName(ImportExportKindCode kind) {
switch (kind) {
case kExternalFunction:
return "function";
case kExternalTable:
return "table";
case kExternalMemory:
return "memory";
case kExternalGlobal:
return "global";
case kExternalException:
return "exception";
}
return "unknown";
}
} // namespace
const char* SectionName(SectionCode code) {
switch (code) {
case kUnknownSectionCode:
return "Unknown";
case kTypeSectionCode:
return "Type";
case kImportSectionCode:
return "Import";
case kFunctionSectionCode:
return "Function";
case kTableSectionCode:
return "Table";
case kMemorySectionCode:
return "Memory";
case kGlobalSectionCode:
return "Global";
case kExportSectionCode:
return "Export";
case kStartSectionCode:
return "Start";
case kCodeSectionCode:
return "Code";
case kElementSectionCode:
return "Element";
case kDataSectionCode:
return "Data";
case kExceptionSectionCode:
return "Exception";
case kDataCountSectionCode:
return "DataCount";
case kNameSectionCode:
return kNameString;
case kSourceMappingURLSectionCode:
return kSourceMappingURLString;
case kDebugInfoSectionCode:
return kDebugInfoString;
case kExternalDebugInfoSectionCode:
return kExternalDebugInfoString;
case kCompilationHintsSectionCode:
return kCompilationHintsString;
case kBranchHintsSectionCode:
return kBranchHintsString;
default:
return "<unknown>";
}
}
namespace {
bool validate_utf8(Decoder* decoder, WireBytesRef string) {
return unibrow::Utf8::ValidateEncoding(
decoder->start() + decoder->GetBufferRelativeOffset(string.offset()),
string.length());
}
// Reads a length-prefixed string, checking that it is within bounds. Returns
// the offset of the string, and the length as an out parameter.
WireBytesRef consume_string(Decoder* decoder, bool validate_utf8,
const char* name) {
uint32_t length = decoder->consume_u32v("string length");
uint32_t offset = decoder->pc_offset();
const byte* string_start = decoder->pc();
// Consume bytes before validation to guarantee that the string is not oob.
if (length > 0) {
decoder->consume_bytes(length, name);
if (decoder->ok() && validate_utf8 &&
!unibrow::Utf8::ValidateEncoding(string_start, length)) {
decoder->errorf(string_start, "%s: no valid UTF-8 string", name);
}
}
return {offset, decoder->failed() ? 0 : length};
}
namespace {
SectionCode IdentifyUnknownSectionInternal(Decoder* decoder) {
WireBytesRef string = consume_string(decoder, true, "section name");
if (decoder->failed()) {
return kUnknownSectionCode;
}
const byte* section_name_start =
decoder->start() + decoder->GetBufferRelativeOffset(string.offset());
TRACE(" +%d section name : \"%.*s\"\n",
static_cast<int>(section_name_start - decoder->start()),
string.length() < 20 ? string.length() : 20, section_name_start);
using SpecialSectionPair = std::pair<base::Vector<const char>, SectionCode>;
static constexpr SpecialSectionPair kSpecialSections[]{
{base::StaticCharVector(kNameString), kNameSectionCode},
{base::StaticCharVector(kSourceMappingURLString),
kSourceMappingURLSectionCode},
{base::StaticCharVector(kCompilationHintsString),
kCompilationHintsSectionCode},
{base::StaticCharVector(kBranchHintsString), kBranchHintsSectionCode},
{base::StaticCharVector(kDebugInfoString), kDebugInfoSectionCode},
{base::StaticCharVector(kExternalDebugInfoString),
kExternalDebugInfoSectionCode}};
auto name_vec = base::Vector<const char>::cast(
base::VectorOf(section_name_start, string.length()));
for (auto& special_section : kSpecialSections) {
if (name_vec == special_section.first) return special_section.second;
}
return kUnknownSectionCode;
}
} // namespace
// An iterator over the sections in a wasm binary module.
// Automatically skips all unknown sections.
class WasmSectionIterator {
public:
explicit WasmSectionIterator(Decoder* decoder)
: decoder_(decoder),
section_code_(kUnknownSectionCode),
section_start_(decoder->pc()),
section_end_(decoder->pc()) {
next();
}
bool more() const { return decoder_->ok() && decoder_->more(); }
SectionCode section_code() const { return section_code_; }
const byte* section_start() const { return section_start_; }
uint32_t section_length() const {
return static_cast<uint32_t>(section_end_ - section_start_);
}
base::Vector<const uint8_t> payload() const {
return {payload_start_, payload_length()};
}
const byte* payload_start() const { return payload_start_; }
uint32_t payload_length() const {
return static_cast<uint32_t>(section_end_ - payload_start_);
}
const byte* section_end() const { return section_end_; }
// Advances to the next section, checking that decoding the current section
// stopped at {section_end_}.
void advance(bool move_to_section_end = false) {
if (move_to_section_end && decoder_->pc() < section_end_) {
decoder_->consume_bytes(
static_cast<uint32_t>(section_end_ - decoder_->pc()));
}
if (decoder_->pc() != section_end_) {
const char* msg = decoder_->pc() < section_end_ ? "shorter" : "longer";
decoder_->errorf(decoder_->pc(),
"section was %s than expected size "
"(%u bytes expected, %zu decoded)",
msg, section_length(),
static_cast<size_t>(decoder_->pc() - section_start_));
}
next();
}
private:
Decoder* decoder_;
SectionCode section_code_;
const byte* section_start_;
const byte* payload_start_;
const byte* section_end_;
// Reads the section code/name at the current position and sets up
// the embedder fields.
void next() {
if (!decoder_->more()) {
section_code_ = kUnknownSectionCode;
return;
}
section_start_ = decoder_->pc();
uint8_t section_code = decoder_->consume_u8("section code");
// Read and check the section size.
uint32_t section_length = decoder_->consume_u32v("section length");
payload_start_ = decoder_->pc();
if (decoder_->checkAvailable(section_length)) {
// Get the limit of the section within the module.
section_end_ = payload_start_ + section_length;
} else {
// The section would extend beyond the end of the module.
section_end_ = payload_start_;
}
if (section_code == kUnknownSectionCode) {
// Check for the known "name", "sourceMappingURL", or "compilationHints"
// section.
// To identify the unknown section we set the end of the decoder bytes to
// the end of the custom section, so that we do not read the section name
// beyond the end of the section.
const byte* module_end = decoder_->end();
decoder_->set_end(section_end_);
section_code = IdentifyUnknownSectionInternal(decoder_);
if (decoder_->ok()) decoder_->set_end(module_end);
// As a side effect, the above function will forward the decoder to after
// the identifier string.
payload_start_ = decoder_->pc();
} else if (!IsValidSectionCode(section_code)) {
decoder_->errorf(decoder_->pc(), "unknown section code #0x%02x",
section_code);
section_code = kUnknownSectionCode;
}
section_code_ = decoder_->failed() ? kUnknownSectionCode
: static_cast<SectionCode>(section_code);
if (section_code_ == kUnknownSectionCode && section_end_ > decoder_->pc()) {
// skip to the end of the unknown section.
uint32_t remaining = static_cast<uint32_t>(section_end_ - decoder_->pc());
decoder_->consume_bytes(remaining, "section payload");
}
}
};
} // namespace
// The main logic for decoding the bytes of a module.
class ModuleDecoderImpl : public Decoder {
public:
explicit ModuleDecoderImpl(const WasmFeatures& enabled, ModuleOrigin origin)
: Decoder(nullptr, nullptr),
enabled_features_(enabled),
origin_(origin) {}
ModuleDecoderImpl(const WasmFeatures& enabled, const byte* module_start,
const byte* module_end, ModuleOrigin origin)
: Decoder(module_start, module_end),
enabled_features_(enabled),
module_start_(module_start),
module_end_(module_end),
origin_(origin) {
if (end_ < start_) {
error(start_, "end is less than start");
end_ = start_;
}
}
void onFirstError() override {
pc_ = end_; // On error, terminate section decoding loop.
}
void DumpModule(const base::Vector<const byte> module_bytes) {
std::string path;
if (FLAG_dump_wasm_module_path) {
path = FLAG_dump_wasm_module_path;
if (path.size() &&
!base::OS::isDirectorySeparator(path[path.size() - 1])) {
path += base::OS::DirectorySeparator();
}
}
// File are named `HASH.{ok,failed}.wasm`.
size_t hash = base::hash_range(module_bytes.begin(), module_bytes.end());
base::EmbeddedVector<char, 32> buf;
SNPrintF(buf, "%016zx.%s.wasm", hash, ok() ? "ok" : "failed");
path += buf.begin();
size_t rv = 0;
if (FILE* file = base::OS::FOpen(path.c_str(), "wb")) {
rv = fwrite(module_bytes.begin(), module_bytes.length(), 1, file);
base::Fclose(file);
}
if (rv != 1) {
OFStream os(stderr);
os << "Error while dumping wasm file to " << path << std::endl;
}
}
void StartDecoding(Counters* counters, AccountingAllocator* allocator) {
CHECK_NULL(module_);
SetCounters(counters);
module_.reset(
new WasmModule(std::make_unique<Zone>(allocator, "signatures")));
module_->initial_pages = 0;
module_->maximum_pages = 0;
module_->mem_export = false;
module_->origin = origin_;
}
void DecodeModuleHeader(base::Vector<const uint8_t> bytes, uint8_t offset) {
if (failed()) return;
Reset(bytes, offset);
const byte* pos = pc_;
uint32_t magic_word = consume_u32("wasm magic");
#define BYTES(x) (x & 0xFF), (x >> 8) & 0xFF, (x >> 16) & 0xFF, (x >> 24) & 0xFF
if (magic_word != kWasmMagic) {
errorf(pos,
"expected magic word %02x %02x %02x %02x, "
"found %02x %02x %02x %02x",
BYTES(kWasmMagic), BYTES(magic_word));
}
pos = pc_;
{
uint32_t magic_version = consume_u32("wasm version");
if (magic_version != kWasmVersion) {
errorf(pos,
"expected version %02x %02x %02x %02x, "
"found %02x %02x %02x %02x",
BYTES(kWasmVersion), BYTES(magic_version));
}
}
#undef BYTES
}
bool CheckSectionOrder(SectionCode section_code,
SectionCode prev_section_code,
SectionCode next_section_code) {
if (next_ordered_section_ > next_section_code) {
errorf(pc(), "The %s section must appear before the %s section",
SectionName(section_code), SectionName(next_section_code));
return false;
}
if (next_ordered_section_ <= prev_section_code) {
next_ordered_section_ = prev_section_code + 1;
}
return true;
}
bool CheckUnorderedSection(SectionCode section_code) {
if (has_seen_unordered_section(section_code)) {
errorf(pc(), "Multiple %s sections not allowed",
SectionName(section_code));
return false;
}
set_seen_unordered_section(section_code);
return true;
}
void DecodeSection(SectionCode section_code,
base::Vector<const uint8_t> bytes, uint32_t offset,
bool verify_functions = true) {
if (failed()) return;
Reset(bytes, offset);
TRACE("Section: %s\n", SectionName(section_code));
TRACE("Decode Section %p - %p\n", bytes.begin(), bytes.end());
// Check if the section is out-of-order.
if (section_code < next_ordered_section_ &&
section_code < kFirstUnorderedSection) {
errorf(pc(), "unexpected section <%s>", SectionName(section_code));
return;
}
switch (section_code) {
case kUnknownSectionCode:
break;
case kDataCountSectionCode:
if (!CheckUnorderedSection(section_code)) return;
if (!CheckSectionOrder(section_code, kElementSectionCode,
kCodeSectionCode))
return;
break;
case kExceptionSectionCode:
if (!CheckUnorderedSection(section_code)) return;
if (!CheckSectionOrder(section_code, kMemorySectionCode,
kGlobalSectionCode))
return;
break;
case kNameSectionCode:
// TODO(titzer): report out of place name section as a warning.
// Be lenient with placement of name section. All except first
// occurrence are ignored.
case kSourceMappingURLSectionCode:
// sourceMappingURL is a custom section and currently can occur anywhere
// in the module. In case of multiple sourceMappingURL sections, all
// except the first occurrence are ignored.
case kDebugInfoSectionCode:
// .debug_info is a custom section containing core DWARF information
// if produced by compiler. Its presence likely means that Wasm was
// built in a debug mode.
case kExternalDebugInfoSectionCode:
// external_debug_info is a custom section containing a reference to an
// external symbol file.
case kCompilationHintsSectionCode:
// TODO(frgossen): report out of place compilation hints section as a
// warning.
// Be lenient with placement of compilation hints section. All except
// first occurrence after function section and before code section are
// ignored.
break;
case kBranchHintsSectionCode:
// TODO(yuri): report out of place branch hints section as a
// warning.
// Be lenient with placement of compilation hints section. All except
// first occurrence after function section and before code section are
// ignored.
break;
default:
next_ordered_section_ = section_code + 1;
break;
}
switch (section_code) {
case kUnknownSectionCode:
break;
case kTypeSectionCode:
DecodeTypeSection();
break;
case kImportSectionCode:
DecodeImportSection();
break;
case kFunctionSectionCode:
DecodeFunctionSection();
break;
case kTableSectionCode:
DecodeTableSection();
break;
case kMemorySectionCode:
DecodeMemorySection();
break;
case kGlobalSectionCode:
DecodeGlobalSection();
break;
case kExportSectionCode:
DecodeExportSection();
break;
case kStartSectionCode:
DecodeStartSection();
break;
case kCodeSectionCode:
DecodeCodeSection(verify_functions);
break;
case kElementSectionCode:
DecodeElementSection();
break;
case kDataSectionCode:
DecodeDataSection();
break;
case kNameSectionCode:
DecodeNameSection();
break;
case kSourceMappingURLSectionCode:
DecodeSourceMappingURLSection();
break;
case kDebugInfoSectionCode:
// If there is an explicit source map, prefer it over DWARF info.
if (module_->debug_symbols.type == WasmDebugSymbols::Type::None) {
module_->debug_symbols = {WasmDebugSymbols::Type::EmbeddedDWARF, {}};
}
consume_bytes(static_cast<uint32_t>(end_ - start_), ".debug_info");
break;
case kExternalDebugInfoSectionCode:
DecodeExternalDebugInfoSection();
break;
case kCompilationHintsSectionCode:
if (enabled_features_.has_compilation_hints()) {
DecodeCompilationHintsSection();
} else {
// Ignore this section when feature was disabled. It is an optional
// custom section anyways.
consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
}
break;
case kBranchHintsSectionCode:
if (enabled_features_.has_branch_hinting()) {
DecodeBranchHintsSection();
} else {
// Ignore this section when feature was disabled. It is an optional
// custom section anyways.
consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
}
break;
case kDataCountSectionCode:
DecodeDataCountSection();
break;
case kExceptionSectionCode:
if (enabled_features_.has_eh()) {
DecodeExceptionSection();
} else {
errorf(pc(),
"unexpected section <%s> (enable with --experimental-wasm-eh)",
SectionName(section_code));
}
break;
default:
errorf(pc(), "unexpected section <%s>", SectionName(section_code));
return;
}
if (pc() != bytes.end()) {
const char* msg = pc() < bytes.end() ? "shorter" : "longer";
errorf(pc(),
"section was %s than expected size "
"(%zu bytes expected, %zu decoded)",
msg, bytes.size(), static_cast<size_t>(pc() - bytes.begin()));
}
}
void DecodeTypeSection() {
uint32_t signatures_count = consume_count("types count", kV8MaxWasmTypes);
module_->types.reserve(signatures_count);
for (uint32_t i = 0; ok() && i < signatures_count; ++i) {
TRACE("DecodeSignature[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
uint8_t kind = consume_u8("type kind");
switch (kind) {
case kWasmFunctionTypeCode: {
const FunctionSig* s = consume_sig(module_->signature_zone.get());
module_->add_signature(s);
break;
}
case kWasmStructTypeCode: {
if (!enabled_features_.has_gc()) {
errorf(pc(),
"invalid struct type definition, enable with "
"--experimental-wasm-gc");
break;
}
const StructType* s = consume_struct(module_->signature_zone.get());
module_->add_struct_type(s);
// TODO(7748): Should we canonicalize struct types, like
// {signature_map} does for function signatures?
break;
}
case kWasmArrayTypeCode: {
if (!enabled_features_.has_gc()) {
errorf(pc(),
"invalid array type definition, enable with "
"--experimental-wasm-gc");
break;
}
const ArrayType* type = consume_array(module_->signature_zone.get());
module_->add_array_type(type);
break;
}
default:
errorf(pc(), "unknown type form: %d", kind);
break;
}
}
module_->signature_map.Freeze();
}
void DecodeImportSection() {
uint32_t import_table_count =
consume_count("imports count", kV8MaxWasmImports);
module_->import_table.reserve(import_table_count);
for (uint32_t i = 0; ok() && i < import_table_count; ++i) {
TRACE("DecodeImportTable[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
module_->import_table.push_back({
{0, 0}, // module_name
{0, 0}, // field_name
kExternalFunction, // kind
0 // index
});
WasmImport* import = &module_->import_table.back();
const byte* pos = pc_;
import->module_name = consume_string(this, true, "module name");
import->field_name = consume_string(this, true, "field name");
import->kind =
static_cast<ImportExportKindCode>(consume_u8("import kind"));
switch (import->kind) {
case kExternalFunction: {
// ===== Imported function ===========================================
import->index = static_cast<uint32_t>(module_->functions.size());
module_->num_imported_functions++;
module_->functions.push_back({nullptr, // sig
import->index, // func_index
0, // sig_index
{0, 0}, // code
true, // imported
false, // exported
false}); // declared
WasmFunction* function = &module_->functions.back();
function->sig_index =
consume_sig_index(module_.get(), &function->sig);
break;
}
case kExternalTable: {
// ===== Imported table ==============================================
if (!AddTable(module_.get())) break;
import->index = static_cast<uint32_t>(module_->tables.size());
module_->num_imported_tables++;
module_->tables.emplace_back();
WasmTable* table = &module_->tables.back();
table->imported = true;
const byte* type_position = pc();
ValueType type = consume_reference_type();
if (!WasmTable::IsValidTableType(type, module_.get())) {
error(
type_position,
"Currently, only externref and function references are allowed "
"as table types");
break;
}
table->type = type;
uint8_t flags = validate_table_flags("element count");
consume_resizable_limits(
"element count", "elements", std::numeric_limits<uint32_t>::max(),
&table->initial_size, &table->has_maximum_size,
std::numeric_limits<uint32_t>::max(), &table->maximum_size,
flags);
break;
}
case kExternalMemory: {
// ===== Imported memory =============================================
if (!AddMemory(module_.get())) break;
uint8_t flags = validate_memory_flags(&module_->has_shared_memory,
&module_->is_memory64);
consume_resizable_limits(
"memory", "pages", kSpecMaxMemoryPages, &module_->initial_pages,
&module_->has_maximum_pages, kSpecMaxMemoryPages,
&module_->maximum_pages, flags);
break;
}
case kExternalGlobal: {
// ===== Imported global =============================================
import->index = static_cast<uint32_t>(module_->globals.size());
module_->globals.push_back({kWasmVoid, false, {}, {0}, true, false});
WasmGlobal* global = &module_->globals.back();
global->type = consume_value_type();
global->mutability = consume_mutability();
if (global->mutability) {
module_->num_imported_mutable_globals++;
}
break;
}
case kExternalException: {
// ===== Imported exception ==========================================
if (!enabled_features_.has_eh()) {
errorf(pos, "unknown import kind 0x%02x", import->kind);
break;
}
import->index = static_cast<uint32_t>(module_->exceptions.size());
const WasmExceptionSig* exception_sig = nullptr;
consume_exception_attribute(); // Attribute ignored for now.
consume_exception_sig_index(module_.get(), &exception_sig);
module_->exceptions.emplace_back(exception_sig);
break;
}
default:
errorf(pos, "unknown import kind 0x%02x", import->kind);
break;
}
}
}
void DecodeFunctionSection() {
uint32_t functions_count =
consume_count("functions count", kV8MaxWasmFunctions);
auto counter =
SELECT_WASM_COUNTER(GetCounters(), origin_, wasm_functions_per, module);
counter->AddSample(static_cast<int>(functions_count));
DCHECK_EQ(module_->functions.size(), module_->num_imported_functions);
uint32_t total_function_count =
module_->num_imported_functions + functions_count;
module_->functions.reserve(total_function_count);
module_->num_declared_functions = functions_count;
for (uint32_t i = 0; i < functions_count; ++i) {
uint32_t func_index = static_cast<uint32_t>(module_->functions.size());
module_->functions.push_back({nullptr, // sig
func_index, // func_index
0, // sig_index
{0, 0}, // code
false, // imported
false, // exported
false}); // declared
WasmFunction* function = &module_->functions.back();
function->sig_index = consume_sig_index(module_.get(), &function->sig);
if (!ok()) return;
}
DCHECK_EQ(module_->functions.size(), total_function_count);
}
void DecodeTableSection() {
// TODO(ahaas): Set the correct limit to {kV8MaxWasmTables} once the
// implementation of ExternRef landed.
uint32_t max_count =
enabled_features_.has_reftypes() ? 100000 : kV8MaxWasmTables;
uint32_t table_count = consume_count("table count", max_count);
for (uint32_t i = 0; ok() && i < table_count; i++) {
if (!AddTable(module_.get())) break;
module_->tables.emplace_back();
WasmTable* table = &module_->tables.back();
const byte* type_position = pc();
ValueType table_type = consume_reference_type();
if (!WasmTable::IsValidTableType(table_type, module_.get())) {
error(type_position,
"Currently, only externref and function references are allowed "
"as table types");
continue;
}
table->type = table_type;
uint8_t flags = validate_table_flags("table elements");
consume_resizable_limits(
"table elements", "elements", std::numeric_limits<uint32_t>::max(),
&table->initial_size, &table->has_maximum_size,
std::numeric_limits<uint32_t>::max(), &table->maximum_size, flags);
if (!table_type.is_defaultable()) {
table->initial_value = consume_init_expr(module_.get(), table_type);
}
}
}
void DecodeMemorySection() {
uint32_t memory_count = consume_count("memory count", kV8MaxWasmMemories);
for (uint32_t i = 0; ok() && i < memory_count; i++) {
if (!AddMemory(module_.get())) break;
uint8_t flags = validate_memory_flags(&module_->has_shared_memory,
&module_->is_memory64);
consume_resizable_limits("memory", "pages", kSpecMaxMemoryPages,
&module_->initial_pages,
&module_->has_maximum_pages, kSpecMaxMemoryPages,
&module_->maximum_pages, flags);
}
}
void DecodeGlobalSection() {
uint32_t globals_count = consume_count("globals count", kV8MaxWasmGlobals);
uint32_t imported_globals = static_cast<uint32_t>(module_->globals.size());
module_->globals.reserve(imported_globals + globals_count);
for (uint32_t i = 0; ok() && i < globals_count; ++i) {
TRACE("DecodeGlobal[%d] module+%d\n", i, static_cast<int>(pc_ - start_));
ValueType type = consume_value_type();
bool mutability = consume_mutability();
if (failed()) break;
WireBytesRef init = consume_init_expr(module_.get(), type);
module_->globals.push_back({type, mutability, init, {0}, false, false});
}
if (ok()) CalculateGlobalOffsets(module_.get());
}
void DecodeExportSection() {
uint32_t export_table_count =
consume_count("exports count", kV8MaxWasmExports);
module_->export_table.reserve(export_table_count);
for (uint32_t i = 0; ok() && i < export_table_count; ++i) {
TRACE("DecodeExportTable[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
module_->export_table.push_back({
{0, 0}, // name
kExternalFunction, // kind
0 // index
});
WasmExport* exp = &module_->export_table.back();
exp->name = consume_string(this, true, "field name");
const byte* pos = pc();
exp->kind = static_cast<ImportExportKindCode>(consume_u8("export kind"));
switch (exp->kind) {
case kExternalFunction: {
WasmFunction* func = nullptr;
exp->index =
consume_func_index(module_.get(), &func, "export function index");
if (failed()) break;
DCHECK_NOT_NULL(func);
module_->num_exported_functions++;
func->exported = true;
// Exported functions are considered "declared".
func->declared = true;
break;
}
case kExternalTable: {
WasmTable* table = nullptr;
exp->index = consume_table_index(module_.get(), &table);
if (table) table->exported = true;
break;
}
case kExternalMemory: {
uint32_t index = consume_u32v("memory index");
// TODO(titzer): This should become more regular
// once we support multiple memories.
if (!module_->has_memory || index != 0) {
error("invalid memory index != 0");
}
module_->mem_export = true;
break;
}
case kExternalGlobal: {
WasmGlobal* global = nullptr;
exp->index = consume_global_index(module_.get(), &global);
if (global) {
global->exported = true;
}
break;
}
case kExternalException: {
if (!enabled_features_.has_eh()) {
errorf(pos, "invalid export kind 0x%02x", exp->kind);
break;
}
WasmException* exception = nullptr;
exp->index = consume_exception_index(module_.get(), &exception);
break;
}
default:
errorf(pos, "invalid export kind 0x%02x", exp->kind);
break;
}
}
// Check for duplicate exports (except for asm.js).
if (ok() && origin_ == kWasmOrigin && module_->export_table.size() > 1) {
std::vector<WasmExport> sorted_exports(module_->export_table);
auto cmp_less = [this](const WasmExport& a, const WasmExport& b) {
// Return true if a < b.
if (a.name.length() != b.name.length()) {
return a.name.length() < b.name.length();
}
const byte* left = start() + GetBufferRelativeOffset(a.name.offset());
const byte* right = start() + GetBufferRelativeOffset(b.name.offset());
return memcmp(left, right, a.name.length()) < 0;
};
std::stable_sort(sorted_exports.begin(), sorted_exports.end(), cmp_less);
auto it = sorted_exports.begin();
WasmExport* last = &*it++;
for (auto end = sorted_exports.end(); it != end; last = &*it++) {
DCHECK(!cmp_less(*it, *last)); // Vector must be sorted.
if (!cmp_less(*last, *it)) {
const byte* pc = start() + GetBufferRelativeOffset(it->name.offset());
TruncatedUserString<> name(pc, it->name.length());
errorf(pc, "Duplicate export name '%.*s' for %s %d and %s %d",
name.length(), name.start(), ExternalKindName(last->kind),
last->index, ExternalKindName(it->kind), it->index);
break;
}
}
}
}
void DecodeStartSection() {
WasmFunction* func;
const byte* pos = pc_;
module_->start_function_index =
consume_func_index(module_.get(), &func, "start function index");
if (func &&
(func->sig->parameter_count() > 0 || func->sig->return_count() > 0)) {
error(pos, "invalid start function: non-zero parameter or return count");
}
}
void DecodeElementSection() {
uint32_t element_count =
consume_count("element count", FLAG_wasm_max_table_size);
for (uint32_t i = 0; i < element_count; ++i) {
bool expressions_as_elements;
WasmElemSegment segment =
consume_element_segment_header(&expressions_as_elements);
if (failed()) return;
DCHECK_NE(segment.type, kWasmBottom);
uint32_t num_elem =
consume_count("number of elements", max_table_init_entries());
for (uint32_t j = 0; j < num_elem; j++) {
WasmElemSegment::Entry init =
expressions_as_elements
? consume_element_expr()
: WasmElemSegment::Entry(WasmElemSegment::Entry::kRefFuncEntry,
consume_element_func_index());
if (failed()) return;
if (!IsSubtypeOf(TypeOf(init), segment.type, module_.get())) {
errorf(pc_,
"Invalid type in the init expression. The expected type is "
"'%s', but the actual type is '%s'.",
segment.type.name().c_str(), TypeOf(init).name().c_str());
return;
}
segment.entries.push_back(init);
}
module_->elem_segments.push_back(std::move(segment));
}
}
void DecodeCodeSection(bool verify_functions) {
StartCodeSection();
uint32_t code_section_start = pc_offset();
uint32_t functions_count = consume_u32v("functions count");
CheckFunctionsCount(functions_count, code_section_start);
for (uint32_t i = 0; ok() && i < functions_count; ++i) {
const byte* pos = pc();
uint32_t size = consume_u32v("body size");
if (size > kV8MaxWasmFunctionSize) {
errorf(pos, "size %u > maximum function size %zu", size,
kV8MaxWasmFunctionSize);
return;
}
uint32_t offset = pc_offset();
consume_bytes(size, "function body");
if (failed()) break;
DecodeFunctionBody(i, size, offset, verify_functions);
}
DCHECK_GE(pc_offset(), code_section_start);
set_code_section(code_section_start, pc_offset() - code_section_start);
}
void StartCodeSection() {
if (ok()) {
// Make sure global offset were calculated before they get accessed during
// function compilation.
CalculateGlobalOffsets(module_.get());
}
}
bool CheckFunctionsCount(uint32_t functions_count, uint32_t error_offset) {
if (functions_count != module_->num_declared_functions) {
errorf(error_offset, "function body count %u mismatch (%u expected)",
functions_count, module_->num_declared_functions);
return false;
}
return true;
}
void DecodeFunctionBody(uint32_t index, uint32_t length, uint32_t offset,
bool verify_functions) {
WasmFunction* function =
&module_->functions[index + module_->num_imported_functions];
function->code = {offset, length};
if (verify_functions) {
ModuleWireBytes bytes(module_start_, module_end_);
VerifyFunctionBody(module_->signature_zone->allocator(),
index + module_->num_imported_functions, bytes,
module_.get(), function);
}
}
bool CheckDataSegmentsCount(uint32_t data_segments_count) {
if (has_seen_unordered_section(kDataCountSectionCode) &&
data_segments_count != module_->num_declared_data_segments) {
errorf(pc(), "data segments count %u mismatch (%u expected)",
data_segments_count, module_->num_declared_data_segments);
return false;
}
return true;
}
void DecodeDataSection() {