Skip to content

Commit 8befacf

Browse files
Guard against oob read in rb_ary_aref1
When the array is shrunk during rb_arithmetic_sequence_beg_len_step, ary_subseq_len returns -1. Return an empty array instead of passing the negative length to ary_make_partial or ary_make_partial_step. [Bug #22325]
1 parent 09a5f2e commit 8befacf

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

‎array.c‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1943,7 +1943,7 @@ rb_ary_aref1(VALUE ary, VALUE arg)
19431943
default:
19441944
if (step == 0) rb_raise(rb_eArgError, "slice step cannot be zero");
19451945
len = ary_subseq_len(ary, beg, len);
1946-
if (len == 0) return ary_new(klass, 0);
1946+
if (len <= 0) return ary_new(klass, 0);
19471947
if (step == 1) return ary_make_partial(ary, klass, beg, len);
19481948
return ary_make_partial_step(ary, klass, beg, len, step);
19491949
}

‎test/ruby/test_array.rb‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1833,6 +1833,33 @@ def test_slice_out_of_range
18331833
assert_equal([100], a.slice(-1, 1_000_000_000))
18341834
end
18351835

1836+
def test_slice_shrinking_array_by_to_int
1837+
bug22325 = '[Bug #22325]'
1838+
cls = Class.new(Numeric) do
1839+
attr_reader :val
1840+
def initialize(ary, val)
1841+
@ary = ary
1842+
@val = val
1843+
end
1844+
def <=>(other)
1845+
val <=> (other.is_a?(self.class) ? other.val : other)
1846+
end
1847+
def to_int
1848+
@ary.clear
1849+
val
1850+
end
1851+
def coerce(other)
1852+
[other, val]
1853+
end
1854+
end
1855+
1856+
ary = @cls[*(1..100).to_a]
1857+
assert_equal([], ary[Range.new(cls.new(ary, 50), cls.new(ary, 60))], bug22325)
1858+
1859+
ary.replace((1..100).to_a)
1860+
assert_equal([], ary[Range.new(cls.new(ary, 50), cls.new(ary, 60)).step(2)], bug22325)
1861+
end
1862+
18361863
def test_slice_gc_compact_stress
18371864
EnvUtil.under_gc_compact_stress { assert_equal([1, 2, 3, 4, 5], (0..10).to_a[1, 5]) }
18381865
EnvUtil.under_gc_compact_stress do

0 commit comments

Comments
 (0)