diff --git a/internal/proc/find.go b/internal/proc/find.go index b1b92922e..0a2d62c4a 100644 --- a/internal/proc/find.go +++ b/internal/proc/find.go @@ -2,7 +2,6 @@ package proc import ( "os" - "os/exec" "path/filepath" "runtime" "strings" @@ -20,10 +19,14 @@ import ( // size and time. func FindTool(name string) string { return Unwrap(name, looked("find\x00"+name, func() lookAnswer { - if p, err := exec.LookPath(name); err == nil { + if p, err := lookPath(name); err == nil { return lookAnswer{path: p} } - return lookAnswer{path: toolIn(name, runtime.GOOS, findDirs())} + dirs := findDirs() + if !mayBeIn(name, dirs) { + return lookAnswer{} + } + return lookAnswer{path: toolIn(name, runtime.GOOS, dirs)} }).path) } diff --git a/internal/proc/listing.go b/internal/proc/listing.go new file mode 100644 index 000000000..065b81e2b --- /dev/null +++ b/internal/proc/listing.go @@ -0,0 +1,164 @@ +package proc + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "time" +) + +// A command that isn't installed was looked for with a stat of every +// name it could have (11 PATHEXT extensions on Windows) in every folder +// of PATH and of findDirs: hundreds of stats a command, and the Library +// and Agents pages ask for about a hundred agents' commands. The answers +// are kept (looked), but every one of them is asked again when any of +// those folders changes, and at the app's start, so the first change on +// the Library page after a start, or after some folder on PATH changed +// while it sat idle, took 5–8s on a Windows machine with 11 agents and an +// antivirus that slows each stat (#1624, Hipple). Each folder's listing is +// read once instead and kept while its modification time is unchanged: a +// command none of them has a name for isn't there, without a stat of its +// own; one that may be is looked for as before. + +// listingRead is how many folders were read, and execLookPath what looks +// for a command that may be there; the tests count both. +var ( + listingRead int + execLookPath = exec.LookPath +) + +var listings struct { + sync.Mutex + m map[string]*listing +} + +type listing struct { + mod time.Time + checked time.Time + // names are the folder's entries, lower-cased, each also as it is up + // to each dot in it: claude.exe is there as "claude" and "claude.exe" + names map[string]bool +} + +// mayBeIn is whether name could be a program in one of dirs: false only +// when every folder was read and none has an entry name could be (name, +// or name and an extension, in any case). A folder that can't be read +// may have it. +func mayBeIn(name string, dirs []string) bool { + if name == "" || strings.ContainsAny(name, `/\:`) { + return true + } + key := strings.ToLower(name) + for _, d := range dirs { + if d == "" { + continue + } + if !filepath.IsAbs(d) { + abs, err := filepath.Abs(d) + if err != nil { + return true + } + d = abs + } + names, ok := listed(d) + if !ok || names[key] { + return true + } + } + return false +} + +// listed is the names in dir, read again when its modification time +// changed (checked once a lookWindow); false when it can't be read. +func listed(dir string) (map[string]bool, bool) { + now := time.Now() + listings.Lock() + l := listings.m[dir] + if l != nil && now.Sub(l.checked) < lookWindow() { + listings.Unlock() + return l.names, true + } + listings.Unlock() + st, err := os.Stat(dir) + if errors.Is(err, os.ErrNotExist) { + // nothing is in a folder that isn't there + listings.Lock() + if listings.m == nil { + listings.m = map[string]*listing{} + } + listings.m[dir] = &listing{checked: now} + listings.Unlock() + return nil, true + } + if err != nil || !st.IsDir() { + return nil, false + } + if l != nil && l.names != nil && l.mod.Equal(st.ModTime()) { + listings.Lock() + l.checked = now + listings.Unlock() + return l.names, true + } + es, err := os.ReadDir(dir) + if err != nil { + return nil, false + } + names := make(map[string]bool, len(es)) + for _, e := range es { + n := strings.ToLower(e.Name()) + names[n] = true + for i := 1; i < len(n); i++ { + if n[i] == '.' { + names[n[:i]] = true + } + } + } + listings.Lock() + if listings.m == nil { + listings.m = map[string]*listing{} + } + listings.m[dir] = &listing{mod: st.ModTime(), checked: now, names: names} + listingRead++ + listings.Unlock() + return names, true +} + +// pathDirs are the folders exec.LookPath looks in: PATH's (an empty +// entry the current folder, but on Windows), and on Windows the current +// folder first unless NoDefaultCurrentDirectoryInExePath is set. +func pathDirs() []string { + dirs := filepath.SplitList(os.Getenv("PATH")) + if runtime.GOOS != "windows" { + // an empty entry is the current folder there + for i, d := range dirs { + if d == "" { + dirs[i] = "." + } + } + } else { + if _, off := os.LookupEnv("NoDefaultCurrentDirectoryInExePath"); !off { + dirs = append([]string{"."}, dirs...) + } + } + return dirs +} + +// lookPath is exec.LookPath, with a command no folder of PATH has a name +// for answered as not found without looking. +func lookPath(name string) (string, error) { + if !mayBeIn(name, pathDirs()) { + return "", &exec.Error{Name: name, Err: exec.ErrNotFound} + } + return execLookPath(name) +} + +// forgetListings drops the folders read. +func forgetListings() { + listings.Lock() + listings.m = nil + listings.Unlock() +} diff --git a/internal/proc/listing_test.go b/internal/proc/listing_test.go new file mode 100644 index 000000000..2eca8b7b6 --- /dev/null +++ b/internal/proc/listing_test.go @@ -0,0 +1,111 @@ +package proc + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" +) + +// countLooks counts the commands looked for on PATH for real, from here on. +func countLooks(t *testing.T) *int { + n := 0 + old := execLookPath + execLookPath = func(name string) (string, error) { n++; return old(name) } + t.Cleanup(func() { execLookPath = old }) + return &n +} + +// A command that isn't installed is answered from each PATH folder's +// listing, read once: before, each was a stat of every name it could have +// in every folder, asked again for about a hundred agents whenever any +// folder changed, and the Library's first change after a start or an idle +// spell took 5–8s on Windows (#1624, Hipple). +func TestMissingCommandsReadEachFolderOnce(t *testing.T) { + var dirs []string + for i := 0; i < 40; i++ { + d := t.TempDir() + os.WriteFile(filepath.Join(d, fmt.Sprintf("tool%d.exe", i)), []byte("x"), 0o755) + dirs = append(dirs, d) + } + t.Setenv("PATH", joinList(dirs)) + t.Setenv("NoDefaultCurrentDirectoryInExePath", "1") + lookWindowFor(t, lookFresh) + looks := countLooks(t) + read := listingRead + for i := 0; i < 100; i++ { + name := fmt.Sprintf("magpie-missing-%d", i) + if p, err := Look(name); err == nil { + t.Fatalf("%s found at %s", name, p) + } else if !isNotFound(err) { + t.Fatalf("%s: %v, want exec.ErrNotFound", name, err) + } + if p := FindTool(name); p != "" { + t.Fatalf("FindTool %s = %s", name, p) + } + } + if *looks != 0 { + t.Errorf("100 missing commands were looked for on PATH %d times, want 0", *looks) + } + if got := listingRead - read; got > len(dirs)+len(findDirs())+1 { + t.Errorf("read %d folders for 100 commands, want each of the %d once", got, len(dirs)) + } +} + +// One that is there, under any of its extensions or another case, is +// looked for as before. +func TestCommandListedIsLookedFor(t *testing.T) { + d := t.TempDir() + t.Setenv("PATH", d) + lookWindowFor(t, 0) + want := installTool(t, d, "magpie-fake-agent") + looks := countLooks(t) + if p, err := Look("magpie-fake-agent"); err != nil || p != want { + t.Fatalf("Look = %q, %v; want %q", p, err, want) + } + if *looks != 1 { + t.Fatalf("looked %d times, want 1", *looks) + } + for _, n := range []string{"magpie-fake-agent.cmd", "Magpie-Fake-Agent.EXE"} { + os.WriteFile(filepath.Join(d, n), nil, 0o755) + if !mayBeIn("magpie-fake-agent", []string{d}) { + t.Errorf("with %s there, magpie-fake-agent isn't thought to be", n) + } + } +} + +// A folder that can't be read may hold the command: it is looked for. +func TestUnreadableFolderMayHoldIt(t *testing.T) { + if runtime.GOOS == "windows" || os.Getuid() == 0 { + t.Skip("needs a folder this user can't list") + } + d := t.TempDir() + installTool(t, d, "magpie-fake-agent") + if err := os.Chmod(d, 0o311); err != nil { // searchable, not listable + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(d, 0o755) }) + t.Setenv("PATH", d) + lookWindowFor(t, 0) + if _, err := Look("magpie-fake-agent"); err != nil { + t.Fatalf("a command in a folder that can't be listed wasn't found: %v", err) + } +} + +func joinList(dirs []string) string { + s := "" + for i, d := range dirs { + if i > 0 { + s += string(os.PathListSeparator) + } + s += d + } + return s +} + +func isNotFound(err error) bool { + e, ok := err.(*exec.Error) + return ok && e.Err == exec.ErrNotFound +} diff --git a/internal/proc/look.go b/internal/proc/look.go index 92b86fd72..1b5c1c55f 100644 --- a/internal/proc/look.go +++ b/internal/proc/look.go @@ -2,7 +2,6 @@ package proc import ( "os" - "os/exec" "path/filepath" "runtime" "strconv" @@ -59,7 +58,7 @@ func LookPath(name string) (string, error) { // answer kept while the PATH folders are unchanged. func Look(name string) (string, error) { a := looked("look\x00"+name, func() lookAnswer { - p, err := exec.LookPath(name) + p, err := lookPath(name) return lookAnswer{p, err} }) return a.path, a.err @@ -72,6 +71,7 @@ func Forget() { looks.m, looks.env, looks.stamp, looks.checked = nil, "", "", time.Time{} looks.gen++ looks.Unlock() + forgetListings() } // looked is the answer kept for key, or ask's, kept.