ContextAsm.nasm 1.29 KB
Newer Older
Florian Schmaus's avatar
Florian Schmaus committed
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
[Section .text]

[GLOBAL switch_and_load_context]
[GLOBAL save_and_switch_context]
[GLOBAL switch_context]

; Stack layout after the state was saved on the stack.
;
;		| ... |
;	 40 | r15 |
;	 32 | r14 |
;	 24 | r13 |
;	 16 | r12 |
;	  8 | rbp |
;	  0 | rbx | <- ToS after switching stack to this context
%macro STATE_SAVE 0
	sub rsp, 48
	mov [rsp+40], r15
	mov [rsp+32], r14
	mov [rsp+24], r13
	mov [rsp+16], r12
	mov [rsp+8],  rbp
	mov [rsp],    rbx
%endmacro

%macro STATE_LOAD 0
	mov rbx, [rsp]
	mov rbp, [rsp+8]
	mov r12, [rsp+16]
	mov r13, [rsp+24]
	mov r14, [rsp+32]
	mov r15, [rsp+40]
	add rsp, 48
%endmacro

; switch_and_load_context(void *to)
;                         rdi
align 16
switch_and_load_context:
	; Load new context.
	mov rsp, [rdi] ; saved rsp
	STATE_LOAD
	ret

; save_and_switch_context(void** savedSpNew, void** savedSpOld)
;                         rdi                rsi
align 16
save_and_switch_context:
	; Store current context.
	STATE_SAVE
	mov [rsi], rsp ; save rsp
	; Fall through

; switch_context(void *contextTos)
;                rdi
switch_context:
	; Switch to new context: Activate the new stack by setting rsp,
	; which must point to a word which represent the memory address
	; where we want to continue.
	mov rsp, [rdi]
61
62
	; Jump to the address rsp currently points at.
	jmp [rsp]