1
0
mirror of https://github.com/simh/simh.git synced 2026-05-15 09:56:35 +00:00

FIO: Fix Big Endian sim_fwrite() error

This problem was discovered by Codex initiated by Perry Metzger.

sim_fwrite() in sim_fio.c has a bug in the big-endian/swapped write
path. When a write spans more than one internal flip buffer, the
function advances its source pointer by size * count on every chunk
instead of by size * c, where c is the number of elements actually
written in that chunk.

This causes later chunks to read from the wrong part of the caller's
buffer, which corrupts the file contents.

Why this is wrong
    sim_fwrite() may break the caller's write into multiple pieces:

    nelem   is the number of elements that fit in the flip buffer
    nbuf    is the number of chunks to write
    c       is the number of elements in the current chunk

    After writing one chunk, the source pointer must advance by the
    size of that chunk:

        sptr = sptr + size * c;

    But the original code advanced by the size of the entire original request
    every time:

        sptr = sptr + size * count;

    That is only correct if there is exactly one chunk.
This commit is contained in:
Perry E. Metzger
2026-04-16 16:02:54 -10:00
committed by Mark Pizzolato
parent 722302c45b
commit d1d85b5a0e

View File

@@ -289,7 +289,7 @@ sptr = (const unsigned char *) bptr; /* init input ptr */
for (i = (int32)nbuf; i > 0; i--) { /* loop on buffers */
c = (i == 1)? lcnt: nelem;
sim_buf_copy_swapped (sim_flip, sptr, size, c);
sptr = sptr + size * count;
sptr = sptr + size * c;
c = fwrite (sim_flip, size, c, fptr);
if (c == 0) {
free(sim_flip);