diff --git a/internal/proc/list.go b/internal/proc/list.go index 2a9937ca9..1a0dba980 100644 --- a/internal/proc/list.go +++ b/internal/proc/list.go @@ -13,19 +13,13 @@ type Process struct { Args string } -// List lists the running processes (Windows: only those named prefix*, -// since asking for all is slow there; elsewhere prefix is ignored). An -// error says the system couldn't be asked, not that nothing runs. -func List(ctx context.Context, prefix string) ([]Process, error) { - out, err := listCommand(ctx, prefix).Output() - if err != nil { - return nil, err - } - return parseList(string(out)), nil -} +// List lists the running processes (Windows: only those named prefix*; +// elsewhere prefix is ignored). An error says the system couldn't be +// asked, not that nothing runs. +func List(ctx context.Context, prefix string) ([]Process, error) { return list(ctx, prefix) } -// parseList reads lines of "pid command line", as ps -o pid=,args= and the -// PowerShell listing print them; a line without a pid is skipped. +// parseList reads lines of "pid command line", as ps -o pid=,args= prints +// them; a line without a pid is skipped. func parseList(out string) []Process { var ps []Process for _, line := range strings.Split(out, "\n") { diff --git a/internal/proc/list_other.go b/internal/proc/list_other.go index 577649fb4..9544110e4 100644 --- a/internal/proc/list_other.go +++ b/internal/proc/list_other.go @@ -2,13 +2,14 @@ package proc -import ( - "context" - "os/exec" -) +import "context" -// listCommand is ps, in its POSIX form, which macOS, Linux and the BSDs -// all take: every process, its id and its whole command line. -func listCommand(ctx context.Context, _ string) *exec.Cmd { - return CommandContext(ctx, "ps", "-A", "-o", "pid=", "-o", "args=") +// list asks ps, in its POSIX form, which macOS, Linux and the BSDs all +// take: every process, its id and its whole command line. +func list(ctx context.Context, _ string) ([]Process, error) { + out, err := CommandContext(ctx, "ps", "-A", "-o", "pid=", "-o", "args=").Output() + if err != nil { + return nil, err + } + return parseList(string(out)), nil } diff --git a/internal/proc/list_windows.go b/internal/proc/list_windows.go index cb15dae16..553e9d62e 100644 --- a/internal/proc/list_windows.go +++ b/internal/proc/list_windows.go @@ -2,18 +2,62 @@ package proc import ( "context" - "os/exec" "strings" + "unsafe" + + "golang.org/x/sys/windows" ) -// listCommand asks WMI, through PowerShell, for the processes named -// prefix*, one "pid command line" line each; a process whose command line -// isn't readable (another user's) prints its id alone. -func listCommand(ctx context.Context, prefix string) *exec.Cmd { - filter := "" - if prefix != "" { - filter = ` -Filter "Name like '` + strings.ReplaceAll(prefix, "'", "''") + `%'"` +// list walks a Toolhelp snapshot for the processes named prefix*, case +// aside, and reads each one's command line from the process itself. It +// used to ask WMI through a new PowerShell each time, which cost a .NET +// start and a WMI query every few seconds while a Codex daemon was +// watched (#3467); this takes no child process and no WMI. A process +// whose command line isn't readable (another user's, a protected one) +// is listed with its id alone, as WMI listed it. +func list(ctx context.Context, prefix string) ([]Process, error) { + snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) + if err != nil { + return nil, err } - return CommandContext(ctx, "powershell", "-NoProfile", "-NonInteractive", "-Command", - `Get-CimInstance Win32_Process`+filter+` | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }`) + defer windows.CloseHandle(snap) + prefix = strings.ToLower(prefix) + var ps []Process + e := windows.ProcessEntry32{Size: uint32(unsafe.Sizeof(windows.ProcessEntry32{}))} + for err = windows.Process32First(snap, &e); err == nil; err = windows.Process32Next(snap, &e) { + if err := ctx.Err(); err != nil { + return nil, err + } + name := windows.UTF16ToString(e.ExeFile[:]) + if e.ProcessID == 0 || !strings.HasPrefix(strings.ToLower(name), prefix) { + continue + } + ps = append(ps, Process{PID: int(e.ProcessID), Args: commandLine(e.ProcessID)}) + } + if err != windows.ERROR_NO_MORE_FILES { + return nil, err + } + return ps, nil +} + +// commandLine is a process's command line as it was started, "" when it +// can't be read. +func commandLine(pid uint32) string { + h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) + if err != nil { + return "" + } + defer windows.CloseHandle(h) + // the answer is a UNICODE_STRING followed by its text; ask for the + // size first, since a command line can run to 32K characters + var n uint32 + _ = windows.NtQueryInformationProcess(h, windows.ProcessCommandLineInformation, nil, 0, &n) + if n < uint32(unsafe.Sizeof(windows.NTUnicodeString{})) { + return "" + } + buf := make([]byte, n) + if err := windows.NtQueryInformationProcess(h, windows.ProcessCommandLineInformation, unsafe.Pointer(&buf[0]), n, &n); err != nil { + return "" + } + return strings.TrimSpace((*windows.NTUnicodeString)(unsafe.Pointer(&buf[0])).String()) } diff --git a/internal/proc/list_windows_test.go b/internal/proc/list_windows_test.go new file mode 100644 index 000000000..386d76eca --- /dev/null +++ b/internal/proc/list_windows_test.go @@ -0,0 +1,47 @@ +package proc + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +// The test binary finds itself by its name's start, in another case too, +// with the command line it was started with (#3467). +func TestListFindsItselfWithItsCommandLine(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + prefix := strings.ToUpper(strings.TrimSuffix(filepath.Base(exe), ".exe")) + ps, err := List(context.Background(), prefix) + if err != nil { + t.Fatal(err) + } + for _, p := range ps { + if p.PID == os.Getpid() { + if !strings.Contains(p.Args, "-test.") { + t.Fatalf("own command line = %q, want the test flags in it", p.Args) + } + return + } + } + t.Fatalf("List(%q) = %v, without this process (%d)", prefix, ps, os.Getpid()) +} + +func TestListLeavesOthersOut(t *testing.T) { + ps, err := List(context.Background(), "no-such-program-3467") + if err != nil || len(ps) != 0 { + t.Fatalf("List = %v, %v; want nothing", ps, err) + } +} + +func BenchmarkList(b *testing.B) { + for b.Loop() { + if _, err := List(context.Background(), "codex"); err != nil { + b.Fatal(err) + } + } +}