Skip to content

Instantly share code, notes, and snippets.

@glinesbdev
Created August 22, 2019 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glinesbdev/654dc81a9188181b711bfb806a2f3dcc to your computer and use it in GitHub Desktop.
Save glinesbdev/654dc81a9188181b711bfb806a2f3dcc to your computer and use it in GitHub Desktop.
MacOS Assembly - Fibonacci
global _main
extern _printf
section .text
_main:
push rbx ; We have to save this since we use it
mov ecx, 90 ; ecx will countdown to 0
xor rax, rax ; rax will hold the current number
xor rbx, rbx ; rbx will hold the next number
inc rbx ; rbx is originally 1
print:
; We may need to call printf, but we are using rax, rbx and rcx.
; printf may destroy rax and rcx so we will save these before the call
; and restore them afterwards.
push rax ; caller-save register
push rcx ; caller-save register
mov rdi, format ; set 1st parameter (format)
mov rsi, rax ; set 2nd parameter (current_number)
xor rax, rax ; because printf is varargs
; Stack is already aligned because we pushed three 8 byte registers
call _printf ; printf(format, current_number)
pop rcx ; restore caller-saved register
pop rax ; restore caller-saved register
mov rdx, rax ; save the current number
mov rax, rbx ; next number is now current
add rbx, rdx ; get the new current number
dec ecx ; count down
jnz print ; if not done counting, do some more
pop rbx ; restore rbx before returning
ret
format:
db "%20ld", 10, 0
@glinesbdev
Copy link
Author

To compile:

nasm -fmacho64 fib.asm
gcc -o fib.o fib
./fib

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment