// Package startprep runs macOS VM pre-launch checks and OpenCore/disk // preparation shared by the desktop window and direct CLI launches. package startprep import ( "context" "fmt" "io" "os" "path/filepath" "strings" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/macos/opencore" "github.com/Nwflower/reims-go/internal/macos/reims" rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/vmstart" ) // Prep runs start preparation against the active runtime. Log receives one // human-readable line per step; the GUI routes it to the VM's log panel, the // CLI to stderr. type Prep struct { Client *reims.Client Runtime rt.Installed // SkipWHPXFallback mirrors the whpx_fallback setting on builtin.guest.macos being off. SkipWHPXFallback bool cfg config.Config log func(string) } // New resolves the active runtime for cfg. It fails when none is installed. func New(cfg config.Config, log func(string)) (*Prep, error) { active, err := rt.ResolveActive(&cfg) if err != nil || active == nil { return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed")) } if log == nil { log = func(string) {} } return &Prep{Client: reims.NewClient(&cfg, *active), Runtime: *active, cfg: cfg, log: log}, nil } // CheckWHPX refuses to start a VM when Windows Hypervisor Platform is not // ready. Without it QEMU aborts with "WHPX: No accelerator found, hr=00000000" // followed by "failed to initialize whpx: No space left on device" (-ENOSPC), // which misleads users into checking disk space. func (p *Prep) CheckWHPX(rep host.Report) error { switch rep.WHPX { case host.WHPXReady: return nil case host.WHPXMissing: return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_missing")) case host.WHPXNoHypervisor: return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_no_hypervisor")) default: return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_unsupported")) } } // CheckMemory refuses to start a VM whose guest RAM cannot be committed right // now, avoiding QEMU's opaque "Cannot set up guest memory 'ram'" exit. func (p *Prep) CheckMemory(memory string, rep host.Report) error { avail, ok := host.CommitAvailGB() if !ok { return nil } memGB, ok := reims.ParseSizeGB(memory) if !ok || memGB+host.StartMarginGB <= avail { return nil } return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.commit_memory", memGB+host.StartMarginGB, memGB, avail, host.RecommendedMemoryGB(rep))) } // Prepare brings a stopped VM's configuration up to date before it starts: // the offline-install helper disk, the recovery boot picker, the macOS // language preset and the WHPX nested-virtualization fallback. cur is updated // to match what was written through `reims-ctl set`. func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { if stripped := reims.StripIncomingDeferArgs(cur.ExtraArgs); stripped != cur.ExtraArgs { if err := p.setExtraArgs(ctx, name, stripped); err == nil { cur.ExtraArgs = stripped } } p.syncOfflineHelper(ctx, name, cur) p.syncRecoveryBootPicker(ctx, name, cur) p.ReplayGuestLang(ctx, cur.Directory) if !p.SkipWHPXFallback { p.applyProbedWHPXCompat(ctx, name, rep, cur) } p.syncHostMemorySMBIOS(ctx, name, rep, cur) } func (p *Prep) syncHostMemorySMBIOS(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { if !p.cfg.SyncHostMemorySMBIOS || rep.MemorySpec == nil || rep.MemorySpec.SpeedMHz <= 0 { return } if reims.HasSMBIOSType17Arg(cur.ExtraArgs) { return } supportsType := reims.ProbeQEMUSupportsSMBIOSMemoryType(p.Runtime.QemuPath(), p.Client.Env) merged := reims.MergeSMBIOSType17Args(cur.ExtraArgs, rep.MemorySpec.SpeedMHz, rep.MemorySpec.MemoryType, supportsType) if merged == cur.ExtraArgs { return } if err := p.setExtraArgs(ctx, name, merged); err != nil { return } cur.ExtraArgs = merged } func (p *Prep) setExtraArgs(ctx context.Context, name, args string) error { return p.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &args}, io.Discard, io.Discard) } // syncOfflineHelper attaches the REIMSHELP HFS+ helper disk while an offline // installer is attached, and strips it once the installer is ejected. func (p *Prep) syncOfflineHelper(ctx context.Context, name string, cur *reims.VMDetail) { if cur.HasInstaller && reims.IsOfflineInstallerPath(cur.InstallerPath) { p.log("Preparing offline install helper disk (REIMSHELP)...") helperPath, err := installer.EnsureOfflineHelperImage(p.cfg.XDGCacheDir(), cur.InstallerPath) if err != nil { p.log("Warning: offline install helper disk skipped: " + err.Error()) return } merged := reims.MergeOfflineHelperArgs(cur.ExtraArgs, helperPath) if merged != cur.ExtraArgs { if err := p.setExtraArgs(ctx, name, merged); err != nil { p.log("Warning: could not attach REIMSHELP disk: " + err.Error()) return } cur.ExtraArgs = merged } return } stripped := reims.StripOfflineHelperArgs(cur.ExtraArgs) if stripped != cur.ExtraArgs { if err := p.setExtraArgs(ctx, name, stripped); err == nil { cur.ExtraArgs = stripped } } } // syncRecoveryBootPicker applies a recovery-mode switch made while the VM was // running: update-opencore needs a stopped VM (upstream 3731afd // opencore.rs:400-402), so the switch is recorded in a marker file and done here. func (p *Prep) syncRecoveryBootPicker(ctx context.Context, name string, cur *reims.VMDetail) { var show bool var done string switch ReadRecoveryMarker(cur.Directory) { case "want": p.log("Enabling OpenCore boot picker for recovery mode...") show, done = true, "on" case "restore": p.log("Restoring OpenCore direct boot after exiting recovery mode...") show, done = false, "" default: return } w := vmstart.LineWriter(p.log) if err := p.Client.UpdateOpenCore(ctx, name, show, w, w); err != nil { p.log("Warning: could not update OpenCore boot picker: " + err.Error()) return } WriteRecoveryMarker(cur.Directory, done) p.ReplayGuestLang(ctx, cur.Directory) } // applyProbedWHPXCompat pre-applies `-machine kernel-irqchip=off` on Windows 11 // builds where WHvPartitionPropertyCodeNestedVirtualization is probed as // unsupported (e.g. hr=0x80370302) and the active runtime lacks // qemu-whpx-nested-virt-nonfatal.patch, avoiding a first-start crash and retry. func (p *Prep) applyProbedWHPXCompat(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { if rep.NeedsColdRebootWorkaround || !rep.WHPXCaps.KernelIrqchipAvailable || rep.WHPXCaps.NestedVirtProperty { return } if p.RuntimeHasPatch("nested-virt-nonfatal") || reims.HasKernelIrqchipArg(cur.ExtraArgs) { return } merged := reims.MergeKernelIrqchipOffArgs(cur.ExtraArgs) if err := p.setExtraArgs(ctx, name, merged); err != nil { return } cur.ExtraArgs = merged code := rep.WHPXCaps.NestedVirtProbeError if code == "" { code = "unsupported" } p.log(i18n.M(p.cfg.Locale, "vmstart.compat.nested_virt", i18n.Vars{"code": code})) } // RuntimeHasPatch reports whether the active runtime was built with a patch // whose name contains substr (case-insensitive). func (p *Prep) RuntimeHasPatch(substr string) bool { needle := strings.ToLower(substr) for _, patch := range p.Runtime.Manifest.Patches { if strings.Contains(strings.ToLower(patch.Name), needle) { return true } } return false } // ApplyGuestLang saves the VM's macOS prev-lang:kbd preference and, when the // VM is stopped, writes it into the OpenCore image right away. A running VM // gets it on its next start (ReplayGuestLang). An empty lang is a no-op. func (p *Prep) ApplyGuestLang(ctx context.Context, vmDir, lang string, running bool) error { norm, err := opencore.NormalizeGuestLang(lang) if err != nil || norm == "" { return err } if err := opencore.WriteSavedGuestLang(vmDir, norm); err != nil { return err } if running { p.log(fmt.Sprintf("Scheduled macOS boot/recovery language (%s) for next start", norm)) return nil } return p.patchGuestLang(ctx, vmDir, norm) } // ReplayGuestLang re-applies the saved language after anything that rebuilds // the OpenCore image (update-opencore, a graphics switch, a clone) and before // every start. Failures are logged, not returned: the VM still boots. func (p *Prep) ReplayGuestLang(ctx context.Context, vmDir string) { saved := opencore.ReadSavedGuestLang(vmDir) if saved == "" { return } if err := p.patchGuestLang(ctx, vmDir, saved); err != nil { p.log(fmt.Sprintf("Warning: could not apply macOS language (%s) to OpenCore: %v", saved, err)) } } func (p *Prep) patchGuestLang(ctx context.Context, vmDir, lang string) error { ocPath := opencore.ResolveOpenCorePath(vmDir) if ocPath == "" { return nil } changed, err := opencore.PatchImagePrevLang(ctx, ocPath, lang, p.Runtime.QemuImgPath(), p.Client.Env) if err != nil { return err } if changed { p.log(fmt.Sprintf("Applied macOS boot/recovery language (%s) to OpenCore NVRAM", lang)) } return nil } const recoveryMarkerFile = ".reims-go-recovery-picker" // ReadRecoveryMarker returns the VM's pending recovery boot-picker state: // "want" (enable on next start), "on" (enabled), "restore" (disable on next // start) or "" (none). func ReadRecoveryMarker(vmDir string) string { if vmDir == "" { return "" } b, err := os.ReadFile(filepath.Join(vmDir, recoveryMarkerFile)) if err != nil { return "" } return strings.TrimSpace(string(b)) } // WriteRecoveryMarker records state; "" removes the marker. func WriteRecoveryMarker(vmDir, state string) { if vmDir == "" { return } p := filepath.Join(vmDir, recoveryMarkerFile) if state == "" { _ = os.Remove(p) return } _ = os.WriteFile(p, []byte(state), 0o644) }