asm linux

por | 6 mayo, 2007

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

 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

Copy this program into a text editor of your choice (I use vi or SciTE), and save it as hello.asm in your home directory (/home/yourname).
4.5 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!

Tags: , ,