Menu
Coddy logo textTech

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:

ArgumentRegisterWhat it doesExample
File descriptorrdiWhere to write (1 = screen)mov rdi, 1
Buffer addressrsiWhere the text is in memorymov rsi, message
Byte countrdxHow many bytes to printmov 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 print

To 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:

  1. The CPU jumps into the Linux kernel
  2. The kernel sees: "write syscall"
  3. It reads rdi (where to write), rsi (where the text is), and rdx (how many bytes)
  1. It prints the text to the screen
  2. 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
    syscall

This program prints Hello and then exits.

challenge icon

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
    syscall
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals