Last active
April 4, 2021 03:54
-
-
Save meerasndr/629b5e6d1877ecff56680dd9a8237a5d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
*C function* | |
int fact(int n){ | |
if (n <= 1) return 1; | |
return n * fact(n-1); | |
} | |
-- | |
*NASM code* | |
default rel | |
global _main | |
section .data | |
number: dd 5 | |
section .text | |
_main: mov eax, 1 | |
mov edi, [number] | |
call .fact | |
.fact: cmp edi, 2 | |
jl .basecase | |
push rbx | |
mov ebx, edi | |
lea edi, [rbx - 1] | |
call .fact | |
imul eax, ebx | |
pop rbx | |
.basecase: | |
ret | |
-- | |
*Step-through* | |
Sample function call: | |
fact(5); | |
edi = 5 | |
1st pass: | |
eax = 1 | |
cmp edi, 2 | |
islesser? No -> move on | |
push rbx | |
mov ebx, edi => ebx = 5 | |
lea edi, rbx - 1 => edi = 4 | |
call fact | |
ebx=5, edi=4 | |
2nd pass: | |
eax=1 | |
cmp edi, 2 // edi < 2 No, move on | |
push rbx | |
mov ebx, edi => ebx = 4 | |
lea edi, rbx-1 => edi = 3 | |
call fact | |
ebx=4, edi=3 | |
3rd pass: | |
eax=1 | |
cmp edi, 2 // edi < 2 No, move on | |
push rbx | |
mov ebx, edi => ebx = 3 | |
lea edi, rbx-1 => edi = 2 | |
call fact | |
ebx=3, edi=2 | |
4th pass: | |
eax=1 | |
cmp edi, 2 // edi<2 No, move on | |
push rbx | |
mov ebx, edi => ebx=2 | |
lea edi, rbx-1 => edi = 1 | |
call fact | |
ebx=2, edi=1 | |
5th pass: | |
eax=1 | |
cmp edi,2 // edi < 2, Yes | |
ret to 4th pass with eax=1 | |
imul eax, ebx 1 * 2 = 2 | |
pop rbx | |
ret to 3rd pass with eax=2 | |
imul eax, ebx => 2 * 3 = 6 | |
pop rbx | |
ret to 2nd pass with eax=6 | |
imul eax, ebx => 6 * 4 = 24 | |
pop rbx | |
ret to 1st pass with eax=24 | |
imul eax, ebx => 24 * 5 = 120 | |
ret with eax=120 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment