Actions
Bug #18138
closedArray#slice! invalid memory access
Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.1.0dev (2021-08-28T14:40:37Z master 808ce96494) [x86_64-linux]
Description
As of 4f24255, the array.c functions rb_ary_slice_bang / ary_slice_bang_by_rb_ary_splice allow a length to be passed to rb_ary_new4 that is too long and which leads to an invalid memory access.
This bug is present in Ruby v3_0_0, v3_0_1, and v3_0_2.
Reproduction¶
This ruby snippet will reproduce valgrind memory warnings:
(1..5000).to_a.slice!(-2, 5000)
The valgrind memory warnings on master
look like:
==228628== Invalid read of size 8
==228628== at 0x48428C0: memmove (vg_replace_strmem.c:1271)
==228628== by 0x356542: ary_memcpy (array.c:316)
==228628== by 0x356542: rb_ary_tmp_new_from_values (array.c:785)
==228628== by 0x356542: rb_ary_new_from_values (array.c:795)
==228628== by 0x356542: ary_slice_bang_by_rb_ary_splice (array.c:4106)
==228628== by 0x35E1DB: rb_ary_slice_bang (array.c:4186)
Fix¶
The fix I'm suggesting is in pull request https://github.com/ruby/ruby/pull/4787
Saving you a click:
diff --git a/array.c b/array.c
index bd323cd..edac216 100644
--- a/array.c
+++ b/array.c
@@ -4096,7 +4096,7 @@ ary_slice_bang_by_rb_ary_splice(VALUE ary, long pos, long len)
else if (orig_len < pos) {
return Qnil;
}
- else if (orig_len < pos + len) {
+ if (orig_len < pos + len) {
len = orig_len - pos;
}
if (len == 0) {
Actions
Like0
Like0Like0Like0