How push and pop in assembly work

I got confused about what pop really does in the assembly. Does pop PUSH value of PUSH ed onto the stack of the last one (this means that it does not apply if we have a MOV value after the last PUSH ed element) or just push any value that has a value onto the stack (thus applying both to MOV and to PUSH ), or does it pop up, which is always indicated by the stack pointer? Consider the following code:

 push $4 mov $5, -4(%esp) add $4, %esp (esp pointing to an unknown value) pop %ebp 

So, in this code, the value entered in ebp should be 4, 5 or an unknown value pointed to by esp ?

+6
source share
2 answers

Last

 POP EBP 

equivalently

 MOV EBP, [ESP] ADD ESP, 4 ; but without modifying flags, like LEA ESP, [ESP+4] 

(in Intel syntax - target on the left, source on the right)

+15
source

PUSH does:

  ESP := ESP-4 ; for x86; -8 for x64 MEMORY[ESP]:=<operandvalue> 

POP does:

  <operandtarget>:=MEMORY[ESP]; ESP:=ESP+4 ; for x86; +8 for x64 

It is much easier to understand what machine instructions are if you write their descriptions in pseudo-code like this. Intel reference manuals are full of such pseudo code, and it is worth your time and trouble to get them and read the details for yourself.

Regarding your specific question: your store of $ 5 at -4 (% esp) is a valid machine instruction, and the processor will execute it without complaint, but it is really extremely dangerous programming. If the processor takes a trap or interrupts immediately after this command, the state of the processor (usually) is saved "over the stack" and overwrites your value. Since interrupts occur asynchronously, the behavior you will see is that, rarely, $ 5 is lost. This makes a very complex debugging program.

"Add $ 4" puts the ESP back in place before the push command. Thus, you cannot say anything about the value that appeared in ebp, except that it is "unknown", as you suggested as one of your options.

+13
source

Source: https://habr.com/ru/post/1203336/


All Articles