Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

rediwm-session: reap the orphans it adopts as a subreaper

oxydizer1cfc3c356679
diff --git a/src/session/supervisor.zig b/src/session/supervisor.zig
index 06417bc..a4bb0cf 100644
--- a/src/session/supervisor.zig
+++ b/src/session/supervisor.zig
@@ -48,10 +48,11 @@ pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8
var preexisting = try descendants(allocator, linux.getpid());
defer preexisting.deinit(allocator);
- // Logout signals arrive through a signalfd; the child gets the old mask back.
+ // Logout signals and child exits arrive through a signalfd; the child gets the old mask back.
var mask = linux.sigemptyset();
linux.sigaddset(&mask, .TERM);
linux.sigaddset(&mask, .INT);
+ linux.sigaddset(&mask, .CHLD);
var old_mask: linux.sigset_t = undefined;
_ = try sys.check(linux.sigprocmask(linux.SIG.BLOCK, &mask, &old_mask));
defer _ = linux.sigprocmask(linux.SIG.SETMASK, &old_mask, null);
@@ -108,7 +109,7 @@ pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8
sys.close(pidfd);
if (options.publication) |p| p.restore() catch |err| sys.diagnostic("activation cleanup pending: {t}", .{err});
}
- stopping = try waitForExit(allocator, parent, pidfd, signal_fd, options.publication, &locked);
+ stopping = try waitForExit(allocator, pid, parent, pidfd, signal_fd, options.publication, &locked);
}
if (stopping) return 0;
const raw = status orelse return 1;
@@ -124,7 +125,7 @@ pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8
/// Serves readiness handshakes and records lock reports until the compositor
/// exits (false) or the supervisor is asked to stop (true).
-fn waitForExit(allocator: std.mem.Allocator, parent: i32, pidfd: i32, signal_fd: i32, maybe_publication: anytype, locked: *bool) !bool {
+fn waitForExit(allocator: std.mem.Allocator, compositor: Pid, parent: i32, pidfd: i32, signal_fd: i32, maybe_publication: anytype, locked: *bool) !bool {
var deadline: ?i64 = sys.monotonicMs() + readiness_timeout_ms;
var parent_open = true;
var packet: [16384]u8 = undefined;
@@ -146,7 +147,12 @@ fn waitForExit(allocator: std.mem.Allocator, parent: i32, pidfd: i32, signal_fd:
}
if (fds[1].revents != 0) {
var info: linux.signalfd_siginfo = undefined;
- _ = linux.read(signal_fd, @ptrCast(&info), @sizeOf(linux.signalfd_siginfo));
+ const got = linux.read(signal_fd, @ptrCast(&info), @sizeOf(linux.signalfd_siginfo));
+ if (linux.errno(got) != .SUCCESS or got != @sizeOf(linux.signalfd_siginfo)) continue;
+ if (info.signo == @intFromEnum(linux.SIG.CHLD)) {
+ reapAdopted(compositor);
+ continue;
+ }
return true;
}
if (fds[2].revents == 0) continue;
@@ -171,6 +177,24 @@ fn waitForExit(allocator: std.mem.Allocator, parent: i32, pidfd: i32, signal_fd:
}
}
+/// The supervisor is a child subreaper, so every orphan of the session (a
+/// double-forked helper, an app whose launcher exited first) becomes its child
+/// and stays a zombie until someone waits for it. Nothing did, so a day of use
+/// left hundreds. Peek first (`NOWAIT`): the compositor's own status is
+/// collected by `stopGroup` and must not be consumed here. A zombie compositor
+/// can hide others behind it, but then the loop is already ending.
+fn reapAdopted(compositor: Pid) void {
+ while (true) {
+ var info = std.mem.zeroes(linux.siginfo_t);
+ const peeked = linux.waitid(.ALL, 0, &info, linux.W.EXITED | linux.W.NOHANG | linux.W.NOWAIT, null);
+ if (linux.errno(peeked) != .SUCCESS) return;
+ const pid = info.fields.common.first.piduid.pid;
+ if (pid == 0 or pid == compositor) return;
+ var reaped = std.mem.zeroes(linux.siginfo_t);
+ if (linux.errno(linux.waitid(.PID, pid, &reaped, linux.W.EXITED | linux.W.NOHANG, null)) != .SUCCESS) return;
+ }
+}
+
/// A compositor that locked and then crashed may die before its report is
/// read; what it left queued still decides how the next one starts.
fn drainLockReports(parent: i32, locked: *bool) void {
diff --git a/tests/rediwm_session.py b/tests/rediwm_session.py
index de442a7..3116dee 100644
--- a/tests/rediwm_session.py
+++ b/tests/rediwm_session.py
@@ -13,6 +13,7 @@ import stat
import subprocess
import sys
import tempfile
+import time
SUPERVISOR = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parents[1] / "zig-out/bin/rediwm-session")
@@ -175,6 +176,47 @@ def test_compositor_environment():
print("rediwm-session: the compositor gets the session PATH/XDG environment and no host display")
+def zombie_children(pid):
+ """Direct children of `pid` that have exited but not been waited for."""
+ children = Path(f"/proc/{pid}/task/{pid}/children").read_text().split()
+ zombies = []
+ for child in children:
+ try:
+ state = Path(f"/proc/{child}/stat").read_text().rsplit(")", 1)[1].split()[0]
+ except OSError:
+ continue
+ if state == "Z":
+ zombies.append(int(child))
+ return zombies
+
+
+def test_adopted_orphans_are_reaped():
+ """The supervisor is a subreaper: orphans of the session become its children and must be reaped."""
+ with tempfile.TemporaryDirectory(prefix="rediwm-session-test-") as directory:
+ tmp = Path(directory)
+ # Each inner subshell loses its parent at once, so the supervisor adopts it; it exits 0.3 s later.
+ body = 'echo ran >>"$0.count"\n( (sleep 0.3) & )\n( (sleep 0.3) & )\n( (sleep 0.3) & )\nsleep 3\nexit 0\n'
+ wrapper, fake = build_wrapper(tmp, body)
+ home = tmp / "home"
+ home.mkdir()
+ process = subprocess.Popen([str(wrapper)], env=isolated_env(home), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ time.sleep(1.5)
+ deadline = time.monotonic() + 1.0
+ zombies = zombie_children(process.pid)
+ while zombies and time.monotonic() < deadline:
+ time.sleep(0.1)
+ zombies = zombie_children(process.pid)
+ assert not zombies, ("exited orphans were never reaped", zombies)
+ assert process.wait(timeout=15) == 0
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait()
+ assert count_runs(fake, "ran") == 1, "reaping must not look like a compositor exit"
+ print("rediwm-session: adopted orphans are reaped while the compositor runs")
+
+
if __name__ == "__main__":
test_clean_exit_does_not_restart()
test_sigterm_does_not_restart()
@@ -183,3 +225,4 @@ if __name__ == "__main__":
test_crash_while_locked_restarts_locked()
test_previous_log_rotated_once_per_login()
test_compositor_environment()
+ test_adopted_orphans_are_reaped()