I'm doing one of many tasks from the book called "Programming From The ground up", by Jonathan Bartlett.
I'm currently at this task from page 72:
The factorial function can be written non-recursively. Do so.
Following program works fine.I'm having trouble understanding where EBX, ECX and EAX registers are on the stack.
Why does following code not use PUSHL and POPL instructions to place registers on stack?
What is difference between pushing registers and them mysteriously existing somewhere on stack?
.section .data
.section .text
.globl _start
_start:
pushl $4 #pushing argument
call factorial #calling function
addl $4, %esp #move stack pointer back
movl %eax, %ebx #place result into ebx for exit status
movl $1, %eax #exit
int $0x80
#finds the factorial of a value
#INPUT: First and only argument is the number to find the factorial for
#NOTES: number must be greater than one Variables:
# %ebx – holds the argument value
# %ecx – holds the index we are multiplying the argument by
# -4(%ebp) – holds the current result
# %eax is used for temporary storage
factorial:
pushl %ebp #save old base pointer
movl %esp, %ebp #make stack pointer the base pointer
subl $4, %esp #get room for local storage
movl 8(%ebp), %ebx #put first argument in %eax
movl %ebx, %ecx #set index to the value of argument
decl %ecx #subtract index by 1 as starting point
movl %ebx, -4(%ebp) #store current result
factorial_loop_start:
movl -4(%ebp), %eax #move current result into %eax
imull %ecx, %eax #multiple current result by index
movl %eax, -4(%ebp) #move new result into storage
decl %ecx #decrease index by 1
cmpl $1, %ecx #if index is 1 jump to end of loop
je end_factorial
jmp factorial_loop_start #if index is not one restart loop
end_factorial:
#movl -4(%ebp), %eax #return value goes in %eax
movl %ebp, %esp #restore stack pointer
popl %ebp #restore base pointer
ret
# To run, from the command line (I'm using an x86-64 build so you may need to assemble differently)
# as --32 factorial.s -o factorial.o
# ld -melf_i386 factorial.o -o factorial
# ./factorial
# echo $?