Assembly
Assembly
I/O System
device CPU Memory
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
• 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
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
registers
CS – code segment reg. IP – instruction pointer
SS – stack segment reg. SP – stack pointer reg.
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
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
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.
• 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
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.
• Physical address is computed in the bus unit of CPU where the segment registers
and Instruction pointer registers are located.
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
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
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
• 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
CX=count CX=count
L1: L1:
Data Data
processing processing
instructions
no instruction no
CX = 0 CX = 0
? ?
yes yes
exit exit
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
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
52. The 8086 unconditional jump: The unconditional jump permanently transfers the
program execution to a new sequence of instructions.
format: jmp target_label
56. Example: Subtract number ‘b’ from ‘a’, if ‘a’ is greater than ‘b’, otherwise subtract
‘a’ from ‘b’.
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
memory
00004H
CS 4 bytes
address of
IP ISR [CS:IP]
00000h
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
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
♦ 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)
Main endp
end Main
.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
Main endp
end Main
67. Summary:
Addition : use instructions
ADD – add by any number
INC - increase by 1
OR – selective addition (bitwise manipulation)
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.
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
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.
76. Example:
• Create a text file by the name of myMacro.lib to include the following
Assembly Ehaque Page 29 of 51
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.
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.
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
• 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.
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.
89. PUSH : The PUSH instruction puts the contents of a word-sized (16 bit) register or
memory operand on to the top of stack.
• 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
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
pop ds
92. Parameter: Address or data values passed between the mainline program and the
procedure is known as parameters.
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.
DISP PROC
push dx ; save register onto the stack
push ax
MYCODE ENDS
END MAIN
push ax
mov al, bb
push ax
mov al, aa
push ax
mov total, al
Assembly Page 35 of 51
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]
MYCODE ENDS
END MAIN
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
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
f) Passing parameters
• By name : C program passes arguments by value through stack. So subroutine
cannot change them.
addem(a, b, c);
- 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
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);
}
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.
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.
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
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 ENDS
mov es, bx
mov di, 80h
mov ch, 00
mov cl, es:[di]
cmp cx, 0000 ; count zero ?
je hlp_msg ; command tail absent !
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.
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
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
• To find where resident programs are loaded in the memory use dos command :
>mem / c
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
install:
mov ax, cs; address CS with DS
Assembly ehaque Page 47 of 51
mov ds, ax
;; find paragraph
mov dx, offset install
mov cl, 4
shr dx, cl; divide by 16 to get paragraph
inx dx; adjust paragraph nos.
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
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);
}
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
126. IN – instruction
The IN instruction inputs a byte or word from a port into the accumulator register AX
(AL).
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
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
• 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
• Program
speaker equ 61h
timer equ 42h
tone equ 1000
MYSTACK SEGMENT para stack 'stack'
DB 16 dup('STACK ')
STKTOP LABEL word
MYSTACK ENDS
mov ax,4C00h
int 21h
MYCODE ENDS
END strt