fiber_call_x86_64.s 2.54 KB
Newer Older
1 2
	.file	"fiber_call_x86_64.s"
	.text
3 4
	.global	__fiber_call
	.type	__fiber_call, @function
5 6

.align 16
7 8 9 10 11 12
__fiber_call:
        # Parameter List (in order)
        # rdi = new stack pointer
        # rsi = first parameter to callback
        # rdx = callback function pointer
        # rcx = new stack limit (not used on most platforms)
13

14 15 16 17 18 19 20 21
        # Return
        # rax = continuation that returned control back to the caller (null if fallthrough)

        # Variables
        # r12 = temporary for the old stack pointer

        ############### Save State ###############
        # Make space for all register state we will store.
22 23
        leaq -0x38(%rsp), %rsp

24
        # Store calee saved general registers.
25 26 27 28 29 30
        movq %r12, 0x00(%rsp)
        movq %r13, 0x08(%rsp)
        movq %r14, 0x10(%rsp)
        movq %r15, 0x18(%rsp)
        movq %rbx, 0x20(%rsp)
        movq %rbp, 0x28(%rsp)
31
        # Store MMX control- and status-word
32
        stmxcsr 0x30(%rsp)
33
        # Store x87 control-word
34
        fnstcw 0x34(%rsp)
35
        ############### Save State ###############
36

37 38
        # Perform change to new stack.
        # Keep old stack as second parameter to our callback function.
39
        movq %rsp, %r12
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
        # Make sure that stack start is properly aligned.
        andq $-16, %rdi
        # Switch to new stack pointer.
        movq %rdi, %rsp

        # Perform actual function call, this will now be on the new stack
        # rdi = first parametor to callback (continuation)
        # rsi = second parameter to callback (arbetary pointer)
        movq %r12, %rdi
        call *%rdx

        # Restore state of returned continuation.
        # To do so we first reset the stack pointer (which we get returned in rax).
        # After that we execute our standard restore procedere to pop the state from the stack.
        movq %rax, %rsp

        ############ Restore State  ############
        # restore calee saved general registers
58
        movq 0x00(%rsp), %r12
59 60 61 62 63 64 65 66 67
        movq 0x08(%rsp), %r13
        movq 0x10(%rsp), %r14
        movq 0x18(%rsp), %r15
        movq 0x20(%rsp), %rbx
        movq 0x28(%rsp), %rbp
        # restore MMX control- and status-word
        ldmxcsr 0x30(%rsp)
        # restore x87 control-word
        fldcw 0x34(%rsp)
68

69
        # Free space for restored state
70
        leaq 0x38(%rsp), %rsp
71 72 73
        ############ Restore State  ############

        # TODO: Maybe look into a 'cleanup' hook for freeing the stack space here.
74

75 76 77
        # Just return back from the call.
        # This is the end of a fiber, so we have no continuation.
        xor %rax, %rax
78
        ret