Professional Documents
Culture Documents
Class Notes Programming
Class Notes Programming
Each family of processors has its own set of instructions for handling
various operations such as getting input from keyboard, displaying
information on screen and performing various other jobs. These set of
instructions are called 'machine language instructions'.
It is most suitable for writing interrupt service routines and other memory
resident programs.
So, the parity bit is used to make the number of bits in a byte odd. If the
parity is even, the system assumes that there had been a parity error
(though rare), which might have been caused due to hardware fault or
electrical disturbance.
The following table shows the positional values for an 8-bit binary number,
where all bits are set ON.
Bit value 1 1 1 1 1 1 1 1
Position value as a 128 64 32 16 8 4 2 1
power of base 2
Bit number 7 6 5 4 3 2 1 0
The value of a binary number is based on the presence of 1 bits and their
positional value. So, the value of a given binary number is −
which is same as 28 - 1.
0 0 0
1 1 1
2 10 2
3 11 3
4 100 4
5 101 5
6 110 6
7 111 7
8 1000 8
9 1001 9
10 1010 A
11 1011 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F
Binary Arithmetic
The following table illustrates four simple rules for binary addition −
0 1 1 1
+0 +0 +1 +1
=0 =1 =10 =11
Rules (iii) and (iv) show a carry of a 1-bit into the next left position.
Example
Decimal Binary
60 00111100
+42 00101010
102 01100110
Example
Number 53 00110101
Reverse the bits 11001010
Add 1 00000001
To subtract one value from another, convert the number being subtracted
to two's complement format and add the numbers.
Example
Subtract 42 from 53
Number 53 00110101
Number 42 00101010
Add 1 00000001
53 - 42 = 11 00001011
The processor may access one or more bytes of memory at a time. Let us
consider a hexadecimal number 0725H. This number will require two bytes
of memory. The high-order byte or most significant byte is 07 and the low-
order byte is 25.
x: memory address
When the processor gets the numeric data from memory to register, it
again reverses the bytes. There are two kinds of memory addresses −
Segment address (or offset) - starting address of a memory segment with the
offset value.
Installing NASM
If you select "Development Tools" while installing Linux, you may get 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 −
Check The netwide assembler (NASM) website for the latest version.
Download the Linux source archive nasm-X.XX.ta.gz, where X.XX is the NASM
version number in the archive.
Unpack the archive into a directory which creates a subdirectory nasm-X. XX.
cd to nasm-X.XX and type ./configure. This shell script will find the best C
compiler to use and set up Makefiles accordingly.
Type make install to install nasm and ndisasm in /usr/local/bin and to install
the man pages.
This should install NASM on your system. Alternatively, you can use an RPM
distribution for the Fedora Linux. This version is simpler to install, just
double-click the RPM file.
Comments
Assembly language comment begins with a semicolon (;). It may contain
any printable character including blank. It can appear on a line by itself, like
−
; This program displays a message on screen
Macros.
The fields in the square brackets are optional. A basic instruction has two
parts, the first one is the name of the instruction (or the mnemonic), which
is to be executed, and the second are the operands or the parameters of
the command.
section .text
section .data
When the above code is compiled and executed, it produces the following
result −
Hello, world!
Compiling and Linking an Assembly Program in
NASM
Make sure you have set the path of nasm and ld binaries in your PATH
environment variable. Now, take the following steps for compiling and
linking the above program −
Type the above code using a text editor and save it as hello.asm.
Make sure that you are in the same directory as where you saved hello.asm.
If there is any error, you will be prompted about that at this stage. Otherwise,
an object file of your program named hello.o will be created.
To link the object file and create an executable file named hello, type ld -m
elf_i386 -s -o hello hello.o
If you have done everything correctly, it will display 'Hello, world!' on the
screen.
Interestingly, if you replace the section keyword with segment, you will get
the same result. Try the following code −
Live Demo
When the above code is compiled and executed, it produces the following
result −
Hello, world!
Memory Segments
A segmented memory model divides the system memory into groups of
independent segments referenced by pointers located in the segment
registers. Each segment is used to contain a specific type of data. One
segment is used to contain instruction codes, another segment stores the
data elements, and a third segment keeps the program stack.
Data segment − It is represented by .data section and the .bss. The .data
section is used to declare the memory region, where data elements are stored
for the program. This section cannot be expanded after the data elements are
declared, and it remains static throughout the program.
The .bss section is also a static memory section that contains buffers for data to
be declared later in the program. This buffer memory is zero-filled.
Stack − This segment contains data values passed to functions and procedures
within the program.
Processor operations mostly involve processing data. This data can be
stored in memory and accessed from thereon. However, reading data from
and storing data into memory slows down the processor, as it involves
complicated processes of sending the data request across the control bus
and into the memory storage unit and getting the data through the same
channel.
The registers store data elements for processing without having to access
the memory. A limited number of registers are built into the processor chip.
Processor Registers
There are ten 32-bit and six 16-bit processor registers in IA-32 architecture.
The registers are grouped into three categories −
General registers,
Segment registers.
The general registers are further divided into the following groups −
Data registers,
Index registers.
Data Registers
Four 32-bit data registers are used for arithmetic, logical, and other
operations. These 32-bit registers can be used in three ways −
Lower halves of the 32-bit registers can be used as four 16-bit data registers:
AX, BX, CX and DX.
Lower and higher halves of the above-mentioned four 16-bit registers can be
used as eight 8-bit data registers: AH, AL, BH, BL, CH, CL, DH, and DL.
Pointer Registers
The pointer registers are 32-bit EIP, ESP, and EBP registers and
corresponding 16-bit right portions IP, SP, and BP. There are three
categories of pointer registers −
Instruction Pointer (IP) − The 16-bit IP register stores the offset address of
the next instruction to be executed. IP in association with the CS register (as
CS:IP) gives the complete address of the current instruction in the code
segment.
Stack Pointer (SP) − The 16-bit SP register provides the offset value within
the program stack. SP in association with the SS register (SS:SP) refers to be
current position of data or address within the program stack.
Base Pointer (BP) − The 16-bit BP register mainly helps in referencing the
parameter variables passed to a subroutine. The address in SS register is
combined with the offset in BP to get the location of the parameter. BP can also
be combined with DI and SI as base register for special addressing.
Index Registers
The 32-bit index registers, ESI and EDI, and their 16-bit rightmost portions.
SI and DI, are used for indexed addressing and sometimes used in addition
and subtraction. There are two sets of index pointers −
Control Registers
The 32-bit instruction pointer register and the 32-bit flags register
combined are considered as the control registers.
Trap Flag (TF) − It allows setting the operation of the processor in single-step
mode. The DEBUG program we used sets the trap flag, so we could step
through the execution one instruction at a time.
Sign Flag (SF) − It shows the sign of the result of an arithmetic operation. This
flag is set according to the sign of a data item following the arithmetic
operation. The sign is indicated by the high-order of leftmost bit. A positive
result clears the value of SF to 0 and negative result sets it to 1.
Auxiliary Carry Flag (AF) − It contains the carry from bit 3 to bit 4 following
an arithmetic operation; used for specialized arithmetic. The AF is set when a 1-
byte arithmetic operation causes a carry from bit 3 into bit 4.
Parity Flag (PF) − It indicates the total number of 1-bits in the result obtained
from an arithmetic operation. An even number of 1-bits clears the parity flag to
0 and an odd number of 1-bits sets the parity flag to 1.
The following table indicates the position of flag bits in the 16-bit Flags
register:
Flag: O D I T S Z A P C
Bit no: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Segment Registers
Segments are specific areas defined in a program for containing data, code
and stack. There are three main segments −
Data Segment − It contains data, constants and work areas. A 16-bit Data
Segment register or DS register stores the starting address of the data
segment.
Apart from the DS, CS and SS registers, there are other extra segment
registers - ES (extra segment), FS and GS, which provide additional
segments for storing data.
Example
Look at the following simple program to understand the use of registers in
assembly programming. This program displays 9 stars on the screen along
with a simple message −
Live Demo
section .text
section .data
s2 times 9 db '*'
When the above code is compiled and executed, it produces the following
result −
System calls are APIs for the interface between the user space and the
kernel space. We have already used the system calls. sys_write and
sys_exit, for writing into the screen and exiting from the program,
respectively.
Store the arguments to the system call in the registers EBX, ECX, etc.
There are six registers that store the arguments of the system call used.
These are the EBX, ECX, EDX, ESI, EDI, and EBP. These registers take the
consecutive arguments, starting with the EBX register. If there are more
than six arguments, then the memory location of the first argument is
stored in the EBX register.
The following code snippet shows the use of the system call sys_exit −
The following code snippet shows the use of the system call sys_write −
The following table shows some of the system calls used in this tutorial −
1 sys_exit int - - - -
Example
The following example reads a number from the keyboard and displays it on
the screen −
Live Demo
userMsg db 'Please enter a number: ' ;Ask the user to enter a number
global _start
mov eax, 4
mov ebx, 1
int 80h
mov eax, 3
mov ebx, 2
int 80h
mov eax, 4
mov ebx, 1
int 80h
mov ebx, 1
mov edx, 5
int 80h
; Exit code
mov eax, 1
mov ebx, 0
int 80h
Register addressing
Immediate addressing
Memory addressing
Register Addressing
In this addressing mode, a register contains the operand. Depending upon
the instruction, the register may be the first operand, the second operand
or both.
For example,
MOV DX, TAX_RATE ; Register in first operand
Immediate Addressing
An immediate operand has a constant value or an expression. When an
instruction with two operands uses immediate addressing, the first operand
may be a register or memory location, and the second operand is an
immediate constant. The first operand defines the length of the data.
For example,
For example,
ADD BYTE_VALUE, DL ; Adds the register in the memory location
Direct-Offset Addressing
This addressing mode uses the arithmetic operators to modify an address.
For example, look at the following definitions that define tables of data −
The following operations access data from the tables in the memory into
registers −
The following code snippet shows how to access different elements of the
variable.
Syntax
The syntax of the MOV instruction is −
MOV destination, source
The MOV instruction may have one of the following five forms −
The MOV instruction causes ambiguity at times. For example, look at the
statements −
WORD 2
DWORD 4
QWORD 8
TBYTE 10
Example
The following program illustrates some of the concepts discussed above. It
stores a name 'Zara Ali' in the data section of the memory, then changes its
value to another name 'Nuha Ali' programmatically and displays both the
names.
Live Demo
section .text
section .data
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.
choice DB 'y'
number DW 12345
neg_number DW -12345
big_number DQ 123456789
real_number1 DD 1.234
real_number2 DQ 123.456
Each decimal value is automatically converted to its 16-bit binary equivalent and
stored as a hexadecimal number.
section .text
section .data
choice DB 'y'
When the above code is compiled and executed, it produces the following
result −
y
Directive Purpose
Multiple Definitions
You can have multiple data definition statements in a program. For example
−
Multiple Initializations
The TIMES directive allows multiple initializations to the same value. For
example, an array named marks of size 9 can be defined and initialized to
zero using the following statement −
marks TIMES 9 DW 0
The TIMES directive is useful in defining arrays and tables. The following
program displays 9 asterisks on the screen −
Live Demo
section .text
section .data
When the above code is compiled and executed, it produces the following
result −
*********
EQU
%assign
%define
For example,
TOTAL_STUDENTS equ 50
You can then use this constant value in your code, like −
WIDTH equ 10
Example
The following example illustrates the use of the EQU directive −
Live Demo
SYS_EXIT equ 1
SYS_WRITE equ 4
STDIN equ 0
STDOUT equ 1
section .text
int 0x80
int 0x80
mov eax, SYS_WRITE
int 0x80
section .data
When the above code is compiled and executed, it produces the following
result −
Hello, programmers!
Welcome to the world of,
Linux assembly programming!
Syntax
The INC instruction has the following syntax −
INC destination
Example
INC EBX ; Increments 32-bit register
Syntax
The DEC instruction has the following syntax −
DEC destination
count dw 0
value db 15
segment .text
inc [count]
dec [value]
Syntax
The ADD and SUB instructions have the following syntax −
ADD/SUB destination, source
Register to register
Memory to register
Register to memory
Example
The following example will ask two digits from the user, store the digits in
the EAX and EBX register, respectively, add the values, store the result in a
memory location 'res' and finally display the result.
SYS_EXIT equ 1
SYS_READ equ 3
SYS_WRITE equ 4
STDIN equ 0
STDOUT equ 1
segment .data
segment .bss
num1 resb 2
num2 resb 2
res resb 1
section .text
int 0x80
mov edx, 2
int 0x80
int 0x80
mov edx, 2
int 0x80
int 0x80
; moving the first number to eax register and second number to ebx
mov edx, 1
int 0x80
exit:
int 0x80
When the above code is compiled and executed, it produces the following
result −
Enter a digit:
3
Please enter a second digit:
4
The sum is:
7
section .text
mov eax,'3'
mov ecx,msg
mov ecx,sum
mov edx, 1
section .data
segment .bss
sum resb 1
When the above code is compiled and executed, it produces the following
result −
The sum is:
7
The MUL/IMUL Instruction
There are two instructions for multiplying binary data. The MUL (Multiply)
instruction handles unsigned data and the IMUL (Integer Multiply) handles
signed data. Both instructions affect the Carry and Overflow flag.
Syntax
The syntax for the MUL/IMUL instructions is as follows −
MUL/IMUL multiplier
Sr.No Scenarios
.
2
When two one-word values are multiplied −
Example
MOV AL, 10
MOV DL, 25
MUL DL
...
IMUL DL
Example
The following example multiplies 3 with 2, and displays the result −
Live Demo
section .text
mov al,'3'
mul bl
mov [res], al
mov ecx,msg
mov ecx,res
mov edx, 1
section .data
segment .bss
res resb 1
When the above code is compiled and executed, it produces the following
result −
The result is:
6
The DIV (Divide) instruction is used for unsigned data and the IDIV (Integer
Divide) is used for signed data.
Syntax
The format for the DIV/IDIV instruction −
DIV/IDIV divisor
Sr.No Scenarios
.
2
When the divisor is 1 word −
The dividend is assumed to be 32 bits long and in the DX:AX registers.
The high-order 16 bits are in DX and the low-order 16 bits are in AX.
After division, the 16-bit quotient goes to the AX register and the 16-bit
remainder goes to the DX register.
Example
The following example divides 8 with 2. The dividend 8 is stored in the 16-
bit AX register and the divisor 2 is stored in the 8-bit BL register.
Live Demo
section .text
mov ax,'8'
div bl
mov [res], ax
mov ecx,msg
mov ecx,res
mov edx, 1
section .data
segment .bss
res resb 1
When the above code is compiled and executed, it produces the following
result −
The result is:
4
The processor instruction set provides the instructions AND, OR, XOR, TEST,
and NOT Boolean logic, which tests, sets, and clears the bits according to
the need of the program.
2 OR OR operand1, operand2
The first operand in all the cases could be either in register or in memory.
The second operand could be either in register/memory or an immediate
(constant) value. However, memory-to-memory operations are not
possible. These instructions compare or match bits of the operands and set
the CF, OF, PF, SF and ZF flags.
The AND operation can be used for clearing one or more bits. For example,
say the BL register contains 0011 1010. If you need to clear the high-order
bits to zero, you AND it with 0FH.
JZ EVEN_NUMBER
Example
Live Demo
section .text
jz evnn
jmp outprog
evnn:
outprog:
section .data
When the above code is compiled and executed, it produces the following
result −
Even Number!
Similarly to clear the entire register you can AND it with 00H.
The OR Instruction
The OR instruction is used for supporting logical expression by performing
bitwise OR operation. The bitwise OR operator returns 1, if the matching
bits from either or both operands are one. It returns 0, if both the bits are
zero.
For example,
Operand1: 0101
Operand2: 0011
----------------------------
After OR -> Operand1: 0111
The OR operation can be used for setting one or more bits. For example, let
us assume the AL register contains 0011 1010, you need to set the four
low-order bits, you can OR it with a value 0000 1111, i.e., FH.
Example
The following example demonstrates the OR instruction. Let us store the
value 5 and 3 in the AL and the BL registers, respectively, then the
instruction,
OR AL, BL
section .text
mov [result], al
mov eax, 4
mov ebx, 1
mov edx, 1
int 0x80
outprog:
section .bss
result resb 1
When the above code is compiled and executed, it produces the following
result −
7
For example,
Operand1: 0101
Operand2: 0011
----------------------------
After XOR -> Operand1: 0110
XORing an operand with itself changes the operand to 0. This is used to
clear a register.
XOR EAX, EAX
For example,
Operand1: 0101 0011
After NOT -> Operand1: 1010 1100
1
Unconditional jump
CMP Instruction
The CMP instruction compares two operands. It is generally used in
conditional execution. This instruction basically subtracts one operand from
the other for comparing whether the operands are equal or not. It does not
disturb the destination or source operands. It is used along with the
conditional jump instruction for decision making.
Syntax
CMP destination, source
CMP compares two numeric data fields. The destination operand could be
either in register or in memory. The source operand could be a constant
(immediate) data, register or memory.
Example
CMP DX, 00 ; Compare the DX value with zero
L7: ...
CMP is often used for comparing whether a counter value has reached the
number of times a loop needs to be run. Consider the following typical
condition −
INC EDX
CMP EDX, 10 ; Compares whether the counter has reached 10
Unconditional Jump
As mentioned earlier, this is performed by the JMP instruction. Conditional
execution often involves a transfer of control to the address of an
instruction that does not follow the currently executing instruction. Transfer
of control may be forward, to execute a new set of instructions or
backward, to re-execute the same steps.
Syntax
The JMP instruction provides a label name where the flow of control is
transferred immediately. The syntax of the JMP instruction is −
JMP label
Example
The following code snippet illustrates the JMP instruction −
L20:
SHL CX, 1 ; shift left CX, this in turn doubles the CX value
Conditional Jump
If some specified condition is satisfied in conditional jump, the control flow
is transferred to a target instruction. There are numerous conditional jump
instructions depending upon the condition and data.
Following are the conditional jump instructions used on signed data used for
arithmetic operations −
Instruction Description Flags tested
Following are the conditional jump instructions used on unsigned data used
for logical operations −
The following conditional jump instructions have special uses and check the
value of flags −
Instruction Description Flags tested
JC Jump If Carry CF
JO Jump If Overflow OF
Example,
CMP AL, BL
JE EQUAL
CMP AL, BH
JE EQUAL
CMP AL, CL
JE EQUAL
NON_EQUAL: ...
EQUAL: ...
Example
The following program displays the largest of three variables. The variables
are double-digit variables. The three variables num1, num2 and num3 have
values 47, 22 and 31, respectively −
Live Demo
section .text
jg check_third_num
check_third_num:
jg _exit
_exit:
mov ecx,msg
mov ecx,largest
mov edx, 2
mov eax, 1
int 80h
section .data
num1 dd '47'
num2 dd '22'
num3 dd '31'
segment .bss
largest resb 2
When the above code is compiled and executed, it produces the following
result −
The largest digit is:
47