Commit b30abee7
b30abee7ae57Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
Merge pull request #1472 from ryanseys/rs-fix-fiberstore-realloc
fiber: check fiber-storage allocations against OOM
Details
- Commit
- b30abee7ae57
- Parent
- 7cc6b50cbf16
- Merge parent
- 676cf226dc46
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 the99+
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 failed114+
realloc leaves the store intact (the old buffer survives) instead of115+
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
}