-
Notifications
You must be signed in to change notification settings - Fork 829
/
codegen_x64.rs
10931 lines (10293 loc) · 426 KB
/
codegen_x64.rs
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
#![allow(clippy::forget_copy)] // Used by dynasm.
#![warn(unused_imports)]
use crate::emitter_x64::*;
use crate::machine::*;
#[cfg(target_arch = "aarch64")]
use dynasmrt::aarch64::Assembler;
#[cfg(target_arch = "x86_64")]
use dynasmrt::x64::Assembler;
use dynasmrt::{AssemblyOffset, DynamicLabel, DynasmApi, DynasmLabelApi};
use smallvec::SmallVec;
use std::{
any::Any,
collections::{BTreeMap, HashMap},
ffi::c_void,
iter, mem,
ptr::NonNull,
slice,
sync::{Arc, RwLock},
usize,
};
use wasmer_runtime_core::{
backend::{
sys::{Memory, Protect},
Architecture, CacheGen, CompilerConfig, ExceptionCode, ExceptionTable, InlineBreakpoint,
InlineBreakpointType, MemoryBoundCheckMode, RunnableModule, Token,
},
cache::{Artifact, Error as CacheError},
codegen::*,
fault::{self, raw::register_preservation_trampoline},
loader::CodeMemory,
memory::MemoryType,
module::{ModuleInfo, ModuleInner},
state::{
x64::new_machine_state, x64::X64Register, x64_decl::ArgumentRegisterAllocator,
FunctionStateMap, MachineState, MachineValue, ModuleStateMap, OffsetInfo, SuspendOffset,
WasmAbstractValue,
},
structures::{Map, TypedIndex},
typed_func::{Trampoline, Wasm},
types::{
FuncIndex, FuncSig, GlobalIndex, ImportedGlobalIndex, LocalFuncIndex, LocalGlobalIndex,
LocalOrImport, MemoryIndex, SigIndex, TableIndex, Type,
},
vm::{self, LocalGlobal, LocalTable, INTERNALS_SIZE},
wasmparser::{MemoryImmediate, Operator, Type as WpType, TypeOrFuncType as WpTypeOrFuncType},
};
#[cfg(target_arch = "aarch64")]
#[allow(dead_code)]
static ARCH: Architecture = Architecture::Aarch64;
#[cfg(target_arch = "x86_64")]
#[allow(dead_code)]
static ARCH: Architecture = Architecture::X64;
/// Inline breakpoint size for x86-64.
pub const INLINE_BREAKPOINT_SIZE_X86_SINGLEPASS: usize = 7;
/// Inline breakpoint size for aarch64.
pub const INLINE_BREAKPOINT_SIZE_AARCH64_SINGLEPASS: usize = 12;
static BACKEND_ID: &str = "singlepass";
#[cfg(target_arch = "x86_64")]
lazy_static! {
/// Performs a System V call to `target` with [stack_top..stack_base] as the argument list, from right to left.
static ref CONSTRUCT_STACK_AND_CALL_WASM: unsafe extern "C" fn (stack_top: *const u64, stack_base: *const u64, ctx: *mut vm::Ctx, target: *const vm::Func) -> u64 = {
let mut assembler = Assembler::new().unwrap();
let offset = assembler.offset();
dynasm!(
assembler
; push r15
; push r14
; push r13
; push r12
; push r11
; push rbp
; mov rbp, rsp
; mov r15, rdi
; mov r14, rsi
; mov r13, rdx
; mov r12, rcx
; mov rdi, r13 // ctx
; sub r14, 8
; cmp r14, r15
; jb >stack_ready
; mov rsi, [r14]
; sub r14, 8
; cmp r14, r15
; jb >stack_ready
; mov rdx, [r14]
; sub r14, 8
; cmp r14, r15
; jb >stack_ready
; mov rcx, [r14]
; sub r14, 8
; cmp r14, r15
; jb >stack_ready
; mov r8, [r14]
; sub r14, 8
; cmp r14, r15
; jb >stack_ready
; mov r9, [r14]
; sub r14, 8
; cmp r14, r15
; jb >stack_ready
; mov rax, r14
; sub rax, r15
; sub rsp, rax
; sub rsp, 8
; mov rax, QWORD 0xfffffffffffffff0u64 as i64
; and rsp, rax
; mov rax, rsp
; loop_begin:
; mov r11, [r14]
; mov [rax], r11
; sub r14, 8
; add rax, 8
; cmp r14, r15
; jb >stack_ready
; jmp <loop_begin
; stack_ready:
; mov rax, QWORD 0xfffffffffffffff0u64 as i64
; and rsp, rax
; call r12
; mov rsp, rbp
; pop rbp
; pop r11
; pop r12
; pop r13
; pop r14
; pop r15
; ret
);
let buf = assembler.finalize().unwrap();
let ret = unsafe { mem::transmute(buf.ptr(offset)) };
mem::forget(buf);
ret
};
}
#[cfg(target_arch = "aarch64")]
#[repr(C)]
#[allow(dead_code)]
struct CallCtx {
ctx: *mut vm::Ctx,
stack: *mut u64,
target: *mut u8,
}
#[cfg(target_arch = "aarch64")]
lazy_static! {
/// Switches stack and executes the provided callback.
static ref SWITCH_STACK: unsafe extern "C" fn (stack: *mut u64, cb: extern "C" fn (*mut u8) -> u64, userdata: *mut u8) -> u64 = {
let mut assembler = Assembler::new().unwrap();
let offset = assembler.offset();
dynasm!(
assembler
; .arch aarch64
; sub x0, x0, 16
; mov x8, sp
; str x8, [x0, 0]
; str x30, [x0, 8]
; adr x30, >done
; mov sp, x0
; mov x0, x2
; br x1
; done:
; ldr x30, [sp, 8]
; ldr x8, [sp, 0]
; mov sp, x8
; br x30
);
let buf = assembler.finalize().unwrap();
let ret = unsafe { mem::transmute(buf.ptr(offset)) };
mem::forget(buf);
ret
};
}
pub struct X64ModuleCodeGenerator {
functions: Vec<X64FunctionCode>,
signatures: Option<Arc<Map<SigIndex, FuncSig>>>,
function_signatures: Option<Arc<Map<FuncIndex, SigIndex>>>,
function_labels: Option<HashMap<usize, (DynamicLabel, Option<AssemblyOffset>)>>,
assembler: Option<Assembler>,
func_import_count: usize,
config: Option<Arc<CodegenConfig>>,
}
pub struct X64FunctionCode {
local_function_id: usize,
signatures: Arc<Map<SigIndex, FuncSig>>,
function_signatures: Arc<Map<FuncIndex, SigIndex>>,
signature: FuncSig,
fsm: FunctionStateMap,
offset: usize,
assembler: Option<Assembler>,
function_labels: Option<HashMap<usize, (DynamicLabel, Option<AssemblyOffset>)>>,
breakpoints: Option<
HashMap<
AssemblyOffset,
Box<dyn Fn(BreakpointInfo) -> Result<(), Box<dyn Any + Send>> + Send + Sync + 'static>,
>,
>,
returns: SmallVec<[WpType; 1]>,
locals: Vec<Location>,
num_params: usize,
local_types: Vec<WpType>,
value_stack: Vec<Location>,
/// Metadata about floating point values on the stack.
fp_stack: Vec<FloatValue>,
control_stack: Vec<ControlFrame>,
machine: Machine,
unreachable_depth: usize,
config: Arc<CodegenConfig>,
exception_table: Option<ExceptionTable>,
}
/// Metadata about a floating-point value.
#[derive(Copy, Clone, Debug)]
struct FloatValue {
/// Do we need to canonicalize the value before its bit pattern is next observed? If so, how?
canonicalization: Option<CanonicalizeType>,
/// Corresponding depth in the main value stack.
depth: usize,
}
impl FloatValue {
fn new(depth: usize) -> Self {
FloatValue {
canonicalization: None,
depth,
}
}
fn cncl_f32(depth: usize) -> Self {
FloatValue {
canonicalization: Some(CanonicalizeType::F32),
depth,
}
}
fn cncl_f64(depth: usize) -> Self {
FloatValue {
canonicalization: Some(CanonicalizeType::F64),
depth,
}
}
fn promote(self, depth: usize) -> FloatValue {
FloatValue {
canonicalization: match self.canonicalization {
Some(CanonicalizeType::F32) => Some(CanonicalizeType::F64),
Some(CanonicalizeType::F64) => panic!("cannot promote F64"),
None => None,
},
depth,
}
}
fn demote(self, depth: usize) -> FloatValue {
FloatValue {
canonicalization: match self.canonicalization {
Some(CanonicalizeType::F64) => Some(CanonicalizeType::F32),
Some(CanonicalizeType::F32) => panic!("cannot demote F32"),
None => None,
},
depth,
}
}
}
/// Type of a pending canonicalization floating point value.
/// Sometimes we don't have the type information elsewhere and therefore we need to track it here.
#[derive(Copy, Clone, Debug)]
enum CanonicalizeType {
F32,
F64,
}
impl CanonicalizeType {
fn to_size(&self) -> Size {
match self {
CanonicalizeType::F32 => Size::S32,
CanonicalizeType::F64 => Size::S64,
}
}
}
trait PopMany<T> {
fn peek1(&self) -> Result<&T, CodegenError>;
fn pop1(&mut self) -> Result<T, CodegenError>;
fn pop2(&mut self) -> Result<(T, T), CodegenError>;
}
impl<T> PopMany<T> for Vec<T> {
fn peek1(&self) -> Result<&T, CodegenError> {
match self.last() {
Some(x) => Ok(x),
None => Err(CodegenError {
message: "peek1() expects at least 1 element".into(),
}),
}
}
fn pop1(&mut self) -> Result<T, CodegenError> {
match self.pop() {
Some(x) => Ok(x),
None => Err(CodegenError {
message: "pop1() expects at least 1 element".into(),
}),
}
}
fn pop2(&mut self) -> Result<(T, T), CodegenError> {
if self.len() < 2 {
return Err(CodegenError {
message: "pop2() expects at least 2 elements".into(),
});
}
let right = self.pop().unwrap();
let left = self.pop().unwrap();
Ok((left, right))
}
}
trait WpTypeExt {
fn is_float(&self) -> bool;
}
impl WpTypeExt for WpType {
fn is_float(&self) -> bool {
match self {
WpType::F32 | WpType::F64 => true,
_ => false,
}
}
}
enum FuncPtrInner {}
#[repr(transparent)]
#[derive(Copy, Clone, Debug)]
struct FuncPtr(*const FuncPtrInner);
unsafe impl Send for FuncPtr {}
unsafe impl Sync for FuncPtr {}
pub struct X64ExecutionContext {
#[allow(dead_code)]
code: CodeMemory,
function_pointers: Vec<FuncPtr>,
function_offsets: Vec<AssemblyOffset>,
signatures: Arc<Map<SigIndex, FuncSig>>,
breakpoints: BreakpointMap,
func_import_count: usize,
msm: ModuleStateMap,
exception_table: ExceptionTable,
}
/// On-disk cache format.
/// Offsets are relative to the start of the executable image.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CacheImage {
/// The executable image.
code: Vec<u8>,
/// Offsets to the start of each function. Including trampoline, if any.
/// Trampolines are only present on AArch64.
/// On x86-64, `function_pointers` are identical to `function_offsets`.
function_pointers: Vec<usize>,
/// Offsets to the start of each function after trampoline.
function_offsets: Vec<usize>,
/// Number of imported functions.
func_import_count: usize,
/// Module state map.
msm: ModuleStateMap,
/// An exception table that maps instruction offsets to exception codes.
exception_table: ExceptionTable,
}
#[derive(Debug)]
pub struct ControlFrame {
pub label: DynamicLabel,
pub loop_like: bool,
pub if_else: IfElseState,
pub returns: SmallVec<[WpType; 1]>,
pub value_stack_depth: usize,
pub fp_stack_depth: usize,
pub state: MachineState,
pub state_diff_id: usize,
}
#[derive(Debug, Copy, Clone)]
pub enum IfElseState {
None,
If(DynamicLabel),
Else,
}
pub struct SinglepassCache {
buffer: Arc<[u8]>,
}
impl CacheGen for SinglepassCache {
fn generate_cache(&self) -> Result<(Box<[u8]>, Memory), CacheError> {
let mut memory = Memory::with_size_protect(self.buffer.len(), Protect::ReadWrite)
.map_err(CacheError::SerializeError)?;
let buffer = &*self.buffer;
unsafe {
memory.as_slice_mut()[..buffer.len()].copy_from_slice(buffer);
}
Ok(([].as_ref().into(), memory))
}
}
impl RunnableModule for X64ExecutionContext {
fn get_func(
&self,
_: &ModuleInfo,
local_func_index: LocalFuncIndex,
) -> Option<NonNull<vm::Func>> {
self.function_pointers[self.func_import_count..]
.get(local_func_index.index())
.and_then(|ptr| NonNull::new(ptr.0 as *mut vm::Func))
}
fn get_module_state_map(&self) -> Option<ModuleStateMap> {
Some(self.msm.clone())
}
fn get_breakpoints(&self) -> Option<BreakpointMap> {
Some(self.breakpoints.clone())
}
fn get_exception_table(&self) -> Option<&ExceptionTable> {
Some(&self.exception_table)
}
unsafe fn patch_local_function(&self, idx: usize, target_address: usize) -> bool {
/*
0: 48 b8 42 42 42 42 42 42 42 42 movabsq $4774451407313060418, %rax
a: 49 bb 43 43 43 43 43 43 43 43 movabsq $4846791580151137091, %r11
14: 41 ff e3 jmpq *%r11
*/
#[repr(packed)]
struct LocalTrampoline {
movabsq_rax: [u8; 2],
addr_rax: u64,
movabsq_r11: [u8; 2],
addr_r11: u64,
jmpq_r11: [u8; 3],
}
self.code.make_writable();
let trampoline = &mut *(self.function_pointers[self.func_import_count + idx].0
as *const LocalTrampoline as *mut LocalTrampoline);
trampoline.movabsq_rax[0] = 0x48;
trampoline.movabsq_rax[1] = 0xb8;
trampoline.addr_rax = target_address as u64;
trampoline.movabsq_r11[0] = 0x49;
trampoline.movabsq_r11[1] = 0xbb;
trampoline.addr_r11 =
register_preservation_trampoline as unsafe extern "C" fn() as usize as u64;
trampoline.jmpq_r11[0] = 0x41;
trampoline.jmpq_r11[1] = 0xff;
trampoline.jmpq_r11[2] = 0xe3;
self.code.make_executable();
true
}
fn get_trampoline(&self, _: &ModuleInfo, sig_index: SigIndex) -> Option<Wasm> {
// Correctly unwinding from `catch_unsafe_unwind` on hardware exceptions depends
// on the signal handlers being installed. Here we call `ensure_sighandler` "statically"
// outside `invoke()`.
fault::ensure_sighandler();
unsafe extern "C" fn invoke(
_trampoline: Trampoline,
ctx: *mut vm::Ctx,
func: NonNull<vm::Func>,
args: *const u64,
rets: *mut u64,
error_out: *mut Option<Box<dyn Any + Send>>,
num_params_plus_one: Option<NonNull<c_void>>,
) -> bool {
let rm: &Box<dyn RunnableModule> = &(&*(*ctx).module).runnable_module;
let args =
slice::from_raw_parts(args, num_params_plus_one.unwrap().as_ptr() as usize - 1);
let ret = match fault::catch_unsafe_unwind(
|| {
// Puts the arguments onto the stack and calls Wasm entry.
#[cfg(target_arch = "x86_64")]
{
let args_reverse: SmallVec<[u64; 8]> = args.iter().cloned().rev().collect();
CONSTRUCT_STACK_AND_CALL_WASM(
args_reverse.as_ptr(),
args_reverse.as_ptr().offset(args_reverse.len() as isize),
ctx,
func.as_ptr(),
)
}
// FIXME: Currently we are doing a hack here to convert between native aarch64 and
// "emulated" x86 ABIs. Ideally, this should be done using handwritten assembly.
#[cfg(target_arch = "aarch64")]
{
struct CallCtx<'a> {
args: &'a [u64],
ctx: *mut vm::Ctx,
callable: NonNull<vm::Func>,
}
extern "C" fn call_fn(f: *mut u8) -> u64 {
unsafe {
let f = &*(f as *const CallCtx);
let callable: extern "C" fn(
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
u64,
)
-> u64 = std::mem::transmute(f.callable);
let mut args = f.args.iter();
callable(
f.ctx as u64,
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
args.next().cloned().unwrap_or(0),
)
}
}
let mut cctx = CallCtx {
args: &args,
ctx: ctx,
callable: func,
};
use libc::{
mmap, munmap, MAP_ANON, MAP_NORESERVE, MAP_PRIVATE, PROT_READ,
PROT_WRITE,
};
const STACK_SIZE: usize = 1048576 * 1024; // 1GB of virtual address space for stack.
let stack_ptr = mmap(
::std::ptr::null_mut(),
STACK_SIZE,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
-1,
0,
);
if stack_ptr as isize == -1 {
panic!("unable to allocate stack");
}
// TODO: Mark specific regions in the stack as PROT_NONE.
let ret = SWITCH_STACK(
(stack_ptr as *mut u8).offset(STACK_SIZE as isize) as *mut u64,
call_fn,
&mut cctx as *mut CallCtx as *mut u8,
);
munmap(stack_ptr, STACK_SIZE);
ret
}
},
rm.get_breakpoints(),
) {
Ok(x) => {
if !rets.is_null() {
*rets = x;
}
true
}
Err(err) => {
*error_out = Some(err);
false
}
};
ret
}
unsafe extern "C" fn dummy_trampoline(
_: *mut vm::Ctx,
_: NonNull<vm::Func>,
_: *const u64,
_: *mut u64,
) {
unreachable!()
}
Some(unsafe {
Wasm::from_raw_parts(
dummy_trampoline,
invoke,
NonNull::new((self.signatures.get(sig_index).unwrap().params().len() + 1) as _), // +1 to keep it non-zero
)
})
}
unsafe fn do_early_trap(&self, data: Box<dyn Any + Send>) -> ! {
fault::begin_unsafe_unwind(data);
}
fn get_code(&self) -> Option<&[u8]> {
Some(&self.code)
}
fn get_offsets(&self) -> Option<Vec<usize>> {
Some(self.function_offsets.iter().map(|x| x.0).collect())
}
fn get_local_function_offsets(&self) -> Option<Vec<usize>> {
Some(
self.function_offsets[self.func_import_count..]
.iter()
.map(|x| x.0)
.collect(),
)
}
/// Returns the inline breakpoint size corresponding to an Architecture.
fn get_inline_breakpoint_size(&self, arch: Architecture) -> Option<usize> {
match arch {
Architecture::X64 => Some(INLINE_BREAKPOINT_SIZE_X86_SINGLEPASS),
Architecture::Aarch64 => Some(INLINE_BREAKPOINT_SIZE_AARCH64_SINGLEPASS),
}
}
/// Attempts to read an inline breakpoint from the code.
///
/// Inline breakpoints are detected by special instruction sequences that never
/// appear in valid code.
fn read_inline_breakpoint(&self, arch: Architecture, code: &[u8]) -> Option<InlineBreakpoint> {
match arch {
Architecture::X64 => {
if code.len() < INLINE_BREAKPOINT_SIZE_X86_SINGLEPASS {
None
} else if &code[..INLINE_BREAKPOINT_SIZE_X86_SINGLEPASS - 1]
== &[
0x0f, 0x0b, // ud2
0x0f, 0xb9, // ud
0xcd, 0xff, // int 0xff
]
{
Some(InlineBreakpoint {
size: INLINE_BREAKPOINT_SIZE_X86_SINGLEPASS,
ty: match code[INLINE_BREAKPOINT_SIZE_X86_SINGLEPASS - 1] {
0 => InlineBreakpointType::Middleware,
_ => return None,
},
})
} else {
None
}
}
Architecture::Aarch64 => {
if code.len() < INLINE_BREAKPOINT_SIZE_AARCH64_SINGLEPASS {
None
} else if &code[..INLINE_BREAKPOINT_SIZE_AARCH64_SINGLEPASS - 4]
== &[
0, 0, 0, 0, // udf #0
0xff, 0xff, 0x00, 0x00, // udf #65535
]
{
Some(InlineBreakpoint {
size: INLINE_BREAKPOINT_SIZE_AARCH64_SINGLEPASS,
ty: match code[INLINE_BREAKPOINT_SIZE_AARCH64_SINGLEPASS - 4] {
0 => InlineBreakpointType::Middleware,
_ => return None,
},
})
} else {
None
}
}
}
}
}
#[derive(Debug)]
pub struct CodegenError {
pub message: String,
}
#[derive(Copy, Clone, Debug)]
struct CodegenConfig {
memory_bound_check_mode: MemoryBoundCheckMode,
enforce_stack_check: bool,
track_state: bool,
full_preemption: bool,
nan_canonicalization: bool,
}
impl ModuleCodeGenerator<X64FunctionCode, X64ExecutionContext, CodegenError>
for X64ModuleCodeGenerator
{
fn new() -> X64ModuleCodeGenerator {
let a = Assembler::new().unwrap();
X64ModuleCodeGenerator {
functions: vec![],
signatures: None,
function_signatures: None,
function_labels: Some(HashMap::new()),
assembler: Some(a),
func_import_count: 0,
config: None,
}
}
/// Singlepass does validation as it compiles
fn requires_pre_validation() -> bool {
false
}
fn backend_id() -> &'static str {
BACKEND_ID
}
fn new_with_target(_: Option<String>, _: Option<String>, _: Option<String>) -> Self {
unimplemented!("cross compilation is not available for singlepass backend")
}
fn check_precondition(&mut self, _module_info: &ModuleInfo) -> Result<(), CodegenError> {
Ok(())
}
fn next_function(
&mut self,
_module_info: Arc<RwLock<ModuleInfo>>,
_loc: WasmSpan,
) -> Result<&mut X64FunctionCode, CodegenError> {
let (mut assembler, mut function_labels, breakpoints, exception_table) =
match self.functions.last_mut() {
Some(x) => (
x.assembler.take().unwrap(),
x.function_labels.take().unwrap(),
x.breakpoints.take().unwrap(),
x.exception_table.take().unwrap(),
),
None => (
self.assembler.take().unwrap(),
self.function_labels.take().unwrap(),
HashMap::new(),
ExceptionTable::new(),
),
};
let begin_offset = assembler.offset();
let begin_label_info = function_labels
.entry(self.functions.len() + self.func_import_count)
.or_insert_with(|| (assembler.new_dynamic_label(), None));
begin_label_info.1 = Some(begin_offset);
assembler.arch_emit_entry_trampoline();
let begin_label = begin_label_info.0;
let mut machine = Machine::new();
machine.track_state = self.config.as_ref().unwrap().track_state;
assembler.emit_label(begin_label);
let signatures = self.signatures.as_ref().unwrap();
let function_signatures = self.function_signatures.as_ref().unwrap();
let sig_index = function_signatures
.get(FuncIndex::new(
self.functions.len() + self.func_import_count,
))
.unwrap()
.clone();
let sig = signatures.get(sig_index).unwrap().clone();
let code = X64FunctionCode {
local_function_id: self.functions.len(),
signatures: signatures.clone(),
function_signatures: function_signatures.clone(),
signature: sig,
fsm: FunctionStateMap::new(new_machine_state(), self.functions.len(), 32, vec![]), // only a placeholder; this is initialized later in `begin_body`
offset: begin_offset.0,
assembler: Some(assembler),
function_labels: Some(function_labels),
breakpoints: Some(breakpoints),
returns: smallvec![],
locals: vec![],
local_types: vec![],
num_params: 0,
value_stack: vec![],
fp_stack: vec![],
control_stack: vec![],
machine,
unreachable_depth: 0,
config: self.config.as_ref().unwrap().clone(),
exception_table: Some(exception_table),
};
self.functions.push(code);
Ok(self.functions.last_mut().unwrap())
}
fn finalize(
mut self,
_: &ModuleInfo,
) -> Result<
(
X64ExecutionContext,
Option<wasmer_runtime_core::codegen::DebugMetadata>,
Box<dyn CacheGen>,
),
CodegenError,
> {
let (assembler, function_labels, breakpoints, exception_table) =
match self.functions.last_mut() {
Some(x) => (
x.assembler.take().unwrap(),
x.function_labels.take().unwrap(),
x.breakpoints.take().unwrap(),
x.exception_table.take().unwrap(),
),
None => (
self.assembler.take().unwrap(),
self.function_labels.take().unwrap(),
HashMap::new(),
ExceptionTable::new(),
),
};
let total_size = assembler.get_offset().0;
let _output = assembler.finalize().unwrap();
let mut output = CodeMemory::new(_output.len());
output[0.._output.len()].copy_from_slice(&_output);
output.make_executable();
let mut out_labels: Vec<FuncPtr> = vec![];
let mut out_offsets: Vec<AssemblyOffset> = vec![];
for i in 0..function_labels.len() {
let (_, offset) = match function_labels.get(&i) {
Some(x) => x,
None => {
return Err(CodegenError {
message: format!("label not found"),
});
}
};
let offset = match offset {
Some(x) => x,
None => {
return Err(CodegenError {
message: format!("offset is none"),
});
}
};
out_labels.push(FuncPtr(
unsafe { output.as_ptr().offset(offset.0 as isize) } as _,
));
out_offsets.push(*offset);
}
let breakpoints: Arc<HashMap<_, _>> = Arc::new(
breakpoints
.into_iter()
.map(|(offset, f)| {
(
unsafe { output.as_ptr().offset(offset.0 as isize) } as usize,
f,
)
})
.collect(),
);
let local_function_maps: BTreeMap<usize, FunctionStateMap> = self
.functions
.iter()
.map(|x| (x.offset, x.fsm.clone()))
.collect();
let msm = ModuleStateMap {
local_functions: local_function_maps,
total_size,
};
let cache_image = CacheImage {
code: output.to_vec(),
function_pointers: out_labels
.iter()
.map(|x| {
(x.0 as usize)
.checked_sub(output.as_ptr() as usize)
.unwrap()
})
.collect(),
function_offsets: out_offsets.iter().map(|x| x.0 as usize).collect(),
func_import_count: self.func_import_count,
msm: msm.clone(),
exception_table: exception_table.clone(),
};
let cache = SinglepassCache {
buffer: Arc::from(bincode::serialize(&cache_image).unwrap().into_boxed_slice()),
};
Ok((
X64ExecutionContext {
code: output,
signatures: self.signatures.as_ref().unwrap().clone(),
breakpoints: breakpoints,
func_import_count: self.func_import_count,
function_pointers: out_labels,
function_offsets: out_offsets,
msm: msm,
exception_table,
},
None,
Box::new(cache),
))
}
fn feed_signatures(&mut self, signatures: Map<SigIndex, FuncSig>) -> Result<(), CodegenError> {