Saturday, January 7, 2012

Running your first Assembly Language program using NASM.

Netwide Assembler (NASM) is an assembler and dissembler for the Intel x86 architecture and is commonly used to create 16-bit, 32-bit (IA-32) and 64-bit (x86-64) programs. It is available for multiple operating systems like Linux or Windows, for example.
An assembler can assemble the assembly code.


Here is a sample code(assembly language) which I copied from Nasm website.Now lets try to compile and run it using nasm.

section .data
 hello:     db 'Hello world!',10    ; 'Hello world!' plus a linefeed character
 helloLen:  equ $-hello             ; Length of the 'Hello world!' string
                                    ; (I'll explain soon)

section .text
 global _start

_start:
 mov eax,4            ; The system call for write (sys_write)
 mov ebx,1            ; File descriptor 1 - standard output
 mov ecx,hello        ; Put the offset of hello in ecx
 mov edx,helloLen     ; helloLen is a constant, so we don't need to say
                      ;  mov edx,[helloLen] to get it's actual value
 int 80h              ; Call the kernel

 mov eax,1            ; The system call for exit (sys_exit)
 mov ebx,0            ; Exit with return code of 0 (no error)
 int 80h

 

Compiling and Linking

  1. If you don't have a terminal or console open, open one now.
  2. Make sure you are in the same directory as where you saved hello.asm.
  3. To assemble the program, type
    nasm -f elf hello.asm
    If there are any errors, NASM will tell you on what line you did what wrong.
  4. Now type 
    ld -s -o hello hello.o

    This will link the object file NASM produced into an executable file.
  5. Run your program by typing ./hello
    (To run programs/scripts in the current directory, you must always type ./ before the name, unless the current directory is in the path.)
You should see     Hello world!    printed to the screen. Congratulations! You have just written your first assembly program in Linux!

Courtesy : Nasm website.