From 064bf225823454be0c9f72ddfca7f7c6cc209cd5 Mon Sep 17 00:00:00 2001 From: Matthew Dillon Date: Thu, 30 Apr 2020 01:39:05 -0700 Subject: [PATCH] libc - Fix a serious memory leak in the nmalloc code * Fix a bug where mtmagazine_free() would assign mt->newmag without re-checking its contents, potentially overwriting an assignment made by _slaballoc(), causing a memory leak. * This bug generally rears its ugly head in heavily pthreaded programs, but it can occur under other conditions too. Reported-by: hsw (irc) --- lib/libc/stdlib/nmalloc.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/libc/stdlib/nmalloc.c b/lib/libc/stdlib/nmalloc.c index 98db601e16..d0b6094512 100644 --- a/lib/libc/stdlib/nmalloc.c +++ b/lib/libc/stdlib/nmalloc.c @@ -1797,10 +1797,17 @@ mtmagazine_free(int zi, void *ptr) * allocation to avoid reentrancy and/or to avoid a * stack overflow if the [zi] happens to be the same that * would be used to allocate the new magazine. + * + * WARNING! Calling _slaballoc() can indirectly modify + * tp->newmag. */ if (tp->newmag == NULL) { - tp->newmag = _slaballoc(sizeof(struct magazine), - SAFLAG_ZERO); + mp = _slaballoc(sizeof(struct magazine), + SAFLAG_ZERO | SAFLAG_MAGS); + if (tp->newmag && mp) + _slabfree(mp, 0, NULL); + else + tp->newmag = mp; if (tp->newmag == NULL) { rc = -1; break; -- 2.11.4.GIT