Table of Contents

Question

In the example function, addme, what would happen if the stack pointer were not properly restored before executing RET?

Answer

Here is the addme function for reference:

push ebp
mov ebp, esp
movsx eax, word ptr [ebp + 8h]
movsx ecx, word ptr [ebp + 0Ch]
add eax, ecx
mov esp, ebp
pop ebp
ret

In this particular case, ESP remains unmodified(equal to EBP) so mov esp, ebp can be safely omitted from the function epilogue.

However, we should remember that we pushed EBP onto the stack in the function prologue and now the top of the stack no longer contains the retaddr so if we removed the pop ebp instruction, the stack would become unbalanced and the subsequent ret instruction would transfer control back to saved EBP register value(which is probably not the valid retaddr) causing undefined behaviour or program crash.

balanced-stack-meme