i386 assembly question: why do I need to meddle with the stack pointer?

Posted by zneak on Stack Overflow See other posts from Stack Overflow or by zneak
Published on 2010-06-06T02:44:16Z Indexed on 2010/06/06 2:52 UTC
Read the original article Hit count: 313

Filed under:
|

Hello everyone,

I decided it would be fun to learn x86 assembly during the summer break. So I started with a very simple hello world program, borrowing on free examples gcc -S could give me. I ended up with this:

HELLO:
    .ascii "Hello, world!\12\0"
    .text

.globl _main
_main:
    pushl   %ebp        # 1. puts the base stack address on the stack
    movl    %esp, %ebp  # 2. puts the base stack address in the stack address register
    subl    $20, %esp   # 3. ???
    pushl   $HELLO      # 4. push HELLO's address on the stack
    call    _puts       # 5. call puts
    xorl    %eax, %eax  # 6. zero %eax, probably not necessary since we didn't do anything with it
    leave               # 7. clean up
    ret                 # 8. return
                        # PROFIT!

It compiles and even works! And I think I understand most of it.

Though, magic happens at step 3. Would I remove this line, my program would die between the call to puts and the xor from a misaligned stack error. And would I change $20 to another value, it'd crash too. So I came to the conclusion that this value is very important.

Problem is, I don't know what it does and why it's needed.

Can anyone explain me? (I'm on Mac OS, would it ever matter.)

© Stack Overflow or respective owner

Related posts about gas

Related posts about asm