Thursday, April 16, 2009

 

Hello World program in assembly

Why break the tradition?


Hello World program in assembly

section .data
msg db "Hello, world!",0
len equ $ - msg
section .text

global _start

_start:

mov edx,len
mov ecx,msg
mov ebx,1
mov eax,4 ; eax = 4 -> write to file
int 0x80

mov ebx,0

mov eax,1 ; eax = 1 -> exit
int 0x80


Key points:

The only interesting thing in the above program is the instruction int 0x80. int 0x80 is a linux system call. int 0x80 provides several different services. The type of service provided by the system call depends on the value in eax.

The first call to int 0x80 is with eax = 4. Eax=4 signifies 'write to a file'. Information about the file descriptor is provided in ebx register. In this case ebx = 1 which refers to stdout. Note that since we are writing to stdout , there is no need to open the file. ecx specifies the pointer to the data and edx specifies the length. The length is computed by subtracting the address of the first byte from the last byte.

For example, here is what the string layout will look like in memory (assume start address 0x100) :

0x100 -> 'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' <-0x10C

Each character is assigned a byte. So the starting address is 0x100 and the address of the byte after the last byte is 0x10d.

This is accomplished by the following line of code in the program:
//$ = 0x10d , msg= 0x100, so len = 0xd
len equ $ - msg


The second call to int 0x80 is with eax = 1. Eax=1 signifies the exit system call. Ebx contains the exit status. Think of it is exit(0) that you see in C programs.


Build the program:
I use the nasm assembler. Typically it comes with the linux distribution. just search for nasm and install.

Assemble:
1) nasm -felf hello.asm

will create hello.o in the same directory.

link:
2)ld hello.o

will create a.out

Run:
a.out

The output will be the 'hello , world!' string.

Comments:

Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]