- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI
# Conflicts:
# frontend/src/i18n.ts
# internal/cli/cli.go
# internal/i18n/i18n.go
371 lines
12 KiB
Go
371 lines
12 KiB
Go
// Package vmstart holds what has to happen around `reims-ctl start` for both
|
|
// the GUI and the CLI (docs/architecture.md principle 3): the commit-memory
|
|
// check, VM preparation before QEMU launches, the macOS language preset and
|
|
// P-core pinning afterwards.
|
|
//
|
|
// Two start steps stay in the GUI because they need a process that outlives
|
|
// the start command: the Guest Tools bridge (guesttools_flow.go) and the Win10
|
|
// cold-reboot watcher (app.go).
|
|
package vmstart
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/config"
|
|
"github.com/Nwflower/reims-go/internal/driver/reims"
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
"github.com/Nwflower/reims-go/internal/installer"
|
|
"github.com/Nwflower/reims-go/internal/opencore"
|
|
rt "github.com/Nwflower/reims-go/internal/runtime"
|
|
)
|
|
|
|
// 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 core plugin's WHPX setting 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 can't be committed right
|
|
// now. Without it QEMU exits with "Cannot set up guest memory 'ram'" (measured
|
|
// 2026-11-28, portable-runtime-spec.md §5.1), which says nothing about what to do.
|
|
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, avail, host.RecommendedMemoryGB(rep)))
|
|
}
|
|
|
|
// WaitForCommitMemory waits up to timeout for Windows to have enough free
|
|
// commit memory (guest RAM + host.StartMarginGB) to start a VM with memory.
|
|
// Used right after a VM exits (Win10 WHPX cold-reboot or restart), when Windows
|
|
// / WHPX partition / GPU driver commit-charge reclamation can lag behind process
|
|
// exit by a few seconds.
|
|
//
|
|
// Returns immediately with true when commit memory is already sufficient, when
|
|
// memory cannot be parsed, or when commit memory cannot be probed. onWait, if
|
|
// non-nil, is called once when waiting begins with (availGB, neededGB).
|
|
func WaitForCommitMemory(ctx context.Context, memory string, timeout time.Duration, onWait func(availGB, neededGB float64)) bool {
|
|
return waitForCommitMemory(ctx, memory, timeout, 250*time.Millisecond, host.CommitAvailGB, onWait)
|
|
}
|
|
|
|
func waitForCommitMemory(
|
|
ctx context.Context,
|
|
memory string,
|
|
timeout, pollInterval time.Duration,
|
|
probe func() (float64, bool),
|
|
onWait func(availGB, neededGB float64),
|
|
) bool {
|
|
memGB, ok := reims.ParseSizeGB(memory)
|
|
if !ok {
|
|
return true
|
|
}
|
|
needed := memGB + host.StartMarginGB
|
|
avail, ok := probe()
|
|
if !ok || needed <= avail {
|
|
return true
|
|
}
|
|
if onWait != nil {
|
|
onWait(avail, needed)
|
|
}
|
|
if timeout <= 0 {
|
|
return false
|
|
}
|
|
if pollInterval <= 0 {
|
|
pollInterval = 250 * time.Millisecond
|
|
}
|
|
timer := time.NewTimer(timeout)
|
|
defer timer.Stop()
|
|
ticker := time.NewTicker(pollInterval)
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return false
|
|
case <-timer.C:
|
|
avail, ok := probe()
|
|
return !ok || needed <= avail
|
|
case <-ticker.C:
|
|
avail, ok := probe()
|
|
if !ok || needed <= avail {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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) {
|
|
p.syncOfflineHelper(ctx, name, cur)
|
|
p.syncRecoveryBootPicker(ctx, name, cur)
|
|
p.ReplayGuestLang(ctx, cur.Directory)
|
|
if !p.SkipWHPXFallback {
|
|
p.applyProbedWHPXCompat(ctx, name, rep, cur)
|
|
}
|
|
}
|
|
|
|
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 := 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
|
|
}
|
|
|
|
// PinQEMU sets a running VM's QEMU process affinity per host.SelectSafeAffinity
|
|
// and returns the line to log about it.
|
|
func PinQEMU(loc i18n.Locale, rep host.Report, pid, vcpus int) string {
|
|
plan := host.SelectSafeAffinity(rep, vcpus)
|
|
if plan.Mode == "all" {
|
|
return i18n.M(loc, "vmstart.pin.skipped", i18n.Vars{"vcpus": vcpus, "pthreads": plan.PThreads})
|
|
}
|
|
err := host.PinProcessToPCores(uint32(pid), plan.Mask)
|
|
if plan.Mode == "non_lpe" {
|
|
if err != nil {
|
|
return fmt.Sprintf("[CPU] Warning: P+E core pinning failed for PID %d: %v", pid, err)
|
|
}
|
|
return i18n.M(loc, "vmstart.pin.non_lpe", i18n.Vars{
|
|
"vcpus": vcpus,
|
|
"pthreads": plan.PThreads,
|
|
"pid": pid,
|
|
"cores": plan.CoreCount,
|
|
"threads": plan.ThreadCount,
|
|
"mask": plan.MaskHex,
|
|
"lpe": rep.LPECoreCount,
|
|
})
|
|
}
|
|
if err != nil {
|
|
return fmt.Sprintf("[CPU] Warning: P-core pinning failed for PID %d: %v", pid, err)
|
|
}
|
|
return i18n.M(loc, "vmstart.pin.pcores", i18n.Vars{
|
|
"pid": pid,
|
|
"cores": plan.CoreCount,
|
|
"threads": plan.ThreadCount,
|
|
"mask": plan.MaskHex,
|
|
"excluded": rep.ECoreCount + rep.LPECoreCount,
|
|
})
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
// LineWriter turns command output into one log call per non-empty line.
|
|
type LineWriter func(string)
|
|
|
|
func (w LineWriter) Write(b []byte) (int, error) {
|
|
sc := bufio.NewScanner(strings.NewReader(string(b)))
|
|
for sc.Scan() {
|
|
if line := strings.TrimSpace(sc.Text()); line != "" {
|
|
w(line)
|
|
}
|
|
}
|
|
return len(b), nil
|
|
}
|