Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 48 additions & 6 deletions internal/proc/ps.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (r *psReader) readPS(ctx context.Context, pid int) (Process, error) {
if err != nil {
return Process{}, classifyPSError(pid, err)
}
p, err := parsePS(out)
p, err := parsePS(out, r.readComm(ctx, pid))
if err != nil {
if errors.Is(err, ErrNotFound) {
return Process{}, err
Expand All @@ -66,6 +66,17 @@ func (r *psReader) readPS(ctx context.Context, pid int) (Process, error) {
return p, nil
}

// readComm returns the executable path of pid as reported by "ps -o comm=",
// which is not split on spaces. It returns "" when ps fails, so the caller
// falls back to the lossy whitespace split.
func (r *psReader) readComm(ctx context.Context, pid int) string {
out, err := r.runner.Run(ctx, "ps", "-o", "comm=", "-p", strconv.Itoa(pid))
if err != nil {
return ""
}
return parsePSComm(out)
}

// classifyPSError maps a failed ps run to a Reader error. ps exits 1 with no
// output when the PID does not exist; any other failure (ps missing, timeout,
// other exit codes) is not "not found" and keeps its cause.
Expand Down Expand Up @@ -112,11 +123,16 @@ func (r *psReader) readAncestors(ctx context.Context, ppid, self int) []Ancestor
// "ps -o pid=,ppid=,user=,lstart=,command= -p <pid>". Empty output yields
// ErrNotFound.
//
// Cmdline is the command column split on whitespace. This is lossy: ps joins
// the arguments with single spaces, so arguments that contain spaces cannot be
// told apart from several arguments. Name is the base name of the first
// token, so an executable path containing spaces is cut off as well.
func parsePS(out []byte) (Process, error) {
// comm is the executable path from "ps -o comm=" (see parsePSComm). When the
// command column starts with it, comm is kept as the first Cmdline element and
// Name is its base name, so executables whose path contains spaces survive.
// With comm empty or not a prefix of the command, the first whitespace token
// is used instead, which cuts such paths off.
//
// The remaining Cmdline is the command column split on whitespace. This is
// lossy: ps joins the arguments with single spaces, so arguments that contain
// spaces cannot be told apart from several arguments.
func parsePS(out []byte, comm string) (Process, error) {
line := strings.TrimSpace(string(out))
if line == "" {
return Process{}, ErrNotFound
Expand All @@ -130,6 +146,8 @@ func parsePS(out []byte) (Process, error) {
return Process{}, fmt.Errorf("parse ps output %q: want at least %d fields, got %d", line, psLeadingFields+1, len(fields))
}

command := commandColumn(line)

pid, err := strconv.Atoi(fields[0])
if err != nil {
return Process{}, fmt.Errorf("parse ps pid %q: %w", fields[0], err)
Expand All @@ -145,6 +163,9 @@ func parsePS(out []byte) (Process, error) {
}

cmdline := fields[psLeadingFields:]
if rest, ok := strings.CutPrefix(command, comm); ok && comm != "" && (rest == "" || rest[0] == ' ') {
cmdline = append([]string{comm}, strings.Fields(rest)...)
}
return Process{
PID: pid,
PPID: ppid,
Expand All @@ -155,6 +176,27 @@ func parsePS(out []byte) (Process, error) {
}, nil
}

// commandColumn returns line without its leading psLeadingFields
// whitespace-separated fields, with the command's own spacing intact.
func commandColumn(line string) string {
rest := line
for range psLeadingFields {
rest = strings.TrimLeft(rest, " \t")
i := strings.IndexAny(rest, " \t")
if i < 0 {
return ""
}
rest = rest[i:]
}
return strings.TrimSpace(rest)
}

// parsePSComm parses "ps -o comm= -p <pid>" output: the first line, trimmed.
func parsePSComm(out []byte) string {
line, _, _ := strings.Cut(string(out), "\n")
return strings.TrimSpace(line)
}

// parseLsofCwd extracts the path from "lsof -Fn" output: the first line that
// starts with "n". It returns "" when there is none.
func parseLsofCwd(out []byte) string {
Expand Down
81 changes: 77 additions & 4 deletions internal/proc/ps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ func psKey(pid int) string {
return execx.Key("ps", "-o", "pid=,ppid=,user=,lstart=,command=", "-p", fmt.Sprint(pid))
}

func commKey(pid int) string {
return execx.Key("ps", "-o", "comm=", "-p", fmt.Sprint(pid))
}

func lsofKey(pid int) string {
return execx.Key("lsof", "-a", "-p", fmt.Sprint(pid), "-d", "cwd", "-Fn")
}
Expand All @@ -48,7 +52,7 @@ func psLine(pid, ppid int, command string) []byte {
}

func TestParsePS_ParsesFields(t *testing.T) {
p, err := parsePS(fixture(t, "ps_one.txt"))
p, err := parsePS(fixture(t, "ps_one.txt"), "")
if err != nil {
t.Fatalf("parsePS: %v", err)
}
Expand All @@ -73,7 +77,7 @@ func TestParsePS_ParsesFields(t *testing.T) {
}

func TestParsePS_CommandWithSpaces(t *testing.T) {
p, err := parsePS(fixture(t, "ps_spaces.txt"))
p, err := parsePS(fixture(t, "ps_spaces.txt"), "")
if err != nil {
t.Fatalf("parsePS: %v", err)
}
Expand All @@ -93,6 +97,75 @@ func TestParsePS_CommandWithSpaces(t *testing.T) {
}
}

func TestParsePS_NameWithSpaces(t *testing.T) {
tests := map[string]struct {
fixture string
comm string
wantName string
wantCmd []string
}{
"spaces": {
"ps_spaces.txt", "/Applications/My App.app/Contents/MacOS/My App", "My App",
[]string{"/Applications/My App.app/Contents/MacOS/My App", "--flag"},
},
"special characters": {
"ps_special.txt",
"/Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Helper (Renderer).app/Contents/MacOS/Google Chrome Helper (Renderer)",
"Google Chrome Helper (Renderer)",
[]string{"/Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Helper (Renderer).app/Contents/MacOS/Google Chrome Helper (Renderer)", "--type=renderer"},
},
"no spaces unchanged": {
"ps_one.txt", "/usr/local/bin/node", "node",
[]string{"/usr/local/bin/node", "/home/devuser/app/server.js", "--port", "3000"},
},
"comm not a prefix falls back": {
"ps_one.txt", "/other/path", "node",
[]string{"/usr/local/bin/node", "/home/devuser/app/server.js", "--port", "3000"},
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
p, err := parsePS(fixture(t, tt.fixture), tt.comm)
if err != nil {
t.Fatalf("parsePS: %v", err)
}
if p.Name != tt.wantName {
t.Errorf("Name = %q, want %q", p.Name, tt.wantName)
}
if !slices.Equal(p.Cmdline, tt.wantCmd) {
t.Errorf("Cmdline = %v, want %v", p.Cmdline, tt.wantCmd)
}
})
}
}

func TestParsePSComm(t *testing.T) {
if got := parsePSComm([]byte("/Applications/LM Studio.app/Contents/MacOS/LM Studio\n")); got != "/Applications/LM Studio.app/Contents/MacOS/LM Studio" {
t.Errorf("comm = %q", got)
}
if got := parsePSComm(nil); got != "" {
t.Errorf("comm of empty output = %q, want empty", got)
}
}

func TestDarwinReader_NameWithSpaces(t *testing.T) {
comm := "/Applications/LM Studio.app/Contents/MacOS/LM Studio"
f := &execx.Fake{Responses: map[string][]byte{
psKey(70): psLine(70, 1, comm+" --port 1234"),
commKey(70): []byte(comm + "\n"),
lsofKey(70): nil,
psKey(1): psLine(1, 0, "/sbin/launchd"),
lsofKey(1): nil,
}}
p, err := newPSReader(f).Read(context.Background(), 70)
if err != nil {
t.Fatalf("Read: %v", err)
}
if p.Name != "LM Studio" {
t.Errorf("Name = %q, want %q", p.Name, "LM Studio")
}
}

func TestParsePS_Malformed(t *testing.T) {
tests := map[string]string{
"too few fields": "12 1 devuser Thu Nov 12\n",
Expand All @@ -102,7 +175,7 @@ func TestParsePS_Malformed(t *testing.T) {
}
for name, in := range tests {
t.Run(name, func(t *testing.T) {
_, err := parsePS([]byte(in))
_, err := parsePS([]byte(in), "")
if err == nil {
t.Fatal("parsePS returned nil error")
}
Expand All @@ -114,7 +187,7 @@ func TestParsePS_Malformed(t *testing.T) {
}

func TestParsePS_EmptyIsNotFound(t *testing.T) {
if _, err := parsePS([]byte(" \n")); !errors.Is(err, ErrNotFound) {
if _, err := parsePS([]byte(" \n"), ""); !errors.Is(err, ErrNotFound) {
t.Fatalf("error = %v, want ErrNotFound", err)
}
}
Expand Down
1 change: 1 addition & 0 deletions internal/proc/testdata/darwin/ps_special.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
812 1 devuser Wed Nov 11 10:00:00 2026 /Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Helper (Renderer).app/Contents/MacOS/Google Chrome Helper (Renderer) --type=renderer
Loading