recursive fibonacci in x86-64 assembly language with NASM on Mac OS X
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; nasm -f macho64 fab.asm && ld -arch x86_64 -lSystem fab.o -o fab && ./fab | |
global start | |
extern _printf | |
section .text | |
fab: | |
; prolog | |
push rbp | |
mov rbp, rsp | |
; get the argument | |
mov rax, [rbp+16] | |
; if a == 0 then return 0 | |
cmp rax, 0 | |
jle fabret | |
; if a == 1 then return 1 | |
cmp rax, 1 | |
je fabret | |
; if a > 1 then return fab(a-1) + fab(a-2) | |
sub rsp, 8 ; make a room for the variable | |
; save "a" as local variable | |
mov [rbp-8], rax | |
mov rbx, rax | |
; (a-1) | |
mov rcx, rbx | |
sub rcx, 1 | |
push rcx | |
call fab | |
add rsp, 8 | |
add [rbp-8], rax | |
; a-2 | |
mov rcx, rbx | |
sub rcx, 2 | |
push rcx | |
call fab | |
add rsp, 8 | |
add [rbp-8], rax | |
add rax, [rbp-8] | |
fabret: | |
; push qword rax | |
; push qword rbx | |
; call fabprint | |
; add rsp, 8 * 2 | |
mov rsp, rbp | |
pop rbp | |
ret | |
; fabprint(N, F) | |
fabprint: | |
push rbp | |
mov rbp, rsp | |
push rax | |
push rbx | |
push rcx | |
push rdx | |
mov rdi, retstr | |
mov rsi, [rbp + 8*1 + 8] | |
mov rdx, [rbp + 8*2 + 8] | |
xor rax, rax | |
call _printf | |
xor rax, rax | |
pop rdx | |
pop rcx | |
pop rbx | |
pop rax | |
pop rbp | |
ret | |
start: | |
push 8 | |
call fab | |
add rsp, 8 | |
push rax | |
push 8 | |
call fabprint | |
add rsp, 16 | |
; 2a prepare the argument for the sys call to exit | |
push dword 0 ; exit status returned to the operating system | |
mov rax, 0x2000001 | |
mov rdi, 0 | |
syscall | |
section .data | |
retstr: db 'fab(%d)=%d', 0xa, 0 | |
section .bss |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment