Hello World in Assembly

Every beginner's first program

Hello reader,

Today we will consider how to write a hello world program in assembly language.

The hello world program, uses the sys.write system call. The write system call documentation can be seen in the man 2 section of write in linux.

$ man 2 write

Documentation for write system call

#include <unistd.h>
#include <string.h>

int main(void)
{
    char *message = "Hello, World!\n";
    int msglen = strlen(message);

    write(1, message, msglen);

    return (0);
}

hello world in C

Okay, let's translate this to Assembly code

section .data
    msg db "Hello, World", 10
    msglen equ 13

section .text
    global _start

_start:
    mov eax, 4 
    mov ebx, 1 
    mov ecx, msg
    mov edx, msglen
    int 0x80

    mov eax, 1
    mov ebx, 0
    int 0x80

Hello World in Assembly:

Explaining the code:

The .data section is used to store values that can be used at runtime of the program. Here stores the values message and msglen. Note the 'db' that is used to define bytes and 'eq' used to define the integer.

The .text section creates a global label named _start, this label must be created and serves as the entry point for the program.

Program enters the _start label:

Following the write call example in our C code

  1. mov eax, 4 : This moves the value 4 into the eax register. Indicating to the kernel that it is the write system call we intend to make. Moving a different number into the eax register may mean another system call eg. read, open, or exit system calls have separate number values.

  2. mov ebx, 1: Indicates we want to write to stdout. Which has the file descriptor 1. It is the same as the first parameter passed into the write call in our initial C code.

  3. mov ecx, msg: This moves the address of the string into the ecx register. Same as the second parameter in the write system call.

  4. mov edx, msglen: This moves the 'msglen' into the edx register. This serves as the third parameter in our write call

  5. int 0x80: This command is called an interrupt. Rightly cause it interrupts the kernel and tells it to call the command specified above. This should print our string but it is not complete yet as we need to return successfully from the code as in the above C code.

  6. mov eax, 1: This moves 1 into the eax register and indicates to the kernel that you want to make the exit command.

  7. mov ebx, 0: Moves 0 into the ebx register and signifies that the code exited successfully.

  8. int 0x80: Interrupt again, to call our exit code.

Compiling our code

$ nasm -f elf64 main.s -o main.o && ld main.o -o main && ./main

If everything worked out successfully. You should get an output 'Hello, World'.

That's all for now.

See you in our next article.