This blog was last modified 428 days before.
Stack Instructions
The word stack here is just the same as the conception you have learnt about before, so here I assume that you already have the basic knowledge about what is stack and how it works.
There are 2 instructions for stack operation: PUSH
and POP
. Also, they do the things as their name imply.
Things to put an eye on:
-
SS
store the address of the stack bottom.SP
. - Stack memory address is from high to low. Means when you use
PUSH
, theSP
decreased. - The basic unit in stack is 2 bytes (a word). So when you push or pop, the
SP
pointer will-2/+2
.
Based on test, inproper stack use like pop when empty may cause program perform unintendedly.
More About Stack
OS Initialize SS
and SP
. These two register would be initailized by OS before your program run, and OS has the the right to decide where the stack is in the memory and the total size of the memory that you can use.
Popped data still exist. When you use POP
to move the SP
, the old stack data remains there until you overwrite that memory address. Some crack trick used this behaviour.
Interesting Experiment
As I said before OS has the right to decide where the stack is. But, where?
At the first I was actually trying to do some wrong stack operation as experiment to see what would happen, and I found the RET
instruction doesn't work as intend. But why?
Notice: I need to say I only try this on
emu8086
simulator and the behaviour may different on the real CPU.
What does RET
do actually? On emu8086
, it would actually pop the data from the stack, and update IP
with that popped value. But again, why?
Bacause this is how it works. When our program start, it could be considered as the OS "call" our program. OS would push the address of the next instruction to the stack first. So normally, when our program finished and return the control to OS (or the one who call this program), they could find where to go next just through pop the stack. (It's similar to the function calling machanism, and you probably here something called Call Stack) If you can't understand it's ok, you will get a more deeper understand to this when learning about function call and CALL
, RET
instructions.
Now consider the ASM code below:
org 0000h
mov ax, 0
push ax
ret
Guess what will happen. It's a dead loop! This program will loop forever, IP
will go to the position where mov ax, 0
lies after RET
.
This is because when the RET
instruction was reached, OS pop the top of the stack which value is 0000h
, then move IP
to CS:[IP]
, and since we have org 0000h
, which set our program start with CS:[0000h]
, so afterall, the RET
will go to the place where our program start and our program loops for an eternity.
Now think about the question:
- What will happen if we change the code to
org 0010h
? Will the program still trapped into loop forever?
No comment