mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
array.c: fix heap-use-after-free in insertion_sort
The key variable in insertion_sort temporarily holds an array element that's been removed from its slot during the sorting process. When sort_cmp yields to a block that triggers GC, key wasn't protected and could be collected. Use arena save/restore around the loop to avoid arena overflow for large arrays. Test case from oss-fuzz: sort! with block containing rescue. Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -2172,16 +2172,21 @@ heapify(mrb_state *mrb, mrb_value ary, mrb_value *a, mrb_int index, mrb_int size
|
||||
static void
|
||||
insertion_sort(mrb_state *mrb, mrb_value ary, mrb_value *a, mrb_int size, mrb_value blk)
|
||||
{
|
||||
int ai = mrb_gc_arena_save(mrb);
|
||||
for (mrb_int i = 1; i < size; i++) {
|
||||
mrb_value key = a[i];
|
||||
mrb_int j = i - 1;
|
||||
|
||||
/* Protect key from GC - it's temporarily out of the array during sort */
|
||||
mrb_gc_protect(mrb, key);
|
||||
|
||||
/* Move elements that are greater than key to one position ahead */
|
||||
while (j >= 0 && sort_cmp(mrb, ary, a[j], key, blk)) {
|
||||
a[j + 1] = a[j];
|
||||
j--;
|
||||
}
|
||||
a[j + 1] = key;
|
||||
mrb_gc_arena_restore(mrb, ai);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user