0
votes

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
You are reserving only 4 bytes for each of .buffer and .FD. But .FD is an 8 byte value and buffer is supposed to be 100 bytes long. How comes the mismatch?fuz
Would this be a solution? .buffer resb 100 .FD resb 8Vexea
yes, that should solve at least this part of your problem.fuz
I think your program lacks an exit system call.fuz
Oh right, the problem is your .buffer only had space for 4 bytes, so of course read overwrote into the resd 1 space for the fd. IDK why you're keeping FD in memory at all; R8, R9, and R10 are free.Peter Cordes