-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathwasm-objects.cc
More file actions
3029 lines (2744 loc) Β· 122 KB
/
wasm-objects.cc
File metadata and controls
3029 lines (2744 loc) Β· 122 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/wasm-objects.h"
#include <optional>
#include "src/base/iterator.h"
#include "src/base/vector.h"
#include "src/builtins/builtins-inl.h"
#include "src/compiler/wasm-compiler.h"
#include "src/debug/debug.h"
#include "src/logging/counters.h"
#include "src/objects/managed-inl.h"
#include "src/objects/objects-inl.h"
#include "src/objects/oddball.h"
#include "src/objects/shared-function-info.h"
#include "src/roots/roots-inl.h"
#include "src/utils/utils.h"
#include "src/wasm/code-space-access.h"
#include "src/wasm/compilation-environment-inl.h"
#include "src/wasm/module-compiler.h"
#include "src/wasm/module-decoder.h"
#include "src/wasm/module-instantiate.h"
#include "src/wasm/serialized-signature-inl.h"
#include "src/wasm/signature-hashing.h"
#include "src/wasm/stacks.h"
#include "src/wasm/value-type.h"
#include "src/wasm/wasm-code-manager.h"
#include "src/wasm/wasm-engine.h"
#include "src/wasm/wasm-limits.h"
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-objects-inl.h"
#include "src/wasm/wasm-subtyping.h"
#include "src/wasm/wasm-value.h"
#if V8_ENABLE_DRUMBRAKE
#include "src/wasm/interpreter/wasm-interpreter-inl.h"
#include "src/wasm/interpreter/wasm-interpreter-runtime.h"
#endif // V8_ENABLE_DRUMBRAKE
// Needs to be last so macros do not get undefined.
#include "src/objects/object-macros.h"
#define TRACE_IFT(...) \
do { \
if (false) PrintF(__VA_ARGS__); \
} while (false)
namespace v8 {
namespace internal {
// Import a few often used types from the wasm namespace.
using WasmFunction = wasm::WasmFunction;
using WasmModule = wasm::WasmModule;
namespace {
// The WasmTableObject::uses field holds pairs of <instance, index>. This enum
// helps compute the respective offset.
enum TableUses : int {
kInstanceOffset,
kIndexOffset,
// Marker:
kNumElements
};
} // namespace
// static
Handle<WasmModuleObject> WasmModuleObject::New(
Isolate* isolate, std::shared_ptr<wasm::NativeModule> native_module,
DirectHandle<Script> script) {
DirectHandle<Managed<wasm::NativeModule>> managed_native_module;
if (script->type() == Script::Type::kWasm) {
managed_native_module = direct_handle(
Cast<Managed<wasm::NativeModule>>(script->wasm_managed_native_module()),
isolate);
} else {
const WasmModule* module = native_module->module();
size_t memory_estimate =
native_module->committed_code_space() +
wasm::WasmCodeManager::EstimateNativeModuleMetaDataSize(module);
managed_native_module = Managed<wasm::NativeModule>::From(
isolate, memory_estimate, std::move(native_module));
}
Handle<WasmModuleObject> module_object = Cast<WasmModuleObject>(
isolate->factory()->NewJSObject(isolate->wasm_module_constructor()));
module_object->set_managed_native_module(*managed_native_module);
module_object->set_script(*script);
return module_object;
}
Handle<String> WasmModuleObject::ExtractUtf8StringFromModuleBytes(
Isolate* isolate, DirectHandle<WasmModuleObject> module_object,
wasm::WireBytesRef ref, InternalizeString internalize) {
base::Vector<const uint8_t> wire_bytes =
module_object->native_module()->wire_bytes();
return ExtractUtf8StringFromModuleBytes(isolate, wire_bytes, ref,
internalize);
}
Handle<String> WasmModuleObject::ExtractUtf8StringFromModuleBytes(
Isolate* isolate, base::Vector<const uint8_t> wire_bytes,
wasm::WireBytesRef ref, InternalizeString internalize) {
base::Vector<const uint8_t> name_vec =
wire_bytes.SubVector(ref.offset(), ref.end_offset());
// UTF8 validation happens at decode time.
DCHECK(unibrow::Utf8::ValidateEncoding(name_vec.begin(), name_vec.length()));
auto* factory = isolate->factory();
return internalize
? factory->InternalizeUtf8String(
base::Vector<const char>::cast(name_vec))
: factory
->NewStringFromUtf8(base::Vector<const char>::cast(name_vec))
.ToHandleChecked();
}
MaybeHandle<String> WasmModuleObject::GetModuleNameOrNull(
Isolate* isolate, DirectHandle<WasmModuleObject> module_object) {
const WasmModule* module = module_object->module();
if (!module->name.is_set()) return {};
return ExtractUtf8StringFromModuleBytes(isolate, module_object, module->name,
kNoInternalize);
}
MaybeHandle<String> WasmModuleObject::GetFunctionNameOrNull(
Isolate* isolate, DirectHandle<WasmModuleObject> module_object,
uint32_t func_index) {
DCHECK_LT(func_index, module_object->module()->functions.size());
wasm::WireBytesRef name =
module_object->module()->lazily_generated_names.LookupFunctionName(
wasm::ModuleWireBytes(module_object->native_module()->wire_bytes()),
func_index);
if (!name.is_set()) return {};
return ExtractUtf8StringFromModuleBytes(isolate, module_object, name,
kNoInternalize);
}
base::Vector<const uint8_t> WasmModuleObject::GetRawFunctionName(
int func_index) {
if (func_index == wasm::kAnonymousFuncIndex) {
return base::Vector<const uint8_t>({nullptr, 0});
}
DCHECK_GT(module()->functions.size(), func_index);
wasm::ModuleWireBytes wire_bytes(native_module()->wire_bytes());
wasm::WireBytesRef name_ref =
module()->lazily_generated_names.LookupFunctionName(wire_bytes,
func_index);
wasm::WasmName name = wire_bytes.GetNameOrNull(name_ref);
return base::Vector<const uint8_t>::cast(name);
}
Handle<WasmTableObject> WasmTableObject::New(
Isolate* isolate, Handle<WasmTrustedInstanceData> trusted_data,
wasm::ValueType type, uint32_t initial, bool has_maximum, uint32_t maximum,
DirectHandle<Object> initial_value, WasmTableFlag table_type) {
CHECK(type.is_object_reference());
DCHECK_LE(initial, v8_flags.wasm_max_table_size);
DirectHandle<FixedArray> entries = isolate->factory()->NewFixedArray(initial);
for (int i = 0; i < static_cast<int>(initial); ++i) {
entries->set(i, *initial_value);
}
DirectHandle<UnionOf<Number, Undefined>> max;
if (has_maximum) {
max = isolate->factory()->NewNumberFromUint(maximum);
} else {
max = isolate->factory()->undefined_value();
}
Handle<JSFunction> table_ctor(
isolate->native_context()->wasm_table_constructor(), isolate);
auto table_obj =
Cast<WasmTableObject>(isolate->factory()->NewJSObject(table_ctor));
DisallowGarbageCollection no_gc;
if (!trusted_data.is_null()) {
table_obj->set_trusted_data(*trusted_data);
} else {
table_obj->clear_trusted_data();
}
table_obj->set_entries(*entries);
table_obj->set_current_length(initial);
table_obj->set_maximum_length(*max);
table_obj->set_raw_type(static_cast<int>(type.raw_bit_field()));
table_obj->set_is_table64(table_type == WasmTableFlag::kTable64);
table_obj->set_uses(ReadOnlyRoots(isolate).empty_fixed_array());
return table_obj;
}
void WasmTableObject::AddUse(Isolate* isolate,
DirectHandle<WasmTableObject> table_obj,
Handle<WasmInstanceObject> instance_object,
int table_index) {
DirectHandle<FixedArray> old_uses(table_obj->uses(), isolate);
int old_length = old_uses->length();
DCHECK_EQ(0, old_length % TableUses::kNumElements);
if (instance_object.is_null()) return;
// TODO(titzer): use weak cells here to avoid leaking instances.
// Grow the uses table and add a new entry at the end.
DirectHandle<FixedArray> new_uses = isolate->factory()->CopyFixedArrayAndGrow(
old_uses, TableUses::kNumElements);
new_uses->set(old_length + TableUses::kInstanceOffset, *instance_object);
new_uses->set(old_length + TableUses::kIndexOffset,
Smi::FromInt(table_index));
table_obj->set_uses(*new_uses);
}
int WasmTableObject::Grow(Isolate* isolate, DirectHandle<WasmTableObject> table,
uint32_t count, DirectHandle<Object> init_value) {
uint32_t old_size = table->current_length();
if (count == 0) return old_size; // Degenerate case: nothing to do.
// Check if growing by {count} is valid.
uint32_t max_size;
if (!Object::ToUint32(table->maximum_length(), &max_size)) {
max_size = v8_flags.wasm_max_table_size;
}
max_size = std::min(max_size, v8_flags.wasm_max_table_size.value());
DCHECK_LE(old_size, max_size);
if (max_size - old_size < count) return -1;
uint32_t new_size = old_size + count;
// Even with 2x over-allocation, there should not be an integer overflow.
static_assert(wasm::kV8MaxWasmTableSize <= kMaxInt / 2);
DCHECK_GE(kMaxInt, new_size);
int old_capacity = table->entries()->length();
if (new_size > static_cast<uint32_t>(old_capacity)) {
int grow = static_cast<int>(new_size) - old_capacity;
// Grow at least by the old capacity, to implement exponential growing.
grow = std::max(grow, old_capacity);
// Never grow larger than the max size.
grow = std::min(grow, static_cast<int>(max_size - old_capacity));
auto new_store = isolate->factory()->CopyFixedArrayAndGrow(
handle(table->entries(), isolate), grow);
table->set_entries(*new_store, WriteBarrierMode::UPDATE_WRITE_BARRIER);
}
table->set_current_length(new_size);
DirectHandle<FixedArray> uses(table->uses(), isolate);
DCHECK_EQ(0, uses->length() % TableUses::kNumElements);
// Tables are stored in the instance object, no code patching is
// necessary. We simply have to grow the raw tables in each instance
// that has imported this table.
// TODO(titzer): replace the dispatch table with a weak list of all
// the instances that import a given table.
for (int i = 0; i < uses->length(); i += TableUses::kNumElements) {
int table_index = Cast<Smi>(uses->get(i + TableUses::kIndexOffset)).value();
DirectHandle<WasmTrustedInstanceData> non_shared_trusted_instance_data{
Cast<WasmInstanceObject>(uses->get(i + TableUses::kInstanceOffset))
->trusted_data(isolate),
isolate};
bool is_shared =
non_shared_trusted_instance_data->module()->tables[table_index].shared;
DirectHandle<WasmTrustedInstanceData> trusted_instance_data =
is_shared
? handle(non_shared_trusted_instance_data->shared_part(), isolate)
: non_shared_trusted_instance_data;
DCHECK_EQ(old_size,
trusted_instance_data->dispatch_table(table_index)->length());
WasmTrustedInstanceData::EnsureMinimumDispatchTableSize(
isolate, trusted_instance_data, table_index, new_size);
#if V8_ENABLE_DRUMBRAKE
if (v8_flags.wasm_jitless &&
trusted_instance_data->has_interpreter_object()) {
wasm::WasmInterpreterRuntime::UpdateIndirectCallTable(
isolate, handle(trusted_instance_data->instance_object(), isolate),
table_index);
}
#endif // V8_ENABLE_DRUMBRAKE
}
for (uint32_t entry = old_size; entry < new_size; ++entry) {
WasmTableObject::Set(isolate, table, entry, init_value);
}
return old_size;
}
bool WasmTableObject::is_in_bounds(uint32_t entry_index) {
return entry_index < static_cast<uint32_t>(current_length());
}
MaybeHandle<Object> WasmTableObject::JSToWasmElement(
Isolate* isolate, DirectHandle<WasmTableObject> table, Handle<Object> entry,
const char** error_message) {
const WasmModule* module = !table->has_trusted_data()
? nullptr
: table->trusted_data(isolate)->module();
return wasm::JSToWasmObject(isolate, module, entry, table->type(),
error_message);
}
void WasmTableObject::SetFunctionTableEntry(Isolate* isolate,
DirectHandle<WasmTableObject> table,
int entry_index,
DirectHandle<Object> entry) {
if (IsWasmNull(*entry, isolate)) {
table->ClearDispatchTables(entry_index); // Degenerate case.
table->entries()->set(entry_index, ReadOnlyRoots(isolate).wasm_null());
return;
}
DCHECK(IsWasmFuncRef(*entry));
DirectHandle<Object> external = WasmInternalFunction::GetOrCreateExternal(
direct_handle(Cast<WasmFuncRef>(*entry)->internal(isolate), isolate));
if (WasmExportedFunction::IsWasmExportedFunction(*external)) {
auto exported_function = Cast<WasmExportedFunction>(external);
auto func_data = exported_function->shared()->wasm_exported_function_data();
DirectHandle<WasmTrustedInstanceData> target_instance_data(
func_data->instance_data(), isolate);
int func_index = func_data->function_index();
const WasmModule* module = target_instance_data->module();
SBXCHECK_BOUNDS(func_index, module->functions.size());
auto* wasm_function = module->functions.data() + func_index;
UpdateDispatchTables(isolate, table, entry_index, wasm_function,
target_instance_data
#if V8_ENABLE_DRUMBRAKE
,
func_index
#endif // V8_ENABLE_DRUMBRAKE
);
} else if (WasmJSFunction::IsWasmJSFunction(*external)) {
UpdateDispatchTables(isolate, table, entry_index,
Cast<WasmJSFunction>(external));
} else {
DCHECK(WasmCapiFunction::IsWasmCapiFunction(*external));
UpdateDispatchTables(isolate, table, entry_index,
Cast<WasmCapiFunction>(external));
}
table->entries()->set(entry_index, *entry);
}
// Note: This needs to be handlified because it transitively calls
// {ImportWasmJSFunctionIntoTable} which calls {NewWasmImportData}.
void WasmTableObject::Set(Isolate* isolate, DirectHandle<WasmTableObject> table,
uint32_t index, DirectHandle<Object> entry) {
// Callers need to perform bounds checks, type check, and error handling.
DCHECK(table->is_in_bounds(index));
DirectHandle<FixedArray> entries(table->entries(), isolate);
// The FixedArray is addressed with int's.
int entry_index = static_cast<int>(index);
switch (table->type().heap_representation_non_shared()) {
case wasm::HeapType::kExtern:
case wasm::HeapType::kString:
case wasm::HeapType::kStringViewWtf8:
case wasm::HeapType::kStringViewWtf16:
case wasm::HeapType::kStringViewIter:
case wasm::HeapType::kEq:
case wasm::HeapType::kStruct:
case wasm::HeapType::kArray:
case wasm::HeapType::kAny:
case wasm::HeapType::kI31:
case wasm::HeapType::kNone:
case wasm::HeapType::kNoFunc:
case wasm::HeapType::kNoExtern:
case wasm::HeapType::kExn:
case wasm::HeapType::kNoExn:
entries->set(entry_index, *entry);
return;
case wasm::HeapType::kFunc:
SetFunctionTableEntry(isolate, table, entry_index, entry);
return;
case wasm::HeapType::kBottom:
UNREACHABLE();
default:
DCHECK(table->has_trusted_data());
if (table->trusted_data(isolate)->module()->has_signature(
table->type().ref_index())) {
SetFunctionTableEntry(isolate, table, entry_index, entry);
return;
}
entries->set(entry_index, *entry);
return;
}
}
Handle<Object> WasmTableObject::Get(Isolate* isolate,
DirectHandle<WasmTableObject> table,
uint32_t index) {
DirectHandle<FixedArray> entries(table->entries(), isolate);
// Callers need to perform bounds checks and error handling.
DCHECK(table->is_in_bounds(index));
// The FixedArray is addressed with int's.
int entry_index = static_cast<int>(index);
Handle<Object> entry(entries->get(entry_index), isolate);
if (IsWasmNull(*entry, isolate)) return entry;
if (IsWasmFuncRef(*entry)) return entry;
switch (table->type().heap_representation_non_shared()) {
case wasm::HeapType::kStringViewWtf8:
case wasm::HeapType::kStringViewWtf16:
case wasm::HeapType::kStringViewIter:
case wasm::HeapType::kExtern:
case wasm::HeapType::kString:
case wasm::HeapType::kEq:
case wasm::HeapType::kI31:
case wasm::HeapType::kStruct:
case wasm::HeapType::kArray:
case wasm::HeapType::kAny:
case wasm::HeapType::kNone:
case wasm::HeapType::kNoFunc:
case wasm::HeapType::kNoExtern:
case wasm::HeapType::kExn:
case wasm::HeapType::kNoExn:
return entry;
case wasm::HeapType::kFunc:
// Placeholder; handled below.
break;
case wasm::HeapType::kBottom:
UNREACHABLE();
default:
DCHECK(table->has_trusted_data());
const WasmModule* module = table->trusted_data(isolate)->module();
if (module->has_array(table->type().ref_index()) ||
module->has_struct(table->type().ref_index())) {
return entry;
}
DCHECK(module->has_signature(table->type().ref_index()));
break;
}
// {entry} is not a valid entry in the table. It has to be a placeholder
// for lazy initialization.
DirectHandle<Tuple2> tuple = Cast<Tuple2>(entry);
auto trusted_instance_data =
handle(Cast<WasmInstanceObject>(tuple->value1())->trusted_data(isolate),
isolate);
int function_index = Cast<Smi>(tuple->value2()).value();
// Create a WasmInternalFunction and WasmFuncRef for the function if it does
// not exist yet, and store it in the table.
Handle<WasmFuncRef> func_ref = WasmTrustedInstanceData::GetOrCreateFuncRef(
isolate, trusted_instance_data, function_index);
entries->set(entry_index, *func_ref);
return func_ref;
}
void WasmTableObject::Fill(Isolate* isolate,
DirectHandle<WasmTableObject> table, uint32_t start,
DirectHandle<Object> entry, uint32_t count) {
// Bounds checks must be done by the caller.
DCHECK_LE(start, table->current_length());
DCHECK_LE(count, table->current_length());
DCHECK_LE(start + count, table->current_length());
for (uint32_t i = 0; i < count; i++) {
WasmTableObject::Set(isolate, table, start + i, entry);
}
}
#if V8_ENABLE_SANDBOX || DEBUG
bool FunctionSigMatchesTable(uint32_t canonical_sig_id,
const WasmModule* module, int table_index) {
wasm::ValueType table_type = module->tables[table_index].type;
DCHECK(table_type.is_object_reference());
// When in-sandbox data is corrupted, we can't trust the statically
// checked types; to prevent sandbox escapes, we have to verify actual
// types before installing the dispatch table entry. There are three
// alternative success conditions:
// (1) Generic "funcref" tables can hold any function entry.
if (table_type.heap_representation_non_shared() == wasm::HeapType::kFunc) {
return true;
}
// (2) Most function types are expected to be final, so they can be compared
// cheaply by canonicalized index equality.
uint32_t canonical_table_type =
module->isorecursive_canonical_type_ids[table_type.ref_index()];
if (V8_LIKELY(canonical_sig_id == canonical_table_type)) return true;
// (3) In the remaining cases, perform the full subtype check.
return wasm::GetWasmEngine()->type_canonicalizer()->IsCanonicalSubtype(
canonical_sig_id, canonical_table_type);
}
#endif // V8_ENABLE_SANDBOX || DEBUG
// static
void WasmTableObject::UpdateDispatchTables(
Isolate* isolate, DirectHandle<WasmTableObject> table, int entry_index,
const wasm::WasmFunction* func,
DirectHandle<WasmTrustedInstanceData> target_instance_data
#if V8_ENABLE_DRUMBRAKE
,
int target_func_index
#endif // V8_ENABLE_DRUMBRAKE
) {
// We simply need to update the IFTs for each instance that imports
// this table.
DirectHandle<FixedArray> uses(table->uses(), isolate);
DCHECK_EQ(0, uses->length() % TableUses::kNumElements);
DirectHandle<TrustedObject> call_ref =
func->imported
// The function in the target instance was imported. Use its imports
// table to look up the ref.
? direct_handle(Cast<TrustedObject>(
target_instance_data->dispatch_table_for_imports()
->implicit_arg(func->func_index)),
isolate)
// For wasm functions, just pass the target instance data.
: target_instance_data;
Address call_target = target_instance_data->GetCallTarget(func->func_index);
#if V8_ENABLE_DRUMBRAKE
if (target_func_index <
static_cast<int>(
target_instance_data->module()->num_imported_functions)) {
target_func_index = target_instance_data->imported_function_indices()->get(
target_func_index);
}
#endif // V8_ENABLE_DRUMBRAKE
const WasmModule* target_module = target_instance_data->module();
uint32_t canonical_sig_id =
target_module->isorecursive_canonical_type_ids[func->sig_index];
for (int i = 0, len = uses->length(); i < len; i += TableUses::kNumElements) {
int table_index = Cast<Smi>(uses->get(i + TableUses::kIndexOffset)).value();
DirectHandle<WasmInstanceObject> instance_object(
Cast<WasmInstanceObject>(uses->get(i + TableUses::kInstanceOffset)),
isolate);
if (v8_flags.wasm_to_js_generic_wrapper && IsWasmImportData(*call_ref)) {
auto orig_ref = Cast<WasmImportData>(call_ref);
DirectHandle<WasmImportData> new_ref =
isolate->factory()->NewWasmImportData(orig_ref);
if (new_ref->instance_data() == instance_object->trusted_data(isolate)) {
WasmImportData::SetIndexInTableAsCallOrigin(new_ref, entry_index);
} else {
WasmImportData::SetCrossInstanceTableIndexAsCallOrigin(
isolate, new_ref, instance_object, entry_index);
}
call_ref = new_ref;
}
Tagged<WasmTrustedInstanceData> non_shared_instance_data =
instance_object->trusted_data(isolate);
bool is_shared = instance_object->module()->tables[table_index].shared;
Tagged<WasmTrustedInstanceData> target_instance_data =
is_shared ? non_shared_instance_data->shared_part()
: non_shared_instance_data;
#if !V8_ENABLE_DRUMBRAKE
SBXCHECK(FunctionSigMatchesTable(
canonical_sig_id, target_instance_data->module(), table_index));
target_instance_data->dispatch_table(table_index)
->Set(entry_index, *call_ref, call_target, canonical_sig_id);
#else // !V8_ENABLE_DRUMBRAKE
if (v8_flags.wasm_jitless &&
instance_object->trusted_data(isolate)->has_interpreter_object()) {
Handle<WasmInstanceObject> instance_handle(*instance_object, isolate);
wasm::WasmInterpreterRuntime::UpdateIndirectCallTable(
isolate, instance_handle, table_index);
}
target_instance_data->dispatch_table(table_index)
->Set(entry_index, *call_ref, call_target, canonical_sig_id,
target_func_index);
#endif // !V8_ENABLE_DRUMBRAKE
}
}
// static
void WasmTableObject::UpdateDispatchTables(
Isolate* isolate, DirectHandle<WasmTableObject> table, int entry_index,
DirectHandle<WasmJSFunction> function) {
DirectHandle<FixedArray> uses(table->uses(), isolate);
DCHECK_EQ(0, uses->length() % TableUses::kNumElements);
// Update the dispatch table for each instance that imports this table.
for (int i = 0; i < uses->length(); i += TableUses::kNumElements) {
int table_index = Cast<Smi>(uses->get(i + TableUses::kIndexOffset)).value();
DirectHandle<WasmTrustedInstanceData> trusted_instance_data(
Cast<WasmInstanceObject>(uses->get(i + TableUses::kInstanceOffset))
->trusted_data(isolate),
isolate);
WasmTrustedInstanceData::ImportWasmJSFunctionIntoTable(
isolate, trusted_instance_data, table_index, entry_index, function);
}
}
// static
void WasmTableObject::UpdateDispatchTables(
Isolate* isolate, DirectHandle<WasmTableObject> table, int entry_index,
DirectHandle<WasmCapiFunction> capi_function) {
DirectHandle<FixedArray> uses(table->uses(), isolate);
DCHECK_EQ(0, uses->length() % TableUses::kNumElements);
// Reconstruct signature.
std::unique_ptr<wasm::ValueType[]> reps;
wasm::FunctionSig sig = wasm::SerializedSignatureHelper::DeserializeSignature(
capi_function->GetSerializedSignature(), &reps);
// Update the dispatch table for each instance that imports this table.
for (int i = 0; i < uses->length(); i += TableUses::kNumElements) {
int table_index = Cast<Smi>(uses->get(i + TableUses::kIndexOffset)).value();
DirectHandle<WasmTrustedInstanceData> trusted_instance_data(
Cast<WasmInstanceObject>(uses->get(i + TableUses::kInstanceOffset))
->trusted_data(isolate),
isolate);
wasm::NativeModule* native_module = trusted_instance_data->native_module();
wasm::WasmImportWrapperCache* cache = native_module->import_wrapper_cache();
auto kind = wasm::ImportCallKind::kWasmToCapi;
uint32_t canonical_type_index =
wasm::GetTypeCanonicalizer()->AddRecursiveGroup(&sig);
int param_count = static_cast<int>(sig.parameter_count());
wasm::WasmCode* wasm_code = cache->MaybeGet(kind, canonical_type_index,
param_count, wasm::kNoSuspend);
if (wasm_code == nullptr) {
wasm::WasmCodeRefScope code_ref_scope;
wasm::WasmImportWrapperCache::ModificationScope cache_scope(cache);
wasm_code = compiler::CompileWasmCapiCallWrapper(native_module, &sig);
wasm::WasmImportWrapperCache::CacheKey key(kind, canonical_type_index,
param_count, wasm::kNoSuspend);
cache_scope[key] = wasm_code;
wasm_code->IncRef();
isolate->counters()->wasm_generated_code_size()->Increment(
wasm_code->instructions().length());
isolate->counters()->wasm_reloc_size()->Increment(
wasm_code->reloc_info().length());
}
Tagged<HeapObject> implicit_arg = capi_function->shared()
->wasm_capi_function_data()
->internal()
->implicit_arg();
Address call_target = wasm_code->instruction_start();
trusted_instance_data->dispatch_table(table_index)
->Set(entry_index, implicit_arg, call_target, canonical_type_index
#if V8_ENABLE_DRUMBRAKE
,
WasmDispatchTable::kInvalidFunctionIndex
#endif // V8_ENABLE_DRUMBRAKE
);
}
}
void WasmTableObject::ClearDispatchTables(int index) {
DisallowGarbageCollection no_gc;
Isolate* isolate = GetIsolate();
Tagged<FixedArray> uses = this->uses();
DCHECK_EQ(0, uses->length() % TableUses::kNumElements);
for (int i = 0, e = uses->length(); i < e; i += TableUses::kNumElements) {
int table_index = Cast<Smi>(uses->get(i + TableUses::kIndexOffset)).value();
Tagged<WasmInstanceObject> target_instance_object =
Cast<WasmInstanceObject>(uses->get(i + TableUses::kInstanceOffset));
Tagged<WasmTrustedInstanceData> non_shared_instance_data =
target_instance_object->trusted_data(isolate);
bool is_shared =
target_instance_object->module()->tables[table_index].shared;
Tagged<WasmTrustedInstanceData> target_instance_data =
is_shared ? non_shared_instance_data->shared_part()
: non_shared_instance_data;
target_instance_data->dispatch_table(table_index)->Clear(index);
#if V8_ENABLE_DRUMBRAKE
if (v8_flags.wasm_jitless &&
non_shared_instance_data->has_interpreter_object()) {
Handle<WasmInstanceObject> instance_handle(*target_instance_object,
isolate);
wasm::WasmInterpreterRuntime::ClearIndirectCallCacheEntry(
isolate, instance_handle, table_index, index);
}
#endif // V8_ENABLE_DRUMBRAKE
}
}
// static
void WasmTableObject::SetFunctionTablePlaceholder(
Isolate* isolate, DirectHandle<WasmTableObject> table, int entry_index,
DirectHandle<WasmTrustedInstanceData> trusted_instance_data,
int func_index) {
// Put (instance, func_index) as a Tuple2 into the entry_index.
// The {WasmExportedFunction} will be created lazily.
// Allocate directly in old space as the tuples are typically long-lived, and
// we create many of them, which would result in lots of GC when initializing
// large tables.
// TODO(42204563): Avoid crashing if the instance object is not available.
CHECK(trusted_instance_data->has_instance_object());
DirectHandle<Tuple2> tuple = isolate->factory()->NewTuple2(
handle(trusted_instance_data->instance_object(), isolate),
handle(Smi::FromInt(func_index), isolate), AllocationType::kOld);
table->entries()->set(entry_index, *tuple);
}
// static
void WasmTableObject::GetFunctionTableEntry(
Isolate* isolate, const WasmModule* module,
DirectHandle<WasmTableObject> table, int entry_index, bool* is_valid,
bool* is_null, MaybeHandle<WasmTrustedInstanceData>* instance_data,
int* function_index, MaybeDirectHandle<WasmJSFunction>* maybe_js_function) {
DCHECK(wasm::IsSubtypeOf(table->type(), wasm::kWasmFuncRef, module));
DCHECK_LT(entry_index, table->current_length());
// We initialize {is_valid} with {true}. We may change it later.
*is_valid = true;
DirectHandle<Object> element(table->entries()->get(entry_index), isolate);
*is_null = IsWasmNull(*element, isolate);
if (*is_null) return;
if (IsWasmFuncRef(*element)) {
DirectHandle<WasmInternalFunction> internal{
Cast<WasmFuncRef>(*element)->internal(isolate), isolate};
element = WasmInternalFunction::GetOrCreateExternal(internal);
}
if (WasmExportedFunction::IsWasmExportedFunction(*element)) {
auto target_func = Cast<WasmExportedFunction>(element);
auto func_data = Cast<WasmExportedFunctionData>(
target_func->shared()->wasm_exported_function_data());
*instance_data = handle(func_data->instance_data(), isolate);
*function_index = func_data->function_index();
*maybe_js_function = MaybeHandle<WasmJSFunction>();
return;
}
if (WasmJSFunction::IsWasmJSFunction(*element)) {
*instance_data = MaybeHandle<WasmTrustedInstanceData>();
*maybe_js_function = Cast<WasmJSFunction>(element);
return;
}
if (IsTuple2(*element)) {
auto tuple = Cast<Tuple2>(element);
*instance_data =
handle(Cast<WasmInstanceObject>(tuple->value1())->trusted_data(isolate),
isolate);
*function_index = Cast<Smi>(tuple->value2()).value();
*maybe_js_function = MaybeDirectHandle<WasmJSFunction>();
return;
}
*is_valid = false;
}
Handle<WasmSuspendingObject> WasmSuspendingObject::New(
Isolate* isolate, DirectHandle<JSReceiver> callable) {
Handle<JSFunction> suspending_ctor(
isolate->native_context()->wasm_suspending_constructor(), isolate);
auto suspending_obj = Cast<WasmSuspendingObject>(
isolate->factory()->NewJSObject(suspending_ctor));
suspending_obj->set_callable(*callable);
return suspending_obj;
}
namespace {
void SetInstanceMemory(Tagged<WasmTrustedInstanceData> trusted_instance_data,
Tagged<JSArrayBuffer> buffer, int memory_index) {
DisallowHeapAllocation no_gc;
const WasmModule* module = trusted_instance_data->module();
const wasm::WasmMemory& memory = module->memories[memory_index];
bool is_wasm_module = module->origin == wasm::kWasmOrigin;
bool use_trap_handler = memory.bounds_checks == wasm::kTrapHandler;
// Asm.js does not use trap handling.
CHECK_IMPLIES(use_trap_handler, is_wasm_module);
// ArrayBuffers allocated for Wasm do always have a BackingStore.
std::shared_ptr<BackingStore> backing_store = buffer->GetBackingStore();
CHECK_IMPLIES(is_wasm_module, backing_store);
CHECK_IMPLIES(is_wasm_module, backing_store->is_wasm_memory());
// Wasm modules compiled to use the trap handler don't have bounds checks,
// so they must have a memory that has guard regions.
// Note: This CHECK can fail when in-sandbox corruption modified a
// WasmMemoryObject. We currently believe that this would at worst
// corrupt the contents of other Wasm memories or ArrayBuffers, but having
// this CHECK in release mode is nice as an additional layer of defense.
CHECK_IMPLIES(use_trap_handler, backing_store->has_guard_regions());
// We checked this before, but a malicious worker thread with an in-sandbox
// corruption primitive could have modified it since then.
size_t byte_length = buffer->byte_length();
SBXCHECK_GE(byte_length, memory.min_memory_size);
trusted_instance_data->SetRawMemory(
memory_index, reinterpret_cast<uint8_t*>(buffer->backing_store()),
byte_length);
#if V8_ENABLE_DRUMBRAKE
if (v8_flags.wasm_jitless &&
trusted_instance_data->has_interpreter_object()) {
AllowHeapAllocation allow_heap;
Isolate* isolate = trusted_instance_data->instance_object()->GetIsolate();
HandleScope scope(isolate);
wasm::WasmInterpreterRuntime::UpdateMemoryAddress(
handle(trusted_instance_data->instance_object(), isolate));
}
#endif // V8_ENABLE_DRUMBRAKE
}
} // namespace
Handle<WasmMemoryObject> WasmMemoryObject::New(Isolate* isolate,
Handle<JSArrayBuffer> buffer,
int maximum,
WasmMemoryFlag memory_type) {
Handle<JSFunction> memory_ctor(
isolate->native_context()->wasm_memory_constructor(), isolate);
auto memory_object = Cast<WasmMemoryObject>(
isolate->factory()->NewJSObject(memory_ctor, AllocationType::kOld));
memory_object->set_array_buffer(*buffer);
memory_object->set_maximum_pages(maximum);
memory_object->set_is_memory64(memory_type == WasmMemoryFlag::kWasmMemory64);
memory_object->set_instances(ReadOnlyRoots{isolate}.empty_weak_array_list());
std::shared_ptr<BackingStore> backing_store = buffer->GetBackingStore();
if (buffer->is_shared()) {
// Only Wasm memory can be shared (in contrast to asm.js memory).
CHECK(backing_store && backing_store->is_wasm_memory());
backing_store->AttachSharedWasmMemoryObject(isolate, memory_object);
} else if (backing_store) {
CHECK(!backing_store->is_shared());
}
// For debugging purposes we memorize a link from the JSArrayBuffer
// to it's owning WasmMemoryObject instance.
Handle<Symbol> symbol = isolate->factory()->array_buffer_wasm_memory_symbol();
Object::SetProperty(isolate, buffer, symbol, memory_object).Check();
return memory_object;
}
MaybeHandle<WasmMemoryObject> WasmMemoryObject::New(
Isolate* isolate, int initial, int maximum, SharedFlag shared,
WasmMemoryFlag memory_type) {
bool has_maximum = maximum != kNoMaximum;
int engine_maximum = memory_type == WasmMemoryFlag::kWasmMemory64
? static_cast<int>(wasm::max_mem64_pages())
: static_cast<int>(wasm::max_mem32_pages());
if (initial > engine_maximum) return {};
#ifdef V8_TARGET_ARCH_32_BIT
// On 32-bit platforms we need an heuristic here to balance overall memory
// and address space consumption.
constexpr int kGBPages = 1024 * 1024 * 1024 / wasm::kWasmPageSize;
// We allocate the smallest of the following sizes, but at least the initial
// size:
// 1) the module-defined maximum;
// 2) 1GB;
// 3) the engine maximum;
int allocation_maximum = std::min(kGBPages, engine_maximum);
int heuristic_maximum;
if (initial > kGBPages) {
// We always allocate at least the initial size.
heuristic_maximum = initial;
} else if (has_maximum) {
// We try to reserve the maximum, but at most the allocation_maximum to
// avoid OOMs.
heuristic_maximum = std::min(maximum, allocation_maximum);
} else if (shared == SharedFlag::kShared) {
// If shared memory has no maximum, we use the allocation_maximum as an
// implicit maximum.
heuristic_maximum = allocation_maximum;
} else {
// If non-shared memory has no maximum, we only allocate the initial size
// and then grow with realloc.
heuristic_maximum = initial;
}
#else
int heuristic_maximum =
has_maximum ? std::min(engine_maximum, maximum) : engine_maximum;
#endif
std::unique_ptr<BackingStore> backing_store =
BackingStore::AllocateWasmMemory(isolate, initial, heuristic_maximum,
memory_type, shared);
if (!backing_store) return {};
Handle<JSArrayBuffer> buffer =
shared == SharedFlag::kShared
? isolate->factory()->NewJSSharedArrayBuffer(std::move(backing_store))
: isolate->factory()->NewJSArrayBuffer(std::move(backing_store));
return New(isolate, buffer, maximum, memory_type);
}
void WasmMemoryObject::UseInInstance(
Isolate* isolate, DirectHandle<WasmMemoryObject> memory,
DirectHandle<WasmTrustedInstanceData> trusted_instance_data,
Handle<WasmTrustedInstanceData> shared_trusted_instance_data,
int memory_index_in_instance) {
SetInstanceMemory(*trusted_instance_data, memory->array_buffer(),
memory_index_in_instance);
if (!shared_trusted_instance_data.is_null()) {
SetInstanceMemory(*shared_trusted_instance_data, memory->array_buffer(),
memory_index_in_instance);
}
Handle<WeakArrayList> instances{memory->instances(), isolate};
auto weak_instance_object = MaybeObjectHandle::Weak(
trusted_instance_data->instance_object(), isolate);
instances = WeakArrayList::Append(isolate, instances, weak_instance_object);
memory->set_instances(*instances);
}
void WasmMemoryObject::SetNewBuffer(Tagged<JSArrayBuffer> new_buffer) {
DisallowGarbageCollection no_gc;
set_array_buffer(new_buffer);
Tagged<WeakArrayList> instances = this->instances();
Isolate* isolate = GetIsolate();
for (int i = 0, len = instances->length(); i < len; ++i) {
Tagged<MaybeObject> elem = instances->Get(i);
if (elem.IsCleared()) continue;
Tagged<WasmInstanceObject> instance_object =
Cast<WasmInstanceObject>(elem.GetHeapObjectAssumeWeak());
Tagged<WasmTrustedInstanceData> trusted_data =
instance_object->trusted_data(isolate);
// TODO(clemens): Avoid the iteration by also remembering the memory index
// if we ever see larger numbers of memories.
Tagged<FixedArray> memory_objects = trusted_data->memory_objects();
int num_memories = memory_objects->length();
for (int mem_idx = 0; mem_idx < num_memories; ++mem_idx) {
if (memory_objects->get(mem_idx) == *this) {
SetInstanceMemory(trusted_data, new_buffer, mem_idx);
}
}
}
}
// static
int32_t WasmMemoryObject::Grow(Isolate* isolate,
Handle<WasmMemoryObject> memory_object,
uint32_t pages) {
TRACE_EVENT0("v8.wasm", "wasm.GrowMemory");
DirectHandle<JSArrayBuffer> old_buffer(memory_object->array_buffer(),
isolate);
std::shared_ptr<BackingStore> backing_store = old_buffer->GetBackingStore();
// Only Wasm memory can grow, and Wasm memory always has a backing store.
DCHECK_NOT_NULL(backing_store);
// Check for maximum memory size.
// Note: The {wasm::max_mem_pages()} limit is already checked in
// {BackingStore::CopyWasmMemory}, and is irrelevant for
// {GrowWasmMemoryInPlace} because memory is never allocated with more
// capacity than that limit.
size_t old_size = old_buffer->byte_length();
DCHECK_EQ(0, old_size % wasm::kWasmPageSize);
size_t old_pages = old_size / wasm::kWasmPageSize;
size_t max_pages = memory_object->is_memory64() ? wasm::max_mem64_pages()
: wasm::max_mem32_pages();
if (memory_object->has_maximum_pages()) {
max_pages = std::min(max_pages,
static_cast<size_t>(memory_object->maximum_pages()));
}
DCHECK_GE(max_pages, old_pages);
if (pages > max_pages - old_pages) return -1;
const bool must_grow_in_place =
old_buffer->is_shared() || backing_store->has_guard_regions();
const bool try_grow_in_place =
must_grow_in_place || !v8_flags.stress_wasm_memory_moving;
std::optional<size_t> result_inplace =
try_grow_in_place
? backing_store->GrowWasmMemoryInPlace(isolate, pages, max_pages)
: std::nullopt;
if (must_grow_in_place && !result_inplace.has_value()) {
// There are different limits per platform, thus crash if the correctness
// fuzzer is running.
if (v8_flags.correctness_fuzzer_suppressions) {
FATAL("could not grow wasm memory");
}
return -1;
}
// Handle shared memory first.
if (old_buffer->is_shared()) {
DCHECK(result_inplace.has_value());
backing_store->BroadcastSharedWasmMemoryGrow(isolate);
// Broadcasting the update should update this memory object too.
CHECK_NE(*old_buffer, memory_object->array_buffer());
size_t new_pages = result_inplace.value() + pages;
// If the allocation succeeded, then this can't possibly overflow:
size_t new_byte_length = new_pages * wasm::kWasmPageSize;
// This is a less than check, as it is not guaranteed that the SAB
// length here will be equal to the stashed length above as calls to
// grow the same memory object can come in from different workers.
// It is also possible that a call to Grow was in progress when
// handling this call.
CHECK_LE(new_byte_length, memory_object->array_buffer()->byte_length());
// As {old_pages} was read racefully, we return here the synchronized
// value provided by {GrowWasmMemoryInPlace}, to provide the atomic
// read-modify-write behavior required by the spec.
return static_cast<int32_t>(result_inplace.value()); // success
}
// Check if the non-shared memory could grow in-place.
if (result_inplace.has_value()) {
// Detach old and create a new one with the grown backing store.
JSArrayBuffer::Detach(old_buffer, true).Check();