MP Lab Manual

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 103

Experiment No.

1
Title: Write an X86/64 ALP to accept five 64 bit Hexadecimal numbers
from user and store them in an array and display the accepted numbers

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:
Experiment No. 1

Aim: Write an X86/64 ALP to accept five 64 bit Hexadecimal numbers from user and store them in an array
and display the accepted numbers.

Objectives:

1) To be familiar with the format of assembly language program structure and instructions.
2) To study the format of assembly language program along with different assembler directives and
different functions of the NASM.

3) To learn the procedure how to store N hexadecimal number in memory.

Environment:

1) CPU: Intel I5 Processor

2) OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3) Editor: gedit, GNU Editor

4) Assembler: NASM (Netwide Assembler)

5) Linker:-LD, GNU Linke

Software Requirements:

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Edito

4. Assembler: NASM (Netwide Assembler)

Theory:

Introduction to Assembly Language Programming:

Each personal computer has a microprocessor that manages the computer's arithmetical, logical and control
activities. Each family of processors has its own set of instructions for handling various operations like
getting input from keyboard, displaying information on screen and performing various other jobs. These set
of instructions are called 'machine language instruction'. Processor understands only machine language
instructions which are strings of 1s and 0s. However machine language is too obscure and complex for using
in software development. So the low level assembly language is designed for a specific family of processors
that represents various instructions in symbolic code and a more understandable form. Assembly language
is a low-level programming language for a computer, or other programmable device specific to particular
computer architecture in contrast to most high-level programming languages, which are generally portable
across multiple systems. Assembly language is converted into executable machine code by a utility program
referred to as an assembler like NASM, MASM etc.

Advantages of Assembly Language

An understanding of assembly language provides knowledge of:


 Interface of programs with OS, processor and BIOS;
 Representation of data in memory and other external devices;
 How processor accesses and executes instruction;
 How instructions accesses and process data;
 How a program access external devices.

Other advantages of using assembly language are:


 It requires less memory and execution time;
 It allows hardware-specific complex jobs in an easier way;
 It is suitable for time-critical jobs;

ALP Step By Step:

Installing NASM:

If you select "Development Tools" while installed Linux, you may NASM installed along with the Linux
operating system and you do not need to download and install it separately. For checking whether you
already have NASM installed, take the following steps:
 Open a Linux terminal.
 Type whereis nasm and press ENTER.
 If it is already installed then a line like, nasm: /usr/bin/nasm appears. Otherwise, you will see
justnasm:, then you need to install NASM.

To install NASM take the following steps:


Open Terminal and run below commands:
 sudo apt-get update
 sudo apt-get install nasm

Assembly Basic Syntax:


An assembly program can be divided into three sections:
 The data section
 The bss section
 The text section
The order in which these sections fall in your program really isn’t important, but by convention the .data
section comes first, followed by the .bss section, and then the .text section.
The .data Section
The .data section contains data definitions of initialized data items. Initialized data is data that has a value
before the program begins running. These values are part of the executable file. They are loaded into
memory when the executable file is loaded into memory for execution. You don’t have to load them with
their values, and no machine cycles are used in their creation beyond what it takes to load the program as a
whole into memory. The important thing to remember about the .data section is that the more initialized
data items you define, the larger the executable file will be, and the longer it will take to load it from disk
into memory when you run it.
The .bss Section
Not all data items need to have values before the program begins running. When you’re reading data from a
disk file, for example, you need to have a place for the data to go after it comes in from disk. Data buffers like
that are defined in the .bss section of your program. You set aside some number of bytes for a buffer and
give the buffer a name, but you don’t say what values are to be present in the buffer. There’s a crucial
difference between data items defined in the .data section and data items defined in the .bss section: data
items in the .data section add to the size of your executable file. Data items in the .bss section do not.

The .text Section


The actual machine instructions that make up your program go into the .text section. Ordinarily, no data
items are defined in .text. The .text section contains symbols called labels that identify locations in the
program code for jumps and calls, but beyond your instruction mnemonics, that’s about it. All global labels
must be declared in the .text section, or the labels cannot be ‘‘seen’’ outside your program by the Linux
linker or the Linux loader. Let’s look at the labels issue a little more closely.

Labels
A label is a sort of bookmark, describing a place in the program code and giving it a name that’s easier to
remember than a naked memory address. Labels are used to indicate the places where jump instructions
should jump to, and they give names to callable assembly language procedures.
Here are the most important things to know about labels:
 Labels must begin with a letter, or else with an underscore, period, or question mark. These last
three have special meanings to the assembler, so don’t use them until you know how NASM
interprets them.
 Labels must be followed by a colon when they are defined. This is basically what tells NASM that the
identifier being defined is a label. NASM will punt if no colon is there and will not flag an error, but
the colon nails it, and prevents a mistyped instruction mnemonic from being mistaken for a label.
Use the colon!
 Labels are case sensitive. So yikes:, Yikes:, and YIKES: are three completely different labels.

Assembly Language Statements

Assembly language programs consist of three types of statements:


 Executable instructions or instructions.
 Assembler directives or pseudo-ops
 Macros

Syntax of Assembly Language Statements

[label] mnemonic [operands] [;comment]

Instructions needed:
EQU- Assign single absolute values to symbols.
MOV- Copies byte or word from specified source to specified destination
CALL- The CALL instruction causes the procedure named in the operand to be executed. JNZ-Jumps if not
equal to Zero 16
JNC-Jumps if no carry is generated

ALGORITHM:
1 Start
2. Declare & initialize the variables in .data section.
3. Declare uninitialized variables in .bss section.
4. Declare Macros for print and exit operation.
5. Initialize pointer with source address of array.
6. Initialize count for number of elements.
7. Put the complete summed rbx value to arr[n]
8. Max display of 16 characters and rsi points to _output[16]
9. Dividing by base 16
10. Terminate the process.
11. Declare the Procedure.
12. Stop.

PROGRAM:

section .data
msg1 db 10,13,"Enter 5 64 bit numbers"
len1 equ $-msg1
msg2 db 10,13,"Entered 5 64 bit numbers"
len2 equ $-msg2
section .bss
array resd 200
counter resb 1
section .text
global _start
_start:;
display
mov Rax,1
mov Rdi,1
mov Rsi,msg1
mov Rdx,len1
syscall;
accept
mov byte[counter],05
mov rbx,00
loop1:
mov rax,0 ; 0 for read
mov rdi,0 ; 0 for keyboard
mov rsi, array ;move pointer to start of array
add rsi,rbx
mov rdx,17
syscall
add rbx,17 ;to move counter
dec byte[counter]
JNZ loop1;
display
mov Rax,1
mov Rdi,1
mov Rsi,msg2
mov Rdx,len2
syscall;
display
mov byte[counter],05
mov rbx,00
loop2:
mov rax,1 ;1 for write
mov rdi, 1 ;1 for monitor
mov rsi, array
add rsi,rbx
mov rdx,17 ;
16 bit +1 for enter
syscall
add rbx,17
dec byte[counter]
JNZ loop2;
exit system call
mov rax ,60
mov rdi,0
syscall ;

output:

Enter 5 64 bit numbers


12;
23;
34;
45;
56;

Entered 5 64 bit numbers


12;
23;
34;
45;
56

Conclusion:

Experiment No. 2
Title: Write an X86/64 ALP to accept a string and to display its length .

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:
Experiment No. 2

Aim: Write an X86/64 ALP to accept a string and to display its length.

Objectives:

1. To learn the instructions related to String

2. To be familiar with data segments.

3. To learn the instructions related to String operation


Environment:

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

Software Requirements

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

Theory:

MACRO:

Writing a macro is another way of ensuring modular programming in assembly language.


 A macro is a sequence of instructions, assigned by a name and could be used anywhere in the
program.
 In NASM, macros are defined with %macro and %endmacro directives.
 The macro begins with the %macro directive and ends with the %endmacro directive.
The Syntax for macro definition −
%macro macro_name number_of_params
<macro body>
%endmacro
Where, number_of_params specifies the number parameters, macro_name specifies the name of the macro.
The macro is invoked by using the macro name along with the necessary parameters. When you need to
use some sequence of instructions many times in a program, you can put those instructions in a macro and
use it instead of writing the instructions all the time.
PROCEDURE:

Procedures or subroutines are very important in assembly language, as the assembly language programs
tend to be large in size. Procedures are identified by a name. Following this name, the body of the
procedure is described which performs a well-defined job. End of the procedure is indicated by a return
statement.

Syntax

Following is the syntax to define a procedure −


proc_name:
procedure body
...
ret
The procedure is called from another function by using the CALL instruction. The CALL instruction should
have the name of the called procedure as an argument as shown below −
CALL proc_name
The called procedure returns the control to the calling procedure by using the RET instruction.
Instructions needed:

MOVS: Move String

CMPS: Compare string

SCAS: Scan string

LODS: Load string

STOS: Store string

ESI: Source index register

EDI: Destination index register

REP: Repeat while ECX not xero 20

REPE/REPZ: Repeat while equal or zero

REPNE/REPNZ: Repeat while not equal or not zero

ALGORITHM:
1 Start

2. Declare & initialize the variables in .data section.

3. Declare uninitialized variables in .bss section.

4. Declare Macros for print and exit operation.

5. Initialize pointer to get input string from user.

6. Initialize counter for calculating no. of chatters in string.

7. Display string entered by user.

8. Put value of count in rax register

9. max size of display , for convinience set to 16 and rsipoints to output[16]

10. setting rdx to null without setting a null byte (a tip i saw on reddit) needed to clean dl for use

11. Declare the Procedure for ascii conversion.

12. Stop

PROGRAM:

section .data
msg1 db 10,13,"Enter a string:"
len1 equ $-msg1
section .bss
str1 resb 200 ;
string declaration
result resb 16
section .text
global _start
_start:;
display
mov Rax,1
mov Rdi,1
mov Rsi,msg1
mov Rdx,len1
syscall;
store string
mov rax,0
mov rdi,0
mov rsi,str1
mov rdx,200
syscall
call display;
exit system call
mov Rax ,60
mov Rdi,0
syscall

%macro dispmsg 2
mov Rax,1
mov Rdi,1
mov rsi,%1
mov rdx,%2
syscall
%endmacro

display:
mov rbx,rax ; store no in rbx
mov rdi,result ;point rdi to result variable
mov cx,16 ;load count of rotation in cl
up1:
rol rbx,04; rotate no of left by four bits
mov al,bl ; move lower byte in al
and al,0fh ;get only LSB
cmp al,09h ;compare with 39h
jg add_37 ;if greater than 39h skip add 37
add al,30h
jmp skip ;
else add 30
add_37:
add al,37h
skip:
mov [rdi],al ;store ascii code in result variable
inc rdi ; point to next byte
dec cx ; decrement counter
jnz up1 ; if not zero jump to repeat
dispmsg result,16 ;call to macro
ret

Output:
enter string
Entered
Mumbai
Length is
06
Exiting now

Conclusion:

Experiment No. 3
Title: Write an X86/64 ALP to find the largest of given
Byte/Word/Dword/64-bit numbers.

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:
Experiment No. 3

Aim: Write an X86/64 ALP to find the largest of given Byte/Word/Dword/64-bit numbers.

Objectives:

1. To understanding of basic data structure

2. To compare the different data structure

3. To make usage of different data structure for hexadecimal number

Environment:

1 CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

Software Requirements:

1 CPU: Intel I5 Processor


2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

Theory:

Datatype in 80386:

The 80386 supports the following  data types they are

  Bit
  Bit Field: A group of at the most 32 bits (4bytes)
  Bit String: A string of contiguous bits of maximum 4Gbytes in length.
  Signed Byte: Signed byte data
  Unsigned Byte: Unsigned byte data.
  Integer word: Signed 16-bit data.
  Long Integer: 32-bit signed data represented in 2's complement form.
  Unsigned Integer Word: Unsigned 16-bit data
  Unsigned Long Integer: Unsigned 32-bit data
  Signed Quad Word: A signed 64-bit data or four word data.
  Unsigned Quad Word: An unsigned 64-bit data.
  Offset: 16/32-bit displacement that points a memory location using any of the addressing modes.
  Pointer: This consists of a pair of 16-bit selector and 16/32-bit offset.
  Character: An ASCII equivalent to any of the alphanumeric or control characters.
  Strings: These are the sequences of bytes, words or double words. A string may contain minimum
one byte and maximum 4 Gigabytes.
 BCD: Decimal digits from 0-9 represented by unpacked bytes.
 Packed BCD: This represents two packed BCD digits using a byte, i.e. from 00 to 99.

Regirs in 80386:
 General Purpose Register: EAX, EBX, ECX, EDX
 Pointer register: ESP, EBP
 Index register: ESI, EDI
 Segment Register: CS, FS, DS, GS, ES, SS
 Eflags register: EFLAGS
 System Address/Memory management Registers : GDTR, LDTR, IDTR
 Control Register: Cr0, Cr1, Cr2, Cr3
 Debug Register : DR0, DR,1 DR2, DR3, DR4, DR5, DR6, DR7
 Test Register: TR0, TR,1 TR2, TR3, TR4, TR5, TR6, TR7

EAX AX

AH,AL

EBX BX

BH,BL

ECX CX

CH,CL
EDX DX

DH,DL

EBP BP

EDI DI

ESI SI

ESP

Size of operands in an Intel assembler instruction


 Specifying the size of an operand in Intel
 The size of the operand (byte, word, double word) is conveyed by the operand itself

 EAX means: a 32 bit operand


 AX means: a 16 bit operand
 AL means: a 8 bit operand the size of the source operand and the destination operand must be equal.
Addressing modes in 80386:

The purpose of using addressing modes is as follows:

1. To give the programming versatility to the user.


2. To reduce the number of bits in addressing field of instruction.

1. Register addressing mode: MOV EAX, EDX


2. Immediate Addressing modes: MOV ECX, 20305060H
3. Direct Addressing mode: MOV AX, [1897 H]
4. Register Indirect Addressing mode MOV EBX, [ECX]
5. Based Mode MOV ESI, [EAX+23H]
6. Index Mode SUB COUNT [EDI], EAX
7. Scaled Index Mode MOV [ESI*8], ECX
8. Based Indexed Mode MOV ESI, [ECX][EBX]
9. Based Index Mode with displacement EA=EBX+EBP+1245678H
10. Based Scaled Index Mode with displacement MOV [EBX*8] [ECX+5678H], ECX
11. String Addressing modes:
12. Implied Addressing modes:
Instructions needed:

ROL: Rotate 32 bits r/m dword left CL times

JBE: Jump short if below or equal

INC: Increment dword register by 1 DEC:

Decrement dword register by 1

ALGORITHM:

1 Start

2. Declare & initialize the variables in .data section.

3. Declare uninitialized variables in .bss section.

4. Declare Macros for print and exit operation.

5. Initialize pointer with source address of array.

6. Initialize count to find the data type of number.

7. Displaying array elements

8. Finding Largest Number by comparing rsi, rax

9. Displaying Largest Number

10. Terminate the process.

11. Declare the Procedure for ascii comparison .

12. Stop.
Program:

section .data

array db 11h,59h,33h,22h,44h

msg1 db 10,"ALP to find the largest number in an array",10

msg1_len equ $ - msg1

msg2 db 10,"The Array contains the elements : ",10

msg2_len equ $ - msg2

msg3 db 10,10, "The Largest number in the array is : ",10

msg3_len equ $ - msg3

section .bss

counter resb 1

result resb 4

%macro write 2

mov rax,1

mov rdi,1

mov rsi,%1

mov rdx,%2

syscall

%endmacro

section .text

global _start

_start:

write msg1 , msg1_len

write msg2 , msg2_len


mov byte[counter],05

mov rsi,array

next: mov al,[rsi]

push rsi

call disp

pop rsi

inc rsi

dec byte[counter]

jnz next

write msg3 , msg3_len

mov byte[counter],05

mov rsi, array mov al, 0 ; al is an 8 bit register , al stores max

repeat: cmp al,[rsi] ;cmp opr1 , opr2 : opr1 - opr2

jg skip

mov al,[rsi]

skip: inc rsi

dec byte[counter]

Jnz repeat

call disp

mov rax,60

mov rdi,1

syscall

disp:

mov bl,al ;store number in bl


mov rdi, result ;point rdi to result variable

mov cx,02 ;load count of rotation in cl

up1:

rol bl,04 ;rotate number left by four bits

mov al,bl ;move lower byte in dl

and al,0fh ; get only LSB

cmp al,09h ;compare with 39h

jg add_37 ;if grater than 39h skip add 37

add al,30h

jmp skip1 ;else add 30

add_37: add al,37h

skip1: mov [rdi],al ;store ascii code in result variable

inc rdi ;point to next byte

dec cx ;decrement the count of digits to display

jnz up1 ;if not zero jump to repeat

write result , 4

ret

Output:

ALP to find the largest number in an array

The Array contains the elements :


1159332244

The Largest number in the array is :


59
Conclusion:

Experiment No. 4

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:

Title: Write a switch case driven X86/64 ALP to perform 64-bit hexadecimal
hexadecimal arithmetic operations (+,-,*, /) using suitable macros

.
Experiment No. 4

Aim: Write a switch case driven X86/64 ALP to perform 64-bit hexadecimal arithmetic operations (+,-,*, /)
using suitable macros. Define procedure for each operation.

Objectives:

 To understand assembly language programming instruction set.

 To understand different assembler directives with examples.

 To apply instruction set for implementing X86/64 bit assembly language programs

Environment:

 Operating System: 64-bit Open source Linux or its derivative

 Programming Tools: Preferably using Linux equivalent or MASM /TASM/NASM/FASM

 Text Editor: geditor

Software Requirements :

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)


5. Linker:-LD, GNU Linker

Theory:

Conditional Transfer Instructions The conditional transfer instructions are jumps that may or may not
transfer control, depending on the state of the CPU flags when the instruction executes.

 Conditional Jump Instructions:

The conditional jumps that are listed as pairs are actually the same instruction. The assembler
provides the alternate mnemonics for greater clarity within a program listing. Conditional jump instructions
contain a displacement which is added to the EIP register if the condition is true. The displacement may be a
byte, a word, or a doubleword. The displacement is signed; therefore, it can be used to jump forward or
backward

 Loop Instructions:

The loop instructions are conditional jumps that use a value placed in ECX to specify
the number of repetitions of a software loop. All loop instructions automatically
decrement ECX and terminate the loop when ECX=0. Four of the five loop instructions
specify a condition involving ZF that terminates the loop before ECX reaches zero.
LOOP (Loop While ECX Not Zero) is a conditional transfer tha automatically
decrements the ECX register before testing ECX for the branch condition. If ECX is non- zero,
the program branches to the target label specified in the instruction. The LOOP instruction
causes the repetition of a code section until the operation of the LOOP instruction decrements
ECX to a value of zero. If LOOP finds ECX=0, control transfers to the instruction immediately
following the LOOP instruction. If the value of ECX is initially zero, then the LOOP executes
232 times.

FLOWCHART:
Program:

%macro IO 4
mov rax,%1
mov rdi,%2
mov rsi,%3
mov rdx,%4
syscall
%endmacro
section .data
m1 db "enter choice (+,-,*, /)" ,10 ; 10d -> line feed
l1 equ $-m1
m2 db "Write a switch case driven X86/64 ALP to perform 64-bit hexadecimal arithmetic operations
(+,-,*, /) using suitable macros. Define procedure for each operation." ,10
l2 equ $-m2
m3 db "rahul ghosh 3236" ,10
l3 equ $-m3
madd db "addition here" ,10
l4 equ $-madd
msub db "subtraction here" ,10
l5 equ $-msub
mmul db "multiplication here" ,10
l6 equ $-mmul
mdiv db "division here" ,10
l7 equ $-mdiv
mspace db 10
m_result db "result is "
m_result_l equ $-m_result
m_qou db "qoutient is "
m_qou_l equ $-m_qou
m_rem db "remainder is "
m_rem_l equ $-m_rem
m_default db "enter correct choice",10
m_default_l equ $-m_default
section .bss
choice resb 2
_output resq 1
_n1 resq 1
_n2 resq 1
temp_1 resq 1
temp_2 resq 1
section .text
global _start
_start:
IO 1,1,m2,l2
IO 1,1,m3,l3
IO 1,1,m1,l1
IO 0,0,choice,2
cmp byte [choice],'+'
jne case2
call add_fun
jmp exit
case2:
cmp byte [choice],'-'
jne case3
call sub_fun
jmp exit
case3:
cmp byte [choice],'*'
jne case4
call mul_fun
jmp exit
case4:
cmp byte [choice],'/'
jne case5
call div_fun
jmp exit
case5:
cmp byte [choice],'a'
jne error
call add_fun
call sub_fun
call mul_fun
call div_fun
jmp exit
error:
IO 1,1,m_default,m_default_l
jmp exit
exit:
mov rax, 60
mov rdi, 0
syscall
add_fun:
IO 1,1,madd,l4
mov qword[_output],0
IO 0,0,_n1,17
IO 1,1,_n1,17
call ascii_to_hex
add qword[_output],rbx
IO 0,0,_n1,17
IO 1,1,_n1,17
call ascii_to_hex
add qword[_output],rbx
mov rbx,[_output]
IO 1,1,mspace,1
IO 1,1,m_result,m_result_l
call hex_to_ascii
ret
sub_fun:
IO 1,1,msub,l5
mov qword[_output],0
IO 0,0,_n1,17
IO 1,1,_n1,17
;IO 1,1,mspace,1
call ascii_to_hex
add qword[_output],rbx
IO 0,0,_n1,17
IO 1,1,_n1,17
;IO 1,1,mspace,1
call ascii_to_hex
sub qword[_output],rbx
mov rbx,[_output]
IO 1,1,mspace,1
IO 1,1,m_result,m_result_l
call hex_to_ascii
ret
mul_fun:
IO 1,1,mmul,l6 ; message
IO 0,0,_n1,17 ; n1 input
IO 1,1,_n1,17
call ascii_to_hex; conversion returns hex value in rbx
mov [temp_1],rbx ; storing hex in temp_1
IO 0,0,_n1,17 ;n2 input
IO 1,1,_n1,17
call ascii_to_hex
mov [temp_2],rbx ; putting hex of n2 in temp_2
mov rax,[temp_1] ; temp_1->rax
mov rbx,[temp_2] ;temp_2->rbx
mul rbx ; multiplication
push rax
push rdx
IO 1,1,mspace,1
IO 1,1,m_result,m_result_l
pop rdx
mov rbx,rdx; setting rbx value for conversion
call hex_to_ascii
pop rax
mov rbx,rax; setting rbx value for conversion
call hex_to_ascii ; final output
ret
div_fun:
IO 1,1,mdiv,l7
IO 0,0,_n1,17 ; n1 input
IO 1,1,_n1,17
call ascii_to_hex; conversion returns hex value in rbx
mov [temp_1],rbx ; storing hex in temp_1
IO 0,0,_n1,17 ;n2 input
IO 1,1,_n1,17
call ascii_to_hex
mov [temp_2],rbx ; putting hex of n2 in temp_2
mov rax,[temp_1] ; temp_1->rax
mov rbx,[temp_2] ;temp_2->rbx
xor rdx,rdx
mov rax,[temp_1] ; temp_1->rax
mov rbx,[temp_2] ; temp_2->rbx
div rbx ; div
push rax
push rdx
IO 1,1,mspace,1
IO 1,1,m_rem,m_rem_l
pop rdx
mov rbx,rdx
call hex_to_ascii; remainder output
IO 1,1,mspace,1
IO 1,1,m_qou,m_qou_l
pop rax
mov rbx,rax
call hex_to_ascii; quotient output
ret
ascii_to_hex:
mov rsi, _n1
mov rcx, 16
xor rbx, rbx
next1:
rol rbx, 4
mov al, [rsi]
cmp al,47h
jge error
cmp al, 39h
jbe sub30h
sub al, 7
sub30h:
sub al, 30h
add bl, al
inc rsi
loop next1
ret
hex_to_ascii:
mov rcx, 16
mov rsi,_output
next2:
rol rbx, 4
mov al, bl
and al, 0Fh
cmp al, 9
jbe add30h
add al, 7
add30h:
add al, 30h
mov [rsi], al
inc rsi
loop next2
IO 1,1,_output,16
IO 1,1,mspace,1
ret

Output:

enter choice (+,-,*, /)


addition here
result is FBBBBBBBBBBBBBBA

Conclusion:
Experiment No. 5

Title: Count numbers of positive and negative numbers from the


array.

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:

Experiment No. 5
Aim: Write an X86/64 ALP to count number of positive and negative numbers from the array.

Objectives:

 To understand assembly language programming instruction set.

 To understand different assembler directives with examples.

 To apply instruction set for implementing X86/64 bit assembly language programs

Environment:

 Operating System: 64-bit Open source Linux or its derivative

 Programming Tools: Preferably using Linux equivalent or MASM /TASM/NASM/FASM

 Text Editor: geditor

Software Requirements :

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

Theory:
The following code snippet shows the use of the system call sys_exit:
MOV EAX, 1 ; system call number
(sys_exit) INT 0x80 ; call kernel
The following code snippet shows the use of the system call sys_write:
MOV EAX,4; system call number (sys_write)
MOV EBX,1; file descriptor (stdout)
MOV ECX, MSG ; message to
write MOV EDX, 4; message
length INT0x80; call kernel

Linux System Calls (64 bit) Sys_write:


MOV RAX,1
MOV RDI,1
MOV RSI,message
MOV RDX,message_length
SYSCALL

Sys_read:
MOV
RAX,0
MOV RDI,0
MOV
RSI,array_name
MOV
RDX,array_size
SYSCALL

Sys_exit:
MOV RAX,60
MOV RDI,0
SYSCALL

Assembly Variables
NASM provides various define directives for reserving storage space for variables. The
define Assembler directive is used for allocation of storage space. It can be used to reserve
as well as initialize one or more bytes.
Allocating Storage Space for Initialized Data
There are five basic forms of the define directive:

Allocating Storage Space for Uninitialized Data


The reserve directives are used for reserving space for uninitialized data. The reserve
directives take a single operand that specifies the number of units of space to be reserved.
Each define directive has a related reserve directive.
There are five basic forms of the reserve directive:

Instructions needed:

1. MOV-Copies byteorword from specified sourceto specified destination

2. ROR-Rotates bits ofbyteorwordright,LSBto MSBand to CF

3. AND-AND each bit in abyteorword with correspondingbit in anotherbyteorword

4. INC-Increments specified byte/word by1

5. DEC-Decrements specified byte/word by1

6. JNZ-Jumps ifnot equal to Zero

7. JNC-Jumps ifno carryisgenerated


8. CMP-Compares to specified bytes orwords

9. JBE-Jumps ifbelow ofequal

10. ADD-Adds specified byteto byteorword to word

11. CALL-Transfers the control from callingprogramto procedure.

12. RET-Return from where call is made

MATHEMATICAL MODEL:

Let S = { s , e , X, Y, Fme, mem│Φs } be the programmer’s perspective of Array


Addition Where

S = System
s =Distinct Start of
System e = Distinct End
Of System X = Set of
Inputs
Y= Set Of outputs
Fme = Central Function
Mem= Memory
Required Φs =
Constraits

Let X be the input such


that X= { X1, X2,X3,--}
Such that there exists function fx1 : X1 {0,1}

X2 Source Array
Let X2 = {{b7-----b0}{ b7-------b0}--------{b7 b6 b5 b4 b3 b2 b1 b0}} where  bi Є X1
There exists a function fX2 :X2 { {00h----FFh}{00h----FFh }{00h----FFh}- - -}

X3 is the two digit count value


Let X3 = b7 b6 b5 b4 b3 b2 b1 b0 where  bi Є X1
There exists a function fX3: X3 { 01h,02h,-,- FFh}
Let Y is the Output
Let Y= b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3 b2
b1 b0 Where bi Є X1
Y { 0000h,0001h,----FFFFh}

Let Fme = { F1 ,F2,F3 }


Where F1 = Accept
F2 = Count
F3 = Display

F1 1) Accept the number stored in array.

F2 Y = ∑ ( X2)

F3 Display Output

ALGORITHM:

1 Start
2. Declare & initialize the variables in .data section.
3. Declare uninitialized variables in .bss section.
4. Declare Macros for print and exit operation.
5. Initialize pointer with source address of array.
6. Initialize count for number of elements.
7. Set RBX as Counter register for storing positive numbers count.
8. Set RCX as Counter register for storing negative numbers count.
9. Get the number in RAX register.
10. Rotate the contents of RAX register left 1 bit to check sign bit.
11. Check if MSB is 1. If yes, goto step 12,else goto step 13.
12. Increment count for counting negative numbers.
13. Increment count for counting positive numbers.
14. Increment pointer.
15. Decrement count
16. Check for count = 0. If yes, goto step 17 else goto step 9.
17. Store the positive numbers count and negative numbers count in buffer.
18. Display first message. Call the procedure to display the positive count.
19. Display second message. Call the procedure to display the negative count.
20. Add newline.
21. Terminate the process.
22. Declare the Procedure.
23. Stop.

Flowchart:
Program:

section .data

msg1 db "Count of Positive numbers:"

len1 equ $-msg1


msg2 db "Count of negative numbers:"

len2 equ $-msg2

array db 10,12,-21,-12,-19,-34,41

%macro print 2

mov rax,01

mov rdi,01

mov rsi,%1

mov rdx,%2

syscall

%endmacro

section .bss

count resb 2

pcount resb 2

ncount resb 2

totalcount resb 2

section .text

global _start

_start:

mov byte[count],07

mov byte[pcount],00

mov byte[ncount],00

mov rsi,array

Up:

mov al,00
add al,[rsi]

js neg

inc byte[pcount]

jmp Down

neg:

inc byte[ncount]

Down:

add rsi,01

dec byte[count]

jnz Up

mov bl,[pcount]

mov dl,[ncount]

b1:

print msg1,len1

mov bh,[pcount]

call disp

print msg2,len2

mov bh,[ncount]

call disp

mov rax,60

mov rdi,00

syscall

disp:

mov byte[count],02
loop:

rol bh,04

mov al,bh

AND al,0FH

cmp al,09

jbe l1

add al,07h

l1:add al,30h

mov[totalcount],al

print totalcount,02

dec byte[count]

jnz loop

ret

Output:

Count of Positive numbers:03


Count of negative numbers:04
[Execution complete with exit code 0]

Conclusion:
Experiment No. 6

Title: Hex to BCD & BCD to Hex Conversion

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:
Experiment No. 6
Aim: Write X86/64 ALP to convert 4-digit Hex number into its equivalent BCD number and 5- digit BCD
number into its equivalent HEX number. Make your program user friendly to accept the choice from user
for: (a) HEX to BCD b) BCD to HEX (c) EXIT. Display proper strings to prompt the user while accepting the
input and displaying the result. (Wherever necessary, use 64-bit registers).

Objectives:

 To understand assembly language programming instruction set.

 To understand different assembler directives with examples.

 To apply instruction set for implementing X86/64 bit assembly language programs

Environment:

 Operating System: 64-bit Open source Linux or its derivative

 Programming Tools: Preferably using Linux equivalent or MASM /TASM/NASM/FASM

 Text Editor: geditor

Software Requirements :

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

MATHEMATICAL MODEL:

Let S = { s , e , X, Y, Fme, mem│Φs } be the programmer‟s perspective of Hex to


BCD & BCD to hex conversion
Let X be the input such that X= { X1, X2,X3, }
Such that there exists function fx1 : X1 {0,1}

X2 is the four Digit Hex Number.


Let X2 = b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3 b2 b1 b0 where
 bi Є X1. There exists a function fX2 : X2 { 0000h,0001h,0002h,-,- FFFFh}

X3 is the Five digit BCD number.


Let X3 = b19 b18 b17 b16 b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5b4 b3 b2 b1
b0 where  bi Є X1
There exists a function fX3: X3 { 00000,00001,----99999}

X4 is the Single digit choice.


Let X4 = b3 b2 b1 b0 where  bi Є X1
There exists a function fX4: X4 { 1,2,3}

Let Y1 is the 5 Digit BCD Output


Let Y= b19 b18 b17 b16 b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3
b2 b1 b0 Where  bi Є X1
Y1 { 00000,00001,----99999}

Let Y2 is the 4 Digit Hex Output


Let Y= b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3 b2
b1 b0 Where  bi Є X1
Y1 { 0000h,0001h,----FFFFh}

Fme 1( Hex to bcd ) = { F1 ,F2,F3 }


Where F1 = Accept X2
F2 = Repeat (X2/10) till quotient =0 & push Remainder on
stack F3 = Pop remainder from stack & display

Fme 2(bcd to hex) = { F1 ,F2,F3,F4 }


Where F1 = Accept BCD digit X3i
F2 = Result= Result*10 + X3i & i=i-1 (Initially
Result=0) F3= repeat F1 onwards untill i=0
F4= Display Result

Fme 3(exit)= {F1}


Where F1= Call Sys_exit Call

Fme = { F1,F2,F3,F4}
Where F1= Accept X4
F2= If X4=1, Call Fme1
F3= If X4=2,Call Fme2
F4= If X4=3, Call Fme3

THEORY:
1. Hexadecimal to BCD conversion:

Conversion of a hexadecimal number can be carried out in different ways e.g.


dividing number by 000Ah and displaying quotient in reverse way.

2. BCD to Hexadecimal number:

Conversion of BCD number to Hexadecimal number can be carried out by


multiplying the BCD digit by its position value and the adding it in the final result.

Special instructions used:

DIV: Unsigned Divide. Result  Quotient in AL and Remainder in AH for 8-bit


division and for 16-bit division Quotient in AX and Remainder in DX

MUL: Unsigned Multiply. For 8-bit operand multiplication result will be stored in
AX and for 16-bit multiplication result is stored in DX:AX Commands.
• To assemble

nasm –f elf 64 hello.nasm -o hello.o

• To link
ld –o hello hello.o

• To execute
./hello

ALGORITHM:
1. Start
2. Initialize data section
3 Display the Menu Message.
4 Accept the choice from the user.
5 If choice=1 then call Hex to bcd procedure. If choice=2 then call Bcd to Hex If
Procedure
choice=3 then call exit procedure
6 Hex to BCD Procedure:
a) Accept 4 Digit Hexadecimal Number.
b) Number=Number/10 & Number=Quotient
c) Push the remainder on the stack
d) If Number=0, Go to next step otherwise go to step b
e) Pop remainder , Convert into ascii & display untill all remainder are popped out
7 Bcd to hex Procedure:
a. RESULT=0
b. Accept BCD Digit
c. Check whether all BCD Digits are accepted. If YES then go to
step e otherwise go to next step
d. RESULT= RESULT*10 + BCD Digit accepted e. Display RESULT

FLOW CHART:
Program:

section .data
    menumsg db 10,10,'###### Menu for Code Conversion ######'
    db 10,'1: Hex to BCD'
    db 10,'2: BCD to Hex'

 db 10,'3: Exit'


    db 10,10,'Please Enter Choice::'
    menumsg_len equ $-menumsg
   hexinmsg db 10,10,'Please enter 4 digit hex number::'
    hexinmsg_len equ $-hexinmsg
bcdopmsg db 10,10,'BCD Equivalent::'
    bcdopmsg_len equ $-bcdopmsg
bcdinmsg db 10,10,'Please enter 5 digit BCD number::'
    bcdinmsg_len equ $-bcdinmsg
hexopmsg db 10,10,'Hex Equivalent::'
    hexopmsg_len equ $-hexopmsg;

section .bss
numascii resb 06  ;common buffer for choice, hex and bcd input
    outputbuff resb 02
    dispbuff resb 08
%macro display 2
       mov rax,01
       mov rdi,01
       mov rsi,%1
       mov rdx,%2
       syscall
    %endmacro
%macro accept 2
      mov rax,0
      mov rdi,0
      mov rsi,%1
      mov rdx,%2
      syscall
       %endmacro;

section .text
 global _start
_start:

menu:    display menumsg,menumsg_len


    accept numascii,2
cmp byte [numascii],'1'
    je hex2bcd_proc
cmp byte [numascii],'2'
    je bcd2hex_proc
   cmp byte [numascii],'3'

je exit
    jmp _start

exit:
    mov rax,60
    mov rbx,0
    syscall;

hex2bcd_proc:
    display hexinmsg,hexinmsg_len
    accept numascii,5
    call packnum
    mov ax,bx  
    mov rcx,0
    mov bx,10;Base of Decimal No. system
h2bup1:mov dx,0
    div bx
    push rdx
    inc rcx
    cmp ax,0
    jne h2bup1
    mov rdi,outputbuff

h2bup2: pop rdx
    add dl,30h
    mov [rdi],dl
    inc rdi
    loop h2bup2
   display bcdopmsg,bcdopmsg_len
    display outputbuff,5
    jmp menu;

bcd2hex_proc:
    display bcdinmsg,bcdinmsg_len
    accept numascii,6
 display hexopmsg,hexopmsg_len
 mov rsi,numascii
    mov rcx,05
    mov rax,0
    mov ebx,0ah
b2hup1: mov rdx,0
    mul ebx
    mov dl,[rsi]
    sub dl,30h
    add rax,rdx
    inc rsi
    loop b2hup1
    mov ebx,eax
    call disp32_num
    jmp menu;

packnum:
    mov bx,0
    mov ecx,04
    mov esi,numascii
up1:
    rol bx,04
    mov al,[esi]
    cmp al,39h
    jbe skip1
    sub al,07h
skip1: sub al,30h
    add bl,al
    inc esi
    loop up1
    ret;
disp32_num:
    mov rdi,dispbuff; point esi to buffer
    mov rcx,08; load number of digits to display
dispup1:
    rol ebx,4; rotate number left by four bits
    mov dl,bl; move lower byte in dl
    and dl,0fh; mask upper digit of byte in dl
    add dl,30h; add 30h to calculate ASCII code
    cmp dl,39h; compare with 39h
    jbe dispskip1; if less than 39h akip adding 07 more
    add dl,07h; else add 07
dispskip1:
    mov [rdi],dl; store ASCII code in buffer
    inc rdi; point to next byte
    loop dispup1; decrement the count of digits to display if not zero jump to repeat
display dispbuff+3,5; Dispays only lower 5 digits as upper three are '0'
   ret

Output:

1: Hex to BCD;

2: BCD to Hex;

3: Exit;

Please Enter Choice::1;

Please enter 4 digit hex number::000F;

BCD Equivalent::15;

1: Hex to BCD
2: BCD to Hex
3: Exit;

Please Enter Choice::2;

Please enter 5 digit BCD number::00015;

Hex Equivalent::0000F

Conclusion:
Experiment No. 7
Title: Write X86/64 ALP to switch from real mode to protected mode
and display the values of GDTR, LDTR, IDTR, TR and MSW Registers

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:
Experiment No. 7

Aim: Write X86/64 ALP to switch from real mode to protected mode and display the values of
GDTR, LDTR, IDTR, TR and MSW Registers.

Objectives:

 To understand assembly language programming instruction set.

 To understand different assembler directives with examples.

 To apply instruction set for implementing X86/64 bit assembly language programs

Environment:

 Operating System: 64-bit Open source Linux or its derivative

 Programming Tools: Preferably using Linux equivalent or MASM /TASM/NASM/FASM

 Text Editor: geditor

Software Requirements :

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

THEORY:

Four registers of the 80386 locate the data structures that control
segmented memory management called as memory management registers:
 GDTR :Global Descriptor Table Register
These register point to the segment descriptor tables GDT. Before any segment register
is changed in protected mode, the GDT register must point to a valid GDT. Initialization
of the GDT and GDTR may be done in real-address mode. The GDT (as well as LDTs)
should reside in RAM, because the processor modifies the accessed bit of descriptors.
The instructions LGDT
and SGDT give access to the GDTR.
 LDTR :Local Descriptor Table Register
These register point to the segment descriptor tables LDT. The LLDT instruction loads
a linear base address and limit value from a six-byte data operand in memory into the
LDTR. The SLDT instruction always store into all 48 bits of the six-byte data operand.
 IDTR Interrupt Descriptor Table Register
This register points to a table of entry points for interrupt handlers (the IDT). The
LIDT instruction loads a linear base address and limit value from a six-byte data
operand in memory into the IDTR. The SIDT instruction always store into all 48 bits
of the six-byte data operand.
 TR Task Register
This register points to the information needed by the processor to define the
current task. These registers store the base addresses of the descriptor tables
(A descriptor table is simply a memory array of 8-byte entries that contain
Descriptors and descriptor stores all the information about segment) in the linear
address space and store the segment limits.
SLDT: Store Local Descriptor Table Register
Operation: DEST ← 48-bit BASE/LIMIT register
contents;

Description: SLDT stores the Local Descriptor Table Register (LDTR) in the two-byte
register or memory location indicated by the effective address operand. This register
is a selector that points into the Global Descriptor Table. SLDT is used only in
operating system software. It is not used in application programs.
Flags Affected: None
SGDT: Store Global Descriptor Table Register
Operation: DEST ← 48-bit BASE/LIMIT register
contents;

Description: SGDT copies the contents of the descriptor table register the six bytes of
memory indicated by the operand. The LIMIT field of the register is assigned to the
first word at the effective address. If the operand-size attribute is 32 bits, the next
three bytes are assigned the BASE field of the register, and the fourth byte is written
with zero. The last byte is undefined. Otherwise, if the operand-size attribute is 16
bits, the next 4 bytes are assigned the 32-bit BASE field of the register. SGDT and SIDT
are used only in operating system software; they are not used in application
programs.

Flags Affected: None


SIDT: Store Interrupt Descriptor Table Register
Operation: DEST ← 48-bit BASE/LIMIT register
contents;

Description: SIDT copies the contents of the descriptor table register the six bytes of
memory indicated by the operand. The LIMIT field of the register is assigned to the
first word at the effective address. If the operand-size attribute is 32 bits, the next
three bytes are assigned the BASE field of the register, and the fourth byte is written
with zero. The last byte is undefined. Otherwise, if the operand-size attribute is 16
bits, the next 4 bytes are assigned the 32-bit BASE field of the register. SGDT and SIDT
are used only in operating system software; they are not used in application
programs.

Flags Affected: None


ALGORITHM:

1. Display welcome message on terminal using macro disp.


2. Store most significant bit of CR0 in eax register.
3. Check the PE bit of CR0.
4. If PE=1 then display message “Processor is in Protected mode”.
5. And if PE=0 then display message “Processor is in Real mode”.
6. Then copies/stores the contents of GDT, IDT, LDT using sgdt, sidt, sldt instruction.
7. Display their contents using macro function disp and disp_num.
FLOWCHART:
Program:

section .data
rmodemsg db 10,"Processor is in Real Mode"
rmsg_len equ $-rmodemsg
pmodemsg db 10,"Processor is in Protected Mode"
pmsg_len equ $-pmodemsg
gdtmsg db 10,"GDT Contents are::"
gdtmsg_len equ $-gdtmsg
ldtmsg db 10,"LDT Contents are::"
ldtmsg_len equ $-ldtmsg
idtmsg db 10,"IDT Contents are::"
idtmsg_len equ $-idtmsg
trmsg db 10,"Task Register Contents are::"
trmsg_len equ $-trmsg
mswmsg db 10,"Machine Status Word::"
mswmsg_len equ $-mswmsg
colmsg db ":"
nwline db 10;
section .bss
gdt resd 1
resw 1
ldt resw 1
idt resd 1
resw 1
tr  resw 1
cr0_data resd 1
dispbuff resb 04
%macro display 2
    mov    rax,1    ;print
    mov    rdi,1    ;stdout/screen
    mov    rsi,%1    ;msg
    mov    rdx,%2    ;msg_len
    syscall
%endmacro;
section .text
global _start
_start:
  smsw eax    ;Stores the machine status word (bits 0 ;through   15 of control register CR0) into eax.
mov [cr0_data],eax
bt eax,0    ;Checking PE(Protected Mode Enable) bit(LSB), ;

if 1=Protected Mode, else Real Mode


jc prmode
display rmodemsg,rmsg_len
 jmp nxt1
prmode: display pmodemsg,pmsg_len
nxt1:sgdt [gdt]    
sldt [ldt]         
 sidt [idt]  
str [tr]   ;.......display gdt data...........
display gdtmsg,gdtmsg_len
mov bx,[gdt+4]
call display16_proc
mov bx,[gdt+2]
 call display16_proc
display colmsg,1
mov bx,[gdt]
call display16_proc ;......display ldt data...........
display ldtmsg,ldtmsg_len
 mov bx,[ldt]
 call display16_proc;......display idt data...........
display idtmsg,idtmsg_len
 mov bx,[idt+4]
 call display16_proc
mov bx,[idt+2]
 call display16_proc
display colmsg,1
mov bx,[idt]
  call display16_proc  ;....display task register data..........
display trmsg,trmsg_len
mov bx,[tr]
  call display16_proc;....display machine status word data......
display mswmsg,mswmsg_len
mov bx,[cr0_data+2]
    call display16_proc
 mov bx,[cr0_data]
    call display16_proc
display nwline,1
mov rax,60
 mov rdi,0
 syscall;

display16_proc:

 mov rdi,dispbuff    ;point esi to buffer


 mov rcx,4        ;load number of digits to display
dispup1:
 rol bx,4        ;rotate number left by four bits
 mov dl,bl        ;move lower byte in dl
  and dl,0fh        ;mask upper digit of byte in dl
  add dl,30h        ;add 30h to calculate ASCII code
  cmp dl,39h        ;compare with 39h
   jbe dispskip1        ;if less than 39h akip adding 07 more
   add dl,07h        ;else add 07

dispskip1:
    mov [rdi],dl    ;store ASCII code in buffer
    inc rdi   ;point to next byte
    loop dispup1   ;decrement the count of digits to display
display dispbuff,4    ;
   ret

Output:

Processor is in Protected Mode;

GDT Contents are::B7304000:007F;

LDT Contents are::0000;

IDT Contents are::81BDD000:0FFF;

Task Register Contents are::0040;

Machine Status Word::8005FFFF;

Conclusion:
Experiment No. 8 & 9
Title: Non-overlapped and overlapped block transfer.
Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:

Experiment No. 8 & 9


Aim: Write X86/64 ALP to perform non-overlapped block transfer with and without string specific
instructions. Block containing data can be defined in the data segment.

Objectives:

 To understand assembly language programming instruction set.

 To understand different assembler directives with examples.

 To apply instruction set for implementing X86/64 bit assembly language programs

Environment:

 Operating System: 64-bit Open source Linux or its derivative

 Programming Tools: Preferably using Linux equivalent or MASM /TASM/NASM/FASM

 Text Editor: geditor

Software Requirements :

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

AD
Theory:
9D
Non-overlapped blocks: 78
In memory, two blocks are known as non-overlapped when none of the element is common.
09
FF
28
F4
3F Memory Block 2
FD
BB
AA
0D
Memory Block 1

In above example of non-overlapped blocks there is no common element between block 1


& 2.
While performing block transfer in case of non-overlapped blocks, we can start transfer
from starting element of source block to the starting element of destination block and then we
can transfer remaining elements one by one.
Overlaped Block:
In memory, two blocks are known as overlapped when at least one element is common
between two blocks.
While performing block transfer we have to see which element/s of source block is/are overlapped. If
ending elements are overlapped then start transferring elements from last and if starting elements
are overlapped then start transfer from first element
AD
9D
78
09
FF
28
F4
3F
Memory Block 2
FD
BB
AA
0D
Common Element

Memory Block 1

Instructions needed:

1. MOVSB-Move string bytes.

2. JNE-Jump if not equal

3. AND-AND each bit in a byte or word with corresponding bit in another byte or word

4. INC-Increments specified byte/word by 1

5. DEC-Decrements specified byte/word by 1

6. JNZ-Jumps if not equal to Zero

7. CMP-Compares to specified bytes or words


8. JBE-Jumps if below of equal

9. CALL-Transfers the control from calling program to procedure.


10. RET-Return from where call is made

ALGORITHM:

1) Non –Overlapped Block Transfer:


In non-overlapped block transfer Source Block & destination blocks are different. Here
we can transfer byte by byte data or word by word data from one block to another block.

i) Start
ii) Initialize data section
iii) Initialize RSI to point to source block
iv) Initialize RDI to point to destination block
v) Initialize the counter equal to length of block
vi) Get byte from source block & copy it into destination block
vii) Increment source & destination pointer
viii) Decrement counter
ix) If counter is not zero go to step vi
x) Display Destination Block
xi) Stop

2) Overlapped Block Transfer.


In Overlapped block transfer there is only one block & within the
same block We are transferring the data.

i) Start
ii) Initialize data section
iii) Accept the overlapping position from the user
iv) Initialize RSI to point to the end of source block
v) Add RSI with overlapping Position & use it as pointer to point
to End of Destination Block.
vi) Initialize the counter equal to length of block
vii) Get byte from source block & copy it into destination block
viii) Decrement source & destination pointer
ix) Decrement counter
x) If counter is not zero go to step vii
xi) Display Destination Block
xii) Stop

Mathematical Model:

Let S = { s , e , X, Y, Fme, mem│Φs } be the programmer’s perspective of Non-over


Lapped & overlapped Block Transfer.

1) Non-Overlapped Block Transfer.


Let X be the input such
that X= { X1, X2,X3,--}
Such that there exists function fx1 : X1 {0,1}
X2 Source Array
Let X2 = {{b7-----b0}{ b7-------b0}--------{b7 b6 b5 b4 b3 b2 b1 b0}} where  bi Є X1
There exists a function fX2 : X2 { {00h----FFh}{00h----FFh }{00h----FFh}- - -}

X3 is destination array before transfer


Let X3={{b7-----b0}{ b7-------b0}--------{b7 b6 b5 b4 b3 b2 b1 b0}} where  bi Є X1
There exists a function fX3 : X3 {{00h----FFh}{00h----FFh }{00h----FFh}-- -}

X4 is the two digit count value equal to length of


block Let X4 = b7 b6 b5 b4 b3 b2 b1 b0 where  bi
Є X1 There exists a function fX4: X4 { 01h,02,-,-
,- FFh}

X5 is the Single digit choice.


Let X5 = b3 b2 b1 b0 where  bi Є X1
There exists a function fX5: X5 { 1,2,3}

Let Y is the Destination Block after transfer


Let Y= ={{b7-----b0}{ b7-------b0}--------{b7 b6 b5 b4 b3 b2 b1 b0}} where  bi Є X1
Where  bi Є X1
Y { {00h----FFh}{00h----FFh }{00h----FFh}-- -}

Fme = { F1 ,F2,F3 ,F4}


Where F1 = Display X2 & X3 (Source block & Destination block before
Transfer) F2 = Copy Byte from X2 (source block) to Y( destination
block)
F3 = Increment Source & destination pointer, X4=X4-1, If not zero
repeat F2 & F3
F4= Display
2) Overlapped Block Transfer.
Let X be the input such
that X= { X1, X2,X3, }
Such that there exists function fx1 : X1 {0,1}
X2 Source Array
Let X2 = {{b7-----b0}{ b7-------b0}--------{b7b6 b5 b4 b3 b2 b1 b0}{00H}{00H}{00H}
{00H}{00H}} where  bi Є X1
There exists a function fX2 : X2 { {00h----FFh}{00h----FFh }{00h----FFh}------
{00h}{00h}{00h}{00h}{00h}}

X3 is the two digit count value equal to length of


block Let X3 = b7 b6 b5 b4 b3 b2 b1 b0 where  bi Є
X1 There exists a function fX3: X3 { 01h,02,-,- ,-
FFh}

X4 is the Single digit choice.


Let X4 = b3 b2 b1 b0 where  bi Є X1
There exists a function fX4: X4 {
1,2,3}

X5 is the position of overlapping


Let X4 = b7 b6 b5 b4 b3 b2 b1 b0 where  bi Є X1
There exists a function fX5: X5 {
01h,02h,03h,04h,05h}

Let Y is the Destination Block after transfer


Let Y= ={{b7-----b0}{ b7-------b0}--------{b7 b6 b5 b4 b3 b2 b1 b0}} where  bi Є X1
Where  bi Є X1
Y { {00h----FFh}{00h----FFh }{00h----FFh}- -}

Fme = { F1 ,F2,F3 ,F4,F5,F6}


Where F1 = Accept X5
F2 = Point to end of source block X2
F3 = pointer to Y= (pointer to
X2)+X5
F4 = Copy Byte from X2 (source block) to Y( destination block)
F5 = Decrement Source & destination pointer, X3=X3-1, If not zero repeat
F4&F5 F6 = Display Y
Commands

• To assemble
nasm –f elf 64 hello.nasm -o hello.o

• To link
ld –o hello hello.o

• To execute -
./hello

Program:

section .data

menumsg db 10,'##Menu for Non-overlapped Block Transfer##',10

db 10,'1.Block Transfer without using string instructions'

db 10,'2.Block Transfer with using string instructions'

db 10,'3.Exit',10

menumsg_len equ $-menumsg

blk_bfrmsg db 10,'Block contents before transfer'

blk_bfrmsg_len equ $-blk_bfrmsg

blk_afrmsg db 10,'Block contents after transfer'

blk_afrmsg_len equ $-blk_afrmsg

srcmsg db 10,'Source block contents::'

srcmsg_len equ $-srcmsg

dstmsg db 10,'Destination block contents::'

dstmsg_len equ $-dstmsg

srcblk db 01h,02h,03h,04h,05h

dstblk db 00,00,00,00,00
spacechar db 20h

spchlength equ $-spacechar

section .bss

optionbuff resb 02

dispbuff resb 02

%macro display 2

mov rax,01

mov rdi,01

mov rsi,%1

mov rdx,%2

syscall

%endmacro

%macro accept 2

mov rax,00

mov rdi,00

mov rsi,%1

mov rdx,%2

syscall

%endmacro

section .text

global _start

_start:

display blk_bfrmsg,blk_bfrmsg_len

call dispsrc_blk_proc

call dispdest_blk_proc
menu: display menumsg,menumsg_len

accept optionbuff,02

cmp byte [optionbuff],31h

je wos

cmp byte [optionbuff],32h

je ws

exit: mov rax,60 ; Exit

mov rbx,00

syscall;

dispsrc_blk_proc:

display srcmsg,srcmsg_len

mov rsi,srcblk

mov rcx,05h

up1:push rcx

mov bl,[rsi]

push rsi

call disp8_proc

display spacechar,spchlength

pop rsi

inc rsi

pop rcx

loop up1

ret;

dispdest_blk_proc:

display dstmsg,dstmsg_len
mov rdi,dstblk

mov rcx,05

up2:push rcx

mov bl,[rdi]

push rdi

call disp8_proc

display spacechar,spchlength

pop rdi

inc rdi

pop rcx

loop up2

ret;

wos:

mov rsi,srcblk

mov rdi,dstblk

mov rcx,05

again: mov bl,[rsi]

mov [rdi],bl

inc rsi

inc rdi

loop again

display blk_afrmsg,blk_afrmsg_len

call dispsrc_blk_proc

call dispdest_blk_proc

jmp menu;
ws:

mov rsi,srcblk

mov rdi,dstblk

mov rcx,05

cld

rep movsb

display blk_afrmsg,blk_afrmsg_len

call dispsrc_blk_proc

call dispdest_blk_proc

jmp menu;

disp8_proc:

mov rsi,dispbuff

mov rcx,02

dup1:

rol bl,4

mov dl,bl

and dl,0Fh

cmp dl,09H

jbe dskip

add dl,07h

dskip:add dl,30h

mov [rsi],dl

inc rsi

loop dup1

display dispbuff,02
ret

Output:

**Block contents before transfer:


*_*Source block contents 01 02 03 04 05
*_*Destination block contents 00 00 00 00 00

***Nonoverlap block transfer***


1.Block transfer without string
2.Block transfer with string
3.exit 1

**Block contents after transfer:


*_*Source block contents 01 02 03 04 05
*_*Destination block contents 01 02 03 04 05

[root@comppl208 nasm-2.10.07]# ./nonoverlap26

**Block contents before transfer:


*_* Source block contents 01 02 03 04 05
*_*Destination block contents 00 00 00 00 00

***Nonoverlap block transfer***


1.Block transfer without string
2.Block transfer with string
3.exit 2
*_*Source block contents 01 02 03 04 05
*_*Destination block contents 01 02 03 04 05
**Block contents after transfer:
*_*Source block contents 01 02 03 04 05
*_*Destination block contents 01 02 03 04 05

[root@comppl208 nasm-2.10.07]# ./nonoverlap26

**Block contents before transfer:


*_*Source block contents 01 02 03 04 05
*_*Destination block contents 00 00 00 00 00

***Nonoverlap block transfer***

1.Block transfer without string


2.Block transfer with string
3.exit 3
[root@comppl208 nasm-2.10.07]#

Conclusion:
Experiment No. 10

Title: Multiplication of two 8 bit nos. using Successive addition


and Shift and add method

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:
Experiment No. 10
Aim: Write X86/64 ALP to perform multiplication of two 8-bit hexadecimal numbers. Use
successive addition and add and shift method. (use of 64-bit registers is expected).

Objectives:

 To understand assembly language programming instruction set.

 To understand different assembler directives with examples.

 To apply instruction set for implementing X86/64 bit assembly language programs

Environment:

 Operating System: 64-bit Open source Linux or its derivative

 Programming Tools: Preferably using Linux equivalent or MASM /TASM/NASM/FASM

 Text Editor: geditor

Software Requirements :

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

Theory:

There are 5 basic form of define reverse directives.


Directives Purpose

DD Define byte
DW Define word
DD Define doubleword
DQ Define quad word
DT Define Ten byte
RESB Reserve byte
RESW Reserve word
RESQ Reserve quad word
REST Reserve ten word

Instructions Needed:
MOV : Move or copy
word ROR : Rotate to
right AND : Logical
AND
INC :
Increment DEC
:
Decrement
JNZ : Jump if not
zero CMP : Compare
JNC : Jump if no
carry JBE : Jump if
below

Shift & Add method:

The method taught in school for multiplying decimal no. is based on calculated partial
products, shifting it to the left & then adding them together. Shift & add multilplication
is similar to the multiplication performed by paper & pencil. This method adds the
multiplicand X to itself Y times where Y denotes the multiplier. To multiply two nos. by
paper & pencil placing the intermediate product in the appropriate positions to the left
of earlier product.

1. Consider 1 byte is in AL & another in BL


2. We have to multiply byte in AL with byte in BL
3. In this method, you add 1 with itself & rotate other no. each times &shift it by 1
bit n left along with carry
4. If carry is present add 2 NOS.
5. Initialize count to n as we are scanning for n digit decrement counter each time,
the bits are added

The result is stored in AX, display the

result. Eg., AH=11H, BL=10H, Count=n

Step 1:

AX=11 + 11 = 22H

Rotate BL by 1 bit to left along with carry 0001 0000

B1=10H 0010 0000 (20)

Step 2:

Decrement count =3
Check for carry, carry is not there So Add with itself

AX=22+22=44H
Rotate BL to left
BL=0 0000 0000 (00)

Step 3:

Decrement count=2

Add no. with itself

AX=44+44=88H

Rotate BL to left

B2=0 (carry) 1000 0000 (80)

Step 4:

Decrement count=0

Add no. with itself,

AX=88+88=110H

Rotate BL to left

BL=0 (carry) 1000 0000 (80)

Step 5:

Decrement count =0, carry is generated

Add Ax, BX

0110+0000=0110H

i.e., 11H+10H=0110H
MATHEMATICAL MODEL:

Let S={s, e, x, y, time, mem ᶲs} be program perspective of multiplication of two 8


bit hexadecimal Nos.

Let X be the input such

that X={x1, x2, x3,..............}

Such that there exists function fx1: x{0,

1} X2={s the two digit multiplicate }

Let x2= b7 b6 b5 b4 b3 b2 b1 b0

Where xb1 € x1 Here exists a function fx2:x2 {00h, 01h, 02h,.....ffh}

X3 is the single digit choice

Let x4 = b3 b2 b1 b0 where (bi x € x1 there Let y is the output)

Y= b15 b14 b13 b12 bb11 b10 b09 b08 b07 b06 b05 b04 b03 b02 b01 b00

(where bi€ x1) Y= {0000b,0001b. .ffffb}

Time ( for successive addition) =

{f1,f2,f3,f4} Where f1 = Accept x2 & x3

F2= Addition (Repeat x2+x1+.............................................& till x3=00)

F3= display

Time (for shift and add)=

{f1,f2,f3} Where

F1= Accept x1&x3


Program:

section .data
welmsg db 10,'Multiplication using successive addition',10
welmsg_len equ $-welmsg
nummsg db 10,'Enter two digits of Number::'
nummsg_len equ $-nummsg
resmsg db 10,'Multiplication of elements::'
resmsg_len equ $-resmsg
blankmsg db 10,'',10
blank_len equ $-blankmsg;

**********.bss Section**********************

section .bss
    numascii resb 03
    num1 resb 02
    num2 resb 02
    result resb 01
    dispbuff resb 04

%macro display 2
    mov rax,01
    mov rdi,01
    mov rsi,%1
    mov rdx,%2
    syscall
%endmacro

%macro accept 2
    mov rax,00
    mov rdi,00
    mov rsi,%1
    mov rdx,%2
    syscall
%endmacro;

**********.text Section**********************
section .text
global _start
_start:

    display welmsg,welmsg_len


display nummsg,nummsg_len
    accept numascii,3
    call packnum
    mov byte[num1],bl

    display nummsg,nummsg_len


    accept numascii,3
    call packnum
    mov byte[num2],bl
    mov cx,[num2]
     mov edx,00h            ;Temporary Addition
    mov eax,[num1]
    addup:    add edx,eax
    loop addup
   mov [result],edx
display resmsg,resmsg_len
    mov ebx,[result]
call disp16_proc
display blankmsg,blank_len
exit:    mov rax,60
    mov rbx,00
    syscall ;

**********Packnum Procedure**********************
packnum:
    mov bl,0
    mov ecx,02
    mov esi,numascii
    up1:rol bl,04
    mov al,[esi]
    cmp al,39h
    jbe skip1
    sub al,07h
 skip1: sub al,30h
    add bl,al
    inc esi
    loop up1
    ret;

**********Display Procedure**********************
disp16_proc:
    mov ecx,4
    mov edi,dispbuff
 dup1:  rol bx,4
    mov al,bl
    and al,0fh
    cmp al,09
    jbe dskip
    add al,07h
 dskip: add al,30h
        mov [edi],al
        inc edi
        loop dup1
        display dispbuff,4
        ret

Output

;[root@localhost MIT2016]# nasm -f elf64 Ass3A.asm


;[root@localhost MIT2016]# ld -o Ass3A Ass3A.o
;[root@localhost MIT2016]# ./Ass3A

;Multiplication using successive addition

;Enter two digits of Number::04

;Enter two digits of Number::05

;Multiplication of elements::0014

;[root@localhost MIT2016]#

Conclusion:
Experiment No. 11

Title: ALP to implement DOS commands TYPE,COPY, & DELETE


using File Operations.
Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:
Experiment No. 11

Aim: Write X86 Assembly Language Program (ALP) to implement following OS commands
i) COPY, ii) TYPE
Using file operations. User is supposed to provide command line arguments.

Objectives:

 To understand assembly language programming instruction set.

 To understand different assembler directives with examples.

 To apply instruction set for implementing X86/64 bit assembly language programs

Environment:

 Operating System: 64-bit Open source Linux or its derivative

 Programming Tools: Preferably using Linux equivalent or MASM /TASM/NASM/FASM

 Text Editor: geditor

Software Requirements :

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

Theory:

PSP-:

Whenever DOS loads a program for execution it creates a 256 byte data
structure called PSP.
It is available at 1st paragraph of true memory program itself is located and
load above psp.

There are two types of disk access method.


1. ASCII method
2. Handles.

Handles-
Use of file handles to file operation the file management function access the file
in fashion similar To that used under UNIX.

ASCII Function calls -:


1. 3H- Creates a file DS:DX.

2. 30H- Open a file.

3. 3EH- Close file.

4. 40H- Write into file.

5. 41H- Delete a file.

6. 17H- Rename a file.

7. 4EH- To check if file exists.

File Control Block (FCB)-

As FCB is a 37 file data structure allocated with the application program memory.

Common FCB Record Operation-:

0FH: Open a File.


10H: Close file.

16H: Create a file.

14H: perform segment Read.

15H: perform segment write.

22H: perform random.

ALGORITHM FOR TYPE:

1. Start
2. Get source file name and destination file name from command tail.
3. If file is not present display error message as “File not found” and stop.
4. If present, open the file in read mode.
5. Read the contents of file and print the data on the screen
6. Stop

ALGORITHM FOR COPY:

1. Start.
2. Get source file name and destination file name from command tail.
3. If file is not present display error message as “File not found” and stop.
4. If present, open the file in read mode.
5. Read name of destination file and open it in read mode.
6. Read the contents of file source and write it into destination file.
7. Stop.

Program:

%macro print 2
mov rax,1
mov rdi,1
mov rsi,%1
mov rdx,%2
syscall
%endmacro

%macro accept 2
mov rax,0
mov rdi,0
mov rsi,%1
mov rdx,%2
syscall

%endmacro

%macro iomodule 4
mov rax,%1
mov rdi,%2
mov rsi,%3
mov rdx,%4
syscall
%endmacro

%macro exit 0
mov rax,60
syscall
%endmacro

section .data
    cmd db 10,13, “command menu”
        db 10,13,”1.TYPE”
        db 10,13,”2.COPY”
        db 10,13,”3.DELETE”
        db 10,13,”4.EXIT”
        db 10,13,”Enter choice:”      
    len equ $ – cmd
    entercmd db 10,13,”Enter command:——: “
    cmdlen equ $ – entercmd
    msg0 db 10,13,”Failed to open the file!!!”
    len0 equ $ – msg0
    msg1 db 10,13,”File opened successfully!!!”
    len1 equ $ – msg1
    msg2 db 10,13,”Failed to open the file!!!”
    len2 equ $ – msg2
    msg3 db 10,13, “Command not found!!!!”
    len3 equ $ – msg3

section .bss
    buffer resb 200
    bufferlen resb 8
    choice resb 50
    chlen equ $ – choice
    fdis1 resb 200
    fdis2 resb 200
    cnt1 resb 2
    ch1 resb 2
    name1 resb 20
    name2 resb 20
    size resb 200
section .text
global _start
_start:
    print cmd, len
    accept ch1, 2
    mov rsi, ch1
    cmp byte[rsi], ‘1’
    je TYPE
    cmp byte[rsi], ‘2’
    je COPY
    cmp byte[rsi], ‘3’

exit
    jmp error

TYPE:
    print entercmd, cmdlen
    accept choice, chlen
    mov rsi, choice
    mov byte[size], al
    dec byte[size]
    mov al, byte[rsi]
nd:

    cmp al, ‘t’


    jne error
    inc rsi
    dec byte[size]
    mov al, byte[rsi]
    cmp al, ‘y’
    jne error
    inc rsi
    dec byte[size]
    mov al, byte[rsi]
    cmp al, ‘p’
    jne error
    inc rsi
    dec byte[size]
    mov al, byte[rsi]
    cmp al, ‘e’
    jne error
    inc rsi
    dec byte[size]

    jmp success
error:
    print msg3, len3
    jmp _start
success:
    inc rsi
    dec byte[size]
    mov rdi, name1
top:
    mov al, byte[rsi]
    mov [rdi], al
    inc rdi
    inc rsi
    dec byte[size]
    jnz top

    iomodule 2, name1, 2, 777


    mov qword[fdis1], rax
    bt rax, 63
    jc error

    iomodule 0, [fdis1], buffer, 200


    mov qword[cnt1], rax

    iomodule 1, 1, buffer, qword[cnt1]

    mov rax, 3
    mov rdi, name1
    syscall
    jmp _start
COPY:
    print entercmd, cmdlen
    accept choice, chlen
    mov byte[size], al
    dec byte[size]
    mov al, byte[rsi]
nd2:
    cmp al, ‘c’
    jne error
    inc rsi
    dec byte[size]
    mov al, byte[rsi]
    cmp al, ‘o’
    jne error
    inc rsi
    dec byte[size]
    mov al, byte[rsi]
    cmp al, ‘p’
    jne error
    inc rsi
    dec byte[size]
    mov al, byte[rsi]
    cmp al, ‘y’
    jne error
    inc rsi
    dec byte[size]

    jmp success2
success2:
        inc rsi
    dec byte[size]
    mov rdi, name1
    mov rcx, 9
nsp:
    mov al, [rsi]
    mov [rdi], al
    inc edi
    inc rsi
    dec byte[size]
    loop nsp

    inc rsi
    dec byte[size]
     xor rdi, rdi
    mov rdi, name2
nnl:
    mov al, [rsi]
    mov [rdi], al
    inc rdi
    inc rsi
    dec byte[size]
    jnz nnl

    iomodule 2, name1, 2, 777


    mov qword[fdis1], rax

    iomodule 0, [fdis1], buffer, 200


    mov qword[cnt1], rax
    iomodule 2, name2, 2, 777
    mov qword[fdis2], rax

    iomodule 1, [fdis2], buffer, qword[cnt1]

    mov rax, 3
    mov rdi, name1
    syscall
    mov rax, 3
    mov rdi, name2
    syscall

jmp _start
    exit

Output:
swlab@swlab-H81-M1:~$ cd Desktop/
swlab@swlab-H81-M1:~/Desktop$ cd cmd/
swlab@swlab-H81-M1:~/Desktop/cmd$ nasm -f elf64 cmd.asm
swlab@swlab-H81-M1:~/Desktop/cmd$ ld -o cmd cmd.o
swlab@swlab-H81-M1:~/Desktop/cmd$ ./cmd
command menu
1.TYPE
2.COPY

Enter command:——

command menu
1.TYPE
2.COPY

1Enter command:——: command menu


1.TYPE
2.COPY

Conclusion:
Experiment No. 12

Title: Find factorial of a given integer number on a command line by


using recursion

Date of Performance: Roll No:

Date of Submission: University Seat No:

Signature of Staff:
Experiment No. 12

Title: Write x86 ALP to find the factorial of a given integer number on a command line by using recursion.
Explicit stack manipulation is expected in the code.

Objectives:

 To understand assembly language programming instruction set.

 To understand different assembler directives with examples.

 To apply instruction set for implementing X86/64 bit assembly language programs

Environment:

 Operating System: 64-bit Open source Linux or its derivative

 Programming Tools: Preferably using Linux equivalent or MASM /TASM/NASM/FASM

 Text Editor: geditor

Software Requirements :

1. CPU: Intel I5 Processor

2. OS:- Windows XP (16 bit Execution ), Fedora 18 (32 & 64 bit Execution)

3. Editor: gedit, GNU Editor

4. Assembler: NASM (Netwide Assembler)

5. Linker:-LD, GNU Linker

Theory:
A recursive procedure is one that calls itself. There are two kind of recursion: direct
and indirect. In direct recursion, the procedure calls itself and in indirect recursion,
the first procedure calls a second procedure, which in turn calls the first procedure.
Recursion could be observed in numerous mathematical algorithms. For example,
consider the case of calculating the factorial of a number. Factorial of a number is

Fact (n) = n * fact (n-1) for n > 0


given by the equation −

For example: factorial of 5 is 1 x 2 x 3 x 4 x 5 = 5 x factorial of 4 and this can be a good


example of showing a recursive procedure. Every recursive algorithm must have an
ending condition, i.e., the recursive calling of the program should be stopped when a
condition is fulfilled. In the case of factorial algorithm, the end condition is reached
when n is 0.

Instructions needed:

1. AND-AND each bit in a byte or word with corresponding bit in another byte or word

2. INC-Increments specified byte/word by1

3. DEC-Decrements specified byte/word by1

4. JG - The command JG simply means: Jump if Greater.

5. CMP-Compares to specified bytes or words

6. MUL - The MUL (Multiply) instruction handles unsigned data

7. CALL-Transfers the control from callingprogramto procedure.

8. ADD- ADD instructions are used for performing simple addition of binary data
in byte, word and doubleword size, i.e., for adding 8-bit, 16-bit or 32-bit
operands, respectively.

9. RET-Return from where call is made

ALGORITHM:

This algorithm use recursive approach to find factorial of N.


1. Start
2. Read: Take input N
3. Retrieve parameter and put it into Register-PUSH
4. Check for base case if n==0
5. move the first argument to %eax
6. If the number is 1, that is our base case, and we simply return.
7. multiply by the result of the last call to factorial.
8. Restore %ebp and %esp to where they were before the function started.
9. return to the function

MATHEMATICAL MODEL:

Let S = { s , e , X, Y, │Φs }
The factorial function is formally defined by the product

This notation works in a similar way to summation notation (Σ), but in this case we
multiply rather than add terms. For example, if n = 4, we would substitute k = 1, then k
= 2, then k = 3 and finally k = 4 and write:

n math, we often come across the following

expression: n!

This is "n factorial", or the product

n(n − 1)(n − 2)(n − 3) ... (3)(2)(1).

Commands

• To assemble
nasm –f elf 64hello.nasm -o hello.o

• To link
ld –o hello hello.o
• To execute -
./hello
JSPM’s
Imperial College of Engineering and Research, Wagholi,
Pune.
(Approved by AICTE, Delhi & Govt. of Maharashtra, affiliated to Savitribai Phule Pune University)
Gat.No.720,Pune-Nagar road,Wagholi,Pune,412207
Department of Computer Engineering
_______________________________________________________________________________________________________

Program:

%macro scall 4   ;common macro for input/output


 mov rax,%1
 mov rdi,%2
 mov rsi,%3
 mov rdx,%4
 syscall
%endmacro

section .data
 num db 00h
 msg db “Factorial is : “
 msglen equ $-msg
 msg1 db “*****Program to find Factorial of a number***** “,0Ah
   db “Enter the number : “,
 msg1len equ $-msg1

 zerofact db ” 00000001 “
 zerofactlen equ $-zerofact

section .bss
 dispnum resb 16
 result resb 4
 temp resb 3

section .text
global _start
_start:

 scall 1,1,msg1,msg1len
 scall 0,0,temp,3   ;accept number from user
 call convert       ;convert number from ascii to hex
 mov [num],dl

 scall 1,1,msg,msglen
JSPM’s
Imperial College of Engineering and Research, Wagholi,
Pune.
(Approved by AICTE, Delhi & Govt. of Maharashtra, affiliated to Savitribai Phule Pune University)
Gat.No.720,Pune-Nagar road,Wagholi,Pune,412207
Department of Computer Engineering
_______________________________________________________________________________________________________
 mov rdx,0        ;RMD
 mov rax,0        ;RMD
 mov al,[num]   ;store number in accumulator
 cmp al,01h 
 jbe endfact
 mov rbx,0        ;RMD
 mov bl,01h
 call factr    ;call factorial procedure
 call display

 call exit
endfact:
 scall 1,1,zerofact,zerofactlen
 call exit

 factr:    ;recursive procedure

   cmp rax,01h
   je retcon1
   push rax 
   dec rax

   call factr

  retcon:
   pop rbx
   mul ebx
   jmp endpr

  retcon1:   ;if rax=1 return


   pop rbx
   jmp retcon
  endpr:

 ret

 display:   ; procedure to convert hex to ascii


JSPM’s
Imperial College of Engineering and Research, Wagholi,
Pune.
(Approved by AICTE, Delhi & Govt. of Maharashtra, affiliated to Savitribai Phule Pune University)
Gat.No.720,Pune-Nagar road,Wagholi,Pune,412207
Department of Computer Engineering
_______________________________________________________________________________________________________
   mov rsi,dispnum+15
   mov rcx,0        ;RMD
   mov cl,16

  cont:
   mov rdx,0        ;RMD
   mov rbx,0        ;RMD
   mov bl,10h
   div ebx
   cmp dl,09h
   jbe skip
   add dl,07h
  skip:
   add dl,30h
   mov [rsi],dl
   dec rsi
   loop cont

   scall 1,1,dispnum,16

 ret

 convert:   ;procedure to convert ascii to hex


   mov rsi,temp
   mov cl,02h
   MOV rax,0        ;RMD
   mov rdx,0        ;RMD
  contc:
   rol dl,04h
   mov al,[rsi]
   cmp al,39h
   jbe skipc
   sub al,07h
  skipc:
   sub al,30h
   add dl,al
   inc rsi
   dec cl
   jnz contc
JSPM’s
Imperial College of Engineering and Research, Wagholi,
Pune.
(Approved by AICTE, Delhi & Govt. of Maharashtra, affiliated to Savitribai Phule Pune University)
Gat.No.720,Pune-Nagar road,Wagholi,Pune,412207
Department of Computer Engineering
_______________________________________________________________________________________________________
 ret

 exit:    ;exit system call

   mov rax,60
   mov rdi,0
   syscall

ret

OUTPUT:
swlab@swlab-Veriton-M200-H81:~/Desktop/dhokane$ nasm -f elf64 fact.asm
swlab@swlab-Veriton-M200-H81:~/Desktop/dhokane$ ld -o fact fact.o
swlab@swlab-Veriton-M200-H81:~/Desktop/dhokane$ ./fact
*****Program to find Factorial of a number*****
Enter the number : 03
Factorial is : 0000000000000006
swlab@swlab-Veriton-M200-H81:~/Desktop/dhokane$

Conclusion:

You might also like