diff options
author | Alan Wu <XrXr@users.noreply.github.com> | 2022-05-05 16:08:24 -0400 |
---|---|---|
committer | Alan Wu <XrXr@users.noreply.github.com> | 2022-05-05 17:37:07 -0400 |
commit | 7448afccb32f78115c05af03421984aa2f2aaf58 (patch) | |
tree | 929ee02d2bfe7adc7b0ccbea58a5192d6113d9b8 /class.c | |
parent | 4acafdf6328cf7ae2b61faa1e309a63a598a7029 (diff) | |
download | ruby-7448afccb32f78115c05af03421984aa2f2aaf58.tar.gz |
Fix potential GC issue while iterating over weak refs
While walking over the list of subclasses for `include` and friends, we
check whether the subclass is a garbage object. After the check, we
allocate objects which might trigger GC and make the subclass garbage,
even though before the allocation the subclass was not garbage. This is
a sort of time-of-check-time-of-use issue.
Fix this by saving the weak reference to a local variable, upgrading it
to a strong reference while we do the allocation. It makes the code look
slightly nicer even if it doesn't fix any runtime issues.
Diffstat (limited to 'class.c')
-rw-r--r-- | class.c | 17 |
1 files changed, 9 insertions, 8 deletions
@@ -1383,17 +1383,18 @@ rb_prepend_module(VALUE klass, VALUE module) /* During lazy sweeping, iclass->klass could be a dead object that * has not yet been swept. */ if (!rb_objspace_garbage_object_p(iclass->klass)) { - if (klass_had_no_origin && klass_origin_m_tbl == RCLASS_M_TBL(iclass->klass)) { + const VALUE subclass = iclass->klass; + if (klass_had_no_origin && klass_origin_m_tbl == RCLASS_M_TBL(subclass)) { // backfill an origin iclass to handle refinements and future prepends - rb_id_table_foreach(RCLASS_M_TBL(iclass->klass), clear_module_cache_i, (void *)iclass->klass); - RCLASS_M_TBL(iclass->klass) = klass_m_tbl; - VALUE origin = rb_include_class_new(klass_origin, RCLASS_SUPER(iclass->klass)); - RCLASS_SET_SUPER(iclass->klass, origin); - RCLASS_SET_INCLUDER(origin, RCLASS_INCLUDER(iclass->klass)); - RCLASS_SET_ORIGIN(iclass->klass, origin); + rb_id_table_foreach(RCLASS_M_TBL(subclass), clear_module_cache_i, (void *)subclass); + RCLASS_M_TBL(subclass) = klass_m_tbl; + VALUE origin = rb_include_class_new(klass_origin, RCLASS_SUPER(subclass)); + RCLASS_SET_SUPER(subclass, origin); + RCLASS_SET_INCLUDER(origin, RCLASS_INCLUDER(subclass)); + RCLASS_SET_ORIGIN(subclass, origin); RICLASS_SET_ORIGIN_SHARED_MTBL(origin); } - include_modules_at(iclass->klass, iclass->klass, module, FALSE); + include_modules_at(subclass, subclass, module, FALSE); } iclass = iclass->next; |