Skip to content

Commit

Permalink
Disable GC during RUBY_INTERNAL_EVENT_NEWOBJ
Browse files Browse the repository at this point in the history
We must disable GC when running RUBY_INTERNAL_EVENT_NEWOBJ hooks because
the callback could call xmalloc which could potentially trigger a GC,
and a lot of code is unsafe to trigger a GC right after an object has
been allocated because they perform initialization for the object and
assume that the GC does not trigger before then.
  • Loading branch information
peterzhu2118 committed Dec 23, 2024
1 parent 4e12c25 commit f4476f0
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion gc.c
Original file line number Diff line number Diff line change
Expand Up @@ -1031,7 +1031,16 @@ newobj_of(rb_ractor_t *cr, VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v
{
memset((char *)obj + RVALUE_SIZE, 0, rb_gc_obj_slot_size(obj) - RVALUE_SIZE);

rb_gc_event_hook(obj, RUBY_INTERNAL_EVENT_NEWOBJ);
/* We must disable GC here because the callback could call xmalloc
* which could potentially trigger a GC, and a lot of code is unsafe
* to trigger a GC right after an object has been allocated because
* they perform initialization for the object and assume that the
* GC does not trigger before then. */
bool gc_disabled = RTEST(rb_gc_disable_no_rest());
{
rb_gc_event_hook(obj, RUBY_INTERNAL_EVENT_NEWOBJ);
}
if (!gc_disabled) rb_gc_enable();
}
RB_VM_LOCK_LEAVE_CR_LEV(cr, &lev);
}
Expand Down

0 comments on commit f4476f0

Please sign in to comment.