Monday, March 17, 2014

Structure of an Assembly Language Program


 




We usually organize our assembly language program in three main sections which are
  1. .data - Contains all initialized data like a hello world string is initialized.
  2. .bss - Contains all uninitialized data
  3. .text - Contains actual assembly language program instructions
  4. .globl _start - External callable routines
  5. _start - Signifies the start of the program like a main() routine in C language.
We would now quickly compose a very simple assembly language program in Linux which just exits. First we need to look at the Linux system calls. The Linux system calls are library of functions which the kernel uses to perform various tasks. List of system calls are available in the following file on Ubuntu 12 or 13  (/usr/include/i386-linux-gnu/asm/unistd_32.h). Opening this file we see the following input. 

#ifndef _ASM_X86_UNISTD_32_H
#define _ASM_X86_UNISTD_32_H 1

#define __NR_restart_syscall 0
#define __NR_exit 1
#define __NR_fork 2
#define __NR_read 3
#define __NR_write 4
#define __NR_open 5
#define __NR_close 6
#define __NR_waitpid 7
#define __NR_creat 8
#define __NR_link 9
#define __NR_unlink 10
#define __NR_execve 11
#define __NR_chdir 12
#define __NR_time 13
#define __NR_mknod 14
#define __NR_chmod 15
#define __NR_lchown 16

Each Linux system call has a number. And we need to use both 0 and 1. System calls are invoked by software interrupt - int 0x80. So how do we pass arguments to system calls in Linux. By putting the the call and its arguments in various registers as shown below.


EAX – System Call number

EBX – 1st Argument

ECX – 2nd Argument

EDX – 3rd Argument

ESI – 4th Argument

EDI – 5th Argument
 So writing our very simple assembly language program 

.section .text
.global _start

_start:
        movl $1, %eax     # Copy/move 1 into register EAX
        movl $0, %ebx     # Copy/move 0 into register EBX
        int $0x80               # Call system interrupt 0x80 for syscall

All this program does is that run and exit. We can compile and load this program by inputting

%  as -o exitnow.o exitnow.s  #Compiling this program
% ld -o exitnow exitnow.o        #Linking this program

No comments:

Post a Comment