Search code examples
assemblyx86fasmstack-frame

Why would an assembly programmer want to subtract from ebp in this location instead of esp?


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?


Solution

  • 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.