Microprocessors · Lecture Notes
Chapter 8.2: Procedures
The same job is needed in many places of a program: printing a piece of text on the screen, splitting a number into decimal digits, searching for a value in an array. Rewriting the code for this job everywhere fills memory and multiplies errors. A procedure lets such a job be written once and called from any place. The 8086 does this with two instructions: CALL writes the return address onto the stack and jumps to the procedure, and RET takes that address from the stack and returns. This note first explains how a procedure is defined and the effect of CALL and RET on registers, the stack, and machine code. It then covers near and far calls, the indirect call, and the clock cycle cost of a call. Next it turns to how parameters are passed through registers, memory, addresses, and the stack, to preserving registers, to the stack frame, and to local variables. The last sections cover example programs, recursion, and common mistakes in procedures. Every piece of code is traced step by step together with registers, flags, and the stack.
Learning outcomes
- Define a procedure
- Write a procedure with PROC/ENDP, place it in the right spot in the program, and tell an assembler directive from a processor instruction.
- Trace CALL and RET
- Show step by step, with the values of IP, SP, and the stack, how the return address is pushed and how RET takes it back; compute the relative displacement in the machine code of CALL.
- Distinguish call types
- Explain what near, far, and indirect calls push onto the stack and what RET, RETF, and RET n pop; show that the procedure type and the return instruction must match.
- Pass parameters
- Send data to a procedure through registers, memory variables, addresses, and the stack; get the result back through a register, a flag, or memory; compare passing by value with passing by address.
- Build a stack frame
- Reach parameters with fixed offsets such as [BP+4] and [BP+6] through BP, open room for local variables with SUB SP, and close the frame in the right order.
- Write safe procedures
- Preserve registers with PUSH/POP, keep the stack balanced, use a single exit point, compute the stack need of recursion, and avoid common mistakes.
8.2.1The procedure concept and its definition
8.2.1.1What is a procedure?
Assembly programs grow long quickly. Jobs such as printing a string on the screen, splitting a number into decimal digits, or searching for a value in an array are needed in many places of a program. Rewriting the same sequence of instructions wherever it is needed creates two problems. First, the program grows needlessly; on small 8086-based systems memory is a limited resource. Second, an error in one copy of the code is present in all copies, and each has to be fixed separately. The function and subroutine concepts of high-level languages solve these problems. Their counterpart in assembly language is the procedure.
A procedure (also called a subroutine) is a piece of code that performs a specific task and can be called from any place in the program. A procedure is called with the CALL instruction. When it finishes its task, it returns with the RET instruction to the instruction right after the one that called it. The address written to the stack at the moment of the call is called the return address.
The most important concept in the definition is the return address. A procedure can be called from different places in the program. The place to return to differs with each call, but the code of the procedure is the same. A procedure cannot keep in its own code where to return to. On every call the CALL instruction writes this information to the stack, and RET reads it from there. So the same RET instruction returns to one address on one call and to another address on another call.
show twice. Each RET returns to the instruction right after the call that started it.Figure 8.2.1 shows this situation. The main program calls the procedure show from two separate places. The return of the first call goes behind the first CALL, and the return of the second call behind the second CALL. Only a single copy of the procedure is loaded in memory.
Using procedures has three benefits. Reuse: the code is written once and called as many times as wanted; code duplication and memory use go down. Readability: the program is divided into small tasks, each with a name. The line CALL print_num is much easier to read than the fifteen instructions that would take its place. Maintenance: an error is fixed in one place, and a procedure can be tested separately from the rest of the program. These properties make a program more structured and understandable.
A procedure has a cost, too. On every call the processor executes the extra CALL and RET instructions and writes the return address to memory and reads it back. This overhead can be computed in clock cycles. It is small, but it shows up in very short jobs that are called very often.
8.2.1.2Defining with PROC and ENDP
In 8086 assembly language a procedure is written between a PROC line that starts with its name and an ENDP line that ends with the same name. The general form is:
name PROC ; start (NEAR by default)
; procedure body goes here
RET
name ENDP ; endThe pattern has three rules. First, name is the name of the procedure and must be written the same at the start and at the end. A definition that starts with p1 PROC and ends with p2 ENDP is an error for the assembler. Second, the name follows the label rules: it starts with a letter or an underscore, cannot start with a digit, and cannot be the same as an instruction name. The assembler binds the name to the address of the first instruction of the procedure. When CALL name is written, this address is used. Third, there must be at least one RET inside the procedure. The processor does not see ENDP. If there is no RET, the flow continues after the last instruction of the procedure with whatever is in memory there.
The type can also be written on the PROC line: name PROC NEAR or name PROC FAR. If no type is written, the procedure is taken as near (NEAR). A near procedure is in the same code segment as the code that calls it. Most of the examples in this note are single-segment .COM programs and all their procedures are near. The effect of a far procedure on the stack is treated together with the types of CALL and RET.
The place of a procedure in the program matters too. The processor executes instructions in memory order and does not stop at a PROC line. If the procedure is written in the middle of the main program, when the main program gets there it executes the instructions of the procedure even though it has not been called. This situation is called falling into the procedure. The safe place is after the final RET of the main program:
ORG 100h
CALL p1
RET ; main program ends
p1 PROC ; after the RET:
; ... ; never fallen into
RET
p1 ENDP
ENDHere the main program consists of two instructions. CALL p1 calls the procedure, and the RET that follows ends the program. Since the instructions of the procedure sit after the RET of the main program, the flow reaches them only through CALL. If the procedure is to be written before the main program, a JMP that jumps over the procedure is put at the start of the main program. In emu8086 examples the second form is also common: JMP start, then the procedures, then the start: label.
Forgetting the RET at the end of the main program. In the program below there is no RET after CALL twice:
ORG 100h
MOV AX, 2
CALL twice
twice PROC
ADD AX, AX
RET
twice ENDPCALL pushes 0106h as the return address, the procedure makes AX 4, and RET returns to 0106h. But 0106h is the first instruction of the procedure itself. The processor “falls into” the procedure once more, AX becomes 8, and this time RET takes the 0000h on the stack and ends the program. Although the procedure was called once, it ran twice, and the result is 8 instead of 4. The assembler cannot catch this error, because the code is syntactically correct.
8.2.1.3Directives and instructions
Two different kinds of element stand side by side in a procedure definition. PROC, ENDP, and END are addressed to the assembler. CALL and RET, on the other hand, are instructions the processor executes. This distinction is the key to understanding how procedures work.
A directive is a line that tells the assembler what to do during translation. A directive is not translated to machine code and takes no space in memory. An instruction is an operation that is translated to one or more bytes and executed by the processor at run time.
| Element | Kind | Job |
|---|---|---|
PROC / ENDP | assembler directive | Tells the assembler the start address and the type (NEAR/FAR) of the procedure. It is not translated to machine code. |
CALL | processor instruction | Pushes the return address onto the stack and jumps to the address of the procedure. The code of the near direct form is E8. |
RET | processor instruction | Takes the return address from the stack and jumps there. The code of the near form is C3. It is used to return both from a procedure and from a .COM program. |
END | assembler directive | Tells the assembler that the source file has ended. |
Table 8.2.1 and Figure 8.2.2 summarize this distinction. Its consequence is: at run time there is no such object as a “procedure”. In memory there are only instruction bytes. The name, start, and end of a procedure live only in the source code and in the assembler's symbol table. For the processor a procedure is nothing but an address range that is jumped into with CALL and left with RET. That is why the ENDP line does not do the work of an “end”. What ends a procedure is the RET instruction inside it.
The second use of RET is also understood from this viewpoint. A .COM program ends like a procedure called by DOS. Before starting the program, DOS writes the INT 20h instruction into the first 256 bytes of the program's segment, the PSP (program segment prefix). Then it pushes the word 0000h onto the stack and starts the program at address 0100h. The final RET of the program takes the 0000h on the stack into IP. The processor executes the INT 20h at CS:0000h, and the program terminates. In emu8086, when a .COM program starts, SP = FFFEh and [FFFEh] = 0000h. In all the trace tables of this note, the 0000h at the bottom of the stack is this word pushed by DOS.
8.2.1.4Modular programming
In large programs the procedures do not fit in one source file either. The program is divided into source files, each collecting related procedures. These files are called modules. Two directives are used to call a procedure in one module from another module:
; main.asm
EXTRN show:NEAR ; in another file
...
CALL show
; tools.asm
PUBLIC show ; exported
show PROC NEAR
...
RET
show ENDPPUBLIC show opens the name show to other modules. EXTRN show:NEAR tells the assembler that this name is defined in another module and that its type is NEAR. When assembling main.asm, the assembler does not know the address of show. It leaves the address field of the CALL instruction blank and leaves a note in the object file saying “the address of show goes here”.
Each module is assembled separately and becomes an object file (.OBJ) (Figure 8.2.3). The linker places the object files one after another, finds the final address of each procedure, and fills in the blank fields in the CALL instructions. Frequently used object files can be gathered in a library (.LIB) file. The linker takes from the library only the procedures the program actually calls. The benefit of this method is that unchanged modules are not reassembled and the same library is used in many programs.
emu8086 does not do separate assembly and linking. In this environment shared code is added with the INCLUDE directive. INCLUDE inserts the text of the named file into the source as it is, and the program is assembled as a single piece. The emu8086.inc file that comes with emu8086 is used this way. The difference between the two methods is that the linker combines object code, while INCLUDE combines source text.
8.2.2CALL and RET
8.2.2.1CALL and RET step by step
The job of CALL and RET is in short “call and return”. Inside the processor this job is split into a few small steps. The smallest example is used to see the steps: the main program calls the procedure m1, m1 writes 5 to BX and returns, and the main program writes 2 to AX and ends.
ORG 100h
CALL m1 ; 0100h: E8 04 00
MOV AX, 2 ; 0103h: B8 02 00
RET ; 0106h: C3 → DOS
m1 PROC
MOV BX, 5 ; 0107h: BB 05 00
RET ; 010Ah: C3 → caller
m1 ENDP
ENDThe addresses and bytes in the comments are how the program looks in memory. ORG 100h says the first instruction will be placed at address 0100h. CALL is 3 bytes and occupies 0100h–0102h. The next instruction starts at 0103h. The first instruction of the procedure, MOV BX, 5, is at 0107h; the value of the label m1 is therefore 0107h.
A near CALL does two things: (1) SP ← SP − 2 and [SS:SP] ← IP, where IP is the address of the instruction after CALL. (2) IP ← target address. A near RET does the opposite: IP ← [SS:SP] and SP ← SP + 2. Neither instruction touches the flags.
The phrase “IP is the address of the instruction after CALL” in the definition comes from how the processor works. In the 8086 the bus interface unit (BIU) fetches instruction bytes from memory and puts them in the 6-byte instruction queue. The execution unit (EU) takes an instruction from the queue and decodes it. When the instruction has been decoded, IP points right behind that instruction's bytes. At the moment CALL starts executing, IP = 0103h. This is the value written to the stack as the return address. The processor does not do an extra addition.
| Step | Operation | IP | SP | Stack |
|---|---|---|---|---|
| 0 | start, the next instruction is CALL m1 | 0100h | FFFEh | [FFFEh] = 0000h |
| 1 | CALL decoded: IP points at the next instruction | 0103h | FFFEh | unchanged |
| 2 | SP ← SP − 2, [SP] ← IP | 0103h | FFFCh | [FFFCh] = 0103h |
| 3 | IP ← 0103h + 0004h | 0107h | FFFCh | unchanged |
| 4 | MOV BX, 5 executed | 010Ah | FFFCh | unchanged |
| 5 | RET: IP ← [SP], SP ← SP + 2 | 0103h | FFFEh | the 0103h at [FFFCh] is now invalid |
| 6 | MOV AX, 2 executed | 0106h | FFFEh | [FFFEh] = 0000h |
Table 8.2.2 gives the steps in order. Three points deserve attention. First, the stack of the 8086 grows downward. CALL first decrements SP and then writes. The return address is therefore written one word below FFFEh, at FFFCh. Second, the target address in step 3 is found with an addition: 0103h + 0004h = 0107h. The value 0004h is the relative displacement inside the CALL instruction; it is explained in detail when the machine code is examined. Third, RET does not erase the value it reads from the stack. 0103h stays at address FFFCh, but since SP now points above it, it is considered invalid. The next PUSH or CALL overwrites this word.
The hardware counterpart of these steps can also be followed. CALL's write to the stack is a memory write bus cycle. The physical address is found as SS × 16 + SP: 07000h + FFFCh = 16FFCh. Since the address is even, the 16-bit word is written in a single bus cycle. In this cycle A0 = 0 and BHE = 0, and the two data bytes pass together on lines D0–D7 and D8–D15. Had SP been at an odd value, the same word would have needed two bus cycles. That is why SP is always kept even. RET does a read bus cycle from the same address.
CALL and RET have one more hardware cost. The BIU may already have fetched into the queue the bytes after CALL, that is, the bytes of MOV AX, 2 at 0103h. When IP changes to 0107h these bytes are useless. The processor flushes the queue and the BIU starts fetching from the new address. The next instruction waits until its bytes arrive from memory. The same happens at RET. This is one reason the clock cycle counts of jump and call instructions are high.
8.2.2.2A simple procedure: code trace
The same program is now traced instruction by instruction from beginning to end. Each row of Table 8.2.3 shows the state after that instruction has executed. It is the same as the values obtained by running the program in emu8086.
| Line | Instruction | IP (next) | SP | AX | BX | Stack |
|---|---|---|---|---|---|---|
| — | start | 0100h | FFFEh | 0000h | 0000h | [FFFEh] = 0000h |
| 2 | CALL m1 | 0107h | FFFCh | 0000h | 0000h | [FFFCh] = 0103h |
| 6 | MOV BX, 5 | 010Ah | FFFCh | 0000h | 0005h | [FFFCh] = 0103h |
| 7 | RET | 0103h | FFFEh | 0000h | 0005h | [FFFEh] = 0000h |
| 3 | MOV AX, 2 | 0106h | FFFEh | 0002h | 0005h | [FFFEh] = 0000h |
| 4 | RET (DOS'a) | 0000h | 0000h | 0002h | 0005h | empty |
The line order is 2, 6, 7, 3, 4. The flow does not follow the order in the source code: CALL jumps to the procedure and RET brings it back. In the last row the main program's RET takes the 0000h on the stack into IP, and SP becomes 0000h, the part of FFFEh + 2 = 10000h that fits in 16 bits. The processor executes the INT 20h at 0700:0000 and the program ends. The result is AX = 0002h, BX = 0005h.
It is also instructive to look at the rows of the table where the registers do not change. CALL and RET do not touch AX and BX. The BX written by the procedure is still 0005h after the return. The procedure and the main program share the same set of registers; the procedure has no registers of its own. This makes passing parameters easy. But the danger of the procedure destroying the caller's registers arises from the same fact. Parameter passing and register preservation deal with these two sides.
8.2.2.3Machine code in memory
When the assembler translates the source code to bytes, the m1 program takes only 11 bytes in memory: E8 04 00 B8 02 00 C3 BB 05 00 C3. No trace of ORG, PROC, ENDP, and END is left.
The first three bytes in Figure 8.2.5 are the CALL instruction. E8 is the opcode of “near, direct CALL”. The two bytes after it are not the absolute address of the target. They are the distance of the target relative to the instruction after CALL.
The relative displacement (rel16) of a near direct CALL is the difference between the target address and the address of the instruction after the CALL: rel16 = target − (address of CALL + 3). While running, the processor computes IP ← IP + rel16. The difference is a 16-bit two's complement number; if the target is behind, rel16 is negative.
For m1, rel16 = 0107h − (0100h + 3) = 0107h − 0103h = 0004h. The 8086 stores multibyte values in little-endian order: the low byte first (04), then the high byte (00). The instruction is therefore E8 04 00.
Using a displacement has a benefit. If the code is moved elsewhere in memory, the difference between the CALL and its target does not change and the instruction keeps working correctly. This property is called position-independent code. Had an absolute address been stored, the address would have had to be fixed up every time the code was moved.
Let us find the machine code of two CALLs: (a) the second CALL m2 at 0107h in the m2 example, m2 = 010Bh; (b) the CALL p at 0120h, p = 0100h.
- Next instruction. (a) 0107h + 3 = 010Ah. (b) 0120h + 3 = 0123h. These addresses are also the return addresses to be pushed onto the stack.
- Difference. (a) 010Bh − 010Ah = 0001h. (b) 0100h − 0123h = −23h. In 16-bit two's complement −23h = 10000h − 23h = FFDDh.
- Bytes. The low byte is written first. (a)
E8 01 00. (b)E8 DD FF. - Check. For (b) the processor computes IP ← 0123h + FFDDh. The sum is 10100h; the carry that does not fit in 16 bits is discarded and IP = 0100h.
The name of the procedure does not appear in the machine code either. m1 exists only in the assembler's symbol table; of it, the machine code keeps only the address 0107h stored as a displacement. The debugger of emu8086 can show names because it stores the symbol table separately.
8.2.2.4Types of CALL and RET
The 8086 has several forms of CALL and RET. The forms are distinguished by two questions. Is the target in the same code segment (near) or in another one (far)? Is the target inside the instruction (direct) or in a register or memory (indirect)?
| Instruction | Code | Bytes | Pushes / pops | Description |
|---|---|---|---|---|
| CALL near | E8 rel16 | 3 | IP | Direct call within the same segment (default). |
| CALL register/memory | FF /2 | 2–4 | IP | Indirect near call: CALL BX, CALL [table+SI]. |
| CALL FAR | 9A ofs seg | 5 | CS, then IP | Procedure in another segment; CS:IP change together. |
| RET | C3 | 1 | IP | Near return. |
| RETF | CB | 1 | IP, then CS | Far return (FAR procedure). |
| RET n | C2 n16 | 3 | IP; SP += n | On return also discards n bytes of parameters from the stack. |
The notation “FF /2” in Table 8.2.4 says that the opcode is FF and that the middle field of the ModR/M byte that follows is 2. The ModR/M byte indicates whether the operand is a register or a memory address. The length of an indirect CALL therefore varies from 2 to 4 bytes depending on the operand. CALL BX is 2 bytes (FF D3). CALL table[SI] carries a 16-bit displacement, so it is 4 bytes (FF 94 10 01). The far RET also has a RETF n form (CA n16).
The assembler encodes the RET inside a procedure according to the type of the procedure. In a procedure declared name PROC NEAR or with no type written, RET becomes C3. Inside name PROC FAR the same word RET is encoded as CB, that is, RETF. The programmer writes the type once on the PROC line, and the assembler fits the return instructions. CALL also looks at the type of the target: if the target is a FAR procedure, the assembler produces the 5-byte far call that starts with 9A.
8.2.2.5Far procedure and far return: code trace
A far (FAR) procedure is in a code segment other than the caller's. To reach it, both CS and IP must change. To be able to return, the old values of both must be saved. A far CALL therefore pushes two words onto the stack: first CS, then IP. RETF pops them in reverse order: first IP, then CS. The order on the stack matches RETF's popping order. The IP pushed last is on top of the stack and is the first one popped.
Which call is needed depends on the structure of the program. A .COM program runs in a single 64 KB segment; CS, DS, ES, and SS carry the same value. In such a program a near call is enough. In large .EXE programs with more than one code segment, a far call is needed for procedures in other segments. A far call is longer (5 bytes) and slower, because it writes two words to the stack and changes CS.
To see how a far return relates to the stack, a small trick can be used in a single-segment program. The two pushes of CALL FAR are done with two separate instructions: first PUSH CS, then a near CALL. The stack takes the layout that follows a far call, and the procedure can return with RETF.
ORG 100h
MOV AX, 5
PUSH CS ; first half of a far call
CALL farp ; pushes IP
ADD AX, 1
RET
farp PROC
SHL AX, 1
RETF ; IP first, then CS
farp ENDPThe byte layout of the code is: MOV AX, 5 3 bytes (0100h–0102h), PUSH CS 1 byte (0103h), CALL farp 3 bytes (0104h–0106h), ADD AX, 1 3 bytes (0107h–0109h), RET 1 byte (010Ah). The procedure starts at 010Bh: SHL AX, 1 2 bytes, RETF 1 byte (010Dh, code CB). Since no type is written on the farp PROC line, it is NEAR; the programmer has deliberately written RETF inside it.
| Line | Instruction | AX | CS:IP (next) | SP | Stack (from the top) |
|---|---|---|---|---|---|
| 2 | MOV AX, 5 | 0005h | 0700:0103 | FFFEh | 0000h |
| 3 | PUSH CS | 0005h | 0700:0104 | FFFCh | [FFFCh] = 0700h, 0000h |
| 4 | CALL farp | 0005h | 0700:010B | FFFAh | [FFFAh] = 0107h, 0700h, 0000h |
| 8 | SHL AX, 1 | 000Ah | 0700:010D | FFFAh | 0107h, 0700h, 0000h |
| 9 | RETF | 000Ah | 0700:0107 | FFFEh | 0000h |
| 5 | ADD AX, 1 | 000Bh | 0700:010A | FFFEh | 0000h |
Two rows of the trace (Table 8.2.5) are important. After line 4 the top of the stack holds the return IP (0107h) and beneath it CS (0700h). This is exactly the layout a real CALL FAR would leave. In line 9 RETF pops two words: IP = 0107h, CS = 0700h. SP grows by 4 to FFFEh. Since CS is already 0700h the change is not visible, but the processor has reloaded CS from the stack. The program continues from ADD AX, 1 and ends with AX = 000Bh. A real far call (9A, 5 bytes) does the same two pushes with a single instruction.
Not matching the type of the procedure with the return instruction. If a procedure called with a near CALL ends with RETF, RETF pops a CS that is not on the stack. If a procedure called with CALL FAR ends with a near RET, CS is left on the stack. In both cases the stack is off by 2 bytes and the return goes to a wrong address. This error is traced step by step among the common mistakes. Writing the type correctly on the PROC line and always using RET as the return instruction prevents this error; the assembler encodes RET according to the type.
8.2.2.6Indirect CALL: code trace
In the CALLs so far the target was written inside the instruction. Which procedure would be called was known when the program was written. In some cases this decision is made at run time. For example, in a menu the operation the user chose is called. For this job the target address is read from a register or from memory. Such a call is called an indirect call.
MOV AX, 6
MOV SI, 2 ; 2nd op (× 2)
CALL table[SI] ; indirect, memory
MOV BX, OFFSET add_one
CALL BX ; indirect, register
RET
table DW add_one, twice
add_one: INC AX
RET
twice: SHL AX, 1
RETtable is an array of words holding the addresses of two procedures. The assembler writes the addresses of the two labels into the line DW add_one, twice: 0114h and 0116h. The table starts at 0110h; the first element is at 0110h and the second at 0112h. Since each element is 2 bytes, the offset of the element with index i is 2 × i (the index starts at 0). SI = 2 selects the second element of the table, that is, the address of twice.
CALL table[SI] computes the effective address as table + SI = 0110h + 2 = 0112h and reads the word there: 0116h. It pushes the return address (010Ah) onto the stack and loads 0116h into IP. There are two memory accesses here: a read from the DS segment to fetch the target, and a write to the SS segment to store the return address. CALL BX, on the other hand, takes the target straight from BX and reads no target from memory.
| Line | Instruction | AX | BX | IP (next) | SP | [FFFCh] |
|---|---|---|---|---|---|---|
| 1 | MOV AX, 6 | 0006h | 0000h | 0103h | FFFEh | — |
| 2 | MOV SI, 2 | 0006h | 0000h | 0106h | FFFEh | — |
| 3 | CALL table[SI] | 0006h | 0000h | 0116h | FFFCh | 010Ah |
| 10 | twice: SHL AX, 1 | 000Ch | 0000h | 0118h | FFFCh | 010Ah |
| 11 | RET | 000Ch | 0000h | 010Ah | FFFEh | (invalid) |
| 4 | MOV BX, OFFSET add_one | 000Ch | 0114h | 010Dh | FFFEh | — |
| 5 | CALL BX | 000Ch | 0114h | 0114h | FFFCh | 010Fh |
| 8 | add_one: INC AX | 000Dh | 0114h | 0115h | FFFCh | 010Fh |
| 9 | RET | 000Dh | 0114h | 010Fh | FFFEh | (invalid) |
CALL table[SI]: the target is read from [table+2] = 0116h, and the return address 010Ah is pushed onto the stack.In the end AX = 13 (000Dh): first 6 × 2 = 12, then 12 + 1 = 13. In the trace (Table 8.2.6) the return addresses of the two calls differ: the first is 010Ah, the second 010Fh. Both are written to the same stack word, [FFFCh], because SP has returned to FFFEh between the two calls. Which procedure is called was chosen at run time through SI or BX. Had SI been 0, the first call would have gone to add_one and the same code would have produced a different result.
There is one more detail in the code. add_one and twice are defined not with PROC/ENDP but with ordinary labels. For the processor there is no difference: CALL jumps to an address and RET returns. PROC/ENDP gives the programmer and the assembler structure and type information.
8.2.2.7A menu with a jump table
The most common use of the indirect call is the jump table. In a menu each option is a procedure, and their addresses sit in order in a table. The key the user presses is converted to a table index, and the matching procedure is called with a single indirect CALL.
MOV AH, 1
INT 21h ; AL = '1'..'3'
SUB AL, '1' ; 0..2
CMP AL, 2
JA invalid ; range check
MOV BL, AL
MOV BH, 0
SHL BX, 1 ; 2-byte entries
CALL ops[BX]
invalid: RET
ops DW sum, diff, prodThe code runs line by line as follows. Function 01h of INT 21h reads a character from the keyboard, echoes it on the screen, and puts its ASCII code in AL. SUB AL, '1' converts the character to a number: '1' (31h) → 0, '2' → 1, '3' → 2. CMP AL, 2 and JA invalid are the range check; if the value is greater than 2, no call is made. The next three instructions move the 8-bit index into the 16-bit BX and multiply it by 2. Since the addresses in the table are 2 bytes, the byte offset of index i is 2i. Shifting left by one bit is the fastest way to multiply by 2. Finally CALL ops[BX] calls the selected procedure.
The range check has a subtlety. JA makes an unsigned comparison. If the '0' key is pressed, the result of SUB AL, '1' is 30h − 31h = FFh. Viewed as signed this is −1 and is less than 2. Viewed as unsigned it is 255 and greater than 2, so JA is taken and '0' is rejected as well. A single unsigned check closes both the lower and the upper bound. The '9' key gives 8 and is rejected too.
The values in Table 8.2.7 are the same as those obtained by adding the three procedures with short bodies and running with five keys in emu8086. Without the range check the '9' key would give BX = 16, and CALL would take the two bytes 16 bytes beyond the table for an address and go there. There is program code or data there; the processor jumps to a meaningless address. In every program that uses a jump table the index must be checked against the table size.
The counterpart of a jump table is a decision chain built with successive CMP and JE instructions. As the number of options grows the chain gets longer, and to reach the last option all the comparisons are executed. A table, on the other hand, reaches the target with a fixed number of instructions regardless of the number of options. Compilers often translate the switch construct of high-level languages this way.
8.2.2.8The timing of CALL and RET
Calling a procedure has a time cost. The instruction timings of the 8086 are given in clock cycles in the Intel manual. Table 8.2.8 gathers the timings of instructions related to procedures.
| Instruction | Clock cycles | Instruction | Clock cycles |
|---|---|---|---|
| CALL near | 19 | RET | 8 |
| CALL register | 16 | RETF | 18 |
| CALL FAR | 28 | RET n | 12 |
| PUSH register | 11 | POP register | 8 |
The values in the table are for the register and direct forms. For forms with a memory operand the time to compute the effective address is added. For example, for CALL table[SI] the manual gives 21 + EA cycles; EA is 9 cycles for displacement-plus-index addressing. CALL is more expensive than RET because it both writes to the stack and computes the target address. In both instructions the instruction queue is flushed and refilled.
How large is the overhead, apart from its real work, of a procedure that saves two registers? If the procedure is called 1000 times on a 5 MHz 8086, how long does this overhead take?
- Instructions. On every call one CALL (19), one RET (8), two PUSHes (2 × 11), and two POPs (2 × 8) are executed.
- Total. 19 + 8 + 2 × (11 + 8) = 27 + 38 = 65 cycles.
- Time. At 5 MHz one cycle is 1 / 5 MHz = 200 ns. 65 × 200 ns = 13,000 ns = 13 µs.
- 1000 calls. 1000 × 13 µs = 13 ms.
13 ms looks small, but if the real work of the procedure is only a few instructions, the overhead can exceed the work itself. At this point a macro is an option. A macro is a text pattern whose body the assembler copies into every place of use. Since there is no CALL and RET, it carries no call overhead, but the code takes space again at every use. The practical rule is: short jobs that run very often (such as printing a single character) suit a macro; long or rarely called jobs suit a procedure.
8.2.3Passing parameters
8.2.3.1Four ways
A procedure often works on an input and produces a result. A procedure that prints on the screen must know the text to be printed, and a procedure that adds must know the numbers to be added. The values the caller gives to the procedure are called parameters, and getting the values to the procedure is called parameter passing. In high-level languages the compiler arranges this itself. In assembly language the programmer chooses the way and follows the same rule in both the caller and the procedure.
Each of the four ways in Figure 8.2.10 has its place.
- Through registers. This is the easiest and fastest way; the parameter is already inside the processor and no memory access is needed. For example AL and BL carry two parameters and AX the result. Since the number of registers is limited, it does not suffice for more than a few parameters.
- Through memory variables. The procedure reads and writes shared variables such as
number1andresult. It is easy, but the procedure stays dependent on those variables. For it to work with other variables, its code has to change. - By address (pointer). Not the data itself but its start address is sent in SI, DI, or BX. A long array or string is processed without being copied. The procedure works with whichever array it is given the address of.
- Through the stack. The parameters are pushed onto the stack with PUSH before CALL. The procedure reads them through the BP register. On return they are discarded from the stack with
RET nor, in the caller, withADD SP, n. The compilers of high-level languages such as C and Pascal use this way.
Whichever way is chosen, a comment block is written at the head of the procedure. The block states the procedure's inputs, outputs, and the registers it destroys. In assembly language there is no compiler check for the name, type, or number of parameters. This comment is the only written record of the contract between the procedure and its caller.
8.2.3.2By value or by address?
A second question, independent of how parameters are passed, is what is given to the procedure: a copy of the data, or the location of the data?
In passing by value the procedure is given a copy of the data. Even if the procedure changes the copy, the original variable in memory does not change. In passing by address (by reference) the procedure is given the address of the data. Through this address the procedure can read and change the original variable.
MOV AX, a ; value: AX holds a copy of a
CALL twice ; AX doubles, a stays the same
LEA SI, a ; address: SI = OFFSET a
CALL twice_m ; [SI] doubles, a changesIn the first two lines the contents of a are copied into AX. twice doubles AX; the result is in AX and a stays in memory with its old value. In the last two lines the address of a is loaded into SI. twice_m doubles the memory word [SI]; what changes is a itself.
Passing by value is fast and safe for small data such as a single number. The procedure cannot accidentally corrupt the caller's variable. Passing by address is needed in three cases: data that does not fit in a register, such as arrays and strings; variables the procedure has to change; and cases where several results have to be written to memory.
LEA SI, a and MOV SI, OFFSET a give the same result: SI carries the offset of a. emu8086 translates this direct-address LEA to the same 3-byte code as MOV (BE + a 16-bit address). In the address computations of this note LEA is counted as 3 bytes. Real 8086 assemblers may also produce this form with the 4-byte encoding 8D 36. MOV SI, a, on the other hand, is a completely different instruction: it loads into SI not the address but the word inside a. This confusion is the most common error of passing by address.
8.2.3.3Swapping by address: code trace
The typical example of passing by address is a procedure that exchanges (swaps) the values of two variables. The procedure takes not two values but two locations. Had it taken values, it could have changed only its own copies.
ORG 100h
LEA SI, a
LEA DI, b
CALL swap
RET
swap PROC ; In: SI, DI (addrs)
PUSH AX
MOV AX, [SI]
XCHG AX, [DI]
MOV [SI], AX
POP AX
RET
swap ENDP
a DW 1234h
b DW 00FFhFirst the layout of the program in memory is worked out. The two LEAs are 3 bytes each (0100h and 0103h). CALL swap is at 0106h and is 3 bytes, so the return address is 0109h. The main program's RET occupies 0109h, and the procedure starts at 010Ah. The procedure's instructions are 1, 2, 2, 2, 1, and 1 bytes, ending with the RET at 0112h. The data follows right behind: a = 0113h, b = 0115h.
The procedure uses AX as an intermediate variable, but AX is neither its input nor its output. It is therefore saved with PUSH AX on entry and restored with POP AX on exit. XCHG AX, [DI] is the heart of the swap: it exchanges AX with the memory word in a single instruction. Three instructions (MOV, XCHG, MOV) complete the swap.
| Line | Instruction | SI | DI | AX | SP | a [0113h] | b [0115h] |
|---|---|---|---|---|---|---|---|
| 2–3 | LEA SI, a · LEA DI, b | 0113h | 0115h | 0000h | FFFEh | 1234h | 00FFh |
| 4 | CALL swap | 0113h | 0115h | 0000h | FFFCh | 1234h | 00FFh |
| 7 | PUSH AX | 0113h | 0115h | 0000h | FFFAh | 1234h | 00FFh |
| 8 | MOV AX, [SI] | 0113h | 0115h | 1234h | FFFAh | 1234h | 00FFh |
| 9 | XCHG AX, [DI] | 0113h | 0115h | 00FFh | FFFAh | 1234h | 1234h |
| 10 | MOV [SI], AX | 0113h | 0115h | 00FFh | FFFAh | 00FFh | 1234h |
| 11 | POP AX | 0113h | 0115h | 0000h | FFFCh | 00FFh | 1234h |
| 12 | RET | 0113h | 0115h | 0000h | FFFEh | 00FFh | 1234h |
XCHG AX, [DI]: b = 1234h, AX = 00FFh. On the right, after POP and RET: AX is back to its old value, and a and b stay exchanged.Four points can be seen in the trace (Table 8.2.9). SI and DI do not change from start to end; they are the addresses sent to the procedure. AX first carries the value of a (1234h) and, after XCHG, the old value of b (00FFh). In memory first b and then a change. Finally POP AX returns AX to its value before the call (0000h). The only visible effect for the caller is that a and b have exchanged places.
The memory-operand form of XCHG performs a read and a write bus cycle on the 8086. Doing the same job with two MOVs would need one more register. In cases where no other bus master must slip in between the read and the write, the LOCK prefix is put in front of the instruction. The prefix keeps the LOCK pin of the 8086 active for the duration of the instruction. In multiprocessor systems, shared variables such as semaphores are therefore changed with LOCK XCHG.
8.2.3.4Parameters in registers: code trace
As an example of passing parameters in registers, the procedure m2 that multiplies two numbers is used. AL and BL stand for the two parameters; m2 multiplies them and puts the result in AX.
MUL BL, and the result is in AX.The procedure's only instruction is MUL. MUL does unsigned multiplication and works in two forms depending on the operand size (Table 8.2.10). The source can be a register or a memory operand but not a constant: MUL 2 is invalid. If the upper half of the product (AH or DX) is nonzero, CF = OF = 1; these flags report whether the result fits in the lower half. SF, ZF, AF, and PF are undefined after MUL.
| Source | Operation | Result |
|---|---|---|
| 8 bits | AL × source | AX |
| 16 bits | AX × source | DX:AX |
ORG 100h
MOV AL, 1 ; 1st parameter
MOV BL, 2 ; 2nd parameter
CALL m2 ; 0104h: E8 04 00
CALL m2 ; 0107h: E8 01 00
RET ; 010Ah: to DOS
m2 PROC ; 010Bh
MUL BL ; AX = AL * BL
RET ; to caller
m2 ENDP
ENDMOV AL, 1 and MOV BL, 2 are 8-bit constant loads of 2 bytes each (B0 01, B3 02). The two CALLs are at 0104h and 0107h. The return address of the first is 0107h and that of the second 010Ah. m2 starts at 010Bh. The machine codes of the two CALLs differ (E8 04 00 and E8 01 00), because the displacement is computed relative to each CALL's own position. The target is 010Bh in both.
| Line | Instruction | IP (next) | SP | AX | BL | CF | [FFFCh] |
|---|---|---|---|---|---|---|---|
| 2 | MOV AL, 1 | 0102h | FFFEh | 0001h | 00h | 0 | — |
| 3 | MOV BL, 2 | 0104h | FFFEh | 0001h | 02h | 0 | — |
| 4 | CALL m2 (1.) | 010Bh | FFFCh | 0001h | 02h | 0 | 0107h |
| 8 | MUL BL | 010Dh | FFFCh | 0002h | 02h | 0 | 0107h |
| 9 | RET | 0107h | FFFEh | 0002h | 02h | 0 | (invalid) |
| 5 | CALL m2 (2.) | 010Bh | FFFCh | 0002h | 02h | 0 | 010Ah |
| 8 | MUL BL | 010Dh | FFFCh | 0004h | 02h | 0 | 010Ah |
| 9 | RET | 010Ah | FFFEh | 0004h | 02h | 0 | (invalid) |
| 6 | RET (DOS'a) | 0000h | 0000h | 0004h | 02h | 0 | — |
The most instructive aspect of the trace (Table 8.2.11) is that the same procedure returns to two different return points. The procedure's RET is the same instruction (010Dh) in both calls. In the first call it finds 0107h on the stack, in the second 010Ah, and returns there.
The second important point is that MUL changes AL. In the first call AX = 1 × 2 = 0002h. AL is now 02h. Since the second call is made without reloading AL, the result of the first call becomes the first parameter of the second: AX = 2 × 2 = 0004h. The program uses this behavior deliberately, but the same situation can also cause an error unnoticed. The “Out: AX” in a procedure's description shows that AL changes as well. In both multiplications AH = 0, so CF = OF = 0.
8.2.3.5Returning the result in a flag: code trace
The result of some procedures is not a number but a yes/no answer: could the file be opened, is the character a digit, was the value found? For such an answer a flag is used instead of spending a register. The carry flag (CF) is the most suitable flag for this. It can be set directly with STC, CLC, and CMC and tested with JC and JNC. DOS services also report an error with CF = 1.
MOV AL, '7'
CALL digit ; CF = 0 → AL = value
MOV BL, AL
MOV AL, 'x'
CALL digit ; CF = 1 → not a digit
RET
digit PROC ; In: AL, Out: CF
SUB AL, '0'
CMP AL, 10 ; 0..9 → borrow, CF = 1
CMC ; digit: CF = 0
RET
digit ENDPThe digit procedure converts the ASCII character in AL to a number and reports through CF whether the character is a digit. SUB AL, '0' subtracts 30h from the character. If the character is in the range '0'–'9', the result is 0–9. CMP AL, 10 makes an unsigned comparison. If AL < 10, the subtraction needs a borrow and CF = 1. If AL ≥ 10, CF = 0. This is the opposite of the meaning wanted. CMC (complement carry) inverts CF: CF = 0 for a digit and CF = 1 for a non-digit. For a character smaller than '0', the SUB result wraps into the range D0h–FFh and counts as greater than 10; that too is rejected.
| Line | Instruction | AL | BL | CF | SP | Note |
|---|---|---|---|---|---|---|
| 1 | MOV AL, '7' | 37h | 00h | 0 | FFFEh | '7' = 37h |
| 2, 8 | CALL digit · SUB AL, '0' | 07h | 00h | 0 | FFFCh | return 0105h; 37h − 30h = 7 |
| 9 | CMP AL, 10 | 07h | 00h | 1 | FFFCh | 7 − 10 needs a borrow |
| 10 | CMC | 07h | 00h | 0 | FFFCh | “is a digit” |
| 11, 3 | RET · MOV BL, AL | 07h | 07h | 0 | FFFEh | value stored |
| 4, 5, 8 | MOV AL, 'x' · CALL · SUB | 48h | 07h | 0 | FFFCh | 78h − 30h = 48h (72); return 010Ch |
| 9 | CMP AL, 10 | 48h | 07h | 0 | FFFCh | 72 ≥ 10, no borrow |
| 10 | CMC | 48h | 07h | 1 | FFFCh | “not a digit” |
| 11 | RET | 48h | 07h | 1 | FFFEh | result in CF |
Two conclusions follow from the trace (Table 8.2.12). First, RET does not touch the flags. The CF set inside the procedure is still valid in the caller after the return. The caller can test the result with JC error or JNC ok. Second, when CF = 1 AL has been corrupted (48h). The contract of the procedure is: the value in AL is meaningful only if CF = 0. The caller must look at the flag first and use the register afterward.
Executing an instruction that changes the flags after STC, CLC, or CMC in a procedure that returns its result in CF. For example, if ADD SP, 2 or CMP is done at the exit after CMC, CF is recomputed and the result is lost. POP and RET do not touch the flags; the instruction that sets the flag must be the last flag-changing instruction before RET.
8.2.3.6Returning several results
A procedure can produce more than one result. Division gives both a quotient and a remainder; a search gives both the “found?” answer and the position. There are three ways for this.
- A register pair. A 32-bit result returns in DX:AX (like the 16-bit MUL). The quotient and remainder return in AL and AH (like the 8-bit DIV).
- A flag and a register. CF reports success and the register holds the value. The caller first looks at the flag with JC.
- Memory. The results are written to an area whose address is given. The number of results is not limited by the number of registers.
The divmod procedure below uses the first two ways together. It divides AX by BL and returns the quotient in AL and the remainder in AH. If the divisor is zero it does not divide and reports an error with CF = 1.
divmod PROC ; In: AX, BL (divisor)
CMP BL, 0 ; Out: AL = quotient
JE error ; AH = remainder
DIV BL ; CF = 1: BL is 0
CLC
RET
error: STC
RET
divmod ENDPThe 8-bit DIV BL divides the 16-bit number in AX by BL. It writes the quotient to AL and the remainder to AH. After DIV all the flags are undefined. That is why, in the success case, CF is cleared explicitly with CLC. There are two RETs in the procedure. This is safe because nothing was pushed onto the stack: both RETs find the return address on top.
| Input | Result | Note |
|---|---|---|
| AX = 100, BL = 7 | AL = 0Eh (14), AH = 02h, CF = 0 | 100 = 7 × 14 + 2; AX = 020Eh |
| AX = 100, BL = 0 | CF = 1, AX = 0064h (unchanged) | DIV is never executed |
| AX = 1000, BL = 2 | divide error (INT 0) | quotient 500 does not fit in AL |
The last row of Table 8.2.13 shows a gap in the procedure. Although the divisor is not zero, the result of 1000 / 2 = 500 does not fit in the 8-bit AL (the largest value is 255). In this case too the 8086 generates a type 0 interrupt (divide error). Since the procedure checks only that the divisor is zero, it cannot catch this case. For a complete check the condition AH < BL must also be tested; the quotient fits in AL only under this condition.
A structure with two RETs is safe only if nothing has been pushed onto the stack. In a procedure that does PUSH, all paths must be merged at a single exit label where the POPs are. This rule is shown with the trace of a search procedure with a single exit point.
8.2.4Preserving registers
8.2.4.1The problem and documentation
The 8086 has eight general-purpose registers, and a procedure and its caller share them. If a procedure changes a register the caller is using without telling it, the caller's code breaks. The most typical example is a loop counter. The caller sets up a loop with CX and calls a procedure from inside the loop. If the procedure also uses CX for its own loop, on return CX holds not the caller's counter but whatever the procedure left.
The first remedy for the problem is documentation. At the head of every procedure its input, output, and the registers it destroys are written:
; m2: computes AL * BL
; In : AL, BL (unsigned)
; Out : AX = AL * BL
; Clobber: CF, OFSomeone who reads this comment knows that after calling m2 the old value in AX will be lost and CF and OF will change. That no other register changes is also a promise of this comment. If the promise is not kept, that is, if the procedure changes a register not named in the comment, the error most often shows up not in the procedure but in the code that calls it. The location and the cause of the error being different makes it hard to find.
Register preservation is a procedure's pushing the registers it uses onto the stack on entry and popping them back in reverse order on exit. The registers then appear to the caller as if they had never changed. Registers that return results are not preserved.
show PROC
PUSH AX ; save what
PUSH SI ; you use
; ... AX and SI are used
POP SI ; in REVERSE
POP AX ; order
RET
show ENDPThe reverse order comes from the last-in, first-out (LIFO) structure of the stack. Since AX was pushed first and SI after it, the value of SI is on top of the stack. The first POP takes that value and must write it to SI. If the order is mixed up, that is, if POP AX is written first, AX is loaded with SI's old value and SI with AX's. The stack is still balanced and RET returns correctly, but the two registers have taken each other's values.
The last sentence of the definition matters too. If a procedure that returns its result in AX pushes AX on entry and pops it back on exit, it erases with its own hand the result it computed. Since the stack is balanced the program does not crash; only the result comes out wrong. The rule is: a procedure preserves the registers it uses and does not preserve the result registers.
8.2.4.2Saving the counter with PUSH CX: code trace
The program below wants to print two lines on the screen. The main loop runs with CX = 2 and calls the procedure stars on every iteration. The procedure uses CX as the inner loop counter to print three # characters. The first and last instructions of the procedure preserve the caller's counter.
MOV CX, 2 ; main loop: 2 rows
row: CALL stars
LOOP row
RET
stars PROC
PUSH CX ; caller's counter
MOV CX, 3 ; inner counter
MOV AX, 0E23h ; AH = 0Eh, AL = '#'
inner: INT 10h
LOOP inner
POP CX ; counter back
RET
stars ENDPMOV AX, 0E23h fills two register halves with a single instruction. AH = 0Eh is the “teletype” function of the BIOS screen service (INT 10h): it writes the character in AL at the cursor position and advances the cursor. AL = 23h is the ASCII code of the character '#'. The LOOP instruction first decrements CX by 1 and then jumps to the label if CX ≠ 0. The inner loop therefore runs exactly three iterations.
| Line | Instruction | CX | SP | Stack (from the top) | Screen |
|---|---|---|---|---|---|
| 1 | MOV CX, 2 | 0002h | FFFEh | 0000h | |
| 2 | CALL stars | 0002h | FFFCh | 0106h, 0000h | |
| 6 | PUSH CX | 0002h | FFFAh | 0002h, 0106h, 0000h | |
| 7–8 | MOV CX, 3 · MOV AX, 0E23h | 0003h | FFFAh | 0002h, 0106h, 0000h | |
| 9–10 | inner loop, 3 iterations | 0000h | FFFAh | 0002h, 0106h, 0000h | ### |
| 11 | POP CX | 0002h | FFFCh | 0106h, 0000h | ### |
| 12 | RET | 0002h | FFFEh | 0000h | ### |
| 3 | LOOP row | 0001h | FFFEh | 0000h | ### |
| 2–12 | second call | 0001h | FFFEh | 0000h | ###### |
| 3 | LOOP row | 0000h | FFFEh | 0000h | ###### |
In the trace (Table 8.2.14) the journey of CX is clearly visible. The caller's counter (2) goes onto the stack with PUSH. The inner loop takes CX from 3 down to 0. POP CX brings back the caller's value. The main LOOP takes this value down to 1 and calls the procedure again for the second row. In the second call a 1 is pushed onto the stack and comes back. The last LOOP makes CX 0 and the loop ends. There are 6 characters on the screen.
At the deepest moment of the stack inside the procedure (during the inner loop), there are two words on the stack: the return address and the saved CX. SP = FFFAh. This layout also explains why the RET at the exit works correctly: after POP CX has taken the saved value, the return address is again on top.
Calling a procedure that uses CX from inside a LOOP-based loop without preserving CX. Without PUSH CX / POP CX the procedure would return with CX = 0. The LOOP in the main loop first decrements CX by 1: 0 − 1 = FFFFh. Since FFFFh is not zero, it jumps. Because every call makes CX 0 again, the loop never ends and characters are printed on the screen without stopping. The fix goes in one of two places: either PUSH CX / POP CX in the procedure, or PUSH CX / CALL stars / POP CX in the caller.
8.2.4.3Does the caller or the callee preserve?
The job of saving registers can be given to one of two places: the procedure itself (the callee preserves) or the code that calls it (the caller preserves). The strengths and weaknesses of the two approaches are in Table 8.2.15.
| Criterion | Callee preserves (PUSH/POP in the procedure) | Caller preserves (around the CALL) |
|---|---|---|
| Where is the code? | once in the procedure | at every call site |
| Unnecessary saving | saved even if the caller does not use that register | only the registers really needed |
| Risk of forgetting | low: written in one place | high: needed again at every call |
| Suited when | library procedures | the old value in the output register is needed |
An example of a case where the caller has to preserve is this. The procedure read_num returns the number it reads from the keyboard in CX. CX is its output, and the procedure cannot preserve it. The caller, however, uses CX as a loop counter. In this case saving the counter is the caller's job:
again: PUSH CX ; caller: counter
CALL read_num ; result in CX
ADD total, CX
POP CX ; counter back
LOOP againBetween PUSH CX and POP CX, CX carries two different meanings. First it is the number read, which is added to total; then it is the loop counter that comes back from the stack. The rule in practice combines the two approaches: a procedure preserves the registers it uses and does not preserve its output registers. If the old value in an output register is needed, the caller saves it.
8.2.4.4A single exit point: code trace
If a procedure that saves registers has more than one return path, a danger arises. If one of the paths skips the POPs and goes straight to RET, RET finds on top of the stack not the return address but a saved register value. That is why in procedures that PUSH, all paths merge at a single exit label where the POPs are.
ORG 100h
LEA SI, arr
MOV CX, 5
MOV AL, 7
CALL find ; CF = 1: found
RET
find PROC ; In: SI, CX, AL
PUSH CX
PUSH SI
XOR BX, BX ; Out: BX = index
scan: CMP [SI], AL
JE found
INC SI
INC BX
LOOP scan
CLC ; not found
JMP done
found: STC
done: POP SI ; single exit point
POP CX
RET
find ENDP
arr DB 3, 9, 7, 1, 4The find procedure searches for the value in AL among CX elements of the byte array SI points at. It returns the result in two ways: if CF = 1 the value was found and BX is its index. If CF = 0 the value is not in the array. During the search the procedure changes SI and CX. Both are inputs and the caller may want to use them on the next call, so they are preserved. BX, on the other hand, is an output and is not preserved. XOR BX, BX is the short way to clear a register (2 bytes).
The layout of the program is: LEA 3 bytes (0100h), MOV CX, 5 3 bytes (0103h), MOV AL, 7 2 bytes (0106h), CALL 3 bytes (0108h). The return address is 010Bh. The procedure starts at 010Ch and ends with the RET at 011Eh. The array is at 011Fh; this is the initial value of SI.
| Line | Instruction | SI | CX | BX | CF | SP | Stack (from the top) |
|---|---|---|---|---|---|---|---|
| 2–4 | LEA, MOV, MOV | 011Fh | 0005h | 0000h | 0 | FFFEh | 0000h |
| 5 | CALL find | 011Fh | 0005h | 0000h | 0 | FFFCh | 010Bh |
| 8–10 | PUSH CX, PUSH SI, XOR | 011Fh | 0005h | 0000h | 0 | FFF8h | 011Fh, 0005h, 010Bh |
| 11–15 | arr[0] = 3 ≠ 7 | 0120h | 0004h | 0001h | 1 | FFF8h | 011Fh, 0005h, 010Bh |
| 11–15 | arr[1] = 9 ≠ 7 | 0121h | 0003h | 0002h | 0 | FFF8h | 011Fh, 0005h, 010Bh |
| 11–12 | arr[2] = 7: ZF = 1, JE taken | 0121h | 0003h | 0002h | 0 | FFF8h | 011Fh, 0005h, 010Bh |
| 18 | found: STC | 0121h | 0003h | 0002h | 1 | FFF8h | 011Fh, 0005h, 010Bh |
| 19–20 | POP SI · POP CX | 011Fh | 0005h | 0002h | 1 | FFFCh | 010Bh |
| 21 | RET | 011Fh | 0005h | 0002h | 1 | FFFEh | 0000h |
It may be striking that the CF column of the table is 1 in the first iteration and then 0 (Table 8.2.16). The reason is CMP. CMP [SI], AL computes 3 − 7 and needs a borrow, so CF = 1. In the second iteration 9 − 7 needs no borrow, and CF = 0. LOOP and INC do not touch CF. The CF values during the search carry no meaning. What is meaningful is the value the procedure sets at the exit with STC or CLC.
The critical moment is the third iteration, where the value is found. JE jumps to found and the loop ends early. At that moment the top of the stack holds not the return address but the saved SI (011Fh) (Figure 8.2.15). found sets CF with STC and the flow moves on to the done label. The not-found path (CLC and JMP done) also arrives at the same label. Since both paths pass through POP SI and POP CX, RET finds 010Bh on top in every case.
Had the programmer used a direct RET at the target of JE, that is, written found: STC / RET, RET would have taken the 011Fh on top for the return address. The processor would have tried to execute the bytes 03h, 09h, 07h at address 011Fh, where the array begins, as instructions. The result would be unpredictable. The program would work correctly only when the search failed, and the error would show up only for some inputs.
8.2.5Parameters on the stack and the stack frame
8.2.5.1Passing parameters on the stack: code trace
Passing parameters in registers has two limits: there are few registers, and every procedure has to document separately which register carries what. Passing parameters on the stack overcomes both. The caller pushes the parameters onto the stack in order before CALL. The procedure reads them from their fixed places on the stack. The number of parameters is limited by the size of the stack, and the rule is the same for every procedure.
How does the procedure find the parameters? It cannot use SP: on the 8086 SP is not an addressing register, and MOV AX, [SP+4] is invalid. Besides, SP changes every time the procedure does a PUSH or POP; the offset of the same parameter would differ at different places in the procedure. The solution is the BP register. Addresses that include BP use the SS segment by default. On entry the procedure copies the value of SP into BP and thus sets up a fixed reference point on the stack.
ORG 100h
MOV AX, 7
PUSH AX ; 1st parameter
MOV AX, 3
PUSH AX ; 2nd parameter
CALL SUM2
ADD SP, 4 ; drop parameters
RET
SUM2 PROC
PUSH BP
MOV BP, SP
MOV AX, [BP+6] ; 1st parameter
ADD AX, [BP+4] ; 2nd parameter
POP BP
RET
SUM2 ENDPThe layout of the program explains the IP values in the trace table. The main program occupies 0100h–010Eh: MOV AX, 7 (3 bytes), PUSH AX (1), MOV AX, 3 (3), PUSH AX (1), CALL SUM2 (3, at 0108h), ADD SP, 4 (3, at 010Bh), and RET (1). SUM2 starts at 010Fh. PUSH BP is 1 byte, MOV BP, SP 2, the two instructions with memory operands 3 each, and POP BP and RET 1 each.
| Line | Instruction | AX | BP | SP | IP (next) | Written to the stack |
|---|---|---|---|---|---|---|
| 2 | MOV AX, 7 | 0007h | 0000h | FFFEh | 0103h | |
| 3 | PUSH AX | 0007h | 0000h | FFFCh | 0104h | [FFFCh] = 0007h |
| 4 | MOV AX, 3 | 0003h | 0000h | FFFCh | 0107h | |
| 5 | PUSH AX | 0003h | 0000h | FFFAh | 0108h | [FFFAh] = 0003h |
| 6 | CALL TOPLA | 0003h | 0000h | FFF8h | 010Fh | [FFF8h] = 010Bh |
| 10 | PUSH BP | 0003h | 0000h | FFF6h | 0110h | [FFF6h] = 0000h |
| 11 | MOV BP, SP | 0003h | FFF6h | FFF6h | 0112h | |
| 12 | MOV AX, [BP+6] | 0007h | FFF6h | FFF6h | 0115h | |
| 13 | ADD AX, [BP+4] | 000Ah | FFF6h | FFF6h | 0118h | |
| 14 | POP BP | 000Ah | 0000h | FFF8h | 0119h | |
| 15 | RET | 000Ah | 0000h | FFFAh | 010Bh | |
| 7 | ADD SP, 4 | 000Ah | 0000h | FFFEh | 010Eh | |
| 8 | RET (DOS'a) | 000Ah | 0000h | 0000h | 0000h |
The first five rows of Table 8.2.17 are the caller's preparation. The two PUSHes write 7 and 3 to the stack, and CALL puts the return address (010Bh) on top of them. When the procedure is entered, the stack, going up from SP, is: [FFF8h] the return address, [FFFAh] the second parameter (3), [FFFCh] the first parameter (7).
The first two instructions of the procedure, PUSH BP and MOV BP, SP, set up the frame. The caller's BP is saved on the stack, because the caller may also be using BP for its own frame. Then BP = SP = FFF6h. From this point on the offset of every parameter relative to BP is fixed:
[BP+0]= [FFF6h]: the saved old BP (0000h),[BP+2]= [FFF8h]: the return address (010Bh),[BP+4]= [FFFAh]: the parameter pushed last (3),[BP+6]= [FFFCh]: the parameter pushed first (7).
The offset of the parameters relative to BP stays the same however much SP changes inside the procedure. Even if the procedure pushes other registers in the meantime, [BP+6] is always the first parameter. MOV AX, [BP+6] computes the physical address as SS × 16 + BP + 6 = 07000h + FFFCh = 16FFCh. No segment prefix is needed, because addresses with BP use SS by default. Had the same address been computed with DS, it would still have come out right in a single-segment .COM program, but would be wrong in .EXE programs where DS ≠ SS.
MOV AX, [BP+6]: BP = FFF6h, the parameters at [BP+4] and [BP+6]. On the right, after the procedure's RET: SP = FFFAh, the parameters still on the stack.The exit is the reverse of the entry. POP BP brings back the caller's BP and SP = FFF8h; the return address is on top. RET returns to 010Bh and SP = FFFAh. At this point the two parameters are still on the stack (Figure 8.2.16). The caller's ADD SP, 4 instruction discards them: SP returns to its value before the PUSHes, FFFEh. The stack is balanced, and the main program's RET correctly finds 0000h. AX = 000Ah = 10 carries the result.
8.2.5.2Who discards the parameters? RET n
The parameters pushed onto the stack have to be discarded somewhere; otherwise every call leaves a few words on the stack. Either the caller or the procedure does this.
RET n is the return instruction that, after taking the return address from the stack and loading it into IP, additionally adds n to SP: IP ← [SP], SP ← SP + 2 + n. n is stored in the instruction as a 16-bit constant (C2 n16, 3 bytes) and is the number of parameter bytes.
Had the last instruction of the procedure SUM2 been RET 4, the caller would not have needed to write ADD SP, 4. While RET 4 runs, SP grows by 6 in all: 2 for the return address and 4 for the two parameters. SP returns to its value before the PUSHes (FFFEh) in a single instruction.
The difference between the two methods is who knows the number of parameters. In RET n the number is fixed inside the procedure. The procedure must always take the same number of parameters. Pascal compilers use this method. With ADD SP, n, on the other hand, the caller knows the number. The same procedure can take a different number of parameters in different calls. Functions of the C language that take a variable number of parameters, such as printf, therefore work with the method where the caller cleans up. Whichever method is chosen, the caller and the procedure must follow the same rule. If both clean up, 4 extra bytes are given back from the stack; if neither does, 4 bytes remain on the stack.
With SP = FFFEh the caller pushes three parameters and makes a near CALL. The procedure starts with PUSH BP and MOV BP, SP. What is BP, where is the first parameter pushed, and how should the procedure return?
- Pushes. Three parameters 6 bytes, CALL 2 bytes, PUSH BP 2 bytes: FFFEh − 10 = FFF4h. BP = FFF4h.
- Offsets. [BP] is the old BP, [BP+2] the return address, [BP+4] the parameter pushed last (the third), [BP+6] the second, and [BP+8] the parameter pushed first.
- Return. After POP BP,
RET 6: SP = FFF6h + 2 + 6 = FFFEh. The stack returns to its state before the call.
8.2.5.3The stack frame and local variables
While running, a procedure may need a place to keep its intermediate results. Registers may not suffice. Keeping intermediate results in global memory variables binds the procedure to those variables and, in a recursive call, makes every level corrupt the same variable. The right place is again the stack.
A stack frame is the region of the stack belonging to one procedure call: the parameters, the return address, the saved old BP, and the local variables. A local variable is a variable that occupies space on the stack only while the procedure runs. BP is the fixed reference point of the frame: parameters are at positive offsets above BP and local variables at negative offsets below it.
The instructions that build and tear down the frame follow the same pattern in every procedure:
PUSH BP
MOV BP, SP
SUB SP, 4 ; local space
MOV [BP-2], AX ; local 1
...
MOV SP, BP ; drop locals
POP BP
RET 4 ; drop 2 paramsSUB SP, 4 opens room for two words on the stack. Nothing is written to this area; SP is just pulled down. The procedure's later PUSHes and calls therefore do not overwrite the local area. The two local variables are at addresses [BP−2] and [BP−4] (Figure 8.2.17). The initial value of the opened area is whatever was left at that address before. Local variables must be given a value before they are used.
On exit MOV SP, BP gives the local area back in a single instruction. It does not matter how many local variables were opened; SP returns to its value at the moment BP was set up. POP BP and RET n follow. This order cannot be broken: a POP BP done without closing the local area loads a local variable into BP instead of the old BP.
The lifetime of a local variable is the lifetime of the call. After the procedure returns, those stack words are overwritten by the next PUSH or CALL. A procedure therefore must not return the address of its local variable as a result. If the same procedure calls itself, every call builds its own frame, and so its own local variables. The levels do not touch each other's variables.
On the 80186 and later processors there is a two-instruction shorthand for this pattern: ENTER builds the frame, and LEAVE does MOV SP, BP and POP BP together. The 8086 does not have these instructions.
8.2.5.4A frame with a local variable: code trace
The procedure below computes x·x + x from the value x in AX. Since MUL overwrites AX, a copy of x is kept in a local variable.
MOV AX, 9
CALL sq_plus ; AX = x·x + x
RET
sq_plus PROC
PUSH BP
MOV BP, SP
SUB SP, 2 ; local [BP-2]
MOV [BP-2], AX ; local = x
MUL AX ; AX = x·x
ADD AX, [BP-2] ; + x
MOV SP, BP ; drop local
POP BP
RET
sq_plus ENDP| Line | Instruction | AX | DX | BP | SP | Stack |
|---|---|---|---|---|---|---|
| 1 | MOV AX, 9 | 0009h | 0000h | 0000h | FFFEh | |
| 2 | CALL sq_plus | 0009h | 0000h | 0000h | FFFCh | [FFFCh] = 0106h |
| 5 | PUSH BP | 0009h | 0000h | 0000h | FFFAh | [FFFAh] = 0000h |
| 6 | MOV BP, SP | 0009h | 0000h | FFFAh | FFFAh | |
| 7 | SUB SP, 2 | 0009h | 0000h | FFFAh | FFF8h | [FFF8h] = local space |
| 8 | MOV [BP-2], AX | 0009h | 0000h | FFFAh | FFF8h | [FFF8h] = 0009h |
| 9 | MUL AX | 0051h | 0000h | FFFAh | FFF8h | |
| 10 | ADD AX, [BP-2] | 005Ah | 0000h | FFFAh | FFF8h | |
| 11 | MOV SP, BP | 005Ah | 0000h | FFFAh | FFFAh | local space released |
| 12 | POP BP | 005Ah | 0000h | 0000h | FFFCh | |
| 13 | RET | 005Ah | 0000h | 0000h | FFFEh | IP = 0106h |
In the trace (Table 8.2.18), after SUB SP, 2, BP = FFFAh and SP = FFF8h. The local variable is at [BP−2] = [FFF8h]; SP points at it and a later PUSH writes below it. MOV [BP-2], AX copies x = 9 into the local. The 16-bit MUL AX computes DX:AX ← AX × AX: 9 × 9 = 81 = 0051h, DX = 0000h. The x in AX is gone, but it sits in the local. ADD AX, [BP-2] gives 81 + 9 = 90 = 005Ah.
MOV SP, BP: SP = BP = FFFAh, the local area released.On exit three instructions tear down the frame in reverse order. MOV SP, BP pulls SP to FFFAh and the local area is released. 0009h is still written at [FFF8h], but it is now outside the stack. POP BP brings back the caller's BP (0000h). RET returns to 0106h. The result is AX = 90.
There is a gap in the documentation of this procedure. The 16-bit MUL always writes to DX too: for x = 9, DX = 0000h. The value the caller keeps in DX is therefore lost. In this trace the difference is not visible because DX is 0 anyway. When x ≥ 256, the product does not fit in 16 bits and DX takes a nonzero value. “Clobber: DX” should be written in the comment, or DX should be preserved in the procedure with PUSH/POP.
8.2.6Example programs
8.2.6.1Hello World: print_me
The first example is the procedure print_me, which prints a string terminated by zero on the screen character by character. The parameter is the address of the string and is passed in SI. The length of the string is not given separately; the procedure stops when it sees the zero byte. Strings in the C language are stored in this form too.
ORG 100h
LEA SI, msg ; SI = address of msg
CALL print_me
RET ; to DOS
print_me PROC
next_char:
CMP b.[SI], 0 ; zero?
JE stop ; yes: done
MOV AL, [SI] ; next ASCII char
MOV AH, 0Eh ; teletype function
INT 10h ; print AL
ADD SI, 1 ; next character
JMP next_char ; loop back
stop:
RET ; to caller
print_me ENDP
msg DB 'Hello World!', 0
ENDThe main program is three instructions. LEA SI, msg loads the address of the string into SI; this is the parameter of the procedure. CALL print_me calls the procedure, and RET ends the program. In the program layout, LEA is 3 bytes (BE 18 01), CALL is at 0103h, and the return address is 0106h. The procedure starts at 0107h and ends with the RET at 0117h. The string is at 0118h: 12 characters and a zero byte.
The first instruction of the procedure is CMP b.[SI], 0. b. is an emu8086 abbreviation of BYTE PTR. Had CMP [SI], 0 been written, the assembler could not know the size of the operation: [SI] can be a byte or a word, and the constant 0 does not indicate a size either. The size is therefore written explicitly. In MASM the same line is written as CMP BYTE PTR [SI], 0.
The loop executes six instructions per iteration: the comparison, the conditional jump, taking the character into AL, writing 0Eh to AH, INT 10h, and advancing SI; then JMP returns to the top. MOV AH, 0Eh could be moved out of the loop, but if it is not certain that INT 10h preserves AH, leaving it inside is safe.
| An | SI | AL | ZF | SP | Screen |
|---|---|---|---|---|---|
LEA SI, msg | msg+0 | — | 0 | FFFEh | |
CALL print_me | msg+0 | — | 0 | FFFCh | |
| iteration 1, CMP: 'H' ≠ 0 | msg+0 | — | 0 | FFFCh | |
| iteration 1, INT 10h | msg+0 | 48h | 0 | FFFCh | H |
| iteration 1, ADD SI, 1 | msg+1 | 48h | 0 | FFFCh | H |
| end of iteration 2 | msg+2 | 65h | 0 | FFFCh | He |
| end of iteration 5 | msg+5 | 6Fh | 0 | FFFCh | Hello |
| end of iteration 11 | msg+11 | 64h | 0 | FFFCh | Hello World |
| end of iteration 12 | msg+12 | 21h | 0 | FFFCh | Hello World! |
| CMP: [SI] = 0, JE stop | msg+12 | 21h | 1 | FFFCh | Hello World! |
the procedure's RET | msg+12 | 21h | 1 | FFFEh | Hello World! |
the main program's RET | msg+12 | 21h | 1 | 0000h | Hello World! |
The loop runs 12 iterations and prints one character in each (Table 8.2.19). The sixth character is a space (20h); a space is a character too and is printed on the screen. In the thirteenth comparison [SI] = 0, ZF = 1, and JE jumps to stop. The zero byte is not printed. Throughout the loop SP = FFFCh: the procedure pushes nothing, and the stack holds only the return address.
The procedure changes SI and does not preserve it. On return SI points at the zero byte at the end of the string (msg + 12 = 0124h). This is a side effect and “Clobber: SI, AX” should be written in the comment. The same procedure can be called for another text by changing only SI: LEA SI, other_msg / CALL print_me.
8.2.6.2Adding two variables
The second example is a procedure that finds its parameters and its result in memory variables.
ORG 100h
start:
CALL AddNumbers ; call it
RET ; to DOS
AddNumbers PROC
MOV AX, number1 ; AX = first number
ADD AX, number2 ; AX += second number
MOV result, AX ; store the result
RET ; end of procedure
AddNumbers ENDP
number1 DW 5 ; first number 5
number2 DW 3 ; second number 3
result DW ? ; holds the resultThe first instruction of the program is CALL at 0100h; the return address is 0103h. The procedure starts at 0104h. The instruction lengths differ from one another. MOV AX, number1 is 3 bytes with the short encoding special to AX (A1 + address). ADD AX, number2 is 4 bytes. MOV result, AX is 3 bytes, again with the AX-specific encoding. The variables are behind the procedure: number1 = 010Fh, number2 = 0111h, result = 0113h.
| Line | Instruction | AX | SP | ZF | CF | result |
|---|---|---|---|---|---|---|
| 3 | CALL AddNumbers | 0000h | FFFCh | 0 | 0 | ? |
| 6 | MOV AX, number1 | 0005h | FFFCh | 0 | 0 | ? |
| 7 | ADD AX, number2 | 0008h | FFFCh | 0 | 0 | ? |
| 8 | MOV result, AX | 0008h | FFFCh | 0 | 0 | 0008h |
| 9 | RET | 0008h | FFFEh | 0 | 0 | 0008h |
| 4 | RET (DOS'a) | 0008h | 0000h | 0 | 0 | 0008h |
Table 8.2.20 also shows the flags of ADD. 5 + 3 = 8 is not zero (ZF = 0) and produces no carry in 16 bits (CF = 0). MOV does not touch the flags. result is stored in memory as 08 00, in little-endian order. DW ? says the initial value is undefined. emu8086 puts 0 in this area, but the program must not rely on this value.
This procedure is short and clear, but it works only with number1, number2, and result. To add two other numbers, either those numbers have to be copied into these variables first or a new procedure has to be written. This is the weakness of passing parameters in memory variables.
8.2.6.3An array sum procedure
The third example adds the elements of an array. It takes two things as parameters: the address of the array (SI) and the number of elements (CX). It returns the result in AL. The procedure works with whichever array it is given the address of.
ORG 100h
LEA SI, vector ; param 1: address
MOV CX, 5 ; param 2: count
CALL sum
MOV m, AL ; result is in AL
RET
sum PROC ; In: SI, CX
MOV AL, 0 ; Out: AL = sum
again:
ADD AL, [SI]
INC SI
LOOP again
RET
sum ENDP
vector DB 5, 4, 5, 2, 1
m DB 0| Line | Instruction / iteration | SI | CX | AL | SP | m |
|---|---|---|---|---|---|---|
| 2–3 | LEA SI, vector · MOV CX, 5 | 0115h | 0005h | 00h | FFFEh | 00h |
| 4 | CALL sum | 0115h | 0005h | 00h | FFFCh | 00h |
| 8 | MOV AL, 0 | 0115h | 0005h | 00h | FFFCh | 00h |
| 10–12 | iteration 1: +5 | 0116h | 0004h | 05h | FFFCh | 00h |
| 10–12 | iteration 2: +4 | 0117h | 0003h | 09h | FFFCh | 00h |
| 10–12 | iteration 3: +5 | 0118h | 0002h | 0Eh | FFFCh | 00h |
| 10–12 | iteration 4: +2 | 0119h | 0001h | 10h | FFFCh | 00h |
| 10–12 | iteration 5: +1 | 011Ah | 0000h | 11h | FFFCh | 00h |
| 13 | RET | 011Ah | 0000h | 11h | FFFEh | 00h |
| 5 | MOV m, AL | 011Ah | 0000h | 11h | FFFEh | 11h |
The sum 5 + 4 + 5 + 2 + 1 = 17 = 11h (Table 8.2.21). After the last iteration SI = 011Ah and points at the variable m right behind the array. When LOOP brings CX down to 0 it is not taken and the flow moves on to RET. The caller writes the result in AL to m.
The two limits of the procedure should be written in its description. First, the sum is kept in the 8-bit AL. If the sum of the elements exceeds 255, the result overflows and only the low 8 bits remain. Second, the procedure changes SI and CX. On return SI points at the end of the array and CX is 0. The same procedure can be called for another array by changing only SI and CX.
8.2.6.4A parameter block
If a procedure has many parameters, registers do not suffice. One solution is to write the parameters in a block that sits one after another in memory and give the procedure only the address of the block. A single register carries as many parameters as wanted.
LEA BX, block
CALL calc ; result = a × b + c
RET
calc PROC ; In: BX = block address
PUSH AX
PUSH DX ; MUL writes DX too
MOV AX, [BX] ; a
MUL WORD PTR [BX+2] ; × b
ADD AX, [BX+4] ; + c
MOV [BX+6], AX ; result
POP DX
POP AX
RET
calc ENDP
block DW 12, 7, 5, ?The block consists of four words (Figure 8.2.19). The procedure reads each parameter at a fixed offset from BX: a at [BX], b at [BX+2], c at [BX+4]. It writes the result to the fourth word of the block, [BX+6]. In the line MUL WORD PTR [BX+2] the size is written explicitly; since MUL's only operand is in memory, the assembler cannot know the size any other way.
The computation goes like this: AX = 12, with MUL DX:AX = 12 × 7 = 84 = 0054h, with ADD AX = 84 + 5 = 89 = 0059h. The result is written to [BX+6]. When run in emu8086 the block starts at 0117h and the result is written to the bytes 011Dh–011Eh as 59 00. Although the procedure uses AX and DX, it preserves both, because it returns its result in memory, not in a register. On return AX and DX hold their values from before the call.
The same procedure is called with another block by changing only BX. The block layout, that is, which parameter sits at which offset, must be documented in the procedure's description. The file and program loading services of DOS use this method too: the caller prepares a parameter block and gives its address in a register.
8.2.6.5Testing a procedure
If a procedure is tried only with ordinary input, its hidden errors do not show up. Testing must cover boundary cases as well: the first and last element, a value that is not present, a one-element input, and an empty input. When the single-exit find procedure (array: 3, 9, 7, 1, 4) is run with these cases, the results in Table 8.2.22 are obtained.
| Case | AL | CX | CF | BX | Assessment |
|---|---|---|---|---|---|
| first element | 3 | 5 | 1 | 0 | correct |
| last element | 4 | 5 | 1 | 4 | correct |
| not in the array | 8 | 5 | 0 | 5 | correct; BX is meaningless, only CF is looked at |
| search in a one-element range | 9 | 1 | 0 | 1 | correct: 9 is the second element, outside the range searched |
| empty array | 7 | 0 | 1 | 2 | wrong: with CX = 0, LOOP goes around 65,536 times |
In all cases CX and SI are at their input values on return; the preservation works correctly. The error shows up only with the empty array. Its cause is how LOOP works: LOOP first decrements CX by 1 and then looks at whether it is zero. In a loop entered with CX = 0, the first LOOP makes CX 0 − 1 = FFFFh and jumps. The loop may go around 65,536 times. The procedure, which should have scanned no elements at all, starts scanning the bytes of the array and “finds” 7 at the third byte.
The fix is to test CX before entering the loop. The JCXZ (jump if CX zero) instruction jumps if CX = 0 and does not look at the flags:
find PROC
PUSH CX
PUSH SI
XOR BX, BX
JCXZ notfound ; empty array: leave without searching
scan: CMP [SI], AL
JE found
INC SI
INC BX
LOOP scan
notfound: CLC ; not found
JMP done
found: STC
done: POP SI
POP CX
RET
find ENDPThe corrected procedure returns CF = 0 and BX = 0 for CX = 0. When 7 is searched with CX = 5, it gives CF = 1, BX = 2 as before. Both results were obtained by running in emu8086. This example shows why testing is prepared as a list for every procedure: the error would not have shown up in any trial with ordinary input.
8.2.6.6Nested calls
A procedure can call another procedure. In this case the stack holds more than one return address at the same time. The LIFO structure of the stack automatically makes the returns happen in the right order: the one called last returns first.
| An | IP | SP | Stack (from the top) |
|---|---|---|---|
| main, before CALL A | 0100h | FFFEh | 0000h |
CALL A (0100h) | 0110h | FFFCh | 0103h, 0000h |
CALL B from inside A (0112h) | 0120h | FFFAh | 0115h, 0103h, 0000h |
B's RET | 0115h | FFFCh | 0103h, 0000h |
A's RET | 0103h | FFFEh | 0000h |
In the table (Table 8.2.23), B's RET takes the 0115h on top of the stack and returns to A. When A's job is done, its RET takes the 0103h one level below and returns to main. Each RET knows only the address on top; it is the structure of the stack that puts the right address on top. Procedures therefore do not have to know how many levels deep they are called.
The same layout can also be followed with a more concrete program. main calls A with AX = 1; A adds 2 to AX, calls B, then adds 4 to AX; B doubles AX. The sequence is 1 → 3 → 6 → 10 and the program ends with AX = 000Ah. At most two return addresses accumulate on the stack.
8.2.6.7Computing the stack need
In nested calls the stack grows by the bytes that accumulate along the deepest call chain. Knowing how much stack a program needs is necessary for reserving enough room for the stack and for preventing the stack from colliding with data or code.
The stack requirement of a program is the sum of the bytes that accumulate along the deepest path of the call tree. Each near CALL adds a 2-byte return address, each far CALL 4 bytes, each PUSH 2 bytes, and each local area its own size.
| Path | Computation | Bytes |
|---|---|---|
| main → A → B | 2 (CALL A) + 4 (PUSH AX, SI) + 2 (CALL B) + 2 (PUSH CX) | 10 |
| main → C | 2 (CALL C) + 6 (PUSH AX, BX, CX) | 8 |
The deepest path is main → A → B and it requires 10 bytes (Table 8.2.24). In a program that starts with SP = FFFEh, SP goes down at most to FFFEh − 10 = FFF4h. Since C saves three registers, it does more PUSHes than A, but its depth is smaller. A and C are never on the stack at the same time: when C is called, A's bytes have long been taken back. The requirement is therefore not the sum of the paths but the largest one.
A margin must be added to the computation. Hardware interrupts can arrive at any moment of the program, at the deepest moment of the stack as well. Each interrupt pushes 6 bytes onto the stack (FLAGS, CS, and IP), and the interrupt service routine adds its own saves. A margin is therefore always left above the computed value. In a .COM program the stack grows downward from the top of the segment, and code and data grow upward from the bottom. When the gap between them is used up, the stack overwrites the data. This is called stack overflow, and the processor does not report it.
8.2.7Recursion
8.2.7.1A procedure that calls itself
We have seen that a procedure can call another procedure. The same mechanism also lets a procedure call itself. For the processor it does not matter which procedure the target of CALL is; it pushes the return address and jumps.
Recursion is a procedure's calling itself, directly or through another procedure. Each call puts a new return address and its own saved values on the stack; the values of each level stay separate from one another. The case in which the procedure returns without calling itself again is called the base case (the stopping condition).
Recursion is a natural solution when the problem becomes smaller at each step and resembles itself. Printing a number in its decimal digits is a good example. To print 472 is to print 47 first and then '2'. To print 47 is to print 4 first and then '7'. 4 has a single digit; nothing else has to be printed to print it. This is the base case.
The base case is essential. A procedure with no base case calls itself forever. Each call adds at least 2 bytes to the stack. SP keeps decreasing, the stack grows down onto the data and code of the program, and the program crashes. Besides printing numbers, computing a factorial, walking a tree, and walking a directory are typical examples of recursion.
8.2.7.2Recursive number printing: code trace
ORG 100h
MOV AX, 472
CALL show
RET
show PROC ; In: AX (unsigned)
XOR DX, DX
MOV BX, 10
DIV BX ; AX = quot., DX = digit
PUSH DX
OR AX, AX ; more digits?
JZ done
CALL show ; upper digits first
done: POP AX
ADD AL, '0'
MOV AH, 0Eh
INT 10h
RET
show ENDPThe procedure prints the unsigned number in AX on the screen. The first three instructions divide the number by 10. The 16-bit DIV BX divides the 32-bit number in DX:AX, so DX is cleared first with XOR DX, DX. After the division AX = number / 10 and DX = number mod 10. The remainder is the last digit of the number and is saved on the stack with PUSH DX. OR AX, AX sets ZF without changing AX: if the quotient is zero there is no other digit to print and JZ jumps to the base case, done. If the quotient is not zero, the procedure calls itself to print the quotient. On the way back the four instructions at done take the saved digit, convert it to ASCII, and print it.
In the program layout the CALLs are in two places. The main program's CALL show is at 0103h and its return address is 0106h. The CALL show inside the procedure is at 0113h and its return address is 0116h, that is, the done label. When the procedure calls itself, the machine code of this CALL is E8 F1 FF: 0107h − 0116h = −0Fh = FFF1h. Since the target is behind, the displacement is negative.
| Line | Event | AX | DX | SP | Stack (from the top) | Screen |
|---|---|---|---|---|---|---|
| 2–3 | AX = 472, CALL show | 01D8h | 0000h | FFFCh | 0106h | |
| 6–9 | level 1: 472 / 10, PUSH DX | 002Fh | 0002h | FFFAh | 2, 0106h | |
| 10–12 | AX ≠ 0: CALL show | 002Fh | 0002h | FFF8h | 0116h, 2, 0106h | |
| 6–12 | level 2: 47 / 10, PUSH, CALL | 0004h | 0007h | FFF4h | 0116h, 7, 0116h, 2, 0106h | |
| 6–11 | level 3: 4 / 10, PUSH; AX = 0, JZ done | 0000h | 0004h | FFF2h | 4, 0116h, 7, 0116h, 2, 0106h | |
| 13–16 | POP AX = 4, print | 0E34h | 0004h | FFF4h | 0116h, 7, 0116h, 2, 0106h | 4 |
| 17, 13–16 | RET → 0116h; POP AX = 7, print | 0E37h | 0004h | FFF8h | 0116h, 2, 0106h | 47 |
| 17, 13–16 | RET → 0116h; POP AX = 2, print | 0E32h | 0004h | FFFCh | 0106h | 472 |
| 17 | last RET → 0106h | 0E32h | 0004h | FFFEh | 0000h | 472 |
The trace (Table 8.2.25) splits into two phases. In the descent phase the procedure separates one digit at each level and calls itself again. Two words are added to the stack at each level: the digit and the return address. But the digits are separated from last to first: first 2, then 7, then 4. At the third level the quotient becomes 0 and the base case is reached. At this moment SP is at its deepest point: FFF2h. The stack holds three digits and three return addresses (Figure 8.2.23).
In the ascent phase each level takes its own digit from the stack and prints it. The digit pushed last (4) comes out first. The digits are thus printed in the reverse of the order they were separated, that is, in the right order. The third level's RET returns to 0116h, to the done line of the second level. The second level prints 7, and its RET also returns to 0116h, this time to the first level. That the same return address appears twice on the stack is natural: both calls were made from the same CALL instruction. The first level prints 2, and the last RET returns to 0106h, to the main program. SP = FFFEh and the stack is balanced.
The last row of the trace is the state right after the outermost RET of the procedure: IP = 0106h, SP = FFFEh. Then the main program's RET takes 0000h and the program ends with SP = 0000h.
Since each level keeps its own digit on the stack, no extra variable or array was needed. The stack gave each of the levels a separate storage area. A loop-based solution also reverses the digits by pushing them onto the stack and then popping them; recursion does this job with the natural layout of CALL and RET.
What does the procedure print when called with AX = 0? How low does SP go at most?
- Division. 0 / 10: AX = 0, DX = 0. The digit 0 is pushed onto the stack.
- Base case. AX = 0, JZ jumps to
done; no new call is made. - Printing. POP AX = 0, ADD AL, '0' → 30h; '0' is printed on the screen.
- Stack. The main program's CALL (2 bytes) and one digit (2 bytes): SP goes down at most to FFFEh − 4 = FFFAh.
Because the base case check is made after the division, the number 0 is also printed as '0' without any extra code.
8.2.7.3Recursion or a loop?
The same job can be done with a loop too: the number is divided by 10 repeatedly, the digits are pushed onto the stack and counted with a counter; a second loop pops the digits and prints them. The comparison of the two solutions is in Table 8.2.26.
| Criterion | Recursion (show) | Loop (division + LOOP) |
|---|---|---|
| Code | short; close to the definition of the problem | needs a counter and a separate printing loop |
| Stack | return address + digit at each level: 4 bytes | 2 bytes per digit |
| Time | CALL + RET at each level (19 + 8 cycles) | no call overhead |
| Risk | if the depth grows without bound, the stack overflows | stack use is limited |
How deep does the stack get at most if the show procedure is called with 65,535, the largest 16-bit unsigned number?
- Number of levels. The number of levels equals the number of digits: 65,535 has five digits, so five levels.
- Bytes. Each level adds a return address (2 bytes) and a digit (2 bytes): 5 × 2 + 5 × 2 = 20 bytes.
- SP. FFFEh − 20 = FFFEh − 14h = FFEAh.
- Time. Five CALLs and five RETs: 5 × (19 + 8) = 135 cycles, 27 µs of call overhead at 5 MHz.
The depth of this procedure is limited to 5, because AX carries at most five digits. When run with 65,535 in emu8086, the smallest value of SP is FFEAh.
The place of the base case matters too. The check must be made before the new CALL. In show the division comes first, then the quotient is checked for zero, and only if it is not zero is the CALL made. Had the check been put after the CALL, no condition would have been tied to the CALL and the procedure would call itself without stopping.
8.2.8Common mistakes
8.2.8.1An unbalanced stack: code trace
Most procedure errors have the same root: when RET executes, the return address is not on top of the stack. The most common cause is a forgotten POP for a PUSH.
ORG 100h
MOV AX, 1234h ; 0100h: B8 34 12
CALL bad ; 0103h: ret = 0106h
RET ; 0106h
bad PROC
PUSH AX ; AX saved...
; ... work ...
RET ; forgot POP AX!
bad ENDP| Line | Instruction | AX | IP (next) | SP | Stack (from the top) |
|---|---|---|---|---|---|
| 2 | MOV AX, 1234h | 1234h | 0103h | FFFEh | 0000h |
| 3 | CALL bad | 1234h | 0107h | FFFCh | 0106h, 0000h |
| 6 | PUSH AX | 1234h | 0108h | FFFAh | 1234h, 0106h, 0000h |
| 8 | RET | 1234h | 1234h | FFFCh | 0106h, 0000h |
RET takes whatever is on top of the stack for the return address (Table 8.2.27). On top is the saved value of AX, 1234h. After RET, IP = 1234h. The processor starts executing the bytes at address CS:1234h as instructions. There is no program code at that address; whatever was left in memory gets executed. The program crashes or behaves unpredictably. The real return address, 0106h, stays on the stack, at the place SP = FFFCh points at, never used.
The rule is: when leaving a procedure, SP must equal its value at entry. Every PUSH must have a POP in reverse order, and on every path of the procedure at that. The error is easier to make as the code between PUSH and RET gets longer and branches multiply. That is why a single exit point is recommended.
8.2.8.2Type mismatch: code trace
The second typical error is a mismatch between the type of the call and the type of the return. In the program below the procedure farp ends with RETF but is called with a near CALL.
ORG 100h
MOV AX, 5
CALL farp ; near CALL: IP only
ADD AX, 1
RET
farp PROC
SHL AX, 1
RETF ; pops IP and CS!
farp ENDP| Line | Instruction | AX | CS:IP (next) | SP | Stack (from the top) |
|---|---|---|---|---|---|
| 2 | MOV AX, 5 | 0005h | 0700:0103 | FFFEh | 0000h |
| 3 | CALL farp | 0005h | 0700:010A | FFFCh | 0106h, 0000h |
| 7 | SHL AX, 1 | 000Ah | 0700:010C | FFFCh | 0106h, 0000h |
| 8 | RETF | 000Ah | 0000:0106 | 0000h | empty |
A near CALL pushes only IP (0106h) onto the stack. RETF, however, pops two words. The first becomes IP: 0106h, which is right. The second becomes CS. Since CS is not on the stack, RETF takes the word one below, the 0000h that DOS pushed for the .COM program. SP grows by 4 and becomes 0000h. The processor jumps to address 0000:0106h (Table 8.2.28).
The physical address 0000:0106h is 00106h. This address is inside the interrupt vector table (00000h–003FFh); the vector of type 41h is in the bytes 00104h–00107h. There is not program code there but the addresses of interrupt routines. The processor takes these bytes for instructions and executes them, and the program crashes. ADD AX, 1 never runs. In the opposite mismatch, that is, when a procedure called with CALL FAR ends with a near RET, CS is left on the stack and the return is again wrong.
8.2.8.3List of mistakes
The most frequent mistakes in procedures are collected in Table 8.2.29. They are mistakes that most assemblers cannot catch and that show up only at run time.
| Mistake | What happens? | Remedy |
|---|---|---|
| Forgetting RET | The processor does not see ENDP; the code or data after the procedure is executed. | Every path of every procedure ends with RET. |
| PUSH / POP imbalance | RET takes a wrong value into IP. | Every PUSH has a POP in reverse order. |
| Falling into a procedure | A procedure in the middle of the main code is executed without being CALLed; its RET at the end ends the program. | Procedures are written after the main program's RET or jumped over with JMP. |
| JMP instead of CALL | JMP pushes no return address; RET returns to an unrelated value on the stack. | A procedure is entered only with CALL. |
| Name mismatch | p1 PROC … p2 ENDP: assembler error. | The same name at the start and at the end. |
| Early RET | A conditional RET after a PUSH takes the saved value for the return address. | All paths go to a single exit label. |
| MOV instead of LEA | MOV SI, arr loads not the address but the first word of the array; the procedure reads from an unrelated address. | For addresses, LEA or MOV SI, OFFSET arr. |
| DX destroyed silently | The 16-bit MUL and DIV write DX too; the caller's DX is erased. | Write “Clobber: DX” in the comment, or PUSH/POP DX. |
| Type mismatch | Near CALL + RETF or CALL FAR + RET: the stack is off by 2 bytes. | Type on the PROC line; always RET for the return. |
| Disturbing the flag | After STC/CLC, an instruction such as ADD or CMP changes CF. | The instruction that sets the flag is the last flag-changing instruction before RET. |
| Preserving the result register | PUSH AX / POP AX erases the result in AX. | Output registers are not preserved. |
| Infinite recursion | If there is no stopping condition, or it is checked after the CALL, each call takes 2 bytes of space and the stack overflows. | The base case is checked before the CALL. |
Using JMP instead of a procedure call. In the program below JMP add has been written instead of CALL add:
ORG 100h
MOV AX, 1
JMP add
MOV BX, 9 ; does it run?
RET
add PROC
ADD AX, 5
RET
add ENDPJMP pushes nothing onto the stack. The RET of add takes DOS's 0000h on top of the stack, and the program silently ends there, with AX = 6. MOV BX, 9 never runs. Since the program does not crash, the error may go unnoticed. Had there been another value on the stack, RET would have returned to a random address.
8.2.9Exercises and solutions
The six exercises from the slides are solved here with intermediate steps.
1. A CALL p at address 0120h calls p at 0100h. What is its machine code? What is pushed onto the stack?
CALL is 3 bytes; the next instruction is at 0123h. Displacement = 0100h − 0123h = −23h. In 16-bit two's complement −23h = FFDDh. The low byte is written first: E8 DD FF. 0123h is pushed onto the stack as the return address. Check: 0123h + FFDDh = 10100h, reduced to 16 bits 0100h.
2. In the m2 example, what would the final AX be if MOV AL, 3 were added before the second CALL m2?
The first call gives AX = 1 × 2 = 0002h. The added instruction makes AL 3; AH stays 00h. The second call gives AX = 3 × 2 = 0006h. This time the first parameter of the second call does not depend on the result of the first call. Since the added instruction is 2 bytes, the address of the second CALL and its return address shift by 2 bytes, but the result does not change.
3. With SP = FFFEh, 3 CALLs are made in a row (no RET at all). What is SP?
Each near CALL pushes 2 bytes onto the stack: FFFEh − 3 × 2 = FFFEh − 6 = FFF8h. There are three return addresses on the stack. Had the calls been far, each would have pushed 4 bytes and SP would be FFF2h.
4. Why is it wrong to call a procedure that destroys CX from inside a LOOP? Propose two fixes.
LOOP keeps its counter in CX. If the procedure changes CX, on return LOOP decrements the value the procedure left instead of the caller's counter. The loop runs the wrong number of times; if the procedure leaves CX = 0, LOOP makes it FFFFh and the loop almost never ends. The first fix is for the procedure to do PUSH CX on entry and POP CX on exit. The second fix is for the caller to write PUSH CX / CALL / POP CX around the CALL. If CX is the output of the procedure, only the second fix is applicable.
5. Write a procedure upper that converts the lowercase letter in AL to uppercase (input/output AL).
upper PROC ; In/Out: AL
cmp al, 'a'
jb done ; below 'a': leave it
cmp al, 'z'
ja done ; above 'z': leave it
sub al, 20h ; 'a' (61h) → 'A' (41h)
done: ret
upper ENDPIn the ASCII table there is a constant difference of 20h between lowercase and uppercase letters. The procedure changes only characters in the range 'a'–'z'; JB and JA are unsigned comparisons. Since it uses no other register, no PUSH/POP is needed. Tried with the characters 'a', 'Z', '{', and '`', the results are 'A', 'Z', '{', and '`'; the characters on both sides of the range do not change.
6. Change print_me so that it returns the number of characters it printed in CX.
MOV CX, 0 is added at the start of the procedure and INC CX next to the ADD SI, 1 in the loop. Since CX is an output, it is not preserved. For 'Hello World!' CX = 12 on return. INC CX changes the flags, but since the CMP at the top of the loop sets ZF again on every iteration, the result is not affected.
8.2.10Summary
- A procedure is a piece of code that performs a specific task, is called with CALL, and returns with RET to right behind the call. The code is written once and called from many places.
- PROC / ENDP and END are directives; they produce no machine code. CALL and RET are processor instructions. Procedures are written after the main program's RET; otherwise the flow falls into the procedure.
- CALL pushes the address of the next instruction onto the stack (SP − 2) and changes IP to the target. A near direct CALL stores the target as a relative displacement: rel16 = target − (address of CALL + 3).
- RET: IP ← [SP], SP + 2. In a .COM program the final RET takes the 0000h pushed by DOS, and the INT 20h in the PSP ends the program.
- A far CALL pushes CS first and then IP (4 bytes); RETF pops IP first and then CS. The type of the call and of the return must match. An indirect CALL takes the target from a register or memory; it is the basis of jump tables.
- Call overhead: CALL 19, RET 8, PUSH 11, POP 8 cycles. The overhead of a procedure that saves two registers is 65 cycles (13 µs at 5 MHz). For very short and frequent jobs a macro is more suitable.
- Parameters are passed in registers, in memory variables, by address (SI/DI/BX), or on the stack. In passing by value a copy is given, in passing by address a location. The result returns in a register, in CF, or in memory.
- Preserving registers: a procedure saves the registers it uses with PUSH and POPs them in reverse order; output registers are not preserved. All paths of a procedure that does PUSH merge at a single exit point.
- The stack frame:
PUSH BP·MOV BP, SP·SUB SP, n. Parameters are at [BP+4], [BP+6]…, local variables at [BP−2], [BP−4]… Exit:MOV SP, BP·POP BP·RET n. - Recursion: a procedure calls itself; each level keeps its own return address and values on the stack. The base case is checked before the CALL. The stack requirement is computed from the deepest call path and a margin is left for interrupts.
- Most errors have their root in the return address not being on top of the stack at the moment of RET: a forgotten POP, an early RET, JMP instead of CALL, a type mismatch.
8.2.11Key terms
- procedure (subroutine)
- procedure call
- return address
- directive
- label
- stack
- stack pointer (SP)
- base pointer (BP)
- push / pop (PUSH / POP)
- LIFO (last in, first out)
- parameter passing
- pass by value / by reference
- register preservation
- stack frame
- local variable
- recursion
- stack overflow / underflow
- offset
- segment
- flag
- little-endian
8.2.12Test Yourself
A
CALL pat address 0150h calls p at 0180h. What are the bytes of the instruction, and what value is pushed onto the stack?Answer
The next instruction is at 0153h. Displacement 0180h − 0153h = 002Dh:
E8 2D 00. 0153h is pushed onto the stack.With SP = FFFEh, the caller pushes two parameters and makes a near CALL. The procedure starts with
PUSH BP,MOV BP, SP,SUB SP, 4. What are BP and SP? At which addresses are the first parameter pushed and the two local variables?Answer
Two parameters (4 bytes), CALL (2), and PUSH BP (2): BP = FFFEh − 8 = FFF6h. After SUB SP, 4, SP = FFF2h. The first parameter is at [BP+6] = FFFCh and the second at [BP+4] = FFFAh. The locals are at [BP−2] = FFF4h and [BP−4] = FFF2h. After
MOV SP, BP,POP BP, andRET 4, SP = FFFEh.A procedure called with AX = 1111h and BX = 2222h executes
PUSH AX,PUSH BX,MOV AX, 0,MOV BX, 0,POP AX,POP BX,RET. What are AX and BX on return? Does RET return to the right address?Answer
The value of BX (2222h) is on top of the stack; the first POP takes it into AX. AX = 2222h and BX = 1111h: the two registers have exchanged places. Since the numbers of PUSHes and POPs are equal, the stack is balanced and RET returns correctly. The error shows up only in the register values.
A procedure that returns its result in CF executes
STC, thenOR AX, AX,POP CX, andRET. What CF does the caller find?Answer
CF = 0. OR is a logic instruction and always clears CF and OF. The value set by STC is lost. POP and RET do not touch the flags; the instruction that sets the flag must be the last flag-changing instruction before RET.
A
CALL FAR PTR fpat 0700:0103 calls the FAR procedure at 0700:0109. How many bytes is the instruction? If SP = FFFEh, what is written to the stack? With which code is the procedure's RET produced?Answer
A far direct CALL is 5 bytes:
9A 09 01 00 07(offset first, then segment). The return address is 0103h + 5 = 0108h. First CS is pushed: [FFFCh] = 0700h; then IP: [FFFAh] = 0108h. SP = FFFAh. The RET in the FAR procedure is encoded as CB (RETF), and on return SP = FFFEh.main calls P; P pushes AX, BX, and CX and calls Q; Q does
PUSH BPandSUB SP, 4. If the program starts with SP = FFFEh, how low does SP go at most? If a margin is left for one interrupt, down to what address must room be reserved?Answer
2 (CALL P) + 6 (three PUSHes) + 2 (CALL Q) + 2 (PUSH BP) + 4 (local area) = 16 bytes. SP goes down at most to FFFEh − 10h = FFEEh. An interrupt pushes 6 bytes more: FFE8h. The interrupt routine's own saves are added to the account as well.
The recursive
showprocedure is called with AX = 1000. What appears on the screen? How low does SP go at most?Answer
1000 appears on the screen; zeros are digits too. 1000 has four digits, four levels: 4 × (2 + 2) = 16 bytes. SP goes down at most to FFFEh − 16 = FFEEh.
The variable
ais at address 0110h and holds 0005h. A programmer writesMOV SI, ainstead ofLEA SI, ato pass by address. What is SI? What does the procedure reach when it reads from[SI]?Answer
MOV SI, aloads the contents of the variable: SI = 0005h. The procedure reads from DS:0005h, that is, in a .COM program from inside the PSP. The value read has nothing to do witha. If the procedure writes, it corrupts the PSP. The assembler does not catch this error, because both instructions are valid.The
sq_plusprocedure with a local variable (x·x + x) is called with AX = 300. What are AX and DX on return? Is the result correct?Answer
300 × 300 = 90,000 = 15F90h. The 16-bit MUL gives DX = 0001h, AX = 5F90h; CF = OF = 1. ADD AX, [BP−2]: 5F90h + 012Ch = 60BCh. On return AX = 60BCh and DX = 0001h. The correct result is 90,300 = 160BCh and does not fit in 16 bits. Since the procedure looks only at AX, the result is wrong; moreover the caller's DX has been corrupted.
8.2.13Further reading
- Intel, The 8086 Family User's Manual (1979): the operation definitions, machine codes, and clock cycle counts of the CALL, RET, PUSH, and POP instructions. The values in Table 8.2.8 are from this source.
- B. B. Brey, The Intel Microprocessors (8th ed.), the “Procedures” section: near and far procedures, the forms of CALL and RET, passing parameters on the stack.
- K. R. Irvine, Assembly Language for x86 Processors (7th ed.), the “Procedures” chapter: stack frames, local variables, recursion, and calling conventions with detailed examples.
- emu8086 documentation, 8086 Assembler Tutorial for Beginners, Part 8 “Procedures”: writing procedures in emu8086 and the print_me example.
8.2.14References
- emu8086 documentation: 8086 Assembler Tutorial for Beginners (Part 8: Procedures).
- Intel, The 8086 Family User's Manual, 1979: CALL, RET, and stack operations.
- B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009: Section 6.3 “Procedures”.
- K. R. Irvine, Assembly Language for x86 Processors, 7th ed., Pearson, 2014: Chapter 5 “Procedures”.
Related pages: Chapter 8.2 slides · © Sercan Külcü. All rights reserved.