Adds reads()

This commit is contained in:
2025-07-31 11:34:50 +02:00
parent ca6027abcd
commit 6f2e427d86
2 changed files with 93 additions and 0 deletions

View File

@@ -10,6 +10,7 @@ section .rodata
section .bss
printfBuff resb printfBuffLen
printfArgs resq 5 ;5=>rsi,rdx,rcx,r8,r9
readsCBuff resb 1
section .text
global __INTERNAL_fmt
@@ -17,6 +18,7 @@ section .text
global puts
global printf
global eprintf
global reads
;----- print(*str[]) -----;
; Prints given string to the console to stdout
@@ -493,3 +495,51 @@ __INTERNAL_fmt:
pop r12
leave
ret
;----- reads(*inputBuffer[], len) -----;
; Reads from console (stdin), stores input to inputBuffer[]
; ~~Return value: Amount of written characters (+EOS) to inputBuffer[] (so RAX-1 => amount of read characters)~~
; Return value: Amount of read characters
; Used registers:
; rax* (ret)
; rdi* (arg) Pointer to inputBuffer[]
; rsi* (arg) Size of inputBuffer[] (or less to read less characters)
; rdx* arg for syscall
; r12 Stores inputBuffer[]
; r13 Stores len
; r14 Counts amount of read characters
reads:
push r12
push r13
push r14
lea r12, [rdi]
mov r13, rsi
dec r13 ;account for EOS
xor r14, r14
.readLoop:
mov rax, NR_read
mov rdi, FD_stdin
lea rsi, [rel readsCBuff]
mov rdx, 1
syscall
mov al, [readsCBuff]
cmp al, NL
je .finish
cmp r14, r13
jae .readLoop ;Keep reading from stdin until \n is found as to flush stdin (too bad sys_lseek is not allowed on stdin, returns ESPIPE;illegal seek)
mov byte [r12], al
inc r12
inc r14
jmp .readLoop
.finish:
mov byte [r12], EOS
mov rax, r14
pop r14
pop r13
pop r12
ret