Why does this ASM code starts with a push?

I’m reading “reverse engineering for beginners” and picking up ASM along the way, one thing i couldn’t figure it out however is why this hello world (in C):
2018-01-04-104417_476x259_scrot

Turns into this ASM code.

Specifically, i don’t understand why it starts with “push ebp”, i know ebp points to the current stack frame, and i imagine that push ebp, mov ebp, esp means “whatever is currently on the stack frame, push it onto the stack and create this new, empty stack frame”. Is that correct?

The push is there to allow you to clear the stack you made without destroying the stack of the calling subroutine/function. A subroutine usually does this:

pushl %ebp
movl %esp, %ebp
# subroutine stuff goes here
movl %ebp, %esp
popl %ebp
ret

Although the leave op can do the same thing (welcome to CISC), so instead you have:

pushl %ebp
movl %esp, %ebp
# subroutine stuff goes here
leave
ret

This just backs up the previous stack base %ebp and restores it after you are done. If the routine doesn’t use the stack, you don’t need that push-mov combo or the leave.

https://en.wikibooks.org/wiki/X86_Assembly/GAS_Syntax#"hello.s"_line-by-line


There is also an enter instruction, but it is slower than

pushl %ebp
movl %esp, %ebp
1 Like

You can also clear the stack with a lot of 0’s :stuck_out_tongue:

Search for cdecl calling convention.

https://en.wikibooks.org/wiki/X86_Disassembly/Calling_Conventions#CDECL

The calling function cleans the stack. This allows CDECL functions to have variable-length argument lists (aka variadic functions).

@Selhar’s ASM code is cleaning the stack itself though, right? Wouldn’t that make it something other than CDECL.

Nevermind, I didn’t understand that correctly, the backing up of EBP is not part of calling conventions at all.

What exactly do you mean by stack cleaning in that snippet of code? If you are talking about the 3rd and 4th instruction those are probably there to align the ESP to 16 bytes (last 4 bits zero).

Sorry, for a second there I thought cleaning the stack was the part where you restore the EBP to the pre-call state. I misunderstood the CDECL example I was looking at.