Code
assembly
; cat_file(path) rdi = path (C string)
section .rodata
buf_len: equ 4096
section .bss
buf: resb buf_len
section .text
global cat_file
cat_file:
; open(path, O_RDONLY, 0) syscall #2
mov rax, 2
mov rsi, 0 ; O_RDONLY
xor rdx, rdx
syscall
test eax, eax
js .fail ; negative -> error
mov r12, rax ; save fd in callee-saved r12
push r12 ; preserve r12 across our own calls
.read_loop:
; read(fd, buf, buf_len) syscall #0
mov rax, 0
mov rdi, r12
lea rsi, [rel buf]
mov rdx, buf_len
syscall
test rax, rax
jle .close ; 0 -> EOF, <0 -> error
mov r13, rax ; save bytes read
; write(1, buf, n) syscall #1
mov rax, 1
mov rdi, 1
lea rsi, [rel buf]
mov rdx, r13
syscall
jmp .read_loop
.close:
; close(fd) syscall #3
mov rax, 3
mov rdi, r12
syscall
pop r12
xor eax, eax
ret
.fail:
mov rax, -1
ret