-
Notifications
You must be signed in to change notification settings - Fork 725
/
Copy pathinterp.cc
2807 lines (2478 loc) · 95.9 KB
/
interp.cc
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 2020 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "wabt/interp/interp.h"
#include <algorithm>
#include <cassert>
#include <cinttypes>
#include "wabt/interp/interp-math.h"
namespace wabt {
namespace interp {
const char* GetName(Mutability mut) {
static const char* kNames[] = {"immutable", "mutable"};
return kNames[int(mut)];
}
const std::string GetName(ValueType type) {
return type.GetName();
}
const char* GetName(ExternKind kind) {
return GetKindName(kind);
}
const char* GetName(ObjectKind kind) {
static const char* kNames[] = {
"Null", "Foreign", "Trap", "Exception", "DefinedFunc", "HostFunc",
"Table", "Memory", "Global", "Tag", "Module", "Instance",
};
WABT_STATIC_ASSERT(WABT_ARRAY_SIZE(kNames) == kCommandTypeCount);
return kNames[int(kind)];
}
//// Refs ////
// static
const Ref Ref::Null{0};
//// Limits ////
Result Match(const Limits& expected,
const Limits& actual,
std::string* out_msg) {
if (actual.initial < expected.initial) {
*out_msg = StringPrintf("actual size (%" PRIu64
") smaller than declared (%" PRIu64 ")",
actual.initial, expected.initial);
return Result::Error;
}
if (expected.has_max) {
if (!actual.has_max) {
*out_msg = StringPrintf(
"max size (unspecified) larger than declared (%" PRIu64 ")",
expected.max);
return Result::Error;
} else if (actual.max > expected.max) {
*out_msg = StringPrintf("max size (%" PRIu64
") larger than declared (%" PRIu64 ")",
actual.max, expected.max);
return Result::Error;
}
}
if (expected.is_64 && !actual.is_64) {
*out_msg = StringPrintf("expected i64 memory, but i32 memory provided");
return Result::Error;
} else if (actual.is_64 && !expected.is_64) {
*out_msg = StringPrintf("expected i32 memory, but i64 memory provided");
return Result::Error;
}
return Result::Ok;
}
//// FuncType ////
std::unique_ptr<ExternType> FuncType::Clone() const {
return std::make_unique<FuncType>(*this);
}
Result Match(const FuncType& expected,
const FuncType& actual,
std::string* out_msg) {
if (expected.params != actual.params || expected.results != actual.results) {
if (out_msg) {
*out_msg = "import signature mismatch";
}
return Result::Error;
}
return Result::Ok;
}
//// TableType ////
std::unique_ptr<ExternType> TableType::Clone() const {
return std::make_unique<TableType>(*this);
}
Result Match(const TableType& expected,
const TableType& actual,
std::string* out_msg) {
if (expected.element != actual.element) {
*out_msg = StringPrintf(
"type mismatch in imported table, expected %s but got %s.",
GetName(expected.element).c_str(), GetName(actual.element).c_str());
return Result::Error;
}
if (Failed(Match(expected.limits, actual.limits, out_msg))) {
return Result::Error;
}
return Result::Ok;
}
//// MemoryType ////
std::unique_ptr<ExternType> MemoryType::Clone() const {
return std::make_unique<MemoryType>(*this);
}
Result Match(const MemoryType& expected,
const MemoryType& actual,
std::string* out_msg) {
if (expected.page_size != actual.page_size) {
*out_msg = StringPrintf(
"page_size mismatch in imported memory, expected %u but got %u.",
expected.page_size, actual.page_size);
return Result::Error;
}
return Match(expected.limits, actual.limits, out_msg);
}
//// GlobalType ////
std::unique_ptr<ExternType> GlobalType::Clone() const {
return std::make_unique<GlobalType>(*this);
}
Result Match(const GlobalType& expected,
const GlobalType& actual,
std::string* out_msg) {
if (actual.mut != expected.mut) {
*out_msg = StringPrintf(
"mutability mismatch in imported global, expected %s but got %s.",
GetName(actual.mut), GetName(expected.mut));
return Result::Error;
}
if (actual.type != expected.type &&
(expected.mut == Mutability::Var ||
!TypesMatch(expected.type, actual.type))) {
*out_msg = StringPrintf(
"type mismatch in imported global, expected %s but got %s.",
GetName(expected.type).c_str(), GetName(actual.type).c_str());
return Result::Error;
}
return Result::Ok;
}
//// TagType ////
std::unique_ptr<ExternType> TagType::Clone() const {
return std::make_unique<TagType>(*this);
}
Result Match(const TagType& expected,
const TagType& actual,
std::string* out_msg) {
if (expected.signature != actual.signature) {
if (out_msg) {
*out_msg = "signature mismatch in imported tag";
}
return Result::Error;
}
return Result::Ok;
}
//// Limits ////
template <typename T>
bool CanGrow(const Limits& limits, T old_size, T delta, T* new_size) {
if (limits.max >= delta && old_size <= limits.max - delta) {
*new_size = old_size + delta;
return true;
}
return false;
}
//// FuncDesc ////
ValueType FuncDesc::GetLocalType(Index index) const {
if (index < type.params.size()) {
return type.params[index];
}
index -= type.params.size();
auto iter = std::lower_bound(
locals.begin(), locals.end(), index + 1,
[](const LocalDesc& lhs, Index rhs) { return lhs.end < rhs; });
assert(iter != locals.end());
return iter->type;
}
//// Store ////
Store::Store(const Features& features) : features_(features) {
Ref ref{objects_.New(new Object(ObjectKind::Null))};
assert(ref == Ref::Null);
roots_.New(ref);
}
#ifndef NDEBUG
bool Store::HasValueType(Ref ref, ValueType type) const {
// TODO opt?
if (!IsValid(ref)) {
return false;
}
if (type == ValueType::ExternRef) {
return true;
}
if (ref == Ref::Null) {
return true;
}
Object* obj = objects_.Get(ref.index);
switch (type) {
case ValueType::FuncRef:
return obj->kind() == ObjectKind::DefinedFunc ||
obj->kind() == ObjectKind::HostFunc;
case ValueType::ExnRef:
return obj->kind() == ObjectKind::Exception;
default:
return false;
}
}
#endif
Store::RootList::Index Store::NewRoot(Ref ref) {
return roots_.New(ref);
}
Store::RootList::Index Store::CopyRoot(RootList::Index index) {
// roots_.Get() returns a reference to an element in an internal vector, and
// roots_.New() might forward its arguments to emplace_back on the same
// vector. This seems to "work" in most environments, but fails on Visual
// Studio 2015 Win64. Copying it to a value fixes the issue.
auto obj_index = roots_.Get(index);
return roots_.New(obj_index);
}
void Store::DeleteRoot(RootList::Index index) {
roots_.Delete(index);
}
void Store::Collect() {
size_t object_count = objects_.size();
assert(gc_context_.call_depth == 0);
gc_context_.marks.resize(object_count);
std::fill(gc_context_.marks.begin(), gc_context_.marks.end(), false);
// First mark all roots.
for (RootList::Index i = 0; i < roots_.size(); ++i) {
if (roots_.IsUsed(i)) {
Mark(roots_.Get(i));
}
}
for (auto thread : threads_) {
thread->Mark();
}
// This vector is often empty since the default maximum
// recursion is usually enough to mark all objects.
while (WABT_UNLIKELY(!gc_context_.untraced_objects.empty())) {
size_t index = gc_context_.untraced_objects.back();
assert(gc_context_.marks[index]);
assert(gc_context_.call_depth == 0);
gc_context_.untraced_objects.pop_back();
objects_.Get(index)->Mark(*this);
}
assert(gc_context_.call_depth == 0);
// Delete all unmarked objects.
for (size_t i = 0; i < object_count; ++i) {
if (objects_.IsUsed(i) && !gc_context_.marks[i]) {
objects_.Delete(i);
}
}
}
void Store::Mark(Ref ref) {
size_t index = ref.index;
if (gc_context_.marks[index])
return;
gc_context_.marks[index] = true;
if (WABT_UNLIKELY(gc_context_.call_depth >= max_call_depth)) {
gc_context_.untraced_objects.push_back(index);
return;
}
gc_context_.call_depth++;
objects_.Get(index)->Mark(*this);
gc_context_.call_depth--;
}
void Store::Mark(const RefVec& refs) {
for (auto&& ref : refs) {
Mark(ref);
}
}
//// Object ////
Object::~Object() {
if (finalizer_) {
finalizer_(this);
}
}
//// Foreign ////
Foreign::Foreign(Store&, void* ptr) : Object(skind), ptr_(ptr) {}
void Foreign::Mark(Store&) {}
//// Frame ////
void Frame::Mark(Store& store) {
store.Mark(func);
}
//// Trap ////
Trap::Trap(Store& store,
const std::string& msg,
const std::vector<Frame>& trace)
: Object(skind), message_(msg), trace_(trace) {}
void Trap::Mark(Store& store) {
for (auto&& frame : trace_) {
frame.Mark(store);
}
}
//// Exception ////
Exception::Exception(Store& store, Ref tag, Values& args)
: Object(skind), tag_(tag), args_(args) {}
void Exception::Mark(Store& store) {
Tag::Ptr tag(store, tag_);
store.Mark(tag_);
ValueTypes params = tag->type().signature;
for (size_t i = 0; i < params.size(); i++) {
if (params[i].IsRef()) {
store.Mark(args_[i].Get<Ref>());
}
}
}
//// Extern ////
template <typename T>
Result Extern::MatchImpl(Store& store,
const ImportType& import_type,
const T& actual,
Trap::Ptr* out_trap) {
const T* extern_type = dyn_cast<T>(import_type.type.get());
if (!extern_type) {
*out_trap = Trap::New(
store,
StringPrintf("expected import \"%s.%s\" to have kind %s, not %s",
import_type.module.c_str(), import_type.name.c_str(),
GetName(import_type.type->kind), GetName(T::skind)));
return Result::Error;
}
std::string msg;
if (Failed(interp::Match(*extern_type, actual, &msg))) {
*out_trap = Trap::New(store, msg);
return Result::Error;
}
return Result::Ok;
}
//// Func ////
Func::Func(ObjectKind kind, FuncType type) : Extern(kind), type_(type) {}
Result Func::Call(Store& store,
const Values& params,
Values& results,
Trap::Ptr* out_trap,
Stream* trace_stream) {
Thread thread(store, trace_stream);
return DoCall(thread, params, results, out_trap);
}
Result Func::Call(Thread& thread,
const Values& params,
Values& results,
Trap::Ptr* out_trap) {
return DoCall(thread, params, results, out_trap);
}
//// DefinedFunc ////
DefinedFunc::DefinedFunc(Store& store, Ref instance, FuncDesc desc)
: Func(skind, desc.type), instance_(instance), desc_(desc) {}
void DefinedFunc::Mark(Store& store) {
store.Mark(instance_);
}
Result DefinedFunc::Match(Store& store,
const ImportType& import_type,
Trap::Ptr* out_trap) {
return MatchImpl(store, import_type, type_, out_trap);
}
Result DefinedFunc::DoCall(Thread& thread,
const Values& params,
Values& results,
Trap::Ptr* out_trap) {
assert(params.size() == type_.params.size());
thread.PushValues(type_.params, params);
RunResult result = thread.PushCall(*this, out_trap);
if (result == RunResult::Trap) {
return Result::Error;
}
result = thread.Run(out_trap);
if (result == RunResult::Trap) {
return Result::Error;
} else if (result == RunResult::Exception) {
// While this is not actually a trap, it is a convenient way
// to report an uncaught exception.
*out_trap = Trap::New(thread.store(), "uncaught exception");
return Result::Error;
}
thread.PopValues(type_.results, &results);
return Result::Ok;
}
//// HostFunc ////
HostFunc::HostFunc(Store&, FuncType type, Callback callback)
: Func(skind, type), callback_(callback) {}
void HostFunc::Mark(Store&) {}
Result HostFunc::Match(Store& store,
const ImportType& import_type,
Trap::Ptr* out_trap) {
return MatchImpl(store, import_type, type_, out_trap);
}
Result HostFunc::DoCall(Thread& thread,
const Values& params,
Values& results,
Trap::Ptr* out_trap) {
return callback_(thread, params, results, out_trap);
}
//// Table ////
Table::Table(Store&, TableType type) : Extern(skind), type_(type) {
elements_.resize(type.limits.initial);
}
void Table::Mark(Store& store) {
store.Mark(elements_);
}
Result Table::Match(Store& store,
const ImportType& import_type,
Trap::Ptr* out_trap) {
return MatchImpl(store, import_type, type_, out_trap);
}
bool Table::IsValidRange(u32 offset, u32 size) const {
size_t elem_size = elements_.size();
return size <= elem_size && offset <= elem_size - size;
}
Result Table::Get(u32 offset, Ref* out) const {
if (IsValidRange(offset, 1)) {
*out = elements_[offset];
return Result::Ok;
}
return Result::Error;
}
Ref Table::UnsafeGet(u32 offset) const {
assert(IsValidRange(offset, 1));
return elements_[offset];
}
Result Table::Set(Store& store, u32 offset, Ref ref) {
assert(store.HasValueType(ref, type_.element));
if (IsValidRange(offset, 1)) {
elements_[offset] = ref;
return Result::Ok;
}
return Result::Error;
}
Result Table::Grow(Store& store, u32 count, Ref ref) {
size_t old_size = elements_.size();
u32 new_size;
assert(store.HasValueType(ref, type_.element));
if (CanGrow<u32>(type_.limits, old_size, count, &new_size)) {
// Grow the limits of the table too, so that if it is used as an
// import to another module its new size is honored.
type_.limits.initial += count;
elements_.resize(new_size);
Fill(store, old_size, ref, new_size - old_size);
return Result::Ok;
}
return Result::Error;
}
Result Table::Fill(Store& store, u32 offset, Ref ref, u32 size) {
assert(store.HasValueType(ref, type_.element));
if (IsValidRange(offset, size)) {
std::fill(elements_.begin() + offset, elements_.begin() + offset + size,
ref);
return Result::Ok;
}
return Result::Error;
}
Result Table::Init(Store& store,
u32 dst_offset,
const ElemSegment& src,
u32 src_offset,
u32 size) {
if (IsValidRange(dst_offset, size) && src.IsValidRange(src_offset, size) &&
TypesMatch(type_.element, src.desc().type)) {
std::copy(src.elements().begin() + src_offset,
src.elements().begin() + src_offset + size,
elements_.begin() + dst_offset);
return Result::Ok;
}
return Result::Error;
}
// static
Result Table::Copy(Store& store,
Table& dst,
u32 dst_offset,
const Table& src,
u32 src_offset,
u32 size) {
if (dst.IsValidRange(dst_offset, size) &&
src.IsValidRange(src_offset, size) &&
TypesMatch(dst.type_.element, src.type_.element)) {
auto src_begin = src.elements_.begin() + src_offset;
auto src_end = src_begin + size;
auto dst_begin = dst.elements_.begin() + dst_offset;
auto dst_end = dst_begin + size;
if (dst.self() == src.self() && src_begin < dst_begin) {
std::move_backward(src_begin, src_end, dst_end);
} else {
std::move(src_begin, src_end, dst_begin);
}
return Result::Ok;
}
return Result::Error;
}
//// Memory ////
Memory::Memory(class Store&, MemoryType type)
: Extern(skind), type_(type), pages_(type.limits.initial) {
data_.resize(pages_ * type_.page_size);
}
void Memory::Mark(class Store&) {}
Result Memory::Match(class Store& store,
const ImportType& import_type,
Trap::Ptr* out_trap) {
return MatchImpl(store, import_type, type_, out_trap);
}
Result Memory::Grow(u64 count) {
u64 new_pages;
if (CanGrow<u64>(type_.limits, pages_, count, &new_pages)) {
// Grow the limits of the memory too, so that if it is used as an
// import to another module its new size is honored.
type_.limits.initial += count;
#if WABT_BIG_ENDIAN
auto old_size = data_.size();
#endif
pages_ = new_pages;
data_.resize(new_pages * type_.page_size);
#if WABT_BIG_ENDIAN
std::move_backward(data_.begin(), data_.begin() + old_size, data_.end());
std::fill(data_.begin(), data_.end() - old_size, 0);
#endif
return Result::Ok;
}
return Result::Error;
}
Result Memory::Fill(u64 offset, u8 value, u64 size) {
if (IsValidAccess(offset, 0, size)) {
#if WABT_BIG_ENDIAN
std::fill(data_.end() - offset - size, data_.end() - offset, value);
#else
std::fill(data_.begin() + offset, data_.begin() + offset + size, value);
#endif
return Result::Ok;
}
return Result::Error;
}
Result Memory::Init(u64 dst_offset,
const DataSegment& src,
u64 src_offset,
u64 size) {
if (IsValidAccess(dst_offset, 0, size) &&
src.IsValidRange(src_offset, size)) {
std::copy(src.desc().data.begin() + src_offset,
src.desc().data.begin() + src_offset + size,
#if WABT_BIG_ENDIAN
data_.rbegin() + dst_offset);
#else
data_.begin() + dst_offset);
#endif
return Result::Ok;
}
return Result::Error;
}
// static
Result Memory::Copy(Memory& dst,
u64 dst_offset,
const Memory& src,
u64 src_offset,
u64 size) {
if (dst.IsValidAccess(dst_offset, 0, size) &&
src.IsValidAccess(src_offset, 0, size)) {
#if WABT_BIG_ENDIAN
auto src_begin = src.data_.end() - src_offset - size;
auto dst_begin = dst.data_.end() - dst_offset - size;
#else
auto src_begin = src.data_.begin() + src_offset;
auto dst_begin = dst.data_.begin() + dst_offset;
#endif
auto src_end = src_begin + size;
auto dst_end = dst_begin + size;
if (src.self() == dst.self() && src_begin < dst_begin) {
std::move_backward(src_begin, src_end, dst_end);
} else {
std::move(src_begin, src_end, dst_begin);
}
return Result::Ok;
}
return Result::Error;
}
Result Instance::CallInitFunc(Store& store,
const Ref func_ref,
Value* result,
Trap::Ptr* out_trap) {
Values results;
Func::Ptr func{store, func_ref};
if (Failed(func->Call(store, {}, results, out_trap))) {
return Result::Error;
}
assert(results.size() == 1);
*result = results[0];
return Result::Ok;
}
//// Global ////
Global::Global(Store& store, GlobalType type, Value value)
: Extern(skind), type_(type), value_(value) {}
void Global::Mark(Store& store) {
if (IsReference(type_.type)) {
store.Mark(value_.Get<Ref>());
}
}
Result Global::Match(Store& store,
const ImportType& import_type,
Trap::Ptr* out_trap) {
return MatchImpl(store, import_type, type_, out_trap);
}
void Global::Set(Store& store, Ref ref) {
assert(store.HasValueType(ref, type_.type));
value_.Set(ref);
}
void Global::UnsafeSet(Value value) {
value_ = value;
}
//// Tag ////
Tag::Tag(Store&, TagType type) : Extern(skind), type_(type) {}
void Tag::Mark(Store&) {}
Result Tag::Match(Store& store,
const ImportType& import_type,
Trap::Ptr* out_trap) {
return MatchImpl(store, import_type, type_, out_trap);
}
//// ElemSegment ////
ElemSegment::ElemSegment(Store& store,
const ElemDesc* desc,
Instance::Ptr& inst)
: desc_(desc) {
Trap::Ptr out_trap;
elements_.reserve(desc->elements.size());
for (auto&& elem_expr : desc->elements) {
Value value;
Ref func_ref = DefinedFunc::New(store, inst.ref(), elem_expr).ref();
if (Failed(inst->CallInitFunc(store, func_ref, &value, &out_trap))) {
WABT_UNREACHABLE; // valid const expression cannot trap
}
elements_.push_back(value.Get<Ref>());
}
}
bool ElemSegment::IsValidRange(u32 offset, u32 size) const {
u32 elem_size = this->size();
return size <= elem_size && offset <= elem_size - size;
}
//// DataSegment ////
DataSegment::DataSegment(const DataDesc* desc)
: desc_(desc), size_(desc->data.size()) {}
bool DataSegment::IsValidRange(u64 offset, u64 size) const {
u64 data_size = size_;
return size <= data_size && offset <= data_size - size;
}
//// Module ////
Module::Module(Store&, ModuleDesc desc)
: Object(skind), desc_(std::move(desc)) {
for (auto&& import : desc_.imports) {
import_types_.emplace_back(import.type);
}
for (auto&& export_ : desc_.exports) {
export_types_.emplace_back(export_.type);
}
}
void Module::Mark(Store&) {}
//// ElemSegment ////
void ElemSegment::Mark(Store& store) {
store.Mark(elements_);
}
//// Instance ////
Instance::Instance(Store& store, Ref module) : Object(skind), module_(module) {
assert(store.Is<Module>(module));
}
// static
Instance::Ptr Instance::Instantiate(Store& store,
Ref module,
const RefVec& imports,
Trap::Ptr* out_trap) {
Module::Ptr mod{store, module};
Instance::Ptr inst = store.Alloc<Instance>(store, module);
size_t import_desc_count = mod->desc().imports.size();
if (imports.size() < import_desc_count) {
*out_trap = Trap::New(store, "not enough imports!");
return {};
}
// Imports.
for (size_t i = 0; i < import_desc_count; ++i) {
auto&& import_desc = mod->desc().imports[i];
Ref extern_ref = imports[i];
if (extern_ref == Ref::Null) {
*out_trap = Trap::New(store, StringPrintf("invalid import \"%s.%s\"",
import_desc.type.module.c_str(),
import_desc.type.name.c_str()));
return {};
}
Extern::Ptr extern_{store, extern_ref};
if (Failed(extern_->Match(store, import_desc.type, out_trap))) {
return {};
}
inst->imports_.push_back(extern_ref);
switch (import_desc.type.type->kind) {
case ExternKind::Func: inst->funcs_.push_back(extern_ref); break;
case ExternKind::Table: inst->tables_.push_back(extern_ref); break;
case ExternKind::Memory: inst->memories_.push_back(extern_ref); break;
case ExternKind::Global: inst->globals_.push_back(extern_ref); break;
case ExternKind::Tag: inst->tags_.push_back(extern_ref); break;
}
}
// Funcs.
for (auto&& desc : mod->desc().funcs) {
inst->funcs_.push_back(DefinedFunc::New(store, inst.ref(), desc).ref());
}
// Tables.
for (auto&& desc : mod->desc().tables) {
inst->tables_.push_back(Table::New(store, desc.type).ref());
}
// Memories.
for (auto&& desc : mod->desc().memories) {
inst->memories_.push_back(Memory::New(store, desc.type).ref());
}
// Globals.
for (auto&& desc : mod->desc().globals) {
Value value;
Ref func_ref = DefinedFunc::New(store, inst.ref(), desc.init_func).ref();
if (Failed(inst->CallInitFunc(store, func_ref, &value, out_trap))) {
return {};
}
inst->globals_.push_back(Global::New(store, desc.type, value).ref());
}
// Tags.
for (auto&& desc : mod->desc().tags) {
inst->tags_.push_back(Tag::New(store, desc.type).ref());
}
// Exports.
for (auto&& desc : mod->desc().exports) {
Ref ref;
switch (desc.type.type->kind) {
case ExternKind::Func: ref = inst->funcs_[desc.index]; break;
case ExternKind::Table: ref = inst->tables_[desc.index]; break;
case ExternKind::Memory: ref = inst->memories_[desc.index]; break;
case ExternKind::Global: ref = inst->globals_[desc.index]; break;
case ExternKind::Tag: ref = inst->tags_[desc.index]; break;
}
inst->exports_.push_back(ref);
}
// Elems.
for (auto&& desc : mod->desc().elems) {
inst->elems_.emplace_back(store, &desc, inst);
}
// Datas.
for (auto&& desc : mod->desc().datas) {
inst->datas_.emplace_back(&desc);
}
// Initialization.
// The MVP requires that all segments are bounds-checked before being copied
// into the table or memory. The bulk memory proposal changes this behavior;
// instead, each segment is copied in order. If any segment fails, then no
// further segments are copied. Any data that was written persists.
enum Pass { Check, Init };
int pass = store.features().bulk_memory_enabled() ? Init : Check;
for (; pass <= Init; ++pass) {
// Elems.
for (auto&& segment : inst->elems_) {
auto&& desc = segment.desc();
if (desc.mode == SegmentMode::Active) {
Result result;
Table::Ptr table{store, inst->tables_[desc.table_index]};
Value value;
Ref func_ref =
DefinedFunc::New(store, inst.ref(), desc.init_func).ref();
if (Failed(inst->CallInitFunc(store, func_ref, &value, out_trap))) {
return {};
}
u64 offset;
if (table->type().limits.is_64) {
offset = value.Get<u64>();
} else {
offset = value.Get<u32>();
}
if (pass == Check) {
result = table->IsValidRange(offset, segment.size()) ? Result::Ok
: Result::Error;
} else {
result = table->Init(store, offset, segment, 0, segment.size());
if (Succeeded(result)) {
segment.Drop();
}
}
if (Failed(result)) {
*out_trap = Trap::New(
store,
StringPrintf("out of bounds table access: elem segment is "
"out of bounds: [%" PRIu64 ", %" PRIu64
") >= max value %u",
offset, offset + segment.size(), table->size()));
return {};
}
} else if (desc.mode == SegmentMode::Declared) {
segment.Drop();
}
}
// Data.
for (auto&& segment : inst->datas_) {
auto&& desc = segment.desc();
if (desc.mode == SegmentMode::Active) {
Result result;
Memory::Ptr memory{store, inst->memories_[desc.memory_index]};
Value offset_op;
Ref func_ref =
DefinedFunc::New(store, inst.ref(), desc.init_func).ref();
if (Failed(inst->CallInitFunc(store, func_ref, &offset_op, out_trap))) {
return {};
}
u64 offset = memory->type().limits.is_64 ? offset_op.Get<u64>()
: offset_op.Get<u32>();
if (pass == Check) {
result = memory->IsValidAccess(offset, 0, segment.size())
? Result::Ok
: Result::Error;
} else {
result = memory->Init(offset, segment, 0, segment.size());
if (Succeeded(result)) {
segment.Drop();
}
}
if (Failed(result)) {
*out_trap = Trap::New(
store, StringPrintf(
"out of bounds memory access: data segment is "
"out of bounds: [%" PRIu64 ", %" PRIu64
") >= max value %" PRIu64,
offset, offset + segment.size(), memory->ByteSize()));
return {};
}
} else if (desc.mode == SegmentMode::Declared) {
segment.Drop();
}
}
}
// Start.
for (auto&& start : mod->desc().starts) {
Func::Ptr func{store, inst->funcs_[start.func_index]};
Values results;
if (Failed(func->Call(store, {}, results, out_trap))) {
return {};
}
}
return inst;
}
void Instance::Mark(Store& store) {
store.Mark(module_);
store.Mark(imports_);
store.Mark(funcs_);
store.Mark(memories_);
store.Mark(tables_);
store.Mark(globals_);
store.Mark(tags_);
store.Mark(exports_);
for (auto&& elem : elems_) {
elem.Mark(store);
}
}
//// Thread ////
Thread::Thread(Store& store, Stream* trace_stream)
: store_(store), trace_stream_(trace_stream) {
store.threads().insert(this);
Thread::Options options;
frames_.reserve(options.call_stack_size);
values_.reserve(options.value_stack_size);
if (trace_stream) {
trace_source_ = std::make_unique<TraceSource>(this);
}