Sunday, August 1, 2010

understand how assembly make use of stack by tracing recursive function call

understand how assembly make use of stack by tracing recursive function call
1 call factorial                                       |  1
  2 addl $4, %esp # scrubs the parameter that was      |  2
  3               # pushed on the stack                |  3 $4
  4 movl %eax, %ebx                                    |  4 ret to 2
  5                                                    |  5 %ebp is 0, after is 5
  6 factorial:                                         |  6 $3
  7   pushl %ebp                                       |  7 ret to 18
  8   movl %esp, %ebp                                  |  8 %ebp is 5, after is 8
  9                                                    |  9 $2
 10   movl 8(%ebp), %ebx                               | 10 ret to 18
 11   cmpl $1, %eax                                    | 11 %ebp is 8, after is 11
 12   je end_fac                                       | 12 $1
 13                                                    | 13 ret to 18
 14   decl %eax                                        | 14 %ebp is 11, after is 14
 15   pushl %eax                                       | 15
 16                                                    | 16
 17   call factorial                                   | 17
 18   movl 8(%ebp), %ebx                               | 18
 19   imull %ebx, %eax                                 | 19 %esp  %ebp
 20                                                    | 20 14    11
 21 end_fac:                                           | 21 11    8
 22   movl %ebp, %esp                                  | 22 8     5
 23   popl %ebp                                        | 23 5     0
 24   ret                                              | 24
 25                                                    | 25
~                                                      |~

Reference:
http://en.wikipedia.org/wiki/Call_stack

http://stackoverflow.com/questions/1395591/what-is-exactly-the-base-pointer-and-stack-pointer-to-what-do-they-point

http://unixwiz.net/techtips/win32-callconv-asm.html

http://en.wikipedia.org/wiki/X86_assembly_language

http://www.xs4all.nl/~smit/asm01001.htm

http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames

No comments: