From 50f92507b742f66ecf4fb322047c5b0675fd34cb Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 11:58:49 +0100 Subject: [PATCH 1/2] vm: keep #ungetc's bytes out of the file, and count them in #pos A File holds its content in buf, and #ungetc spliced the pushed-back bytes into it with no record of where they were. A later buffered write flushed buf whole, so the bytes reached the disk, and the cursor ignored them: MRI's position is the descriptor's offset minus what the read buffer still holds, so every write after an ungetc landed late. io_pushback.go records the region the bytes occupy and implements io.c's io_unread: writes, #flush, #seek, #rewind, #pos=, #truncate, #syswrite and #pwrite drop the pushback and move to the logical position; #pos (io_tell) drops it when that position is valid and answers it negative otherwise; #sysread and #sysseek refuse "for buffered IO"; flushes, #pread's fallback and File#size see the file without it. IO#reopen and set_encoding_by_bom, which replace the buffer, reset the region, and reopen(io) adopts the file's bytes, not the other stream's pushback. StringIO keeps its own semantics, now MRI's: strio_unget_bytes writes the pushback into the string over the bytes just read, where it was spliced in like a file's. Refs #974 Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + internal/vm/io.go | 25 +++- internal/vm/io_descriptors.go | 38 +++-- internal/vm/io_pushback.go | 178 +++++++++++++++++++++++ internal/vm/io_pushback_internal_test.go | 32 ++++ internal/vm/io_pushback_test.go | 114 +++++++++++++++ 6 files changed, 369 insertions(+), 19 deletions(-) create mode 100644 internal/vm/io_pushback.go create mode 100644 internal/vm/io_pushback_internal_test.go create mode 100644 internal/vm/io_pushback_test.go diff --git a/README.md b/README.md index 061ce711..51f639bd 100644 --- a/README.md +++ b/README.md @@ -876,6 +876,7 @@ Otherwise: | `File::Stat#==` | `a == b` is `false` for two stats of the same file (MRI: `true`); `a.==(b)` answers `true` | | `File#stat` on a file unlinked while open | raises `Errno::ENOENT`; MRI answers from the open descriptor. rbgo's streams are buffered by path and hold no descriptor | | `IO#pwrite` / `IO#pread` on a file unlinked or replaced while open | both reach the file **by its path**, since streams hold no descriptor. A `#pwrite`'s bytes are on disk when it returns, and only those bytes: the stream's other pending writes stay pending, as with `pwrite(2)`. `#pread` sees another writer's bytes and this stream's own pending writes, which it flushes first, as `rb_io_pread` does ([#949](https://github.com/go-embedded-ruby/ruby/issues/949)). The difference is with a path that no longer names the opened file. Unlinked, both fall back to the stream's buffer, where MRI still reaches the old inode. Replaced, they reach the new file. Same root as the row above. Two deliberate divergences. First, `#pread`'s length is bounded by the file's size, so `f.pread(2**40, 0)` returns at once, where MRI 4.0.7 tries to allocate the full length. Second, a hole lives in memory when it has to: a `#pwrite` that would open a hole larger than 64 MiB past the end of the stream's in-memory copy is refused with `Errno::EFBIG` once the path is gone, where MRI writes a sparse file through its descriptor. When the file is reachable, the hole goes to disk as in MRI, and a refusal from the file (EFBIG, ENOSPC, EIO) is raised with its errno ([#973](https://github.com/go-embedded-ruby/ruby/issues/973)) | +| `IO#ungetc` / `#ungetbyte` on a `File` longer than 8192 bytes | as in MRI, pushed-back bytes are read-buffer bytes and never reach the file. `#pos` subtracts them, and is negative when more was pushed back than read. A write, `#flush`, `#seek`, `#rewind`, `#truncate` or `#pwrite` drops them first. `#sysread` and `#sysseek` refuse with "for buffered IO" ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The divergence is MRI's read-buffer capacity: MRI reads 8192 bytes ahead, so on a larger file, pushing back more than was read raises `IOError: ungetbyte failed`. rbgo accepts it, and a following write lands at end-of-file. On a file of at most 8192 bytes the two agree | | an unflushed file whose directory is removed before the program ends | loses its bytes; MRI, holding a descriptor to an unlinked file, still writes them. Teardown re-opens the path to flush it, so it gets `ENOENT` — and reports nothing, as MRI's shutdown ignores a failing `fflush`. Same root again: streams are buffered by path, which is also [#635](https://github.com/go-embedded-ruby/ruby/issues/635) | | `Errno` | all **158** of MRI's constant names are present, but **32** report errno `0` where MRI has a real number (`EAUTH`, `EBADRPC`, `EDEVERR`, …). Measured by set difference on darwin: 81 names are zero-valued under rbgo, 49 under MRI, and every MRI zero is also zero under rbgo. Go's portable `syscall` package does not expose the platform-only names | | `pp` | neither `Kernel#pp` nor `require "pp"` exists (`require "prettyprint"` does work) | diff --git a/internal/vm/io.go b/internal/vm/io.go index 932a79fd..ae544c00 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -143,6 +143,10 @@ type IOObj struct { // holds its whole output; bytes written to the stream are kept in popen.stdin, // out of the buffer being read, and cannot reach a child that is already gone. popen *popenProc + + // ungetLo/ungetHi bound the bytes #ungetc/#ungetbyte spliced into buf on a + // file stream, which are not the file's (io_pushback.go). Empty when equal. + ungetLo, ungetHi int } // pipeBuf is the shared byte channel behind an IO.pipe reader/writer pair. Each @@ -209,7 +213,8 @@ func (o *IOObj) writeBytes(p []byte) int { return len(p) } if o.isStr { - if o.appendMode { // append mode: every write lands at end, ignoring position + o.unreadPushback(true) // rb_io_check_writable → io_unread (#974) + if o.appendMode { // append mode: every write lands at end, ignoring position o.pos = len(o.buf) } if end := o.pos + len(p); end > len(o.buf) { @@ -666,7 +671,7 @@ func (vm *VM) registerIO() { if st, err := os.Stat(o.path); err == nil { return object.IntValue(st.Size()) } - return object.IntValue(int64(len(o.buf))) + return object.IntValue(int64(len(o.diskBytes()))) }) cFile.define("flock", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { return vm.fileFlock(self.(*IOObj), clampInt(vm.toIntCoerce(args[0]))) @@ -1285,12 +1290,13 @@ func ioFlush(o *IOObj) { return } o.wbufDirty = false - err := os.WriteFile(o.path, o.buf, 0o644) + content := o.diskBytes() // never the bytes #ungetc pushed back (#974) + err := os.WriteFile(o.path, content, 0o644) if err == nil { return } if errors.Is(err, fs.ErrPermission) { - err = withOwnerWrite(o.path, err, func() error { return os.WriteFile(o.path, o.buf, 0o644) }) + err = withOwnerWrite(o.path, err, func() error { return os.WriteFile(o.path, content, 0o644) }) } if err != nil { raiseOpenErrno(err, o.path) @@ -1703,6 +1709,7 @@ func defIOWrite(cls *RClass) { o := self.(*IOObj) ioClosedRealIO(o) // MRI: IO#flush raises on a closed stream; StringIO#flush does not ioFlush(o) + o.unreadPushback(true) // rb_io_flush_raw: io_unread when readable (#974) return self }) cls.define("fsync", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { @@ -2064,7 +2071,9 @@ func defStringIORead(cls *RClass) { if o.closed && !ioIsStringIO(o) { raise("IOError", "closed stream") } - return object.IntValue(int64(o.pos)) + // rb_io_tell: the descriptor's offset minus what the read buffer still + // holds, pushback included — negative when more was pushed back than read. + return object.IntValue(int64(o.tellPos())) }) // #tell is a true alias of #pos, as in MRI. defineBuiltinSecondName(cls, "tell", "pos") @@ -2077,6 +2086,7 @@ func defStringIORead(cls *RClass) { if n < 0 { raise("Errno::EINVAL", "Invalid argument") } + o.unreadPushback(true) // io_seek → flush_before_seek → io_unread (#974) o.pos = n return args[0] }) @@ -2096,6 +2106,9 @@ func defStringIORead(cls *RClass) { whence = vm.seekWhence(args[1]) } } + // io_seek → flush_before_seek → io_unread: the pushback is dropped and + // SEEK_CUR counts from the logical position (#974). + o.unreadPushback(true) var newPos int switch whence { case 1: // SEEK_CUR @@ -2116,6 +2129,7 @@ func defStringIORead(cls *RClass) { cls.define("rewind", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { o := self.(*IOObj) ioClosedRealIO(o) // real IO/File raises on a closed stream; StringIO tolerates it + o.unreadPushback(true) // io_seek(fptr, 0, 0) → io_unread (#974) o.pos, o.lineno = 0, 0 // #rewind resets both the position and the line number return object.IntValue(0) }) @@ -2133,6 +2147,7 @@ func defStringIORead(cls *RClass) { if n < 0 { raise("Errno::EINVAL", "Invalid argument") } + o.unreadPushback(true) // rb_io_check_writable → io_unread (#974) if n < len(o.buf) { o.buf = o.buf[:n] } else if n > len(o.buf) { diff --git a/internal/vm/io_descriptors.go b/internal/vm/io_descriptors.go index d921f22d..b06f8c32 100644 --- a/internal/vm/io_descriptors.go +++ b/internal/vm/io_descriptors.go @@ -140,6 +140,11 @@ func defIOReadExtra(cls *RClass) { } return ioReadResult(nil, nil) } + // rb_io_sysread: READ_DATA_BUFFERED. Pushed-back bytes are buffered data + // the descriptor never had (#974). + if o.pushbackUnread() > 0 { + raise("IOError", "sysread for buffered IO") + } if o.pos >= len(o.buf) { // MRI empties the output buffer (io_set_read_length to 0) before // signalling end-of-file. @@ -345,12 +350,13 @@ func defIOSeekable(cls *RClass) { // Unreadable by path (removed between the two calls, permission): // the buffer below is what this stream last saw. } - if off >= int64(len(o.buf)) { + content := o.diskBytes() // pread reads the file, never the pushback (#974) + if off >= int64(len(content)) { raise("EOFError", "end of file reached") } // off+n is never formed: with n near MaxInt it overflowed into a slice // bounds panic (#973). What is left past off bounds the read instead. - rest := o.buf[off:] + rest := content[off:] return ioReadResult(rest[:min(n, len(rest))], buf) }) cls.define("pwrite", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { @@ -365,7 +371,8 @@ func defIOSeekable(cls *RClass) { if off < 0 { raise("Errno::EINVAL", "Invalid argument - pwrite") } - o.writable = true // a written File flushes its buffer back on flush/close + o.unreadPushback(true) // rb_io_check_writable → io_unread (#974) + o.writable = true // a written File flushes its buffer back on flush/close vm.trackOpenFile(o) // #949: MRI's rb_io_pwrite is pwrite(2), so the bytes are on disk the // moment it returns, and ONLY those bytes: the stream's other pending @@ -407,6 +414,11 @@ func defIOSeekable(cls *RClass) { if len(args) > 1 { whence = vm.seekWhence(args[1]) // accepts :SET/:CUR/:END symbols } + // rb_io_sysseek: READ_DATA_BUFFERED on a readable stream. Pushed-back + // bytes are buffered data the descriptor never had (#974). + if !o.rdClosed && o.pushbackUnread() > 0 { + raise("IOError", "sysseek for buffered IO") + } switch whence { case 1: // SEEK_CUR o.pos += amount @@ -471,6 +483,7 @@ func defIOSeekable(cls *RClass) { if o.path != "" && !o.writable { if b, err := os.ReadFile(o.path); err == nil { o.buf = b + o.ungetLo, o.ungetHi = 0, 0 // fresh content: no pushback in it (#974) } } enc := ioStripBOM(o) @@ -517,16 +530,7 @@ func detectBOM(p []byte) (int, string) { // ioUnget inserts p immediately before the cursor (leaving the cursor on the // re-inserted bytes) so a following read returns them first — the pushback model // shared by ungetbyte and ungetc. -func ioUnget(o *IOObj, p []byte) { - if len(p) == 0 { - return - } - out := make([]byte, 0, len(o.buf)+len(p)) - out = append(out, o.buf[:o.pos]...) - out = append(out, p...) - out = append(out, o.buf[o.pos:]...) - o.buf = out -} +func ioUnget(o *IOObj, p []byte) { o.unget(p) } // ioReadResult returns data as a fresh String, or fills the caller's output // buffer String and returns it — the shared return convention of the length-taking @@ -710,7 +714,12 @@ func ioReopenIO(vm *VM, o, other *IOObj) object.Value { o.reopened = other return o } - o.buf, o.pos, o.lineno = other.buf, other.pos, other.lineno + // io_reopen reads the position with io_tell(orig), which drops orig's + // pushback when the position is valid; what is left of it is orig's read + // buffer, not file content, so the adopted copy is the file's (#974). + other.unreadPushback(false) + o.buf, o.pos, o.lineno = other.diskBytes(), other.pos, other.lineno + o.ungetLo, o.ungetHi = 0, 0 o.rdClosed, o.wrClosed, o.writable = other.rdClosed, other.wrClosed, other.writable o.appendMode, o.openMode, o.binmode = other.appendMode, other.openMode, other.binmode o.extEnc, o.intEnc = other.extEnc, other.intEnc @@ -769,6 +778,7 @@ func ioReopenPath(vm *VM, o *IOObj, pos []object.Value, opts *object.Hash) objec } fresh := openFileIO(o.cls, name, modeBase(mode)) o.buf, o.pos, o.path = fresh.buf, fresh.pos, fresh.path + o.ungetLo, o.ungetHi = 0, 0 // the read buffer, pushback included, is dropped (#974) if keepHalves { o.writable, o.appendMode, o.openMode = !o.wrClosed, false, "" } else { diff --git a/internal/vm/io_pushback.go b/internal/vm/io_pushback.go new file mode 100644 index 00000000..3d06bf9a --- /dev/null +++ b/internal/vm/io_pushback.go @@ -0,0 +1,178 @@ +package vm + +// Pushback on a file stream (#974). +// +// A File here holds its whole content in buf, and #ungetc / #ungetbyte splice +// the pushed-back bytes into buf ahead of the cursor so the next read returns +// them. Those bytes are not the file's: in MRI they live in the read buffer +// (fptr->rbuf) and never reach the descriptor. Two things followed from +// splicing them in without remembering where they were: +// +// - a later buffered write flushed buf whole, so the pushed-back bytes landed +// on disk ("getc; ungetc 'Z'; seek end; write" left a Z in the file); +// - the cursor ignored them, where MRI's position is the descriptor's offset +// MINUS what is still in the read buffer, so #pos and the place a write +// lands were wrong by the number of bytes pushed back. +// +// The bytes stay spliced in buf, because every read method walks buf from pos +// and that must keep returning them first. What is added is the region +// [ungetLo, ungetHi) of buf they occupy, and the io.c operations that consume +// it: +// +// - io_unread(fptr, discard_rbuf) is unreadPushback. Every write +// (rb_io_check_writable), #flush, #seek, #rewind, #pos= and #truncate call it +// with discard: the pushback is dropped and the cursor goes to the logical +// position L = (where the cursor was in the file) − (pushback still unread). +// - io_tell is the same with discard false, so #pos drops the pushback when L +// is a valid offset and keeps it when L is negative — and answers L either +// way, as rb_io_tell's "pos -= fptr->rbuf.len" does. +// +// L is negative when more bytes were pushed back than had been read. lseek +// then fails and the descriptor stays where the read-ahead left it, which is +// where a following write lands: 0 when nothing had been read, and otherwise +// end-of-file — MRI reads a file of up to 8192 bytes whole, and a larger one +// refuses that much pushback with "ungetbyte failed" (io_ungetbyte's capacity +// check), which this model does not reproduce. +// +// Only file streams are tracked. StringIO#ungetc writes into its string +// (strio_unget_bytes) and a pipe cannot seek (FMODE_DUPLEX makes io_unread a +// no-op), so both keep the plain splice. + +// pushbackTracked reports whether o is a file stream whose pushback must be +// kept out of the file. +func (o *IOObj) pushbackTracked() bool { + return o.isStr && o.path != "" && o.strObj == nil && o.pipe == nil && o.popen == nil +} + +// compactPushback removes the pushed-back bytes reads have already consumed, +// leaving the unread rest (if any) starting exactly at pos. Consumed pushback +// is not file content either: left in buf, a later #seek back and #read would +// return it, and a flush would write it. +// With no region (both bounds 0) it falls through to the reset at the end. +func (o *IOObj) compactPushback() { + if o.pos < o.ungetLo { + // The cursor was moved back past the pushback by a path that did not + // unread first; the bytes are still not the file's, so drop them. + o.buf = append(o.buf[:o.ungetLo], o.buf[o.ungetHi:]...) + o.ungetLo, o.ungetHi = 0, 0 + return + } + end := min(o.pos, o.ungetHi) + if c := end - o.ungetLo; c > 0 { + o.buf = append(o.buf[:o.ungetLo], o.buf[end:]...) + o.pos -= c + o.ungetHi -= c + } + if o.ungetHi <= o.pos { + o.ungetLo, o.ungetHi = 0, 0 + return + } + o.ungetLo = o.pos +} + +// pushbackUnread is the number of pushed-back bytes not yet read again — the +// part of fptr->rbuf.len this model can account for. Only unget on a tracked +// stream records a region, so an untracked one always answers 0. +func (o *IOObj) pushbackUnread() int { + o.compactPushback() + return o.ungetHi - o.ungetLo +} + +// unreadPushback is io_unread: see the file comment. +func (o *IOObj) unreadPushback(discard bool) { + u := o.pushbackUnread() + if u == 0 { + return + } + logical := o.pos - u + if logical < 0 && !discard { + return // lseek failed: io_unread keeps the read buffer + } + o.buf = append(o.buf[:o.pos], o.buf[o.ungetHi:]...) + o.ungetLo, o.ungetHi = 0, 0 + switch { + case logical >= 0: + o.pos = logical + case o.pos > 0: + o.pos = len(o.buf) // the read-ahead reached end-of-file + } +} + +// tellPos is rb_io_tell: the logical position, which is negative when more +// was pushed back than read. +func (o *IOObj) tellPos() int { + o.unreadPushback(false) + return o.pos - o.pushbackUnread() +} + +// diskBytes is the stream's content as the file holds it: buf without the +// pushed-back bytes. It copies only when there are some. +func (o *IOObj) diskBytes() []byte { + u := o.pushbackUnread() + if u == 0 { + return o.buf + } + out := make([]byte, 0, len(o.buf)-u) + out = append(out, o.buf[:o.ungetLo]...) + return append(out, o.buf[o.ungetHi:]...) +} + +// unget splices p in ahead of the cursor, recording the region on a tracked +// stream. +func (o *IOObj) unget(p []byte) { + if len(p) == 0 { + return + } + if o.strObj != nil { + o.strioUngetBytes(p) + return + } + tracked := o.pushbackTracked() + if tracked { + o.compactPushback() + if o.ungetHi <= o.ungetLo { + o.ungetLo, o.ungetHi = o.pos, o.pos + } + } + out := make([]byte, 0, len(o.buf)+len(p)) + out = append(out, o.buf[:o.pos]...) + out = append(out, p...) + out = append(out, o.buf[o.pos:]...) + o.buf = out + if tracked { + o.ungetHi += len(p) + } +} + +// strioUngetBytes is ext/stringio strio_unget_bytes: a StringIO's pushback is +// written INTO its string, over the bytes just read, and the position moves +// back by its length. Only when more is pushed back than the position allows +// does the string grow, the unread rest moving right to make room. Splicing +// the bytes in instead — what this did for StringIO before #974 — left the +// string one character longer and the position unchanged: +// StringIO.new("0123") getc, ungetc "Z", write "AB" gave "0AB23" at pos 1, +// where MRI has "AB23" at pos 0. +func (o *IOObj) strioUngetBytes(cp []byte) { + cl, pos, n := len(cp), o.pos, len(o.buf) + rest := pos - n + if cl > pos { + ex := cl - n + if rest < 0 { + ex = cl - pos + } + grown := make([]byte, n+ex) + copy(grown, o.buf) + if rest < 0 { + copy(grown[cl:], o.buf[pos:]) + } + o.buf, pos = grown, 0 + } else { + if rest > 0 { // pos past the end: the gap is NUL-filled + o.buf = append(o.buf, make([]byte, rest)...) + } + pos -= cl + } + copy(o.buf[pos:], cp) + o.pos = pos + o.syncStr() +} diff --git a/internal/vm/io_pushback_internal_test.go b/internal/vm/io_pushback_internal_test.go new file mode 100644 index 00000000..fd489dd6 --- /dev/null +++ b/internal/vm/io_pushback_internal_test.go @@ -0,0 +1,32 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import "testing" + +// TestCompactPushbackDropsARegionTheCursorWentBackPast: every path that moves a +// file stream's cursor backwards unreads first, so this state is not reachable +// from Ruby today. It is the one a future path that forgets would create, and +// without the guard the region would be stretched over file bytes — +// [pos, ungetHi) — and those bytes dropped from the file at the next write. +func TestCompactPushbackDropsARegionTheCursorWentBackPast(t *testing.T) { + o := &IOObj{isStr: true, path: "f", buf: []byte("01Z234"), pos: 0, ungetLo: 2, ungetHi: 3} + if u := o.pushbackUnread(); u != 0 { + t.Fatalf("pushbackUnread = %d, want 0", u) + } + if got := string(o.buf); got != "01234" || o.pos != 0 { + t.Errorf("buf=%q pos=%d, want \"01234\" pos=0", got, o.pos) + } +} + +// TestDiskBytesDoesNotCopyWithoutPushback: diskBytes runs on every flush, so +// with no pushback it must hand back the buffer itself rather than a copy of +// the whole file. +func TestDiskBytesDoesNotCopyWithoutPushback(t *testing.T) { + o := &IOObj{isStr: true, path: "f", buf: make([]byte, 1<<16), pos: 10} + if n := testing.AllocsPerRun(100, func() { _ = o.diskBytes() }); n != 0 { + t.Errorf("diskBytes allocated %v times per call, want 0", n) + } +} diff --git a/internal/vm/io_pushback_test.go b/internal/vm/io_pushback_test.go new file mode 100644 index 00000000..0fd33866 --- /dev/null +++ b/internal/vm/io_pushback_test.go @@ -0,0 +1,114 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "fmt" + "path/filepath" + "testing" +) + +// TestUngetcOnAFileIsNotTheFiles: bytes #ungetc pushes back onto a File are +// read-buffer bytes, never the file's, and the position counts them (#974). +// Every want is MRI 4.0.7's output for the same program (arm64-darwin25, +// rubydiff, 2026-11-22). Before the fix rbgo wrote "0AB23456789" for the +// first row — the write landed after the pushback instead of over it — and +// the seek-to-end row left the pushed-back Z in the file. +func TestUngetcOnAFileIsNotTheFiles(t *testing.T) { + p := filepath.ToSlash(filepath.Join(t.TempDir(), "f")) + cases := []struct{ name, act, want string }{ + {"a write lands where the pushback starts", + `f.getc; f.ungetc("Z"); f.write("AB")`, `"AB23456789\nabc\n"`}, + {"after read(2)", `f.read(2); f.ungetc("Z"); f.write("AB")`, `"0AB3456789\nabc\n"`}, + {"after gets", `f.gets; f.ungetc("Z"); f.write("AB")`, `"0123456789ABbc\n"`}, + {"consumed pushback is not file content either", + `f.read(3); f.ungetc("Z"); print f.read(2).inspect; f.write("AB")`, `"Z3""0123AB6789\nabc\n"`}, + {"partly consumed pushback", `f.getc; f.ungetc("ZY"); print f.getc, f.pos; f.write("AB")`, + `Z0"AB23456789\nabc\n"`}, + {"two ungetc stack", `f.getc; f.ungetc("Z"); f.ungetc("Y"); print f.read(3).inspect; f.write("AB")`, + `"YZ1""01AB456789\nabc\n"`}, + {"a seek drops the pushback", `f.getc; f.ungetc("Z"); f.seek(0, IO::SEEK_END); f.write("x")`, + `"0123456789\nabc\nx"`}, + {"SEEK_CUR counts from the logical position", `f.getc; f.ungetc("Z"); f.seek(2, IO::SEEK_CUR); print f.read(2).inspect`, + `"23""0123456789\nabc\n"`}, + {"rewind drops it", `f.getc; f.ungetc("Z"); f.rewind; print f.read(3).inspect`, `"012""0123456789\nabc\n"`}, + {"pos drops it when the position is valid", `f.getc; f.ungetc("Z"); print f.pos, f.getc.inspect`, + `0"0""0123456789\nabc\n"`}, + {"pos keeps it and is negative when more was pushed back than read", + `f.getc; f.ungetc("ZZ"); print f.pos, f.getc.inspect`, `-1"Z""0123456789\nabc\n"`}, + {"a negative position writes where the read-ahead stopped", + `f.getc; f.ungetc("ZZ"); f.write("AB"); print f.pos`, `17"0123456789\nabc\nAB"`}, + {"nothing read: the write lands at 0", `f.ungetc("Z"); print f.pos; f.write("AB")`, `-1"AB23456789\nabc\n"`}, + {"flush drops it", `f.getc; f.ungetc("Z"); f.flush; print f.pos, f.read(2).inspect`, `0"01""0123456789\nabc\n"`}, + {"truncate drops it", `f.getc; f.ungetc("Z"); f.truncate(4); print f.pos, f.read.inspect`, `0"0123""0123"`}, + {"pwrite drops it", `f.getc; f.ungetc("Z"); f.pwrite("Q", 5); print f.pos, f.read(2).inspect`, + `0"01""01234Q6789\nabc\n"`}, + {"syswrite drops it", `f.getc; f.ungetc("Z"); f.syswrite("AB")`, `"AB23456789\nabc\n"`}, + {"pread reads the file", `f.getc; f.ungetc("Z"); print f.pread(3, 0).inspect`, `"012""0123456789\nabc\n"`}, + {"size is the file's", `f.getc; f.ungetc("Z"); print f.size`, `15"0123456789\nabc\n"`}, + {"closing writes nothing", `f.getc; f.ungetc("Z")`, `"0123456789\nabc\n"`}, + {"sysread refuses buffered data", `f.getc; f.ungetc("Z"); begin; f.sysread(2); rescue IOError => e; print e.message; end`, + `sysread for buffered IO"0123456789\nabc\n"`}, + {"sysseek refuses buffered data", `f.getc; f.ungetc("Z"); begin; f.sysseek(0); rescue IOError => e; print e.message; end`, + `sysseek for buffered IO"0123456789\nabc\n"`}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + src := fmt.Sprintf("p_ = %q; File.binwrite(p_, \"0123456789\\nabc\\n\")\n"+ + "File.open(p_, \"r+\") { |f| %s }\nprint File.binread(p_).inspect", p, c.act) + if got := eval(t, src); got != c.want { + t.Errorf("got=%s\nwant=%s", got, c.want) + } + }) + } +} + +// TestReopenDropsThePushback: IO#reopen must not carry pushed-back bytes into +// the stream it rebinds, nor leave the region pointing into content that has +// been replaced. Wants: MRI 4.0.7 (arm64-darwin25, rubydiff, 2026-11-22). +func TestReopenDropsThePushback(t *testing.T) { + d := filepath.ToSlash(t.TempDir()) + src := fmt.Sprintf(`a = %q + "/a"; b = %q + "/b" +File.binwrite(a, "0123456789"); File.binwrite(b, "abcdefghij") +f = File.open(a, "r+"); f.getc; f.ungetc("Z"); f.reopen(b, "r+"); print f.read(3).inspect; f.write("XY"); f.close +print File.binread(a).inspect, File.binread(b).inspect +File.binwrite(a, "0123456789"); File.binwrite(b, "abcdefghij") +f = File.open(a, "r+"); g = File.open(b, "r+"); g.read(2); g.ungetc("Z"); f.reopen(g); print f.pos, f.read(3).inspect; f.close; g.close +print File.binread(a).inspect, File.binread(b).inspect`, d, d) + want := `"abc""0123456789""abcXYfghij"1"bcd""0123456789""abcdefghij"` + if got := eval(t, src); got != want { + t.Errorf("got=%s\nwant=%s", got, want) + } +} + +// TestStringIOUngetcWritesIntoTheString: StringIO's pushback is not the file +// model above — ext/stringio strio_unget_bytes writes it INTO the string, over +// the bytes just read, and moves the position back. Before #974 it was spliced +// in like a file's: the first row printed 1"0AB23". Every want is MRI 4.0.7's +// output (arm64-darwin25, rubydiff, 2026-11-22); the last column checks the +// caller's String object is the one changed. +func TestStringIOUngetcWritesIntoTheString(t *testing.T) { + cases := []struct{ name, act, want string }{ + {"over the byte just read", `s.getc; s.ungetc("Z"); print s.pos; s.write("AB")`, `0"AB23"`}, + {"longer than the position: the string grows", `s.getc; s.ungetc("ZZZ"); print s.pos, s.read.inspect`, `0"ZZZ123""ZZZ123"`}, + {"at 0", `s.ungetc("XY"); print s.pos, s.read(3).inspect`, `0"XY0""XY0123"`}, + {"past the end: NUL-filled gap", `s.pos = 7; s.ungetc("Z"); print s.pos`, `6"0123\u0000\u0000Z"`}, + {"past the end and longer than the position", `s.pos = 6; s.ungetc("ZZZZZZZZZ"); print s.pos`, `0"ZZZZZZZZZ"`}, + {"ungetbyte", `s.read; s.ungetbyte(65); print s.pos, s.read.inspect`, `3"A""012A"`}, + {"multibyte", `s.read(2); s.ungetc("é"); print s.pos, s.read.inspect`, `0"é23""é23"`}, + {"codepoint", `s.read(3); s.ungetc(0x41); print s.pos`, `2"01A3"`}, + // strio_ungetc returns before strio_unget_bytes for an empty string, which + // would otherwise NUL-fill the gap past the end. + {"empty, past the end: nothing", `s.pos = 6; s.ungetc(""); s.ungetbyte(""); print s.pos`, `6"0123"`}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + src := fmt.Sprintf("require \"stringio\"; str = +\"0123\"; s = StringIO.new(str); %s; print str.inspect, str.equal?(s.string)", c.act) + if got, want := eval(t, src), c.want+"true"; got != want { + t.Errorf("got=%s\nwant=%s", got, want) + } + }) + } +} From 926fba15f376dd0e0ecbb44b2598a0800ace037b Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 14:17:57 +0100 Subject: [PATCH 2/2] vm: leave a failed unread where MRI's descriptor is When more is pushed back than was read, io_unread's lseek fails and the stream stays where its descriptor is. #977's first commit put that at end-of-file whenever anything had been read, which holds only after a buffered read (getc, gets, getbyte, readchar): those fill rbuf ahead, and MRI reads a file of up to 8192 bytes whole. IO#read and #readpartial on an empty rbuf read straight into the string (io_bufread, io_getpartial), so the descriptor is at the cursor: f.read(1); f.ungetc("XYZ"); f.write("Q") writes Q at offset 1 under MRI 4.0.7; rbgo appended it. The stream now keeps fdAt, the descriptor's offset while rbuf holds nothing. Every operation that empties rbuf sets it to the cursor: a discarding unread, a seek, #pos=, #rewind, a write, and a direct read. A buffered read moves the cursor past it, and then the descriptor is at end-of-file. A read that starts with pushback in rbuf is not direct: io_bufread takes the pushback and refills with io_fillbuf. Two neighbours found by the same probes: - File#size on a writable stream runs flush_before_seek, whose io_unread drops the pushback (rb_file_size); rbgo kept it. - #readpartial and #read_nonblock return only what rbuf holds while pushback is left (io_getpartial); rbgo read on into the file. Also the coverage gate that failed #977 on ubuntu and macOS: diskBytes' copy branch was reached by no test. "a pending write is flushed without the pushback" reaches it through #flush. Measured with rubydiff against MRI 4.0.7 (the installed one; the io_unread read is from the 4.0.9 source): 48 new probe rows across 16 read/seek/write sequences, plus the earlier #974 probes, all agree except the known 8192-byte capacity row. 11 rows added to TestUngetcOnAFileIsNotTheFiles. Refs #974 Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- internal/vm/io.go | 24 ++++++++++++--- internal/vm/io_pushback.go | 53 +++++++++++++++++++++++++++++---- internal/vm/io_pushback_test.go | 20 +++++++++++++ internal/vm/spawn.go | 12 ++++++-- 5 files changed, 98 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 51f639bd..44faeac2 100644 --- a/README.md +++ b/README.md @@ -876,7 +876,7 @@ Otherwise: | `File::Stat#==` | `a == b` is `false` for two stats of the same file (MRI: `true`); `a.==(b)` answers `true` | | `File#stat` on a file unlinked while open | raises `Errno::ENOENT`; MRI answers from the open descriptor. rbgo's streams are buffered by path and hold no descriptor | | `IO#pwrite` / `IO#pread` on a file unlinked or replaced while open | both reach the file **by its path**, since streams hold no descriptor. A `#pwrite`'s bytes are on disk when it returns, and only those bytes: the stream's other pending writes stay pending, as with `pwrite(2)`. `#pread` sees another writer's bytes and this stream's own pending writes, which it flushes first, as `rb_io_pread` does ([#949](https://github.com/go-embedded-ruby/ruby/issues/949)). The difference is with a path that no longer names the opened file. Unlinked, both fall back to the stream's buffer, where MRI still reaches the old inode. Replaced, they reach the new file. Same root as the row above. Two deliberate divergences. First, `#pread`'s length is bounded by the file's size, so `f.pread(2**40, 0)` returns at once, where MRI 4.0.7 tries to allocate the full length. Second, a hole lives in memory when it has to: a `#pwrite` that would open a hole larger than 64 MiB past the end of the stream's in-memory copy is refused with `Errno::EFBIG` once the path is gone, where MRI writes a sparse file through its descriptor. When the file is reachable, the hole goes to disk as in MRI, and a refusal from the file (EFBIG, ENOSPC, EIO) is raised with its errno ([#973](https://github.com/go-embedded-ruby/ruby/issues/973)) | -| `IO#ungetc` / `#ungetbyte` on a `File` longer than 8192 bytes | as in MRI, pushed-back bytes are read-buffer bytes and never reach the file. `#pos` subtracts them, and is negative when more was pushed back than read. A write, `#flush`, `#seek`, `#rewind`, `#truncate` or `#pwrite` drops them first. `#sysread` and `#sysseek` refuse with "for buffered IO" ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The divergence is MRI's read-buffer capacity: MRI reads 8192 bytes ahead, so on a larger file, pushing back more than was read raises `IOError: ungetbyte failed`. rbgo accepts it, and a following write lands at end-of-file. On a file of at most 8192 bytes the two agree | +| `IO#ungetc` / `#ungetbyte` on a `File` longer than 8192 bytes | as in MRI, pushed-back bytes are read-buffer bytes and never reach the file. `#pos` subtracts them, and is negative when more was pushed back than read. A write, `#flush`, `#seek`, `#rewind`, `#truncate`, `#pwrite` or `File#size` on a writable stream drops them first. When the position was negative, the stream ends up where MRI's descriptor is: at the cursor after `#read`, `#readpartial`, `#read_nonblock`, a seek or a write, and at end-of-file after a buffered read (`#getc`, `#gets`, …), which reads ahead. `#readpartial` and `#read_nonblock` return no more than the pushback while some is left. `#sysread` and `#sysseek` refuse with "for buffered IO" ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The divergence is MRI's read-buffer capacity: MRI reads 8192 bytes ahead, so on a larger file, pushing back more than was read raises `IOError: ungetbyte failed`. rbgo accepts it, and a following write lands at end-of-file. On a file of at most 8192 bytes the two agree | | an unflushed file whose directory is removed before the program ends | loses its bytes; MRI, holding a descriptor to an unlinked file, still writes them. Teardown re-opens the path to flush it, so it gets `ENOENT` — and reports nothing, as MRI's shutdown ignores a failing `fflush`. Same root again: streams are buffered by path, which is also [#635](https://github.com/go-embedded-ruby/ruby/issues/635) | | `Errno` | all **158** of MRI's constant names are present, but **32** report errno `0` where MRI has a real number (`EAUTH`, `EBADRPC`, `EDEVERR`, …). Measured by set difference on darwin: 81 names are zero-valued under rbgo, 49 under MRI, and every MRI zero is also zero under rbgo. Go's portable `syscall` package does not expose the platform-only names | | `pp` | neither `Kernel#pp` nor `require "pp"` exists (`require "prettyprint"` does work) | diff --git a/internal/vm/io.go b/internal/vm/io.go index ae544c00..7ed03393 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -147,6 +147,9 @@ type IOObj struct { // ungetLo/ungetHi bound the bytes #ungetc/#ungetbyte spliced into buf on a // file stream, which are not the file's (io_pushback.go). Empty when equal. ungetLo, ungetHi int + // fdAt is where MRI's descriptor is while its read buffer holds no file + // bytes; a failed io_unread leaves the cursor there (io_pushback.go). + fdAt int } // pipeBuf is the shared byte channel behind an IO.pipe reader/writer pair. Each @@ -222,6 +225,7 @@ func (o *IOObj) writeBytes(p []byte) int { } copy(o.buf[o.pos:], p) o.pos += len(p) + o.fdAt = o.pos // a write leaves rbuf empty and the descriptor past it o.syncStr() if o.path != "" { o.wbufDirty = true // bytes accepted but not on disk: MRI's fptr->wbuf.len @@ -668,6 +672,12 @@ func (vm *VM) registerIO() { raise("IOError", "closed stream") } ioFlush(o) + if o.writable { + // rb_file_size: flush_before_seek on a writable stream, whose + // io_unread drops what #ungetc pushed back (#974). A read-only + // stream keeps it, and its buffer answers without it below. + o.unreadPushback(true) + } if st, err := os.Stat(o.path); err == nil { return object.IntValue(st.Size()) } @@ -2087,7 +2097,7 @@ func defStringIORead(cls *RClass) { raise("Errno::EINVAL", "Invalid argument") } o.unreadPushback(true) // io_seek → flush_before_seek → io_unread (#974) - o.pos = n + o.pos, o.fdAt = n, n return args[0] }) cls.define("seek", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { @@ -2123,7 +2133,7 @@ func defStringIORead(cls *RClass) { if newPos < 0 { raise("Errno::EINVAL", "Invalid argument") } - o.pos = newPos + o.pos, o.fdAt = newPos, newPos return object.IntValue(0) }) cls.define("rewind", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { @@ -2131,6 +2141,7 @@ func defStringIORead(cls *RClass) { ioClosedRealIO(o) // real IO/File raises on a closed stream; StringIO tolerates it o.unreadPushback(true) // io_seek(fptr, 0, 0) → io_unread (#974) o.pos, o.lineno = 0, 0 // #rewind resets both the position and the line number + o.fdAt = 0 return object.IntValue(0) }) cls.define("truncate", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { @@ -2215,15 +2226,20 @@ func defStringIORead(cls *RClass) { if o.pos >= len(o.buf) { return result(nil, n > 0) // a length read at EOF is nil; a 0-length read is "" } + wasAt := o.atDescriptor() // io_bufread: an empty rbuf is bypassed end := min(o.pos+n, len(o.buf)) data := o.buf[o.pos:end] o.pos = end - return result(data, false) + v := result(data, false) // copies data before readThrough compacts buf + o.readThrough(wasAt) + return v } start := min(o.pos, len(o.buf)) // pos= may have moved past the end data := o.buf[start:] o.pos = len(o.buf) - return result(data, false) + v := result(data, false) + o.readThrough(true) // read_all drains rbuf and reads the rest directly + return v }) // readpartial(maxlen, out = nil): read up to maxlen bytes, blocking only until // some are available. On the in-memory buffer that is the leading maxlen bytes; diff --git a/internal/vm/io_pushback.go b/internal/vm/io_pushback.go index 3d06bf9a..edefab25 100644 --- a/internal/vm/io_pushback.go +++ b/internal/vm/io_pushback.go @@ -28,11 +28,22 @@ package vm // way, as rb_io_tell's "pos -= fptr->rbuf.len" does. // // L is negative when more bytes were pushed back than had been read. lseek -// then fails and the descriptor stays where the read-ahead left it, which is -// where a following write lands: 0 when nothing had been read, and otherwise -// end-of-file — MRI reads a file of up to 8192 bytes whole, and a larger one -// refuses that much pushback with "ungetbyte failed" (io_ungetbyte's capacity -// check), which this model does not reproduce. +// then fails and the descriptor stays where it was, which is where a following +// write lands. Where it was depends on how the bytes were read: +// +// - a buffered read (getc, gets, getbyte, readchar, ...) fills rbuf ahead of +// the cursor, and MRI reads a file of up to 8192 bytes whole: the +// descriptor is at end-of-file. A larger file refuses that much pushback +// with "ungetbyte failed" (io_ungetbyte's capacity check), which this +// model does not reproduce; +// - IO#read and #readpartial on an empty rbuf read straight into the string +// (io_bufread, io_getpartial), and a successful or discarding io_unread +// empties rbuf: the descriptor is at the cursor, and stays there. +// +// fdAt is that second case: the offset the descriptor is at while rbuf holds +// no file bytes. Every operation that empties rbuf sets it to the cursor; a +// buffered read moves the cursor past it, and then the descriptor is at +// end-of-file. // // Only file streams are tracked. StringIO#ungetc writes into its string // (strio_unget_bytes) and a pipe cannot seek (FMODE_DUPLEX makes io_unread a @@ -82,6 +93,9 @@ func (o *IOObj) pushbackUnread() int { func (o *IOObj) unreadPushback(discard bool) { u := o.pushbackUnread() if u == 0 { + if discard { + o.fdAt = o.pos // rbuf emptied: the descriptor is at the cursor + } return } logical := o.pos - u @@ -93,9 +107,36 @@ func (o *IOObj) unreadPushback(discard bool) { switch { case logical >= 0: o.pos = logical - case o.pos > 0: + case o.pos != o.fdAt: o.pos = len(o.buf) // the read-ahead reached end-of-file } + o.fdAt = o.pos +} + +// atDescriptor reports whether rbuf is empty: no pushback, and no file bytes +// read ahead of the cursor. Only then do IO#read and #readpartial go straight +// to the descriptor; with anything buffered, io_bufread takes it and refills +// with io_fillbuf, a buffered read-ahead. +func (o *IOObj) atDescriptor() bool { + return o.pushbackUnread() == 0 && o.pos == o.fdAt +} + +// readThrough follows a read that went straight to the descriptor (wasAt): +// rbuf is still empty and the descriptor is at the cursor. +func (o *IOObj) readThrough(wasAt bool) { + if wasAt { + o.compactPushback() + o.fdAt = o.pos + } +} + +// partialLimit is io_getpartial's bound: with pushback in rbuf, #readpartial +// and #read_nonblock return only what is buffered, never reading on past it. +func (o *IOObj) partialLimit(n int) int { + if u := o.pushbackUnread(); u > 0 { + return min(n, u) + } + return n } // tellPos is rb_io_tell: the logical position, which is negative when more diff --git a/internal/vm/io_pushback_test.go b/internal/vm/io_pushback_test.go index 0fd33866..7838ae8a 100644 --- a/internal/vm/io_pushback_test.go +++ b/internal/vm/io_pushback_test.go @@ -53,6 +53,26 @@ func TestUngetcOnAFileIsNotTheFiles(t *testing.T) { `sysread for buffered IO"0123456789\nabc\n"`}, {"sysseek refuses buffered data", `f.getc; f.ungetc("Z"); begin; f.sysseek(0); rescue IOError => e; print e.message; end`, `sysseek for buffered IO"0123456789\nabc\n"`}, + // A negative position after a direct read: io_bufread / io_getpartial + // read straight into the string when rbuf is empty, so when io_unread's + // lseek fails the descriptor is at the cursor, not at end-of-file. + {"read(n) leaves the descriptor at the cursor", `f.read(1); f.ungetc("XYZ"); f.write("Q"); print f.pos`, + `2"0Q23456789\nabc\n"`}, + {"readpartial too", `f.readpartial(2); f.ungetc("XYZ"); f.write("Q"); print f.pos`, `3"01Q3456789\nabc\n"`}, + {"read_nonblock too", `f.read_nonblock(1); f.ungetc("XYZ"); f.flush; print f.pos, f.read(2).inspect`, + `1"12""0123456789\nabc\n"`}, + {"a seek empties rbuf", `f.seek(1); f.ungetc("XYZ"); f.write("Q")`, `"0Q23456789\nabc\n"`}, + {"pos= empties rbuf", `f.pos = 2; f.ungetc("WXYZ"); f.write("Q")`, `"01Q3456789\nabc\n"`}, + {"a write empties rbuf", `f.write("Q"); f.ungetc("XYZ"); f.write("R")`, `"QR23456789\nabc\n"`}, + {"a read past the pushback refills ahead to end-of-file", + `f.read(1); f.ungetc("XY"); f.read(4); f.ungetc("STUVWXYZ"); f.write("Q"); print f.pos`, + `16"0123456789\nabc\nQ"`}, + {"readpartial stops at the pushback", `f.read(1); f.ungetc("XY"); print f.readpartial(5)`, `XY"0123456789\nabc\n"`}, + {"read_nonblock stops at the pushback", `f.read(1); f.ungetc("XY"); print f.read_nonblock(5)`, `XY"0123456789\nabc\n"`}, + {"size drops the pushback of a writable stream", `f.read(1); f.ungetc("XYZ"); print [f.size, f.pos, f.read(2)].inspect`, + `[15, 1, "12"]"0123456789\nabc\n"`}, + {"a pending write is flushed without the pushback", `f.write("AB"); f.getc; f.ungetc("ZY"); f.flush; print f.pos`, + `1"AB23456789\nabc\n"`}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { diff --git a/internal/vm/spawn.go b/internal/vm/spawn.go index d5e4a47a..c2bfe0ab 100644 --- a/internal/vm/spawn.go +++ b/internal/vm/spawn.go @@ -147,9 +147,13 @@ func (vm *VM) registerSpawn() { } else if n > avail { n = avail } + n = o.partialLimit(n) + wasAt := o.atDescriptor() // io_getpartial reads the descriptor when rbuf is empty (#974) data := o.buf[o.pos : o.pos+n] o.pos += n - return ioReadResult(data, buf) + v := ioReadResult(data, buf) // copies data before readThrough compacts buf + o.readThrough(wasAt) + return v }) // readpartial(maxlen, outbuf = nil): a length-limited read that, unlike @@ -193,9 +197,13 @@ func (vm *VM) registerSpawn() { if n > avail { n = avail } + n = o.partialLimit(n) + wasAt := o.atDescriptor() // io_getpartial reads the descriptor when rbuf is empty (#974) data := o.buf[o.pos : o.pos+n] o.pos += n - return ioReadResult(data, buf) + v := ioReadResult(data, buf) // copies data before readThrough compacts buf + o.readThrough(wasAt) + return v }) // IO#reopen and IO#fcntl live in io_descriptors.go, beside the rest of the