summaryrefslogtreecommitdiff
path: root/internal/tui/pidpicker/proclist.go
blob: 73ff209ee59864da78ba3173e802fcdb98b339b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package pidpicker

import (
	"bytes"
	"cmp"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strconv"
	"strings"
	"sync"
)

// ProcessInfo is the metadata shown in the PID picker list.
type ProcessInfo struct {
	Pid       int
	ParentPID int
	Comm      string
	Cmdline   string
}

// ScanProcesses returns process metadata from /proc.
func ScanProcesses() ([]ProcessInfo, error) {
	return scanProcessesFrom("/proc")
}

// ScanThreads returns thread metadata from /proc/<pid>/task for one process.
func ScanThreads(pid int) ([]ProcessInfo, error) {
	return scanThreadsFrom("/proc", pid)
}

// ScanAllThreads returns thread metadata from /proc/*/task.
func ScanAllThreads() ([]ProcessInfo, error) {
	return scanAllThreadsFrom("/proc")
}

func scanProcessesFrom(procRoot string) ([]ProcessInfo, error) {
	entries, err := os.ReadDir(procRoot)
	if err != nil {
		return nil, fmt.Errorf("read proc root %q: %w", procRoot, err)
	}

	processes := make([]ProcessInfo, 0, len(entries))
	for _, entry := range entries {
		process, ok := readProcessInfo(procRoot, entry)
		if !ok {
			continue
		}
		processes = append(processes, process)
	}

	slices.SortFunc(processes, func(a, b ProcessInfo) int {
		return cmp.Compare(a.Pid, b.Pid)
	})
	return processes, nil
}

func readProcessInfo(procRoot string, entry fs.DirEntry) (ProcessInfo, bool) {
	if !entry.IsDir() {
		return ProcessInfo{}, false
	}

	pid, err := strconv.Atoi(entry.Name())
	if err != nil {
		return ProcessInfo{}, false
	}

	statPath := filepath.Join(procRoot, entry.Name(), "stat")
	statData, err := os.ReadFile(statPath)
	if err != nil {
		return ProcessInfo{}, false
	}

	comm, err := parseCommFromStat(string(statData))
	if err != nil {
		return ProcessInfo{}, false
	}

	cmdlinePath := filepath.Join(procRoot, entry.Name(), "cmdline")
	cmdlineData, err := os.ReadFile(cmdlinePath)
	if err != nil {
		cmdlineData = nil
	}

	return ProcessInfo{
		Pid:       pid,
		ParentPID: pid,
		Comm:      comm,
		Cmdline:   normalizeCmdline(cmdlineData),
	}, true
}

func parseCommFromStat(statLine string) (string, error) {
	open := strings.IndexByte(statLine, '(')
	close := strings.LastIndexByte(statLine, ')')
	if open < 0 || close < 0 || close <= open+1 {
		return "", fmt.Errorf("invalid stat line")
	}

	comm := statLine[open+1 : close]
	if strings.TrimSpace(comm) == "" {
		return "", fmt.Errorf("empty comm in stat line")
	}
	return comm, nil
}

func normalizeCmdline(raw []byte) string {
	if len(raw) == 0 {
		return ""
	}

	trimmed := bytes.TrimRight(raw, "\x00")
	if len(trimmed) == 0 {
		return ""
	}

	parts := bytes.Split(trimmed, []byte{0})
	out := make([]string, 0, len(parts))
	for _, part := range parts {
		if len(part) == 0 {
			continue
		}
		out = append(out, string(part))
	}
	return strings.Join(out, " ")
}

func scanThreadsFrom(procRoot string, pid int) ([]ProcessInfo, error) {
	taskRoot := filepath.Join(procRoot, strconv.Itoa(pid), "task")
	entries, err := os.ReadDir(taskRoot)
	if err != nil {
		return nil, fmt.Errorf("read task root %q: %w", taskRoot, err)
	}

	cmdlineData, _ := os.ReadFile(filepath.Join(procRoot, strconv.Itoa(pid), "cmdline"))
	cmdline := normalizeCmdline(cmdlineData)

	threads := make([]ProcessInfo, 0, len(entries))
	for _, entry := range entries {
		thread, ok := readThreadInfo(taskRoot, entry, cmdline)
		if !ok {
			continue
		}
		threads = append(threads, thread)
	}

	slices.SortFunc(threads, func(a, b ProcessInfo) int {
		return cmp.Compare(a.Pid, b.Pid)
	})
	return threads, nil
}

func readThreadInfo(taskRoot string, entry fs.DirEntry, cmdline string) (ProcessInfo, bool) {
	if !entry.IsDir() {
		return ProcessInfo{}, false
	}

	tid, err := strconv.Atoi(entry.Name())
	if err != nil {
		return ProcessInfo{}, false
	}

	commPath := filepath.Join(taskRoot, entry.Name(), "comm")
	commData, err := os.ReadFile(commPath)
	if err != nil {
		return ProcessInfo{}, false
	}
	comm := strings.TrimSpace(string(commData))
	if comm == "" {
		return ProcessInfo{}, false
	}

	return ProcessInfo{
		Pid:       tid,
		ParentPID: extractPIDFromPath(taskRoot),
		Comm:      comm,
		Cmdline:   cmdline,
	}, true
}

func scanAllThreadsFrom(procRoot string) ([]ProcessInfo, error) {
	processes, err := scanProcessesFrom(procRoot)
	if err != nil {
		return nil, err
	}

	threads := make([]ProcessInfo, 0, len(processes)*8)
	var mu sync.Mutex
	var wg sync.WaitGroup
	sem := make(chan struct{}, 16)

	for _, p := range processes {
		pid := p.Pid
		wg.Add(1)
		go func() {
			defer wg.Done()
			sem <- struct{}{}
			defer func() { <-sem }()

			perProc, err := scanThreadsFrom(procRoot, pid)
			if err != nil {
				return
			}
			mu.Lock()
			threads = append(threads, perProc...)
			mu.Unlock()
		}()
	}
	wg.Wait()

	slices.SortFunc(threads, func(a, b ProcessInfo) int {
		if a.Pid != b.Pid {
			return cmp.Compare(a.Pid, b.Pid)
		}
		return cmp.Compare(a.ParentPID, b.ParentPID)
	})
	return threads, nil
}

func extractPIDFromPath(taskRoot string) int {
	parts := strings.Split(filepath.Clean(taskRoot), string(os.PathSeparator))
	if len(parts) < 2 {
		return -1
	}
	pid, err := strconv.Atoi(parts[len(parts)-2])
	if err != nil {
		return -1
	}
	return pid
}