Skip to content

Commit

Permalink
Raise ArgumentError if IO.read is provided negative offset
Browse files Browse the repository at this point in the history
Fixes [Bug #19380]
  • Loading branch information
jeremyevans committed Mar 24, 2023
1 parent 836e9a1 commit 6c60006
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
4 changes: 4 additions & 0 deletions io.c
Expand Up @@ -12125,9 +12125,13 @@ static VALUE
rb_io_s_read(int argc, VALUE *argv, VALUE io)
{
VALUE opt, offset;
long off;
struct foreach_arg arg;

argc = rb_scan_args(argc, argv, "13:", NULL, NULL, &offset, NULL, &opt);
if (!NIL_P(offset) && (off = NUM2LONG(offset)) < 0) {
rb_raise(rb_eArgError, "negative offset %ld given", off);
}
open_key_args(io, argc, argv, opt, &arg);
if (NIL_P(arg.io)) return Qnil;
if (!NIL_P(offset)) {
Expand Down
15 changes: 12 additions & 3 deletions spec/ruby/core/io/read_spec.rb
Expand Up @@ -128,9 +128,18 @@
-> { IO.read @fname, -1 }.should raise_error(ArgumentError)
end

it "raises an Errno::EINVAL when not passed a valid offset" do
-> { IO.read @fname, 0, -1 }.should raise_error(Errno::EINVAL)
-> { IO.read @fname, -1, -1 }.should raise_error(Errno::EINVAL)
ruby_version_is ''...'3.3' do
it "raises an Errno::EINVAL when not passed a valid offset" do
-> { IO.read @fname, 0, -1 }.should raise_error(Errno::EINVAL)
-> { IO.read @fname, -1, -1 }.should raise_error(Errno::EINVAL)
end
end

ruby_version_is '3.3' do
it "raises an ArgumentError when not passed a valid offset" do
-> { IO.read @fname, 0, -1 }.should raise_error(ArgumentError)
-> { IO.read @fname, -1, -1 }.should raise_error(ArgumentError)
end
end

it "uses the external encoding specified via the :external_encoding option" do
Expand Down
3 changes: 3 additions & 0 deletions test/ruby/test_io.rb
Expand Up @@ -2866,6 +2866,9 @@ def test_s_read
assert_equal("foo\nbar\nbaz\n", File.read(t.path))
assert_equal("foo\nba", File.read(t.path, 6))
assert_equal("bar\n", File.read(t.path, 4, 4))

assert_raise(ArgumentError) { File.read(t.path, -1) }
assert_raise(ArgumentError) { File.read(t.path, 1, -1) }
}
end

Expand Down

0 comments on commit 6c60006

Please sign in to comment.