Skip to content
69 changes: 59 additions & 10 deletions pkg/command/process_identity_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,30 +94,79 @@ func darwinProcessGroupMemberMatches(
pgid, wantSession int,
identity string,
) (matches, leaderMismatch bool, err error) {
processGroupID := int(process.Eproc.Pgid)
if processGroupID != pgid {
if int(process.Eproc.Pgid) != pgid {
return false, false, nil
}
pid := int(process.Proc.P_pid)
isLeader := pid == pgid
if isLeader && !darwinLeaderStartMatches(process, identity) {
return false, true, nil
}
// kill(-pgid, sig) returns EPERM for a zombie-only group on darwin.
if darwinProcessIsZombie(process) {
return false, false, nil
}
return darwinSessionMatches(pid, isLeader, wantSession)
}

func darwinSessionMatches(
pid int,
isLeader bool,
wantSession int,
) (matches, leaderMismatch bool, err error) {
sessionID, err := darwinSessionID(pid)
if errors.Is(err, syscall.ESRCH) {
return false, false, nil
}
if err != nil {
return false, false, err
}
if pid == pgid {
leaderIdentity, err := processTreeIdentity(pid)
if err != nil {
return false, false, err
}
if leaderIdentity != "" && leaderIdentity != identity {
return false, true, nil
}
if isLeader && sessionID != wantSession {
return false, true, nil
}
return sessionID == wantSession, false, nil
}

func darwinSessionID(pid int) (int, error) {
return unix.Getsid(pid)
}

// x/sys/unix does not export SZOMB.
const darwinProcessStateZombie = 5

func darwinProcessIsZombie(process unix.KinfoProc) bool {
return process.Proc.P_stat == darwinProcessStateZombie
}

func darwinLeaderStartMatches(process unix.KinfoProc, identity string) bool {
parts := strings.Split(identity, ":")
if len(parts) != 3 {
return false
}
return parts[1] == strconv.FormatInt(int64(process.Proc.P_starttime.Sec), 10) &&
parts[2] == strconv.FormatInt(int64(process.Proc.P_starttime.Usec), 10)
}

func processIsLive(pid int) (bool, error) {
process, err := unix.SysctlKinfoProc("kern.proc.pid", pid)
if err != nil {
if processLookupConfirmsExit(pid, err) {
return false, nil
}
return false, err
}
return !darwinProcessIsZombie(*process), nil
}

func processGroupHasLivingMembers(pgid int) (bool, error) {
processes, err := unix.SysctlKinfoProcSlice("kern.proc.all")
if err != nil {
return false, err
}
for _, process := range processes {
if int(process.Eproc.Pgid) == pgid && !darwinProcessIsZombie(process) {
return true, nil
}
}
return false, nil
}
155 changes: 155 additions & 0 deletions pkg/command/process_identity_darwin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//go:build darwin

package command

import (
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/unix"
)

const (
darwinTestPollTimeout = 5 * time.Second
darwinTestPollInterval = 10 * time.Millisecond
)

func startGatedGroupLeader(t *testing.T, script string) (pid int, release func(), arg string) {
t.Helper()
arg = filepath.Join(t.TempDir(), "ready")
// #nosec G204 -- the fixed shell script and all paths are test-controlled.
cmd := exec.Command("sh", "-c", script, "sh", arg)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
stdin, err := cmd.StdinPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
pid = cmd.Process.Pid
t.Cleanup(func() {
_ = syscall.Kill(-pid, syscall.SIGKILL)
_ = cmd.Wait()
})
return pid, func() { require.NoError(t, stdin.Close()) }, arg
}

func waitForZombie(t *testing.T, pid int) {
t.Helper()
require.Eventually(t, func() bool {
proc, err := unix.SysctlKinfoProc("kern.proc.pid", pid)
return err == nil && int(proc.Proc.P_pid) == pid && darwinProcessIsZombie(*proc)
}, darwinTestPollTimeout, darwinTestPollInterval, "process %d did not become a zombie", pid)
}

func startZombieGroupLeader(t *testing.T) (pid int, identity string) {
t.Helper()
pid, release, _ := startGatedGroupLeader(t, `read _`)
identity = processTreeIdentityForTest(t, pid)
release()
waitForZombie(t, pid)
return pid, identity
}

func TestDarwinZombieLeaderIsNotLiveGroupMember(t *testing.T) {
pid, identity := startZombieGroupLeader(t)

live, err := processIsLive(pid)
require.NoError(t, err)
assert.False(t, live, "zombie leader reported live")

living, err := processGroupHasLivingMembers(pid)
require.NoError(t, err)
assert.False(t, living, "zombie-only group reported living members")

matches, err := processGroupMatchesIdentity(pid, identity)
require.NoError(t, err)
assert.False(t, matches, "zombie-only group matched saved identity")
}

func TestDarwinKillWorkerTreeOnZombieOnlyGroupSucceeds(t *testing.T) {
pid, identity := startZombieGroupLeader(t)

require.NoError(t, killWorkerTreeWithIdentity(pid, "detached-task", identity))
waitForZombie(t, pid)
}

func TestDarwinZombieLeaderWithLiveChildKeepsGroupMatched(t *testing.T) {
pid, release, readyFile := startGatedGroupLeader(t, `sleep 30 & echo $! > "$1"; read _`)
childPID := waitForChildPID(t, readyFile)
childGroup, err := unix.Getpgid(childPID)
require.NoError(t, err)
require.Equal(t, pid, childGroup, "child must share the leader's process group")
identity := processTreeIdentityForTest(t, pid)

release()
waitForZombie(t, pid)
childLive, err := processIsLive(childPID)
require.NoError(t, err)
require.True(t, childLive, "child must outlive the zombie leader")

matches, err := processGroupMatchesIdentity(pid, identity)
require.NoError(t, err)
assert.True(t, matches, "live child must keep the group matched")
living, err := processGroupHasLivingMembers(pid)
require.NoError(t, err)
assert.True(t, living, "live child must count as a living member")

require.NoError(t, killWorkerTreeWithIdentity(pid, "detached-task", identity))
require.Eventually(t, func() bool {
live, err := processIsLive(childPID)
return err == nil && !live
}, darwinTestPollTimeout, darwinTestPollInterval, "child %d survived termination", childPID)
}

func TestDarwinZombieLeaderWithLiveChildRejectsStaleIdentity(t *testing.T) {
pid, release, readyFile := startGatedGroupLeader(t, `sleep 30 & echo $! > "$1"; read _`)
childPID := waitForChildPID(t, readyFile)
identity := processTreeIdentityForTest(t, pid)
stale := identity[:strings.LastIndex(identity, ":")] + ":0"

release()
waitForZombie(t, pid)

matches, err := processGroupMatchesIdentity(pid, stale)
require.NoError(t, err)
assert.False(t, matches, "stale identity matched a group")
require.NoError(t, killWorkerTreeWithIdentity(pid, "detached-task", stale))
childLive, err := processIsLive(childPID)
require.NoError(t, err)
assert.True(t, childLive, "stale identity must not terminate the child")
}

func waitForChildPID(t *testing.T, readyFile string) int {
t.Helper()
var childPID int
require.Eventually(t, func() bool {
// #nosec G304 -- this test reads only its own temporary readiness file.
data, err := os.ReadFile(readyFile)
if err != nil || !strings.HasSuffix(string(data), "\n") {
return false
}
childPID, err = strconv.Atoi(strings.TrimSpace(string(data)))
return err == nil
}, darwinTestPollTimeout, darwinTestPollInterval, "child did not report its PID")
return childPID
}

func TestDarwinProcessGroupHasLivingMembersSeesLiveChild(t *testing.T) {
cmd := exec.Command("sleep", "30")
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
require.NoError(t, cmd.Start())
t.Cleanup(func() {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
_ = cmd.Wait()
})

living, err := processGroupHasLivingMembers(cmd.Process.Pid)
require.NoError(t, err)
assert.True(t, living)
}
61 changes: 61 additions & 0 deletions pkg/command/process_identity_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,3 +263,64 @@ func linuxProcessStatFields(stat []byte) ([]string, bool) {
}
return strings.Fields(statText[closingParen+2:]), true
}

func processIsLive(pid int) (bool, error) {
fields, ok, err := linuxProcessStat(pid)
if err != nil || !ok {
return false, err
}
if len(fields) == 0 {
return false, fmt.Errorf("read process state for process %d", pid)
}
return !linuxProcessStateIsExited(fields[0]), nil
}

type linuxStatReader func(pid int) ([]string, bool, error)

func processGroupHasLivingMembers(pgid int) (bool, error) {
if pgid <= 0 {
return false, fmt.Errorf("invalid process group %d", pgid)
}
entries, err := os.ReadDir("/proc")
if err != nil {
return false, err
}
pids := make([]int, 0, len(entries))
for _, entry := range entries {
if pid, err := strconv.Atoi(entry.Name()); err == nil {
pids = append(pids, pid)
}
}
return linuxLivingGroupMembers(pids, pgid, linuxProcessStat)
}

func linuxLivingGroupMembers(pids []int, pgid int, readStat linuxStatReader) (bool, error) {
var skipped error
for _, pid := range pids {
member, err := linuxProcessIsLiveGroupMember(pid, pgid, readStat)
if err != nil {
if !linuxCanSkipProcessStatError(pid, pgid, err) {
return false, err
}
skipped = errors.Join(skipped, fmt.Errorf("inspect process %d: %w", pid, err))
continue
}
if member {
return true, nil
}
}
return linuxProcessGroupMatchResult(pgid, false, skipped)
}

func linuxProcessIsLiveGroupMember(pid, pgid int, readStat linuxStatReader) (bool, error) {
fields, ok, err := readStat(pid)
if err != nil || !ok || len(fields) == 0 {
return false, err
}
processGroup, _, ok := linuxProcessGroupIDs(fields)
return ok && processGroup == pgid && !linuxProcessStateIsExited(fields[0]), nil
}

func linuxProcessStateIsExited(state string) bool {
return state == "Z" || state == "X"
}
Loading
Loading