From 99a2da697905c3bf5c33f5a995d7bb88aee4d518 Mon Sep 17 00:00:00 2001 From: Yusuke Endoh Date: Wed, 28 Oct 2026 01:30:17 +0900 Subject: [PATCH 01/16] Fetch the underlying data after argument conversions Converting an argument (`to_int`, `to_str`, `to_s`, ...) may call back into Ruby code, which may call `StringIO#reopen` on the same stream. `reopen(other)` replaces the underlying `struct StringIO` and frees the old one, so a pointer fetched before the conversion became stale. Fetch the pointer again after the conversions, and after yielding in `each_line`. In `strio_init`, let `rb_io_extract_modeenc` write into a local instead of `ptr->flags`. Reported-by: Zabith (https://hackerone.com/nmzabith) Co-Authored-By: Claude Mythos 5.1 --- ext/stringio/stringio.c | 58 +++++++++++++++++++++--------- test/stringio/test_stringio.rb | 64 ++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 17 deletions(-) diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index fb885e3..59f9a4a 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -97,7 +97,7 @@ struct StringIO { }; static struct StringIO *get_strio_for_read(VALUE self); -static VALUE strio_init(int, VALUE *, struct StringIO *, VALUE); +static VALUE strio_init(int, VALUE *, VALUE); static VALUE strio_unget_bytes(struct StringIO *, const char *, rb_len_t); static rb_len_t strio_write(VALUE self, VALUE str); @@ -196,12 +196,12 @@ strio_substr(struct StringIO *ptr, rb_len_t pos, rb_len_t len, rb_encoding *enc) } static VALUE -strio_readbuf(struct StringIO *ptr, VALUE str) +strio_readbuf(VALUE self, VALUE str) { if (!NIL_P(str)) { StringValue(str); rb_str_modify(str); - if (str == ptr->string) { + if (str == get_strio_for_read(self)->string) { rb_raise(rb_eArgError, "cannot read into the underlying string"); } } @@ -326,7 +326,7 @@ strio_initialize(int argc, VALUE *argv, VALUE self) DATA_PTR(self) = ptr = strio_alloc(); } rb_call_super(0, 0); - return strio_init(argc, argv, ptr, self); + return strio_init(argc, argv, self); } static int @@ -398,8 +398,9 @@ set_encoding_by_bom(struct StringIO *ptr) } static VALUE -strio_init(int argc, VALUE *argv, struct StringIO *ptr, VALUE self) +strio_init(int argc, VALUE *argv, VALUE self) { + struct StringIO *ptr; VALUE string, vmode, opt; int oflags; rb_io_mode_t fmode; @@ -415,6 +416,7 @@ strio_init(int argc, VALUE *argv, struct StringIO *ptr, VALUE self) } /* The conversions above may freeze this stream. */ rb_check_frozen(self); + ptr = StringIOForRead(self); ptr->flags = fmode; if (!NIL_P(string) && readonly_string_p(string)) { @@ -609,6 +611,7 @@ strio_set_string(VALUE self, VALUE string) rb_io_taint_check(self); ptr->flags &= ~FMODE_READWRITE; StringValue(string); + ptr = StringIO(self); ptr->flags = readonly_string_p(string) ? FMODE_READABLE : FMODE_READWRITE; ptr->pos = 0; ptr->lineno = 0; @@ -839,7 +842,8 @@ strio_get_lineno(VALUE self) static VALUE strio_set_lineno(VALUE self, VALUE lineno) { - StringIO(self)->lineno = NUM2LEN(lineno); + rb_len_t n = NUM2LEN(lineno); + StringIO(self)->lineno = n; return lineno; } @@ -901,7 +905,7 @@ strio_reopen(int argc, VALUE *argv, VALUE self) if (argc == 1 && !RB_TYPE_P(*argv, T_STRING)) { return strio_copy(self, *argv); } - return strio_init(argc, argv, StringIO(self), self); + return strio_init(argc, argv, self); } /* @@ -929,6 +933,7 @@ strio_set_pos(VALUE self, VALUE pos) { struct StringIO *ptr = StringIO(self); rb_len_t p = NUM2LEN(pos); + ptr = StringIO(self); if (p < 0) { error_inval(0); } @@ -967,13 +972,16 @@ strio_seek(int argc, VALUE *argv, VALUE self) VALUE whence; struct StringIO *ptr = StringIO(self); rb_len_t amount, offset; + long w; rb_scan_args(argc, argv, "11", NULL, &whence); amount = NUM2LEN(argv[0]); if (CLOSED(self)) { rb_raise(rb_eIOError, "closed stream"); } - switch (NIL_P(whence) ? 0 : NUM2LONG(whence)) { + w = NIL_P(whence) ? 0 : NUM2LONG(whence); + ptr = StringIO(self); + switch (w) { case 0: offset = 0; break; @@ -1224,6 +1232,9 @@ strio_ungetc(VALUE self, VALUE c) } else { StringValue(c); + ptr = readable(self); + check_modifiable(ptr); + if (NIL_P(ptr->string)) return Qnil; if (RSTRING_LEN(c) == 0) return Qnil; enc = rb_enc_get(ptr->string); enc2 = rb_enc_get(c); @@ -1254,12 +1265,15 @@ strio_ungetbyte(VALUE self, VALUE c) /* rb_int_and() not visible from exts */ VALUE v = rb_funcall(c, '&', 1, INT2FIX(0xff)); const char cc = NUM2INT(v) & 0xFF; - strio_unget_bytes(ptr, &cc, 1); + c = rb_str_new(&cc, 1); } else { StringValue(c); - strio_unget_string(ptr, c); } + ptr = readable(self); + check_modifiable(ptr); + if (NIL_P(ptr->string)) return Qnil; + strio_unget_string(ptr, c); return Qnil; } @@ -1476,8 +1490,9 @@ struct getline_arg { }; static struct getline_arg * -prepare_getline_args(struct StringIO *ptr, struct getline_arg *arg, int argc, VALUE *argv) +prepare_getline_args(VALUE self, struct StringIO **ptrp, struct getline_arg *arg, int argc, VALUE *argv) { + struct StringIO *ptr; VALUE rs, lim, opts; rb_len_t limit = -1; int respect_chomp; @@ -1507,6 +1522,7 @@ prepare_getline_args(struct StringIO *ptr, struct getline_arg *arg, int argc, VA if (!NIL_P(lim)) limit = NUM2LEN(lim); break; } + *ptrp = ptr = readable(self); if (!NIL_P(ptr->string) && !NIL_P(rs)) { rb_encoding *enc_rs, *enc_io; enc_rs = rb_enc_get(rs); @@ -1758,7 +1774,7 @@ strio_gets(int argc, VALUE *argv, VALUE self) struct getline_arg arg; VALUE str; - if (prepare_getline_args(ptr, &arg, argc, argv)->limit == 0) { + if (prepare_getline_args(self, &ptr, &arg, argc, argv)->limit == 0) { if (NIL_P(ptr->string)) return Qnil; return rb_enc_str_new(0, 0, get_enc(ptr)); } @@ -1993,11 +2009,11 @@ strio_each(int argc, VALUE *argv, VALUE self) RETURN_ENUMERATOR(self, argc, argv); - if (prepare_getline_args(ptr, &arg, argc, argv)->limit == 0) { + if (prepare_getline_args(self, &ptr, &arg, argc, argv)->limit == 0) { rb_raise(rb_eArgError, "invalid limit: 0 for each_line"); } - while (!NIL_P(line = strio_getline(&arg, ptr))) { + while (!NIL_P(line = strio_getline(&arg, StringIOForRead(self)))) { rb_yield(line); } return self; @@ -2018,7 +2034,7 @@ strio_readlines(int argc, VALUE *argv, VALUE self) struct StringIO *ptr = readable(self); struct getline_arg arg; - if (prepare_getline_args(ptr, &arg, argc, argv)->limit == 0) { + if (prepare_getline_args(self, &ptr, &arg, argc, argv)->limit == 0) { rb_raise(rb_eArgError, "invalid limit: 0 for readlines"); } @@ -2061,6 +2077,7 @@ strio_write(VALUE self, VALUE str) if (!RB_TYPE_P(str, T_STRING)) str = rb_obj_as_string(str); + ptr = writable(self); if (NIL_P(ptr->string)) return 0; enc = get_enc(ptr); enc2 = rb_enc_get(str); @@ -2222,6 +2239,7 @@ strio_putc(VALUE self, VALUE ch) } else { char c = NUM2CHR(ch); + ptr = writable(self); if (NIL_P(ptr->string)) return ch; str = rb_str_new(&c, 1); } @@ -2336,7 +2354,7 @@ strio_read(int argc, VALUE *argv, VALUE self) switch (argc) { case 2: - str = strio_readbuf(ptr, argv[1]); + str = strio_readbuf(self, argv[1]); /* fall through */ case 1: if (!NIL_P(argv[0])) { @@ -2344,6 +2362,8 @@ strio_read(int argc, VALUE *argv, VALUE self) if (len < 0) { rb_raise(rb_eArgError, "negative length %"PRIdLEN" given", len); } + ptr = readable(self); + str = strio_readbuf(self, str); if (eos_p(ptr)) { if (!NIL_P(str)) rb_str_resize(str, 0); if (len == 0) { @@ -2357,6 +2377,7 @@ strio_read(int argc, VALUE *argv, VALUE self) } /* fall through */ case 0: + ptr = readable(self); if (NIL_P(ptr->string)) return Qnil; len = RSTRING_LEN(ptr->string); if (len <= ptr->pos) { @@ -2482,7 +2503,8 @@ strio_pread(int argc, VALUE *argv, VALUE self) rb_syserr_fail_str(EINVAL, rb_sprintf("pread: Invalid offset argument: %" PRIsVALUE, rb_offset)); } - rb_buf = strio_readbuf(ptr, rb_buf); + rb_buf = strio_readbuf(self, rb_buf); + ptr = readable(self); if (len == 0) { if (NIL_P(rb_buf)) { @@ -2613,6 +2635,7 @@ strio_truncate(VALUE self, VALUE len) VALUE string = writable(self)->string; rb_len_t l = NUM2LEN(len); rb_len_t plen; + string = writable(self)->string; if (l < 0) { error_inval("negative length"); } @@ -2695,6 +2718,7 @@ strio_set_encoding(int argc, VALUE *argv, VALUE self) enc = convconfig.enc2; } } + ptr = StringIO(self); ptr->enc = enc; if (!NIL_P(ptr->string) && WRITABLE(self) && !str_chilled_p(ptr->string)) { rb_enc_associate(ptr->string, enc); diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 5de2e03..e49b335 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1347,6 +1347,70 @@ def test_set_encoding_by_bom_null_device assert_nil(StringIO.new(nil, "r:BOM|UTF-8").string) end + def test_reopen_during_argument_conversion + ops = [ + ->(f, c) {f.read(c)}, + ->(f, c) {f.read(5, c)}, + ->(f, c) {f.pread(5, c)}, + ->(f, c) {f.pread(5, 0, c)}, + ->(f, c) {f.pos = c}, + ->(f, c) {f.seek(c)}, + ->(f, c) {f.lineno = c}, + ->(f, c) {f.truncate(c)}, + ->(f, c) {f.write(c)}, + ->(f, c) {f.putc(c)}, + ->(f, c) {f.ungetc(c)}, + ->(f, c) {f.ungetbyte(c)}, + ->(f, c) {f.gets(c)}, + ->(f, c) {f.gets(nil, c)}, + ->(f, c) {f.readlines(c)}, + ->(f, c) {f.each_line(c) {}}, + ->(f, c) {f.string = c}, + ->(f, c) {f.reopen("", c)}, + ] + ops.each do |op| + f = StringIO.new("hello\n" * 10) + g = StringIO.new("world\n" * 10) + c = Object.new + c.define_singleton_method(:to_int) {f.reopen(g); 5} + c.define_singleton_method(:to_str) {f.reopen(g); "r".dup} + c.define_singleton_method(:to_s) {f.reopen(g); "r".dup} + op.call(f, c) + assert_same(g.string, f.string, op.source_location.join(":")) + end + + f = StringIO.new("hello") + g = StringIO.new("world") + c = Object.new + c.define_singleton_method(:to_str) {f.reopen(g); "US-ASCII"} + f.set_encoding(c) + assert_equal(Encoding::US_ASCII, g.external_encoding) + end + + def test_reopen_in_each_line_block + f = StringIO.new("a\nb\nc\n") + g = StringIO.new("x\ny\n") + lines = [] + f.each_line {|l| lines << l; f.reopen(g)} + assert_equal(["a\n", "x\n", "y\n"], lines) + end + + def test_reopen_during_argument_conversion_to_underlying_string + ops = [ + ->(f, c, g) {f.read(c, g.string)}, + ->(f, c, g) {f.read(5, c)}, + ->(f, c, g) {f.pread(5, 0, c)}, + ] + ops.each do |op| + f = StringIO.new("hello") + g = StringIO.new("world") + c = Object.new + c.define_singleton_method(:to_int) {f.reopen(g); 5} + c.define_singleton_method(:to_str) {f.reopen(g); g.string} + assert_raise(ArgumentError, op.source_location.join(":")) {op.call(f, c, g)} + end + end + private def assert_string(content, encoding, str, mesg = nil) From d272a0424a1d3fc4a5c393290dcf807114472b85 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 17:01:38 +0900 Subject: [PATCH 02/16] Don't clear flags of the old stream in `StringIO#string=` `string=` cleared the read/write flags before converting the argument. If the conversion reopens the receiver, the flags of the old stream are cleared but never restored, because the new flags are set on the replacement. Another stream that shares the old data (e.g. one made by `dup`) is left closed. The clearing is a leftover of the old code that closed the stream for a `nil` argument. The flags are overwritten after the conversion, so just remove it, and fetch the data only once after the conversion. This also stops leaving the stream closed when the conversion raises. Co-Authored-By: Claude Opus 5.5 --- ext/java/org/jruby/ext/stringio/StringIO.java | 1 - ext/stringio/stringio.c | 3 +-- test/stringio/test_stringio.rb | 10 ++++++++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/ext/java/org/jruby/ext/stringio/StringIO.java b/ext/java/org/jruby/ext/stringio/StringIO.java index dbaa69f..1a9b64f 100644 --- a/ext/java/org/jruby/ext/stringio/StringIO.java +++ b/ext/java/org/jruby/ext/stringio/StringIO.java @@ -1449,7 +1449,6 @@ public IRubyObject set_string(ThreadContext context, IRubyObject arg) { boolean locked = lock(context, ptr); try { - ptr.flags &= ~OpenFile.READWRITE; RubyString str = arg.convertToString(); ptr.flags = str.isFrozen() ? OpenFile.READABLE : OpenFile.READWRITE; ptr.pos = 0; diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index 59f9a4a..d851f52 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -606,10 +606,9 @@ strio_get_string(VALUE self) static VALUE strio_set_string(VALUE self, VALUE string) { - struct StringIO *ptr = StringIO(self); + struct StringIO *ptr; rb_io_taint_check(self); - ptr->flags &= ~FMODE_READWRITE; StringValue(string); ptr = StringIO(self); ptr->flags = readonly_string_p(string) ? FMODE_READABLE : FMODE_READWRITE; diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index e49b335..fb7326c 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1387,6 +1387,16 @@ def test_reopen_during_argument_conversion assert_equal(Encoding::US_ASCII, g.external_encoding) end + def test_set_string_reopen_during_conversion_keeps_shared_stream + f = StringIO.new("hello") + shared = f.dup + g = StringIO.new("world") + c = Object.new + c.define_singleton_method(:to_str) {f.reopen(g); "new".dup} + f.string = c + assert_equal(["new", "hello"], [g.string, shared.read]) + end + def test_reopen_in_each_line_block f = StringIO.new("a\nb\nc\n") g = StringIO.new("x\ny\n") From ccb649e0f360e67746af173aef3c886506ed2cd7 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 17:01:38 +0900 Subject: [PATCH 03/16] Fetch the underlying data after argument conversions on JRuby Apply the same fix as the C extension to the JRuby extension. `StringIO#reopen(other)` replaces `ptr`, so data fetched before an argument conversion may belong to the old stream. Convert arguments before taking the lock and fetch `ptr` again after the conversions in `read`, `pread`, `seek`, `string=`, `truncate`, `ungetc`, `ungetbyte` and `strioInit`. `readBuf` now compares the buffer with the current underlying string instead of the one passed in. Use `num2int`/`num2long` instead of `fix2int`/`fix2long` for `lineno=`, `pos=`, `read`, `pread` and `truncate`. The latter assume the argument is a `Fixnum` and raise `ClassCastException` for an object that responds to `to_int`. Co-Authored-By: Claude Opus 5.5 --- ext/java/org/jruby/ext/stringio/StringIO.java | 153 +++++++++++------- 1 file changed, 94 insertions(+), 59 deletions(-) diff --git a/ext/java/org/jruby/ext/stringio/StringIO.java b/ext/java/org/jruby/ext/stringio/StringIO.java index 1a9b64f..f6a19e2 100644 --- a/ext/java/org/jruby/ext/stringio/StringIO.java +++ b/ext/java/org/jruby/ext/stringio/StringIO.java @@ -334,53 +334,57 @@ private void strioInit(ThreadContext context, int argc, IRubyObject arg0, IRubyO StringIOData ptr = this.getPtrForWrite(); - boolean locked = lock(context, ptr); - try { - IRubyObject maybeOptions = context.nil; - switch (argc) { - case 1: - maybeOptions = ArgsUtil.getOptionsArg(runtime, arg0); - if (maybeOptions.isNil()) { - string = arg0; - } - break; - case 2: - string = arg0; - maybeOptions = ArgsUtil.getOptionsArg(runtime, arg1); - if (maybeOptions.isNil()) { - vmode = arg1; - } - break; - case 3: + IRubyObject maybeOptions = context.nil; + switch (argc) { + case 1: + maybeOptions = ArgsUtil.getOptionsArg(runtime, arg0); + if (maybeOptions.isNil()) { string = arg0; + } + break; + case 2: + string = arg0; + maybeOptions = ArgsUtil.getOptionsArg(runtime, arg1); + if (maybeOptions.isNil()) { vmode = arg1; - maybeOptions = ArgsUtil.getOptionsArg(runtime, arg2); - if (maybeOptions.isNil()) { - throw context.runtime.newArgumentError(argc, 0, 2); - } - break; - } - if (!maybeOptions.isNil()) { - argc--; - } - // Don't share these with other calls: the conversions in - // extractModeEncoding may call StringIO methods. - Object vmodeAndVpermP = EncodingUtils.vmodeVperm(vmode, null); - IOEncodable.ConvConfig ioEncodable = new IOEncodable.ConvConfig(); - int[] fmode = {0}; - - // switch to per-use oflags if it is ever used in the future - EncodingUtils.extractModeEncoding(context, ioEncodable, vmodeAndVpermP, maybeOptions, OFLAGS_UNUSED, fmode); - vmode = EncodingUtils.vmode(vmodeAndVpermP); - - if (!string.isNil()) { - string = string.convertToString(); - } else if (argc == 0) { - string = RubyString.newEmptyString(runtime, runtime.getDefaultExternalEncoding()); - } - // The conversions above may freeze this stream. - checkFrozen(); - ptr.flags = fmode[0]; + } + break; + case 3: + string = arg0; + vmode = arg1; + maybeOptions = ArgsUtil.getOptionsArg(runtime, arg2); + if (maybeOptions.isNil()) { + throw context.runtime.newArgumentError(argc, 0, 2); + } + break; + } + if (!maybeOptions.isNil()) { + argc--; + } + // Don't share these with other calls: the conversions in + // extractModeEncoding may call StringIO methods. + Object vmodeAndVpermP = EncodingUtils.vmodeVperm(vmode, null); + IOEncodable.ConvConfig ioEncodable = new IOEncodable.ConvConfig(); + int[] fmodeP = {0}; + + // switch to per-use oflags if it is ever used in the future + EncodingUtils.extractModeEncoding(context, ioEncodable, vmodeAndVpermP, maybeOptions, OFLAGS_UNUSED, fmodeP); + int fmode = fmodeP[0]; + vmode = EncodingUtils.vmode(vmodeAndVpermP); + + if (!string.isNil()) { + string = string.convertToString(); + } else if (argc == 0) { + string = RubyString.newEmptyString(runtime, runtime.getDefaultExternalEncoding()); + } + + // The conversions above may freeze or reopen this stream. + checkFrozen(); + ptr = this.getPtrForWrite(); + + boolean locked = lock(context, ptr); + try { + ptr.flags = fmode; if (!string.isNil() && string.isFrozen()) { if ((ptr.flags & OpenFile.WRITABLE) != 0) { @@ -1025,7 +1029,8 @@ public IRubyObject lineno(ThreadContext context) { @JRubyMethod(name = "lineno=", required = 1) public IRubyObject set_lineno(ThreadContext context, IRubyObject arg) { - getPtrForWrite().lineno = RubyNumeric.fix2int(arg); + int lineno = RubyNumeric.num2int(arg); + getPtrForWrite().lineno = lineno; return context.nil; } @@ -1130,19 +1135,26 @@ private IRubyObject readCommon(ThreadContext context, int argc, IRubyObject arg0 IRubyObject str = context.nil; boolean binary = false; StringIOData ptr = this.getPtrForWrite(); + int len = 0; + + // Convert the arguments before fetching the data, as the + // conversions may reopen this stream. + if (argc == 2) str = readBuf(context, arg1); + if (argc >= 1 && !arg0.isNil()) { + len = RubyNumeric.num2int(arg0); + str = readBuf(context, str); + } + checkReadable(); + ptr = this.getPtrForWrite(); int pos = ptr.pos; boolean locked = lock(context, ptr); try { - int len; final RubyString string; switch (argc) { case 2: - str = readBuf(context, ptr, arg1); case 1: if (!arg0.isNil()) { - len = RubyNumeric.fix2int(arg0); - if (len < 0) { throw runtime.newArgumentError("negative length " + len + " given"); } @@ -1234,16 +1246,16 @@ private RubyString preadCommon(ThreadContext context, int argc, IRubyObject arg0 switch (argc) { case 3: - str = readBuf(context, ptr, arg2); + str = readBuf(context, arg2); case 2: - len = RubyNumeric.fix2int(arg0); + len = RubyNumeric.num2int(arg0); if (!arg0.isNil()) { if (len < 0) { throw runtime.newArgumentError("negative length " + len + " given"); } } - offset = RubyNumeric.fix2int(arg1); + offset = RubyNumeric.num2int(arg1); if (offset < 0) { throw runtime.newErrnoEINVALError("pread: Invalid offset argument"); } @@ -1253,6 +1265,11 @@ private RubyString preadCommon(ThreadContext context, int argc, IRubyObject arg0 throw runtime.newArgumentError(argc, 0, 2); } + // The conversions above may reopen this stream. + str = readBuf(context, str); + checkReadable(); + ptr = this.getPtrForRead(); + boolean locked = lock(context, ptr); try { if (len == 0) { @@ -1414,9 +1431,14 @@ private RubyFixnum seekCommon(ThreadContext context, int argc, IRubyObject arg0, checkOpen(); + int w = whence.isNil() ? 0 : RubyNumeric.num2int(whence); + // The conversion above may reopen this stream. + ptr = this.getPtrForWrite(); + checkOpen(); + boolean locked = lock(context, ptr); try { - switch (whence.isNil() ? 0 : RubyNumeric.num2int(whence)) { + switch (w) { case 0: break; case 1: @@ -1445,11 +1467,14 @@ private RubyFixnum seekCommon(ThreadContext context, int argc, IRubyObject arg0, @JRubyMethod(name = "string=", required = 1) public IRubyObject set_string(ThreadContext context, IRubyObject arg) { + checkFrozen(); + + RubyString str = arg.convertToString(); + // The conversion above may reopen this stream. StringIOData ptr = this.getPtrForWrite(); boolean locked = lock(context, ptr); try { - RubyString str = arg.convertToString(); ptr.flags = str.isFrozen() ? OpenFile.READABLE : OpenFile.READWRITE; ptr.pos = 0; ptr.lineno = 0; @@ -1477,7 +1502,8 @@ public IRubyObject sync(ThreadContext context) { public IRubyObject truncate(ThreadContext context, IRubyObject len) { checkWritable(); - int l = RubyFixnum.fix2int(len); + int l = RubyNumeric.num2int(len); + checkWritable(); StringIOData ptr = this.getPtrForWrite(); RubyString string = ptr.string; @@ -1524,6 +1550,10 @@ public IRubyObject ungetc(ThreadContext context, IRubyObject arg) { ungetbyteCommon(context, buf, 0, len); } else { arg = arg.convertToString(); + // The conversion above may reopen this stream. + checkModifiable(); + checkReadable(); + if (getPtrForWrite().string == null) return context.nil; enc = getEncoding(); RubyString argStr = (RubyString) arg; enc2 = argStr.getEncoding(); @@ -1628,7 +1658,12 @@ public IRubyObject ungetbyte(ThreadContext context, IRubyObject arg) { if (arg instanceof RubyInteger) { ungetbyteCommon(context, ((RubyInteger) ((RubyInteger) arg).op_mod(context, 256)).getIntValue()); } else { - ungetbyteCommon(context, arg.convertToString()); + RubyString str = arg.convertToString(); + // The conversion above may reopen this stream. + checkReadable(); + checkModifiable(); + if (getPtrForWrite().string == null) return context.nil; + ungetbyteCommon(context, str); } return context.nil; @@ -1730,12 +1765,12 @@ private static IRubyObject substrString(RubyString ch, IRubyObject str, Ruby run return str; } - private static IRubyObject readBuf(ThreadContext context, StringIOData ptr, IRubyObject arg) { + private IRubyObject readBuf(ThreadContext context, IRubyObject arg) { if (!arg.isNil()) { arg = arg.convertToString(); RubyString str = (RubyString) arg; modifyString(str); - if (str == ptr.string) { + if (str == getPtrForRead().string) { throw context.runtime.newArgumentError("cannot read into the underlying string"); } } From a5b99b89a50e775c11520dfdfdd0223f317c0953 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 17:17:49 +0900 Subject: [PATCH 04/16] Check closed state after converting whence in `StringIO#seek` `seek` checked whether the stream is closed before converting `whence`. `whence.to_int` may reopen the receiver onto a closed stream, and then `seek` changed the position of that closed stream instead of raising `IOError`. Check the closed state after the conversion instead. This also matches `IO#seek`, which converts `whence` before checking the closed state. Co-Authored-By: Claude Opus 5.5 --- ext/java/org/jruby/ext/stringio/StringIO.java | 2 -- ext/stringio/stringio.c | 4 ++-- test/stringio/test_stringio.rb | 10 ++++++++++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/ext/java/org/jruby/ext/stringio/StringIO.java b/ext/java/org/jruby/ext/stringio/StringIO.java index f6a19e2..12d7eba 100644 --- a/ext/java/org/jruby/ext/stringio/StringIO.java +++ b/ext/java/org/jruby/ext/stringio/StringIO.java @@ -1429,8 +1429,6 @@ private RubyFixnum seekCommon(ThreadContext context, int argc, IRubyObject arg0, StringIOData ptr = this.getPtrForWrite(); - checkOpen(); - int w = whence.isNil() ? 0 : RubyNumeric.num2int(whence); // The conversion above may reopen this stream. ptr = this.getPtrForWrite(); diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index d851f52..ab1de03 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -975,11 +975,11 @@ strio_seek(int argc, VALUE *argv, VALUE self) rb_scan_args(argc, argv, "11", NULL, &whence); amount = NUM2LEN(argv[0]); + w = NIL_P(whence) ? 0 : NUM2LONG(whence); + ptr = StringIO(self); if (CLOSED(self)) { rb_raise(rb_eIOError, "closed stream"); } - w = NIL_P(whence) ? 0 : NUM2LONG(whence); - ptr = StringIO(self); switch (w) { case 0: offset = 0; diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index fb7326c..da0bea3 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1397,6 +1397,16 @@ def test_set_string_reopen_during_conversion_keeps_shared_stream assert_equal(["new", "hello"], [g.string, shared.read]) end + def test_seek_reopen_to_closed_during_whence_conversion + f = StringIO.new("hello") + g = StringIO.new("world") + g.close + c = Object.new + c.define_singleton_method(:to_int) {f.reopen(g); 0} + assert_raise(IOError) {f.seek(3, c)} + assert_equal(0, g.pos) + end + def test_reopen_in_each_line_block f = StringIO.new("a\nb\nc\n") g = StringIO.new("x\ny\n") From 050be3af84e88116a3c3ddffac3eaa51ed89b66d Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 17:36:07 +0900 Subject: [PATCH 05/16] Check readability for each line in `StringIO#each_line` `each_line` checked readability only once before the loop. If the block closed the stream, or reopened it onto a stream that is not readable, `each_line` kept reading lines from it. Use `readable()` to fetch the stream for each line, as the JRuby extension and `IO` do. Also remove the `readable()` call at the beginning of `gets`, `each_line` and `readlines`. Its result is overwritten by `prepare_getline_args()`, which checks readability after converting the arguments. As a result, these methods convert the arguments before checking readability, and `each_line` without a block returns an enumerator even for a closed stream, as `IO` and the JRuby extension do. Co-Authored-By: Claude Opus 5.5 --- ext/stringio/stringio.c | 8 ++++---- test/stringio/test_stringio.rb | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index ab1de03..735485d 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -1769,7 +1769,7 @@ strio_getline(struct getline_arg *arg, struct StringIO *ptr) static VALUE strio_gets(int argc, VALUE *argv, VALUE self) { - struct StringIO *ptr = readable(self); + struct StringIO *ptr; struct getline_arg arg; VALUE str; @@ -2003,7 +2003,7 @@ static VALUE strio_each(int argc, VALUE *argv, VALUE self) { VALUE line; - struct StringIO *ptr = readable(self); + struct StringIO *ptr; struct getline_arg arg; RETURN_ENUMERATOR(self, argc, argv); @@ -2012,7 +2012,7 @@ strio_each(int argc, VALUE *argv, VALUE self) rb_raise(rb_eArgError, "invalid limit: 0 for each_line"); } - while (!NIL_P(line = strio_getline(&arg, StringIOForRead(self)))) { + while (!NIL_P(line = strio_getline(&arg, readable(self)))) { rb_yield(line); } return self; @@ -2030,7 +2030,7 @@ static VALUE strio_readlines(int argc, VALUE *argv, VALUE self) { VALUE ary, line; - struct StringIO *ptr = readable(self); + struct StringIO *ptr; struct getline_arg arg; if (prepare_getline_args(self, &ptr, &arg, argc, argv)->limit == 0) { diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index da0bea3..7c8f271 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1415,6 +1415,38 @@ def test_reopen_in_each_line_block assert_equal(["a\n", "x\n", "y\n"], lines) end + def test_reopen_to_unreadable_in_each_line_block + f = StringIO.new("a\nb\n") + g = StringIO.new("x\ny\n") + g.close_read + lines = [] + assert_raise(IOError) {f.each_line {|l| lines << l; f.reopen(g)}} + assert_equal(["a\n"], lines) + end + + def test_close_in_each_line_block + f = StringIO.new("a\nb\n") + lines = [] + assert_raise(IOError) {f.each_line {|l| lines << l; f.close}} + assert_equal(["a\n"], lines) + end + + def test_each_line_without_block_on_closed_stream + f = StringIO.new("a\nb\n") + f.close + assert_kind_of(Enumerator, f.each_line) + end + + def test_getline_methods_convert_arguments_before_readable_check + f = StringIO.new("a\nb\n") + f.close + c = Object.new + c.define_singleton_method(:to_str) {raise TypeError, "converted"} + assert_raise_with_message(TypeError, "converted") {f.gets(c)} + assert_raise_with_message(TypeError, "converted") {f.readlines(c)} + assert_raise_with_message(TypeError, "converted") {f.each_line(c) {}} + end + def test_reopen_during_argument_conversion_to_underlying_string ops = [ ->(f, c, g) {f.read(c, g.string)}, From 42c86525a3c2b623d3effc71cf1e2e91b8fb07a2 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 17:55:47 +0900 Subject: [PATCH 06/16] Fetch the underlying data after conversions and yields in more methods on JRuby `write` checked writability only before `to_s`. If `to_s` reopened the receiver onto a read-only stream, `write` wrote to that stream. Check writability again after the conversion, as the C extension does. `each_byte` and `each_codepoint` fetched the data only once before the loop. If the block reopened the receiver, they kept reading the old data. Fetch the data for each byte or codepoint, as `strio_to_read()` in the C extension does, and don't hold the lock while yielding. As a side effect, `each_byte` and `each_codepoint` no longer raise `NullPointerException` for a null device stream, and they read data appended in the block, as the C extension does. Co-Authored-By: Claude Fable 5.2 --- ext/java/org/jruby/ext/stringio/StringIO.java | 72 ++++++++++--------- test/stringio/test_stringio.rb | 25 +++++++ 2 files changed, 64 insertions(+), 33 deletions(-) diff --git a/ext/java/org/jruby/ext/stringio/StringIO.java b/ext/java/org/jruby/ext/stringio/StringIO.java index 12d7eba..2e0a8c0 100644 --- a/ext/java/org/jruby/ext/stringio/StringIO.java +++ b/ext/java/org/jruby/ext/stringio/StringIO.java @@ -633,23 +633,24 @@ public IRubyObject each_byte(ThreadContext context, Block block) { if (!block.isGiven()) return enumeratorize(runtime, this, "each_byte"); - checkReadable(); - StringIOData ptr = this.getPtrForWrite(); - if (ptr.string == null) return this; - - boolean locked = lock(context, ptr); - try { - ByteList bytes = ptr.string.getByteList(); + while (true) { + // Fetch the data for each byte, since the block may close or + // reopen this stream. + checkReadable(); + StringIOData ptr = this.getPtrForWrite(); + int c; - // Check the length every iteration, since - // the block can modify this string. - while (ptr.pos < bytes.length()) { - // check readability for each loop, since it could get closed - checkReadable(); - block.yield(context, runtime.newFixnum(bytes.get(ptr.pos++) & 0xFF)); + boolean locked = lock(context, ptr); + try { + if (ptr.string == null) break; + ByteList bytes = ptr.string.getByteList(); + if (ptr.pos >= bytes.length()) break; + c = bytes.get(ptr.pos++) & 0xFF; + } finally { + if (locked) unlock(ptr); } - } finally { - if (locked) unlock(ptr); + + block.yield(context, runtime.newFixnum(c)); } return this; @@ -1782,6 +1783,8 @@ private long stringIOWrite(ThreadContext context, Ruby runtime, IRubyObject arg) RubyString str = arg.asString(); int len, olen; + // The conversion above may reopen this stream. + checkWritable(); StringIOData ptr = this.getPtrForWrite(); boolean locked = lock(context, ptr); @@ -2006,32 +2009,35 @@ public IRubyObject each_codepoint(ThreadContext context, Block block) { if (!block.isGiven()) return enumeratorize(runtime, this, "each_codepoint"); checkReadable(); + final Encoding enc = getEncoding(); - StringIOData ptr = this.getPtrForWrite(); - if (ptr.string == null) return this; - - boolean locked = lock(context, ptr); - try { - final Encoding enc = getEncoding(); - RubyString myString = ptr.string; - final ByteList string = myString.getByteList(); - final byte[] stringBytes = string.getUnsafeBytes(); - int begin = string.getBegin(); - for (; ; ) { - // check readability for each loop, since it could get closed - checkReadable(); + while (true) { + // Fetch the data for each codepoint, since the block may close or + // reopen this stream. + checkReadable(); + StringIOData ptr = this.getPtrForWrite(); + int c; + boolean locked = lock(context, ptr); + try { + if (ptr.string == null) break; + final ByteList string = ptr.string.getByteList(); + final byte[] stringBytes = string.getUnsafeBytes(); + int begin = string.getBegin(); int pos = ptr.pos; - if (pos >= string.realSize()) return this; + if (pos >= string.realSize()) break; - int c = StringSupport.codePoint(runtime, enc, stringBytes, begin + pos, begin + string.realSize()); + c = StringSupport.codePoint(runtime, enc, stringBytes, begin + pos, begin + string.realSize()); int n = StringSupport.codeLength(enc, c); ptr.pos = pos + n; - block.yield(context, runtime.newFixnum(c)); + } finally { + if (locked) unlock(ptr); } - } finally { - if (locked) unlock(ptr); + + block.yield(context, runtime.newFixnum(c)); } + + return this; } public static class GenericReadable { diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 7c8f271..548b986 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1415,6 +1415,31 @@ def test_reopen_in_each_line_block assert_equal(["a\n", "x\n", "y\n"], lines) end + def test_reopen_to_unwritable_during_write_conversion + f = StringIO.new("hello".dup) + g = StringIO.new("world".dup, "r") + c = Object.new + c.define_singleton_method(:to_s) {f.reopen(g); "XY"} + assert_raise(IOError) {f.write(c)} + assert_equal("world", g.string) + end + + def test_reopen_in_each_byte_block + f = StringIO.new("ab") + g = StringIO.new("xy") + bytes = [] + f.each_byte {|b| bytes << b; f.reopen(g)} + assert_equal("axy".bytes, bytes) + end + + def test_reopen_in_each_codepoint_block + f = StringIO.new("ab") + g = StringIO.new("xy") + codepoints = [] + f.each_codepoint {|c| codepoints << c; f.reopen(g)} + assert_equal("axy".codepoints, codepoints) + end + def test_reopen_to_unreadable_in_each_line_block f = StringIO.new("a\nb\n") g = StringIO.new("x\ny\n") From 66376b9fcf9a4953900dd1e932929eae339288cf Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 17:58:54 +0900 Subject: [PATCH 07/16] Fetch the encoding for each codepoint in `StringIO#each_codepoint` `each_codepoint` fetched the encoding only once before the loop. If the block reopened the receiver onto a stream in another encoding, or changed the encoding by `set_encoding`, the rest of the data was read in the old encoding. Fetch the encoding for each codepoint, as `each_char` does. On JRuby, also pass the end of the string instead of the end of the backing array to `StringSupport.codePoint()`. It read bytes after the end of the string when the string shared its backing array and ended with a truncated character. Co-Authored-By: Claude Fable 5.2 --- ext/java/org/jruby/ext/stringio/StringIO.java | 4 +--- ext/stringio/stringio.c | 3 +-- test/stringio/test_stringio.rb | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/ext/java/org/jruby/ext/stringio/StringIO.java b/ext/java/org/jruby/ext/stringio/StringIO.java index 2e0a8c0..24e1cf1 100644 --- a/ext/java/org/jruby/ext/stringio/StringIO.java +++ b/ext/java/org/jruby/ext/stringio/StringIO.java @@ -2008,9 +2008,6 @@ public IRubyObject each_codepoint(ThreadContext context, Block block) { if (!block.isGiven()) return enumeratorize(runtime, this, "each_codepoint"); - checkReadable(); - final Encoding enc = getEncoding(); - while (true) { // Fetch the data for each codepoint, since the block may close or // reopen this stream. @@ -2027,6 +2024,7 @@ public IRubyObject each_codepoint(ThreadContext context, Block block) { int pos = ptr.pos; if (pos >= string.realSize()) break; + final Encoding enc = getEncoding(); c = StringSupport.codePoint(runtime, enc, stringBytes, begin + pos, begin + string.realSize()); int n = StringSupport.codeLength(enc, c); ptr.pos = pos + n; diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index 735485d..990b0f8 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -1438,9 +1438,8 @@ strio_each_codepoint(VALUE self) RETURN_ENUMERATOR(self, 0, 0); - ptr = readable(self); - enc = get_enc(ptr); while ((ptr = strio_to_read(self)) != NULL) { + enc = get_enc(ptr); c = rb_enc_codepoint_len(RSTRING_PTR(ptr->string)+ptr->pos, RSTRING_END(ptr->string), &n, enc); ptr->pos += n; diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 548b986..faabaf8 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1440,6 +1440,22 @@ def test_reopen_in_each_codepoint_block assert_equal("axy".codepoints, codepoints) end + def test_reopen_to_other_encoding_in_each_codepoint_block + f = StringIO.new("ab") + g = StringIO.new("xy".encode("UTF-16LE")) + codepoints = [] + f.each_codepoint {|c| codepoints << c; f.reopen(g)} + assert_equal("axy".codepoints, codepoints) + end + + def test_each_codepoint_truncated_char_in_shared_string + s = "aあzz" + f = StringIO.new(s.byteslice(0, 3)) + codepoints = [] + assert_raise(ArgumentError) {f.each_codepoint {|c| codepoints << c}} + assert_equal([0x61], codepoints) + end + def test_reopen_to_unreadable_in_each_line_block f = StringIO.new("a\nb\n") g = StringIO.new("x\ny\n") From 935a206cc6f8a0c6be9093047b6c851f64d0d092 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 18:09:10 +0900 Subject: [PATCH 08/16] Check frozen state after argument conversions in `StringIO#reopen` `strio_init()` fetched the data by `StringIOForRead()` after the argument conversions. It doesn't check whether the receiver is frozen, so `reopen` modified the receiver even if a conversion froze it. Use `StringIO()` instead, as other methods and the JRuby extension do. `strio_init()` is also used by `initialize`. So calling `initialize` again on a frozen `StringIO` now raises `FrozenError` instead of modifying it, as the JRuby extension does. Co-Authored-By: Claude Fable 5.2 --- ext/stringio/stringio.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index 990b0f8..007e214 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -416,7 +416,7 @@ strio_init(int argc, VALUE *argv, VALUE self) } /* The conversions above may freeze this stream. */ rb_check_frozen(self); - ptr = StringIOForRead(self); + ptr = StringIO(self); ptr->flags = fmode; if (!NIL_P(string) && readonly_string_p(string)) { From 48847a8aa9c850782da962bf0e81a2d60d850245 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 18:27:20 +0900 Subject: [PATCH 09/16] Fetch the underlying data after loading a transcoder or an encoding `rb_str_conv_enc()` and `rb_enc_find_index()` may load a transcoder or an encoding. Loading calls `to_path` of objects in `$LOAD_PATH`, which may reopen the stream. `write`, `ungetc` and `set_encoding_by_bom` kept using the pointer fetched before that. Fetch the pointer again after them. `set_encoding_by_bom()` detects the BOM again if the underlying string is changed. The fetched stream may be a null device stream, so check it: * `write` returns 0 for a null device stream. This also fixes a crash of `write` to a null device stream with an encoding, such as `StringIO.new(nil, external_encoding: "UTF-8")`, on both of the C extension and the JRuby extension. * `detect_bom()` accepts `nil`. This also fixes a crash of `set_encoding_by_bom` of a null device stream on both extensions. Co-Authored-By: Claude Fable 5.2 --- ext/java/org/jruby/ext/stringio/StringIO.java | 1 + ext/stringio/stringio.c | 31 +++++++--- test/stringio/test_stringio.rb | 56 ++++++++++++++++++- 3 files changed, 80 insertions(+), 8 deletions(-) diff --git a/ext/java/org/jruby/ext/stringio/StringIO.java b/ext/java/org/jruby/ext/stringio/StringIO.java index 24e1cf1..e68939e 100644 --- a/ext/java/org/jruby/ext/stringio/StringIO.java +++ b/ext/java/org/jruby/ext/stringio/StringIO.java @@ -1800,6 +1800,7 @@ private long stringIOWrite(ThreadContext context, Ruby runtime, IRubyObject arg) str = converted; encStr = str.getEncoding(); } + if (ptr.string == null) return 0; final ByteList strByteList = str.getByteList(); len = str.size(); if (len == 0) return 0; diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index 007e214..c0ec4e3 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -380,12 +380,22 @@ detect_bom(VALUE str, int *bomlen) return 0; } -static rb_encoding * -set_encoding_by_bom(struct StringIO *ptr) +static struct StringIO * +set_encoding_by_bom(VALUE self) { - int bomlen, idx = detect_bom(ptr->string, &bomlen); + struct StringIO *ptr; + VALUE string; + int bomlen, idx; rb_encoding *extenc = NULL; + /* Finding an encoding may load it, and that may call back into + * Ruby code. Detect again if the underlying string is changed. */ + do { + string = StringIO(self)->string; + idx = detect_bom(string, &bomlen); + ptr = StringIO(self); + } while (ptr->string != string); + if (idx) { extenc = rb_enc_from_index(idx); ptr->pos = bomlen; @@ -394,7 +404,7 @@ set_encoding_by_bom(struct StringIO *ptr) } } ptr->enc = extenc; - return extenc; + return ptr; } static VALUE @@ -441,7 +451,7 @@ strio_init(int argc, VALUE *argv, VALUE self) } ptr->pos = 0; ptr->lineno = 0; - if (ptr->flags & FMODE_SETENC_BY_BOM) set_encoding_by_bom(ptr); + if (ptr->flags & FMODE_SETENC_BY_BOM) ptr = set_encoding_by_bom(self); RB_FL_SET_RAW(self, (ptr->flags & FMODE_READWRITE) * (STRIO_READABLE / FMODE_READABLE)); return self; } @@ -1239,6 +1249,10 @@ strio_ungetc(VALUE self, VALUE c) enc2 = rb_enc_get(c); if (enc != enc2 && enc != rb_ascii8bit_encoding()) { c = rb_str_conv_enc(c, enc2, enc); + /* Loading a transcoder may call back into Ruby code. */ + ptr = readable(self); + check_modifiable(ptr); + if (NIL_P(ptr->string)) return Qnil; } strio_unget_string(ptr, c); return Qnil; @@ -2085,7 +2099,10 @@ strio_write(VALUE self, VALUE str) rb_enc_check(rb_enc_from_encoding(enc), str); } str = converted; + /* Loading a transcoder may call back into Ruby code. */ + ptr = writable(self); } + if (NIL_P(ptr->string)) return 0; len = RSTRING_LEN(str); if (len == 0) return 0; check_modifiable(ptr); @@ -2737,9 +2754,9 @@ strio_set_encoding(int argc, VALUE *argv, VALUE self) static VALUE strio_set_encoding_by_bom(VALUE self) { - struct StringIO *ptr = StringIO(self); + struct StringIO *ptr = set_encoding_by_bom(self); - if (!set_encoding_by_bom(ptr)) return Qnil; + if (!ptr->enc) return Qnil; return rb_enc_from_encoding(ptr->enc); } diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index faabaf8..abde953 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1415,6 +1415,60 @@ def test_reopen_in_each_line_block assert_equal(["a\n", "x\n", "y\n"], lines) end + # Loading a transcoder or an encoding calls #to_path of objects in + # $LOAD_PATH. This must run in a separate process because it's + # called only when they aren't loaded yet. + def assert_reopen_during_load(prepare, operate) + assert_separately(%w[-rstringio], "#{<<-"begin;"}\n#{<<-"end;"}") + begin; + f, g = #{prepare} + path = Object.new + path.define_singleton_method(:to_path) do + if f + f.reopen(g) + f = nil + GC.start + end + "/nonexistent" + end + $LOAD_PATH.unshift(path) + begin + stream = f + actual = #{operate} + ensure + $LOAD_PATH.delete(path) + end + f, = #{prepare} + stream = f + expected = #{operate} + assert_equal(expected, actual) + end; + end + + def test_reopen_during_transcoder_load_in_write + assert_reopen_during_load(<<-'PREPARE', <<-'OPERATE') + 2.times.map {StringIO.new("".encode("EUC-JP"))} + PREPARE + [stream.write("\u3042"), stream.string] + OPERATE + end + + def test_reopen_during_transcoder_load_in_ungetc + assert_reopen_during_load(<<-'PREPARE', <<-'OPERATE') + 2.times.map {StringIO.new("abc".encode("EUC-JP"))} + PREPARE + [stream.ungetc("\u3042"), stream.string] + OPERATE + end + + def test_reopen_during_encoding_load_in_set_encoding_by_bom + assert_reopen_during_load(<<-'PREPARE', <<-'OPERATE') + 2.times.map {StringIO.new("\xFE\xFFab".b)} + PREPARE + [stream.set_encoding_by_bom, stream.pos, stream.string.encoding] + OPERATE + end + def test_reopen_to_unwritable_during_write_conversion f = StringIO.new("hello".dup) g = StringIO.new("world".dup, "r") @@ -1449,7 +1503,7 @@ def test_reopen_to_other_encoding_in_each_codepoint_block end def test_each_codepoint_truncated_char_in_shared_string - s = "aあzz" + s = "a\u3042zz" f = StringIO.new(s.byteslice(0, 3)) codepoints = [] assert_raise(ArgumentError) {f.each_codepoint {|c| codepoints << c}} From 95799ff86d335eec43834039363eb43953a947e7 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 18:35:30 +0900 Subject: [PATCH 10/16] Verify that operations are applied to the reopened stream in tests `test_reopen_during_argument_conversion` only checked that the receiver shares the string with the reopened stream. It is true once the conversion reopens the receiver, whether the operation uses the stale data or not. So the test relied on a crash by use-after-free on CRuby, and it passed on JRuby without fetching the data again. Compare the result and the state of the stream with those of the same operation without reopening. Also add a test for `ungetbyte` with an `Integer`. It calls `Integer#&`, which may be redefined to reopen the stream. Co-Authored-By: Claude Fable 5.2 --- test/stringio/test_stringio.rb | 45 +++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index abde953..4deadb7 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1369,14 +1369,25 @@ def test_reopen_during_argument_conversion ->(f, c) {f.reopen("", c)}, ] ops.each do |op| + # Applies op to io. io is reopened to target during the + # argument conversion if target is given. + run = ->(io, target) do + c = Object.new + c.define_singleton_method(:to_int) {io.reopen(target) if target; 5} + c.define_singleton_method(:to_str) {io.reopen(target) if target; "r".dup} + c.define_singleton_method(:to_s) {io.reopen(target) if target; "r".dup} + result = op.call(io, c) + result = nil if result.equal?(io) or result.equal?(c) + [result, io.pos, io.lineno, io.string] + end + message = op.source_location.join(":") f = StringIO.new("hello\n" * 10) g = StringIO.new("world\n" * 10) - c = Object.new - c.define_singleton_method(:to_int) {f.reopen(g); 5} - c.define_singleton_method(:to_str) {f.reopen(g); "r".dup} - c.define_singleton_method(:to_s) {f.reopen(g); "r".dup} - op.call(f, c) - assert_same(g.string, f.string, op.source_location.join(":")) + actual = run.call(f, g) + assert_same(g.string, f.string, message) + # The operation must be applied to the reopened stream. + expected = run.call(StringIO.new("world\n" * 10), nil) + assert_equal(expected, actual, message) end f = StringIO.new("hello") @@ -1469,6 +1480,28 @@ def test_reopen_during_encoding_load_in_set_encoding_by_bom OPERATE end + def test_reopen_during_integer_and_in_ungetbyte + assert_separately(%w[-rstringio], "#{<<-"begin;"}\n#{<<-"end;"}") + begin; + f = StringIO.new("hello".dup) + g = StringIO.new("world".dup) + stream = f + Integer.class_eval do + alias_method :and_without_reopen, :& + define_method(:&) do |other| + if f + reopening, f = f, nil + reopening.reopen(g) + GC.start + end + and_without_reopen(other) + end + end + stream.ungetbyte(0x41) + assert_equal("A", stream.read(1)) + end; + end + def test_reopen_to_unwritable_during_write_conversion f = StringIO.new("hello".dup) g = StringIO.new("world".dup, "r") From b4f2bb6a51394f82ce5644f366aa46d3975515d5 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 18:43:33 +0900 Subject: [PATCH 11/16] Don't share mode parsing state between calls on JRuby `initialize`, `reopen` and `set_encoding` used thread-local holders to pass the mode to `EncodingUtils.extractModeEncoding()`. It converts the mode and the encoding options, which may call these methods again, for example by `StringIO.new` in `to_str`. The nested call overwrote and cleared the holders, and the outer call raised `NullPointerException`. Create the holders for each call instead. Co-Authored-By: Claude Fable 5.2 --- test/stringio/test_stringio.rb | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 4deadb7..4197a2e 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1300,9 +1300,20 @@ def test_set_string_via_dup_with_gc end def test_new_during_mode_conversion - mode = Object.new - mode.define_singleton_method(:to_str) {StringIO.new("", "a"); "r"} - assert_predicate(StringIO.new("".dup, mode), :closed_write?) + inner = nil + c = Object.new + c.define_singleton_method(:to_str) {inner = StringIO.new("inner".dup, "a"); "r"} + outer = StringIO.new("outer".dup, c) + assert_equal(["outer", false, true, "inner", true, false], + [outer.string, outer.closed_read?, outer.closed_write?, + inner.string, inner.closed_read?, inner.closed_write?]) + + f = StringIO.new("hello".dup) + c = Object.new + c.define_singleton_method(:to_str) {f.set_encoding("UTF-16LE"); "r"} + f.reopen("outer".dup, c) + assert_equal(["outer", false, true], + [f.string, f.closed_read?, f.closed_write?]) end def test_reopen_freeze_during_argument_conversion From 209ae7756a6cd10d6d9695686f2e9c77daa8724e Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Fri, 13 Nov 2026 18:43:33 +0900 Subject: [PATCH 12/16] Check the separator encoding after argument conversions on JRuby `Getline.getlineCall()` checks whether the encoding of the separator is compatible with the encoding of the stream. `gets`, `each_line` and `readlines` passed the encoding fetched before it converts the arguments. If a conversion reopened the receiver onto a stream in another encoding, they read the stream with an incompatible separator and returned strings split in the middle of a character. Do the same check as `prepare_getline_args()` in the C extension again in the callbacks, which are called after the conversions. Co-Authored-By: Claude Fable 5.2 --- ext/java/org/jruby/ext/stringio/StringIO.java | 27 +++++++++++++++++++ test/stringio/test_stringio.rb | 15 +++++++++++ 2 files changed, 42 insertions(+) diff --git a/ext/java/org/jruby/ext/stringio/StringIO.java b/ext/java/org/jruby/ext/stringio/StringIO.java index e68939e..54d8d27 100644 --- a/ext/java/org/jruby/ext/stringio/StringIO.java +++ b/ext/java/org/jruby/ext/stringio/StringIO.java @@ -819,8 +819,31 @@ public IRubyObject gets(ThreadContext context, IRubyObject[] args) { } } + // MRI: the encoding check in prepare_getline_args + // + // Getline.getlineCall does this with the encoding fetched before the + // argument conversions, which may reopen this stream. + private IRubyObject checkRSEncoding(ThreadContext context, IRubyObject rs) { + if (getPtrForRead().string == null || !(rs instanceof RubyString)) return rs; + + RubyString rsStr = (RubyString) rs; + Encoding encRs = rsStr.getEncoding(); + Encoding encIo = getEncoding(); + if (encRs != encIo && + (rsStr.scanForCodeRange() != StringSupport.CR_7BIT || + (rsStr.size() > 0 && !encIo.isAsciiCompatible()))) { + if (rs == context.runtime.getGlobalVariables().getDefaultSeparator()) { + rs = RubyString.newEmptyString(context.runtime, encIo).cat('\n', encIo); + } else { + throw context.runtime.newArgumentError("encoding mismatch: " + encIo + " IO with " + encRs + " RS"); + } + } + return rs; + } + private static final Getline.Callback GETLINE = (context, self, rs, limit, chomp, block) -> { self.checkReadable(); + rs = self.checkRSEncoding(context, rs); if (limit == 0) { if (self.getPtrForWrite().string == null) return context.nil; @@ -848,6 +871,8 @@ public IRubyObject gets(ThreadContext context, IRubyObject[] args) { throw context.runtime.newArgumentError("invalid limit: 0 for each_line"); } + rs = self.checkRSEncoding(context, rs); + if (rs.isNil()) chomp = false; while (!(line = self.getline(context, rs, limit, chomp)).isNil()) { @@ -871,6 +896,8 @@ public IRubyObject gets(ThreadContext context, IRubyObject[] args) { throw context.runtime.newArgumentError("invalid limit: 0 for readlines"); } + rs = self.checkRSEncoding(context, rs); + if (rs.isNil()) chomp = false; while (!(line = self.getline(context, rs, limit, chomp)).isNil()) { diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 4197a2e..e871e47 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1513,6 +1513,21 @@ def test_reopen_during_integer_and_in_ungetbyte end; end + def test_reopen_to_other_encoding_during_separator_conversion + ops = [ + ->(f, c) {f.gets(c)}, + ->(f, c) {f.readlines(c)}, + ->(f, c) {f.each_line(c) {}}, + ] + ops.each do |op| + f = StringIO.new("a\nb\n") + g = StringIO.new("x\ny\n".encode("UTF-16LE")) + c = Object.new + c.define_singleton_method(:to_str) {f.reopen(g); "\n"} + assert_raise(ArgumentError, op.source_location.join(":")) {op.call(f, c)} + end + end + def test_reopen_to_unwritable_during_write_conversion f = StringIO.new("hello".dup) g = StringIO.new("world".dup, "r") From 1541ce0d32fa391e1a483dc203becc06b5b3cb64 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Mon, 16 Nov 2026 16:27:33 +0900 Subject: [PATCH 13/16] Check frozen state in `StringIO#initialize_copy` `reopen(other)` checks whether the receiver is frozen before it converts the argument by `to_strio`, but `strio_copy()` didn't check it after the conversion. So it modified the receiver that the conversion froze. Calling `initialize_copy` directly also modified a frozen `StringIO`. Check it in `strio_copy()` after the conversion, in the same order as `Object#initialize_copy`. `dup` and `clone` aren't affected because the copy isn't frozen yet when `initialize_copy` is called. Co-Authored-By: Claude Fable 5.2 --- test/stringio/test_stringio.rb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index e871e47..abfcd94 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1345,6 +1345,7 @@ def test_initialize_copy_frozen f.freeze assert_raise(FrozenError) {f.send(:initialize_copy, StringIO.new("world"))} assert_equal("hello", f.string) + assert_same(f, f.send(:initialize_copy, f)) end def test_write_null_device_with_encoding @@ -1528,6 +1529,13 @@ def test_reopen_to_other_encoding_during_separator_conversion end end + def test_dup_and_clone_frozen + f = StringIO.new("hello") + f.freeze + assert_equal(["hello", false], [f.dup.string, f.dup.frozen?]) + assert_equal(["hello", true], [f.clone.string, f.clone.frozen?]) + end + def test_reopen_to_unwritable_during_write_conversion f = StringIO.new("hello".dup) g = StringIO.new("world".dup, "r") From bb1d1eab0f6bccaf94967bc38cd6bc8a35688629 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Mon, 16 Nov 2026 16:27:33 +0900 Subject: [PATCH 14/16] Add comments for fetching the underlying data again Fetching the underlying data twice looks redundant. Note that the second one is needed because the conversions between them may reopen the stream. Co-Authored-By: Claude Fable 5.2 --- ext/stringio/stringio.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index c0ec4e3..421d49b 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -942,6 +942,7 @@ strio_set_pos(VALUE self, VALUE pos) { struct StringIO *ptr = StringIO(self); rb_len_t p = NUM2LEN(pos); + /* The conversion above may reopen this stream. */ ptr = StringIO(self); if (p < 0) { error_inval(0); @@ -986,6 +987,7 @@ strio_seek(int argc, VALUE *argv, VALUE self) rb_scan_args(argc, argv, "11", NULL, &whence); amount = NUM2LEN(argv[0]); w = NIL_P(whence) ? 0 : NUM2LONG(whence); + /* The conversions above may reopen this stream. */ ptr = StringIO(self); if (CLOSED(self)) { rb_raise(rb_eIOError, "closed stream"); @@ -1241,6 +1243,7 @@ strio_ungetc(VALUE self, VALUE c) } else { StringValue(c); + /* The conversion above may reopen this stream. */ ptr = readable(self); check_modifiable(ptr); if (NIL_P(ptr->string)) return Qnil; @@ -1283,6 +1286,7 @@ strio_ungetbyte(VALUE self, VALUE c) else { StringValue(c); } + /* The conversions above may reopen this stream. */ ptr = readable(self); check_modifiable(ptr); if (NIL_P(ptr->string)) return Qnil; @@ -2089,6 +2093,7 @@ strio_write(VALUE self, VALUE str) if (!RB_TYPE_P(str, T_STRING)) str = rb_obj_as_string(str); + /* The conversion above may reopen this stream. */ ptr = writable(self); if (NIL_P(ptr->string)) return 0; enc = get_enc(ptr); @@ -2254,6 +2259,7 @@ strio_putc(VALUE self, VALUE ch) } else { char c = NUM2CHR(ch); + /* The conversion above may reopen this stream. */ ptr = writable(self); if (NIL_P(ptr->string)) return ch; str = rb_str_new(&c, 1); @@ -2377,6 +2383,7 @@ strio_read(int argc, VALUE *argv, VALUE self) if (len < 0) { rb_raise(rb_eArgError, "negative length %"PRIdLEN" given", len); } + /* The conversions above may reopen this stream. */ ptr = readable(self); str = strio_readbuf(self, str); if (eos_p(ptr)) { @@ -2392,6 +2399,7 @@ strio_read(int argc, VALUE *argv, VALUE self) } /* fall through */ case 0: + /* The conversions above may reopen this stream. */ ptr = readable(self); if (NIL_P(ptr->string)) return Qnil; len = RSTRING_LEN(ptr->string); @@ -2519,6 +2527,7 @@ strio_pread(int argc, VALUE *argv, VALUE self) } rb_buf = strio_readbuf(self, rb_buf); + /* The conversions above may reopen this stream. */ ptr = readable(self); if (len == 0) { @@ -2650,6 +2659,7 @@ strio_truncate(VALUE self, VALUE len) VALUE string = writable(self)->string; rb_len_t l = NUM2LEN(len); rb_len_t plen; + /* The conversion above may reopen this stream. */ string = writable(self)->string; if (l < 0) { error_inval("negative length"); @@ -2733,6 +2743,7 @@ strio_set_encoding(int argc, VALUE *argv, VALUE self) enc = convconfig.enc2; } } + /* The conversions above may reopen this stream. */ ptr = StringIO(self); ptr->enc = enc; if (!NIL_P(ptr->string) && WRITABLE(self) && !str_chilled_p(ptr->string)) { From f96baa9fea3894834a90446c1e97e21e7f0dbc75 Mon Sep 17 00:00:00 2001 From: Sutou Kouhei Date: Mon, 16 Nov 2026 17:09:03 +0900 Subject: [PATCH 15/16] Omit tests that use `assert_separately` on JRuby They are for behavior that JRuby doesn't have: JRuby doesn't load transcoders and encodings by `require`, and `ungetbyte` doesn't call `Integer#&` there. `assert_separately` also doesn't work well with JRuby on CI. It raised `NoMethodError` in `EnvUtil` on Windows, and it may time out because starting JRuby is slow. Co-Authored-By: Claude Fable 5.2 --- test/stringio/test_stringio.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index abfcd94..6c86489 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1442,6 +1442,7 @@ def test_reopen_in_each_line_block # $LOAD_PATH. This must run in a separate process because it's # called only when they aren't loaded yet. def assert_reopen_during_load(prepare, operate) + omit "JRuby doesn't load transcoders and encodings" if RUBY_ENGINE == "jruby" assert_separately(%w[-rstringio], "#{<<-"begin;"}\n#{<<-"end;"}") begin; f, g = #{prepare} @@ -1493,6 +1494,7 @@ def test_reopen_during_encoding_load_in_set_encoding_by_bom end def test_reopen_during_integer_and_in_ungetbyte + omit "JRuby doesn't call Integer#&" if RUBY_ENGINE == "jruby" assert_separately(%w[-rstringio], "#{<<-"begin;"}\n#{<<-"end;"}") begin; f = StringIO.new("hello".dup) From 6fe28c3400c67018b85ad951063ec606b437f6ec Mon Sep 17 00:00:00 2001 From: Yusuke Endoh Date: Fri, 27 Nov 2026 13:26:03 +0900 Subject: [PATCH 16/16] Check the separator encoding after a reopen in StringIO#each_line If the block reopens the stream onto one in another encoding, the separator built for the old stream split the characters of the new one. Co-Authored-By: Claude Opus 5.5 --- ext/java/org/jruby/ext/stringio/StringIO.java | 3 ++ ext/stringio/stringio.c | 51 +++++++++++-------- test/stringio/test_stringio.rb | 8 +++ 3 files changed, 42 insertions(+), 20 deletions(-) diff --git a/ext/java/org/jruby/ext/stringio/StringIO.java b/ext/java/org/jruby/ext/stringio/StringIO.java index 54d8d27..720627d 100644 --- a/ext/java/org/jruby/ext/stringio/StringIO.java +++ b/ext/java/org/jruby/ext/stringio/StringIO.java @@ -871,12 +871,15 @@ private IRubyObject checkRSEncoding(ThreadContext context, IRubyObject rs) { throw context.runtime.newArgumentError("invalid limit: 0 for each_line"); } + IRubyObject origRs = rs; rs = self.checkRSEncoding(context, rs); if (rs.isNil()) chomp = false; while (!(line = self.getline(context, rs, limit, chomp)).isNil()) { + StringIOData prev = self.getPtrForRead(); block.yieldSpecific(context, line); + if (self.getPtrForRead() != prev) rs = self.checkRSEncoding(context, origRs); } return self; diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c index 421d49b..3ad8c35 100644 --- a/ext/stringio/stringio.c +++ b/ext/stringio/stringio.c @@ -1501,10 +1501,35 @@ bm_search(const char *little, rb_len_t llen, const char *big, rb_len_t blen, con struct getline_arg { VALUE rs; + VALUE orig_rs; rb_len_t limit; unsigned int chomp: 1; }; +static VALUE +getline_rs(struct StringIO *ptr, VALUE rs) +{ + if (!NIL_P(ptr->string) && !NIL_P(rs)) { + rb_encoding *enc_rs, *enc_io; + enc_rs = rb_enc_get(rs); + enc_io = get_enc(ptr); + if (enc_rs != enc_io && + (rb_enc_str_coderange(rs) != ENC_CODERANGE_7BIT || + (RSTRING_LEN(rs) > 0 && !rb_enc_asciicompat(enc_io)))) { + if (rs == rb_rs) { + rs = rb_enc_str_new(0, 0, enc_io); + rb_str_buf_cat_ascii(rs, "\n"); + } + else { + rb_raise(rb_eArgError, "encoding mismatch: %s IO with %s RS", + rb_enc_name(enc_io), + rb_enc_name(enc_rs)); + } + } + } + return rs; +} + static struct getline_arg * prepare_getline_args(VALUE self, struct StringIO **ptrp, struct getline_arg *arg, int argc, VALUE *argv) { @@ -1539,25 +1564,8 @@ prepare_getline_args(VALUE self, struct StringIO **ptrp, struct getline_arg *arg break; } *ptrp = ptr = readable(self); - if (!NIL_P(ptr->string) && !NIL_P(rs)) { - rb_encoding *enc_rs, *enc_io; - enc_rs = rb_enc_get(rs); - enc_io = get_enc(ptr); - if (enc_rs != enc_io && - (rb_enc_str_coderange(rs) != ENC_CODERANGE_7BIT || - (RSTRING_LEN(rs) > 0 && !rb_enc_asciicompat(enc_io)))) { - if (rs == rb_rs) { - rs = rb_enc_str_new(0, 0, enc_io); - rb_str_buf_cat_ascii(rs, "\n"); - } - else { - rb_raise(rb_eArgError, "encoding mismatch: %s IO with %s RS", - rb_enc_name(enc_io), - rb_enc_name(enc_rs)); - } - } - } - arg->rs = rs; + arg->orig_rs = rs; + arg->rs = getline_rs(ptr, rs); arg->limit = limit; arg->chomp = 0; if (!NIL_P(opts)) { @@ -2029,8 +2037,11 @@ strio_each(int argc, VALUE *argv, VALUE self) rb_raise(rb_eArgError, "invalid limit: 0 for each_line"); } - while (!NIL_P(line = strio_getline(&arg, readable(self)))) { + while (!NIL_P(line = strio_getline(&arg, ptr))) { + struct StringIO *prev = ptr; rb_yield(line); + ptr = readable(self); + if (ptr != prev) arg.rs = getline_rs(ptr, arg.orig_rs); } return self; } diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb index 6c86489..57702ab 100644 --- a/test/stringio/test_stringio.rb +++ b/test/stringio/test_stringio.rb @@ -1611,6 +1611,14 @@ def test_getline_methods_convert_arguments_before_readable_check assert_raise_with_message(TypeError, "converted") {f.each_line(c) {}} end + def test_reopen_to_other_encoding_in_each_line_block + f = StringIO.new("a\nb\n") + g = StringIO.new("x\ny\n".encode("UTF-16LE")) + lines = [] + f.each_line {|l| lines << l; f.reopen(g) if lines.size == 1} + assert_equal(["a\n", "x\n".encode("UTF-16LE"), "y\n".encode("UTF-16LE")], lines) + end + def test_reopen_during_argument_conversion_to_underlying_string ops = [ ->(f, c, g) {f.read(c, g.string)},