Behaviour of ebp and esp in stacks using function with parameter

橙三吉。 提交于 2019-12-01 11:27:11

During the first function execution esp and ebp have the same value only immediately after the instruction mov ebp, esp. After that and esp, -16 zeroes the lowest 4 bits (the lowest nibble) of esp, and esp and ebp diverge, unless the lowest bits of esp were zeroes already. Then sub esp, 32 subtracts 32 from esp and here esp and ebp diverge for sure.

push ebp                   ; esp = esp - 4; [esp] = ebp.
mov ebp, esp               ; ebp = esp. create the stack frame. 
and esp, -16               ; make lowest 4 bits of esp zeros, for alignment.
sub esp, 32                ; esp = esp - 32. make space for local variables.
mov DWORD PTR[esp+28], 5   ; a = 5
mov DWORD PTR[esp+24], 4   ; b = 4
mov DWORD PTR[esp+20], 2   ; c = 2
mov eax, DWORD PTR[esp+20] ; eax = c (eax = 2)
mov DWORD PTR[esp+8], eax  ; [esp+8] = dword 2
mov eax, DWORD PTR[esp+24] ; eax = b (eax = 4)
mov DWORTD PTR[esp+4], eax ; [esp+4] = dword 4
mov eax, DWORD PTR[esp+28] ; eax = a (eax = 5)
mov DWORD PTR[esp], eax    ; [esp] = dword 5
call sum                   ; the above lines define the parameters for the
                           ; function sum, that is called now.

Then regarding your second question:

push ebp                   ; esp = esp - 4; [esp] = ebp.
mov ebp, esp               ; ebp = esp.
sub esp, 16                ; esp = esp - 16. create space for local variables.
                           ; at this point:
                           ; [ebp]    == old value of ebp.
                           ; [ebp+4]  == return address pushed by call,
                           ;             to be used by the next ret.
                           ; [ebp+8]  == dword 5 (a)
                           ; [ebp+12] == dword 4 (b)
                           ; [ebp+16] == dword 2 (c)
mov eax, DWORD PTR[ebp+12] ; eax = 4
mov edx, DWORD PTR[ebp+8]  ; edx = 5. gets overwritten by the next instruction.          
mov edx, eax               ; edx = eax = 4

Don't assume esp == ebp. In this second function too esp and ebp diverge upon execution of the instruction sub esp,16. Learn to use a debugger, for example GDB and single-step through the code and follow the values of registers (especially esp) and memory after each instruction. You can also debug the code in your head as I did above, but if you are a beginner in assembly, using a debugger is usually a lot easier and a lot less error-prone.

Sparky

The following has fairly decent explanation of what is going on with the stack, stack frame, ebp and esp when calling a routine with parameters. I hope it is helpful. What is stack frame in assembly?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!