diff options
author | Peter Zhu <peter@peterzhu.ca> | 2023-09-05 13:34:46 -0400 |
---|---|---|
committer | Peter Zhu <peter@peterzhu.ca> | 2023-09-05 14:32:15 -0400 |
commit | 9a8398a18f364d3bcfc8d2744162d3572d9491e4 (patch) | |
tree | 4d9202dffe750a9c9377f18755e33d3556ab3246 /gc.c | |
parent | 06a1d16dc2108c54090a0fca8b356f39ef353a99 (diff) |
Introduce rb_gc_remove_weak
If we're during incremental marking, then Ruby code can execute that
deallocates certain memory buffers that have been called with
rb_gc_mark_weak, which can cause use-after-free bugs.
Notes
Notes:
Merged: https://github.com/ruby/ruby/pull/8375
Diffstat (limited to 'gc.c')
-rw-r--r-- | gc.c | 23 |
1 files changed, 23 insertions, 0 deletions
@@ -6924,6 +6924,27 @@ rb_gc_mark_weak(VALUE *ptr) objspace->profile.weak_references_count++; } +void +rb_gc_remove_weak(VALUE parent_obj, VALUE *ptr) +{ + rb_objspace_t *objspace = &rb_objspace; + + /* If we're not incremental marking, then the state of the objects can't + * change so we don't need to do anything. */ + if (!is_incremental_marking(objspace)) return; + /* If parent_obj has not been marked, then ptr has not yet been marked + * weak, so we don't need to do anything. */ + if (!RVALUE_MARKED(parent_obj)) return; + + VALUE **ptr_ptr; + rb_darray_foreach(objspace->weak_references, i, ptr_ptr) { + if (*ptr_ptr == ptr) { + *ptr_ptr = NULL; + break; + } + } +} + /* CAUTION: THIS FUNCTION ENABLE *ONLY BEFORE* SWEEPING. * This function is only for GC_END_MARK timing. */ @@ -8151,6 +8172,8 @@ gc_update_weak_references(rb_objspace_t *objspace) size_t retained_weak_references_count = 0; VALUE **ptr_ptr; rb_darray_foreach(objspace->weak_references, i, ptr_ptr) { + if (!ptr_ptr) continue; + VALUE obj = **ptr_ptr; if (RB_SPECIAL_CONST_P(obj)) continue; |