From ec62549fc1aa1ccd16ec3f7dc0cdd2bc31c02d37 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 8 Sep 2026 20:26:59 +0200 Subject: [PATCH 1/2] io: IO::Buffer transfer/locked/bitwise-bang/for-writability + size validation (core/io +46) Advance IO::Buffer conformance against MRI 4.0.x. References read: MRI io_buffer.c (io_buffer_transfer, io_buffer_locked, io_buffer_and/or/xor/not!, io_buffer_for, io_buffer_initialize/resize, io_buffer_valid_p) and ruby/spec core/io/buffer/{and,or,xor,not,transfer,locked,valid,resize,for,null, initialize}_spec.rb. Every value below verified byte-for-byte against ruby 4.0.5. New / fixed: - Exceptions IO::Buffer::LockedError / InvalidatedError / AllocationError (all RuntimeError subclasses). - In-place bitwise operators #and!/#or!/#xor!/#not! (mutate the receiver, return self; AccessError on a read-only buffer). The binary &/|/^ argument type error now reads "wrong argument type X (expected IO::Buffer)" (nil/true/false lower-cased), matching MRI. - #transfer: moves memory and kind (external/read-only/slice) to a fresh buffer and nullifies the source; refused while locked with LockedError. - #locked / #locked?: locks the buffer for the block, #resize and #transfer raise LockedError inside, re-entry raises "Buffer already locked!"; the lock does not propagate to or from slices. - IO::Buffer.for over a *mutable* String (with a block) now aliases the String's bytes and is writable (writes propagate); a frozen source or the no-block form stays a read-only copy. - .new / #resize size validation: non-Integer -> TypeError "not an Integer", negative -> ArgumentError "Size can't be negative!"; #resize(0) frees the buffer, and a freed external buffer may be re-grown into an internal one. - #valid? now reports slice invalidation: a slice invalidates when its source is freed, transferred, or resized out from under it, but a slice of a String-backed buffer stays valid after the buffer is freed; operations on an invalidated slice raise InvalidatedError "Buffer has been invalidated!". core/io: pass 1090->1136, fail 180->168, error 159->125. Full whitebox coverage (100% on io_buffer.go); go build/test ./..., wasip1 build, and gofmt all clean. Co-Authored-By: Claude Opus 4.8 --- internal/vm/io_buffer.go | 199 ++++++++++++++++++++++--- internal/vm/io_buffer_internal_test.go | 75 ++++++++++ 2 files changed, 254 insertions(+), 20 deletions(-) diff --git a/internal/vm/io_buffer.go b/internal/vm/io_buffer.go index 7aebb3d1..5d26751a 100644 --- a/internal/vm/io_buffer.go +++ b/internal/vm/io_buffer.go @@ -24,6 +24,29 @@ type ioBuffer struct { external bool // memory owned elsewhere (.for copies a String, .string yields) borrowed bool // a slice sharing another buffer's memory — neither external nor internal freed bool + locked bool // inside a #locked block (blocks resize/transfer, reentrant lock) + parent *ioBuffer // for a slice, the buffer it was sliced from (nil for a non-slice) + sliceOff int // this slice's offset within parent (only meaningful when parent != nil) + sliceLen int // this slice's length within parent (only meaningful when parent != nil) +} + +// sliceValid reports IO::Buffer#valid?. A non-slice is always valid (freeing it +// does not invalidate it — io_buffer.c io_buffer_valid_p). A slice becomes +// invalid when its source has been freed or reallocated so the slice no longer +// falls inside it; a slice of a String-backed (external) buffer stays valid even +// after the buffer is freed because the String keeps the memory alive. +func (b *ioBuffer) sliceValid() bool { + if b.parent == nil { + return true + } + p := b.parent + if p.external { + return true + } + if p.freed { + return false + } + return b.sliceOff+b.sliceLen <= len(p.data) } func (b *ioBuffer) ToS() string { @@ -92,6 +115,35 @@ func bufInt(v object.Value) int64 { func bufUint(v object.Value) uint64 { return uint64(bufInt(v)) } +// bufSizeArg validates an IO::Buffer size (.new / #resize): a non-Integer raises +// TypeError "not an Integer" and a negative value raises ArgumentError "Size +// can't be negative!" — the exact checks and messages from io_buffer.c +// (io_buffer_initialize / io_buffer_resize, via RB_INTEGER_TYPE_P and the +// negative-size guard). +func bufSizeArg(v object.Value) int64 { + n, ok := v.(object.Integer) + if !ok { + raise("TypeError", "not an Integer") + } + if int64(n) < 0 { + raise("ArgumentError", "Size can't be negative!") + } + return int64(n) +} + +// bufferArgTypeName names v the way io_buffer.c's "wrong argument type %s +// (expected IO::Buffer)" does: nil/true/false spelled in lower case, otherwise +// the class name. classNameOf already yields "nil" for nil. +func bufferArgTypeName(v object.Value) string { + if b, ok := v.(object.Bool); ok { + if bool(b) { + return "true" + } + return "false" + } + return classNameOf(v) +} + func bufFloat(v object.Value) float64 { switch n := v.(type) { case object.Float: @@ -120,6 +172,9 @@ func bufferTypeName(v object.Value) (string, bufType) { // live returns the buffer's bytes, raising if it has been freed (the IO::Buffer // operations that touch memory require a live buffer). func (b *ioBuffer) live() []byte { + if b.parent != nil && !b.sliceValid() { + raise("IO::Buffer::InvalidatedError", "Buffer has been invalidated!") + } if b.freed { raise("IO::Buffer::AccessError", "The buffer is not allocated!") } @@ -152,9 +207,17 @@ func (vm *VM) registerIOBuffer() { } { cBuf.consts[name] = object.IntValue(val) } - access := newClass("IO::Buffer::AccessError", vm.consts["RuntimeError"].(*RClass)) + rtErr := vm.consts["RuntimeError"].(*RClass) + access := newClass("IO::Buffer::AccessError", rtErr) cBuf.consts["AccessError"] = access vm.consts["IO::Buffer::AccessError"] = access + // LockedError/InvalidatedError/AllocationError are all RuntimeError + // subclasses in io_buffer.c (rb_eIOBufferLockedError etc.). + for _, ex := range []string{"LockedError", "InvalidatedError", "AllocationError"} { + c := newClass("IO::Buffer::"+ex, rtErr) + cBuf.consts[ex] = c + vm.consts["IO::Buffer::"+ex] = c + } sm := func(name string, fn NativeFn) { cBuf.smethods[name] = &Method{name: name, owner: cBuf, native: fn} } dm := func(name string, fn NativeFn) { cBuf.define(name, fn) } @@ -162,7 +225,7 @@ func (vm *VM) registerIOBuffer() { sm("new", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { size := int64(65536) if len(args) > 0 { - size = intArg(args[0]) + size = bufSizeArg(args[0]) } flags := int64(0) if len(args) > 1 { @@ -171,8 +234,17 @@ func (vm *VM) registerIOBuffer() { return &ioBuffer{data: make([]byte, size), readonly: flags&128 != 0} }) sm("for", func(vm *VM, _ object.Value, args []object.Value, blk *Proc) object.Value { - s := vm.strArgConv(args, 0) - buf := &ioBuffer{data: append([]byte(nil), s...), external: true, readonly: true} + // io_buffer.c io_buffer_for: without a block the buffer is always a + // read-only copy; with a block over a *mutable* String the buffer aliases + // the String's bytes (writes propagate) and is writable, while a frozen + // String still yields a read-only buffer. + buf := &ioBuffer{external: true} + if s, ok := args[0].(*object.String); ok && blk != nil && !s.Frozen { + buf.data = s.MutableBytes() + } else { + buf.data = append([]byte(nil), vm.strArgConv(args, 0)...) + buf.readonly = true + } if blk == nil { return buf } @@ -206,13 +278,13 @@ func (vm *VM) registerIOBuffer() { } pred("null?", func(b *ioBuffer) bool { return b.freed }) pred("empty?", func(b *ioBuffer) bool { return !b.freed && len(b.data) == 0 }) - pred("valid?", func(b *ioBuffer) bool { return true }) + pred("valid?", func(b *ioBuffer) bool { return b.sliceValid() }) pred("external?", func(b *ioBuffer) bool { return !b.freed && b.external }) pred("internal?", func(b *ioBuffer) bool { return !b.freed && !b.external && !b.borrowed }) pred("mapped?", func(b *ioBuffer) bool { return false }) pred("shared?", func(b *ioBuffer) bool { return false }) pred("private?", func(b *ioBuffer) bool { return false }) - pred("locked?", func(b *ioBuffer) bool { return false }) + pred("locked?", func(b *ioBuffer) bool { return b.locked }) pred("readonly?", func(b *ioBuffer) bool { return b.readonly }) // slice(offset = 0, length = size - offset) returns a buffer that shares this @@ -234,21 +306,34 @@ func (vm *VM) registerIOBuffer() { if off < 0 || length < 0 || off+length > len(data) { raise("ArgumentError", "Specified offset+length is bigger than the buffer size!") } - return &ioBuffer{data: data[off : off+length : off+length], readonly: b.readonly, borrowed: true} + return &ioBuffer{data: data[off : off+length : off+length], readonly: b.readonly, borrowed: true, parent: b, sliceOff: off, sliceLen: length} }) // resize(size) reallocates the buffer to the new size, preserving the leading // bytes (a larger buffer is zero-filled). An external buffer (from .for / // .string, or a slice) cannot be resized. dm("resize", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { b := self.(*ioBuffer) - b.live() - if b.external { + if b.locked { + raise("IO::Buffer::LockedError", "Cannot resize locked buffer!") + } + size := bufSizeArg(args[0]) + // A live external buffer (.for/.string) cannot be resized; a *freed* + // (null) one may be, reallocating into a fresh internal buffer. + if b.external && !b.freed { raise("IO::Buffer::AccessError", "Cannot resize external buffer!") } - nd := make([]byte, int(intArg(args[0]))) + if size == 0 { + b.data = nil + b.freed = true + return b + } + nd := make([]byte, size) copy(nd, b.data) b.data = nd + b.freed = false + b.external = false b.borrowed = false + b.parent = nil return b }) @@ -259,6 +344,48 @@ func (vm *VM) registerIOBuffer() { return b }) + // transfer (io_buffer.c io_buffer_transfer) moves this buffer's memory and its + // kind (external/read-only/slice) to a fresh buffer and nullifies the original, + // so #null? on the source becomes true. It is refused while the buffer is + // locked. + dm("transfer", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + b := self.(*ioBuffer) + if b.locked { + raise("IO::Buffer::LockedError", "Cannot transfer ownership of locked buffer!") + } + nb := &ioBuffer{ + data: b.data, + readonly: b.readonly, + external: b.external, + borrowed: b.borrowed, + parent: b.parent, + sliceOff: b.sliceOff, + sliceLen: b.sliceLen, + } + b.freed = true + b.data = nil + return nb + }) + + // locked (io_buffer.c io_buffer_locked) marks the buffer locked for the + // duration of the block, so #locked? is true inside and structural changes + // (#resize/#transfer) raise LockedError. Re-entering raises "Buffer already + // locked!". The lock does not propagate to or from slices. + dm("locked", func(vm *VM, self object.Value, _ []object.Value, blk *Proc) object.Value { + b := self.(*ioBuffer) + if blk == nil { + // io_buffer.c io_buffer_locked checks rb_block_given_p explicitly and + // raises "no block given" (no "(yield)" suffix, unlike a bare yield). + raise("LocalJumpError", "no block given") + } + if b.locked { + raise("IO::Buffer::LockedError", "Buffer already locked!") + } + b.locked = true + defer func() { b.locked = false }() + return vm.callBlock(blk, []object.Value{b}) + }) + // get_string(offset = 0, length = size - offset, encoding = BINARY). dm("get_string", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { b := self.(*ioBuffer) @@ -355,19 +482,27 @@ func (vm *VM) registerIOBuffer() { return object.IntValue(int64(n)) }) - // Bitwise operators combine two equal-length buffers (or a buffer and a shorter - // one, repeating it) into a fresh internal buffer; ~ complements every byte. + // maskBytes reads the argument buffer of a binary bitwise operator, raising the + // io_buffer.c messages: TypeError "wrong argument type X (expected IO::Buffer)" + // for a non-buffer, ArgumentError for a zero-length mask. + maskBytes := func(v object.Value) []byte { + other, ok := v.(*ioBuffer) + if !ok { + raise("TypeError", "wrong argument type %s (expected IO::Buffer)", bufferArgTypeName(v)) + } + ob := other.live() + if len(ob) == 0 { + raise("ArgumentError", "Other buffer has zero length!") + } + return ob + } + // Bitwise operators combine two buffers (a shorter mask is repeated across the + // source): &/|/^ return a fresh internal buffer, and!/or!/xor! mutate the + // receiver in place and return it. ~ / not! complement every byte likewise. bitOp := func(name string, op func(a, b byte) byte) { dm(name, func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { a := self.(*ioBuffer).live() - other, ok := args[0].(*ioBuffer) - if !ok { - raise("TypeError", "no implicit conversion of %s into IO::Buffer", classNameOf(args[0])) - } - ob := other.live() - if len(ob) == 0 { - raise("ArgumentError", "Other buffer has zero length!") - } + ob := maskBytes(args[0]) out := make([]byte, len(a)) for i := range a { out[i] = op(a[i], ob[i%len(ob)]) @@ -375,9 +510,24 @@ func (vm *VM) registerIOBuffer() { return &ioBuffer{data: out} }) } + bitOpBang := func(name string, op func(a, b byte) byte) { + dm(name, func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + b := self.(*ioBuffer) + b.checkWritable() + a := b.live() + ob := maskBytes(args[0]) + for i := range a { + a[i] = op(a[i], ob[i%len(ob)]) + } + return b + }) + } bitOp("&", func(a, b byte) byte { return a & b }) bitOp("|", func(a, b byte) byte { return a | b }) bitOp("^", func(a, b byte) byte { return a ^ b }) + bitOpBang("and!", func(a, b byte) byte { return a & b }) + bitOpBang("or!", func(a, b byte) byte { return a | b }) + bitOpBang("xor!", func(a, b byte) byte { return a ^ b }) dm("~", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { a := self.(*ioBuffer).live() out := make([]byte, len(a)) @@ -386,6 +536,15 @@ func (vm *VM) registerIOBuffer() { } return &ioBuffer{data: out} }) + dm("not!", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + b := self.(*ioBuffer) + b.checkWritable() + a := b.live() + for i := range a { + a[i] = ^a[i] + } + return b + }) // == (and inspect) are handled by the shared valueEqual / Inspect paths. dm("to_s", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { diff --git a/internal/vm/io_buffer_internal_test.go b/internal/vm/io_buffer_internal_test.go index dbbea4c4..417d96f4 100644 --- a/internal/vm/io_buffer_internal_test.go +++ b/internal/vm/io_buffer_internal_test.go @@ -108,3 +108,78 @@ func TestIOBuffer(t *testing.T) { } } } + +// TestIOBufferWave21 covers the wave-21 IO::Buffer additions: the +// LockedError/InvalidatedError/AllocationError exceptions, .new/#resize size +// validation, .for block writability (mutable vs frozen source), the in-place +// bitwise operators and!/or!/xor!/not!, #transfer, #locked/#locked?, and slice +// invalidation via #valid?. Every value verified byte-for-byte against ruby +// 4.0.5. +func TestIOBufferWave21(t *testing.T) { + cases := []struct{ src, want string }{ + // Exception constants (all RuntimeError subclasses, per io_buffer.c). + {`p [IO::Buffer.const_defined?(:LockedError), IO::Buffer.const_defined?(:InvalidatedError), IO::Buffer.const_defined?(:AllocationError)]`, `[true, true, true]`}, + {`p IO::Buffer::LockedError.ancestors.include?(RuntimeError)`, `true`}, + {`p IO::Buffer::InvalidatedError.ancestors.include?(RuntimeError)`, `true`}, + {`p IO::Buffer::AllocationError.ancestors.include?(RuntimeError)`, `true`}, + // .new size validation: non-Integer => TypeError, negative => ArgumentError. + {`begin; IO::Buffer.new(-1); rescue => e; p [e.class, e.message]; end`, `[ArgumentError, "Size can't be negative!"]`}, + {`begin; IO::Buffer.new(0.0); rescue => e; p [e.class, e.message]; end`, `[TypeError, "not an Integer"]`}, + {`begin; IO::Buffer.new(nil); rescue => e; p [e.class, e.message]; end`, `[TypeError, "not an Integer"]`}, + // #resize size validation shares the same helper. + {`begin; IO::Buffer.new(4).resize(-1); rescue => e; p [e.class, e.message]; end`, `[ArgumentError, "Size can't be negative!"]`}, + {`begin; IO::Buffer.new(4).resize(nil); rescue => e; p [e.class, e.message]; end`, `[TypeError, "not an Integer"]`}, + {`begin; IO::Buffer.new(4).resize(10.0); rescue => e; p [e.class, e.message]; end`, `[TypeError, "not an Integer"]`}, + // #resize(0) frees the buffer; a freed external buffer can be re-grown. + {`b = IO::Buffer.new(4); b.resize(0); p b.null?`, `true`}, + {`b = IO::Buffer.for("test"); b.free; b.resize(10); p [b.size, b.internal?]`, `[10, true]`}, + // .for over a mutable String (with a block) aliases it and is writable; + // a frozen source, or no block, yields a read-only copy. + {`s = +"forstring"; IO::Buffer.for(s) { |b| b.set_string("XY") }; p s`, `"XYrstring"`}, + {`IO::Buffer.for(+"abc") { |b| p b.readonly? }`, `false`}, + {`IO::Buffer.for("abc".freeze) { |b| p b.readonly? }`, `true`}, + {`p IO::Buffer.for(+"abc").readonly?`, `true`}, + {`class T21; def to_str; "hi"; end; end; IO::Buffer.for(T21.new) { |b| p b.get_string }`, `"hi"`}, + // In-place bitwise operators mutate the receiver and return it. + {`IO::Buffer.for(+"12345") { |b| IO::Buffer.for(+"\xF8\x8F") { |m| r = b.and!(m); p [r.equal?(b), b.get_string.bytes] } }`, `[true, [48, 2, 48, 4, 48]]`}, + {`IO::Buffer.for(+"\x0f\xf0") { |b| IO::Buffer.for(+"\xff\x0f") { |m| b.or!(m); p b.get_string.bytes } }`, `[255, 255]`}, + {`IO::Buffer.for(+"\x0f\xf0") { |b| IO::Buffer.for(+"\xff\x0f") { |m| b.xor!(m); p b.get_string.bytes } }`, `[240, 255]`}, + {`IO::Buffer.for(+"\x0f") { |b| b.not!; p b.get_string.bytes }`, `[240]`}, + {`IO::Buffer.for(+"ab") { |b| IO::Buffer.for(+"\xff") { |m| p b.and!(m).external? } }`, `true`}, + // In-place ops on a read-only buffer raise AccessError. + {`begin; IO::Buffer.for("x").and!(IO::Buffer.for("\xff")); rescue => e; p [e.class, e.message]; end`, `[IO::Buffer::AccessError, "Buffer is not writable!"]`}, + {`begin; IO::Buffer.for("x").not!; rescue => e; p e.class; end`, `IO::Buffer::AccessError`}, + // Bitwise-operator argument-type message (nil/true/false lower-cased). + {`begin; IO::Buffer.for("x") & true; rescue => e; p [e.class, e.message]; end`, `[TypeError, "wrong argument type true (expected IO::Buffer)"]`}, + {`begin; IO::Buffer.for("x") & false; rescue => e; p e.message; end`, `"wrong argument type false (expected IO::Buffer)"`}, + {`begin; IO::Buffer.for("x") & "y"; rescue => e; p e.message; end`, `"wrong argument type String (expected IO::Buffer)"`}, + {`begin; IO::Buffer.for("x") & nil; rescue => e; p e.message; end`, `"wrong argument type nil (expected IO::Buffer)"`}, + {`begin; IO::Buffer.for(+"x") { |b| b.and!(IO::Buffer.new(0)) }; rescue ArgumentError => e; p e.message; end`, `"Other buffer has zero length!"`}, + // #transfer moves memory and kind to a fresh buffer, nullifying the source. + {`b = IO::Buffer.new(4); b.set_string("test"); nb = b.transfer; p [b.null?, nb.null?, nb.get_string, nb.internal?]`, `[true, false, "test", true]`}, + {`fb = IO::Buffer.for("test"); nfb = fb.transfer; p [nfb.external?, nfb.readonly?, fb.null?]`, `[true, true, true]`}, + {`buf = IO::Buffer.new(4); buf.set_string("test"); sl = buf.slice(0, 2); ns = sl.transfer; ns.set_string("ea"); p [sl.null?, buf.get_string]`, `[true, "east"]`}, + {`b = IO::Buffer.new(4); b.locked { begin; b.transfer; rescue => e; p [e.class, e.message]; end }`, `[IO::Buffer::LockedError, "Cannot transfer ownership of locked buffer!"]`}, + // #locked / #locked?: reentrancy, no-block, resize refusal, no propagation. + {`b = IO::Buffer.new(4); r = nil; b.locked { r = b.locked? }; p [r, b.locked?]`, `[true, false]`}, + {`b = IO::Buffer.new(4); b.locked { begin; b.locked {}; rescue => e; p [e.class, e.message]; end }`, `[IO::Buffer::LockedError, "Buffer already locked!"]`}, + {`begin; IO::Buffer.new(4).locked; rescue => e; p [e.class, e.message]; end`, `[LocalJumpError, "no block given"]`}, + {`b = IO::Buffer.new(4); b.locked { begin; b.resize(8); rescue => e; p [e.class, e.message]; end }`, `[IO::Buffer::LockedError, "Cannot resize locked buffer!"]`}, + {`b = IO::Buffer.new(4); s = b.slice(0, 2); r = nil; b.locked { r = [b.locked?, s.locked?] }; p r`, `[true, false]`}, + // #valid?: a non-slice is always valid; a slice invalidates when its source + // is freed, transferred, or resized out from under it, but a slice of a + // String-backed buffer stays valid after the buffer is freed. + {`b = IO::Buffer.new(4); b.free; p b.valid?`, `true`}, + {`b = IO::Buffer.new(4); s = b.slice(0, 2); p s.valid?`, `true`}, + {`b = IO::Buffer.new(4); s = b.slice(0, 2); b.transfer; p [s.null?, s.valid?]`, `[false, false]`}, + {`b = IO::Buffer.new(4); s = b.slice(0, 2); b.free; p s.valid?`, `false`}, + {`b = IO::Buffer.new(4); s = b.slice(2, 2); b.resize(3); p s.valid?`, `false`}, + {`b = IO::Buffer.for("alive"); s = b.slice(0, 2); b.free; p s.valid?`, `true`}, + {`b = IO::Buffer.new(4); s = b.slice(0, 2); b.transfer; begin; s.get_string; rescue => e; p [e.class, e.message]; end`, `[IO::Buffer::InvalidatedError, "Buffer has been invalidated!"]`}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want+"\n" { + t.Errorf("src=%q got=%q want=%q", c.src, got, c.want+"\n") + } + } +} From 39e2da42ccf6a3ce65972c77c2d274bf87ce27e6 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 8 Sep 2026 20:35:51 +0200 Subject: [PATCH 2/2] io: IO#advise as a validated no-op (core/io advise_spec 0->13) Reference: MRI io.c rb_io_advise + advice_arg_check, and ruby/spec core/io/advise_spec.rb. rbgo has no posix_fadvise (as MRI on a platform without it), so #advise validates its arguments and returns nil. Checks, in MRI's order and verified byte-for-byte against ruby 4.0.5 on darwin: - a non-Symbol advice raises TypeError "advice must be a Symbol"; - an unrecognized advice raises NotImplementedError "Unsupported advice: :sym" (recognized: :normal :sequential :random :willneed :dontneed :noreuse); - a closed stream raises IOError "closed stream"; - offset and len are coerced as off_t (reusing ioOfftArg): a non-Integer raises TypeError, a too-large Bignum RangeError; - wrong arity (0 or >3 args) raises ArgumentError. advise_spec: 13 examples now all pass (was 6 error + 7 fail). Whitebox test covers every branch; io.go stays at 100% coverage, gofmt clean, wasip1 builds. Co-Authored-By: Claude Opus 4.8 --- internal/vm/io.go | 30 +++++++++++++++++ internal/vm/io_advise_test.go | 61 +++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 internal/vm/io_advise_test.go diff --git a/internal/vm/io.go b/internal/vm/io.go index 2a978769..fb94c7c4 100644 --- a/internal/vm/io.go +++ b/internal/vm/io.go @@ -816,6 +816,36 @@ func defIOWrite(cls *RClass) { ioClosedRealIO(self.(*IOObj)) // as flush: real IO raises on close, StringIO does not return object.IntValue(0) }) + // IO#advise(advice, offset = 0, len = 0) (rb_io_advise + advice_arg_check in + // io.c). rbgo has no posix_fadvise, so like MRI on a platform without it the + // call is a validated no-op returning nil. Argument checks, in MRI's order: + // a non-Symbol advice raises TypeError; an unrecognized one NotImplementedError + // "Unsupported advice: :sym"; a closed stream IOError; then offset and len are + // coerced as off_t (a non-Integer raises TypeError, a too-large Bignum + // RangeError). + cls.define("advise", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { + if len(args) < 1 || len(args) > 3 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 1..3)", len(args)) + } + sym, ok := args[0].(object.Symbol) + if !ok { + raise("TypeError", "advice must be a Symbol") + } + switch string(sym) { + case "normal", "sequential", "random", "willneed", "dontneed", "noreuse": + // recognized advice types (io.c io_advise_sym_to_const) + default: + raise("NotImplementedError", "Unsupported advice: %s", args[0].Inspect()) + } + ioClosedRealIO(self.(*IOObj)) + if len(args) > 1 && !object.IsNil(args[1]) { + vm.ioOfftArg(args[1]) // offset: coerced for its TypeError/RangeError checks + } + if len(args) > 2 && !object.IsNil(args[2]) { + vm.ioOfftArg(args[2]) // len: likewise + } + return object.NilV + }) // These sync/sync= entries serve a real IO; StringIO overrides both in // defStringIOExtra (its #sync is always true), so the closed-stream guard here // only ever fires for a real IO/File, which MRI makes raise IOError. diff --git a/internal/vm/io_advise_test.go b/internal/vm/io_advise_test.go new file mode 100644 index 00000000..1d5f50a7 --- /dev/null +++ b/internal/vm/io_advise_test.go @@ -0,0 +1,61 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "fmt" + "path/filepath" + "testing" +) + +// TestIOAdvise covers IO#advise (rb_io_advise): the six recognized advice types +// as validated no-ops returning nil, the optional offset/len (present, nil, and +// coercion errors), and the error branches — a non-Symbol advice (TypeError), an +// unrecognized one (NotImplementedError "Unsupported advice: :sym"), wrong arity +// (ArgumentError), a non-Integer or too-large offset/len (TypeError / RangeError), +// and a closed stream (IOError). Every line verified byte-for-byte against ruby +// 4.0.5 on darwin. File-backed via a per-test temp dir so no machine file is +// touched; the asserted classes/messages are platform-independent. +func TestIOAdvise(t *testing.T) { + dir := t.TempDir() + path := filepath.ToSlash(filepath.Join(dir, "advise.txt")) + src := fmt.Sprintf(` +f = File.open(%q, "w+") +p f.advise(:normal) +p f.advise(:sequential) +p f.advise(:random) +p f.advise(:willneed) +p f.advise(:dontneed) +p f.advise(:noreuse) +p f.advise(:normal, 0) +p f.advise(:normal, nil) +p f.advise(:normal, 0, 0) +p f.advise(:normal, 0, nil) +begin; f.advise("normal"); rescue Exception => e; p e.class; end +begin; f.advise(:foo); rescue Exception => e; p [e.class, e.message]; end +begin; f.advise; rescue Exception => e; p e.class; end +begin; f.advise(:normal, 0, 0, 0); rescue Exception => e; p e.class; end +begin; f.advise(:normal, "wat"); rescue Exception => e; p e.class; end +begin; f.advise(:normal, 0, "wat"); rescue Exception => e; p e.class; end +begin; f.advise(:normal, 10 ** 32); rescue Exception => e; p e.class; end +begin; f.advise(:normal, 0, 10 ** 32); rescue Exception => e; p e.class; end +f.close +begin; f.advise(:normal); rescue Exception => e; p [e.class, e.message]; end +`, path) + want := "nil\nnil\nnil\nnil\nnil\nnil\n" + + "nil\nnil\nnil\nnil\n" + + "TypeError\n" + + "[NotImplementedError, \"Unsupported advice: :foo\"]\n" + + "ArgumentError\n" + + "ArgumentError\n" + + "TypeError\n" + + "TypeError\n" + + "RangeError\n" + + "RangeError\n" + + "[IOError, \"closed stream\"]\n" + if got := eval(t, src); got != want { + t.Errorf("src=%q\n got=%q\nwant=%q", src, got, want) + } +}