| 1 | package vm |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | "syscall" |
| 12 | "time" |
| 13 | |
| 14 | "golang.org/x/sys/windows" |
| 15 | ) |
| 16 | |
| 17 | func isWindowsQEMU(pid int, dir, name string) bool { |
| 18 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 19 | defer cancel() |
| 20 | root := os.Getenv("SystemRoot") |
| 21 | if root == "" { |
| 22 | root = `C:\Windows` |
| 23 | } |
| 24 | cmd := exec.CommandContext(ctx, filepath.Join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), "-NoProfile", "-NonInteractive", "-Command", |
| 25 | `[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); (Get-CimInstance Win32_Process -Filter 'ProcessId=`+strconv.Itoa(pid)+`').CommandLine | ConvertTo-Json -Compress`) |
| 26 | cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} |
| 27 | out, err := cmd.Output() |
| 28 | if err != nil { |
| 29 | return false |
| 30 | } |
| 31 | var command string |
| 32 | if json.Unmarshal(out, &command) != nil { |
| 33 | return false |
| 34 | } |
| 35 | return windowsQEMUCommandMatches(command, dir, name) |
| 36 | } |
| 37 | |
| 38 | func windowsQEMUCommandMatches(command, dir, name string) bool { |
| 39 | args, err := windows.DecomposeCommandLine(command) |
| 40 | if err != nil || len(args) == 0 || !strings.EqualFold(filepath.Base(args[0]), "qemu-system-x86_64.exe") { |
| 41 | return false |
| 42 | } |
| 43 | gotName, gotPID := false, false |
| 44 | for i := 1; i+1 < len(args); i++ { |
| 45 | switch args[i] { |
| 46 | case "-name": |
| 47 | gotName = args[i+1] == "lima-"+name |
| 48 | i++ |
| 49 | case "-pidfile": |
| 50 | gotPID = strings.EqualFold(filepath.Clean(args[i+1]), filepath.Join(dir, "qemu.pid")) |
| 51 | i++ |
| 52 | } |
| 53 | } |
| 54 | return gotName && gotPID |
| 55 | } |