I was reading this tutorial on assembly: http://orangejuiceliberationfront.com/intel-assembler-on-mac-os-x/ and I came across this basic assembly code:
.text
.globl _main
_main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
movl $0, %eax
leave
ret
And I kinda understand most of this, but I don't know why subl $8, %esp
is called. I understand that it subtracts 8 bytes from esp, but I have no idea why that is necessary or why its done. The tutorial said it balances the stack onto a 16-byte boundary, but I don't know what "balancing" the stack means or why using the number 8 makes a 16 byte boundary.
Later in the tutorial is show how to define a function, and call it like this:
.text
.globl _doSomething
_doSomething:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
nop
leave
ret
.globl _main
_main:
pushl %ebp
movl %esp, %ebp
subl $24, %esp
movl $3, (%esp)
call _doSomething
movl $0, %eax
leave
ret
And the tutorial there was "8 to align, 16 for our 4-byte parameter and padding" on this line: subl $24, %esp
But if there is a 4 byte parameter and padding, why are we using the number 16? Also, what parameter?
I am on a Intel Core mac, running OS X 10.9.3, compiling with gcc -S -m32 .
I'm very new to assembly, so please make your answers as simple as possible. Thanks!
Let's look at a sequence of instructions:
1. nop #call-stack is aligned to 16 bytes (sp is multiple of 16) to start.
2. call function #pushes return address (4 bytes) onto stack.
---(called function)
3. push %ebp #pushes base-pointer (4 bytes) onto stack, which is now 8-byte aligned
---cannot call function that expects to find 16-byte aligned stack---
4. sub $8, %esp #aligns stack to 16 bytes
5. call other_function