Hello, world and the data section

Bytes in the data section, a write system call, and the assembler computing a string's length for you.

What you'll learn
  • Lay out bytes in a .data section and refer to them by label
  • Call sys_write with a file descriptor, a buffer address and a length
  • Use the assembler's $ symbol to compute a length at build time

A program that prints needs two things the first lesson did not have: some bytes to print, and a second system call.

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

section .text
_start:
    mov eax, 4          ; sys_write
    mov ebx, 1          ; file descriptor 1 = stdout
    mov ecx, msg        ; address of the bytes
    mov edx, len        ; how many bytes
    int 0x80

    mov eax, 1          ; sys_exit
    mov ebx, 0
    int 0x80

db (“define bytes”) places the 13 characters of Hello, world! and a newline (0x0a) into the data section. The label msg is just the address of the first byte — so mov ecx, msg loads a number like 0x0804a000, not the text.

len equ $ - msg is computed by the assembler, not the CPU. $ means “the current address”, which right after the string is one past its last byte; subtracting the start gives 14. As the script’s comment says, writing 14 by hand would work, but would silently break the moment the message changed.

02_hello_world.asm. The green row is the .data section as the program sees it. Watch ecx receive an address, not text, and the write call print exactly edx bytes from there.

Two system calls

sys_write takes three arguments, mirroring C’s write(fd, buf, count): ebx is the file descriptor (1 for standard output), ecx the address of the bytes, and edx the count. The kernel copies the bytes out and returns the number written in eax. Then sys_exit ends the program with status 0, the conventional “success”.

Nothing here knows about strings: there is no terminating zero, and the kernel writes exactly edx bytes. Set edx too large and whatever follows msg in memory gets printed too.

Try it yourself. Write the message to standard error instead (file descriptor 2) and confirm with ./hello 2>/dev/null that it disappears. Then add a second string bye db "Bye!", 0x0a and print both with two sys_write calls. What happens if you print msg with edx set to len + 5?

View source on GitHub →