Skip to content

Commit f4476f0

Browse files
committed
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.
1 parent 4e12c25 commit f4476f0

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

gc.c

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1031,7 +1031,16 @@ newobj_of(rb_ractor_t *cr, VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v
10311031
{
10321032
memset((char *)obj + RVALUE_SIZE, 0, rb_gc_obj_slot_size(obj) - RVALUE_SIZE);
10331033

1034-
rb_gc_event_hook(obj, RUBY_INTERNAL_EVENT_NEWOBJ);
1034+
/* We must disable GC here because the callback could call xmalloc
1035+
* which could potentially trigger a GC, and a lot of code is unsafe
1036+
* to trigger a GC right after an object has been allocated because
1037+
* they perform initialization for the object and assume that the
1038+
* GC does not trigger before then. */
1039+
bool gc_disabled = RTEST(rb_gc_disable_no_rest());
1040+
{
1041+
rb_gc_event_hook(obj, RUBY_INTERNAL_EVENT_NEWOBJ);
1042+
}
1043+
if (!gc_disabled) rb_gc_enable();
10351044
}
10361045
RB_VM_LOCK_LEAVE_CR_LEV(cr, &lev);
10371046
}

0 commit comments

Comments
 (0)