The kernel doesn’t know what
printfis. 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.
; 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 progbitsmessage_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;$ - messagesubtracts the string’s start address to yield its length in bytes;- the
message_lensymbol has typea(absolute): it occupies no space in.rodataand shows up innmwith 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,1for 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 .
Here, I deliberately copy rax into rdi right after write, so the program exits with status 14—the length of the printed string.
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 $?
14strace 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 toexit;exit(14)— the only way out of the process; there is no return instruction in_start;= ?onexit—straceprints no return value because a successfulexitnever 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 _startWhy 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:
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
-
“You can skip the length: the kernel will print until the end of the string.”
Fact: withoutmov edx,rdxhappened to hold0upon entering_starton this machine (though the OS doesn’t guarantee zeroed registers at startup); the program prints nothing and exits with code0.
Cause: the third argument towriteis an exact byte count—there is no “until null” mode.
Fix: compute the length withequ $ - labelright below the string declaration and load it intordx. -
“The string in
.rodatais null-terminated, and that’s enough.”
Fact:straceon the second testbed showswrite(1, "hello", 5), even though the buffer holdshello, kernel\n.
Cause: the kernel copies exactlyrdxbytes; nobody scans the buffer for a null byte.
Fix: let the assembler compute the length instead of counting by hand, and verify it against anxxddump. -
“The exit code can be any integer.”
Fact:mov edi, 300followed byexitmakesecho $?print44.
Cause: the kernel keeps only the lowest 8 bits of the exit status, i.e., .
Fix: stick to codes0–255and don’t try to pack larger values into exit status. -
“The entry point is called
main, just like in C.”
Fact:ldemits a warning, though it still produces an executable:text/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000The process still launches from
0x401000and returns the expected code.
Cause: when_startis missing, the linker falls back to the start of the.textsection.
Fix: declareglobal _startexplicitly and verifyEntry point addresswithreadelf -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
writeprints the string"stdout"followed by a newline to descriptor1; - the second
writeprints the string"stderr"followed by a newline to descriptor2; - 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.
./two_lines; echo $?prints both lines and exit code7../two_lines 2>/dev/nullkeeps only the first stream’s line../two_lines 2>&1 >/dev/nullkeeps only the second stream’s line.strace -e write,exit ./two_linesshows twowritecalls 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:
$ ./two_lines 2>/dev/null
stdout
$ ./two_lines 2>&1 >/dev/null
stderrBoth 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
- The kernel starts a process at the
_startaddress recorded by the linker ine_entry. writeexpects the syscall number inrax, descriptor inrdi, buffer address inrsi, and length inrdx.- A string in memory carries no length metadata: the assembler computes the byte count via
equ $ - label. exittakes the exit code inrdiand keeps only the lowest 8 bits.strace,xxd, andreadelf -hWconfirm syscall arguments, buffer bytes, and the entry point.