forked from bytecodealliance/wasmtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc_environ.rs
More file actions
3809 lines (3455 loc) · 141 KB
/
Copy pathfunc_environ.rs
File metadata and controls
3809 lines (3455 loc) · 141 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
mod gc;
use crate::compiler::Compiler;
use crate::translate::{
FuncTranslationState, GlobalVariable, Heap, HeapData, StructFieldsVec, TableData, TableSize,
TargetEnvironment,
};
use crate::{BuiltinFunctionSignatures, TRAP_INTERNAL_ASSERT};
use cranelift_codegen::cursor::FuncCursor;
use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
use cranelift_codegen::ir::immediates::{Imm64, Offset32, V128Imm};
use cranelift_codegen::ir::pcc::Fact;
use cranelift_codegen::ir::types::*;
use cranelift_codegen::ir::{self, types};
use cranelift_codegen::ir::{ArgumentPurpose, ConstantData, Function, InstBuilder, MemFlags};
use cranelift_codegen::isa::{TargetFrontendConfig, TargetIsa};
use cranelift_entity::{EntityRef, PrimaryMap, SecondaryMap};
use cranelift_frontend::Variable;
use cranelift_frontend::{FuncInstBuilder, FunctionBuilder};
use smallvec::SmallVec;
use std::mem;
use wasmparser::{Operator, WasmFeatures};
use wasmtime_environ::{
BuiltinFunctionIndex, DataIndex, ElemIndex, EngineOrModuleTypeIndex, FuncIndex, GlobalIndex,
IndexType, Memory, MemoryIndex, Module, ModuleInternedTypeIndex, ModuleTranslation,
ModuleTypesBuilder, PtrSize, Table, TableIndex, TripleExt, Tunables, TypeConvert, TypeIndex,
VMOffsets, WasmCompositeInnerType, WasmFuncType, WasmHeapTopType, WasmHeapType, WasmRefType,
WasmResult, WasmValType,
};
use wasmtime_environ::{FUNCREF_INIT_BIT, FUNCREF_MASK};
use wasmtime_math::f64_cvt_to_int_bounds;
#[derive(Debug)]
pub(crate) enum Extension {
Sign,
Zero,
}
/// A struct with an `Option<ir::FuncRef>` member for every builtin
/// function, to de-duplicate constructing/getting its function.
pub(crate) struct BuiltinFunctions {
types: BuiltinFunctionSignatures,
builtins: [Option<ir::FuncRef>; BuiltinFunctionIndex::len() as usize],
}
impl BuiltinFunctions {
fn new(compiler: &Compiler) -> Self {
Self {
types: BuiltinFunctionSignatures::new(compiler),
builtins: [None; BuiltinFunctionIndex::len() as usize],
}
}
fn load_builtin(&mut self, func: &mut Function, index: BuiltinFunctionIndex) -> ir::FuncRef {
let cache = &mut self.builtins[index.index() as usize];
if let Some(f) = cache {
return *f;
}
let signature = func.import_signature(self.types.wasm_signature(index));
let name =
ir::ExternalName::User(func.declare_imported_user_function(ir::UserExternalName {
namespace: crate::NS_WASMTIME_BUILTIN,
index: index.index(),
}));
let f = func.import_function(ir::ExtFuncData {
name,
signature,
colocated: true,
});
*cache = Some(f);
f
}
}
// Generate helper methods on `BuiltinFunctions` above for each named builtin
// as well.
macro_rules! declare_function_signatures {
($(
$( #[$attr:meta] )*
$name:ident( $( $pname:ident: $param:ident ),* ) $( -> $result:ident )?;
)*) => {
$(impl BuiltinFunctions {
$( #[$attr] )*
pub(crate) fn $name(&mut self, func: &mut Function) -> ir::FuncRef {
self.load_builtin(func, BuiltinFunctionIndex::$name())
}
})*
};
}
wasmtime_environ::foreach_builtin_function!(declare_function_signatures);
/// The `FuncEnvironment` implementation for use by the `ModuleEnvironment`.
pub struct FuncEnvironment<'module_environment> {
compiler: &'module_environment Compiler,
isa: &'module_environment (dyn TargetIsa + 'module_environment),
module: &'module_environment Module,
types: &'module_environment ModuleTypesBuilder,
wasm_func_ty: &'module_environment WasmFuncType,
sig_ref_to_ty: SecondaryMap<ir::SigRef, Option<&'module_environment WasmFuncType>>,
needs_gc_heap: bool,
#[cfg(feature = "gc")]
ty_to_gc_layout: std::collections::HashMap<
wasmtime_environ::ModuleInternedTypeIndex,
wasmtime_environ::GcLayout,
>,
#[cfg(feature = "gc")]
gc_heap: Option<Heap>,
/// The Cranelift global holding the GC heap's base address.
#[cfg(feature = "gc")]
gc_heap_base: Option<ir::GlobalValue>,
/// The Cranelift global holding the GC heap's base address.
#[cfg(feature = "gc")]
gc_heap_bound: Option<ir::GlobalValue>,
#[cfg(feature = "wmemcheck")]
translation: &'module_environment ModuleTranslation<'module_environment>,
/// Heaps implementing WebAssembly linear memories.
heaps: PrimaryMap<Heap, HeapData>,
/// Cranelift tables we have created to implement Wasm tables.
tables: SecondaryMap<TableIndex, Option<TableData>>,
/// The Cranelift global holding the vmctx address.
vmctx: Option<ir::GlobalValue>,
/// The Cranelift global for our vmctx's `*mut VMStoreContext`.
vm_store_context: Option<ir::GlobalValue>,
/// The PCC memory type describing the vmctx layout, if we're
/// using PCC.
pcc_vmctx_memtype: Option<ir::MemoryType>,
/// Caches of signatures for builtin functions.
builtin_functions: BuiltinFunctions,
/// Offsets to struct fields accessed by JIT code.
pub(crate) offsets: VMOffsets<u8>,
tunables: &'module_environment Tunables,
/// A function-local variable which stores the cached value of the amount of
/// fuel remaining to execute. If used this is modified frequently so it's
/// stored locally as a variable instead of always referenced from the field
/// in `*const VMStoreContext`
fuel_var: cranelift_frontend::Variable,
/// A cached epoch deadline value, when performing epoch-based
/// interruption. Loaded from `VMStoreContext` and reloaded after
/// any yield.
epoch_deadline_var: cranelift_frontend::Variable,
/// A cached pointer to the per-Engine epoch counter, when
/// performing epoch-based interruption. Initialized in the
/// function prologue. We prefer to use a variable here rather
/// than reload on each check because it's better to let the
/// regalloc keep it in a register if able; if not, it can always
/// spill, and this isn't any worse than reloading each time.
epoch_ptr_var: cranelift_frontend::Variable,
fuel_consumed: i64,
/// A `GlobalValue` in CLIF which represents the stack limit.
///
/// Typically this resides in the `stack_limit` value of `ir::Function` but
/// that requires signal handlers on the host and when that's disabled this
/// is here with an explicit check instead. Note that the explicit check is
/// always present even if this is a "leaf" function, as we have to call
/// into the host to trap when signal handlers are disabled.
pub(crate) stack_limit_at_function_entry: Option<ir::GlobalValue>,
}
impl<'module_environment> FuncEnvironment<'module_environment> {
pub fn new(
compiler: &'module_environment Compiler,
translation: &'module_environment ModuleTranslation<'module_environment>,
types: &'module_environment ModuleTypesBuilder,
wasm_func_ty: &'module_environment WasmFuncType,
) -> Self {
let tunables = compiler.tunables();
let builtin_functions = BuiltinFunctions::new(compiler);
// This isn't used during translation, so squash the warning about this
// being unused from the compiler.
let _ = BuiltinFunctions::raise;
Self {
isa: compiler.isa(),
module: &translation.module,
compiler,
types,
wasm_func_ty,
sig_ref_to_ty: SecondaryMap::default(),
needs_gc_heap: false,
#[cfg(feature = "gc")]
ty_to_gc_layout: std::collections::HashMap::new(),
#[cfg(feature = "gc")]
gc_heap: None,
#[cfg(feature = "gc")]
gc_heap_base: None,
#[cfg(feature = "gc")]
gc_heap_bound: None,
heaps: PrimaryMap::default(),
tables: SecondaryMap::default(),
vmctx: None,
vm_store_context: None,
pcc_vmctx_memtype: None,
builtin_functions,
offsets: VMOffsets::new(compiler.isa().pointer_bytes(), &translation.module),
tunables,
fuel_var: Variable::new(0),
epoch_deadline_var: Variable::new(0),
epoch_ptr_var: Variable::new(0),
// Start with at least one fuel being consumed because even empty
// functions should consume at least some fuel.
fuel_consumed: 1,
#[cfg(feature = "wmemcheck")]
translation,
stack_limit_at_function_entry: None,
}
}
pub(crate) fn pointer_type(&self) -> ir::Type {
self.isa.pointer_type()
}
pub(crate) fn vmctx(&mut self, func: &mut Function) -> ir::GlobalValue {
self.vmctx.unwrap_or_else(|| {
let vmctx = func.create_global_value(ir::GlobalValueData::VMContext);
if self.isa.flags().enable_pcc() {
// Create a placeholder memtype for the vmctx; we'll
// add fields to it as we lazily create HeapData
// structs and global values.
let vmctx_memtype = func.create_memory_type(ir::MemoryTypeData::Struct {
size: 0,
fields: vec![],
});
self.pcc_vmctx_memtype = Some(vmctx_memtype);
func.global_value_facts[vmctx] = Some(Fact::Mem {
ty: vmctx_memtype,
min_offset: 0,
max_offset: 0,
nullable: false,
});
}
self.vmctx = Some(vmctx);
vmctx
})
}
pub(crate) fn vmctx_val(&mut self, pos: &mut FuncCursor<'_>) -> ir::Value {
let pointer_type = self.pointer_type();
let vmctx = self.vmctx(&mut pos.func);
pos.ins().global_value(pointer_type, vmctx)
}
fn get_table_copy_func(
&mut self,
func: &mut Function,
dst_table_index: TableIndex,
src_table_index: TableIndex,
) -> (ir::FuncRef, usize, usize) {
let sig = self.builtin_functions.table_copy(func);
(
sig,
dst_table_index.as_u32() as usize,
src_table_index.as_u32() as usize,
)
}
#[cfg(feature = "threads")]
fn get_memory_atomic_wait(
&mut self,
func: &mut Function,
memory_index: MemoryIndex,
ty: ir::Type,
) -> (ir::FuncRef, usize) {
match ty {
I32 => (
self.builtin_functions.memory_atomic_wait32(func),
memory_index.index(),
),
I64 => (
self.builtin_functions.memory_atomic_wait64(func),
memory_index.index(),
),
x => panic!("get_memory_atomic_wait unsupported type: {x:?}"),
}
}
fn get_global_location(
&mut self,
func: &mut ir::Function,
index: GlobalIndex,
) -> (ir::GlobalValue, i32) {
let pointer_type = self.pointer_type();
let vmctx = self.vmctx(func);
if let Some(def_index) = self.module.defined_global_index(index) {
let offset = i32::try_from(self.offsets.vmctx_vmglobal_definition(def_index)).unwrap();
(vmctx, offset)
} else {
let from_offset = self.offsets.vmctx_vmglobal_import_from(index);
let global = func.create_global_value(ir::GlobalValueData::Load {
base: vmctx,
offset: Offset32::new(i32::try_from(from_offset).unwrap()),
global_type: pointer_type,
flags: MemFlags::trusted().with_readonly().with_can_move(),
});
(global, 0)
}
}
/// Get or create the `ir::Global` for the `*mut VMStoreContext` in our
/// `VMContext`.
fn get_vmstore_context_ptr_global(&mut self, func: &mut ir::Function) -> ir::GlobalValue {
if let Some(ptr) = self.vm_store_context {
return ptr;
}
let offset = self.offsets.ptr.vmctx_store_context();
let base = self.vmctx(func);
let ptr = func.create_global_value(ir::GlobalValueData::Load {
base,
offset: Offset32::new(offset.into()),
global_type: self.pointer_type(),
flags: ir::MemFlags::trusted().with_readonly().with_can_move(),
});
self.vm_store_context = Some(ptr);
ptr
}
/// Get the `*mut VMStoreContext` value for our `VMContext`.
fn get_vmstore_context_ptr(&mut self, builder: &mut FunctionBuilder) -> ir::Value {
let global = self.get_vmstore_context_ptr_global(&mut builder.func);
builder.ins().global_value(self.pointer_type(), global)
}
fn fuel_function_entry(&mut self, builder: &mut FunctionBuilder<'_>) {
// On function entry we load the amount of fuel into a function-local
// `self.fuel_var` to make fuel modifications fast locally. This cache
// is then periodically flushed to the Store-defined location in
// `VMStoreContext` later.
builder.declare_var(self.fuel_var, ir::types::I64);
self.fuel_load_into_var(builder);
self.fuel_check(builder);
}
fn fuel_function_exit(&mut self, builder: &mut FunctionBuilder<'_>) {
// On exiting the function we need to be sure to save the fuel we have
// cached locally in `self.fuel_var` back into the Store-defined
// location.
self.fuel_save_from_var(builder);
}
fn fuel_before_op(
&mut self,
op: &Operator<'_>,
builder: &mut FunctionBuilder<'_>,
reachable: bool,
) {
if !reachable {
// In unreachable code we shouldn't have any leftover fuel we
// haven't accounted for since the reason for us to become
// unreachable should have already added it to `self.fuel_var`.
debug_assert_eq!(self.fuel_consumed, 0);
return;
}
self.fuel_consumed += match op {
// Nop and drop generate no code, so don't consume fuel for them.
Operator::Nop | Operator::Drop => 0,
// Control flow may create branches, but is generally cheap and
// free, so don't consume fuel. Note the lack of `if` since some
// cost is incurred with the conditional check.
Operator::Block { .. }
| Operator::Loop { .. }
| Operator::Unreachable
| Operator::Return
| Operator::Else
| Operator::End => 0,
// everything else, just call it one operation.
_ => 1,
};
match op {
// Exiting a function (via a return or unreachable) or otherwise
// entering a different function (via a call) means that we need to
// update the fuel consumption in `VMStoreContext` because we're
// about to move control out of this function itself and the fuel
// may need to be read.
//
// Before this we need to update the fuel counter from our own cost
// leading up to this function call, and then we can store
// `self.fuel_var` into `VMStoreContext`.
Operator::Unreachable
| Operator::Return
| Operator::CallIndirect { .. }
| Operator::Call { .. }
| Operator::ReturnCall { .. }
| Operator::ReturnCallRef { .. }
| Operator::ReturnCallIndirect { .. } => {
self.fuel_increment_var(builder);
self.fuel_save_from_var(builder);
}
// To ensure all code preceding a loop is only counted once we
// update the fuel variable on entry.
Operator::Loop { .. }
// Entering into an `if` block means that the edge we take isn't
// known until runtime, so we need to update our fuel consumption
// before we take the branch.
| Operator::If { .. }
// Control-flow instructions mean that we're moving to the end/exit
// of a block somewhere else. That means we need to update the fuel
// counter since we're effectively terminating our basic block.
| Operator::Br { .. }
| Operator::BrIf { .. }
| Operator::BrTable { .. }
// Exiting a scope means that we need to update the fuel
// consumption because there are multiple ways to exit a scope and
// this is the only time we have to account for instructions
// executed so far.
| Operator::End
// This is similar to `end`, except that it's only the terminator
// for an `if` block. The same reasoning applies though in that we
// are terminating a basic block and need to update the fuel
// variable.
| Operator::Else => self.fuel_increment_var(builder),
// This is a normal instruction where the fuel is buffered to later
// get added to `self.fuel_var`.
//
// Note that we generally ignore instructions which may trap and
// therefore result in exiting a block early. Current usage of fuel
// means that it's not too important to account for a precise amount
// of fuel consumed but rather "close to the actual amount" is good
// enough. For 100% precise counting, however, we'd probably need to
// not only increment but also save the fuel amount more often
// around trapping instructions. (see the `unreachable` instruction
// case above)
//
// Note that `Block` is specifically omitted from incrementing the
// fuel variable. Control flow entering a `block` is unconditional
// which means it's effectively executing straight-line code. We'll
// update the counter when exiting a block, but we shouldn't need to
// do so upon entering a block.
_ => {}
}
}
fn fuel_after_op(&mut self, op: &Operator<'_>, builder: &mut FunctionBuilder<'_>) {
// After a function call we need to reload our fuel value since the
// function may have changed it.
match op {
Operator::Call { .. } | Operator::CallIndirect { .. } => {
self.fuel_load_into_var(builder);
}
_ => {}
}
}
/// Adds `self.fuel_consumed` to the `fuel_var`, zero-ing out the amount of
/// fuel consumed at that point.
fn fuel_increment_var(&mut self, builder: &mut FunctionBuilder<'_>) {
let consumption = mem::replace(&mut self.fuel_consumed, 0);
if consumption == 0 {
return;
}
let fuel = builder.use_var(self.fuel_var);
let fuel = builder.ins().iadd_imm(fuel, consumption);
builder.def_var(self.fuel_var, fuel);
}
/// Loads the fuel consumption value from `VMStoreContext` into `self.fuel_var`
fn fuel_load_into_var(&mut self, builder: &mut FunctionBuilder<'_>) {
let (addr, offset) = self.fuel_addr_offset(builder);
let fuel = builder
.ins()
.load(ir::types::I64, ir::MemFlags::trusted(), addr, offset);
builder.def_var(self.fuel_var, fuel);
}
/// Stores the fuel consumption value from `self.fuel_var` into
/// `VMStoreContext`.
fn fuel_save_from_var(&mut self, builder: &mut FunctionBuilder<'_>) {
let (addr, offset) = self.fuel_addr_offset(builder);
let fuel_consumed = builder.use_var(self.fuel_var);
builder
.ins()
.store(ir::MemFlags::trusted(), fuel_consumed, addr, offset);
}
/// Returns the `(address, offset)` of the fuel consumption within
/// `VMStoreContext`, used to perform loads/stores later.
fn fuel_addr_offset(
&mut self,
builder: &mut FunctionBuilder<'_>,
) -> (ir::Value, ir::immediates::Offset32) {
let vmstore_ctx = self.get_vmstore_context_ptr(builder);
(
vmstore_ctx,
i32::from(self.offsets.ptr.vmstore_context_fuel_consumed()).into(),
)
}
/// Checks the amount of remaining, and if we've run out of fuel we call
/// the out-of-fuel function.
fn fuel_check(&mut self, builder: &mut FunctionBuilder) {
self.fuel_increment_var(builder);
let out_of_gas_block = builder.create_block();
let continuation_block = builder.create_block();
// Note that our fuel is encoded as adding positive values to a
// negative number. Whenever the negative number goes positive that
// means we ran out of fuel.
//
// Compare to see if our fuel is positive, and if so we ran out of gas.
// Otherwise we can continue on like usual.
let zero = builder.ins().iconst(ir::types::I64, 0);
let fuel = builder.use_var(self.fuel_var);
let cmp = builder
.ins()
.icmp(IntCC::SignedGreaterThanOrEqual, fuel, zero);
builder
.ins()
.brif(cmp, out_of_gas_block, &[], continuation_block, &[]);
builder.seal_block(out_of_gas_block);
// If we ran out of gas then we call our out-of-gas intrinsic and it
// figures out what to do. Note that this may raise a trap, or do
// something like yield to an async runtime. In either case we don't
// assume what happens and handle the case the intrinsic returns.
//
// Note that we save/reload fuel around this since the out-of-gas
// intrinsic may alter how much fuel is in the system.
builder.switch_to_block(out_of_gas_block);
self.fuel_save_from_var(builder);
let out_of_gas = self.builtin_functions.out_of_gas(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
builder.ins().call(out_of_gas, &[vmctx]);
self.fuel_load_into_var(builder);
builder.ins().jump(continuation_block, &[]);
builder.seal_block(continuation_block);
builder.switch_to_block(continuation_block);
}
fn epoch_function_entry(&mut self, builder: &mut FunctionBuilder<'_>) {
builder.declare_var(self.epoch_deadline_var, ir::types::I64);
// Let epoch_check_full load the current deadline and call def_var
builder.declare_var(self.epoch_ptr_var, self.pointer_type());
let epoch_ptr = self.epoch_ptr(builder);
builder.def_var(self.epoch_ptr_var, epoch_ptr);
// We must check for an epoch change when entering a
// function. Why? Why aren't checks at loops sufficient to
// bound runtime to O(|static program size|)?
//
// The reason is that one can construct a "zip-bomb-like"
// program with exponential-in-program-size runtime, with no
// backedges (loops), by building a tree of function calls: f0
// calls f1 ten times, f1 calls f2 ten times, etc. E.g., nine
// levels of this yields a billion function calls with no
// backedges. So we can't do checks only at backedges.
//
// In this "call-tree" scenario, and in fact in any program
// that uses calls as a sort of control flow to try to evade
// backedge checks, a check at every function entry is
// sufficient. Then, combined with checks at every backedge
// (loop) the longest runtime between checks is bounded by the
// straightline length of any function body.
let continuation_block = builder.create_block();
let cur_epoch_value = self.epoch_load_current(builder);
self.epoch_check_full(builder, cur_epoch_value, continuation_block);
}
#[cfg(feature = "wmemcheck")]
fn hook_malloc_exit(&mut self, builder: &mut FunctionBuilder, retvals: &[ir::Value]) {
let check_malloc = self.builtin_functions.check_malloc(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
let func_args = builder
.func
.dfg
.block_params(builder.func.layout.entry_block().unwrap());
let len = if func_args.len() < 3 {
return;
} else {
// If a function named `malloc` has at least one argument, we assume the
// first argument is the requested allocation size.
func_args[2]
};
let retval = if retvals.len() < 1 {
return;
} else {
retvals[0]
};
builder.ins().call(check_malloc, &[vmctx, retval, len]);
}
#[cfg(feature = "wmemcheck")]
fn hook_free_exit(&mut self, builder: &mut FunctionBuilder) {
let check_free = self.builtin_functions.check_free(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
let func_args = builder
.func
.dfg
.block_params(builder.func.layout.entry_block().unwrap());
let ptr = if func_args.len() < 3 {
return;
} else {
// If a function named `free` has at least one argument, we assume the
// first argument is a pointer to memory.
func_args[2]
};
builder.ins().call(check_free, &[vmctx, ptr]);
}
fn epoch_ptr(&mut self, builder: &mut FunctionBuilder<'_>) -> ir::Value {
let vmctx = self.vmctx(builder.func);
let pointer_type = self.pointer_type();
let base = builder.ins().global_value(pointer_type, vmctx);
let offset = i32::from(self.offsets.ptr.vmctx_epoch_ptr());
let epoch_ptr = builder
.ins()
.load(pointer_type, ir::MemFlags::trusted(), base, offset);
epoch_ptr
}
fn epoch_load_current(&mut self, builder: &mut FunctionBuilder<'_>) -> ir::Value {
let addr = builder.use_var(self.epoch_ptr_var);
builder.ins().load(
ir::types::I64,
ir::MemFlags::trusted(),
addr,
ir::immediates::Offset32::new(0),
)
}
fn epoch_check(&mut self, builder: &mut FunctionBuilder<'_>) {
let continuation_block = builder.create_block();
// Load new epoch and check against the cached deadline.
let cur_epoch_value = self.epoch_load_current(builder);
self.epoch_check_cached(builder, cur_epoch_value, continuation_block);
// At this point we've noticed that the epoch has exceeded our
// cached deadline. However the real deadline may have been
// updated (within another yield) during some function that we
// called in the meantime, so reload the cache and check again.
self.epoch_check_full(builder, cur_epoch_value, continuation_block);
}
fn epoch_check_cached(
&mut self,
builder: &mut FunctionBuilder,
cur_epoch_value: ir::Value,
continuation_block: ir::Block,
) {
let new_epoch_block = builder.create_block();
builder.set_cold_block(new_epoch_block);
let epoch_deadline = builder.use_var(self.epoch_deadline_var);
let cmp = builder.ins().icmp(
IntCC::UnsignedGreaterThanOrEqual,
cur_epoch_value,
epoch_deadline,
);
builder
.ins()
.brif(cmp, new_epoch_block, &[], continuation_block, &[]);
builder.seal_block(new_epoch_block);
builder.switch_to_block(new_epoch_block);
}
fn epoch_check_full(
&mut self,
builder: &mut FunctionBuilder,
cur_epoch_value: ir::Value,
continuation_block: ir::Block,
) {
// We keep the deadline cached in a register to speed the checks
// in the common case (between epoch ticks) but we want to do a
// precise check here by reloading the cache first.
let vmstore_ctx = self.get_vmstore_context_ptr(builder);
let deadline = builder.ins().load(
ir::types::I64,
ir::MemFlags::trusted(),
vmstore_ctx,
ir::immediates::Offset32::new(self.offsets.ptr.vmstore_context_epoch_deadline() as i32),
);
builder.def_var(self.epoch_deadline_var, deadline);
self.epoch_check_cached(builder, cur_epoch_value, continuation_block);
let new_epoch = self.builtin_functions.new_epoch(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
// new_epoch() returns the new deadline, so we don't have to
// reload it.
let call = builder.ins().call(new_epoch, &[vmctx]);
let new_deadline = *builder.func.dfg.inst_results(call).first().unwrap();
builder.def_var(self.epoch_deadline_var, new_deadline);
builder.ins().jump(continuation_block, &[]);
builder.seal_block(continuation_block);
builder.switch_to_block(continuation_block);
}
/// Get the Memory for the given index.
fn memory(&self, index: MemoryIndex) -> Memory {
self.module.memories[index]
}
/// Get the Table for the given index.
fn table(&self, index: TableIndex) -> Table {
self.module.tables[index]
}
/// Cast the value to I64 and sign extend if necessary.
///
/// Returns the value casted to I64.
fn cast_index_to_i64(
&self,
pos: &mut FuncCursor<'_>,
val: ir::Value,
index_type: IndexType,
) -> ir::Value {
match index_type {
IndexType::I32 => pos.ins().uextend(I64, val),
IndexType::I64 => val,
}
}
/// Convert the target pointer-sized integer `val` into the memory/table's index type.
///
/// For memory, `val` is holding a memory length (or the `-1` `memory.grow`-failed sentinel).
/// For table, `val` is holding a table length.
///
/// This might involve extending or truncating it depending on the memory/table's
/// index type and the target's pointer type.
fn convert_pointer_to_index_type(
&self,
mut pos: FuncCursor<'_>,
val: ir::Value,
index_type: IndexType,
// When it is a memory and the memory is using single-byte pages,
// we need to handle the tuncation differently. See comments below.
//
// When it is a table, this should be set to false.
single_byte_pages: bool,
) -> ir::Value {
let desired_type = index_type_to_ir_type(index_type);
let pointer_type = self.pointer_type();
assert_eq!(pos.func.dfg.value_type(val), pointer_type);
// The current length is of type `pointer_type` but we need to fit it
// into `desired_type`. We are guaranteed that the result will always
// fit, so we just need to do the right ireduce/sextend here.
if pointer_type == desired_type {
val
} else if pointer_type.bits() > desired_type.bits() {
pos.ins().ireduce(desired_type, val)
} else {
// We have a 64-bit memory/table on a 32-bit host -- this combo doesn't
// really make a whole lot of sense to do from a user perspective
// but that is neither here nor there. We want to logically do an
// unsigned extend *except* when we are given the `-1` sentinel,
// which we must preserve as `-1` in the wider type.
match single_byte_pages {
false => {
// In the case that we have default page sizes, we can
// always sign extend, since valid memory lengths (in pages)
// never have their sign bit set, and so if the sign bit is
// set then this must be the `-1` sentinel, which we want to
// preserve through the extension.
//
// When it comes to table, `single_byte_pages` should have always been set to false.
// Then we simply do a signed extension.
pos.ins().sextend(desired_type, val)
}
true => {
// For single-byte pages, we have to explicitly check for
// `-1` and choose whether to do an unsigned extension or
// return a larger `-1` because there are valid memory
// lengths (in pages) that have the sign bit set.
let extended = pos.ins().uextend(desired_type, val);
let neg_one = pos.ins().iconst(desired_type, -1);
let is_failure = pos.ins().icmp_imm(IntCC::Equal, val, -1);
pos.ins().select(is_failure, neg_one, extended)
}
}
}
}
/// Set up the necessary preamble definitions in `func` to access the table identified
/// by `index`.
///
/// The index space covers both imported and locally declared tables.
fn ensure_table_exists(&mut self, func: &mut ir::Function, index: TableIndex) {
if self.tables[index].is_some() {
return;
}
let pointer_type = self.pointer_type();
let (ptr, base_offset, current_elements_offset) = {
let vmctx = self.vmctx(func);
if let Some(def_index) = self.module.defined_table_index(index) {
let base_offset =
i32::try_from(self.offsets.vmctx_vmtable_definition_base(def_index)).unwrap();
let current_elements_offset = i32::try_from(
self.offsets
.vmctx_vmtable_definition_current_elements(def_index),
)
.unwrap();
(vmctx, base_offset, current_elements_offset)
} else {
let from_offset = self.offsets.vmctx_vmtable_from(index);
let table = func.create_global_value(ir::GlobalValueData::Load {
base: vmctx,
offset: Offset32::new(i32::try_from(from_offset).unwrap()),
global_type: pointer_type,
flags: MemFlags::trusted().with_readonly().with_can_move(),
});
let base_offset = i32::from(self.offsets.vmtable_definition_base());
let current_elements_offset =
i32::from(self.offsets.vmtable_definition_current_elements());
(table, base_offset, current_elements_offset)
}
};
let table = &self.module.tables[index];
let element_size = if table.ref_type.is_vmgcref_type() {
// For GC-managed references, tables store `Option<VMGcRef>`s.
ir::types::I32.bytes()
} else {
self.reference_type(table.ref_type.heap_type).0.bytes()
};
let base_gv = func.create_global_value(ir::GlobalValueData::Load {
base: ptr,
offset: Offset32::new(base_offset),
global_type: pointer_type,
flags: if Some(table.limits.min) == table.limits.max {
// A fixed-size table can't be resized so its base address won't
// change.
MemFlags::trusted().with_readonly().with_can_move()
} else {
MemFlags::trusted()
},
});
let bound = if Some(table.limits.min) == table.limits.max {
TableSize::Static {
bound: table.limits.min,
}
} else {
TableSize::Dynamic {
bound_gv: func.create_global_value(ir::GlobalValueData::Load {
base: ptr,
offset: Offset32::new(current_elements_offset),
global_type: ir::Type::int(
u16::from(self.offsets.size_of_vmtable_definition_current_elements()) * 8,
)
.unwrap(),
flags: MemFlags::trusted(),
}),
}
};
self.tables[index] = Some(TableData {
base_gv,
bound,
element_size,
});
}
fn get_or_init_func_ref_table_elem(
&mut self,
builder: &mut FunctionBuilder,
table_index: TableIndex,
index: ir::Value,
cold_blocks: bool,
) -> ir::Value {
let pointer_type = self.pointer_type();
self.ensure_table_exists(builder.func, table_index);
let table_data = self.tables[table_index].clone().unwrap();
// To support lazy initialization of table
// contents, we check for a null entry here, and
// if null, we take a slow-path that invokes a
// libcall.
let (table_entry_addr, flags) = table_data.prepare_table_addr(self, builder, index);
let value = builder.ins().load(pointer_type, flags, table_entry_addr, 0);
if !self.tunables.table_lazy_init {
return value;
}
// Mask off the "initialized bit". See documentation on
// FUNCREF_INIT_BIT in crates/environ/src/ref_bits.rs for more
// details. Note that `FUNCREF_MASK` has type `usize` which may not be
// appropriate for the target architecture. Right now its value is
// always -2 so assert that part doesn't change and then thread through
// -2 as the immediate.
assert_eq!(FUNCREF_MASK as isize, -2);
let value_masked = builder.ins().band_imm(value, Imm64::from(-2));
let null_block = builder.create_block();
let continuation_block = builder.create_block();
if cold_blocks {
builder.set_cold_block(null_block);
builder.set_cold_block(continuation_block);
}
let result_param = builder.append_block_param(continuation_block, pointer_type);
builder.set_cold_block(null_block);
builder.ins().brif(
value,
continuation_block,
&[value_masked.into()],
null_block,
&[],
);
builder.seal_block(null_block);
builder.switch_to_block(null_block);
let index_type = self.table(table_index).idx_type;
let table_index = builder.ins().iconst(I32, table_index.index() as i64);
let lazy_init = self
.builtin_functions
.table_get_lazy_init_func_ref(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
let index = self.cast_index_to_i64(&mut builder.cursor(), index, index_type);
let call_inst = builder.ins().call(lazy_init, &[vmctx, table_index, index]);
let returned_entry = builder.func.dfg.inst_results(call_inst)[0];
builder
.ins()
.jump(continuation_block, &[returned_entry.into()]);
builder.seal_block(continuation_block);
builder.switch_to_block(continuation_block);
result_param
}
#[cfg(feature = "wmemcheck")]
fn check_malloc_start(&mut self, builder: &mut FunctionBuilder) {
let malloc_start = self.builtin_functions.malloc_start(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
builder.ins().call(malloc_start, &[vmctx]);
}
#[cfg(feature = "wmemcheck")]
fn check_free_start(&mut self, builder: &mut FunctionBuilder) {
let free_start = self.builtin_functions.free_start(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
builder.ins().call(free_start, &[vmctx]);
}
#[cfg(feature = "wmemcheck")]
fn current_func_name(&self, builder: &mut FunctionBuilder) -> Option<&str> {
let func_index = match &builder.func.name {
ir::UserFuncName::User(user) => FuncIndex::from_u32(user.index),
_ => {
panic!("function name not a UserFuncName::User as expected")
}
};
self.translation
.debuginfo
.name_section
.func_names
.get(&func_index)
.copied()
}
/// Proof-carrying code: create a memtype describing an empty
/// runtime struct (to be updated later).
fn create_empty_struct_memtype(&self, func: &mut ir::Function) -> ir::MemoryType {
func.create_memory_type(ir::MemoryTypeData::Struct {
size: 0,
fields: vec![],