Function Prologue with Stack Realignment (x86, Linux, GCC)
What a function prologue is
When you call a function in C, the compiler has to prepare some “setup code” at the start of the function. This setup (the prologue) usually:
- Saves important registers so they can be restored later.
- Creates a “stack frame” so the function has its own workspace on the stack.
- Makes sure the stack is aligned the way the compiler/CPU expect.
On plain 32-bit Linux, functions often start with:
push ebp
mov ebp, espBut modern GCC sometimes adds a stack realignment prologue to guarantee the stack is 16-byte aligned (needed for SIMD instructions, ABI rules, or optimization).
1. On Entry to main
The stack looks like this (higher addresses at the top):
esp -> [ return address ] ; pushed by CALL instruction
[ argc ]
[ argv pointer ]
[ envp pointer ]2. lea ecx, [esp+4]
Save a pointer to the arguments:
ecx = esp + 4 -> points to argcNow we can still reach argc/argv even if we change esp.
3. and esp, -16
Align esp down to a multiple of 16.
Example: if esp was 0xbfffff0c, now it becomes 0xbfffff00.
This discards the old top of stack location—so the return address is no longer sitting where we expect.
4. push DWORD PTR [ecx-4]
Restore the return address.
ecx = old esp + 4, soecx-4 = old esp.- At
[old esp]was the return address. - Push it back on the new, aligned stack.
esp -> [ return address ] ; restored
(aligned stack continues)5. push ebp / mov ebp, esp
Classic frame pointer setup:
esp -> [ old ebp ]
[ return address ]Now ebp = esp, marking the base of this new stack frame.
6. push ebx / push ecx / mov ebx, ecx
- Save registers that must be preserved.
- Keep
ecx(pointer to argc/argv) in a safe register (ebx).
So now:
[ebx] = argc
[ebx+4] = argv
[ebx+8] = envpSummary
- Concept name: Stack realignment prologue (or “function prologue with stack alignment”).
- Purpose: Ensure stack is 16-byte aligned for ABI/optimizations.
- How: Temporarily saves argument pointer, realigns
esp, restores return address, then sets up a normal frame.
Resources
| Link | Description |
|---|---|