Skip to content
Myr

util_windows.go

This file

Path

src/util/util_windows.go

226 lines · 6.3 KiB · Go

Last changed by

Terminate child processes on Windows (#4723)PJ Ebybefore adoptionfff7eda

History of this file

Take it

1//go:build windows23package util45import (6	"fmt"7	"os"8	"os/exec"9	"path/filepath"10	"regexp"11	"strings"12	"sync/atomic"13	"syscall"1415	"golang.org/x/sys/windows"16)1718type shellType int1920const (21	shellTypeUnknown shellType = iota22	shellTypeCmd23	shellTypePowerShell24	shellTypePwsh25)2627var escapeRegex = regexp.MustCompile(`[&|<>()^%!"]`)2829type Executor struct {30	shell     string31	shellType shellType32	args      []string33	shellPath atomic.Value34}3536func NewExecutor(withShell string) *Executor {37	shell := os.Getenv("SHELL")38	args := strings.Fields(withShell)39	if len(args) > 0 {40		shell = args[0]41	} else if len(shell) == 0 {42		shell = "cmd"43	}4445	shellType := shellTypeUnknown46	basename := filepath.Base(shell)47	if len(args) > 0 {48		args = args[1:]49	} else if strings.HasPrefix(basename, "cmd") {50		shellType = shellTypeCmd51		args = []string{"/s/c"}52	} else if strings.HasPrefix(basename, "pwsh") {53		shellType = shellTypePwsh54		args = []string{"-NoProfile", "-Command"}55	} else if strings.HasPrefix(basename, "powershell") {56		shellType = shellTypePowerShell57		args = []string{"-NoProfile", "-Command"}58	} else {59		args = []string{"-c"}60	}61	return &Executor{shell: shell, shellType: shellType, args: args}62}6364// ExecCommand executes the given command with $SHELL65//66// On Windows, setpgid controls whether the spawned process is placed in a new67// process group (so that it can be signaled independently, e.g. for previews).68// However, we only do this for "pwsh" and non-standard shells, because cmd.exe69// and Windows PowerShell ("powershell.exe") don't always exit on Ctrl-Break.70//71// NOTE: For "powershell", we should ideally set output encoding to UTF8,72// but it is left as is now because no adverse effect has been observed.73func (x *Executor) ExecCommand(command string, setpgid bool) *exec.Cmd {74	shell := x.shell75	if cached := x.shellPath.Load(); cached != nil {76		shell = cached.(string)77	} else {78		if strings.Contains(shell, "/") {79			out, err := exec.Command("cygpath", "-w", shell).Output()80			if err == nil {81				shell = strings.Trim(string(out), "\n")82			}83		}84		x.shellPath.Store(shell)85	}8687	var creationFlags uint3288	// Set new process group for pwsh (PowerShell 7+) and unknown/posix-ish shells89	if setpgid && (x.shellType == shellTypePwsh || x.shellType == shellTypeUnknown) {90		creationFlags = windows.CREATE_NEW_PROCESS_GROUP91	}9293	var cmd *exec.Cmd94	if x.shellType == shellTypeCmd {95		cmd = exec.Command(shell)96		cmd.SysProcAttr = &syscall.SysProcAttr{97			HideWindow:    false,98			CmdLine:       fmt.Sprintf(`%s "%s"`, strings.Join(x.args, " "), command),99			CreationFlags: creationFlags,100		}101	} else {102		args := x.args103		if setpgid && x.shellType == shellTypePwsh {104			// pwsh needs -NonInteractive flag to exit on Ctrl-Break105			args = append([]string{"-NonInteractive"}, x.args...)106		}107		cmd = exec.Command(shell, append(args, command)...)108		cmd.SysProcAttr = &syscall.SysProcAttr{109			HideWindow:    false,110			CreationFlags: creationFlags,111		}112	}113	return cmd114}115116func (x *Executor) Become(stdin *os.File, environ []string, command string) {117	cmd := x.ExecCommand(command, false)118	cmd.Stdin = stdin119	cmd.Stdout = os.Stdout120	cmd.Stderr = os.Stderr121	cmd.Env = environ122	err := cmd.Start()123	if err != nil {124		fmt.Fprintf(os.Stderr, "fzf (become): %s\n", err.Error())125		os.Exit(127)126	}127	err = cmd.Wait()128	if err != nil {129		if exitError, ok := err.(*exec.ExitError); ok {130			os.Exit(exitError.ExitCode())131		}132	}133	os.Exit(0)134}135136func escapeArg(s string) string {137	b := make([]byte, 0, len(s)+2)138	b = append(b, '"')139	slashes := 0140	for i := 0; i < len(s); i++ {141		c := s[i]142		switch c {143		default:144			slashes = 0145		case '\\':146			slashes++147		case '"':148			for ; slashes > 0; slashes-- {149				b = append(b, '\\')150			}151			b = append(b, '\\')152		}153		b = append(b, c)154	}155	for ; slashes > 0; slashes-- {156		b = append(b, '\\')157	}158	b = append(b, '"')159	return escapeRegex.ReplaceAllStringFunc(string(b), func(match string) string {160		return "^" + match161	})162}163164func (x *Executor) QuoteEntry(entry string) string {165	switch x.shellType {166	case shellTypeCmd:167		/* Manually tested with the following commands:168		   fzf --preview "echo {}"169		   fzf --preview "type {}"170		   echo .git\refs\| fzf --preview "dir {}"171		   echo .git\refs\\| fzf --preview "dir {}"172		   echo .git\refs\\\| fzf --preview "dir {}"173		   reg query HKCU | fzf --reverse --bind "enter:reload(reg query {})"174		   fzf --disabled --preview "echo {q} {n} {}" --query "&|<>()@^%!"175		   fd -H --no-ignore -td -d 4 | fzf --preview "dir {}"176		   fd -H --no-ignore -td -d 4 | fzf --preview "eza {}" --preview-window up177		   fd -H --no-ignore -td -d 4 | fzf --preview "eza --color=always --tree --level=3 --icons=always {}"178		   fd -H --no-ignore -td -d 4 | fzf --preview ".\eza.exe --color=always --tree --level=3 --icons=always {}" --with-shell "powershell -NoProfile -Command"179		*/180		return escapeArg(entry)181	case shellTypePowerShell, shellTypePwsh:182		escaped := strings.ReplaceAll(entry, `"`, `\"`)183		return "'" + strings.ReplaceAll(escaped, "'", "''") + "'"184	default:185		return "'" + strings.ReplaceAll(entry, "'", "'\\''") + "'"186	}187}188189// KillCommand kills the process for the given command190func KillCommand(cmd *exec.Cmd) error {191	// Safely handle nil command or process.192	if cmd == nil || cmd.Process == nil {193		return nil194	}195	// If it has its own process group, we can send it Ctrl-Break196	if cmd.SysProcAttr != nil && cmd.SysProcAttr.CreationFlags&windows.CREATE_NEW_PROCESS_GROUP != 0 {197		if err := windows.GenerateConsoleCtrlEvent(windows.CTRL_BREAK_EVENT, uint32(cmd.Process.Pid)); err == nil {198			return nil199		}200	}201	// If it's the same process group, or if sending the console control event202	// fails (e.g., no console, different console, or process already exited),203	// fall back to a standard kill.  This probably won't *help* if there's I/O204	// going on, because Wait() will still hang until the I/O finishes unless we205	// hard-kill the entire process group.  But it doesn't hurt to try!206	return cmd.Process.Kill()207}208209// IsWindows returns true on Windows210func IsWindows() bool {211	return true212}213214// SetNonblock executes syscall.SetNonblock on file descriptor215func SetNonblock(file *os.File, nonblock bool) {216	syscall.SetNonblock(syscall.Handle(file.Fd()), nonblock)217}218219// Read executes syscall.Read on file descriptor220func Read(fd int, b []byte) (int, error) {221	return syscall.Read(syscall.Handle(fd), b)222}223224func SetStdin(file *os.File) {225	// No-op226}