Access to stack frames in assembly language

I'm new to assembly and then I came across this article

he says this code

void MyFunction() { int a, b, c; a = 10; b = 5; c = 2; 

equivalent to this

 push ebp ; save the value of ebp mov ebp, esp ; ebp now points to the top of the stack sub esp, 12 ; space allocated on the stack for the local variables mov [ebp - 4], 10 ; location of variable a mov [ebp - 8], 5 ; location of b mov [ebp - 12], 2 ; location of c 

According to this video , in order to access the stack value above the base pointer, we must add. If it is below the pointer, we must subtract it. Based on this example above, they subtracted something from the base pointer to move the location of the necessary variables, which contradicts what is indicated in the video.

What did I miss? I know that sub esp, 12 allocates space for local variables, so I mean that EBP is lower than this distribution, so I think it should be [ebp + something] not minus.

So, when he did this sub esp, 12, this is what Stack looks like.

  ESP is here | 2 | Ebp + 12 | 5 | Ebp + 8 | 4 | Ebp + 4 | | Old EBP value 

Was this article wrong or did I misunderstand it?

+4
source share
2 answers

The reason for using ebp is that esp will change, for example. passing arguments to a subroutine. This way, your ebp will allow you to access the same variable using the same offset, regardless of where esp is pointing at this point.

When you push values ​​on the stack, its value decreases; increases when it appears.

The code subtracts 12 (4 * 3) to make room for 32-bit (4 bytes) integers. Ebp points to the bottom where esp was before. This way you access the variable using a negative offset, for example. EBP-4. Thus, your picture is wrong: ebp + Whatever indicates what your code should not work with.

  BEFORE lower address | |<-------------- esp (=ebp after mov ebp, esp) | | higher address AFTER mov ebp, esp; sub esp, 12 lower address |<-------------- esp | | |<-------------- ebp | | higher address AFTER mov [ebp-4], 10 ecc. lower address | 2 <-------------- esp | 5 | 10 |<-------------- ebp | | higher address 

At this point, [esp] will be extracted [ebp-12], that is 2.

+6
source

stack-pointer (base-pointer) -address "grows" down to a lower address in the address space.
Your stack starts with, for example, 0x70000000 , and when you push something on it, esp (ebp) will be dropped using dword β†’ 0x6ffffffc (if I'm right).

See here , here , and.

+2
source

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


All Articles