Title: Assembly Language Lecture 4
1Assembly LanguageLecture 4
- CE 3105
- By
- Niravesh Srikalra
2Overview
- JMP and LOOP instructions
- More about the assembler and linker
- Operators and expressions
- Indirect addressing
- More 80386 and 80486 instructions
- DOS Function Calls
3JMP and LOOP Instructions
- JMP is an unconditional jump to a code label
- LOOP creates a counting loop, using CX as the
default counter - LOOPD uses ECX as the counter register
- LOOPW uses CX as the counter register
- (only necessary in 32-bit mode programming)
4JMP Distance Modifiers
- JMP SHORT destination
- /- 127 bytes
- JMP NEARPTR destination
- same code segment
- (default in the small and compact memory models)
- JMP FARPTR destination
- different code segment
- (default in the large, medium, and huge memory
models)
5JMP Example
- Unconditional Transfer of control to a label
Label1 . . jmp Label1
6Instruction
t
- Compare Transfer Logical Shift and
- Operations Operations Operations
Rotate - CMP CALL AND SAR/SHR
- TEST jmp NOT SAL/SHL
- Jnnn OR RCR/ROR
- LOOP XOR RCL/ROL
- RETn
- Jnnn means all condition jump instructions such
as JNE and JL.
7SHORT, NEAR, AND FAR ADDRESSES
- 1. A short address, limited to a distance of -128
(80H) to 127 (7FH) bytes. - 2. A near address, limited to a distance of
-32,768 (8000H) to 32,767 (7FFFH) bytes within
the same segment. - 3. A far address, which may be within the same
segment at a distance over 32K, or in another
segment.
8Short, Near, and Far addresses
9JMP
- The operand of a JMP, Jnnn (conditional jump), or
LOOP instruction refers to the label of another
instruction. - The following example jumps to L10, which is the
label of an INC instruction
JMP L10 L10 INC CX
10THE JMP INSTRUCTION
- A commonly-used instruction for transferring
control is the JMP (Jump) instruction. - A jump is unconditional because the operation
transfers control under all circumstances. - JMP also flushes the processor's prefect
instruction queue so that a program with many
jump operations may lose some processing speed. - The format for JMP is
- label jmp short/near/far address
11Short and Near Jumps
- A JMP operation within the same segment may be
short or near (or even far if the destination is
a procedure with the FAR attribute). On its first
pass through a source program, the assembler
generates the length of each instruction.
However, a JMP instruction may be two, three, or
four bytes long. A JMP operation to a label
within-128 (80H) to 127 (7FH) bytes is a short
jump. The assembler generates one byte for the
operation (EB) and one byte for the operand. The
operand acts as an offset value chat the
processor adds to the IP register when executing
the program. - A JMP that exceeds -128 to 127 bytes becomes a
near jump (within 32K), for which the assembler
generates different machine code (E9) and a
2-byte operand (8086/80286) or 4-byte operand
(80386). For now, we'll pass on the far jump.
12Backward Jumps
- A jump may be backward or forward.
- The assembler may have already encountered the
designated operand (a backward jump) within
-128 bytes, as in -
L10 Jump address Â
JMP L10 Backward jump
13Forward Jumps
- In this case, the assembler generates a 2-byte
machine instruction. - In a forward jump, the assembler has not yet
encountered the designated operand - Â Â
JMP L20 Forward jump L20 Jump address
14Example JMP instruction
- 0100 138 0000 MOV AX ,00 Initialize AX and
- 0103 BB 0000 MOV BX,00 BX to zero,
- 0106 B9 0001 MOV CX,01 CX to 01
- 0109 A20
- 0109 05 0001 ADD AX, O1 Increment AX
- O1OC 03 DS ADD BX,AX Add AX to BX
- 010E D1 E1 SHL CX,1 Double CX
- 0110 EB F7 JMP A20 Repeat
15THE LOOP INSTRUCTION
- The JMP instruction in the previous slide causes
an endless loop. But a standard practice is to
code a routine that loops a specified number of
times or until it reaches a particular condition.
- The LOOP instruction, which serves this purpose,
requires an initial value in CX. For each
iteration, LOOP automatically deducts 1 from CX.
Once CX reaches zero, control drops through to
the following instruction if CX is nonzero,
control jumps to the operand address. - The format for LOOP is
- label LOOP short-address
16LOOP
- Note The distance to the operand must be a short
jump, within -128 to 127 bytes. - For an operation that exceeds this limit, the
assembler issues a message such as relative jump
out of range."
17LOOP simulation
-
- jcxz A10
- A01 ...
- ...
- DEC CX
- JNZ A01
- A10
18LOOP example
- 0100 B8 0001 MOV AX,00 Initialize AX and
- 0103 BB 0001 MOV BX,00 BX to zero,
- 0106 BA 0001 MOV DX,01 DX to 01
- 0109 B9 OOOA MOV CX,8 Initialize for
- O1OC A20 8 loops
- O1OC 40 INC AX Increment AX
- O1OD 03 DS ADD BX,AX Add AX to BX
- 01OF D1 E2 SHL DX,1 Double DX
- 0111 E2 F9 LOOP A20 Decrement CX,
- loop if nonzero
19LOOPE/LOOPZ and LOOPNE/LOOPNZ
- There are two variations on the LOOP instruction,
both of which also decrement CX by - 1. LOOPE/LOOPZ (loop while equal/zero)
- continues looping as long as CX is zero
or - the zero condition is set.
- 2. LOOPNE/LOOPNZ (loop while not equal/zero)
- continues looping as long as CX is not
zero or - the zero condition is not set.
- Neither LOOP nor its LOOPxx variants changes the
setting of any flags in the Flags register.
However, because other instructions within the
loop routine do change flags, the program in
Figure 7-2 uses LOOP, and not its LOOPxx variants.
20The Flags Register
- The remaining material in this chapter requires a
more detailed knowledge of the Flags register. - This register contains 16 bits, which various
instructions set to indicate the effect of their
operation. - In all cases, a flag remains set until another
instruction changes it. - The Flags register contains the following
commonly-used bits - Â
Bit no. 15 14 13 12
11 10 9 8
7 6 5 4 3
2 1 0 Flag.
O
D I T S Z
A P
C
21The Flags Register
- CF (Carry Flag).
- Contains a carry (0 or 1) out of the high-order
(leftmost) bit of a data item following an
unsigned arithmetic operation and some shift and
rotate operations. Some disk operations use the
CF to indicate success (0) or failure (I). JC and
JNC test this flag.
22The Flags Register
- PF (Parity Flag).
- Contains a check of the low-order eight bits of
a data item after an arithmetic operation. An
even number of 1-bits clears the PF to 0, and an
odd number of 1bits sets it to 1. This flag is
not to be confused with the parity bit described
in Chapter 1 and is seldom of concern in
conventional programming. JP and JPO test this
flag. - Â
23The Flags Register
- AF (Auxiliary Carry Flag). Concerned with
arithmetic on ASCII and BCD packed fields,
covered in Chapter 13. The AF is set when a
1-byte arithmetic operation causes a carry out of
bit 3 (the fourth bit from the right) into bit 4. - Â
24The Flags Register
- ZF (Zero Flag).
- Cleared or set as a result of an arithmetic or
logical operation. Unexpectedly, a nonzero result
clears the ZF to 0, and a zero result sets it to
1. However, the setting, if not apparently
correct, is logically correct 0 means no (the
result is not equal to zero), and 1 means yes
(the result equals zero). JE and JZ (among other
instructions) test the ZF.
25The Flags Register
- SF (Sign Flag).
- Set according to the sign
- (high-order or leftmost bit)
- of a data item following an arithmetic
operation - A positive value clears the SF to 0, and
negative sets it to 1. - JG and JL (among other instructions) test the
SF. - Â
26The Flags Register
- TF (Trap Flag).
- When set, causes the processor to execute in
single-step mode,that is, one instruction at a
time under user control. Debuggers set the TF for
single-step execution, and that's about the only
place where you'd expect to find it. The INT 03
operation is used to set the TF. - Â
27The Flags Register
- IF (Interrupt Flag).
- Disables external interrupts when 0, and enables
interrupts when 1. The IF may be set by an STI
instruction and cleared by CLI, and is used
in-critical situations. - Â
- DF (Direction Flag).
- Used by string operations to determine the
direction of data transfer. When the DF is 0, the
string operation performs left-to-right data
transfer when it is 1, the string operation
performs right-to-left data transfer
28The Flags Register
- OF (Overflow Flag).
- Indicates a carry out of the high-order
(1eftmost) sign bit of a data item following a
signed arithmetic operation. JO and JNO test the
OF.
29CMP instruction
- CMP is used to compare two numeric data fields,
one or both of which are contained in aregister. - Its format is
-
- The result of a CMP operation affects the AF, CF,
OF, PF, SF, and ZF flags, although you do not
have to test these flags individually.
label CMP register/memory,register/memory/immed
iate
30CMP
- The following code tests DX for a zero value
- CMP DX,00 DX zero?
- Â
- JE L10 If yes, jump to L10
- (action if nonzero)
-
- L10 ... Jump point if DX zero
- Â
- If DX contains zero, CMP sets the ZF to 1, and
may or may not change the settings of other
flags. The JE (Jump if Equal) instruction tests
only the ZF. Because ZF contains 1 (meaning a
zero condition), JE transfers control (jumps) to
the address indicated by operand L10.
31CMP
- In effect, a CMP operation compares the first to
the second operand for example, is the value of
the first operand higher than, equal to, or lower
than the value of the second operand? (CMP acts
like SUB without the additional storage cycle
required for execution.) The next section
provides the various ways of transferring control
based on tested conditions.
32CONDITIONAL JUMP INSTRUCTIONS
- The processor supports a variety of conditional
jump instructions that transfer control depending
on settings in the Flags register. For example,
you can compare or add two fields and then jump
conditionally according to flag values that the
compare sets. The format for the conditional jump
is - label Jnnn short-address
33Signed and Unsigned Data
- An unsigned numeric item (logical data) treats
all bits as data bitstypical examples are
numeric values such as customer numbers, phone
numbers, and many rates and factors. - A signed numeric item (arithmetic data) treats
the leftmost bit as a sign, where 0 means
positive and 1 means negative typical examples
are quantity, bank balance, and temperature,
which may be either positive or negative. -
34Example
- In the next example, assume that CX contains
11000110 and DX contains 00010110. - The instruction CMP CX,DX compares the contents
of CX to the contents of DX. - If you treat the data as unsigned, CX is larger
- If you treat the data as signed, however, CX is
smaller because of the negative sign. - The use here of CMP is valid, and you have to
select the appropriate conditional jump
instruction, such as JB (Jump Below) for unsigned
data or JL (Jump Low) for signed data.
35Jumps Based on Unsigned (Logical) Data
- The following conditional jumps are
- used for unsigned data
- Â
- Â
- Â
- You can express each of these conditional jumps
in one of - the two symbolic operations choose the one that
is clearer and more descriptive.
SYMBOL DESCRIPTION FLAGS TESTED JE/JZ Jump
Equal or Jump Zero ZF JNE/JNZ Jump Not Equal
or Jump Not Zero ZF JA/JNBE Jump Above or Jump
Not Below/Equal CF, ZF JAE/JNB Jump Above/Equal
or Jump Not Below CF JB/JNAE Jump Below or Jump
Not Above/Equal CF JBE/JNA Jump Below/Equal or
Jump Not Above AF, CF
36Jumps Based on Signed (Arithmetic) Data
- The following conditional jumps are used for
signed data - Â
- Â
- The jumps for testing equal/zero (JE/JZ) and not
equal/zero (JNE/JNZ) are included in the lists
for both unsigned and signed data because the
condition exists regardless of the presence or
absence of a sign.
SYMBOL DESCRIPTION FLAGS TESTED JE/JZ Jump
Equal or Jump Zero ZF JNE/JNZ Jump Not Equal
or Jump Not Zero ZF JG/JNLE Jump Greater or
Jump Not Less/Equal SF, OF, ZF JGE/JNL Jump
Greater or Equal or Jump Not Less
OF, SF JL/JNGE Jump Less or Jump Not
Greater/Equal OF, SF JLE/JNG Jump
Less/Equal or Jump Not Greater OF, SF, ZF
37Special Arithmetic Tests
- The following conditional jump instructions have
special uses - Â
- Â
- Â
- Â
- Â
SYMBOL DESCRIPTION FLAGS TESTED JCXZ Jump if
CX is Zero none JC Jump Carry(same as
JB) CF JNC Jump No Carry CF JO Jump
Overflow OF JNO Jump No Overflow OF JP/JPE
Jump Parity or Jump Parity Even PF JNP/JPO Jump
No Parity or Jump Parity Odd PF JS Jump
Sign(negative) SF JNS Jump No Sign(positive)
SF
38JCXZ
- JCXZ tests the contents of CX for zero. This
instruction need not be placed immediately
following an arithmetic or compare operation. One
use for JCXZ could be at the start of a loop to
ensure that the routine is bypassed if CX is
initially zero. JC and JNC are often used to test
the success or failure of disk operations.
39Reminder
- Now, don't expect to memorize the names of all
these instructions or the flags they test. As. a
reminder, however, note that a jump for unsigned
data is equal, above, or below, whereas a jump
for signed data is equal, greater, or less. The
jumps for testing the Carry, Overflow, and Parity
flags have unique purposes. The assembler
translates symbolic to object code, regardless of
which instruction you use but, for example, JAE
and JGE, although apparently similar, do not test
the same flags (because JAE assumes unsigned data
and JGE assumes signed data).
40Example Jnnn
- Example 1 Any Condition True Example 2 All
Conditions True
CMP AL, 0 CMP AL, 0 JE equal JNE not
equal CMP AL, 1 CMP AL, 1
JE equal JNE not equal CMP AL, 2 CMP AL,
2 JE equal JNE not equal not equal
ltprocessinggt equal ltprocessinggt ... ..
. equal ltprocessinggt... not-equal
ltprocessinggt
41Exercise
- Write a condition check in assembly for letters
input from the keyboard - Write a condition check in assembly for digits
input from the keyboard - Write a condition check in assembly for capital
letters input from the keyboard - Write a condition check in assembly for small
letters input from the keyboard
42More About the Assembler andLinker
- Topics
- Source Listing
- Map File
- Memory models
- Overlapping segments
- Target processor directives
43Source Listing
44Map File
- Segments always begin on even-paragraph
boundaries.
45Memory Models
46Overlapping Segments
Start Stop Length Name Class 00000 00010
00011 _TEXT CODE 00020 0002F 00010 _DATA
DATA 00030 0012F 00100 STACK STACK
Program entry point at 00000000
47Target Processor Directives
48Operator Precedence Table
49Offset, Seg , Ptr , Label, and Even
- OFFSET returns the 16-bit address (offset) of a
label - SEG returns the segment portion of a label's
address - PTR overrides the default size of an operand
- LABEL redefines the size attribute of a data
label - EVEN aligns the next instruction to a 16-bit
boundary - EVENDATA aligns the next data label on a 16-bit
boundary
50TYPE and SIZE Operators
- TYPE
- returns the size, in bytes of a single element
of a data label (variable) - LENGTH
- returns a count of the number of individual
elements in a data label that uses the DUP
operator - SIZE
- returns the product of TYPE LENGTH
51TYPE
- TYPE returns the size attribute
.data myByte db 1,2,3,4 myWord dw
1000h,2000h,3000h myDouble dd 12345678h myQuad dq
1,2,3 .code mov ax,TYPE myByte 1 mov ax,TYPE
myWord 2 mov ax,TYPE myDouble 4 mov ax,TYPE
myQuad 8
52LENGTH
- Returns a count of the number of individual
elements in a data label that uses the DUP
operator
.data myByte db 20 dup(?) myWord dw 5
dup(0) .code mov ax,LENGTH myByte 20 mov
ax,LENGTH myWord 5
53SIZE
- Returns TYPE multiplied by LENGTH
.data myByte db 20 dup(?) myWord dw 5
dup(0) .code mov ax,SIZE myByte 20 (20
1) mov ax,SIZE myWord 10 (5 2)
54Indirect Addressing
- Indirect Operands
- si, di, bx, bp
- Based and Indexed Operands
- arraysi, arraydi, arraybx
- Base-Index Operands
- bxsi, bxdi
- Base-Index with Displacement
- arraybxsi, arraybxdi
55Indirect Operand Example
.data aString db "ABCDEFG .code mov bx,offset
aString add bx,5 mov dl,bx
56Example
.data aList db 10h,20h,30h sum db 0 .code mov
bx,offset aList mov al,bx AL 10h inc
bx add al,bx AL 30h inc bx add al,bx
AL 60h mov si,offset sum get offset of
sum mov si,al store the sum
If you want to paste a code example such as this
into a program, remember that the code segment
must always begin with the following
statements mov ax,_at_data mov ds,ax
57Adding 16-bit Integers
.data wordList dw 1000h,2000h,3000h, 0 .code mov
bx,offset wordList mov ax,bx first
number add ax,bx2 second number add
ax,bx4 third number mov bx6,ax store
the sum
5832-Bit Registers
- The .386 directive permits any of the following
registers to be used as indirect operands - EAX, EBX, ECX, EDX, ESI, EDI, EBP
.386 mov ax,ebx3 mov dl,stringedx mov
ecx,esi mov ebx,eax
59Displaying a String
.data string db "This is a string." COUNT
(string) calculate string length .code mov
cx,COUNT loop counter mov si,offset
string L1 mov ah,2 DOS function display
char mov dl,si get character from array int
21h display it now inc si point to next
character Loop L1 decrement CX, repeat until
0
60Summing an Integer Array
.data intarray dw 0100h,0200h,0300h,0400h COUNT
( intarray) / (TYPE intarray) .code mov ax,0
zero accumulator mov di,offset intarray
address of array mov cx,COUNT loop
counter L1 add ax,di add an integer add
di,TYPE intarray point to next integer Loop L1
repeat until CX 0
61Based and Indexed Operands
- The Microsoft assembler permits the same address
expression to be notated in various ways
62Two Two-Dimensional Array Example
- Each row of this table contains five bytes. BX
points to the beginning of the second row
.data ROWSIZE 5 array db 2h, 16h, 4h, 22h,
13h db 19h, 42h, 64h, 44h, 88h .code mov
bx,ROWSIZE mov al,arraybx AL 19h
63Based-Index Operands
- Add the value of a base register to an index
register, producing an effective address of 0157
64Base-Index Example
.data ROWSIZE 5 array db 10h, 20h, 30h, 40h,
50h db 60h, 70h, 80h, 90h,0A0h db
0B0h,0C0h,0D0h,0E0h,0F0h .code mov bx,offset
array point to the array add bx,ROWSIZE
choose second row mov si,2 choose third
column mov al,bx si get the value
65Base-Index with Displacement
.data ROWSIZE 5 array db 10h, 20h, 30h, 40h,
50h db 60h, 70h, 80h, 90h,0A0h db
0B0h,0C0h,0D0h,0E0h,0F0h .code mov bx,ROWSIZE
row 1 mov si,2 column 2 mov dl,arraybx
si DL 80h
66Mismatching Operand Sizes
1 title Mismatching Operand Sizes 2 3 .model
small 4 .stack 100h 5 .code 6 main proc 7
mov ax,_at_data 8 mov ds,ax 9 mov
ax,value1 10 mov ah,value2 11 mov
ax,4C00h 12 int 21h 13 main endp 14 15
.data 16 value1 db 0Ah 17 value2 dw
1000h 18 end main (9) warning A4031 Operand
types must match (10) warning A4031 Operand
types must match
67Miscellaneous Errors
1 title Miscellaneous Errors Program 2 3
.model small 4 .stack 100h 5 .code 6 main
proc 7 mov ax,_at_data 8 mov ds,ax 9 mov
ax,bx cx 10 mov bx,value1 2 11 mov byte
ptr value3,al 12 mov cx,ax 13 mov cs,ds 14
mov ax,4C00h 15 int 21h 16 main endp 17
.data 18 value1 db 0Ah 19 value2 db 14h 20
value3 dw 1000h
68Intel386 and Intel486 Instructions
- MOVZX - Move with zero-extend extend
- moves 8-bit operand into a 16 bit register,
fills upper bit register with zeros - moves 16-bit operand into a 32 bit register,
fills upper bits with zeros - MOVSX - Move with sign-extend
- moves 8-bit operand into a 16 bit register, sign
extends into upper bits - moves 16-bit operand into a 32 bit register,
sign extends into upper bits
69MOVZX and MOVSX Examples
.data var16 dw 1234h var8 db -2 FEh .code mov
bl,22h movzx ax,bl AX 0022h movzx
edx,var16 EDX 00001234h movsx cx,var8
,var8 CX FFFEh
70DOS Function Calls (INT 21h)
- The INT 21h instruction activates a DOS function
call before invoking INT 21h register. - Some functions require that you assign values to
certain registers before invoking INT 21h. - Some functions return values in registers.
71Simple Console I/O
- mov ah,1 single character input
- int 21h
- mov ah,2 single character output
- mov dl,'A'
- int 21h
- mov ah,9 string output
- mov dx,offset message
- int 21h
72INT 21h Standard Input
- 01h Filtered Input With Echo
- 06h Direct Input Without Waiting
- 07h Direct Input, No Ctrl-Break
- 08h Direct Input with Ctrl-Break
- 0Ah Buffered Input
- 0Bh Get Input Status
- 0Ch Clear Input Buffer, Invoke Input Function
- 3Fh Read From File or Device
73Comparison of Standard Input
74Keyboard Parameter Record(Function 0Ah)
753Fh Read from File or Device
- When the user presses Enter at the end of the
input, two bytes (0Dh,0Ah) are appended to the
string in the input buffer and the count in AX
includes the extra characters.
buffer db 127 dup(0) .. mov ah,3Fh read from
file/device mov bx,0 device keyboard mov
cx,127 request 127 bytes maximum mov
dx,offset buffer int 21h AX number chars
typed 2
7640h Write to File or Device
buffer db 127 dup(0) count dw ? . mov ah,40h
read from file/device mov bx,1 device
console mov cx,count number of chars to
write mov dx,offset buffer int 21h
772Ah Get Date, 2Bh Set Date
mov ah,2Ah int 21h mov year,cx mov month,dh mov
day,dl mov dayOfWeek,al
mov ah,2Bh mov cx,year mov dh,month mov
dl,day int 21h cmp al,0 jne badDate
2B Requires administrator privileges under
Windows NT.
782Ch Get Time, 2Dh Set Time
mov ah,2Dh mov ch,hours mov cl,minutes mov
dh,seconds int 21h cmp al,0 jne badTime
mov ah,2Ch int 21h mov hours,ch mov
minutes,cl mov seconds,dh
2D Requires administrator privileges under
Windows NT.