stacks
home

Stack Intro
A stack is a LIFO data structure Can only add and remove from ONE end (TOP) PUSH POP Managed by the CPU, using SP (stack pointer) note: esp is 32 bit pointer

emu Stack

Emu stack documentation


*** We only use 16 bit pops and pushes with emu8086 *** PUSH syntax: PUSH r/m16 POP syntax: POP r/m16 !! NOTE: can only push 16 bit values
Save & Restore in OPPOSITE Order ==================================== Save and restore registers when they contain important values. Note that the PUSH and POP instructions are in the opposite order: push si ; push registers push cx push bx ..... code pop bx ; opposite order pop cx pop si
Nested Loop =========== Remember the nested loop we created ? It's easy to push the outer loop counter before entering the inner loop: mov cx, 100 ; set outer loop count L1: ; begin the outer loop push cx ; save outer loop count mov cx,20 ; set inner loop count L2: ; begin the inner loop ; ; loop L2 ; repeat the inner loop pop cx ; restore outer loop count loop L1 ; repeat the outer loop
Related Instructions: ==================== PUSHF and POPF push and pop the FLAGS register PUSHA pushes the 16-bit general-purpose registers on the stack order: AX, CX, DX, BX, SP, BP, SI, DI POPA pops the same registers off the stack in reverse order (PUSHAD and POPAD do the same for 32-bit registers)

Code
; this sample shows how the stack works. ; click 'stack' button in emulator to see the contents of the stack. ; stack is important element in computer architecture. ; this code does nothing useful, except printing "Hi" in the end. name "stack" org 100h ; create tiny com file. mov ax, 1234h push ax mov dx, 5678h push dx pop bx pop cx ; function call pushes ip value of the next instruction: call tfunc mov ax, 7890h push ax pop bx ; interrupts are like funtions, ; but in addition they push code segment into the stack mov ax, 3 int 10h ; set standard video mode. ; a typical use of stack is to set segment registers. ; set ds to video memory segment: CAN'T SET DS DIRECTLY mov ax, 0b800h push ax pop ds ; print "hi", use colors mov [170h], 'H' mov [172h], 'i' mov [171h], 11001110b ; color attribute for 'h' mov [173h], 10011110b ; color attribute for 'i' ; wait for any key press.... mov ah, 0 int 16h ; here we "pop" the ip value, and return control to the OS ret ; THE TEST PROCEDURE: TFUNC PROC xor bx, bx xor cx, cx ; here we "pop" the ip value,and return control to the main program: ret TFUNC ENDP END