Disable GC during RUBY_INTERNAL_EVENT_NEWOBJ

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.
This commit is contained in:
Peter Zhu 2024-12-20 16:48:48 -05:00
parent 4e12c25778
commit f4476f0d07
Notes: git 2024-12-23 14:03:49 +00:00

9
gc.c
View File

@ -1031,8 +1031,17 @@ 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); memset((char *)obj + RVALUE_SIZE, 0, rb_gc_obj_slot_size(obj) - RVALUE_SIZE);
/* 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); rb_gc_event_hook(obj, RUBY_INTERNAL_EVENT_NEWOBJ);
} }
if (!gc_disabled) rb_gc_enable();
}
RB_VM_LOCK_LEAVE_CR_LEV(cr, &lev); RB_VM_LOCK_LEAVE_CR_LEV(cr, &lev);
} }