Files
Reims-Go/internal/host/host_windows.go
T
NwflowerandClaude Opus 5.5 c0f08be124 feat: per-VM CPU affinity, disk snapshots, SSH helpers and VM window actions
Backend
- Per-VM CPU affinity (vmstart/affinity.go, affinity_flow.go): modes auto /
  all / P-cores / non-LP-E / custom, saved in the VM folder, applied to the
  QEMU process on start (GUI and CLI) and live via SetVMAffinity; copied on
  clone. Start summary logs the resolved mapping. Host report gains CPU
  topology helpers (mask <-> CPU list).
- Offline qcow2 restore points via qemu-img (driver/reims/snapshot.go,
  snapshot_flow.go): list / create / restore / delete.
- SSH helpers (ssh_flow.go): remembered user, open a terminal, write an
  ~/.ssh/config entry, open VS Code Remote-SSH.
- FocusVMWindow brings the QEMU window forward (restoring it if minimized);
  CopyVMScreenshot copies a full-resolution frame to the clipboard.
- DeliverPathsToGuest copies dropped host files into the shared folder;
  main.go enables Wails file drop on elements marked --wails-drop-target.
- VM note (.reims-go-note) and a storage breakdown (extras_flow.go).

Frontend
- VM page: running state's "Show Window" and the screen preview use
  FocusVMWindow; camera button and More-menu item copy a screenshot;
  editable note under the name; SSH row shows the saved user with
  Terminal / config / VS Code actions; restore-point list; install guide
  steps can be ticked off; drop files onto the page to send them.
- Sidebar right-click menu per VM (start, show window, screenshot, stop,
  restart, settings, folders, clone, delete); double-click and Ctrl+Enter
  still run the main action.
- AffinityDialog opened from the VM menu and VM settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:00:48 -07:00

547 lines
16 KiB
Go

//go:build windows
package host
import (
"encoding/binary"
"fmt"
"math/bits"
"path/filepath"
"runtime"
"sort"
"strings"
"syscall"
"unsafe"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx")
procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx")
procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW")
procDeviceIoControl = kernel32.NewProc("DeviceIoControl")
procOpenProcess = kernel32.NewProc("OpenProcess")
procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask")
procGetProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask")
procSetProcessInformation = kernel32.NewProc("SetProcessInformation")
procCloseHandle = kernel32.NewProc("CloseHandle")
advapi32 = syscall.NewLazyDLL("advapi32.dll")
procRegOpenKeyExW = advapi32.NewProc("RegOpenKeyExW")
procRegQueryValueExW = advapi32.NewProc("RegQueryValueExW")
procRegCloseKey = advapi32.NewProc("RegCloseKey")
shell32 = syscall.NewLazyDLL("shell32.dll")
procShellExecuteW = shell32.NewProc("ShellExecuteW")
)
const (
hkeyLocalMachine = 0x80000002
keyRead = 0x20019
regSZ = 1
regExpandSZ = 2
regMultiSZ = 7
processSetInformation = 0x0200
processQueryLimitedInformation = 0x1000
processPowerThrottlingClass = 4
powerThrottlingCurrentVersion = 1
powerThrottlingExecutionSpeed = 0x1
whvCapHypervisorPresent = 0x00000001
)
type memoryStatusEx struct {
Length uint32
MemoryLoad uint32
TotalPhys uint64
AvailPhys uint64
TotalPageFile uint64
AvailPageFile uint64
TotalVirtual uint64
AvailVirtual uint64
AvailExtendedVirtual uint64
}
// Inspect collects Windows host capabilities without requiring administrator privileges.
func Inspect(dataRoot string) Report {
rep := Report{
OS: "windows",
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
DataRoot: dataRoot,
WHPX: probeWHPX(),
NeedsColdRebootWorkaround: probeNeedsColdRebootWorkaround(),
GPUs: probeVulkanGPUs(),
}
if rep.WHPX == WHPXReady {
rep.WHPXCaps = probeWHPXCapabilities()
}
rep.RecommendedGPU = PickRecommendedGPU(rep.GPUs)
if topo, ok := probeHybridTopology(); ok {
rep.PhysicalCores = topo.phys
rep.PCoreCount = topo.pCount
rep.ECoreCount = topo.eCount
rep.LPECoreCount = topo.lpeCount
rep.HasHybridCores = topo.eCount > 0 || topo.lpeCount > 0
rep.PCoreMask = topo.pMask
rep.PCoreMaskHex = fmt.Sprintf("0x%X", topo.pMask)
rep.PCoreLogicalCPUs = topo.pLPs
rep.ECoreLogicalCPUs = topo.eLPs
if topo.lpeCount > 0 && topo.nonLPEMask > 0 {
rep.NonLPEMask = topo.nonLPEMask
rep.NonLPEMaskHex = fmt.Sprintf("0x%X", topo.nonLPEMask)
rep.NonLPELogicalCPUs = topo.nonLPELPs
}
rep.CPUTopology = topo.cpus
}
if len(rep.CPUTopology) == 0 {
rep.CPUTopology = DefaultCPUTopology(rep.LogicalCPUs)
}
if totalGB, availGB, ok := probeMemoryGB(); ok {
rep.TotalRAMGB = totalGB
rep.AvailRAMGB = availGB
}
if ms, ok := memoryStatus(); ok {
rep.MemoryLoadPct = int(ms.MemoryLoad)
}
if limitGB, availGB, ok := probeCommitGB(); ok {
rep.CommitLimitGB = limitGB
rep.CommitAvailGB = availGB
}
if freeGB, ok := probeFreeDiskGB(dataRoot); ok {
rep.FreeDiskGB = freeGB
}
rep.DataRootDriveType = probeDriveType(dataRoot)
rep.Displays = probeDisplays()
rep.PrimaryDisplay = PrimaryDisplayOf(rep.Displays)
rep.DisplayPresets, rep.RecommendedResolution = RecommendDisplayPresets(rep.PrimaryDisplay)
rep.HiDPIAdvice = HiDPIAdvice(rep.PrimaryDisplay, rep.DisplayPresets)
rep.FullscreenHiDPI = FullscreenStartsHiDPI(rep.PrimaryDisplay)
rep.ProcessorScheduling = probeProcessorScheduling()
rep.Audio = ProbeAudio()
return rep
}
// PinProcessToPCores restricts the given PID's affinity mask to the given bitmask.
func PinProcessToPCores(pid uint32, mask uint64) error {
return SetProcessAffinityMask(pid, mask)
}
// SetProcessAffinityMask sets the Win32 processor affinity mask for pid.
func SetProcessAffinityMask(pid uint32, mask uint64) error {
if mask == 0 {
return fmt.Errorf("invalid affinity mask 0")
}
h, _, err := procOpenProcess.Call(uintptr(processSetInformation), 0, uintptr(pid))
if h == 0 {
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
r, _, err := procSetProcessAffinityMask.Call(h, uintptr(mask))
if r == 0 {
return fmt.Errorf("SetProcessAffinityMask(%d, 0x%X): %w", pid, mask, err)
}
return nil
}
// GetProcessAffinityMask reads the current process and system affinity masks for pid.
func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) {
h, _, err := procOpenProcess.Call(uintptr(processQueryLimitedInformation), 0, uintptr(pid))
if h == 0 {
return 0, 0, fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
var procMask, sysMask uintptr
r, _, err := procGetProcessAffinityMask.Call(
h,
uintptr(unsafe.Pointer(&procMask)),
uintptr(unsafe.Pointer(&sysMask)),
)
if r == 0 {
return 0, 0, fmt.Errorf("GetProcessAffinityMask(%d): %w", pid, err)
}
return uint64(procMask), uint64(sysMask), nil
}
type processPowerThrottlingState struct {
Version uint32
ControlMask uint32
StateMask uint32
}
// DisableProcessPowerThrottling opts pid out of Windows EcoQoS execution-speed
// power throttling so background / unfocused QEMU threads are not parked onto
// efficiency or LP-E cores by the scheduler.
func DisableProcessPowerThrottling(pid uint32) error {
if err := procSetProcessInformation.Find(); err != nil {
return err
}
h, _, err := procOpenProcess.Call(uintptr(processSetInformation), 0, uintptr(pid))
if h == 0 {
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
state := processPowerThrottlingState{
Version: powerThrottlingCurrentVersion,
ControlMask: powerThrottlingExecutionSpeed,
StateMask: 0,
}
r, _, err := procSetProcessInformation.Call(
h,
uintptr(processPowerThrottlingClass),
uintptr(unsafe.Pointer(&state)),
uintptr(unsafe.Sizeof(state)),
)
if r == 0 {
return fmt.Errorf("SetProcessInformation(ProcessPowerThrottling, %d): %w", pid, err)
}
return nil
}
// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows Hypervisor Platform.
func EnableWHPXElevated() error {
verb, _ := syscall.UTF16PtrFromString("runas")
file, _ := syscall.UTF16PtrFromString("powershell.exe")
params, _ := syscall.UTF16PtrFromString(`-NoProfile -Command "Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All -NoRestart; Write-Host 'Done. Please restart Windows.'; Start-Sleep -Seconds 3"`)
r, _, err := procShellExecuteW.Call(
0,
uintptr(unsafe.Pointer(verb)),
uintptr(unsafe.Pointer(file)),
uintptr(unsafe.Pointer(params)),
0,
1, // SW_SHOWNORMAL
)
if r <= 32 {
return fmt.Errorf("ShellExecuteW runas failed (code %d): %w", r, err)
}
return nil
}
func probeWHPX() WHPXState {
mod := syscall.NewLazyDLL("WinHvPlatform.dll")
if err := mod.Load(); err != nil {
return WHPXMissing
}
proc := mod.NewProc("WHvGetCapability")
if err := proc.Find(); err != nil {
return WHPXMissing
}
var capVal uint64
var written uint32
hr, _, _ := proc.Call(
uintptr(whvCapHypervisorPresent),
uintptr(unsafe.Pointer(&capVal)),
uintptr(unsafe.Sizeof(capVal)),
uintptr(unsafe.Pointer(&written)),
)
if int32(hr) < 0 {
return WHPXNoHypervisor
}
if capVal&1 != 0 {
return WHPXReady
}
return WHPXNoHypervisor
}
// probeNeedsColdRebootWorkaround reports true on Windows hosts whose WinHvPlatform.dll
// does not export WHvResetPartition (e.g. Windows 10 19045), where in-guest warm reboots
// stall with WHPX Unexpected VP exit code 4 unless QEMU exits via -no-reboot and is
// cold-restarted in a fresh Hyper-V partition.
func probeNeedsColdRebootWorkaround() bool {
mod := syscall.NewLazyDLL("WinHvPlatform.dll")
if err := mod.Load(); err != nil {
return false
}
return mod.NewProc("WHvResetPartition").Find() != nil
}
type hybridTopology struct {
phys int
pCount int
eCount int
lpeCount int
pMask uint64
nonLPEMask uint64
pLPs []int
eLPs []int
nonLPELPs []int
cpus []LogicalCPUInfo
}
func probeHybridTopology() (topo hybridTopology, ok bool) {
var bufLen uint32
procGetLogicalProcessorInformationEx.Call(0, 0, uintptr(unsafe.Pointer(&bufLen)))
if bufLen == 0 {
return
}
buf := make([]byte, bufLen)
r, _, _ := procGetLogicalProcessorInformationEx.Call(
0, // RelationProcessorCore
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(&bufLen)),
)
if r == 0 {
return
}
type coreRec struct {
eff byte
mask uint64
}
var cores []coreRec
effSet := make(map[byte]bool)
var maxEff byte
var minEff byte = 0xFF
for off := uint32(0); off+48 <= bufLen; {
size := binary.LittleEndian.Uint32(buf[off+4 : off+8])
if size < 48 || off+size > bufLen {
break
}
eff := buf[off+9]
mask := binary.LittleEndian.Uint64(buf[off+32 : off+40])
if eff > maxEff {
maxEff = eff
}
if eff < minEff {
minEff = eff
}
effSet[eff] = true
cores = append(cores, coreRec{eff: eff, mask: mask})
off += size
}
if len(cores) == 0 {
return
}
hasThreeTiers := len(effSet) >= 3
isHybrid := len(effSet) >= 2
topo.phys = len(cores)
var eMask uint64
for coreIdx, c := range cores {
tier := "standard"
switch {
case c.eff == maxEff:
topo.pCount++
topo.pMask |= c.mask
topo.nonLPEMask |= c.mask
if isHybrid {
tier = "p"
}
case hasThreeTiers && c.eff == minEff:
topo.lpeCount++
tier = "lpe"
default:
topo.eCount++
eMask |= c.mask
topo.nonLPEMask |= c.mask
tier = "e"
}
smt := bits.OnesCount64(c.mask) > 1
for i := 0; i < 64; i++ {
if c.mask&(uint64(1)<<uint(i)) != 0 {
topo.cpus = append(topo.cpus, LogicalCPUInfo{
Index: i,
CoreIndex: coreIdx,
Tier: tier,
SMT: smt,
})
}
}
}
sort.Slice(topo.cpus, func(i, j int) bool {
return topo.cpus[i].Index < topo.cpus[j].Index
})
if !hasThreeTiers {
topo.nonLPEMask = 0
}
for i := 0; i < 64; i++ {
bit := uint64(1) << uint(i)
if topo.pMask&bit != 0 {
topo.pLPs = append(topo.pLPs, i)
}
if eMask&bit != 0 {
topo.eLPs = append(topo.eLPs, i)
}
if topo.nonLPEMask&bit != 0 {
topo.nonLPELPs = append(topo.nonLPELPs, i)
}
}
ok = true
return
}
func probeMemoryGB() (totalGB, availGB float64, ok bool) {
ms, ok := memoryStatus()
if !ok {
return 0, 0, false
}
const gb = 1024 * 1024 * 1024
return float64(ms.TotalPhys) / gb, float64(ms.AvailPhys) / gb, true
}
// probeCommitGB reads the system commit limit and what is still free in it.
// GlobalMemoryStatusEx's "page file" fields are the commit limit and the
// available commit for the system (not the page file alone).
func probeCommitGB() (limitGB, availGB float64, ok bool) {
ms, ok := memoryStatus()
if !ok {
return 0, 0, false
}
const gb = 1024 * 1024 * 1024
return float64(ms.TotalPageFile) / gb, float64(ms.AvailPageFile) / gb, true
}
func memoryStatus() (memoryStatusEx, bool) {
var ms memoryStatusEx
ms.Length = uint32(unsafe.Sizeof(ms))
r, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&ms)))
return ms, r != 0
}
// CommitAvailGB is the commit memory free right now (for start-time checks).
func CommitAvailGB() (float64, bool) {
_, avail, ok := probeCommitGB()
return avail, ok
}
func probeFreeDiskGB(path string) (float64, bool) {
vol := filepath.VolumeName(path)
if vol != "" {
path = vol + `\`
}
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return 0, false
}
var freeBytesAvail, totalBytes, totalFree uint64
r, _, _ := procGetDiskFreeSpaceExW.Call(
uintptr(unsafe.Pointer(p)),
uintptr(unsafe.Pointer(&freeBytesAvail)),
uintptr(unsafe.Pointer(&totalBytes)),
uintptr(unsafe.Pointer(&totalFree)),
)
if r == 0 {
return 0, false
}
return float64(freeBytesAvail) / (1024 * 1024 * 1024), true
}
// probeDriveType detects whether path resides on a local fixed drive, USB
// external enclosure (via IOCTL_STORAGE_QUERY_PROPERTY BusTypeUsb=7),
// removable drive, or network share. Requires no admin privileges.
func probeDriveType(path string) string {
vol := filepath.VolumeName(path)
if vol == "" {
return "unknown"
}
root := vol + `\`
p, err := syscall.UTF16PtrFromString(root)
if err != nil {
return "unknown"
}
dt, _, _ := procGetDriveTypeW.Call(uintptr(unsafe.Pointer(p)))
switch dt {
case 2: // DRIVE_REMOVABLE
return "removable"
case 4: // DRIVE_REMOTE
return "network"
case 3: // DRIVE_FIXED
if isUSBBusVolume(vol) {
return "usb"
}
return "fixed"
default:
return "unknown"
}
}
func isUSBBusVolume(vol string) bool {
if len(vol) < 2 || vol[1] != ':' {
return false
}
devPath, err := syscall.UTF16PtrFromString(`\\.\` + vol[:2])
if err != nil {
return false
}
// Access = 0 allows metadata IOCTLs (IOCTL_STORAGE_QUERY_PROPERTY) without elevation.
h, err := syscall.CreateFile(devPath, 0, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE, nil, syscall.OPEN_EXISTING, 0, 0)
if err != nil || h == syscall.InvalidHandle {
return false
}
defer syscall.CloseHandle(h)
const ioctlStorageQueryProperty = 0x002D1400
var query [12]byte // STORAGE_PROPERTY_QUERY: PropertyId=0 (StorageDeviceProperty), QueryType=0
var out [512]byte
var returned uint32
r, _, _ := procDeviceIoControl.Call(
uintptr(h),
ioctlStorageQueryProperty,
uintptr(unsafe.Pointer(&query[0])),
uintptr(len(query)),
uintptr(unsafe.Pointer(&out[0])),
uintptr(len(out)),
uintptr(unsafe.Pointer(&returned)),
0,
)
if r == 0 || returned < 32 {
return false
}
// STORAGE_DEVICE_DESCRIPTOR.BusType is a 4-byte enum at offset 28; BusTypeUsb == 7.
busType := binary.LittleEndian.Uint32(out[28:32])
return busType == 7
}
func probeVulkanGPUs() []GPUInfo {
const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`
var out []GPUInfo
for i := 0; i < 32; i++ {
sub := fmt.Sprintf(`%s\%04d`, baseKey, i)
desc, okDesc := regReadString(hkeyLocalMachine, sub, "DriverDesc")
if !okDesc || desc == "" {
continue
}
icd, _ := regReadString(hkeyLocalMachine, sub, "VulkanDriverName")
if icd == "" {
continue
}
out = append(out, GPUInfo{
Name: desc,
VulkanICD: icd,
Kind: ClassifyGPU(desc),
})
}
return out
}
func regReadString(root uintptr, subKey, valueName string) (string, bool) {
sk, err := syscall.UTF16PtrFromString(subKey)
if err != nil {
return "", false
}
var hKey uintptr
r, _, _ := procRegOpenKeyExW.Call(root, uintptr(unsafe.Pointer(sk)), 0, keyRead, uintptr(unsafe.Pointer(&hKey)))
if r != 0 {
return "", false
}
defer procRegCloseKey.Call(hKey)
vn, err := syscall.UTF16PtrFromString(valueName)
if err != nil {
return "", false
}
var typ, size uint32
r, _, _ = procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), 0, uintptr(unsafe.Pointer(&size)))
if r != 0 || size == 0 {
return "", false
}
buf := make([]uint16, (size+1)/2)
r, _, _ = procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size)))
if r != 0 {
return "", false
}
if typ != regSZ && typ != regExpandSZ && typ != regMultiSZ {
return "", false
}
// For REG_MULTI_SZ, take the first NUL-terminated entry (64-bit Vulkan ICD JSON).
return strings.TrimSpace(syscall.UTF16ToString(buf)), true
}