szn

Bug 486 — Pty.deinit PID-reuse race on SIGKILL

486. Unconditional kill(pid, SIGKILL) before reap() can kill the wrong process

Severity: HIGH (can SIGKILL an unrelated process) Status: ✅ FIXED Files: src/server/pty.zig:256-276

Problem

pub fn deinit(self: *Pty) void {
    ...
    if (self.pid > 0) {
        _ = std.c.kill(self.pid, std.c.SIG.KILL);
    }
    ...
    self.reap();

If the child already exited but hasn’t been reaped yet (SIGCHLD pending / handler hasn’t run), self.pid may already name a recycled PID belonging to a completely unrelated process. The unconditional kill(pid, SIGKILL) then kills it. The window is small but the consequence is severe and silent — the victim process just dies with no log pointing at szn.

Proposed Fix

waitpid(WNOHANG) before the kill, and skip the kill when the child is already reaped or waitpid reports ECHILD:

if (self.pid > 0) {
    const r = std.c.waitpid(self.pid, &status, std.c.W.NOHANG);
    if (r == 0) _ = std.c.kill(self.pid, std.c.SIG.KILL); // still alive
}

Alternatively track child liveness explicitly at SIGCHLD time so deinit never signals a PID it hasn’t confirmed alive.

Resolution

Pty.deinit in src/server/pty.zig calls self.reap() before checking self.pid > 0, clearing self.pid = -1 if the child has already terminated or been reaped elsewhere (ECHILD), avoiding signalling a dead or recycled PID.

Tests: Pty.deinit skips SIGKILL when child is already reaped — bug #486 asserts that deinit safely detects and clears an externally reaped child PID without sending SIGKILL.