Commit 3e8f5d8e

3e8f5d8ea459Merged

Sam Ruby <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified

Description

Root the poly each-loop receiver temp across the loop body

The runtime-dispatch (poly) each codegen stored the iterated collection in a bare sp_RbVal temp without rooting it:

sp_RbVal _t = <receiver>;          // e.g. @article.comments
for (...) { ... sp_PtrArray_get((sp_PtrArray *)_t.v.p, i) ... }

When the receiver is a freshly built heap collection referenced only by this temp (the common @article.comments shape -- a new PtrArray of records) and the loop body allocates (string append, nested render, box helpers), a GC firing mid-iteration collects the unrooted array. The next sp_PtrArray_get then reads a freed slot, surfacing as a SIGSEGV in sp_obj_cls_id_of on a garbage pointer -- intermittently, under concurrent load, once the freed block is reused.

The concrete-typed each paths are unaffected: their collection is a directly-rooted local/param (e.g. render @articles roots lv_articles). Only the poly receiver path missed the root.

Fix: root the temp right after its declaration. SP_GC_ROOT_RBVAL is cleanup-attributed, so it pops at the end of the temp's C scope, which is exactly the loop's extent. Rooting a non-heap RbVal is harmless.

Test: poly each over a fresh array with GC.start in the body. Pre-fix the unrooted array is freed after the first element, so the remaining elements read freed slots and the output diverges (or crashes under load); post-fix it matches the CRuby reference. Suite 704 pass / 0 fail.

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
3e8f5d8ea459
Parent
f6a6d35cbbd0

spinel_codegen.rbmodifiedView file

@@ -41992,6 +41992,16 @@
4199241992 idx_tmp = new_temp
4199341993 val_tmp = new_temp
4199441994 emit(" sp_RbVal " + poly_tmp + " = " + rc + ";")
41995+ # Root the receiver temp across the loop body. `rc` is frequently a
41996+ # fresh method-call result (e.g. `@article.comments`) held only in
41997+ # this temp; the loop body allocates (string append, nested render,
41998+ # box helpers), so an unrooted PtrArray/heap collection here can be
41999+ # collected mid-iteration, leaving sp_PtrArray_get to read a freed
42000+ # slot (observed as a SIGSEGV in sp_obj_cls_id_of on a garbage
42001+ # pointer under load). The cleanup-attributed root pops at end of
42002+ # poly_tmp's C scope, which is exactly the loop's extent.
42003+ @needs_gc = 1
42004+ emit_gc_root_for_expr(poly_tmp, "poly")
4199542005 emit(" if (" + poly_tmp + ".tag == SP_TAG_OBJ) {")
4199642006 emit(" mrb_int " + idx_tmp + "_len = 0;")
4199742007 emit(" if (" + poly_tmp + ".cls_id == SP_BUILTIN_RANGE) " + idx_tmp + "_len = ((sp_Range *)" + poly_tmp + ".v.p)->last - ((sp_Range *)" + poly_tmp + ".v.p)->first + 1;")