From 0047b755c96603066ffbdc25b4a6ad4a87be918f Mon Sep 17 00:00:00 2001 From: Stephen Heumann Date: Sat, 25 Jun 2022 21:37:47 -0500 Subject: [PATCH] Fix bug with fseek(..., SEEK_CUR) on read-only streams. This would seek to the wrong location, and in some cases try to seek before the beginning of the file, leading to an error condition. The problem stemmed from fseek calling fflush, which sets up the stream's buffer state in a way appropriate for writing but not for reading. It then calls ftell, which (for a read-only stream) would misinterpret this state and miscalculate the current position. The fix is to make fflush work correctly on a read-only stream, setting up the state for reading. (User code calling fflush on a read-only stream would be undefined behavior, but since fseek does it we need to make it work.) This fixes #6. --- stdio.asm | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/stdio.asm b/stdio.asm index 9a83e7b..755336c 100644 --- a/stdio.asm +++ b/stdio.asm @@ -4484,7 +4484,7 @@ orVal ds 2 for setting the case of characters iny txa sta [stream],Y - ldy #FILE_base set the end of buffer mark + ldy #FILE_base set the end of buffer mark lda [stream],Y ldy #FILE_size clc @@ -4500,13 +4500,20 @@ orVal ds 2 for setting the case of characters dey dey sta [stream],Y - ldy #FILE_size set the number of chars the buffer + ldy #FILE_flag if read stream + lda [stream],Y + bit _IOREAD + beq ib1 + lda #0 set count of chars in buffer to 0 + tax + bra ib2 else +ib1 ldy #FILE_size set the number of chars the buffer lda [stream],Y can hold tax iny iny lda [stream],Y - ldy #FILE_cnt+2 +ib2 ldy #FILE_cnt+2 sta [stream],Y dey dey