Advertisement
mdgaziur001

fibonacci in asm(gas)

Nov 21st, 2022
1,467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. .section .text
  2. .global main
  3. .intel_syntax noprefix
  4.  
  5. # takes value in rdi and returns in rax
  6. fib:
  7.   cmp rdi, 1
  8.   jl .br1                         # if (n < 1)
  9.   je .br2                         # else if (n == 1)
  10.   jmp .normal                     # else
  11.  
  12. .br1:
  13.   mov rax, 0                      # return 0;
  14.   ret
  15.  
  16. .br2:
  17.   mov rax, 1                      # return 1;
  18.   ret
  19.  
  20. .normal:
  21.   # int x = fib(n - 1);
  22.   push rdi
  23.   sub rdi, 1
  24.   call fib
  25.  
  26.   # int y = fib(n - 2);
  27.   pop rdi
  28.   sub rdi, 2
  29.   push rax
  30.   call fib
  31.  
  32.   # int result = x + y;
  33.   mov rbx, rax
  34.   pop rax
  35.   add rbx, rax
  36.  
  37.   # return result;
  38.   mov rax, rbx
  39.   ret
  40.  
  41. main:
  42.   push rbp
  43.   mov rbp, rsp
  44.   sub rsp, 16
  45.  
  46.   # printf("Enter n: ");
  47.   lea rdi, qword ptr [rip+.fmt_prompt]
  48.   xor rax, rax
  49.   call printf@plt
  50.  
  51.   # scanf("%d", &n);
  52.   lea rdi, qword ptr [rip+.fmt_scanf]
  53.   lea rsi, qword ptr [rip+n]
  54.   xor rax, rax
  55.   call scanf@plt
  56.  
  57.   # int result = fib(n);
  58.   mov rdi, qword ptr [rip+n]
  59.   call fib@plt
  60.  
  61.   # printf("Fibonacci of %d is %d", n, result);
  62.   lea rdi, qword ptr [rip+.fmt_printf]
  63.   mov rsi, qword ptr [rip+n]
  64.   mov rdx, rax
  65.   xor rax, rax
  66.   call printf@plt
  67.  
  68.   add rsp, 16
  69.   pop rbp
  70.  
  71.   # return 0;
  72.   xor rax, rax
  73.   ret
  74.  
  75. .section .bss
  76. n:
  77.   .zero 8
  78.  
  79. .section .rodata
  80. .fmt_prompt:
  81.   .asciz "Enter n: "
  82.  
  83. .fmt_scanf:
  84.   .asciz "%d"
  85.  
  86. .fmt_printf:
  87.   .asciz "Fibonacci of %d is %d\n"
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement