57
[2011]
In general, programming of a microprocessor
usually takes several iterations before the right
sequence of machine code instructions is written.
The process, however, is facilitated using a
special program called an “Assembler”.
The Assembler allows the user to write
alphanumeric instructions, or mnemonics, called
Assembly Language instructions.
The Assembler, in turn, generates the desired
machine instructions from the Assembly Language
instructions.
[2011] 58
For the entire lab session, we will use the
following software
Linux OS(Linux Mint)
Netwide Assembler NASM (8086_Assembler)
[2011] 59
Steps to execute an assembly program
. Write the code on any text editor
. Save the file as file_name.asm and set the
type to All files.
• Make sure that you are in the same directory as where
you saved your program
file_name.asm
• If there is any error, you will be prompted about that at
this stage. Otherwise, an object file of your program
named file_name.o will be created.
To link the object file and create an executable file:
ld -m elf_i386 -s -o file_name file_name.o
. Execute by typing: ./file_name
[2011] 60
Assembling the program:
The assembler is used to convert the assembly language
instructions to machine code.
It is used immediately after writing the Assembly
Language program.
It starts by checking the syntax, or validity of the
structure, of each instruction in the source file.
If any errors are found, the assembler displays a report
on these errors along with a brief explanation of their
nature.
However, if the program does not contain any errors, the
assembler produces an object file that has the same name
as the original file but with the “o” extension
[2011] 61
linking
The linker is used to convert the object file to an
executable file.
The executable file is the final set of machine
code instructions that can directly be executed
by the microprocessor.
An object file may represent one segment of a
long program.
This segment cannot operate by itself, and must be
integrated with other object files representing the
rest of the program, in order to produce the final
self-contained executable file.
[2011] 62
Executing the program
The executable file contains the machine language code.
It can be loaded in the RAM and be executed by the
microprocessor simply by typing, from the DOS prompt, the
name of the file followed by the Carriage Return Key (Enter
Key).
If the program produces an output on the screen, or a
sequence of control signals to control a piece of hardware,
the effect should be noticed almost immediately.
However, if the program manipulates data in memory, nothing
would seem to have happened as a result of executing the
program.
[2011] 63
Structure of an Assembly Language Program
An assembly language program is written according the
following structure and includes the following assembler
directives:
The data section
The bss section
The text section
The data Section
The data section is used for declaring initialized data or
constants.
This data does not change at runtime.
You can declare various constant values, file names or
buffer size etc. in this section.
The syntax for declaring data section is:
section .data
[2011] 64
Program Structure
The bss Section
The bss section is used for declaring variables.
The syntax for declaring bss section is:
section .bss
The text section
The text section is used for keeping the actual code.
This section must begin with the declaration global
main or global _start which tells the kernel where
the program execution begins.
The syntax for declaring text section is:
section .text
global main/ _start
main:/_start 65
[2011]
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
or, on the same line along with an instruction, like:
add eax ,ebx ; adds ebx to eax
66
[2011]
Assembly Language Statements
Assembly language programs consist of three types of statements:
Executable instructions or instructions
Assembler directives or pseudo-ops
Macros
The executable instructions or simply instructions tell the processor
what to do. Each instruction consists of an operation code (opcode). Each
executable instruction generates one machine language instruction.
The assembler directives or pseudo-ops tell the assembler about the
various aspects of the assembly process.
These are non-executable and do not generate machine language instructions.
Macros are basically a text substitution mechanism.
Syntax of Assembly Language Statements
Assembly language statements are entered one statement per line. Each
statement follows the following format:
[label] mnemonic [operands] [; comment]
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. [2011]
67
Symbols
A symbolic name consists of a sequence of letters, digits,
and special characters, with the following restrictions:
A symbol cannot begin with a numeric digit.
A name can have any combination of upper and lower case
alphabetic characters.
The assembler treats upper and lower case equivalently.
A symbol may contain any number of characters, however
only the first 31 are used.
The assembler ignores all characters beyond the 31st.
The _, $, ?, and @ symbols may appear anywhere within a
symbol.
However, $ and ? are special symbols; you cannot create a symbol
made up solely of these two characters.
A symbol cannot match any name that is a reserved
symbol [2011] 68
Symbols
ome examples of valid symbols include:
L1 Bletch RightHe
Right_Here Item1 __Special $1234
@Home $_@1 Dollar$
WhereAmI? @1234
Some examples of illegal symbols include:
1TooMany - Begins with a digit.
[Link] - Contains a period in the middle of the
symbol.
$ - Cannot have $ or ? by itself.
LABEL - Assembler reserved word.
Right Here - Symbols cannot contain spaces.
Hi,There - or other special symbols besides _, ?,
$, [2011] and @. 69
Variables
Here we will simply use the 8086 registers
as the variables in our programs.
Registers have predefined names and do not
need to be declared.
[2011] 70
Variable Declaration
NASM provides various define directives for reserving storage space
or variables. The define assembler directive is used for allocation of
orage space.
t can be used to reserve as well as initialize one or more bytes.
Allocating Storage Space for Initialized Dat
The syntax for storage allocation statement for initialized data is:
variable-name] define-directive initial-value [, initial-value] ...
Where, variable-name is the identifier for each storage space. The
ssembler associates an offset value for each variable name defined in
he data segment.
There are five basic forms of the define directive:
Directive Purpose StorageSpace
DB DefineByte allocates1byte
DW DefineWord allocates2bytes
DD DefineDoubleword allocates4bytes
DQ DefineQuadword allocates8bytes
DT DefineTenBytes allocates10bytes
[2011] 71
Each variable has a type and assigned a memory address.
Example
Byte Variables
Assembler directive format assigning a byte
variable
Syntax: Name DB initial value
A question mark (“?”) place in initial value leaves variable
uninitialized
L DB 4 ;define variable L with initial value 4
J DB ? ;Define variable J with uninitialized value
Name DB "Course" ;allocate 6 bytes for name
K DB 5, 3,-1 ;allocate 3 bytes
72
[2011]
VARIABLE DECLARATION
L1 db 0; byte labeled L1 with initial value 0
L2 dw 1000 ; word labeled L2 with initial value 1000
3 db 110101b ; byte initialized to binary 110101
L4 db 12h
; byte initialized to hex 12 (18 in decimal)
L5 db 17o
; byte initialized to octal 17 (15 in decimal)
6 dd 1A92h ; double word initialized to hex 1A92
L7 resb 1
; 1 uninitialized byte
L8 db "A"
; byte initialized to ASCII code for A (65)
ouble quotes and single quotes are treated the same.
onsecutive data definitions are stored sequentially in
emory. That is, the word L2 is stored immediately after L
memory. Sequences of memory may also be defined.
L9 db 0, 1, 2, 3; defines 4 bytes
10 db "w", "o", "r", ’d’, 0 ; defines a C string = "word"
73
L11 db ’word’, 0; same as L10 [2011]
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:
Directive Purpose
RESB ReserveaByte
RESW ReserveaWord
RESD ReserveaDoubleword
RESQ ReserveaQuadword
REST ReserveaTenBytes
74
[2011]
Allocating Storage Space for Uninitialized Data
Multiple Definitions
You can have multiple data definition statements in a program. For
example:
choice DB 'Y' ;ASCII of y = 79H
number1 DW 12345 ;12345D = 3039H
number2 DD 12345679 ;123456789D = 75BCD15H
The assembler allocates contiguous memory for multiple variable
definitions.
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.
[2011] 75
There are several directives provided by NASM that define constants. Some of them
are :
EQU
%assign
%define
The EQU Directive
The EQU directive is used for defining constants.
The syntax of the EQU directive is as follows:
CONSTANT_NAME EQU expression
For example,
TOTAL_STUDENTS equ 50
You can then use this constant value in your code, like:
mov ecx, TOTAL_STUDENTS
cmp eax, TOTAL_STUDENTS
The operand of an EQU statement can be an expression:
LENGTH equ 20
WIDTH equ 10
AREA equ length * width
Above code segment would define AREA as 200. [2011]
76
The %assign Directive
The %assign directive can be used to define numeric constants like
the EQU directive. This directive allows redefinition.
For example, you may define the constant TOTAL as:
%assign TOTAL 10
Later in the code, you can redefine it as:
%assign TOTAL 20
This directive is case-sensitive.
The %define Directive
The %define directive allows defining both numeric and string
constants. This directive is similar to the #define in C.
For example, you may define the constant PTR as:
%define PTR [EBP+4]
The above code replaces PTR by [EBP+4].
This directive also allows redefinition and it is case-sensitive.
[2011] 77
stem calls are APIs for the interface between the user space and
e kernel space.
u can make use of Linux system calls in your assembly programs. You
ed to take the following steps for using Linux system calls in your
ogram:
Put the system call number in the EAX register.
Store the arguments to the system call in the registers EBX, ECX, et
Call the relevant interrupt (80h).
The result is usually returned in the EAX register.
ere are six registers that store the arguments of the system call
ed. These are the EBX, ECX, EDX, ESI, EDI, and EBP. These
gisters take the consecutive arguments, starting with the EBX
gister.
e following code snippet shows the use of the system call sys_exit:
mov eax,1; system call number (sys_exit)
int 0x80 ; call kernel
[2011] 78
here are some of system calls commonly used
No FuncNam Description
e
1 exit terminatethecurrentprocess
2 fork createachildprocess
3 read readfromafiledescriptor
4 write writetoafiledescriptor
5 open openafileordevice
6 close closeafiledescriptor
• The7following code
waitpid
snippet shows the use of the system
waitforprocesstermination
call sys_write:
mov edx,4 ; message length
mov ecx,msg ; message to write
mov ebx,1 ; file descriptor (stdout)
mov eax,4 ; system call number (sys_write)
79
int 0x80 ; call kernel(interrupt) [2011]
Some practical Examples
ortant!!!
To display a message/value
place the address of the message/value to be displayed
ecx (e.g. mov ecx,msg)
place the length of the message/value to be displayed t
edx register (e.g. mov edx,length)
Place the Sys_write call number to eax (e.g. mov eax,4)
Place the standard output device to ebx(e.g. mov ebx,1
Call for interrupt (int 0x80)
To read data from keyboard
Place the sys_read call number to eax (e.g. mov eax, 3)
Place the standard input device no to ebx ([Link] ebx
Place the address of the data to ecx (e.g. mov ecx, num
Place the size of the data to edx (e.g. mov edx, 5 )
Call for interrupt (int 80h)
80
[2011]
Some practical Examples
. [Link]
. msg db 'Hello World!', 0Ah; assign msg variable with your
message string
. SECTION .text
4. global _start
5. _start:
6. mov edx, 13 ; number of bytes to write - one for each letter plus
0Ah (line feed character)
7. mov ecx, msg ; move the memory address of our
message string into ecx
8. mov ebx, 1 ; write to the STDOUT file
9. mov eax, 4 ; invoke SYS_WRITE (kernel opcode 4)
[Link] 80h ; intrrupt [2011]
81
Some practical Examples
section .data
SYS_EXIT equ 1
SYS_READ equ 3
SYS_WRITE equ 4
STDIN equ 0
STDOUT equ 1
msg1 db "Enter Your Name", 0xA,0xD
len1 equ $- msg1
msg2 db "Hello! "
len2 equ $- msg2
segment .bss
name resb 20;reserving a memory for name
82
[2011]
section .text Some practical Examples
global _start ;must be declared for using gcc
_start: ;tell linker entry point
;prompting for message 1
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, msg1
mov edx, len1
int 0x80
;reading name
mov eax, SYS_READ
mov ebx, STDIN
mov ecx, name
mov edx, 20
int 0x80 83
[2011]
Some practical Examples
;displaying the message
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, msg2
mov edx, len2
int 0x80
; print the Message
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, name
mov edx, 20
int 0x80
;exit:
mov eax, SYS_EXIT 84
int 0x80 [2011]
Some practical Examples
ection .data ;Data segment
Ask the user to enter a number
msg1 db 'Please enter a number: '
en1 equ $-msg1 ;The length of the message
msg2 db 'The Entered number is: '
en2 equ $-msg2
section .bss
um resb 5 ;Uninitialized data
85
[2011]
Some practical Examples
section .text ;Code Segment
global _start
start:
;User prompt
mov eax, 4 ;sys_write
mov ebx, 1
mov ecx, msg1
mov edx, len1
int 80h
Read and store the user input
mov eax, 3 ;sys_read
mov ebx, 2 ;STDIN
mov ecx, num
mov edx, 5 ;5 bytes of that information
int 80h [2011]
86
Some practical Examples
Output the message 'The entered number is: '
mov eax, 4
mov ebx, 1
mov ecx, msg2
mov edx, len2
int 80h
;Output the number entered
mov eax, 4
mov ebx, 1
mov ecx, num
mov edx, 5
int 80h
Exit code
mov eax, 1
mov ebx, 0 87
int 80h [2011]
Some practical Examples
4. Aprogram to add two integers
section .text
global _start
_start:
mov eax,'2‘
sub eax,'0' ;to connvert to ASCII
mov ebx,'4‘
sub ebx,'0';to convert to ASCII
add eax,ebx
add eax,'0' ;to convert to Decimal
ov [sum],eax ;copying the result to sum
v ecx,msg ; placing the address of the message to
v edx,len ;placing the length of the message to ed
v ebx,1 ;stdout
mov eax,4 ;sys_write
int 0x80 ;call for interrupt 88
[2011]
Some practical Examples
4. Aprogram to add two integers
mov ecx,sum ;
mov edx,10 ; size of the sum
mov ebx,1 ; stdout
mov eax,4 ;sys_write
nt 0x80
section .data
msg db "The sum is:",0xA,0xD
en equ $-msg
section .bss
sum resb 10
89
[2011]
te 1.
an Assembly program to perform addition of two numbers t
m keyboard
te 2.
an Assembly program to display a character ‘@’
[2011] 90