From eac0f2e2e9bfffea2c8e81720d6864dacb95cba7 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 13:08:59 +0100 Subject: [PATCH 1/9] vm: flush only the byte ranges this stream wrote ioFlush wrote the stream's whole in-memory copy over the file with os.WriteFile. Another writer's bytes elsewhere in the file, an append made by another process, or a truncation were all overwritten by the next flush. MRI flushes its write buffer at the stream's offset and touches nothing else. The stream now records the [lo, hi) spans it wrote (io_dirty.go): touching or overlapping spans merge, and past 256 separate spans the list collapses into its union so scattered writes cannot grow it without bound. A flush writes each span at its offset with WriteAt, or appends it in append mode. #truncate clips the spans and #pwrite's fallback marks its range. The dirty list replaces the wbufDirty flag, so there is one record of what is pending. A refused flush now raises the errno the system answered, as rb_io_flush_raw does through rb_sys_fail_on_write. It used to be flattened to ENOENT (or EACCES), so a flush to a directory raised ENOENT where EISDIR is the answer, and a full disk raised ENOENT where ENOSPC is. Measured against MRI 4.0.9 with rubydiff: 7 of 8 probe rows diverged before, all 8 agree after. TestAFlushWritesOnlyWhatThisStreamWrote carries the 8 rows. mutsweep over io_dirty.go: the empty-span refusal and the open-error refusal are caught; the write-error refusal is held by TestAFlushThatCannotWriteRaises, which needs /dev/full and so runs on the Linux lane only. Refs #974 Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + internal/vm/filestat_internal_test.go | 12 +-- internal/vm/io.go | 45 +++++----- internal/vm/io_descriptors.go | 8 +- internal/vm/io_dirty.go | 114 ++++++++++++++++++++++++++ internal/vm/io_dirty_internal_test.go | 89 ++++++++++++++++++++ internal/vm/io_dirty_test.go | 47 +++++++++++ internal/vm/shutdown_flush_test.go | 4 +- internal/vm/wave32_ioenc_test.go | 4 +- 9 files changed, 290 insertions(+), 34 deletions(-) create mode 100644 internal/vm/io_dirty.go create mode 100644 internal/vm/io_dirty_internal_test.go create mode 100644 internal/vm/io_dirty_test.go diff --git a/README.md b/README.md index 44faeac2..aeda1be8 100644 --- a/README.md +++ b/README.md @@ -877,6 +877,7 @@ Otherwise: | `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`, `#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 | +| `IO#flush` on a `File` another writer changed | as in MRI, a flush puts on disk only the byte ranges this stream wrote, at their offsets (appended in append mode), so another writer's bytes elsewhere in the file, an append, or a truncation stand. A flush the system refuses raises its own errno (`Errno::ENOSPC`, `Errno::EISDIR`, …) ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The divergence is a bound: past 256 separate unflushed ranges, rbgo merges them into one span, and a flush then rewrites the gaps between them with its own copy of those bytes. MRI's 8192-byte write buffer flushes long before that. Reaching the file by path is the same root as the rows above | | 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/filestat_internal_test.go b/internal/vm/filestat_internal_test.go index 8d089e47..529c9ec4 100644 --- a/internal/vm/filestat_internal_test.go +++ b/internal/vm/filestat_internal_test.go @@ -441,22 +441,22 @@ func TestStatGroupsDefault(t *testing.T) { // TestIOFlushError covers ioFlush's write-failure branch: flushing a writable // file stream whose path is an unwritable directory raises Errno::ENOENT. func TestIOFlushError(t *testing.T) { - o := &IOObj{isStr: true, writable: true, wbufDirty: true, path: "/no/such/dir/x.txt", buf: []byte("data")} + o := &IOObj{isStr: true, writable: true, dirty: []ioSpan{{0, 4}}, path: "/no/such/dir/x.txt", buf: []byte("data")} if got := catchRaise(func() { ioFlush(o) }); got != "Errno::ENOENT" { t.Errorf("ioFlush error: got %q want Errno::ENOENT", got) } // Each of these is a no-op: no write is attempted, so none raises. Every row - // is pending (wbufDirty) except the last, so each one is refused by its own - // clause of the guard alone. The unwritable path makes an attempted write + // is pending (a dirty range) except the last, so each one is refused by its + // own clause of the guard alone. The unwritable path makes an attempted write // visible as Errno::ENOENT rather than as a file appearing somewhere. noops := []struct { name string o *IOObj }{ - {"not writable", &IOObj{isStr: true, writable: false, wbufDirty: true, path: "/no/such/dir/x.txt"}}, - {"no path", &IOObj{isStr: true, writable: true, wbufDirty: true, path: ""}}, + {"not writable", &IOObj{isStr: true, writable: false, dirty: []ioSpan{{0, 4}}, path: "/no/such/dir/x.txt"}}, + {"no path", &IOObj{isStr: true, writable: true, dirty: []ioSpan{{0, 4}}, path: ""}}, // #969: nothing pending, so even a writable stream with a path does not - // write. The same stream with wbufDirty set raised above. + // write. The same stream with a dirty range raised above. {"nothing pending", &IOObj{isStr: true, writable: true, path: "/no/such/dir/x.txt", buf: []byte("data")}}, } for _, c := range noops { diff --git a/internal/vm/io.go b/internal/vm/io.go index 7ed03393..524687a7 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -78,13 +78,9 @@ type IOObj struct { // write converter applies, translating every "\n" the stream is asked to // write. Only the stream path carries it — #syswrite and #write_nonblock go // to the descriptor and are not decorated. - newline string - // wbufDirty stands in for MRI's fptr->wbuf.len: bytes a buffered #write has - // accepted but not yet put on disk. Only #syswrite reads it, to reproduce - // rb_io_syswrite's "syswrite for buffered IO" warning; every flush clears it. - wbufDirty bool - openMode string // the fopen-style access mode a file stream was opened with ("r", "w+", "ab"…) - nonblock bool // O_NONBLOCK is set (io/nonblock): false for a file, true for a pipe end + newline string + openMode string // the fopen-style access mode a file stream was opened with ("r", "w+", "ab"…) + nonblock bool // O_NONBLOCK is set (io/nonblock): false for a file, true for a pipe end // encSet records that #set_encoding has resolved this stream's encodings // against the defaults in force at that moment (io.c io_encoding_set → // rb_io_ext_int_to_enc). An empty extEnc then means "no encoding" — MRI's @@ -144,6 +140,12 @@ type IOObj struct { // out of the buffer being read, and cannot reach a child that is already gone. popen *popenProc + // dirty holds the file ranges written but not yet flushed (io_dirty.go): + // a flush writes these, never the whole buffer. It is MRI's fptr->wbuf, and + // the ONLY record that something is pending (pending()): a separate flag + // beside it could say "pending" with no range to write, and did (#974). + dirty []ioSpan + // 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 @@ -224,12 +226,12 @@ func (o *IOObj) writeBytes(p []byte) int { o.buf = append(o.buf, make([]byte, end-len(o.buf))...) } copy(o.buf[o.pos:], p) + if o.path != "" { // bytes accepted but not on disk: MRI's fptr->wbuf + o.markDirty(o.pos, o.pos+len(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 - } if o.sync { // sync=true: a File's writes reach disk immediately (no buffering) ioFlush(o) } @@ -1291,25 +1293,27 @@ func notRegular(p string) bool { // disk: MRI's io_fflush with an empty write buffer writes nothing. Before this // gate, a stream opened "r+" or "a" and closed untouched put its open-time // snapshot back over another writer's bytes, and re-created a file unlinked -// while it was open. wbufDirty stands in for fptr->wbuf.len, and every write -// into the buffer that must reach the disk sets it (writeBytes, and #pwrite's -// buffer fallback); opens that truncate do so on disk at once and need no -// flush. +// while it was open. The pending ranges (o.dirty) stand in for fptr->wbuf, and +// every write into the buffer that must reach the disk records one +// (writeBytes, and #pwrite's buffer fallback); opens that truncate do so on +// disk at once and need no flush. func ioFlush(o *IOObj) { - if !o.writable || o.path == "" || !o.wbufDirty { + if !o.writable || o.path == "" || !o.pending() { return } - o.wbufDirty = false content := o.diskBytes() // never the bytes #ungetc pushed back (#974) - err := os.WriteFile(o.path, content, 0o644) + // Only the ranges this stream wrote, at their offsets (io_dirty.go): the + // rest of the file may be another writer's by now (#974). + defer func() { o.dirty = o.dirty[:0] }() + err := o.writeDirty(content) if err == nil { return } if errors.Is(err, fs.ErrPermission) { - err = withOwnerWrite(o.path, err, func() error { return os.WriteFile(o.path, content, 0o644) }) + err = withOwnerWrite(o.path, err, func() error { return o.writeDirty(content) }) } if err != nil { - raiseOpenErrno(err, o.path) + raiseFlushErr(err, o.path) } } @@ -1381,7 +1385,7 @@ func (vm *VM) flushOpenFiles() { files := vm.openFiles vm.openFiles = nil for _, o := range files { - if o.closed || !o.writable || !o.wbufDirty { + if o.closed || !o.writable || !o.pending() { continue } vm.flushOneAtTeardown(o) @@ -2159,6 +2163,7 @@ func defStringIORead(cls *RClass) { raise("Errno::EINVAL", "Invalid argument") } o.unreadPushback(true) // rb_io_check_writable → io_unread (#974) + o.clipDirty(n) // io_fflush then ftruncate: nothing pending survives past n 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 b06f8c32..53bbdcda 100644 --- a/internal/vm/io_descriptors.go +++ b/internal/vm/io_descriptors.go @@ -179,7 +179,7 @@ func defIOReadExtra(cls *RClass) { } str := vm.asWriteString(args[0]) ioCheckOpen(o) - if o.wbufDirty { + if o.pending() { vm.rbWarn("syswrite for buffered IO") } n := o.writeBytes(ioShortWrite(o, str.Bytes())) @@ -337,7 +337,7 @@ func defIOSeekable(cls *RClass) { // there since this stream was opened. rb_io_pread flushes this stream's // own pending writes first, and so does this, so they are seen too. if p, ok := ioPositionalPath(o); ok { - if o.wbufDirty { + if o.pending() { ioFlush(o) } data, err := preadFile(p, n, off) @@ -377,7 +377,7 @@ func defIOSeekable(cls *RClass) { // #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 // writes stay pending. pwriteFile does exactly that, so on success - // nothing new is waiting and wbufDirty is left as it was. + // nothing new is waiting and the pending ranges are left as they were. if p, ok := ioPositionalPath(o); ok { err := pwriteFile(p, data, off) if err == nil { @@ -399,7 +399,7 @@ func defIOSeekable(cls *RClass) { if !o.mirrorPwrite(data, off) { raise("Errno::EFBIG", "File too large @ rb_io_pwrite - %s", o.path) } - o.wbufDirty = true + o.markDirty(int(off), int(off)+len(data)) return object.IntValue(int64(len(data))) }) cls.define("sysseek", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { diff --git a/internal/vm/io_dirty.go b/internal/vm/io_dirty.go new file mode 100644 index 00000000..bad7460f --- /dev/null +++ b/internal/vm/io_dirty.go @@ -0,0 +1,114 @@ +package vm + +import "os" + +// Pending writes on a file stream are RANGES, not the whole buffer (#974). +// +// A File here holds its whole content in buf, and a flush used to put buf back +// with os.WriteFile: truncate, then write everything. MRI's io_fflush writes +// only fptr->wbuf — the bytes this stream was asked to write, at the offsets +// it wrote them — so whatever another writer put elsewhere in the file since +// the open survives, as does a truncation another process made. Writing the +// snapshot back erased both, at every flush, every #pread with a write +// pending, and every close. +// +// So writeBytes and #pwrite's buffer fallback record the span they changed, +// in file offsets (no pushback is in buf at that moment: a write unreads +// first, see io_pushback.go), and ioFlush writes those spans and nothing else, +// without truncating. A stream opened for appending writes them with O_APPEND +// instead, so they land after whatever the file has grown to, as MRI's +// O_APPEND descriptor does. +// +// Spans are merged when they touch. Past ioDirtyMax separate spans they are +// coalesced into their union, which bounds the bookkeeping of a program that +// writes at many scattered offsets; the cost is that the bytes between them +// are written back too, which is the old behaviour confined to that range. +const ioDirtyMax = 256 + +// ioSpan is a half-open byte range [lo, hi) of a file. +type ioSpan struct{ lo, hi int } + +// pending reports whether a write is waiting to reach the file: MRI's +// fptr->wbuf.len != 0. +func (o *IOObj) pending() bool { return len(o.dirty) > 0 } + +// markDirty records that [lo, hi) of the file holds bytes not yet written. +func (o *IOObj) markDirty(lo, hi int) { + if hi <= lo { + return + } + merged := ioSpan{lo, hi} + kept := o.dirty[:0] + for _, s := range o.dirty { + if s.hi < merged.lo || s.lo > merged.hi { + kept = append(kept, s) + continue + } + merged.lo, merged.hi = min(merged.lo, s.lo), max(merged.hi, s.hi) + } + o.dirty = append(kept, merged) + if len(o.dirty) > ioDirtyMax { + u := o.dirty[0] + for _, s := range o.dirty[1:] { + u.lo, u.hi = min(u.lo, s.lo), max(u.hi, s.hi) + } + o.dirty = append(o.dirty[:0], u) + } +} + +// clipDirty drops what lies at or past n: #truncate has cut the file there on +// disk, so a pending byte beyond it must not bring the length back. +func (o *IOObj) clipDirty(n int) { + kept := o.dirty[:0] + for _, s := range o.dirty { + if s.lo < n { + kept = append(kept, ioSpan{s.lo, min(s.hi, n)}) + } + } + o.dirty = kept +} + +// writeDirty puts the pending spans of content on disk, at their offsets, or +// appended for an append-mode stream. The file is created if it is missing, +// which is what os.WriteFile did here before: the stream holds no descriptor +// to the unlinked inode MRI would still write to, and dropping the bytes would +// be worse than putting them back under the path. +func (o *IOObj) writeDirty(content []byte) error { + flags := os.O_WRONLY | os.O_CREATE + if o.appendMode { + flags |= os.O_APPEND + } + f, err := os.OpenFile(o.path, flags, 0o644) + if err != nil { + return err + } + for _, s := range o.dirty { + hi := min(s.hi, len(content)) + if s.lo >= hi { + continue + } + if o.appendMode { + _, err = f.Write(content[s.lo:hi]) + } else { + _, err = f.WriteAt(content[s.lo:hi], int64(s.lo)) + } + if err != nil { + _ = f.Close() + return err + } + } + return f.Close() +} + +// raiseFlushErr raises a failed flush as MRI's rb_io_flush_raw does, through +// rb_sys_fail_on_write: the errno the system answered, not one guessed from +// the path. ENOSPC from a full disk, EISDIR, EROFS all keep their class. +func raiseFlushErr(err error, path string) { + if eno, ok := errnoOfError(err); ok { + if name, ok := errnoClasses[eno]; ok { + raise("Errno::"+name, "%s @ rb_io_flush_raw - %s", errnoStrerror(eno), path) + } + raise("SystemCallError", "%s @ rb_io_flush_raw - %s", errnoStrerror(eno), path) + } + raise("Errno::EIO", "Input/output error @ rb_io_flush_raw - %s", path) +} diff --git a/internal/vm/io_dirty_internal_test.go b/internal/vm/io_dirty_internal_test.go new file mode 100644 index 00000000..2632e100 --- /dev/null +++ b/internal/vm/io_dirty_internal_test.go @@ -0,0 +1,89 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "fmt" + "os" + "testing" +) + +// TestAFlushThatCannotOpenRaisesTheOpensError: the open's own errno is what is +// raised. A missing directory would not show it — the errno is recovered from +// the path either way — but a directory answers EISDIR only to the open. +func TestAFlushThatCannotOpenRaisesTheOpensError(t *testing.T) { + o := &IOObj{isStr: true, writable: true, dirty: []ioSpan{{0, 4}}, path: t.TempDir(), buf: []byte("data")} + if got := catchRaise(func() { ioFlush(o) }); got != "Errno::EISDIR" { + t.Errorf("ioFlush to a directory raised %q, want Errno::EISDIR", got) + } +} + +// TestAFlushThatCannotWriteRaises: the file opened, and the write itself was +// refused — /dev/full answers every write with ENOSPC. The error must be +// raised, not dropped while the next span is tried and Close reports success. +// Linux only: no other CI platform has /dev/full. +func TestAFlushThatCannotWriteRaises(t *testing.T) { + if _, err := os.Stat("/dev/full"); err != nil { + t.Skip("no /dev/full on this platform") + } + o := &IOObj{isStr: true, writable: true, dirty: []ioSpan{{0, 4}}, path: "/dev/full", buf: []byte("data")} + if got := catchRaise(func() { ioFlush(o) }); got != "Errno::ENOSPC" { + t.Errorf("ioFlush to /dev/full raised %q, want Errno::ENOSPC", got) + } +} + +// TestMarkDirtyMergesTouchingSpans: spans that overlap or touch become one; +// spans with a gap stay apart, because the gap may be another writer's. +func TestMarkDirtyMergesTouchingSpans(t *testing.T) { + cases := []struct { + name string + marks [][2]int + want string + }{ + {"empty span ignored", [][2]int{{3, 3}}, "[]"}, + {"adjacent", [][2]int{{0, 2}, {2, 4}}, "[{0 4}]"}, + {"adjacent, other order", [][2]int{{2, 4}, {0, 2}}, "[{0 4}]"}, + {"overlapping", [][2]int{{0, 3}, {2, 6}}, "[{0 6}]"}, + {"contained", [][2]int{{0, 6}, {2, 3}}, "[{0 6}]"}, + {"a gap of one byte stays", [][2]int{{0, 2}, {3, 4}}, "[{0 2} {3 4}]"}, + {"a bridge joins three", [][2]int{{0, 2}, {5, 6}, {2, 5}}, "[{0 6}]"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + o := &IOObj{} + for _, m := range c.marks { + o.markDirty(m[0], m[1]) + } + if got := fmt.Sprint(o.dirty); got != c.want { + t.Errorf("dirty = %s, want %s", got, c.want) + } + }) + } +} + +// TestMarkDirtyCoalescesPastTheBound: one span more than ioDirtyMax collapses +// the list into its union, so scattered writes cannot grow it without bound. +func TestMarkDirtyCoalescesPastTheBound(t *testing.T) { + o := &IOObj{} + for i := range ioDirtyMax { + o.markDirty(10*i, 10*i+1) + } + if len(o.dirty) != ioDirtyMax { + t.Fatalf("%d spans after %d separate marks, want %d", len(o.dirty), ioDirtyMax, ioDirtyMax) + } + o.markDirty(10*ioDirtyMax, 10*ioDirtyMax+1) + if want := fmt.Sprint([]ioSpan{{0, 10*ioDirtyMax + 1}}); fmt.Sprint(o.dirty) != want { + t.Errorf("dirty = %v, want %s", o.dirty, want) + } +} + +// TestClipDirtyCutsAtTheTruncation: a span past n goes, one across n is cut. +func TestClipDirtyCutsAtTheTruncation(t *testing.T) { + o := &IOObj{dirty: []ioSpan{{0, 2}, {3, 8}, {8, 9}, {12, 14}}} + o.clipDirty(5) + if got, want := fmt.Sprint(o.dirty), "[{0 2} {3 5}]"; got != want { + t.Errorf("dirty = %s, want %s", got, want) + } +} diff --git a/internal/vm/io_dirty_test.go b/internal/vm/io_dirty_test.go new file mode 100644 index 00000000..1aa5e07d --- /dev/null +++ b/internal/vm/io_dirty_test.go @@ -0,0 +1,47 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "fmt" + "path/filepath" + "testing" +) + +// TestAFlushWritesOnlyWhatThisStreamWrote: another writer's bytes, put in the +// file while this stream had a write pending, survive the flush (#974). Every +// want is MRI 4.0.7's output for the same program (arm64-darwin25, rubydiff, +// 2026-11-22). Before the fix a flush rewrote the stream's whole snapshot: +// the first row ended "AB23456789", the other writer's XY gone. +func TestAFlushWritesOnlyWhatThisStreamWrote(t *testing.T) { + p := filepath.ToSlash(filepath.Join(t.TempDir(), "f")) + cases := []struct{ name, mode, act, want string }{ + {"another writer's bytes elsewhere", "r+", + `f.write("AB"); File.open(p_, "r+") { |g| g.seek(5); g.write("XY") }`, `"AB234XY789"`}, + {"pread's flush keeps them too", "r+", + `f.write("AB"); File.open(p_, "r+") { |g| g.seek(5); g.write("XY") }; print f.pread(10, 0).inspect`, + `"AB234XY789""AB234XY789"`}, + {"another writer's append", "r+", + `f.write("AB"); File.open(p_, "a") { |g| g.write("TAIL") }`, `"AB23456789TAIL"`}, + {"two separate ranges, another write between them", "r+", + `f.seek(8); f.write("Q"); f.seek(1); f.write("W"); File.open(p_, "r+") { |g| g.seek(4); g.write("M") }`, + `"0W23M567Q9"`}, + {"append mode lands after the file's new end", "a", + `f.write("AB"); File.open(p_, "a") { |g| g.write("TAIL") }`, `"0123456789TAILAB"`}, + {"a hole past the end", "r+", `f.seek(12); f.write("Z")`, `"0123456789\x00\x00Z"`}, + {"another process's truncation stands", "r+", `f.write("AB"); File.truncate(p_, 3)`, `"AB2"`}, + {"a write after a flush writes only itself", "r+", + `f.write("AB"); f.flush; File.open(p_, "r+") { |g| g.write("xyz") }; f.write("C")`, `"xyC3456789"`}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + src := fmt.Sprintf("p_ = %q; File.binwrite(p_, \"0123456789\")\n"+ + "File.open(p_, %q) { |f| %s }\nprint File.binread(p_).inspect", p, c.mode, c.act) + if got := eval(t, src); got != c.want { + t.Errorf("got=%s\nwant=%s", got, c.want) + } + }) + } +} diff --git a/internal/vm/shutdown_flush_test.go b/internal/vm/shutdown_flush_test.go index 17edcad2..6509ea0c 100644 --- a/internal/vm/shutdown_flush_test.go +++ b/internal/vm/shutdown_flush_test.go @@ -275,8 +275,8 @@ func TestATeardownFlushNeitherRaisesNorSkipsTheRest(t *testing.T) { good := filepath.Join(dir, "good.txt") vm := New(os.Stdout) vm.openFiles = []*IOObj{ - {isStr: true, writable: true, wbufDirty: true, path: filepath.Join(dir, "no-such-dir", "bad.txt"), buf: []byte("lost")}, - {isStr: true, writable: true, wbufDirty: true, path: good, buf: []byte("kept")}, + {isStr: true, writable: true, dirty: []ioSpan{{0, 4}}, path: filepath.Join(dir, "no-such-dir", "bad.txt"), buf: []byte("lost")}, + {isStr: true, writable: true, dirty: []ioSpan{{0, 4}}, path: good, buf: []byte("kept")}, } if r := func() (r any) { defer func() { r = recover() }() diff --git a/internal/vm/wave32_ioenc_test.go b/internal/vm/wave32_ioenc_test.go index 84fb18e4..fc474d60 100644 --- a/internal/vm/wave32_ioenc_test.go +++ b/internal/vm/wave32_ioenc_test.go @@ -306,8 +306,8 @@ func TestIOSysWriteGoesToTheDescriptor(t *testing.T) { // TestIOSysWriteWarnsAfterBufferedWrite covers rb_io_syswrite's // `if (fptr->wbuf.len) rb_warn("syswrite for buffered IO")` — bytes a buffered -// #write accepted but has not put on disk, which is what wbufDirty stands in -// for. A #read leaves nothing buffered, so it must NOT warn. +// #write accepted but has not put on disk, which is what the pending ranges +// (IOObj.dirty) stand in for. A #read leaves nothing buffered, so it must NOT warn. func TestIOSysWriteWarnsAfterBufferedWrite(t *testing.T) { dir := ioScratchDir(t) q := func(name string) string { From 4efc544ee46c0cbaa126bdccc4bc69f046bc8479 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 15:46:43 +0100 Subject: [PATCH 2/9] vm: test a refused flush write on macOS too, through RLIMIT_FSIZE TestAFlushThatCannotWriteRaises needs /dev/full, which only the Linux runner has, so on macOS nothing failed when writeDirty dropped a write error (mutsweep: io_dirty.go's err != nil after WriteAt survived there). A write past RLIMIT_FSIZE answers EFBIG once the open has succeeded, and the Go runtime ignores SIGXFSZ, so the same assertion now holds on darwin and linux both. Refs #974 Co-Authored-By: Claude Opus 5.5 --- internal/vm/io_dirty_fsize_internal_test.go | 39 +++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 internal/vm/io_dirty_fsize_internal_test.go diff --git a/internal/vm/io_dirty_fsize_internal_test.go b/internal/vm/io_dirty_fsize_internal_test.go new file mode 100644 index 00000000..0ffd1ed1 --- /dev/null +++ b/internal/vm/io_dirty_fsize_internal_test.go @@ -0,0 +1,39 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build darwin || linux + +package vm + +import ( + "path/filepath" + "syscall" + "testing" +) + +// TestAFlushPastTheFileSizeLimitRaises: the file opened, and the write itself +// was refused. With RLIMIT_FSIZE below the span's offset, write(2) answers +// EFBIG (the Go runtime ignores SIGXFSZ, so the process survives it). This is +// TestAFlushThatCannotWriteRaises for platforms with no /dev/full: the error +// must be raised, not dropped while Close reports success. +func TestAFlushPastTheFileSizeLimitRaises(t *testing.T) { + path := filepath.Join(t.TempDir(), "f") + o := &IOObj{isStr: true, writable: true, dirty: []ioSpan{{8, 12}}, path: path, buf: []byte("0123456789ab")} + var old syscall.Rlimit + if err := syscall.Getrlimit(syscall.RLIMIT_FSIZE, &old); err != nil { + t.Skipf("getrlimit: %v", err) + } + limited := old + limited.Cur = 4 + if err := syscall.Setrlimit(syscall.RLIMIT_FSIZE, &limited); err != nil { + t.Skipf("setrlimit: %v", err) + } + got := catchRaise(func() { ioFlush(o) }) + if err := syscall.Setrlimit(syscall.RLIMIT_FSIZE, &old); err != nil { + t.Fatalf("restoring RLIMIT_FSIZE: %v", err) + } + if got != "Errno::EFBIG" { + t.Errorf("a flush past RLIMIT_FSIZE raised %q, want Errno::EFBIG", got) + } +} From f570a4202da5af12c16f4985a5f7a091995798e1 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 16:44:40 +0100 Subject: [PATCH 3/9] vm: test ioFlush's gate directly, so removing it fails instead of hanging ioFlush writes only a writable stream with a path and pending bytes. Nothing asserted that directly: with the gate deleted, the suite hung on a stream whose flush blocked (mutsweep: io.go's gate HUNG), which is no verdict. Three rows now assert that a read-only stream, one with no path and one with nothing pending leave the file as it was and raise nothing. Refs #974 Co-Authored-By: Claude Opus 5.5 --- internal/vm/io_dirty_internal_test.go | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/internal/vm/io_dirty_internal_test.go b/internal/vm/io_dirty_internal_test.go index 2632e100..0ed49c6c 100644 --- a/internal/vm/io_dirty_internal_test.go +++ b/internal/vm/io_dirty_internal_test.go @@ -7,6 +7,7 @@ package vm import ( "fmt" "os" + "path/filepath" "testing" ) @@ -34,6 +35,34 @@ func TestAFlushThatCannotWriteRaises(t *testing.T) { } } +// TestIOFlushWritesOnlyAWritableFileWithPendingBytes: ioFlush's gate. A +// read-only stream, a stream with no path, and one with nothing pending put +// nothing on disk and raise nothing, whatever its buffer holds: a read-only +// stream's buffer is a snapshot that another writer may have overtaken. Each +// row would otherwise write "XXXX" over the file, or raise on the empty path. +func TestIOFlushWritesOnlyAWritableFileWithPendingBytes(t *testing.T) { + path := filepath.Join(t.TempDir(), "f") + cases := []struct { + name string + o *IOObj + }{ + {"read-only", &IOObj{isStr: true, dirty: []ioSpan{{0, 4}}, path: path, buf: []byte("XXXX")}}, + {"no path", &IOObj{isStr: true, writable: true, dirty: []ioSpan{{0, 4}}, buf: []byte("XXXX")}}, + {"nothing pending", &IOObj{isStr: true, writable: true, path: path, buf: []byte("XXXX")}}, + } + for _, c := range cases { + if err := os.WriteFile(path, []byte("data"), 0o644); err != nil { + t.Fatal(err) + } + if got := catchRaise(func() { ioFlush(c.o) }); got != "" { + t.Errorf("%s: ioFlush raised %q", c.name, got) + } + if got, _ := os.ReadFile(path); string(got) != "data" { + t.Errorf("%s: the file holds %q, want \"data\"", c.name, got) + } + } +} + // TestMarkDirtyMergesTouchingSpans: spans that overlap or touch become one; // spans with a gap stay apart, because the gap may be another writer's. func TestMarkDirtyMergesTouchingSpans(t *testing.T) { From 18964d02a00a7341a944efb4c163e2b20ac89697 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 15:45:07 +0100 Subject: [PATCH 4/9] vm: write only into the file a stream opened, never what its path names now A File holds no descriptor: flushes, #pwrite and #truncate reopen its path. MRI writes through the descriptor it opened, so a file renamed over the path, or a symlink put in its place, is never touched, and an unlinked file is not created again. Reopening by path did touch them: with the path swapped for a symlink between the open and the flush, the stream's pending bytes were written into the link's target (#974, its TOCTOU item). A file stream now records the identity of the file it opened (io_identity.go). Every write that goes back through the path checks it on the path before the open, so a fifo or a device put in its place is not opened, and on the descriptor after, so a rename in between is caught. When the path names another file, nothing is written there and the bytes stay in the stream's buffer, where its own reads, #size and #pread still see them. withOwnerWrite grants and restores the owner-write bit only on that file. Measured against MRI 4.0.7 with rubydiff: the 12 rows of probe974t.rb and probe974t2.rb that diverged now agree, and the guard rows (a file opened through a symlink, a read-only file written by the open's grant, plain integer flags) behaved the same before and after. #truncate on an unlinked file now succeeds as MRI's ftruncate does, where it raised Errno::ENOENT (#635); TestWave28TruncateFileOnDisk, which pinned that divergence, now asserts MRI's answer. Refs #974 Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- internal/vm/file_mode.go | 12 +- internal/vm/io.go | 17 +- internal/vm/io_class.go | 2 +- internal/vm/io_descriptors.go | 11 +- internal/vm/io_dirty.go | 16 +- internal/vm/io_identity.go | 115 ++++++++++++ internal/vm/io_identity_internal_test.go | 206 +++++++++++++++++++++ internal/vm/io_identity_test.go | 80 ++++++++ internal/vm/io_positional.go | 22 ++- internal/vm/io_positional_internal_test.go | 4 +- internal/vm/wave28_cover_gaps_test.go | 18 +- 12 files changed, 467 insertions(+), 39 deletions(-) create mode 100644 internal/vm/io_identity.go create mode 100644 internal/vm/io_identity_internal_test.go create mode 100644 internal/vm/io_identity_test.go diff --git a/README.md b/README.md index aeda1be8..4323a659 100644 --- a/README.md +++ b/README.md @@ -875,9 +875,10 @@ Otherwise: | `Numeric#to_int` | not defined — `Complex(2.9, 0).to_int` raises `NoMethodError`; MRI returns `2` | | `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#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 or replaced. Both fall back to the stream's buffer and leave the path alone, as MRI does, but MRI's bytes reach the old inode, which other processes holding it would see. 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`, `#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 | | `IO#flush` on a `File` another writer changed | as in MRI, a flush puts on disk only the byte ranges this stream wrote, at their offsets (appended in append mode), so another writer's bytes elsewhere in the file, an append, or a truncation stand. A flush the system refuses raises its own errno (`Errno::ENOSPC`, `Errno::EISDIR`, …) ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The divergence is a bound: past 256 separate unflushed ranges, rbgo merges them into one span, and a flush then rewrites the gaps between them with its own copy of those bytes. MRI's 8192-byte write buffer flushes long before that. Reaching the file by path is the same root as the rows above | +| a `File` whose path is unlinked, renamed over, or swapped for a symlink while it is open | as in MRI, its writes never reach what the path names now. A stream records the file it opened, and a flush, `#close`, `#pwrite`, `#truncate` or `sync = true` write checks the path against it before opening it and checks the opened file after, so a file put in its place, or the target of a symlink put there, is left alone, and an unlinked file is not created again. Before, a symlink swapped in between the open and the flush received the stream's pending bytes ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The stream's own reads, `#size` and `#pread` still see its bytes. The divergence: MRI's bytes land on the orphaned inode, where rbgo keeps them in the stream's buffer, so another process holding that inode does not see them. A fifo swapped in between rbgo's two checks can still make the open block. A file opened through a symlink is written through it, as in MRI | | 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/file_mode.go b/internal/vm/file_mode.go index 9b2bba0a..ebd97fc6 100644 --- a/internal/vm/file_mode.go +++ b/internal/vm/file_mode.go @@ -45,15 +45,23 @@ func chmodMode(m int64) fs.FileMode { // darwin keeps sticky through a write and loses setuid and setgid, which is // the kernel clearing them on a write, and restoring the mode read BEFORE the // write would put a setuid bit back on content that was just changed. -func withOwnerWrite(path string, refused error, write func() error) error { +// +// ident is the file the stream opened (io_identity.go), or nil. The mode is +// changed only while path still names it: a chmod follows a symlink, and one +// put in the file's place must not lend its target the owner-write bit. When +// path names another file, nothing is done and errNotTheOpenedFile returned. +func withOwnerWrite(path string, ident os.FileInfo, refused error, write func() error) error { st, err := os.Stat(path) if err != nil { return refused } + if ident != nil && !os.SameFile(ident, st) { + return errNotTheOpenedFile + } ownerWrite := st.Mode() & 0o200 _ = os.Chmod(path, st.Mode()&chmodBits|0o200) werr := write() - if after, err := os.Stat(path); err == nil { + if after, err := os.Stat(path); err == nil && os.SameFile(st, after) { _ = os.Chmod(path, after.Mode()&chmodBits&^0o200|ownerWrite) } return werr diff --git a/internal/vm/io.go b/internal/vm/io.go index 524687a7..747603d6 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -152,6 +152,9 @@ type IOObj struct { // 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 + // ident is the regular file this stream opened, which a write back by + // path must still find there (io_identity.go). Nil when there is none. + ident os.FileInfo } // pipeBuf is the shared byte channel behind an IO.pipe reader/writer pair. Each @@ -680,7 +683,9 @@ func (vm *VM) registerIO() { // stream keeps it, and its buffer answers without it below. o.unreadPushback(true) } - if st, err := os.Stat(o.path); err == nil { + // fstat(2) of the file the stream opened: the path's answer only while + // it still names that file (io_identity.go), the buffer's otherwise. + if st, err := os.Stat(o.path); err == nil && o.namesOpenedFile(st) { return object.IntValue(st.Size()) } return object.IntValue(int64(len(o.diskBytes()))) @@ -1030,6 +1035,7 @@ func openFileSpec(cls *RClass, p string, ms *ioModeSpec, perm int64, permGiven b o.rdClosed = !ms.readable o.wrClosed = !ms.writable o.appendMode = ms.appendMode + o.rememberFile() return o } @@ -1266,6 +1272,7 @@ func openFileIO(cls *RClass, p, mode string) *IOObj { case 'r': o.wrClosed = !plus } + o.rememberFile() return o } @@ -1310,9 +1317,11 @@ func ioFlush(o *IOObj) { return } if errors.Is(err, fs.ErrPermission) { - err = withOwnerWrite(o.path, err, func() error { return o.writeDirty(content) }) + err = withOwnerWrite(o.path, o.ident, err, func() error { return o.writeDirty(content) }) } - if err != nil { + // A path that no longer names the opened file is left alone, and the bytes + // stay in the buffer: MRI's go to the orphaned inode (io_identity.go). + if err != nil && !errors.Is(err, errNotTheOpenedFile) { raiseFlushErr(err, o.path) } } @@ -2174,7 +2183,7 @@ func defStringIORead(cls *RClass) { // that size at once, not at the next flush, which is what File.size and a // second stream opened on the same path see straight afterwards. if o.path != "" && !ioIsStringIO(o) { - if err := os.Truncate(o.path, int64(n)); err != nil { + if err := o.truncateOpenedFile(int64(n)); err != nil { raiseOpenErrno(err, o.path) } } diff --git a/internal/vm/io_class.go b/internal/vm/io_class.go index f4cfae68..f8b81b4e 100644 --- a/internal/vm/io_class.go +++ b/internal/vm/io_class.go @@ -259,7 +259,7 @@ func (vm *VM) ioAdoptFd(cls *RClass, fd int, pos []object.Value, opts *object.Ha func (vm *VM) ioAdoptDescriptor(o, src *IOObj, pos []object.Value, opts *object.Hash) { ms := vm.ioResolveModeEnc(pos, opts) - o.isStr, o.buf, o.path = true, src.buf, src.path + o.isStr, o.buf, o.path, o.ident = true, src.buf, src.path, src.ident o.binmode, o.noAutoclose = ms.binmode, ms.noAutoclose o.extEnc, o.intEnc, o.newline = ms.extEnc, ms.intEnc, ms.newline if ms.explicit { diff --git a/internal/vm/io_descriptors.go b/internal/vm/io_descriptors.go index 53bbdcda..b4928278 100644 --- a/internal/vm/io_descriptors.go +++ b/internal/vm/io_descriptors.go @@ -379,7 +379,7 @@ func defIOSeekable(cls *RClass) { // writes stay pending. pwriteFile does exactly that, so on success // nothing new is waiting and the pending ranges are left as they were. if p, ok := ioPositionalPath(o); ok { - err := pwriteFile(p, data, off) + err := pwriteFile(p, o.ident, data, off) if err == nil { o.mirrorPwrite(data, off) // best effort: the file has the bytes return object.IntValue(int64(len(data))) @@ -388,8 +388,9 @@ func defIOSeekable(cls *RClass) { // the largest offset, ENOSPC, EIO. MRI raises that errno; it used to // be swallowed here and the bytes put in the buffer instead. A // refusal for permission is the one kept as before: the owner-write - // retry failed, so the buffer below is the stream's grant. - if !errors.Is(err, fs.ErrPermission) { + // retry failed, so the buffer below is the stream's grant. A path + // replaced since the check above goes to the buffer too (#974). + if !errors.Is(err, fs.ErrPermission) && !errors.Is(err, errNotTheOpenedFile) { raisePwriteErr(err, o.path) } } @@ -726,7 +727,7 @@ func ioReopenIO(vm *VM, o, other *IOObj) object.Value { o.isStr, o.w, o.pipe, o.isWriteEnd = other.isStr, other.w, other.pipe, other.isWriteEnd o.pipeSynced, o.reopened = other.pipeSynced, other.reopened // "if (RTEST(orig->pathv)) fptr->pathv = orig->pathv; else … fptr->pathv = Qnil" - o.path = other.path + o.path, o.ident = other.path, other.ident o.cls = other.cls // RBASIC_SET_CLASS(io, rb_obj_class(nfile)) return o } @@ -777,7 +778,7 @@ func ioReopenPath(vm *VM, o *IOObj, pos []object.Value, opts *object.Hash) objec ioFlush(o) } fresh := openFileIO(o.cls, name, modeBase(mode)) - o.buf, o.pos, o.path = fresh.buf, fresh.pos, fresh.path + o.buf, o.pos, o.path, o.ident = fresh.buf, fresh.pos, fresh.path, fresh.ident 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, "" diff --git a/internal/vm/io_dirty.go b/internal/vm/io_dirty.go index bad7460f..a7164a0d 100644 --- a/internal/vm/io_dirty.go +++ b/internal/vm/io_dirty.go @@ -69,16 +69,20 @@ func (o *IOObj) clipDirty(n int) { } // writeDirty puts the pending spans of content on disk, at their offsets, or -// appended for an append-mode stream. The file is created if it is missing, -// which is what os.WriteFile did here before: the stream holds no descriptor -// to the unlinked inode MRI would still write to, and dropping the bytes would -// be worse than putting them back under the path. +// appended for an append-mode stream. They are written only into the file the +// stream opened (io_identity.go): when the path no longer names it, MRI's +// bytes go to the orphaned inode and nothing at the path changes, so nothing +// is written and the bytes stay in the buffer. Only a stream that recorded no +// file creates one at a missing path, as it did before. func (o *IOObj) writeDirty(content []byte) error { - flags := os.O_WRONLY | os.O_CREATE + flags := os.O_WRONLY + if o.ident == nil { + flags |= os.O_CREATE + } if o.appendMode { flags |= os.O_APPEND } - f, err := os.OpenFile(o.path, flags, 0o644) + f, err := openOpenedFile(o.path, o.ident, flags) // errNotTheOpenedFile: ioFlush writes nothing if err != nil { return err } diff --git a/internal/vm/io_identity.go b/internal/vm/io_identity.go new file mode 100644 index 00000000..1a912ff3 --- /dev/null +++ b/internal/vm/io_identity.go @@ -0,0 +1,115 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "errors" + "os" +) + +// The file a stream opened (#974, its TOCTOU item). +// +// A File here holds no descriptor: flushes, #pwrite and #truncate reopen the +// stream's PATH. MRI writes through the descriptor it opened, so what the path +// names afterwards is not its concern: a file unlinked while open keeps +// receiving the stream's bytes on its orphaned inode, and a file renamed over +// the path or a symlink put in its place is never touched. Reopening by path +// did touch it. With the path swapped for a symlink to another file between +// the open and the flush, the stream's pending bytes were written into that +// other file; with the file unlinked, the flush created a new one in its +// place. +// +// So a file stream records the identity of the file it opened (ident, from +// os.Stat right after the open), and every write that goes back through the +// path checks it twice: on the path before opening it, so that a fifo or a +// device put in its place is never opened (an open for writing on a fifo +// blocks until a reader comes), and on the descriptor after, so that a rename +// between the two is caught. When the path no longer names that file, nothing +// is written there: the bytes stay in the stream's buffer, where its own reads +// still see them, which is what MRI's orphaned inode gives at the path. +// +// A stream with no regular file behind it (StringIO, a device, a fifo, IO.new +// on a descriptor) records nothing, and keeps the behaviour it had. +// +// The check on the path and the open are two system calls, so a fifo swapped +// in between them can still make the open block. Closing that window needs a +// non-blocking open, which is a per-platform flag; the descriptor check after +// the open already keeps such a file from being written. + +// errNotTheOpenedFile reports that a stream's path no longer names the file the +// stream opened: unlinked, renamed over, or replaced by something else. +var errNotTheOpenedFile = errors.New("the path no longer names the file this stream opened") + +// betweenCheckAndOpen, when set, runs in openOpenedFile between the check on +// the path and the open: the window a rename can use. Only tests set it, to +// replace the file there and assert that the check on the descriptor catches it. +var betweenCheckAndOpen func(path string) + +// rememberFile records the identity of the regular file at o.path, which has +// just been opened. +func (o *IOObj) rememberFile() { + if st, err := os.Stat(o.path); err == nil && st.Mode().IsRegular() { + // On Windows a FileInfo from os.Stat fetches its file ID lazily, BY + // PATH, at its first os.SameFile; fetched later it would be the ID of + // whatever the path names then, and every replacement would compare + // equal. Comparing it with itself now fetches and caches it while the + // path still names the opened file. Elsewhere the ID is already there. + _ = os.SameFile(st, st) + o.ident = st + } +} + +// namesOpenedFile reports whether st is the file this stream opened. A stream +// that recorded none accepts any. +func (o *IOObj) namesOpenedFile(st os.FileInfo) bool { + return o.ident == nil || os.SameFile(o.ident, st) +} + +// truncateOpenedFile is #truncate's ftruncate(2), reached by path. When the +// path no longer names the file the stream opened, nothing is truncated: MRI's +// ftruncate changes only the orphaned inode. With no file recorded it is a +// plain truncate of the path. +func (o *IOObj) truncateOpenedFile(n int64) error { + f, err := openOpenedFile(o.path, o.ident, os.O_WRONLY) + if errors.Is(err, errNotTheOpenedFile) { + return nil + } + if err != nil { + return err + } + terr := f.Truncate(n) + cerr := f.Close() + if terr != nil { + return terr + } + return cerr +} + +// openOpenedFile opens path with flag only while it still names ident, the +// file a stream opened; see the file comment. With ident nil it is a plain +// open. A path that is gone or names another file is errNotTheOpenedFile. +func openOpenedFile(path string, ident os.FileInfo, flag int) (*os.File, error) { + if ident != nil { + st, err := os.Stat(path) + if err != nil || !os.SameFile(ident, st) { + return nil, errNotTheOpenedFile + } + } + if betweenCheckAndOpen != nil { + betweenCheckAndOpen(path) + } + f, err := os.OpenFile(path, flag, 0o644) + if err != nil { + return nil, err + } + if ident != nil { + st, err := f.Stat() + if err != nil || !os.SameFile(ident, st) { + _ = f.Close() + return nil, errNotTheOpenedFile + } + } + return f, nil +} diff --git a/internal/vm/io_identity_internal_test.go b/internal/vm/io_identity_internal_test.go new file mode 100644 index 00000000..92bd6071 --- /dev/null +++ b/internal/vm/io_identity_internal_test.go @@ -0,0 +1,206 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "testing" +) + +// identOf records a file's identity the way rememberFile does. +func identOf(t *testing.T, path string) os.FileInfo { + t.Helper() + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + _ = os.SameFile(st, st) + return st +} + +// writeFile writes content to path, failing the test on error. +func writeFile(t *testing.T, path, content string, perm os.FileMode) { + t.Helper() + if err := os.WriteFile(path, []byte(content), perm); err != nil { + t.Fatal(err) + } +} + +// replaceFile renames a new file with content over path. +func replaceFile(t *testing.T, path, content string, perm os.FileMode) { + t.Helper() + tmp := path + ".new" + writeFile(t, tmp, content, perm) + if err := os.Rename(tmp, path); err != nil { + t.Fatal(err) + } +} + +// TestOpenOpenedFileOpensOnlyThatFile: each refusal below is a path that names +// something other than the file the stream opened. +func TestOpenOpenedFileOpensOnlyThatFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "f") + writeFile(t, path, "abc", 0o644) + ident := identOf(t, path) + + f, err := openOpenedFile(path, ident, os.O_RDONLY) + if err != nil { + t.Fatalf("the opened file itself: %v", err) + } + _ = f.Close() + + if _, err := openOpenedFile(filepath.Join(dir, "gone"), ident, os.O_RDONLY); !errors.Is(err, errNotTheOpenedFile) { + t.Errorf("a path that is gone: got %v, want errNotTheOpenedFile", err) + } + if _, err := openOpenedFile(filepath.Join(dir, "gone"), ident, os.O_WRONLY|os.O_CREATE); !errors.Is(err, errNotTheOpenedFile) { + t.Errorf("a path that is gone, with O_CREATE: got %v, want errNotTheOpenedFile", err) + } + if _, err := os.Stat(filepath.Join(dir, "gone")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("a refused O_CREATE created the file: %v", err) + } + + replaceFile(t, path, "other", 0o644) + if _, err := openOpenedFile(path, ident, os.O_WRONLY); !errors.Is(err, errNotTheOpenedFile) { + t.Errorf("a file renamed over the path: got %v, want errNotTheOpenedFile", err) + } + + // With no identity it is a plain open, which is what a stream with no + // regular file behind it keeps. + f, err = openOpenedFile(path, nil, os.O_RDONLY) + if err != nil { + t.Fatalf("no identity: %v", err) + } + _ = f.Close() + if _, err := openOpenedFile(filepath.Join(dir, "gone"), nil, os.O_RDONLY); errors.Is(err, errNotTheOpenedFile) || err == nil { + t.Errorf("no identity, a path that is gone: got %v, want the open's own error", err) + } +} + +// TestOpenOpenedFileChecksTheDescriptor: a rename between the check on the +// path and the open is caught by the check on what was opened, and the file +// that took the path is not written. +func TestOpenOpenedFileChecksTheDescriptor(t *testing.T) { + path := filepath.Join(t.TempDir(), "f") + writeFile(t, path, "abc", 0o644) + ident := identOf(t, path) + + betweenCheckAndOpen = func(p string) { replaceFile(t, p, "other", 0o644) } + defer func() { betweenCheckAndOpen = nil }() + f, err := openOpenedFile(path, ident, os.O_WRONLY) + if !errors.Is(err, errNotTheOpenedFile) { + if f != nil { + _ = f.Close() + } + t.Fatalf("got %v, want errNotTheOpenedFile", err) + } + if f != nil { + t.Error("a refused open handed back a file") + } + if got, _ := os.ReadFile(path); string(got) != "other" { + t.Errorf("the replacement holds %q, want \"other\"", got) + } +} + +// TestTruncateOpenedFile: the opened file is truncated, a replacement is not, +// and a stream with no identity truncates its path. +func TestTruncateOpenedFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "f") + writeFile(t, path, "abcdef", 0o644) + o := &IOObj{path: path} + o.rememberFile() + if o.ident == nil { + t.Fatal("rememberFile recorded nothing for a regular file") + } + if err := o.truncateOpenedFile(2); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != "ab" { + t.Errorf("the opened file: %q, want \"ab\"", got) + } + replaceFile(t, path, "other", 0o644) + if err := o.truncateOpenedFile(1); err != nil { + t.Errorf("a replaced path: %v, want nil", err) + } + if got, _ := os.ReadFile(path); string(got) != "other" { + t.Errorf("the replacement: %q, want \"other\"", got) + } + plain := &IOObj{path: path} + if err := plain.truncateOpenedFile(1); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != "o" { + t.Errorf("no identity: %q, want \"o\"", got) + } + if err := (&IOObj{path: filepath.Join(dir, "gone"), ident: o.ident}).truncateOpenedFile(0); err != nil { + t.Errorf("a path that is gone: %v, want nil", err) + } + + // The opened file's own errors are reported, not taken for a replacement. + own := filepath.Join(dir, "own") + writeFile(t, own, "abc", 0o644) + ow := &IOObj{path: own} + ow.rememberFile() + if err := ow.truncateOpenedFile(-1); err == nil { + t.Error("a truncate to -1 reported success") + } + if runtime.GOOS != "windows" && os.Getuid() != 0 { + if err := os.Chmod(own, 0o444); err != nil { + t.Fatal(err) + } + if err := ow.truncateOpenedFile(0); !errors.Is(err, os.ErrPermission) { + t.Errorf("a read-only file: %v, want a permission error", err) + } + } + + // rememberFile records nothing for what is not a regular file. + d := &IOObj{path: dir} + d.rememberFile() + if d.ident != nil { + t.Error("rememberFile recorded a directory") + } +} + +// TestWithOwnerWriteTouchesOnlyTheOpenedFile: the owner-write grant goes to +// the file the stream opened, never to what its path names now. +func TestWithOwnerWriteTouchesOnlyTheOpenedFile(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("asserts Unix permission bits") + } + dir := t.TempDir() + path := filepath.Join(dir, "f") + writeFile(t, path, "abc", 0o444) + ident := identOf(t, path) + refused := errors.New("refused") + + // The path names another file: nothing runs, nothing is chmodded. + replaceFile(t, path, "other", 0o444) + called := false + err := withOwnerWrite(path, ident, refused, func() error { called = true; return nil }) + if !errors.Is(err, errNotTheOpenedFile) || called { + t.Errorf("a replaced path: err=%v called=%v, want errNotTheOpenedFile and no write", err, called) + } + if st, _ := os.Stat(path); st.Mode().Perm() != 0o444 { + t.Errorf("the replacement's mode became %v", st.Mode().Perm()) + } + + // Replaced DURING the write: the restoring chmod is skipped, so the + // file that took the path keeps its own owner-write bit. + ident = identOf(t, path) + err = withOwnerWrite(path, ident, refused, func() error { + replaceFile(t, path, "third", 0o644) + return nil + }) + if err != nil { + t.Fatal(err) + } + if st, _ := os.Stat(path); st.Mode().Perm() != 0o644 { + t.Errorf("a file put in place during the write: mode %v, want 0644", st.Mode().Perm()) + } +} diff --git a/internal/vm/io_identity_test.go b/internal/vm/io_identity_test.go new file mode 100644 index 00000000..b00455a7 --- /dev/null +++ b/internal/vm/io_identity_test.go @@ -0,0 +1,80 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "fmt" + "path/filepath" + "runtime" + "testing" +) + +// TestAWriteByPathReachesOnlyTheOpenedFile: a File writes through the file it +// opened, never through whatever its path names later (#974, TOCTOU). Every +// want is MRI 4.0.7's output for the same program (arm64-darwin25, rubydiff, +// 2026-11-22). The first seven rows diverged before the fix. The symlink row +// is the security one: a stream whose path was swapped for a symlink wrote its +// pending bytes into the link's target ("ABctim"). The last four are guards: a +// file opened THROUGH a symlink, a read-only file written by the open's grant, +// and plain writes, which must keep reaching the file. +func TestAWriteByPathReachesOnlyTheOpenedFile(t *testing.T) { + const prelude = "path = File.join(d, \"f\"); other = File.join(d, \"other\")\n" + + "replace = ->(c) { File.write(other, c); File.rename(other, path) }\n" + cases := []struct { + name, src, want string + symlink bool // needs File.symlink, which Windows runners refuse + unixMode bool // asserts permission bits Windows does not keep + }{ + {name: "an unlinked file is not created again", src: `f = File.open(path, "w"); f.write("AB"); File.delete(path); f.flush + a = File.exist?(path); f.close; p [a, File.exist?(path)]`, want: "[false, false]\n"}, + {name: "a file renamed over the path is not written", src: `f = File.open(path, "w"); f.write("AB"); replace.("other"); f.close + p File.read(path)`, want: "\"other\"\n"}, + {name: "a symlink put in its place is not followed", symlink: true, src: `victim = File.join(d, "victim"); File.write(victim, "victim") + f = File.open(path, "w"); f.write("AB"); File.delete(path); File.symlink(victim, path); f.close + p File.read(victim)`, want: "\"victim\"\n"}, + {name: "pwrite", src: `f = File.open(path, "w"); f.write("x"); f.flush; replace.("other"); f.pwrite("ZZ", 0); f.close + p File.read(path)`, want: "\"other\"\n"}, + {name: "truncate", src: `f = File.open(path, "w"); f.write("xyz"); f.flush; replace.("other"); f.truncate(1); f.close + p File.read(path)`, want: "\"other\"\n"}, + {name: "the stream's own reads still see its bytes", src: `File.write(path, "abcdef") + f = File.open(path, "r+"); f.write("XY"); replace.("other"); f.rewind + p [f.read, f.size, f.pread(2, 0)]; f.close; p File.read(path)`, want: "[\"XYcdef\", 6, \"XY\"]\n\"other\"\n"}, + {name: "append mode", src: `File.write(path, "abc"); f = File.open(path, "a"); f.write("Z"); replace.("other"); f.close + p File.read(path)`, want: "\"other\"\n"}, + {name: "integer flags", src: `File.write(path, "abc"); f = File.open(path, File::RDWR); f.write("Z"); replace.("other"); f.close + p File.read(path)`, want: "\"other\"\n"}, + {name: "after reopen, the reopened file", src: `real = File.join(d, "real"); File.write(path, "abc"); File.write(real, "real") + f = File.open(real, "r+"); f.reopen(path, "r+"); f.write("Z"); replace.("other"); f.close + p [File.read(path), File.read(real)]`, want: "[\"other\", \"real\"]\n"}, + {name: "sync = true", src: `File.write(path, "abc"); f = File.open(path, "r+"); f.sync = true; replace.("other"); f.write("Z"); f.close + p File.read(path)`, want: "\"other\"\n"}, + {name: "deleted, then created again by another writer", src: `File.write(path, "abc") + f = File.open(path, "r+"); f.write("Z"); File.delete(path); File.write(path, "new"); f.close + p File.read(path)`, want: "\"new\"\n"}, + // Guards: these must keep writing. + {name: "guard: opened through a symlink", symlink: true, src: `real = File.join(d, "real"); link = File.join(d, "link") + File.write(real, "0123"); File.symlink(real, link) + f = File.open(link, "r+"); f.write("AB"); f.close; a = File.read(real) + f = File.open(link, "a"); f.write("Z"); f.flush; f.pwrite("Q", 0); f.truncate(3); f.close + p [a, File.read(real)]`, want: "[\"AB23\", \"QB2\"]\n"}, + {name: "guard: a read-only file written by the open's grant", unixMode: true, + src: `f = File.new(path, "w", 0o444); f.write("ro"); f.close; p [File.read(path), File.stat(path).mode & 0o777]`, + want: "[\"ro\", 292]\n"}, + {name: "guard: plain integer flags", src: `File.write(path, "abc"); f = File.open(path, File::RDWR); f.write("Z"); f.close + p File.read(path)`, want: "\"Zbc\"\n"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if runtime.GOOS == "windows" && (c.symlink || c.unixMode) { + t.Skip("needs symlinks or Unix permission bits") + } + d := filepath.ToSlash(t.TempDir()) + src := fmt.Sprintf("d = %q\n%s%s\n", d, prelude, c.src) + if got := eval(t, src); got != c.want { + t.Errorf("got=%q\nwant=%q", got, c.want) + } + }) + } +} diff --git a/internal/vm/io_positional.go b/internal/vm/io_positional.go index 3d626aa6..7f8698ae 100644 --- a/internal/vm/io_positional.go +++ b/internal/vm/io_positional.go @@ -40,7 +40,10 @@ func ioPositionalPath(o *IOObj) (string, bool) { return "", false } st, err := os.Stat(o.path) // "" (a StringIO) does not resolve either - if err != nil || !st.Mode().IsRegular() { + // A path that now names another file is not reachable either (#974): MRI's + // descriptor still reaches the file it opened, whose bytes are the + // buffer's. + if err != nil || !st.Mode().IsRegular() || !o.namesOpenedFile(st) { return "", false } return o.path, true @@ -48,11 +51,12 @@ func ioPositionalPath(o *IOObj) (string, bool) { // pwriteFile writes data at off in the file at path and touches nothing else: // no other byte of the file, and nothing of the stream that opened it. A write -// past the end leaves a hole, as pwrite(2) does. -func pwriteFile(path string, data []byte, off int64) error { - err := writeAtPath(path, data, off) +// past the end leaves a hole, as pwrite(2) does. ident is the file the stream +// opened, or nil (io_identity.go). +func pwriteFile(path string, ident os.FileInfo, data []byte, off int64) error { + err := writeAtPath(path, ident, data, off) if errors.Is(err, fs.ErrPermission) { - err = writeAtWithOwnerWrite(path, data, off, err) + err = writeAtWithOwnerWrite(path, ident, data, off, err) } return err } @@ -61,12 +65,12 @@ func pwriteFile(path string, data []byte, off int64) error { // owner-write bit put back for the length of the write (withOwnerWrite): the // stream already holds the descriptor's grant (`File.new(path, "w", 0444)` // writes through), and reopening by path must not take it away. -func writeAtWithOwnerWrite(path string, data []byte, off int64, refused error) error { - return withOwnerWrite(path, refused, func() error { return writeAtPath(path, data, off) }) +func writeAtWithOwnerWrite(path string, ident os.FileInfo, data []byte, off int64, refused error) error { + return withOwnerWrite(path, ident, refused, func() error { return writeAtPath(path, ident, data, off) }) } -func writeAtPath(path string, data []byte, off int64) error { - f, err := os.OpenFile(path, os.O_WRONLY, 0) +func writeAtPath(path string, ident os.FileInfo, data []byte, off int64) error { + f, err := openOpenedFile(path, ident, os.O_WRONLY) if err != nil { return err } diff --git a/internal/vm/io_positional_internal_test.go b/internal/vm/io_positional_internal_test.go index 72e75933..705a2903 100644 --- a/internal/vm/io_positional_internal_test.go +++ b/internal/vm/io_positional_internal_test.go @@ -62,7 +62,7 @@ func TestWriteAtWithOwnerWriteKeepsTheRefusal(t *testing.T) { t.Errorf("an unreadable mode crashed the retry: %v", r) } }() - err = writeAtWithOwnerWrite(filepath.Join(t.TempDir(), "gone"), []byte("x"), 0, refused) + err = writeAtWithOwnerWrite(filepath.Join(t.TempDir(), "gone"), nil, []byte("x"), 0, refused) }() if !errors.Is(err, refused) { t.Errorf("got %v, want the original refusal", err) @@ -76,7 +76,7 @@ func TestWriteAtPathReportsAFailedWrite(t *testing.T) { if err := os.WriteFile(file, []byte("0123"), 0o644); err != nil { t.Fatal(err) } - if err := writeAtPath(file, []byte("x"), -1); err == nil { + if err := writeAtPath(file, nil, []byte("x"), -1); err == nil { t.Error("a write at offset -1 reported success") } } diff --git a/internal/vm/wave28_cover_gaps_test.go b/internal/vm/wave28_cover_gaps_test.go index 6beb0e65..3dc4b145 100644 --- a/internal/vm/wave28_cover_gaps_test.go +++ b/internal/vm/wave28_cover_gaps_test.go @@ -74,13 +74,11 @@ end // file on disk is that size at once, which is what File.size and a second // stream opened on the same path see straight afterwards. MRI 4.0.5 prints 3. // -// The second case documents a DIVERGENCE rather than asserting a contract. -// MRI's rb_io_truncate is ftruncate(2) on the descriptor, so it succeeds after -// the path is unlinked; rbgo's IOObj is buffer-backed with a synthetic fd, so -// it truncates by path and answers ENOENT. That is the same root cause as -// File#stat on an unlinked file, and it is tracked in issue #635 — recorded -// here so the branch is exercised and the difference is visible at the point -// where someone would otherwise read rbgo's answer as correct. +// The second case: MRI's rb_io_truncate is ftruncate(2) on the descriptor, so +// it succeeds after the path is unlinked. rbgo's IOObj is buffer-backed with a +// synthetic fd and truncates by path; it answered ENOENT (#635) until it +// learned the file it opened (#974), and now leaves a path that no longer +// names that file alone and succeeds, as MRI does. func TestWave28TruncateFileOnDisk(t *testing.T) { dir := t.TempDir() src := `p1 = ` + rq(dir+"/sz.txt") + ` @@ -100,8 +98,10 @@ rescue => e p e.class.to_s end ` - // MRI prints 3 then :ok. rbgo prints 3 then the errno, per #635. - if got, want := runFS(t, src), "3\n\"Errno::ENOENT\"\n"; got != want { + // MRI prints 3 then :ok: its ftruncate reaches the unlinked inode. rbgo + // raised Errno::ENOENT here (#635) until a stream recorded the file it + // opened (#974): the path that no longer names it is now left alone. + if got, want := runFS(t, src), "3\n:ok\n"; got != want { t.Errorf("truncate on disk: got %q want %q", got, want) } } From 8c2906386809124fadd3c57e96558f3ac11b2651 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 18:21:30 +0100 Subject: [PATCH 5/9] vm: pin the opened inode, so a reused inode number is not the opened file The Linux runner showed the row "deleted, then created again by another writer" writing the stream's byte into the new file: ext4 gave the new file the old inode number, and os.SameFile took it for the file the stream opened. MRI's open descriptor keeps the inode alive, so its number cannot be reused while the stream is open. On Unix a file stream now holds a descriptor on the file it opened (pin, opened O_RDONLY or else O_WRONLY, with O_NONBLOCK|O_NOCTTY so a fifo cannot block it), takes its identity from that descriptor, and releases it when it closes or moves to another file. A stream adopting another's file (IO#reopen, IO.new on its descriptor) gets its own dup. A file whose mode refuses both opens keeps the plain stat identity. #truncate on a file made read-only after the open now lends the open's grant for the call, as a flush does: MRI 4.0.7 truncates through its descriptor ([2, 292]) where rbgo raised Errno::EACCES. Its refusals are raised with their errno. Tests: the pin and its dup; the truncate grant at the Ruby level and its refusal; raiseFlushErr's three error shapes; a dirty span past the content. rubydiff against MRI 4.0.7: probe978t, probe974t, probe974t2 agree. Refs #974 Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- internal/vm/io.go | 9 +- internal/vm/io_class.go | 2 + internal/vm/io_descriptors.go | 12 +++ internal/vm/io_dirty_internal_test.go | 39 ++++++++ internal/vm/io_identity.go | 69 +++++++++++-- internal/vm/io_identity_internal_test.go | 24 +++++ internal/vm/io_identity_test.go | 3 + internal/vm/io_pin_other.go | 18 ++++ internal/vm/io_pin_unix.go | 48 +++++++++ internal/vm/io_pin_unix_internal_test.go | 121 +++++++++++++++++++++++ 11 files changed, 334 insertions(+), 13 deletions(-) create mode 100644 internal/vm/io_pin_other.go create mode 100644 internal/vm/io_pin_unix.go create mode 100644 internal/vm/io_pin_unix_internal_test.go diff --git a/README.md b/README.md index 4323a659..110d161d 100644 --- a/README.md +++ b/README.md @@ -878,7 +878,7 @@ Otherwise: | `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 or replaced. Both fall back to the stream's buffer and leave the path alone, as MRI does, but MRI's bytes reach the old inode, which other processes holding it would see. 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`, `#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 | | `IO#flush` on a `File` another writer changed | as in MRI, a flush puts on disk only the byte ranges this stream wrote, at their offsets (appended in append mode), so another writer's bytes elsewhere in the file, an append, or a truncation stand. A flush the system refuses raises its own errno (`Errno::ENOSPC`, `Errno::EISDIR`, …) ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The divergence is a bound: past 256 separate unflushed ranges, rbgo merges them into one span, and a flush then rewrites the gaps between them with its own copy of those bytes. MRI's 8192-byte write buffer flushes long before that. Reaching the file by path is the same root as the rows above | -| a `File` whose path is unlinked, renamed over, or swapped for a symlink while it is open | as in MRI, its writes never reach what the path names now. A stream records the file it opened, and a flush, `#close`, `#pwrite`, `#truncate` or `sync = true` write checks the path against it before opening it and checks the opened file after, so a file put in its place, or the target of a symlink put there, is left alone, and an unlinked file is not created again. Before, a symlink swapped in between the open and the flush received the stream's pending bytes ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The stream's own reads, `#size` and `#pread` still see its bytes. The divergence: MRI's bytes land on the orphaned inode, where rbgo keeps them in the stream's buffer, so another process holding that inode does not see them. A fifo swapped in between rbgo's two checks can still make the open block. A file opened through a symlink is written through it, as in MRI | +| a `File` whose path is unlinked, renamed over, or swapped for a symlink while it is open | as in MRI, its writes never reach what the path names now. A stream records the file it opened, and a flush, `#close`, `#pwrite`, `#truncate` or `sync = true` write checks the path against it before opening it and checks the opened file after, so a file put in its place, or the target of a symlink put there, is left alone, and an unlinked file is not created again. Before, a symlink swapped in between the open and the flush received the stream's pending bytes ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The stream's own reads, `#size` and `#pread` still see its bytes. On Unix the stream also holds a descriptor on the file it opened, only to keep that inode alive, so a file deleted and created again at once cannot reuse its inode number and pass for it. A file made read-only after the open is still truncated by `#truncate`, as MRI's `ftruncate` on the open descriptor does. The divergence: MRI's bytes land on the orphaned inode, where rbgo keeps them in the stream's buffer, so another process holding that inode does not see them. A fifo swapped in between rbgo's two checks can still make the open block. A file opened through a symlink is written through it, as in MRI | | 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 747603d6..957cb198 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -155,6 +155,10 @@ type IOObj struct { // ident is the regular file this stream opened, which a write back by // path must still find there (io_identity.go). Nil when there is none. ident os.FileInfo + // pin is a descriptor held on that file, only to keep its inode number + // from being reused while the stream is open (io_identity.go). Nil where + // the platform needs none or the file refused it. + pin *os.File } // pipeBuf is the shared byte channel behind an IO.pipe reader/writer pair. Each @@ -1788,6 +1792,7 @@ func defIOWrite(cls *RClass) { ioFlush(o) o.pipeEndClosed() o.releaseLockFd() // close(2) drops any flock this stream still holds + o.unpin() o.closed = true return object.NilV }) @@ -2183,9 +2188,7 @@ func defStringIORead(cls *RClass) { // that size at once, not at the next flush, which is what File.size and a // second stream opened on the same path see straight afterwards. if o.path != "" && !ioIsStringIO(o) { - if err := o.truncateOpenedFile(int64(n)); err != nil { - raiseOpenErrno(err, o.path) - } + o.truncateOnDisk(int64(n)) } return object.IntValue(0) }) diff --git a/internal/vm/io_class.go b/internal/vm/io_class.go index f8b81b4e..8d764873 100644 --- a/internal/vm/io_class.go +++ b/internal/vm/io_class.go @@ -260,6 +260,8 @@ func (vm *VM) ioAdoptFd(cls *RClass, fd int, pos []object.Value, opts *object.Ha func (vm *VM) ioAdoptDescriptor(o, src *IOObj, pos []object.Value, opts *object.Hash) { ms := vm.ioResolveModeEnc(pos, opts) o.isStr, o.buf, o.path, o.ident = true, src.buf, src.path, src.ident + o.unpin() + o.pin = dupPin(src.pin) // its own, so either stream may close first o.binmode, o.noAutoclose = ms.binmode, ms.noAutoclose o.extEnc, o.intEnc, o.newline = ms.extEnc, ms.intEnc, ms.newline if ms.explicit { diff --git a/internal/vm/io_descriptors.go b/internal/vm/io_descriptors.go index b4928278..0a7a0866 100644 --- a/internal/vm/io_descriptors.go +++ b/internal/vm/io_descriptors.go @@ -223,11 +223,13 @@ func defIOReadExtra(cls *RClass) { } o.rdClosed, o.closed = true, true o.pipeEndClosed() + o.unpin() return object.NilV } o.rdClosed = true if o.wrClosed { // both halves shut ⇒ the stream is fully closed o.closed = true + o.unpin() } return object.NilV }) @@ -246,12 +248,14 @@ func defIOReadExtra(cls *RClass) { ioFlush(o) o.wrClosed, o.closed = true, true o.pipeEndClosed() + o.unpin() return object.NilV } ioFlush(o) o.wrClosed = true if o.rdClosed { o.closed = true + o.unpin() } return object.NilV }) @@ -728,6 +732,10 @@ func ioReopenIO(vm *VM, o, other *IOObj) object.Value { o.pipeSynced, o.reopened = other.pipeSynced, other.reopened // "if (RTEST(orig->pathv)) fptr->pathv = orig->pathv; else … fptr->pathv = Qnil" o.path, o.ident = other.path, other.ident + o.unpin() + // Its own pin, so either stream may close first. + o.pin = dupPin(other.pin) + o.cls = other.cls // RBASIC_SET_CLASS(io, rb_obj_class(nfile)) return o } @@ -779,6 +787,10 @@ 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, o.ident = fresh.buf, fresh.pos, fresh.path, fresh.ident + o.unpin() + // The stream takes the new file's pin over. + o.pin, fresh.pin = fresh.pin, nil + 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, "" diff --git a/internal/vm/io_dirty_internal_test.go b/internal/vm/io_dirty_internal_test.go index 0ed49c6c..f2c7f03e 100644 --- a/internal/vm/io_dirty_internal_test.go +++ b/internal/vm/io_dirty_internal_test.go @@ -5,9 +5,11 @@ package vm import ( + "errors" "fmt" "os" "path/filepath" + "syscall" "testing" ) @@ -35,6 +37,43 @@ func TestAFlushThatCannotWriteRaises(t *testing.T) { } } +// TestWriteDirtySkipsASpanPastTheContent: a span that starts at or past the +// end of what is to be written puts nothing on disk, rather than a slice +// bound panic or a write of bytes that are not there. +func TestWriteDirtySkipsASpanPastTheContent(t *testing.T) { + path := filepath.Join(t.TempDir(), "f") + if err := os.WriteFile(path, []byte("data"), 0o644); err != nil { + t.Fatal(err) + } + o := &IOObj{path: path, dirty: []ioSpan{{6, 8}, {0, 2}}} + if err := o.writeDirty([]byte("XY")); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != "XYta" { + t.Errorf("the file holds %q, want \"XYta\"", got) + } +} + +// TestRaiseFlushErrKeepsWhatTheErrorSays: an errno with an Errno class raises +// that class; an errno with none raises SystemCallError, as MRI's +// rb_syserr_fail does for an unknown errno; an error carrying no errno at all +// is an I/O error. +func TestRaiseFlushErrKeepsWhatTheErrorSays(t *testing.T) { + cases := []struct { + err error + want string + }{ + {syscall.Errno(errnoNumbers["ENOSPC"]), "Errno::ENOSPC"}, + {syscall.Errno(4093), "SystemCallError"}, + {errors.New("no errno here"), "Errno::EIO"}, + } + for _, c := range cases { + if got := catchRaise(func() { raiseFlushErr(c.err, "f") }); got != c.want { + t.Errorf("raiseFlushErr(%v) raised %q, want %q", c.err, got, c.want) + } + } +} + // TestIOFlushWritesOnlyAWritableFileWithPendingBytes: ioFlush's gate. A // read-only stream, a stream with no path, and one with nothing pending put // nothing on disk and raise nothing, whatever its buffer holds: a read-only diff --git a/internal/vm/io_identity.go b/internal/vm/io_identity.go index 1a912ff3..12834ad3 100644 --- a/internal/vm/io_identity.go +++ b/internal/vm/io_identity.go @@ -6,6 +6,7 @@ package vm import ( "errors" + "io/fs" "os" ) @@ -33,6 +34,18 @@ import ( // A stream with no regular file behind it (StringIO, a device, a fifo, IO.new // on a descriptor) records nothing, and keeps the behaviour it had. // +// An identity is a device and an inode number, and an inode number is reused +// once its file is gone: on ext4, a file deleted and created again at once at +// the same path often gets the old number back, and compared equal to the file +// the stream opened (the Linux runner showed it, writing the stream's byte into +// the new file). MRI's open descriptor keeps the inode alive, so its number +// cannot be reused. On Unix a stream therefore holds a descriptor too (pin, +// io_pin_unix.go), only to keep the inode alive, and takes its identity from +// that descriptor; the pin is released when the stream closes, and a stream that +// adopts another's file gets its own dup. A file whose mode refuses both a read +// and a write open gets no pin and keeps the plain stat identity, and with it +// the reuse window. +// // The check on the path and the open are two system calls, so a fifo swapped // in between them can still make the open block. Closing that window needs a // non-blocking open, which is a per-platform flag; the descriptor check after @@ -48,16 +61,39 @@ var errNotTheOpenedFile = errors.New("the path no longer names the file this str var betweenCheckAndOpen func(path string) // rememberFile records the identity of the regular file at o.path, which has -// just been opened. +// just been opened, and pins its inode where the platform allows it. func (o *IOObj) rememberFile() { - if st, err := os.Stat(o.path); err == nil && st.Mode().IsRegular() { - // On Windows a FileInfo from os.Stat fetches its file ID lazily, BY - // PATH, at its first os.SameFile; fetched later it would be the ID of - // whatever the path names then, and every replacement would compare - // equal. Comparing it with itself now fetches and caches it while the - // path still names the opened file. Elsewhere the ID is already there. - _ = os.SameFile(st, st) - o.ident = st + o.unpin() + o.ident = nil + // The identity is the pinned descriptor's own, so the two cannot name + // different files. + if pin := pinFile(o.path); pin != nil { + if pst, err := pin.Stat(); err == nil && pst.Mode().IsRegular() { + o.pin, o.ident = pin, pst + return + } + _ = pin.Close() // a directory, a device, a fifo: nothing to remember + return + } + st, err := os.Stat(o.path) + if err != nil || !st.Mode().IsRegular() { + return + } + // On Windows a FileInfo from os.Stat fetches its file ID lazily, BY PATH, + // at its first os.SameFile; fetched later it would be the ID of whatever + // the path names then, and every replacement would compare equal. + // Comparing it with itself now fetches and caches it while the path still + // names the opened file. Elsewhere the ID is already there. + _ = os.SameFile(st, st) + o.ident = st +} + +// unpin releases the descriptor holding the opened file's inode, when the +// stream closes or moves to another file. +func (o *IOObj) unpin() { + if o.pin != nil { + _ = o.pin.Close() + o.pin = nil } } @@ -87,6 +123,21 @@ func (o *IOObj) truncateOpenedFile(n int64) error { return cerr } +// truncateOnDisk is the disk half of IO#truncate. MRI's ftruncate goes through +// the descriptor the open granted, so a file made read-only since is still +// truncated; reaching it by path, the open's grant is lent for the call, as a +// flush does (withOwnerWrite). A path that no longer names the opened file is +// left alone; any other refusal is raised with its errno. +func (o *IOObj) truncateOnDisk(n int64) { + err := o.truncateOpenedFile(n) + if errors.Is(err, fs.ErrPermission) { + err = withOwnerWrite(o.path, o.ident, err, func() error { return o.truncateOpenedFile(n) }) + } + if err != nil && !errors.Is(err, errNotTheOpenedFile) { + raiseOpenErrno(err, o.path) + } +} + // openOpenedFile opens path with flag only while it still names ident, the // file a stream opened; see the file comment. With ident nil it is a plain // open. A path that is gone or names another file is errNotTheOpenedFile. diff --git a/internal/vm/io_identity_internal_test.go b/internal/vm/io_identity_internal_test.go index 92bd6071..c4227ad4 100644 --- a/internal/vm/io_identity_internal_test.go +++ b/internal/vm/io_identity_internal_test.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "testing" ) @@ -167,6 +168,29 @@ func TestTruncateOpenedFile(t *testing.T) { } } +// TestTruncateOnDiskRaisesARefusal: a truncate the file refuses is raised with +// its errno. A directory under a stream that recorded no file is the case: the +// open for writing is refused before any truncate. +func TestTruncateOnDiskRaisesARefusal(t *testing.T) { + o := &IOObj{path: t.TempDir()} + if got := catchRaise(func() { o.truncateOnDisk(0) }); !strings.HasPrefix(got, "Errno::") { + t.Errorf("truncating a directory raised %q, want an Errno", got) + } + // A replaced path is left alone, and nothing is raised. + path := filepath.Join(t.TempDir(), "f") + writeFile(t, path, "abcdef", 0o644) + r := &IOObj{path: path} + r.rememberFile() + defer r.unpin() + replaceFile(t, path, "other", 0o644) + if got := catchRaise(func() { r.truncateOnDisk(1) }); got != "" { + t.Errorf("a replaced path raised %q", got) + } + if got, _ := os.ReadFile(path); string(got) != "other" { + t.Errorf("the replacement holds %q, want \"other\"", got) + } +} + // TestWithOwnerWriteTouchesOnlyTheOpenedFile: the owner-write grant goes to // the file the stream opened, never to what its path names now. func TestWithOwnerWriteTouchesOnlyTheOpenedFile(t *testing.T) { diff --git a/internal/vm/io_identity_test.go b/internal/vm/io_identity_test.go index b00455a7..2f80bd68 100644 --- a/internal/vm/io_identity_test.go +++ b/internal/vm/io_identity_test.go @@ -62,6 +62,9 @@ func TestAWriteByPathReachesOnlyTheOpenedFile(t *testing.T) { {name: "guard: a read-only file written by the open's grant", unixMode: true, src: `f = File.new(path, "w", 0o444); f.write("ro"); f.close; p [File.read(path), File.stat(path).mode & 0o777]`, want: "[\"ro\", 292]\n"}, + {name: "guard: truncate a file made read-only after the open", unixMode: true, + src: `File.write(path, "abcdef"); f = File.open(path, "r+"); File.chmod(0o444, path); f.truncate(2); f.close + p [File.size(path), File.stat(path).mode & 0o777]`, want: "[2, 292]\n"}, {name: "guard: plain integer flags", src: `File.write(path, "abc"); f = File.open(path, File::RDWR); f.write("Z"); f.close p File.read(path)`, want: "\"Zbc\"\n"}, } diff --git a/internal/vm/io_pin_other.go b/internal/vm/io_pin_other.go new file mode 100644 index 00000000..4ea946d1 --- /dev/null +++ b/internal/vm/io_pin_other.go @@ -0,0 +1,18 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build windows || wasm || plan9 + +package vm + +import "os" + +// pinFile holds nothing here. On Windows an open handle would refuse the +// file's deletion and renaming, which a stream must not do, and NTFS file IDs +// carry a sequence number, so a recreated file never takes the old one's ID. +// wasm and Plan 9 keep the plain stat identity. +func pinFile(string) *os.File { return nil } + +// dupPin has no pin to duplicate here. +func dupPin(*os.File) *os.File { return nil } diff --git a/internal/vm/io_pin_unix.go b/internal/vm/io_pin_unix.go new file mode 100644 index 00000000..5177cd78 --- /dev/null +++ b/internal/vm/io_pin_unix.go @@ -0,0 +1,48 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !windows && !wasm && !plan9 + +package vm + +import ( + "os" + + "golang.org/x/sys/unix" +) + +// pinFile opens a descriptor on whatever path names, only to hold its inode: +// see io_identity.go, which keeps it for a regular file alone. Non-blocking, +// so that a fifo cannot block the open, and O_NOCTTY, so that a terminal never +// becomes the controlling one; read-only first, and write-only for a file whose +// mode refuses reading. nil when neither opens. +func pinFile(path string) *os.File { + for _, flag := range []int{os.O_RDONLY, os.O_WRONLY} { + if f, err := os.OpenFile(path, flag|unix.O_NONBLOCK|unix.O_NOCTTY, 0); err == nil { + return f + } + } + return nil +} + +// dupFd is dup(2) with close-on-exec, the seam a test uses to make it fail. +var dupFd = func(fd int) (int, error) { return unix.FcntlInt(uintptr(fd), unix.F_DUPFD_CLOEXEC, 0) } + +// dupPin gives a second stream its own descriptor on the pinned inode, so that +// closing one stream leaves the other's pin in place. nil when f is nil, closed, +// or the dup fails, which leaves that stream with an unpinned identity. +func dupPin(f *os.File) *os.File { + if f == nil { + return nil + } + rc, err := f.SyscallConn() + if err != nil { + return nil + } + nfd, derr := -1, error(nil) + if err := rc.Control(func(fd uintptr) { nfd, derr = dupFd(int(fd)) }); err != nil || derr != nil { + return nil + } + return os.NewFile(uintptr(nfd), f.Name()) +} diff --git a/internal/vm/io_pin_unix_internal_test.go b/internal/vm/io_pin_unix_internal_test.go new file mode 100644 index 00000000..88fa9cff --- /dev/null +++ b/internal/vm/io_pin_unix_internal_test.go @@ -0,0 +1,121 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !windows && !wasm && !plan9 + +package vm + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +// TestRememberFilePinsTheOpenedInode: a regular file is pinned and its +// identity is the pin's; unpin releases the descriptor. Without the pin, a +// file deleted and created again at once on ext4 takes the old inode number +// and passes for the opened one. +func TestRememberFilePinsTheOpenedInode(t *testing.T) { + path := filepath.Join(t.TempDir(), "f") + writeFile(t, path, "abc", 0o644) + o := &IOObj{path: path} + o.rememberFile() + if o.pin == nil || o.ident == nil { + t.Fatalf("pin=%v ident=%v, want both", o.pin, o.ident) + } + pst, err := o.pin.Stat() + if err != nil || !os.SameFile(pst, o.ident) { + t.Errorf("the identity is not the pin's: %v", err) + } + pin := o.pin + o.unpin() + if o.pin != nil { + t.Error("unpin left the pin") + } + if _, err := pin.Stat(); !errors.Is(err, os.ErrClosed) { + t.Errorf("unpin did not close the descriptor: %v", err) + } + o.unpin() // a second release is a no-op + + // Remembering again releases the previous pin first. + o.rememberFile() + first := o.pin + o.rememberFile() + if _, err := first.Stat(); !errors.Is(err, os.ErrClosed) { + t.Errorf("a second rememberFile leaked the first pin: %v", err) + } + o.unpin() +} + +// TestRememberFileOutsideARegularFile: a directory is opened by pinFile and +// let go, and a file no open accepts keeps the plain stat identity. +func TestRememberFileOutsideARegularFile(t *testing.T) { + dir := t.TempDir() + d := &IOObj{path: dir} + d.rememberFile() + if d.pin != nil || d.ident != nil { + t.Errorf("a directory: pin=%v ident=%v, want neither", d.pin, d.ident) + } + gone := &IOObj{path: filepath.Join(dir, "gone")} + gone.rememberFile() + if gone.pin != nil || gone.ident != nil { + t.Errorf("a missing path: pin=%v ident=%v, want neither", gone.pin, gone.ident) + } + if os.Getuid() == 0 { + t.Skip("root opens a file whatever its mode") + } + wo := filepath.Join(dir, "wo") + writeFile(t, wo, "abc", 0o200) + w := &IOObj{path: wo} + w.rememberFile() + if w.pin == nil { + t.Error("a write-only file was not pinned through the write-only open") + } + w.unpin() + none := filepath.Join(dir, "none") + writeFile(t, none, "abc", 0o000) + n := &IOObj{path: none} + n.rememberFile() + if n.pin != nil || n.ident == nil { + t.Errorf("a file no open accepts: pin=%v ident=%v, want the stat identity alone", n.pin, n.ident) + } +} + +// TestDupPinGivesItsOwnDescriptor: the dup survives the original's close and +// names the same inode; nil, a closed pin and a failed dup give no pin. +func TestDupPinGivesItsOwnDescriptor(t *testing.T) { + path := filepath.Join(t.TempDir(), "f") + writeFile(t, path, "abc", 0o644) + pin := pinFile(path) + if pin == nil { + t.Fatal("pinFile refused a readable file") + } + dup := dupPin(pin) + if dup == nil { + t.Fatal("dupPin refused an open pin") + } + a, _ := pin.Stat() + _ = pin.Close() + b, err := dup.Stat() + if err != nil || !os.SameFile(a, b) { + t.Errorf("the dup does not hold the same inode after the original closed: %v", err) + } + _ = dup.Close() + + if dupPin(nil) != nil { + t.Error("dupPin(nil) gave a pin") + } + if dupPin(pin) != nil { + t.Error("dupPin of a closed pin gave a pin") + } + again := pinFile(path) + defer func() { _ = again.Close() }() + saved := dupFd + dupFd = func(int) (int, error) { return -1, errors.New("dup refused") } + defer func() { dupFd = saved }() + if dupPin(again) != nil { + t.Error("a failed dup gave a pin") + } +} From 705397add9b2c88de7f751bbe5c54b538911efe7 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 18:30:32 +0100 Subject: [PATCH 6/9] vm: hold dupPin's and rememberFile's refusals with tests mutsweep left four refusals that nothing held: - dupPin's nil check doubled f.SyscallConn's own (os.ErrInvalid for a nil *os.File); it is gone, and the dupPin(nil) row now holds that error check. - dupPin's check on the dup's error: the failing seam returned -1, and os.NewFile(-1) is nil anyway. A row now reports an error along with a valid descriptor number. - rememberFile's stat fallback was never reached for a non-regular file. A mode-000 directory refuses both pin opens and reaches it. Refs #974 Co-Authored-By: Claude Opus 5.5 --- internal/vm/io_pin_unix.go | 6 ++---- internal/vm/io_pin_unix_internal_test.go | 27 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/internal/vm/io_pin_unix.go b/internal/vm/io_pin_unix.go index 5177cd78..cf50c371 100644 --- a/internal/vm/io_pin_unix.go +++ b/internal/vm/io_pin_unix.go @@ -33,10 +33,8 @@ var dupFd = func(fd int) (int, error) { return unix.FcntlInt(uintptr(fd), unix.F // closing one stream leaves the other's pin in place. nil when f is nil, closed, // or the dup fails, which leaves that stream with an unpinned identity. func dupPin(f *os.File) *os.File { - if f == nil { - return nil - } - rc, err := f.SyscallConn() + rc, err := f.SyscallConn() // os.ErrInvalid for a nil f + if err != nil { return nil } diff --git a/internal/vm/io_pin_unix_internal_test.go b/internal/vm/io_pin_unix_internal_test.go index 88fa9cff..9b0a5bb8 100644 --- a/internal/vm/io_pin_unix_internal_test.go +++ b/internal/vm/io_pin_unix_internal_test.go @@ -11,6 +11,8 @@ import ( "os" "path/filepath" "testing" + + "golang.org/x/sys/unix" ) // TestRememberFilePinsTheOpenedInode: a regular file is pinned and its @@ -81,6 +83,18 @@ func TestRememberFileOutsideARegularFile(t *testing.T) { if n.pin != nil || n.ident == nil { t.Errorf("a file no open accepts: pin=%v ident=%v, want the stat identity alone", n.pin, n.ident) } + // A directory no open accepts reaches the stat fallback, which must not + // record it either. + shut := filepath.Join(dir, "shut") + if err := os.Mkdir(shut, 0o000); err != nil { + t.Fatal(err) + } + defer func() { _ = os.Chmod(shut, 0o700) }() + s := &IOObj{path: shut} + s.rememberFile() + if s.pin != nil || s.ident != nil { + t.Errorf("a directory no open accepts: pin=%v ident=%v, want neither", s.pin, s.ident) + } } // TestDupPinGivesItsOwnDescriptor: the dup survives the original's close and @@ -118,4 +132,17 @@ func TestDupPinGivesItsOwnDescriptor(t *testing.T) { if dupPin(again) != nil { t.Error("a failed dup gave a pin") } + // The error decides, not the number: a dup that reports a failure along + // with a valid descriptor number gives no pin. + spare, err := unix.Dup(int(again.Fd())) + if err != nil { + t.Fatal(err) + } + defer func() { _ = unix.Close(spare) }() + dupFd = func(int) (int, error) { return spare, errors.New("dup refused") } + if got := dupPin(again); got != nil { + t.Error("a dup that reported an error gave a pin") + spare = -1 // the pin owns it now + _ = got.Close() + } } From f21e4e64c606fbcd72e0ae08c7785f1c99ed277e Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 18:34:14 +0100 Subject: [PATCH 7/9] vm: assert dupPin(nil)'s outcome rather than let a panic answer for it Refs #974 Co-Authored-By: Claude Opus 5.5 --- internal/vm/io_pin_unix_internal_test.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/internal/vm/io_pin_unix_internal_test.go b/internal/vm/io_pin_unix_internal_test.go index 9b0a5bb8..9def1665 100644 --- a/internal/vm/io_pin_unix_internal_test.go +++ b/internal/vm/io_pin_unix_internal_test.go @@ -118,9 +118,18 @@ func TestDupPinGivesItsOwnDescriptor(t *testing.T) { } _ = dup.Close() - if dupPin(nil) != nil { - t.Error("dupPin(nil) gave a pin") - } + // A nil pin is refused by SyscallConn's error, and gives no pin rather than + // a crash further in. + func() { + defer func() { + if r := recover(); r != nil { + t.Errorf("dupPin(nil) panicked: %v", r) + } + }() + if dupPin(nil) != nil { + t.Error("dupPin(nil) gave a pin") + } + }() if dupPin(pin) != nil { t.Error("dupPin of a closed pin gave a pin") } From 034a846a348282b4e579256855bf2e5ea44c75d1 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 18:42:26 +0100 Subject: [PATCH 8/9] vm: keep the AIX build, which has no F_DUPFD_CLOEXEC golang.org/x/sys defines no F_DUPFD_CLOEXEC for AIX, so the pin's dup broke `GOOS=aix go build ./internal/vm`, which main builds. No CI lane compiles AIX, so a cross-build found it. The dup moves to dupCloexec, per platform: fcntl(F_DUPFD_CLOEXEC) everywhere it exists, and on AIX dup(2) then FD_CLOEXEC under syscall.ForkLock, as the os package does, so that no child forked between the two calls inherits the descriptor. Checked: aix/ppc64 vet; solaris, illumos, dragonfly, openbsd, netbsd, freebsd, plan9 builds. Refs #974 Co-Authored-By: Claude Opus 5.5 --- internal/vm/io_pin_dup_aix.go | 24 ++++++++++++++++++++++++ internal/vm/io_pin_dup_cloexec.go | 15 +++++++++++++++ internal/vm/io_pin_unix.go | 5 +++-- 3 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 internal/vm/io_pin_dup_aix.go create mode 100644 internal/vm/io_pin_dup_cloexec.go diff --git a/internal/vm/io_pin_dup_aix.go b/internal/vm/io_pin_dup_aix.go new file mode 100644 index 00000000..8c9f8018 --- /dev/null +++ b/internal/vm/io_pin_dup_aix.go @@ -0,0 +1,24 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build aix + +package vm + +import "syscall" + +// dupCloexec duplicates fd with close-on-exec set. AIX has no F_DUPFD_CLOEXEC +// in golang.org/x/sys, so it is dup(2) then FD_CLOEXEC, both under +// syscall.ForkLock, as the os package does: no child forked between the two +// calls inherits the descriptor. +func dupCloexec(fd int) (int, error) { + syscall.ForkLock.RLock() + defer syscall.ForkLock.RUnlock() + nfd, err := syscall.Dup(fd) + if err != nil { + return -1, err + } + syscall.CloseOnExec(nfd) + return nfd, nil +} diff --git a/internal/vm/io_pin_dup_cloexec.go b/internal/vm/io_pin_dup_cloexec.go new file mode 100644 index 00000000..d85ac6ee --- /dev/null +++ b/internal/vm/io_pin_dup_cloexec.go @@ -0,0 +1,15 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !windows && !wasm && !plan9 && !aix + +package vm + +import "golang.org/x/sys/unix" + +// dupCloexec duplicates fd with close-on-exec set in the same call, so that no +// child forked meanwhile inherits it. +func dupCloexec(fd int) (int, error) { + return unix.FcntlInt(uintptr(fd), unix.F_DUPFD_CLOEXEC, 0) +} diff --git a/internal/vm/io_pin_unix.go b/internal/vm/io_pin_unix.go index cf50c371..9f3ed49b 100644 --- a/internal/vm/io_pin_unix.go +++ b/internal/vm/io_pin_unix.go @@ -26,8 +26,9 @@ func pinFile(path string) *os.File { return nil } -// dupFd is dup(2) with close-on-exec, the seam a test uses to make it fail. -var dupFd = func(fd int) (int, error) { return unix.FcntlInt(uintptr(fd), unix.F_DUPFD_CLOEXEC, 0) } +// dupFd is dup(2) with close-on-exec (dupCloexec, per platform), the seam a +// test uses to make it fail. +var dupFd = dupCloexec // dupPin gives a second stream its own descriptor on the pinned inode, so that // closing one stream leaves the other's pin in place. nil when f is nil, closed, From d49cec5f0297e2b49c23de98026d04c34dfc31e8 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 22 Nov 2026 21:00:33 +0100 Subject: [PATCH 9/9] vm: map a Win32 error code as rb_w32_map_errno does before raising a flush The Windows runner failed TestIOFlushError: a flush under a missing directory raised Errno::ENOTDIR where Errno::ENOENT is wanted. On Windows a syscall.Errno carries the Win32 code itself: ERROR_PATH_NOT_FOUND is 3. errnoClasses is keyed by the numbers Go invented for the POSIX names, so 3 landed on an unrelated class. Before this PR a flush flattened every error to ENOENT, which hid it. MRI maps every Win32 code through errmap (win32/win32.c:145, v4.0.9, rb_w32_map_errno): ERROR_PATH_NOT_FOUND and ERROR_FILE_NOT_FOUND are ENOENT, ERROR_ACCESS_DENIED EACCES, ERROR_DISK_FULL ENOSPC, and so on; a code at or above WSABASEERR is kept; any other is EINVAL. errno_win32_windows.go ports the Win32 rows of that table, keyed by golang.org/x/sys/windows constants so that no number is typed by hand, and mapHostErrno applies it. It is the identity elsewhere. raiseFlushErr maps the code before choosing the class. The raisers that predate this PR (sysFail and the others) still read a Win32 code as a POSIX number; that is filed separately. TestRaiseFlushErrKeepsWhatTheErrorSays's "no class" row moves from 4093 to 9999999: on Windows 4093 is now an unknown Win32 code below WSABASEERR, which MRI maps to EINVAL. TestMapHostErrnoIsRbW32MapErrno holds the table's rows on Windows. Refs #974 Co-Authored-By: Claude Opus 5.5 --- internal/vm/errno_win32_other.go | 12 ++ internal/vm/errno_win32_windows.go | 129 ++++++++++++++++++ .../vm/errno_win32_windows_internal_test.go | 50 +++++++ internal/vm/io_dirty.go | 4 +- internal/vm/io_dirty_internal_test.go | 4 +- 5 files changed, 197 insertions(+), 2 deletions(-) create mode 100644 internal/vm/errno_win32_other.go create mode 100644 internal/vm/errno_win32_windows.go create mode 100644 internal/vm/errno_win32_windows_internal_test.go diff --git a/internal/vm/errno_win32_other.go b/internal/vm/errno_win32_other.go new file mode 100644 index 00000000..4e56de8a --- /dev/null +++ b/internal/vm/errno_win32_other.go @@ -0,0 +1,12 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !windows + +package vm + +// mapHostErrno is the identity outside Windows: a syscall.Errno already holds +// the POSIX number its Errno class is registered under. See +// errno_win32_windows.go. +func mapHostErrno(eno int64) int64 { return eno } diff --git a/internal/vm/errno_win32_windows.go b/internal/vm/errno_win32_windows.go new file mode 100644 index 00000000..c5cfa809 --- /dev/null +++ b/internal/vm/errno_win32_windows.go @@ -0,0 +1,129 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build windows + +package vm + +import ( + "syscall" + + "golang.org/x/sys/windows" +) + +// win32Errnos is MRI's errmap (win32/win32.c, v4.0.9), the Win32 rows: the +// errno class rb_w32_map_errno gives each Win32 error code. On Windows a +// syscall.Errno carries the Win32 code itself, where errnoNumbers holds the +// numbers Go invented for the POSIX names, so a code looked up there directly +// lands on an unrelated class (ERROR_PATH_NOT_FOUND, 3, read as ENOTDIR). +// +// ERROR_INVALID_HANDLE appears twice in errmap, as EBADF and then EINVAL; the +// first row is the one rb_w32_map_errno's loop returns, so it alone is here. +// The WSA rows are left out: their codes are at or above WSABASEERR, which +// mapHostErrno keeps as they are, as rb_w32_map_errno does for a WSA code +// absent from the table. +var win32Errnos = map[syscall.Errno]string{ + windows.ERROR_INVALID_FUNCTION: "EINVAL", + windows.ERROR_FILE_NOT_FOUND: "ENOENT", + windows.ERROR_PATH_NOT_FOUND: "ENOENT", + windows.ERROR_TOO_MANY_OPEN_FILES: "EMFILE", + windows.ERROR_ACCESS_DENIED: "EACCES", + windows.ERROR_INVALID_HANDLE: "EBADF", + windows.ERROR_ARENA_TRASHED: "ENOMEM", + windows.ERROR_NOT_ENOUGH_MEMORY: "ENOMEM", + windows.ERROR_INVALID_BLOCK: "ENOMEM", + windows.ERROR_BAD_ENVIRONMENT: "E2BIG", + windows.ERROR_BAD_FORMAT: "ENOEXEC", + windows.ERROR_INVALID_ACCESS: "EINVAL", + windows.ERROR_INVALID_DATA: "EINVAL", + windows.ERROR_INVALID_DRIVE: "ENOENT", + windows.ERROR_CURRENT_DIRECTORY: "EACCES", + windows.ERROR_NOT_SAME_DEVICE: "EXDEV", + windows.ERROR_NO_MORE_FILES: "ENOENT", + windows.ERROR_WRITE_PROTECT: "EROFS", + windows.ERROR_BAD_UNIT: "ENODEV", + windows.ERROR_NOT_READY: "ENXIO", + windows.ERROR_BAD_COMMAND: "EACCES", + windows.ERROR_CRC: "EACCES", + windows.ERROR_BAD_LENGTH: "EACCES", + windows.ERROR_SEEK: "EIO", + windows.ERROR_NOT_DOS_DISK: "EACCES", + windows.ERROR_SECTOR_NOT_FOUND: "EACCES", + windows.ERROR_OUT_OF_PAPER: "EACCES", + windows.ERROR_WRITE_FAULT: "EIO", + windows.ERROR_READ_FAULT: "EIO", + windows.ERROR_GEN_FAILURE: "EACCES", + windows.ERROR_LOCK_VIOLATION: "EACCES", + windows.ERROR_SHARING_VIOLATION: "EACCES", + windows.ERROR_WRONG_DISK: "EACCES", + windows.ERROR_SHARING_BUFFER_EXCEEDED: "EACCES", + windows.ERROR_BAD_NETPATH: "ENOENT", + windows.ERROR_NETWORK_ACCESS_DENIED: "EACCES", + windows.ERROR_BAD_NET_NAME: "ENOENT", + windows.ERROR_FILE_EXISTS: "EEXIST", + windows.ERROR_CANNOT_MAKE: "EACCES", + windows.ERROR_FAIL_I24: "EACCES", + windows.ERROR_INVALID_PARAMETER: "EINVAL", + windows.ERROR_NO_PROC_SLOTS: "EAGAIN", + windows.ERROR_DRIVE_LOCKED: "EACCES", + windows.ERROR_BROKEN_PIPE: "EPIPE", + windows.ERROR_DISK_FULL: "ENOSPC", + windows.ERROR_INVALID_TARGET_HANDLE: "EBADF", + windows.ERROR_WAIT_NO_CHILDREN: "ECHILD", + windows.ERROR_CHILD_NOT_COMPLETE: "ECHILD", + windows.ERROR_DIRECT_ACCESS_HANDLE: "EBADF", + windows.ERROR_NEGATIVE_SEEK: "EINVAL", + windows.ERROR_SEEK_ON_DEVICE: "EACCES", + windows.ERROR_DIR_NOT_EMPTY: "ENOTEMPTY", + windows.ERROR_DIRECTORY: "ENOTDIR", + windows.ERROR_NOT_LOCKED: "EACCES", + windows.ERROR_BAD_PATHNAME: "ENOENT", + windows.ERROR_MAX_THRDS_REACHED: "EAGAIN", + windows.ERROR_LOCK_FAILED: "EACCES", + windows.ERROR_ALREADY_EXISTS: "EEXIST", + windows.ERROR_INVALID_STARTING_CODESEG: "ENOEXEC", + windows.ERROR_INVALID_STACKSEG: "ENOEXEC", + windows.ERROR_INVALID_MODULETYPE: "ENOEXEC", + windows.ERROR_INVALID_EXE_SIGNATURE: "ENOEXEC", + windows.ERROR_EXE_MARKED_INVALID: "ENOEXEC", + windows.ERROR_BAD_EXE_FORMAT: "ENOEXEC", + windows.ERROR_ITERATED_DATA_EXCEEDS_64k: "ENOEXEC", + windows.ERROR_INVALID_MINALLOCSIZE: "ENOEXEC", + windows.ERROR_DYNLINK_FROM_INVALID_RING: "ENOEXEC", + windows.ERROR_IOPL_NOT_ENABLED: "ENOEXEC", + windows.ERROR_INVALID_SEGDPL: "ENOEXEC", + windows.ERROR_AUTODATASEG_EXCEEDS_64k: "ENOEXEC", + windows.ERROR_RING2SEG_MUST_BE_MOVABLE: "ENOEXEC", + windows.ERROR_RELOC_CHAIN_XEEDS_SEGLIM: "ENOEXEC", + windows.ERROR_INFLOOP_IN_RELOC_CHAIN: "ENOEXEC", + windows.ERROR_FILENAME_EXCED_RANGE: "ENOENT", + windows.ERROR_NESTING_NOT_ALLOWED: "EAGAIN", + 229: "EPIPE", // ERROR_PIPE_LOCAL, which win32.c defines itself + windows.ERROR_BAD_PIPE: "EPIPE", + windows.ERROR_PIPE_BUSY: "EAGAIN", + windows.ERROR_NO_DATA: "EPIPE", + windows.ERROR_PIPE_NOT_CONNECTED: "EPIPE", + windows.ERROR_OPERATION_ABORTED: "EINTR", + windows.ERROR_NOT_ENOUGH_QUOTA: "ENOMEM", + windows.ERROR_MOD_NOT_FOUND: "ENOENT", + windows.ERROR_PRIVILEGE_NOT_HELD: "EACCES", + windows.ERROR_CANT_RESOLVE_FILENAME: "ELOOP", +} + +// wsaBaseErr is WSABASEERR: from there up a code is a socket error, or one of +// the numbers Go invented for the POSIX names, and is kept as it is. +const wsaBaseErr = 10000 + +// mapHostErrno is rb_w32_map_errno: the errno number of the class MRI raises +// for the Win32 code eno. A code in errmap gets its class; a code at or above +// WSABASEERR is kept; any other code is EINVAL. +func mapHostErrno(eno int64) int64 { + if eno == 0 || eno >= wsaBaseErr { + return eno + } + if name, ok := win32Errnos[syscall.Errno(eno)]; ok { + return errnoNumbers[name] + } + return errnoNumbers["EINVAL"] +} diff --git a/internal/vm/errno_win32_windows_internal_test.go b/internal/vm/errno_win32_windows_internal_test.go new file mode 100644 index 00000000..dc901881 --- /dev/null +++ b/internal/vm/errno_win32_windows_internal_test.go @@ -0,0 +1,50 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build windows + +package vm + +import ( + "syscall" + "testing" + + "golang.org/x/sys/windows" +) + +// TestMapHostErrnoIsRbW32MapErrno: each row is what MRI's rb_w32_map_errno +// (win32/win32.c, v4.0.9) gives for the code. ERROR_PATH_NOT_FOUND is the row +// the Windows runner showed: read as a POSIX number, 3 raised Errno::ENOTDIR +// where MRI raises Errno::ENOENT. +func TestMapHostErrnoIsRbW32MapErrno(t *testing.T) { + cases := []struct { + eno syscall.Errno + want string + }{ + {windows.ERROR_PATH_NOT_FOUND, "ENOENT"}, + {windows.ERROR_FILE_NOT_FOUND, "ENOENT"}, + {windows.ERROR_ACCESS_DENIED, "EACCES"}, + // errmap's first row for it; the second says EINVAL. + {windows.ERROR_INVALID_HANDLE, "EBADF"}, + {windows.ERROR_DIRECTORY, "ENOTDIR"}, + {windows.ERROR_DISK_FULL, "ENOSPC"}, + // ERROR_PIPE_LOCAL, which win32.c defines itself. + {229, "EPIPE"}, + // Absent from errmap, and below WSABASEERR. + {windows.ERROR_INVALID_NAME, "EINVAL"}, + // A number Go invented for a POSIX name: kept. + {syscall.ENOENT, "ENOENT"}, + } + for _, c := range cases { + if got := mapHostErrno(int64(c.eno)); got != errnoNumbers[c.want] { + t.Errorf("mapHostErrno(%d) = %d (%s), want %s", c.eno, got, errnoClasses[got], c.want) + } + } + if got := mapHostErrno(0); got != 0 { + t.Errorf("mapHostErrno(0) = %d, want 0", got) + } + if got := mapHostErrno(int64(windows.WSAECONNRESET)); got != int64(windows.WSAECONNRESET) { + t.Errorf("a WSA code was changed to %d", got) + } +} diff --git a/internal/vm/io_dirty.go b/internal/vm/io_dirty.go index a7164a0d..d8f79a28 100644 --- a/internal/vm/io_dirty.go +++ b/internal/vm/io_dirty.go @@ -106,9 +106,11 @@ func (o *IOObj) writeDirty(content []byte) error { // raiseFlushErr raises a failed flush as MRI's rb_io_flush_raw does, through // rb_sys_fail_on_write: the errno the system answered, not one guessed from -// the path. ENOSPC from a full disk, EISDIR, EROFS all keep their class. +// the path. ENOSPC from a full disk, EISDIR, EROFS all keep their class. On +// Windows the Win32 code is first mapped as rb_w32_map_errno does. func raiseFlushErr(err error, path string) { if eno, ok := errnoOfError(err); ok { + eno = mapHostErrno(eno) if name, ok := errnoClasses[eno]; ok { raise("Errno::"+name, "%s @ rb_io_flush_raw - %s", errnoStrerror(eno), path) } diff --git a/internal/vm/io_dirty_internal_test.go b/internal/vm/io_dirty_internal_test.go index f2c7f03e..58cea61d 100644 --- a/internal/vm/io_dirty_internal_test.go +++ b/internal/vm/io_dirty_internal_test.go @@ -64,7 +64,9 @@ func TestRaiseFlushErrKeepsWhatTheErrorSays(t *testing.T) { want string }{ {syscall.Errno(errnoNumbers["ENOSPC"]), "Errno::ENOSPC"}, - {syscall.Errno(4093), "SystemCallError"}, + // No class anywhere: on Windows it is past WSABASEERR, so mapHostErrno + // keeps it, where a smaller unknown code would become EINVAL. + {syscall.Errno(9999999), "SystemCallError"}, {errors.New("no errno here"), "Errno::EIO"}, } for _, c := range cases {