0% found this document useful (0 votes)
15 views51 pages

Assembly

The document provides a comprehensive overview of computer programming, focusing on assembly language and its components, including the CPU architecture, memory organization, and the translation of high and low-level languages. It details the structure and function of various registers, the types of buses, and the steps involved in writing and executing assembly programs. Additionally, it includes examples of assembly statements and directives, illustrating how to create and run a simple program.

Uploaded by

SirousFekri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views51 pages

Assembly

The document provides a comprehensive overview of computer programming, focusing on assembly language and its components, including the CPU architecture, memory organization, and the translation of high and low-level languages. It details the structure and function of various registers, the types of buses, and the steps involved in writing and executing assembly programs. Additionally, it includes examples of assembly statements and directives, illustrating how to create and run a simple program.

Uploaded by

SirousFekri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Assembly Ehaque Page 1 of 51

1. Job of computer: Process data under the guidance of program


2. Program : Sequence of instruction
HLL program
3. Two type of languages for program writing
• High level language (near to human language)
Translator
• Low level language (near to machine language )
compiler/
4. Machine Language : Language of computer- Train of
interpreter
electric pulses (Binary voltage levels).
• Binary voltage levels are referred to as logic
LLL program
constants 0 and 1.
Assembly
• Machine language is thus represented as strings
of 0’s and 1’s
Translator
5. Assembly Language : Human understandable version
Assembler
of machine language, where op-code, memory addresses
and constant are given English type names.
6. Translation schemes for high and low level language Machine
Ref. to the figure. language program

7. Components of computer system and their jobs


1- Central processing unit, (CPU), 2 – System memory (RAM – random accessible
read / write memory), 3 – Port memory (input / out put devices), 4 – interconnecting
system bus.

I/O System
device CPU Memory

- exchange data -input program - Stores program,


between and data, input data and
computer and process data, processed data
external world output processed
-all peripheral data
devices, key -sequence
board, HDD, various
monitor, mouse, components of
printer are computer
connected here

8. Bus : Electrical connection lines originating from pins of CPU carrying similar type
of signals
9. Type of bus and their usage:
• Data bus: Data transfer between CPU and peripherals.
Number of data bus lines determines size of data, also known as bandwidth
• Address bus: Determines the source and destination of data transfer between
CPU and peripherals
Number of address bus lines determines maximum size of external memory,
which is equal to 2No. of address lines .
Assembly Ehaque Page 2 of 51

• Control bus: Contain signals to sequence, activate and use the peripheral device
as well as notify the CPU
10. Components of central processing unit and their jobs:
• Arithmetic and logic unit (ALU): Data processing
• Control unit (CU) : Sequences components of CPU
• Temporary registers : Storage for input & processed data
11. Registers : Electronic data storage units. Data stored in the form of binary voltage
levels. Registers can be accessed by its address (index)
12. System memory : Array of huge number of registers
13. Information needed to write Assembly language program: Assembly (machine)
language is machine (CPU) dependent. Manufacturer of CPU provides information
regarding:
a. Pinout diagram
b. Register set (Programming model – registers accessible to a programmer writing
program in low level language)
c. Instruction set (operational code and its name- Mnemonics)
14. Graphical representation of CPU 8086

BIU- Bus interface unit, EU – Execution unit

15. CPU 8086 - pins


Data bus : 16 data lines designated as D15D14D13 ... D1D0 .
• Can carry 16bits data.
Address bus : 20 data lines designated as A19 A18A17 ... A1 A0 , carries 20bits address
• Size of memory = 2address lines = 220 = 1048576 or 1048K memory locations of 1
byte size or just 1 mega byte
Assembly Ehaque Page 3 of 51

• With address lines the least address is 0000 0000 0000 0000 0000b or 00000h and
the highest address is 1111 1111 1111 1111 1111b or FFFFFh total 1048576d or
1 M locations
Control bus: RD/-read, WR/-write INTR-interrupt line etc

16. Programming model of 8086 CPU


15 87
1. General purpose

AX AH AL Accumulator reg.
registers

BX BH BL Base reg.
CX CH CL Counter reg.
DX DH DL Data reg.

15 15
DS – data segment reg. SI – source index reg.

3. Index / Pointer
2. Segment
registers

ES – extra data segment DI – destination index

registers
CS – code segment reg. IP – instruction pointer
SS – stack segment reg. SP – stack pointer reg.

15 BP – base pointer reg.


4.

Flag

17. Type of 8086 CPU Registers: Depending upon contents of register CPU registers
can be divided into
1. Data registers – holds data for an operation in ALU
2. Address registers – holds address of instruction or data. Used to access memory
locations.
Address registers are divided into
a. segment registers,
b. pointer registers,
c. index registers.
3. Status or flags register – keeps the current status of the processor

18. Data registers or general purpose register


Works with ALU to store input / result data. Almost all logic and arithmatic operation
can be done on them,

The four 16bits data registers are called:


a. AX- accumulator register
b. BX – base register
c. CX – count register
d. DX – data register
Assembly Ehaque Page 4 of 51

The high and low bytes of the data registers can be accessed seperately.
• The high and low byte of AX register are AH and AL
• The high and low byte of BX register are BH and BL
• The high and low byte of CX register are CH and CL
• The high and low byte of DX register are DH and DL

Special functions of data registers


• AX- accumulator register : multiplication, division, data input / output operation
• BX – base register : used as address register
• CX – count register : used as counter for loop and shift data
• DX – data register : used along AX register in multiplication, division, data input /
output

19. Segment registers – stores segment base number.


• 8086 provides the provision to split the program into 4 parts (segments) to contain
data, program code, stack and extra data separately.
• The segments are loaded into memory at paragraph boundaries - addresses whose
least 4 bits are zeros, viz., XXXX0h
• Segment base number is obtained by dividing the 20 bits segment base address by
10h or 16d, viz., XXXXh
• Used with pointer and index registers to create physical address of memory
locations.

The four 16bits segment registers are called:


a. DS - data segment register
b. SS – stack segment register
c. CS – code segment register
d. ES – extra data segment register

20. Pointer and Index registers – stores displacement (offset) of a memory location
from the base address in a segment.
• Used with segment registers to create physical address of memory locations.

The five 16bits Index and Pointer registers are called:


a. SI - source index register
b. DI – destination index register
c. SP – stack pointer register
d. BP – base pointer register
e. IP - instruction pointer

• All index and pointer registers except instruction pointer register are located in the
execution unit of CPU.

21. Flags register: Indicates status of microprocessor by setting individual bits called
flags.
Two types of flags:
Assembly Ehaque Page 5 of 51

a. Status flags – reflects the result of an instruction executed by the CPU


b. Control flags – enables or disables certain operation of the processor

22. Offset address (16bits): Displacement of a memory location from the segment base
address is called offset address
• Offset address is contained in pointer and index registers.
• The first byte in a segment has offset 0 and the last offset in a segment is FFFFh ,
determined by the size of pointer and index registers, which are 16bits long.
• The maximum length of a segment is 216 = 65536 bytes ≈ 64Kb
• The maximum length of a program is 4* 216 = 262144 bytes ≈ 256Kb
• Offset registers for
data segment are SI, DI, BX
stack segment are SP, BP
code segment is IP
• The offset address of memory location is defined by the programmer.

23. Effective address: Association shown as REGsegment : REG pointer / index . or


XXXXh:YYYYh – where XXXX is the segment base number , YYYY is the offset
address.
• Segment base numbers are contained in segment registers
• DS for data segment
• SS for stack segment
• CS for code segment
• ES for extra data segment
Segment base number is same for all locations of a segment
• Association of segment and pointer / index registers
• Data segment : DS:SI or DS:DI or DS: BX
• Extra data segment : ES:DI or ES: BX
• Stack segment : SS:SP, SS:BP
• Code segment : CS:IP

24. Physical (Absolute) address: It is the 20bits address of a memory location.


• Absolute address is equal to segment base number contained in segment register
multiplied by 10h and adding to the offset contained in corresponding pointer or
index registers.

Data segment DS*16d + SI


DS*16d + DI
DS*16d + BX
Extra data ES*16d + DI
segment ES*16d + BX
Stack segment SS*16d + SP
SS*16d + BP
Code segment CS*16d + IP
Assembly Ehaque Page 6 of 51

• Physical address is computed in the bus unit of CPU where the segment registers
and Instruction pointer registers are located.

25. Logical segments of an assembly program


a) data segment – contains directives to reserve and initialize data variables
b) stack segment – contains directives to reserve and initialize memory locations to
keep return addresses and temporary variables
c) code segment – contains codes to carry out data processing
d) extra data segment - contains directives to reserve and initialize data variables, if
the data segment is full. This segment is optional

26. .Type of assembly statements


a) Directive: commands to assembler such as SEGMENT, ENDS, DB, DW, DD,
DUP(), ASSUME, SEG, OFFSET
b) Instruction: commands to CPU provided by instruction set such as MOV, ADD,
SUB, MUL, DIV, SHL, SHR, CMP, JMP, Jcondition

27. Format of assembly statements


Label: statements ; comments
a) Format of assembly directives
Label: Directive ; comments
b) Format of assembly instruction
Label: Mnemonic Destination, Source ; comments
• Label – named memory location
• Mnemonic – name of operation codes (included in instruction set)
• Destination and source are the addresses of CPU and system memory registers
• CPU register addresses have names given in programming model
• Memory register addresses may be named by programmer or can be used by
its value

28. Definition of logical segment


segName SEGMENT
----------------
----------------
segName ENDS

29. Steps of program writing


a) Declare and define data
b) Declare and define stack
c) Declare and define instruction code
• Instruct the assembler to use a logical segment as physical segment
• Get the segment base number of data and stack segment in DS and SS
registers
• Write the data processing part of program
• Copy data from memory into CPU registers
• Do arithmetic / logic operation on data
Assembly Ehaque Page 7 of 51

• Copy results from CPU registers to memory


• Call the Operating System to carry out input / output job (Optional)
• Call the Operating System to terminate the program

30. Example: Add two numbers 05h and 04h and display it on monitor
C++ program
#include <stdlib.h>
void main()
{
char aa = 05, bb = 04, sum ;
sum = aa + bb ;
printf(”%d”, sum );
}
Assembly program
;; definition of logical data segment SEGMENT- ENDS : define a logical segment in
datas SEGMENT the memory. The starting memory location is given
aa DB 05h some name, used for reference.
bb DB 04h DB : (define byte) reserve a byte size memory ,
initialize it with a byte size number or leave it
sum DB ? uninitialized (?). The memory location may be
datas ENDS named and used as variable

;; definition of logical stack segment n DUP(m): reserve ‘n’ byte size memory
stacks SEGMENT locations, initialize it with a byte size number or
DB 100 DUP(0) leave it uninitialized (?). The memory location is
not named
stacks ENDS

;; definition of logical code segment ASSUME: declare which logical segment will be
codes SEGMENT used as physical segments – code, data and stack
ASSUME CS: codes, DS: datas, segments
SS: stacks
start: ;; beginning address of program ({) Initialization of Segments registers
MOV ax, SEG datas When the operating system loads a program into
MOV ds, ax memory for execution
• The OS loads the CS segment register only with
MOV cx, SEG stacks segment base number.
MOV ss, cx • The DS, SS segment register is to be loaded with
segment base number by programmer.
SEG : load a register with segment base number.
• Data can be copied into segment registers
through general purpose register only
;; data processing
MOV al, aa
MOV cl, bb
ADD al, cl Operating system call for Input / output
MOV sum, al • Convert the binary number into ASCII by adding
30h
;; display result on monitor • Put the data in DL reg.
Assembly Ehaque Page 8 of 51

ADD al, 30h • Put function number = 02h to display character in


MOV dl, al AH reg
MOV ah, 02h • OS call to branch to subroutine, whose address is
in Interrupt vector table at location 0084h from
INT 21h base of memory

;; terminate program System call for return to operating system


MOV ax, 4C00h • Put function number = 4Ch in AH reg
INT 21h • Put 00h in AL reg for normal termination
• OS call to branch to subroutine, whose address is
codes ENDS in Interrupt vector table at location 0084h from
base of memory
END start ;; end of program (})

31. Steps to process assembly language program


Program creation and execution
1.Write program Use notepad.exe or edit.com at DOS prompt. Name it as
any_name.asm

2.Assemble the At DOS prompt write command


program MASM any_name.asm
Create object file Press 4 times enter key
Object file any_name.obj is created

3.Create At DOS prompt write command


executive file LINK any_name.obj
Press 4 times enter key
Executive file any_name.exe is created

4.Run the At DOS prompt write command


program any_name
Press enter key
5. Debug the See the execution of the statements of the program, contents of CPU
program reg. and memory variables
At DOS prompt write command
DEBUG any_name.exe
Press enter key.
Type the following single letter commands followed by enter keys
-U see the listing of program
-R see the content of CPU registers
-T single step through the statements of the program
-P execute a subroutine fully
-G execute the program fully
-D DS:0000 dump the contents of data segment from base address
-D SS:FFF0 dump the contents of stack segment from address
FFFF0h to FFFFh
-Q exit DEBUG
Assembly Ehaque Page 9 of 51

32. Summery of directives


a. Definition and declaration of segment:
SEGMENT Define start of logical segments SegName SEGMENT
ENDS Declare the conclusion of a logical SegName ENDS
segment
ASSUME Identify the use of logical segments as ASSUME CS: CsegName,
physical segments- code segment, data DS: DsegName, SS: SsegName
segment, stack segment,
SEG Get segment base number into a register Mov ax, SEG SsegName
OFFSET Get displacement of the location of a Mov ax, OFFSET varName
variable from the base of the segment
(offset address) into a register

b. Definition and declaration of variable in data segment:


DB define byte reserve a byte (8bits) of data in memory
DW define word reserve two bytes (16bits) of data in memory
DD define reserve four bytes (32bits) of data in memory
double word
n DUP(x) Duplicate characters
reserve ‘n’ locations in memory and fill them with characters ‘x’
x may be number, literal- character between apostrophes ‘X’, or
unspecified ‘?’
DataName DB content
DataName –variable (any name given to memory location)
The content is 8bit number- without extension treated as decimal number, with
extension ‘h’ treated as hexadecimal number, or ‘?’ for non-specification
Example: AUGEND DB 05h
SUM DB ?
DataName DW content
The content is 16bit number- also known as word
Example: MULTIPLY DW 05A2h;
Array of numbers:
ArrayNam DB list_of_numbers_separated_by_commas
Example: MYARRAY DB 12h, 0ABh, 24h
Hex numbers starting with letters A, B,…,F must start with 0
String of letters:
StrName DB ‘A’,’B’,’B’,’A’,’$’
Or
StrName DB ‘ABBA$’
Same as
StrName DB ‘ABBA’, 24h
Strings must be concluded by dollar sign ($) or 24h, which is known as end of string
marker.
Letters in the string are converted into their ASCII codes by assembler.
Assembly Ehaque Page 10 of 51

Un-named array
DB 100 DUP(12) ; set aside 100 bytes of data, fill them with 12
DB 10 DUP (?) ; set aside 10 bytes with non-specified data
DB 20 DUP (‘A’) ; set aside 20 bytes of data, fill them with ASCII value of ‘A’ which
is 41h

c. Definition of constants
EQU Name a constant value, Three EQU 03h
• no memory is reserved for constants

33. Example: Write a program to display string HELLO WORLD


datas SEGMENT
Hello DB “Hello world $”
datas ENDS
staks SEGMENT
DB 100 dup()
staks ENDS
codes SEGMENT
ASSUME CS: codes, DS: datas, SS: staks
Start:
MOV AX, SEG datas
MOV DS, AX
MOV CX, SEG staks
MOV SS, CX

MOV AH, 09h


MOV DX, OFFSET Hello
INT 21h

MOV AX, 4C00h


INT 21h
codes ENDS
END START

34. Category of instructions


1.Data transfer Between registers and memory MOV
Stack manipulation PUSH, POP
Between CPU and IO devices IN, OUT
2.Arithmatic operations: ADD, SUB, MUL, DIV, SHR, SHL, INC, DEC
3.Logical operation: OR, AND, XOR, NOT, CMP
4.Branching: JMP , JCND, LOOP, CALL, RET, INT
5.CPU control: HLT, NOP
Assembly Ehaque Page 11 of 51

35. Memory mapping – It is a stair like diagram representing the offset address (index),
content and name for the memory location
R A M (data segment)
address content name
Absolute Effective address
20 bits Segment offset
base
number
Contained Contained
in DS reg in SI, DI,
BX regs
XXXX2h XXXX 0002h ? sum
XXXX1h XXXX 0001h 04h bb
XXXX0h XXXX 0000h 05h aa
Segment base address is XXXX0h and the base number is XXXXh

36. Memory mapping of data and stack segments of previous program


R A M (data segment) R A M (stack segment)
Offset content Name Offset content
address given address
FFFFh ? FFFFh 00h 100
00h locations
0003h ? 00h filled with
0002h ? sum FF9Ch 00h 00h
0001h 04h bb FF9Ch 00h
0000h 02h aa FF9Ah 00h
Segment base is at 0000h Segment base is at FF9Ah

• Code and data segments grows upward (in the direction of increasing address)
• Stack segment grows downward (in the direction of decreasing address)

37. Addressing mode: It is the way in which the addresses are specified for the source or
destination address.
38. Types of addressing mode
1. Register addressing mode, 2. Immediate addressing mode, 3. Memory addressing
mode
39. Types of memory addressing mode
1. Direct memory addressing mode, 2. indirect memory addressing mode, 3. Base
indexed memory addressing mode
40. Types of indirect memory addressing mode
1. Base addressing, 2 index addressing
41. Definition of addressing modes
1. Register addressing mode: When the name of a register is used to identify the
location of data.
• Source registers may be 8 working registers (AX, BX, CX, DX, SI, DI, BP, SP) and
4 segment registers (CS, DS, SS, ES) except IP and FLAG register.
Assembly Ehaque Page 12 of 51

• Destination may be 8 working registers (AX, BX, CX, DX, SI, DI, BP, SP) and 3
segment registers (DS, SS, ES) except IP, CS and FLAG register.
• Size of source and destination registers must be same to hold same size data
Example: mov AX, BX : AX ← BX

2. Immediate addressing mode: Data is the part of the instruction fetched by the CPU
from code memory and appears as the source operand
• Source constant number available in instruction
• Destination may be 8 working registers (AX, BX, CX, DX, SI, DI, BP, SP) and
except 4 segment registers (CS, DS, SS, ES), IP, and FLAG register.
• Destination may be memory location
• Immediate data cannot be destination operand.
• Immediate data may not be moved to any segment register. It can be moved by
putting it into a working register first. Then from the working register to segment
register.
• No moves of immediate data to CS register allowed.
• Example: mov AX, 0007h : AX ← 0007h
3. Memory addressing mode: When external memory is accessed by CPU.
• Three types of external memory addressing mode:
a. Direct, b. Indirect, and c. Base indexed
3a. Direct memory addressing mode: address in external memory is specified as a fixed
address number
• Named address of memory or enclosed in brackets ([ ]) address of memory operand
is used
• Only one of the operand can be direct memory address of a memory location
• Source operand may be immediate data or 8 working registers (AX, BX, CX, DX, SI,
DI, BP, SP) and 4 segment registers (CS, DS, SS, ES) except IP and FLAG register.
• Destination operand may be 8 working registers (AX, BX, CX, DX, SI, DI, BP, SP)
and 3 segment registers (DS, SS, ES), except IP, CS and FLAG register.
• The quantity inside the brackets is an offset into a memory segment. If not specified
which segment register is to be used to form the physical address, assembler uses
default segment registers as given below
Offset register Default segment Optional segment
IP CS none
SP SS none
BP SS CS, DS, ES
Any other offset DS CS, ES, SS
• The default segment register for most variables is usually DS.
• Example:
• mov AL, [0001h] ; AL ← contents of memory location whose offset address is
0001h
• mov AL, aa ; AL ← contents of memory location whose offset address is
named as ‘aa’ (viz., variable ‘aa’)
Assembly Ehaque Page 13 of 51

3b. Indirect memory addressing mode: Here any one of registers BX, BP, SI, or DI can
be used to hold the address number of the memory location.
A constant displacement number may also be added to the base / index register to form
the final effective address.
• Two types of indirect memory addressing mode
• Base addressing – when any of the base register BX or BP are used for indirect
addressing
• Index addressing – when any of the index register SI or DI are used for indirect
addressing
• Brackets ([ ]) are used around the name of the register that holds the indirect address.
• CPU combines the content of the registers to the segment register to form the physical
memory address.
• Data segment register DS will be assigned by default if BX, SI or DI are used to
indirectly addressed memory.
• Stack segment register SS will be assigned by default if BP is used to indirectly
addressed memory.
• For string moves DI defaults to ES.
• Data may be exchanged between registers and memory location, Immediate number
may be loaded into memory using indirect memory addressing
• Example:
• Mov BX, 0001h ; BX ← address of memory location 0001h
Mov AL, [BX] ; AL ← the content of memory location whose address is in BX
register
• Mov BX, 0000h ; BX ← address of memory location 0000h
Mov AL, [BX+aa] ; AL ← the content of memory location whose address is sum of
content of BX register and address denoted by ‘aa’
• Instead of base register BX, index registers SI / DI can also be used

3c. Base indexed memory addressing mode : It uses one of the base registers BX or BP
and one of the index register DI or SI to form an indirect memory address.
A constant displacement number may also be added to the base plus index register sum to
form the final effective address.
• BP or BX may be added to SI or DI
• BP may not be added to BX
• DI may not be added to SI
• Data may be exchanged between registers and memory location, Immediate number
may be loaded into memory using base index addressing
• DS is the default segment register for base-index addressing.
• Example:
• Mov BX, 0000h ; BX ← 0000h
Mov SI, 0001h ; SI ← 0001h
Mov AL, [BX+SI+aa] ; AL ← the content of memory location whose address is
sum of contents of BX, SI registers, and address denoted by ‘aa’
Assembly Ehaque Page 14 of 51

42. Example of writing the data processing part with different memory addressing
modes
1. Direct memory addressing mode: Address in external memory is specified as a
fixed address number
MOV al, aa MOV al, [0000h]
MOV bl, bb MOV cl, [0001h]
ADD al, bl ADD al, cl
MOV sum, al MOV [0003h], al
2. Indirect memory addressing mode: any one of registers BX, BP, SI, or DI can be
used to hold the address number of the memory location.
2a. Base addressing mode: 2b. index addressing mode:
MOV bx, 0000h MOV si, 0000h
MOV al, [bx] MOV al, [si]
Inc bx Inc bx
MOV cl, [bx] MOV cl, [si]
ADD al, cl ADD al, cl
Inc bx Inc bx
MOV [bx], al MOV [si], al
2c.Base addressing mode with 2d. index addressing mode with
displacement displacement
MOV bx, 0000h MOV si, 0000h
MOV al, [bx] MOV al, [si]
MOV cl, [bx+1] MOV cl, [si+1]
ADD al, cl ADD al, cl
MOV [bx+2], al MOV [si+2], al

43. Repetitive processing


Example: Add seven numbers 03, 04, 05, 06, 07, 08, 09 and display it on monitor
C++ program
#include <stdlib.h>
# define count 07
void main()
{
char aa[] = {03, 04, 05, 06, 07, 08, 09 }, sum=0, i ;
for(i=0; i<count; i++)sum = sum + aa[i];
printf(”%d”, sum );
}
44. Two methods of repetitive processing
• Use CX register to contain the count and LOOP label – instruction. CX is
automatically decremented on each step and compared with zero . Repetition is
carried out if the content of CX is not zero.
• Use any general purpose register to contain the count and JNZ label- instruction.
The register is decremented on each step. Repetition is carried out until the
content of the register becomes zero.
Assembly Ehaque Page 15 of 51

Repetition by using general


Repetition by CX register and purpose register and
LOOP LABEL instruction JUMP_Condition instruction

CX=count CX=count
L1: L1:

Data Data
processing processing

Done by separate DEC and JNZ


Done automatically by LOOP
CX = CX-1 CX = CX-1

instructions
no instruction no
CX = 0 CX = 0
? ?
yes yes

exit exit

45. Example: using CX register and LOOP instruction


.DATA ; base indirect memory addressing mode
aa DB 03, 04, 05, 06, 07, 08, 09 ; aa is declared as an array
sum DB 00
count EQU 07 ; definition of constant ‘count’, no memory location is reserved
.CODE
Mov cx, count
Mov bx, OFFSET aa ; BX has offset address of array ‘aa’
Mov al, sum
For: add al, [bx] ; use BX as pointer (indirect memory addressing mode )
Inc bx ; BX points to next element of array ‘aa’
Loop For ; decrease CX and branch to instruction with label ‘for’ until
; content of CX is zero
Mov sum, al
.DATA ; base register with displacement indirect memory addressing
aa DB 03, 04, 05, 06, 07, 08, 09 ; aa is declared as an array
sum DB 00
count EQU 07 ; definition of constant ‘count’, no memory location is reserved
.CODE
Mov cx, count
Mov bx, 0000 ; BX has offset address 0000of array ‘aa’
Mov al, sum
For: add al, [bx + aa] ; aa is the name of data memory location 0000h
Inc bx ; BX points to next element of array ‘aa’
Loop For ; decrease CX and branch to instruction with label ‘for’ until
; content of CX is zero
Mov sum, al
Assembly Ehaque Page 16 of 51

46. Branching instructions: Transfer control to certain instruction if some conditions are
found valid as result of execution of some instructions such as compare, arithmetic
operations etc.
format: JUMP TARGET_LABEL

47. Two types of branching instructions: conditional and unconditional

48. Conditional jump:The conditional jump look at the state of specified flag(s) in the
flag register to determine whether a jump should be made or not.
- format: jumpif target_label
- All conditional jumps are short type jumps. That is- the destination label should
be in the same code segment and the destination address must be in the range of -
128 to +127 bytes from the current jump instruction, ( current instruction pointer
IP register value).
49. Flag register of 8086 CPU: six status flags that indicates the conditions that are
present after an instruction has been executed, are CF- carry, PF- parity, OF-
overflow, AF- auxiliary carry, ZF- zero, SF- sign

50. Fragment of the 8086 flag register


11 10 9 8 7 6 5 4 3 2 1 0 <-bits
OF DF IF TF SF ZF AF PF CF
control flags status flags
CF- carry, PF- parity
OF- overflow, AF- auxiliary carry
ZF- zero, SF- sign

51. 8086 JumpIf instructions


mnemonic condition tested “ Jump if . . . “
JA / JNBE (CF or ZF)=0 above / not below nor equal
JAE / JNB CF=0 above or equal / not below
JB / JNAE CF=1 below / not above nor equal
JBE / JNA (CF or ZF)=1 below or equal / not above
JC CF=1 carry
JE / JZ ZF=1 equal / zero
JG / JNLE ((SF xor OF) or ZF)=0 greater / not less nor equal
JGE / JNL (SF xor OF)=0 greater or equal / not less
JL / JNGE (SF xor OF)=1 less / not greater nor equal
JLE / JNG ((SF xor OF) or ZF)=1 less or equal / not greater
JNC CF=0 not carry
JNE / JNZ ZF=0 not equal / not zero
JNO OF=0 not overflow
JNP / JPO PF=0 not parity / parity odd
JNS SF=0 not sign
JO OF=1 overflow
JP / JPE PF=1 parity / parity even
JS SF=1 sign
Assembly Ehaque Page 17 of 51

52. The 8086 unconditional jump: The unconditional jump permanently transfers the
program execution to a new sequence of instructions.
format: jmp target_label

53. Types of unconditional jump


a) The direct within- segment short jump: jump to -128 to +127 bytes of the current
instruction, (IP ← IP + signed disp8), the jmp is two bytes long by declaring the
label SHORT.
Format JMP SHORT TARGET
b) The direct within- segment near jump: jump to any point within the current 64-
kbytes code segment, (IP ← IP + disp16), the jmp is three bytes long
Format JMP TARGET
54. Example: using CX (general purpose register) and JNZ instruction
.DATA ; base indirect memory addressing mode
aa DB 03, 04, 05, 06, 07, 08, 09 ; aa is declared as an array
sum DB 00
count EQU 07 ; definition of constant ‘count’, no memory location is reserved
.CODE
Mov cx, count
Mov bx, OFFSET aa ; BX has offset address of array ‘aa’
Mov al, sum
For_L: add al, [bx] ; use BX as pointer (indirect memory addressing mode )
Inc bx ; BX points to next element of array ‘aa’
Dec cx ; decrease CX
jnz For_L ; branch to instruction with label ‘for’ until
; content of CX is not zero
Mov sum, al

55. IF (condition)expression ELSE expression


Use CMP (compare) and Jcondition Label instructions.
Format of compare instruction: CMP destination, source
destination, source
Reg, reg / mem Pseudocode:
Reg /mem, immediate IF condition is true
Ax, immediate THEN
The source operand is subtracted from the Execute true branch statements
destination, flags are set, operands are not ELSE
affected Execute true branch statements
END_IF
Assembly Ehaque Page 18 of 51

56. Example: Subtract number ‘b’ from ‘a’, if ‘a’ is greater than ‘b’, otherwise subtract
‘a’ from ‘b’.

datas SEGMENT C++ program


aa DB 05h #include <stdlib.h>
bb DB 09h void main()
cc db 00h {
datas ENDS char aa = 05, bb = 09, cc ;
staks SEGMENT if (a > b)cc = aa – bb;
DB 100 dup() else
staks ENDS cc = bb – aa;
codes SEGMENT printf(”%d”, cc );
ASSUME CS: codes, DS: datas, SS: staks }
Start:
MOV AX, SEG datas
MOV DS, AX
MOV CX, SEG staks
MOV SS, CX

MOV AL, aa
MOV BL, bb
CMP AL, BL ;AL > BL ?
JBE ELSE_L ; No
THEN: ; Yes
SUB AL, BL
MOV cc, AL
JMP DISP_L
ELSE_L:
SUB BL, AL
MOV cc, BL

DISP_L:
MOV DL, cc
ADD DL, 30h ; convert into ASCII
MOV AH, 02h ; call display character function
INT 21h ; OS call to display it

MOV AX, 4C00h


INT 21h
codes ENDS
END START

57. Two types of statements of a program


a. processing data- location is CPU
b. accessing input / output devices for data input / output
Example: Get data from keyboard , show data on the video display ,
Assembly Ehaque Page 19 of 51

58. Two ways of accessing input / output devices


a. Direct access – by using MOV instruction, devices are memory mapped
b. Direct access – by using IN / OUT instructions, devices are IO mapped
c. Use Operating system calls, so that the OS handles the IO task

59. MOV instruction– transfer data between CPU and IO device


• Each IO device is mapped into the system memory mapping and treated as system
memory location.
• The address is 16 bits.
• Amounts to a large wastage of memory space.
MOV data_Reg, [Memory_address16] ; read data from IO device
MOV [Memory_address16], data_Reg ; write data to IO device

60. IN / OUT instructions – get data from IO device


• Each IO device is mapped into a separate IO memory mapping and given an
unique address – known as port address, by which it can be accessed.
• Port address may be
• 8bits (ports specified between 00 to FFh , addressed directly using port
numbers)
• 16bits (port addresses specified between 0000 to FFFFh - addressed indirectly
using DX to hold IO addressed)
• IN instruction – input data from IO port.
Destination is AL /AX register
a. Port address is 8bits
IN AL /AX , Port_number8 ;Data is copied into AL/AX register
b. Port address is 16bits
MOV DX, Port_address16 ;port address is copied into DX register
IN AL /AX, DX ;Data is copied into AL/AX register
• OUT instructions– write data into IO port
Source is AL register
a. Port address is 8bits
OUT Port_number8 , AL/AX ;Data is copied from AL register into IO
b. Port address is 16bits
MOV DX, Port_address16 ;port address is copied into DX register
OUT DX, AL/AX ;Data is copied into AL register

61. Use Operating System calls


• Software modules to activate the IO devices (also called device drivers) are stored
into ROM BIOS and DISK IOS
• During booting of DOS, these device drivers are loaded into memory,
• The addresses of the device drivers are loaded in the base of the system memory
[RAM] to form a table.
• Each address is four bytes long and constitutes the form CS:IP
• The table is 1000 bytes long. Thus it can contain maximum addresses of 250
device drivers.
Assembly Ehaque Page 20 of 51

Memory mapping of the Interrupt vector Table


003E8H

1000 bytes from base of


Interrupt Vector table

memory
00004H
CS 4 bytes
address of
IP ISR [CS:IP]
00000h

• The modules can be accessed by calling the OS through interrupt mechanism


• Thus the modules are called interrupt service routine [ISR]
• The table is known as Interrupt vector table [IVT].
• Instruction to activate ISRs: INT interrupt_Num .
• When the CPU comes across the INT instruction, it suspends the current job and
branches to ISR whose address is contained in the IVT at memory location
interrupt_Num multiplied by four.
• Each ISR contains several functions. Functions are selected by function number
entered into AH reg. Other necessary parameters are passed through other data
registers.
• Few of the functions of DOS interrupt 21h are described bellow :
♦ Transmission of data between CPU
a. Function 01h: Keyboard input and IO devices are done through ASCII
Output: returns the ASCII code codes.
of key pressed in AL ♦ Numbers received from IO devices are
MOV AH, 01h to be converted into binary.
INT 21h ♦ For numbers 0 to 9 subtract 30h from
the ASCII code
♦ For numbers Ah to Fh subtract 37h
b. Function 02h: Display a character, from the ASCII code
whose ASCII code is in DL ♦ Numbers transmitted to IO devices are
MOV AH, 02h to be converted into ASCII.
MOV DL, character ♦ For numbers 0 to 9 add 30h to the
INT 21h binary
♦ For numbers Ah to Fh add 37h to the
binary
c. Function 09h: Print string, DS:DX
contains pointer to the character string
ending with ‘$’ or 24h (end of string marker)
MOV AH, 09h
MOV DX, OFFSET character
INT 21h

d. Function 4Ch: Terminate current process MOV AH, 4Ch


and transfer controls to the invoking MOV AL, 00h
process. AL contains the return code INT 21h
Assembly Ehaque Page 21 of 51

Summary:
Tasks Function Register to Parameter Register Operating Data returned
No. contain to contain system
Function No. parameter call
Input character 01h AH nil nil Int 21h ASCII code of
from key board key pressed in
AL
Display a 02h AH ASCII code DL Int 21h nil
character on video of character
monitor
Display a string 09h AH Offset DX Int 21h nil
on video monitor address of
the string
Terminate and 4Ch AH 00h AL Int 21h nil
exit program

62. Example: In the previous program input


numbers from key board C++ program
datas SEGMENT #include <stdlib.h>
aa DB 00h void main()
bb DB 00h {
char aa , bb , cc ;
cc db 00h scanf(“%d%d”, aa, bb);
datas ENDS if (a > b)cc = aa – bb;
staks SEGMENT else
DB 100 dup() cc = bb – aa;
staks ENDS printf(”%d”, cc );
}// scanf() and printf()
codes SEGMENT are
ASSUME CS: codes, DS: datas, calls to OS
SS: staks
Start:
MOV AX, SEG datas
MOV DS, AX
MOV CX, SEG staks
MOV SS, CX
MOV AH, 01h ; function - input from keyboard
INT 21h ; DOS call
; ASCII of key pressed is in AL
SUB al, 30h ; convert into binary
MOV aa, al

MOV AH, 01h


INT 21h
SUB al, 30h
MOV bb, al

MOV AL, aa
MOV BL, bb
CMP AL, BL ;AL > BL ?
JBE ELSE_L ; No
Assembly Ehaque Page 22 of 51

THEN: ; Yes
SUB AL, BL
MOV cc, AL
JMP DISP_L
ELSE_L:
SUB BL, AL
MOV cc, BL
DISP_L:
MOV DL, cc
ADD DL, 30h ; convert binary into ASCII
MOV AH, 02h ; call display character function
INT 21h ; OS call to display it
MOV AX, 4C00h
INT 21h
codes ENDS
END START

63. Arithmetic instructions


• Addition : ADD destination, source
destination source
Register Register / memory
Register / memory immediate
ADD AL, NUM8 ; AL ← AL+NUM8

• Increment : INC destination


Increments the destination operand by 1
Destination
Register / memory
INC CL ;CL ← CL + 1

• Subtraction: SUB destination, source


destination source
Register Register / memory
Register / memory immediate
SUB BL, NUM8 ; BL ← BL+NUM8

• Decrement: DEC destination


Decrements the destination operand by 1
Destination
Register / memory
DEC CL ;CL ← CL - 1

• Multiplication : MUL Source


♦ Multiplier is the source operand which is Register / memory
♦ Multiplicand is AL for byte multiplication (8 bit source), product is returned
in AX
Assembly Ehaque Page 23 of 51

♦ Multiplicand is AX for word multiplication (16 bit source), product is returned


in DX:AX (higher word in DX and lower word in AX)
♦ Summary
Type of inputs output
multiplication Destination Source (product)
(multiplicand) (multiplier)
Default- not
mentioned in
instruction
8 bits AL reg / mem (8 bits) AX
16 bits AX reg / mem (16 bits) DX:AX

MOV BL, multiplier


MOV AL, multiplicand
MUL BL
; AX contains the product

• Shift Left: SHL destination, source


♦ Can be used if the multiplier is multiple of 2.
♦ Shift left is equivalent to multiply the destination by 2power
♦ Destination is Register / memory
♦ The source is the power of 2
♦ If the multiplier is 21, power is 1
• SHL destination, 1 ; shift the destination one binary digit to left
power
♦ If the multiplier is 2 , and power is greater than 1
• SHL destination, CL ; shift the destination more than once to left,
; CL contains the power of 2
power EQU 02h
MOV CL, power
MOV AX, multiplicand
SHL AX, CL ; AX ← AX * 22

• Division : DIV Source


♦ Divisor is the source operand which is Register / memory
♦ Dividend is AX for byte division (8 bit source), quotient is returned in AL,
remainder is returned in AH
♦ Dividend is DX:AX for word division (16 bit source) - higher word in DX and
lower word in AX, quotient is returned in AX, remainder is returned in DX
♦ If the quotient is greater than 8 bits (16 bits for word division), then INT 00h
is generated
Assembly Ehaque Page 24 of 51

♦ Summary
Type of inputs output
division Destination Source (remainder) (quotient)
(dividend) (divisor)
Default- not
mentioned in
instruction
8 bits AX reg / mem AH AL
(8 bits)
16 bits DX:AX reg / mem DX AX
(16 bits)

MOV BL, Divisor


MOV AX, Dividend
DIV BL
; AL contains quotient and AH contains remainder

• Shift Right: SHR destination, source


♦ Can be used if the divisor is multiple of 2.
♦ Shift right is equivalent to divide the destination by 2power
♦ Destination is Register / memory
♦ The source is the power of 2
♦ The quotient is returned in the destination and the remainder is lost
♦ If the divisor is 21, power is 1
• SHR destination, 1 ; shift the destination one binary digit to left
power
♦ If the divisor is 2 , and power is greater than 1
• SHR destination, CL ; shift the destination more than once to left,
; CL contains the power of 2
Power EQU 02h
MOV CL, Power
MOV AX, dividend
SHR AX, CL ; AX ← AX ÷ 22

64. Example : Find the average of numbers C++ program


.MODEL SMALL #include <stdlib.h>
.DATA # define count 07
aa DB 03, 04, 05, 06, 07, 08, 0Ah void main()
quotient DB 00 {
remaind DB 00 char aa[] = {03, 04, 05, 06, 07, 08, 09 };
count EQU 07 int sum=0, i , avg;
.STACK 100h for(i=0; i<count; i++)sum = sum + aa[i];
.CODE avg = sum / count;
Main PROC printf(”%d”, avg );
Mov ax, @DATA }
Mov DS, AX
Assembly Ehaque Page 25 of 51

Mov cx, count


Mov bx, OFFSET aa
Mov ax, 00h
For_L: add al, [bx]
Inc bx
Loop For_L
;; AL contains the sum
Mov cl, count
Div cl
Mov quotient, al
Mov remaind, ah

Mov ax, 4c00h


Int 21h

Main endp
end Main

65. Logic instructions


Truth table of OR function
• Logical inclusive : performs logical OR
input output
operation on each bit position of the operands
and place the result in destination. 0 0 0
OR destination, source 0 1 1
destination source 1 0 1
Register Register / memory 1 1 1
Register / memory immediate

• Logical conjunction : performs logical AND Truth table of AND function


operation on each bit position of the operands input output
and place the result in destination. 0 0 0
AND destination, source 0 1 0
destination source 1 0 0
Register Register / memory 1 1 1
Register / memory immediate
♦ Used for masking – hide some bits of a
number, for example, unpacking a hex number

• Logical exclusive OR : performs exclusive Truth table of XOR function


OR operation on each bit position of the input output
operands and place the result in destination. 0 0 0
XOR destination, source 0 1 1
destination source 1 0 1
Register Register / memory 1 1 0
Register / memory immediate
Assembly Ehaque Page 26 of 51

66. Example : Display an 8 bit number on monitor ( in hex form )

.MODEL SMALL
.DATA
aa DB 0A8h
mask1 EQU 0F0h
mask2 EQU 0Fh
power EQU 04h
.STACK 100h
.CODE
Main PROC
Mov ax, @DATA
Mov DS, AX

;; separate the lower digit


Mov al, aa
And al, mask1 ; AL contains A0h, 8 is masked out
Mov cl, power ; CL contains the shift count
Shr al, cl ; AL contains 0Ah

cmp al, 09h


ja num_A_F
Add al, 30h ; convert binary into ASCII, if number less than A
jmp disp
num_A_F:
Add al, 37h ; convert binary into ASCII, if number greater than 9
disp:
mov ah, 02h
mov dl, al
int 21h ; higher digit displayed

;; separate the lower digit


Mov al, aa
And al, mask2 ; AL contains 08h, A is masked out

cmp al, 09h


ja num_A_F
Add al, 30h ; convert binary into ASCII, if number less than A
jmp disp
num_A_F:
Add al, 37h ; convert binary into ASCII, if number greater than 9
disp:
mov ah, 02h
mov dl, al
int 21h ; lower digit displayed
Assembly Ehaque Page 27 of 51

Mov ax, 4c00h


Int 21h

Main endp
end Main

67. Summary:
Addition : use instructions
ADD – add by any number
INC - increase by 1
OR – selective addition (bitwise manipulation)

Subtraction: use instructions


SUB – subtract by any number
DEC - decrease by 1
AND – selective subtraction (bitwise manipulation)

Multiplication: use instructions


Repetitive ADD with LOOP instruction (using CX reg)
MUL – multiply with any number
SHL - multiply with a number, which is multiple of 2

Division: use instructions


Repetitive SUB with LOOP instruction (using CX reg)
DIV – divide by any number
SHR - divide by a number, which is multiple of 2

68. Repetitive blocks of instructions at different locations in a program can be defined


by
a. Macro
b. Procedure

69. Macro: A macro is a symbolic name given to one or more assembly language
statements. Macro statements are inserted in the program from where it is called,
during the assembly of the source program. Thus the size of program grows.

70. Defining Macro


Format:
MacroName MACRO [parameter 1] [, parameter 2]
Statements
Statements
ENDM

71. Location of macro : A macro can be defined


a. Any where in the program. (Usually at the top of the program)
b. In a separate text file (Stored Macros in an INCLUDE file)
Assembly Ehaque Page 28 of 51

72. Calling Macro: A macro is called by coding its name along with the value to be
passed in the body (processing part) of the program
Format:
MacroName [argument 1] [,argument 2]

73. Example
Disp MACRO MES ; Define Macro
mov ah, 09h
mov dx,offset MES
int 21h
ENDM
.MODEL SMALL
.DATA
Mesg db ‘ Happy new year ‘, 0dh, 0ah, 24h
.STACK 100h
.CODE
Main PROC
Mov ax, @DATA
Mov DS, AX

disp mesg ; calling macro

Mov ax, 4C00h


Int 21h
Main endp
end Main

74. Part of the listing


Offset Code Mnemonics
000B 8E DA mov ds,dx
disp mesg ; calling macro
Statements of the
000D B4 09 1 mov ah, 09h macro inserted in
000F BA 0000 R 1 mov dx,offset mesg the program at the
0012 CD 21 1 int 21h location of
0014 B8 4C00 mov ax,4C00h
0017 CD 21 int 21h

75. Macros defined in separate text file: A separate file can be created to include only
macros. These macros can be copied at assembly time with the help of INCLUDE
directive in the source program.

• INCLUDE is surrounded by IF1 & ENDIF directives


Statements of the
to tell the assembler MASM to include the macros only
macro inserted in
on its first pass.
the program at the
• Location of IF1 – ENDIF location is at the top location of
of program calling the macro

76. Example:
• Create a text file by the name of myMacro.lib to include the following
Assembly Ehaque Page 29 of 51

Disp macro msg mov dl, 30h l6: cmp dh, 00


mov ah, 09h l1: cmp cx, 10000 jz l7
mov dx, offset msg jb l2 mov ah, 02
int 21h mov dh, 01 int 21h
endm inc dl
sub cx, 10000 mov dl, 30h
Clrscr macro jmp l1 l7: cmp cx, 10
Mov ax, 0600h jb l8
Mov bh, 07 l2: cmp dh, 00 mov dh, 01
Mov cx, 0000h jz l3 inc dl
Mov dl, 80 mov ah, 02 sub cx, 10
Mov dh, 24 int 21h jmp l7
Int 10h mov dl, 30h
Endm l3: cmp cx, 1000 l8: cmp dh, 00
jb l4 jz l9
gotoxy macro row, column mov dh, 01 mov ah, 02
Mov ah, 02 inc dl int 21h
Mov bh, 00 sub cx, 1000
Mov dh, row jmp l3 L9: mov dl, 30h
Mov dl, column add dl, cl
Int 10h l4: cmp dh, 00 mov ah, 02
Endm jz l5 int 21h
mov ah, 02
Disp_at macro row, column, string int 21h mov ah, 02
Clrscr mov dl, ‘d’
Gotoxy row, column mov dl, 30h int 21h
Disp string l5: cmp cx, 100 endm
Endm jb l6
mov dh, 01
printd macro bx inc dl
local l1, l2, l3, l4, l5, l6, l7, l8, l9 sub cx, 100
mov cx, bx jmp l5
mov dh, 00

77. Example: Program using include file containing macros


IF1
INCLUDE myMacro.lib
ENDIF
.MODEL SMALL
.DATA
greeting db ‘hello from row 10, column 15, $’, 0dh, 0ah
.STACK 100h
.CODE
Main PROC
Mov ax, @DATA
Mov DS, AX

Disp_at 10, 15, greeting ; calling macro

Mov ax, 4C00h


Int 21h

Main endp
end Main

78. Procedure: A procedure is a block of instructions that is written once, but can be
executed as needed at any point in a program.

A procedure is a group of related program instructions with common function.


Assembly Page 30 of 51

79. Three jobs related with procedure


♦ Definition of procedure
♦ Passing parameters to procedure
♦ Invoking of procedure

80. Type of procedures as per location


a. near procedures - procedure located in the current code segment ,
b. far procedures - procedure located in other segments ,.
c. external procedures - procedure located in another program module.

81. Definition (structure) of procedure : the PROC & ENDP directives and RET
instruction:
♦ The PROC directive declares the beginning of a procedure.
♦ The ENDP directive declares the end of a procedure.
♦ RET is required to return back to the calling program
♦ Procedure located in the current code segment are defined after the exit to
operating system instruction of the main program.

prog_name PROC [near / far]


push regs
-----
statements
-----
Pop regs
RET
prog_name ENDP

82. Invoking of procedure - CALL instruction : Process of transferring control from the
main part of a program to a procedure is defined as calling (a procedure)
format: CALL near_procedure
CALL far_procedure
Part of a program using procedure
♦ The location of invoking a procedure is start:
anywhere in the main program before program statements;
pass parameter
termination and in the procedures before RET call proc_name
instruction statements;
mov ax, 4c00h
int 21h
usage:
proc_name proc near
♦ direct calling
call SUB1 ; procedure in the push regs
statements;
call near ptr SUB1 ; same segment. statements;
call far ptr SUB2 ; procedure in other segment. pop regs
ret

♦ indirect calling proc_name endp


call word ptr [bx] ; call to near procedure
segname ends
call MEM_WORD ; word size variable end start
Assembly Page 31 of 51

call dword ptr [bx] ; call to far procedure


call MEM_DWORD ; double word size variable

83. Mechanism of calling a procedure:


• When a near procedure is called instruction pointer register (IP) is incremented so
that it points to the next instruction and is then pushed on to the stack. Then the
offset of the called procedure is moved into the IP.

• When a far procedure is called code segment register (CS) is pushed onto the stack,
followed by IP. Then the procedure’s segment number is moved into CS and its
offset is moved into IP.

84. RET instruction: Process of transferring control from a procedure to the place in the
main part of a program where the call was made is defined as returning.
Format: RET
• Usually the RET is the last procedure instruction.

85. Mechanism of returning to calling program


• The RET instruction makes the CPU leave the procedure and return to calling
program. RET gets the return address off the stack . The program continues to
execute at the new address.
• For near procedure the RET pops one word into the IP, an offset for IP for the
calling program only
• For far procedure the RET pops two words off the stack , an offset for IP and then
a segment number for CS of the calling program

86. Stack: The stack is the memory buffer, which holds return addresses while the CPU is
executing a procedure. The stack is also used to store data - registers and memory
operand temporarily.

87. Registers addressing the stack


• The SS -stack segment register contains the base number of stack segment.
• The SP- stack pointer register contains the address of the top of the stack, where
last value was stored.
• The BP - base pointer register is used to manipulate the stack, instead of SP
• The effective address is represented as SS:SP, SS:BP

88. Data transfer instruction to be used with stack


a. PUSH - write word onto stack
b. POP - get word off stack

89. PUSH : The PUSH instruction puts the contents of a word-sized (16 bit) register or
memory operand on to the top of stack.

• Format: PUSH source


The source may be word-sized (16 bit) register or memory operand.
Assembly Page 32 of 51

Usage: push ax ; save content of general purpose register


push ds ; or content of a segment register
push cs ; including code segment register
push [TABLE + si] ; save the content of memory location

• At first the stack pointer register (SP) is decremented by 2, then the data is copied
on to the stack at the location pointed by SP.
mov ax, 1000h
push ax
stack before stack after
000Fh 00 <--SP 000Fh 00
000Eh 00 000Eh 00
000Dh 000Dh 10 <--SP
000Ch 000Ch 00

90. POP : The POP instruction takes a word off the stack and put it into memory location
or register.
• After the content of the stack, pointed by stack pointer register (SP), is copied into
a word-sized (16 bit) register or memory location, the stack pointer register (SP) is
incremented by 2 .
• format: POP destination
The destination may be word-sized (16 bit) register (but cannot be CS & IP
registers) or memory operand
Usage: pop ax ; restore content of general purpose register
pop ds ; or content of a segment register
pop [TABLE + si] ; restore the content of memory location

• Always POP words in reverse order as were pushed on to the stack !


• While defining a procedure it is a good practice to save (push) the contents of the
registers whose content may change onto the stack and restore them back (pop) in
the corresponding registers at the end of the procedure before RET statement !

91. Examples:
• saving and restoring registers:
push ax ; save AX
push dx ; save DX
mov dx, offset MESSAGE ; DX points to the string
mov ah, 09h ; function display string
int 21h
pop dx ; restore DX
pop ax ; restore AX - in reverse order

• copy one segment register into another:


push es
Assembly Page 33 of 51

pop ds

92. Parameter: Address or data values passed between the mainline program and the
procedure is known as parameters.

93. Passing parameter to procedures :


1 Passing parameter by name : When data values of variables in the calling program
are passed to a procedure, it does not get changed, if it is altered in the called
procedure.
2 Passing parameter by reference : When addresses of variables in the calling
program are passed to a procedure, the contents of the variables changes, if it is
altered in the called procedure.
3 Location of parameter passing is just before the calling of a procedure in a
program

94. Methods of parameter passing to and from procedures: There are four methods of
parameter passing
a) passing parameter in registers
b) passing parameters using stack memory
c) passing parameters using general memory
d) passing parameters using pointers ( memory location)

• Passing parameter in registers : In case where few parameters are needed to pass
to a procedure we can use registers. The result is returned from the procedure
through some register.
• Passing parameters using general memory: In case where a large number of
parameters are needed to pass to a procedure dedicated section of general
memory is used.
• Passing parameters using pointers (memory location): A more versatile way to
pass parameter to procedure is to pass pointers to desired data ( which may be
located any where in the memory), most suitable for passing arrays or other data
structures to and from procedure.
• Passing parameters using stack memory: For those programs which allows
several users to time-share a system, often the stack memory is used to pass
parameters to and from procedures.

95. Retuning the result: In the case of passing parameter by name, the results can be
returned through registers.

By convention registers AX and register pair DX:AX are used to return 16 bit and 32
bit results.

96. Example # 1. : Use of procedure - Passing parameter in registers


CR EQU 0Dh
LF EQU 0Ah
DOL EQU 24h
.MODEL SMALL
.DATA
Assembly Page 34 of 51

MES DB 'happy new year, 1999', CR, LF, DOL


.STACK 100h
.CODE
Main PROC
Mov ax, @DATA
Mov DS, AX

mov dx, offset MES ; pass parameter


call DISP ; call procedure

mov ax, 4C00h ; return to dos


int 21h
Main ENDP

DISP PROC
push dx ; save register onto the stack
push ax

mov ah, 09h ; display message


int 21h

pop ax ; restore original value of register from stack


pop dx

ret ; transfer control to the calling program


DISP ENDP

MYCODE ENDS
END MAIN

Example # 2. : Use of procedure - Passing parameters using stack memory:


• Here BP register is used to access data from the stack.
.MODEL SMALL
.DATA RAM
aa DB 01 top of stack
bb DB 02 address content name
00
cc DB 03
BP+8 03 cc
total DB ?
00
.STACK 100h BP+6 02 bb Parameters
.CODE 00
Main PROC BP+4 01 aa
Mov ax, @DATA IPH Return
Mov DS, AX IPL address
BPH
mov ah, 00 BP→ BPL ←SP
mov al, cc
Pass parameter
over stack

push ax
mov al, bb
push ax
mov al, aa
push ax

call SUM ; call procedure

mov total, al
Assembly Page 35 of 51

mov ax, 4C00h


int 21h
Main ENDP

SUM PROC
push BP ; save BP register onto the stack
mov bp, sp ; copy content of SP into BP

get parameter
mov al, byte ptr [bp + 8]

from stack
add al, byte ptr [bp + 6]
add al, byte ptr [bp + 4]

mov ah, 00; form the output


pop BP; restore BP register from stack
ret
DISP ENDP

MYCODE ENDS
END MAIN

97. External procedures: Separately assembled modules.


a) Between assembly language modules
b) Between High Level Language program and assembly language module

98. External reference directives: The directives allowing to share information between
modules that will eventually link to form a program are
a. PUBLIC
b. EXTRN
• PUBLIC and EXTRN are often used to share procedure.

99. PUBLIC directive: The PUBLIC directive makes one or more symbol(s) available to
other modules that will eventually linked to this one.
• A PUBLIC directive can list variable names, labels (including PROC labels) and
names defined by an EQU directive.
Format: PUBLIC name

100. EXTRN directive : The EXTRN directive is used to tell the assembler that the
names or the labels following the directive are in some other modules.
• While calling a procedure which is in a program module assembled at a different
time from the module which contains the CALL instruction, the procedure must be
declared external.
Format: EXTRN name : type
• name is the symbol defined and declared PUBLIC in some other module
• type can be one of the following:
♦ if name is a symbol in a data segment or extra segment, then type can be
BYTE, WORD or DWORD,
♦ if name is a procedure label, then type can be NEAR or FAR,
♦ if name is a CONSTANT defined by an EQU directive, then type must be
ABS.
Assembly Page 36 of 51

101. Example of separately assembled modules.

;; main module ASM13a.ASM ;; secondary module ASM13B.ASM


CR EQU 0Dh PUBLIC DISP ; can be used by other
LF EQU 0Ah ; module
DOL EQU 24h CDE SEGMENT para public 'code'
MYDATA SEGMENT ASSUME cs:CDE
MES DB 'happy new year, 1999', CR, LF, DOL DISP PROC FAR
Y2K DB 'messy year', CR, LF, DOL push dx ; save register onto stack
MYDATA ENDS push ax
mov ah, 09h ;display message
MYSTACK SEGMENT int 21h
DB 100 dup(0)
MYSTACK ENDS pop ax ; restore register contents
pop dx ; from stack memory
EXTRN DISP: FAR ; DISP in another module
ret
MYCODE SEGMENT DISP ENDP
ASSUME cs:MYCODE,ds:MYDATA,ss:MYSTACK
MAIN PROC CDE ENDS
mov ax, seg MYSTACK END DISP
mov ss, ax

mov dx, seg MYDATA


mov ds, dx
mov dx, offset MES
call DISP
mov dx, offset Y2K
call DISP
mov ax, 4C00h
int 21h
MAIN ENDP
MYCODE ENDS
END MAIN

102. Assembling & Linking separate modules


The modules are assembled separately, viz.,
- MASM ASM13a.ASM <cr>
- MASM ASM13b.ASM <cr>
to yield the object files, which are linked together as
- LINK ASM13a.OBJ + ASM13b.OBJ <cr>
to yield the executive file.

103. Linking to High Level language


a) Separate modules
b) In line assembly for C++ programs

104. Separate modules


a) Segment names
Are usually standard but can be overridden using options with command line
compiler.

• Declaration for code section in TurboC


Segment names must be capitalized with a preceding underscore.
_TEXT segment byte public ‘CODE’
Assembly ehaque Page 37 of 51

• Declaration for data section containing initialized data


_ DATA segment word public ‘DATA’

• Declaration for uninitialized data


_ BSS segment word public ‘BSS’

b) Saving registers
At the beginning of the procedure, registers BP, CS, DS, SS, ES, SI, DI should also be
saved and restored at the end of the procedure.

c) Identifiers
Any name in the procedure should begin with an underscore, viz.,
_TEXT segment
_addem proc
public _addem
_count dw 0000

d) Defining functions
Functions must be declared in C program as:
extern int sub1( );
function name
return type
external qualifier

extern void sub1( );


return no value

extern int sub1( int param1, int param2 );


integer parameter
e) Function results
TurboC functions returns 16 bit values in AX and 32 bits values in DX:AX registers.
Larger data structures are stored in a static data location and a pointer to the data is
returned in AX (16 bits) or DX:AX (32 bits) registers.

f) Passing parameters
• By name : C program passes arguments by value through stack. So subroutine
cannot change them.
addem(a, b, c);

• By reference : To access the original variables, parameters must be passed by


reference i.e., address of parameters has to be passed.
addem(&a, &b, &c);

105. Stack frame


The calling C program pushes the arguments in a last one first manner. Then return
address is pushed on the stack, i.e.,
Assembly ehaque Page 38 of 51

- the last argument in the list is the first to be stored in the highest available
location in the stack memory,
- the last entry is the return address of the calling module.

106. Example
RAM
Program # 1 top of
/* hllc.c program to be interfaced
with hlla.asm assembly program */
stack
# include <stdio.h>
extern int addem( int, int, int); [BP+8] 0003 c
[BP+6] 0002 b parameters
void main(void)
{
[BP+4] 0001 a
int a =1, b = 2, c = 3, total; [BP+2] ret. address
printf("\n adding 1 + 2 + 3:"); BP BP SP
total = addem( a, b, c );
printf("\n Total = %d", total);
} /* hllc.c*/

Program # 2
Title hlla.asm : subroutine called by hllc.c
public _addem
_TEXT segment byte public 'CODE'
assume cs: _TEXT
_addem proc near
push bp
mov bp, sp
mov ax, [bp + 8]
add ax, [bp + 6]
add ax, [bp + 4]
pop bp
ret
_addem endp
_TEXT ends
end

Compilation
TCC hllc.c creates hllc.obj file
TASM hlla.asm creates hlla.obj file

Linking
TLINK hllc.obj + hlla.obj creates hllc.exe file

Note
In practice the author created a project (PRJ) file and added both source C & ASM
files. Afterwards the execution file was automatically built by selecting MAKE option
from COMPILE menu. The directory C:\TC\BIN should contain file TASM.EXE.
Assembly ehaque Page 39 of 51

107. In line assembly for C++ programs


i) The assembly language statement is preceded with keyword ‘asm’.
Format: asm opcode operand

Example:
// hllc1.cpp inline assembly demo
# include <iostream.h> End of string
void main(void) marker
{
char *msg = "Happy new year $";
cout <<"\n get message \n";
asm mov ah, 09
asm mov dx, msg
asm int 21h
cout << "\n done...";
}

ii) The block of assembly statements is confined by opening and closing braces. The
block is preceded with keyword ‘asm’. ( Keyword ‘asm’ and opening brace ‘{’
should be in the same line ).
Format: asm {
Opcode operand ;
----------- ;
----------- ;
}

Example:
// hllc2.cpp inline assembly demo
# include <iostream.h> End of string
void main(void) marker
{
char *msg = "Happy new year $";
cout <<"\n get message \n";
asm{
mov ah, 09
mov dx, msg
int 21h
}
cout << "\n done...";
}
108. File Processing (part 1)
The DOS open and create operations takes as input the file C-program
name and return a small integer called the file handle. All other # include <stdio.h>
input / output operations use the file handle to specify the file void main (void)
upon which they operate. {
The main operations are sequential reading and writing of the FILE *in;
file from the current position (maintained by DOS) and altering in = fopen(\\autoexec.bat, “r”);
the current position to effect random access to the file. fclose(in);
}

109. DOS file name


DOS file name variable length character string terminated by a zero (0), viz.,
FNAME DB ‘A:\source\myprog.asm’, 0
Such strings are called ASCIIZ strings, that is a string of charters terminated by a zero byte.

110. Create file (3Ch, 5Bh)


The term file refers to a collection of related data accessible by name. Filles are created and
written to the secondary storage memory viz., magnetic disks.
To create a file and get the file handle we use DOS function call 3Ch or 5Bh (placed in AH),
DS:DX must point to the start of an ASCIIZ string which contain the disk drive number, the path
and the file name terminated with a all zero’s byte, CX must contain an attribute value which
indicates the type of the file, viz., attribute code of 00 for normal file, 01 for read only file, 02 for
hidden file and 04 for system file, execute the INT21h instruction. The handle for the opened file
is return in the AX register.
DOS function call 3Ch creates or truncate an existing file to 0 bytes, while DOS
function call 5Bh creates or aborts if the file already exists.

If DOS sets the Carry flag there is an error and an error code is returned in AX: 2 -
file not found, 3 - path not found, 4 - too many open files, 5 - access denied.
create_file # 1: create_file # 2:
mov ah, 3Ch ; function create file mov ah, 5Bh ; function create file
mov dx, offset NEWFILE ; ASCIIZ string with file mov dx, offset NEWFILE ; ASCIIZ string with file
; name ; name
mov cx, 0000h ; normal attribute mov cx, 0000h ; normal attribute
int 21h ; call DOS int 21h ; call DOS
jc DISPLAY_ERROR ; error ? display a jc DISPLAY_ERROR ; error ? display a
; message ; message
mov NEWFILEHANDLE, ax ; no error ? save the mov NEWFILEHANDLE, ax ; no error ? save the
;handle ;handle
. .
. .
NEWFILE db ‘NEWFILE.DOC’, 0 NEWFILE db ‘NEWFILE.DOC’, 0
NEWFILEHANDLE dw ? NEWFILEHANDLE dw ?
To open a file in output mode for sequential writing function 3Ch is good.

111. Open file (3Dh)


Opening a file means copying the file parameters from the directory to a file control block in the
memory and marking the file as open.
To open a file and get the file handle we use DOS function call 3Dh (place in AH), DS:DX must
point to the start of an ASCIIZ string which contain the disk drive number, the path and the file
name terminated with a all zero’s byte, AL must contain an access code which indicates the type
of operation that one wants to perform on the file, viz., access code of 00 for read only, 01 for
write only, and 02 for read and write, execute the INT21h instruction. The handle for the opened
file is returned in the AX register.
open_file:
mov ah, 3Dh ; function open file
mov dx, offset INFILE ; ASCIIZ string with file name
mov al, 00h ; choose input mode
int 21h ; call DOS
jc DISPLAY_ERROR ; error ? display a message
mov INFILEHANDLE, ax ; no error ? save the handle
-
INFILE db ‘A:\FILE1.DOC’, 0
INFILEHANDLE dw ?
To read and write data to a file (specifically random access file updating) requires function 3Dh.

112. Read a file or device (3Fh)


To read a file we use DOS function call 3Fh (place in AH), BX must contain the file handle, CX
the numbers of bytes to read from the file, DS:DX must point to the buffer location in the memory
that the data from the file will be read into, execute the INT21h instruction. After the file is read AX
contains the number of bytes actually read from the file.
read_file: INFILEHANDLE dw ?
mov ah, 3Fh ; function read from file (device = 0 - keyboard)
mov bx, INFILEHANDLE ; BX = file read_from_keyboard:
handle mov ah, 3Fh ; read from file / device
mov cx, 512 ; number of bytes to mov bx, 0 ; device = keyboard
;read mov cx, 127 ; request 127 bytes
mov dx, offset INFILEBUFF ; maximum
int 21h ; call DOS mov dx, offset INKEYBUFF
jc DISPLAY_ERROR ; error ? display a int 21h ; call DOS
; message, if carry set jc DISPLAY_ERROR ; error ? display a
cmp ax, cx ; fewer bytes read ? ; message, if carry set
jb EOF_REACHED ; yes quit reading .
. .
. INKEYBUFF dw ?
INFILE db ‘A:\FILE1.DOC’, 0 ; AX = character count +2, DOS includes 0Dh & 0Ah

113. Write to file or device (40h)


To write to file or device we use DOS function call 40h (placed in AH), place valid file handle into
BX, place the number of bytes to write in CX and point DS:DX to the buffer where data are
stored, then execute the INT21h instruction. DOS automatically updates the file pointer after
writing to the file.
write_to_file:
mov ah, 40Fh ; function write to file
mov bx, HANDLE ; BX = file handle returned by OPEN
Write to video monitor:
mov cx, 100h ; number of bytes to write
mov dx, offset BUFFER ; DX points to buffer device equ 02
int 21h ; call DOS
jc DISPLAY_ERROR ; error ? display a message, if carry set mov bx, device
cmp ax, cx ; all bytes written ?
jne CLOSE_FILE ; no, disk is full
.
HANDLE dw ?
BUFFER db 100h dup(?) ; output buffer

114. Close file (3Eh)


Closing a file means updating the directory information for the file and marking the file as closed.
To close a file we use DOS function call 3Eh (place in AH), place the file handle into BX, execute
the INT21h instruction.
close_file:
mov ah, 3Eh ; function close file
mov bx, INFILEHANDLE ; BX = file handle
int 21h ; call DOS
jc DISPLAY_ERROR ; error ? display a message, if carry set
.
.
INFILE db ‘A:\FILE1.DOC’, 0
INFILEHANDLE dw ?

Move File Pointer Function (42h)


115.
Moves the file pointer to a new location. ( the file must be open ).
The input registers are:
AH 42h
AL Method Code (Type of offset how the pointer
will be set)
0 - offset from the beginning of the file,
1 - offset from the current location,
2 - offset from the end of the file.
BX File handle
CX Offset high CX:DX
DX Offset low (32 bit offset)

Result:
If error the carry flag is set (CF = 1),
If successful DX:AX returns new location of the file pointer relative to the start of the file.

Example: Append to a file


Use method code 2 to position the file pointer to the end of the file before writing any new
record.
mov ah, 42h ; set current file pointer
mov al, 02h ; AL = seek type (from EOF)
mov cx, 0 ; CX= high-distance
mov dx, 0 ; DX= low-distance
mov bx, HANDLE
int 21h ; AX= number of bytes actually read

116. Program Segment Prefix (PSP)


When the DOS loads an executable program ( with extension .COM or .EXE ) in the
memory, the DOS creates an area of 100h (256) bytes, containing some vital information
about the application program, just ahead of the program. This area is called program
segment prefix.

117. DOS command tail area


It is the part of program segment prefix where, when a program is executed, any text typed
after the program name is automatically stored.

DOS command tail area starts at address PSP:80h, its maximum size is FFh (128) bytes.
The first byte contains a count of the number of the characters entered. The last byte is
carriage return (0Dh), this is not included in the character count.

Example:
Suppose we need to pass the name lg.asm to a program asm85.exe. The DOS command
line will be: asm85 lg.asm

The content of the command tail are as follows:


offset 80h 81h 82h 83h 84h 85h 86h 87h 89h
Content 07h 20h 6ch 67h 2eh 61h 73h 6dh 0dh
count l g . a s m CR
1 2 3 4 5 6 7
Assembly ehaque Page 43 of 51

118. Finding Program Segment Prefix


When DOS loads an application program (extension .exe), registers DS and ES points to
the PSP. Later reset those registers to the data segment at the beginning of the program.
Registers CS and IP points to the base of code segment.

Memory map of EXE file C program:


contents #include <stdlib.h>
Inital register value #include <stdio.h>
#include <string.h>
Program DS,ES main(argc, argv)
Segment int argc;
Preffix char *argv[];
100h bytes {
code CS, IP char sfile[12];
segment FILE *sfp;
if ( argc != 2)
area {
data printf("\n Format: > psp fileName ");
segment exit(0);
area }
Stack strcpy( sfile, argv[1]);
segment sfp = fopen(sfile,"r");
if(sfp == NULL)
{
puts("Cannot Open the File");
exit(0);
}
fclose(sfp);
}

For application program (extension .com), registers CS, SS, DS and ES all points to the
PSP. The IP points to offset 0100h, where the program code begins.
Memory map of COM file
Address contents Inital register value
0000h Program CS,DS,ES,SS
Segment
Preffix
100h bytes
code/
data IP = 0100h
area
Stack area
100h bytes
FFFFh SP

119. Example
MYDATA SEGMENT para public 'data'
FNAME DB 30 dup(0) ; file name from PSP
HANDLE DW 0 ; Handle for file
err_mesg DB ' File cannot be opened', 0dh, 0ah, 24h
help_msg DB ' usage >psp FileName', 0dh, 0ah, 24h
MYDATA ENDS

MYSTACK SEGMENT para stack 'stack'


DW 100 dup(0)
STKTOP LABEL word
Assembly ehaque Page 44 of 51

MYSTACK ENDS

MYCODE SEGMENT para public 'code'


ASSUME cs:MYCODE, ds:MYDATA, ss:MYSTACK
STRT:
mov bx, ds
mov ax, seg MYSTACK
mov ss, ax
mov sp, offset STKTOP
mov dx, seg MYDATA
mov ds, dx

mov es, bx
mov di, 80h
mov ch, 00
mov cl, es:[di]
cmp cx, 0000 ; count zero ?
je hlp_msg ; command tail absent !

dec cx ; not to include carriage return


mov si, 0000
cmd_tail:
mov al, es:[di + 2]
mov [fname + si], al
inc si
inc di
loop cmd_tail
mov [fname + si],0 ; make ASCIIZ

mov ah, 3Dh ; open file


mov al, 00h ; choose input mode
mov dx, offset FNAME
int 21h
jc err_msg
mov HANDLE, ax
hlp_msg:
mov ah, 09h
mov dx, offset help_msg
int 21h
jmp dos
err_msg:
mov ah, 09h
mov dx, offset err_mesg
int 21h
dos:
mov ax, 4C00h ;return to DOS
int 21h
MYCODE ENDS
END strt

120. Memory resident program


A memory resident program also known as terminate and stay resident program [TSR] is
one that is installed in the memory and stay there until it is removed by the user or the
computer is rebooted.

Such program might remain hidden and then be activated by special key strokes, or by
intercepting the IBM PC interrupt, such as timer interrupt, access to hardware interrupts
etc., which may be originated by other programs.
Assembly ehaque Page 45 of 51

TSR get loaded on the top of DOS. It remains resident in the memory in a dormant state,
doing nothing, but occupying memory even after termination.

122. Mechanism of activation of TSRs


- TSR gets activated by the process involved with interrupts and the interrupt vector
table [IVT],
- TSR steals the normal interrupt by replacing the address in IVT with the address of
one of the TSR routines,
- This routine checks for an event connected with an interrupt service routine [ISR]. If it
gets one, the TSR is activated, otherwise it passes control to the original ISR.

ROM BIOS ROM BIOS

TSR transfers
Control to ROM
TSR BIOS routine
Call to a
ROM BIOS
routine
DOS Call to a ROM DOS
BIOS routine
Interrupted
By TSR
IVT IVT

No TSR in memory TSR loaded in memory

122. DOS function calls to create TSRs


121 DOS function # 35 : get interrupt vector
Returns the segment - offset address of an interrupt vector.
Calls the function with the desired vector number in AL,
The 32 bit address (vector) is returned in ES:BX register pair.
Example:
mov ah, 35h
mov al, 09h; for interrupt # 9 : input a character from keyboard and store it in a
int 21h; 2 byte circullar buffer located in low memory (0000:041Ah)

mov int9, bx; store offset &


mov int9 + 2, es; segment address of ISR
int9 label word dd ?; store old interrupt # 9 address

122 DOS function # 25 : set interrupt vector


Replace one of the interrupt vectors with a users routine address in the memory.
Calls the function with the interrupt number in AL,
and
the segment-offset 32 bit address (vector) of user defined interrupt (TSR) routine in
DS:BX register pair.
Example:
mov ax, seg our_routine
Assembly ehaque Page 46 of 51

mov ds, ax
mov ah, 25h; set interrupt vector
mov al, 09h; for interrupt # 9 : input a character from
keyboard
mov dx, offset our_routine
int 21h;
------
------
our_routine proc; for new interrupt # 9 handler here

123 For terminate and stay resident


Use
i) DOS function # 27 : DX contains the offset of the end of resident code.
or
ii) DOS function # 21 : AH = 31h ( function number )
DX contains the size of the executable portion of the program
i.e., size in bytes divided by 16.

• To find where resident programs are loaded in the memory use dos command :
>mem / c

121. Form of interrupt handler (ref.Jones W B: Assembly language, page # 409)


handler proc far;
push all register used;
process interrupt;
pop all pushed registers;
iret
handler endp

122. Call old interrupt handler from new one (ref.Jones W B: Assembly language, page #
409)
SEG OldIntVec must be in a segment register
pushf; push flags for other handler
sti; or ‘ cli ’ if necessary
call OldIntVec

123. Skeleton of TSR program (ref.Brey B B: Intel MPUs, page # 272)


.Model tiny
.code
.startup
jmp install; skip
addr dd ?; old interrept vector
new proc far; new interrupt procrdure
iret; do nothing interrupt
new endp

install:
mov ax, cs; address CS with DS
Assembly ehaque Page 47 of 51

mov ds, ax

;; get vector # 0 address


mov ax, 3500h; function # 35 in AH, vector # 0 in AL
int 21h

;; save vector address at addr


mov word ptr addr, bx; offset
mov word ptr addr, es; segment

;; install new interrupt vector 0 address


mov ax, 2500h; function # 25 in AH, vector # 0 in AL
mov dx, offset new
int 21h

;; find paragraph
mov dx, offset install
mov cl, 4
shr dx, cl; divide by 16 to get paragraph
inx dx; adjust paragraph nos.

;; exit to dos as tsr


mov ax, 3100h; function # 31 in AH, error code # 0 in AL
int 21h
end

124. Example:
a) Assembly program
Title ASM17pa.asm Two byte sequence for a keyboard entry
code segment
assume cs: code, ds: code
org 100h; the executive file of ‘com’ type
start:
jmp setup; jump to installation routine

;; memory resident code begins here


int9_handler proc far
sti; reenable hardware interrupt
pushf
call dword ptr cs:[old_interrupt9]; jump to int9 routine
sti
pushf
call dword ptr cs:[old_interrupt9]; type character twice
iret
old_interrupt9 dd ?; store old_interrupt9 address
int9_handler endp
end_isr label byte
;; end of TSR program

;; save a copy of original int9 vector


;; setup the address of our program as the new vector
;; terminate this program and leave int9_handler in memory
setup:
mov ax, 3509h; get int9 vector
int 21h;
Assembly ehaque Page 48 of 51

;; save int9 vector


mov word ptr old_interrupt9, bx
mov word ptr old_interrupt9 + 2, es

mov ax, 2509h; set int9 vector


mov dx, offset int9_handler
int 21h;

mov dx, offset end_isr; end of resident code


int 27h;
code ends
end start

• Compile the program as


Masm asm17pa
link / tiny asm17pa

Q. Use debugger ‘debug.exe’ to verify that the address of ISR for interrupt # 9 in the IVT
is replaced by the address of our interrupt handler and the address of old one is written
at the proper memory location as directed in the program ? Also verify that the TSR
address corresponds to the program ? The TSR address can be found by ‘ mem /debug
/p ‘ command at C:> prompt ?

b) C program version
// Title ASM17pc.c Two byte sequence for a keyboard entry
# include <dos.h>
void interrupt(*prev)();
void interrupt our();

void main(void)
{
prev = getvect(9);
setvect(9, our);
keep(0, 500);
}

void interrupt our()


{
(*prev)();
(*prev)();
}

Q. Modify the C program so that the key press will be echoed for a random number of time ?
Hints: use for – loop and function – random( ).
Assembly ehaque Page 49 of 51

125. Accessing input / output ports


Ports are connection between the CPU and other devices connected to computer. Each
port has a specific address. The 8086 CPU is capable of addressing 65536 ports.

Most devices have


• one or more status port, which can be used to see if a character is ready.
• one or more data ports, through which input / output data is transferred.

126. IN – instruction
The IN instruction inputs a byte or word from a port into the accumulator register AX
(AL).

Format: IN accumulator, port


Port may be a constant in the range 0 – FFh or it may be a value in DX register between
0 – FFFFh.
Accumulator must be register AL for 8 bit transfers and AX register for 16 bit transfers.

127. Examples
In al, 3Ch ; input byte from port 3Ch
In al, dx ; DX contains a port address
In ax, 60h ; input word from port 60h
In ax, dx ; input word from port whose address is in DX

128. OUT – instruction


The OUT instruction outputs a byte or word from the accumulator register AX (AL) to a
port.

Format: OUT port, accumulator

Examples
Out 3Ch, al ; output byte from port 3Ch
Out dx, al ; DX contains a port address
Out 60h, ax ; output word from port 60h
Out dx, ax ; output word from port whose address is in DX

129. Example - Controlling the speaker of PC


• The speaker control port ( number 61h) turns the speaker ‘on’ and ‘off’ by controlling
the 8255 programmable peripheral interface chip.

• To turn the speaker ‘on’, input the current value in port 61h, set the lowest 2 bits, and
output the byte back through the port.

• To turn the speaker ‘off’, clear bits 0 and 1 and output the status again.
Assembly ehaque Page 50 of 51

• The 8253 timer chip controls the frequency (pitch) of the sound being generated. To
use send a value between 0 – 255 to port 42h.
Vcc
Timer
clk
IRQ vector 8 (18.2 Hz)
#0 out
gate

clk DRQ 0 (DRAM refresh)


#1 out
gate Vcc
1,193,180 Hz
clk
#2 out
PB0 gate
PB1

Speaker & Timer circuit in PC


IO ports 40h – 43h programs the timer,
IO ports 61h programs the PB0 & PB1.

• Program
speaker equ 61h
timer equ 42h
tone equ 1000
MYSTACK SEGMENT para stack 'stack'
DB 16 dup('STACK ')
STKTOP LABEL word
MYSTACK ENDS

MYCODE SEGMENT para public 'code'


ASSUME cs:MYCODE, ss:MYSTACK
strt:
mov ax, seg MYSTACK
mov ss,ax
mov sp,offset STKTOP

mov di, tone


beeps: mov bx, di ; beeps start
mov ax, 34dch ; dx:ax = 1193180 Hz (1234DCh)
mov dx, 12h
div bx ; get the count
out 42h, al ; enter the count into control reg of 8253
mov al, ah
out 42h, al
in al, 61h ; get speaker status
push ax
or al, 03 ; set lowest two bits
out 61h, al ; turn speaker ‘on’

mov si, 0fffh ; create delay


l0: mov cx, 0ffffh
l1: loop l1
dec si
jnz l0
Assembly ehaque Page 51 of 51

pop ax ; get original status


and al, 0fch ; clear lowest two bits
out 61h, al ; turn speaker ‘off’

sub di, 100 ; change tone


cmp di, 100
jnz beeps

mov ax,4C00h
int 21h

MYCODE ENDS
END strt

You might also like