Re: Any explanations



"John" <spamtrap@xxxxxxxxxx> wrote in message
news:1156649393.433513.187070@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
call __alloca
call ___main
leave
xorl %eax, %eax
ret


These two instructions (out of order) save and replace the current stack
pointer. They are equivalent the 'leave' instruction. These two when
combined with the 'subl $8, %esp' are the C function's prolog. The prolog
and epilog (below) create and destroy the stackframe, respectively.
pushl %ebp
movl %esp, %ebp

This allocates space for a 'long'. This is usually for passed arguments,
but main has none due to 'void'. Since there are no declaread variables, I
can only assume that alloca() or the secondary main() consumes a stack
argument.
subl $8, %esp

Again, you usually see this for a argument passed by a register. Perhaps it
is consumed by alloca() or the secondary main().
movl $16, %eax

I can only assume Mr. Collins statement about stack alignment is correct for
the following:
andl $-16, %esp

calls alloca() and a secondary main(). These are not present in C code.
They either have something to do with C++ or your program.
call __alloca
call ___main

This restores the saved stack pointer. It is equivalent to 'movl %ebp,
%esp; popl %ebp'. It is also the C functions epilog.
leave

This generates the zero and return for the return(0).
xorl %eax, %eax
ret



Rod Pemberton

.



Relevant Pages

  • Re: Newbie question...
    ... "and esp, 0xFFFFFFF0" probably makes it clearer that we're aligning the stack to 16 bytes. ... Make ebp a kind of "semi stack frame pointer". ... We "return foo " in eax. ...
    (alt.lang.asm)
  • Re: Newbie question...
    ... and esp, -16 ... mov ebp, esp ... Since the x86 increments esp with "pop", the new stack pointer is aligned ... add eax, 15 ...
    (alt.lang.asm)
  • Re: Ann: Luxasm 00.01.00 (2004-04-08)
    ... add esp, 12 ... push assembler ... %define lenvp ebp + 16 ... or eax, eax ...
    (alt.lang.asm)
  • Re: Reading floating-point input from stdin in NASM
    ... lea eax, ... push dword int_format ... mov ebp, esp ...
    (comp.lang.asm.x86)
  • Re: Any explanations
    ... movl %esp, %ebp ... xorl %eax, %eax ... I guess alloca allocate some memory? ...
    (comp.lang.asm.x86)