Menu
CoddyTech

The Read Syscall

Part of the Functions, Stack and Strings section of Coddy's Assembly journey. Lesson 27 of 33.

Until now the locked main.asm read your input and called your code. In this project you write the whole program yourself, starting at _start, and build a small version of wc, the Unix tool that counts the lines, words and characters of a text.

The read syscall is the opposite of write: it copies bytes from an input into memory. Its number is 0, and file descriptor 0 is standard input (stdin):

mov rax, 0          ; syscall number for read
mov rdi, 0          ; file descriptor 0: stdin
mov rsi, buffer     ; where the bytes go
mov rdx, 4096       ; the most bytes to read
syscall

The buffer is space you reserve in the .bss section. buffer resb 4096 reserves 4096 bytes, set to zero when the program starts, without storing them in the program file.

section .bss
    buffer resb 4096

After the syscall, rax holds how many bytes were read, and 0 means the input was empty. read adds no zero byte at the end, so the count is the only way to know where the input stops. Keep it in a register that the next syscall does not change, such as rbx: a syscall overwrites rax, rcx and r11.

The last byte read is at [buffer + rbx - 1] when the count is in rbx. Checking it tells you whether the input ended with a newline (byte 10):

cmp byte [buffer + rbx - 1], 10
je .ends_with_newline
challenge icon

Challenge

Easy

Write a program that prints its input back. In _start, read up to 4096 bytes into buffer (rax = 0, rdi = 0, rsi = buffer, rdx = 4096), then write the bytes read to stdout (rax = 1, rdi = 1, rsi = buffer, rdx = the count). If the input is not empty and its last byte is not a newline, also print a newline. Exit with code 0.

Example: for the input hello the program prints hello and a newline.

Write the whole program in main.asm. The locked lib.asm holds print_number and print_char.

Try it yourself

bits 64
section .bss
    buffer resb 4096
section .text
    global _start
_start:
    ; Read the input into buffer, then write it back.
    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 Functions, Stack and Strings

Practice on your own: Assembly playground