|
| 1 | +; ----------------------------------------------------------------------------- |
| 2 | +; A 64-bit Linux application that writes the first 90 Fibonacci numbers. To |
| 3 | +; assemble and run: |
| 4 | +; |
| 5 | +; nasm -felf64 fib.asm && gcc fib.o && ./a.out |
| 6 | +; ----------------------------------------------------------------------------- |
| 7 | + |
| 8 | + global main |
| 9 | + extern printf |
| 10 | + |
| 11 | + section .text |
| 12 | +main: |
| 13 | + push rbx ; we have to save this since we use it |
| 14 | + |
| 15 | + mov ecx, 90 ; ecx will countdown to 0 |
| 16 | + xor rax, rax ; rax will hold the current number |
| 17 | + xor rbx, rbx ; rbx will hold the next number |
| 18 | + inc rbx ; rbx is originally 1 |
| 19 | +print: |
| 20 | + ; We need to call printf, but we are using rax, rbx, and rcx. printf |
| 21 | + ; may destroy rax and rcx so we will save these before the call and |
| 22 | + ; restore them afterwards. |
| 23 | + |
| 24 | + push rax ; caller-save register |
| 25 | + push rcx ; caller-save register |
| 26 | + |
| 27 | + mov rdi, format ; set 1st parameter (format) |
| 28 | + mov rsi, rax ; set 2nd parameter (current_number) |
| 29 | + xor rax, rax ; because printf is varargs |
| 30 | + |
| 31 | + ; Stack is already aligned because we pushed three 8 byte registers |
| 32 | + call printf ; printf(format, current_number) |
| 33 | + |
| 34 | + pop rcx ; restore caller-save register |
| 35 | + pop rax ; restore caller-save register |
| 36 | + |
| 37 | + mov rdx, rax ; save the current number |
| 38 | + mov rax, rbx ; next number is now current |
| 39 | + add rbx, rdx ; get the new next number |
| 40 | + dec ecx ; count down |
| 41 | + jnz print ; if not done counting, do some more |
| 42 | + |
| 43 | + pop rbx ; restore rbx before returning |
| 44 | + ret |
| 45 | +format: |
| 46 | + db "%20ld", 10, 0 |
0 commit comments