Commit 822ba282

822ba282a8f9Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 2 files · ~2 modified

Description

fix: bigint GC safety via sp_gc_alloc_nogc (no-collect allocator)

Root cause: nested bigint expressions like sp_bigint_mul(sp_bigint_add(a,b), c) have intermediate results on the C stack that are not GC-rooted. If the inner call triggers GC (via sp_gc_alloc threshold check), intermediates are collected.

Fix: bigint objects are allocated via sp_gc_alloc_nogc which adds objects to the old heap (with finalizer for mpz_clear) but never triggers GC collection. GC triggers at the next regular sp_gc_alloc call instead.

pidigits n=1000: correct output, 0.05s (Ruby 0.15s, 3x faster). 68 tests pass, bootstrap clean.

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

Details

Commit
822ba282a8f9
Parent
166702795e7d

lib/sp_bigint.cmodifiedView file

@@ -5262,8 +5262,8 @@
52625262 mpz_t mpz;
52635263 } sp_Bigint;
52645264
5265-/* GC integration: use Spinel's GC allocator when available */
5266-extern void *sp_gc_alloc(size_t sz, void(*fin)(void*), void(*scn)(void*)) __attribute__((weak));
5265+/* GC integration: use Spinel's no-collect allocator to avoid GC during nested bigint ops */
5266+extern void *sp_gc_alloc_nogc(size_t sz, void(*fin)(void*), void(*scn)(void*)) __attribute__((weak));
52675267
52685268 static mpz_ctx_t sp_mpz_ctx_storage;
52695269 static mpz_ctx_t *sp_mpz_ctx = NULL;
@@ -5284,8 +5284,8 @@
52845284
52855285 static sp_Bigint *sp_bigint_alloc(void) {
52865286 sp_bigint_init_ctx();
5287- if (sp_gc_alloc) {
5288- return (sp_Bigint*)sp_gc_alloc(sizeof(sp_Bigint), sp_bigint_finalizer, NULL);
5287+ if (sp_gc_alloc_nogc) {
5288+ return (sp_Bigint*)sp_gc_alloc_nogc(sizeof(sp_Bigint), sp_bigint_finalizer, NULL);
52895289 }
52905290 return (sp_Bigint*)calloc(1, sizeof(sp_Bigint));
52915291 }
@@ -5306,7 +5306,7 @@
53065306 void sp_bigint_free(sp_Bigint *b) {
53075307 if (b) {
53085308 mpz_clear(sp_mpz_ctx, &b->mpz);
5309- if (!sp_gc_alloc) free(b);
5309+ if (!sp_gc_alloc_nogc) free(b);
53105310 }
53115311 }
53125312