MP 3
MP 3
MP 3
Session XIX
Interrupts, DOS Services
09.11.2005
Dr. K.Rajanikanth
M.S.Ramaiah Institute of Technology, Bangalore
---------------------------------------------------------------Learning Objectives:
Understand interrupt system of 8086 and learn to write Interrupt Service Routines
Introduction:
When the interrupt occurs and is recognized, the values of the Flag register, CS
and IP registers are saved on the stack and the control is transferred from the
executing program to an associated Interrupt Service Routine (ISR). After
completing the ISR control returns to the interrupted program.
Thus, this mechanism is similar to yet different from Far Call. CALL is always an
instruction in the program. The mechanism of calling & returning from ISR is
some what different from normal CALL mechanism.
Interrupts
Interrupt Service
Routine (ISR)
CALL
Interrupt
Return from
Interrupt
RETURN
(ISR; Interrupt Service Procedure; Interrupt Handler All mean the same)
Interrupt can be because of:
An external interrupt signal at the pins NMI or INTR . These are called
Hardware interrupts (studied in a later session).
Whatever be the source of interrupt & what ever be the type code:
One interrupt vector is required for each interrupt type code. We have 256
possible interrupt type codes and thus 256 possible interrupt vectors.
Consequently, to specify all these interrupt vectors, we need 256 x 4 =
1024 bytes of memory.
Interrupt Vector Table: A table of 1024 bytes containing the 256 interrupt
vectors. Address range is 00000H (0:0) to 003FFH (0:03FFH). This is a memory
block of 1KB starting from 00000H
Function
00H 03H
Divide Error
04H 07H
Single Step
08H 0BH
NMI
0CH 0FH
Breakpoint
10H 13H
Interrupt on Overflow
14H 7FH
Reserved
80H 3FFH
User-Defined
Type Codes
0
1
2
3
4
5 1F
20H - FFH
Interrupt Processing:
When an interrupt is to be processed:
T and I flags are cleared (disabling Single Step and External Interrupts)
To return from the ISR, the interrupt return (IRET) instruction is used.
I Flag:
CLI (Clear Interrupt Flag) instruction also clears the I flag disabling recognition
of interrupts from INTR pin.
T Flag:
Setting the T flag enables Single Step. The, after the execution of every
instruction, an interrupt of type 1 is generated. This feature is quite useful for
debugging. (The ISR can display Register values & other useful information.)
Evidently, within the ISR, Single Step should not be in effect! So T is cleared. On
return from ISR, the value of T is restored.
T Flag - 1
Program to be traced
(single-stepped):
T flag = 1
INT 3 is 1 Byte long. (The only special case). Rest of INT n instructions are all
2 Byte long.
A software interrupt instruction is more convenient than far call. It occupies less
memory as it needs only 1 or 2 bytes as against the 5 bytes required for a far Call.
Further, there is no need to remember the CS:IP values. These values are obtained
from the Interrupt Vector Table.
opcode
type code
INT 3 Instruction:
Only INT n instruction that is 1 Byte long! Rest are 2 Byte long.
This is often used to effect a breakpoint in the program. The breakpoint service
routine can provide Register values and other information useful for debugging.
Any INT n can be used for implement a breakpoint. However, as INT 3 is only
1-byte long, it is comparatively easier to insert this instruction into the program.
INTO Instruction:
This instruction is placed in the program usually after arithmetic instructions that
may lead to overflow condition. (Recall that JO instruction also detects overflow
condition.)
Interrupts in PC:
Several interrupt type codes are dedicated to interrupts from hardware devices
like key board, mouse etc. Examples: 9 for Keyboard; 17H for Parallel Port.
DOS Services:
Examples:
Before invoking a DOS function, user must Save & Restore registers if necessary.
Lower Level direct control of various I/O devices is possible via BIOS (Basic
Input Output System) function calls like INT 10H, INT 11H etc. (Not discussed in
this session)
Reading Keyboard:
When a character typed on the key board is read, it may return the standard 7-Bit
ASCII code corresponding to the key typed. Additionally, Extended ASCII codes
are used to represent Function Keys, Key Combinations (Keys in combination
with Shift, Control, Alt keys). The full list of key codes used in a standard PC is
available in the Text Book.
The code corresponding to the key typed is read. Further, the same character is
displayed on the screen also (echo). This routine responds to CNTL-C (That is,
when CNTL-C is typed, an immediate exit to DOS occurs)
The Read Key Procedure may distinguish these cases suitably (for example, via
Carry flag). In the following routine, CARRY is cleared to indicate standard key
code and it is set to indicate extended key code.
KEY PROC FAR
MOV AH, 01H
INT
21H
OR
AL, AL
JNZ
KEY1
INT
21H
STC
KEY1: RET
KEY
ENDP
The code corresponding to the key typed is read. However, the character is not
displayed on the screen also (no echo). Also, this routine does not respond to
CNTL-C (That is, typing CNTL-C does not cause an exit to DOS)
The Read Key Procedure may distinguish these cases suitably (for example, via
Carry flag). In the following routine, Z = 1 indicates that no key was typed. If Z =
0, the key code is returned in AL and the CARRY is cleared to indicate standard
key code and it is set to indicate extended key code.
KEYS
PROC FAR
MOV
AH, 06H
MOV
DL, 0FFH
INT
21H
JE
KEYS
OR
AL, AL
JNZ
KEYS1
INT
21H
STC
KEYS1: RET
KEYS
ENDP
This service is used to read an entire line of characters. The characters read are
maintained in a buffer. Thus, this is Buffered Keyboard Input service.
Function Code: 0A H
Input Parameters:
DS:DX = Address of the Buffer
First byte of Buffer = Maximum Number of Characters to be read (up to 255)
Characters are read (displaying them as they are read) until the specified number
of characters are read OR until the Enter key (code is 0DH) is typed.
Upon return:
Hence, the Buffer Size must be 2 more than the number of characters to be read!
.MODEL
SMALL
.DATA
BUF1 DB
.CODE
.STARTUP
MOV BUF1, 100
21H
Function Code: 02H or 06H As both of these are quite similar, we will illustrate
the use of Function Code 6 only.
TINY
.CODE
.STARTUP
MOV AH, 06H
MOV DL, 41H ; Display character A, ASCII code is 41H
INT
21H
.EXIT
END
Display Character String:
It could include control characters like Carriage Return (0DH), Line Feed (0AH)
etc. However, the character $ is used as the terminator and thus can not be part of
the string. ($ could be displayed as a single character using Function Code 06H as
explained above.)
MODEL SMALL
.DATA
MSG1
DB
.CODE
.STARTUP
MOV AH, 09H
MOV DX, OFFSET MSG1
INT
21H
.EXIT
END
Terminate Program:
EXIT directive used in all the examples described so far effects program
termination by using Function Code 4CH (Terminate Program)
21H
Instead of .EXIT, the above 2 lines could be directly written by the programmer.
These services allow the user to set / read the interrupt vector corresponding to a
type code. This is preferred to directly manipulating the Interrupt Vector Table.
Advanced Microprocessors
Session XX
Modular Programming
11.11.2005
Dr. K.Rajanikanth
M.S.Ramaiah Institute of Technology, Bangalore
---------------------------------------------------------------Learning Objectives:
Concepts:
The basic idea is the classical Divide & Conquer approach. Program is
composed from several smaller modules. Modules could be developed by separate
teams concurrently. The modules are only assembled producing .OBJ modules
(Object modules). Each module is produced from a separate Assembly Language
program.
Concepts - 2
ASM File #1
Assembler
ASM File #2
Assembler
.OBJ file
.OBJ file
Linker
ASM File #n
Assembler
.EXE
.OBJ file
Concepts - 3
ASM File
Assembler
ASM File
Assembler
.OBJ file
.OBJ file
Linker
.EXE
In Module A , we defined
BUF1 DB 10 DUP (?)
BUF1 is not defined in Module B. Thus, when assembling Module B, we will get
the assembly error of Undefined Symbol. Note that the symbol is actually
defined in Module A. But, the two modules are assembled independently!
Solution:
Properly used, Public and External facilities allow modules to communicate with
each other, which is essential for Modular Programming.
File 1: PROG1.ASM
.MODEL SMALL
.DATA
PUBLIC
BUF1
PUBLIC
BUF2
BUF1 DB
10 DUP (?)
BUF2 DW
10 DUP (?)
.CODE
.STARTUP
PUBLIC
RDKEY PROC
MOV AH, 1
INT 21H
RDKEY
ENDP
END
RDKEY
FAR
In another program PROG2.ASM, we make use of the symbols BUF1, BUF2 and
RDKEY. We declare them as EXTRN. Such a declaration indicates that the
definitions for these symbols are not in this module; how ever this is not to be treated
as an error. These symbols are expected to be defined in other modules which will be
specified during LINK time.
Further, note that the type of the EXTRN data items must be declared for proper
assembly. Similarly, the FAR / NEAR nature of an EXTRN procedure also must be
declared for the Assembler to generate correct code.
File 2: PROG2.ASM
.MODEL
SMALL
.DATA
EXTRN
BUF1:BYTE
EXTRN
BUF2:WORD
.CODE
EXTRN
RDKEY:FAR
.STARTUP
MOV DX, OFFSET BUF1
MOV CX, 10
L1:
CALL RDKEY
STOSB
LOOP L1
MOV BUF2, AX
.EXIT
END
Another way that more clearly illustrates the Modular Programming approach is
as follows :
Only assemble (not link) the two programs separately, getting the two
.OBJ files.
Run LINK utility and specify the two .OBJ files as inputs.
LIBRARIES:
Only the required .OBJ files are extracted from the Library File and linked in to
the program.
LIB Command:
The LIB command provides the following facilities:
Replace an existing .OBJ file in the Library with another .OBJ file with the same
name (equivalent to Delete followed by Add)
If the named Library file does not exist, the system prompts whether to create?
Type Y
Examples
Create a Library file called MYIO1.LIB and add the module PROG1 to the
library:
>LIB MYIO1.LIB
Copyright messages etc from the utility
Library file does not exist. Create? Y
Operations: +PROG1
List File: MYIO1
To the Library file called MYIO1.LIB add the module PROG2:
> LIB MYIO1.LIB
Copyright messages etc from the utility
Operations: +PROG2
>
To the Library file called MYIO1.LIB add the module PROG3:
>LIB MYIO1.LIB
Copyright messages etc from the utility
Operations: +PROG3
>
Alternatively, the 3 modules could be added to the Library file as shown below:
>LIB MYIO1.LIB
Copyright messages etc from the utility
Library file does not exist. Create? Y
Operations: PROG1 + PROG2 + PROG3
List File: MYIO1
>
From the Library file called MYIO1.LIB, remove the module PROG2:
> LIB MYIO1.LIB
Copyright messages etc from the utility
Operations: -PROG2
>
Once we create Library files, we can use them to link the required modules in to
the application program by specifying the Library files to the Linker. With ML or
with LINK, specify the Library files required in response to the prompt
Libraries [.lib]:
Macros
Macros provide several powerful mechanisms useful for the development of
generic programs.
We could consider the macro as shorthand for a piece of text; somewhat like a
new pseudo-code instruction.
Macros are similar to procedures in some respects, yet are quite different in many
other respects.
Procedure:
Execution time overhead is present because of the call and return instructions.
Macro:
CALL
Macro invoked
MACRO
Inserted in
place
RETURN
MACRO Definition:
A macro has a name. The body of the macro is defined between a pair of directives,
MACRO and ENDM. Two macros are defined in the example given below.
Examples of Macro Definitions:
; Definition of a Macro named PA2C
PA2C
MACRO
PUSH AX
PUSH BX
PUSH CX
ENDM
MACRO
POP CX
POP BX
POP AX
ENDM
Note how the macro name is replaced by the associated set of instructions. Thus,
macro name does not appear in the expanded source code. In other words, the actual
Assembler does not see the macros. What gets assembled is the expanded source.
This process is illustrated in the following figure:
MACROS (continued)
.ASM file
with Macros
Macro
Preproc
essor
Assemble &
Link
.EXE file
Example:
COPY
MACRO
A,B
PUSH AX
MOV AX, B
MOV A, AX
POP AX
ENDM
The macro is invoked in the following code with actual parameters as VAR1 and
VAR2. Thus during the macro expansion, the parameter A is replaced by VAR1 and
the parameter B is replaced by VAR2.
COPY
VAR1, VAR2
Assume that a macro definition includes a label RD1 as in the following example:
READ MACRO
PUSH
RD1: MOV
A
DX
AH, 06
MOV
DL, 0FFH
INT
21H
JE
RD1
MOV
A, AL
POP
DX
ENDM
The problem is that the label RD1 appears in the expansion of READ VAR1 as
well as in the expansion of READ VAR2. Hence, the label RD1 appears in both
the expansions. In other words, the Assembler sees the label RD1 at two different
places and this results in the Multiple Definition error!
LOCAL
RD1
PUSH
DX
RD1: MOV
AH, 06
MOV
DL, 0FFH
INT
21H
JE
RD1
MOV
A, AL
POP
DX
ENDM
VAR1
DX
AH, 06
MOV
DL, 0FFH
INT
21H
JE
MOV
VAR1, AL
POP
DX
Subsequently, if we write
READ
VAR2
DX
AH, 06
MOV
DL, 0FFH
INT
21H
JE
MOV
VAR2, AL
POP
DX
Note how each invocation of the READ macro gets expanded with a new and
unique label, generated automatically by the Assembler, in place of the local variable
RD1. Further, note that LOCAL directive must immediately follow the MACRO
directive. Another feature to note is that Comments in Macros are preceded by ;; (two
semicolons) , and not as usual by ; (a single semicolon).
File of Macros:
We can place all the required Macros in a file of its own and then include the file
into the source.
Advanced Features:
Conditional Assembly
Conditional Assembly:
Example: Assume that our generic program has the following statements:
IF WIDT
WIDE
DB
72
DB
80
ELSE
WIDE
ENDIF
Now the assembly language program that is generated depends on the value of
WIDT. Assume the block is preceded by
WIDT EQU 1
Then the assembled code is:
WIDE DB
72
It is important to note that the Assembler sees a source file that has only the above
statement.
Another case:
WIDT EQU 0
IF WIDT
WIDE DB 72
ELSE
WIDE DB 80
ENDIF
80
There are several other directives that can be used for Conditional Assembly as
listed below:
IF
IFB
IFNB
IFDEF
IFNDEF
IFIDN
IFDIF
With each of the above constructs, the code that follows gets assembled only if the
stated condition is true.
REPEAT Statement:
This statement allows a block of code to be repeated the specified number of times.
This avoids repetitive typing and is much more elegant than Editor-level Copy-andPaste operation.
Example:
REPEAT 3
INT 21H
INC
DL
ENDM
The generated code would be 3 repetitions of the block of 2 statements enclosed
within REPEAT and ENDM as shown below:
INT 21H
INC DL
INT 21H
INC DL
INT 21H
INC DL
WHILE Statement:
This statement allows a block of code to be repeated while the condition specified
with the WHILE is true.
Example: Consider the following code
SQ LABEL BYTE
SEED = 1
RES = SEED * SEED
WHILE RES LE 9
DB
RES
SEED = SEED + 1
RES = SEED * SEED
ENDM
Note that SEED and the arithmetic statements involving SEED and RES are all
Assembly time actions. Apart from the initial label SQ, the only statement to actually
get repeated is DB RES.
The logic is follows: Initially the label SQ is generated. SEED is initialized to 1 and
RES is computed as 1 * 1 = 1. Now RES LE 9 is true as the value of RES is 1 which
is less than 9. So the code DB 1 is generated. The next statement within the scope of
WHILE, SEED = SEED + 1 is executed making SEED assume the value of 2. The
next statement within the scope of WHILE is RES = SEED * SEED. This is also
executed and RES assumes the value of 4. This completes one pass of execution of
the WHILE block. So, the condition associated with WHILE is again evaluated. This
is again TRUE as 4 is less than 9. So again DB 9 is generated. Reasoning as before,
we see that DB 9 is also generated. However, in the next pass SEED is 4 and RES is
16. So the condition RES LE 9 evaluates to FALSE and WHILE loop is exited!
Thus the generated code is:
SQ
DB
01
DB
04
DB
09
FOR Statement:
This is very similar to the FOR of languages like PERL. With the FOR statement, a
control variable and a list of values are specified. The control variable is successively
assigned values from the specified list and for each such value, the following block of
statements is repeated.
Example:
DISP MACRO CHR:VARARG
MOV AH, 2
FOR ARG, <CHR>
MOV DL, ARG
INT
21H
ENDM
ENDM
The outer Macro has one parameter which is specified as sequence of characters of
variable length. The inner FOR statement has two enclosed statements which will be
repeated for each value in the list <CHR>. Thus in the following illustration, DISP is
invoked with 3 characters as parameters. The two statements within FOR scope are
thus repeated 3 times with ARG successively assuming the 3 characters.
Thus, the statement
DISP V,T,U
gets expanded as
MOV
AH, 2
MOV
DL,V
INT
21H
MOV
DL, T
INT
21H
MOV
DL, U
INT
21H
Summary:
Used properly, they can reduce effort required to develop large and complex
programs. Further, Macros make it easy to develop Generic Programs which can
be easily adapted for specific applications.
Advanced Microprocessors
Session XXI
Data Conversion Routines
15.11.2005
Dr. K.Rajanikanth
----------------------------------------------------Learning Objectives:
Learn to develop Data Conversion Routines
Introduction:
Often Data available in one format needs to be converted in to some other format.
Examples:
ASCII to Binary
Binary to ASCII
Algorithm
Look Up Table
Another Example: Binary number: 0000 0010 0100 0011 = 0243H = 579 D
To display this on the screen, we need Three ASCII characters, 5, 7 and 9.
ASCII code for character 5 is 35H,
ASCII code for character 7 is 37H, and
ASCII code for character 9 is 39H
So, we need to produce 35H, 37H and 39H as output given 0243H as input
Divide 57 by 10;
Divide 5 by 10;
While retrieving, add 30H to convert the digit to ASCII code and then display it
(or print it, or save it)
; Test value
CALL B2A
.EXIT
B2A
PROC
NEAR
PUSH DX
PUSH CX
PUSH BX
B2A1:
MOV
CX, 0
MOV
BX, 10
; Divisor is 10
MOV DX, 0
DIV
; Divide by 10
BX
PUSH DX
INC
CX
OR
AX, AX
JNZ
B2A1
DX
; Retrieve remainder in DL
; Convert to ASCII
INT
21H
LOOP B2A2
BX
POP
CX
POP
DX
RET
B2A
ENDP
END
Notes:
DIV instruction requires the 32-bit dividend in the register pair DX and AX.
The number to be converted (and subsequently, the quotient) is in AX. So, DX
is cleared to 0 to set up the correct dividend.
When the input number is less than 100, an alternative, simpler method exists.
Separate the two bytes (unpack) to get the two ASCII characters representing the
given number (33H and 39H).
Works only when the number is less than 100 as the maximum unpacked BCD
that we can have in the AX register is 0909H only.
AL, 2AH
; Test value
CALL
B2A
.EXIT
B2A
PROC
NEAR
PUSH DX
MOV AH, 0
; AX = Number
AAM
; AX = Unpacked BCD
; Convert to ASCII
PUSH AX
; Now, unpack and display
MOV DL, AH
; First Digit
; Display Function
INT
21H
POP
AX
; Retrieve value
MOV DL, AL
; Second Digit
; Display Function
INT
21H
DX
RET
B2A
ENDP
END
Refinements:
Can we replace leading 0 with a blank so that the display looks better? Thus,
instead of 07, the display should be 7.
Yes. We need to check if the first digit is 0. If so, display 20H (blank);
else, display the digit.
We need to modify the previous program to incorporate this check for a leading 0.
21H
B2A1:
; First Digit = 0?
JZ
B2A1
; Add 10H more to get the correct ASCII Code for the digit
MOV DL , AH
; First Digit
21H
AL, 2AH
; Test value
CALL
B2A
.EXIT
B2A
PROC
NEAR
PUSH DX
MOV AH, 0
; AX = Number
AAM
; AX = Unpacked BCD
; Convert to ASCII
PUSH AX
; Now, unpack and display
ADD AH, 20H
CMP AH, 20H
; First Digit = 0?
JZ
B2A1
INT
21H
POP
AX
; Retrieve value
MOV DL, AL
; Second Digit
; Display Function
INT
21H
DX
RET
B2A
ENDP
END
Conversion Procedure:
First ASCII digit 31H; Subtract 30H to get corresponding BCD digit 01H.
Next ASCII digit 35H; Subtract 30H to get corresponding BCD digit 05H.
Next ASCII digit 36H; Subtract 30H to get corresponding BCD digit 06H.
Based on the above ideas, the following program implements the ASCII to Binary
Conversion.
DW
.CODE
.STARTUP
SMALL
CALL RDNUM
MOV TEMP, AX
.EXIT
RDNUM PROC NEAR
PUSH BX
PUSH CX
RDN1:
MOV CX, 10
; Multiplier is 10
MOV BX, 0
; Result initialized to 0
MOV AH, 1
INT
21H
; Check the character. If less than 0 or greater than 9 Number entry is over
CMP AL, 0
JB
RDN2
CMP AL,9
JA
RDN2
AL, 30H
; BCD Digit
PUSH AX
MOV AX, BX
MUL
CX
MOV
BX, AX
POP
AX
MOV
AH, 0
; AX = Current Digit
ADD
BX, AX
; Update Result
JMP
RDN1
; Repeat
; Result = Result * 10
MOV
AX, BX
POP
CX
POP
BX
RET
RDNUM
ENDP
; Result in AX
END
Notes:
a
f
b
dp g
g
e
Bit = 1 Segment is on
d
dp
= 0 Segment is off
a
f
b
0
g
e
dp
Based on the above logic, the following FAR Procedure returns the 7-Segment code
in the AL register, corresponding to the BCD digit provided as input parameter in the
AL register before calling the procedure.
; BCD to 7-Segment Code Program
; Input: AL = BCD Digit
; Output: AL = 7-Segment code.
BT7SEG
PROC FAR
PUSH BX
MOV BX, OFFSET TABLE
XLAT CS: TABLE
POP BX
RET
TABLE
DB
3FH ; 0
DB
06H ; 1
DB
5BH ; 2
DB
4FH ; 3
DB
66H ; 4
DB
6DH ; 5
BT7SEG
DB
7DH ; 6
DB
07H ; 7
DB
7FH ; 8
DB
6FH ; 9
ENDP
Notes:
XLAT instruction does not normally contain an operand. Here we are using the
operand (TABLE). It is a dummy operand! It is being used here only to specify
segment override. XLAT uses DS by default. Here the table is in CS. So segment
override is being specified.
Advanced Microprocessors
Session XIV
Program Control Instructions - 1
21.10.2005
Dr. K.Rajanikanth
M.S.Ramaiah Institute of Technology, Bangalore
------------------------------------------Learning Objectives:
Learn to use conditional and unconditional jump instructions to control flow of program.
Examples:
Instruction at reset CS:IP: At rest, 8086 begins execution at the address
FFFF:0000H (absolute address of FFFF0H). There are only 16 bytes from this
location to the end of the memory space (FFFFH)! It is unlikely that any
meaningful program can be written within this space. Thus the instruction at this
reset location is usually a long jump instruction that transfers control to some
suitable lower address based on the available memory.
A Sorting Program: A comparison-based sorting program would need to swap or
not swap two elements based on the outcome of the comparison of the two
elements. This would mean that we need an instruction to conditionally jump to
some other location in the program.
Any number of such examples can be given to illustrate the need for instructions
that alter the linear flow of control, either unconditionally or conditionally.
Unconditional and Conditional Jump Instructions allow such a control over the
execution flow.
Unconditional Jump:
After:
CS=FFFF; IP=0000
CS=F000; IP=8000
FFFF0
F0
00
80
00
EA
Unconditionally
Jump here
F8000
01
00
B8
Target
Location
The instructions used for such unconditional jumps are discussed in detail later.
Conditional Jump:
Values of one or more flags are used in deciding whether a jump is to be executed
or not.
Thus, a jump may or may not occur depending on the values of such flag bits
The instructions used for such conditional jumps are discussed in detail later.
All have similar behavior; but differ in where the target instruction is allowed to
be and consequently, the instruction lengths also differ. And that is the main
advantage.
Both Short Jump and Near Jump are called intra-segment jumps also because in
both the cases, there is no change in the CS value and only IP is changed. In other
words, the jump is to a location that is within the same code segment.
For these jumps, the target IP value is not specified as absolute value. Instead,
displacement (relative distance) from the current IP is specified.
Thus both are relative jumps. (Called Relative Program Memory Addressing in
earlier sessions)
Jump can be forward (to a higher address) or backwards (to a lower address).
Short and Near Jumps differ in the way the displacement is specified.
This instruction occupies 2 bytes; the first byte specifies the opcode and the
second byte specifies the relative displacement as a signed 8-bit quantity. The
format is shown below:
Opcode
EB
Displacement
8-Bit Signed Value
Jmp Target
10002
10001
10000
1A
EB
10005
10004
10003
F2
EB
Jmp Target
In a typical Assembly Language Program, we use labels for branch targets and
the Assembler will automatically compute the displacement.
Anyway, most Assemblers choose the short form if possible (that is, if the
displacement is in the range of -128 to +127)
Example: JMP $ + 2 jumps over the next 2 memory locations following the JMP
instruction. Thus if the above instruction starts at 1000:0010, the after the jump,
control is transferred to the instruction at 1000: 0014
This is quite similar to Short Jump except that the displacement is specified as
16 Bit signed integer rather than as 8-bit integer.
Instruction is 3 Byte long. The first byte specifies the opcode and the next two
bytes specify the displacement. The format is shown in the following figure:
Opcode
E9
Displacement
Low Byte
High Byte
10003
10002
10001
10000
FF
F2
E9
10006
10005
10004
XOR BX, BX
ST1: MOV AX, 1
ADD AX, BX
JMP NXT5
; Some instructions
NXT5: MOV BX, AX
The above program is quite similar to Short Jump Program listed earlier except that the
displacement to NXT5 is assumed to be greater than 127 and hence the instruction JMP
NXT5 is assembled as Near Jump.
This instruction is 5 Byte long. The first byte specifies the opcode, the next 2
bytes specify the new IP value and the last 2 bytes specify the new CS value. The
format is shown in the following figure:
IP
Opcode
EA
Low
Byte
CS
Low
Byte
Low
Byte
Low
Byte
10
00
00
20011
20010
04
EA
10005
10004
10003
Jmp Target
In such cases, the Linker will fill the CS and IP values at the link time.
JMP L1
A 16-Bit register may be used as the operand for the jump instruction. (Indirect
Jump)
Contents of the register are transferred directly into IP (no concept of relative
displacement).
FAR PTR directive indicates a far jump ( jump table is assumed to contain
double words giving CS, IP values)
Conditional Jump
Conditional jumps are always short jumps (relative displacement is -128 to +127).
Based on the values of one or more flags, jump to target address may occur or
execution may continue with the next sequential instruction.
Usually preceded by instructions like CMP, SUB, TEST, AND etc which affect
the flags.
Example:
CMP AX, BX
JZ
LAB1
MOV AX, BX
LAB1: MOV CX, AX
In the above program, equality of the operands is tested based on the Z flag.
Thus, we have one set of conditional jump instructions that are to be used if the
numbers are to be interpreted as
Mnemonic
Condition
JA
Jump if above
JAE
C=0
JB
C=1
Jump if below
JBE
Z=1 or C=1
Operation
Mnemonic
Condition
Operation
JG
JGE
S=O
JL
S< >O
JLE
(Both S and O Flags are required to test the condition when comparing signed numbers!)
Mnemonic
Condition
Operation
JE or JZ
Z=1
JNE or JNZ
Z=0
Mnemonic
Condition
Operation
JC
C=1
JNC
C=0
Jump if no carry
JO
O=1
Jump if overflow
JNO
O=0
Jump if no overflow
JS
S=1
JNS
S=0
Jump if no sign
Mnemonic
Condition
Operation
JP or JPE
P=1
JNP or JPO
P=0
JCXZ
CX = 0
Jump if CX = 0
(Note that the last instruction, JCXZ is some what different from the rest in the sense
that it tests the contents of CX register rather than flags. This instruction, generally
used in loops, is illustrated in later sessions. Programs illustrating other conditional
jump instructions are also discussed in later sessions.)
Advanced Microprocessors
Session XV
Program Control Instructions - 2
25.10.2005
Dr. K.Rajanikanth
Understand machine control instructions (WAIT, ESC, NOP, HLT & LOCK
Prefix)
LOOP Instruction:
Program loops are quite common. Most of the counting loops have a typical
structure that is shown below:
MOV CX, 10H ; Initialize the count that determines the number of
; times the loop is to be executed.
Start1: Instructions constituting the loop body
DEC CX
; Decrement counter
If the pair of instructions that test whether the loop body is to be executed again or
not, that is the instructions, DEC CX and JNZ Start1, could be combined in to
one instruction, we would get more elegant and clearer program.
These instructions are similar to LOOP instruction except that equality (Z flag) is
also tested. This allows a loop to be controlled by a count as well as a comparison
test (like in the case of String instructions).
ESC Instruction
This instruction is related to 8087 Numeric Data Coprocessor. Details of 8087 are
discussed in later sessions. Briefly, 8087 provides support for floating point
operations and works as a coprocessor to 8086. It
The program has instructions for 8086 as well as 8087. How does 8087 know the
instruction is for itself? The solution to this problem is the ESC instruction.
ESC indicates that it is 8087 instruction. Opcode has 11011 as the higher-order 5
bits. Thus ESC is never used by itself.
WAIT Instruction
TEST/ is sampled during leading edge of CLK in each clock cycle during
waiting.
When 8086 needs the result from 8087, it executes the WAIT instruction.
When 8087 is busy executing its instruction, it sets its BUSY pin = HIGH. Thus
TEST/ of 8086 will also be HIGH. This forces 8086 to wait for the completion
of 8087 activity.
When 8087 is not executing its instruction, its BUSY pin = LOW and thus the
TEST/ of 8086 will also be LOW. This allows 8086 to continue its execution.
NOP Instruction
Used in early days to provide for manual code patches. Some NOP instructions
would be written every 100 bytes or so. When code was to be patched, the space
occupied by the NOP instructions was used. However, this is irrelevant in modern
times because the program development usually is based on Assemblers nad
manual coding is no more common.
Another use for this instruction is that it could be used for producing short time
delays if delay accuracy is not of concern.
HLT Instruction
As the name implies, it halts the program; the processor enters the HALT
state.
An interrupt or a hardware reset will force the 8086 out of the HALT state.
May be used when the program has to wait for an interrupt to occur; but rarely
used so in practice.
In the early days, this instruction was used in the trainer kits as the last instruction
of a user program. It is no more used in this fashion. In fact, presently it is rarely
used for any other purpose either!
LOCK Prefix
When such an instruction is executed, the LOCK/ pin of 8086 is activated (forced
LOW). Now, another bus master can not gain control of the bus until the end of
the bus lock. Thus the Lock prefixed instruction executes as an indivisible
instruction even if it has several memory cycles. (Without the LOCK prefix, the
bus could be taken over by another bus master after a memory cycle, even if the
current instruction is not completed!)
Procedures
Only one copy of the procedure is stored in the memory; and it can be called as
many times as needed.
As only one copy is stored, it saves memory; but has execution time overhead for
the call and return operations.
CALL transfers control to the procedure like with a jump; but unlike a jump,
procedure has a RETURN instruction which returns control to the instruction
following the CALL instruction! In order to implement such a return, the
necessary information is stored on a stack, before transferring control to the
procedure.
Further, nested procedures calls are possible. In other words, Procedure A can call
Procedure B which in turn calls Procedure C. After completing Procedure C,
control returns to Procedure B and after completing Procedure B, control returns
to Procedure A. Logically, such a nesting of calls can be to any level, though in
practice Assemblers impose implementation-dependent limits on the nesting
depth.
Procedure
JMP
CALL
RETURN
Nesting of Procedures
CALL
CALL
CALL
RETURN
RETURN
RETURN
From the above figure we see that return addresses are known in one order and
are used for implementing return in exactly the reverse order. Thus a Stack
would be the most convenient data structure for storing return addresses
Call can be to a procedure in the same code segment. In such a case, we specify
only IP as relative distance or indirectly as actual value. This is known as NEAR
CALL.
In ALP, procedure starts with PROC directive and ends with ENDP directive.
Similar to Near Jump except that current IP is saved on the stack before
transferring control to the new IP with CS remaining the same.
opcode
E8
Displacement
Low Byte
High Byte
10003
10002
10001
10000
20
1A
E9
10006
10005
10004
00
03
Saving IP:
Before CALL:
SS = A000 H ; SP = A000 H
IP = 0003
In ALP, NEAR indicates near procedure. The following program fragment illustrates the
coding and using of a near procedure:
ST1
ST1
ENDP
CALL ST1
FAR CALL is like FAR JMP in the sense that it can call a procedure available
any where in the code space.
Both current IP and CS are saved on the stack and then control is transferred to
the new CS:IP
The instruction is 5 Byte long. The first byte specifies the opcode, the next two
bytes specify the new IP value and the next two bytes specify the new CS value.
The format is shown below:
IP
opcode
E8
Low
Byte
CS
High
Byte
Low
Byte
High
Byte
The operation of the Far Call instruction is illustrated in the following figure:
10
00
00
20011
20010
04
9A
10005
10004
10003
Branch to 10004 H
Far Procedure
Example:
SUM1 PROC FAR
SUM1 ENDP
Now, a CALL to SUM1 is assembled as FAR CALL.
As with JMP, 16-Bit register may be used as the operand for the CALL
instruction. (Indirect CALL)
Again, as with JMP, contents of the register are transferred directly into IP (no
concept of relative displacement).
FAR PTR directive indicates a far CALL ( the table is assumed to contain double
words giving CS, IP values)
The control returns to the instruction following the CALL instruction in the
calling program. Corresponding to the two varieties of CALL instructions (near &
far), two forms of RET instructions (near & far) exist.
Near RET instruction pops a 16-Bit word from the stack and places it in the IP.
Far RET instruction pops two 16-Bit words from the stack and places them in IP
& CS.
In ALP, RET is written within the procedure, before the ENDP directive and the
Assembler will automatically select the proper RET instruction!