Skip to content

Commit

Permalink
[Bug #19748] Fix out-of-bound access in String#byteindex
Browse files Browse the repository at this point in the history
  • Loading branch information
nobu committed Jun 28, 2023
1 parent 715c5ca commit bc3ac18
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
17 changes: 7 additions & 10 deletions string.c
Expand Up @@ -3970,31 +3970,28 @@ rb_str_byteindex_m(int argc, VALUE *argv, VALUE str)
long pos;

if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
long slen = RSTRING_LEN(str);
pos = NUM2LONG(initpos);
}
else {
pos = 0;
}
if (pos < 0) {
pos += RSTRING_LEN(str);
if (pos < 0) {
pos += slen;
}
if (pos < 0 || pos > slen) {
if (RB_TYPE_P(sub, T_REGEXP)) {
rb_backref_set(Qnil);
}
return Qnil;
}
}
else {
pos = 0;
}

if (!str_check_byte_pos(str, pos)) {
rb_raise(rb_eIndexError,
"offset %ld does not land on character boundary", pos);
}

if (RB_TYPE_P(sub, T_REGEXP)) {
if (pos > RSTRING_LEN(str)) {
rb_backref_set(Qnil);
return Qnil;
}
if (rb_reg_search(sub, str, pos, 0) < 0) {
return Qnil;
}
Expand Down
3 changes: 3 additions & 0 deletions test/ruby/test_string.rb
Expand Up @@ -3397,6 +3397,9 @@ def o.to_str; "bar"; end
assert_byteindex(6, S("にんにちは"), S("に"), 6)
assert_byteindex(6, S("にんにちは"), /に./, 6)
assert_raise(IndexError) { S("にんにちは").byteindex(?に, 7) }

s = S("foobarbarbaz")
assert !1000.times.any? {s.byteindex("", 100_000_000)}
end

def test_byterindex
Expand Down

0 comments on commit bc3ac18

Please sign in to comment.