Commit 676cf226

676cf226dc46Merged

Ryan Seys <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

fiber: check fiber-storage allocations against OOM

sp_FiberStore_set doubled the capacity and then reused the realloc results without checking them: a failed realloc left s->cap corrupted, leaked the old buffer, and wrote through a NULL pointer on the line below. sp_FiberStore_new had the same unchecked malloc pattern.

Grow each array into a temporary and commit s->keys/s->vals/s->cap only after both succeed, so a failed realloc leaves the store intact (the original buffer survives) rather than NULL-deref'ing or double-freeing a moved buffer; raise NoMemoryError instead of crashing. Guard the initial mallocs the same way.

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

Details

Commit
676cf226dc46
Parent
ef0dd7102c46

lib/sp_fiber.cmodifiedView file

@@ -94,6 +94,13 @@
9494 s->cap = 8; s->len = 0;
9595 s->keys = (sp_sym *)malloc(sizeof(sp_sym) * s->cap);
9696 s->vals = (sp_RbVal *)malloc(sizeof(sp_RbVal) * s->cap);
97+ if (!s->keys || !s->vals) {
98+ /* If one side succeeded, release it now rather than waiting for the
99+ finalizer -- and NULL both so that finalizer's free stays a no-op. */
100+ free(s->keys); free(s->vals);
101+ s->keys = NULL; s->vals = NULL;
102+ sp_raise_cls("NoMemoryError", "failed to allocate fiber storage");
103+ }
97104 return s;
98105 }
99106 static sp_RbVal sp_FiberStore_get(sp_FiberStore *s, sp_sym k) {
@@ -103,9 +110,16 @@
103110 static void sp_FiberStore_set(sp_FiberStore *s, sp_sym k, sp_RbVal v) {
104111 for (mrb_int i = 0; i < s->len; i++) if (s->keys[i] == k) { s->vals[i] = v; return; }
105112 if (s->len == s->cap) {
106- s->cap *= 2;
107- s->keys = (sp_sym *)realloc(s->keys, sizeof(sp_sym) * s->cap);
108- s->vals = (sp_RbVal *)realloc(s->vals, sizeof(sp_RbVal) * s->cap);
113+ /* Grow each array into a temp and commit only on success, so a failed
114+ realloc leaves the store intact (the old buffer survives) instead of
115+ NULL-deref'ing on the write below or double-freeing a moved buffer. */
116+ mrb_int nc = s->cap * 2;
117+ sp_sym *nk = (sp_sym *)realloc(s->keys, sizeof(sp_sym) * nc);
118+ if (!nk) sp_raise_cls("NoMemoryError", "failed to grow fiber storage");
119+ s->keys = nk;
120+ sp_RbVal *nv = (sp_RbVal *)realloc(s->vals, sizeof(sp_RbVal) * nc);
121+ if (!nv) sp_raise_cls("NoMemoryError", "failed to grow fiber storage");
122+ s->vals = nv; s->cap = nc;
109123 }
110124 s->keys[s->len] = k; s->vals[s->len] = v; s->len++;
111125 }