[PATCH] malloc-standard: synchronize on fork

Rich Felker dalias at aerifal.cx
Mon Mar 28 15:15:03 UTC 2011


On Sun, Mar 27, 2011 at 10:47:10PM +0300, Timo Teräs wrote:
> On 03/27/2011 10:21 PM, Rich Felker wrote:
> > On Sat, Mar 26, 2011 at 08:28:04PM +0200, Timo Teräs wrote:
> >> Otherwise other threads can leave malloc state locked, and the child
> >> will hang indefinitely if it tries to malloc something.
> >
> > This change by itself breaks as much as it fixes, unless the mutex
> > implementation is reentrant and recursive. fork() is specified to be
> > async-signal-safe, which means it's legal for a signal handler to call
> > fork() while malloc() is being executed. With your patch, this will
> > hang the program.
> 
> It is recursive mutex. It's works perfectly fine if same thread locks
> that mutex multiple times.

But not from a signal handler. There's almost surely a race between
locking the mutex and having it in the right state so that the signal
handler sees it's the owner.

> Doing fork from signal handler seems utterly stupid. That would need
> extra precautions to work properly, because the malloc code is not
> re-entrant.

Right. But fork() is required to be async-signal-safe.

> But this is not the case I'm fixing. It's thread A doing malloc while
> thread B is forking.

I know you're trying to fix this. You're breaking something else at
the same time.

> As such, this does not break anything. Or could you provide example code
> on scenario that this breaks (and which was not broken before this)?

It breaks the case where a thread in the middle of acquiring the lock
in malloc() receives a signal and calls fork() from the signal
handler. This is perfectly legal code.

> This does not address the case that the thread forking is doing malloc
> and forks from signal handler. That case is just utterly broken and not
> worth fixing IMHO.

Yet this one is required by POSIX to work, and the case you're fixing
is not required by POSIX to work.

Rich


More information about the uClibc mailing list