Search code examples
assemblystackcpu-registersmasm32

Assembly - Stack , Procedures, ESP, EBP, SS - Help me understand


I'm having difficulty understanding what's going on here, as far as what is on the stack, and where registers ESP, EBP, and SS are pointing to at the point in the code that says HERE. Here's my code

include \masm32\include\masm32rt.inc
.data?
    value DWORD ?
.code
start:
    push 42
    push 5
    call xyz
    mov value, EAX
    print str$(value)
    exit
xyz:
    enter 4, 0
    ; HERE
    leave
    ret 8
end start

So I need to see what's on the stack.

Here's my best guess as to where everything is (below is a text stack)

My Attempt 2.0


Solution

  • The stack will look like:

    42
    5
    return address
    previous ebp pushed by "enter"; new ebp points here
    4 uninitialized bytes due to "enter"; esp points here
    

    You can of course see this in a debugger:

    6       push 42
    (gdb) s
    start () at test.s:7
    7       push 5
    (gdb) 
    start () at test.s:8
    8       call xyz
    (gdb) p/x $eip+5
    $5 = 0x80483e5         # This is the return address (call is 5 bytes)
    (gdb) p/x $ebp
    $6 = 0xffffda78        # This is the ebp in the caller
    (gdb) s
    xyz () at test.s:11
    11      enter 4, 0
    (gdb) 
    12      leave
    (gdb) p/x $ebp
    $7 = 0xffffd9ec        # This is the current ebp
    (gdb) p/x $esp
    $8 = 0xffffd9e8        # This is esp
    (gdb) x/x $esp
    0xffffd9e8: 0x0804841b # Top of stack, 4 garbage bytes, esp points here
    (gdb) x
    0xffffd9ec: 0xffffda78 # Saved ebp, current ebp points here
    (gdb) x
    0xffffd9f0: 0x080483e5 # Return address
    (gdb) x
    0xffffd9f4: 0x00000005 # argument "5"
    (gdb) x
    0xffffd9f8: 0x0000002a # argument "42"
    

    SS is the stack segment, it is preset by the OS, it doesn't point anywhere but has base address 0 and is not changed.

    Note that enter x, 0 is equivalent to:

    push ebp
    mov ebp, esp
    sub esp, x