1 ; Chapter 4 Factorial (recursive)
     
2 ; 
     
3 ; Computes the factorial
     
4 ; Demonstrates recursive functions and the stack.
     
5 ;
     
6 ;     $ ./go.sh ch04.2_factorial
     
7 ;     Exited with code: 24
     
8 ;
     
9 section .data
    
10 
    11 section .text
    
12 
    13 ; Start - Call power twice, return result
    
14 ; ---------------------------------------------------------
    
15 global _start
    
16 _start:
    
17     push dword 4     ; push function arg on stack
    
18 
    19     call factorial   ; call recursive function!
    
20 
    21     ; Move the stack pointer BACKWARD (by adding) to remove
    
22     ; the parameter that was pushed onto the stack. 
    
23     add esp, 4
    
24 
    25     ; Move the answer in eax to ebx to use as exit code.
    
26     mov ebx, eax
    
27     mov eax, 1       ; syscall 'exit'
    
28     int 0x80         ; linux interrupt
    
29 
    30 ; factorial function
    
31 ; ---------------------------------------------------------
    
32 ; input:
    
33 ;   arg1 -> eax   is the base number
    
34 ; output:
    
35 ;   answer in eax
    
36 ;
    
37 ; Note: This function calls itself recursively!
    
38 global factorial:function
    
39 factorial:
    
40     push ebp       ; save base pointer
    
41     mov ebp, esp   ; set it to stack pointer
    
42 
    43     ; Get first param into eax
    
44     ;   ebp + 4 is the return address
    
45     ;   ebp + 8 is the first param
    
46     mov eax, [ebp + 8]
    
47 
    48     ; If the param is 1, that's our base case, return it!
    
49     cmp eax, 1
    
50     je .end_factorial
    
51 
    52     ; Keep going: decrement the value and recurse!
    
53     dec eax
    
54     push eax ; push param
    
55     call factorial
    
56 
    57     ; Recursion done, stack is now full of values to be
    
58     ; multiplied. Register eax contains the previous result.
    
59     mov ebx, [ebp + 8]
    
60     imul eax, ebx
    
61 
    62 .end_factorial:
    
63     ; Restore stack stuff and return. Answer already in eax.
    
64     mov esp, ebp
    
65     pop ebp
    
66     ret