John wrote:
I would like to understand the following C++/C program in assembly
int main(void){
return 0;
}
================g++ -O -S compile.cpp
.file "x.c"
.def ___main; .scl 2; .type 32; .endef
.file "x.c"
.def ___main; .scl 2; .type 32; .endef
.text
.align 2
.p2align 4,,15
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
pushl %ebp
movl $16, %eax
probably the argument to the 'alloca' call. Alloca allocates stack
space. Not sure why it is being called.
>
movl %esp, %ebp
>
subl $8, %esp
this is generally how local variables are allocated. The pushl ebp, move
esp, ebp, and subl 8, esp could be replaced by an enter instruction, but
that is a lot slower so most compilers do this explicitly. You haven't
declared local variables so this might have something to do with C++
exception handling.
>
andl $-16, %esp
align the stack. Stack alignment is done by GCC because floating point
accesses are significantly faster when aligned.
>
call __alloca
now allocate space on the stack. Not sure what is happening here. Could
be allocating something required for C++ exception use. or could be doing
alignment for the next call, or could be
allocating space for return data from the next call
>
call ___main
this is probably a C++ stub that somehow executes the constructors for
file-scope objects.
>
>
leave
restore ESP and EBP to what they were when the function entered
(same as movl %ebp, %esp, popl %ebp)
>
xorl %eax, %eax
this is the code for the 'return 0' statement. By convention integers
are returned in EAX. This instruction sets EAX to 0.
>
ret
What is actually going on? Why subtract 8 from esp (is that the stack
pointer?)
why this magical -16? what happens when alloca and main are called?
What
is leave and xorl? Is there a explanation of something like this or a
tutorial on
the web that can help me understand this?
Thanks a lot,
--j
..