Skip to content

--die-with-parent fails to clean up due to a race condition if the parent bwrap process is killed soon after startup #633

Open

Description

@artli
$ cat bwrap_race.sh
echo "BASHPID=$BASHPID"
bwrap --die-with-parent --dev-bind / / --unshare-pid -- sleep 1234 &
BWRAP_PARENT=$!
echo "BWRAP_PARENT=$BWRAP_PARENT"
BWRAP_CHILD=$(ps axo ppid,pid | grep -P "^$BWRAP_PARENT " | awk '{print $2}')
echo "BWRAP_CHILD=$BWRAP_CHILD"
kill $BWRAP_PARENT
while kill -0 $BWRAP_CHILD; do sleep 0.5; done
$ ./bwrap_race.sh 
BASHPID=3552608
BWRAP_PARENT=3552609
BWRAP_CHILD=3552613
./bwrap_race.sh: line 8: 3552609 Terminated              bwrap --die-with-parent --dev-bind / / --unshare-pid -- sleep 1234
<hangs while waiting for BWRAP_CHILD to exit>

I.e. if the parent bwrap process is killed soon after startup, the child bwrap process stops being able to clean up properly. This is probably because the setting of PR_SET_PDEATHSIG in the child doesn't happen immediately and when it does happen, the original parent is already dead, so PR_SET_PDEATHSIG becomes attached to PID 1. (Note: the script above depends on timing and might need to be run in a loop and/or a carefully placed sleep to show this result.)

In a different terminal:

$ ps axo pid,ppid,pgid,cmd | grep 3552608
3552608 3371626 3552608 -bash
3552613       1 3552608 bwrap --die-with-parent --dev-bind / / --unshare-pid -- sleep 1234
3552615 3552613 3552608 sleep 1234
3554357 3552608 3552608 sleep 0.5
3554359 3373029 3554358 grep --color=auto 3552608
$ kill -9 3552608
$ ps axo pid,ppid,pgid,cmd | grep 3552608
3552613       1 3552608 bwrap --die-with-parent --dev-bind / / --unshare-pid -- sleep 1234
3552615 3552613 3552608 sleep 1234
3554915 3373029 3554914 grep --color=auto 3552608
$ kill -9 3552613
$ ps axo pid,ppid,pgid,cmd | grep 3552608
3555757 3373029 3555756 grep --color=auto 3552608
$

See also https://stackoverflow.com/questions/42496478/prctlpr-set-pdeathsig-race-condition for a discussion of this race condition and possible mitigations.

Activity

  1. DemiMarie commented on Sep 9, 2025

    @DemiMarie

    See #700 for a solution.

  2. JAYM-ODIS commented on Oct 21, 2026

    @JAYM-ODIS

    We hit a variant of this in production that is worse than a missed cleanup. The orphaned child never runs the command at all. It blocks forever and holds the caller's stdout/stderr pipes open.

    Setup: bwrap 0.12.0 (Debian trixie package), kernel 6.12, unprivileged user namespaces (bwrap not setuid). We spawn it from Python with subprocess.Popen(argv, stdout=PIPE, stderr=PIPE) and SIGKILL it when the user cancels, which can land in the first few milliseconds:

    bwrap --unshare-all --die-with-parent --new-session \
      --ro-bind /usr /usr --ro-bind /lib /lib --ro-bind /lib64 /lib64 --symlink usr/bin /bin \
      --proc /proc --dev /dev -- /usr/bin/sleep 0.2
    

    Result: we killed bwrap's pid at a random point 0–4 ms after spawn. In 13 of 300 kills a bwrap child survived with ppid 1 and wchan eventfd_read, and it never exits. Our read of the stdout pipe never sees EOF, so anything waiting for the tool's output waits forever.

    Why, as we read the 0.12.0 source: after raw_clone, the child blocks in read (child_wait_fd, &val, 8) ("Wait for the parent to init uid/gid maps and drop caps") until the parent writes the eventfd. The child does not set PR_SET_PDEATHSIG before that read; its handle_die_with_parent () calls come later. If the parent is killed before its write (child_wait_fd, ...), nothing ever writes the eventfd. The child holds its own copy of that fd, and an eventfd has no EOF, so the read never returns.

    That puts this window before the PR_SET_PDEATHSIG race discussed in #700 and #730. Closing that race would not release a child stuck here. If the child waited on a pipe instead, and closed its own write end, the parent's death would read as EOF and the child could exit. That is similar in spirit to the --exit-on-readable idea in #730.

    Workaround for callers, in case it helps anyone else: put bwrap in its own process group (process_group=0 in Python, or setpgid(0, 0) before exec) and kill the group instead of the pid. In this window the child has not yet reached --new-session's setsid (), so it is still in the group. With that change we saw 0 stuck children in 600 kills.

    Repro script
    import os, random, select, signal, subprocess, sys, time
    mode, trials = sys.argv[1], int(sys.argv[2])   # mode: "pid" or "group"
    ARGV = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session",
            "--ro-bind", "/usr", "/usr", "--ro-bind", "/lib", "/lib", "--ro-bind", "/lib64", "/lib64",
            "--symlink", "usr/bin", "/bin", "--proc", "/proc", "--dev", "/dev",
            "--", "/usr/bin/sleep", "0.2"]
    hung, rng = 0, random.Random(1)
    for _ in range(trials):
        kw = {"process_group": 0} if mode == "group" else {}
        p = subprocess.Popen(ARGV, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kw)
        time.sleep(rng.uniform(0, 0.004))
        os.killpg(p.pid, signal.SIGKILL) if mode == "group" else p.kill()
        p.wait()
        r, _, _ = select.select([p.stdout], [], [], 2.0)
        if not (r and p.stdout.read() == b""):
            hung += 1
        p.stdout.close(); p.stderr.close()
    print(f"{mode}: {hung}/{trials} kills left the stdout pipe open after 2 s")

    python3 repro.py pid 300 vs python3 repro.py group 600. Survivors show up in ps -eo pid,ppid,wchan:20,args | grep '[b]wrap'.

  3. sdougbrown commented on Oct 24, 2026

    @sdougbrown

    i hit this issue as well while messing around building my own agent harness nonsense. tacking on more details to help reproduce and allowing the fine maintainers here to direct a more appropriate fix. i'm happy to slop together a PR naturally but that's probably not a productive use of everyone's time here 😅


    👾 AI Agent

    Confirming the 2026-10-21 report above from another caller, with a couple of extra data points.

    Our setup. A Go program (https://github.com/sdougbrown/poo) runs commands under
    bwrap --unshare-all --die-with-parent --new-session --as-pid-1 --proc /proc --dev /dev --tmpfs /tmp --json-status-fd 4 … -- /path/to/helper …, spawned via os/exec. The
    contract we test is that a sandbox never outlives the process that started it, so we
    have a test that spawns a child which starts one sandbox and SIGKILLs itself
    immediately after the sandbox exists. In CI (go test -race ./... on a loaded 4-core
    runner) that test failed on 2 of 4 runs; idle machines never reproduce it.

    Forensics of the survivor (reproduced deterministically by running the launcher
    with no parent-death signal set, then killing the caller immediately after spawn —
    30/30 stranded): a sleeping bwrap process, the sandbox directory still in its argv,
    ppid 1, wchan=do_wait_intr_irq, no children. Same signature as the report above.

    Why, as we read the source (0.8.0 and 0.12.0 agree): the launcher clones the
    namespace child, then arms its own PDEATHSIG, writes the initial JSON status
    document, and only then writes the child_wait_fd eventfd that releases the child.
    The child blocks in read(child_wait_fd) before it arms its own
    handle_die_with_parent() (0.8.0: gate read 3013, arm 3337; 0.12.0: 3198/3492). If
    the launcher dies in that window, nothing ever writes the eventfd, and an eventfd has
    no EOF — the child waits forever.

    One detail that made our window much wider than a single syscall: we set
    PR_SET_PDEATHSIG on the launcher ourselves (SysProcAttr.Pdeathsig), which is
    cleared when the kernel execs a setuid bwrap (as Debian-family packages ship it).
    With the signal gone, the launcher survives the caller's death and instead dies on its
    own: its JSON status write fails (the only reader died with the caller), and the child
    — already cloned — is stranded. With a non-setuid bwrap the window is just
    clone→release, but under load the launcher is descheduled inside it easily, which is
    why only loaded CI runners saw it.

    Workaround, independently confirmed: kill the process group rather than the pid.
    The namespace child is still in the launcher's group until --new-session's
    setsid(), so a group kill reaches it. We additionally made our Start wait until
    the sandbox's init reports itself ready (a first report on a pipe the caller holds),
    so the caller's own death right after spawn hands the teardown to the init, which
    watches a pipe for the caller's death — but the window while Start is still running
    can only be closed on the bwrap side.

    Fix suggestions, in what we think is increasing order of coverage:

    1. Arm the child's parent-death signal before it reads child_wait_fd (move the
      child-path handle_die_with_parent() call above the gate read), combined with the
      getppid() check from PR_SET_PDEATHSIG is racy unless there is a check for the parent having already died #700 so an already-dead parent is detected. That closes the
      whole clone→release window in one move.
    2. Alternatively (or additionally) make the gate a pipe whose write end the child
      closes, so the launcher's death reads as EOF — in the spirit of the
      --exit-on-readable idea in fix(bwrap): close pdeathsig parent race #730.

    Happy to provide the repro harness (a small Go test plus a shell probe) or any further
    detail that helps.

  4. Takyon236 commented on Nov 15, 2026

    @Takyon236

    Two reproducers for this that need no timing, in case they help as regression tests. Both
    behave the same on 0.11.0 (distribution package) and on 0.13.1 built from the release tag
    (kernel 7.2, x86_64, unprivileged user namespaces, bwrap not setuid).

    1. The launcher exits after the clone and its child stays blocked for ever. No signal and no
    --die-with-parent are involved: any exit of the launcher between the clone and the
    child_wait_fd write does it. Here the --info-fd write fails:

    $ bwrap --ro-bind / / --info-fd 3 true 3>/dev/full; echo "exit status $?"; sleep 1
    bwrap: Write to info_fd: No space left on device
    exit status 1
    $ ps -C bwrap -o pid,ppid,stat,etimes,wchan:20,args
        PID    PPID STAT ELAPSED WCHAN                COMMAND
     923874    1621 S          1 do_wait_intr_irq     bwrap --ro-bind / / --info-fd 3 true
    

    30 of 30 runs on each version left that process (reparented, in read() on
    anon_inode:[eventfd], no children); one I watched was unchanged after 60 s. Adding
    --die-with-parent --unshare-pid --new-session changes nothing: 30 of 30 again. The same
    happens when the reader of a --json-status-fd or --info-fd pipe has gone away (EPIPE or
    SIGPIPE in the launcher), which is how the reports above reached it.

    In 0.13.1: the launcher clones at
    L3115, may exit in
    dump_info (L451,
    called at L3160-L3174) or wait at --userns-block-fd (L3176-L3181), and releases the child
    only at L3185. The
    child waits at
    L3238 on an eventfd
    of which it holds a copy itself, so the launcher's exit can never end that read, and it has not
    armed PR_SET_PDEATHSIG yet.

    2. The launcher is killed while the child is in setup; the command still starts. The child
    is held at --block-fd only to make the window as long as needed; without it the window is the
    child's setup time.

    d=$(mktemp -d); mkfifo "$d/hold"; exec 9<>"$d/hold"
    bwrap --die-with-parent --unshare-pid --ro-bind / / --block-fd 8 sleep 300 8<"$d/hold" 9>&- &
    sleep 1                 # the child now waits on --block-fd
    kill -9 $!; wait $!     # the launcher is gone
    echo go >&9             # only now release the child
    sleep 1
    ps -C bwrap -o pid,ppid,stat,etimes,wchan:20,args
    
        PID    PPID STAT ELAPSED WCHAN                COMMAND
     924703    1621 S          2 do_wait              bwrap --die-with-parent --unshare-pid --ro-bind / / --block-fd 8 sleep 300
    

    20 of 20 runs on each version: the remaining bwrap is pid 1 of the sandbox with sleep 300 as
    its child, and nothing ends it. As a control, releasing the child first and killing the caller
    once sleep runs left nothing in 20 of 20. The child's only handle_die_with_parent () calls
    are at L3535 and, in
    the sandbox's pid 1,
    L612: after
    setup_newroot (L3334), --block-fd (L3431-L3436), setsid (L3471) and the fork (L3479 onwards). By
    then the launcher is dead, and the prctl does not fire for a parent that has already exited.

    With natural timing (same command without --block-fd, SIGKILL 0-6 ms after starting it, 300
    runs each): killing the launcher left the command running in 65 runs and a child blocked on the
    eventfd in 4 on 0.11.0, and the command running in 38 and none blocked on 0.13.1. Killing the
    launcher's parent instead left the command running in 83 (0.11.0) and 59 (0.13.1); in 45 and 28
    of those the launcher itself survived, because its parent died before the launcher's own prctl
    at L3158.

    Case 1 would be closed by the pipe already suggested above in place of the eventfd for
    child_wait_fd: the child closes its copy of the write end, so the launcher's exit reads as end
    of file and the child can exit instead of waiting. Case 2 needs the child to arm its
    parent-death signal before that read rather than at L3535, and then to check that the launcher
    is still there, since it may have written the release and died before the arming. The same pipe
    can answer that if the launcher keeps its end open (a hang-up seen after the arming means the
    launcher is gone), which also works under --unshare-pid, where getppid () is 0.

    The outputs and counts above are from runs on my own machine; an AI assistant helped me run the series and write this up. The last paragraph is a reading of the source, not a tested patch.

  5. tomyan-ki commented on Nov 20, 2026

    @tomyan-ki

    We hit this with bubblewrap 0.12.0 (Ubuntu 24.04 kernel, --unshare-all --die-with-parent, unprivileged user namespace). A program that runs bwrap was SIGKILLed 0–30 ms after starting it, 90 times per run. Every run left one to four sandboxes behind. Each survivor was bwrap's init in the sandbox's PID namespace (NSpid: <n> 1), re-parented to PID 1 (PPid: 1), often with the sandboxed command already running under it. The outer bwrap never survived.

    As far as we can tell from bubblewrap.c (0.12.0, and main today), the cloned child starts without a parent-death signal, because clone clears it. It does the whole sandbox setup, forks the command, and only then calls handle_die_with_parent() in do_init(). If the outer bwrap has died by then, the child has already been re-parented, so its PR_SET_PDEATHSIG refers to a parent that never dies, and nothing checks getppid().

    Setting PR_SET_PDEATHSIG in our own child before it execs bwrap made no difference, which fits: the gap is between raw_clone() and do_init(). Setting the signal in the child straight after raw_clone() and then checking getppid() against the expected parent, as #730 proposed, looks like it would close it. For now we rely on running as PID 1 of a PID namespace, so the kernel kills everything when we die.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions