On this page

The kernel doesn’t know what printf is. It only sees a syscall number, argument registers, and an exact byte count.

In C99, CRT runs before main (lesson 02): it prepares arguments, invokes main, and terminates the process via exit once main returns. In assembly, there is no such wrapper: the kernel jumps straight to the address in the ELF header, and the very first instruction is yours.

By the time that first instruction runs, the process already has three standard streams open, inherited from the shell—each assigned a file descriptor (we’ll break down the descriptor table in lesson 12):

  • fd 0 — stdin (standard input);
  • fd 1 — stdout (standard output);
  • fd 2 — stderr (standard error).

write takes that descriptor number in rdi, so mov edi, 1 targets standard output. In this lesson, I build a minimal program that writes to stdout and exits with a status code equal to the number of bytes written.

Mental Model: C99 Wrapper vs. Raw Syscall

What it looks like in C99 What happens under the hood
printf("hello") is a single operation printf is a libc function; the write syscall is what actually pushes bytes to the terminal
A string “knows” its own length Memory holds raw bytes only; length is passed as a separate argument
return 0 ends the program Inside _start, there is nowhere to return: the exit syscall terminates the process
A program starts at main The kernel starts execution at the _start address stored in the ELF file’s e_entry field

The _start Entry Point

When building with nasm and ld without libc, you declare the _start symbol explicitly.

hello_contract.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; hello_contract.asm — first conversation with the kernel: write and exit via syscall.

default rel

%define SYS_WRITE 1
%define SYS_EXIT 60
%define STDOUT 1

section .rodata
    message: db "hello, kernel", 10
    message_len: equ $ - message

section .text
    global _start

; ------------------------------------------------------------------------------
; _start — entry point whose address the kernel reads from the ELF header.
; Input:    rsp -> argc, argv, envp (unused in this lesson)
; Output:   never returns; exit status = bytes written by write (14)
; Clobbers: rax, rcx, rdx, rsi, rdi, r11 (syscall contract; flags untouched)
; ------------------------------------------------------------------------------
_start:
    ; syscall: write(STDOUT, message, message_len)
    mov eax, SYS_WRITE
    mov edi, STDOUT
    lea rsi, [message]
    mov edx, message_len
    syscall

    ; syscall: exit(rax)
    mov rdi, rax
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

message_len is defined with equ rather than db: it’s an assembly-time constant and takes up zero bytes in memory. You saw this line in lesson 01 inside test.asm; here’s how its syntax works:

  • $ evaluates to the current assembly address—the position right after the last emitted byte;
  • $ - message subtracts the string’s start address to yield its length in bytes;
  • the message_len symbol has type a (absolute): it occupies no space in .rodata and shows up in nm with no section address.

The code uses 32-bit windows eax, edi, and edx instead of rax, rdi, and rdx: writing to a 32-bit register clears the upper 32 bits (the zero-extension rule from lesson 03), and the values fit in 32 bits anyway—making the instructions shorter.

The write Contract

The write syscall expects its arguments in fixed registers:

  • rax — syscall number, 1;
  • rdi — file descriptor, 1 for standard output;
  • rsi — address of the buffer’s first byte;
  • rdx — number of bytes to write.

The return value comes back in rax: a non-negative byte count on success, or a negative error code. The kernel doesn’t scan for a null terminator and doesn’t bounds-check your string—it trusts rdx. At the hardware level, syscall overwrites rcx (saving the next instruction’s address, rip) and r11 (saving RFLAGS); we cover this mechanism in detail in lesson 12.

The difference between calling printf in C and invoking syscall directly comes down to the number of layers above the kernel:

C99:   printf("hello\n") ─► [libc user-space buffer] ─┐
                                                     ├─► syscall ─► kernel (fd 1: stdout)
ASM:   _start: rax=1, rdi=1, rsi=&msg, rdx=14 ───────┘

Exiting the Process

The exit syscall (rax = 60) takes the exit status in rdi. The kernel keeps only the lowest 8 bits: passing 300 turns into 300 mod 256=44300 \bmod 256 = 44.

Here, I deliberately copy rax into rdi right after write, so the program exits with status 14—the length of the printed string.

Why `exit(14)` isn't success
Under POSIX rules, any non-zero exit code—including 14—signals failure: if you run ./build/hello_contract && echo done or put this binary in a Makefile recipe, the chain aborts. Here (and in several upcoming testbeds without libc or printf), we use the exit code purely as a convenient one-byte transport channel from a register to the terminal (echo $?). In real programs, always return 0 on success.

Checking in the Terminal

Building and running gives the expected byte count as the process exit status:

$ cd lessons/04-first-program
$ make build
$ ./build/hello_contract
hello, kernel
$ echo $?
14

strace shows the same arguments exactly as the kernel sees them:

$ strace -e write,exit ./build/hello_contract > /dev/null
write(1, "hello, kernel\n", 14)         = 14
exit(14)                                = ?
+++ exited with 14 +++
  • write(1, ...) — descriptor, buffer contents, and requested length;
  • = 14 — bytes written, which also becomes the argument to exit;
  • exit(14) — the only way out of the process; there is no return instruction in _start;
  • = ? on exit — strace prints no return value because a successful exit never returns; the actual status appears on the +++ exited with 14 +++ line.

The file is built as EXEC, with e_entry pointing straight at _start:

$ readelf -hW build/hello_contract | grep -E 'Type:|Entry'
  Type:                              EXEC (Executable file)
  Entry point address:               0x401000
$ nm build/hello_contract | grep -E ' T _start'
0000000000401000 T _start

Why a String Doesn’t Know Its Length

A second testbed writes only five bytes from the exact same buffer. The only difference from hello_contract.asm is a single constant in rdx; the buffer and entry point are identical:

nasm
section .rodata
    message: db "hello, kernel", 10

_start:
    ; remaining instructions match hello_contract.asm
    mov edx, 5
    syscall
$ strace -e write,exit ./build/hello_short > /dev/null
write(1, "hello", 5)                    = 5
exit(5)                                 = ?
+++ exited with 5 +++

The buffer in .rodata didn’t change. A byte-by-byte dump confirms there is no hidden null terminator or length prefix:

$ objcopy -O binary --only-section=.rodata build/hello_contract rodata.bin
$ xxd -g 1 rodata.bin
00000000: 68 65 6c 6c 6f 2c 20 6b 65 72 6e 65 6c 0a        hello, kernel.

objcopy -O binary extracts raw contents into a flat binary file, while --only-section=.rodata keeps only that single section—letting xxd display just the string bytes with no ELF headers.

  • 68 65 6c 6c 6f — hello, one ASCII byte per character;
  • 2c 20 — comma and space;
  • 6b 65 72 6e 65 6c — kernel;
  • 0a — newline, the only control byte in the buffer.

The length 14 matches the number of bytes in the file. Without mov edx, the syscall reads whatever was sitting in rdx on entry to _start (on this testbed it happened to be 0, so write wrote zero bytes and returned 0)—you can’t rely on that.

Unlike lesson 02, where the first 4 bytes of .rodata were occupied by _IO_stdin_used from crt1.o, this binary is linked directly with ld and no CRT, so the string starts right at offset zero of the section.

Common Pitfalls

  1. “You can skip the length: the kernel will print until the end of the string.”
    Fact: without mov edx, rdx happened to hold 0 upon entering _start on this machine (though the OS doesn’t guarantee zeroed registers at startup); the program prints nothing and exits with code 0.
    Cause: the third argument to write is an exact byte count—there is no “until null” mode.
    Fix: compute the length with equ $ - label right below the string declaration and load it into rdx.

  2. “The string in .rodata is null-terminated, and that’s enough.”
    Fact: strace on the second testbed shows write(1, "hello", 5), even though the buffer holds hello, kernel\n.
    Cause: the kernel copies exactly rdx bytes; nobody scans the buffer for a null byte.
    Fix: let the assembler compute the length instead of counting by hand, and verify it against an xxd dump.

  3. “The exit code can be any integer.”
    Fact: mov edi, 300 followed by exit makes echo $? print 44.
    Cause: the kernel keeps only the lowest 8 bits of the exit status, i.e., 300 mod 256300 \bmod 256.
    Fix: stick to codes 0–255 and don’t try to pack larger values into exit status.

  4. “The entry point is called main, just like in C.”
    Fact: ld emits a warning, though it still produces an executable:

    text
    /usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000

    The process still launches from 0x401000 and returns the expected code.
    Cause: when _start is missing, the linker falls back to the start of the .text section.
    Fix: declare global _start explicitly and verify Entry point address with readelf -hW.

Lab

Goal. Build two_lines.asm to write two lines to different streams and exit with the byte count of the second call.

Contract and requirements.

  • the first write prints the string "stdout" followed by a newline to descriptor 1;
  • the second write prints the string "stderr" followed by a newline to descriptor 2;
  • the exit code equals the number of bytes written by the second call;
  • lengths of both strings are computed by the assembler, not hardcoded by hand.

Verification criteria.

  1. ./two_lines; echo $? prints both lines and exit code 7.
  2. ./two_lines 2>/dev/null keeps only the first stream’s line.
  3. ./two_lines 2>&1 >/dev/null keeps only the second stream’s line.
  4. strace -e write,exit ./two_lines shows two write calls with different file descriptors.
Expected output and walkthrough

When both streams share the same tty or pipe, write(1, ...) and write(2, ...) are synchronous syscalls from the same process, so bytes arrive in call order. Redirections verify the split across descriptors:

text
$ ./two_lines 2>/dev/null
stdout
$ ./two_lines 2>&1 >/dev/null
stderr

Both commands exit with 7 (again, used as a teaching indicator for byte length rather than POSIX success), because the exit code comes from rax after the second write, and stderr\n is 7 bytes long.

Redirection order matters: 2>&1 >/dev/null first binds stderr to the current terminal, then sends stdout to /dev/null. Swap them, and the first stream ends up on your terminal instead.

Lab source code, Makefile, and automated tests for this lesson: lessons/04-first-program.

Summary

  1. The kernel starts a process at the _start address recorded by the linker in e_entry.
  2. write expects the syscall number in rax, descriptor in rdi, buffer address in rsi, and length in rdx.
  3. A string in memory carries no length metadata: the assembler computes the byte count via equ $ - label.
  4. exit takes the exit code in rdi and keeps only the lowest 8 bits.
  5. strace, xxd, and readelf -hW confirm syscall arguments, buffer bytes, and the entry point.
Next Up
Our program can talk to the kernel now, though when an argument is wrong we’re left guessing what sits in the registers. In lesson 05, I pause the process before an instruction executes, inspect registers and memory in GDB, and track down the cause of truncated output.