Will add more in the future but just gonna write some basic assembly to show you what it might look like.
Factorials and Rescursive functions Link to heading
Below is a demonstration of how to calculate the factorial of a number pushed onto the stack in x86 assembly, the x86_64 will be below
1; calculate the factorial
2; 3! = 3 * 2 * 1
3
4; x86 32 bit example
5
6.section .data
7
8.section .text
9.globl _start
10.globl factorial
11
12_start:
13 pushl $4 ; push argument (factorial 4)
14 call factorial
15 addl $4, %esp ; scrub parameter, always return SP to where it was before
16 ; we called a function
17 movl %eax, %ebx ; store in ebx as our return status
18
19 movl $1, %eax
20 int $0x80
21
22.type factorial, @function
23factorial:
24 pushl %ebp ; push so we can restore ebp afterwards
25 movl %esp, %ebp ; we dont want to modify the SP so we push it to ebp
26 movl 8(%ebp), %eax
27 cmpl $1, %eax
28 je end_factorial
29 decl %eax
30 pushl %eax ; push it for our call to factorial
31 call factorial
32 movl 8(%ebp), %ebx ; reload our parameter in %ebx
33 imull %ebx, %eax
34
35end_factorial:
36 movl %ebp, %esp ; restoring ebp and esp to where
37 popl %ebp ; they were before the function started
38
39 ret
1; calculate the factorial
2; 3! = 3 * 2 * 1
3
4; x86_64 64bit example
5
6.section .data
7
8.section .text
9.globl _start
10.globl factorial
11
12_start:
13 movl $5, %rdi
14 call factorial
15 mov %rax, %rdi
16 jmp exit
17
18.type factorial, @function
19factorial:
20 movl %rdi, %rax
21 cmpl $1, %rax
22 je end_factorial
23 decl %rax
24 movl %rax, %rdi
25 call factorial
26 movl %rax, %rbx
27 imull %rbx, %rax
28
29exit:
30 ret
more to come…