This is an archive of the discontinued LLVM Phabricator instance.

[lldb] Make ProcessLauncherPosixFork (mostly) async-signal-safe
ClosedPublic

Authored by labath on Dec 22 2021, 6:31 AM.

Details

Summary

Multithreaded applications using fork(2) need to be extra careful about
what they do in the fork child. Without any special precautions (which
only really work if you can fully control all threads) they can only
safely call async-signal-safe functions. This is because the forked
child will contain snapshot of the parents memory at a random moment in
the execution of all of the non-forking threads (this is where the
similarity with signals comes in).

For example, the other threads could have been holding locks that can
now never be released in the child process and any attempt to obtain
them would block. This is what sometimes happen when using tcmalloc --
our fork child ends up hanging in the memory allocation routine. It is
also what happened with our logging code, which is why we added a
pthread_atfork hackaround.

This patch implements a proper fix to the problem, by which is to make
the child code async-signal-safe. The ProcessLaunchInfo structure is
transformed into a simpler ForkLaunchInfo representation, one which can
be read without allocating memory and invoking complex library
functions.

Strictly speaking this implementation is not async-signal-safe, as it
still invokes library functions outside of the posix-blessed set of
entry points. Strictly adhering to the spec would mean reimplementing a
lot of the functionality in pure C, so instead I rely on the fact that
any reasonable implementation of some functions (e.g.,
basic_string::c_str()) will not start allocating memory or doing other
unsafe things.

The new child code does not call into our logging infrastructure, which
enables us to remove the pthread_atfork call from there.

Diff Detail

Event Timeline

labath created this revision.Dec 22 2021, 6:31 AM
labath requested review of this revision.Dec 22 2021, 6:31 AM
Herald added a project: Restricted Project. · View Herald TranscriptDec 22 2021, 6:31 AM
mgorny accepted this revision.Dec 22 2021, 6:56 AM

I don't see anything obviously wrong here. I presume you've tested it, so LGTM.

This revision is now accepted and ready to land.Dec 22 2021, 6:56 AM