Microprocessors · Lecture Notes
Chapter 9.2: The emu8086.inc Library
Almost every program written in assembly prints something to the screen, reads something from the keyboard or shows a number in decimal. Each of these jobs takes several BIOS and DOS services called in the right order. emu8086 collects these frequently needed jobs in a ready-made library called emu8086.inc. These notes begin by showing how the library is brought into a program with the INCLUDE directive and what determines the size of the program. They then treat the screen macros (PUTC, GOTOXY, PRINT, PRINTN, CURSOROFF, CURSORON) together with their expansions. Next come the procedures used with DEFINE_ and CALL: PRINT_STRING and PTHIS, which print strings, GET_STRING, which reads a string from the keyboard, CLEAR_SCREEN, which clears the screen, SCAN_NUM, which reads a number, and PRINT_NUM and PRINT_NUM_UNS, which print one. The logic of each procedure is traced register by register with a plain equivalent code. The last sections are given to example programs that put all the parts together and to the mistakes most often made when using the library.
Learning outcomes
- Explain the INCLUDE directive
- Explain that a library file is added to the source as text during assembly, which folders the assembler searches for the file, and that program size is determined only by the macros that are used and the procedures that are defined.
- Use the screen macros
- Show which BIOS service and which instruction sequence the macros PUTC, GOTOXY, PRINT, PRINTN, CURSOROFF and CURSORON expand to; work out the cursor position, the end of line and screen scrolling in advance.
- Define and call procedures correctly
- Add procedures to the program with the DEFINE_ macros, call them with CALL, know the input and output registers of each procedure, and say which registers are preserved.
- Trace the string and number procedures
- Trace the logic of PRINT_STRING, PTHIS, GET_STRING, SCAN_NUM, PRINT_NUM and PRINT_NUM_UNS step by step at the level of registers, stack and buffer; explain the difference between the signed and unsigned interpretations.
- Write example programs
- Write programs that read numbers, compute, print the result and arrange the screen using the library's macros and procedures; recognize the common mistakes.
9.2.1The library and INCLUDE
9.2.1.1A library of common functions
Even printing a single character on the 8086 takes several instructions. The character goes in AL, the service number in AH, and the BIOS screen interrupt INT 10h is called. In the process the old value of AX is destroyed; if the value is needed it must be pushed on the stack first and popped afterwards. Printing a number in decimal is longer still: the number is divided by 10, the remainders become digits, the digits are converted to ASCII codes and printed in the right order. Reading a multi-digit number from the keyboard is the same job in reverse. These patterns are needed again in almost every program. Rewriting them every time is both a waste of time and a source of bugs.
emu8086 solves this with a library. The emu8086.inc file that comes with the installation contains ready-made macros and procedures for screen, keyboard and number handling. The programmer adds this file at the top of the source and uses the functions in it by name. The library brings no new capability: everything in it is built from BIOS and DOS interrupts, that is, from instructions the programmer could have written too. The gain is the reuse of tested code.
A library is a source file that contains ready-made macros and procedures and is used by being added to other programs. The library of emu8086 is the file emu8086.inc; the extension inc shows that it is an include file.
One limit of the library should be known from the start. emu8086.inc is specific to the emu8086 environment. Another assembler such as MASM or TASM does not recognize this file, and the library's macros may not be fully compatible with the macro language of those assemblers. The code inside, however, consists of ordinary 8086 instructions. Understanding how the library works therefore also teaches how to write code that does the same job in other environments. For this purpose the trace sections of these notes show the logic of each procedure with a plain equivalent code.
9.2.1.2The INCLUDE directive
Definitions in another file are brought into the source with the INCLUDE directive. For emu8086.inc the line is:
include 'emu8086.inc'INCLUDE is the directive that tells the assembler to put the text of the named file in place of this line. The directive produces no processor instruction; its job is finished during assembly. A running program contains no instruction called "INCLUDE".
The file name may be written with or without quotes: include 'emu8086.inc' and include emu8086.inc do the same job. Letter case does not matter either. The assembler searches for the file in two places (Figure 9.2.1). First it looks in the folder of the source file being assembled. If the file is not there, it looks in the Inc folder of the emu8086 installation. Because emu8086.inc is placed in this folder by the installation, in most programs it is found in the second step. If the programmer writes a library of their own and puts it in the same folder as the source, it is found in the first step. If a file with the same name also exists in the source folder, the one in the source folder wins.
The position of the directive matters too. A macro can be used only after its definition; the assembler reads the source from top to bottom and, if it meets a macro name whose definition it has not seen, takes it for an instruction and reports an error. The include line is therefore written at the very beginning of the source, before ORG 100h. Since the line itself produces no bytes, putting it first does not change the program's addresses.
Writing the include line at the end of the program, right before END. When the assembler reaches a line such as PUTC 'A' it has not yet seen the definition of PUTC and reports an unknown-instruction error. The definitions of macros must come before their uses.
9.2.1.3The source after INCLUDE
The easiest way to see what INCLUDE does is to think about the source the assembler sees. The assembler deletes the include line and puts the whole text of emu8086.inc in its place. It then assembles the resulting single piece of source. A simplified picture looks like this:
; in place of the include line:
PUTC MACRO char ; template: 0 bytes
...
ENDM
GOTOXY MACRO col, row
...
ENDM
DEFINE_SCAN_NUM MACRO
... ; procedure template
ENDM
; the program itself:
ORG 100h
PUTC 'A' ; 8 bytes here
RETThree conclusions follow from this picture. First, most of the library consists of MACRO … ENDM blocks. A macro definition is only a template; the assembler notes it down somewhere but produces no bytes for it. A macro that is never used adds not a single byte to the program. Second, code is generated where the macro is used. In the program above, the line PUTC 'A', once expanded, produces a sequence of five instructions and 8 bytes. The whole program consists of these 8 bytes plus the 1 byte of RET: 9 bytes.
The third conclusion concerns procedures. The procedures in the library are also stored not directly as code but inside macros. For example, the whole code of the SCAN_NUM procedure is the body of a macro called DEFINE_SCAN_NUM. If the program does not write the DEFINE_SCAN_NUM line, the macro is never expanded and the code of SCAN_NUM does not enter the program. Thus including the whole library does not enlarge the program. Program size is determined by only two things: every use of the macros that are used, and the procedures defined with DEFINE_.
| In the source | Code produced | When? |
|---|---|---|
include 'emu8086.inc' | none | definitions are only read |
macro use (PUTC 'A') | the macro's body, with the parameters substituted | again at every use |
DEFINE_SCAN_NUM | the whole code of the procedure | once, at the place of the line |
CALL scan_num | a 3-byte CALL instruction | at every call |
Nothing called "emu8086.inc" is left inside the running program. In memory there are only expanded macro instructions and defined procedures. In emu8086's memory window or disassembler, PUSH, MOV, INT and POP instructions are seen where PUTC was. This matters for debugging: when single-stepping, one macro line corresponds to several instruction steps.
9.2.1.4What is in the library?
The contents of emu8086.inc fall into two groups (Table 9.2.2, Table 9.2.3). Macros are written directly by name. Procedures are first defined with a DEFINE_ macro and then called with CALL.
| Macro | Task | In the background |
|---|---|---|
PUTC char | writes a single character where the cursor is | INT 10h, AH = 0Eh |
GOTOXY col, row | moves the cursor to the given column and row | INT 10h, AH = 02h |
PRINT string | prints a string | character by character with 0Eh |
PRINTN string | prints a string, then moves to a new line | character by character with 0Eh; 13, 10 at the end |
CURSOROFF | hides the cursor | INT 10h, AH = 01h |
CURSORON | shows the cursor | INT 10h, AH = 01h |
| Procedure | Task | Definition line |
|---|---|---|
PRINT_STRING | prints the zero-terminated string at DS:SI | DEFINE_PRINT_STRING |
PTHIS | prints the string right after the CALL | DEFINE_PTHIS |
GET_STRING | reads a string from the keyboard | DEFINE_GET_STRING |
CLEAR_SCREEN | clears the screen | DEFINE_CLEAR_SCREEN |
SCAN_NUM | reads a signed number from the keyboard into CX | DEFINE_SCAN_NUM |
PRINT_NUM | prints AX as a signed number | DEFINE_PRINT_NUM + DEFINE_PRINT_NUM_UNS |
PRINT_NUM_UNS | prints AX as an unsigned number | DEFINE_PRINT_NUM_UNS |
The difference between the two groups is the basic difference between a macro and a procedure. A macro is copied to every place where it is used; it suits short, frequent jobs. The code of a procedure exists once in memory and every use goes there with CALL; it suits long jobs. The library makes this distinction sensibly. PUTC is 8 bytes, and the cost of a CALL and RET would be close to the job itself; that is why it is a macro. SCAN_NUM, on the other hand, is hundreds of bytes of code that checks the minus sign, backspace and overflow. Copying it at every use would swell the program quickly; that is why it is a procedure.
The time of a procedure call can be computed too. On the 8086 a direct CALL within the same segment takes 19 clock cycles and a near RET 8. On a 5 MHz 8086 one cycle is 200 ns, so the cost of calling and returning is 27 × 200 ns = 5.4 µs. An INT 10h that writes a character, however, runs hundreds of instructions inside the BIOS. For screen and keyboard jobs the time of CALL/RET is therefore negligible; what really decides is the space taken in memory.
9.2.2Screen macros
9.2.2.1The text screen, the cursor and BIOS services
The output window of emu8086 imitates the standard text screen of the PC. The screen consists of 80 columns and 25 rows. Each cell holds one character. The position of a cell is given as a (column, row) pair: the top-left corner is (0, 0) and the bottom-right corner is (79, 24). Counting starts at zero; "column 10" is therefore the eleventh cell from the left.
The cursor is the position on the screen where the next character will be written. The BIOS keeps the cursor's column and row in its own data area. The services that write characters put the character in the cell where the cursor is and advance the cursor one position to the right.
Behind the screen there is a region of memory. In colour text mode the memory of the video card starts at segment B800h in the processor's address space. Each cell holds two bytes: the ASCII code of the character and an attribute byte that determines its colour. The video card reads this memory tens of times a second and draws it on the screen. The most direct way to put a character on the screen is to write to this memory with MOV. For the processor this is an ordinary memory write bus cycle; a physical address such as B8xxxh appears on the address bus and the character code on the data bus.
The library's macros do not write to this memory directly; they use the BIOS screen services. The INT 10h instruction takes the processor to a BIOS routine in the ROM on the motherboard. The routine decides what to do by looking at the service number in AH. The BIOS takes care of details such as advancing the cursor, moving to the next line at the end of a line, and scrolling the screen on the last row. The three services the library uses are in Table 9.2.4.
| AH | Service | Inputs | Used by |
|---|---|---|---|
| 01h | set the cursor shape | CH = start, CL = end scan line | CURSOROFF, CURSORON |
| 02h | set the cursor position | BH = page, DH = row, DL = column | GOTOXY |
| 0Eh | write a character and advance the cursor (teletype) | AL = character | PUTC, PRINT, PRINTN |
The name of the 0Eh service comes from old typewriter-telegraph machines. Like those machines, the service writes the character and advances the paper, that is, the cursor. It also interprets control characters as such a machine would: 13 takes the cursor to the start of the line, 10 to the next line, 8 moves it one position left and 7 makes a sound. This feature explains most of the behavior of the screen macros.
9.2.2.2What do PUTC and GOTOXY expand to?
PUTC takes a single parameter: the character to print. The parameter may be a constant (PUTC 65), a character constant (PUTC 'B') or an 8-bit register or variable (PUTC AL). When expanding the macro, the assembler puts this text where the parameter is written. PUTC 'A' expands to these five instructions:
PUSH AX ; save AX
MOV AL, 'A' ; the parameter
MOV AH, 0Eh ; teletype
INT 10h
POP AX ; restore AXThe instructions do the following in order. PUSH AX decreases SP by 2 and writes the current value of AX to the stack. MOV AL, 'A' puts 41h in AL and does not touch AH. MOV AH, 0Eh puts the service number in AH; AX = 0E41h now. INT 10h pushes the flags, CS and IP on the stack and passes to the BIOS. The BIOS writes 'A' to the cell where the cursor is, moves the cursor one position to the right and returns with IRET. POP AX restores the old value from the stack into AX and increases SP by 2. On leaving the macro, AX, SP and the flags are back to their values at entry. The calling code does not notice that AX changed temporarily.
The size of the expansion is computed from the machine codes: PUSH AX 1 byte (50h), MOV AL, 41h 2 bytes (B0 41), MOV AH, 0Eh 2 bytes (B4 0E), INT 10h 2 bytes (CD 10), POP AX 1 byte (58h). The total is 8 bytes.
GOTOXY takes two parameters: the column first, then the row. GOTOXY 10, 5 expands like this:
PUSH AX
PUSH BX
PUSH DX
MOV AH, 02h ; set cursor position
MOV DH, 5 ; row
MOV DL, 10 ; column
MOV BH, 0 ; page 0
INT 10h
POP DX
POP BX
POP AXThe macro uses AH, BH, DH and DL; that is why it saves AX, BX and DX. The POPs are done in the reverse order of the PUSHes: DX, the last one pushed, is restored first. The expansion is 16 bytes: three PUSHes and three POPs take 6 bytes, four MOV r8, constant take 8 bytes, and INT 10h takes 2 bytes. BH = 0 selects the first display page of the text mode. The memory of a colour text card has room for several screen pages; emu8086 programs always use page 0.
The order of the parameters is the point most often confused. The macro uses the mathematical (x, y) order: the horizontal position (column) first, then the vertical position (row). The BIOS, however, expects the row in DH and the column in DL. The macro does this conversion itself: it puts the second parameter in DH and the first in DL.
Writing GOTOXY 5, 10 and expecting the cursor to go to row 5. The macro takes 5 as the column and 10 as the row; the cursor goes to column 5 of row 10. A similar trap is to keep the position in AH: in the expansion of GOTOXY AL, AH, MOV AH, 02h runs first and then MOV DH, AH writes 2 as the row. For example with AL = 20 and AH = 7 the cursor goes not to row 7 but to row 2, to position (20, 2). The position must first be moved into registers the macro does not use.
9.2.2.3PRINT and PRINTN
PRINT prints a string. Its parameter is a constant text given in quotes in the source: PRINT 'Hello World!'. The macro embeds this text in the code and prints it character by character with service 0Eh. The expansion of PRINT in emu8086.inc has the following structure (the local label names are simplified):
PUSH AX
PUSH SI
JMP skip ; jump over the string
str DB 'Hello World!', 0
skip:
LEA SI, str
next:
MOV AL, CS:[SI] ; read the character from the code segment
CMP AL, 0
JZ done
INC SI
MOV AH, 0Eh
INT 10h
JMP next
done:
POP SI
POP AXThe most interesting aspect of the expansion is the position of the string. The string sits in the middle of the code, and a JMP jumps over it so that the processor does not take it for instructions. The labels specific to the macro get unique names at every expansion through the LOCAL directive; when PRINT is used a second time there is no label clash. Because the string is inside the code, it is in the code segment, and the characters are read with CS:[SI]. In a .COM program CS = DS, so the prefix makes no difference; but thanks to the prefix the macro also works correctly when DS points to another segment.
The expansion saves SI and AX. Its size depends on the length of the string: for a string of n characters, n + 1 bytes of data and 23 bytes of code, 24 + n bytes in all. PRINT 'Hello World!' takes 36 bytes for its 12 characters. The loop code is copied again at every use of PRINT.
PRINTN does the same job and merely appends the bytes 13 and 10 to the end of the string. The macro defines the string as DB 'text', 13, 10, 0. 13 (CR, carriage return) takes the cursor to column 0 of the line and 10 (LF, line feed) takes it one line down. Together they move to a new line (Figure 9.2.2). PRINT 'a' followed by PRINT 'b' leaves ab on the screen. PRINTN 'a' followed by PRINT 'b', however, writes a on one line and b at the start of the next line. The expansion of PRINTN is 2 bytes longer than that of PRINT.
The parameter of PRINT must be a constant text known at assembly time. Because the macro embeds the text in the code, it cannot print a string that is created at run time, for example a name read from the keyboard. When PRINT name is written, the assembler produces the line DB name, 0. This line tries to define the address of the variable name as a byte; the result is either an error or a meaningless byte. Strings created at run time are printed with PRINT_STRING.
9.2.2.4Example: a screen with macros
The first example in emu8086's library documentation uses three macros together:
include emu8086.inc
ORG 100h
PRINT 'Hello World!'
GOTOXY 10, 5
PUTC 65 ; 65 - is an ASCII code for 'A'
PUTC 'B'
RET ; return to operating system.
END ; directive to stop the compiler.The first two lines produce no code. include adds the macro definitions, and ORG 100h tells the assembler that the program starts at offset 0100h. In .COM programs the first 256 bytes (0000h–00FFh) are reserved for DOS's program segment prefix (PSP), so the code starts at 0100h. When the program starts the screen is empty and the cursor is at (0, 0).
PRINT 'Hello World!' writes 12 characters to columns 0–11 of row 0. Because the BIOS moves the cursor one position right after each character, the cursor ends at (12, 0). GOTOXY 10, 5 moves the cursor to column 10, row 5; it writes nothing to the screen. PUTC 65 uses the number as a character code: 65 = 41h, which is 'A' in ASCII. 'A' is written to cell (10, 5) and the cursor moves on to (11, 5). PUTC 'B' does the same job with a character constant; the assembler converts 'B' to 42h. 'B' is written to (11, 5) and the cursor moves on to (12, 5). RET ends the program. The END directive only tells the assembler that the source is over; it produces no code.
| Line | Cursor (column, row) | Written to the screen | Explanation |
|---|---|---|---|
include emu8086.inc | (0, 0) | — | the macro definitions are added, no code |
ORG 100h | (0, 0) | — | the .COM program starts at 0100h |
PRINT 'Hello World!' | (12, 0) | Hello World! (columns 0–11, row 0) | 12 characters |
GOTOXY 10, 5 | (10, 5) | — | only the cursor moves |
PUTC 65 | (11, 5) | A into cell (10, 5) | 65 = 41h = 'A' |
PUTC 'B' | (12, 5) | B into cell (11, 5) | character constant |
RET | (12, 5) | — | return to DOS |
The machine code of the program runs from 0100h to 0144h. The 36-byte PRINT expansion occupies 0100h–0123h, the 16-byte GOTOXY expansion 0124h–0133h and the two PUTC expansions 0134h–0143h; RET is at 0144h. Although eight lines show in the source, the processor runs 35 different instructions. Because the PRINT loop runs 12 times, the number of instructions executed exceeds a hundred.
9.2.2.5CURSOROFF and CURSORON
The cursor on the text screen is a small line that the video card makes blink. The height of the line is given in scan lines of the character cell. In colour text mode a character cell is 8 or 16 scan lines high; the cursor normally covers a line or two at the bottom of the cell. Service 01h of INT 10h sets the shape of the cursor: CH is the start and CL the end scan line.
Bit 5 of CH has a special meaning. If this bit is set to 1, the cursor is not drawn on the screen at all. CURSOROFF in the library writes 28h to CH: 28h = 0010 1000b, and its bit 5 is 1. CURSORON loads a normal shape with bit 5 equal to 0 through the same service. Both macros save and restore AX and CX.
PRINTN 'Full name:' ; print, then go to the next line
CURSOROFF
GOTOXY 30, 12
PRINT 'Welcome'
CURSORONIn this fragment "Full name:" is printed first and the cursor moves to the start of the next line. CURSOROFF hides the cursor. GOTOXY moves the cursor to (30, 12) and "Welcome" is written to columns 30–36. During this the blinking cursor does not wander over the screen. CURSORON makes the cursor visible again; the cursor is at (37, 12). Hiding the cursor changes only the display; the cursor's position is still kept in the BIOS and the writing services keep advancing it. On game and menu screens the blinking cursor is hidden because it distracts.
9.2.2.6Control characters
The first 32 codes of the ASCII table do not correspond to a printable shape. These codes are called control characters. Service 0Eh interprets four of them like a typewriter (Table 9.2.6). When PUTC is used with these codes it writes no shape on the screen but steers the cursor.
| Code | Name | Effect |
|---|---|---|
| 07h | BEL (bell) | a short beep from the speaker; the cursor does not move |
| 08h | BS (backspace) | the cursor moves one position left; it does not erase the character; no effect at column 0 |
| 0Ah | LF (line feed) | the cursor moves down one line, the column is unchanged; on the last row the screen scrolls up one line |
| 0Dh | CR (carriage return) | the cursor returns to column 0 of the same line; the text on the line stays in place |
A new line is therefore written with two characters: CR first, then LF. The 13, 10 pair that PRINTN appends is the combination of these two movements. Even with the order reversed (10, 13) the cursor ends up in the same place: it first moves down one line and then returns to the start of that line. This is why the line ending in DOS and Windows text files is the CR LF pair.
To erase a character from the screen, BS alone is not enough; it moves the cursor left but the character stays. Erasing is done in three steps. PUTC 8 moves the cursor left. PUTC ' ' writes a space over the character and moves the cursor right again. The second PUTC 8 brings the cursor back to the emptied cell. The library's procedures that handle the backspace key fix the screen with this triple.
9.2.2.7CR and LF separately: a code trace
To see what CR and LF do separately, the program below uses INT 10h without macros. AH = 0Eh is loaded once; since the BIOS does not change AH in service 0Eh, it stays valid for the later calls too.
ORG 100h
MOV AH, 0Eh ; teletype
MOV AL, 'a'
INT 10h
MOV AL, 'b'
INT 10h
MOV AL, 10 ; LF only
INT 10h
MOV AL, 'c'
INT 10h
MOV AL, 13 ; CR only
INT 10h
MOV AL, 'd'
INT 10h
RET| Instructions | AL | Cursor (column, row) | Screen |
|---|---|---|---|
MOV AH, 0Eh / MOV AL, 'a' / INT 10h | 61h | (1, 0) | a |
MOV AL, 'b' / INT 10h | 62h | (2, 0) | ab |
MOV AL, 10 / INT 10h | 0Ah | (2, 1) | ab |
MOV AL, 'c' / INT 10h | 63h | (3, 1) | ab / ··c |
MOV AL, 13 / INT 10h | 0Dh | (0, 1) | ab / ··c |
MOV AL, 'd' / INT 10h | 64h | (1, 1) | ab / d·c |
In the table "/" marks a line break and "·" an empty cell. When only LF is sent, the cursor moves down a line but stays in column 2; 'c' is written to column 2 of the next line, and the lines drift like a staircase. When only CR is sent, the cursor returns to the start of the same line; the 'c' on the line is not erased. 'd' is written to column 0, and the screen shows "d c" under "ab" (Figure 9.2.4). A proper new line needs both codes together.
INT 10h/0Eh changes no register except AX; in this program AH also stays 0Eh throughout the calls. This behavior is a documented feature of the BIOS, but it must not be generalized to other services. Some INT 10h services change AX, others BP. That the library macros save AX at every use is therefore a safe habit.
9.2.2.8End of line and screen scrolling
After service 0Eh writes a character to column 79, it moves the cursor to the start of the next line by itself. This is how PRINT continues a long string without cutting it off. If the cursor is on the last row (24) and has to move to the next line, the BIOS scrolls the whole screen up one line. The top row disappears, an empty row appears at the bottom and the cursor moves to this new row. Scrolling is the copying of the lower 24 rows of video memory up by one row.
GOTOXY 75, 24 is followed by PRINT 'Welcome'. Let us find where the text ends up on the screen and the final position of the cursor.
- The cursor is at (75, 24). "W", "e", "l", "c", "o" are written to columns 75, 76, 77, 78 and 79 in turn.
- After writing to column 79 the cursor must move to the next row. Since the cursor is on the last row, the screen scrolls up one line. "Welco" moves up to row 23; row 24 is emptied and the cursor comes to (0, 24).
- "m" and "e" are written to columns 0 and 1 of row 24. The cursor stays at (2, 24).
In the end "Welco" is in columns 75–79 of row 23, "me" at the start of row 24, and the cursor is at (2, 24) (Figure 9.2.5).
GOTOXY and PUTC do not check positions. For a call such as GOTOXY 85, 3 the BIOS's behavior is not defined; the cursor may go somewhere invisible and later writes appear in unexpected places. The programmer must keep positions within 0–79 (column) and 0–24 (row).
9.2.2.9GOTOXY and video memory
A chosen cell on the screen can be described in three different ways: with the macro call (GOTOXY 10, 5), with the register values that go to the BIOS (AH = 02h, DH = 5, DL = 10, BH = 0), and with the cell's address in video memory. The last is useful for understanding what happens inside the BIOS.
In video memory the cells are laid out row by row, from left to right. Since each cell takes two bytes, the offset of the (column, row) cell is computed as follows:
offset = (row × 80 + column) × 2
The byte at an even address is the ASCII code of the character, and the byte at an odd address is the attribute byte. For GOTOXY 10, 5 followed by PUTC 'A' the computation is: (5 × 80 + 10) × 2 = 410 × 2 = 820 = 0334h. 'A' (41h) is written to B800:0334h and the attribute byte (07h, light gray on black) to B800:0335h. The physical address is B8000h + 0334h = B8334h. For the bottom-right corner of the screen, (79, 24), the offset is (24 × 80 + 79) × 2 = 3998 = 0F9Eh. A page of 80 × 25 cells takes 4000 bytes.
Knowing these addresses also makes it possible to do what the macros do by writing to memory directly. For example, the sequence MOV AX, 0B800h, MOV ES, AX, MOV BYTE PTR ES:[0334h], 'A' writes 'A' to the same cell. The difference is that the cursor does not advance and the screen does not scroll: direct writing leaves all the details the BIOS takes care of to the programmer. The library macros are slower but do not require thinking about these details.
9.2.2.10Printing two digits: a code trace
That PUTC preserves AX may look like a small detail. The example below shows why this detail is useful. The program prints a number from 0 to 99 in AL as two decimal digits. The AAM instruction is used to separate the digits. In the code the expansions of two PUTCs are written out explicitly instead of as macros:
ORG 100h
MOV AL, 58
AAM ; AH = 5, AL = 8
ADD AX, 3030h ; '5', '8'
PUSH AX ; PUTC AH expansion
MOV AL, AH
MOV AH, 0Eh
INT 10h
POP AX ; AX restored: 3538h
PUSH AX ; PUTC AL expansion
MOV AL, AL
MOV AH, 0Eh
INT 10h
POP AX
RETAAM (ASCII adjust after multiply) divides AL by 10: it writes the quotient to AH and the remainder to AL. For a number from 0 to 99, the tens digit is left in AH and the units digit in AL. SF, ZF and PF are set according to AL. On the 8086, AAM takes 83 clock cycles.
MOV AL, 58 puts 58 = 3Ah in AL. AAM divides 58 by 10: AH = 5, AL = 8, that is, AX = 0508h. Since only AL is divided, the number must be in the range 0–99; from 100 on, the quotient is no longer a single digit. ADD AX, 3030h adds 30h to both bytes at once. Adding 30h to a digit converts it to an ASCII digit: 5 + 30h = 35h = '5', 8 + 30h = 38h = '8'. No carry arises between the two bytes in the addition, because 08h + 30h = 38h fits in 8 bits.
The first expansion prints the tens digit. PUSH AX puts 3538h on the stack, SP = FFFCh. MOV AL, AH copies '5' to AL and MOV AH, 0Eh loads the service number; AX = 0E35h. The units digit has been erased from the register. INT 10h prints 5 on the screen. POP AX brings back 3538h; '8' is in AL again. The second expansion prints the units digit with the same pattern. MOV AL, AL changes nothing but is harmless; the macro produces this instruction when the parameter is AL.
| Instruction(s) | AH | AL | SP | [FFFCh] | Screen |
|---|---|---|---|---|---|
MOV AL, 58 | 00h | 3Ah | FFFEh | — | |
AAM | 05h | 08h | FFFEh | — | |
ADD AX, 3030h | 35h | 38h | FFFEh | — | |
PUSH AX | 35h | 38h | FFFCh | 3538h | |
MOV AL, AH / MOV AH, 0Eh / INT 10h | 0Eh | 35h | FFFCh | 3538h | 5 |
POP AX | 35h | 38h | FFFEh | — | 5 |
| second expansion (5 instructions) | 35h | 38h | FFFEh | — | 58 |
At the end of the program 58 is on the screen and AX is again 3538h (Table 9.2.8). Because PUTC preserves AX, the two digits could be printed one after the other without being copied to a separate register. Had the macro not preserved AX, the first PUTC would have erased '8' and the programmer would have had to move the units digit into another register beforehand. Written with macros in the source, the same program contains only the lines PUTC AH and PUTC AL.
9.2.3Using the procedures
9.2.3.1DEFINE_ and CALL
Using a procedure from the library takes two steps. First the procedure is defined once: for this, the macro whose name starts with DEFINE_ is written. Then the procedure is called with CALL wherever the program needs it. A typical skeleton looks like this:
include 'emu8086.inc'
ORG 100h
...
CALL print_num ; use
...
RET
DEFINE_PRINT_NUM ; define
DEFINE_PRINT_NUM_UNS
ENDA DEFINE_ macro is a macro whose body carries the entire code of a library procedure. Where the macro is expanded, it places the procedure as a PROC … ENDP block. Each procedure is defined at most once in a program; if it is defined twice, the same label is created twice and the assembler reports an error.
The place where the macro is expanded is the procedure's place in memory. In the source the DEFINE_ lines are usually written between the main program's final RET and the END directive (Figure 9.2.6). In memory the main code comes first, then the RET, then the code of the procedures. The processor runs the main code from top to bottom, returns to DOS with the RET, and enters the code of the procedures only through CALL.
This layout is the usual one but not the only safe place. Every DEFINE_ macro in emu8086.inc contains a guard: at the start of the body there is a JMP that jumps over the procedure. The structure of DEFINE_SCAN_NUM is roughly this:
JMP skip_proc_scan_num ; keep the flow out of the body
SCAN_NUM PROC NEAR
... ; the procedure's code
RET
SCAN_NUM ENDP
skip_proc_scan_num:Even if a DEFINE_ line is written by mistake right below ORG 100h, the program works correctly. The first instruction the processor runs is this JMP, which jumps past the body to the start of the main program. The price is an extra JMP instruction in the program. Still, collecting the DEFINE_ lines between RET and END keeps the program readable and avoids needless jumps.
Procedure names are written in lowercase in the source: CALL print_num, CALL scan_num. emu8086 does not distinguish case in labels; CALL PRINT_NUM goes to the same label. Lowercase is the notation used in the documentation, and it visually separates the procedure name from the macro name (DEFINE_PRINT_NUM).
If a procedure calls another procedure, the two must be defined together. After printing the sign of the number, PRINT_NUM has PRINT_NUM_UNS print the absolute value. If only DEFINE_PRINT_NUM is written, the assembler cannot find the label at the line CALL PRINT_NUM_UNS inside PRINT_NUM and reports an undefined-label error. The reverse causes no error: PRINT_NUM_UNS can be defined alone.
Writing CALL scan_num and forgetting DEFINE_SCAN_NUM. That the library has been included does not mean the procedure is defined; unless the macro is expanded, the label scan_num does not exist. emu8086 reports an "undefined" error for this label during assembly.
The memory cost of a macro and a procedure can be compared with a concrete example. Suppose a program prints ten different messages. With PRINT every message carries its own loop code: every expansion holds 23 bytes of code plus the bytes of the message. With PRINT_STRING the loop exists once in memory; for each message only a 3-byte LEA SI, msg and a 3-byte CALL print_string are added. With ten seven-character messages the program takes about 310 bytes using PRINT and about 160 bytes using PRINT_STRING. The price of the saving is time: every call spends an extra 27 clock cycles on CALL and RET.
9.2.3.2Input and output registers
A procedure receives its parameters in registers and returns its result in a register. What each register means is written in the procedure's documentation, and the programmer must follow it (Table 9.2.9).
| Procedure | Input | Output | Details |
|---|---|---|---|
| PRINT_STRING | DS:SI = address of the string | — | the string must end with 0 |
| PTHIS | the string right after the CALL | — | advances the return address itself |
| GET_STRING | DS:DI = buffer, DX = size | a 0-terminated string in the buffer | at most DX − 1 characters |
| CLEAR_SCREEN | — | — | the cursor goes to (0, 0) |
| SCAN_NUM | keyboard | CX (signed) | the old value in CX is lost |
| PRINT_NUM | AX (signed) | — | PRINT_NUM_UNS must be defined too |
| PRINT_NUM_UNS | AX (unsigned) | — | 0 … 65,535 |
The library's procedures push the other registers they use on the stack on entry and pop them on exit. For example GET_STRING saves AX, CX, DI and DX, and SCAN_NUM saves DX, AX and SI. The only register that changes for the calling program is the output register. The flags, however, are not preserved: the CMP and arithmetic instructions inside the procedure change them. A flag set before a CALL must not be relied on after the CALL.
The output register has a consequence too. Because SCAN_NUM writes its result to CX, the old value in CX is lost. A program that keeps a loop counter in CX must save the counter itself before calling SCAN_NUM:
MOV CX, 3 ; three numbers to read
again: PUSH CX ; save the counter
CALL scan_num ; CX = the number read
MOV AX, CX
ADD BX, AX ; add to the sum
POP CX ; restore the counter
LOOP againWithout the PUSH CX, LOOP would use the number the user entered as the counter. If the user enters 0, LOOP decrements CX to FFFFh and the loop runs another 65,535 times.
9.2.3.3PRINT_STRING and PTHIS
The library has two procedures that print strings. Both print a string marked at its end with a 0 byte; they differ in where they get the string's address.
A null-terminated string is a string that ends with a byte of value 0 after its characters. The length is not stored separately; the code that reads the string stops when it sees the 0 byte. Strings in the C language have this form too.
PRINT_STRING takes the string's address from DS:SI. Its use takes two instructions:
LEA SI, msg
CALL print_string
...
msg DB 'Hello', 0LEA SI, msg loads the offset of msg into SI. emu8086 assembles this LEA with a direct address to the same 3-byte code as MOV SI, OFFSET msg (BE ll hh); in real MASM the same instruction is 4 bytes. The procedure saves AX and SI, then reads the bytes that SI points to in turn. If a byte is not 0 it is printed with service 0Eh and SI is incremented. When 0 is read, SI and AX are restored and the procedure returns. The string sits in the program's data area; the same string can be printed again in different places of the program.
PTHIS takes its name from the English phrase print this. It takes the string's address not from a register but from the stack. The string is written right after the CALL instruction:
CALL pthis
DB 'Hello', 0
; execution continues hereThe PRINT macro copies its loop code at every use; PRINT_STRING and PTHIS print any number of strings with a single copy of code. PTHIS's advantage over PRINT_STRING is convenience: there is no need to name the string and define it in a separate data area.
9.2.3.4Ways to print a string
With the library there are four ways to print a string on the screen (Table 9.2.10). The fourth is a DOS service outside the library but is included in the table for comparison.
| Method | Where is the string? | Terminator | Address | Suitable when |
|---|---|---|---|---|
PRINT 'text' | inside the code (macro expansion) | 0 (added by the macro) | the macro takes it itself (CS:SI) | a constant message printed once |
| PRINT_STRING | in the data area | 0 | DS:SI | a string printed in several places or created at run time |
| PTHIS | right after the CALL | 0 | the return address on the stack | many short constant messages |
| INT 21h, AH = 09h | in the data area | '$' | DS:DX | a DOS program without the library |
The terminator itself cannot be printed. In a string ending in '$' the '$' character, and in a string ending in 0 the 0 byte, counts as the end of the string. In a program that prints prices, the message "100 $" cannot be printed with INT 21h/09h; the message ends before the '$'. The same message prints without trouble with PRINT_STRING.
The buffer must match the method too. The buffer that GET_STRING fills ends with 0 and is printed directly with PRINT_STRING. If the same buffer is printed with INT 21h/09h, DOS looks for '$'. Because there is no '$' in the buffer, DOS dumps the bytes beyond the buffer onto the screen as well and continues until it meets the first '$'. Meaningless characters appear on the screen.
9.2.3.5How does PTHIS work?
PTHIS relies on knowing what CALL pushes on the stack. CALL pushes the address of the instruction after it, that is, the return address, on the stack and jumps to the procedure. The processor does not check whether there is an instruction at the "next instruction"; it merely adds the length of the CALL to IP. If a string sits right after the CALL, the pushed address is the address of the string's first byte. PTHIS uses this address as the address of the string.
The procedure does four things (Figure 9.2.7). First it takes the return address from the stack into SI with POP SI. Then it reads and prints the bytes SI points to until a 0; SI increases after every read. When 0 is read, SI points one past the 0 byte: this address is the first instruction after the string. The procedure puts this address back on the stack with PUSH SI. Finally RET takes the new address on the stack into IP. The processor skips the string and continues from the instruction after it; the string's bytes are never mistaken for instructions and executed.
The PTHIS in the library also preserves the caller's SI and AX. AX is pushed on the stack. SI cannot be pushed, because the return address sits on top of the stack and has to be taken first. The procedure therefore stores the old value of SI in a 2-byte variable in the code segment (CS:temp1) and restores it from there at the end. Since the string's bytes are also in the code segment, they are read with CS:[SI].
Tracing with addresses makes the mechanism concrete. In the example program that reads and prints a number, CALL pthis is at 010Bh and is 3 bytes long. After it comes a 21-byte string starting at 010Eh: 13, 10, "You have entered: " and 0. The string occupies 010Eh–0122h; CALL print_num is at 0123h.
| Moment | SP | Top of stack | SI | Explanation |
|---|---|---|---|---|
before CALL pthis | FFFEh | 0000h | msg1 | IP = 010Bh |
after CALL pthis | FFFCh | 010Eh | msg1 | return address = the string's first byte |
after POP SI | FFFEh | 0000h | 010Eh | the old SI is in CS:temp1 |
| when 0 is read | FFFEh | 0000h | 0123h | 21 bytes read, 20 characters printed |
after PUSH SI | FFFCh | 0123h | 0123h | the new return address |
after RET | FFFEh | 0000h | msg1 | IP = 0123h: CALL print_num |
The "0000h" in the table is the word DOS puts on the stack when a .COM program starts (Table 9.2.11). In the library version AX is also pushed after the POP SI, so the stack's inner state is one word deeper than shown in the table; the table shows only the steps concerning the return address.
The same idea exists in the PRINT macro: PRINT also embeds the data in the code. The difference is that PRINT jumps over the data with a JMP, whereas PTHIS changes the address RET will return to. Changing the return address is a powerful but dangerous technique. If the string is not terminated with 0, PTHIS also prints the instruction bytes after the string and returns to a random place where it finds a 0; the program may hang.
9.2.3.6GET_STRING and CLEAR_SCREEN
GET_STRING reads a line of text from the user. The characters read are written to the memory area that DS:DI points to. This area is called a buffer; the programmer reserves it beforehand with a definition such as DB n DUP(0). DX is the size of the buffer in bytes. Because the procedure puts a 0 at the end of the string, it accepts at most DX − 1 characters. Reading ends when the user presses Enter.
CLEAR_SCREEN clears the screen and takes the cursor to the top-left corner, (0, 0). It has no input or output register. The procedure first fills the whole screen with blank lines using service 06h of INT 10h (scroll window up), then moves the cursor to (0, 0) with service 02h. It reads the number of rows and columns of the screen from the BIOS data area: the byte at 0040:0084h holds the number of rows minus one, and the word at 0040:004Ah the number of columns. For this it sets DS temporarily to 0040h; it saves DS and the other registers it uses on the stack.
LEA DI, buf ; buffer
MOV DX, 20 ; size
CALL get_string
CALL clear_screen
LEA SI, buf
CALL print_string
RET
buf DB 20 DUP(0)This program reads a name of at most 19 characters, clears the screen and prints the name in the top-left corner. Because GET_STRING ends the buffer with 0, the same buffer is given to PRINT_STRING without any conversion. For the three procedures the program uses, the lines DEFINE_GET_STRING, DEFINE_CLEAR_SCREEN and DEFINE_PRINT_STRING must be added after the RET.
9.2.3.7The logic of GET_STRING: a code trace
The GET_STRING in the library is long because it also handles backspace and a full buffer. The essence of the reading loop can be traced with the plain equivalent below. The buffer is 4 bytes and the user will type "Ece".
LEA DI, buf ; buffer address
MOV DX, 4 ; buffer size
get_key: CMP DX, 1 ; keep 1 byte for the 0
JBE done
MOV AH, 01h
INT 21h ; AL = key (echoed)
CMP AL, 13 ; Enter?
JE done
MOV [DI], AL ; store in the buffer
INC DI
DEC DX
JMP get_key
done: MOV BYTE PTR [DI], 0
RET
buf DB 4 DUP(?)The program starts at 0100h. LEA DI, buf is 3 bytes, MOV DX, 4 3 and CMP DX, 1 3; the rest of the loop, MOV BYTE PTR [DI], 0 and RET end at 011Ch. The buffer starts at 011Dh: buf+0 = 011Dh, buf+3 = 0120h.
The CMP DX, 1 / JBE done pair at the start of the loop checks the remaining room. DX is the number of bytes left. If DX ≤ 1, only the final 0 has room and reading ends. JBE makes an unsigned comparison; it also jumps when DX is 0. Service 01h of INT 21h waits for a key, writes the key's ASCII code to AL and echoes the character to the screen. If it is not Enter (13), the character is written to the buffer, DI advances and the remaining room DX decreases by one.
| Step | AL | DI | DX | ZF | Buffer (buf+0…3) | Screen |
|---|---|---|---|---|---|---|
LEA DI, ad / MOV DX, 4 | 00h | 011Dh | 0004h | 0 | ? ? ? ? | |
CMP DX, 1 / JBE (4 > 1, no jump) | 00h | 011Dh | 0004h | 0 | ? ? ? ? | |
INT 21h ('E'), CMP AL, 13 | 45h | 011Dh | 0004h | 0 | ? ? ? ? | E |
MOV [DI], AL / INC DI / DEC DX | 45h | 011Eh | 0003h | 0 | E ? ? ? | E |
| 2nd pass ('c') | 63h | 011Fh | 0002h | 0 | E c ? ? | Ec |
| 3rd pass ('e') | 65h | 0120h | 0001h | 0 | E c e ? | Ece |
CMP DX, 1 / JBE done (jumps) | 65h | 0120h | 0001h | 1 | E c e ? | Ece |
MOV BYTE PTR [DI], 0 | 65h | 0120h | 0001h | 1 | E c e 0 | Ece |
At the start of the fourth pass DX = 1: only the final 0 has room (Table 9.2.12). CMP DX, 1 finds equality and ZF = 1; JBE jumps. Even if the user typed more, it would not be read; at most DX − 1 = 3 characters have been accepted. The buffer becomes 'E', 'c', 'e', 0 and can be printed with PRINT_STRING. The plain version ends by itself when the buffer is full; the version in the library, however, waits for Enter.
9.2.3.8GET_STRING in detail and backspace handling
The GET_STRING in the library differs from the plain version in four respects.
- Echo control. The key is read without echo: service 00h of INT 16h writes the key to AL (ASCII) and AH (scan code) but prints nothing on the screen. The procedure prints on the screen, with service 0Eh, only the character it has taken into the buffer. Keys that are not accepted thus leave no trace on the screen.
- Full buffer. After DX − 1 characters have been taken, new letters are ignored. The procedure does not finish by itself; it waits for Enter or backspace. The user can erase the last wrongly typed letter and correct it.
- Backspace (8). If there are letters in the buffer, DI is moved back by one and 8, ' ', 8 are printed on the screen. If the buffer is empty the key is ignored; the cursor does not go back past the start of the input and the prompt on the screen is not erased.
- Enter (13). Enter is not written to the buffer. A 0 is put in its place and the procedure returns. If DX ≤ 1 is given, no reading is done and the buffer is not touched.
The hardware side of keyboard reading should be known too. When a key is pressed, the keyboard controller activates the IRQ1 line of the 8259 interrupt controller. The processor drops what it is doing and runs the BIOS routine INT 09h. The routine reads the key's scan code from port 60h, finds its ASCII equivalent and writes both to the keyboard buffer in segment 0040h. INT 16h/00h reads from this buffer; if the buffer is empty it waits until a key arrives. The "waiting" of GET_STRING lies inside this loop.
When GET_STRING returns, the cursor is right after the text entered. The procedure does not print Enter on the screen; the next output starts on the same line. To move to the next line, PUTC 13 and PUTC 10 are added after the call.
The logic of backspace is again traced with a plain equivalent. The code below reads keys without echo, appends letters to the buffer, on backspace erases the last letter from the buffer and the screen, and on Enter ends the buffer with 0. The user will press A, b, backspace, c and Enter in turn.
ORG 100h
LEA DI, buf
get_key: MOV AH, 0
INT 16h ; AL = key (no echo)
CMP AL, 13 ; Enter?
JE done
MOV AH, 0Eh
CMP AL, 8 ; backspace?
JNE store
CMP DI, OFFSET buf
JE get_key ; no letter to erase
DEC DI
INT 10h ; 8: cursor left
MOV AL, ' '
INT 10h ; a space over the letter
MOV AL, 8
INT 10h ; left again
JMP get_key
store: MOV [DI], AL
INC DI
INT 10h ; echo
JMP get_key
done: MOV BYTE PTR [DI], 0
RET
buf DB 6 DUP(?)Two details of the code need attention. MOV AH, 0Eh is done before the comparisons; AH is thus ready for both the echo and the erase triple. Because MOV does not change the flags, the result of the CMP that follows is not affected. The INT 10h in the backspace branch moves the cursor left because AL still holds 8; the key's code is used directly as a control character.
| Event | AL | DI | Cursor column | Buffer | Screen |
|---|---|---|---|---|---|
LEA DI, ad | 00h | buf+0 | 0 | ? ? ? ? ? ? | |
| INT 16h: 'A'; not Enter or backspace | 41h | buf+0 | 0 | ? ? ? ? ? ? | |
store: write, advance, echo | 41h | buf+1 | 1 | A ? ? ? ? ? | A |
| same path for 'b' | 62h | buf+2 | 2 | A b ? ? ? ? | Ab |
INT 16h: backspace; CMP AL, 8 → ZF = 1 | 08h | buf+2 | 2 | A b ? ? ? ? | Ab |
CMP DI, OFFSET ad (not equal) / DEC DI | 08h | buf+1 | 2 | A b ? ? ? ? | Ab |
| the 8, ' ', 8 triple | 08h | buf+1 | 1 | A b ? ? ? ? | A |
| 'c': written over the byte of 'b' | 63h | buf+2 | 2 | A c ? ? ? ? | Ac |
Enter: JE done, 0 is written | 0Dh | buf+2 | 2 | A c 0 ? ? ? | Ac |
DEC DI does not erase the byte of 'b' from memory; that byte merely falls outside the string and the next letter is written over it (Table 9.2.13). The erasing is done in two places at once: moving DI back in the buffer, and printing the triple on the screen. If one of the two is forgotten, the screen and the buffer no longer agree. For example, if the triple is forgotten, "Abc" stays on the screen and "Ac" in the buffer. With the same input the library version makes the buffer 'A', 'c', 0; it sends 'A', 'b', 8, ' ', 8 and 'c' to the screen, and "Ac" appears on the screen.
9.2.3.9Buffer size and overflow
GET_STRING does not know the real size of the buffer; it trusts only the number the programmer gives in DX. If DX is larger than the buffer's real size, the procedure overwrites the variables after the buffer.
In memory buf DB 4 DUP(0) is defined, followed by value DW 0 and last DB 5. The program calls GET_STRING with MOV DX, 8 and the user types "Istanbul" and presses Enter.
- Since DX = 8, the procedure accepts at most 7 characters: "Istanbu". The eighth letter, 'l', is ignored.
- The first four characters, "Ista", are written to the four bytes of the buffer.
- 'n' (6Eh) and 'b' (62h) are written to the two bytes of value. Since the word is read little-endian, value = 626Eh.
- 'u' (75h = 117) is written over last; last = 117.
- The final 0 is written to the byte after last. That byte may belong to another variable or to code.
No error message appears in the program. value and last have been silently corrupted.
This error is called a buffer overflow. In assembly there is no mechanism that checks array bounds; every memory write looks only at the address. The safe rule is simple: DX is always given equal to the size reserved with DUP. One way to guarantee this automatically is to put a label right after the buffer and write MOV DX, buf_end - buf; then when the buffer is enlarged, DX changes by itself.
Taking DX to be "the number of characters to read". DX is the size of the buffer and includes the final 0. To read a name of 10 characters the buffer must be DB 11 DUP(0) and DX = 11. With DB 10 DUP(0) and DX = 10 only 9 characters are accepted.
9.2.4Number procedures
9.2.4.1SCAN_NUM, PRINT_NUM and PRINT_NUM_UNS
The processor keeps numbers in binary; the user, however, writes and reads numbers with decimal digits. The "307" that comes from the keyboard is three separate ASCII codes: 33h, 30h and 37h. For the program to compute, these codes must be converted into the binary number 0133h. When printing a number on the screen the job runs the other way: the digits of 0133h are found and each is converted to an ASCII code. The library's three number procedures perform these two conversions (Table 9.2.14).
| Procedure | What does it do? | Input / output | Definition |
|---|---|---|---|
| SCAN_NUM | reads a multi-digit signed number from the keyboard; ends with Enter | output: CX | DEFINE_SCAN_NUM |
| PRINT_NUM | prints the signed number in AX in decimal | input: AX | DEFINE_PRINT_NUM + DEFINE_PRINT_NUM_UNS |
| PRINT_NUM_UNS | prints the unsigned number in AX in decimal | input: AX | DEFINE_PRINT_NUM_UNS |
The difference between the two print procedures is how the 16 bits in AX are interpreted. In the unsigned interpretation the 16 bits denote the range 0 … 65,535. In the signed interpretation two's complement is used and the range is −32,768 … 32,767. For numbers whose most significant bit is 0, the two interpretations agree. For numbers whose most significant bit is 1, the signed value is found by subtracting 65,536 from the unsigned value.
In two's complement representation, −x is written by inverting all the bits of x and adding 1. In 16 bits this equals 65,536 − x. The 8086 instruction NEG takes the two's complement of a number.
For example, the unsigned value of FFE7h is 65,511. Because its most significant bit is 1, its signed value is 65,511 − 65,536 = −25. Seen the other way round, 25 = 0019h; inverting the bits gives FFE6h and adding 1 gives FFE7h. The same FFE7h is printed as "-25" by PRINT_NUM and as "65511" by PRINT_NUM_UNS. The bits do not change; only the interpretation does.
9.2.4.2The logic of SCAN_NUM: a code trace
When a decimal number is read from left to right, every new digit shifts the previous result one place to the left. For "307", 3 is read; when 0 arrives, the result becomes 3 × 10 + 0 = 30; when 7 arrives, 30 × 10 + 7 = 307. The rule in short is result ← result × 10 + digit. This method is also known as Horner's method and does not require knowing the length of the number in advance. The essence of SCAN_NUM is the plain equivalent below; the minus sign and the overflow check have been left out.
ORG 100h
XOR CX, CX ; result = 0
get_key: MOV AH, 01h
INT 21h ; AL = key (echoed)
CMP AL, 13 ; Enter?
JE done
SUB AL, '0' ; ASCII → digit
CBW ; AX = digit
XCHG AX, CX ; AX=result, CX=digit
MOV BX, 10
MUL BX ; AX = result × 10
ADD CX, AX ; CX = result×10 + digit
JMP get_key
done: RETEvery line of the code serves a purpose. XOR CX, CX clears CX; XORing a register with itself is shorter than MOV CX, 0 (2 bytes against 3) and sets ZF to 1. SUB AL, '0' finds the value of the digit by subtracting 30h from the ASCII code. CBW extends AL to AX as a signed value; for digits 0–9, AH = 0. XCHG AX, CX swaps the two registers: the result moves to AX for the multiplication, and the digit waits in CX. The swap is necessary because MUL always expects the multiplicand in AX. MUL BX performs DX:AX ← AX × BX; as long as the result fits in 16 bits, DX stays 0. ADD CX, AX adds the product to the digit and writes the new result into CX again.
| Step | AX | CX | BX | ZF | CX (decimal) | Screen |
|---|---|---|---|---|---|---|
XOR CX, CX | 0000h | 0000h | 0000h | 1 | 0 | |
MOV AH, 01h / INT 21h: '3' | 0133h | 0000h | 0000h | 1 | 0 | 3 |
CMP / JE / SUB AL, '0' | 0103h | 0000h | 0000h | 0 | 0 | 3 |
CBW / XCHG AX, CX | 0000h | 0003h | 0000h | 0 | 3 | 3 |
MOV BX, 10 / MUL BX / ADD CX, AX | 0000h | 0003h | 000Ah | 0 | 3 | 3 |
'0' is read, SUB, CBW, XCHG | 0003h | 0000h | 000Ah | 1 | 0 | 30 |
MUL BX / ADD CX, AX | 001Eh | 001Eh | 000Ah | 0 | 30 | 30 |
'7' is read, SUB, CBW | 0007h | 001Eh | 000Ah | 0 | 30 | 307 |
XCHG / MUL BX / ADD CX, AX | 012Ch | 0133h | 000Ah | 0 | 307 | 307 |
Enter: AL = 0Dh, CMP AL, 13 | 010Dh | 0133h | 000Ah | 1 | 307 | 307 |
JE done / RET | 010Dh | 0133h | 000Ah | 1 | 307 | 307 |
A few points of the table need explanation (Table 9.2.15). INT 21h/01h writes the key to AL but does not touch AH; AH stays at 01h, the service number, and AX appears as 0133h. When '0' is read, the result of SUB is 0 and ZF = 1. 30 × 10 = 300 = 012Ch; adding 7 gives CX = 307 = 0133h. When Enter is read, CMP finds equality, ZF = 1 and JE leaves the loop. The result is in CX, as in SCAN_NUM.
Multiplication is the most expensive step of this loop. On the 8086 MUL r16 takes 118–133 clock cycles; at 5 MHz about 25 µs. For a three-digit number three multiplications are made. This time is negligible next to the speed at which the user presses keys. Still, multiplying by 10 can also be done with shifts. Since x × 10 = x × 8 + x × 2, the product can be computed with SHL and ADD instructions in far fewer cycles.
9.2.4.3The checks in SCAN_NUM
The SCAN_NUM in the library adds five checks on top of the plain equivalent:
- The minus sign. The '-' key sets a sign flag. When Enter is pressed and the flag is set,
NEG CXis applied. - A key that is not a digit. The procedure first prints every key on the screen and then checks it. If the key is not in the range '0'–'9', it is erased from the screen (8, ' ', 8) and does not join the number.
- Backspace. It discards the last digit: CX ← CX / 10. The last character is erased from the screen as well.
- Overflow. If the number would not fit in 16 bits, the last digit is not accepted. If DX ≠ 0 after the multiplication or CF = 1 in the addition, the procedure restores the previous value and erases the last digit from the screen.
- The echo of Enter. Enter is also printed on the screen. Code 13 returns the cursor to the start of the line but does not move it down a line.
The last item is the most surprising behavior in practice. When SCAN_NUM returns, the cursor is at the start of the line that holds the number entered. Anything printed right afterwards overwrites the number entered and the prompt. This is why example programs add PUTC 13, PUTC 10 after SCAN_NUM, or start the next message with 13, 10.
| Input | CX | PRINT_NUM | Explanation |
|---|---|---|---|
| 307 | 0133h | 307 | the usual case |
| -25 | FFE7h | -25 | NEG at Enter: 0019h → FFE7h |
| 12a3 | 007Bh | 123 | 'a' is erased from the screen and does not join the number |
| 40000 | 9C40h | -25536 | fits in 16 bits but exceeds the signed range |
| 70000 | 1B58h | 7000 | the last 0 is not accepted: 7000 × 10 = 70,000 > 65,535 |
| -40000 | 63C0h | 25536 | the two's complement of 9C40h is 63C0h |
The last three rows of the table show a limit of the procedure (Table 9.2.16). Digits are accumulated as an unsigned 16-bit number and the sign is applied at the end. The overflow check looks only at the 65,535 limit. Inputs between 32,768 and 65,535 are therefore accepted without error but appear negative in the signed interpretation. For example 40,000 = 9C40h; its signed value is 40,000 − 65,536 = −25,536. When −40,000 is entered, the two's complement of 9C40h, 63C0h = 25,536, results, and an input with a minus sign gives a positive result. For a correct result the user's input must stay in the range −32,768 … 32,767.
9.2.4.4The logic of PRINT_NUM_UNS: a code trace
The decimal digits of a number are found by dividing it repeatedly by 10. The remainder of each division is a digit, and the quotient is the number for the next step. The problem is that the digits come out from right to left, that is, in reverse order: the first remainder of 1205 is 5 and the last is 1. On the screen, however, 1 must be printed first. The stack is a natural tool for this reversal: the remainders are pushed in order and then popped in reverse order.
ORG 100h
MOV AX, 1205 ; the number to print
MOV BX, 10
XOR CX, CX ; digit counter
divide: XOR DX, DX
DIV BX ; AX=quotient, DX=remainder
PUSH DX ; digit onto the stack
INC CX
OR AX, AX ; quotient 0?
JNZ divide
emit: POP AX ; most significant first
ADD AL, '0'
MOV AH, 0Eh
INT 10h
LOOP emit
RETDIV BX divides the 32-bit DX:AX by BX: it writes the quotient to AX and the remainder to DX. XOR DX, DX before the division is mandatory. If the previous remainder is left in DX, the dividend DX:AX becomes too large; if the quotient does not fit in 16 bits, the processor generates interrupt type 0 (divide error). CX counts how many digits have been pushed; in the second loop, LOOP makes sure the same number of POPs is done. OR AX, AX does not change AX but sets the flags: if the quotient is 0, ZF = 1 and the loop ends.
| Step | AX | DX | CX | SP | Stack (from the top) | Screen |
|---|---|---|---|---|---|---|
start (MOV, MOV, XOR) | 04B5h | 0000h | 0000h | FFFEh | — | |
| 1st division: 1205 / 10 | 0078h | 0005h | 0001h | FFFCh | 5 | |
| 2nd division: 120 / 10 | 000Ch | 0000h | 0002h | FFFAh | 0, 5 | |
| 3rd division: 12 / 10 | 0001h | 0002h | 0003h | FFF8h | 2, 0, 5 | |
| 4th division: 1 / 10 | 0000h | 0001h | 0004h | FFF6h | 1, 2, 0, 5 | |
OR AX, AX → ZF = 1, JNZ does not jump | 0000h | 0001h | 0004h | FFF6h | 1, 2, 0, 5 | |
| 1st print: POP, add '0', INT 10h, LOOP | 0E31h | 0001h | 0003h | FFF8h | 2, 0, 5 | 1 |
| 2nd print | 0E32h | 0001h | 0002h | FFFAh | 0, 5 | 12 |
| 3rd print | 0E30h | 0001h | 0001h | FFFCh | 5 | 120 |
| 4th print, LOOP ends | 0E35h | 0001h | 0000h | FFFEh | — | 1205 |
After four divisions the most significant digit, 1, is on top of the stack (Table 9.2.17). The print loop pops the digits in the order 1, 2, 0, 5 and prints them. After each POP, ADD AL, '0' converts the digit to ASCII and MOV AH, 0Eh loads the service number; this is where AX values such as 0E31h and 0E32h come from. When the loop ends, SP is FFFEh again: four POPs have matched four PUSHes. The stack column of the table does not show DOS's 0000h word at FFFEh.
9.2.4.5The library's method: a decreasing divisor
PRINT_NUM_UNS in the library produces the same output with another method. Instead of always dividing the number by 10, it divides by the place values: first by 10,000, then by 1000, 100, 10 and 1. The quotient of each division is a digit and is printed the moment it is computed. The remainder becomes the number for the next pass. Because the digits come out from left to right, no stack or reversal is needed.
- The divisor BX starts at 10,000 and is divided by 10 after every pass. When BX becomes 0, printing ends.
- The quotient (0–9) is a digit; it is converted to ASCII with
ADD AL, 30hand printed with PUTC. Since 65,535 ÷ 10,000 = 6, the quotient always fits in AL. - CX is used as a flag. While CX = 1, a pass is skipped if the number is smaller than the divisor; this way leading zeros are not printed. Once the first digit has been printed CX becomes 0, and the zeros in between are printed from then on.
- There is a separate branch for AX = 0 that prints '0' directly. Without this branch every pass would be skipped and nothing would be printed on the screen.
| Divisor (BX) | Flag (CX) | Number (AX) | Action | Screen |
|---|---|---|---|---|
| 10.000 | 1 | 3007 | number < divisor and no digit yet: skip | — |
| 1000 | 1 | 3007 | 3007 ÷ 1000 = 3, remainder 7; CX = 0 | 3 |
| 100 | 0 | 7 | 7 ÷ 100 = 0, remainder 7 | 30 |
| 10 | 0 | 7 | 7 ÷ 10 = 0, remainder 7 | 300 |
| 1 | 0 | 7 | 7 ÷ 1 = 7, remainder 0 | 3007 |
| 0 | 0 | 0 | divisor 0: done | 3007 |
The 3007 example shows clearly why the flag is needed (Table 9.2.18). In the first pass, since 3007 < 10,000, the quotient would be 0; this zero is a leading zero and must not be printed. In the passes that divide by 100 and 10 the quotient is also 0, but these zeros are inside the number and must be printed. The difference is told apart only by the question "has the first digit been printed?"; CX holds this information. For 40,000, in the first pass 40,000 ÷ 10,000 = 4 is printed and CX becomes 0. In the next four passes four 0s are printed; 40000 appears on the screen.
Reducing the divisor is also a division: the library does BX ← BX / 10 with DIV. During this the number in AX is saved on the stack. The procedure pushes AX, BX, CX and DX on entry and pops them on exit; no register changes for the caller.
9.2.4.6PRINT_NUM and the minus sign: a code trace
PRINT_NUM uses PRINT_NUM_UNS to print a signed number. If the number is negative, '-' is printed first, and then the absolute value of the number is printed as unsigned. The code below is the equivalent of PRINT_NUM in the library:
ORG 100h
MOV AX, -25 ; AX = FFE7h
CALL print_num
RET
print_num PROC
PUSH AX
OR AX, AX ; SF = sign bit
JNS positive
NEG AX ; AX = 0019h
PUSH AX ; PUTC '-' expansion
MOV AL, '-'
MOV AH, 0Eh
INT 10h
POP AX
positive: CALL print_num_uns
POP AX ; AX = FFE7h restored
RET
print_num ENDPAt the line MOV AX, -25 the assembler computes the two's complement of −25 and produces the instruction that loads FFE7h into AX. CALL print_num is at 0103h and is 3 bytes long; the return address 0106h is pushed on the stack. The procedure first saves AX, because NEG will change it. OR AX, AX sets the flags without changing the number: since the most significant bit is 1, SF = 1. JNS (jump if no sign) does not jump. NEG AX computes 0 − FFE7h = 0019h = 25; since the result is positive, SF = 0. The expansion of PUTC '-' prints the minus sign. CALL print_num_uns prints the digits of 25. Finally POP AX restores FFE7h into AX.
| Instruction(s) | AX | SP | SF | Stack (FFFAh, FFFCh) | Screen |
|---|---|---|---|---|---|
MOV AX, -25 | FFE7h | FFFEh | 0 | —, — | |
CALL print_num | FFE7h | FFFCh | 0 | —, 0106h | |
PUSH AX / OR AX, AX | FFE7h | FFFAh | 1 | FFE7h, 0106h | |
JNS (no jump) / NEG AX | 0019h | FFFAh | 0 | FFE7h, 0106h | |
| PUTC '-' expansion (5 instructions) | 0019h | FFFAh | 0 | FFE7h, 0106h | - |
CALL print_num_uns (after it returns) | 0019h | FFFAh | 0 | FFE7h, 0106h | -25 |
POP AX | FFE7h | FFFCh | 0 | —, 0106h | -25 |
RET (from print_num) | FFE7h | FFFEh | 0 | —, — | -25 |
After the number has been printed it is still in AX (Table 9.2.19). The calling program can go on using the same number for another job. Because PRINT_NUM_UNS saves all the registers it uses, the steps inside it are reduced to a single row of the table. The PRINT_NUM in the library also contains a branch that prints '0' directly for AX = 0. It also tests the sign with CMP AX, 0 instead of OR; the two instructions set SF in the same way.
One consequence of this design is remarkable: for −32,768 (8000h), NEG again produces 8000h, because +32,768 does not exist in the 16-bit signed range. PRINT_NUM first prints '-' and then gives 8000h to PRINT_NUM_UNS. PRINT_NUM_UNS prints 8000h as the unsigned 32,768, and the correct result, −32768, appears on the screen. Printing the absolute value as unsigned solves this edge case by itself.
9.2.4.7Extracting digits: comparing the two methods
| Criterion | Stack method (divide by 10, push, pop in reverse order) | Decreasing divisor (10,000, 1000, …) |
|---|---|---|
| Number of divisions | as many as there are digits | up to five; plus one division each to reduce the divisor |
| Stack use | 2 bytes per digit | only the saved registers |
| Leading zeros | do not arise by themselves | skipped with the flag |
| Fixed width (00042) | extra code needed | automatic when the flag is cleared |
| Other bases | the divisor becomes 2, 8 or 16; in base 16 digits above 9 become 'A'–'F' | the divisor sequence changes with the base (4096, 256, 16, 1 in base 16) |
| Output order | first onto the stack, then to the screen in reverse order | left to right, the moment it is computed |
The two methods give the same output: for 1205 both print the digits 1, 2, 0, 5 (Table 9.2.20). The choice is decided by stack use, fixed width and the need for other bases. In time, the cost of DIV is decisive. On the 8086 DIV r16 takes 144–162 clock cycles. For 1205 the stack method does 4 divisions. The decreasing-divisor method does four divisions by 1000, 100, 10 and 1, and five more divisions to reduce the divisor; the division is skipped in the first pass. The stack method is therefore about twice as fast. The library's choice was made for not using the stack and for easy adaptation to fixed width.
9.2.4.8The same bits, two interpretations
When the outputs of the two procedures for a value given in AX are put side by side, the difference of interpretation is clearly visible (Table 9.2.21).
| AX | Most significant bit | PRINT_NUM | PRINT_NUM_UNS |
|---|---|---|---|
| 0000h | 0 | 0 | 0 |
| 7FFFh | 0 | 32767 | 32767 |
| 8000h | 1 | -32768 | 32768 |
| 9C40h | 1 | -25536 | 40000 |
| FFE7h | 1 | -25 | 65511 |
| FFFFh | 1 | -1 | 65535 |
The rule is single: if the most significant bit is 0, the two procedures print the same thing; if it is 1, PRINT_NUM prints the unsigned value minus 65,536. The program must know which interpretation is correct; the processor does not. The addition and subtraction instructions produce the same bits for both interpretations; only the reading of the flags changes. CF shows unsigned overflow and OF signed overflow. Values that cannot be negative, such as a counter, an address or a length, are printed with PRINT_NUM_UNS; values that can be negative, such as a temperature or a difference, with PRINT_NUM.
Printing an unsigned value that can exceed 32,767 with PRINT_NUM. AX = 40,000 (9C40h) appears as −25536 with PRINT_NUM. If the value's meaning is unsigned, PRINT_NUM_UNS must be used.
9.2.5Example programs
9.2.5.1Read a number and print it
The second example in emu8086's library documentation uses four procedures together. The program asks the user for a number, reads it and prints it back:
include 'emu8086.inc'
ORG 100h
LEA SI, msg1 ; ask for the number
CALL print_string ;
CALL scan_num ; get number in CX.
MOV AX, CX ; copy the number to AX.
CALL pthis ; print the following string:
DB 13, 10, 'You have entered: ', 0
CALL print_num ; print number in AX.
RET ; return to operating system.
msg1 DB 'Enter the number: ', 0
DEFINE_SCAN_NUM
DEFINE_PRINT_STRING
DEFINE_PRINT_NUM
DEFINE_PRINT_NUM_UNS ; required for print_num.
DEFINE_PTHIS
END ; directive to stop the compiler.The flow of the program is short. LEA SI, msg1 loads the address of the prompt string into SI and PRINT_STRING prints it. SCAN_NUM reads the number and puts it in CX. MOV AX, CX moves the number to the register PRINT_NUM expects. PTHIS prints the string after the CALL: since the string starts with 13, 10, it first moves to the next line. PRINT_NUM prints the number as signed and RET ends the program. The lines after msg1 are data and procedure definitions; the flow never reaches them after the RET.
The layout of the main program in memory is in Table 9.2.22. All the CALLs are 3-byte near calls (E8 and a 16-bit displacement). Note that the string sits in the middle of the code area: 010Eh–0122h is data, not instructions.
| Address | Bytes | Line |
|---|---|---|
| 0100h | 3 | LEA SI, msg1 (BE 27 01) |
| 0103h | 3 | CALL print_string |
| 0106h | 3 | CALL scan_num |
| 0109h | 2 | MOV AX, CX (8B C1) |
| 010Bh | 3 | CALL pthis |
| 010Eh | 21 | DB 13, 10, 'You have entered: ', 0 |
| 0123h | 3 | CALL print_num |
| 0126h | 1 | RET (C3) |
| 0127h | 19 | msg1 DB 'Enter the number: ', 0 |
| 013Ah | … | procedures expanded by the DEFINE_ macros |
Suppose the user types -25 and presses Enter. In the trace table, two moments are shown for the CALL lines: inside the procedure (while the return address is on the stack) and the return (Table 9.2.23).
| Line | SI | CX | AX | SP | Screen |
|---|---|---|---|---|---|
LEA SI, msg1 | 0127h | (size) | 0000h | FFFEh | |
CALL print_string (inside) | 0127h | (size) | 0000h | FFFCh | Enter the number:␣ |
CALL scan_num (inside) | 0127h | … | 0000h | FFFCh | Enter the number: -25 |
CALL scan_num (return) | 0127h | FFE7h | 0000h | FFFEh | Enter the number: -25 |
MOV AX, CX | 0127h | FFE7h | FFE7h | FFFEh | Enter the number: -25 |
CALL pthis | 0127h | FFE7h | FFE7h | FFFCh | … |
| the string is printed | 0127h | FFE7h | FFE7h | FFFCh | … / You have entered:␣ |
CALL print_num (inside) | 0127h | FFE7h | FFE7h | FFFCh | … / You have entered: -25 |
RET | 0127h | FFE7h | FFE7h | 0000h | … / You have entered: -25 |
A few details of the table need explanation. SI stays at 0127h throughout the program, because PRINT_STRING and PTHIS save and restore SI. AX is also 0000h after SCAN_NUM; SCAN_NUM saves AX. The only register that changes is the output register CX: the two's complement of −25, FFE7h. The initial value of CX is shown as "(size)". When emu8086 loads a .COM program it puts the program's size in bytes into CX. This value is lost when SCAN_NUM clears CX and does not affect the result. The last RET takes the 0000h that DOS put on the stack into IP; SP = FFFEh + 2 = 0000h. The processor goes to the INT 20h at the start of the PSP and the program ends.
The final state of the screen is two lines. The first line reads "Enter the number: -25" and the second "You have entered: -25". Because SCAN_NUM echoed Enter only as CR, the cursor had returned to the start of the first line. The 13 and 10 at the start of the PTHIS string take the cursor to the start of the second line. Had the string not started with 13, 10, "You have entered: " would have been written over the first line and the prompt would have been erased.
9.2.5.2The sum of two numbers
The second example reads two numbers and prints their sum. Signed overflow is checked too.
include 'emu8086.inc'
ORG 100h
CALL scan_num ; 1st number → CX
MOV BX, CX ; save
PUTC 13
PUTC 10 ; next line
CALL scan_num ; 2nd number → CX
PUTC 13
PUTC 10
MOV AX, BX
ADD AX, CX ; signed sum
JO overflow
CALL print_num
RET
overflow: PUTC '?'
RET
DEFINE_SCAN_NUM
DEFINE_PRINT_NUM
DEFINE_PRINT_NUM_UNS
ENDThree details of the program are important. First, the second SCAN_NUM also writes its result to CX; so that the first number is not lost, it is moved to BX first. The choice of BX is not random: SCAN_NUM does not use BX, and PUTC touches only AX. Second, because Enter only returns to the start of the line, PUTC 13 and PUTC 10 follow every SCAN_NUM; the second number and the result are printed on separate lines. Third, JO catches signed overflow.
The overflow flag (OF) becomes 1 when the result of a signed operation does not fit in the 16-bit signed range (−32,768 … 32,767). In an addition OF = 1 if the two operands have the same sign and the result has the opposite sign. The JO instruction jumps if OF = 1.
| Inputs | BX | CX | AX = BX + CX | OF | Last line |
|---|---|---|---|---|---|
| 120, −45 | 0078h | FFD3h | 004Bh | 0 | 75 |
| −7, −8 | FFF9h | FFF8h | FFF1h | 0 | -15 |
| 30000, 5000 | 7530h | 1388h | 88B8h | 1 | ? |
In the first two rows the result is in the signed range (Table 9.2.24). In the addition 120 + (−45), CF = 1, because as unsigned numbers 0078h + FFD3h exceeds 16 bits. This carry is meaningless in signed arithmetic and OF stays 0. In the third row the sum of the two positive numbers is 35,000 and exceeds 32,767. The most significant bit of the result 88B8h is 1; the sum of two positive numbers appears negative and OF = 1. JO jumps and '?' is printed on the screen. Without the JO, PRINT_NUM would have printed 88B8h as −30536.
9.2.5.3A framed title
The third example clears the screen and draws a framed heading starting at column 10. The library macros are used together with the programmer's own procedure.
include 'emu8086.inc'
ORG 100h
CALL clear_screen
GOTOXY 10, 2
CALL rule
GOTOXY 10, 3
PRINT '| REPORT |'
GOTOXY 10, 4
CALL rule
GOTOXY 0, 6 ; cursor below
RET
rule PROC ; +----------+
PUTC '+'
MOV CX, 10
dash: PUTC '-'
LOOP dash
PUTC '+'
RET
rule ENDP
DEFINE_CLEAR_SCREEN
ENDThe rule procedure prints a '+', prints '-' ten times and ends with a '+': the 12-character "+----------+". The string in the heading line is also 12 characters: two edge bars, two spaces, "REPORT" and two spaces. The three lines are therefore aligned one above the other in columns 10–21 (Figure 9.2.10). The final GOTOXY 0, 6 takes the cursor below the frame; when the program ends, whatever emu8086 prints does not land on top of the heading.
Two points of the program show the relationship between a macro and a loop. The PUTC '-' in the loop is written once in the source, so it is expanded once; the 8-byte expansion runs 10 times but is not copied 10 times. The copying of the macro happens at assembly time, the repetition of the loop at run time. The second point concerns registers. The LOOP counter is in CX. Because PUTC uses only AX and restores it, it does not touch CX and the counter is safe. Had a procedure that clobbers CX, such as SCAN_NUM, been called in the loop, the counter would have had to be protected with PUSH CX / POP CX. The definition of rule is also after the RET, like the library procedures.
9.2.6Common mistakes
The mistakes made when using the library are mostly not noticed during assembly; the program runs but gives a wrong result. The mistakes below are the ones students working with emu8086 meet most often.
Forgetting the DEFINE_ line. If there is a CALL scan_num but no DEFINE_SCAN_NUM, the assembler cannot find the label and reports an "undefined" error. For PRINT_NUM, DEFINE_PRINT_NUM_UNS is also needed.
Not terminating the string with 0. PRINT_STRING and PTHIS print until they see a 0. With a definition without 0 such as msg DB 'Number: ', the bytes after the string are also dumped to the screen. These are often procedure code, and meaningless characters appear on the screen. With PTHIS, in addition, the return address slips to a wrong place and the program may hang.
Looking for the result in AX. SCAN_NUM writes its result to CX. If MOV AX, CX is forgotten before PRINT_NUM, the old value in AX is printed. General rule: if the documentation of a procedure does not say that a register is preserved, the register must not be assumed to be preserved.
Expecting a new line after Enter. After SCAN_NUM the cursor is at the start of the line where the input is. The next output is written over the number entered and the prompt. If 42 is read with the prompt "Num: " and PRINT_NUM is called right away, "42m: 42" is left on the screen. PUTC 13, PUTC 10 must be inserted in between.
Giving too large a buffer size. If DX is larger than the buffer's real size, GET_STRING overwrites the variables after the buffer. The error appears only when those variables are used.
The position of the DEFINE_ lines, however, is not a source of errors. Because every DEFINE_ macro begins with a JMP that jumps over the procedure body, the processor does not enter the body even if the line is put at the start of the program (Figure 9.2.11). The price is an extra jump instruction. The usual place is between RET and END.
9.2.7Exercises and solutions
Exercise 1. Write, with macros, the program that prints "CENTER" in the middle of the screen (column 35, row 12).
include 'emu8086.inc'
ORG 100h
GOTOXY 35, 12
PRINT 'CENTER'
RET"CENTER" is written to columns 35–40 of row 12 and the cursor stays at (41, 12). For a six-character text to sit exactly in the middle, the start column must be (80 − 6) / 2 = 37; 35 is an approximate middle. General rule for centering: start column = (80 − length) / 2.
Exercise 2. Write the program that reads two numbers from the user and prints their sum.
The solution is the sum-of-two-numbers example. The parts needed: CALL scan_num → MOV BX, CX → PUTC 13, PUTC 10 → CALL scan_num → MOV AX, BX → ADD AX, CX → CALL print_num; the definitions DEFINE_SCAN_NUM, DEFINE_PRINT_NUM and DEFINE_PRINT_NUM_UNS. If PUTC 13 and PUTC 10 are forgotten, the second number is written over the first and only the last things written can be read on the screen.
Exercise 3. If the PRINT macro is used 10 times, how many times do the strings and the loop code exist? Compare with PRINT_STRING.
With PRINT there are 10 copies: every expansion carries its own string and its own 23-byte loop code. With PRINT_STRING the loop code exists once; memory holds 10 strings and, for each string, one LEA SI and one CALL (3 + 3 bytes). With ten seven-character messages the program with PRINT is about 310 bytes and the one with PRINT_STRING about 160 bytes. The gap grows as the number of messages grows; on the other hand every CALL/RET pair adds 27 clock cycles.
Exercise 4. What do PRINT_NUM and PRINT_NUM_UNS print when AX = 8000h?
The unsigned value of 8000h is 32,768; PRINT_NUM_UNS prints "32768". Because its most significant bit is 1, its signed value is 32,768 − 65,536 = −32,768; PRINT_NUM prints "-32768". This is the smallest number of the 16-bit signed range, and NEG does not change it; PRINT_NUM still prints correctly, because it prints the absolute value as unsigned.
Exercise 5. What happens if DEFINE_PTHIS is written right below ORG 100h?
The program still works correctly. The first instruction of the macro is JMP skip_proc_pthis; the processor jumps over the body of PTHIS and reaches the first instruction of the main program. The price is an extra JMP, and the addresses of the main program shift forward by the size of the body. Without the protective JMP the processor would have entered the code of PTHIS directly: POP SI would take DOS's 0000h word from the stack, print the bytes of the PSP as a string and return to an invalid address.
Exercise 6. Get the user's name with GET_STRING and print "Hello, name!".
include 'emu8086.inc'
ORG 100h
LEA DI, buf
MOV DX, 20
CALL get_string
PUTC 13
PUTC 10
PRINT 'Hello, '
LEA SI, buf
CALL print_string
PUTC '!'
RET
buf DB 20 DUP(0)
DEFINE_GET_STRING
DEFINE_PRINT_STRING
ENDIf the user types "Ece" and presses Enter, "Ece" appears on the first line of the screen and "Hello, Ece!" on the second. Without PUTC 13 and PUTC 10, after GET_STRING the cursor would stay right after "Ece" and "EceHello, Ece!" would appear on a single line. The buffer is 20 bytes and DX = 20; a name of at most 19 characters is accepted.
9.2.8Summary
- emu8086.inc is the library that contains ready-made macros and procedures for screen, keyboard and number jobs. Everything in it is ordinary 8086 code built on BIOS and DOS interrupts.
- INCLUDE is a directive: it puts the text of the file in place of the line during assembly and produces no code. The file is searched for first in the source folder, then in emu8086's Inc folder. The line is written at the start of the source.
- A macro definition and a procedure whose DEFINE_ has not been written add no bytes to the program. Program size is determined by every use of the macros that are used and the procedures defined with DEFINE_.
- The screen macros are built on INT 10h: PUTC and PRINT use service 0Eh, GOTOXY 02h, CURSOROFF and CURSORON 01h. The macros save the registers they use; PUTC is 8 bytes, GOTOXY 16 bytes.
- GOTOXY uses the column, row order; the BIOS expects the row in DH and the column in DL. The top-left is (0, 0), the bottom-right (79, 24). The address of a cell in video memory is B800h:(row × 80 + column) × 2.
- PRINT embeds the string in the code and jumps over it with a JMP; the loop code is copied at every use. PRINTN appends 13, 10. A new line needs CR (13) and LF (10) together. After column 79 the cursor moves to the next line, and on the last row the screen scrolls.
- Procedures are defined once with DEFINE_ and called with CALL. Every DEFINE_ macro begins with a JMP that jumps over the body; the usual place is between RET and END. PRINT_NUM also requires PRINT_NUM_UNS.
- Input and output registers: PRINT_STRING DS:SI, GET_STRING DS:DI and DX, SCAN_NUM → CX, PRINT_NUM and PRINT_NUM_UNS ← AX. The other registers are preserved, the flags are not.
- PTHIS uses the return address that CALL pushed on the stack as the address of the string; after printing the string it moves the address past the 0, and RET returns to the instruction after the string.
- GET_STRING reads at most DX − 1 characters, ends the buffer with 0, handles backspace and does not print Enter. If DX is given larger than the real size of the buffer, the variables after the buffer are overwritten.
- SCAN_NUM accumulates digits with the rule result ← result × 10 + digit; it applies the minus sign at the end with NEG, rejects keys that are not digits and digits that push the number past 65,535. Enter returns only to the start of the line.
- PRINT_NUM_UNS prints the digits left to right with a decreasing divisor (10,000, 1000, …); it skips leading zeros with a flag. The stack method gives the same result by dividing by 10 and popping the digits from the stack in reverse order. PRINT_NUM prints '-' for a negative number and then the absolute value as unsigned.
- The same 16 bits are read in two ways: if the most significant bit is 1, the signed value = the unsigned value − 65,536 (FFE7h = −25 = 65,511).
9.2.9Key terms
- library
- directive
- macro
- macro expansion
- procedure
- procedure call
- return address
- parameter passing
- register preservation
- cursor
- string
- control character
- ASCII
- BIOS
- service
- video memory (text mode)
- keyboard buffer
- signed / unsigned number
- two's complement
- label
9.2.10Test Yourself
In the expansion of
GOTOXY 3, 7, what are AH, BH, DH and DL just before INT 10h is called? How many bytes is the expansion and which registers does it save?Answer
AH = 02h, BH = 0, DH = 7 (row), DL = 3 (column). The expansion is 16 bytes: three PUSHes and three POPs take 6 bytes, four
MOV r8, constanttake 8 bytes, andINT 10htakes 2 bytes. AX, BX and DX are saved on the stack and restored in reverse order.In colour text mode, at which offset in video memory does the character in cell (35, 12) sit? What is its physical address?
Answer
(12 × 80 + 35) × 2 = 995 × 2 = 1990 = 07C6h. The character is at B800:07C6h and the attribute byte at B800:07C7h. The physical address is B8000h + 07C6h = B87C6h.
On an empty screen with the cursor at (0, 0),
PRINTN 'Hello'and thenPUTC 'X'run. Which cell is X written to? Where is the cursor at the end?Answer
"Hello" is written to columns 0–4 of row 0. The 13 that PRINTN appends takes the cursor to (0, 0) and the 10 to (0, 1). X is written to (0, 1) and the cursor moves to (1, 1).
While SCAN_NUM runs, the user presses the keys 5, b, 0 and Enter in turn. What is CX when the procedure returns? What is left on the screen?
Answer
Because 'b' is not a digit, it is printed on the screen, then erased with 8, ' ', 8 and does not join the number. The number becomes 5 × 10 + 0 = 50: CX = 0032h. "50" is left on the screen; Enter returns the cursor to the start of the line.
What does the stack digit-extraction code (divide by 10, push, pop with LOOP) print for AX = 0? Why does the library's decreasing-divisor method need a separate branch for AX = 0?
Answer
The stack code enters the loop at least once: 0 / 10 = 0, the remainder 0 is pushed and CX = 1. OR AX, AX makes ZF = 1, the print loop runs once and "0" is printed. In the decreasing-divisor method, while the flag CX = 1 a pass is skipped if the number is smaller than the divisor. Since AX = 0 is smaller than every divisor, all the passes are skipped and nothing is printed; the separate branch therefore prints '0'.
GET_STRING is called with
MOV DX, 1and the user types "abc" and presses Enter. What is written to the buffer?Answer
Nothing. With DX ≤ 1 the buffer has room only for the final 0, and the procedure returns without reading anything; not even a 0 is written to the buffer, and the old contents stay as they were. The keys pressed wait in the keyboard buffer and the next read service picks them up.
In a .COM program
CALL pthisis at 0100h, followed right after byDB 'Hello', 13, 10, 0. Which address does CALL push on the stack? Which address does the RET of PTHIS return to?Answer
CALL is 3 bytes; 0103h is pushed on the stack, the address of the string's first byte, 'H'. The string is 5 + 2 + 1 = 8 bytes and occupies 0103h–010Ah. When PTHIS reads the 0 at 010Ah, SI = 010Bh; this value is put on the stack and RET returns to 010Bh.
What do PRINT_NUM and PRINT_NUM_UNS print when AX = C350h?
Answer
C350h = 50,000; PRINT_NUM_UNS prints "50000". Because the most significant bit is 1, the signed value is 50,000 − 65,536 = −15,536; PRINT_NUM prints "-15536".
9.2.11Further reading
- The
Inc/emu8086.incfile in the emu8086 installation: the source code of all the macros and procedures in the library. The overflow check of SCAN_NUM and the decreasing-divisor loop of PRINT_NUM_UNS can be read there line by line. - The emu8086 help documents, the pages "emu8086.inc — library of common functions" and "Macros": usage examples of the library and the general rules of macros.
- B. B. Brey, The Intel Microprocessors (8th ed.): procedures, macros and BIOS video services; converting decimal numbers to binary and back.
- R. Brown, "Ralf Brown's Interrupt List": a detailed list of the INT 10h, INT 16h and INT 21h services with their input and output registers.
9.2.12References
- emu8086 help documents: the pages "emu8086.inc — library of common functions" and "Macros".
- The Inc/emu8086.inc file in the emu8086 installation (source code of the macros and procedures).
- B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009 — procedures and macros.
- A. S. Tanenbaum, Modern Operating Systems, 3rd ed., Pearson, 2008.
- Intel, The 8086 Family User's Manual, 1979 — definitions of the CALL, RET, MUL, DIV and AAM instructions and their clock-cycle counts.
Related pages: Chapter 9.2 slides · © Sercan Külcü. All rights reserved.