Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,7 @@ Otherwise:
| `File::Stat#==` | `a == b` is `false` for two stats of the same file (MRI: `true`); `a.==(b)` answers `true` |
| `File#stat` on a file unlinked while open | raises `Errno::ENOENT`; MRI answers from the open descriptor. rbgo's streams are buffered by path and hold no descriptor |
| `IO#pwrite` / `IO#pread` on a file unlinked or replaced while open | both reach the file **by its path**, since streams hold no descriptor. A `#pwrite`'s bytes are on disk when it returns, and only those bytes: the stream's other pending writes stay pending, as with `pwrite(2)`. `#pread` sees another writer's bytes and this stream's own pending writes, which it flushes first, as `rb_io_pread` does ([#949](https://github.com/go-embedded-ruby/ruby/issues/949)). The difference is with a path that no longer names the opened file. Unlinked, both fall back to the stream's buffer, where MRI still reaches the old inode. Replaced, they reach the new file. Same root as the row above. Two deliberate divergences. First, `#pread`'s length is bounded by the file's size, so `f.pread(2**40, 0)` returns at once, where MRI 4.0.7 tries to allocate the full length. Second, a hole lives in memory when it has to: a `#pwrite` that would open a hole larger than 64 MiB past the end of the stream's in-memory copy is refused with `Errno::EFBIG` once the path is gone, where MRI writes a sparse file through its descriptor. When the file is reachable, the hole goes to disk as in MRI, and a refusal from the file (EFBIG, ENOSPC, EIO) is raised with its errno ([#973](https://github.com/go-embedded-ruby/ruby/issues/973)) |
| `IO#ungetc` / `#ungetbyte` on a `File` longer than 8192 bytes | as in MRI, pushed-back bytes are read-buffer bytes and never reach the file. `#pos` subtracts them, and is negative when more was pushed back than read. A write, `#flush`, `#seek`, `#rewind`, `#truncate`, `#pwrite` or `File#size` on a writable stream drops them first. When the position was negative, the stream ends up where MRI's descriptor is: at the cursor after `#read`, `#readpartial`, `#read_nonblock`, a seek or a write, and at end-of-file after a buffered read (`#getc`, `#gets`, …), which reads ahead. `#readpartial` and `#read_nonblock` return no more than the pushback while some is left. `#sysread` and `#sysseek` refuse with "for buffered IO" ([#974](https://github.com/go-embedded-ruby/ruby/issues/974)). The divergence is MRI's read-buffer capacity: MRI reads 8192 bytes ahead, so on a larger file, pushing back more than was read raises `IOError: ungetbyte failed`. rbgo accepts it, and a following write lands at end-of-file. On a file of at most 8192 bytes the two agree |
| an unflushed file whose directory is removed before the program ends | loses its bytes; MRI, holding a descriptor to an unlinked file, still writes them. Teardown re-opens the path to flush it, so it gets `ENOENT` — and reports nothing, as MRI's shutdown ignores a failing `fflush`. Same root again: streams are buffered by path, which is also [#635](https://github.com/go-embedded-ruby/ruby/issues/635) |
| `Errno` | all **158** of MRI's constant names are present, but **32** report errno `0` where MRI has a real number (`EAUTH`, `EBADRPC`, `EDEVERR`, …). Measured by set difference on darwin: 81 names are zero-valued under rbgo, 49 under MRI, and every MRI zero is also zero under rbgo. Go's portable `syscall` package does not expose the platform-only names |
| `pp` | neither `Kernel#pp` nor `require "pp"` exists (`require "prettyprint"` does work) |
Expand Down
49 changes: 40 additions & 9 deletions internal/vm/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,13 @@ type IOObj struct {
// holds its whole output; bytes written to the stream are kept in popen.stdin,
// out of the buffer being read, and cannot reach a child that is already gone.
popen *popenProc

// ungetLo/ungetHi bound the bytes #ungetc/#ungetbyte spliced into buf on a
// file stream, which are not the file's (io_pushback.go). Empty when equal.
ungetLo, ungetHi int
// fdAt is where MRI's descriptor is while its read buffer holds no file
// bytes; a failed io_unread leaves the cursor there (io_pushback.go).
fdAt int
}

// pipeBuf is the shared byte channel behind an IO.pipe reader/writer pair. Each
Expand Down Expand Up @@ -209,14 +216,16 @@ func (o *IOObj) writeBytes(p []byte) int {
return len(p)
}
if o.isStr {
if o.appendMode { // append mode: every write lands at end, ignoring position
o.unreadPushback(true) // rb_io_check_writable → io_unread (#974)
if o.appendMode { // append mode: every write lands at end, ignoring position
o.pos = len(o.buf)
}
if end := o.pos + len(p); end > len(o.buf) {
o.buf = append(o.buf, make([]byte, end-len(o.buf))...)
}
copy(o.buf[o.pos:], p)
o.pos += len(p)
o.fdAt = o.pos // a write leaves rbuf empty and the descriptor past it
o.syncStr()
if o.path != "" {
o.wbufDirty = true // bytes accepted but not on disk: MRI's fptr->wbuf.len
Expand Down Expand Up @@ -663,10 +672,16 @@ func (vm *VM) registerIO() {
raise("IOError", "closed stream")
}
ioFlush(o)
if o.writable {
// rb_file_size: flush_before_seek on a writable stream, whose
// io_unread drops what #ungetc pushed back (#974). A read-only
// stream keeps it, and its buffer answers without it below.
o.unreadPushback(true)
}
if st, err := os.Stat(o.path); err == nil {
return object.IntValue(st.Size())
}
return object.IntValue(int64(len(o.buf)))
return object.IntValue(int64(len(o.diskBytes())))
})
cFile.define("flock", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return vm.fileFlock(self.(*IOObj), clampInt(vm.toIntCoerce(args[0])))
Expand Down Expand Up @@ -1285,12 +1300,13 @@ func ioFlush(o *IOObj) {
return
}
o.wbufDirty = false
err := os.WriteFile(o.path, o.buf, 0o644)
content := o.diskBytes() // never the bytes #ungetc pushed back (#974)
err := os.WriteFile(o.path, content, 0o644)
if err == nil {
return
}
if errors.Is(err, fs.ErrPermission) {
err = withOwnerWrite(o.path, err, func() error { return os.WriteFile(o.path, o.buf, 0o644) })
err = withOwnerWrite(o.path, err, func() error { return os.WriteFile(o.path, content, 0o644) })
}
if err != nil {
raiseOpenErrno(err, o.path)
Expand Down Expand Up @@ -1703,6 +1719,7 @@ func defIOWrite(cls *RClass) {
o := self.(*IOObj)
ioClosedRealIO(o) // MRI: IO#flush raises on a closed stream; StringIO#flush does not
ioFlush(o)
o.unreadPushback(true) // rb_io_flush_raw: io_unread when readable (#974)
return self
})
cls.define("fsync", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
Expand Down Expand Up @@ -2064,7 +2081,9 @@ func defStringIORead(cls *RClass) {
if o.closed && !ioIsStringIO(o) {
raise("IOError", "closed stream")
}
return object.IntValue(int64(o.pos))
// rb_io_tell: the descriptor's offset minus what the read buffer still
// holds, pushback included — negative when more was pushed back than read.
return object.IntValue(int64(o.tellPos()))
})
// #tell is a true alias of #pos, as in MRI.
defineBuiltinSecondName(cls, "tell", "pos")
Expand All @@ -2077,7 +2096,8 @@ func defStringIORead(cls *RClass) {
if n < 0 {
raise("Errno::EINVAL", "Invalid argument")
}
o.pos = n
o.unreadPushback(true) // io_seek → flush_before_seek → io_unread (#974)
o.pos, o.fdAt = n, n
return args[0]
})
cls.define("seek", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
Expand All @@ -2096,6 +2116,9 @@ func defStringIORead(cls *RClass) {
whence = vm.seekWhence(args[1])
}
}
// io_seek → flush_before_seek → io_unread: the pushback is dropped and
// SEEK_CUR counts from the logical position (#974).
o.unreadPushback(true)
var newPos int
switch whence {
case 1: // SEEK_CUR
Expand All @@ -2110,13 +2133,15 @@ func defStringIORead(cls *RClass) {
if newPos < 0 {
raise("Errno::EINVAL", "Invalid argument")
}
o.pos = newPos
o.pos, o.fdAt = newPos, newPos
return object.IntValue(0)
})
cls.define("rewind", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
o := self.(*IOObj)
ioClosedRealIO(o) // real IO/File raises on a closed stream; StringIO tolerates it
o.unreadPushback(true) // io_seek(fptr, 0, 0) → io_unread (#974)
o.pos, o.lineno = 0, 0 // #rewind resets both the position and the line number
o.fdAt = 0
return object.IntValue(0)
})
cls.define("truncate", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
Expand All @@ -2133,6 +2158,7 @@ func defStringIORead(cls *RClass) {
if n < 0 {
raise("Errno::EINVAL", "Invalid argument")
}
o.unreadPushback(true) // rb_io_check_writable → io_unread (#974)
if n < len(o.buf) {
o.buf = o.buf[:n]
} else if n > len(o.buf) {
Expand Down Expand Up @@ -2200,15 +2226,20 @@ func defStringIORead(cls *RClass) {
if o.pos >= len(o.buf) {
return result(nil, n > 0) // a length read at EOF is nil; a 0-length read is ""
}
wasAt := o.atDescriptor() // io_bufread: an empty rbuf is bypassed
end := min(o.pos+n, len(o.buf))
data := o.buf[o.pos:end]
o.pos = end
return result(data, false)
v := result(data, false) // copies data before readThrough compacts buf
o.readThrough(wasAt)
return v
}
start := min(o.pos, len(o.buf)) // pos= may have moved past the end
data := o.buf[start:]
o.pos = len(o.buf)
return result(data, false)
v := result(data, false)
o.readThrough(true) // read_all drains rbuf and reads the rest directly
return v
})
// readpartial(maxlen, out = nil): read up to maxlen bytes, blocking only until
// some are available. On the in-memory buffer that is the leading maxlen bytes;
Expand Down
38 changes: 24 additions & 14 deletions internal/vm/io_descriptors.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,11 @@ func defIOReadExtra(cls *RClass) {
}
return ioReadResult(nil, nil)
}
// rb_io_sysread: READ_DATA_BUFFERED. Pushed-back bytes are buffered data
// the descriptor never had (#974).
if o.pushbackUnread() > 0 {
raise("IOError", "sysread for buffered IO")
}
if o.pos >= len(o.buf) {
// MRI empties the output buffer (io_set_read_length to 0) before
// signalling end-of-file.
Expand Down Expand Up @@ -345,12 +350,13 @@ func defIOSeekable(cls *RClass) {
// Unreadable by path (removed between the two calls, permission):
// the buffer below is what this stream last saw.
}
if off >= int64(len(o.buf)) {
content := o.diskBytes() // pread reads the file, never the pushback (#974)
if off >= int64(len(content)) {
raise("EOFError", "end of file reached")
}
// off+n is never formed: with n near MaxInt it overflowed into a slice
// bounds panic (#973). What is left past off bounds the read instead.
rest := o.buf[off:]
rest := content[off:]
return ioReadResult(rest[:min(n, len(rest))], buf)
})
cls.define("pwrite", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
Expand All @@ -365,7 +371,8 @@ func defIOSeekable(cls *RClass) {
if off < 0 {
raise("Errno::EINVAL", "Invalid argument - pwrite")
}
o.writable = true // a written File flushes its buffer back on flush/close
o.unreadPushback(true) // rb_io_check_writable → io_unread (#974)
o.writable = true // a written File flushes its buffer back on flush/close
vm.trackOpenFile(o)
// #949: MRI's rb_io_pwrite is pwrite(2), so the bytes are on disk the
// moment it returns, and ONLY those bytes: the stream's other pending
Expand Down Expand Up @@ -407,6 +414,11 @@ func defIOSeekable(cls *RClass) {
if len(args) > 1 {
whence = vm.seekWhence(args[1]) // accepts :SET/:CUR/:END symbols
}
// rb_io_sysseek: READ_DATA_BUFFERED on a readable stream. Pushed-back
// bytes are buffered data the descriptor never had (#974).
if !o.rdClosed && o.pushbackUnread() > 0 {
raise("IOError", "sysseek for buffered IO")
}
switch whence {
case 1: // SEEK_CUR
o.pos += amount
Expand Down Expand Up @@ -471,6 +483,7 @@ func defIOSeekable(cls *RClass) {
if o.path != "" && !o.writable {
if b, err := os.ReadFile(o.path); err == nil {
o.buf = b
o.ungetLo, o.ungetHi = 0, 0 // fresh content: no pushback in it (#974)
}
}
enc := ioStripBOM(o)
Expand Down Expand Up @@ -517,16 +530,7 @@ func detectBOM(p []byte) (int, string) {
// ioUnget inserts p immediately before the cursor (leaving the cursor on the
// re-inserted bytes) so a following read returns them first — the pushback model
// shared by ungetbyte and ungetc.
func ioUnget(o *IOObj, p []byte) {
if len(p) == 0 {
return
}
out := make([]byte, 0, len(o.buf)+len(p))
out = append(out, o.buf[:o.pos]...)
out = append(out, p...)
out = append(out, o.buf[o.pos:]...)
o.buf = out
}
func ioUnget(o *IOObj, p []byte) { o.unget(p) }

// ioReadResult returns data as a fresh String, or fills the caller's output
// buffer String and returns it — the shared return convention of the length-taking
Expand Down Expand Up @@ -710,7 +714,12 @@ func ioReopenIO(vm *VM, o, other *IOObj) object.Value {
o.reopened = other
return o
}
o.buf, o.pos, o.lineno = other.buf, other.pos, other.lineno
// io_reopen reads the position with io_tell(orig), which drops orig's
// pushback when the position is valid; what is left of it is orig's read
// buffer, not file content, so the adopted copy is the file's (#974).
other.unreadPushback(false)
o.buf, o.pos, o.lineno = other.diskBytes(), other.pos, other.lineno
o.ungetLo, o.ungetHi = 0, 0
o.rdClosed, o.wrClosed, o.writable = other.rdClosed, other.wrClosed, other.writable
o.appendMode, o.openMode, o.binmode = other.appendMode, other.openMode, other.binmode
o.extEnc, o.intEnc = other.extEnc, other.intEnc
Expand Down Expand Up @@ -769,6 +778,7 @@ func ioReopenPath(vm *VM, o *IOObj, pos []object.Value, opts *object.Hash) objec
}
fresh := openFileIO(o.cls, name, modeBase(mode))
o.buf, o.pos, o.path = fresh.buf, fresh.pos, fresh.path
o.ungetLo, o.ungetHi = 0, 0 // the read buffer, pushback included, is dropped (#974)
if keepHalves {
o.writable, o.appendMode, o.openMode = !o.wrClosed, false, ""
} else {
Expand Down
Loading
Loading