Microprocessors · Lecture Notes
Chapter 8.1: The Stack
While a program runs, many values have to be set aside for a short time: the old value of a register, the return address of a procedure, the flags of an interrupted program, to name the first. For these jobs the 8086 uses a region of memory as the stack. The value put on the stack last is the first to be taken back. This note begins with the stack concept and the last-in, first-out discipline. It then explains how the stack is addressed through the SS and SP registers, why it grows downward, and which bus cycles the 8086 uses to reach it. Next it takes up, one by one, the effect of PUSH, POP, PUSHF, and POPF on registers, flags, and memory. Every example in the slides is traced step by step together with the registers and the stack: saving a value, swapping, rotating three registers, and reversing an array with the stack. The last section covers errors such as unbalanced PUSH and POP, stack overflow, and underflow, and the ways to guard against them.
Learning outcomes
- Explain the stack model
- Explain the last-in, first-out (LIFO) discipline of the stack, how the 8086 stack is addressed with SS:SP, and why it grows downward; compute the physical address of the top of the stack.
- Trace PUSH and POP
- Know the valid operand types for PUSH and POP, and show step by step, at byte level, how SP and stack memory change with each instruction.
- Save and swap registers
- Use the stack in the right order to preserve and restore a register's value, swap two registers, and reverse an array.
- Preserve the flags
- Save the flags register on the stack with PUSHF and POPF, restore flags that an operation has destroyed, and interpret the flags word bit by bit.
- Recognize stack errors
- Recognize the symptoms of unbalanced PUSH and POP, wrong ordering, stack overflow, and underflow, and apply the coding rules that prevent them.
- Trace the stack in emu8086
- Interpret the register panel, the stack window, and the memory view while single-stepping a program.
8.1.1The stack concept
8.1.1.1What is a stack?
The 8086 has eight general-purpose registers. A program often uses all of them, and at some point space runs short. For example, AX may hold a sum while AX is also needed for something else. One solution is to write the sum to a variable and read it back later. But defining a separate variable for every intermediate value clutters the program. Besides, it is not always known in advance how many values will have to be saved. One procedure can call another, and that one yet another. The return address of every call has to be kept somewhere, and the depth of calls depends on the flow of the program.
These needs share one property: the value saved last is the first one asked back. The innermost procedure finishes first, and its return address is the address saved last. When a register is borrowed temporarily, too, the value saved last is the first one restored. The 8086 supports a memory region that follows this discipline at the hardware level.
A stack is an area of memory set aside for temporary data and used in last-in, first-out order. On the 8086 the location of the stack is determined by the registers SS (stack segment) and SP (stack pointer). Putting a value on the stack is called a push; taking a value from the stack is called a pop.
The programmer reaches the stack with two instructions. PUSH puts a 16-bit value on the stack. POP takes a 16-bit value off the stack and writes it to a destination. The stack is an area used not only by the programmer but by the processor as well. When the CALL instruction calls a procedure, it puts the return address on the stack. The RET at the end of the procedure takes this address off the stack and returns there. When INT calls an interrupt, similar work is done. The flags register, the code segment (CS), and the instruction pointer (IP) are saved on the stack; with IRET the interrupt is returned from and the three values are restored. The interrupt routines of the operating system and the BIOS use the same stack to preserve registers.
Having so many users of the stack also brings a responsibility. Every value the programmer puts on the stack sits in the same area as the processor's return addresses. If the programmer leaves a value on the stack or takes one extra, the processor's return address shifts and the program returns to a wrong address. Stack safety is therefore treated in a section of its own.
On the 8086 the unit of the stack is the word. Always 2 bytes are written to the stack and always 2 bytes are read from it. An 8-bit operand such as in PUSH AL is therefore invalid. If a byte has to be saved, the 16-bit register that contains it is pushed; PUSH AX puts both AL and AH on the stack. The stack also has a direction. It grows from high addresses toward low ones, that is, downward. These two rules determine every detail of the PUSH and POP instructions.
| User | Instruction | Put on the stack | Taken back by |
|---|---|---|---|
| programmer | PUSH, PUSHF | register, segment register, memory word, flags | POP, POPF |
| processor (procedure) | CALL | return address (IP for a near call, CS and IP for a far call) | RET, RETF |
| processor (interrupt) | INT n, hardware interrupt | FLAGS, CS, and IP | IRET |
| operating system, BIOS | interrupt routines | the registers the routine uses | the POPs at the end of the routine |
Table 8.1.1 summarizes the four users of the stack. The subject of this note is the first row: the programmer's use of the stack with PUSH, POP, PUSHF, and POPF. The effect of CALL and RET on the stack is mentioned only briefly, from the stack's point of view. The definition of procedures, parameter passing, and the stack frame are the subject of the Procedures note.
8.1.1.2Last in, first out (LIFO)
The word stack describes this discipline well in its everyday meaning, too. Think of plates piled on a table. A new plate is always put on top. When a plate is to be taken, the top one is taken. To reach a plate in the middle, all those above it have to be lifted off first. The plate put down last is taken first, and the plate put down first is taken last.
LIFO (last in, first out) is the discipline “the last one in is the first one out”. The last element added to a structure is the first element removed from it. The stack works in LIFO order; only the topmost element is accessible. The topmost element is called the top of the stack.
The opposite of LIFO is FIFO (first in, first out): the first one in is the first one out. A queue at a bank or a keyboard buffer works in FIFO order. The difference between the two disciplines is easiest to see with a sequence of numbers. Let 1, 2, 3, 4, and 5 be put on the stack in that order. The first value taken is 5. Then 4, 3, and 2 are taken, and 1 last. Had the same values been put in a FIFO queue, they would come out in the order 1, 2, 3, 4, 5.
Figure 8.1.1 shows this process at three moments. The stack in the figure is a conceptual drawing; there are no memory addresses yet. What matters is that each POP takes the value that is on top at that moment. The third POP takes 3, because 5 and 4 have been taken earlier and 2 and 1 remain on the stack.
The LIFO discipline has two consequences in programming. The first is that the stack gives values back in reverse order. This property can be used deliberately: pushing an array onto the stack in order and then popping it reverses the array. The second is that if several registers are saved and later restored to their old places, the POP order must be the reverse of the PUSH order. If AX, BX, and CX were pushed in this order, the restore order is CX, BX, AX. This rule is called mirror order. Written one below the other, the PUSHes and POPs stand like an image in a mirror.
Pushing registers in the order PUSH AX, PUSH BX and restoring them in the order POP AX, POP BX. This sequence does not preserve the registers; it swaps their values: since BX was pushed last, the first POP writes it into AX. The error is not noticed at assembly time, because all four instructions are valid. The program just produces a wrong result.
8.1.1.3The stack segment: SS and SP
The memory of the 8086 is divided into segments. In every memory access a 16-bit segment value and a 16-bit offset are combined. For code, CS and IP are used; for data, most often DS and an addressing expression. There is a dedicated register pair for the stack as well.
SS (stack segment) is the segment register that holds the start of the 64 KB segment in which the stack lives. SP (stack pointer) is the 16-bit register that holds the offset, within that segment, of the word on top of the stack. SS:SP always points at the top of the stack, that is, at the word put there last. The physical address of the top of the stack is SS × 10h + SP.
The physical address computation is the same as for code and data accesses. The segment value is multiplied by 16; in hexadecimal this means appending a 0 to the right of the number. Then the offset is added and the 20-bit address is found.
When emu8086 loads a .COM program, it sets all the segment registers to 0700h and SP to FFFEh. The physical address of the top of the stack is found as follows:
- Stack segment: SS = 0700h.
- The segment value is multiplied by 16: 0700h × 10h = 07000h.
- The offset is added: 07000h + FFFEh = 16FFEh.
The top of the stack is at physical address 16FFEh. The addition produces a carry: 7000h + FFFEh = 16FFEh, so the result exceeds 16 bits. Because the address bus is 20 bits wide, this overflow is not lost; it appears as bit 16 of the 20-bit address.
The initial values of SS and SP are usually determined not by the programmer but by the operating system that loads the program into memory (Figure 8.1.2). In a .COM program, code, data, and stack share a single 64 KB segment. The loader makes SS the same as CS and sets SP to the end of the segment, FFFEh. In an .EXE program, on the other hand, the stack is a separate segment. The location of the segment and the initial value of SP are written in the header of the .EXE file; the loader puts these values into SS and SP. In the source code, a directive such as .STACK 100h reserves a 256-byte stack segment. In emu8086, an .EXE program written with .stack 100h, .data, and .code in that order starts with SS = 0710h and SP = 0100h. The top of the stack is then at physical address 07100h + 0100h = 07200h; the first PUSH writes to 071FEh.
The stack is not reached through SP alone. BP (the base pointer) also uses the SS segment by default. An instruction such as MOV AX, [BP+4] reads address SS:BP+4 even though no segment prefix is written. BP is therefore the right register for reaching data inside the stack, for example parameters passed to a procedure on the stack. SP, on the other hand, cannot be used in an addressing expression on the 8086: MOV AX, [SP] is invalid. To read the value on top of the stack without removing it, SP is first copied into BX or BP.
It is also possible for a program to move the stack itself. For this, new values are loaded into SS and SP. If an interrupt arrives between these two loads, the processor writes FLAGS, CS, and IP to an address that is half old and half new. The 8086 contains a safeguard against this danger. After an instruction that writes to a segment register with MOV or POP, no interrupt is accepted until the next instruction finishes. That is why, when changing the stack, SS is loaded first and SP immediately after:
MOV AX, 2000h
MOV SS, AX ; interrupts held off one instruction
MOV SP, 0100h ; SS:SP = 2000:0100, consistentIf the order of the two lines is swapped, the protection does not work. The deferral covers only the instruction following the one that writes to the segment register.
8.1.1.4The stack grows downward
In a .COM program there are three regions inside the single 64 KB segment. The first 256 bytes of the segment (0000h–00FFh) are the program segment prefix (PSP). DOS fills this area when it loads the program; the command line and return information are here. The program starts at address 0100h, as the ORG 100h directive demands; code and data are laid out upward. The stack starts at the very top of the segment, at FFFEh, and grows downward.
The logic of this layout is clear in Figure 8.1.3. The program and the stack grow toward each other from the two ends of the segment. How much room the program takes is known at assembly time. How deep the stack will get is determined at run time, by the number of calls and PUSHes. Placing the two regions at opposite ends lets whichever needs it use all of the free space in between. Had the stack grown upward, a fixed size would have had to be reserved after the end of the program, and that size would have been either too much or too little.
The downward growth of the stack shows up in the instructions in a simple way. Each PUSH decreases SP by 2. Each POP increases SP by 2. As the value of SP gets smaller, the stack gets deeper. The number of words on the stack can also be computed from SP. For example, if SP = FFFEh at the start and SP = FFF8h now, (FFFEh − FFF8h) / 2 = 3 words have been pushed onto the stack.
How deep the stack can get in a .COM program can also be computed. The example program that reverses an array with the stack is 26 bytes and occupies addresses 0100h–0119h. The first free byte after the program is 011Ah. The stack starts at FFFEh; after n PUSHes SP = FFFEh − 2n. For the stack not to overwrite the program, SP ≥ 011Ah must hold. From this, n ≤ (FFFEh − 011Ah) / 2 = (65,534 − 282) / 2 = 32,626. In this program up to 32,626 words can be put on the stack. In practice this limit is hardly approached, but an infinite loop or infinite recursion exceeds it in no time.
Understanding “top of the stack” as “the highest address”. The top of the stack is the place where the word put last is found and where SP points. Because the stack grows downward, this place is the lowest address among the items on the stack. If small addresses are drawn at the top in figures, the word “top” is also visually right; the stack figures in this note use this layout.
8.1.1.5Stack access in hardware
PUSH and POP are a single instruction from the software point of view. In hardware, two units of the 8086 work together. The execution unit (EU) decodes the instruction and decreases or increases SP by 2 in its own arithmetic-logic unit. The bus interface unit (BIU) computes the physical address and accesses memory. The address adder in the BIU shifts SS left by 4 bits and adds SP. The resulting 20-bit address is put out on the address/data lines in a memory write (PUSH) or read (POP) bus cycle.
The data bus of the 8086 is 16 bits wide. If a word sits at an even address, it is transferred in a single bus cycle, that is, in four clock cycles (T1–T4). In this cycle A0 = 0 and BHE = 0; the low byte passes on lines D0–D7 and the high byte on D8–D15. As long as SP is even, every PUSH is a single write cycle and every POP a single read cycle. If SP falls to an odd value, the word is transferred in two separate cycles and each access takes four clock cycles longer. Loaders therefore always start SP with an even value, and programs never change SP by an odd amount.
There is one more detail that tells outside circuits about stack access. In the T2–T4 interval of each bus cycle, the 8086 puts status bits on lines A16/S3–A19/S6. The bits S4 and S3 tell which segment register is used in that cycle. If S4 = 0 and S3 = 1, that cycle is an access to the SS segment, that is, to the stack. A designer can decode these bits to route stack accesses to a separate memory bank and thus use a memory area larger than 1 MB. In ordinary PCs these bits are not used, but on a logic analyzer they are useful for seeing when a program accesses the stack.
| S4 | S3 | Segment used | Example access |
|---|---|---|---|
| 0 | 0 | ES (extra segment) | destination of string instructions, access with an ES prefix |
| 0 | 1 | SS (stack segment) | PUSH, POP, CALL, RET, BP-based access |
| 1 | 0 | CS or no segment | instruction fetch, I/O and interrupt acknowledge cycles |
| 1 | 1 | DS (data segment) | ordinary variable access |
On the 8088 the situation is different. The external data bus of the 8088 is 8 bits wide; every word is transferred in two separate byte cycles. So on the 8088 every PUSH and POP takes two memory cycles even when SP is even. From the programming point of view the two processors are the same; only the timings differ. All the examples in this note are for the 8086.
8.1.2PUSH and POP
8.1.2.1The PUSH instruction
The PUSH source instruction puts a copy of the 16-bit source on top of the stack. The source does not change; a copy of it appears on the stack. The source can be of four kinds: a general-purpose or pointer register, a segment register, a word in memory, and, from the 80186 on, an immediate value. Table 8.1.3 gives these kinds with examples.
| Form | Valid operands | Example |
|---|---|---|
| PUSH register | AX, BX, CX, DX, SI, DI, BP, SP | PUSH AX |
| PUSH segment register | CS, DS, SS, ES | PUSH DS |
| PUSH memory | [BX], [BX+SI+7], 16-bit variable | PUSH [BX], PUSH num |
| PUSH immediate | 5, −24, 3Fh, 10001101b | PUSH 3Fh (not on the 8086) |
The last row of the table carries a warning. PUSH with an immediate value is not in the instruction set of the 8086 and 8088; it arrived with the 80186. emu8086 accepts and runs this instruction. But in a program written for a real 8086, a constant is first loaded into a register, and then the register is pushed:
MOV AX, 5
PUSH AX ; instead of PUSH 5 on the 8086For PUSH with a memory operand, the size of the operand must be a word. For a variable defined as num DW 0BEEFh, PUSH num is valid; the two bytes of the variable are copied to the stack. A byte variable defined with DB, however, cannot be pushed. The same rule applies to registers: PUSH AL and PUSH byte_var give an assembly error. The flags register cannot be written as an ordinary operand; it has a separate instruction, PUSHF.
Pushing SP itself carries an interesting detail. The PUSH SP instruction both decrements SP and writes it to the stack, and which happens first changes the result. The 8086 first decrements SP and then writes the decremented value. With SP = FFFEh, PUSH SP puts FFFCh on the stack. The 80286 and later processors write the value from before the decrement, FFFEh. This difference was used in old programs to tell whether the processor was an 8086 or an 80286. In a portable program PUSH SP is not relied on; if the value of SP is needed, it is first copied into another register.
Taking PUSH 5 for an 8086 instruction because it worked in emu8086. emu8086 accepts some 80186 instructions and only gives a warning. When the same code runs on a real 8086 or 8088, the processor interprets these bytes as some other instruction and the program behaves unexpectedly.
8.1.2.2The POP instruction
The POP destination instruction reads the word on top of the stack, writes it to the destination, and moves the top of the stack up by one word. The destination types resemble the source types of PUSH, but with two omissions (Table 8.1.4).
| Form | Valid operands | Example |
|---|---|---|
| POP register | AX, BX, CX, DX, SI, DI, BP, SP | POP BX |
| POP segment register | DS, SS, ES (not CS) | POP DS |
| POP memory | [BX], [BX+SI+7], 16-bit variable | POP result |
Why is there no POP CS? CS determines the segment from which instructions are fetched. Had POP CS changed CS and left IP as it was, the next instruction would be fetched from the same offset in a completely different segment. The program flow would jump to a random place. That is why CS changes only together with IP: far JMP and CALL, RETF, INT, and IRET load CS and IP in the same instruction. Assemblers do not accept POP CS. On the first 8086s the code of this instruction (0Fh) worked in an undocumented way; Intel used this code on the 80286 as the prefix of new two-byte instructions.
Why is there no POP constant? POP 5 is meaningless. POP takes a value from the stack, and a place is needed to write that value to. A constant is not a place a value can be written to. If the value on top of the stack is not needed and is only to be discarded, there are two ways. The value is taken into a register that is not in use, or 2 is added directly to SP (ADD SP, 2). The second way changes the flags; the first does not.
Flags. PUSH and POP do not touch the flags. Even if 0000h arrives in AX with POP AX, ZF does not change; what changes ZF is an arithmetic or logic operation, not a data transfer. The only exception to this rule is POPF. POPF loads the word it takes from the stack into the whole flags register.
Copying between segment registers. On the 8086 there is no direct MOV from one segment register to another; MOV DS, CS is invalid. This copy is done in two ways. Either the value is passed through a general-purpose register (MOV AX, CS and MOV DS, AX), or the stack is used:
PUSH CS ; value of CS onto the stack
POP DS ; DS ← CS
PUSH DS ; value of DS onto the stack
POP ES ; ES ← DSThe advantage of copying through the stack is that it disturbs no general-purpose register. If the value of AX is to be preserved, the first way requires saving AX separately; the second does not. The idiom PUSH CS with POP DS is common in programs whose data sits in the code segment and at the start of interrupt routines. In emu8086, if DS is set to 1234h and these four instructions are run, ES = 1234h and DS = 0700h; SP returns to FFFEh.
8.1.2.3How PUSH and POP work
Both instructions consist of two steps. The order of the steps determines what SP points at at each moment.
PUSH source: (1) SP ← SP − 2; (2) [SS:SP] ← source. POP destination: (1) destination ← [SS:SP]; (2) SP ← SP + 2. PUSH first decrements and then writes; POP first reads and then increments. SP therefore always points at the topmost occupied cell.
This ordering is called the “full stack” convention. The cell SP points at always holds a valid value. Some processors use the opposite convention: SP points at the next free cell, and PUSH first writes and then decrements. Whichever convention is chosen, PUSH and POP must be exact opposites. On the 8086, PUSH is “decrement, write” and POP is “read, increment”.
Figure 8.1.4 shows the two instructions at four moments. At the start SP = FFFEh and AX = 1234h. At address FFFEh sits the word 0000h that DOS put for the .COM program; the job of this word is explained at the end of the program.
- PUSH AX, step 1. SP ← FFFEh − 2 = FFFCh. The top of the stack moves down by one word. The cell at FFFCh holds, for now, an old, meaningless value.
- PUSH AX, step 2. [SS:FFFCh] ← 1234h. A copy of AX is written into the new top cell. AX does not change.
- POP BX, step 1. BX ← [SS:FFFCh] = 1234h. The value is read from the top of the stack.
- POP BX, step 2. SP ← FFFCh + 2 = FFFEh. The top of the stack moves up by one word.
The last step has an important consequence. POP does not erase the value it reads from memory. The 1234h at FFFCh stays there; it is just now above SP, that is, outside the stack. In the figure this cell is drawn faded. The next PUSH overwrites the same cell. For this reason, trying to reach a value that has been taken off the stack by reading memory again is not reliable. If an interrupt arrives in between, the processor writes FLAGS, CS, and IP to exactly those cells, and the old value is lost.
Thinking that after a POP the value is erased from memory and 0 is written in its place. POP only reads and increments SP. In the memory window of emu8086 the old values remain visible. These values are not “on the stack”; the stack is only the region from SP up to FFFEh.
8.1.2.4Byte order on the stack
The stack works with words, while memory is addressed in bytes. When a word is written to memory, its two bytes get two separate addresses. For this the 8086 uses the little-endian convention: the low byte of the word is written to the lower address and the high byte to the next address. The rule is the same for the stack.
When PUSH AX runs with AX = 1234h, SP = FFFCh. The low byte of the word, 34h (AL), is written to address FFFCh, and the high byte, 12h (AH), to address FFFDh (Figure 8.1.5). SP always points at the low byte of the word, that is, at the smaller address. The stack window of emu8086 shows words and writes 1234h on this line. The memory window, however, shows bytes in order: first 34, then 12. The two windows present the same data in different ways. That the value looks “reversed” in the memory window is not an error but a natural result of the little-endian convention.
This convention can also be tested with a program. To read the bytes on top of the stack, SP is copied into a base register, because the 8086 has no [SP] addressing expression:
ORG 100h
MOV AX, 1234h
PUSH AX
MOV BX, SP ; BX = FFFCh
MOV CL, [BX] ; CL = 34h, low byte
MOV CH, [BX+1] ; CH = 12h, high byte
POP DX ; DX = 1234hThe program runs as follows. PUSH AX makes SP FFFCh and writes the bytes 34h and 12h to FFFCh and FFFDh. MOV BX, SP makes BX FFFCh. [BX] uses the DS segment by default. In a .COM program DS = SS, so DS:FFFCh is the same physical address as the top of the stack: 07000h + FFFCh = 16FFCh. MOV CL, [BX] reads 34h from there, and MOV CH, [BX+1] reads 12h from 16FFDh. CX = 1234h. Finally POP DX reads the two bytes again as a word: DX = 1234h. In an .EXE program DS and SS may differ. Then [BX] reads the data segment, not the stack; in that case one must write SS:[BX] or use BP instead of BX.
SP staying even is related to this byte-level structure too. As long as SP is even, every stack word starts at an even address and the 8086 moves it in a single bus cycle. If SP were odd, the low byte of the word would fall on an odd address and the high byte on an even one, and two separate cycles would be needed. The program would still run correctly, just more slowly.
8.1.2.5What changes and what does not?
All instructions that use the stack change SP. Whether they write to memory, whether they change a destination, and their effect on the flags differ, however. Table 8.1.5 gives these effects side by side.
| Instruction | SP | Memory | Destination | Flags |
|---|---|---|---|---|
PUSH src | −2 | [SS:SP] ← source | — | unchanged |
POP dest | +2 | read, not erased | destination ← [SS:SP] | unchanged |
PUSHF | −2 | [SS:SP] ← FLAGS | — | unchanged |
POPF | +2 | read | FLAGS ← [SS:SP] | all loaded |
CALL (near) | −2 | [SS:SP] ← return IP | IP ← target | unchanged |
RET (near) | +2 | read | IP ← [SS:SP] | unchanged |
INT n | −6 | FLAGS, CS, IP | CS:IP ← vector | IF = TF = 0 |
IRET | +6 | read | IP, CS, FLAGS | all loaded |
The most important column of the table is the last one. PUSH, POP, and PUSHF do not touch the flags. This means the result of a comparison, that is, the flags, can be carried safely across PUSH and POP. In the code below, CMP sets ZF to 1. Then AX is put on the stack, changed, and taken back. Since these three instructions do not touch ZF, JE is still taken:
MOV AX, 5
CMP AX, 5 ; ZF = 1
PUSH AX
MOV AX, 7 ; MOV does not change flags
POP AX ; AX = 5, ZF still 1
JE equal ; takenHad an instruction that changes the flags come in between, an ADD for instance, the result of the comparison would have been lost. In that case PUSHF and POPF are used to save the flags. The stack effect of CALL and RET is very similar to that of PUSH and POP: CALL pushes the return address and RET pops it. The difference is that the destination is IP, not a register. INT pushes three words, that is, 6 bytes, and is the only push instruction among these that changes the flags: on entering the interrupt routine, IF and TF are cleared.
8.1.2.6Machine codes and clock cycles
The stack instructions are among the shortest on the 8086. Pushing or popping a register takes a single byte. Five bits of the opcode determine the instruction and the remaining three the register. The code is 50h + r for PUSH and 58h + r for POP. The register numbers follow the general order of the 8086: AX = 0, CX = 1, DX = 2, BX = 3, SP = 4, BP = 5, SI = 6, DI = 7. So PUSH AX = 50h, PUSH BX = 53h, POP BX = 5Bh, and POP DI = 5Fh.
Segment registers are single bytes too. The push code is 06h + 8 × s and the pop code is 07h + 8 × s, where s is the number ES = 0, CS = 1, SS = 2, DS = 3. PUSH ES = 06h, PUSH CS = 0Eh, PUSH SS = 16h, PUSH DS = 1Eh; POP ES = 07h, POP SS = 17h, POP DS = 1Fh. In this scheme the code of POP CS would have been 0Fh; this code fell out of use along with POP CS. The forms with a memory operand use a ModR/M byte: PUSH memory = FFh /6, POP memory = 8Fh /0. For example, for a variable at address 0109h, PUSH num = FF 36 09 01, four bytes. PUSHF = 9Ch and POPF = 9Dh.
| Instruction | Code | Bytes | Clock cycles |
|---|---|---|---|
PUSH register | 50h + r | 1 | 11 |
PUSH seg | 06h + 8s | 1 | 10 |
PUSH memory | FFh /6 | 2–4 | 16 + EA |
POP register | 58h + r | 1 | 8 |
POP seg | 07h + 8s | 1 | 8 |
POP memory | 8Fh /0 | 2–4 | 17 + EA |
PUSHF | 9Ch | 1 | 10 |
POPF | 9Dh | 1 | 8 |
The timings in Table 8.1.6 are for the case where the words sit at even addresses. A PUSH takes 11 clock cycles; on a 5 MHz 8086 one clock cycle is 200 ns, so this is 2.2 µs. Four cycles of this time are the memory write cycle; the rest is decoding the instruction and decrementing SP. The forms with a memory operand have two memory accesses: one to the variable and one to the stack. The time is therefore longer, and the time of the effective address computation is added. On the 8088 four more cycles are added to each word access.
8.1.3Examples: code traces
All the programs in this section were run in emu8086 as .COM programs. At the start CS = DS = SS = ES = 0700h, IP = 0100h, and SP = FFFEh; unless stated otherwise the other registers are 0000h. In the trace tables each row gives the state after that instruction has executed. The values that change in that row are highlighted. The stack column shows only the occupied cells that SP points at and below; the 0000h at FFFEh is the word DOS put for the .COM program.
8.1.3.1First example: PUSH AX / POP BX
The first program copies a value from AX to BX through the stack. This could also have been done with MOV BX, AX; the aim is to see the working of the stack in its plainest form.
ORG 100h
MOV AX, 42 ; AX = 42
PUSH AX ; push AX
POP BX ; pop into BX
RET ; return to the OS
ENDThe program consists of four instructions and 6 bytes: MOV AX, 42 is 3 bytes (B8 2A 00, 0100h–0102h), PUSH AX is 1 byte (50, 0103h), POP BX is 1 byte (5B, 0104h), and RET is 1 byte (C3, 0105h).
In the line MOV AX, 42 the number has no h at the end. The assembler reads it as a decimal number: 42 = 2 × 16 + 10 = 2Ah. AX = 002Ah, not 0042h. This small detail is one of the points beginners stumble on most often in emu8086. PUSH AX makes SP FFFEh − 2 = FFFCh and writes [FFFCh] ← 002Ah; at byte level [FFFCh] = 2Ah and [FFFDh] = 00h. POP BX takes the 002Ah at FFFCh into BX and brings SP back to FFFEh. The value has been copied from AX to BX through the stack; AX keeps its value too.
| Instruction | IP (next) | AX | BX | SP | Stack (from the top) |
|---|---|---|---|---|---|
| start | 0100h | 0000h | 0000h | FFFEh | 0000h |
MOV AX, 42 | 0103h | 002Ah | 0000h | FFFEh | 0000h |
PUSH AX | 0104h | 002Ah | 0000h | FFFCh | 002Ah, 0000h |
POP BX | 0105h | 002Ah | 002Ah | FFFEh | 0000h |
RET | 0000h | 002Ah | 002Ah | 0000h | (empty) |
The last row shows the role of the stack at the end of the program (Table 8.1.7). RET takes the word on top of the stack as the return address. The stack holds only the 0000h put by DOS; IP = 0000h and SP = FFFEh + 2 = 0000h. SP wraps around in 16 bits. The processor goes to address 0700:0000, the start of the PSP. The first two bytes of the PSP are CD 20, which is the INT 20h instruction that terminates the program. The program thus ends properly. This mechanism works only if the stack is balanced: when RET is reached, DOS's 0000h must be on top of the stack.
8.1.3.2LIFO order: 1, 2, 3 go in, 3, 2, 1 come out
The second program shows the LIFO discipline with real registers. AX is loaded with 1, 2, and 3 in turn, and each value is pushed onto the stack. Then POP BX is done three times.
MOV AX, 1 ; AX = 1
PUSH AX ; push 1
MOV AX, 2 ; AX = 2
PUSH AX ; push 2
MOV AX, 3 ; AX = 3
PUSH AX ; push 3
POP BX ; BX ← 3
POP BX ; BX ← 2
POP BX ; BX ← 1| Instruction | AX | BX | SP | Stack (from the top, DOS word excluded) |
|---|---|---|---|---|
| start | 0000h | 0000h | FFFEh | (empty) |
MOV AX, 1 | 0001h | 0000h | FFFEh | (empty) |
PUSH AX | 0001h | 0000h | FFFCh | 0001h |
MOV AX, 2 | 0002h | 0000h | FFFCh | 0001h |
PUSH AX | 0002h | 0000h | FFFAh | 0002h, 0001h |
MOV AX, 3 | 0003h | 0000h | FFFAh | 0002h, 0001h |
PUSH AX | 0003h | 0000h | FFF8h | 0003h, 0002h, 0001h |
POP BX | 0003h | 0003h | FFFAh | 0002h, 0001h |
POP BX | 0003h | 0002h | FFFCh | 0001h |
POP BX | 0003h | 0001h | FFFEh | (empty) |
Two points stand out in the trace (Table 8.1.8). First, when a new value is loaded into AX, the old value is not lost; the preceding PUSH has copied it onto the stack. When AX = 0002h, 0001h is safe on the stack. Second, the values arriving in BX are in the reverse of the order they went in: first 3, then 2, then 1. Since three PUSHes and three POPs were done, SP returns to where it started, FFFEh. At the end of the program AX = 0003h remains, because the last value loaded into AX is 3 and the POPs change only BX.
8.1.3.3Saving a register's value
The most common use of the stack is to borrow a register temporarily for another job and then return it to its old value. The program first loads AX with 1234h. Then it saves AX, writes another value into AX, and restores the saved value.
ORG 100h
MOV AX, 1234h
PUSH AX ; save AX
MOV AX, 5678h ; change AX
POP AX ; restore old value
RET
END| Instruction | AX | SP | [FFFCh] | Note |
|---|---|---|---|---|
MOV AX, 1234h | 1234h | FFFEh | — | value to be preserved |
PUSH AX | 1234h | FFFCh | 1234h | a copy of AX on the stack |
MOV AX, 5678h | 5678h | FFFCh | 1234h | AX is being used for another job |
POP AX | 1234h | FFFEh | 1234h | the old value is back; the cell was not erased |
RET | 1234h | 0000h | 1234h | IP ← 0000h, INT 20h in the PSP |
The program is 9 bytes: two three-byte MOVs and one-byte PUSH, POP, and RET. The fourth column of Table 8.1.9 shows once more that POP does not erase memory: [FFFCh] = 1234h after the POP too. This pattern is the same as procedures PUSHing the registers they use on entry and POPping them on exit. If a procedure is going to destroy AX, it writes PUSH AX on entry and POP AX on exit. The program that called the procedure does not notice that AX was changed. This method is called preserving registers.
AX holds the counter of a loop and BX the address of an array. In the middle of the loop a character is to be printed on the screen by loading AH = 02h and DL = the character and calling INT 21h. Function 02h of INT 21h also changes AL: when the function ends, AL is the character printed. Since both halves of AX will be disturbed, the printing is wrapped like this:
PUSH AX ; save the counter
PUSH DX ; DX will be disturbed too
MOV AH, 2
MOV DL, '*'
INT 21h ; AL = '*'
POP DX ; mirror order: DX first
POP AX ; the counter is backSince the PUSH order is AX, DX, the POP order is DX, AX. BX is not touched, so it is not saved. Each register saved costs two instructions and 19 clock cycles (11 + 8); only registers that are really disturbed are saved.
8.1.3.4Swapping two registers with the stack
The opposite of mirror order, that is, POPping in the same order, swaps the values. This is sometimes a mistake and sometimes a method used deliberately.
ORG 100h
MOV AX, 1212h ; AX ← 1212h
MOV BX, 3434h ; BX ← 3434h
PUSH AX ; push AX
PUSH BX ; push BX
POP AX ; AX ← old BX
POP BX ; BX ← old AX
RET
ENDWhen emu8086 loads this program, CX shows 000Bh. This value is the byte count of the program: the two MOVs are 3 bytes each, the four stack instructions and RET one byte each, 3 + 3 + 1 + 1 + 1 + 1 + 1 = 11 bytes in all. After loading, emu8086 writes the size of the .COM program into CX; the DOS DEBUG program likewise writes the length of the file it loaded into BX:CX. This is a custom, not a rule. A program must not trust the initial value of CX and must load CX itself before using it. In the other traces of this note the initial value of CX is taken as 0000h; since the swap program does not use CX, the result does not change.
| Instruction | AX | BX | SP | Stack (from the top) |
|---|---|---|---|---|
| start | 0000h | 0000h | FFFEh | 0000h |
MOV AX, 1212h | 1212h | 0000h | FFFEh | 0000h |
MOV BX, 3434h | 1212h | 3434h | FFFEh | 0000h |
PUSH AX | 1212h | 3434h | FFFCh | 1212h, 0000h |
PUSH BX | 1212h | 3434h | FFFAh | 3434h, 1212h, 0000h |
POP AX | 3434h | 3434h | FFFCh | 1212h, 0000h |
POP BX | 3434h | 1212h | FFFEh | 0000h |
RET | 3434h | 1212h | 0000h | (empty); IP = 0000h |
The secret of the swap is LIFO (Table 8.1.10). Since BX was pushed last, it is on top of the stack and the first POP AX takes it. Then POP BX takes the next value, AX's old value 1212h. For a moment AX and BX are both 3434h; during this time the stack holds 1212h safely. Had the POPs been done in mirror order, that is, POP BX first and then POP AX, the values would have stayed where they were.
8.1.3.5Three registers: POP in the same order
With three registers the same experiment gives a more interesting result. This program was loaded as a .BIN file in the slides. emu8086 starts a .BIN file with CS = SS = 0100h and IP = 0000h; SP is again FFFEh. Because the segment value is different, the physical addresses change, but the offsets and the SP values are the same as in the .COM program.
mov ax, 2
mov bx, 4
mov cx, 8
push ax
push bx
push cx
pop ax
pop bx
pop cx| Instruction | AX | BX | CX | SP | Stack (from the top) |
|---|---|---|---|---|---|
mov ax, 2 | 0002h | 0000h | 0000h | FFFEh | (empty) |
mov bx, 4 | 0002h | 0004h | 0000h | FFFEh | (empty) |
mov cx, 8 | 0002h | 0004h | 0008h | FFFEh | (empty) |
push ax | 0002h | 0004h | 0008h | FFFCh | 0002h |
push bx | 0002h | 0004h | 0008h | FFFAh | 0004h, 0002h |
push cx | 0002h | 0004h | 0008h | FFF8h | 0008h, 0004h, 0002h |
pop ax | 0008h | 0004h | 0008h | FFFAh | 0004h, 0002h |
pop bx | 0008h | 0004h | 0008h | FFFCh | 0002h |
pop cx | 0008h | 0004h | 0002h | FFFEh | (empty) |
In the end AX = 0008h, BX = 0004h, and CX = 0002h (Table 8.1.11). AX and CX have changed places and BX stayed where it was. The reason is that the middle value is in the middle both when pushing and when popping. In general, if n registers are pushed in one order and popped in the same order, the register sequence is reversed: the first register gets the value of the last, and the last gets the value of the first. With three registers, the middle one is the fixed point. At the line pop bx, 0004h is written to BX again; since the value does not change, it is not highlighted in the table, but the instruction was executed and SP increased.
8.1.3.6Reversing an array with the stack
The reversing property of LIFO can be applied to a string as well. The program pushes the characters of the string 'ABC' onto the stack in order, then pops them from the stack and prints them on the screen. CBA appears on the screen.
ORG 100h
MOV SI, OFFSET msg
MOV CX, 3
put: MOV AL, [SI]
PUSH AX ; save the char
INC SI
LOOP put
MOV CX, 3
prt: POP DX ; DL = char
MOV AH, 2
INT 21h ; print DL
LOOP prt
RET
msg DB 'ABC' ; 0117hFirst the layout of the program in memory is worked out, because the address of the variable msg comes after the code. Table 8.1.12 gives the address and machine code of every instruction. The code takes 23 bytes, from 0100h to 0116h. The following msg is at addresses 0117h–0119h; the bytes 41h, 42h, and 43h are the ASCII codes of the characters 'A', 'B', and 'C'. The program is 26 bytes in all.
| Line | Address | Code | Instruction |
|---|---|---|---|
| 2 | 0100h | BE 17 01 | MOV SI, OFFSET msg |
| 3 | 0103h | B9 03 00 | MOV CX, 3 |
| 4 | 0106h | 8A 04 | put: MOV AL, [SI] |
| 5 | 0108h | 50 | PUSH AX |
| 6 | 0109h | 46 | INC SI |
| 7 | 010Ah | E2 FA | LOOP put |
| 8 | 010Ch | B9 03 00 | MOV CX, 3 |
| 9 | 010Fh | 5A | prt: POP DX |
| 10 | 0110h | B4 02 | MOV AH, 2 |
| 11 | 0112h | CD 21 | INT 21h |
| 12 | 0114h | E2 F9 | LOOP prt |
| 13 | 0116h | C3 | RET |
| 14 | 0117h | 41 42 43 | msg DB 'ABC' |
The second byte of the LOOP instructions is the relative jump displacement. LOOP put is at 010Ah and is two bytes; the next instruction is at 010Ch. To return to 0106h the displacement must be 0106h − 010Ch = −6; the 8-bit two's complement of −6 is FAh. For LOOP prt the displacement is 010Fh − 0116h = −7 = F9h.
First loop: pushing the characters. SI holds the string and CX the loop counter. In each iteration MOV AL, [SI] reads a character into AL. Since a byte cannot be pushed onto the stack, PUSH AX pushes AL together with AH as a word. Because AH = 00h at the start of the program, 0041h, 0042h, and 0043h go onto the stack. INC SI points at the next character; LOOP put decrements CX by 1 and returns to the top if CX ≠ 0. After three iterations SI = 011Ah and SP = FFF8h. On top of the stack is the 'C' pushed last.
| Line | Instruction | AX | CX | SI | SP | Stack (from the top, DOS word excluded) |
|---|---|---|---|---|---|---|
| 2 | MOV SI, OFFSET msg | 0000h | 0000h | 0117h | FFFEh | (empty) |
| 3 | MOV CX, 3 | 0000h | 0003h | 0117h | FFFEh | (empty) |
| 4 | MOV AL, [SI] | 0041h | 0003h | 0117h | FFFEh | (empty) |
| 5 | PUSH AX | 0041h | 0003h | 0117h | FFFCh | 0041h |
| 6 | INC SI | 0041h | 0003h | 0118h | FFFCh | 0041h |
| 7 | LOOP put | 0041h | 0002h | 0118h | FFFCh | 0041h |
| 4 | MOV AL, [SI] | 0042h | 0002h | 0118h | FFFCh | 0041h |
| 5 | PUSH AX | 0042h | 0002h | 0118h | FFFAh | 0042h, 0041h |
| 6 | INC SI | 0042h | 0002h | 0119h | FFFAh | 0042h, 0041h |
| 7 | LOOP put | 0042h | 0001h | 0119h | FFFAh | 0042h, 0041h |
| 4 | MOV AL, [SI] | 0043h | 0001h | 0119h | FFFAh | 0042h, 0041h |
| 5 | PUSH AX | 0043h | 0001h | 0119h | FFF8h | 0043h, 0042h, 0041h |
| 6 | INC SI | 0043h | 0001h | 011Ah | FFF8h | 0043h, 0042h, 0041h |
| 7 | LOOP put | 0043h | 0000h | 011Ah | FFF8h | 0043h, 0042h, 0041h |
There is also a small detail about the flags in the first loop. INC SI updates the arithmetic flags other than CF. When SI = 0118h, the low byte 18h = 0001 1000b contains two 1 bits; PF = 1. At SI = 0119h and 011Ah the number of 1s in the low bytes is odd and PF = 0. These flags do not affect the result of the program, because LOOP does not look at the flags; it tests only CX.
Second loop: popping and printing. CX is set to 3 again. In each iteration POP DX takes the word on top of the stack into DX; DL is the character and DH is 00h. MOV AH, 2 selects the DOS character output function, and INT 21h prints the character in DL (Figure 8.1.6). Function 02h of INT 21h has a side effect: when the function ends, AL is the character printed. AX therefore changes after every INT 21h. In the first iteration AL is already 43h, so no difference shows; in the following iterations AL = 42h and AL = 41h. The first to come off the stack is 'C', then 'B', and 'A' last.
| Line | Instruction | AX | CX | DX | SP | Screen |
|---|---|---|---|---|---|---|
| 8 | MOV CX, 3 | 0043h | 0003h | 0000h | FFF8h | |
| 9 | POP DX | 0043h | 0003h | 0043h | FFFAh | |
| 10 | MOV AH, 2 | 0243h | 0003h | 0043h | FFFAh | |
| 11 | INT 21h | 0243h | 0003h | 0043h | FFFAh | C |
| 12 | LOOP prt | 0243h | 0002h | 0043h | FFFAh | C |
| 9 | POP DX | 0243h | 0002h | 0042h | FFFCh | C |
| 10 | MOV AH, 2 | 0243h | 0002h | 0042h | FFFCh | C |
| 11 | INT 21h | 0242h | 0002h | 0042h | FFFCh | CB |
| 12 | LOOP prt | 0242h | 0001h | 0042h | FFFCh | CB |
| 9 | POP DX | 0242h | 0001h | 0041h | FFFEh | CB |
| 10 | MOV AH, 2 | 0242h | 0001h | 0041h | FFFEh | CB |
| 11 | INT 21h | 0241h | 0001h | 0041h | FFFEh | CBA |
| 12 | LOOP prt | 0241h | 0000h | 0041h | FFFEh | CBA |
| 13 | RET | 0241h | 0000h | 0041h | 0000h | CBA |
In the last row of Table 8.1.14, SP = 0000h and IP = 0000h; RET has taken DOS's 0000h word. The program executes 28 instructions in all and ends with the INT 20h in the PSP. Because the two loops run the same number of iterations, three POPs correspond to three PUSHes and the stack is balanced. Had the loop counts been different, for example had the second loop mistakenly started with CX = 2, 'A' would have stayed on the stack and RET would have taken it for the return address: IP = 0041h. The program would jump into the middle of the PSP and not terminate properly.
The same method can also be used to reverse a string in place in memory without printing it. In the second loop the character is taken with POP AX and written back into the string from the start with MOV [SI], AL; for this, SI is first brought back to the start of the string. The stack acts here as an intermediate buffer. There is no need to define a separate buffer array, but each character takes 2 bytes on the stack.
Assuming AX does not change after an INT 21h call. Function AH = 02h makes AL equal to the printed character; function AH = 09h leaves 24h ('$') in AL. If a loop counter or an intermediate result is kept in AL, write PUSH AX before the call and POP AX after it.
8.1.3.7What happens to the registers?
The prediction question in the slides is a piece of code in which PUSHes and POPs are used in a mixed order. At the start SP = FFFEh.
MOV AX, 1111h
MOV BX, 2222h
MOV CX, 3333h
PUSH AX
PUSH BX
PUSH CX
POP AX
POP CX
PUSH AX
POP BX
POP BXThe solution is found by writing down the contents of the stack step by step. After the three PUSHes the stack, from top to bottom, is 3333h, 2222h, 1111h and SP = FFF8h. POP AX takes the top 3333h: AX = 3333h. POP CX takes the next 2222h: CX = 2222h, SP = FFFCh. Only 1111h is left on the stack. PUSH AX pushes 3333h again and POP BX takes it right away: BX = 3333h. The last POP BX takes the 1111h on the stack and overwrites BX's value from a moment ago: BX = 1111h.
The result is AX = 3333h, BX = 1111h, CX = 2222h, and SP = FFFEh. Since four PUSHes and four POPs were done, the stack is balanced. The values have gone one full turn among the registers: AX took CX's old value, CX took BX's, and BX took AX's. In questions like this the most reliable method is to draw the stack as a column on paper and mark the top cell at every instruction.
8.1.3.8Comparing swap methods
There are three ways to swap two registers. Swapping with the stack takes four instructions: PUSH AX, PUSH BX, POP AX, POP BX. Swapping with a temporary register takes three MOVs: MOV CX, AX, MOV AX, BX, MOV BX, CX. The third way is the 8086's swap instruction: XCHG AX, BX.
| Method | Bytes | Memory accesses | Clock cycles | Side effect and scope |
|---|---|---|---|---|
| with the stack | 4 | 4 | 2 × 11 + 2 × 8 = 38 | no register is disturbed; also works for segment registers |
| with a temporary register | 6 | 0 | 3 × 2 = 6 | the value of CX is destroyed |
XCHG AX, BX | 1 (93h) | 0 | 3 | shortest and fastest; cannot be used with segment registers |
Table 8.1.15 gives a clear conclusion: the best way to swap two general-purpose registers is XCHG. The instruction is one byte. For XCHG swapping AX with another 16-bit register there are short codes of the form 90h + r; since the number of BX is 3, the code is 93h. At 5 MHz, swapping with the stack takes 38 × 200 ns = 7.6 µs, and XCHG takes 0.6 µs. The real value of the stack method is not swapping but saving. Preserving registers during a procedure or an interrupt, holding intermediate results temporarily, and copying segment registers (PUSH DS, POP ES) are the real jobs of the stack. Since segment registers cannot be swapped with XCHG, swapping them is also done with the stack: PUSH DS, PUSH ES, POP DS, POP ES.
8.1.3.9The interactive stack simulator
The interactive simulator in the slides shows the registers AX, BX, CX, and SP and the stack cells around SS:SP. The register values can be edited in hexadecimal. Six buttons run the instructions PUSH AX, PUSH BX, PUSH CX, POP AX, POP BX, and POP CX, and the instructions run accumulate in a list. With the simulator all the ordering examples of this note can be tried again: mirror order, swapping, rotating three registers.
An important case the simulator shows is POP from an empty stack. The real 8086 does not prevent it. If POP is done when the stack is empty, SP still increases by 2 and whatever is at that address in the segment is read. There is no way for the processor to know whether the stack is empty or full; SP is just a number. Keeping track of the limits of the stack is entirely the programmer's job.
8.1.4Saving the flags: PUSHF and POPF
8.1.4.1The flags word
The flags register (FLAGS) of the 8086 is a 16-bit register, but only nine of its bits are used. Six status flags describe the result of the last arithmetic or logic operation: CF (carry, bit 0), PF (parity, bit 2), AF (auxiliary carry, bit 4), ZF (zero, bit 6), SF (sign, bit 7), and OF (overflow, bit 11). Three control flags determine the behavior of the processor: TF (trap, bit 8), IF (interrupt, bit 9), and DF (direction, bit 10). The remaining bits are unused. On the 8086, bit 1 and bits 12–15 always read as 1; bit 3 and bit 5 are 0.
PUSHF pushes the 16-bit word of the flags register onto the stack: SP ← SP − 2, [SS:SP] ← FLAGS. POPF loads the word on top of the stack into the flags register: FLAGS ← [SS:SP], SP ← SP + 2. PUSHF does not change the flags; POPF can change all the flags at once.
In a program the flags are read one at a time: JC looks at CF and JZ at ZF. There is no MOV that accesses the whole flags register directly. LAHF copies only the low byte (SF, ZF, AF, PF, CF) into AH; it does not reach OF, DF, IF, and TF. The only way to save and restore the whole flags register is the stack. The stack is also used to bring the flags word into a register: PUSHF followed by POP AX. At the start of a .COM program these two instructions bring F202h into AX. F000h is the four constant 1 bits, 0200h is IF = 1, and 0002h is the constant 1 in bit 1. After STC the same two instructions give F203h; the difference is bit 0, CF.
8.1.4.2PUSHF and POPF: code trace
The program below saves the flags of an addition, puts in between another addition that destroys the flags, and restores the saved flags.
ORG 100h
MOV AX, 0FFFFh
ADD AX, 1 ; CF=1, ZF=1
PUSHF ; save flags
MOV BX, 5
ADD BX, 3 ; CF=0, ZF=0
POPF ; restore flags
RETThe number in the first line is written as 0FFFFh. If a hexadecimal number starts with a letter, a 0 is added in front so the assembler does not take it for a name; writing FFFFh gives an error. ADD AX, 1 computes FFFFh + 1 = 1 0000h. The result is 17 bits; the low 16 bits, 0000h, are written to AX and the 1 carried out goes to CF. Since the result is zero, ZF = 1. The low byte of 0000h has no 1 bits, that is, an even number of them, and PF = 1. In the low nibble F + 1 = 10h produces a carry, so AF = 1. SF = 0 and OF = 0: −1 + 1 = 0 is correct as signed, too.
PUSHF pushes the flags word at this moment. The value of the word is computed from the bits: the constant bits F000h + 0002h, 0200h for IF, 0040h for ZF, 0010h for AF, 0004h for PF, and 0001h for CF. The total is F257h. [FFFCh] = 57h and [FFFDh] = F2h. MOV BX, 5 does not change the flags. ADD BX, 3 computes 5 + 3 = 8: no carry, the result is not zero. CF, ZF, PF, and AF all become 0. 8 = 0000 1000b has a single 1 bit, so PF = 0. The flags of the first addition are lost. POPF loads F257h into the flags register, and CF = 1, ZF = 1, PF = 1, AF = 1 come back. AX and BX are not touched; AX = 0000h and BX = 0008h remain.
| Instruction | AX | BX | SP | Flags | Stack (from the top) |
|---|---|---|---|---|---|
MOV AX, 0FFFFh | FFFFh | 0000h | FFFEh | odItszapc | 0000h |
ADD AX, 1 | 0000h | 0000h | FFFEh | odItsZAPC | 0000h |
PUSHF | 0000h | 0000h | FFFCh | odItsZAPC | F257h, 0000h |
MOV BX, 5 | 0000h | 0005h | FFFCh | odItsZAPC | F257h, 0000h |
ADD BX, 3 | 0000h | 0008h | FFFCh | odItszapc | F257h, 0000h |
POPF | 0000h | 0008h | FFFEh | odItsZAPC | 0000h |
RET | 0000h | 0008h | 0000h | odItsZAPC | (empty); IP = 0000h |
The final state of the program is seen in Table 8.1.16. What would have happened had POP BX been written instead of POPF? F257h would again have been taken from the stack, but this time written to BX: BX = F257h. The flags would have stayed CF = 0 and ZF = 0 as after the second addition. This experiment shows the difference between POPF and POP clearly. Both instructions take the same word from the stack; only their destinations differ.
The program is 15 bytes. ADD BX, 3 is encoded with three bytes (83 C3 03): the opcode 83h says the 8-bit immediate is sign-extended to 16 bits. ADD AX, 1, on the other hand, is encoded with the short form special to AX as 05 01 00. PUSHF (9Ch) and POPF (9Dh) are one byte each.
Pushing another value onto the stack before restoring the flags saved with PUSHF, and then loading that value into the flags register with POPF. In the sequence PUSHF, PUSH AX, …, POPF, POP AX, POPF loads the value of AX as flags, and the old flags word arrives in AX. Flags and registers obey mirror order too: PUSH AX, PUSHF, …, POPF, POP AX.
8.1.4.3Changing the flags word
There are direct instructions for CF, DF, and IF: STC/CLC/CMC, STD/CLD, STI/CLI. There is no instruction that changes TF. The only way to set TF to 1 goes through the stack. The flags word is pushed onto the stack, taken into a register, bit 8 is changed, the word is pushed again, and it is loaded into the flags register with POPF:
PUSHF
POP AX
OR AX, 0100h ; bit 8 = TF
PUSH AX
POPF ; TF = 1Debuggers use this pattern to run a program one step at a time. When TF = 1, the processor generates a type 1 interrupt after every instruction. OF can be changed the same way; there is no instruction that sets OF directly either. In this pattern AX is destroyed; if AX is to be preserved, the pattern is placed between PUSH AX and POP AX.
Another use of changing the flags word on the stack is in interrupt routines. If an interrupt routine wants to return error information to the calling program through CF, it changes bit 0 of the FLAGS copy on the stack. When IRET restores this copy, the calling program sees CF. Most DOS functions report errors this way, as CF = 1.
8.1.4.4Instructions that use the stack automatically
Some instructions do by themselves what PUSHF and POPF do. INT n first pushes the flags word, then CS and IP; it then clears IF and TF. IRET restores IP, CS, and the flags word. Interrupt routines therefore do not save the flags themselves; INT does this automatically. In ordinary code, PUSHF and POPF are needed to preserve a result, because CALL does not save the flags.
CALL and RET also use the stack automatically. A near CALL pushes the offset of the instruction after it, that is, the return address, and decrements SP by 2. RET pops this address into IP and increments SP by 2. A far CALL pushes CS first and then IP; RETF takes the two back in reverse order. From the stack's point of view, these instructions are PUSHes and POPs whose destination is IP. If a PUSH inside a procedure does not have a matching POP, RET takes the forgotten value instead of the return address. All the stack safety rules rest on this simple observation.
| Instruction | Pushes (in order) | Popped by | SP difference |
|---|---|---|---|
CALL (near) | IP | RET | 2 bytes |
CALL (far) | CS, IP | RETF | 4 bytes |
INT n, hardware interrupt | FLAGS, CS, IP | IRET | 6 bytes |
8.1.5Stack safety
8.1.5.1The balance rule and the end of a .COM program
The PUSH and POP instructions hold temporary data while the program runs. The integrity of the stack is kept by an equal number of PUSHes and POPs. This rule must hold not on just one path of the program but on every path and in every branch. If the numbers of PUSHes and POPs are not equal, the stack is corrupted and it may not be possible to return to the operating system.
A piece of code is stack-balanced if the value of SP at its exit equals the value of SP at its entry. In a balanced piece every PUSH (and PUSHF) has a matching POP (or POPF). If the piece has more than one exit, the balance must hold for each exit separately.
Why balance matters so much shows at the end of a .COM program. RET expects a return address on top of the stack. When DOS starts a .COM program, it puts 0000h on the stack. If the program is balanced, the final RET takes this word and goes to CS:0000h, the start of the PSP. The INT 20h there terminates the program. If the program is not balanced, RET takes some other word.
Stack errors come in three forms, and each gives different symptoms (Figure 8.1.8). With an extra PUSH, RET takes the data put last instead of the return address and jumps to a random address. With an extra POP, the return address is “eaten” into a register; RET takes the word after it and again returns to the wrong place. With the wrong order, the stack is balanced and the program returns to the right place, but the values get mixed up. The program silently runs wrong. The third is the hardest to find, because the program does not crash.
8.1.5.2Error example: an unbalanced PUSH
In the program below AX is put on the stack but never taken back.
ORG 100h
MOV AX, 1234h
PUSH AX ; no POP!
RET ; IP ← ?| Instruction | IP (next) | AX | SP | Stack (from the top) |
|---|---|---|---|---|
| start | 0100h | 0000h | FFFEh | 0000h |
MOV AX, 1234h | 0103h | 1234h | FFFEh | 0000h |
PUSH AX | 0104h | 1234h | FFFCh | 1234h, 0000h |
RET | 1234h | 1234h | FFFEh | 0000h |
RET takes the word on top of the stack for the return address (Table 8.1.18). IP = 1234h and SP goes up to FFFEh. The processor starts executing the bytes at address 0700:1234h as instructions. This program is only 5 bytes; there is no program at address 1234h, only whatever was left in that region of memory. The program crashes or freezes. The odd thing is that DOS's 0000h word is still on the stack. The information needed for the return has not been lost; one word has just been left below.
The fix is easy: add a POP AX before RET, or do not write the PUSH at all. The real difficulty is that the imbalance often hides in one branch. In the code below, AX is pushed on both branches but popped on only one:
PUSH AX
CMP BX, 0
JE done ; no POP on this branch!
; … work using AX …
POP AX
done: RETAs long as BX ≠ 0 the program works correctly. The first time BX = 0, RET jumps to the value of AX. Errors of this kind are not easily caught in testing. The rule is: the number of PUSHes and POPs of each branch (JMP, Jcc) is counted separately. The safest solution is to put the POP under a single exit label and direct all branches there. In this example the fix is to jump to a label before the POP instead of JE done.
8.1.5.3Extra POP and wrong order
The effect of an extra POP can also be seen in a trace:
ORG 100h
MOV AX, 5
PUSH AX
POP BX
POP CX ; extra POP
RETPUSH AX and POP BX are balanced; BX = 0005h and SP = FFFEh. The extra POP CX takes DOS's 0000h word into CX and makes SP FFFEh + 2 = 0000h. SP has wrapped around in 16 bits. RET now reads the word at SS:0000h. This address is the start of the PSP, and its first two bytes are CD 20. In little-endian order this word is 20CDh. IP = 20CDh and the processor jumps to an address unrelated to the program. The return address, 0000h, has been “eaten” by CX.
The wrong order gives a different symptom. The sequence PUSH AX, PUSH BX, …, POP AX, POP BX is balanced; RET returns to the right place. But the values of AX and BX have been swapped. The program that called the procedure expects to find in AX the value it left there and continues with a wrong value. The error shows up only when this value is used, and often far from the procedure.
8.1.5.4Stack overflow and underflow
If the imbalance is repeated continuously instead of once, the stack goes beyond its limits. The 8086 does not check these limits; there is no error interrupt, only corruption.
Stack overflow is the pushing of more values than the area set aside for the stack can hold, so that SP goes below the stack area. Stack underflow is the popping of a value that was never pushed, so that SP goes above the stack area.
Typical causes of overflow are infinite recursion and a PUSH without a POP inside a loop. As SP gets smaller the stack descends and, in a .COM program, overwrites the data in the same segment and then the code (Figure 8.1.9). After the code is overwritten, in the next round the processor executes stack data as instructions. The symptom is often seen far from where the overflow began.
A small example of a PUSH without a POP in a loop is:
ORG 100h
MOV CX, 3
MOV AX, 0100h
again: PUSH AX
INC AX
LOOP again
RETThe loop runs three iterations and pushes 0100h, 0101h, and 0102h onto the stack. SP = FFF8h. RET takes the 0102h on top of the stack and IP = 0102h. This address is inside the program but is not the start of an instruction: MOV CX, 3 occupies 0100h–0102h and 0102h is its last byte. The processor takes the 00h byte for the start of a new instruction and begins executing a meaningless sequence. Instead of three iterations, a loop that starts with CX = 0 runs 65,536. In that case about 128 KB of values are pushed onto the stack. The 64 KB segment cannot hold that much: SP wraps around and the stack overwrites the code of the program.
Underflow is popping a value that was never pushed. If POP is done with SP = FFFEh, SP = 0000h; the 16-bit addition wraps. The value read is garbage or, in a .COM program, DOS's 0000h. The next PUSH takes SP down to FFFEh and overwrites DOS's word. The program then cannot terminate properly with RET, because the 0000h needed for the return has been overwritten.
The way to prevent overflow is to choose a stack area of sufficient size. The size of the stack area is chosen from the deepest call chain and the largest number of PUSHes of the program. Each CALL takes 2 bytes (4 bytes for a far call), each PUSH 2 bytes, and each interrupt 6 bytes. Interrupts can arrive at any moment of the program; hardware interrupt routines use the same stack and need room for the registers they save. In .EXE programs a separate stack segment of sufficient size is reserved with a directive such as .STACK 100h. A separate segment has another advantage: even if the stack overflows it does not overwrite the code, it only corrupts the memory below its own segment.
A program makes at most four levels of nested near CALLs. Each procedure pushes three registers on entry. A hardware interrupt can arrive at any moment of the program, and the interrupt routine pushes four registers. How deep can the stack get at most?
- Calls: 4 levels × (2 bytes return address + 3 × 2 bytes registers) = 4 × 8 = 32 bytes.
- Interrupt: 6 bytes (FLAGS, CS, IP) + 4 × 2 bytes of registers = 14 bytes.
- Total: 32 + 14 = 46 bytes.
The stack gets at most 46 bytes deep. The 256 bytes reserved with .STACK 100h are more than enough for this program; the margin is left for procedures added later and for the BIOS routines' own use.
8.1.5.5Good practices
Most stack errors are prevented with a few coding habits. The six rules in the slides are:
- Mirror order. The reverse of the order
PUSH AX,PUSH BX,PUSH CXisPOP CX,POP BX,POP AX. Written one below the other, the code should look like a mirror image. - Single exit. Use a single exit label in a procedure instead of several RETs. The POPs are written once and all branches pass through them.
- Do not touch SP. SP is changed directly for only two jobs: clearing the parameters passed on the stack (
ADD SP, n) and reserving room for local variables (SUB SP, n). n must always be even. - The BP frame. Data on the stack cannot be reached with
[SP+n], because on the 8086 SP is not a base register. DoMOV BP, SPand use[BP+n]; BP addresses the SS segment by default. - Protect the segments. Routines that change DS or ES must PUSH and POP them as well. The calling program cannot know that its data segment has changed.
- Check with emu8086. Open the stack window and check that SP returns to its value at entry before RET.
Figure 8.1.10 gives mirror order visually. The lines between the PUSHes and POPs form nested arcs. If the lines cross, the order is wrong. This picture resembles the nesting of opening and closing parentheses: the parenthesis opened last is closed first.
The skeleton below shows all these rules together:
my_proc PROC
PUSH AX ; registers in use
PUSH BX
PUSH DS ; a segment will change too
; … work …
JC done ; the error branch also leaves through the exit
; … work …
done: POP DS ; mirror order
POP BX
POP AX
RET
my_proc ENDP8.1.5.6Tracing the stack in emu8086
All the trace tables of this note can be reproduced step by step in emu8086. The method has four steps.
- Compile and load. The program is assembled with the compile button and loaded into the emulator with emulate. The register panel shows the initial values of CS, IP, SS, and SP: for a .COM program 0700h, 0100h, 0700h, and FFFEh.
- Single step. The single step button runs one instruction per press, and the registers that change are highlighted. Step back undoes the last step; it is handy for seeing the effect of a PUSH again.
- The stack window. The stack button at the bottom opens a window that shows the words around SS:SP. The row SP points at is marked. With every PUSH the marker moves up a row (to a smaller address), and with every POP down a row.
- The memory view. The list in the middle of the emulator shows the bytes in hexadecimal, decimal, and ASCII. The bytes
B8 12 12are the instructionMOV AX, 1212h. The little-endian convention shows up here:MOV AX, 1234his encoded as B8 34 12.
After loading, CX shows the byte count of the program; in the swap example this value is 000Bh, that is, 11 bytes. A program must not rely on this value and must load CX itself before using it. The 0000h seen on the FFFEh row of the emu8086 stack window is not a coincidence either; it is the return address for the RET at the end of the program. Looking at this row before every RET of a program is the shortest way to check the stack balance.
8.1.6Exercises and solutions
The five exercises from the slides are solved here with intermediate steps.
1. With SS = 2000h and SP = 0100h, what are the physical addresses of the bytes written after PUSH AX?
PUSH first decrements SP: SP = 0100h − 2 = 00FEh. The new top of the stack is 2000h × 10h + 00FEh = 20000h + 00FEh = 200FEh. In little-endian order AL is written to 200FEh and AH to 200FFh. With AX = 1234h, [200FEh] = 34h and [200FFh] = 12h.
2. After MOV AX,1 / MOV BX,2 / MOV CX,3 / PUSH AX / PUSH BX / PUSH CX / POP BX / POP CX / POP AX, what are AX, BX, CX?
After the three PUSHes the stack, from top to bottom, is 3, 2, 1. POP BX takes 3, POP CX takes 2, and POP AX takes 1. The result is AX = 1, BX = 3, CX = 2. AX stays where it was, and BX and CX are swapped. AX stays fixed because it is both the first register pushed and the last one popped.
3. Copy the value of DS into ES using only PUSH and POP.
PUSH DS followed by POP ES. The two instructions are two bytes (1Eh, 07h) and disturb no general-purpose register. The stack stays balanced.
4. With SP = FFFEh, PUSH AX / PUSH BX / PUSHF / POP CX are executed. What is SP, and what arrives in CX?
Three pushes decrease SP by 6, and one pop increases it by 2: FFFEh − 6 + 2 = FFFAh. CX receives the word pushed last, that is, the flags word at the moment of PUSHF. At the start of a .COM program this value is F202h. Copies of AX and BX remain on the stack; if the program were ended with RET in this state, it would return to the value of BX.
5. Write a PUSH/POP sequence that preserves AX and the flags during an operation.
PUSH AX, PUSHF, … operation …, POPF, POP AX. Since the flags were pushed last, they are popped first; the sequence obeys mirror order. For example, with AX = 0000h and CF = ZF = 1, let MOV AX, 7 and ADD AX, 1 run inside the wrapper. At the end of the wrapper AX = 0000h, CF = 1, ZF = 1, and SP = FFFEh.
8.1.7Summary
- The stack is an area of memory set aside for temporary data and working in last-in, first-out (LIFO) order. The programmer (PUSH, POP), the processor (CALL, INT), and the operating system use the same stack.
- The top of the stack is SS:SP; its physical address is SS × 10h + SP. In a .COM program SS = CS and SP = FFFEh; in an .EXE program the values in the header are used. BP also addresses the SS segment by default; SP cannot be used in an addressing expression.
- The stack grows downward: PUSH decreases SP by 2 and POP increases it by 2. The unit is always the word;
PUSH ALis invalid. In a .COM program the code grows up and the stack down, and they share the free space in between. - PUSH: first SP ← SP − 2, then [SS:SP] ← source. POP: first destination ← [SS:SP], then SP ← SP + 2. POP does not erase memory. SP always points at the topmost occupied cell.
- PUSH takes a register, a segment register, or a memory word; PUSH with an immediate exists only on the 80186 and later. There are no POP CS and no POP constant. On the 8086,
PUSH SPwrites the decremented value. - A word is written to the stack little-endian: the low byte at the address SP points at, the high byte one above. SP is kept even; an odd SP makes every access take two bus cycles.
- PUSH, POP, and PUSHF do not change the flags; POPF loads all the flags. The result of a CMP is carried safely across PUSH and POP.
- When saving registers, the POP order is the reverse of the PUSH order (mirror order); POPping in the same order swaps or reverses the values. An array can be reversed with the stack. The best way to swap two registers is XCHG; the real job of the stack is saving.
- PUSHF/POPF save and restore the whole flags register. The flags word is brought into a register with PUSHF and POP; TF is changed this way. INT pushes the flags automatically; CALL does not.
- An equal number of PUSHes and POPs is done on every path and in every branch. In a .COM program the final RET takes the 0000h DOS put there, and the INT 20h in the PSP ends the program. With an extra PUSH, RET returns to data; with an extra POP, to beyond the stack.
- The 8086 does not check overflow and underflow: SP wraps in 16 bits and the stack can overwrite the code. The stack area is chosen taking into account the deepest call chain, the largest number of PUSHes, and interrupts.
8.1.8Key terms
- stack
- LIFO (last in, first out)
- push / pop (PUSH / POP)
- stack segment (SS)
- pointer register (SP, BP)
- base pointer (BP)
- flags register (FLAGS)
- stack overflow / underflow
- little-endian / big-endian
- segment:offset (logical address)
- physical address
- default segment
- return address
- register preservation
- data transfer instruction
8.1.9Test Yourself
With SS = 3000h and SP = 0000h,
PUSH AXruns. What is SP? To which physical addresses are the two bytes of AX written?Answer
SP = 0000h − 2 = FFFEh; the 16-bit subtraction wraps. The top of the stack is 30000h + FFFEh = 3FFFEh. AL is written to 3FFFEh and AH to 3FFFFh. The initial value SP = 0000h can be used so that the stack starts at the very top of the segment; the first PUSH writes to the last word of the segment.
After the sequence
MOV AX, 1A2Bh,PUSH AX,MOV BX, SP,MOV DL, [BX+1],MOV DH, [BX],POP AX(.COM program, starting with SP = FFFEh), what are BX and DX?Answer
BX = FFFCh. [FFFCh] = 2Bh (low byte), [FFFDh] = 1Ah (high byte). DL = 1Ah, DH = 2Bh; DX = 2B1Ah. Because the bytes were read into the opposite places, DX is AX with its bytes exchanged.
With AX = AAAAh, BX = BBBBh, CX = CCCCh,
PUSH AX,PUSH BX,PUSH CX,POP BX,POP AX,POP CXrun. What are the three registers in the end?Answer
The stack, from top to bottom, is CCCCh, BBBBh, AAAAh. BX = CCCCh, AX = BBBBh, CX = AAAAh. Each register has taken the value of another; the stack is balanced.
After the sequence
STC,PUSHF,CLC,POPF, what is CF? IfPOP AXhad been written instead ofPOPF, what would CF and AX be (at the start of the program IF = 1, the other flags 0)?Answer
POPF restores the word saved after STC: CF = 1. With POP AX, CF stays 0 as CLC left it, and AX = F203h (constant bits F002h, IF 0200h, CF 0001h).
A .COM program ends with
MOV AX, 5,PUSH AX,PUSH AX,POP BX,RET. What is IP after RET? Does the program terminate properly?Answer
Two PUSHes are matched by one POP; the second 0005h is left on top of the stack. RET takes this value: IP = 0005h. The processor jumps to an address inside the PSP; the program never reaches INT 20h and does not terminate properly.
The 26-byte program that reverses an array with the stack occupies 0100h–0119h. How many words can be pushed at most onto a stack starting from SP = FFFEh without overwriting the program?
Answer
After n pushes SP = FFFEh − 2n, and SP ≥ 011Ah must hold. n ≤ (FFFEh − 011Ah) / 2 = (65,534 − 282) / 2 = 32,626. At most 32,626 words can be pushed.
A student puts
PUSH CX,INC CX,POP CXbetweenCMP AX, BXandJE. Does JE jump on the result of the comparison?Answer
No. PUSH and POP do not change the flags, but
INC CXsets ZF again according to the new value of CX. JE now looks at the result of INC, not of CMP. The fix is to put PUSHF/POPF in between, or to move the INC before the comparison.How many clock cycles does swapping with the stack (two PUSHes, two POPs) take on the 8086, compared with
XCHG AX, BX? What is the difference in µs at 5 MHz?Answer
With the stack: 2 × 11 + 2 × 8 = 38 cycles. XCHG AX, BX: 3 cycles. The difference is 35 cycles; at 5 MHz one cycle is 200 ns, so 35 × 200 ns = 7 µs.
8.1.10Further reading
- Intel, The 8086 Family User's Manual (1979): the exact definitions, encodings, and clock cycle counts of PUSH, POP, PUSHF, POPF, CALL, RET, INT, and IRET; the meaning of the S3–S6 status bits. The values in Tables 8.1.2 and 8.1.6 are from this source.
- B. B. Brey, The Intel Microprocessors (8th ed.), Chapter 4: the stack instructions among the data transfer instructions, initializing the stack, and detailed examples of PUSH/POP.
- K. R. Irvine, Assembly Language for x86 Processors (7th ed.), the section on stack operations: the runtime stack, preserving registers, and the example of reversing a string with the stack.
8.1.11References
- Intel, The 8086 Family User's Manual, 1979 — instruction definitions of PUSH, POP, CALL, RET, INT, IRET.
- B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009 — Chapters 4 and 6.
- K. R. Irvine, Assembly Language for x86 Processors, 7th ed., Pearson, 2014 — stack operations and procedures.
- emu8086 help documentation: 8086 Assembler Tutorial, Part 9 (The Stack).
Related pages: Chapter 8.1 slides · © Sercan Külcü. All rights reserved.