Nasm

From Schmid.wiki
Jump to: navigation, search

Contents

Software

Use nasm.

Hello World

Basically, there are two ways of making an assembler code hello world-program.

  1. You can make a system call interrupt
  2. You can call a C library function like 'puts' or 'printf'

The example below uses 'puts'.

Source

        extern  puts            ; the C function to be called

        SECTION .data           ; *DATA SECTION*, initialized variables
txt:    db "Hello World", 10, 0 ; equivalent to C string: "Hello World\n"

        SECTION .text           ; *CODE SECTION*
        global main             ; the standard gcc entry point
main:                           ; the program label for the entry point
        push    ebp             ; set up stack frame
        mov     ebp,esp

        push    txt             ; push address of 'txt' to the stack
        call    puts            ; call C function 'puts'. It expects a 32 bit
                                ; pointer to a string on the stack
        add     esp, 4          ; pop 'txt' from stack by moving 32 bit = 4 bytes up

        mov     esp, ebp        ; takedown stack frame
        pop     ebp             ; same as "leave" op

        mov     eax,0           ; normal, no error, return value
        ret                     ; return

Assemble, link, and run

nasm -f elf hello.asm && gcc -o hello hello.o && ./hello

Tips

When using C library calls, always remember to check the size of the expected arguments, otherwise you will get unexpected results. A standard integer is 32 bit right now.

References

Personal tools