Reputation: 2537
I am having slight confusion about the usage of ebp and esp in relation to setting up a stack frame in x86 assembly language. In this following code:
section '.code' code readable executable ; define the code section of the file
main: ;main label is where execution begins
push ebp
mov ebp,esp ;set up the base ptr
sub ebp,4 ;subtract 4 from ebp
mov dword [esp],msg
call [printf]
mov dword [esp],p ; pass pause>nul cmd to system to hold the box open
call [system]
mov dword [esp],0 ;pass NULL to exit
call [exit]
The programmer has subtracted 4 from ebp but I'm not sure why. Typically, I see a subtract from ESP here instead of EBP. What is the purpose of subtracting from EBP here?
Upvotes: 1
Views: 1018
Reputation: 47653
Your code seem to be from a FASM tutorial where the full code looked like:
format PE console
entry main
include 'macro/import32.inc'
section '.data' data readable writeable
msg db "hello world!",0
p db "pause>nul",0
section '.code' code readable executable
main:
push ebp
mov ebp,esp
sub ebp,4
mov dword [esp],msg
call [printf]
mov dword [esp],p
call [system]
mov dword [esp],0
call [exit]
section '.idata' import data readable
library msvcrt,'msvcrt.dll'
import msvcrt,\
printf,'printf',\
system,'system',\
exit,'exit'
In the description of the code the author wrote this:
Starting with our entrypoint label main, I set up a stack frame and allocate 4 bytes on the stack by subtracting 4 from the value of esp. Now in that 4 byte range I place the address of msg in there and call printf,
This leads me to believe that the actual instruction the author intended was:
sub esp, 4
The code effectively has a typo. The description is correct, the code is wrong.
Upvotes: 2
Reputation: 18531
This is definitely a bug:
push ebp ; 1
mov ebp,esp ; 2
sub ebp,4 ; 3
mov dword [esp],msg ; 4
Because instructions 2 and 3 only modify the ebp
register (but not esp
) instruction 4 will overwrite the value pushed in instruction 1.
I doubt that the programmer intended that.
Upvotes: 5