Skip to content

Instantly share code, notes, and snippets.

@dgalling
Created December 20, 2011 04:45
Show Gist options
  • Save dgalling/1500301 to your computer and use it in GitHub Desktop.
Save dgalling/1500301 to your computer and use it in GitHub Desktop.
default rel
bits 64
; stuff we need to export to C
global _fiber_new
global _fiber_yield
global _fiber_start
global _fiber_resume
global _main
; stuff we need from C
extern _malloc
extern _printf
section .data
str: db 'Hello, world',10,0
section .bss
current_fiber: resq 1
saved_rbp: resq 1
saved_rsp: resq 1
section .text
_fiber_new:
mov r12, rdi
mov rdi, 4096 ; allocate space for a fiber
call _malloc
mov qword [rax], r12 ; set the initial rip of the fiber to the
; function pointer passed in as the first
; argument
mov rbx, rax
add rbx, 4088
mov qword [rax + 16], rbx
mov qword [rax + 24], rbx ; set up initial stack
ret
_fiber_yield:
pop qword [current_fiber] ; the fiber should resume at the return
; address of this function
jmp _fiber_cleanup
_fiber_resume:
mov [current_fiber], rdi ; save the address of the fiber
pop qword [rdi + 8] ; pop the return address into memory
mov qword [saved_rsp], rsp
mov qword [saved_rbp], rbp
mov rbp, qword [rdi + 16]
mov rsp, qword [rdi + 24]
call [rdi]
jmp _fiber_cleanup
_fiber_start:
jmp _fiber_resume
_fiber_cleanup:
mov rax, [current_fiber]
add rax, 16
mov qword [rax], rbp
add rax, 8
mov qword [rax], rsp
mov rsp, qword [saved_rsp]
mov rbp, qword [saved_rbp]
sub rax, 16
jmp [rax]
_main:
mov rdi, _func
call _fiber_new
mov rax, 0
ret
_func:
push rbp
mov rbp, rsp
sub rsp, 8
mov rdi, str
call _printf
add rsp, 8
mov rsp, rbp
pop rbp
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment