From b5c064a6fc9660cf643cd79caaa18309498ec0d4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timo=20Ter=C3=A4s?= <timo.teras@iki.fi>
Date: Sat, 26 Mar 2011 20:23:09 +0200
Subject: [PATCH 6/8] malloc-standard: synchronize on fork
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Otherwise other threads can leave malloc state locked, and the child
will hang indefinitely if it tries to malloc something.

Signed-off-by: Timo Teräs <timo.teras@iki.fi>
Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
---
 libc/stdlib/malloc-standard/free.c |   17 +++++++++++++++++
 1 files changed, 17 insertions(+), 0 deletions(-)

diff --git a/libc/stdlib/malloc-standard/free.c b/libc/stdlib/malloc-standard/free.c
index 39e54d6..df512cc 100644
--- a/libc/stdlib/malloc-standard/free.c
+++ b/libc/stdlib/malloc-standard/free.c
@@ -118,6 +118,21 @@ int malloc_trim(size_t pad)
   to inline it at all call points, which turns out not to be an
   optimization at all. (Inlining it in __malloc_consolidate is fine though.)
 */
+static void _malloc_lock(void)
+{
+    __UCLIBC_MUTEX_LOCK_CANCEL_UNSAFE(__malloc_lock);
+}
+
+static void _malloc_unlock(void)
+{
+    __UCLIBC_MUTEX_UNLOCK_CANCEL_UNSAFE(__malloc_lock);
+}
+
+static void _malloc_reset(void)
+{
+    __UCLIBC_MUTEX_INIT_VAR(__malloc_lock);
+}
+
 static void malloc_init_state(mstate av)
 {
     int     i;
@@ -145,6 +160,8 @@ static void malloc_init_state(mstate av)
 
     av->top            = initial_top(av);
     av->pagesize       = malloc_getpagesize;
+
+    __libc_atfork(_malloc_lock, _malloc_unlock, _malloc_reset);
 }
 
 
-- 
1.7.8.4

