8086 Assembler Tutorial For Beginners (Part 9)
8086 Assembler Tutorial For Beginners (Part 9)
The Stack
Stack is an area of memory for keeping temporary data. Stack is used by CALL instruction to keep return address for
procedure, RET instruction gets this value from the stack and returns to that offset. Quite the same thing happens when INT
instruction calls an interrupt, it stores in stack flag register, code segment and offset. IRET instruction is used to return from
interrupt call.
PUSH REG
PUSH SREG
PUSH memory
PUSH immediate
POP REG
POP SREG
POP memory
Notes:
It is very important to do equal number of PUSHs and POPs, otherwise the stack maybe corrupted and it will be impossible
to return to operating system. As you already know we use RET instruction to return to operating system, so when program
starts there is a return address in stack (generally it's 0000h).
PUSH and POP instruction are especially useful because we don't have too much registers to operate with, so here is a trick:
Restore the original value of the register from stack (using POP).
Here is an example:
The exchange happens because stack uses LIFO (Last In First Out) algorithm, so when we push 1212h and then 3434h, on
pop we will first get 3434h and only after it 1212h.
The stack memory area is set by SS (Stack Segment) register, and SP (Stack Pointer) register. Generally operating system
sets values of these registers on program start.
Add 2 to SP register.
The current address pointed by SS:SP is called the top of the stack.
For COM files stack segment is generally the code segment, and stack pointer is set to value of 0FFFEh. At the address
SS:0FFFEh stored a return address for RET instruction that is executed in the end of the program.
You can visually see the stack operation by clicking on [Stack] button on emulator window. The top of the stack is marked
with "<" sign.