forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule-decoder-impl.h
More file actions
2888 lines (2652 loc) Β· 110 KB
/
module-decoder-impl.h
File metadata and controls
2888 lines (2652 loc) Β· 110 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 2022 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.
#ifndef V8_WASM_MODULE_DECODER_IMPL_H_
#define V8_WASM_MODULE_DECODER_IMPL_H_
#if !V8_ENABLE_WEBASSEMBLY
#error This header should only be included if WebAssembly is enabled.
#endif // !V8_ENABLE_WEBASSEMBLY
#include "src/base/platform/wrappers.h"
#include "src/logging/counters.h"
#include "src/strings/unicode.h"
#include "src/utils/ostreams.h"
#include "src/wasm/canonical-types.h"
#include "src/wasm/constant-expression-interface.h"
#include "src/wasm/function-body-decoder-impl.h"
#include "src/wasm/module-decoder.h"
#include "src/wasm/wasm-engine.h"
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-subtyping.h"
#include "src/wasm/well-known-imports.h"
namespace v8::internal::wasm {
#define TRACE(...) \
do { \
if (v8_flags.trace_wasm_decoder) PrintF(__VA_ARGS__); \
} while (false)
constexpr char kNameString[] = "name";
constexpr char kSourceMappingURLString[] = "sourceMappingURL";
constexpr char kInstTraceString[] = "metadata.code.trace_inst";
constexpr char kCompilationHintsString[] = "compilationHints";
constexpr char kBranchHintsString[] = "metadata.code.branch_hint";
constexpr char kDebugInfoString[] = ".debug_info";
constexpr char kExternalDebugInfoString[] = "external_debug_info";
constexpr char kBuildIdString[] = "build_id";
inline const char* ExternalKindName(ImportExportKindCode kind) {
switch (kind) {
case kExternalFunction:
return "function";
case kExternalTable:
return "table";
case kExternalMemory:
return "memory";
case kExternalGlobal:
return "global";
case kExternalTag:
return "tag";
}
return "unknown";
}
inline 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.
inline WireBytesRef consume_string(Decoder* decoder,
unibrow::Utf8Variant grammar,
const char* name, ITracer* tracer) {
if (tracer) {
tracer->Description(name);
tracer->Description(" ");
}
uint32_t length = decoder->consume_u32v("length", tracer);
if (tracer) {
tracer->Description(": ");
tracer->Description(length);
tracer->NextLine();
}
uint32_t offset = decoder->pc_offset();
const uint8_t* string_start = decoder->pc();
// Consume bytes before validation to guarantee that the string is not oob.
if (length > 0) {
if (tracer) {
tracer->Bytes(decoder->pc(), length);
tracer->Description(name);
tracer->Description(": ");
tracer->Description(reinterpret_cast<const char*>(decoder->pc()), length);
tracer->NextLine();
}
decoder->consume_bytes(length, name);
if (decoder->ok()) {
switch (grammar) {
case unibrow::Utf8Variant::kLossyUtf8:
break;
case unibrow::Utf8Variant::kUtf8:
if (!unibrow::Utf8::ValidateEncoding(string_start, length)) {
decoder->errorf(string_start, "%s: no valid UTF-8 string", name);
}
break;
case unibrow::Utf8Variant::kWtf8:
if (!unibrow::Wtf8::ValidateEncoding(string_start, length)) {
decoder->errorf(string_start, "%s: no valid WTF-8 string", name);
}
break;
case unibrow::Utf8Variant::kUtf8NoTrap:
UNREACHABLE();
}
}
}
return {offset, decoder->failed() ? 0 : length};
}
inline WireBytesRef consume_string(Decoder* decoder,
unibrow::Utf8Variant grammar,
const char* name) {
return consume_string(decoder, grammar, name, ITracer::NoTrace);
}
inline WireBytesRef consume_utf8_string(Decoder* decoder, const char* name,
ITracer* tracer) {
return consume_string(decoder, unibrow::Utf8Variant::kUtf8, name, tracer);
}
inline SectionCode IdentifyUnknownSectionInternal(Decoder* decoder,
ITracer* tracer) {
WireBytesRef string = consume_utf8_string(decoder, "section name", tracer);
if (decoder->failed()) {
return kUnknownSectionCode;
}
const uint8_t* 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(kInstTraceString), kInstTraceSectionCode},
{base::StaticCharVector(kCompilationHintsString),
kCompilationHintsSectionCode},
{base::StaticCharVector(kBranchHintsString), kBranchHintsSectionCode},
{base::StaticCharVector(kDebugInfoString), kDebugInfoSectionCode},
{base::StaticCharVector(kExternalDebugInfoString),
kExternalDebugInfoSectionCode},
{base::StaticCharVector(kBuildIdString), kBuildIdSectionCode}};
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;
}
// An iterator over the sections in a wasm binary module.
// Automatically skips all unknown sections.
class WasmSectionIterator {
public:
explicit WasmSectionIterator(Decoder* decoder, ITracer* tracer)
: decoder_(decoder),
tracer_(tracer),
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 uint8_t* 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 uint8_t* payload_start() const { return payload_start_; }
uint32_t payload_length() const {
return static_cast<uint32_t>(section_end_ - payload_start_);
}
const uint8_t* 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_;
ITracer* tracer_;
SectionCode section_code_;
const uint8_t* section_start_;
const uint8_t* payload_start_;
const uint8_t* 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();
// Empty line before next section.
if (tracer_) tracer_->NextLine();
uint8_t section_code = decoder_->consume_u8("section kind", tracer_);
if (tracer_) {
tracer_->Description(": ");
tracer_->Description(SectionName(static_cast<SectionCode>(section_code)));
tracer_->NextLine();
}
// Read and check the section size.
uint32_t section_length = decoder_->consume_u32v("section length", tracer_);
if (tracer_) {
tracer_->Description(section_length);
tracer_->NextLine();
}
payload_start_ = decoder_->pc();
section_end_ = payload_start_ + section_length;
if (section_length > decoder_->available_bytes()) {
decoder_->errorf(
section_start_,
"section (code %u, \"%s\") extends past end of the module "
"(length %u, remaining bytes %u)",
section_code, SectionName(static_cast<SectionCode>(section_code)),
section_length, decoder_->available_bytes());
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 uint8_t* module_end = decoder_->end();
decoder_->set_end(section_end_);
section_code = IdentifyUnknownSectionInternal(decoder_, tracer_);
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_ = 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", tracer_);
}
}
};
inline void DumpModule(const base::Vector<const uint8_t> module_bytes,
bool ok) {
std::string path;
if (v8_flags.dump_wasm_module_path) {
path = v8_flags.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`.
// Limit the hash to 8 characters (32 bits).
uint32_t hash = static_cast<uint32_t>(GetWireBytesHash(module_bytes));
base::EmbeddedVector<char, 32> buf;
SNPrintF(buf, "%08x.%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;
}
}
// The main logic for decoding the bytes of a module.
class ModuleDecoderImpl : public Decoder {
public:
ModuleDecoderImpl(WasmEnabledFeatures enabled_features,
base::Vector<const uint8_t> wire_bytes, ModuleOrigin origin,
WasmDetectedFeatures* detected_features,
ITracer* tracer = ITracer::NoTrace)
: Decoder(wire_bytes),
enabled_features_(enabled_features),
detected_features_(detected_features),
module_(std::make_shared<WasmModule>(origin)),
module_start_(wire_bytes.begin()),
module_end_(wire_bytes.end()),
tracer_(tracer) {}
void onFirstError() override {
pc_ = end_; // On error, terminate section decoding loop.
}
void DecodeModuleHeader(base::Vector<const uint8_t> bytes) {
if (failed()) return;
Reset(bytes);
const uint8_t* pos = pc_;
uint32_t magic_word = consume_u32("wasm magic", tracer_);
if (tracer_) tracer_->NextLine();
#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", tracer_);
if (tracer_) tracer_->NextLine();
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) {
// Check the order of ordered sections.
if (section_code >= kFirstSectionInModule &&
section_code < kFirstUnorderedSection) {
if (section_code < next_ordered_section_) {
errorf(pc(), "unexpected section <%s>", SectionName(section_code));
return false;
}
next_ordered_section_ = section_code + 1;
return true;
}
// Ignore ordering problems in unknown / custom sections. Even allow them to
// appear multiple times. As optional sections we use them on a "best
// effort" basis.
if (section_code == kUnknownSectionCode) return true;
if (section_code > kLastKnownModuleSection) return true;
// The rest is standardized unordered sections; they are checked more
// thoroughly..
DCHECK_LE(kFirstUnorderedSection, section_code);
DCHECK_GE(kLastKnownModuleSection, section_code);
// Check that unordered sections don't appear multiple times.
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);
// Define a helper to ensure that sections <= {before} appear before the
// current unordered section, and everything >= {after} appears after it.
auto check_order = [this, section_code](SectionCode before,
SectionCode after) -> bool {
DCHECK_LT(before, after);
if (next_ordered_section_ > after) {
errorf(pc(), "The %s section must appear before the %s section",
SectionName(section_code), SectionName(after));
return false;
}
if (next_ordered_section_ <= before) next_ordered_section_ = before + 1;
return true;
};
// Now check the ordering constraints of specific unordered sections.
switch (section_code) {
case kDataCountSectionCode:
return check_order(kElementSectionCode, kCodeSectionCode);
case kTagSectionCode:
return check_order(kMemorySectionCode, kGlobalSectionCode);
case kStringRefSectionCode:
// TODO(12868): If there's a tag section, assert that we're after the
// tag section.
return check_order(kMemorySectionCode, kGlobalSectionCode);
case kInstTraceSectionCode:
// Custom section following code.metadata tool convention containing
// offsets specifying where trace marks should be emitted.
// Be lenient with placement of instruction trace section. All except
// first occurrence after function section and before code section are
// ignored.
return true;
default:
return true;
}
}
void DecodeSection(SectionCode section_code,
base::Vector<const uint8_t> bytes, uint32_t offset) {
if (failed()) return;
Reset(bytes, offset);
TRACE("Section: %s\n", SectionName(section_code));
TRACE("Decode Section %p - %p\n", bytes.begin(), bytes.end());
if (!CheckSectionOrder(section_code)) return;
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();
break;
case kElementSectionCode:
DecodeElementSection();
break;
case kDataSectionCode:
DecodeDataSection();
break;
case kNameSectionCode:
DecodeNameSection();
break;
case kSourceMappingURLSectionCode:
DecodeSourceMappingURLSection();
break;
case kDebugInfoSectionCode:
module_->debug_symbols[WasmDebugSymbols::Type::EmbeddedDWARF] = {
WasmDebugSymbols::Type::EmbeddedDWARF, {}};
consume_bytes(static_cast<uint32_t>(end_ - start_), ".debug_info");
break;
case kExternalDebugInfoSectionCode:
DecodeExternalDebugInfoSection();
break;
case kBuildIdSectionCode:
DecodeBuildIdSection();
break;
case kInstTraceSectionCode:
if (enabled_features_.has_instruction_tracing()) {
DecodeInstTraceSection();
} else {
// Ignore this section when feature is disabled. It is an optional
// custom section anyways.
consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
}
break;
case kCompilationHintsSectionCode:
// TODO(jkummerow): We're missing tracing support for well-known
// custom sections. This confuses `wami --full-hexdump` e.g.
// for the modules created by
// mjsunit/wasm/compilation-hints-streaming-compilation.js.
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 kTagSectionCode:
DecodeTagSection();
break;
case kStringRefSectionCode:
if (enabled_features_.has_stringref()) {
DecodeStringRefSection();
} else {
errorf(pc(),
"unexpected section <%s> (enable with "
"--experimental-wasm-stringref)",
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()));
}
}
static constexpr const char* TypeKindName(uint8_t kind) {
switch (kind) {
// clang-format off
case kWasmFunctionTypeCode: return "func";
case kWasmStructTypeCode: return "struct";
case kWasmArrayTypeCode: return "array";
case kWasmContTypeCode: return "cont";
default: return "unknown";
// clang-format on
}
}
TypeDefinition consume_base_type_definition(bool is_descriptor) {
const bool is_final = true;
const bool shared = false;
uint8_t kind = consume_u8(" kind", tracer_);
if (tracer_) {
tracer_->Description(": ");
tracer_->Description(TypeKindName(kind));
}
switch (kind) {
case kWasmFunctionTypeCode: {
const FunctionSig* sig = consume_sig(&module_->signature_zone);
if (sig == nullptr) {
CHECK(!ok());
return {};
}
return {sig, kNoSuperType, is_final, shared};
}
case kWasmStructTypeCode: {
module_->is_wasm_gc = true;
const StructType* type =
consume_struct(&module_->signature_zone, is_descriptor);
if (type == nullptr) {
CHECK(!ok());
return {};
}
return {type, kNoSuperType, is_final, shared};
}
case kWasmArrayTypeCode: {
module_->is_wasm_gc = true;
const ArrayType* type = consume_array(&module_->signature_zone);
if (type == nullptr) {
CHECK(!ok());
return {};
}
return {type, kNoSuperType, is_final, shared};
}
case kWasmContTypeCode: {
if (!enabled_features_.has_wasmfx()) {
error(pc() - 1,
"core stack switching not enabled (enable with "
"--experimental-wasm-wasmfx)");
return {};
}
const uint8_t* pos = pc();
HeapType hp = consume_heap_type();
if (!hp.is_index()) {
error(pos, "cont type must refer to a signature index");
return {};
}
ContType* type = module_->signature_zone.New<ContType>(hp.ref_index());
return {type, kNoSuperType, is_final, shared};
}
default:
if (tracer_) tracer_->NextLine();
errorf(pc() - 1, "unknown type form: %d", kind);
return {};
}
}
TypeDefinition consume_described_type(bool is_descriptor) {
uint8_t kind = read_u8<Decoder::FullValidationTag>(pc(), "type kind");
if (kind == kWasmDescriptorCode) {
if (!enabled_features_.has_custom_descriptors()) {
error(pc(),
"descriptor types need --experimental-wasm-custom-descriptors");
return {};
}
detected_features_->add_custom_descriptors();
consume_bytes(1, " described_by", tracer_);
const uint8_t* pos = pc();
uint32_t descriptor = consume_u32v("descriptor", tracer_);
if (descriptor >= module_->types.size()) {
errorf(pos, "descriptor type index %u is out of bounds", descriptor);
return {};
}
if (tracer_) tracer_->NextLine();
TypeDefinition type = consume_base_type_definition(is_descriptor);
if (type.kind != TypeDefinition::kStruct) {
error(pos - 1, "'descriptor' may only be used with structs");
return {};
}
type.descriptor = ModuleTypeIndex{descriptor};
return type;
} else {
return consume_base_type_definition(is_descriptor);
}
}
TypeDefinition consume_describing_type(size_t current_type_index) {
uint8_t kind = read_u8<Decoder::FullValidationTag>(pc(), "type kind");
if (kind == kWasmDescribesCode) {
if (!enabled_features_.has_custom_descriptors()) {
error(pc(),
"descriptor types need --experimental-wasm-custom-descriptors");
return {};
}
detected_features_->add_custom_descriptors();
consume_bytes(1, " describes", tracer_);
const uint8_t* pos = pc();
uint32_t describes = consume_u32v("describes", tracer_);
if (describes >= current_type_index) {
error(pos, "types can only describe previously-declared types");
return {};
}
if (tracer_) tracer_->NextLine();
TypeDefinition type = consume_described_type(true);
if (type.kind != TypeDefinition::kStruct) {
error(pos - 1, "'describes' may only be used with structs");
return {};
}
type.describes = ModuleTypeIndex{describes};
return type;
} else {
return consume_described_type(false);
}
}
TypeDefinition consume_shared_type(size_t current_type_index) {
uint8_t kind = read_u8<Decoder::FullValidationTag>(pc(), "type kind");
if (kind == kSharedFlagCode) {
if (!v8_flags.experimental_wasm_shared) {
errorf(pc() - 1,
"unknown type form: %d, enable with --experimental-wasm-shared",
kind);
return {};
}
module_->has_shared_part = true;
consume_bytes(1, " shared", tracer_);
TypeDefinition type = consume_describing_type(current_type_index);
if (type.kind == TypeDefinition::kFunction ||
type.kind == TypeDefinition::kCont) {
// TODO(42204563): Support shared functions/continuations.
error(pc() - 1, "shared functions/continuations are not supported yet");
return {};
}
type.is_shared = true;
return type;
} else {
return consume_describing_type(current_type_index);
}
}
// {current_type_index} is the index of the type that's being decoded.
// Any supertype must have a lower index.
TypeDefinition consume_subtype_definition(size_t current_type_index) {
uint8_t kind = read_u8<Decoder::FullValidationTag>(pc(), "type kind");
if (kind == kWasmSubtypeCode || kind == kWasmSubtypeFinalCode) {
module_->is_wasm_gc = true;
bool is_final = kind == kWasmSubtypeFinalCode;
consume_bytes(1, is_final ? " subtype final, " : " subtype extensible, ",
tracer_);
constexpr uint32_t kMaximumSupertypes = 1;
uint32_t supertype_count =
consume_count("supertype count", kMaximumSupertypes);
uint32_t supertype = kNoSuperType.index;
if (supertype_count == 1) {
supertype = consume_u32v("supertype", tracer_);
if (supertype >= current_type_index) {
errorf("type %u: invalid supertype %u", current_type_index,
supertype);
return {};
}
if (tracer_) {
tracer_->Description(supertype);
tracer_->NextLine();
}
}
TypeDefinition type = consume_shared_type(current_type_index);
type.supertype = ModuleTypeIndex{supertype};
type.is_final = is_final;
return type;
} else {
return consume_shared_type(current_type_index);
}
}
void DecodeTypeSection() {
TypeCanonicalizer* type_canon = GetTypeCanonicalizer();
uint32_t types_count = consume_count("types count", kV8MaxWasmTypes);
for (uint32_t i = 0; ok() && i < types_count; ++i) {
TRACE("DecodeType[%d] module+%d\n", i, static_cast<int>(pc_ - start_));
uint8_t kind = read_u8<Decoder::FullValidationTag>(pc(), "type kind");
size_t initial_size = module_->types.size();
uint32_t group_size = 1;
if (kind == kWasmRecursiveTypeGroupCode) {
module_->is_wasm_gc = true;
uint32_t rec_group_offset = pc_offset();
consume_bytes(1, "rec. group definition", tracer_);
if (tracer_) tracer_->NextLine();
group_size = consume_count("recursive group size", kV8MaxWasmTypes);
if (tracer_) tracer_->RecGroupOffset(rec_group_offset, group_size);
}
if (initial_size + group_size > kV8MaxWasmTypes) {
errorf(pc(), "Type definition count exceeds maximum %zu",
kV8MaxWasmTypes);
return;
}
// We need to resize types before decoding the type definitions in this
// group, so that the correct type size is visible to type definitions.
module_->types.resize(initial_size + group_size);
for (uint32_t j = 0; j < group_size; j++) {
if (tracer_) tracer_->TypeOffset(pc_offset());
TypeDefinition type = consume_subtype_definition(initial_size + j);
if (failed()) return;
module_->types[initial_size + j] = type;
}
FinalizeRecgroup(group_size, type_canon);
if (kind == kWasmRecursiveTypeGroupCode && tracer_) {
tracer_->Description("end of rec. group");
tracer_->NextLine();
}
}
}
void FinalizeRecgroup(uint32_t group_size, TypeCanonicalizer* type_canon) {
// Now that we have decoded the entire recgroup, check its validity,
// initialize additional data, and canonicalize it:
// - check supertype validity
// - propagate subtyping depths
// - validate is_shared bits and set up RefTypeKind fields
WasmModule* module = module_.get();
uint32_t end_index = static_cast<uint32_t>(module->types.size());
uint32_t start_index = end_index - group_size;
for (uint32_t i = start_index; ok() && i < end_index; ++i) {
TypeDefinition& type_def = module_->types[i];
bool is_shared = type_def.is_shared;
switch (type_def.kind) {
case TypeDefinition::kFunction: {
base::Vector<const ValueType> all = type_def.function_sig->all();
size_t count = all.size();
ValueType* storage = const_cast<ValueType*>(all.begin());
for (uint32_t j = 0; j < count; j++) {
value_type_reader::Populate(&storage[j], module);
ValueType type = storage[j];
if (is_shared && !type.is_shared()) {
DCHECK(v8_flags.experimental_wasm_shared);
uint32_t retcount =
static_cast<uint32_t>(type_def.function_sig->return_count());
const char* param_or_return =
j < retcount ? "return" : "parameter";
uint32_t index = j < retcount ? j : j - retcount;
// {pc_} isn't very accurate, it's pointing at the end of the
// recgroup. So to ease debugging, we print the type's index.
errorf(pc_,
"Type %u: shared signature must have shared %s types, "
"actual type for %s %d is %s",
i, param_or_return, param_or_return, index,
type.name().c_str());
return;
}
}
break;
}
case TypeDefinition::kStruct: {
size_t count = type_def.struct_type->field_count();
ValueType* storage =
const_cast<ValueType*>(type_def.struct_type->fields().begin());
for (uint32_t j = 0; j < count; j++) {
value_type_reader::Populate(&storage[j], module);
ValueType type = storage[j];
if (is_shared && !type.is_shared()) {
errorf(pc_,
"Type %u: shared struct must have shared field types, "
"actual type for field %d is %s",
i, j, type.name().c_str());
return;
}
}
if (type_def.descriptor.valid()) {
const TypeDefinition& descriptor =
module->type(type_def.descriptor);
if (descriptor.describes.index != i) {
uint32_t d = type_def.descriptor.index;
errorf(pc_,
"Type %u has descriptor %u but %u doesn't describe %u", i,
d, d, i);
return;
}
if (descriptor.is_shared != type_def.is_shared) {
errorf(pc_,
"Type %u and its descriptor %u must have same sharedness",
i, type_def.descriptor.index);
return;
}
}
if (type_def.describes.valid()) {
if (module->type(type_def.describes).descriptor.index != i) {
uint32_t d = type_def.describes.index;
errorf(pc_,
"Type %u describes %u but %u isn't a descriptor for %u", i,
d, d, i);
return;
}
}
break;
}
case TypeDefinition::kArray: {
value_type_reader::Populate(
const_cast<ArrayType*>(type_def.array_type)
->element_type_writable_ptr(),
module);
ValueType type = type_def.array_type->element_type();
if (is_shared && !type.is_shared()) {
errorf(pc_,
"Type %u: shared array must have shared element type, "
"actual element type is %s",
i, type.name().c_str());
return;
}
break;
}
case TypeDefinition::kCont: {
ModuleTypeIndex contfun_typeid =
type_def.cont_type->contfun_typeindex();
const TypeDefinition contfun_type =
module_->types[contfun_typeid.index];
if (contfun_type.kind != TypeDefinition::kFunction) {
errorf(pc_,
"Type %u: cont type must refer to a signature index, "
"actual type is %s",
i, module_->heap_type(contfun_typeid).name().c_str());
return;
}
if (is_shared && !contfun_type.is_shared) {
errorf(pc_,
"Type %u: shared cont type must refer to a shared signature,"
" actual type is %s",
module_->heap_type(contfun_typeid).name().c_str());
return;
}
break;
}
}
}
module->isorecursive_canonical_type_ids.resize(end_index);
type_canon->AddRecursiveGroup(module, group_size);
for (uint32_t i = start_index; ok() && i < end_index; ++i) {
TypeDefinition& type_def = module_->types[i];
ModuleTypeIndex explicit_super = type_def.supertype;
if (!explicit_super.valid()) continue; // No supertype.
DCHECK_LT(explicit_super.index, i); // Checked during decoding.
uint32_t depth = module->type(explicit_super).subtyping_depth + 1;
type_def.subtyping_depth = depth;
DCHECK_GE(depth, 0);
if (depth > kV8MaxRttSubtypingDepth) {
errorf("type %u: subtyping depth is greater than allowed", i);
return;
}
// This check is technically redundant; we include for the improved error
// message.
if (module->type(explicit_super).is_final) {
errorf("type %u extends final type %u", i, explicit_super.index);
return;
}
if (!ValidSubtypeDefinition(ModuleTypeIndex{i}, explicit_super, module,
module)) {
errorf("type %u has invalid explicit supertype %u", i,
explicit_super.index);
return;
}
}
}
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_));
if (tracer_) tracer_->ImportOffset(pc_offset());
const uint8_t* pos = pc_;
WireBytesRef module_name =
consume_utf8_string(this, "module name", tracer_);
WireBytesRef field_name =
consume_utf8_string(this, "field name", tracer_);
ImportExportKindCode kind =
static_cast<ImportExportKindCode>(consume_u8("kind", tracer_));
if (tracer_) {
tracer_->Description(": ");
tracer_->Description(ExternalKindName(kind));
}
module_->import_table.push_back(WasmImport{
.module_name = module_name, .field_name = field_name, .kind = kind});
WasmImport* import = &module_->import_table.back();
switch (kind) {
case kExternalFunction: {
// ===== Imported function ===========================================
import->index = static_cast<uint32_t>(module_->functions.size());
module_->num_imported_functions++;
module_->functions.push_back(WasmFunction{
.func_index = import->index,
.imported = true,
});
WasmFunction* function = &module_->functions.back();
function->sig_index =
consume_sig_index(module_.get(), &function->sig);
break;
}
case kExternalTable: {
// ===== Imported table ==============================================
import->index = static_cast<uint32_t>(module_->tables.size());
const uint8_t* type_position = pc();
ValueType type = consume_value_type(module_.get());
if (!type.is_object_reference()) {
errorf(type_position, "Invalid table type %s", type.name().c_str());
break;
}
module_->num_imported_tables++;
module_->tables.push_back(WasmTable{
.type = type,
.imported = true,
});
WasmTable* table = &module_->tables.back();
consume_table_flags(table);
DCHECK_IMPLIES(table->shared,
v8_flags.experimental_wasm_shared || !ok());
if (table->shared && v8_flags.experimental_wasm_shared) {
module_->has_shared_part = true;
if (!IsShared(type, module_.get())) {
errorf(type_position,
"Shared table %i must have shared element type, actual "
"type %s",
i, type.name().c_str());
break;
}
}
// Note that we should not throw an error if the declared maximum size
// is oob. We will instead fail when growing at runtime.
uint64_t kNoMaximum = kMaxUInt64;
consume_resizable_limits(
"table", "elements", wasm::max_table_size(), &table->initial_size,
table->has_maximum_size, kNoMaximum, &table->maximum_size,
table->is_table64() ? k64BitLimits : k32BitLimits);
break;
}
case kExternalMemory: {