Project

General

Profile

Actions

Bug #22716

closed

ARGF uses a non-IO $stdin as an IO when ARGV contains "-"

Bug #22716: ARGF uses a non-IO $stdin as an IO when ARGV contains "-"

Added by saddestmartian (sad mart) 1 day ago. Updated about 4 hours ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 4.1.0dev (2026-12-03T23:00:19Z master bcd243e8e8) +PRISM [x86_64-linux]
[ruby-core:127844]

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:

$ ruby -rstringio -e '$stdin = StringIO.new("x\n"); p readlines' -

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

Updated by nobu (Nobuyoshi Nakada) about 4 hours ago Actions #1 [ruby-core:127891]

  • Status changed from Open to Closed
Actions

Also available in: PDF Atom