0% found this document useful (0 votes)
360 views

Assignment No 1: Write X86 ALP To Count, Positive and Negative Numbers From The Array

1. The document provides instructions on writing an x86 assembly language program to count positive and negative numbers from an array. 2. It includes sections on declaring variables and data segments, reading input from the keyboard, displaying output to the monitor, defining macros and procedures, and algorithms for converting between hexadecimal and ASCII representations of numbers. 3. The main tasks of the program are to declare an array with positive and negative numbers, iterate through the array checking the sign of each number, increment the appropriate count variable, and call a display procedure to output the final counts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
360 views

Assignment No 1: Write X86 ALP To Count, Positive and Negative Numbers From The Array

1. The document provides instructions on writing an x86 assembly language program to count positive and negative numbers from an array. 2. It includes sections on declaring variables and data segments, reading input from the keyboard, displaying output to the monitor, defining macros and procedures, and algorithms for converting between hexadecimal and ASCII representations of numbers. 3. The main tasks of the program are to declare an array with positive and negative numbers, iterate through the array checking the sign of each number, increment the appropriate count variable, and call a display procedure to output the final counts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 142

Assignment No 1

Write X86 ALP to count, positive and negative


numbers from the array

1
ALP Program Structure
Section .Data (declare Data segment)
; initialized variable Declaration
Section .BSS (declare Block Started by Segment sort of Extra data
segment)

; uninitialized variable Declaration


Section .Text (declare Code segment)
Global _start (Entry point for program)
_Start:
;Program code goes here
01/01/2022 2
; semicolon is used to give comment
Section .Data initialized variable Declaration

Syntax
Var_Name Data_Type Variable_Value
Data_Type
DB- Declare/Define Byte (8 bit)
DW- Declare/Define Word (16 bit)
DD- Declare/Define Double Word (32bit)
DQ- Declare/Define Quad Word (64 bit)
Eg. A DB 50
Declare Variable A of type byte with value 50
3
msg db 10, "The sum of array elements is:"
msg_len equ $-msg
;this calculates length of msg and assigns to var msg_len

EQU –directive assigns right side value to left side variable


10-New line Ascii value in Decimal (you can use 0Ah in hex)
$-is current address of Prompt or pointer
Msg -starting address of varible msg
In above eg.
Let
starting address of msg is 100, then
$=129 (including spaces)
$-msg=129-100=29
msg_len=29

4
Section .BSS ; uninitialized variable
Declaration
Syntax
Var_Name RES memory_Type Memory Size
RES-Reserve memory
RESB,RESW,RESD,RESQ- Reserve byte,word,double
word,quad word memory
Eg.
A resb 50
Declare Variable A and allocate 50 bytes memory
for it.
01/01/2022 5
Input/ Read System Call
mov rax,0 ;function to Read(function no compulsory inRAX)
mov rdi, 0 ; read through keyboard
mov rsi, Variable Name
mov rdx, variable length in bytes
syscall ;System call

;Accept input through keyboard and store at variable


name for specified variable length
01/01/2022 6
Display/ Write System Call
mov rax,1 ;function to Display(function no compulsory inRAX)
mov rdi, 1 ; Display on monitor
mov rsi, Variable Name
mov rdx, variable length in bytes
syscall ;System call

;Display variable_name contents of specified variable


length on monitor
01/01/2022 7
Exit System Call
mov rax, 60 ;function to exit or terminate
program (function no compulsory inRAX)
mov rdi, 1/0 ; with status either 0 or 1
syscall ;System call

01/01/2022 8
Declaration of Macro Syntax
%macro macro_Name no_of_ parameters
%1 ;first parameter
%2 ;second parameter
%3 ; third parameter
and so on
%endmacro

Calling of macro--
macro_Name first parameter, second parameter, ; third
parameter
01/01/2022 9
Macro Syntax
%macro read 2 ; ; name of macro , 2 parameters are passed
• mov rax,0 ; read syscall
• mov rdi,0 ; keyboard
• mov rsi,%1 ;variable
• mov rdx,%2 ; variable length in bytes
• syscall
• %endmacro

Calling of macro--
read MSG, 100;

01/01/2022 10
Procedure Syntax
• Procedure declaration and defination (should be after exit
code in program)

Procedure_Name:
;code of procedure

RET
 Procedure call in program
call Procedure_Name
01/01/2022 11
Example
Display:
;code of procedure display

RET
Calling ->

Call Display

01/01/2022 12
Difference between macro and procedure

• When call macro code is inserted in main


program and executed as a program
instructions
• When call procedure control transfers to
procedure definition executes code in
procedure location and control returns back to
main program

01/01/2022 13
Display Procedure

When you want to display number on screen you need to convert number from hex to ascii
format

01/01/2022 14
Algorithm for number display on screen-Hex to
Ascii conversion
1. Take cnt value as 16 into cnt variable; count for 16 digits to
display
2. Move address of “result” variable into rdi.
3. Rotate left rbx register by 4 bits. ;rbx reg =16 digit number to
display
4. Move bl into al.
5. And al with 0FH.
6. Compare al with 09H.
7. if greater Add 37H into al.
8. Else Add 30H into al.

01/01/2022 15
9. Move al into memory location pointed by
rdi.
10.Increment rdi.
11. Loop the statements till count value
becomes zero.
12.Return from procedure.

01/01/2022 16
display:
;---------------------mov rbx,[num] ;STORE NUMBER IN rBX ----------------------
mov rdi,dispbuff ;POINT rSI TO NUM_BUFFER

;LOAD NUMBER OF DIGITS TO DISPLAY


mov cx,16 ;LOAD COUNT OF ROTATION IN CL
up1:
rol rbx,04 ;ROTATE NUMBER LEFT BY FOUR BITS
mov al,bl ;MOVE LOWER BYTE IN DL
and al,0fh ;MASK UPPER DIGIT OF BYTE IN DL(GET ONLY LSB)
add al,30h ;ADD 30H TO CALCULATE ASCII CODE
cmp al,39h ;COMPARE WITH 39H
jg add_37
;IF grater THAN 39H AKIP ADD 37
add al,30h
Jmp skip1 ;ELSE ADD 30
add_37 : add al,37h
skip1 :mov [rdi],al ;STORE ASCII CODE IN DNUM_BUFFER
inc rdi ;POINT TO NEXT BYTE
dec cx ;DECREMENT THE COUNT OF DIGITS TO DISPLAY
jnz up1 ;IF NOT ZERO JUMP TO REPEAT

dispmsg dispbuff,16 ;CALL TO MACRO


ret
01/01/2022 17
converting number from ascii to HEX

When you accept input from user ,input will store in ascii format in memory. To
perform operations on data you need to convert ascii value to Hex format

01/01/2022 18
Algorithm
1. XOR rbx with rbx to initialize it to 0.
2. XOR rcx with rcx to initialize it to 0.
3. XOR rax with rax to initialize it to 0.
4. Move 16 to rcx register.;number count to convert
5. Move the address of “num” variable into rsi.
6. Rotate left rbx by 4 bits.
7. Move value at memory location pointed by rsi into al.
8. Compare al with 39H.

01/01/2022 19
9. If greater Subtract 37H from al.
10.Else Subtract 30H from al.
11. Add al into bl.
12. Increment rsi pointer
13.Loop the statements till counter becomes
zero.
14.Return from procedure.

01/01/2022 20
Ascii_to_Hex:
mov rbx,0 ;INITIALISE BL BY 0
mov rcx,16 ;INITIALIZE COUNTER AS 16
mov rsi,num_ascii ;POINT ESI TO num_ascii
up2:
rol rbx ,04 ;ROTATE BL TO LEFT
mov al,[rsi] ;MOV NUMBER INTO AL
cmp al,39h ;COMPARE AL(NO IN ASCII) WITH 39H
jg sub_37 ;JUMP IF greater THAN 39h
sub al,30h ; else SUB 30h
Jmp skip2 ;
sub_37 : sub al,37h ;SUB 37 h
skip2 :add rbx,rax ;ADD PREVIOUS NO INTO CURRENT
inc rsi ;INCREMENT ESI
loop up2 ;RPEATE LOOP
ret

01/01/2022 21
To check output of stack in debugging use
following commands
1. Nasm –f elf64 ndp.asm
2. Ld –o ndp ndp.o
3. Gdb ndp
4. Break _start ;you can set any breakpoints in program
5. Run
6. Ni ;next instruction execute
7. Info reg ; system register contents can view
8. Info float ; stack registers can view starting from R7 to
R0
9. Ni
10. x/10xh &result ; contents of result variable can
check
01/01/2022 22
1 : Count +ve & -ve nos
• Declare Array by assigning multiple values

01/01/2022 23
Logic for positive /negatiove number
checking
1. To check whether number is positive or negative
check sign bit of number.
2. To check bit we can use BT-bit test instruction
3. Or shift number to left side by 1 bit so sign bit will
shift in carry bit
4. Or rotate number to left side by 1 bit so sign bit will
shift in carry bit
5. Check carry bit
1. If carry bit=1 then number is negative
2. Else If carry bit=0 number is positive

01/01/2022 24
1.
Algorithm
Declare array with 64bit numbers,positive count,negative count
2. Point rsi to array
3. Take counter as no of elements
4. Take contents of rsi; first element from array
5. Check 63rd bit using BT instruction/rotate to left by 1 bit using ROL
instruction/shift to left by 1 bit using SHL instruction
6. Check bit in carry using JC instruction
7. If carry=1 then increment negative number count
8. Else increment negative number count
9. Increment rsi pointer to point next number from array
10. Repeat cheking procedure till counter will not become zero
11. Call display procedure to convert positive number count in ascii and
display the number
12. Call display procedure to convert negative number count in ascii
and display the number
01/01/2022 25
You can use SHL/ROL/BT 63

01/01/2022 26
Assignment no 2
• Overlapped and non overlapped Block
Transfer (with and Without string instructions)

01/01/2022 27
Block Data transfer
1. Initialize Array count
2. Define source Array (Array 1)
3. Define Destination Array (Array 2) (all Zero)
4. Display menu using Display macro
5. Accept Choice from user using Accept macro
6. If 1 call non overlapped Block Trasnsfer without string instructions
Procedure else continue
7. If 2 call non overlapped Block Trasnsfer with string instructions
Procedure else continue
8. If 3 call overlapped Block Trasnsfer without string instructions Procedure
else continue
9. If 4 call call overlapped Block Trasnsfer with string instructions
Procedure else exit
10. If 5 Use Exit system call to exit
11. Stop
01/01/2022 28
 In Procedures ---
1. Display source and destination addresses and
contents before block transfer
2. Copy Elements from source array to Destination
array till count reaches to zero
3. For overlapped select position in destination
array to copy elements from array1 to array 2
4. Display Source and destination array with
Addresses after BT

01/01/2022 29
Non-overlapped BT without string instructons
1. Point rsi to source
2. Point rdi to destination
3. Take counter for number to transfer from source to
destination
4. Take contents of rsi in rax
5. Mov rax to contents of rdi
6. Inc rsi and rdi by 8bytes
7. Decrement counter
8. Repeat procedure till counter will not become zero
9. Display source and destination addresses and contents.

01/01/2022 30
Non-overlapped BT with string instructons
1. Point rsi to source
2. Point rdi to destination
3. Take counter in RCX for number to transfer from source to
destination
4. Clear direction flag using CLD instruction; if cld=0 it will set
RSI and RDI in auto increment mode. No need to increment
pointers explicitly.
5. Transfer contents from rsi to rdi using string instruction
movsb ; movsq instruction automatically transfers contents
from rsi to rdi
6. Repeat procedure till counter will not become zero using
REP instruction as a prefix to movsq instruction ; no need to
decrement rcx explicitly. Rep instruction loops till rcx=0
7. Display source and destination addresses and contents.
01/01/2022 31
overlapped BT without string instructons
Section .Data
source dq
1111111111111111h,2222222222222222h,3333333333333333h,0h,0h

1. Point rsi to source+2 ;point rsi to source block last position


2. Point rdi to source+4 ; point rdi to destination block last position. 1
element from source is overlapped. You can overlap from any position
3. Take counter for number to transfer from source to destination
4. Take contents of rsi in rax
5. Mov rax to contents of rdi
6. dec rsi and rdi by 8 bytes
7. Decrement counter
8. Repeat procedure till counter will not become zero
9. Display source and destination addresses and contents.
01/01/2022 32
Non-overlapped BT with string instructons
1. Point rsi to source+2 ;point rsi to source block last position
2. Point rdi to source+4 ; point rdi to destination block last position. 1
element from source is overlapped. You can overlap from any
position
3. Take counter in RCX for number to transfer from source to
destination
4. Set direction flag using STD instruction; if std=1 it will set RSI
and RDI in auto decrement mode. No need to decrement pointers
explicitly.
5. Transfer contents from rsi to rdi using string instruction movsq ;
movsq instruction automatically transfers contents from rsi to rdi
6. Repeat procedure till counter will not become zero using REP
instruction as a prefix to movsq instruction ; no need to decrement
rcx explicitly. Rep instruction loops till rcx=0
7.01/01/2022
Display source and destination addresses and contents. 33
01/01/2022 34
01/01/2022 35
01/01/2022 36
Output
• Output should be in format

Address:Contents

01/01/2022 37
Display source address:Contents
1. Take counter for number of elements to display . In our case it is 3
2. Take pointer r8 to point source; take address of source in r8 to display
3. Take r8 in rbx and call display procedure; display address first. In
display procedure instead of using rdi pointer use r9 bcz in write system call you need to use rsi
and rdi

4. Display explicit ‘:’


5. Take contents of r8 in rbx and call display procedure; contents
will display here
6. Increment r8 by 8bytes
7. Repeat loop till counter will not become zero

01/01/2022 38
Display destination address:Contents
1. Take counter for number of elements to display . In our case it is 3
2. Take pointer r8 to point Destination; take address of source in r8 to display
3. Take r8 in rbx and call display procedure; display address first. In
display procedure instead of using rdi pointer use r9 bcz in write system call you need to use rsi
and rdi

4. Display explicit ‘:’


5. Take contents of r8 in rbx and call display procedure; contents
will display here
6. Increment r8 by 8bytes
7. Repeat loop till counter will not become zero

01/01/2022 39
Assignment no 3
• Hex to BCD and BCD to Hex conversion

01/01/2022 40
number Conversion
1. Start
2. Display menu
3. Accept Choice from user
4. If choice is 1 call Hex_to_BCD Procedure else
continue
5. If choice is 2 call BCD_to_Hex Procedure else
continue
6. If choice is 3 Use Exit system call to exit
7. Stop
01/01/2022 41
Hexadecimal to BCD conversion
 Conversion of a hexadecimal number can be
carried out by dividing number by 10 or 0Ah
and displaying remainder in reverse way

01/01/2022 42
H->B
1. Accept 4 digit hex number from user
2. Convert number from Ascii to hex by calling conversion
procedure
3. Take number in Accumulator
4. Divide no by 10 or 0Ah; after division quotient goes in AX
and remainder is in DX
5. Push dx on stack
6. Increment counter ; to pop dx from stack
7. Compare quotient with zero. Repeat the procedure till it will
not become zero
8. Pop dx from stack
9. Convert to ascii and display 1 digit
10. Repeat pop dx and display procedure till counter will not
become zero
01/01/2022 43
BCD to Hexadecimal number
 Conversion of BCD number to Hexadecimal number
can be carried out by multiplying the previous result
by 10 0r 0AH and adding new digit to it

01/01/2022 44
1. Accept 5 digit bcd number from user
2. Take rsi pointer to point number; pointing to first number ascii value
3. Take counter with 5 value
4. Take zero in Accumulator
5. Take zero in rdx
6. Multiply accumulator by 10 or 0Ah
7. Take first value of rsi in dl register and convert to hex by subtracting
30h
8. Add this value to accumulator
9. Increment rsi pointer; now points to 2nd ascii value
10.Repeat the procedure of taking zero in rdx and multiplying till
counter will not become zero
11.Finally display accumalator contents by calling conversion procedure

01/01/2022 45
01/01/2022 46
01/01/2022 47
01/01/2022 48
01/01/2022 49
Assignment 4
• Write X86 ALP to perform multiplication of
two 8- bit hexadecimal numbers.
1. successive addition
2. add and shift method
use of 64-bit registers is expected

01/01/2022 50
Algorithm
1. Display menu
2. Accept choice
3. If 1 call successive addition
4. Else if 2 call add and shift procedure
5. Else call exit

01/01/2022 51
successive addition
1. Accept 2 8-bit numbers
2. Convert from ascii to hex
3. Add first number to result variable till second
number will not become zero.
; second no is acting as a count
Eg. 02 *03
add 02 three times.
Or add 03 two times

01/01/2022 52
mov al,[num1]
mov bl,[num2]
lp: Add [result],ax
Dec bl
Jnz lp
;convert result and display

01/01/2022 53
Add and Shift
1. Take num1 in ax;multiplicand ;8bit multiplicand
2. Take num2 in bx;multiplier; 8bit multiplier
3. Take count as number of bits; count=8bit
4. Take result variable of size word with zero value initially
5. Shift multiplier (num2) right by 1 bit using shr instruction
6. Check bit using carry;JC instruction can be used
7. If carry bit =1 then
8. Shift multiplicand (num1) left by 1 bit and add into result variable
9. Else if carry bit=0 only shift multiplicand (num1) left by 1 bit no
need to add
10.Repeat procedure till count become zero

01/01/2022 54
mov al,[num1]
mov bl,[num2]
mov [cnt],8
Lp1: Shr bx,1
Jnc lp
Add [result],ax
lp:shl ax,1
Dec [cnt]
Jnz lp1
;convert result and display
01/01/2022 55
Assignment 5 : Far Procedure

Write X86 ALP to find,


a) Number of Blank spaces
b) Number of lines
c) Occurrence of a particular character.
Accept the data from the text file. The text file has to be accessed
during Program_1 execution and write FAR PROCEDURES in
Program_2 for the rest of the
Processing. Use of PUBLIC and EXTERN directives is mandatory.

01/01/2022 56
NASM assembly program structure
;file.asm
;section .data
;section .bss
;section .text
global _start
_start:
;;
Procedures
01/01/2022 57
• If procedures have defined and called in same
program ie in same code segment then it is
near procedure call
• But If procedures have defined called in one
program and called in another program ie in
other code segment then it is far procedure
call

01/01/2022 58
NASM assembly program structure: Near
Procedure

01/01/2022 59
• To call far procedures or far variables we need
to declare them as a public (using global
keyword) procedures or variables in defining
program.
• And declare as a extern using EXTERN keyword
in calling program

01/01/2022 60
01/01/2022 61
Execution
• $ nasm -f elf64 file1.asm
• $ nasm –f elf64 file2.asm
• $ ld –o file file1.o file2.o

• $ ./file

01/01/2022 62
File operations : Open & Close

mov rax,2 ;open


mov rdi,filename ;terminated with '\0'
mov rsi,mode ;0R,1W,2RW
mov rdx,permissions ;rwxrwxrwxo(octal)
Syscall
Returns : rax = filehandle (on success)
rax = 1
(on failure)

01/01/2022 63
SYSTEM CALL OPEN File

mov rax, 2 ; 'open' syscall returns file handle in rax if file opened
successfully else returns -1
mov rdi, filename1 ; file name
mov rsi, 2 ; mode of file 0-read,1-write,2 –read and write
mov rdx, 0777o ; permissions set
Syscall

mov [fd_in], rax ;returns file handle in rax

01/01/2022 64
SYSTEM CALL READ File

mov rax, 0 ; ‘Read' syscall


mov rdi, [fd_in] ; file Pointer
mov rsi, Buffer ; variable Buffer for read
mov rdx, length ; len of data want to read
Syscall

;returns length ie number of bytes read in rax register.

01/01/2022 65
SYSTEM CALL
• CLOSE File

mov rax,3
mov rdi,[fd_in]
syscall

01/01/2022 66
Algorithm –no of new lines
1. Accept file name from user
2. End filename with null char ie 0
3. Open a file using function 2
4. Read file in buffer variable using function 0
5. You will get length of file (number bytes read in rax with EOF)
6. Dec rax to get actual length
7. Point rsi to point the buffer
8. Take contents of rsi in al and compare with 0aH
9. If equal then increment the new line counter
10.Else increment rsi pointer
11.Repeat the procedure till actual length will not become zero
12.Call display procedure to convert new line counter in ascii and
display the number
01/01/2022 67
Algorithm –no of blank spaces
1. Accept file name from user
2. End filename with null char ie 0
3. Open a file using function 2
4. Read file in buffer variable using function 0
5. You will get length of file (number bytes read in rax with EOF)
6. Dec rax to get actual length
7. Point rsi to point the buffer
8. Take contents of rsi in al and compare with 20H
9. If equal then increment the blank space counter
10.Else increment rsi pointer
11.Repeat the procedure till actual length will not become zero
12.Call display procedure to convert blank space counter in ascii
and display the number
01/01/2022 68
Algorithm –substring occurance
1. Accept substring to search ; length1 for 1 and length2 for 2 string
st nd

2. Point rsi to the buffer


3. Point rdi to the substring
4. Take contents of rsi in al and compare with contents of rdi
5. If equal then increment the rsi and rdi
6. Decrement length1 and length2
If match found for 1st char but not for next chars then reinitialise rdi to substring , length2 to
default length
If match found for then increment sustring count and reinitialise rdi to substring , length2 to
default length
Repeat loop till length2 not equal to zero
7. If not equal increment rsi ,decrement length1
8. Repeat the procedure till length1 will not become zero
9. Call display procedure to convert substring count in ascii and display
the number
01/01/2022 69
Mov rsi,buf
Mov rcx,[abuf_len]

lp:mov al,[rsi]

Cmp al,20h ;space ascii value 32 (20H)/for new line compare with 0aH
Je incscount
jmp skip
incscount :inc qword[spacecount]
Skip:inc rsi
Dec ,[abuf_len]
Jnz lp
01/01/2022 70
Assignment no 6
• check the mode of processor(Real or Protected),
then read GDTR, LDTR and IDTR and display the
same.

01/01/2022 71
• GDTR,IDTR -48 bit in size; 12digits=48 bits
• TR, LDTR-16 bit in size
• MSW -32 bit in size

• They hold 32 bit base address and 16 bit limit


• so output format should be
• Base address:limit

01/01/2022 72
Algorithm
1. To check operating mode of processor we can
check PE bit of control word register CR0
2. CR0 is nothing but Machine Status Word
3. So read contents of MSW by using SMSW
instruction
4. And check 0th bit by using either ROR/SHR or BT
instruction
5. If carry bit=1 then processor will be in protected
mode else processor is in real mode
6. Display msg accordingly
01/01/2022 73
1. Take variable to hold all register contents of required
size
2. Store register contents by using store instruction; eg.
sgdt [gdtr] ;gdtr is variable
3. let the contents of GDTR
4. 12345678ABCD ;ABCD is limit
5. These Contents will be stored in memory like
6. CDAB78563412
7. So to display first point to last byte, take contents
,convert and display
8. Decrement pointer and repeat procedure
01/01/2022 74
Check Operating mode of processor by reading MSW

smsw eax ;Reading CR0

mov [controlword],eax

ror eax,1 ;Checkin PE bit, if 1=Protected Mode, else Real Mode


jc prmode
disp rmodemsg,rmsg_len
jmp nxt1

prmode:disp pmodemsg,pmsg_len

01/01/2022 75
Display Register contents
sgdt [gdtr]
sldt [ldtr]
sidt [idtr]
Str [tr]
Smsw [msw]
disp gdtmsg,gmsg_len
mov bx,[gdt+4]
call disp_num
mov bx,[gdt+2]
call disp_num
disp colmsg,1
mov bx,[gdt]
call disp_num
01/01/2022 76
Assignment 7 : Bubble Sort

• Write X86 ALP -To sort the list of integers in


ascending / descending order using bubble
sort. Read the input from the text file and
write the sorted data back to the same text
file.

01/01/2022 77
1. Accept file name from user;
2. Dec rax; getting length in rax with enter key
3. End filename with null car; mov [filename+rax],0
4. Open file using function 2
5. Read file in buff using function 0; rax will hold actual length of file
including EOF so decrement rax
6. Buff will hold ascii values of file contents
1. Eg . Data .txt contain
2. 1
3. 2
4. 3
5. 4
6. 5
7. Then buff will contain
8. 310A320A330A340A350A

01/01/2022 78
9. We want to perform bubble sort so we need to
find array contents without enter key ascii value
so,
10.Point rsi to buff and rdi to another variable array
11.Take contents of rsi transfer to contents of rdi
12.Increment rdi to hold second value
13.Increment rsi two times to point second value
14.Repeat procedure till actual length will not
become zero
15.Perform bubble sort operation on array
16.Write contents using function 1 in same file
01/01/2022 79
01/01/2022 80
01/01/2022 81
01/01/2022 82
01/01/2022 83
Assignment 8
DOS Commands
• Algorithm
1.Accept Filenames from Command line.
2.Display MENU:-
1.TYPE
2.COPY
3.DEL
3.Procedure for TYPE command
4.Procedure for COPE command
5.Procedure for DELETE command
6.EXIT

01/01/2022 84
Run the program and give arguments to exe file
– Nasm –f elf64 a.asm
– Ld –o a a.o
– ./a data.txt

Data.txt is command line argument to exe file a


It will store in stack
Structure of stack is given in next slide
top of stack hold argument count in RCX
Next position hold address of executable file path in rsi
Next position hold address of first argument in rsi
Next position hold address of second argument in rsi
Next position hold address of third argument in rsi
And so on
01/01/2022 85
Stack When You Run Program

01/01/2022 86
• In our example RCX=1 only one argument for
data.txt
• Rsi =address of ./a
• Rsi=address of data.txt
• Rsi will point to d
• Rsi+1 will point to a
• Rsi+2 will point to t
• Rsi+3 will point to a
• And so on till 0;null char

01/01/2022 87
Algorithm to read filename
1. Point rdi to variable to hold filename given as
argument
2. pop argument count ie rcx
3. Pop rsi ;add of ./a
4. Pop rsi; add of data.txt
5. Take contents of rsi in al
6. And transfer to rdi
7. Increment rsi and rdi pointers
8. Repeat procedure till null char ie. [rsi]=0
01/01/2022 88
How to Fetch Command line Argument
mov rcx,00
pop rcx ;Argument count

pop rsi ; get pointer for executeable file path


pop rsi ; get pointer for arg1

Mov rdi, filename1 ;Filename1 variable to store arg1


;read in filename1 var

Lp: Mov al,[rsi]


Mov [rdi],al
Inc rsi
Inc rdi
Cmp al,0
Jne lp

01/01/2022 89
SYSTEM CALL
• OPEN File
mov rax, 2 ; 'open' syscall
mov rdi, filename1 ; file name
mov rsi, 2 ; mode of file 0-read,1-write,2 –read and write
mov rdx, 0777o ; permissions set
Syscall

mov [fd_in], rax ;returns file handle in rax

01/01/2022 90
SYSTEM CALL
• READ File
mov rax, 0 ; ‘Read' syscall
mov rdi, [fd_in] ; file Pointer
mov rsi, Buffer ; variable Buffer for read
mov rdx, length ; len of data want to read
Syscall

01/01/2022 91
SYSTEM CALL
• WRITE File
mov rax, 01 ; ‘Write' syscall
mov rdi, [fd_in] ; file Pointer
mov rsi, Buffer ; Buffer for write
mov rdx, length ; len of data want to read
Syscall

01/01/2022 92
SYSTEM CALL
• DELETE File

mov rax,87
mov rdi,Fname
syscall

01/01/2022 93
SYSTEM CALL
• CLOSE File

mov rax,3
mov rdi,[fd_in]
syscall

01/01/2022 94
Algorithm -type
1. Take file name as argument
2. Open file using function 2
3. Read file in buff using function 0
4. You will get length in rax; including EOF
5. Decrement length rax
6. Write file contents( read in buff) using
function 1 on monitor;
7. Close file
01/01/2022 95
Algorithm -delete
1. Take file name as argument
2. Delete file using function 87
3. end

01/01/2022 Prof.M.D.Sale,SCOE,Pune 96
Algorithm -copy
1. Take two file names as argument
2. Open file1 using function 2
3. Open file2 using function 2
4. Read file1 in buff using function 0
5. You will get length in rax; including EOF
6. Decrement length rax
7. Write file1 contents( read in buff) using function 1 in file 2
8. Close file1
9. Close file 2

01/01/2022 97
type
mov rax,2 ;open 1st file
mov rdi,file1
mov rsi,2
mov rdx,0777o
syscall

b2:cmp rax,-1d
je displayerror
mov [fhandle1],rax ;copy the fhandle from the rax

;similarly open second file for copy operation

01/01/2022 98
• mov rax,0 ;read the 1st file
• mov rdi,[fhandle1]
• mov rsi,buffer
• mov rdx,bufferlen
• Syscall

• Dec rax
• Mov [actual_len],rax

• mov rax,1 ;write the 1st file on monitor


• mov rdi,1
• mov rsi,buffer
• mov rdx, [actual_len]
• Syscall

01/01/2022 99
delete
• mov rax,87 ;function to delete file
• mov rdi,filename1
• Syscall

01/01/2022 100
copy
• Open first file ,second file
• Read first file in buffer

• mov rax,1 ;write the 1st file in second file


• mov rdi,[fhandle2]
• mov rsi,buffer
• mov rdx, [actual_len]
• Syscall
01/01/2022 101
Assignment no 9

Calculate Factorial of number using


Recursion

01/01/2022 102
Factorial Logic
Trace of a call to Factorial: int z = factorial(4)
factorial(4)= Returns 3*2 = 6 and
4 * factorial(3) terminates

We can’t evaluate 3! factorial(3)=


directly, so we call
factorial (3) 3 * factorial(2)
Returns 2*1 =2
We can’t evaluate 2!
Directly, so we call
factorial(2)= and terminates
factorial(2) 2 * factorial(1)

Returns 1*1
We can’t evaluate 1! factorial(1)=
directly – call and terminates
factorial(1) 1 * factorial(0)

We must call
factorial(0) BASE CASE: Returns 1
factorial(0)= 1 and terminates

finally, factorial(4) computes 4*6, returns 24, and terminates


01/01/2022 103
Algorithm
1. Read value as a command line argument; you
will get ascii value in stack
2. Pop arg cnt,rsi,rsi
3. Take contents from rsi and convert in hex
4. Call factorial function recursively
5. Display factorial

01/01/2022 104
factorial function
• Push number on stack
• Compare number with 1
• If not 1 then decrement number and call
procedure recursively
• if it is 1
• Pop number from stack
• Multiply with result variable
• Return from procedure

01/01/2022 105
ASM PROGRAM
;get number from command argument in rax
mov [no1],rax

call factorial
Xor rax,rax
mov rax, qword[result]

call display ; displays a 8 digit hex number in rax

01/01/2022 106
Factorial Recursion
factorial:
push rcx ;rcx holding number
cmp rcx,01 ;compare number with 1 .if it is not one then recursively
decrement and store on stack
jne continue
jmp exit2
continue :dec rcx
call factorial
exit2:pop rcx ;pop number from stack
mov rax,rcx
mul qword[result] ;multiply with result var
mov qword[result],rax
ret

01/01/2022 107
Assignment no 10
80387 mean ,Variance ,Deviation

01/01/2022 108
To check output of stack in debugging use following
commands
1. Nasm –f elf64 ndp.asm
2. Ld –o ndp ndp.o
3. Gdb ndp
4. Break _start ;you can set any breakpoints in program
5. Run
6. Ni ;next instruction execute
7. Info reg ; system register contents can view
8. Info float ; stack registers can view starting from R7 to R0
9. Ni
10. x/10xh &result ; contents of result variable can check

01/01/2022 109
Algorithm
1. Declare array to calculate mean
2. eg. array dd 1.0,1.0,1.0,1.1,1.5
3. Take count of numbers; =5
4. Initialize ndp wit FINIT instruction
5. Load zero on top of stack in ndp using FLDZ instruction
6. Take pointer rsi to point to array first element
7. Add first value in ST(0)
8. Increment pointer by 4 bytes; as data is of double word type
9. Repeat procedure till counter =0
10.Divide by count to top of stack; st0=mean in our case it may be
1.123……
11.Store mean in variable
01/01/2022 110
For Display Output

12.Decide how many decimal points you want to


deisplay lets 2 decimal points u want to display
13.So, Multiply by 100 to top of stack; decimal point
will shift by 2 positions right by this mul operation ; in
our case it will something like 112.3…….
14.Store BCD of stack top in variable.; in our case it will
00000…..112

15.In memory this number will store like this 80bit


value-
12010000000000000000

01/01/2022 111
;remember 80 bit=10 bytes
1byte=2digits,10bytes=20digits to display
16.Now point r8 to last position ie 10th byte
17.Take counter of 9 to display integer part
18.Take contents of r8 ;2 digits ; first two zeros in first loop and so on
19.Convert and display 2 digits
20.Decrement r8 to point 9th byte
21.Repeat display procedure till counter will not become zero
16. 000000000000000001
22.Display explicit decimal point ; 000000000000000001.
23.Take contents of r8 ;2 digits ; r8 is pointing to 0th byte
24.Convert and display 2 digits ;000000000000000001.12
01/01/2022 112
Mean operation
finit ;initialize Floating Point Unit
fldz ;load zero on ST0-ST0=0
mov rsi,array ;point rsi to array First element
xor rcx,rcx ;make rcx 0
mov cx,[datacnt] ;load counter
lp: fadd dword[rsi] ;add first element of array
Add rsi,4 ; INCREMENT pointer by 4 as data is of size double word
loop lp ;keep adding till counter not zero

• ;top of stack is now holding addition of all 5 values in our case


fidiv word[count] ;divide by number count
fst dword[mean] ; store result in variable mean bcz we need it for
variance

01/01/2022 113
Display Result
FIMUL [hundred] ;want to display 2 decimal points so multiply by 100 to
st0
FBST tword[result] ;store mean from st0 to result variable as BCD value
xor rcx,rcx ;make rcx 0
mov rcx,09h ;load counter by 9
mov r8,result +9 ;point r8 to base of 10th byte digit ;after that we
;print decimal pt.
up2:
mov bl,[r8] ;mov current byte pointed by r8 to bl
call display ;convert it to ASCII and display 2 digits
dec r8 ;decrement pointer
loop up2 ;repeat steps till rcx is not zero
display decpt,1 ;diaply decimal point after 8digits
mov bl,[r8] ;display remaining two digits
call display ;convert it to ASCII and display 2 digits
01/01/2022 114
• Like this calculate variance,deviation and
display the result

01/01/2022 115
Assignment no 11

Roots of quadratic equation 80387

01/01/2022 116
Formula

01/01/2022 117
ALgorithm
1. Declare a,b,c,four,two with values
2. Initialize stack
3. Load b on top of stack ;st0 =b
4. Multiply b with top of stack
5. Load four on top of stack ; b2 will shift to st1 st0=4,st1=b2
6. Multiply a with top of stack ; st0=4a
7. Multiply c with top of stack ; st0=4ac
8. Substract 4ac from b2 ;st0=b2-4ac
9. Compare b2-4ac is equal to zero using either FCOM or FTST
instruction; this comparison sets condition bits in status word
register
10. Store status word register in any register using FSTSW AX
01/01/2022
11. Store higher part of this register in flag register using SAHF 118
12. Use jump instruction to check value either JL,JB
13. If this value is less than zero then display massage complex root
Else continue to find root value
14. Take squre root of top of stack; st0=b2-4ac using FSQRT
instruction
15. Store this value in variasble bcz we have to calculate 2 roots
16. Substract b from st0; st0=st0-b
17. Divide st0 by 2
18. Divide st0 by a
19. Now st0 is holding first root
20. Display the root using display387 procedure
21. Similarly calculate second root and display
01/01/2022 119
For Display Output
1. Decide how many decimal points you want to
deisplay lets 2 decimal points u want to display
2. So, Multiply by 100 to top of stack; decimal
point will shift by 2 positions right by this mul
operation; let it will something like 112.3…….
3. Store BCD of stack top in variable.; in our case it will
00000…..112

4. In memory this number will store like this 80bit


value-
1. 12010000000000000000

01/01/2022 120
;remember 80 bit=10 bytes
1byte=2digits,10bytes=20digits to display
5. Now point r8 to last position ie 10th byte
6. Take counter of 9 to display integer part
7. Take contents of r8 ;2 digits ; first two zeros in first loop and so on
8. Convert and display 2 digits
9. Decrement r8 to point 9th byte
10.Repeat display procedure till counter will not become zero
1. 000000000000000001
11.Display explicit decimal point ; 000000000000000001.
12.Take contents of r8 ;2 digits ; r8 is pointing to 0th byte
13.Convert and display 2 digits ;000000000000000001.12
01/01/2022 121
Display Result
FIMUL [hundred] ;want to display 2 decimal points so multiply by 100 to
st0
FBST tword[result] ;store mean from st0 to result variable as BCD value
xor rcx,rcx ;make rcx 0
mov rcx,09h ;load counter by 9
mov r8,result +9 ;point r8 to base of 10th byte digit ;after that we
;print decimal pt.
up2:
mov bl,[r8] ;mov current byte pointed by r8 to bl
call display ;convert it to ASCII and display 2 digits
dec r8 ;decrement pointer
loop up2 ;repeat steps till rcx is not zero
display decpt,1 ;diaply decimal point after 8digits
mov bl,[r8] ;display remaining two digits
call display ;convert it to ASCII and display 2 digits
01/01/2022 122
Assignment no 12

01/01/2022 123
Commands for 16 bit programming
• TSR programs implement in TASM- 16bit
programming in windows
• Use following commands
– Edit filname.asm ;open file
– Tasm filename.asm ;assemble file
– Tlink filename/t ;link and load file(u can use
filename.obj )
– Filename ; execute filename(u can use use
filename.exe)
01/01/2022 124
TSR: Terminate but Stay Resident
• Transient programs: .EXE, .COM
• TSR programs: .COM
– Can be loaded after DOS is loaded,
– Stay in the memory, even if they are not active on
your screen,
– They appear to exit, but remain in the memory to
perform tasks in the background,

01/01/2022 125
Structure of TSR
• Divided into three sections:
– Data area
– Resident routine and
– Initialisation routine

01/01/2022 126
Resident Routine
• Portion of program which will be made
resident in the memory to perform specified
task.
• During execution of specified task original
register contents may get change so these
contents must be preserved and again loaded
before calling original interrupt service routine

01/01/2022 127
MYINT08:
PUSH AX
PUSH BX ;We can use or
PUSH CX
PUSH DX
PUSH SI
PUSH DI
PUSH SI
PUSH DS
PUSH ES
;// Specified task
POP AX
POP BX ;We can use or
POP CX
POP DX POP SI
POP DI POP SI POP DS
POP ES
JMP CS:SAVEINT08
01/01/2022 128
Initialization routine

It execute only once.

When executed reserves memory block where
resident program resides.

Resident program may get executed periodically or
on demand. For this interrupt capture process is
used.

In that process ,modify the content of IVT entries
& contain new address pointing to resident
program.

Save original content of IVT so that after resident
program execution control transfer to original ISR
01/01/2022 129
Initialization Routine
• Does the preliminary work to make resident routine
stay resident in the memory,
• It executes only once,
• It performs following steps
– 1) Get the original address of specified interrupt from IVT and
save it
– 2) Store the address of resident program in the IVT in place of
original address,
– 3) Calculate the size of the resident routine including Data
area and PSP. Reserve the memory area of this size and make
the program resident

01/01/2022 130
Initialization Routine Continued . . .

• To perform these three steps we use three INT


21H functions
– Function 35H: Get Interrupt Address
• Call with AH=35H, AL= int #
• Returns vector address in ES:BX
– Function 25H: Set Interrupt Address
• Call with AH=25H, AL=int # , DS:DX= segment:offset of
interrupt handling routine
– Function 31H: Make program resident

01/01/2022 131
Terminate But Stay Resident (TSR)
01/01/2022 133
01/01/2022 134
01/01/2022 135
WHY .model tiny ?
• As it is .com pgm
• Consist of only one segment ie code segment
so model of memory is .model tiny

01/01/2022 136
WHY ORG 0100h
• .COM program starts at the end of PSP
• PSP location is from 00H –FFH
• So after that code starts at 0100h

01/01/2022 137
Why jmp to transient section
• As resident is always in memory but inactive
state
• So to activate it transient section to b
activated first

01/01/2022 138
Algorithm of initialisation routine
1. Clear interrupt flag to avoid any hardware interrupt during the process of

initialisation,

2. Read the original vector address entry and store is in data area

3. Set the vector address to our interrupt service routine

4. Set interrupt flag

5. Terminate and make it resident

ATTRIBUTE BYTE    BL     R     G     B    I      R      G    B

BACKGROUND      FOREGROUND

6. FORMULA TO CALCULATE OFFSET IN VIDEO RAM USING X,Y CO-ORDINATES

= [(Y * 80)+X]*2
01/01/2022 139
Algorithm of program: (Resident Routine)

1. ORG 100H

2. Unconditionally jump to initialisation routine

3. Reserve memory loctations to store the registers and original vector address

4. Store the registers temporarily

5. Read time

6. Initialise base address(B800h) of page-0 of video RAM in ES and offset(3984h) of a

location where we want to display the RTC,

7. Display HH:MM:SS

8. Restore the original register contents


01/01/2022 140
9. Call the original interrupt service procedure
INIT: CLI
MOV AH,35H ;GET VECTOR
MOV AL,08H ;OF TYPE 08
INT 21H ;WHICH RETURNS VECTOR ADDRESS IN ES:BX

MOV WORD PTR SAVEINT08,BX


MOV WORD PTR SAVEINT08+2,ES

MOV AH,25H ;SET VECTOR


MOV AL,08H ;OF TYPE 08
LEA DX,MYINT08 ;ENTRY POINT OF MY ISR STORED IN DS:DX
INT 21H

MOV AH,31H ;TERMINATE AND MAKE RESIDENT


LEA DX,INIT ;SIZE OF MEMORY BLOCK
STI ;SET IF
INT 21H
END START
01/01/2022 141
RTC
Reading Real Time Clock
MOV AH,02H ;READ CLOCK. RETURNS CH=HH, CL=MM, DH=SS IN BCD
INT 1AH

Displaying on screen (Resolution 80-by-25 Text Mode)


MOV DI,3984 ;OFFSET WHERE WE WANT TO DISPLAY HH:MM:SS
-
MOV ES:[DI],AX

01/01/2022 142

You might also like