I am new to assembly and trying to make a function that prints a file to stdout.
After the first iteration, it reads and prints 100 bytes succesfully. When it loops again after that, the read syscall throws a -9 error code (Or a bad file number error)
prtopenf:
section .data
.bufsize dq 100
section .bss
.buffer resd 1
.FD resd 1
section .text
; rdi is argument FD
push rbp
mov rbp, rsp
mov [.FD], rdi ; save local file descriptor
; seek beginning of the file
mov rax, 8 ; file lseek
mov rdi, [.FD]
mov rsi, 0 ; begin of file
syscall
; keep printing until call returns 0 read
.prtloop:
; read buffer
xor rax, rax
mov rdi, [.FD]
mov rsi, .buffer
mov rdx, [.bufsize]
syscall
; look for errors or end of file
cmp rax, 0
jl .readerror
je .done
; write buffer
mov rax, 1 ; write
mov rdi, 1 ; stdout file descriptor
mov rsi, .buffer ; buffer memory address
mov rdx, [.bufsize] ; size of buffer
syscall
jmp .prtloop
.readerror:
mov rsp, rbp
pop rbp
ret
.done:
mov rsp, rbp
pop rbp
ret
.buffer
and.FD
. But.FD
is an 8 byte value and buffer is supposed to be 100 bytes long. How comes the mismatch? – fuzexit
system call. – fuz.buffer
only had space for 4 bytes, so of courseread
overwrote into theresd 1
space for the fd. IDK why you're keeping FD in memory at all; R8, R9, and R10 are free. – Peter Cordes