Bug #22716
closedARGF uses a non-IO $stdin as an IO when ARGV contains "-"
Description
$stdin can be any object, and ARGF reads through it when it is not an IO. When ARGV contains "-", however, argf_next_argv() sets the current file to $stdin and then uses it as an IO (rb_io_ascii8bit_binmode(), GetOpenFile(), writes to fptr->encs) without checking its type:
Expected: ["x\n"], as without -.
Actual on master and 4.0.10: -e:1:in 'ARGF.class#readlines': uninitialized stream (IOError).
Actual on 3.4.13: closed stream (IOError), or a segmentation fault in some runs.
Other $stdin objects, such as objects with instance variables or delegators like Tempfile, crash instead of raising, because their memory is read and written as an rb_io_t. For example, on master and 4.0.10:
# ruby poc.rb -
buf = "\0".b * 200
o = Object.new
o.instance_variable_set(:@buf, buf)
def o.binmode = self
def o.gets(*) = nil
$stdin = o
ARGF.binmode
p buf.bytesize #=> 17179869384, expected 200
ARGF.set_encoding has the same problem after forwarding to a non-IO $stdin, with or without -.
Reproduced on 3.2.11, 3.3.14, 3.4.13, 4.0.10 and master.
A patch with tests: https://github.com/ruby/ruby/pull/20477