Write Syscall (1)
Part of the Fundamentals section of Coddy's Assembly journey — lesson 35 of 45.
You already know how to exit a program. But exiting silently is not very useful. You want your program to print output so the user can see something.
For that, you need the write syscall.
What is the write syscall?
The write syscall tells the operating system to print text to the screen (or write to a file). It is how your program produces output.
The syscall number for write is 1.
How write works:
Unlike the exit syscall (which only needs one argument), write needs three arguments:
| Argument | Register | What it does | Example |
|---|---|---|---|
| File descriptor | rdi | Where to write (1 = screen) | mov rdi, 1 |
| Buffer address | rsi | Where the text is in memory | mov rsi, message |
| Byte count | rdx | How many bytes to print | mov rdx, 13 |
The write syscall in action:
mov rax, 1 ; syscall number for write
mov rdi, 1 ; file descriptor 1 = stdout (screen)
mov rsi, msg ; address of the string to print
mov rdx, 13 ; number of bytes to print
syscall ; ask the OS to printTo print a message on the screen, we need 5 lines. First, we put the syscall number 1 into rax for write. Then we put 1 into rdi to tell the OS to print to the screen.
Next, we put the address of the string (msg) into rsi. After that, we put the number of bytes (13) into rdx. Finally, we execute syscall to ask the OS to print.
What happens when you execute write:
- The CPU jumps into the Linux kernel
- The kernel sees: "write syscall"
- It reads
rdi(where to write),rsi(where the text is), andrdx(how many bytes)
- It prints the text to the screen
- It returns control to your program
Putting it together with a string:
section .data
msg db 'Hello', 0x0a ; string with newline
section .text
global _start
_start:
mov rax, 1 ; write syscall
mov rdi, 1 ; stdout
mov rsi, msg ; address of string
mov rdx, 6 ; length (Hello + newline = 6 bytes)
syscall
mov rax, 60 ; exit syscall
mov rdi, 0
syscallThis program prints Hello and then exits.
Challenge
Write a program that prints the message "Hi" followed by a newline. Use the write syscall.
The string is already defined for you in the test harness. You only need to write the syscall setup.
Try it yourself
section .data
msg db 'Hi', 0x0a
msgLen equ $ - msg
section .text
global _start
_start:
; TODO: Set up and call the write syscall to print msg
; Use rax=1, rdi=1, rsi=msg, rdx=msgLen
; Exit the program
mov rax, 60
mov rdi, 0
syscallThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
1The Machine
What is CPUMemoryRegisters vs MemoryHow instructions workTwo-File PatternThe x86-64 Architecture