0

I am trying to understand how the following code could work in Assembly:

MOV DI, 0765h
MOV BX, 0B00h
MOV SI, 0505h
PUSH DI
PUSH BX
PUSH SI
MOV BP, SP
MOV CX, [BP+2]

After the first 3 instructions the stack will have 0765h on bottom and 0505h on top. If we move SP to BP then does that mean that the first value in the stack will be 0505h (as well as the top one) or does it mean that now the stack has only one element (the addresses themselves changed)?

If it's the first case, then I assume that while BP refers to the value inside the base of the pointer, [BP] would refer to the address itself? So would the last instruction move the value inside the SP into CX, since the stack has 3 elements? But then what would be the difference between BP and [BP], if [BP+2] would basically refer to the value inside the address BP+2? So then [BP+2] would mean first taking the address of BP, adding 2, then returning the value inside that address? Sort of like if BP was a variable in C++ and we'd do &(*BP+2)? What does [BP] mean then? Is [BP] even a valid instruction?

And if it's the second case and the stack ends up having only one element, how does the last instruction even make sense? In that case it would have undefined behavior I assume, so perhaps it's the first possibility that is correct (the previous paragraph).

Lastrevio2
  • 51
  • 6
  • see: https://stackoverflow.com/questions/10362511/basic-use-of-immediates-vs-square-brackets-in-yasm-nasm-x86-assembly – Erik Eidt Dec 21 '21 at 15:39
  • 4
    I think you're overthinking this. Moving (actually copying) `sp` to `bp` does not change the stack at all. You are just pointing `bp` at the top of the stack is all. After `mov bp, sp`, both `sp` and `bp` point to the top of the stack. So `[bp + 2]` references the second *word* on the stack, namely 0B00h. What this does for you is that `bp` (as long as you don't change it) will give you a known, fixed reference to those values you just pushed even if, later, you decide to push more values onto the stack (thus changing `sp`, but not `bp`). – lurker Dec 21 '21 at 15:48

0 Answers0