Commit 6e86ed91

6e86ed917e73Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 5 files · +2 added · ~3 modified

Description

gc: don't trace foreign FFI pointers as heap objects

A pointer obtained through FFI (ffi_read_ptr, a :ptr-returning ffi_func, or an ffi_buffer address) was boxed as sp_box_obj(p, SP_BUILTIN_OBJECT), i.e. tag SP_TAG_OBJ. When kept alive in an ivar or array, sp_mark_rbval ran sp_gc_mark on it -- treating foreign (e.g. libsqlite-owned) memory as a GC allocation, reading a bogus header behind the pointer and eventually jumping through a garbage ->scan hook (intermittent SIGSEGV; deterministic abort under SPINEL_GC_VERIFY). SP_BUILTIN_OBJECT also tags real Object.new instances, which are GC-managed and must stay traced, so the two can't share a sentinel.

Add a distinct SP_BUILTIN_FOREIGN_PTR cls_id sentinel (in sp_gc.h, where the inline mark helper can see it) and a sp_box_foreign_ptr() box helper. The three FFI pointer codegen sites use it, and sp_mark_rbval skips SP_TAG_OBJ values carrying that sentinel. Existing behavior is unchanged for every other value: only the new sentinel is excluded from the mark path.

Reproduced with a minimal libsqlite-style case (FFI func writing a malloc'd pointer into a buffer, read back via ffi_read_ptr, stored across GC churn): SIGSEGV / SPINEL_GC_VERIFY abort before, clean after. The added test exercises the foreign-pointer codegen + scan path.

Gates: 928 tests pass, 57 benchmarks pass, optcarrot checksum 59662, clang clean (compiler + runtime), optcarrot emitted C unchanged.

Fixes #1439

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

Details

Commit
6e86ed917e73
Parent
29e9e948c4ce

lib/sp_gc.hmodifiedView file

@@ -25,6 +25,12 @@
2525 #define SP_TAG_SYM 6
2626 #define SP_TAG_CLASS 7
2727 #define SP_TAG_ENCODING 8
28+/* SP_TAG_OBJ cls_id sentinel for an opaque foreign/FFI pointer (e.g. a
29+ ffi_read_ptr / ffi func ptr return). It is NOT a sp_gc_alloc allocation, so
30+ the collector must not trace it -- sp_mark_rbval skips it. Kept here (not with
31+ the other SP_BUILTIN_* in sp_runtime.h) so the inline mark helper can see it.
32+ Value is the next free slot below SP_BUILTIN_METHOD (-24). */
33+#define SP_BUILTIN_FOREIGN_PTR (-25)
2834 typedef struct { int tag; int cls_id; union { mrb_int i; const char *s; mrb_float f; mrb_bool b; void *p; } v; } sp_RbVal;
2935
3036 /* ---- Collector globals shared with the generated TU ----
@@ -79,7 +85,7 @@
7985 }
8086 static inline void sp_mark_rbval(sp_RbVal v) {
8187 if (v.tag == SP_TAG_STR) sp_mark_string(v.v.s);
82- else if (v.tag == SP_TAG_OBJ) sp_gc_mark(v.v.p);
88+ else if (v.tag == SP_TAG_OBJ && v.cls_id != SP_BUILTIN_FOREIGN_PTR) sp_gc_mark(v.v.p);
8389 }
8490 /* Closure-cell content markers. A captured non-int local is laundered into the
8591 pointer-sized mrb_int cell as (uintptr_t)<ptr>; the cell's GC scan marks the