Files
Reims-Go/internal/host/hypervisor.go
T
Dnyo666 ff99d8d702 feat(host,ui): add opt-in Hyper-V boot switch and hypervisor launch detection (#122)
- Distinguish hypervisor launch disabled (hypervisor_off) from BIOS/UEFI
  virtualization disabled (no_hypervisor) via unprivileged Win32 & DeviceGuard
  probes without spawning background PowerShell/BCD processes
- Add default-off `enable_hypervisor_switch` preference in Settings -> General
  with confirmation modal, active VM/task guards, HVCI notice, same-boot undo,
  and single-UAC System32 execution without auto-restarting Windows
- Update Engine page, first-run Setup, `reims-go doctor`, and VM startprep
  diagnostics for `hypervisor_off` and pending boot states
2026-12-03 13:39:08 +08:00

268 lines
7.1 KiB
Go

package host
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
)
const (
HypervisorBootAuto = "auto"
HypervisorBootOff = "off"
// bootEpochToleranceSec absorbs small wall-clock NTP adjustments when the
// fallback wall-clock boot epoch is used without a kernel volatile boot marker.
bootEpochToleranceSec = 120
pendingBootFileName = "hypervisor-boot-pending.json"
)
// HypervisorExecError reports a non-zero exit code from an elevated Windows
// virtualization configuration command (bcdedit / dism).
type HypervisorExecError struct {
Command string
ExitCode uint32
}
func (e *HypervisorExecError) Error() string {
return fmt.Sprintf("%s exited with code %d (0x%X)", e.Command, e.ExitCode, e.ExitCode)
}
// ClassifyWHPXState maps unprivileged Windows capability probes into a concrete
// WHPX readiness state, distinguishing "hypervisor launch turned off in BCD"
// (where firmware virtualization is still available) from BIOS VT-x/AMD-V off.
func ClassifyWHPXState(dllPresent, hypervisorPresent, firmwareVirtEnabled bool) WHPXState {
if !dllPresent {
return WHPXMissing
}
if hypervisorPresent {
return WHPXReady
}
if firmwareVirtEnabled {
return WHPXHypervisorOff
}
return WHPXNoHypervisor
}
// EvaluateDeviceGuard interprets unprivileged DeviceGuard registry values into
// HVCI (Memory Integrity) and VBS running flags.
func EvaluateDeviceGuard(vbsEnable, hvciEnabled, secureKernelRunning uint32) (hvci, vbs bool) {
hvci = hvciEnabled == 1
vbs = secureKernelRunning == 1 || vbsEnable == 1
return hvci, vbs
}
type bootSession struct {
Marker string
EpochSec int64
TickMs uint64
}
func (s bootSession) valid() bool {
return s.Marker != "" || s.EpochSec > 0
}
type pendingHypervisorRecord struct {
BootMarker string `json:"boot_marker,omitempty"`
BootEpoch int64 `json:"boot_epoch"`
TickMs uint64 `json:"tick_ms,omitempty"`
Target string `json:"target"` // "auto" | "off"
}
var (
pendingBootMu sync.Mutex
pendingBootMem *pendingHypervisorRecord
pendingBootPath string
)
func absInt64(v int64) int64 {
if v < 0 {
return -v
}
return v
}
func sameBootSession(saved pendingHypervisorRecord, cur bootSession) bool {
if !cur.valid() {
return false
}
// Monotonic uptime guard: within a single OS boot session (including across
// S3 sleep or S4 hibernate), GetTickCount64 never goes backwards, whereas a
// fast reboot resets uptime back near zero.
if saved.TickMs > 0 && cur.TickMs > 0 && cur.TickMs < saved.TickMs {
return false
}
if saved.BootMarker != "" && cur.Marker != "" {
return saved.BootMarker == cur.Marker
}
if saved.BootEpoch <= 0 || cur.EpochSec <= 0 {
return false
}
return absInt64(saved.BootEpoch-cur.EpochSec) <= bootEpochToleranceSec
}
// ResolvePendingHypervisorTarget computes the new pending boot target after a
// successful SetHypervisorBootElevated(enable) call against liveState.
// Returning "" means the requested boot state matches the currently running
// state (for example, undoing a pending change before restarting Windows).
func ResolvePendingHypervisorTarget(liveState WHPXState, enable bool) string {
if enable {
if liveState == WHPXReady {
return ""
}
return HypervisorBootAuto
}
if liveState != WHPXReady {
return ""
}
return HypervisorBootOff
}
func pendingBootFilePath(dataRoot string) string {
if dataRoot == "" {
return ""
}
return filepath.Join(dataRoot, "tmp", pendingBootFileName)
}
func writePendingFileAtomic(path string, data []byte) error {
dir := filepath.Dir(path)
f, err := os.CreateTemp(dir, ".hypervisor-pending-*")
if err != nil {
return err
}
tmpName := f.Name()
if _, err := f.Write(data); err != nil {
_ = f.Close()
_ = os.Remove(tmpName)
return err
}
if err := f.Close(); err != nil {
_ = os.Remove(tmpName)
return err
}
if err := os.Rename(tmpName, path); err != nil {
_ = os.Remove(tmpName)
return err
}
return nil
}
// RecordPendingHypervisorBoot records (or clears) the pending hypervisor boot
// mode for the current OS boot session. If <dataRoot>/tmp already exists, it is
// also persisted atomically there so reopening Reims-Go before restarting
// Windows retains the indicator without writing to uninitialized paths.
func RecordPendingHypervisorBoot(dataRoot string, liveState WHPXState, enable bool) string {
return recordPendingHypervisorBootSession(dataRoot, liveState, enable, currentBootSession())
}
func recordPendingHypervisorBootAt(dataRoot string, liveState WHPXState, enable bool, bootEpoch int64) string {
return recordPendingHypervisorBootSession(dataRoot, liveState, enable, bootSession{EpochSec: bootEpoch})
}
func recordPendingHypervisorBootSession(dataRoot string, liveState WHPXState, enable bool, sess bootSession) string {
target := ResolvePendingHypervisorTarget(liveState, enable)
pendingBootMu.Lock()
defer pendingBootMu.Unlock()
p := pendingBootFilePath(dataRoot)
if target == "" || !sess.valid() {
pendingBootMem = nil
if p != "" {
_ = os.Remove(p)
}
if pendingBootPath != "" && pendingBootPath != p {
_ = os.Remove(pendingBootPath)
}
pendingBootPath = ""
return ""
}
rec := pendingHypervisorRecord{
BootMarker: sess.Marker,
BootEpoch: sess.EpochSec,
TickMs: sess.TickMs,
Target: target,
}
pendingBootMem = &rec
if p != "" {
tmpDir := filepath.Dir(p)
if st, err := os.Stat(tmpDir); err == nil && st.IsDir() {
if raw, merr := json.Marshal(rec); merr == nil {
if writePendingFileAtomic(p, append(raw, '\n')) == nil {
if pendingBootPath != "" && pendingBootPath != p {
_ = os.Remove(pendingBootPath)
}
pendingBootPath = p
}
}
}
}
return target
}
// ReadPendingHypervisorBoot returns "auto", "off", or "" for the current Windows
// boot session. Read-only: never creates directories or writes files during Inspect.
func ReadPendingHypervisorBoot(dataRoot string, liveState WHPXState) string {
return readPendingHypervisorBootSession(dataRoot, liveState, currentBootSession())
}
func readPendingHypervisorBootAt(dataRoot string, liveState WHPXState, bootEpoch int64) string {
return readPendingHypervisorBootSession(dataRoot, liveState, bootSession{EpochSec: bootEpoch})
}
func readPendingHypervisorBootSession(dataRoot string, liveState WHPXState, sess bootSession) string {
if !sess.valid() {
return ""
}
validTarget := func(rec pendingHypervisorRecord) string {
if !sameBootSession(rec, sess) {
return ""
}
switch rec.Target {
case HypervisorBootAuto:
if liveState == WHPXReady {
return ""
}
return HypervisorBootAuto
case HypervisorBootOff:
if liveState != WHPXReady {
return ""
}
return HypervisorBootOff
default:
return ""
}
}
pendingBootMu.Lock()
if pendingBootMem != nil {
t := validTarget(*pendingBootMem)
if t == "" {
pendingBootMem = nil
pendingBootPath = ""
}
pendingBootMu.Unlock()
if t != "" {
return t
}
} else {
pendingBootMu.Unlock()
}
p := pendingBootFilePath(dataRoot)
if p == "" {
return ""
}
raw, err := os.ReadFile(p)
if err != nil {
return ""
}
var rec pendingHypervisorRecord
if json.Unmarshal(raw, &rec) != nil {
return ""
}
return validTarget(rec)
}