Merge main and preserve Guest Tools file sync compatibility

This commit is contained in:
YXC0915 committed 2026-12-01 10:02:08 +08:00
commit 2d5ee45163
78 files changed
+10803 -551

No files matched your search

+1
View File
@@ -1,2 +1,3 @@
*.patch -text
*.diff -text
internal/guesttools/file_sync.sh text eol=lf
+27 -2
View File
@@ -142,6 +142,21 @@ jobs:
if ($LASTEXITCODE) { throw 'reims-util fetch failed' }
git -C $utilRepo checkout -q --detach FETCH_HEAD
if ($LASTEXITCODE) { throw 'reims-util checkout failed' }
$m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan'
$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.toml')
if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') {
$m2vRev = $Matches[1]
} else {
$lockTxt = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.lock')
if ($lockTxt -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' }
$m2vRev = $Matches[1]
}
git init -q $m2vRepo
if ($LASTEXITCODE) { throw 'metal2vulkan init failed' }
git -C $m2vRepo fetch -q --depth 1 https://github.com/steelbrain/metal2vulkan.git $m2vRev
if ($LASTEXITCODE) { throw 'metal2vulkan fetch failed' }
git -C $m2vRepo checkout -q --detach FETCH_HEAD
if ($LASTEXITCODE) { throw 'metal2vulkan checkout failed' }
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
$releaseId = "$short${{ needs.resolve.outputs.suffix }}"
"short=$short" >> $env:GITHUB_OUTPUT
@@ -151,7 +166,7 @@ jobs:
# conflict without touching the patch (AGENTS.md rule 4).
$resultFile = Join-Path $env:RUNNER_TEMP 'patches.json'
try {
pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -ResultFile $resultFile
pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -Metal2VulkanRepo $m2vRepo -ResultFile $resultFile
$ok = $LASTEXITCODE -eq 0
} finally {
if (Test-Path $resultFile) {
@@ -163,11 +178,20 @@ jobs:
}
}
if (-not $ok) { throw 'patch queue does not apply' }
$cargoHome = Join-Path $env:RUNNER_TEMP 'cargo'
$m2vFwd = $m2vRepo.Replace('\', '/')
$cargoCfg = @"
[patch."https://github.com/steelbrain/metal2vulkan"]
metal2vulkan = { path = "$m2vFwd/crates/metal2vulkan" }
metal2vulkan-runtime = { path = "$m2vFwd/crates/metal2vulkan-runtime" }
"@ -replace '(?m)^ ', ''
[IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false))
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV
"METAL2VULKAN_DIR=$m2vRepo" >> $env:GITHUB_ENV
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
"RELEASE_ID=$releaseId" >> $env:GITHUB_ENV
"CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV
"CARGO_HOME=$cargoHome" >> $env:GITHUB_ENV
"XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV
"XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV
@@ -200,6 +224,7 @@ jobs:
& ./scripts/pack-runtime.ps1 `
-ReimsRepo $env:UPSTREAM_DIR `
-UtilRepo $env:REIMS_UTIL_DIR `
-Metal2VulkanRepo $env:METAL2VULKAN_DIR `
-CargoHome $env:CARGO_HOME `
-QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') `
-Msys2 '${{ steps.msys2.outputs.msys2-location }}' `
+6 -3
View File
@@ -20,7 +20,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
| :--- | :--- |
| **声明式配置** | 一台虚拟机对应一份声明式配置,界面只编辑配置项,不让用户直接拼 QEMU 命令行参数。 |
| **先校验,后保存** | 保存前在 Go 端完成前置校验(CPU 核数、可用提交内存上限、Vulkan ICD 路径存在性、切换磁盘控制器前是否已弹出安装盘),非法值在提交前拦截。 |
| **随时可编辑,标明生效时机** | 无论虚拟机运行与否,设置面板均可打开编辑;每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 |
| **标明设置的生效时机** | 虚拟机运行中或已停止时可编辑设置。每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 |
**写入约束**:凡属于上游 `reims-ctl` 管理的配置项,一律通过 `reims-ctl set` 写入,不直接改写 `vm.toml`,确保上游校验与 OpenCore 重建逻辑照常生效。
@@ -55,11 +55,14 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
| **正在创建** | 创建流程进行中 | 无(展示分步进度) | 取消创建 |
| **已停止** | 上游 `stopped` | **启动** | 设置、恢复点、更多(派生副本、扩容/回收、打开目录、删除) |
| **正在启动** | 发起 `start` 至 `running` | 启动中(忙碌态,禁用) | 设置、强制关机 |
| **运行中** | 上游 `running` | **显示 VM 窗口** | 关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) |
| **运行中** | 上游 `running` | **显示 VM 窗口** | 挂起(需支持此功能的内核)、关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) |
| **正在停止** | 发起 `stop` 至 `stopped` | 停止中(忙碌态,禁用) | 强制关机 |
| **正在挂起** | 正在保存运行状态 | 挂起中(忙碌态,禁用) | 强制关机 |
| **已挂起** | 运行状态已保存到磁盘 | **恢复**(需支持此功能的内核) | 更多(放弃挂起状态、打开目录) |
| **正在恢复** | 正在从磁盘恢复运行状态 | 恢复中(忙碌态,禁用) | 强制关机 |
| **配置损坏** | 上游 `broken` | **查看问题** | 打开目录、删除 |
- 暂不提供暂停或运行中热快照状态(`paused` / `saving` / `restoring`),直到上游验证 `reims-vgpu` 显存与设备状态序列化。
- 已挂起时,恢复或放弃挂起状态后才可修改配置、管理磁盘和安装或弹出 Guest Tools。切换到不支持挂起的内核时,禁用恢复并提示用户切换内核。放弃挂起状态须经破坏性操作确认框确认。
- 禁用按钮不占据主操作位置;状态变化时直接切换为当前最合适的主操作。
---
+43 -8
View File
@@ -20,7 +20,7 @@ import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFo
import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats'
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
import { Button, Tip, TooltipProvider } from './ui/controls'
import { Modal } from './ui/dialog'
import { ConfirmDialog, Modal } from './ui/dialog'
import { Toaster, useToasts } from './ui/toast'
import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails'
@@ -41,6 +41,9 @@ const errText = (e: unknown) => parseAppError(e).summary
const failKey: Record<VMAction, I18nKey> = {
start: 'failStart',
suspend: 'failSuspend',
resume: 'failResume',
discardSuspend: 'failDiscardSuspend',
focus: 'failFocus',
fullscreen: 'failFullscreen',
screenshot: 'failScreenshot',
@@ -85,6 +88,7 @@ export const App: React.FC = () => {
const [affinityTarget, setAffinityTarget] = useState<string | null>(null)
const [affinityVersion, setAffinityVersion] = useState(0)
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
const [cloneSource, setCloneSource] = useState<string | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
@@ -331,6 +335,7 @@ export const App: React.FC = () => {
const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : ''
const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : []
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
const canSuspend = state?.can_suspend ?? false
onTaskRef.current = (task: Task) => {
if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) {
@@ -656,6 +661,7 @@ export const App: React.FC = () => {
}
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
if (!canSuspend && (action === 'suspend' || action === 'resume')) return
const activeBusy = activeVMBusy(name)
if (
activeBusy
@@ -667,6 +673,9 @@ export const App: React.FC = () => {
}
switch (action) {
case 'start': return runVMAction(name, action, () => api.StartVM(name))
case 'suspend': return runVMAction(name, action, () => api.SuspendVM(name), tr('toastSuspended', { name }))
case 'resume': return runVMAction(name, action, () => api.ResumeVM(name), tr('toastResumed', { name }))
case 'discardSuspend': return setDiscardSuspendTarget(name)
case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e))
case 'fullscreen':
return runVMAction(name, action, async () => {
@@ -705,23 +714,25 @@ export const App: React.FC = () => {
}
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
const vm = vms.find((v) => v.name === name)
const st = state?.transitions[name] ?? vm?.state ?? 'stopped'
if (action === 'settings') {
if (st === 'suspended' || st === 'suspending' || st === 'resuming') return
setSelected(name)
api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
return
}
const vm = vms.find((v) => v.name === name)
const st = state?.transitions[name] ?? vm?.state ?? 'stopped'
onVMActionFor(name, action, st === 'running')
}
// The state's own main action (Start, or Show Window while running), shared by
// The state's own main action (Start, Resume while suspended, or Show Window while running), shared by
// Ctrl+Enter and a double-click in the sidebar.
const primaryAction = (name: string) => {
const vm = vms.find((v) => v.name === name)
if (!vm || activeVMBusy(name)) return
const st = state?.transitions[name] ?? vm.state
if (st === 'stopped') onVMActionFor(name, 'start', false)
else if (st === 'suspended') onVMActionFor(name, 'resume', false)
else if (st === 'running') onVMActionFor(name, 'focus', true)
}
@@ -731,6 +742,12 @@ export const App: React.FC = () => {
if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name }))
}
const confirmDiscardSuspend = () => {
const name = discardSuspendTarget
setDiscardSuspendTarget(null)
if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspend(name), tr('toastDiscardSuspend', { name }))
}
const confirmOnlineRecovery = () => {
const name = onlineRecoveryTarget
setOnlineRecoveryTarget(null)
@@ -859,11 +876,11 @@ export const App: React.FC = () => {
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
const k = e.key.toLowerCase()
if (k === 'n') { e.preventDefault(); openWizard() }
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) }
else if (k === 'l') { e.preventDefault(); toggleLogs() }
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) }
@@ -881,7 +898,11 @@ export const App: React.FC = () => {
useEffect(() => {
const offSelect = events.onTraySelectVM((name) => { setSelected(name) })
const offNew = events.onTrayNewVM(() => { openWizardRef.current() })
return () => { offSelect(); offNew() }
const offDiscard = events.onTrayDiscardSuspend((name) => {
setSelected(name)
setDiscardSuspendTarget(name)
})
return () => { offSelect(); offNew(); offDiscard() }
}, [])
// Native Wails file drag-and-drop delivery into the selected VM's shared folder.
@@ -950,10 +971,11 @@ export const App: React.FC = () => {
state: effectiveState,
busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name),
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
canSuspend,
} : null}
onNewVM={openWizard}
onVMAction={onVMAction}
onVMSettings={() => { if (detail) setShowSettings(true) }}
onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }}
onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }}
onNavigate={setSelected}
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
@@ -1019,6 +1041,7 @@ export const App: React.FC = () => {
busyActions={busy}
selected={selected}
hostReady={hostReady}
canSuspend={canSuspend}
onSelect={setSelected}
displayNames={displayNames}
macosMajors={macosMajors}
@@ -1077,6 +1100,7 @@ export const App: React.FC = () => {
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
macosMajor={macosMajors[selectedVM.name] ?? null}
state={effectiveState}
canSuspend={canSuspend}
guideActive={state.active_guides?.includes(selectedVM.name) ?? false}
installGuideEnabled={!!state.install_guide_enabled}
detail={detail}
@@ -1281,6 +1305,17 @@ export const App: React.FC = () => {
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
)}
{discardSuspendTarget && (
<ConfirmDialog
title={tr('discardSuspendTitle', { name: displayNames[discardSuspendTarget] || discardSuspendTarget })}
description={tr('discardSuspendDesc')}
cancelLabel={tr('cancel')}
confirmLabel={tr('discardSuspendConfirm')}
onCancel={() => setDiscardSuspendTarget(null)}
onConfirm={confirmDiscardSuspend}
/>
)}
{cloneSource && (
<CloneDialog
locale={locale}
+14 -28
View File
@@ -1,7 +1,7 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import React, { useState } from 'react'
import { t } from '../i18n'
import { Locale } from '../types'
import { ConfirmDialog } from '../ui/dialog'
interface Props {
locale: Locale
@@ -13,32 +13,18 @@ interface Props {
export const DeleteDialog: React.FC<Props> = ({ locale, name, onCancel, onConfirm }) => {
const [keepFiles, setKeepFiles] = useState(false)
return (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'deleteTitle', { name })}</Alert.Title>
<Alert.Description className="dialog-desc">
{t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')}
</Alert.Description>
<label className="choice">
<input type="checkbox" checked={keepFiles} onChange={(e) => setKeepFiles(e.target.checked)} />
{t(locale, 'deleteKeepFiles')}
</label>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<button type="button" className="btn">{t(locale, 'cancel')}</button>
</Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-danger" onClick={() => onConfirm(keepFiles)}>
{t(locale, 'deleteConfirm')}
</button>
</Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
<ConfirmDialog
title={t(locale, 'deleteTitle', { name })}
description={t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')}
cancelLabel={t(locale, 'cancel')}
confirmLabel={t(locale, 'deleteConfirm')}
onCancel={onCancel}
onConfirm={() => onConfirm(keepFiles)}
>
<label className="choice">
<input type="checkbox" checked={keepFiles} onChange={(e) => setKeepFiles(e.target.checked)} />
{t(locale, 'deleteKeepFiles')}
</label>
</ConfirmDialog>
)
}
+24 -5
View File
@@ -1,5 +1,5 @@
import * as Ctx from '@radix-ui/react-context-menu'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import React, { useRef } from 'react'
import { I18nKey, t } from '../i18n'
import { Locale, VMListItem } from '../types'
@@ -24,6 +24,8 @@ interface Props {
busyActions?: Record<string, VMAction>
selected: string
hostReady: boolean
/** Whether the active runtime supports VM suspend/resume. */
canSuspend: boolean
onSelect: (id: string) => void
/** VM name → display name (its note); empty or missing shows the name. */
displayNames?: Record<string, string>
@@ -44,7 +46,7 @@ interface Props {
}
export const Sidebar: React.FC<Props> = ({
locale, vms, transitions, busyActions = {}, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot,
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot,
}) => {
const tr = (k: I18nKey) => t(locale, k)
const listRef = useRef<HTMLDivElement>(null)
@@ -118,7 +120,8 @@ export const Sidebar: React.FC<Props> = ({
const st = transitions[vm.name] ?? vm.state
const running = st === 'running'
const stopped = st === 'stopped'
const transitioning = st === 'starting' || st === 'stopping'
const suspended = st === 'suspended'
const transitioning = st === 'starting' || st === 'stopping' || st === 'suspending' || st === 'resuming'
const busyAction = Object.prototype.hasOwnProperty.call(busyActions, vm.name) ? busyActions[vm.name] : undefined
const vmBusy = !!busyAction
const label = displayNames[vm.name] || vm.name
@@ -159,6 +162,17 @@ export const Sidebar: React.FC<Props> = ({
<Play size={14} /> {tr('start')}
</Ctx.Item>
)}
{suspended && (
<>
<Ctx.Item className="menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vm.name, 'resume')}>
<Play size={14} /> {tr('resume')}
</Ctx.Item>
{!canSuspend && <Ctx.Label className="menu-group-label">{tr('resumeUnavailable')}</Ctx.Label>}
<Ctx.Item className="menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'discardSuspend')}>
<Power size={14} /> {tr('discardSuspend')}
</Ctx.Item>
</>
)}
{running && (
<>
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'focus')}>
@@ -170,6 +184,11 @@ export const Sidebar: React.FC<Props> = ({
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
<Camera size={14} /> {tr('copyScreenshot')}
</Ctx.Item>
{canSuspend && (
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'suspend')}>
<Pause size={14} /> {tr('suspend')}
</Ctx.Item>
)}
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'stop')}>
<Square size={14} /> {tr('stop')}
</Ctx.Item>
@@ -184,7 +203,7 @@ export const Sidebar: React.FC<Props> = ({
</Ctx.Item>
)}
<Ctx.Separator className="menu-sep" />
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'settings')}>
<Ctx.Item className="menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vm.name, 'settings')}>
<Settings size={14} /> {tr('settingsEllipsis')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
@@ -199,7 +218,7 @@ export const Sidebar: React.FC<Props> = ({
<FolderOpen size={14} /> {tr('openFolder')}
</Ctx.Item>
<Ctx.Separator className="menu-sep" />
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
<Trash size={14} /> {tr('delete')}
</Ctx.Item>
</Ctx.Content>
+11 -5
View File
@@ -27,7 +27,7 @@ interface Props {
canDark?: boolean
onThemeMode: (mode: ThemeMode) => void
/** The selected VM and its current state, or null on the system pages. */
vm: { name: string; state: string; busy: boolean; graphics?: string } | null
vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null
onNewVM: () => void
onVMAction: (action: VMAction) => void
onVMSettings: () => void
@@ -62,7 +62,8 @@ export const TitleMenus: React.FC<Props> = ({
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping'
const suspended = vm?.state === 'suspended'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
const vmBusy = !vm || vm.busy
const canFullscreen = running && vm?.graphics !== 'vmware-svga'
const stats = useVMStats(canFullscreen && vm ? vm.name : null, running)
@@ -218,17 +219,22 @@ export const TitleMenus: React.FC<Props> = ({
<Menu.Separator className="menu-sep" />
{running
? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
: suspended
? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
{suspended && !vm?.canSuspend && <Menu.Label className="menu-group-label">{tr('resumeUnavailable')}</Menu.Label>}
{item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })}
{item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })}
{item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })}
{item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })}
{item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })}
<Menu.Separator className="menu-sep" />
{item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm })}
{item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })}
{item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
<Menu.Separator className="menu-sep" />
{suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })}
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || transitioning })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })}
</>
))}
{menu('view', tr('menuView'), (
+114 -30
View File
@@ -27,6 +27,7 @@ import {
Minimize2,
Monitor,
Network,
Pause,
Pencil,
Play,
Plus,
@@ -40,7 +41,7 @@ import {
Upload,
UserRound,
} from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import React, { useEffect, useId, useRef, useState } from 'react'
import { I18nKey, locText, t } from '../i18n'
import {
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel,
@@ -55,6 +56,9 @@ import { VersionArt } from './VersionArt'
export type VMAction =
| 'start'
| 'suspend'
| 'resume'
| 'discardSuspend'
| 'stop'
| 'forceStop'
| 'restart'
@@ -92,6 +96,8 @@ interface Props {
/** macOS major version (26, 15, …) for the artwork shown before a first frame; null if unknown. */
macosMajor: number | null
state: string
/** Whether the active runtime supports VM suspend/resume. */
canSuspend: boolean
/** Whether the native VM-window installation guide is currently active for this boot. */
guideActive: boolean
/** Whether the builtin.install-guide plugin is enabled. */
@@ -132,13 +138,17 @@ interface Spec {
}
export const VMPage: React.FC<Props> = ({
locale, name, displayName, onDisplayNameSaved, macosMajor, state, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
locale, name, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
const running = state === 'running'
const suspended = state === 'suspended'
const guestToolsLocked = suspended || state === 'suspending' || state === 'resuming'
const resumeHintId = useId()
const guestToolsHintId = useId()
const installing = !!detail && (detail.has_installer || detail.recovery_mode)
const transitioning = state === 'starting' || state === 'stopping'
const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming'
// Polled here rather than in App so each tick re-renders only this page.
const stats = useVMStats(name, running)
@@ -318,7 +328,7 @@ export const VMPage: React.FC<Props> = ({
}
// One primary action per state (docs/design-guidelines.md §4): Start while
// stopped, Show Window while running. Ctrl+Enter triggers it (App.tsx).
// stopped, Resume while suspended, Show Window while running. Ctrl+Enter triggers it (App.tsx).
let primary: React.ReactNode = null
let secondary: React.ReactNode = null
if (state === 'stopped') {
@@ -329,10 +339,29 @@ export const VMPage: React.FC<Props> = ({
</Button>
</Tip>
)
} else if (suspended) {
primary = (
<Tip label={tr('resume')} shortcut={PRIMARY_SHORTCUT} disabled={!canSuspend}>
<Button
variant={canSuspend ? 'primary' : 'secondary'}
icon={<Play size={14} aria-hidden="true" />}
busy={busyAction === 'resume'}
disabled={busy || !canSuspend}
aria-describedby={!canSuspend ? resumeHintId : undefined}
onClick={() => onAction('resume')}
>
{tr('resume')}
</Button>
</Tip>
)
} else if (state === 'starting') {
primary = <Button variant="primary" busy>{tr('state_starting')}</Button>
} else if (state === 'stopping') {
primary = <Button busy>{tr('state_stopping')}</Button>
} else if (state === 'suspending') {
primary = <Button busy>{tr('state_suspending')}</Button>
} else if (state === 'resuming') {
primary = <Button variant="primary" busy>{tr('state_resuming')}</Button>
} else if (running) {
const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow')
primary = (
@@ -343,7 +372,14 @@ export const VMPage: React.FC<Props> = ({
</Tip>
)
secondary = (
<Button icon={<Square size={12} aria-hidden="true" />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
<>
{canSuspend && (
<Button icon={<Pause size={13} aria-hidden="true" />} busy={busyAction === 'suspend'} disabled={busy} onClick={() => onAction('suspend')}>
{tr('suspend')}
</Button>
)}
<Button icon={<Square size={12} aria-hidden="true" />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
</>
)
} else if (state === 'broken') {
primary = <Button variant="primary" icon={<Terminal size={14} aria-hidden="true" />} onClick={onViewLogs}>{tr('viewLogs')}</Button>
@@ -431,15 +467,15 @@ export const VMPage: React.FC<Props> = ({
{detail && (
<>
{installing ? (
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('finishInstall')}>
<Menu.Item className="menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('finishInstall')}>
<LifeBuoy size={14} /> {tr('finishInstall')}
</Menu.Item>
) : (
<>
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('enterRecovery')}>
<Menu.Item className="menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('enterRecovery')}>
<LifeBuoy size={14} /> {tr('enterRecovery')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={running || transitioning || busy} onSelect={() => onAction('cloneVM')}>
<Menu.Item className="menu-item" disabled={running || suspended || transitioning || busy} onSelect={() => onAction('cloneVM')}>
<CopyPlus size={14} /> {tr('cloneVM')}
</Menu.Item>
</>
@@ -478,12 +514,17 @@ export const VMPage: React.FC<Props> = ({
</Menu.Item>
))}
<Menu.Separator className="menu-sep" />
{suspended && (
<Menu.Item className="menu-item danger" disabled={busy} onSelect={() => onAction('discardSuspend')}>
<Power size={14} /> {tr('discardSuspend')}
</Menu.Item>
)}
{(running || transitioning) && (
<Menu.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
<Power size={14} /> {tr('forceStop')}
</Menu.Item>
)}
<Menu.Item className="menu-item danger" disabled={running || transitioning || busy} onSelect={onDelete}>
<Menu.Item className="menu-item danger" disabled={running || suspended || transitioning || busy} onSelect={onDelete}>
<Trash size={14} /> {tr('delete')}
</Menu.Item>
</Menu.Content>
@@ -563,11 +604,23 @@ export const VMPage: React.FC<Props> = ({
onCopy(rows.join('\n'))
}
const pillClass = running ? ' is-running' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : ''
const pillClass = running ? ' is-running' : suspended ? ' is-suspended' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : ''
const dropStyle = detail && !installing
? ({ '--wails-drop-target': 'drop' } as React.CSSProperties)
: undefined
const formatSuspendTime = (iso?: string) => {
if (!iso) return ''
const ms = Date.parse(iso)
if (!Number.isFinite(ms)) return ''
try {
const loc = locale === 'en-XA' ? 'en-US' : locale
return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(ms))
} catch {
return ''
}
}
return (
<div className="page vm-page vm-page-drop rg-p-vm-page" style={dropStyle}>
{dropping && (
@@ -588,10 +641,10 @@ export const VMPage: React.FC<Props> = ({
thumb={thumb}
art={<VersionArt shape="screen" className="vm-screen-art" major={macosMajor} name={shownName} />}
running={running}
startLabel={tr('start')}
startLabel={suspended ? tr('resume') : tr('start')}
showLabel={tr('showWindow')}
shotLabel={tr('copyScreenshot')}
onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined}
onStart={!busy && (state === 'stopped' || (suspended && canSuspend)) ? () => onAction(suspended ? 'resume' : 'start') : undefined}
onShow={running && !busy ? () => onAction('focus') : undefined}
onScreenshot={running && !busy ? () => onAction('screenshot') : undefined}
/>
@@ -631,8 +684,10 @@ export const VMPage: React.FC<Props> = ({
<div className="vm-hero-actions">
{primary}
{secondary}
<Tip label={tr('settings')} shortcut="Ctrl+,">
<Button icon={<Settings size={14} aria-hidden="true" />} disabled={!detail} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
<Tip label={suspended ? tr('suspendedSettingsHint') : tr('settings')} shortcut={suspended ? undefined : 'Ctrl+,'}>
<span>
<Button icon={<Settings size={14} aria-hidden="true" />} disabled={!detail || suspended || transitioning} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
</span>
</Tip>
{menu}
</div>
@@ -667,6 +722,29 @@ export const VMPage: React.FC<Props> = ({
</div>
)}
{suspended && (() => {
const suspTime = formatSuspendTime(detail?.suspend_info?.created_at)
const suspSize = detail?.suspend_info?.vmstate_size
? formatBytes(detail.suspend_info.vmstate_size, locale)
: (detail?.memory ? formatMemory(detail.memory, locale) : '—')
return (
<div className="notice notice-info">
<span className="notice-main">
<Pause size={15} className="notice-icon" aria-hidden="true" />
<span className="notice-text">
<span className="notice-title">{tr('suspendedNoticeTitle')}</span>
<span className="notice-sub">
{suspTime
? tr('suspendedNoticeDescWithTime', { time: suspTime, size: suspSize })
: tr('suspendedNoticeDesc', { size: suspSize })}
</span>
{!canSuspend && <span id={resumeHintId} className="notice-sub">{tr('resumeUnavailable')}</span>}
</span>
</span>
</div>
)
})()}
{pending.length > 0 && (
<div className="notice notice-info">
<span className="notice-main">
@@ -853,9 +931,15 @@ export const VMPage: React.FC<Props> = ({
const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const minimumAgentVersion = gtMountMode === 'sync' ? 7 : 3
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < minimumAgentVersion
// Plugin switched off: show the state and hide controls that would only fail.
const gtOff = !!detail.guest_tools_disabled
const gtAttached = detail.guest_tools_attached
const showToolsAction = !gtOff && (gtAttached || !gtConnected || needsUpgrade)
const toolsAction = gtAttached ? 'detachGuestTools' : 'attachGuestTools'
const toolsActionLabel = gtAttached ? 'detachGuestTools' : needsUpgrade ? 'gtUpdate' : 'gtInstall'
// One status word per state; how files are shared goes in the tooltip.
let gtTone: 'ok' | 'warn' | 'idle' = 'idle'
@@ -968,20 +1052,20 @@ export const VMPage: React.FC<Props> = ({
</span>
</Tip>
</div>
{suspended && showToolsAction && (
<span id={guestToolsHintId} className="hint">{tr('suspendedGuestToolsHint')}</span>
)}
<div className="conn-ctrl">
{gtOff ? null : detail.guest_tools_attached ? (
<Button busy={busyAction === 'detachGuestTools'} disabled={busy} onClick={() => onAction('detachGuestTools')}>
{tr('detachGuestTools')}
</Button>
) : (!gtConnected || needsUpgrade) && (
{showToolsAction && (
<Button
variant={detail.guest_tools_configured ? 'secondary' : 'primary'}
icon={<Disc size={13} aria-hidden="true" />}
busy={busyAction === 'attachGuestTools'}
disabled={busy}
onClick={() => onAction('attachGuestTools')}
variant={gtAttached || detail.guest_tools_configured || guestToolsLocked ? 'secondary' : 'primary'}
icon={gtAttached ? undefined : <Disc size={13} aria-hidden="true" />}
busy={busyAction === toolsAction}
disabled={busy || guestToolsLocked}
aria-describedby={suspended ? guestToolsHintId : undefined}
onClick={() => onAction(toolsAction)}
>
{needsUpgrade ? tr('gtUpdate') : tr('gtInstall')}
{tr(toolsActionLabel)}
</Button>
)}
</div>
@@ -1041,12 +1125,12 @@ export const VMPage: React.FC<Props> = ({
<span>{tr('snapshotsTitle')}</span>
<span className="snap-meta-hint">· {tr('snapshotHint')}</span>
</span>
<Tip label={running || transitioning ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
<Tip label={running || suspended || transitioning ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
<span>
<Button
variant="ghost"
icon={<Plus size={13} aria-hidden="true" />}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => setCreatingSnap((v) => !v)}
>
{tr('snapshotCreate')}
@@ -1092,7 +1176,7 @@ export const VMPage: React.FC<Props> = ({
<Button
icon={<RotateCcw size={13} aria-hidden="true" />}
busy={snapBusy === `restore:${s.name}`}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => setRestoreTarget(s.name)}
>
{tr('snapshotRestore')}
@@ -1102,7 +1186,7 @@ export const VMPage: React.FC<Props> = ({
label={tr('snapshotDelete')}
icon={<Trash size={14} />}
busy={snapBusy === `delete:${s.name}`}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => void handleDeleteSnapshot(s.name)}
/>
</div>
+42
View File
@@ -24,6 +24,10 @@ export const vmZh: Record<string, string> = {
"diagBackingChainWarn": "当前系统盘 CoW 派生链深度为 {depth} 层(≥ 2),未分配簇读穿透会拖慢小文件 I/O,建议合并为独立镜像或基于基础镜像重新派生",
"diagExternalDriveWarn": "数据目录在外置或网络盘上({dir}),读写会明显变慢",
"diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿",
"discardSuspend": "放弃挂起状态",
"discardSuspendConfirm": "放弃并关机",
"discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。",
"discardSuspendTitle": "放弃「{name}」的挂起状态?",
"displayNameEdit": "点按以修改显示名称",
"displayNameEditEllipsis": "修改显示名称…",
"displayNameLabel": "显示名称",
@@ -41,6 +45,7 @@ export const vmZh: Record<string, string> = {
"failAttachInstaller": "挂载镜像失败",
"failCloneVM": "派生 CoW 副本失败",
"failDelete": "删除失败",
"failDiscardSuspend": "放弃挂起状态失败",
"failEject": "弹出安装盘失败",
"failEnterRecovery": "进入恢复模式失败",
"failExportDiagnostics": "导出排障日志失败",
@@ -50,10 +55,12 @@ export const vmZh: Record<string, string> = {
"failGuestTools": "Guest Tools 操作失败",
"failOpenFolder": "无法打开文件夹",
"failRestart": "重启失败",
"failResume": "恢复失败",
"failScreenshot": "截屏失败",
"failSnapshot": "恢复点操作失败",
"failStart": "启动失败",
"failStop": "关机失败",
"failSuspend": "挂起失败",
"failType": "键入失败",
"failUpgradeNVMe": "升级到 NVMe 失败",
"fieldAudio": "音频",
@@ -111,6 +118,8 @@ export const vmZh: Record<string, string> = {
"pendingTitle": "下次启动生效",
"pickRecoveryTitle": "选择离线镜像(.img / .dmg)",
"restartToApply": "重启以应用",
"resume": "恢复",
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
"sendText": "发送文本到虚拟机…",
"sendTextConfirm": "发送 (Ctrl+Enter)",
"sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。",
@@ -155,14 +164,24 @@ export const vmZh: Record<string, string> = {
"state_broken": "出错",
"state_creating": "正在创建",
"state_driver_unavailable": "驱动不可用",
"state_resuming": "恢复中",
"state_running": "运行中",
"state_starting": "启动中",
"state_stopped": "已停止",
"state_stopping": "停止中",
"state_suspended": "已挂起",
"state_suspending": "挂起中",
"suspend": "挂起",
"suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改",
"suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
"suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
"suspendedNoticeTitle": "已保存运行状态",
"suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置",
"techInfo": "技术信息",
"toastCloned": "已派生 CoW 副本「{name}」",
"toastDeleted": "已删除 {name}",
"toastDiagExported": "已导出脱敏排障日志包 (.zip)",
"toastDiscardSuspend": "已放弃 {name} 的挂起状态",
"toastEjected": "已弹出安装盘",
"toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery",
"toastEnterRecoveryNextStart": "已准备进入恢复模式,重启后显示引导菜单",
@@ -182,11 +201,13 @@ export const vmZh: Record<string, string> = {
"toastOnlineRecoveryStarted": "正在拉取在线恢复镜像(约 1 GB),完成后自动挂载",
"toastPreventSleepOff": "已关闭 macOS 防休眠守护",
"toastPreventSleepOn": "已开启 macOS 防休眠守护",
"toastResumed": "{name} 已恢复",
"toastScreenshotCopied": "已复制虚拟机画面",
"toastSnapshotCreated": "已创建恢复点 {name}",
"toastSnapshotDeleted": "已删除恢复点 {name}",
"toastSnapshotRestored": "已回滚到 {name}",
"toastStopped": "{name} 已关机",
"toastSuspended": "{name} 已挂起",
"toastTyped": "{n, plural, other {已键入 # 个字符}}",
"toggleFullscreen": "切换全屏",
"typeClipboard": "粘贴剪贴板到虚拟机",
@@ -219,6 +240,10 @@ export const vmEn: Record<string, string> = {
"diagBackingChainWarn": "System disk CoW backing chain is {depth} layers deep (\u003e= 2); read-through slows small-file I/O — consider flattening or re-deriving from the base image",
"diagExternalDriveWarn": "The data folder is on an external or network drive ({dir}); disk access will be slow",
"diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter",
"discardSuspend": "Discard saved state",
"discardSuspendConfirm": "Discard \u0026 Power Off",
"discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.",
"discardSuspendTitle": "Discard saved state for “{name}”?",
"displayNameEdit": "Click to change the display name",
"displayNameEditEllipsis": "Change Display Name…",
"displayNameLabel": "Display name",
@@ -236,6 +261,7 @@ export const vmEn: Record<string, string> = {
"failAttachInstaller": "Couldn’t attach the image",
"failCloneVM": "Couldn’t create CoW clone",
"failDelete": "Couldn’t delete",
"failDiscardSuspend": "Couldn’t discard saved state",
"failEject": "Couldn’t eject the installer",
"failEnterRecovery": "Couldn’t enter recovery mode",
"failExportDiagnostics": "Couldn’t export diagnostics",
@@ -245,10 +271,12 @@ export const vmEn: Record<string, string> = {
"failGuestTools": "Guest Tools operation failed",
"failOpenFolder": "Couldn’t open the folder",
"failRestart": "Couldn’t restart",
"failResume": "Couldn’t resume",
"failScreenshot": "Screenshot failed",
"failSnapshot": "Restore point failed",
"failStart": "Couldn’t start",
"failStop": "Couldn’t shut down",
"failSuspend": "Couldn’t suspend",
"failType": "Couldn’t type into the VM",
"failUpgradeNVMe": "Couldn’t upgrade to NVMe",
"fieldAudio": "Audio",
@@ -306,6 +334,8 @@ export const vmEn: Record<string, string> = {
"pendingTitle": "Applies on next start",
"pickRecoveryTitle": "Choose an offline image (.img / .dmg)",
"restartToApply": "Restart to apply",
"resume": "Resume",
"resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM",
"sendText": "Send text to VM…",
"sendTextConfirm": "Send (Ctrl+Enter)",
"sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.",
@@ -350,14 +380,24 @@ export const vmEn: Record<string, string> = {
"state_broken": "Error",
"state_creating": "Creating",
"state_driver_unavailable": "Driver unavailable",
"state_resuming": "Resuming",
"state_running": "Running",
"state_starting": "Starting",
"state_stopped": "Stopped",
"state_stopping": "Stopping",
"state_suspended": "Suspended",
"state_suspending": "Suspending",
"suspend": "Suspend",
"suspendedGuestToolsHint": "Resume or discard saved state to make changes",
"suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.",
"suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.",
"suspendedNoticeTitle": "Saved state ready",
"suspendedSettingsHint": "Resume or discard saved state before changing settings",
"techInfo": "Technical details",
"toastCloned": "CoW clone “{name}” created",
"toastDeleted": "{name} deleted",
"toastDiagExported": "Redacted diagnostics archive exported (.zip)",
"toastDiscardSuspend": "Discarded saved state for {name}",
"toastEjected": "Installer ejected",
"toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start",
"toastEnterRecoveryNextStart": "Recovery mode ready — restart to open the boot menu",
@@ -377,11 +417,13 @@ export const vmEn: Record<string, string> = {
"toastOnlineRecoveryStarted": "Downloading online recovery image (~1 GB); will attach when ready",
"toastPreventSleepOff": "Prevent-sleep guard disabled",
"toastPreventSleepOn": "Prevent-sleep guard enabled",
"toastResumed": "{name} resumed",
"toastScreenshotCopied": "VM screenshot copied",
"toastSnapshotCreated": "Created restore point {name}",
"toastSnapshotDeleted": "Deleted restore point {name}",
"toastSnapshotRestored": "Restored to {name}",
"toastStopped": "{name} shut down",
"toastSuspended": "{name} suspended",
"toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}",
"toggleFullscreen": "Toggle full screen",
"typeClipboard": "Send clipboard to VM",
+21
View File
@@ -137,6 +137,10 @@ export type I18nKey =
| "diagBackingChainWarn"
| "diagExternalDriveWarn"
| "diagHighMemWarn"
| "discardSuspend"
| "discardSuspendConfirm"
| "discardSuspendDesc"
| "discardSuspendTitle"
| "diskCompactAction"
| "diskCompactDesc"
| "diskCompactDone"
@@ -202,6 +206,7 @@ export type I18nKey =
| "failCloneVM"
| "failCreate"
| "failDelete"
| "failDiscardSuspend"
| "failDownload"
| "failEject"
| "failEnterRecovery"
@@ -213,12 +218,14 @@ export type I18nKey =
| "failGuestTools"
| "failOpenFolder"
| "failRestart"
| "failResume"
| "failRuntime"
| "failSSH"
| "failScreenshot"
| "failSnapshot"
| "failStart"
| "failStop"
| "failSuspend"
| "failType"
| "failUpgradeNVMe"
| "fieldAudio"
@@ -617,6 +624,8 @@ export type I18nKey =
| "resolution"
| "restart"
| "restartToApply"
| "resume"
| "resumeUnavailable"
| "runtimeAlpha"
| "runtimeAlphaHint"
| "runtimeChannel_alpha"
@@ -740,10 +749,13 @@ export type I18nKey =
| "state_broken"
| "state_creating"
| "state_driver_unavailable"
| "state_resuming"
| "state_running"
| "state_starting"
| "state_stopped"
| "state_stopping"
| "state_suspended"
| "state_suspending"
| "statsCPU"
| "statsDisk"
| "statsDiskSub"
@@ -774,6 +786,12 @@ export type I18nKey =
| "summarySSH"
| "summarySSHPort"
| "summarySource"
| "suspend"
| "suspendedGuestToolsHint"
| "suspendedNoticeDesc"
| "suspendedNoticeDescWithTime"
| "suspendedNoticeTitle"
| "suspendedSettingsHint"
| "taskAppUpdate"
| "taskCreate"
| "taskDownload"
@@ -800,6 +818,7 @@ export type I18nKey =
| "toastCreated"
| "toastDeleted"
| "toastDiagExported"
| "toastDiscardSuspend"
| "toastDownloadPaused"
| "toastEjected"
| "toastEnterRecovery"
@@ -822,6 +841,7 @@ export type I18nKey =
| "toastPreventSleepOff"
| "toastPreventSleepOn"
| "toastQueueCanceled"
| "toastResumed"
| "toastRuntimeReady"
| "toastSSHConfigWritten"
| "toastSSHUserSaved"
@@ -832,6 +852,7 @@ export type I18nKey =
| "toastSnapshotDeleted"
| "toastSnapshotRestored"
| "toastStopped"
| "toastSuspended"
| "toastTyped"
| "toggleFullscreen"
| "typeClipboard"
+9 -2
View File
@@ -292,6 +292,10 @@ h1, h2, h3, p { margin: 0; }
.status { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; display: inline-block; }
.status-running { background: var(--status-running); }
.status-stopped { border: 1.5px solid var(--status-idle); }
.status-suspended {
width: 7px; height: 8px; border-radius: 0;
background: linear-gradient(90deg, var(--status-busy) 0 2.5px, transparent 2.5px 4.5px, var(--status-busy) 4.5px 7px);
}
.status-busy { background: conic-gradient(var(--status-busy) 0 50%, transparent 50% 100%); border: 1.5px solid var(--status-busy); animation: pulse 1.4s ease-in-out infinite; }
.status-warn { background: var(--status-busy); }
.status-broken { background: var(--status-error); border-radius: 1.5px; transform: rotate(45deg); width: 7px; height: 7px; }
@@ -366,6 +370,7 @@ h1, h2, h3, p { margin: 0; }
.vm-hero-pill.is-running {
background: var(--ok-soft); border-color: transparent; color: var(--ok-text);
}
.vm-hero-pill.is-suspended,
.vm-hero-pill.is-busy {
background: var(--warn-soft); border-color: transparent; color: var(--warn-text);
}
@@ -952,8 +957,10 @@ button.status-issue + .status-metric { margin-left: 6px; }
.toast[data-swipe="cancel"] { transform: translateX(0); transition: transform var(--dur) var(--ease-out); }
.toast[data-swipe="end"] { animation: toast-swipe-out var(--dur-fast) var(--ease-out) both; }
:root[dir="rtl"] .toast[data-swipe="end"] { animation: toast-swipe-out-rtl var(--dur-fast) var(--ease-out) both; }
.toast-main-row { display: flex; align-items: flex-start; gap: var(--sp-3); width: 100%; min-width: 0; }
.toast-main-row > svg { margin-top: 2px; flex-shrink: 0; }
.toast-main-row { display: flex; align-items: center; gap: var(--sp-3); width: 100%; min-width: 0; }
.toast-main-row > svg { flex-shrink: 0; }
.toast-main-row:has(.toast-desc) { align-items: flex-start; }
.toast-main-row:has(.toast-desc) > svg { margin-top: 2px; }
.toast.ok .toast-main-row > svg { color: var(--status-running); }
.toast.error .toast-main-row > svg { color: var(--status-error); }
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
+2 -1
View File
@@ -48,7 +48,7 @@ export type RemoteRuntime = Model<runtime.Remote> & {
}
export type VMListItem = Model<reims.VMListItem> & {
state: 'running' | 'stopped' | 'broken'
state: 'running' | 'stopped' | 'suspended' | 'broken'
}
export type PendingChange = app.PendingChange
@@ -63,6 +63,7 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
}
export type AppUpdateInfo = version.UpdateInfo
export type SuspendInfo = reims.SuspendInfo
export type VMDetail = reims.VMDetail
export type VMStats = app.VMStats
export type DriveShareSettings = Model<app.DriveShareSettings>
+3 -2
View File
@@ -87,11 +87,12 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
)
IconButton.displayName = 'IconButton'
export type StatusKind = 'running' | 'stopped' | 'busy' | 'broken' | 'warn'
export type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn'
export function statusKind(state: string): StatusKind {
if (state === 'running') return 'running'
if (state === 'starting' || state === 'stopping' || state === 'creating') return 'busy'
if (state === 'suspended') return 'suspended'
if (state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' || state === 'creating') return 'busy'
if (state === 'driver_unavailable') return 'warn'
if (state === 'broken') return 'broken'
return 'stopped'
+31 -1
View File
@@ -1,7 +1,37 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import * as RDialog from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import React from 'react'
import { IconButton } from './controls'
import { Button, IconButton } from './controls'
interface ConfirmDialogProps {
title: string
description: string
cancelLabel: string
confirmLabel: string
onCancel: () => void
onConfirm: () => void
children?: React.ReactNode
}
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<div className="dialog-body">
<Alert.Title className="dialog-title">{title}</Alert.Title>
<Alert.Description className="dialog-desc">{description}</Alert.Description>
{children}
</div>
<div className="dialog-foot">
<Alert.Cancel asChild><Button>{cancelLabel}</Button></Alert.Cancel>
<Alert.Action asChild><Button variant="danger" onClick={onConfirm}>{confirmLabel}</Button></Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
interface Props {
title: string
+1
View File
@@ -180,6 +180,7 @@ export const events = {
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb),
onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb),
onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb),
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
emitUIPong: () => eventsEmit('reims:ui-pong'),
+6
View File
@@ -47,6 +47,8 @@ export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
export function DiscardSuspend(arg1:string):Promise<void>;
export function DeliverFileToGuest(arg1:string):Promise<string>;
export function DeliverPathsToGuest(arg1:string,arg2:Array<string>):Promise<Array<string>>;
@@ -183,6 +185,8 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeRe
export function RestartVM(arg1:string):Promise<void>;
export function ResumeVM(arg1:string):Promise<void>;
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
@@ -225,6 +229,8 @@ export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
export function SuspendVM(arg1:string):Promise<void>;
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
export function ToggleVMFullscreen(arg1:string):Promise<boolean>;
+12
View File
@@ -78,6 +78,10 @@ export function DeleteVM(arg1, arg2) {
return window['go']['app']['App']['DeleteVM'](arg1, arg2);
}
export function DiscardSuspend(arg1) {
return window['go']['app']['App']['DiscardSuspend'](arg1);
}
export function DeliverFileToGuest(arg1) {
return window['go']['app']['App']['DeliverFileToGuest'](arg1);
}
@@ -350,6 +354,10 @@ export function RestartVM(arg1) {
return window['go']['app']['App']['RestartVM'](arg1);
}
export function ResumeVM(arg1) {
return window['go']['app']['App']['ResumeVM'](arg1);
}
export function RestoreSnapshot(arg1, arg2) {
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
}
@@ -434,6 +442,10 @@ export function SuggestLanguagePack() {
return window['go']['app']['App']['SuggestLanguagePack']();
}
export function SuspendVM(arg1) {
return window['go']['app']['App']['SuspendVM'](arg1);
}
export function ToggleBorderless(arg1, arg2) {
return window['go']['app']['App']['ToggleBorderless'](arg1, arg2);
}
+70
View File
@@ -6,6 +6,7 @@ export namespace app {
optimizations: host.Optimization[];
runtimes: runtime.Installed[];
active_runtime?: runtime.Installed;
can_suspend: boolean;
vms: reims.VMListItem[];
transitions: Record<string, string>;
pending_changes: Record<string, Array<PendingChange>>;
@@ -30,6 +31,7 @@ export namespace app {
this.optimizations = this.convertValues(source["optimizations"], host.Optimization);
this.runtimes = this.convertValues(source["runtimes"], runtime.Installed);
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
this.can_suspend = source["can_suspend"];
this.vms = this.convertValues(source["vms"], reims.VMListItem);
this.transitions = source["transitions"];
this.pending_changes = this.convertValues(source["pending_changes"], Array<PendingChange>, true);
@@ -411,6 +413,7 @@ export namespace app {
uptime_seconds: number;
guest_tools_connected: boolean;
guest_tools_mount_mode?: string;
guest_tools_agent_version?: number;
guest_tools_sleep_guard: boolean;
static createFrom(source: any = {}) {
@@ -435,6 +438,7 @@ export namespace app {
this.uptime_seconds = source["uptime_seconds"];
this.guest_tools_connected = source["guest_tools_connected"];
this.guest_tools_mount_mode = source["guest_tools_mount_mode"];
this.guest_tools_agent_version = source["guest_tools_agent_version"];
this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"];
}
}
@@ -2296,6 +2300,52 @@ export namespace reims {
this.guest_lang = source["guest_lang"];
}
}
export class SuspendInfo {
schema_version: number;
vm_name: string;
cpus: number;
memory: string;
graphics: string;
displays: number;
resolution: string;
disk_controller: string;
cpu_model?: string;
audio: boolean;
audio_backend?: string;
network: boolean;
ssh_port: number;
extra_args?: string;
runtime_commit: string;
vendor_qemu_commit?: string;
created_at: string;
vmstate_size: number;
static createFrom(source: any = {}) {
return new SuspendInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.schema_version = source["schema_version"];
this.vm_name = source["vm_name"];
this.cpus = source["cpus"];
this.memory = source["memory"];
this.graphics = source["graphics"];
this.displays = source["displays"];
this.resolution = source["resolution"];
this.disk_controller = source["disk_controller"];
this.cpu_model = source["cpu_model"];
this.audio = source["audio"];
this.audio_backend = source["audio_backend"];
this.network = source["network"];
this.ssh_port = source["ssh_port"];
this.extra_args = source["extra_args"];
this.runtime_commit = source["runtime_commit"];
this.vendor_qemu_commit = source["vendor_qemu_commit"];
this.created_at = source["created_at"];
this.vmstate_size = source["vmstate_size"];
}
}
export class VMDetail {
name: string;
state: string;
@@ -2337,6 +2387,7 @@ export namespace reims {
guest_tools_disabled?: boolean;
shared_dir?: string;
guest_lang?: string;
suspend_info?: SuspendInfo;
static createFrom(source: any = {}) {
return new VMDetail(source);
@@ -2384,7 +2435,26 @@ export namespace reims {
this.guest_tools_disabled = source["guest_tools_disabled"];
this.shared_dir = source["shared_dir"];
this.guest_lang = source["guest_lang"];
this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class VMListItem {
name: string;
+77 -17
View File
@@ -43,6 +43,7 @@ type AppState struct {
Optimizations []host.Optimization `json:"optimizations"`
Runtimes []rt.Installed `json:"runtimes"`
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
CanSuspend bool `json:"can_suspend"`
VMs []reims.VMListItem `json:"vms"`
Transitions map[string]string `json:"transitions"`
PendingChanges map[string][]PendingChange `json:"pending_changes"`
@@ -220,7 +221,7 @@ func (a *App) shutdown(ctx context.Context) {
// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`.
// Start, stop and delete call wakePoll so their result shows up at once.
const (
pollBusy = 2 * time.Second
pollBusy = 2 * time.Second
// Exits are caught at once by watchExits and GUI actions call wakePoll, so
// the steady tick only has to notice VMs started or removed elsewhere (CLI).
pollSteady = 10 * time.Second
@@ -265,6 +266,7 @@ func (a *App) pollVMs(ctx context.Context) {
if err != nil {
continue
}
enrichVMListStates(vms)
watchExits(ctx, vms, exitWatched, a.wakePoll)
type pinCandidate struct {
name string
@@ -291,7 +293,10 @@ func (a *App) pollVMs(ctx context.Context) {
}
}
if tr, ok := a.transitions[vm.Name]; ok {
if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") {
if (tr == "starting" && vm.State == "running") ||
(tr == "stopping" && vm.State == "stopped") ||
(tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) ||
(tr == "resuming" && vm.State == "running") {
delete(a.transitions, vm.Name)
if vm.State == "stopped" {
delete(a.pendingChanges, vm.Name)
@@ -454,7 +459,12 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) {
if err != nil {
return nil, err
}
return c.List(ctx)
vms, err := c.List(ctx)
if err != nil {
return nil, err
}
enrichVMListStates(vms)
return vms, nil
}
// qemuImage is the executable reims-ctl reports as a running VM's PID.
@@ -649,6 +659,7 @@ func (a *App) GetState() AppState {
Optimizations: opts,
Runtimes: runtimes,
ActiveRuntime: active,
CanSuspend: active != nil && active.Manifest.HasCapability("vm-suspend"),
VMs: vms,
Transitions: trCopy,
PendingChanges: pcCopy,
@@ -673,12 +684,17 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
if err != nil {
return d, err
}
d.RecoveryMode = isRecoveryModeActive(d)
a.populateGuestToolsDetail(&d)
a.populateGuestLangDetail(&d)
a.populateVMDetail(&d)
return d, nil
}
func (a *App) populateVMDetail(d *reims.VMDetail) {
d.RecoveryMode = isRecoveryModeActive(*d)
a.populateGuestToolsDetail(d)
a.populateGuestLangDetail(d)
a.populateSuspendDetail(d)
}
func (a *App) SetLocale(raw string) error {
a.mu.Lock()
a.cfg.Locale = i18n.ParsePreference(raw)
@@ -767,6 +783,7 @@ func (a *App) startTray() {
},
GetSnapshot: func() tray.Snapshot {
a.mu.Lock()
cfgCopy := *a.cfg
loc := a.cfg.Locale
cached := append([]reims.VMListItem(nil), a.lastVMs...)
transitions := make(map[string]string, len(a.transitions))
@@ -774,6 +791,10 @@ func (a *App) startTray() {
transitions[k] = v
}
a.mu.Unlock()
canSuspend := false
if active, err := rt.ResolveActive(&cfgCopy); err == nil && active != nil {
canSuspend = active.Manifest.HasCapability("vm-suspend")
}
if len(cached) == 0 {
if vms, err := a.listVMsInternal(context.Background()); err == nil {
cached = vms
@@ -797,9 +818,10 @@ func (a *App) startTray() {
}
effLoc := i18n.EffectiveLocale(loc)
return tray.Snapshot{
Locale: effLoc,
LocaleZh: effLoc == i18n.ZhCN,
VMs: items,
Locale: effLoc,
LocaleZh: effLoc == i18n.ZhCN,
CanSuspend: canSuspend,
VMs: items,
}
},
})
@@ -827,6 +849,15 @@ func (a *App) trayVMAction(name string, act tray.Action) {
switch act {
case tray.ActStart:
err, failTitle = a.StartVM(name), i18n.M(loc, "tray.notify.start_fail", vars)
case tray.ActSuspend:
err, failTitle = a.SuspendVM(name), i18n.M(loc, "tray.notify.suspend_fail", vars)
case tray.ActResume:
err, failTitle = a.ResumeVM(name), i18n.M(loc, "tray.notify.resume_fail", vars)
case tray.ActDiscardSuspend:
a.ShowMainWindow()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:tray-discard-suspend", name)
}
case tray.ActStop:
err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
case tray.ActForceStop:
@@ -878,7 +909,13 @@ func (a *App) SetDataRoot(dir string) error {
curAppUpdateChannel := a.cfg.AppUpdateChannel
curMinToTray := a.cfg.MinimizeToTray
for _, v := range a.lastVMs {
if v.State == "running" || v.State == "starting" || v.State == "stopping" {
if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
for _, tr := range a.transitions {
if tr != "" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
@@ -1063,10 +1100,16 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
}
func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
cur, err := a.GetVMDetail(opts.Name)
c, err := a.client()
if err != nil {
return err
}
cur, release, err := vmstart.LockVM(a.baseCtx(), c, opts.Name)
if err != nil {
return err
}
defer release()
a.populateVMDetail(&cur)
a.mu.Lock()
root := a.cfg.DataRoot
loc := a.cfg.Locale
@@ -1074,10 +1117,6 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
c, err := a.client()
if err != nil {
return err
}
w := vmstart.LineWriter(func(line string) { a.emitLog(opts.Name, line) })
if reims.HasCtlSetChanges(opts) {
if err := c.Set(context.Background(), opts, w, w); err != nil {
@@ -1235,7 +1274,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
a.mu.Lock()
tr := a.transitions[name]
a.mu.Unlock()
if tr == "stopping" {
if tr == "stopping" || tr == "suspending" {
return
}
@@ -1313,6 +1352,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
s = reims.StripIncomingDeferArgs(s)
return strings.TrimSpace(s)
}
@@ -1322,6 +1362,14 @@ func (a *App) StartVM(name string) error {
return err
}
c := prep.Client
curDetail, release, err := vmstart.LockVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
if curDetail.State == "stopped" && reims.HasSuspendState(curDetail.Directory) {
return a.resumeLocked(prep, curDetail)
}
a.mu.Lock()
root := a.cfg.DataRoot
tmpDir := a.cfg.TempDir()
@@ -1331,7 +1379,6 @@ func (a *App) StartVM(name string) error {
a.emitLog(name, "Start refused: "+err.Error())
return err
}
curDetail, _ := c.Show(context.Background(), name)
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
a.emitLog(name, "Start refused: "+err.Error())
return err
@@ -1470,6 +1517,11 @@ func (a *App) StopVM(name string, force bool) error {
if err != nil {
return err
}
release, err := vmstart.LockVMForStop(a.baseCtx(), c, name, force)
if err != nil {
return err
}
defer release()
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.mu.Lock()
@@ -1538,6 +1590,14 @@ func (a *App) EjectInstaller(name string) error {
if err != nil {
return err
}
d, release, err := vmstart.LockVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
if a.isVMSuspended(d) {
return i18n.NewCodedError(a.locale(), "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
a.emitLog(name, "Ejecting installer from "+name+"...")
if err := c.Eject(context.Background(), name, w, w); err != nil {
+6 -1
View File
@@ -39,13 +39,18 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
src, err := a.GetVMDetail(sourceName)
src, release, err := vmstart.LockVM(ctx, c, sourceName)
if err != nil {
return err
}
defer release()
a.populateVMDetail(&src)
if a.isVMRunning(ctx, c, sourceName, src) {
return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil)
}
if a.isVMSuspended(src) {
return i18n.NewCodedError(loc, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil)
}
if src.HasInstaller {
return i18n.NewCodedError(loc, "E_VM_CLONE_RECOVERY", "err.clone.in_recovery", i18n.Vars{"name": sourceName}, nil)
}
+11 -2
View File
@@ -7,6 +7,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -24,13 +25,17 @@ func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error)
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockVM(ctx, c, name)
if err != nil {
return reims.DiskResizeResult{}, err
}
defer release()
if a.isVMRunning(ctx, c, name, d) {
return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
}
if a.isVMSuspended(d) {
return reims.DiskResizeResult{}, fmt.Errorf("resume or discard suspend state for %s before resizing its disk", name)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
@@ -70,13 +75,17 @@ func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) {
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockVM(ctx, c, name)
if err != nil {
return reims.DiskCompactResult{}, err
}
defer release()
if a.isVMRunning(ctx, c, name, d) {
return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
}
if a.isVMSuspended(d) {
return reims.DiskCompactResult{}, fmt.Errorf("resume or discard suspend state for %s before reclaiming disk space", name)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
+4 -5
View File
@@ -225,13 +225,11 @@ func (a *App) AttachGuestTools(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
if d.Directory == "" {
return fmt.Errorf("VM %s has no directory", name)
}
defer release()
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
return err
@@ -281,10 +279,11 @@ func (a *App) DetachGuestTools(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
ctx := context.Background()
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
+8 -4
View File
@@ -80,10 +80,11 @@ func (a *App) EnterRecovery(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
@@ -126,10 +127,11 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
if err != nil {
return "", err
}
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return "", err
}
defer release()
path := strings.TrimSpace(installerPath)
if path == "" {
path, err = a.pickCachedRecoveryInstaller()
@@ -232,10 +234,11 @@ func (a *App) FinishInstall(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
@@ -325,10 +328,11 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
if d.HasInstaller {
return errors.New("exit recovery mode (eject installer) before switching disk controller")
}
+6 -1
View File
@@ -9,6 +9,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -78,13 +79,17 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
c := reims.NewClient(&cfgCopy, *active)
ctx := a.baseCtx()
d, err := a.GetVMDetail(name)
d, release, err := vmstart.LockVM(ctx, c, name)
if err != nil {
return err
}
defer release()
if a.isVMRunning(ctx, c, name, d) {
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil)
}
if a.isVMSuspended(d) {
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
diskPath := resolveVMDiskPath(d)
if diskPath == "" {
return i18n.NewCodedError(loc, "E_SNAPSHOT_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": name}, nil)
+7 -4
View File
@@ -27,9 +27,11 @@ type VMStats struct {
DiskBackingBroken bool `json:"disk_backing_broken,omitempty"`
DiskBackingDepthWarn bool `json:"disk_backing_depth_warn,omitempty"`
UptimeSeconds int64 `json:"uptime_seconds"`
GuestToolsConnected bool `json:"guest_tools_connected"`
GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"`
GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"`
GuestToolsConnected bool `json:"guest_tools_connected"`
GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"`
GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"`
GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"`
}
func resolveVMDiskPath(d reims.VMDetail) string {
@@ -53,7 +55,7 @@ func resolveVMDiskPath(d reims.VMDetail) string {
}
// GetVMStats samples QEMU CPU/memory usage (when running), disk actual vs
// virtual capacity, and live Guest Tools 2.0 connection state.
// virtual capacity, and live Guest Tools status.
func (a *App) GetVMStats(name string) (VMStats, error) {
stats := VMStats{Name: name}
c, err := a.client()
@@ -114,6 +116,7 @@ func (a *App) GetVMStats(name string) (VMStats, error) {
st := srv.Status(name, 15*time.Second)
stats.GuestToolsConnected = st.Connected
stats.GuestToolsMountMode = st.MountMode
stats.GuestToolsAgentVersion = st.AgentVersion
stats.GuestToolsSleepGuard = st.SleepActive
}
return stats, nil
+196
View File
@@ -0,0 +1,196 @@
package app
import (
"fmt"
"os"
"time"
"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/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func enrichVMListStates(vms []reims.VMListItem) {
for i := range vms {
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
vms[i].State = "suspended"
}
}
}
func (a *App) populateSuspendDetail(d *reims.VMDetail) {
if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) {
d.State = "suspended"
if info, err := reims.ReadSuspendInfo(d.Directory); err == nil {
d.SuspendInfo = info
}
}
}
func (a *App) isVMSuspended(d reims.VMDetail) bool {
return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory))
}
// SuspendVM saves a VM's running state and closes its QEMU process.
func (a *App) SuspendVM(name string) error {
prep, err := a.prep(name)
if err != nil {
return err
}
ctx := a.baseCtx()
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
defer release()
end, err := a.beginSuspendTransition(name, "suspending")
if err != nil {
return err
}
defer end()
a.mu.Lock()
mgr, gt := a.pluginMgr, a.guestTools
a.mu.Unlock()
event := plugin.VMEventPayload{VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, event)
}
lastPct := -1
info, err := prep.SuspendSnapshot(ctx, d, func(p qmp.MigrateProgress) {
if p.Total > 0 {
pct := int(p.Transferred * 100 / p.Total)
if pct >= lastPct+25 || p.Status == "completed" {
lastPct = pct
a.emitLog(name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
}
}
})
if err != nil {
a.emitLog(name, "Suspend error: "+err.Error())
return err
}
a.cancelRebootWatcher(name)
stopVMMonitor(name)
if gt != nil {
gt.UnregisterVM(name)
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, event)
}
a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(info.VMStateSize)/float64(1<<30)))
return nil
}
// ResumeVM restores a suspended VM with its original media and devices.
func (a *App) ResumeVM(name string) error {
prep, err := a.prep(name)
if err != nil {
return err
}
d, release, err := vmstart.LockVM(a.baseCtx(), prep.Client, name)
if err != nil {
return err
}
defer release()
return a.resumeLocked(prep, d)
}
func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error {
name := d.Name
end, err := a.beginSuspendTransition(name, "resuming")
if err != nil {
return err
}
defer end()
a.mu.Lock()
root, tmpDir, mgr := a.cfg.DataRoot, a.cfg.TempDir(), a.pluginMgr
a.mu.Unlock()
rep := host.Inspect(root)
var qmpAddr string
if d.State == "stopped" && reims.HasSuspendState(d.Directory) && rep.NeedsColdRebootWorkaround {
sockPath := qmp.RebootSocketPath(d.Directory, tmpDir, name)
if qmp.HasWin10RebootUnixArgs(d.ExtraArgs, sockPath) {
a.cancelRebootWatcher(name)
if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove stale reboot socket: %w", err)
}
qmpAddr = "unix:" + sockPath
}
}
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...)
}
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) {
prep.Client.Env = append(prep.Client.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
startAt := time.Now()
out := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
if err := prep.ResumeSnapshot(a.baseCtx(), d, rep, out, out); err != nil {
a.emitLog(name, "Resume error: "+err.Error())
return err
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, QMPAddr: qmpAddr,
})
} else if qmpAddr != "" {
a.watchWin10ColdReboot(name, qmpAddr)
}
a.startVMMonitor(name, d, startAt)
a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds()))
return nil
}
// DiscardSuspend deletes a stopped VM's saved execution state.
func (a *App) DiscardSuspend(name string) error {
c, err := a.client()
if err != nil {
return err
}
d, release, err := vmstart.LockVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
if err := vmstart.DiscardSnapshot(a.locale(), d); err != nil {
return err
}
a.emitLog(name, "Discarded suspend state for "+name)
a.wakePoll()
a.emitStateChanged()
return nil
}
func (a *App) beginSuspendTransition(name, state string) (func(), error) {
a.mu.Lock()
loc := a.cfg.Locale
if a.transitions[name] != "" {
a.mu.Unlock()
return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
}
a.transitions[name] = state
a.mu.Unlock()
a.emitStateChanged()
return func() {
a.mu.Lock()
delete(a.transitions, name)
a.mu.Unlock()
a.wakePoll()
a.emitStateChanged()
}, nil
}
func (a *App) emitStateChanged() {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}
+65
View File
@@ -0,0 +1,65 @@
package app
import (
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/driver/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
suspendedDir := t.TempDir()
stoppedDir := t.TempDir()
if err := os.WriteFile(reims.SuspendStatePath(suspendedDir)+".tmp", []byte("0123456789"), 0o600); err != nil {
t.Fatal(err)
}
media := filepath.Join(suspendedDir, "disk.qcow2")
for _, path := range []string{media, filepath.Join(suspendedDir, "vm.toml")} {
if err := os.WriteFile(path, []byte("state"), 0o600); err != nil {
t.Fatal(err)
}
}
if _, err := reims.SealSuspend(
reims.VMDetail{Name: "mac-a", Directory: suspendedDir, CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"},
rt.Installed{Commit: "3731afd"},
[]string{media},
); err != nil {
t.Fatal(err)
}
vms := []reims.VMListItem{
{Name: "mac-a", Dir: suspendedDir, State: "stopped"},
{Name: "mac-b", Dir: stoppedDir, State: "stopped"},
{Name: "mac-c", Dir: suspendedDir, State: "running"},
}
enrichVMListStates(vms)
if vms[0].State != "suspended" {
t.Fatalf("mac-a state = %q, want suspended", vms[0].State)
}
if vms[1].State != "stopped" {
t.Fatalf("mac-b state = %q, want stopped", vms[1].State)
}
if vms[2].State != "running" {
t.Fatalf("running VM must stay running, got %q", vms[2].State)
}
a := &App{}
det := reims.VMDetail{Name: "mac-a", Directory: suspendedDir, State: "stopped"}
a.populateSuspendDetail(&det)
if det.State != "suspended" || det.SuspendInfo == nil || det.SuspendInfo.VMStateSize != 10 {
t.Fatalf("populateSuspendDetail failed: %+v", det)
}
if !a.isVMSuspended(det) {
t.Fatal("expected isVMSuspended=true")
}
}
func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) {
got := stripLegacyManagedExtraArgs("-machine kernel-irqchip=on -incoming defer")
if got != "-machine kernel-irqchip=on" {
t.Fatalf("stripLegacyManagedExtraArgs = %q", got)
}
}
+57 -3
View File
@@ -134,6 +134,9 @@ func printUsage(loc i18n.Locale) {
"cli.usage.cmd_vm_compact",
"cli.usage.cmd_vm_start",
"cli.usage.cmd_vm_stop",
"cli.usage.cmd_vm_suspend",
"cli.usage.cmd_vm_resume",
"cli.usage.cmd_vm_discard_suspend",
"cli.usage.cmd_vm_type",
"cli.usage.cmd_inst_list",
"cli.usage.cmd_inst_dl",
@@ -370,7 +373,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject|type>")
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|suspend|resume|discard-suspend|eject|type>")
}
prep, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
if err != nil {
@@ -389,6 +392,13 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
fmt.Println(i18n.T(loc, "vm.empty"))
return nil
}
for i := range vms {
if st, _ := vms[i]["state"].(string); st == "stopped" {
if dir, _ := vms[i]["dir"].(string); reims.HasSuspendState(dir) {
vms[i]["state"] = "suspended"
}
}
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(vms)
@@ -519,6 +529,14 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
AudioBackend: strings.TrimSpace(*audioBackend),
GuestLang: strings.TrimSpace(*guestLang),
}
d, release, err := vmstart.LockVM(ctx, client, setOpts.Name)
if err != nil {
return err
}
defer release()
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(loc, "E_SET_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": setOpts.Name}, nil)
}
if reims.HasCtlSetChanges(setOpts) {
if err := client.Set(ctx, setOpts, os.Stdout, os.Stderr); err != nil {
return err
@@ -543,11 +561,39 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm stop <name>")
}
release, err := vmstart.LockVMForStop(ctx, client, args[1], false)
if err != nil {
return err
}
defer release()
return client.Stop(ctx, args[1], os.Stdout, os.Stderr)
case "suspend":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm suspend <name>")
}
return suspendVM(ctx, cfg, prep, args[1])
case "resume":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm resume <name>")
}
return resumeVM(ctx, cfg, prep, args[1])
case "discard-suspend":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm discard-suspend <name>")
}
return discardSuspendVM(ctx, cfg, prep, args[1])
case "eject":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm eject <name>")
}
d, release, err := vmstart.LockVM(ctx, client, args[1])
if err != nil {
return err
}
defer release()
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(loc, "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil)
}
return client.Eject(ctx, args[1], os.Stdout, os.Stderr)
case "type":
// Paste as keystrokes: the text argument, else stdin.
@@ -576,13 +622,17 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
if len(args) < 3 {
return fmt.Errorf("usage: reims-go vm resize <name> <size> (e.g. 256G or +64G)")
}
d, err := client.Show(ctx, args[1])
d, release, err := vmstart.LockVM(ctx, client, args[1])
if err != nil {
return err
}
defer release()
if d.State == "running" {
return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1]))
}
if reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(loc, "E_RESIZE_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil)
}
diskPath := resolveCLIDiskPath(d)
res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), client.Env, diskPath, args[2], os.Stdout, os.Stderr)
if err != nil {
@@ -595,13 +645,17 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm compact <name>")
}
d, err := client.Show(ctx, args[1])
d, release, err := vmstart.LockVM(ctx, client, args[1])
if err != nil {
return err
}
defer release()
if d.State == "running" {
return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1]))
}
if reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(loc, "E_COMPACT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil)
}
diskPath := resolveCLIDiskPath(d)
res, err := reims.CompactDisk(ctx, active.QemuImgPath(), client.Env, diskPath, os.Stdout, os.Stderr)
if err != nil {
+12
View File
@@ -11,6 +11,7 @@ import (
"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/plugin"
@@ -49,6 +50,17 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
if viaWindow && windowHandoffWorks {
return startInWindow(ctx, cfg, name)
}
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
defer release()
if d.State == "running" {
return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name))
}
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
return resumeLocked(ctx, cfg, prep, d, rep)
}
// Honour the core plugin's WHPX setting, as the window does.
st := plugin.ReadState(cfg.DataRoot)
+71
View File
@@ -0,0 +1,71 @@
package cli
import (
"context"
"fmt"
"os"
"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/vmstart"
)
func suspendVM(ctx context.Context, _ *config.Config, prep *vmstart.Prep, name string) error {
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
defer release()
fmt.Fprintf(os.Stderr, "Suspending %s to %s...\n", name, reims.SuspendStateFileName)
info, err := prep.SuspendSnapshot(ctx, d, nil)
if err != nil {
return err
}
fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(info.VMStateSize)/float64(1<<30))
return nil
}
func resumeVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
defer release()
return resumeLocked(ctx, cfg, prep, d, host.Inspect(cfg.DataRoot))
}
func resumeLocked(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, d reims.VMDetail, rep host.Report) error {
fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", d.Name, reims.SuspendStateFileName)
startAt := time.Now()
if err := prep.ResumeSnapshot(ctx, d, rep, os.Stdout, os.Stderr); err != nil {
return err
}
if vms, err := prep.Client.List(ctx); err == nil {
for _, vm := range vms {
if vm.Name != d.Name || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
continue
}
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, d.Directory, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
fmt.Fprintln(os.Stderr, line)
}
}
}
fmt.Printf("Resumed %s in %.1fs\n", d.Name, time.Since(startAt).Seconds())
return nil
}
func discardSuspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
defer release()
if err := vmstart.DiscardSnapshot(cfg.Locale, d); err != nil {
return err
}
fmt.Printf("Discarded suspend state for %s\n", name)
return nil
}
+16
View File
@@ -6,6 +6,7 @@ import (
"os"
"path/filepath"
"runtime"
"strings"
"github.com/Nwflower/reims-go/internal/i18n"
)
@@ -53,6 +54,21 @@ func DefaultDataRoot() string {
return filepath.Join(home, "reims-go-data")
}
// ExpandHomePath resolves a leading ~ for the current user.
func ExpandHomePath(path string) string {
if path != "~" && !strings.HasPrefix(path, "~/") && !strings.HasPrefix(path, `~\`) {
return path
}
home, err := os.UserHomeDir()
if err != nil {
return path
}
if path == "~" {
return home
}
return filepath.Join(home, path[2:])
}
// CurrentDataRoot is the data folder in effect: REIMS_GO_DATA_ROOT, else the
// folder chosen at first launch (LocationPath), else DefaultDataRoot.
func CurrentDataRoot() string {
+10 -4
View File
@@ -88,8 +88,9 @@ type VMDetail struct {
GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"`
// GuestToolsDisabled is set when the Guest Tools plugin is switched off.
GuestToolsDisabled bool `json:"guest_tools_disabled,omitempty"`
SharedDir string `json:"shared_dir,omitempty"`
GuestLang string `json:"guest_lang,omitempty"`
SharedDir string `json:"shared_dir,omitempty"`
GuestLang string `json:"guest_lang,omitempty"`
SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"`
}
type ValidationIssue struct {
@@ -258,6 +259,10 @@ func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n
if strings.TrimSpace(o.Name) == "" {
issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: i18n.T(loc, "validate.missing_name")})
}
if current.State == "suspended" {
issues = append(issues, ValidationIssue{Field: "state", Code: "vm_suspended", Message: i18n.T(loc, "validate.vm_suspended")})
return issues
}
if o.CPUs != 0 && (o.CPUs < 1 || (rep.LogicalCPUs > 0 && o.CPUs > rep.LogicalCPUs)) {
issues = append(issues, ValidationIssue{Field: "cpus", Code: "invalid_cpus", Message: i18n.T(loc, "validate.invalid_cpus", max(rep.LogicalCPUs, 1))})
}
@@ -548,6 +553,7 @@ func parseDisplayCount(v string) int {
}
// ParseShow parses the text output of `reims-ctl show <name>` while redacting MAC addresses.
// Paths under the user's home are abbreviated upstream (3731afd, cli.rs:1117,1189-1192).
func ParseShow(name, text string) VMDetail {
d := VMDetail{
Name: name,
@@ -577,7 +583,7 @@ func ParseShow(name, text string) VMDetail {
case "kind":
d.Kind = v
case "directory":
d.Directory = v
d.Directory = config.ExpandHomePath(v)
case "cpus":
d.CPUs, _ = strconv.Atoi(v)
case "memory":
@@ -622,7 +628,7 @@ func ParseShow(name, text string) VMDetail {
d.HasOpenCore = v != ""
case "installer":
d.HasInstaller = v != "" && !strings.EqualFold(v, "none")
d.InstallerPath = v
d.InstallerPath = config.ExpandHomePath(v)
case "cpu model":
d.CPUModel = v
case "audio":
+21
View File
@@ -1,6 +1,7 @@
package reims
import (
"path/filepath"
"reflect"
"strings"
"testing"
@@ -63,6 +64,26 @@ func TestParseShowRedactsMACAndDetectsInstaller(t *testing.T) {
}
}
func TestParseShowExpandsHomeRelativePaths(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
vm := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "vms", "macos-15")
image := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "installers", "macOS-Sequoia-15.7-offline-installer.img")
tilde := "~" + string(filepath.Separator)
d := ParseShow("macos-15", " directory "+tilde+vm+"\n installer "+tilde+image+"\n")
if want := filepath.Join(home, vm); d.Directory != want {
t.Errorf("VM directory = %q, want %q", d.Directory, want)
}
if want := filepath.Join(home, image); !d.HasInstaller || d.InstallerPath != want {
t.Errorf("installer attached = %t, path = %q, want attached at %q", d.HasInstaller, d.InstallerPath, want)
}
d = ParseShow("macos-15", " directory ~\n installer none\n")
if d.Directory != home || d.HasInstaller {
t.Errorf("VM directory = %q, want %q, installer attached = %t, want false", d.Directory, home, d.HasInstaller)
}
}
func TestOfflineCreateTurnsNetworkOff(t *testing.T) {
args, err := BuildCreateArgs(CreateOpts{Name: "m1", MacOS: "26.7.3", Offline: true})
if err != nil {
+241
View File
@@ -0,0 +1,241 @@
package reims
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
const (
// SuspendStateFileName holds the QEMU mapped-ram + device VMState snapshot.
SuspendStateFileName = "suspend.vmstate"
// SuspendMetaFileName records the hardware and runtime fingerprint used to
// create suspend.vmstate so incompatible resumes are caught before launch.
SuspendMetaFileName = "suspend.json"
// SuspendSchemaVersion is the current metadata schema version.
SuspendSchemaVersion = 2
)
// SuspendInfo describes a VM's saved suspend-to-disk state inside its VM folder.
type SuspendInfo struct {
SchemaVersion int `json:"schema_version"`
VMName string `json:"vm_name"`
CPUs int `json:"cpus"`
Memory string `json:"memory"`
Graphics string `json:"graphics"`
Displays int `json:"displays"`
Resolution string `json:"resolution"`
DiskController string `json:"disk_controller"`
CPUModel string `json:"cpu_model,omitempty"`
Audio bool `json:"audio"`
AudioBackend string `json:"audio_backend,omitempty"`
Network bool `json:"network"`
SSHPort int `json:"ssh_port"`
ExtraArgs string `json:"extra_args,omitempty"`
RuntimeCommit string `json:"runtime_commit"`
VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"`
CreatedAt string `json:"created_at"`
VMStateSize int64 `json:"vmstate_size"`
}
// SuspendStatePath returns the path to a VM's suspend snapshot file.
func SuspendStatePath(vmDir string) string {
return filepath.Join(vmDir, SuspendStateFileName)
}
// SuspendMetaPath returns the path to a VM's suspend metadata JSON file.
func SuspendMetaPath(vmDir string) string {
return filepath.Join(vmDir, SuspendMetaFileName)
}
// HasSuspendState reports whether vmDir contains a complete suspend snapshot
// (both a non-empty suspend.vmstate and its suspend.json metadata).
func HasSuspendState(vmDir string) bool {
state, _ := suspendFiles(vmDir)
return state != ""
}
func suspendFiles(vmDir string) (state, meta string) {
if strings.TrimSpace(vmDir) == "" {
return "", ""
}
state, meta = SuspendStatePath(vmDir), SuspendMetaPath(vmDir)
nonEmpty := func(path string) bool {
st, err := os.Stat(path)
return err == nil && st.Mode().IsRegular() && st.Size() > 0
}
if nonEmpty(meta) {
if nonEmpty(state) {
return state, meta
}
return "", ""
}
// A staged record is written only after the full state file was
// synced. Preserve that pair if either of the publication steps fails.
if nonEmpty(meta + ".tmp") {
if nonEmpty(state) {
return state, meta + ".tmp"
}
if nonEmpty(state + ".tmp") {
return state + ".tmp", meta + ".tmp"
}
}
return "", ""
}
// ReadSuspendInfo reads suspend.json from vmDir and refreshes VMStateSize from
// the actual suspend.vmstate file on disk.
func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) {
state, meta := suspendFiles(vmDir)
if state == "" {
return nil, os.ErrNotExist
}
b, err := os.ReadFile(meta)
if err != nil {
return nil, err
}
var info SuspendInfo
if err := json.Unmarshal(b, &info); err != nil {
return nil, fmt.Errorf("parse %s: %w", SuspendMetaFileName, err)
}
if st, err := os.Stat(state); err == nil {
info.VMStateSize = st.Size()
}
return &info, nil
}
// BuildSuspendInfo snapshots a VM's hardware and runtime fingerprint for suspend.json.
func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) SuspendInfo {
return SuspendInfo{
SchemaVersion: SuspendSchemaVersion,
VMName: d.Name,
CPUs: d.CPUs,
Memory: strings.TrimSpace(d.Memory),
Graphics: strings.TrimSpace(d.Graphics),
Displays: d.Displays,
Resolution: strings.TrimSpace(d.Resolution),
DiskController: strings.TrimSpace(d.DiskController),
CPUModel: strings.TrimSpace(d.CPUModel),
Audio: d.Audio,
AudioBackend: strings.TrimSpace(d.AudioBackend),
Network: d.Network,
SSHPort: d.SSHPort,
ExtraArgs: StripIncomingDeferArgs(d.ExtraArgs),
RuntimeCommit: strings.TrimSpace(active.Commit),
VendorQemuCommit: strings.TrimSpace(active.Manifest.VendorQemuCommit),
CreatedAt: time.Now().UTC().Format(time.RFC3339),
VMStateSize: vmstateSize,
}
}
// RemoveSuspendState deletes suspend.vmstate, suspend.json, and any partial
// temporary files inside vmDir.
func RemoveSuspendState(vmDir string) error {
if strings.TrimSpace(vmDir) == "" {
return nil
}
var firstErr error
for _, name := range []string{
SuspendMetaFileName,
SuspendMetaFileName + ".tmp",
SuspendStateFileName,
SuspendStateFileName + ".tmp",
} {
if err := os.Remove(filepath.Join(vmDir, name)); err != nil && !os.IsNotExist(err) && firstErr == nil {
firstErr = err
}
}
return firstErr
}
// ValidateSuspendCompatibility checks that the VM hardware and runtime match
// the fingerprint stored when the VM was suspended. Returns human-readable
// mismatch descriptions; an empty slice means compatible.
func ValidateSuspendCompatibility(meta SuspendInfo, cur VMDetail, active rt.Installed) []string {
var diffs []string
if meta.CPUs > 0 && cur.CPUs > 0 && meta.CPUs != cur.CPUs {
diffs = append(diffs, fmt.Sprintf("CPUs (%d -> %d)", meta.CPUs, cur.CPUs))
}
if meta.Memory != "" && cur.Memory != "" && !strings.EqualFold(strings.TrimSpace(meta.Memory), strings.TrimSpace(cur.Memory)) {
diffs = append(diffs, fmt.Sprintf("Memory (%s -> %s)", meta.Memory, cur.Memory))
}
if meta.Graphics != "" && cur.Graphics != "" && !strings.EqualFold(strings.TrimSpace(meta.Graphics), strings.TrimSpace(cur.Graphics)) {
diffs = append(diffs, fmt.Sprintf("Graphics (%s -> %s)", meta.Graphics, cur.Graphics))
}
if meta.Displays > 0 && cur.Displays > 0 && meta.Displays != cur.Displays {
diffs = append(diffs, fmt.Sprintf("Displays (%d -> %d)", meta.Displays, cur.Displays))
}
if meta.DiskController != "" && cur.DiskController != "" && !strings.EqualFold(strings.TrimSpace(meta.DiskController), strings.TrimSpace(cur.DiskController)) {
diffs = append(diffs, fmt.Sprintf("Disk controller (%s -> %s)", meta.DiskController, cur.DiskController))
}
if meta.Audio != cur.Audio {
diffs = append(diffs, fmt.Sprintf("Audio (%v -> %v)", meta.Audio, cur.Audio))
}
if meta.Network != cur.Network {
diffs = append(diffs, fmt.Sprintf("Network (%v -> %v)", meta.Network, cur.Network))
}
if meta.VendorQemuCommit != "" && active.Manifest.VendorQemuCommit != "" &&
!strings.EqualFold(strings.TrimSpace(meta.VendorQemuCommit), strings.TrimSpace(active.Manifest.VendorQemuCommit)) {
diffs = append(diffs, fmt.Sprintf("QEMU commit (%s -> %s)", shortRev(meta.VendorQemuCommit), shortRev(active.Manifest.VendorQemuCommit)))
} else if meta.RuntimeCommit != "" && active.Commit != "" &&
!strings.EqualFold(strings.TrimSpace(meta.RuntimeCommit), strings.TrimSpace(active.Commit)) {
diffs = append(diffs, fmt.Sprintf("Runtime (%s -> %s)", meta.RuntimeCommit, active.Commit))
}
return diffs
}
func shortRev(rev string) string {
rev = strings.TrimSpace(rev)
if len(rev) > 8 {
return rev[:8]
}
return rev
}
// HasIncomingDeferArg reports whether extraArgs contains `-incoming defer`.
func HasIncomingDeferArg(extraArgs string) bool {
tokens := splitShellTokens(extraArgs)
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" {
return true
}
if tok == "-incoming=defer" {
return true
}
}
return false
}
// StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer`
// arguments from QEMU extra-args while leaving all other arguments intact.
func StripIncomingDeferArgs(existing string) string {
tokens := splitShellTokens(existing)
cleaned := make([]string, 0, len(tokens))
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" {
i++
continue
}
if tok == "-incoming=defer" {
continue
}
cleaned = append(cleaned, tok)
}
return strings.Join(cleaned, " ")
}
// MergeIncomingDeferArgs idempotently appends `-incoming defer` to extra-args.
func MergeIncomingDeferArgs(existing string) string {
base := StripIncomingDeferArgs(existing)
if base == "" {
return "-incoming defer"
}
return base + " -incoming defer"
}
@@ -0,0 +1,26 @@
//go:build !windows
package reims
import (
"errors"
"fmt"
"os"
"syscall"
)
func lockVMFile(f *os.File) error {
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if errors.Is(err, syscall.EWOULDBLOCK) {
return ErrVMOperationBusy
}
return err
}
func mediaFileID(path string, info os.FileInfo) (uint64, uint64, error) {
st, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return 0, 0, fmt.Errorf("file identity unavailable for %s", path)
}
return uint64(st.Dev), uint64(st.Ino), nil
}
@@ -0,0 +1,39 @@
//go:build windows
package reims
import (
"errors"
"os"
"golang.org/x/sys/windows"
)
func lockVMFile(f *os.File) error {
err := windows.LockFileEx(windows.Handle(f.Fd()),
windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
0, 1, 0, new(windows.Overlapped))
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {
return ErrVMOperationBusy
}
return err
}
func mediaFileID(path string, _ os.FileInfo) (uint64, uint64, error) {
name, err := windows.UTF16PtrFromString(path)
if err != nil {
return 0, 0, err
}
handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil,
windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
if err != nil {
return 0, 0, err
}
defer windows.CloseHandle(handle)
var info windows.ByHandleFileInformation
if err := windows.GetFileInformationByHandle(handle, &info); err != nil {
return 0, 0, err
}
return uint64(info.VolumeSerialNumber), uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow), nil
}
+121
View File
@@ -0,0 +1,121 @@
package reims
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestSuspendStateLifecycle(t *testing.T) {
dir := t.TempDir()
if HasSuspendState(dir) {
t.Fatal("empty dir should not have suspend state")
}
// Only vmstate without meta -> incomplete.
if err := os.WriteFile(SuspendStatePath(dir)+".tmp", []byte("vmstate-bytes"), 0o644); err != nil {
t.Fatal(err)
}
if HasSuspendState(dir) {
t.Fatal("vmstate without suspend.json should not count as complete suspend state")
}
active := rt.Installed{
Commit: "3731afd-p9",
Manifest: rt.Manifest{
VendorQemuCommit: "4571bc5fecb039e8cfd6837e077810fbe074e11b",
},
}
detail := VMDetail{
Name: "tahoe",
Directory: dir,
CPUs: 8,
Memory: "8G",
Graphics: "reims-vgpu",
Displays: 1,
Resolution: "1920x1080",
DiskController: "nvme",
Audio: true,
Network: true,
ExtraArgs: "-machine kernel-irqchip=on -incoming defer",
}
media := filepath.Join(dir, "disk.qcow2")
for _, path := range []string{media, filepath.Join(dir, "vm.toml")} {
if err := os.WriteFile(path, []byte("state"), 0o600); err != nil {
t.Fatal(err)
}
}
if _, err := SealSuspend(detail, active, []string{media}); err != nil {
t.Fatalf("SealSuspend: %v", err)
}
if !HasSuspendState(dir) {
t.Fatal("expected HasSuspendState=true after writing both files")
}
got, err := ReadSuspendInfo(dir)
if err != nil {
t.Fatalf("ReadSuspendInfo: %v", err)
}
if got.VMStateSize != 13 || got.CPUs != 8 || got.ExtraArgs != "-machine kernel-irqchip=on" {
t.Fatalf("unexpected suspend info: %+v", got)
}
// Compatible check passes.
if diffs := ValidateSuspendCompatibility(*got, detail, active); len(diffs) != 0 {
t.Fatalf("expected compatible, got %v", diffs)
}
// Hardware and runtime mismatch checks trigger.
changedDetail := detail
changedDetail.CPUs = 12
changedDetail.Memory = "16G"
changedRT := active
changedRT.Manifest.VendorQemuCommit = "deadbeef00000000000000000000000000000000"
diffs := ValidateSuspendCompatibility(*got, changedDetail, changedRT)
if len(diffs) != 3 {
t.Fatalf("expected 3 diffs, got %v", diffs)
}
if err := RemoveSuspendState(dir); err != nil {
t.Fatalf("RemoveSuspendState: %v", err)
}
if HasSuspendState(dir) {
t.Fatal("expected HasSuspendState=false after RemoveSuspendState")
}
}
func TestIncomingDeferArgsIdempotent(t *testing.T) {
if HasIncomingDeferArg("") || HasIncomingDeferArg("-machine q35") {
t.Fatal("unexpected HasIncomingDeferArg=true")
}
m := MergeIncomingDeferArgs(`-drive "id=x,file=C:/a b/c.img"`)
if !HasIncomingDeferArg(m) {
t.Fatalf("expected -incoming defer in %q", m)
}
if m2 := MergeIncomingDeferArgs(m); m2 != m {
t.Fatalf("MergeIncomingDeferArgs not idempotent: %q vs %q", m2, m)
}
if s := StripIncomingDeferArgs(m + " -incoming=defer"); s != `-drive "id=x,file=C:/a b/c.img"` {
t.Fatalf("StripIncomingDeferArgs = %q", s)
}
}
func TestValidateSetRejectsSuspendedVM(t *testing.T) {
issues := ValidateSetLocalized(
SetOpts{Name: "tahoe", CPUs: 6},
VMDetail{Name: "tahoe", State: "suspended", CPUs: 8, Memory: "8G"},
host.Report{LogicalCPUs: 16, TotalRAMGB: 32},
i18n.EnUS,
)
if len(issues) == 0 || issues[0].Code != "vm_suspended" {
t.Fatalf("expected vm_suspended validation issue, got %+v", issues)
}
if !strings.Contains(strings.ToLower(issues[0].Message), "suspend") {
t.Fatalf("unexpected message: %q", issues[0].Message)
}
}
@@ -0,0 +1,185 @@
package reims
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
var ErrVMOperationBusy = errors.New("another operation holds the VM lock")
// LockVMOperation serializes GUI and CLI operations on the same VM directory.
// The lock file stays in place so contenders always lock the same inode.
func LockVMOperation(vmDir string) (func(), error) {
if strings.TrimSpace(vmDir) == "" {
return nil, fmt.Errorf("VM directory is required")
}
f, err := os.OpenFile(filepath.Join(vmDir, ".reims-go-vm-operation.lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err := lockVMFile(f); err != nil {
_ = f.Close()
return nil, err
}
return func() { _ = f.Close() }, nil
}
type mediaFingerprint struct {
Path string `json:"path"`
Volume uint64 `json:"volume"`
FileID uint64 `json:"file_id"`
Size int64 `json:"size"`
MTime int64 `json:"mtime_ns"`
}
type suspendRecord struct {
SuspendInfo
ConfigHash string `json:"config_sha256"`
Media []mediaFingerprint `json:"media"`
}
func fingerprintMedia(path string) (mediaFingerprint, error) {
st, err := os.Stat(path)
if err != nil {
return mediaFingerprint{}, err
}
if !st.Mode().IsRegular() {
return mediaFingerprint{}, fmt.Errorf("attached path is not a regular file: %s", path)
}
volume, id, err := mediaFileID(path, st)
if err != nil {
return mediaFingerprint{}, err
}
return mediaFingerprint{Path: path, Volume: volume, FileID: id, Size: st.Size(), MTime: st.ModTime().UnixNano()}, nil
}
func suspendConfigHash(vmDir string) (string, error) {
data, err := os.ReadFile(filepath.Join(vmDir, "vm.toml"))
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:]), nil
}
// SealSuspend publishes a completed migration as the only usable snapshot.
// Every failure leaves the migration file available and the sender still alive.
func SealSuspend(d VMDetail, active rt.Installed, paths []string) (SuspendInfo, error) {
if len(paths) == 0 {
return SuspendInfo{}, fmt.Errorf("cannot seal a snapshot without attached media")
}
dir := d.Directory
tmp := SuspendStatePath(dir) + ".tmp"
state, err := os.OpenFile(tmp, os.O_RDWR, 0)
if err != nil {
return SuspendInfo{}, err
}
st, err := state.Stat()
if err == nil && (!st.Mode().IsRegular() || st.Size() == 0) {
err = fmt.Errorf("suspend snapshot is empty or is not a regular file")
}
if err == nil {
err = state.Sync()
}
if err := errors.Join(err, state.Close()); err != nil {
return SuspendInfo{}, err
}
configHash, err := suspendConfigHash(dir)
if err != nil {
return SuspendInfo{}, err
}
record := suspendRecord{
SuspendInfo: BuildSuspendInfo(d, active, st.Size()),
ConfigHash: configHash,
Media: make([]mediaFingerprint, 0, len(paths)),
}
for _, path := range paths {
item, err := fingerprintMedia(path)
if err != nil {
return SuspendInfo{}, fmt.Errorf("fingerprint attached media: %w", err)
}
record.Media = append(record.Media, item)
}
metaTmp := SuspendMetaPath(dir) + ".tmp"
if err := stageSuspendRecord(metaTmp, record); err != nil {
return SuspendInfo{}, err
}
if err := os.Rename(tmp, SuspendStatePath(dir)); err != nil {
return SuspendInfo{}, err
}
if err := os.Rename(metaTmp, SuspendMetaPath(dir)); err != nil {
return SuspendInfo{}, err
}
return record.SuspendInfo, nil
}
func stageSuspendRecord(path string, record suspendRecord) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
err = enc.Encode(record)
if err == nil {
err = f.Sync()
}
return errors.Join(err, f.Close())
}
// ValidateSuspendFiles checks contents and identities before starting incoming
// QEMU and returns the expected media paths for validation before load.
func ValidateSuspendFiles(d VMDetail, active rt.Installed) (string, []string, error) {
state, meta := suspendFiles(d.Directory)
if state == "" {
return "", nil, os.ErrNotExist
}
data, err := os.ReadFile(meta)
if err != nil {
return "", nil, err
}
var record suspendRecord
if err := json.Unmarshal(data, &record); err != nil {
return "", nil, err
}
if record.SchemaVersion != SuspendSchemaVersion || record.ConfigHash == "" || len(record.Media) == 0 {
return "", nil, fmt.Errorf("snapshot has no supported VM and media fingerprint")
}
st, err := os.Stat(state)
if err != nil {
return "", nil, err
}
if !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() != record.VMStateSize {
return "", nil, fmt.Errorf("snapshot file size changed")
}
diffs := ValidateSuspendCompatibility(record.SuspendInfo, d, active)
configHash, err := suspendConfigHash(d.Directory)
if err != nil {
return "", nil, err
}
if configHash != record.ConfigHash {
diffs = append(diffs, "VM configuration changed")
}
paths := make([]string, 0, len(record.Media))
for _, expected := range record.Media {
current, err := fingerprintMedia(expected.Path)
if err != nil || current != expected {
diffs = append(diffs, fmt.Sprintf("attached media changed (%s)", expected.Path))
}
paths = append(paths, expected.Path)
}
if len(diffs) > 0 {
return "", nil, errors.New(strings.Join(diffs, ", "))
}
slices.Sort(paths)
return state, paths, nil
}
@@ -0,0 +1,89 @@
package reims
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestVMOperationLockExcludesAnotherHandle(t *testing.T) {
dir := t.TempDir()
release, err := LockVMOperation(dir)
if err != nil {
t.Fatal(err)
}
if _, err = LockVMOperation(dir); !errors.Is(err, ErrVMOperationBusy) {
t.Fatalf("second lock = %v, want busy", err)
}
release()
release, err = LockVMOperation(dir)
if err != nil {
t.Fatal(err)
}
release()
}
func TestSuspendTransactionRejectsChangedBackingFile(t *testing.T) {
dir := t.TempDir()
top := filepath.Join(dir, "disk.qcow2")
base := filepath.Join(dir, "base.qcow2")
for _, path := range []string{top, base, filepath.Join(dir, "vm.toml"), SuspendStatePath(dir) + ".tmp"} {
if err := os.WriteFile(path, []byte("test data"), 0o600); err != nil {
t.Fatal(err)
}
}
d := VMDetail{Name: "test", Directory: dir, CPUs: 2, Memory: "4G"}
runtime := rt.Installed{Commit: "test"}
if _, err := SealSuspend(d, runtime, []string{top, base}); err != nil {
t.Fatal(err)
}
if _, _, err := ValidateSuspendFiles(d, runtime); err != nil {
t.Fatal(err)
}
st, err := os.Stat(base)
if err != nil {
t.Fatal(err)
}
if err := os.Rename(base, base+".old"); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(base, []byte("test data"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(base, st.ModTime(), st.ModTime()); err != nil {
t.Fatal(err)
}
if _, _, err := ValidateSuspendFiles(d, runtime); err == nil || !strings.Contains(err.Error(), "base.qcow2") {
t.Fatalf("replaced backing file not detected: %v", err)
}
}
func TestSuspendTransactionKeepsSealedFilesWhenPublicationFails(t *testing.T) {
dir := t.TempDir()
media := filepath.Join(dir, "OVMF_VARS.fd")
stagedState := SuspendStatePath(dir) + ".tmp"
for _, path := range []string{media, filepath.Join(dir, "vm.toml"), stagedState} {
if err := os.WriteFile(path, []byte("test state"), 0o600); err != nil {
t.Fatal(err)
}
}
if err := os.Mkdir(SuspendMetaPath(dir), 0o700); err != nil {
t.Fatal(err)
}
d := VMDetail{Name: "test", Directory: dir}
runtime := rt.Installed{Commit: "test"}
if _, err := SealSuspend(d, runtime, []string{media}); err == nil {
t.Fatal("expected publication to fail")
}
if !HasSuspendState(dir) {
t.Fatal("published state and staged metadata should be recoverable")
}
state, paths, err := ValidateSuspendFiles(d, runtime)
if err != nil || state != SuspendStatePath(dir) || len(paths) != 1 || paths[0] != media {
t.Fatalf("recoverable snapshot = %q, %v, %v", state, paths, err)
}
}
+6 -2
View File
@@ -4,6 +4,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
)
@@ -19,8 +20,11 @@ func TestGuestAgentClipboardScript(t *testing.T) {
agent := string(GuestAgentScript())
start := strings.Index(agent, "read_local_clipboard() {")
end := strings.Index(agent, "sync_files() {")
if start < 0 || end <= start || !strings.Contains(agent, "agent_version\\\":6") {
t.Fatal("missing generated clipboard code or agent version 6")
if start < 0 || end <= start {
t.Fatal("missing generated clipboard code")
}
if !regexp.MustCompile(`agent_version\\":([6-9]|[1-9][0-9]+)\}`).MatchString(agent) {
t.Fatal("clipboard sync requires agent version 6 or newer")
}
if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) {
t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u")
+437
View File
@@ -0,0 +1,437 @@
package guesttools
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
const (
syncScopeHeader = "X-Reims-Sync-Scope"
syncDigestHeader = "X-Reims-File-SHA256"
)
func syncFileScope(token string, root *os.Root) (string, error) {
// A replacement directory at the same path must start fresh sync history.
dir, err := root.Open(".")
if err != nil {
return "", err
}
defer dir.Close()
id, err := sharedDirectoryID(dir)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root.Name()+"\n"+id))), nil
}
func syncFileTag(info fs.FileInfo) string {
return fmt.Sprintf("\"%d-%d\"", info.ModTime().UnixNano(), info.Size())
}
func isIgnoredSharedName(name string) bool {
return name == "" || strings.HasPrefix(name, ".")
}
func validSyncFileName(name string) bool {
return strings.TrimSpace(name) == name && !strings.ContainsAny(name, "\t\r\n")
}
// sharedFilePath returns the one relative path used by both the legacy copy
// endpoints and the versioned sync operations.
func sharedFilePath(name string) (string, error) {
name = strings.TrimSpace(name)
parts := strings.FieldsFunc(name, func(r rune) bool { return r == '/' })
if len(parts) == 0 || len(parts) > MaxSharedDepth || strings.HasPrefix(name, "/") {
return "", errors.New("invalid relative path")
}
for _, part := range parts {
if isIgnoredSharedName(part) || strings.ContainsAny(part, "\x00:\\<>|\"?*") {
return "", errors.New("invalid path segment")
}
}
rel := strings.Join(parts, "/")
if !filepath.IsLocal(filepath.FromSlash(rel)) {
return "", errors.New("invalid relative path")
}
return rel, nil
}
func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
versioned := r.URL.Query().Get("sync") == "1"
if vm.sharedDir == "" {
if versioned {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
}
return
}
unavailable := http.StatusInternalServerError
if versioned {
unavailable = http.StatusServiceUnavailable
}
root, err := openSharedRoot(vm.sharedRoot, !versioned)
if err != nil {
http.Error(w, "shared directory unavailable", unavailable)
return
}
defer root.Close()
var scope string
if versioned {
scope, err = syncFileScope(vm.token, root)
if err != nil {
http.Error(w, "shared directory unavailable", unavailable)
return
}
}
files, err := listSharedFiles(root.FS(), func(name string) (os.FileInfo, error) {
return statDAVEntry(root, name)
}, versioned)
if err != nil {
http.Error(w, "shared directory unavailable", unavailable)
return
}
if versioned {
w.Header().Set(syncScopeHeader, scope)
}
sort.Slice(files, func(i, j int) bool { return files[i].name < files[j].name })
w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8")
for _, file := range files {
_, _ = fmt.Fprintf(w, "%d\t%d\t", file.info.ModTime().Unix(), file.info.Size())
if versioned {
_, _ = fmt.Fprintf(w, "%s\t", syncFileTag(file.info))
}
_, _ = fmt.Fprintln(w, file.name)
}
}
type sharedFileEntry struct {
name string
info fs.FileInfo
}
func listSharedFiles(fsys fs.FS, stat func(string) (os.FileInfo, error), versioned bool) ([]sharedFileEntry, error) {
var files []sharedFileEntry
err := fs.WalkDir(fsys, ".", func(name string, d fs.DirEntry, err error) error {
if name == "." {
return err
}
if err != nil {
return nil
}
if isIgnoredSharedName(d.Name()) || d.Type()&os.ModeSymlink != 0 {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if strings.Count(name, "/")+1 > MaxSharedDepth {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if versioned && !validSyncFileName(name) {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
info, err := stat(name)
if err != nil && d.IsDir() {
return fs.SkipDir
}
if err != nil || !isSharedRegularFile(info.Mode()) || info.Size() > MaxUploadBytes {
return nil
}
if len(files) == MaxSharedFiles {
return fs.SkipAll
}
files = append(files, sharedFileEntry{name, info})
return nil
})
return files, err
}
func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
rawName := r.URL.Query().Get("path")
name, err := sharedFilePath(rawName)
if err != nil || vm.sharedDir == "" {
http.Error(w, "invalid shared file path", http.StatusBadRequest)
return
}
scope := r.Header.Get(syncScopeHeader)
writing := r.Method == http.MethodPut || r.Method == http.MethodPost
switch r.Method {
case http.MethodHead, http.MethodDelete:
if scope == "" {
http.Error(w, "sync scope required", http.StatusPreconditionRequired)
return
}
case http.MethodGet, http.MethodPut, http.MethodPost:
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
root, err := openSharedRoot(vm.sharedRoot, scope == "" && writing)
if err != nil {
switch {
case scope != "":
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
case !writing && errors.Is(err, fs.ErrNotExist):
http.NotFound(w, r)
default:
http.Error(w, "shared directory unavailable", http.StatusInternalServerError)
}
return
}
defer root.Close()
if scope != "" {
current, err := syncFileScope(vm.token, root)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
if !validSyncFileName(rawName) || scope != current {
http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed)
return
}
}
if writing {
s.writeSharedFile(w, r, root, name, scope != "")
} else {
s.readSharedFile(w, r, root, name, scope != "")
}
}
func matchSyncFile(r *http.Request, info fs.FileInfo) bool {
if tag := r.Header.Get("If-Match"); tag != "" {
return info != nil && isSharedRegularFile(info.Mode()) && syncFileTag(info) == tag
}
return r.Header.Get("If-None-Match") != "*" || info == nil
}
// A path replaced by a symlink or directory is a conflict rather than a
// missing file. Missing files are the only ones that propagate a deletion.
func checkSharedFileParents(root *os.Root, name string) error {
for i, ch := range name {
if ch != '/' {
continue
}
info, err := statDAVEntry(root, name[:i])
if err == os.ErrPermission || (err == nil && !info.IsDir()) {
return fs.ErrInvalid
}
if err != nil {
return err
}
}
return nil
}
func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) {
if err := checkSharedFileParents(root, name); err != nil {
return nil, err
}
info, err := statDAVEntry(root, name)
if err == os.ErrPermission || (err == nil && !isSharedRegularFile(info.Mode())) {
return nil, fs.ErrInvalid
}
return info, err
}
func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) {
deleting := r.Method == http.MethodDelete
expectedDigest := r.Header.Get(syncDigestHeader)
if deleting && (r.Header.Get("If-Match") == "" || expectedDigest == "") {
http.Error(w, "file revision required", http.StatusPreconditionRequired)
return
}
info, err := statSharedFile(root, name)
switch {
case errors.Is(err, fs.ErrNotExist):
http.NotFound(w, r)
return
case errors.Is(err, fs.ErrInvalid):
status := http.StatusBadRequest
if versioned {
status = http.StatusConflict
}
http.Error(w, "path is not a regular file", status)
return
case err != nil:
http.Error(w, "file unavailable", http.StatusInternalServerError)
return
case versioned && !matchSyncFile(r, info):
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
tag := syncFileTag(info)
if !deleting {
w.Header().Set("ETag", tag)
}
head := r.Method == http.MethodHead
if head && r.URL.Query().Get("sha256") != "1" {
return
}
if (head || deleting) && info.Size() > MaxUploadBytes {
http.Error(w, "file exceeds sync size limit", http.StatusRequestEntityTooLarge)
return
}
file, err := root.Open(name)
if err != nil {
http.Error(w, "file unavailable", http.StatusInternalServerError)
return
}
opened, err := file.Stat()
if err != nil || !isSharedRegularFile(opened.Mode()) || !os.SameFile(info, opened) || syncFileTag(opened) != tag {
_ = file.Close()
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
if r.Method == http.MethodGet {
defer file.Close()
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10))
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
_, _ = io.Copy(w, file)
return
}
h := sha256.New()
n, err := io.Copy(h, io.LimitReader(file, info.Size()+1))
_ = file.Close()
if err != nil || n != info.Size() {
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
digest := fmt.Sprintf("%x", h.Sum(nil))
if head {
w.Header().Set(syncDigestHeader, digest)
return
}
s.fileMu.Lock()
defer s.fileMu.Unlock()
current, err := statSharedFile(root, name)
if digest != expectedDigest || err != nil || !os.SameFile(opened, current) || !matchSyncFile(r, current) {
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
if r.Context().Err() == nil {
if err := root.Remove(name); err != nil {
http.Error(w, "file deletion failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
}
func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) {
if err := checkSharedFileParents(root, name); err != nil && !errors.Is(err, fs.ErrNotExist) {
http.Error(w, "upload directory unavailable", http.StatusConflict)
return
}
dir := path.Dir(name)
if err := root.MkdirAll(dir, 0o755); err != nil {
http.Error(w, "upload directory unavailable", http.StatusInternalServerError)
return
}
parent, err := root.OpenRoot(dir)
if err != nil {
http.Error(w, "upload directory unavailable", http.StatusInternalServerError)
return
}
defer parent.Close()
tmpName := ".reims-upload-" + rand.Text()
tmp, err := parent.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
http.Error(w, "upload file unavailable", http.StatusInternalServerError)
return
}
defer parent.Remove(tmpName)
h := sha256.New()
var dst io.Writer = tmp
if versioned {
dst = io.MultiWriter(tmp, h)
}
n, copyErr := io.Copy(dst, io.LimitReader(r.Body, MaxUploadBytes+1))
closeErr := tmp.Close()
switch {
case n > MaxUploadBytes:
http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge)
return
case copyErr != nil || closeErr != nil:
http.Error(w, "write failed", http.StatusInternalServerError)
return
}
if ts, err := strconv.ParseInt(r.URL.Query().Get("mtime"), 10, 64); err == nil && ts > 0 {
t := time.Unix(ts, 0)
_ = parent.Chtimes(tmpName, t, t)
}
s.fileMu.Lock()
defer s.fileMu.Unlock()
currentParent, err := statDAVEntry(root, dir)
openedParent, openErr := parent.Stat(".")
if err != nil || openErr != nil || !os.SameFile(currentParent, openedParent) || checkSharedFileParents(root, name) != nil {
http.Error(w, "upload directory changed", http.StatusConflict)
return
}
name = path.Base(name)
info, err := statSharedFile(parent, name)
if errors.Is(err, fs.ErrInvalid) {
http.Error(w, "path is not a regular file", http.StatusConflict)
return
}
if err != nil && !errors.Is(err, fs.ErrNotExist) {
http.Error(w, "file unavailable", http.StatusInternalServerError)
return
}
var uploadedTag string
if versioned {
if !matchSyncFile(r, info) {
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
uploaded, err := parent.Stat(tmpName)
if err != nil {
http.Error(w, "uploaded file unavailable", http.StatusInternalServerError)
return
}
uploadedTag = syncFileTag(uploaded)
}
if err := parent.Rename(tmpName, name); err != nil {
http.Error(w, "publish uploaded file failed", http.StatusInternalServerError)
return
}
if versioned {
w.Header().Set("ETag", uploadedTag)
w.Header().Set(syncDigestHeader, fmt.Sprintf("%x", h.Sum(nil)))
}
w.WriteHeader(http.StatusOK)
}
+219
View File
@@ -0,0 +1,219 @@
# Keep confirmed pairs scoped to the current shared directories on both sides.
sync_files() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
sync_guest_root=$(sync_guest_root_id) || return 0
sync_remote="$TMP_DIR/sync-remote.tsv"
sync_local="$TMP_DIR/sync-local.tsv"
sync_headers="$TMP_DIR/sync-headers"
sync_plan="$TMP_DIR/sync-plan.tsv"
sync_delta="$TMP_DIR/sync-delta.tsv"
sync_state=/dev/null
if ! sync_request -fsS -m 5 -D "$sync_headers" -o "$sync_remote" "$REIMS_HOST_URL/v1/files?sync=1" 2>/dev/null; then
return 0
fi
sync_scope=$(sync_header X-Reims-Sync-Scope)
case "$sync_scope" in
"") ;;
*[!0-9a-f]*) return 0 ;;
*) sync_state="$APP_DIR/file-sync-$sync_scope-$sync_guest_root.tsv" ;;
esac
sync_previous="$sync_state"
[ -f "$sync_state" ] || sync_previous=/dev/null
if ! find "$SHARE_SYNC"/. -name '.*' ! -name . -prune -o -type f -exec /bin/sh -c '
root=$1
tab=$2
shift 2
newline=$(printf "\nx")
newline=${newline%x}
cr=$(printf "\r")
for file do
rel=${file#"$root"/./}
case "$rel" in *"$tab"*|*"$newline"*|*"$cr"*) continue ;; esac
row=$(stat -f "%m${tab}%z${tab}%Fm:%Fc:%i:%z" "$file") || exit 1
printf "%s\t%s\n" "$row" "$rel"
done
' sh "$SHARE_SYNC" "$TAB" {} + > "$sync_local" 2>/dev/null; then
return 0
fi
# A missing path is a deletion only after a confirmed pair has existed.
# If the remaining copy changed, preserve it using the usual copy rules.
awk -F '\t' -v extended="$sync_scope" '
BEGIN { OFS = FS }
FILENAME == ARGV[1] {
previousLocal[$4] = $1; previousRemote[$4] = $2; state[$4] = $3; paths[$4] = 1
}
FILENAME == ARGV[2] {
p = extended == "" ? $3 : $4
if (p != "") {
remoteTime[p] = $1; remoteSize[p] = $2; remote[p] = extended == "" ? "-" : $3; paths[p] = 1
}
}
FILENAME == ARGV[3] && $4 != "" {
localTime[$4] = $1; localSize[$4] = $2; local[$4] = $3; paths[$4] = 1
}
END {
for (p in paths) {
l = p in local; r = p in remote
paired = state[p] != "" && state[p] != "different"
op = ""
if (l && r) {
if (remoteTime[p] + 0 > localTime[p] + 2) op = "download"
else if (localTime[p] + 0 > remoteTime[p] + 2 && localSize[p] <= 268435456) op = "upload"
else if (extended != "" && localTime[p] == remoteTime[p] && localSize[p] == remoteSize[p] &&
(local[p] != previousLocal[p] || remote[p] != previousRemote[p])) op = "verify"
} else if (r) {
op = paired && remote[p] == previousRemote[p] ? "delete-host" : "download"
} else if (l) {
if (paired && local[p] == previousLocal[p]) op = "delete-guest"
else if (localSize[p] <= 268435456) op = "upload"
} else {
op = "forget"
}
if (op != "") {
localRevision = l ? local[p] : "-"
remoteRevision = r ? remote[p] : "-"
localMtime = l ? localTime[p] : "-"
digest = state[p] != "" ? state[p] : "-"
print op, localRevision, remoteRevision, localMtime, digest, p
}
}
}
' "$sync_previous" "$sync_remote" "$sync_local" > "$sync_plan" || return 0
: > "$sync_delta" || return 0
sync_verify_left=8
while IFS="$TAB" read -r sync_op sync_guest_rev sync_host_rev sync_guest_time sync_digest sync_rel; do
sync_apply_file
done < "$sync_plan"
if [ "$sync_state" != /dev/null ]; then
awk -F '\t' '
$1 == "-" { delete rows[$4]; next }
{ rows[$4] = $0 }
END { for (p in rows) print rows[p] }
' "$sync_previous" "$sync_delta" > "$TMP_DIR/sync-state.next" &&
mv -f "$TMP_DIR/sync-state.next" "$sync_state"
fi
}
sync_request() {
curl -H "Authorization: Bearer $REIMS_TOKEN" "$@"
}
sync_header() {
awk -v name="$1:" 'tolower($1) == tolower(name) { sub(/\r$/, "", $2); print $2; exit }' "$sync_headers"
}
sync_guest_root_id() {
[ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] &&
stat -f '%d-%i-%B' "$SHARE_SYNC" 2>/dev/null
}
sync_guest_revision() {
[ "$(sync_guest_root_id)" = "$sync_guest_root" ] || return 1
sync_check=$1
while [ "$sync_check" != "$SHARE_SYNC" ]; do
[ ! -L "$sync_check" ] || return 1
sync_check=${sync_check%/*}
done
if [ -f "$1" ]; then
stat -f '%Fm:%Fc:%i:%z' "$1" 2>/dev/null
elif [ ! -e "$1" ]; then
printf '%s\n' '-'
fi
}
sync_record() {
[ -n "$1" ] && [ -n "$2" ] && [ -n "$3" ] || return 0
printf '%s\t%s\t%s\t%s\n' "$1" "$2" "$3" "$sync_rel" >> "$sync_delta"
}
sync_apply_file() {
case "/$sync_rel/" in //*|*/../*|*/./*|*//*) return ;; esac
sync_target="$SHARE_SYNC/$sync_rel"
[ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0
sync_url="$REIMS_HOST_URL/v1/file?path=$(urlencode "$sync_rel")"
if [ -n "$sync_scope" ]; then
set -- -H "X-Reims-Sync-Scope: $sync_scope"
if [ "$sync_host_rev" != - ]; then
set -- "$@" -H "If-Match: $sync_host_rev"
fi
else
set --
fi
case "$sync_op" in
delete-host)
sync_status=$(sync_request -sS -m 60 "$@" -H "X-Reims-File-SHA256: $sync_digest" -X DELETE \
-o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0
case "$sync_status" in
204) sync_record - - -; return ;;
412) sync_op=download ;;
*) return 0 ;;
esac
;;
delete-guest|forget)
# A partial host listing cannot confirm that a file was deleted.
sync_status=$(sync_request -sS -m 10 "$@" -I -o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0
[ "$sync_status" = 404 ] || return 0
if [ "$sync_op" = "forget" ]; then
sync_record - - -
return
fi
sync_actual=$(hash_file "$sync_target")
[ -n "$sync_actual" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0
if [ "$sync_actual" = "$sync_digest" ]; then
rm "$sync_target" && sync_record - - -
return
fi
sync_op=upload
;;
esac
case "$sync_op" in
download)
sync_part="$TMP_DIR/sync-download.part"
if sync_request -fsS -m 60 "$@" -D "$sync_headers" -o "$sync_part" "$sync_url" 2>/dev/null; then
sync_download_digest=""
if [ -n "$sync_scope" ]; then
sync_download_digest=$(hash_file "$sync_part")
fi
if sync_stamp=$(TZ=UTC date -r "$(sync_header X-File-Mtime)" '+%Y%m%d%H%M.%S' 2>/dev/null); then
TZ=UTC touch -t "$sync_stamp" "$sync_part" 2>/dev/null || true
fi
if [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] &&
mkdir -p "$(dirname "$sync_target")" && mv -f "$sync_part" "$sync_target"; then
sync_record "$(sync_guest_revision "$sync_target")" "$(sync_header ETag)" "$sync_download_digest"
fi
fi
rm -f "$sync_part"
;;
upload)
if [ -n "$sync_scope" ] && [ "$sync_host_rev" = - ]; then
set -- "$@" -H 'If-None-Match: *'
fi
if sync_request -fsS -m 60 "$@" -X PUT --data-binary "@$sync_target" -D "$sync_headers" -o /dev/null \
"$sync_url&mtime=$sync_guest_time" 2>/dev/null &&
[ -n "$sync_scope" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then
sync_record "$sync_guest_rev" "$(sync_header ETag)" "$(sync_header X-Reims-File-SHA256)"
fi
;;
verify)
# Bound initial migration work when adopting pre-existing copies.
[ "$sync_verify_left" -gt 0 ] || return 0
sync_verify_left=$((sync_verify_left - 1))
if sync_request -fsS -m 15 "$@" -I -D "$sync_headers" -o /dev/null "$sync_url&sha256=1" 2>/dev/null; then
sync_host_hash=$(sync_header X-Reims-File-SHA256)
sync_guest_hash=$(hash_file "$sync_target")
if [ -n "$sync_host_hash" ] && [ -n "$sync_guest_hash" ] &&
[ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then
[ "$sync_host_hash" = "$sync_guest_hash" ] || sync_host_hash=different
sync_record "$sync_guest_rev" "$sync_host_rev" "$sync_host_hash"
fi
fi
;;
esac
}
@@ -0,0 +1,12 @@
//go:build !windows && !unix
package guesttools
import (
"errors"
"os"
)
func sharedDirectoryID(*os.File) (string, error) {
return "", errors.ErrUnsupported
}
@@ -0,0 +1,18 @@
//go:build unix
package guesttools
import (
"fmt"
"os"
"syscall"
)
func sharedDirectoryID(dir *os.File) (string, error) {
info, err := dir.Stat()
if err != nil {
return "", err
}
stat := info.Sys().(*syscall.Stat_t)
return fmt.Sprintf("%x:%x", stat.Dev, stat.Ino), nil
}
@@ -0,0 +1,16 @@
package guesttools
import (
"fmt"
"os"
"syscall"
)
func sharedDirectoryID(dir *os.File) (string, error) {
var info syscall.ByHandleFileInformation
if err := syscall.GetFileInformationByHandle(syscall.Handle(dir.Fd()), &info); err != nil {
return "", err
}
return fmt.Sprintf("%x:%08x%08x:%x", info.VolumeSerialNumber, info.FileIndexHigh,
info.FileIndexLow, info.CreationTime.Nanoseconds()), nil
}
+158
View File
@@ -0,0 +1,158 @@
package guesttools
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestFileSyncRequiresConfirmedRevisionAndContent(t *testing.T) {
root := t.TempDir()
shared := filepath.Join(root, "share")
srv := NewTransportServer(&memClipboard{})
port, err := srv.Start(-1)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = srv.Close(context.Background()) })
cfg, err := LoadOrCreateVMConfig(root, "sync-test", shared, port)
if err != nil {
t.Fatal(err)
}
srv.RegisterVM(cfg)
request := func(method, path, body string, headers http.Header, want int) (http.Header, string) {
t.Helper()
req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, path), strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
if headers != nil {
req.Header = headers.Clone()
}
req.Header.Set("Authorization", "Bearer "+cfg.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil || resp.StatusCode != want {
t.Fatalf("%s %s: status=%d, want=%d, body=%q, read error=%v", method, path, resp.StatusCode, want, b, err)
}
return resp.Header, string(b)
}
const fileURL = "/v1/file?path=entry.txt"
const contents = "original"
digest := fmt.Sprintf("%x", sha256.Sum256([]byte(contents)))
list, _ := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK)
scope := list.Get(syncScopeHeader)
if scope == "" {
t.Fatal("missing sync scope")
}
conditions := make(http.Header)
conditions.Set(syncScopeHeader, scope)
conditions.Set("If-None-Match", "*")
created, _ := request(http.MethodPut, fileURL+"&mtime=1700000000", contents, conditions, http.StatusOK)
tag := created.Get("ETag")
if tag == "" || created.Get(syncDigestHeader) != digest {
t.Fatalf("upload revision or digest missing: %v", created)
}
_, legacyList := request(http.MethodGet, "/v1/files", "", nil, http.StatusOK)
_, versionedList := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK)
if legacyList != "1700000000\t8\tentry.txt\n" ||
versionedList != "1700000000\t8\t"+tag+"\tentry.txt\n" {
t.Fatalf("unexpected file listings: legacy=%q, versioned=%q", legacyList, versionedList)
}
request(http.MethodPut, fileURL, "overwritten", conditions, http.StatusPreconditionFailed)
conditions.Del("If-None-Match")
conditions.Set("If-Match", tag)
probed, _ := request(http.MethodHead, fileURL+"&sha256=1", "", conditions, http.StatusOK)
if probed.Get(syncDigestHeader) != digest {
t.Fatalf("unexpected digest: %v", probed)
}
request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionRequired)
conditions.Set(syncDigestHeader, digest)
conditions.Set("If-Match", "\"stale-revision\"")
request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed)
conditions.Set("If-Match", tag)
request(http.MethodPut, fileURL+"&mtime=1700000000", "modified", nil, http.StatusOK)
request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed)
_, got := request(http.MethodGet, fileURL, "", nil, http.StatusOK)
if got != "modified" {
t.Fatalf("modified copy was lost: %q", got)
}
conditions.Set(syncDigestHeader, fmt.Sprintf("%x", sha256.Sum256([]byte(got))))
request(http.MethodDelete, fileURL, "", conditions, http.StatusNoContent)
request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound)
if err := os.Rename(shared, filepath.Join(root, "old-share")); err != nil {
t.Fatal(err)
}
request(http.MethodGet, "/v1/files?sync=1", "", conditions, http.StatusServiceUnavailable)
request(http.MethodHead, fileURL, "", conditions, http.StatusServiceUnavailable)
srv.RegisterVM(cfg)
list, _ = request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK)
newScope := list.Get(syncScopeHeader)
if newScope == "" || newScope == scope {
t.Fatalf("recreated share must have a new scope: %q", newScope)
}
request(http.MethodHead, fileURL, "", conditions, http.StatusPreconditionFailed)
request(http.MethodPut, fileURL, "stale upload", conditions, http.StatusPreconditionFailed)
conditions = http.Header{syncScopeHeader: {newScope}}
request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound)
request(http.MethodPut, "/v1/file?path=nested/file.txt", contents, conditions, http.StatusOK)
_, got = request(http.MethodGet, "/v1/file?path=nested/file.txt", "", conditions, http.StatusOK)
if got != contents {
t.Fatalf("nested file contents: %q", got)
}
}
func TestFileSyncConfinesUploadToShare(t *testing.T) {
shared, outside := t.TempDir(), t.TempDir()
link := filepath.Join(shared, "linked")
if err := os.Symlink(outside, link); err != nil {
if runtime.GOOS != "windows" {
t.Skipf("directory symlink unavailable: %v", err)
}
output, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput()
if err != nil {
t.Fatalf("create test junction: %v: %s", err, output)
}
}
srv := NewTransportServer(&memClipboard{})
token := strings.Repeat("a", 64)
srv.RegisterVM(VMConfig{VMName: "sync-test", Token: token, SharedDir: shared})
list := httptest.NewRequest(http.MethodGet, "/v1/files?sync=1", nil)
list.Header.Set("Authorization", "Bearer "+token)
listed := httptest.NewRecorder()
srv.handleListFiles(listed, list)
scope := listed.Header().Get(syncScopeHeader)
if listed.Code != http.StatusOK || scope == "" {
t.Fatalf("listing failed: %d: %s", listed.Code, listed.Body)
}
for _, version := range []string{"", scope} {
req := httptest.NewRequest(http.MethodPut, "/v1/file?path=linked/upload.txt", strings.NewReader("test upload"))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set(syncScopeHeader, version)
res := httptest.NewRecorder()
srv.handleFile(res, req)
if res.Code < http.StatusBadRequest {
t.Fatalf("upload through an out-of-share link succeeded: %d", res.Code)
}
if _, err := os.Stat(filepath.Join(outside, "upload.txt")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("upload escaped share: %v", err)
}
}
}
+11 -62
View File
@@ -2,6 +2,7 @@ package guesttools
import (
"bytes"
_ "embed"
"fmt"
"io"
"os"
@@ -15,8 +16,11 @@ const (
InstallCommand = "sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command"
)
//go:embed file_sync.sh
var guestFileSync string
// BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS")
// containing the per-VM Bearer token config, Guest Tools 4 POSIX agent script
// containing the per-VM Bearer token config, Guest Tools POSIX agent script
// (text + PNG image clipboard with long-poll, WebDAV live mount with fallback
// sync, and caffeinate prevent-sleep daemon), plus install/uninstall/pmset scripts.
func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
@@ -65,7 +69,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files)
}
// GuestAgentScript returns the Guest Tools 4 stock-macOS POSIX shell daemon
// GuestAgentScript returns the Guest Tools stock-macOS POSIX shell daemon
// (no Xcode or Python required):
// - Two-way UTF-8 text + PNG screenshot clipboard with server long-polling
// - Zero-duplication WebDAV shared folder mount (~/Desktop/ReimsShare) with automatic sync fallback
@@ -73,7 +77,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
// - Live host-controlled prevent-sleep guard via `caffeinate -dims` (no sudo required)
func GuestAgentScript() []byte {
return []byte(`#!/bin/sh
# Reims Guest Tools 4: clipboard, WebDAV share, read-only Windows drives, prevent-sleep.
# Reims Guest Tools: clipboard, WebDAV share, read-only Windows drives, prevent-sleep.
set -u
# Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified
@@ -309,7 +313,7 @@ report_status() {
curl -fsS -m 3 -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":6}" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":7}" \
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true
}
@@ -484,62 +488,7 @@ sync_clipboard() {
esac
}
sync_files() {
[ "$mount_mode" = "webdav" ] && return 0
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
remote_list="$TMP_DIR/remote_files.tsv"
if ! curl -fsS -m 5 \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/files" -o "$remote_list" 2>/dev/null; then
return 0
fi
# 1. Host -> Guest (download new or strictly newer files)
while IFS="$TAB" read -r rmtime rsize rrel; do
[ -n "$rrel" ] || continue
local_path="$SHARE_SYNC/$rrel"
need_dl=0
if [ ! -f "$local_path" ]; then
need_dl=1
else
lmtime=$(stat -f '%m' "$local_path" 2>/dev/null || echo 0)
if [ "$rmtime" -gt $((lmtime + 2)) ]; then
need_dl=1
fi
fi
if [ "$need_dl" -eq 1 ]; then
mkdir -p "$(dirname "$local_path")"
enc=$(urlencode "$rrel")
dl_tmp="$TMP_DIR/dl.part"
if curl -fsS -m 60 \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/file?path=$enc" -o "$dl_tmp" 2>/dev/null; then
mv -f "$dl_tmp" "$local_path"
touch -d "@$rmtime" "$local_path" 2>/dev/null || true
else
rm -f "$dl_tmp"
fi
fi
done <"$remote_list"
# 2. Guest -> Host (upload new or strictly newer files)
find "$SHARE_SYNC" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do
rel=${fpath#"$SHARE_SYNC/"}
[ -n "$rel" ] || continue
lmtime=$(stat -f '%m' "$fpath" 2>/dev/null || echo 0)
lsize=$(stat -f '%z' "$fpath" 2>/dev/null || echo 0)
[ "$lsize" -le 268435456 ] || continue
rmtime=$(awk -F '\t' -v p="$rel" '$3==p {print $1; exit}' "$remote_list")
[ -n "$rmtime" ] || rmtime=0
if [ "$lmtime" -gt $((rmtime + 2)) ]; then
enc=$(urlencode "$rel")
curl -fsS -m 60 -X PUT \
-H "Authorization: Bearer $REIMS_TOKEN" \
--data-binary "@$fpath" \
"$REIMS_HOST_URL/v1/file?path=$enc&mtime=$lmtime" >/dev/null 2>&1 || true
fi
done
}
` + guestFileSync + `
text_input_loop() {
hdr="$TMP_DIR/txt_hdr"
@@ -668,12 +617,12 @@ launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST
# Verify host bridge connectivity immediately.
. "$APP_DIR/config"
if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then
echo "Reims Guest Tools 4 installed and connected!"
echo "Reims Guest Tools installed and connected!"
echo "Clipboard: UTF-8 text + PNG screenshots (two-way)"
echo "Shared folder: ~/Desktop/ReimsShare (WebDAV live mount, auto-fallback to sync)"
echo "Prevent-sleep: controlled live from Reims-Go host UI"
else
echo "Reims Guest Tools 4 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
fi
`)
}
+2 -2
View File
@@ -280,8 +280,8 @@ func TestListSharedFilesSkipsUnavailableEntries(t *testing.T) {
}
}
return statDAVEntry(root, name)
})
if err != nil || len(list) != 1 || list[0].rel != "visible.txt" || list[0].size != int64(len("contents")) {
}, false)
if err != nil || len(list) != 1 || list[0].name != "visible.txt" || list[0].info.Size() != int64(len("contents")) {
t.Fatalf("list = %+v, err = %v", list, err)
}
}
+1 -243
View File
@@ -11,13 +11,10 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
@@ -198,6 +195,7 @@ type registeredVM struct {
// (reachable from QEMU SLIRP guests as http://10.0.2.2:<port>).
type Server struct {
mu sync.RWMutex
fileMu sync.Mutex
clipWriteMu sync.Mutex
clip Clipboard
vms map[string]*registeredVM // keyed by VM name
@@ -1178,243 +1176,3 @@ func (s *Server) handleHostText(w http.ResponseWriter, r *http.Request) {
}
w.WriteHeader(http.StatusAccepted)
}
func isIgnoredSharedName(name string) bool {
return name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "._")
}
// sharedFilePath validates a relative slash path used by the legacy sync API.
func sharedFilePath(rel string) (string, error) {
if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) {
return "", errors.New("invalid path")
}
trimmed := strings.TrimSpace(rel)
if trimmed == "" || strings.HasPrefix(trimmed, "/") {
return "", errors.New("invalid relative path")
}
for _, rawSeg := range strings.Split(trimmed, "/") {
if rawSeg == ".." || rawSeg == "." {
return "", errors.New("path traversal not allowed")
}
}
clean := path.Clean(trimmed)
if clean == "" || clean == "." || strings.HasPrefix(clean, "..") {
return "", errors.New("invalid relative path")
}
parts := strings.Split(clean, "/")
if len(parts) > MaxSharedDepth {
return "", errors.New("path too deep")
}
for _, seg := range parts {
if seg == "" || seg == "." || seg == ".." || strings.ContainsAny(seg, `:\<>|"?*`) || isIgnoredSharedName(seg) {
return "", errors.New("invalid path segment")
}
}
return clean, nil
}
func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if vm.sharedDir == "" {
w.WriteHeader(http.StatusOK)
return
}
root, err := openSharedRoot(vm.sharedRoot, true)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer root.Close()
list, err := listSharedFiles(root.FS(), func(name string) (os.FileInfo, error) {
return statDAVEntry(root, name)
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
sort.Slice(list, func(i, j int) bool { return list[i].rel < list[j].rel })
w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8")
for _, e := range list {
_, _ = fmt.Fprintf(w, "%d\t%d\t%s\n", e.mtime, e.size, e.rel)
}
}
type sharedFileEntry struct {
mtime int64
size int64
rel string
}
func listSharedFiles(fsys fs.FS, stat func(string) (os.FileInfo, error)) ([]sharedFileEntry, error) {
var list []sharedFileEntry
err := fs.WalkDir(fsys, ".", func(rel string, d fs.DirEntry, err error) error {
if err != nil {
if rel == "." {
return err
}
return fs.SkipDir
}
if rel == "." {
return nil
}
name := d.Name()
if isIgnoredSharedName(name) {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if strings.Count(rel, "/")+1 > MaxSharedDepth {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if d.Type() == os.ModeDir {
return nil
}
info, err := stat(rel)
if err != nil {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if !isSharedRegularFile(info.Mode()) || info.Size() > MaxUploadBytes {
return nil
}
if len(list) >= MaxSharedFiles {
return fs.SkipAll
}
list = append(list, sharedFileEntry{mtime: info.ModTime().Unix(), size: info.Size(), rel: rel})
return nil
})
return list, err
}
func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if vm.sharedDir == "" {
http.Error(w, "shared directory not configured", http.StatusBadRequest)
return
}
rel, err := sharedFilePath(r.URL.Query().Get("path"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodPut && r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
root, err := openSharedRoot(vm.sharedRoot, r.Method != http.MethodGet)
if err != nil {
if r.Method == http.MethodGet && os.IsNotExist(err) {
http.NotFound(w, r)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer root.Close()
switch r.Method {
case http.MethodGet:
info, err := statDAVEntry(root, rel)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
if err == os.ErrPermission {
http.Error(w, "not a regular file", http.StatusBadRequest)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !isSharedRegularFile(info.Mode()) {
http.Error(w, "not a regular file", http.StatusBadRequest)
return
}
f, err := root.Open(rel)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
info, err = f.Stat()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !isSharedRegularFile(info.Mode()) {
http.Error(w, "not a regular file", http.StatusBadRequest)
return
}
w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10))
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = io.Copy(w, f)
case http.MethodPut, http.MethodPost:
dir := path.Dir(rel)
if err := root.MkdirAll(dir, 0o755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
parent, err := root.OpenRoot(dir)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer parent.Close()
tmpName := ".reims-upload-" + rand.Text()
tmp, err := parent.OpenFile(tmpName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
saved := false
defer func() {
if !saved {
_ = parent.Remove(tmpName)
}
}()
n, copyErr := io.Copy(tmp, io.LimitReader(r.Body, MaxUploadBytes+1))
closeErr := tmp.Close()
if copyErr != nil || closeErr != nil || n > MaxUploadBytes {
if n > MaxUploadBytes {
http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "write failed", http.StatusInternalServerError)
return
}
if mtimeStr := r.URL.Query().Get("mtime"); mtimeStr != "" {
if ts, perr := strconv.ParseInt(mtimeStr, 10, 64); perr == nil && ts > 0 {
t := time.Unix(ts, 0)
if err := parent.Chtimes(tmpName, t, t); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
if err := parent.Rename(tmpName, path.Base(rel)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
saved = true
w.WriteHeader(http.StatusOK)
}
}
+54
View File
@@ -45,11 +45,14 @@ var catalog = map[Locale]map[string]string{
"cli.usage.cmd_version": " version 查看当前版本",
"cli.usage.cmd_vm_compact": " vm compact <name> 停机回收 .qcow2 磁盘未用空间",
"cli.usage.cmd_vm_create": " vm create [options] <name> 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)",
"cli.usage.cmd_vm_discard_suspend": " vm discard-suspend <name> 放弃已保存的挂起状态并回到关机状态",
"cli.usage.cmd_vm_list": " vm list 列出已创建的虚拟机",
"cli.usage.cmd_vm_resize": " vm resize <name> <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)",
"cli.usage.cmd_vm_resume": " vm resume <name> 从磁盘挂起状态恢复虚拟机",
"cli.usage.cmd_vm_set": " vm set [options] <name> 修改虚拟机配置(下次启动生效)",
"cli.usage.cmd_vm_start": " vm start <name> 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动",
"cli.usage.cmd_vm_stop": " vm stop|eject <name> 停止 / 弹出安装盘",
"cli.usage.cmd_vm_suspend": " vm suspend <name> 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)",
"cli.usage.cmd_vm_type": " vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)",
"cli.usage.header": "reims-go - Windows 一站式免编译 reims-vgpu 启动器",
"cli.usage.line_cmd": " reims-go [--lang <BCP-47|auto|en-XA>] [--data-root DIR] <命令> [参数]",
@@ -134,6 +137,14 @@ var catalog = map[Locale]map[string]string{
"err.snapshot.qcow2_only": "恢复点仅支持 .qcow2 格式磁盘",
"err.snapshot.qemu_img_failed": "恢复点操作未完成({snap})",
"err.snapshot.vm_running": "请先停止「{name}」再创建、回滚或删除恢复点",
"err.suspend.action_blocked": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作",
"err.suspend.busy": "虚拟机「{name}」正在执行状态切换,请稍后再试",
"err.suspend.discard_running": "虚拟机「{name}」正在运行,无法放弃挂起状态",
"err.suspend.disk_space": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)",
"err.suspend.incompatible": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动",
"err.suspend.not_found": "未找到「{name}」的完整挂起状态文件",
"err.suspend.not_running": "虚拟机「{name}」未在运行,无法挂起",
"err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本",
"err.update_changed": "已下载的更新文件被改动过,请重新下载",
"err.update_dev_build": "开发版本不支持应用内更新",
"err.update_no_asset": "这个版本没有提供 Windows 程序文件,请到发布页手动下载",
@@ -429,35 +440,45 @@ var catalog = map[Locale]map[string]string{
"toastSSHUserSaved": "已保存 SSH 用户名",
"toastSaved": "已保存",
"toastSavedNextStart": "已保存,下次启动生效",
"tray.menu.discard_suspend": "放弃挂起状态…(&X)",
"tray.menu.force_stop": "强制关机(&F)",
"tray.menu.new_vm": "新建虚拟机(&N)…",
"tray.menu.open_in_app": "在 Reims-Go 中查看(&V)",
"tray.menu.quit": "退出 Reims-Go(&Q)",
"tray.menu.restart": "重启(&R)",
"tray.menu.resume": "恢复(&U)",
"tray.menu.resume_unavailable": "恢复(当前内核不支持挂起)",
"tray.menu.screenshot": "复制屏幕截图(&C)",
"tray.menu.shared_folder": "打开共享文件夹(&H)",
"tray.menu.show": "显示 Reims-Go(&O)",
"tray.menu.show_window": "显示窗口(&W)",
"tray.menu.start": "启动(&S)",
"tray.menu.stop": "关机(&D)",
"tray.menu.suspend": "挂起(&P)",
"tray.menu.toggle_fullscreen": "切换全屏",
"tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态",
"tray.notify.focus_fail": "找不到 {name} 的窗口",
"tray.notify.force_stop_fail": "无法强制关机 {name}",
"tray.notify.fullscreen_fail": "无法切换 {name} 全屏",
"tray.notify.restart_fail": "无法重启 {name}",
"tray.notify.resume_fail": "无法恢复 {name}",
"tray.notify.screenshot_fail": "截图失败:{name}",
"tray.notify.screenshot_ok": "已复制屏幕截图",
"tray.notify.shared_fail": "无法打开共享文件夹",
"tray.notify.start_fail": "无法启动 {name}",
"tray.notify.stop_fail": "无法关机 {name}",
"tray.notify.suspend_fail": "无法挂起 {name}",
"tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}",
"tray.running.many": "Reims-Go — {count} 台虚拟机运行中",
"tray.running.one": "Reims-Go — 1 台虚拟机运行中",
"tray.state.broken": "配置损坏",
"tray.state.resuming": "正在恢复…",
"tray.state.running": "运行中",
"tray.state.starting": "启动中…",
"tray.state.stopped": "已停止",
"tray.state.stopping": "正在关机…",
"tray.state.suspended": "已挂起",
"tray.state.suspending": "正在挂起…",
"tray.state.unknown": "未知",
"updateCancel": "取消下载",
"updateCapsuleAvailable": "{v} 可用",
@@ -498,6 +519,7 @@ var catalog = map[Locale]map[string]string{
"validate.missing_name": "虚拟机名称不能为空",
"validate.missing_release": "请选择要离线安装的 macOS 版本",
"validate.name_taken": "已存在名为 {name} 的虚拟机",
"validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置",
"viewLogs": "查看日志",
"vm.already_running": "{name} 已在运行中",
"vm.compact.done": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)",
@@ -557,11 +579,14 @@ var catalog = map[Locale]map[string]string{
"cli.usage.cmd_version": " version Show current version",
"cli.usage.cmd_vm_compact": " vm compact <name> Compact stopped .qcow2 disk to reclaim unused space",
"cli.usage.cmd_vm_create": " vm create [options] <name> Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)",
"cli.usage.cmd_vm_discard_suspend": " vm discard-suspend <name> Discard a saved suspend state and return the VM to powered off",
"cli.usage.cmd_vm_list": " vm list List virtual machines",
"cli.usage.cmd_vm_resize": " vm resize <name> <size> Expand stopped VM disk (e.g. 256G or +64G)",
"cli.usage.cmd_vm_resume": " vm resume <name> Resume a suspended VM from disk",
"cli.usage.cmd_vm_set": " vm set [options] <name> Update VM settings (applies on next start)",
"cli.usage.cmd_vm_start": " vm start <name> Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process",
"cli.usage.cmd_vm_stop": " vm stop|eject <name> Stop / eject installer",
"cli.usage.cmd_vm_suspend": " vm suspend <name> Suspend a running VM to disk for fast resume across restarts",
"cli.usage.cmd_vm_type": " vm type <name> [text] Type text into a running VM as US-keyboard keys (stdin if no text)",
"cli.usage.header": "reims-go - Portable one-stop reims-vgpu launcher for Windows",
"cli.usage.line_cmd": " reims-go [--lang <BCP-47|auto|en-XA>] [--data-root DIR] <command> [args]",
@@ -646,6 +671,14 @@ var catalog = map[Locale]map[string]string{
"err.snapshot.qcow2_only": "Restore points are only supported on .qcow2 disks",
"err.snapshot.qemu_img_failed": "Restore point operation could not finish ({snap})",
"err.snapshot.vm_running": "Stop “{name}” before creating, restoring or deleting a restore point",
"err.suspend.action_blocked": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this",
"err.suspend.busy": "VM “{name}” is busy transitioning; try again in a moment",
"err.suspend.discard_running": "VM “{name}” is currently running; suspend state cannot be discarded",
"err.suspend.disk_space": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)",
"err.suspend.incompatible": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state",
"err.suspend.not_found": "No complete suspend state found for “{name}”",
"err.suspend.not_running": "VM “{name}” is not running and cannot be suspended",
"err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support",
"err.update_changed": "The downloaded update changed on disk; download it again",
"err.update_dev_build": "In-app update is disabled in development builds",
"err.update_no_asset": "This release has no Windows executable; download it from the release page",
@@ -941,35 +974,45 @@ var catalog = map[Locale]map[string]string{
"toastSSHUserSaved": "Saved SSH username",
"toastSaved": "Saved",
"toastSavedNextStart": "Saved — applies on next start",
"tray.menu.discard_suspend": "Discard Saved Stat&e…",
"tray.menu.force_stop": "&Force Shut Down",
"tray.menu.new_vm": "&New Virtual Machine…",
"tray.menu.open_in_app": "Show in &Reims-Go",
"tray.menu.quit": "&Quit Reims-Go",
"tray.menu.restart": "&Restart",
"tray.menu.resume": "Res&ume",
"tray.menu.resume_unavailable": "Resume (runtime lacks suspend support)",
"tray.menu.screenshot": "&Copy Screenshot",
"tray.menu.shared_folder": "Open S&hared Folder",
"tray.menu.show": "&Show Reims-Go",
"tray.menu.show_window": "Show &Window",
"tray.menu.start": "&Start",
"tray.menu.stop": "Shut &Down",
"tray.menu.suspend": "Sus&pend",
"tray.menu.toggle_fullscreen": "Toggle full screen",
"tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}",
"tray.notify.focus_fail": "Couldn't find the window of {name}",
"tray.notify.force_stop_fail": "Couldn't force shut down {name}",
"tray.notify.fullscreen_fail": "Couldn’t toggle full screen for {name}",
"tray.notify.restart_fail": "Couldn't restart {name}",
"tray.notify.resume_fail": "Couldn't resume {name}",
"tray.notify.screenshot_fail": "Screenshot failed: {name}",
"tray.notify.screenshot_ok": "Screenshot copied",
"tray.notify.shared_fail": "Couldn't open the shared folder",
"tray.notify.start_fail": "Couldn't start {name}",
"tray.notify.stop_fail": "Couldn't shut down {name}",
"tray.notify.suspend_fail": "Couldn't suspend {name}",
"tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}",
"tray.running.many": "Reims-Go — {count} VMs running",
"tray.running.one": "Reims-Go — 1 VM running",
"tray.state.broken": "Broken",
"tray.state.resuming": "Resuming…",
"tray.state.running": "Running",
"tray.state.starting": "Starting…",
"tray.state.stopped": "Stopped",
"tray.state.stopping": "Shutting down…",
"tray.state.suspended": "Suspended",
"tray.state.suspending": "Suspending…",
"tray.state.unknown": "Unknown",
"updateCancel": "Cancel download",
"updateCapsuleAvailable": "{v} available",
@@ -1010,6 +1053,7 @@ var catalog = map[Locale]map[string]string{
"validate.missing_name": "VM name is required",
"validate.missing_release": "Choose the macOS release to install offline",
"validate.name_taken": "A VM named {name} already exists",
"validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings",
"viewLogs": "View logs",
"vm.already_running": "{name} is already running",
"vm.compact.done": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)",
@@ -1074,6 +1118,13 @@ var paramOrder = map[string][]string{
"err.plugin.system_locked": {"id"},
"err.snapshot.qemu_img_failed": {"snap"},
"err.snapshot.vm_running": {"name"},
"err.suspend.action_blocked": {"name"},
"err.suspend.busy": {"name"},
"err.suspend.discard_running": {"name"},
"err.suspend.disk_space": {"need", "avail"},
"err.suspend.incompatible": {"diffs"},
"err.suspend.not_found": {"name"},
"err.suspend.not_running": {"name"},
"err.update_not_writable": {"dir"},
"err.vm_not_running": {"name"},
"err.vm_window_not_found": {"name"},
@@ -1145,13 +1196,16 @@ var paramOrder = map[string][]string{
"toastInstallerReady": {"v"},
"toastRuntimeReady": {"v"},
"toastSSHConfigWritten": {"alias"},
"tray.notify.discard_suspend_fail": {"name"},
"tray.notify.focus_fail": {"name"},
"tray.notify.force_stop_fail": {"name"},
"tray.notify.fullscreen_fail": {"name"},
"tray.notify.restart_fail": {"name"},
"tray.notify.resume_fail": {"name"},
"tray.notify.screenshot_fail": {"name"},
"tray.notify.start_fail": {"name"},
"tray.notify.stop_fail": {"name"},
"tray.notify.suspend_fail": {"name"},
"tray.running": {"count"},
"tray.running.many": {"count"},
"updateCapsuleAvailable": {"v"},
+5 -1
View File
@@ -6,6 +6,8 @@ import (
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
)
const progressFile = ".reims-go-install-guide.json"
@@ -55,7 +57,9 @@ func (g *Guide) Resume(dir, media string, recovery bool) bool {
return recovery
}
if recovery {
if cp.Kind == g.Kind && strings.EqualFold(cp.Media, media) && cp.Step.recoveryStep(g.Kind) {
// Older checkpoints may contain the abbreviated installer path from show.
sameMedia := strings.EqualFold(config.ExpandHomePath(cp.Media), media)
if cp.Kind == g.Kind && sameMedia && cp.Step.recoveryStep(g.Kind) {
g.initial = cp.Step
}
return true
@@ -2,6 +2,7 @@ package installguide
import (
"errors"
"path/filepath"
"testing"
"time"
)
@@ -148,3 +149,17 @@ func TestGuideKeepsMediaAndVMProgressSeparate(t *testing.T) {
t.Fatal("clone inherited source disk preparation")
}
}
func TestGuideResumesWithExpandedInstallerPath(t *testing.T) {
home := t.TempDir()
t.Setenv("USERPROFILE", home)
dir := t.TempDir()
g := Guide{Name: "macos-15", Kind: Offline, PID: 33}
g.Resume(dir, `~\macOS-15-offline-installer.img`, true)
if err := g.save(command, 0); err != nil {
t.Fatal(err)
}
if !g.Resume(dir, filepath.Join(home, "macOS-15-offline-installer.img"), true) || g.initial != command {
t.Fatalf("guide resumed at %s, want %s", g.initial, command)
}
}
+31 -9
View File
@@ -45,15 +45,26 @@ func (c *Conn) Close() error { return c.nc.Close() }
type qmpReply struct {
Return json.RawMessage `json:"return"`
Error *struct {
Class string `json:"class"`
Desc string `json:"desc"`
} `json:"error"`
Event string `json:"event"`
Error *commandError `json:"error"`
Event string `json:"event"`
}
// Query runs one command and waits for its JSON return value, skipping async events.
type commandError struct {
Class string `json:"class"`
Desc string `json:"desc"`
}
func (e *commandError) Error() string { return e.Class + ": " + e.Desc }
// Query runs one command with the default 5-second timeout and waits for its
// JSON return value, skipping async events.
func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
return c.QueryWithTimeout(command, args, 5*time.Second)
}
// QueryWithTimeout runs one command and waits up to timeout for its JSON return
// value, skipping async events.
func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration) (json.RawMessage, error) {
req := map[string]any{"execute": command}
if args != nil {
req["arguments"] = args
@@ -62,7 +73,10 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
if err != nil {
return nil, err
}
_ = c.nc.SetDeadline(time.Now().Add(5 * time.Second))
if timeout <= 0 {
timeout = 5 * time.Second
}
_ = c.nc.SetDeadline(time.Now().Add(timeout))
if _, err := c.nc.Write(append(b, '\n')); err != nil {
return nil, fmt.Errorf("QMP %s: %w", command, err)
}
@@ -72,7 +86,7 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
continue
}
if r.Error != nil {
return nil, fmt.Errorf("QMP %s: %s: %s", command, r.Error.Class, r.Error.Desc)
return nil, fmt.Errorf("QMP %s: %w", command, r.Error)
}
if r.Return != nil {
return append(json.RawMessage(nil), r.Return...), nil
@@ -84,8 +98,16 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
return nil, fmt.Errorf("QMP %s: connection closed", command)
}
// Execute runs one command and waits for its reply, skipping async events.
// Execute runs one command with the default timeout and waits for its reply,
// skipping async events.
func (c *Conn) Execute(command string, args any) error {
_, err := c.Query(command, args)
return err
}
// ExecuteWithTimeout runs one command and waits up to timeout for its reply,
// skipping async events.
func (c *Conn) ExecuteWithTimeout(command string, args any, timeout time.Duration) error {
_, err := c.QueryWithTimeout(command, args, timeout)
return err
}
+59
View File
@@ -0,0 +1,59 @@
package qmp
import (
"encoding/json"
"fmt"
"path/filepath"
"slices"
"strings"
)
// AttachedFiles lists the inserted image and backing files for each block
// device. QEMU's resolved image names include the real pflash and CD drives.
func (c *Conn) AttachedFiles(vmDir string) ([]string, error) {
raw, err := c.Query("query-block", nil)
if err != nil {
return nil, err
}
type image struct {
Filename string `json:"filename"`
Backing *image `json:"backing-image"`
}
var devices []struct {
Device string `json:"device"`
Inserted *struct {
Image *image `json:"image"`
Backing string `json:"backing_file"`
} `json:"inserted"`
}
if err := json.Unmarshal(raw, &devices); err != nil {
return nil, fmt.Errorf("decode query-block: %w", err)
}
var paths []string
for _, d := range devices {
if d.Inserted == nil {
continue
}
if d.Inserted.Image == nil || (d.Inserted.Backing != "" && d.Inserted.Image.Backing == nil) {
return nil, fmt.Errorf("cannot identify the complete attached disk or backing chain")
}
for img := d.Inserted.Image; img != nil; img = img.Backing {
if img.Filename == "" {
return nil, fmt.Errorf("block device has no filename")
}
name := img.Filename
if strings.HasPrefix(name, "json:") {
return nil, fmt.Errorf("block device %s uses a non-persistent or unresolvable image; eject it before suspending", d.Device)
}
if !filepath.IsAbs(name) {
name = filepath.Join(vmDir, name)
}
paths = append(paths, filepath.Clean(name))
}
}
if len(paths) == 0 {
return nil, fmt.Errorf("no attached media reported by QEMU")
}
slices.Sort(paths)
return slices.Compact(paths), nil
}
+367
View File
@@ -0,0 +1,367 @@
package qmp
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strings"
"time"
)
const (
// DefaultMultifdChannels is the parallel I/O channel count used for
// mapped-ram file snapshots on Windows.
DefaultMultifdChannels = 4
migratePollInterval = 200 * time.Millisecond
migrateCmdTimeout = 2 * time.Minute
migrateTotalTimeout = 15 * time.Minute
)
// MigrateProgress carries the latest snapshot save/load progress from QMP
// `query-migrate`.
type MigrateProgress struct {
Status string `json:"status"`
Transferred int64 `json:"transferred"`
Remaining int64 `json:"remaining"`
Total int64 `json:"total"`
TotalTimeMs int64 `json:"total_time_ms"`
}
type migrateInfo struct {
Status string `json:"status"`
ErrorDesc string `json:"error-desc"`
TotalTimeMs int64 `json:"total-time"`
RAM *struct {
Transferred int64 `json:"transferred"`
Remaining int64 `json:"remaining"`
Total int64 `json:"total"`
} `json:"ram"`
}
type vmStatusReply struct {
Running bool `json:"running"`
Status string `json:"status"`
}
// ErrIncompleteSuspend marks a save that QEMU rejected, failed, or cancelled.
// The caller may remove its staging file once QEMU no longer writes to it.
var ErrIncompleteSuspend = errors.New("incomplete suspend snapshot")
type migrationFailure struct {
status string
desc string
}
func (e *migrationFailure) Error() string {
if e.desc != "" {
return fmt.Sprintf("migration %s: %s", e.status, e.desc)
}
return "migration " + e.status
}
// A timeout or a dropped connection can hide a completed migration.
type unknownSuspendOutcome struct{ error }
func (e *unknownSuspendOutcome) Unwrap() error { return e.error }
// SuspendToFile pauses a running Intel VM via QMP, writes a mapped-ram +
// multifd file snapshot to vmstatePath, waits for completion, and shuts down
// QEMU cleanly via `quit`.
//
// If migration fails before reaching completion while the VM is merely paused
// (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so
// the running VM is not left frozen.
func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), seal func([]string) error) error {
if seal == nil {
return errors.New("suspend snapshot requires a seal callback")
}
addr := SocketPath(vmDir)
c, err := Dial(ctx, "unix", addr)
if err != nil {
return err
}
defer c.Close()
paths, err := c.AttachedFiles(vmDir)
if err != nil {
return err
}
err = suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) })
var unknown *unknownSuspendOutcome
if errors.As(err, &unknown) {
_ = c.Close()
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 8*time.Second)
defer cancel()
fresh, dialErr := dialMigrateConnWithRetry(cleanup, "unix", addr, 3*time.Second)
if dialErr == nil {
defer fresh.Close()
if cancelIncompleteSuspend(cleanup, fresh) {
return fmt.Errorf("%w: %w", ErrIncompleteSuspend, err)
}
}
}
return err
}
func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress), seal func(*Conn) error) error {
if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil {
return fmt.Errorf("pause VM before suspend: %w", err)
}
st, err := queryVMStatus(c)
if err != nil {
tryResumePaused(c)
return fmt.Errorf("verify paused state: %w", err)
}
if st.Running {
return fmt.Errorf("VM remained running after stop (status=%s)", st.Status)
}
if err := configureMappedRAM(c); err != nil {
tryResumePaused(c)
return err
}
args := map[string]any{
"channels": fileChannels(vmstatePath),
}
if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil {
var rejected *commandError
if errors.As(err, &rejected) {
tryResumePaused(c)
return fmt.Errorf("%w: start snapshot save: %w", ErrIncompleteSuspend, err)
}
return &unknownSuspendOutcome{fmt.Errorf("start snapshot save: %w", err)}
}
if err := waitMigrateDone(ctx, c, onProgress); err != nil {
var failed *migrationFailure
if errors.As(err, &failed) {
tryResumePaused(c)
return fmt.Errorf("%w: save snapshot: %w", ErrIncompleteSuspend, err)
}
return &unknownSuspendOutcome{fmt.Errorf("save snapshot: %w", err)}
}
if seal != nil {
if err := seal(c); err != nil {
// The source still owns the session. Leave it paused and retain
// the completed file if publishing the save failed.
return fmt.Errorf("seal snapshot before exiting QEMU: %w", err)
}
}
// Migration completed (RUN_STATE_POSTMIGRATE): never send `cont` here;
// exit QEMU cleanly so the disk and WHPX partition close.
if err := c.ExecuteWithTimeout("quit", nil, 15*time.Second); err != nil {
// QEMU may close the QMP socket immediately upon receiving `quit`.
if !isConnClosedErr(err) {
return fmt.Errorf("quit QEMU after suspend: %w", err)
}
}
return nil
}
// ResumeFromFile connects to a QEMU process started with `-incoming defer`,
// loads the mapped-ram + multifd file snapshot from vmstatePath, waits for
// completion, and resumes execution with `cont`.
//
// On any error, vmstatePath is left untouched so the caller can retry.
func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), checkMedia func(*Conn) error) error {
c, err := dialMigrateConnWithRetry(ctx, "unix", SocketPath(vmDir), 10*time.Second)
if err != nil {
return err
}
defer c.Close()
if checkMedia != nil {
if err := checkMedia(c); err != nil {
return err
}
}
return resumeFromFileConn(ctx, c, vmstatePath, onProgress)
}
func resumeFromFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error {
if err := configureMappedRAM(c); err != nil {
return err
}
args := map[string]any{
"channels": fileChannels(vmstatePath),
"exit-on-error": false,
}
if err := c.ExecuteWithTimeout("migrate-incoming", args, migrateCmdTimeout); err != nil {
return fmt.Errorf("start snapshot restore: %w", err)
}
if err := waitMigrateDone(ctx, c, onProgress); err != nil {
return fmt.Errorf("restore snapshot: %w", err)
}
if err := c.ExecuteWithTimeout("cont", nil, 30*time.Second); err != nil {
return fmt.Errorf("resume VM execution after restore: %w", err)
}
return nil
}
// QuitVM sends QMP `quit` to the VM's QMP socket (best-effort cleanup for a
// failed incoming-resume QEMU process).
func QuitVM(ctx context.Context, vmDir string) error {
c, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return err
}
defer c.Close()
if err := c.ExecuteWithTimeout("quit", nil, 10*time.Second); err != nil && !isConnClosedErr(err) {
return err
}
return nil
}
func configureMappedRAM(c *Conn) error {
caps := map[string]any{
"capabilities": []map[string]any{
{"capability": "mapped-ram", "state": true},
{"capability": "multifd", "state": true},
},
}
if err := c.ExecuteWithTimeout("migrate-set-capabilities", caps, 15*time.Second); err != nil {
return fmt.Errorf("enable mapped-ram/multifd capabilities: %w", err)
}
params := map[string]any{
"multifd-channels": DefaultMultifdChannels,
}
if err := c.ExecuteWithTimeout("migrate-set-parameters", params, 15*time.Second); err != nil {
return fmt.Errorf("set multifd-channels: %w", err)
}
return nil
}
func fileChannels(vmstatePath string) []map[string]any {
return []map[string]any{
{
"channel-type": "main",
"addr": map[string]any{
"transport": "file",
"filename": filepath.Clean(vmstatePath),
"offset": 0,
},
},
}
}
func queryVMStatus(c *Conn) (vmStatusReply, error) {
raw, err := c.QueryWithTimeout("query-status", nil, 15*time.Second)
if err != nil {
return vmStatusReply{}, err
}
var st vmStatusReply
if err := json.Unmarshal(raw, &st); err != nil {
return vmStatusReply{}, fmt.Errorf("parse query-status: %w", err)
}
return st, nil
}
func tryResumePaused(c *Conn) {
st, err := queryVMStatus(c)
if err != nil || st.Running {
return
}
// Only resume when QEMU is still in ordinary paused state (never postmigrate).
if st.Status == "paused" {
_ = c.ExecuteWithTimeout("cont", nil, 10*time.Second)
}
}
func cancelIncompleteSuspend(ctx context.Context, c *Conn) bool {
cancelSent := false
for ctx.Err() == nil {
info, err := queryMigration(c, 2*time.Second)
if err != nil {
return false
}
switch info.Status {
case "failed", "cancelled":
tryResumePaused(c)
return true
case "completed", "none", "":
return false
}
if !cancelSent {
// Completion can race cancellation. Check the terminal status
// even if QEMU rejects the cancel request.
_ = c.ExecuteWithTimeout("migrate_cancel", nil, 2*time.Second)
cancelSent = true
}
sleep(ctx, migratePollInterval)
}
return false
}
func queryMigration(c *Conn, timeout time.Duration) (migrateInfo, error) {
var info migrateInfo
raw, err := c.QueryWithTimeout("query-migrate", nil, timeout)
if err != nil {
return info, err
}
if err := json.Unmarshal(raw, &info); err != nil {
return info, fmt.Errorf("parse query-migrate: %w", err)
}
return info, nil
}
func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgress)) error {
deadline := time.Now().Add(migrateTotalTimeout)
for {
if err := ctx.Err(); err != nil {
return err
}
if time.Now().After(deadline) {
return errors.New("timed out waiting for migration to finish")
}
info, err := queryMigration(c, migrateCmdTimeout)
if err != nil {
return err
}
prog := MigrateProgress{
Status: info.Status,
TotalTimeMs: info.TotalTimeMs,
}
if info.RAM != nil {
prog.Transferred = info.RAM.Transferred
prog.Remaining = info.RAM.Remaining
prog.Total = info.RAM.Total
}
if onProgress != nil {
onProgress(prog)
}
switch info.Status {
case "completed":
return nil
case "failed", "cancelled":
return &migrationFailure{status: info.Status, desc: strings.TrimSpace(info.ErrorDesc)}
}
sleep(ctx, migratePollInterval)
}
}
func dialMigrateConnWithRetry(ctx context.Context, network, addr string, timeout time.Duration) (*Conn, error) {
deadline := time.Now().Add(timeout)
var lastErr error
for {
c, err := Dial(ctx, network, addr)
if err == nil {
return c, nil
}
lastErr = err
if ctx.Err() != nil || time.Now().After(deadline) {
return nil, lastErr
}
sleep(ctx, 100*time.Millisecond)
}
}
func isConnClosedErr(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "connection closed") || strings.Contains(s, "eof") || strings.Contains(s, "wsarecv") || strings.Contains(s, "broken pipe")
}
+380
View File
@@ -0,0 +1,380 @@
package qmp
import (
"bufio"
"context"
"encoding/json"
"errors"
"net"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
)
func TestSuspendToFileRequiresSeal(t *testing.T) {
if err := SuspendToFile(context.Background(), t.TempDir(), "state", nil, nil); err == nil ||
!strings.Contains(err.Error(), "seal callback") {
t.Fatalf("suspend without a seal callback: %v", err)
}
}
func TestSuspendMigrationFailedBeforeSeal(t *testing.T) {
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
reply := map[string]any{}
switch req.Execute {
case "query-status":
reply["status"] = "paused"
reply["running"] = false
case "query-migrate":
reply["status"] = "failed"
reply["error-desc"] = "write failed"
case "quit":
t.Error("QEMU would exit after an incomplete save")
}
return map[string]any{"return": reply}, false
})
ctx := context.Background()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
err = suspendToFileConn(ctx, c, "state.tmp", nil, func(*Conn) error {
t.Error("an incomplete save reached seal")
return nil
})
if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "write failed") {
t.Fatalf("incomplete save = %v", err)
}
}
func TestCancelIncompleteSuspendRechecksTerminalStatus(t *testing.T) {
for _, terminal := range []string{"cancelled", "completed"} {
t.Run(terminal, func(t *testing.T) {
cancelled := false
addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "query-migrate":
status := "active"
if cancelled {
status = terminal
}
return map[string]any{"return": map[string]any{"status": status}}, false
case "migrate_cancel":
cancelled = true
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
}
return map[string]any{"return": map[string]any{}}, false
})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
want := terminal == "cancelled"
if got := cancelIncompleteSuspend(ctx, c); got != want {
t.Fatalf("safe discard = %t, want %t", got, want)
}
cmds := recorded()
if sawCont := len(cmds) > 0 && cmds[len(cmds)-1].Execute == "cont"; sawCont != want {
t.Fatalf("unexpected rollback commands: %v", cmds)
}
})
}
}
func TestAttachedFiles(t *testing.T) {
vmDir := t.TempDir()
disk := filepath.Join(vmDir, "disk.qcow2")
parent := filepath.Join(vmDir, "base.qcow2")
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
if req.Execute != "query-block" {
t.Errorf("unexpected command: %s", req.Execute)
}
return map[string]any{"return": []map[string]any{
{"device": "disk", "inserted": map[string]any{"image": map[string]any{
"filename": disk, "backing-image": map[string]any{"filename": parent},
}}},
{"device": "empty", "inserted": nil},
}}, false
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
got, err := c.AttachedFiles(vmDir)
if err != nil || !slices.Equal(got, []string{parent, disk}) {
t.Fatalf("attached files = %v, %v", got, err)
}
}
func TestAttachedFilesRejectsTemporaryOverlay(t *testing.T) {
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
return map[string]any{"return": []map[string]any{
{"device": "installer", "inserted": map[string]any{"image": map[string]any{
"filename": "json:temporary disk descriptor",
}}},
}}, false
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if _, err := c.AttachedFiles(t.TempDir()); err == nil || !strings.Contains(err.Error(), "installer uses a non-persistent") {
t.Fatalf("temporary installer overlay = %v", err)
}
}
func TestSuspendSealFailureDoesNotQuitSource(t *testing.T) {
addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "completed"}}, false
case "quit":
t.Error("QEMU would exit with an unsealed snapshot")
}
return map[string]any{"return": map[string]any{}}, false
})
ctx := context.Background()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
sealErr := errors.New("unable to publish state")
if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) || errors.Is(err, ErrIncompleteSuspend) {
t.Fatalf("suspend error = %v", err)
}
cmds := recorded()
if len(cmds) == 0 || cmds[len(cmds)-1].Execute != "query-migrate" {
t.Fatalf("unexpected commands: %+v", cmds)
}
}
type mockQMPReq struct {
Execute string `json:"execute"`
Arguments json.RawMessage `json:"arguments"`
}
func startMockQMP(t *testing.T, handle func(req mockQMPReq) (reply map[string]any, closeAfter bool)) (string, func() []mockQMPReq) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen mock QMP: %v", err)
}
t.Cleanup(func() { _ = ln.Close() })
var mu sync.Mutex
var recorded []mockQMPReq
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(nc net.Conn) {
defer nc.Close()
_, _ = nc.Write([]byte(`{"QMP":{"version":{"qemu":{"major":9,"minor":2,"micro":0}},"capabilities":[]}}` + "\n"))
sc := bufio.NewScanner(nc)
for sc.Scan() {
var req mockQMPReq
if err := json.Unmarshal(sc.Bytes(), &req); err != nil {
return
}
if req.Execute == "qmp_capabilities" {
_, _ = nc.Write([]byte(`{"return":{}}` + "\n"))
continue
}
mu.Lock()
recorded = append(recorded, req)
mu.Unlock()
reply, closeAfter := handle(req)
if reply != nil {
b, _ := json.Marshal(reply)
_, _ = nc.Write(append(b, '\n'))
}
if closeAfter {
return
}
}
}(conn)
}
}()
return ln.Addr().String(), func() []mockQMPReq {
mu.Lock()
defer mu.Unlock()
return append([]mockQMPReq(nil), recorded...)
}
}
func TestSuspendToFileHappyPath(t *testing.T) {
polls := 0
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate-set-parameters", "migrate":
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "query-migrate":
polls++
if polls == 1 {
return map[string]any{"return": map[string]any{
"status": "active",
"ram": map[string]any{"transferred": 1024, "remaining": 1024, "total": 2048},
}}, false
}
return map[string]any{"return": map[string]any{
"status": "completed",
"total-time": 4500,
"ram": map[string]any{"transferred": 2048, "remaining": 0, "total": 2048},
}}, false
case "quit":
return map[string]any{"return": map[string]any{}}, true
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
var progress []MigrateProgress
if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) {
progress = append(progress, p)
}, nil); err != nil {
t.Fatalf("suspendToFileConn: %v", err)
}
if len(progress) != 2 || progress[1].Status != "completed" {
t.Fatalf("unexpected progress: %+v", progress)
}
got := cmds()
var names []string
for _, r := range got {
names = append(names, r.Execute)
}
want := "stop,query-status,migrate-set-capabilities,migrate-set-parameters,migrate,query-migrate,query-migrate,quit"
if strings.Join(names, ",") != want {
t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want)
}
}
func TestSuspendToFileFailureResumesPausedVM(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate-set-parameters", "cont":
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "migrate":
return map[string]any{"error": map[string]any{"class": "GenericError", "desc": "disk full"}}, false
default:
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil)
if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "disk full") {
t.Fatalf("expected disk full error, got %v", err)
}
var sawCont bool
for _, r := range cmds() {
if r.Execute == "cont" {
sawCont = true
}
if r.Execute == "quit" {
t.Fatal("must not quit QEMU when migrate fails")
}
}
if !sawCont {
t.Fatal("expected cont rollback when migrate fails while paused")
}
}
func TestResumeFromFileHappyPath(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming", "cont":
return map[string]any{"return": map[string]any{}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "completed", "total-time": 1900}}, false
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
if err := resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil); err != nil {
t.Fatalf("resumeFromFileConn: %v", err)
}
got := cmds()
var names []string
var sawExitOnErrorFalse bool
for _, r := range got {
names = append(names, r.Execute)
if r.Execute == "migrate-incoming" && strings.Contains(string(r.Arguments), `"exit-on-error":false`) {
sawExitOnErrorFalse = true
}
}
want := "migrate-set-capabilities,migrate-set-parameters,migrate-incoming,query-migrate,cont"
if strings.Join(names, ",") != want {
t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want)
}
if !sawExitOnErrorFalse {
t.Fatal("expected migrate-incoming to pass exit-on-error:false")
}
}
func TestResumeFromFileFailedDoesNotCont(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming":
return map[string]any{"return": map[string]any{}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "failed", "error-desc": "corrupt RVGSNAP1 snapshot"}}, false
default:
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
err = resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil)
if err == nil || !strings.Contains(err.Error(), "corrupt RVGSNAP1 snapshot") {
t.Fatalf("expected corrupt snapshot error, got %v", err)
}
for _, r := range cmds() {
if r.Execute == "cont" {
t.Fatal("must not issue cont when restore failed")
}
}
}
+24 -3
View File
@@ -89,9 +89,7 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string {
}
cleaned = append(cleaned, tok)
}
escaped := strings.ReplaceAll(sockPath, ",", ",,")
escaped = strings.ReplaceAll(escaped, `\`, `/`)
qmpVal := fmt.Sprintf("unix:%s,server=on,wait=off", escaped)
qmpVal := win10RebootUnixTarget(sockPath)
if strings.ContainsAny(qmpVal, " \t") {
qmpVal = `"` + strings.ReplaceAll(qmpVal, `"`, `\"`) + `"`
}
@@ -99,6 +97,29 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string {
return strings.Join(cleaned, " ")
}
func win10RebootUnixTarget(sockPath string) string {
escaped := strings.ReplaceAll(sockPath, ",", ",,")
escaped = strings.ReplaceAll(escaped, "\\", "/")
return "unix:" + escaped + ",server=on,wait=off"
}
// HasWin10RebootUnixArgs checks for the private socket Reims-Go configured,
// without accepting other monitors declared in extra-args.
func HasWin10RebootUnixArgs(extraArgs, sockPath string) bool {
tokens := splitShellTokens(extraArgs)
want := win10RebootUnixTarget(sockPath)
var noReboot, socket bool
for i, token := range tokens {
if token == "-no-reboot" {
noReboot = true
}
if token == "-qmp" && i+1 < len(tokens) && strings.Trim(tokens[i+1], "'\"") == want {
socket = true
}
}
return noReboot && socket
}
func isManagedQMPTarget(arg string) bool {
arg = strings.Trim(arg, "'\"")
if !strings.HasSuffix(arg, ",server=on,wait=off") {
+17
View File
@@ -10,6 +10,23 @@ import (
"time"
)
func TestHasWin10RebootUnixArgs(t *testing.T) {
sock := "D:\\VM data\\group,1\\reims-go-reboot.sock"
args := MergeWin10RebootUnixArgs("-machine q35", sock)
if !HasWin10RebootUnixArgs(args, sock) {
t.Fatal("saved socket with escaped comma and quoted path was not recognized")
}
if HasWin10RebootUnixArgs(strings.ReplaceAll(args, "-no-reboot", ""), sock) {
t.Fatal("recognized a monitor without the cold-reboot flag")
}
if HasWin10RebootUnixArgs(args, "D:/other/reims-go-reboot.sock") {
t.Fatal("recognized a different monitor")
}
if HasWin10RebootUnixArgs("-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off", sock) {
t.Fatal("recognized a legacy TCP monitor")
}
}
func TestMergeWin10RebootUnixArgs(t *testing.T) {
got := MergeWin10RebootUnixArgs("", `D:\Data\reims-go\vms\m0\reims-go-reboot.sock`)
want := "-no-reboot -qmp unix:D:/Data/reims-go/vms/m0/reims-go-reboot.sock,server=on,wait=off"
+10
View File
@@ -152,6 +152,7 @@ func (m Manifest) EffectiveCapabilities() []string {
for _, c := range m.Capabilities {
add(c)
}
var hasWin32MappedRAM, hasIntelWHPXSuspend, hasVGPUSnapshotReplay bool
for _, p := range m.Patches {
low := strings.ToLower(p.Name)
switch {
@@ -169,8 +170,17 @@ func (m Manifest) EffectiveCapabilities() []string {
}
case strings.Contains(low, "display-fixed-mode"):
add("display-fixed-mode")
case strings.Contains(low, "win32-mapped-ram-io"):
hasWin32MappedRAM = true
case strings.Contains(low, "intel-whpx-suspend"):
hasIntelWHPXSuspend = true
case strings.Contains(low, "reims-vgpu-snapshot-replay"):
hasVGPUSnapshotReplay = true
}
}
if hasWin32MappedRAM && hasIntelWHPXSuspend && hasVGPUSnapshotReplay {
add("vm-suspend")
}
return out
}
+35
View File
@@ -85,6 +85,41 @@ func TestKindRegistryAndCapabilities(t *testing.T) {
t.Fatalf("%s: HasCapability(win32-unicode-input) = %v, want %v", tc.name, got, tc.want)
}
}
// vm-suspend requires all three runtime pieces (Win32 mapped-ram I/O, Intel WHPX suspend,
// and vGPU snapshot replay) unless explicitly declared in Capabilities.
for _, tc := range []struct {
name string
m Manifest
want bool
}{
{
name: "partial-suspend-patches",
m: Manifest{Patches: []Patch{
{Name: "qemu-win32-mapped-ram-io.patch"},
{Name: "qemu-intel-whpx-suspend.patch"},
}},
want: false,
},
{
name: "all-suspend-patches",
m: Manifest{Patches: []Patch{
{Name: "qemu-win32-mapped-ram-io.patch"},
{Name: "qemu-intel-whpx-suspend.patch"},
{Name: "reims-vgpu-snapshot-replay.patch"},
}},
want: true,
},
{
name: "explicit-vm-suspend-capability",
m: Manifest{Capabilities: []string{"vm-suspend"}},
want: true,
},
} {
if got := tc.m.HasCapability("vm-suspend"); got != tc.want {
t.Fatalf("%s: HasCapability(vm-suspend) = %v, want %v", tc.name, got, tc.want)
}
}
}
func TestMultiKindCoexistenceAndCompatibility(t *testing.T) {
+111 -29
View File
@@ -25,9 +25,10 @@ func (v VMItem) title() string {
// Snapshot holds the live state read each time the user opens the tray menu.
type Snapshot struct {
Locale i18n.Locale
LocaleZh bool // legacy fallback when Locale is empty
VMs []VMItem
Locale i18n.Locale
LocaleZh bool // legacy fallback when Locale is empty
CanSuspend bool
VMs []VMItem
}
// Action is a per-VM command picked from the tray menu.
@@ -43,6 +44,9 @@ const (
ActSharedFolder
ActOpenInApp
ActToggleFullscreen
ActSuspend
ActResume
ActDiscardSuspend
)
// Callbacks wires tray actions back into the Wails application. Each runs
@@ -72,6 +76,7 @@ const (
dotNone dotKind = iota
dotRunning
dotStopped
dotSuspended
dotBusy
dotBroken
)
@@ -89,12 +94,17 @@ type menuEntry struct {
}
type texts struct {
show, newVM, quit string
start, stop, forceStop, restart, showWindow, shot string
shared, openInApp string
running, stopped, starting, stopping, broken, unknown string
show, newVM, quit string
start, stop, forceStop, restart, showWindow, shot string
suspend, resume, discardSuspend string
shared, openInApp string
running, stopped, suspended string
starting, stopping, suspending, resuming string
broken, unknown string
toggleFullscreen string
resumeUnavailable string
}
func menuTexts(snap Snapshot) texts {
@@ -107,25 +117,33 @@ func menuTexts(snap Snapshot) texts {
}
}
return texts{
show: i18n.T(loc, "tray.menu.show"),
newVM: i18n.T(loc, "tray.menu.new_vm"),
quit: i18n.T(loc, "tray.menu.quit"),
start: i18n.T(loc, "tray.menu.start"),
stop: i18n.T(loc, "tray.menu.stop"),
forceStop: i18n.T(loc, "tray.menu.force_stop"),
restart: i18n.T(loc, "tray.menu.restart"),
showWindow: i18n.T(loc, "tray.menu.show_window"),
shot: i18n.T(loc, "tray.menu.screenshot"),
shared: i18n.T(loc, "tray.menu.shared_folder"),
openInApp: i18n.T(loc, "tray.menu.open_in_app"),
running: i18n.T(loc, "tray.state.running"),
stopped: i18n.T(loc, "tray.state.stopped"),
starting: i18n.T(loc, "tray.state.starting"),
stopping: i18n.T(loc, "tray.state.stopping"),
broken: i18n.T(loc, "tray.state.broken"),
unknown: i18n.T(loc, "tray.state.unknown"),
show: i18n.T(loc, "tray.menu.show"),
newVM: i18n.T(loc, "tray.menu.new_vm"),
quit: i18n.T(loc, "tray.menu.quit"),
start: i18n.T(loc, "tray.menu.start"),
stop: i18n.T(loc, "tray.menu.stop"),
forceStop: i18n.T(loc, "tray.menu.force_stop"),
restart: i18n.T(loc, "tray.menu.restart"),
suspend: i18n.T(loc, "tray.menu.suspend"),
resume: i18n.T(loc, "tray.menu.resume"),
discardSuspend: i18n.T(loc, "tray.menu.discard_suspend"),
showWindow: i18n.T(loc, "tray.menu.show_window"),
shot: i18n.T(loc, "tray.menu.screenshot"),
shared: i18n.T(loc, "tray.menu.shared_folder"),
openInApp: i18n.T(loc, "tray.menu.open_in_app"),
running: i18n.T(loc, "tray.state.running"),
stopped: i18n.T(loc, "tray.state.stopped"),
suspended: i18n.T(loc, "tray.state.suspended"),
starting: i18n.T(loc, "tray.state.starting"),
stopping: i18n.T(loc, "tray.state.stopping"),
suspending: i18n.T(loc, "tray.state.suspending"),
resuming: i18n.T(loc, "tray.state.resuming"),
broken: i18n.T(loc, "tray.state.broken"),
unknown: i18n.T(loc, "tray.state.unknown"),
toggleFullscreen: i18n.T(loc, "tray.menu.toggle_fullscreen"),
resumeUnavailable: i18n.T(loc, "tray.menu.resume_unavailable"),
}
}
@@ -138,7 +156,7 @@ func decodeVMCmd(id int) (int, Action, bool) {
}
off := id - cmdVMBase
act := Action(off % vmSlot)
if act < ActStart || act > ActToggleFullscreen {
if act < ActStart || act > ActDiscardSuspend {
return 0, 0, false
}
return off / vmSlot, act, true
@@ -174,13 +192,38 @@ func buildMenu(snap Snapshot) []menuEntry {
sub = []menuEntry{
show, cmd(ActToggleFullscreen, t.toggleFullscreen),
cmd(ActScreenshot, t.shot), cmd(ActSharedFolder, t.shared), sep,
}
if snap.CanSuspend {
sub = append(sub, cmd(ActSuspend, t.suspend))
}
sub = append(sub,
cmd(ActRestart, t.restart), cmd(ActStop, t.stop), cmd(ActForceStop, t.forceStop), sep,
cmd(ActOpenInApp, t.openInApp),
)
case "suspended":
dot, state = dotSuspended, t.suspended
resume := cmd(ActResume, t.resume)
resume.Default = snap.CanSuspend
if !snap.CanSuspend {
resume.Label = t.resumeUnavailable
resume.Disabled = true
}
case "starting", "stopping":
dot, state = dotBusy, t.starting
if vm.State == "stopping" {
sub = []menuEntry{
resume, cmd(ActDiscardSuspend, t.discardSuspend), sep,
cmd(ActSharedFolder, t.shared), sep,
cmd(ActOpenInApp, t.openInApp),
}
case "starting", "stopping", "suspending", "resuming":
dot = dotBusy
switch vm.State {
case "stopping":
state = t.stopping
case "suspending":
state = t.suspending
case "resuming":
state = t.resuming
default:
state = t.starting
}
sub = []menuEntry{cmd(ActForceStop, t.forceStop), sep, cmd(ActOpenInApp, t.openInApp)}
case "broken":
@@ -209,6 +252,8 @@ func dotPixels(size int, kind dotKind) []byte {
switch kind {
case dotRunning:
r, g, b = 0x30, 0xD1, 0x58
case dotSuspended:
r, g, b = 0xFF, 0x9F, 0x0A
case dotBusy:
r, g, b = 0xFF, 0x9F, 0x0A
case dotBroken:
@@ -219,12 +264,49 @@ func dotPixels(size int, kind dotKind) []byte {
return px
}
c := float64(size) / 2
const ss = 4 // 4×4 supersampling for smooth edges
if kind == dotSuspended {
halfH := float64(size) * 0.28
barW := maxf(1.8, float64(size)*0.15)
gap := maxf(1.2, float64(size)*0.12)
for y := 0; y < size; y++ {
for x := 0; x < size; x++ {
hits := 0
for sy := 0; sy < ss; sy++ {
for sx := 0; sx < ss; sx++ {
dx := float64(x) + (float64(sx)+0.5)/ss - c
dy := float64(y) + (float64(sy)+0.5)/ss - c
adx := dx
if adx < 0 {
adx = -adx
}
ady := dy
if ady < 0 {
ady = -ady
}
if ady <= halfH && adx >= gap/2 && adx <= gap/2+barW {
hits++
}
}
}
if hits == 0 {
continue
}
a := hits * 255 / (ss * ss)
off := (y*size + x) * 4
px[off+0] = uint8(int(b) * a / 255)
px[off+1] = uint8(int(g) * a / 255)
px[off+2] = uint8(int(r) * a / 255)
px[off+3] = uint8(a)
}
}
return px
}
outer := float64(size) * 0.28 // dot diameter ≈ 56% of the check-mark cell
inner := 0.0
if kind == dotStopped {
inner = outer - maxf(1.4, float64(size)*0.09)
}
const ss = 4 // 4×4 supersampling for smooth edges
for y := 0; y < size; y++ {
for x := 0; x < size; x++ {
hits := 0
+42 -6
View File
@@ -18,10 +18,11 @@ func findEntry(entries []menuEntry, label string) *menuEntry {
}
func TestBuildMenuPerState(t *testing.T) {
menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{
menu := buildMenu(Snapshot{LocaleZh: true, CanSuspend: true, VMs: []VMItem{
{Name: "macos-tahoe", Label: "日常", State: "running"},
{Name: "macos-dev", State: "stopped"},
{Name: "macos-busy", State: "starting"},
{Name: "macos-sleep", State: "suspended"},
}})
if !menu[0].Default || menu[0].ID != cmdShow {
t.Fatalf("first item should be the default Show, got %+v", menu[0])
@@ -40,6 +41,15 @@ func TestBuildMenuPerState(t *testing.T) {
if len(run.Sub) < 2 || run.Sub[1].ID != vmCmd(0, ActToggleFullscreen) || run.Sub[1].Label != "切换全屏" || run.Sub[1].Default {
t.Fatalf("running VM should offer Toggle Fullscreen after Show Window: %+v", run.Sub)
}
var hasSuspend bool
for _, e := range run.Sub {
if e.ID == vmCmd(0, ActSuspend) {
hasSuspend = true
}
}
if !hasSuspend {
t.Fatalf("running VM with CanSuspend should offer Suspend: %+v", run.Sub)
}
stop := findEntry(menu, "macos-dev\t已停止")
if stop == nil || stop.Dot != dotStopped || stop.Sub[0].ID != vmCmd(1, ActStart) || !stop.Sub[0].Default {
@@ -55,18 +65,38 @@ func TestBuildMenuPerState(t *testing.T) {
if busy == nil || busy.Dot != dotBusy || busy.Sub[0].ID != vmCmd(2, ActForceStop) {
t.Fatalf("starting VM should only offer force stop first: %+v", busy)
}
susp := findEntry(menu, "macos-sleep\t已挂起")
if susp == nil || susp.Dot != dotSuspended || susp.Sub[0].ID != vmCmd(3, ActResume) || !susp.Sub[0].Default {
t.Fatalf("suspended VM should default to Resume: %+v", susp)
}
}
func TestSuspendedVMWithoutCompatibleRuntime(t *testing.T) {
menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{{Name: "macos-sleep", State: "suspended"}}})
vm := findEntry(menu, "macos-sleep\t已挂起")
if vm == nil {
t.Fatal("suspended VM is missing from the tray menu")
}
resume := vm.Sub[0]
if resume.ID != vmCmd(0, ActResume) || !resume.Disabled || resume.Default || resume.Label != "恢复(当前内核不支持挂起)" {
t.Fatalf("resume should be disabled and explain why: %+v", resume)
}
if discard := vm.Sub[1]; discard.ID != vmCmd(0, ActDiscardSuspend) || discard.Disabled {
t.Fatalf("discard should remain available: %+v", discard)
}
}
func TestDecodeVMCmdRoundTrip(t *testing.T) {
for i := 0; i < maxTrayVMs; i++ {
for act := ActStart; act <= ActToggleFullscreen; act++ {
for act := ActStart; act <= ActDiscardSuspend; act++ {
gi, ga, ok := decodeVMCmd(vmCmd(i, act))
if !ok || gi != i || ga != act {
t.Fatalf("vmCmd(%d,%d) decoded to (%d,%d,%v)", i, act, gi, ga, ok)
}
}
}
for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActToggleFullscreen+1), cmdVMBase + maxTrayVMs*vmSlot} {
for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActDiscardSuspend+1), cmdVMBase + maxTrayVMs*vmSlot} {
if _, _, ok := decodeVMCmd(id); ok {
t.Fatalf("id %d should not decode as a VM command", id)
}
@@ -84,9 +114,15 @@ func TestDotPixels(t *testing.T) {
if alpha(ring, size/2, size/2) != 0 {
t.Fatal("stopped dot should be a ring with a clear centre")
}
for i := 0; i < len(run); i += 4 {
if run[i] > run[i+3] || run[i+1] > run[i+3] || run[i+2] > run[i+3] {
t.Fatal("pixels must be premultiplied (colour ≤ alpha)")
paused := dotPixels(size, dotSuspended)
if alpha(paused, 0, 0) != 0 || alpha(paused, size/2-2, size/2) == 0 || alpha(paused, size/2+2, size/2) == 0 {
t.Fatal("suspended mark should draw two visible vertical pause bars")
}
for _, buf := range [][]byte{run, paused} {
for i := 0; i < len(buf); i += 4 {
if buf[i] > buf[i+3] || buf[i+1] > buf[i+3] || buf[i+2] > buf[i+3] {
t.Fatal("pixels must be premultiplied (colour ≤ alpha)")
}
}
}
}
+231
View File
@@ -0,0 +1,231 @@
package vmstart
import (
"context"
"errors"
"fmt"
"io"
"os"
"slices"
"strings"
"time"
"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/qmp"
)
// LockVM reads the VM again after locking its directory so that another
// process cannot change the state between inspection and operation.
func LockVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) {
d, err := c.Show(ctx, name)
if err != nil {
return d, nil, err
}
release, err := reims.LockVMOperation(d.Directory)
if errors.Is(err, reims.ErrVMOperationBusy) {
return d, nil, i18n.NewCodedError(c.Locale, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
}
if err != nil {
return d, nil, err
}
cur, err := c.Show(ctx, name)
if err == nil && cur.Directory != d.Directory {
err = fmt.Errorf("VM directory changed while waiting to operate on %s", name)
}
if err != nil {
release()
return cur, nil, err
}
return cur, release, nil
}
// LockMutableVM protects configuration and media updates and rejects updates
// while a published suspend state depends on the current configuration.
func LockMutableVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) {
d, release, err := LockVM(ctx, c, name)
if err != nil {
return d, nil, err
}
if reims.HasSuspendState(d.Directory) {
release()
return d, nil, i18n.NewCodedError(c.Locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
return d, release, nil
}
// LockVMForStop serializes graceful shutdown. Emergency shutdown is also
// the escape path for a stalled operation that already holds the lock.
func LockVMForStop(ctx context.Context, c *reims.Client, name string, force bool) (func(), error) {
if force {
return func() {}, nil
}
_, release, err := LockVM(ctx, c, name)
return release, err
}
func (p *Prep) checkSuspendRuntime(d reims.VMDetail) error {
kind := strings.ToLower(d.Kind)
if !p.Runtime.Manifest.HasCapability("vm-suspend") || strings.Contains(kind, "arm64") || strings.Contains(kind, "aarch64") {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil)
}
return nil
}
// SuspendSnapshot saves and publishes a VM snapshot while the caller holds
// LockVM. The source exits only after the snapshot and metadata are durable.
func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress func(qmp.MigrateProgress)) (reims.SuspendInfo, error) {
var info reims.SuspendInfo
if err := p.checkSuspendRuntime(d); err != nil {
return info, err
}
pid, err := vmPID(ctx, p.Client, d.Name)
if err != nil {
return info, err
}
if pid == 0 {
return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": d.Name}, nil)
}
if memGB, ok := reims.ParseSizeGB(d.Memory); ok {
if avail := host.Inspect(d.Directory).FreeDiskGB; avail > 0 && avail < memGB+1 {
return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{
"need": fmt.Sprintf("%.1f", memGB+1), "avail": fmt.Sprintf("%.1f", avail),
}, nil)
}
}
state := reims.SuspendStatePath(d.Directory)
tmp := state + ".tmp"
meta := reims.SuspendMetaPath(d.Directory)
for _, path := range []string{state, tmp, meta, meta + ".tmp"} {
if _, err := os.Lstat(path); !os.IsNotExist(err) {
if err != nil {
return info, err
}
return info, fmt.Errorf("previous suspend data still exists: %s", path)
}
}
err = qmp.SuspendToFile(ctx, d.Directory, tmp, progress, func(paths []string) error {
var err error
info, err = reims.SealSuspend(d, p.Runtime, paths)
return err
})
if err != nil {
return info, cleanupSuspendAttempt(tmp, err)
}
waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
defer cancel()
if err := host.WaitProcessExit(waitCtx, uint32(pid), "qemu-system-x86_64.exe"); err != nil {
if !errors.Is(err, errors.ErrUnsupported) {
return info, err
}
for {
cur, err := vmPID(waitCtx, p.Client, d.Name)
if err != nil || cur == 0 {
return info, err
}
select {
case <-waitCtx.Done():
return info, waitCtx.Err()
case <-time.After(100 * time.Millisecond):
}
}
}
return info, nil
}
func cleanupSuspendAttempt(tmp string, err error) error {
if errors.Is(err, qmp.ErrIncompleteSuspend) {
if removeErr := os.Remove(tmp); removeErr != nil && !os.IsNotExist(removeErr) {
return errors.Join(err, fmt.Errorf("remove incomplete snapshot: %w", removeErr))
}
}
return err
}
// ResumeSnapshot owns the incoming launch and snapshot consumption while
// the caller holds LockVM. The original configuration must be restored
// before guest execution can continue.
func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, rep host.Report, out, stderr io.Writer) error {
if err := p.checkSuspendRuntime(d); err != nil {
return err
}
if d.State == "running" {
return fmt.Errorf("%s", i18n.T(p.Client.Locale, "vm.already_running", d.Name))
}
if !reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": d.Name}, nil)
}
state, paths, err := reims.ValidateSuspendFiles(d, p.Runtime)
if err != nil {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{"diffs": err.Error()}, err)
}
if err := p.CheckWHPX(rep); err != nil {
return err
}
if err := p.CheckMemory(d.Memory, rep); err != nil {
return err
}
c := p.Client
incoming := reims.MergeIncomingDeferArgs(d.ExtraArgs)
if err := c.Set(ctx, reims.SetOpts{Name: d.Name, ExtraArgs: &incoming}, out, stderr); err != nil {
return err
}
startErr := c.Start(ctx, d.Name, out, stderr)
restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
restoreErr := c.Set(restoreCtx, reims.SetOpts{Name: d.Name, ExtraArgs: &d.ExtraArgs}, out, stderr)
cancel()
if restoreErr != nil {
restoreErr = fmt.Errorf("restore original VM start arguments: %w", restoreErr)
}
if err := errors.Join(startErr, restoreErr); err != nil {
p.stopFailedIncoming(ctx, d)
return err
}
err = qmp.ResumeFromFile(ctx, d.Directory, state, nil, func(conn *qmp.Conn) error {
attached, err := conn.AttachedFiles(d.Directory)
if err != nil {
return err
}
if !slices.Equal(paths, attached) {
return fmt.Errorf("incoming QEMU opened different media from the saved VM")
}
return nil
})
if err != nil {
p.stopFailedIncoming(ctx, d)
return err
}
if err := reims.RemoveSuspendState(d.Directory); err != nil {
p.log("Warning: could not remove consumed suspend files: " + err.Error())
}
return nil
}
func (p *Prep) stopFailedIncoming(ctx context.Context, d reims.VMDetail) {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
defer cancel()
if err := qmp.QuitVM(cleanup, d.Directory); err != nil {
_ = p.Client.StopForce(cleanup, d.Name, io.Discard, io.Discard)
}
}
func DiscardSnapshot(loc i18n.Locale, d reims.VMDetail) error {
if d.State == "running" {
return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": d.Name}, nil)
}
return reims.RemoveSuspendState(d.Directory)
}
func vmPID(ctx context.Context, c *reims.Client, name string) (int, error) {
vms, err := c.List(ctx)
if err != nil {
return 0, err
}
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil {
return *vm.PID, nil
}
}
return 0, nil
}
+48
View File
@@ -0,0 +1,48 @@
package vmstart
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/qmp"
)
func TestForceStopDoesNotWaitForVMInspectionOrLock(t *testing.T) {
// A forced stop must not ask reims-ctl to show the VM before it can
// invoke stop --force. A stalled owner may also be holding its lock.
release, err := LockVMForStop(context.Background(), nil, "stalled", true)
if err != nil {
t.Fatal(err)
}
release()
}
func TestCleanupSuspendAttempt(t *testing.T) {
for _, tt := range []struct {
name string
err error
keep bool
}{
{"migration failed", fmt.Errorf("%w: disk full", qmp.ErrIncompleteSuspend), false},
{"seal failed", errors.New("could not publish suspend metadata"), true},
{"unknown outcome", errors.New("connection closed"), true},
} {
t.Run(tt.name, func(t *testing.T) {
tmp := filepath.Join(t.TempDir(), "suspend.vmstate.tmp")
if err := os.WriteFile(tmp, []byte("snapshot data"), 0o600); err != nil {
t.Fatal(err)
}
if err := cleanupSuspendAttempt(tmp, tt.err); !errors.Is(err, tt.err) {
t.Fatalf("cleanup lost the save error: %v", err)
}
_, err := os.Stat(tmp)
if tt.keep && err != nil || !tt.keep && !os.IsNotExist(err) {
t.Fatalf("stat after cleanup = %v, want keep=%t", err, tt.keep)
}
})
}
}
+5
View File
@@ -147,6 +147,11 @@ func waitForCommitMemory(
// 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)
+73
View File
@@ -407,6 +407,10 @@
"tray.menu.new_vm": "&New Virtual Machine…",
"tray.menu.quit": "&Quit Reims-Go",
"tray.menu.start": "&Start",
"tray.menu.suspend": "Sus&pend",
"tray.menu.resume": "Res&ume",
"tray.menu.resume_unavailable": "Resume (runtime lacks suspend support)",
"tray.menu.discard_suspend": "Discard Saved Stat&e…",
"tray.menu.stop": "Shut &Down",
"tray.menu.force_stop": "&Force Shut Down",
"tray.menu.restart": "&Restart",
@@ -417,8 +421,11 @@
"tray.menu.open_in_app": "Show in &Reims-Go",
"tray.state.running": "Running",
"tray.state.stopped": "Stopped",
"tray.state.suspended": "Suspended",
"tray.state.starting": "Starting…",
"tray.state.stopping": "Shutting down…",
"tray.state.suspending": "Suspending…",
"tray.state.resuming": "Resuming…",
"tray.state.broken": "Broken",
"tray.state.unknown": "Unknown",
"tray.notify.start_fail": {
@@ -427,6 +434,24 @@
"name"
]
},
"tray.notify.suspend_fail": {
"message": "Couldn't suspend {name}",
"$params": [
"name"
]
},
"tray.notify.resume_fail": {
"message": "Couldn't resume {name}",
"$params": [
"name"
]
},
"tray.notify.discard_suspend_fail": {
"message": "Couldn't discard saved state for {name}",
"$params": [
"name"
]
},
"tray.notify.stop_fail": {
"message": "Couldn't shut down {name}",
"$params": [
@@ -820,6 +845,9 @@
"cli.usage.cmd_vm_compact": " vm compact <name> Compact stopped .qcow2 disk to reclaim unused space",
"cli.usage.cmd_vm_start": " vm start <name> Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process",
"cli.usage.cmd_vm_stop": " vm stop|eject <name> Stop / eject installer",
"cli.usage.cmd_vm_suspend": " vm suspend <name> Suspend a running VM to disk for fast resume across restarts",
"cli.usage.cmd_vm_resume": " vm resume <name> Resume a suspended VM from disk",
"cli.usage.cmd_vm_discard_suspend": " vm discard-suspend <name> Discard a saved suspend state and return the VM to powered off",
"cli.usage.cmd_vm_type": " vm type <name> [text] Type text into a running VM as US-keyboard keys (stdin if no text)",
"cli.usage.cmd_inst_list": " installer list List offline macOS installers Apple offers (needs network)",
"cli.usage.cmd_inst_dl": " installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)",
@@ -954,6 +982,51 @@
},
"core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically",
"validate.invalid_guest_lang": "Invalid guest language code (expected format like zh-Hans:0 or en-US:0)",
"validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings",
"err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support",
"err.suspend.busy": {
"message": "VM “{name}” is busy transitioning; try again in a moment",
"$params": [
"name"
]
},
"err.suspend.not_running": {
"message": "VM “{name}” is not running and cannot be suspended",
"$params": [
"name"
]
},
"err.suspend.disk_space": {
"message": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)",
"$params": [
"need",
"avail"
]
},
"err.suspend.not_found": {
"message": "No complete suspend state found for “{name}”",
"$params": [
"name"
]
},
"err.suspend.incompatible": {
"message": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state",
"$params": [
"diffs"
]
},
"err.suspend.discard_running": {
"message": "VM “{name}” is currently running; suspend state cannot be discarded",
"$params": [
"name"
]
},
"err.suspend.action_blocked": {
"message": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this",
"$params": [
"name"
]
},
"err.dataroot.busy_vms": "Stop all running virtual machines before switching the data folder",
"err.dataroot.busy_tasks": "Wait for active download or creation tasks to finish before switching the data folder",
"font.script.zh_hant": "Traditional Chinese (繁體中文)",
+21
View File
@@ -43,9 +43,30 @@
"fieldVMName": "VM name",
"state_running": "Running",
"state_stopped": "Stopped",
"state_suspended": "Suspended",
"state_starting": "Starting",
"state_stopping": "Stopping",
"state_suspending": "Suspending",
"state_resuming": "Resuming",
"state_broken": "Error",
"suspend": "Suspend",
"resume": "Resume",
"resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM",
"discardSuspend": "Discard saved state",
"discardSuspendTitle": "Discard saved state for “{name}”?",
"discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.",
"discardSuspendConfirm": "Discard & Power Off",
"suspendedNoticeTitle": "Saved state ready",
"suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.",
"suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.",
"suspendedSettingsHint": "Resume or discard saved state before changing settings",
"suspendedGuestToolsHint": "Resume or discard saved state to make changes",
"toastSuspended": "{name} suspended",
"toastResumed": "{name} resumed",
"toastDiscardSuspend": "Discarded saved state for {name}",
"failSuspend": "Couldn’t suspend",
"failResume": "Couldn’t resume",
"failDiscardSuspend": "Couldn’t discard saved state",
"pendingTitle": "Applies on next start",
"restartToApply": "Restart to apply",
"guideTitle": "Recovery mode",
+73
View File
@@ -407,6 +407,10 @@
"tray.menu.new_vm": "新建虚拟机(&N)…",
"tray.menu.quit": "退出 Reims-Go(&Q)",
"tray.menu.start": "启动(&S)",
"tray.menu.suspend": "挂起(&P)",
"tray.menu.resume": "恢复(&U)",
"tray.menu.resume_unavailable": "恢复(当前内核不支持挂起)",
"tray.menu.discard_suspend": "放弃挂起状态…(&X)",
"tray.menu.stop": "关机(&D)",
"tray.menu.force_stop": "强制关机(&F)",
"tray.menu.restart": "重启(&R)",
@@ -417,8 +421,11 @@
"tray.menu.open_in_app": "在 Reims-Go 中查看(&V)",
"tray.state.running": "运行中",
"tray.state.stopped": "已停止",
"tray.state.suspended": "已挂起",
"tray.state.starting": "启动中…",
"tray.state.stopping": "正在关机…",
"tray.state.suspending": "正在挂起…",
"tray.state.resuming": "正在恢复…",
"tray.state.broken": "配置损坏",
"tray.state.unknown": "未知",
"tray.notify.start_fail": {
@@ -427,6 +434,24 @@
"name"
]
},
"tray.notify.suspend_fail": {
"message": "无法挂起 {name}",
"$params": [
"name"
]
},
"tray.notify.resume_fail": {
"message": "无法恢复 {name}",
"$params": [
"name"
]
},
"tray.notify.discard_suspend_fail": {
"message": "无法放弃 {name} 的挂起状态",
"$params": [
"name"
]
},
"tray.notify.stop_fail": {
"message": "无法关机 {name}",
"$params": [
@@ -820,6 +845,9 @@
"cli.usage.cmd_vm_compact": " vm compact <name> 停机回收 .qcow2 磁盘未用空间",
"cli.usage.cmd_vm_start": " vm start <name> 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动",
"cli.usage.cmd_vm_stop": " vm stop|eject <name> 停止 / 弹出安装盘",
"cli.usage.cmd_vm_suspend": " vm suspend <name> 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)",
"cli.usage.cmd_vm_resume": " vm resume <name> 从磁盘挂起状态恢复虚拟机",
"cli.usage.cmd_vm_discard_suspend": " vm discard-suspend <name> 放弃已保存的挂起状态并回到关机状态",
"cli.usage.cmd_vm_type": " vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)",
"cli.usage.cmd_inst_list": " installer list 列出 Apple 提供的离线安装包版本(需联网)",
"cli.usage.cmd_inst_dl": " installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)",
@@ -954,6 +982,51 @@
},
"core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数",
"validate.invalid_guest_lang": "客户机系统语言标识格式无效(如 zh-Hans:0、en-US:0)",
"validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置",
"err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本",
"err.suspend.busy": {
"message": "虚拟机「{name}」正在执行状态切换,请稍后再试",
"$params": [
"name"
]
},
"err.suspend.not_running": {
"message": "虚拟机「{name}」未在运行,无法挂起",
"$params": [
"name"
]
},
"err.suspend.disk_space": {
"message": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)",
"$params": [
"need",
"avail"
]
},
"err.suspend.not_found": {
"message": "未找到「{name}」的完整挂起状态文件",
"$params": [
"name"
]
},
"err.suspend.incompatible": {
"message": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动",
"$params": [
"diffs"
]
},
"err.suspend.discard_running": {
"message": "虚拟机「{name}」正在运行,无法放弃挂起状态",
"$params": [
"name"
]
},
"err.suspend.action_blocked": {
"message": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作",
"$params": [
"name"
]
},
"err.dataroot.busy_vms": "仍有虚拟机正在运行,请先全部关机后再切换数据目录",
"err.dataroot.busy_tasks": "仍有后台下载或创建任务进行中,请等待任务结束或取消后再切换数据目录",
"font.script.zh_hant": "繁体中文(繁體中文)",
+21
View File
@@ -43,9 +43,30 @@
"fieldVMName": "虚拟机名称",
"state_running": "运行中",
"state_stopped": "已停止",
"state_suspended": "已挂起",
"state_starting": "启动中",
"state_stopping": "停止中",
"state_suspending": "挂起中",
"state_resuming": "恢复中",
"state_broken": "出错",
"suspend": "挂起",
"resume": "恢复",
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
"discardSuspend": "放弃挂起状态",
"discardSuspendTitle": "放弃「{name}」的挂起状态?",
"discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。",
"discardSuspendConfirm": "放弃并关机",
"suspendedNoticeTitle": "已保存运行状态",
"suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
"suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
"suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置",
"suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改",
"toastSuspended": "{name} 已挂起",
"toastResumed": "{name} 已恢复",
"toastDiscardSuspend": "已放弃 {name} 的挂起状态",
"failSuspend": "挂起失败",
"failResume": "恢复失败",
"failDiscardSuspend": "放弃挂起状态失败",
"pendingTitle": "下次启动生效",
"restartToApply": "重启以应用",
"guideTitle": "恢复模式",
+36 -3
View File
@@ -4,12 +4,12 @@
## 维护原则
1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu) 和 [`reims-util`](https://github.com/steelbrain/reims-util)。
1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)、[`reims-util`](https://github.com/steelbrain/reims-util) 和 [`metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。
2. **人工提 PR,冲突即停**:更新上游基线时由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按顺序执行 `git apply --check`。已合入上游(反向检查通过)的补丁会自动跳过并开 Issue 提醒退役;遇到冲突时立刻中止构建,不自动改写补丁。
3. **文件格式约束**:所有 `.patch` 文件必须为 **无 BOM、LF 行尾**(由 `.gitattributes` 中的 `*.patch -text` 约束),避免 `git apply` 在 Windows 上失败。
4. **来源透明与协议兼容**:每个运行时包的 `manifest.json` 与 `patches/` 目录必须如实记录实际应用的全部补丁及哈希;本目录补丁不适用根目录的 Apache-2.0,而是遵循目标上游兼容协议(详见 [`patches/LICENSE`](LICENSE))。
本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树。用相同的 MSYS2 CLANG64 工具链安装其中的 `reims-util` 后,把同一工作树传给打包脚本。
本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树,`-Metal2VulkanRepo` 指向 `reims-vgpu/Cargo.toml` 固定版本的 `metal2vulkan` 工作树(并通过 `$CARGO_HOME/config.toml` 的 `[patch."https://github.com/steelbrain/metal2vulkan"]` 覆盖,使 `reims-vgpu/Cargo.lock` 与上游保持逐字节一致)。用相同的 MSYS2 CLANG64 工具链构建后,把同一组工作树传给打包脚本。
---
@@ -19,17 +19,20 @@
| 补丁文件 | 目标仓库与路径 | 解决的问题 | 当前状态 |
| :--- | :--- | :--- | :--- |
| [`reims-vgpu-cargo-lock.patch`](reims-vgpu-cargo-lock.patch) | `reims-vgpu` (`Cargo.lock`) | 补齐 `metal2vulkan` 三个 crate 的 `source` 锁定信息,使源码包与实际 Cargo 构建逐字节一致 | 仅用于构建可复现;上游补齐 `Cargo.lock` 后删除 |
| [`reims-vgpu-win32-unicode-input.patch`](reims-vgpu-win32-unicode-input.patch) | `reims-vgpu` (`crates/reims-vgpu-window`) | 通过 `SDL_SetWindowsMessageHook` 在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时转发非物理按键的 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`,解决 Windows IME 与中文输入被吞 | 待编入 `alpha` 冒烟验证后提 PR |
| [`reims-vgpu-display-fixed-mode.patch`](reims-vgpu-display-fixed-mode.patch) | `reims-vgpu` (`crates/reims-vgpu-window`, `crates/reims-vgpu`) | 新增 `REIMS_VGPU_WINDOW_FIXED_MODE=1` 将全屏/窗口物理尺寸与客体渲染分辨率解耦,按 `scale * (guest_w / drawable_w)` 推导有效 DPI,并在帧尺寸与目标区域不一致时自动走线性采样 GPU 着色器缩放(支持 4K 全屏 1.5× 超采样 `5120×2880` HiDPI) | `git apply --check` 在 `3731afd9` 通过;待编入 `alpha` 真机验证后提 PR |
| [`reims-ctl-win32-random-bytes.patch`](reims-ctl-win32-random-bytes.patch) | `reims-vgpu` (`crates/reims-ctl/src/vm.rs`) | 修复 Windows 下打不开 `/dev/urandom` 时回退到低熵时间戳种子的缺陷,改用标准库 `RandomState`(底层调用 `ProcessPrng`)生成 MAC/ROM 随机字节 | `git apply --check` 通过;待编入 `alpha` 验证后提 PR |
| [`reims-ctl-virtio-discard-iothread.patch`](reims-ctl-virtio-discard-iothread.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 为 VirtIO 系统盘补齐 `discard=unmap`(与 NVMe 一致透传客体 TRIM)并启用独立 `-object iothread,id=io0`,避免块完成回调与 QEMU 主循环争抢 | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;真机实测与休眠唤醒通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR |
| [`reims-ctl-qcow2-l2-cache.patch`](reims-ctl-qcow2-l2-cache.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 按 `qcow2` 文件头虚拟容量与簇大小计算全覆盖所需 `l2-cache-size`(上限 32 MiB,仅大于 8 MiB 默认值时追加),避免非 Linux 宿主默认 8 MiB 上限仅覆盖 64 GiB | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;128 GiB 镜像真机实测通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR |
| [`reims-vgpu-snapshot-replay.patch`](reims-vgpu-snapshot-replay.patch) | `reims-vgpu` (`crates/reims-vgpu*`) | 实现 GPU 静止、实时对象日志与 `RVGSNAP1` 二进制编解码(含统一计数边界校验、因果父对象保留、`whole_library_key` 索引及未附着延迟 SurfaceCache 持久化)、显存与事件保存/重放及严格错误传播 | 单元测试、双进程 RTX A5000 Vulkan 测试及 Intel macOS 26.7.3 同 PID Metal 读回实测通过;待提 PR |
| [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `reims-util` (`src/http.rs`, `src/installer.rs`) | 对有 Apple 分块校验数据的完整离线包并发请求四段,按顺序校验并写入镜像。分段读取失败时用原有单路下载继续 | 待编入 `alpha` 冒烟验证 |
| [`metal2vulkan-snapshot-replay.patch`](metal2vulkan-snapshot-replay.patch) | `metal2vulkan` (`crates/metal2vulkan-runtime/src/`) | 暴露 Private/Shared/Managed 缓冲与纹理(含多层/多 Mip)及事件计数的快照读出与精确地址/内容回写接口 | 随 `reims-vgpu-snapshot-replay.patch` 在干净 checkout 构建并实测通过;待提 PR |
| [`qemu-whpx-win10-compat.patch`](qemu-whpx-win10-compat.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 修复 Windows 10 19045 上两处 WHPX 必现崩溃(探测 TSC deadline 污染主分区、`WHvResetPartition` 未判空) | 已在 Win10 19045 真机验证并随稳定运行时发布;待提 PR |
| [`qemu-whpx-win10-startup-ipis.patch`](qemu-whpx-win10-startup-ipis.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 在 Win10 开启 `kernel-irqchip` 且多核启动时经 `WHvRequestInterrupt` 转发 INIT/SIPI,避免 XNU 从核卡死(依赖上一项) | 8/12 核冷启动通过;客体软重启待验证,待提 PR |
| [`qemu-whpx-nested-virt-nonfatal.patch`](qemu-whpx-nested-virt-nonfatal.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 部分 Win11 宿主设置嵌套虚拟化属性返回 `0x80370302` 时改为警告并清零特性位,保留 `kernel-irqchip=on` 加速(依赖前两项) | 待编入 `alpha` 并在 Win11 真机验证后提 PR |
| [`qemu-win32-coroutine-fiber-commit.patch`](qemu-win32-coroutine-fiber-commit.patch) | `vendor/qemu` (`util/coroutine-windows.c`) | 改用 `CreateFiberEx(64 KiB, 1 MiB, ...)` 将协程初始提交降至 1/16,并判空与检查 `IsThreadAFiber()`,避免高并发 I/O 时 `SwitchToFiber(NULL)` 崩溃 | `git apply --check` 通过;待编入 `alpha` 真机验证后提 PR |
| [`qemu-win32-mapped-ram-io.patch`](qemu-win32-mapped-ram-io.patch) | `vendor/qemu` (`io/channel*.c`, `migration/*.c`) | 为 Win32 `QIOChannelFile` 实现 `preadv`/`pwritev`(合并读写路径、零写保护与文件指针恢复),并解除 `mapped-ram` + `multifd` 文件快照在 Windows 下的 POSIX 限制 | Win11 WHPX 真机跨进程及真实宿主重启恢复实测通过;待提 PR |
| [`qemu-intel-whpx-suspend.patch`](qemu-intel-whpx-suspend.patch) | `vendor/qemu` (`accel/whpx/`, `target/i386/whpx/`, `hw/misc/applesmc.c`, `hw/display/reims-graphics-pci.c`, `migration/`) | 为 Intel x86-64 WHPX 实现停机文件挂起(限制在已暂停 VM 的 `MIG_MODE_NORMAL` + `file:` 迁移入口,保留非 `normal`/在线迁移与 `savevm` 拦截)、完整 LAPIC/x2APIC/TSC/AppleSMC 与 `reims-graphics-pci` VMState 保存恢复 | 7 项 QMP 闸门回归 + Win11 WHPX 真机解锁桌面同 PID Metal 读回及真实宿主重启通过;待提 PR |
---
@@ -103,6 +106,36 @@
- **最小修复**:仅当磁盘为 `qcow2` 且本地可读有效头时,读取虚拟容量与 `cluster_bits` 计算 `virtual_size / cluster_size * 8` 向上取整至 MiB(上限 32 MiB),大于 8 MiB 时追加 `,l2-cache-size={mib}M`;不存在文件时静默忽略,不影响现有单元测试。
- **实测证据**(128 GiB 镜像 16 MiB L2 缓存):`rand-read-large`(热缓存)QEMU 块层平均读延迟从 128.5 μs 降至 70.6 μs(-45.1%),端到端耗时从 1,623.6 ms 降至 1,498.7 ms(-7.7%),仅增加 8 MiB 内存占用且无稳定性风险。
### 9. `qemu-win32-mapped-ram-io.patch`
- **建议 PR 标题**:`io/channel-file & migration: support Win32 positioned vector I/O for mapped-ram file snapshots`
- **目标**:`steelbrain/qemu-reims-vgpu`(`io/channel-file.c`, `io/channel*.c`, `migration/file.c`, `migration/ram.c`, `migration/qemu-file.c`, `migration/channel-block.c`)
- **影响环境**:Windows 宿主使用 `mapped-ram` + `multifd` 执行停机文件挂起与恢复的场景。
- **根因**:上游 `QIOChannelFile` 的 `preadv`/`pwritev` 仅在非 Win32 路径实现,`mapped-ram` 与 `multifd` 文件通道在 Windows 上直接受限。
- **最小修复**:合并 Win32 定位读写公共逻辑(统一偏移校验、溢出安全分块、EOF/短写语义区分、零字节写入返回 `EIO` 防止死循环以及恢复原文件指针),并开放 Win32 `mapped-ram` + `multifd` 文件路径。
### 10. `qemu-intel-whpx-suspend.patch`
- **建议 PR 标题**:`whpx & reims-graphics-pci: support paused-VM file suspend and resume on Intel x86-64`
- **目标**:`steelbrain/qemu-reims-vgpu`(`accel/whpx/whpx-common.c`, `include/system/whpx-common.h`, `target/i386/whpx/whpx-all.c`, `target/i386/whpx/whpx-apic.c`, `hw/misc/applesmc.c`, `hw/display/reims-graphics-pci.c`, `migration/migration.c`, `migration/savevm.c`)
- **影响环境**:Intel x86-64 macOS 客体在 Windows WHPX 上的停机挂起至磁盘与跨进程/跨宿主重启恢复。
- **最小修复**:
1. 保留非 `MIG_MODE_NORMAL` 模式的 WHPX migration blocker,并在 `qmp_migrate()`、WHPX `MIG_EVENT_SETUP` 回调与 `save_snapshot()` 强制检查:仅放行已暂停 VM 的 `MIG_MODE_NORMAL` + `file:` 路径,拒绝运行中迁移、非 `file:` 传输、postcopy、background-snapshot、COLO 及 `savevm`。
2. 补齐 WHPX x86-64 vCPU/LAPIC/x2APIC/TSC 寄存器与 AppleSMC、`reims-graphics-pci` 设备 VMState 保存恢复回调(含损坏快照向 QMP 返回错误并保留挂起文件)。
- **实测证据**:7 项 QMP 闸门回归全部通过;Windows 11 WHPX + RTX A5000 + Intel macOS 26.7.3 解锁桌面实测跨完整 QEMU 退出及真实 Windows 重启恢复,首帧 1920×1080 SHA-256 完全一致,原应用 PID / Metal 队列 / Private 资源读回 100% 匹配。
### 11. `metal2vulkan-snapshot-replay.patch`
- **建议 PR 标题**:`runtime: add snapshot readback and exact-address restore hooks for buffers, textures, and events`
- **目标**:`steelbrain/metal2vulkan`(`crates/metal2vulkan-runtime/src/{block,device,event,floor,lib,memory,places}.rs`)
- **最小修复**:为 `metal2vulkan-runtime` 增加共享/私有池块分配恢复、Private 缓冲/纹理全子资源(含多 mip/slice)内容读回与回写、以及事件值读写接口,使上层 `reims-vgpu` 可在宿主进程重启后原位重建客体可见 GPU 地址与显存内容。
### 12. `reims-vgpu-snapshot-replay.patch`
- **建议 PR 标题**:`graphics & pool: add RVGSNAP1 device quiesce, live object log, and strict snapshot replay`
- **目标**:`steelbrain/reims-vgpu`(`crates/reims-vgpu*`)
- **最小修复**:
1. 统一 `quiesce_device()` 静止流程(排空传输与编译任务、刷写表面缓存并等待 GPU 空闲),由 `reims-vgpu-c` 暴露保存/加载 C ABI 供 `reims-graphics-pci` VMState 调用。
2. 新增 `RVGSNAP1` 二进制快照编解码,由 `Dec::checked_count` / `read_vec` 在分配前统一按剩余字节和最小条目大小校验计数并校验尾部无多余字节。
3. 完整保存与回放共享/私有内存池、实时对象日志(含 `whole_library_key` 索引与因果父对象保留,避免 ARC 释放 `MTLLibrary` 后导致活跃管线回放失败)、事件计数、Private 缓冲/纹理与未附着延迟 `SurfaceCache`(含 VA-API P010 视频帧),任何关键对象或显存保存/恢复失败均向 QMP 返回错误且不解除静止。
- **实测证据**:干净上游 checkout 通过 `reims-vgpu-graphics` 与 `reims-vgpu` 快照单元测试及 `reims-vgpu-c` 零警告 release 构建;RTX A5000 双进程 Vulkan 读回与 Intel macOS 26.7.3 解锁桌面跨进程同 PID Metal 读回(Buffer/Texture/Event/SharedEvent + 恢复后原队列继续 Compute 变异)100% 通过。
---
## 关注中的上游 PR 与演进
+525
View File
@@ -0,0 +1,525 @@
diff --git a/crates/metal2vulkan-runtime/src/block.rs b/crates/metal2vulkan-runtime/src/block.rs
index 0ac77ecac0f3abb9e9b76fb82d17c3536e22f4f5..426d025513a2f04e97f31efa66d1632635f7254d 100644
--- a/crates/metal2vulkan-runtime/src/block.rs
+++ b/crates/metal2vulkan-runtime/src/block.rs
@@ -54,6 +54,12 @@ impl Block {
Block { claim }
}
+ /// Returns capture/replay address metadata for this block (if supported).
+ pub fn capture_info(&self) -> Option<memory::BlockCaptureInfo> {
+ let (core, block) = self.held().ok()?;
+ core.pool.capture_info(&block.memory)
+ }
+
/// Whether the block is of `core`'s device.
pub(crate) fn is_of(&self, core: &Arc<Core>) -> bool {
Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core)
diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs
index 8edf1f27202f9a19b19cc4a4484d1e31341b8ab1..68f79440cc7727f2fae6063756380fe7a85ce7f9 100644
--- a/crates/metal2vulkan-runtime/src/device.rs
+++ b/crates/metal2vulkan-runtime/src/device.rs
@@ -273,6 +273,7 @@ pub(crate) struct Core {
/// every render pipeline takes its colour flag, and a draw reads an attachment of its pass
/// with the image in the feedback layout.
pub(crate) feedback_loop: bool,
+ pub(crate) capture_replay: bool,
/// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists
/// it): a lost device's fault report, read once, at its first loss (`crate::fault`).
pub(crate) fault: Option<ash::ext::device_fault::Device>,
@@ -860,6 +861,7 @@ impl Device {
ticks,
calibrated,
feedback_loop: capabilities.feedback_loop,
+ capture_replay: capabilities.buffer_device_address_capture_replay,
fault,
indirect,
attachment_reads: capabilities.attachment_reads,
@@ -1140,6 +1142,41 @@ impl Device {
/// allocation past the device's count; [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped)
/// where the consumer did not map the allocation the take made; [`Error::Vulkan`] where the
/// device is out of memory or lost; [`Error::Quiesced`].
+ /// Whether Vulkan `bufferDeviceAddressCaptureReplay` is enabled on this device.
+ pub fn buffer_device_address_capture_replay(&self) -> bool {
+ self.shared.core.capture_replay
+ }
+
+ /// Waits non-destructively until all in-flight GPU work has completed and retired.
+ pub fn wait_idle(&self) -> Result<(), Error> {
+ let core = &self.shared.core;
+ if core.closed() {
+ return Err(Error::Quiesced);
+ }
+ // Wait for submitted command buffers to retire on the completion thread.
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while core.pool.in_flight() > 0 && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ // SAFETY: `device` is live and wait_idle synchronizes all host queues.
+ let _q = lock(&core.queues.runtime);
+ unsafe { core.device.device_wait_idle() }.map_err(Error::vulkan("vkDeviceWaitIdle"))?;
+ Ok(())
+ }
+
+ /// Replays a previously captured block at its exact Vulkan device address.
+ pub fn take_block_replayed(&self, capture: memory::BlockCaptureInfo) -> Result<Block, Error> {
+ let core = &self.shared.core;
+ if core.closed() {
+ return Err(Error::Quiesced);
+ }
+ let memory = core.pool.take_replayed(core, capture, crate::counters::Site::take(capture.class))?;
+ let info = memory.info();
+ let block = memory::Block::new(memory, Arc::clone(core));
+ Ok(Block::claim(core, info, block))
+ }
+
+ /// Allocates a new GPU memory block of `class` and `len` bytes.
pub fn take_block(&self, class: MemoryClass, len: u64) -> Result<Block, Error> {
let core = &self.shared.core;
if core.closed() {
diff --git a/crates/metal2vulkan-runtime/src/event.rs b/crates/metal2vulkan-runtime/src/event.rs
index fe95046625fb1d1c81e2925458c22c4dd3641197..8b47e5604f50dec0549733c515ce80e02dbe348e 100644
--- a/crates/metal2vulkan-runtime/src/event.rs
+++ b/crates/metal2vulkan-runtime/src/event.rs
@@ -140,6 +140,35 @@ impl Event {
}
}
+impl Event {
+ /// Reads the current signaled value of this timeline event (for checkpointing).
+ pub fn signaled_value(&self) -> u64 {
+ let inner = &self.inner;
+ let state = lock(&inner.state);
+ let floor = state.observed.max(state.floor);
+ inner.reached(None).map_or(floor, |reached| reached.max(floor))
+ }
+
+ /// Restores the timeline semaphore and CPU floor to `value` on a freshly created event.
+ pub fn restore_signaled_value(&self, value: u64) -> Result<(), Error> {
+ if value == 0 {
+ return Ok(());
+ }
+ let inner = &self.inner;
+ let info = vk::SemaphoreSignalInfo::default()
+ .semaphore(inner.semaphore)
+ .value(value);
+ // SAFETY: `semaphore` is a live timeline semaphore on `inner.core.device`.
+ unsafe { inner.core.device.signal_semaphore(&info) }
+ .map_err(Error::vulkan("vkSignalSemaphore"))?;
+ let mut state = lock(&inner.state);
+ state.floor = state.floor.max(value);
+ state.observed = state.observed.max(value);
+ inner.changed.notify_all();
+ Ok(())
+ }
+}
+
impl SharedEvent {
/// `signaledValue`: the higher of the semaphore's value and the host's floor, the semaphore's
/// value being one a host wait confirmed: a counter read finds it, and a wait with a timeout
diff --git a/crates/metal2vulkan-runtime/src/floor.rs b/crates/metal2vulkan-runtime/src/floor.rs
index 0e165934f4b7534d0a093b1a22bcd763a47db8d7..90c7f9e354af205aa5a6b2fbeb506e58fbba1ab8 100644
--- a/crates/metal2vulkan-runtime/src/floor.rs
+++ b/crates/metal2vulkan-runtime/src/floor.rs
@@ -1079,6 +1079,8 @@ pub struct Capabilities {
/// [`ATTACHMENT_READ_EXTENSIONS`]: a draw reads an attachment through the attachment feedback
/// loop, the feedback layout its image moves to and the flag every render pipeline takes.
pub feedback_loop: bool,
+ /// Whether `bufferDeviceAddressCaptureReplay` is enabled for checkpoint/restore.
+ pub buffer_device_address_capture_replay: bool,
/// The features device creation enables: every one the floor requires, each of the optional,
/// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment
/// and fault-report ones the device reports, the attachment-read ones where
@@ -1425,6 +1427,10 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else {
return Err(BelowFloor { missing });
};
+ let capture_replay = reported.vulkan12.buffer_device_address_capture_replay == vk::TRUE;
+ if capture_replay {
+ features.vulkan12.buffer_device_address_capture_replay = vk::TRUE;
+ }
for feature in (OPTIONAL.iter().chain(STEP_RATES))
.chain(MIN_LOD_CLAMPS)
.chain(FILL_MODES)
@@ -1491,6 +1497,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE,
attachment_reads,
feedback_loop,
+ buffer_device_address_capture_replay: capture_replay,
features,
extensions: DEVICE_EXTENSIONS
.iter()
diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs
index a2d59cc6f31eb64307c1a886fe7cf75f401511b1..557a1a4b213773df976895f703cd4c037ad2602b 100644
--- a/crates/metal2vulkan-runtime/src/lib.rs
+++ b/crates/metal2vulkan-runtime/src/lib.rs
@@ -100,7 +100,7 @@ pub use host_bytes::HostBytes;
pub use import::ImportHandle;
pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType};
pub use instance::{Instance, PhysicalDevice};
-pub use memory::{AllocationId, AllocationInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
+pub use memory::{AllocationId, AllocationInfo, BlockCaptureInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
/// `MTLLibrary`: the translator's, read from AIR or a metallib.
/// `MTLSamplerDescriptor`: the translator's.
pub use metal2vulkan::bind::SamplerDescriptor;
diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs
index 173e0858f2e6d07660cafd5f7893aee280f2dcdc..2864f4ba6b48a4892e6d9651548c75a4babcf395 100644
--- a/crates/metal2vulkan-runtime/src/memory.rs
+++ b/crates/metal2vulkan-runtime/src/memory.rs
@@ -235,8 +235,28 @@ impl AllocationId {
/// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer
/// usage and a device address, spans it; an imported or exported block is the whole of an
/// allocation of its own. Only an exported block is exportable.
+/// Capture/replay address metadata for restoring a block at its exact Vulkan device address.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct BlockCaptureInfo {
+ /// Storage mode (`Shared` or `Private`).
+ pub class: MemoryClass,
+ /// Full parent Vulkan allocation length in bytes.
+ pub alloc_len: u64,
+ /// Offset of this block inside its parent allocation.
+ pub offset: u64,
+ /// Block length in bytes.
+ pub len: u64,
+ /// Guest-visible `VkDeviceAddress` of this block's first byte.
+ pub gpu_address: u64,
+ /// Opaque capture address of the parent `VkBuffer`.
+ pub opaque_buffer_address: u64,
+ /// Opaque capture address of the parent `VkDeviceMemory`.
+ pub opaque_memory_address: u64,
+}
+
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
+/// Metadata describing an allocated GPU memory block.
pub struct BlockInfo {
/// The block's number.
pub id: BlockId,
@@ -611,6 +631,10 @@ struct Allocation {
buffer: vk::Buffer,
/// The device address of its first byte.
address: u64,
+ /// Opaque capture address of `buffer` (0 if capture-replay unsupported).
+ opaque_buffer_address: u64,
+ /// Opaque capture address of `memory` (0 if capture-replay unsupported).
+ opaque_memory_address: u64,
len: u64,
mapping: Option<Mapping>,
device_local: bool,
@@ -823,6 +847,8 @@ struct State {
/// The internal the block-maker thread took up and is making ([`run`]).
making: Option<Internal>,
stop: bool,
+ replaying: bool,
+ making_ahead: bool,
next_id: u32,
next_allocation: u32,
/// The allocations [`BlockMappings::map`] accepted whose unmap has not run.
@@ -952,6 +978,8 @@ impl Pool {
asked: [true; INTERNALS],
making: None,
stop: false,
+ replaying: false,
+ making_ahead: false,
next_id: 1,
next_allocation: 1,
mapped: HashSet::new(),
@@ -1368,6 +1396,158 @@ impl Pool {
}
}
+ /// Returns capture/replay info for a pool block, if capture-replay is enabled.
+ pub(crate) fn capture_info(&self, memory: &Memory) -> Option<BlockCaptureInfo> {
+ if memory.own.is_some() {
+ return None;
+ }
+ let state = self.lock();
+ let alloc = state.allocations[memory.class.index()]
+ .iter()
+ .find(|a| a.memory == memory.memory)?;
+
+ Some(BlockCaptureInfo {
+ class: memory.class,
+ alloc_len: alloc.len,
+ offset: memory.base,
+ len: memory.len,
+ gpu_address: memory.address,
+ opaque_buffer_address: alloc.opaque_buffer_address,
+ opaque_memory_address: alloc.opaque_memory_address,
+ })
+ }
+
+ /// Replays a previously captured pool block at its exact Vulkan device address.
+ pub(crate) fn take_replayed(
+ &self,
+ core: &Core,
+ cap: BlockCaptureInfo,
+ site: Site,
+ ) -> Result<Memory, Error> {
+ let index = cap.class.index();
+ // 1. Check if the parent allocation is already present (e.g. another sub-block restored it,
+ // or a pre-stocked idle reserve landed at the exact same address!).
+ {
+ let mut state = self.lock();
+ if state.stop {
+ return Err(Error::Quiesced);
+ }
+ let id = number(&mut state)?;
+ let want_base = cap.gpu_address.saturating_sub(cap.offset);
+ if let Some(alloc) = state.allocations[index].iter_mut().find(|a| {
+ a.address == want_base
+ && a.opaque_buffer_address == cap.opaque_buffer_address
+ && a.opaque_memory_address == cap.opaque_memory_address
+ && a.len == cap.alloc_len
+ }) {
+ if alloc.free.take_at(cap.offset, cap.len) {
+ let carve = alloc.carve(cap.offset);
+ alloc.live += 1;
+ alloc.placed += cap.len;
+ alloc.ahead = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ return Ok(carve.block(id, cap.class, cap.len));
+ }
+ }
+ }
+ // 2. Pause block-maker ahead allocations, wait for any in-flight ahead make,
+ // and purge idle reserve slabs so none collide with the target opaque VA!
+ let idle_allocs: Vec<Allocation> = {
+ let mut state = self.lock();
+ state.replaying = true;
+ while state.making_ahead {
+ state = self.wait(state);
+ }
+ // Re-check if an ahead allocation that just finished landed at the exact target VA!
+ let want_base = cap.gpu_address.saturating_sub(cap.offset);
+ let hit = state.allocations[index].iter_mut().find_map(|a| {
+ if a.address == want_base
+ && a.opaque_buffer_address == cap.opaque_buffer_address
+ && a.opaque_memory_address == cap.opaque_memory_address
+ && a.len == cap.alloc_len
+ && a.free.take_at(cap.offset, cap.len)
+ {
+ let carve = a.carve(cap.offset);
+ a.live += 1;
+ a.placed += cap.len;
+ a.ahead = false;
+ Some(carve)
+ } else {
+ None
+ }
+ });
+ if let Some(carve) = hit {
+ let id = number(&mut state)?;
+ state.replaying = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ return Ok(carve.block(id, cap.class, cap.len));
+ }
+ let mut drained = Vec::new();
+ for c in MemoryClass::ALL {
+ let ci = c.index();
+ let mut kept = Vec::new();
+ for a in state.allocations[ci].drain(..) {
+ if a.live == 0 {
+ drained.push(a);
+ } else {
+ kept.push(a);
+ }
+ }
+ state.allocations[ci] = kept;
+ self.settle(&mut state, c);
+ }
+ drained
+ };
+ for a in idle_allocs {
+ free_idle(core, a);
+ }
+ // 3. Allocate at the exact captured opaque buffer + memory addresses.
+ let alloc_res = make_allocation_ex(
+ core,
+ cap.class,
+ cap.alloc_len,
+ Some(site),
+ Some((cap.opaque_buffer_address, cap.opaque_memory_address)),
+ );
+ let mut allocation = match alloc_res {
+ Ok(a) => a,
+ Err(e) => {
+ let mut state = self.lock();
+ state.replaying = false;
+ self.changed.notify_all();
+ return Err(e);
+ }
+ };
+ let mapped = self.map(&allocation, cap.class, true);
+ if !mapped {
+ free_allocation(core, allocation);
+ let mut state = self.lock();
+ state.replaying = false;
+ self.changed.notify_all();
+ return Err(Error::Limit(Limit::AllocationNotMapped {
+ class: cap.class,
+ len: cap.alloc_len,
+ }));
+ }
+ let ok = allocation.free.take_at(cap.offset, cap.len);
+ debug_assert!(ok, "fresh allocation must contain captured block range");
+ let mut state = self.lock();
+ let id = number(&mut state)?;
+ let memory = allocation.carve(cap.offset).block(id, cap.class, cap.len);
+ allocation.live = 1;
+ allocation.placed = cap.len;
+ state.allocations[index].push(allocation);
+ state.replaying = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ Ok(memory)
+ }
+
/// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its
/// allocation at once.
pub(crate) fn give_back(&self, memory: Memory) {
@@ -1788,12 +1968,16 @@ pub(crate) fn run(core: Arc<Core>) {
state = pool.lock();
continue;
}
- let wanted = (MemoryClass::ALL.into_iter())
- .find(|&class| !state.failed[class.index()] && !state.whole(class));
+ let wanted = (!state.replaying).then(|| {
+ (MemoryClass::ALL.into_iter())
+ .find(|&class| !state.failed[class.index()] && !state.whole(class))
+ }).flatten();
if let Some(class) = wanted {
+ state.making_ahead = true;
drop(state);
let made = ahead(&core, class);
state = pool.lock();
+ state.making_ahead = false;
match made {
// Idle from now: the reserve, which the idle rule does not weigh.
Some(mut allocation) => {
@@ -2022,6 +2206,16 @@ fn make_allocation(
class: MemoryClass,
len: u64,
site: Option<Site>,
+) -> Result<Allocation, Error> {
+ make_allocation_ex(core, class, len, site, None)
+}
+
+fn make_allocation_ex(
+ core: &Core,
+ class: MemoryClass,
+ len: u64,
+ site: Option<Site>,
+ replay: Option<(u64, u64)>,
) -> Result<Allocation, Error> {
let device = &core.device;
let (id, freed_at) = {
@@ -2031,22 +2225,38 @@ fn make_allocation(
state.freed_at[class.index()],
)
};
- let info = vk::BufferCreateInfo::default()
+ let mut buf_opaque = vk::BufferOpaqueCaptureAddressCreateInfo::default()
+ .opaque_capture_address(replay.map_or(0, |(b, _)| b));
+ let mut info = vk::BufferCreateInfo::default()
.size(len)
.usage(floor::BUFFER_USAGE)
.sharing_mode(vk::SharingMode::EXCLUSIVE);
+ if core.capture_replay {
+ info = info.flags(vk::BufferCreateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY);
+ if replay.is_some_and(|(b, _)| b != 0) {
+ info = info.push_next(&mut buf_opaque);
+ }
+ }
// SAFETY: the device is live, and the create info valid: `len` is at most its
// `maxBufferSize`.
let buffer =
unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?;
// SAFETY: the buffer is the device's.
let requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
- let mut flags =
- vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS);
- let allocate_info = vk::MemoryAllocateInfo::default()
+ let mut mem_flags = vk::MemoryAllocateFlags::DEVICE_ADDRESS;
+ if core.capture_replay {
+ mem_flags |= vk::MemoryAllocateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY;
+ }
+ let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(mem_flags);
+ let mut mem_opaque = vk::MemoryOpaqueCaptureAddressAllocateInfo::default()
+ .opaque_capture_address(replay.map_or(0, |(_, m)| m));
+ let mut allocate_info = vk::MemoryAllocateInfo::default()
.allocation_size(requirements.size.max(len))
.memory_type_index(core.memory_type(class))
.push_next(&mut flags);
+ if core.capture_replay && replay.is_some_and(|(_, m)| m != 0) {
+ allocate_info = allocate_info.push_next(&mut mem_opaque);
+ }
let bits = requirements.memory_type_bits;
// SAFETY: the floor chose the memory type for buffers of this usage on this device, and
// `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow.
@@ -2065,6 +2275,8 @@ fn make_allocation(
memory,
buffer,
address: 0,
+ opaque_buffer_address: 0,
+ opaque_memory_address: 0,
len,
mapping: None,
device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0,
@@ -2101,6 +2313,13 @@ fn make_allocation(
let of = vk::BufferDeviceAddressInfo::default().buffer(buffer);
// SAFETY: the buffer has device-address usage and is bound.
allocation.address = unsafe { device.get_buffer_device_address(&of) };
+ if core.capture_replay {
+ allocation.opaque_buffer_address =
+ unsafe { device.get_buffer_opaque_capture_address(&of) };
+ let mof = vk::DeviceMemoryOpaqueCaptureAddressInfo::default().memory(memory);
+ allocation.opaque_memory_address =
+ unsafe { device.get_device_memory_opaque_capture_address(&mof) };
+ }
(core.spans).made(
buffer,
allocation.address,
diff --git a/crates/metal2vulkan-runtime/src/places.rs b/crates/metal2vulkan-runtime/src/places.rs
index 137fb5790de850552affd179497df69d9912266a..3d679bbaa5285e87d1639a7cc140e0025b49e84f 100644
--- a/crates/metal2vulkan-runtime/src/places.rs
+++ b/crates/metal2vulkan-runtime/src/places.rs
@@ -248,6 +248,33 @@ impl Ranges {
Some(at)
}
+ /// Takes the exact range `at..at + len` if it is completely free.
+ pub(crate) fn take_at(&mut self, at: u64, len: u64) -> bool {
+ let Some(stop) = at.checked_add(len) else {
+ return false;
+ };
+ let Some(index) = self
+ .free
+ .iter()
+ .position(|&(start, end)| start <= at && stop <= end)
+ else {
+ return false;
+ };
+ let (start, end) = self.free[index];
+ match (start < at, stop < end) {
+ (false, false) => {
+ self.free.remove(index);
+ }
+ (true, false) => self.free[index] = (start, at),
+ (false, true) => self.free[index] = (stop, end),
+ (true, true) => {
+ self.free[index] = (start, at);
+ self.free.insert(index + 1, (stop, end));
+ }
+ }
+ true
+ }
+
/// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it.
pub(crate) fn give(&mut self, offset: u64, len: u64) {
let end = offset + len;
+906
View File
@@ -0,0 +1,906 @@
diff --git a/accel/whpx/whpx-common.c b/accel/whpx/whpx-common.c
index 63e941496d055f1075e8e860b3785a179bb42edf..13bf3e890a93000e32fd0036fc1fde7a75c46eb4 100644
--- a/accel/whpx/whpx-common.c
+++ b/accel/whpx/whpx-common.c
@@ -50,8 +50,14 @@ struct WHPDispatch whp_dispatch;
void whpx_flush_cpu_state(CPUState *cpu)
{
if (cpu->vcpu_dirty) {
- whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE);
+ WHPXStateLevel level = (cpu->accel && cpu->accel->loadvm_pending)
+ ? WHPX_LEVEL_FULL_STATE
+ : WHPX_LEVEL_RUNTIME_STATE;
+ whpx_set_registers(cpu, level);
cpu->vcpu_dirty = false;
+ if (cpu->accel) {
+ cpu->accel->loadvm_pending = false;
+ }
}
}
@@ -207,6 +213,19 @@ static void do_whpx_cpu_synchronize_pre_loadvm(CPUState *cpu,
run_on_cpu_data arg)
{
cpu->vcpu_dirty = true;
+ if (cpu->accel) {
+ cpu->accel->loadvm_pending = true;
+ }
+}
+
+static void do_whpx_cpu_synchronize_post_loadvm(CPUState *cpu,
+ run_on_cpu_data arg)
+{
+ if (cpu->accel && cpu->accel->loadvm_pending) {
+ whpx_set_registers(cpu, WHPX_LEVEL_FULL_STATE);
+ cpu->vcpu_dirty = false;
+ cpu->accel->loadvm_pending = false;
+ }
}
/*
@@ -237,7 +256,36 @@ void whpx_cpu_synchronize_pre_loadvm(CPUState *cpu)
static void whpx_pre_resume_vm(AccelState *as, bool step_pending)
{
+ CPUState *cpu;
+ bool any_loadvm = false;
+
whpx_global.step_pending = step_pending;
+
+ CPU_FOREACH(cpu) {
+ if (cpu->accel && cpu->accel->loadvm_pending) {
+ any_loadvm = true;
+ break;
+ }
+ }
+ if (any_loadvm) {
+ uint64_t max_tsc = 0;
+ CPU_FOREACH(cpu) {
+ uint64_t t = cpu_env(cpu)->tsc;
+ if (t > max_tsc) {
+ max_tsc = t;
+ }
+ }
+ if (whp_dispatch.WHvSuspendPartitionTime) {
+ whp_dispatch.WHvSuspendPartitionTime(whpx_global.partition);
+ }
+ CPU_FOREACH(cpu) {
+ if (cpu->accel && cpu->accel->loadvm_pending) {
+ cpu_env(cpu)->tsc = max_tsc;
+ run_on_cpu(cpu, do_whpx_cpu_synchronize_post_loadvm,
+ RUN_ON_CPU_NULL);
+ }
+ }
+ }
}
/*
@@ -525,7 +573,7 @@ static void whpx_log_sync(MemoryListener *listener,
{
MemoryRegion *mr = section->mr;
- if (!memory_region_is_ram(mr)) {
+ if (!memory_region_is_ram(mr) || !runstate_is_running()) {
return;
}
diff --git a/hw/display/reims-graphics-pci.c b/hw/display/reims-graphics-pci.c
index db10858b65dc0447f7d0e660fca6f1acc3bb7473..976b5d4e3bd4d93d2e9a401fd494eeb2d8e6a442 100644
--- a/hw/display/reims-graphics-pci.c
+++ b/hw/display/reims-graphics-pci.c
@@ -114,7 +114,9 @@
#endif
#include "qapi/error.h"
#include "qapi/qapi-commands-ui.h"
-#include "migration/blocker.h"
+#include "migration/misc.h"
+#include "migration/vmstate.h"
+#include "migration/qemu-file-types.h"
#include "hw/core/qdev-properties.h"
#include "hw/pci/pci_device.h"
#include "hw/pci/msix.h"
@@ -232,6 +234,10 @@ struct ReimsGraphicsPCIState {
bool irqfd_made; /* the notifier is initialised */
RvgGraphicsDevice *device;
VMChangeStateEntry *vm_state; /* the teardown at QEMU's quit */
+ NotifierWithReturn mig_notifier;
+ bool mig_notifier_added;
+ bool mig_quiesced;
+ bool region_registered;
/* The displays, display i head i: the first `displays` of them. */
ReimsGraphicsHead heads[RVG_GRAPHICS_DISPLAYS_MAX];
ThreadPool *pool; /* where the consoles' reads of the displays run */
@@ -283,7 +289,6 @@ struct ReimsGraphicsPCIState {
QEMU_BUILD_BUG_ON(RVG_GRAPHICS_MSIX_VECTORS != 1);
-static Error *reims_graphics_mig_blocker;
/* ------ Interrupts ------ */
@@ -1388,6 +1393,7 @@ static bool reims_graphics_pool_add(ReimsGraphicsPCIState *s,
memory_region_init_ram_ptr(&piece->mr, OBJECT(piece),
"reims-graphics-pci.pool-piece", ask->size,
ask->host);
+ qemu_ram_unset_migratable(piece->mr.ram_block);
/*
* Inside the add's transaction: on its own, set_unmergeable commits
* (and renders every flat view) for a region that is in none yet.
@@ -2111,6 +2117,14 @@ static void reims_graphics_pci_teardown(ReimsGraphicsPCIState *s, bool quit)
ReimsGraphicsHead *head;
uint32_t i;
+ if (s->mig_notifier_added) {
+ migration_remove_notifier(&s->mig_notifier);
+ s->mig_notifier_added = false;
+ }
+ if (s->region_registered) {
+ vmstate_unregister_ram(&s->region, DEVICE(dev));
+ s->region_registered = false;
+ }
if (s->vm_state) {
qemu_del_vm_change_state_handler(s->vm_state);
s->vm_state = NULL;
@@ -2477,6 +2491,158 @@ static bool reims_graphics_linux_floor(Error **errp)
return true;
}
+
+static int reims_graphics_pci_mig_notify(NotifierWithReturn *notify,
+ MigrationEvent *e, Error **errp)
+{
+ ReimsGraphicsPCIState *s =
+ container_of(notify, ReimsGraphicsPCIState, mig_notifier);
+
+ if (!s->device) {
+ return 0;
+ }
+ switch (e->type) {
+ case MIG_EVENT_SETUP:
+ if (!s->mig_quiesced) {
+ RvgStatus status = rvg_graphics_device_quiesce(s->device);
+ if (status != RVG_OK) {
+ error_setg(errp, "%s: rvg_graphics_device_quiesce failed: %s",
+ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status));
+ return -1;
+ }
+ reims_graphics_pool_bh(s);
+ s->mig_quiesced = true;
+ }
+ break;
+ case MIG_EVENT_DONE:
+ case MIG_EVENT_FAILED:
+ if (s->mig_quiesced) {
+ rvg_graphics_device_unquiesce(s->device);
+ s->mig_quiesced = false;
+ }
+ break;
+ default:
+ break;
+ }
+ return 0;
+}
+
+static int reims_graphics_vgpu_snapshot_put(QEMUFile *f, void *pv, size_t size,
+ const VMStateField *field,
+ JSONWriter *vmdesc)
+{
+ ReimsGraphicsPCIState *s = pv;
+ uint8_t *data = NULL;
+ uintptr_t len = 0;
+ uintptr_t off = 0;
+ RvgStatus status;
+
+ if (!s->device) {
+ qemu_put_be64(f, 0);
+ return 0;
+ }
+ status = rvg_graphics_device_snapshot_save(s->device, &data, &len);
+ if (status != RVG_OK) {
+ error_report("%s: rvg_graphics_device_snapshot_save failed: %s",
+ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status));
+ return -EIO;
+ }
+ qemu_put_be64(f, (uint64_t)len);
+ while (off < len) {
+ size_t chunk = (size_t)MIN(len - off, (uintptr_t)(1 * MiB));
+ qemu_put_buffer(f, data + off, chunk);
+ off += chunk;
+ }
+ rvg_graphics_snapshot_free(data, len);
+ return qemu_file_get_error(f);
+}
+
+static int reims_graphics_vgpu_snapshot_get(QEMUFile *f, void *pv, size_t size,
+ const VMStateField *field)
+{
+ ReimsGraphicsPCIState *s = pv;
+ uint64_t len = qemu_get_be64(f);
+ uint8_t *buf = NULL;
+ uint64_t off = 0;
+ RvgStatus status;
+
+ if (qemu_file_get_error(f)) {
+ return qemu_file_get_error(f);
+ }
+ if (len == 0) {
+ return 0;
+ }
+ if (len > (uint64_t)8 * GiB || !s->device) {
+ error_report("%s: invalid vgpu snapshot length %" PRIu64,
+ TYPE_REIMS_GRAPHICS_PCI, len);
+ return -EINVAL;
+ }
+ buf = g_try_malloc(len);
+ if (!buf) {
+ return -ENOMEM;
+ }
+ while (off < len) {
+ size_t chunk = (size_t)MIN(len - off, (uint64_t)(1 * MiB));
+ size_t got = qemu_get_buffer(f, buf + off, chunk);
+ if (got != chunk) {
+ g_free(buf);
+ return -EIO;
+ }
+ off += got;
+ }
+ status = rvg_graphics_device_snapshot_load(s->device, buf, (size_t)len);
+ g_free(buf);
+ if (status != RVG_OK) {
+ error_report("%s: rvg_graphics_device_snapshot_load failed: %s",
+ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status));
+ return -EIO;
+ }
+ return 0;
+}
+
+static const VMStateInfo vmstate_info_reims_vgpu_snapshot = {
+ .name = "reims-vgpu-snapshot",
+ .get = reims_graphics_vgpu_snapshot_get,
+ .put = reims_graphics_vgpu_snapshot_put,
+};
+
+static int reims_graphics_pci_post_load(void *opaque, int version_id)
+{
+ ReimsGraphicsPCIState *s = opaque;
+ PCIDevice *dev = PCI_DEVICE(s);
+
+ /* Synchronously map all restored Shared Pool pieces into guest GPA before cont. */
+ reims_graphics_pool_bh(s);
+
+ if (msix_enabled(dev)) {
+ if (s->irqfd_made) {
+ reims_graphics_pci_irqfd_enable(s);
+ } else if (s->msi_direct_made) {
+ reims_graphics_pci_direct_enable(s);
+ }
+ }
+ return 0;
+}
+
+static const VMStateDescription vmstate_reims_graphics_pci = {
+ .name = TYPE_REIMS_GRAPHICS_PCI,
+ .version_id = 1,
+ .minimum_version_id = 1,
+ .post_load = reims_graphics_pci_post_load,
+ .fields = (const VMStateField[]) {
+ VMSTATE_PCI_DEVICE(parent_obj, ReimsGraphicsPCIState),
+ VMSTATE_MSIX(parent_obj, ReimsGraphicsPCIState),
+ {
+ .name = "reims_vgpu_snapshot",
+ .info = &vmstate_info_reims_vgpu_snapshot,
+ .flags = VMS_SINGLE,
+ .size = sizeof(ReimsGraphicsPCIState),
+ .offset = 0,
+ },
+ VMSTATE_END_OF_LIST()
+ }
+};
+
static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
{
ReimsGraphicsPCIState *s = REIMS_GRAPHICS_PCI(dev);
@@ -2577,13 +2743,7 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
}
reims_graphics_pci_check_low_ram();
- if (reims_graphics_mig_blocker == NULL) {
- error_setg(&reims_graphics_mig_blocker,
- "Migration state blocked by reims-graphics-pci");
- if (migrate_add_blocker(&reims_graphics_mig_blocker, errp) < 0) {
- return;
- }
- }
+
/*
* The guest's RAM, through which the GPU uses an IOSurface's own pages in
@@ -2707,6 +2867,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
base = rvg_graphics_device_region(s->device, &size);
memory_region_init_ram_ptr(&s->region, OBJECT(dev),
"reims-graphics-pci.region", size, base);
+ vmstate_register_ram(&s->region, DEVICE(dev));
+ s->region_registered = true;
pci_register_bar(dev, RVG_GRAPHICS_PCI_BAR_REGION,
PCI_BASE_ADDRESS_SPACE_MEMORY |
PCI_BASE_ADDRESS_MEM_TYPE_64 |
@@ -2728,6 +2890,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
}
s->vm_state = qemu_add_vm_change_state_handler(
reims_graphics_pci_vm_state_change, s);
+ migration_add_notifier(&s->mig_notifier, reims_graphics_pci_mig_notify);
+ s->mig_notifier_added = true;
return;
fail:
@@ -2795,6 +2959,7 @@ static void reims_graphics_pci_class_init(ObjectClass *klass, const void *data)
rc->phases.hold = reims_graphics_pci_reset;
dc->desc = "reims-graphics GPU";
+ dc->vmsd = &vmstate_reims_graphics_pci;
dc->hotpluggable = false;
set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories);
device_class_set_props(dc, reims_graphics_pci_properties);
diff --git a/hw/misc/applesmc.c b/hw/misc/applesmc.c
index 84bcf4df0abb15ea73fc03ecc2a2c236ae4a7c8c..2dcc20aa0e28104f5d9fa2e2a4a5ffaee4648821 100644
--- a/hw/misc/applesmc.c
+++ b/hw/misc/applesmc.c
@@ -37,6 +37,7 @@
#include "qemu/error-report.h"
#include "qemu/module.h"
#include "qemu/timer.h"
+#include "migration/vmstate.h"
#include "qom/object.h"
#include "hw/acpi/acpi_aml_interface.h"
@@ -108,7 +109,7 @@ struct AppleSMCState {
uint8_t status;
uint8_t status_1e;
uint8_t last_ret;
- char key[4];
+ uint8_t key[4];
uint8_t read_pos;
uint8_t data_len;
uint8_t data_pos;
@@ -407,11 +408,30 @@ static void build_applesmc_aml(AcpiDevAmlIf *adev, Aml *scope)
aml_append(scope, dev);
}
+static const VMStateDescription vmstate_applesmc = {
+ .name = "applesmc",
+ .version_id = 1,
+ .minimum_version_id = 1,
+ .fields = (const VMStateField[]) {
+ VMSTATE_UINT8(cmd, AppleSMCState),
+ VMSTATE_UINT8(status, AppleSMCState),
+ VMSTATE_UINT8(status_1e, AppleSMCState),
+ VMSTATE_UINT8(last_ret, AppleSMCState),
+ VMSTATE_UINT8_ARRAY(key, AppleSMCState, 4),
+ VMSTATE_UINT8(read_pos, AppleSMCState),
+ VMSTATE_UINT8(data_len, AppleSMCState),
+ VMSTATE_UINT8(data_pos, AppleSMCState),
+ VMSTATE_UINT8_ARRAY(data, AppleSMCState, 255),
+ VMSTATE_END_OF_LIST()
+ }
+};
+
static void qdev_applesmc_class_init(ObjectClass *klass, const void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass);
+ dc->vmsd = &vmstate_applesmc;
dc->realize = applesmc_isa_realize;
dc->unrealize = applesmc_unrealize;
device_class_set_legacy_reset(dc, qdev_applesmc_isa_reset);
diff --git a/include/system/whpx-common.h b/include/system/whpx-common.h
index 79710e2fb3c96edda813fadbda5f8ceabcc5afac..a6fcbd2346b8e34a26f868a0ec19250a0fd268a6 100644
--- a/include/system/whpx-common.h
+++ b/include/system/whpx-common.h
@@ -9,6 +9,7 @@ struct AccelCPUState {
bool ready_for_pic_interrupt;
uint64_t tpr;
bool interruption_pending;
+ bool loadvm_pending;
/* Must be the last field as it may have a tail */
WHV_RUN_VP_EXIT_CONTEXT exit_ctx;
};
diff --git a/migration/migration.c b/migration/migration.c
index 5686209ab11b263b20776d79df79baecd26c5970..f105f616d1dbc88daac2c573c9a95cd02305d9ab 100644
--- a/migration/migration.c
+++ b/migration/migration.c
@@ -63,6 +63,7 @@
#include "system/dirtylimit.h"
#include "qemu/sockets.h"
#include "system/kvm.h"
+#include "system/whpx.h"
#include "math.h"
#define NOTIFIER_ELEM_INIT(array, elem) \
@@ -2174,6 +2175,34 @@ void qmp_migrate(const char *uri, bool has_channels,
return;
}
+ if (whpx_enabled()) {
+ if (has_resume && resume) {
+ error_setg(errp, "WHPX: migration resume is not supported");
+ return;
+ }
+ if (migrate_mode() != MIG_MODE_NORMAL) {
+ error_setg(errp, "WHPX: only normal migration mode is supported");
+ return;
+ }
+ if (runstate_is_running()) {
+ error_setg(errp,
+ "WHPX: live migration is not supported while the VM is running; stop the VM first");
+ return;
+ }
+ if (main_ch->addr->transport != MIGRATION_ADDRESS_TYPE_FILE) {
+ error_setg(errp,
+ "WHPX: only stopped-VM file suspend (file: URI) is supported");
+ return;
+ }
+ if (migrate_postcopy() || migrate_background_snapshot() ||
+ migrate_colo() || migrate_dirty_bitmaps() ||
+ migrate_return_path()) {
+ error_setg(errp,
+ "WHPX: unsupported migration capability for stopped-VM file suspend");
+ return;
+ }
+ }
+
if (!migrate_prepare(s, has_resume && resume, errp)) {
/* Error detected, put into errp */
return;
diff --git a/migration/savevm.c b/migration/savevm.c
index fe94ba96e432c8555bcfc58d97f3830a86eaab60..2a1944010c595995f6d75d3cb4d6ca67525ec1fa 100644
--- a/migration/savevm.c
+++ b/migration/savevm.c
@@ -64,6 +64,7 @@
#include "system/runstate.h"
#include "system/system.h"
#include "system/xen.h"
+#include "system/whpx.h"
#include "migration/colo.h"
#include "qemu/bitmap.h"
#include "net/announce.h"
@@ -3317,6 +3318,12 @@ bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
return false;
}
+ if (whpx_enabled()) {
+ error_setg(errp,
+ "WHPX: internal VM snapshots are not supported; use stopped-VM file migration");
+ return false;
+ }
+
if (!replay_can_snapshot()) {
error_setg(errp, "Record/replay does not allow making snapshot "
"right now. Try once more later.");
diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c
index f093b59c0f04e1cdf6a14172d3b059068e61ac00..30b64eb901dcb6d0781c87dfc4241e6b4abe635c 100644
--- a/target/i386/whpx/whpx-all.c
+++ b/target/i386/whpx/whpx-all.c
@@ -32,6 +32,7 @@
#include "qapi/qapi-types-common.h"
#include "qapi/qapi-type-infos-common.h"
#include "migration/blocker.h"
+#include "migration/misc.h"
#include "host-cpu.h"
#include "accel/accel-cpu-target.h"
#include <winerror.h>
@@ -56,6 +57,24 @@
#define HV_X64_MSR_VP_ASSIST_PAGE 0x40000073
#define HV_X64_MSR_GUEST_IDLE 0x400000f0
+#define WHPX_MP_STATE_RUNNABLE 0
+#define WHPX_MP_STATE_UNINITIALIZED 1
+#define WHPX_MP_STATE_HALTED 3
+
+static void whpx_set_reg_optional(CPUState *cpu, WHV_REGISTER_NAME reg,
+ WHV_REGISTER_VALUE val)
+{
+ whp_dispatch.WHvSetVirtualProcessorRegisters(
+ whpx_global.partition, cpu->cpu_index, &reg, 1, &val);
+}
+
+static bool whpx_get_reg_optional(CPUState *cpu, WHV_REGISTER_NAME reg,
+ WHV_REGISTER_VALUE *val)
+{
+ return SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorRegisters(
+ whpx_global.partition, cpu->cpu_index, &reg, 1, val));
+}
+
static bool is_modern_os = true;
static bool whpx_msr_exits_available = true;
static bool whpx_forward_startup_ipis;
@@ -636,18 +655,8 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level)
whpx_set_reg(cpu, WHvX64RegisterCr8, cr8);
}
- /* 8 Debug Registers - Skipped */
-
- /*
- * Extended control registers needs to be handled separately depending
- * on whether xsave is supported/enabled or not.
- */
- whpx_set_xcrs(cpu);
-
- if (whpx_is_xsave_enabled(cpu)) {
- whpx_set_xsave_state(cpu);
- }
- whpx_set_legacy_fp_registers(cpu, level);
+ /* 8 Debug Registers - restored below for FULL_STATE */
+ /* XCR0/XSAVE/FP restored AFTER CR0/CR4/EFER are committed to WHPX */
/* MSRs */
assert(whpx_register_names[idx] == WHvX64RegisterEfer);
@@ -694,10 +703,77 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level)
hr);
}
+ if (level > WHPX_LEVEL_FAST_RUNTIME_STATE) {
+ whpx_set_xcrs(cpu);
+ if (!whpx_is_xsave_enabled(cpu) || whpx_set_xsave_state(cpu) != 0) {
+ whpx_set_legacy_fp_registers(cpu, level);
+ }
+ }
+
if (level >= WHPX_LEVEL_FULL_STATE) {
- WHV_REGISTER_VALUE apic_base = {};
- apic_base.Reg64 = cpu_get_apic_base(X86_CPU(cpu)->apic_state);
- whpx_set_reg(cpu, WHvX64RegisterApicBase, apic_base);
+ static const WHV_REGISTER_NAME dr_names[6] = {
+ WHvX64RegisterDr0, WHvX64RegisterDr1, WHvX64RegisterDr2,
+ WHvX64RegisterDr3, WHvX64RegisterDr6, WHvX64RegisterDr7,
+ };
+ WHV_REGISTER_VALUE dr_vals[6] = {
+ { .Reg64 = env->dr[0] }, { .Reg64 = env->dr[1] },
+ { .Reg64 = env->dr[2] }, { .Reg64 = env->dr[3] },
+ { .Reg64 = env->dr[6] }, { .Reg64 = env->dr[7] },
+ };
+ whp_dispatch.WHvSetVirtualProcessorRegisters(
+ whpx->partition, cpu->cpu_index, dr_names, 6, dr_vals);
+
+ WHV_REGISTER_VALUE v = {};
+ v.Reg64 = env->tsc_aux;
+ whpx_set_reg_optional(cpu, WHvX64RegisterTscAux, v);
+
+ /* Do not write WHvX64RegisterTscAdjust after WHvX64RegisterTsc,
+ * as MSR_IA32_TSC_ADJUST shifts the vCPU TSC offset in Hyper-V. */
+ if (env->spec_ctrl) {
+ v.Reg64 = env->spec_ctrl;
+ whpx_set_reg_optional(cpu, WHvX64RegisterSpecCtrl, v);
+ }
+ if (env->mtrr_deftype) {
+ v.Reg64 = env->mtrr_deftype;
+ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrDefType, v);
+ for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
+ v.Reg64 = env->mtrr_var[i].base;
+ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysBase0 + i, v);
+ v.Reg64 = env->mtrr_var[i].mask;
+ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysMask0 + i, v);
+ }
+ for (i = 0; i < 11; i++) {
+ v.Reg64 = env->mtrr_fixed[i];
+ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrFix64k00000 + i, v);
+ }
+ }
+
+ if (!whpx_irqchip_in_kernel()) {
+ WHV_REGISTER_VALUE apic_base = {};
+ apic_base.Reg64 = cpu_get_apic_base(X86_CPU(cpu)->apic_state);
+ whpx_set_reg(cpu, WHvX64RegisterApicBase, apic_base);
+ }
+
+ if (!whpx->tsc_deadline_refused) {
+ WHV_REGISTER_VALUE tsc_deadline = { .Reg64 = env->tsc_deadline };
+ whpx_set_reg(cpu, WHvX64RegisterTscDeadline, tsc_deadline);
+ }
+
+ if (whpx_irqchip_in_kernel()) {
+ WHV_REGISTER_VALUE activity = {};
+ whpx_get_reg_optional(cpu, WHvRegisterInternalActivityState, &activity);
+ activity.InternalActivity.StartupSuspend =
+ (env->mp_state == WHPX_MP_STATE_UNINITIALIZED);
+ activity.InternalActivity.HaltSuspend = 0;
+ whpx_set_reg(cpu, WHvRegisterInternalActivityState, activity);
+ }
+
+ {
+ WHV_REGISTER_VALUE intr_state = {};
+ intr_state.InterruptState.InterruptShadow =
+ !!(env->hflags & HF_INHIBIT_IRQ_MASK);
+ whpx_set_reg_optional(cpu, WHvRegisterInterruptState, intr_state);
+ }
}
}
@@ -940,6 +1016,9 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level)
}
if (!env->tsc_valid) {
+ if (!runstate_is_running() && whp_dispatch.WHvSuspendPartitionTime) {
+ whp_dispatch.WHvSuspendPartitionTime(whpx->partition);
+ }
whpx_get_tsc(cpu);
env->tsc_valid = !runstate_is_running();
}
@@ -1016,10 +1095,9 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level)
*/
whpx_get_xcrs(cpu);
- if (whpx_is_xsave_enabled(cpu)) {
- whpx_get_xsave_state(cpu);
+ if (!whpx_is_xsave_enabled(cpu) || whpx_get_xsave_state(cpu) != 0) {
+ whpx_get_legacy_fp_registers(cpu, level);
}
- whpx_get_legacy_fp_registers(cpu, level);
/* MSRs */
assert(whpx_register_names[idx] == WHvX64RegisterEfer);
@@ -1051,11 +1129,83 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level)
assert(idx == RTL_NUMBER_OF(whpx_register_names));
+ if (level >= WHPX_LEVEL_FULL_STATE) {
+ static const WHV_REGISTER_NAME dr_names[6] = {
+ WHvX64RegisterDr0, WHvX64RegisterDr1, WHvX64RegisterDr2,
+ WHvX64RegisterDr3, WHvX64RegisterDr6, WHvX64RegisterDr7,
+ };
+ WHV_REGISTER_VALUE dr_vals[6] = {};
+ if (SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorRegisters(
+ whpx->partition, cpu->cpu_index, dr_names, 6, dr_vals))) {
+ env->dr[0] = dr_vals[0].Reg64;
+ env->dr[1] = dr_vals[1].Reg64;
+ env->dr[2] = dr_vals[2].Reg64;
+ env->dr[3] = dr_vals[3].Reg64;
+ env->dr[6] = dr_vals[4].Reg64;
+ env->dr[7] = dr_vals[5].Reg64;
+ }
+
+ WHV_REGISTER_VALUE v = {};
+ if (whpx_get_reg_optional(cpu, WHvX64RegisterTscAux, &v)) {
+ env->tsc_aux = v.Reg64;
+ }
+ if (whpx_get_reg_optional(cpu, WHvX64RegisterTscAdjust, &v)) {
+ env->tsc_adjust = v.Reg64;
+ }
+ if (whpx_get_reg_optional(cpu, WHvX64RegisterSpecCtrl, &v)) {
+ env->spec_ctrl = v.Reg64;
+ }
+ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrDefType, &v)) {
+ env->mtrr_deftype = v.Reg64;
+ for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
+ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysBase0 + i, &v)) {
+ env->mtrr_var[i].base = v.Reg64;
+ }
+ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysMask0 + i, &v)) {
+ env->mtrr_var[i].mask = v.Reg64;
+ }
+ }
+ for (i = 0; i < 11; i++) {
+ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrFix64k00000 + i, &v)) {
+ env->mtrr_fixed[i] = v.Reg64;
+ }
+ }
+ }
+ if (!whpx->tsc_deadline_refused &&
+ whpx_get_reg_optional(cpu, WHvX64RegisterTscDeadline, &v)) {
+ env->tsc_deadline = v.Reg64;
+ }
+ if (whpx_irqchip_in_kernel() &&
+ whpx_get_reg_optional(cpu, WHvRegisterInternalActivityState, &v)) {
+ if (v.InternalActivity.StartupSuspend) {
+ env->mp_state = WHPX_MP_STATE_UNINITIALIZED;
+ } else if (v.InternalActivity.HaltSuspend) {
+ env->mp_state = WHPX_MP_STATE_HALTED;
+ } else {
+ env->mp_state = WHPX_MP_STATE_RUNNABLE;
+ }
+ }
+ if (whpx_get_reg_optional(cpu, WHvRegisterPendingInterruption, &v) &&
+ v.PendingInterruption.InterruptionPending) {
+ warn_report("WHPX: vCPU %d saved with PendingInterruption type=%u vec=%u",
+ cpu->cpu_index,
+ (unsigned)v.PendingInterruption.InterruptionType,
+ (unsigned)v.PendingInterruption.InterruptionVector);
+ }
+ }
+
if (whpx_irqchip_in_kernel()) {
whpx_apic_get(x86_cpu->apic_state);
}
x86_update_hflags(env);
+ if (level >= WHPX_LEVEL_FULL_STATE) {
+ WHV_REGISTER_VALUE intr_state = {};
+ if (whpx_get_reg_optional(cpu, WHvRegisterInterruptState, &intr_state) &&
+ intr_state.InterruptState.InterruptShadow) {
+ env->hflags |= HF_INHIBIT_IRQ_MASK;
+ }
+ }
}
static int emulate_instruction(CPUState *cpu, const uint8_t *insn_bytes, size_t insn_len)
@@ -2515,8 +2665,12 @@ int whpx_vcpu_run(CPUState *cpu)
do {
if (cpu->vcpu_dirty) {
- whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE);
+ WHPXStateLevel level = vcpu->loadvm_pending
+ ? WHPX_LEVEL_FULL_STATE
+ : WHPX_LEVEL_RUNTIME_STATE;
+ whpx_set_registers(cpu, level);
cpu->vcpu_dirty = false;
+ vcpu->loadvm_pending = false;
}
if (exclusive_step_mode == WHPX_STEP_NONE) {
@@ -2982,6 +3136,28 @@ int whpx_vcpu_run(CPUState *cpu)
*/
static Error *whpx_migration_blocker;
+static NotifierWithReturn whpx_migration_notifier;
+static bool whpx_migration_notifier_added;
+
+static int whpx_migration_setup_notifier(NotifierWithReturn *notify,
+ MigrationEvent *e, Error **errp)
+{
+ if (e->type != MIG_EVENT_SETUP) {
+ return 0;
+ }
+ if (runstate_is_running()) {
+ error_setg(errp,
+ "WHPX: live migration is not supported while the VM is running; stop the VM first");
+ return -1;
+ }
+ if (migrate_mode() != MIG_MODE_NORMAL ||
+ migrate_postcopy_ram() || migrate_background_snapshot()) {
+ error_setg(errp,
+ "WHPX: only stopped-VM normal file suspend is supported");
+ return -1;
+ }
+ return 0;
+}
static void whpx_cpu_update_state(void *opaque, bool running, RunState state)
{
@@ -3006,20 +3182,27 @@ int whpx_init_vcpu(CPUState *cpu)
UINT64 freq = 0;
int ret;
- /* Add migration blockers for all unsupported features of the
- * Windows Hypervisor Platform
+ /*
+ * WHPX lacks dirty-page tracking, so live migration and non-normal modes
+ * remain blocked. Only stopped-VM normal file suspend (stop -> migrate ->
+ * quit) is permitted and enforced both at migration entry and on setup.
*/
- if (whpx_migration_blocker == NULL) {
+ if (!whpx_migration_blocker) {
+ unsigned non_normal_modes = (BIT(MIG_MODE__MAX) - 1) &
+ ~BIT(MIG_MODE_NORMAL);
error_setg(&whpx_migration_blocker,
- "State blocked due to missing dirty memory tracking support,"
- "And some system register/state save-restore ");
-
- if (migrate_add_blocker(&whpx_migration_blocker, &local_error) < 0) {
- error_report_err(local_error);
- ret = -EINVAL;
- goto error;
+ "WHPX: migration mode is not supported (only stopped-VM normal file suspend)");
+ migrate_add_blocker_modes(&whpx_migration_blocker, non_normal_modes,
+ &local_error);
+ if (local_error) {
+ error_propagate(&error_fatal, local_error);
}
}
+ if (!whpx_migration_notifier_added) {
+ migration_add_notifier(&whpx_migration_notifier,
+ whpx_migration_setup_notifier);
+ whpx_migration_notifier_added = true;
+ }
vcpu = g_new0(AccelCPUState, 1);
diff --git a/target/i386/whpx/whpx-apic.c b/target/i386/whpx/whpx-apic.c
index 547b1cd2671bb6b8fb5a826ab5af5ef89b0997be..75ecf48feb48b448cb39d5878d9bb86b0fa5746a 100644
--- a/target/i386/whpx/whpx-apic.c
+++ b/target/i386/whpx/whpx-apic.c
@@ -35,13 +35,17 @@ static void whpx_put_apic_state(APICCommonState *s,
memset(kapic, 0, sizeof(*kapic));
if (s->apicbase & MSR_IA32_APICBASE_EXTD) {
kapic->fields[0x2].data = s->initial_apic_id;
+ kapic->fields[0xd].data =
+ ((s->initial_apic_id & ~0xfu) << 12) |
+ (1u << (s->initial_apic_id & 0xfu));
+ kapic->fields[0xe].data = 0;
} else {
kapic->fields[0x2].data = s->id << 24;
+ kapic->fields[0xd].data = s->log_dest << 24;
+ kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff;
}
kapic->fields[0x3].data = s->version | ((APIC_LVT_NB - 1) << 16);
kapic->fields[0x8].data = s->tpr;
- kapic->fields[0xd].data = s->log_dest << 24;
- kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff;
kapic->fields[0xf].data = s->spurious_vec;
for (i = 0; i < 8; i++) {
kapic->fields[0x10 + i].data = s->isr[i];
@@ -212,10 +216,18 @@ static void whpx_apic_put(CPUState *cs, run_on_cpu_data data)
&kapic,
sizeof(kapic));
if (FAILED(hr)) {
+ struct whpx_lapic_state cur = {};
+ whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2(
+ whpx_global.partition, cs->cpu_index, &cur, sizeof(cur), NULL);
fprintf(stderr,
- "WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n",
- hr);
-
+ "WHvSetVirtualProcessorInterruptControllerState2 failed: %08lx cpu=%d apicbase=0x%llx\n",
+ hr, cs->cpu_index, (unsigned long long)s->apicbase);
+ for (int idx = 0; idx < 256; idx++) {
+ if (kapic.fields[idx].data || cur.fields[idx].data) {
+ fprintf(stderr, " lapic[0x%02x]: put=0x%08x cur=0x%08x\n",
+ idx, kapic.fields[idx].data, cur.fields[idx].data);
+ }
+ }
abort();
}
}
@@ -224,8 +236,17 @@ void whpx_apic_get(APICCommonState *s)
{
CPUState *cpu = CPU(s->cpu);
struct whpx_lapic_state kapic;
+ WHV_REGISTER_NAME base_reg = WHvX64RegisterApicBase;
+ WHV_REGISTER_VALUE base_val = {};
+ HRESULT hr;
+
+ hr = whp_dispatch.WHvGetVirtualProcessorRegisters(
+ whpx_global.partition, cpu->cpu_index, &base_reg, 1, &base_val);
+ if (SUCCEEDED(hr)) {
+ s->apicbase = base_val.Reg64;
+ }
- HRESULT hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2(
+ hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2(
whpx_global.partition,
cpu->cpu_index,
&kapic,
@@ -233,7 +254,7 @@ void whpx_apic_get(APICCommonState *s)
NULL);
if (FAILED(hr)) {
fprintf(stderr,
- "WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n",
+ "WHvGetVirtualProcessorInterruptControllerState2 failed: %08lx\n",
hr);
abort();
@@ -242,6 +263,17 @@ void whpx_apic_get(APICCommonState *s)
whpx_get_apic_state(s, &kapic);
}
+static void do_whpx_apic_get(CPUState *cs, run_on_cpu_data data)
+{
+ APICCommonState *s = data.host_ptr;
+ whpx_apic_get(s);
+}
+
+static void whpx_apic_pre_save(APICCommonState *s)
+{
+ run_on_cpu(CPU(s->cpu), do_whpx_apic_get, RUN_ON_CPU_HOST_PTR(s));
+}
+
static void whpx_apic_post_load(APICCommonState *s)
{
run_on_cpu(CPU(s->cpu), whpx_apic_put, RUN_ON_CPU_HOST_PTR(s));
@@ -379,6 +411,7 @@ static void whpx_apic_class_init(ObjectClass *klass, const void *data)
k->set_base = apic_set_base;
k->set_tpr = whpx_apic_set_tpr;
k->get_tpr = whpx_apic_get_tpr;
+ k->pre_save = whpx_apic_pre_save;
k->post_load = whpx_apic_post_load;
k->vapic_base_update = whpx_apic_vapic_base_update;
k->external_nmi = whpx_apic_external_nmi;
+727
View File
@@ -0,0 +1,727 @@
diff --git a/include/io/channel.h b/include/io/channel.h
index 834ba7c30986dd48686705da5aa7197eb228cef7..87f751308d6fdd7b87e31be44fca07fe93501aba 100644
--- a/include/io/channel.h
+++ b/include/io/channel.h
@@ -146,12 +146,12 @@ struct QIOChannelClass {
ssize_t (*io_pwritev)(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp);
ssize_t (*io_preadv)(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp);
int (*io_shutdown)(QIOChannel *ioc,
QIOChannelShutdown how,
@@ -160,8 +160,8 @@ struct QIOChannelClass {
bool enabled);
void (*io_set_delay)(QIOChannel *ioc,
bool enabled);
- off_t (*io_seek)(QIOChannel *ioc,
- off_t offset,
+ int64_t (*io_seek)(QIOChannel *ioc,
+ int64_t offset,
int whence,
Error **errp);
void (*io_set_aio_fd_handler)(QIOChannel *ioc,
@@ -579,7 +579,7 @@ int qio_channel_close(QIOChannel *ioc,
*
*/
ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
- size_t niov, off_t offset, Error **errp);
+ size_t niov, int64_t offset, Error **errp);
/**
* qio_channel_pwrite
@@ -595,7 +595,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
*
*/
ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
- off_t offset, Error **errp);
+ int64_t offset, Error **errp);
/**
* qio_channel_pwritev_all:
@@ -614,7 +614,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp);
/**
@@ -635,7 +635,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
const void *buf,
size_t buflen,
- off_t offset,
+ int64_t offset,
Error **errp);
/**
@@ -656,7 +656,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
*
*/
ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
- size_t niov, off_t offset, Error **errp);
+ size_t niov, int64_t offset, Error **errp);
/**
* qio_channel_pread
@@ -672,7 +672,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
*
*/
ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
- off_t offset, Error **errp);
+ int64_t offset, Error **errp);
/**
* qio_channel_preadv_all_eof:
@@ -695,7 +695,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp);
/**
@@ -717,7 +717,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp);
/**
@@ -741,7 +741,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
void *buf,
size_t buflen,
- off_t offset,
+ int64_t offset,
Error **errp);
/**
@@ -763,7 +763,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc,
void *buf,
size_t buflen,
- off_t offset,
+ int64_t offset,
Error **errp);
/**
@@ -861,10 +861,10 @@ void qio_channel_set_cork(QIOChannel *ioc,
* Not all implementations will support this facility,
* so may report an error.
*
- * Returns: the new position on success, (off_t)-1 on failure
+ * Returns: the new position on success, (int64_t)-1 on failure
*/
-off_t qio_channel_io_seek(QIOChannel *ioc,
- off_t offset,
+int64_t qio_channel_io_seek(QIOChannel *ioc,
+ int64_t offset,
int whence,
Error **errp);
diff --git a/include/system/ramblock.h b/include/system/ramblock.h
index 24c970d393e9cc3463fa46a9bcace7937e50fde4..981470f59d569181f859718942ecb9a855f33078 100644
--- a/include/system/ramblock.h
+++ b/include/system/ramblock.h
@@ -68,7 +68,7 @@ struct RAMBlock {
* offset in the file pages belonging to this ramblock are saved,
* used only during migration to a file.
*/
- off_t bitmap_offset;
+ int64_t bitmap_offset;
uint64_t pages_offset;
/* Bitmap of already received pages. Only used on destination side. */
diff --git a/io/channel-buffer.c b/io/channel-buffer.c
index 189fa67ac21df8a8dff868a477a8021873bd22c7..873e80faeb8a8496ddb6fb0743a17ad599a60654 100644
--- a/io/channel-buffer.c
+++ b/io/channel-buffer.c
@@ -124,8 +124,8 @@ static int qio_channel_buffer_set_blocking(QIOChannel *ioc G_GNUC_UNUSED,
}
-static off_t qio_channel_buffer_seek(QIOChannel *ioc,
- off_t offset,
+static int64_t qio_channel_buffer_seek(QIOChannel *ioc,
+ int64_t offset,
int whence,
Error **errp)
{
diff --git a/io/channel-file.c b/io/channel-file.c
index 2487adaea2ad7108310b94910153a4ffbf6eb094..2fb80f90e1c6251c1b2b493e8ebb6566b6b0b769 100644
--- a/io/channel-file.c
+++ b/io/channel-file.c
@@ -27,6 +27,9 @@
#include "qemu/module.h"
#include "qemu/sockets.h"
#include "trace.h"
+#ifdef WIN32
+#include <winioctl.h>
+#endif
QIOChannelFile *
qio_channel_file_new_fd(int fd)
@@ -42,7 +45,7 @@ qio_channel_file_new_fd(int fd)
ioc->fd = fd;
- if (lseek(fd, 0, SEEK_CUR) != (off_t)-1) {
+ if (lseek(fd, 0, SEEK_CUR) != (int64_t)-1) {
qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE);
}
@@ -74,6 +77,9 @@ qio_channel_file_new_path(const char *path,
ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE));
+#ifdef O_BINARY
+ flags |= O_BINARY;
+#endif
if (flags & O_CREAT) {
ioc->fd = qemu_create(path, flags & ~O_CREAT, mode, errp);
} else {
@@ -84,9 +90,18 @@ qio_channel_file_new_path(const char *path,
return NULL;
}
- if (lseek(ioc->fd, 0, SEEK_CUR) != (off_t)-1) {
+ if (lseek(ioc->fd, 0, SEEK_CUR) != (int64_t)-1) {
qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE);
}
+#ifdef WIN32
+ if (flags & O_CREAT) {
+ HANDLE h = (HANDLE)_get_osfhandle(ioc->fd);
+ if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_DISK) {
+ DWORD br = 0;
+ DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &br, NULL);
+ }
+ }
+#endif
trace_qio_channel_file_new_path(ioc, path, flags, mode, ioc->fd);
@@ -170,7 +185,7 @@ static ssize_t qio_channel_file_writev(QIOChannel *ioc,
static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
@@ -196,7 +211,7 @@ static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
@@ -216,6 +231,125 @@ static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
}
return ret;
}
+#elif defined(WIN32)
+static ssize_t qio_channel_file_prw_win32(QIOChannel *ioc,
+ const struct iovec *iov,
+ size_t niov,
+ int64_t offset,
+ bool is_write,
+ Error **errp)
+{
+ static const size_t max_chunk = 16U * 1024U * 1024U;
+ QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
+ HANDLE h = (HANDLE)_get_osfhandle(fioc->fd);
+ LARGE_INTEGER zero = { .QuadPart = 0 };
+ LARGE_INTEGER saved = { .QuadPart = 0 };
+ bool have_saved = false;
+ uint64_t cur;
+ ssize_t total = 0;
+ ssize_t ret = -1;
+ size_t i = 0;
+
+ if (offset < 0) {
+ error_setg_errno(errp, EINVAL, "Invalid negative offset for %s",
+ is_write ? "pwritev" : "preadv");
+ return -1;
+ }
+ if (h == INVALID_HANDLE_VALUE) {
+ error_setg_errno(errp, EBADF, "Invalid file handle for %s",
+ is_write ? "pwritev" : "preadv");
+ return -1;
+ }
+
+ cur = (uint64_t)offset;
+ have_saved = SetFilePointerEx(h, zero, &saved, FILE_CURRENT);
+
+ while (i < niov) {
+ uint8_t *base = (uint8_t *)iov[i].iov_base;
+ size_t run = iov[i].iov_len;
+ size_t j = i + 1;
+
+ while (j < niov && (uint8_t *)iov[j].iov_base == base + run &&
+ run < max_chunk && iov[j].iov_len <= max_chunk - run) {
+ run += iov[j].iov_len;
+ j++;
+ }
+ if (run == 0) {
+ i = j;
+ continue;
+ }
+
+ size_t done = 0;
+ while (done < run) {
+ DWORD chunk = (DWORD)MIN(run - done, max_chunk);
+ DWORD xfer = 0;
+ OVERLAPPED ov;
+ BOOL ok;
+
+ memset(&ov, 0, sizeof(ov));
+ ov.Offset = (DWORD)(cur & 0xFFFFFFFFULL);
+ ov.OffsetHigh = (DWORD)(cur >> 32);
+ if (is_write) {
+ ok = WriteFile(h, base + done, chunk, &xfer, &ov);
+ } else {
+ ok = ReadFile(h, base + done, chunk, &xfer, &ov);
+ }
+ if (!ok) {
+ DWORD err = GetLastError();
+ if (!is_write && err == ERROR_HANDLE_EOF) {
+ ret = total;
+ goto out;
+ }
+ error_setg_win32(errp, err,
+ is_write ? "Unable to pwritev to file"
+ : "Unable to preadv from file");
+ goto out;
+ }
+ if (xfer == 0) {
+ if (!is_write || total > 0) {
+ ret = total;
+ goto out;
+ }
+ error_setg_errno(errp, EIO, "pwritev made no progress");
+ goto out;
+ }
+ done += xfer;
+ cur += xfer;
+ total += xfer;
+ if (is_write && xfer < chunk) {
+ /* Preserve short-write semantics for caller retry/error handling. */
+ ret = total;
+ goto out;
+ }
+ }
+ i = j;
+ }
+
+ ret = total;
+out:
+ if (have_saved) {
+ SetFilePointerEx(h, saved, NULL, FILE_BEGIN);
+ }
+ return ret;
+}
+
+static ssize_t qio_channel_file_preadv(QIOChannel *ioc,
+ const struct iovec *iov,
+ size_t niov,
+ int64_t offset,
+ Error **errp)
+{
+ return qio_channel_file_prw_win32(ioc, iov, niov, offset, false, errp);
+}
+
+static ssize_t qio_channel_file_pwritev(QIOChannel *ioc,
+ const struct iovec *iov,
+ size_t niov,
+ int64_t offset,
+ Error **errp)
+{
+ return qio_channel_file_prw_win32(ioc, iov, niov, offset, true, errp);
+}
#endif /* CONFIG_PREADV */
static int qio_channel_file_set_blocking(QIOChannel *ioc,
@@ -223,7 +357,11 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc,
Error **errp)
{
#ifdef WIN32
- /* not implemented */
+ QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
+ if (enabled ||
+ GetFileType((HANDLE)_get_osfhandle(fioc->fd)) == FILE_TYPE_DISK) {
+ return 0;
+ }
error_setg_errno(errp, errno, "Failed to set FD nonblocking");
return -1;
#else
@@ -237,16 +375,20 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc,
}
-static off_t qio_channel_file_seek(QIOChannel *ioc,
- off_t offset,
+static int64_t qio_channel_file_seek(QIOChannel *ioc,
+ int64_t offset,
int whence,
Error **errp)
{
QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);
- off_t ret;
+ int64_t ret;
+#ifdef WIN32
+ ret = (int64_t)_lseeki64(fioc->fd, (int64_t)offset, whence);
+#else
ret = lseek(fioc->fd, offset, whence);
- if (ret == (off_t)-1) {
+#endif
+ if (ret == (int64_t)-1) {
error_setg_errno(errp, errno,
"Unable to seek to offset %lld whence %d in file",
(long long int)offset, whence);
@@ -314,7 +456,7 @@ static void qio_channel_file_class_init(ObjectClass *klass,
ioc_klass->io_writev = qio_channel_file_writev;
ioc_klass->io_readv = qio_channel_file_readv;
ioc_klass->io_set_blocking = qio_channel_file_set_blocking;
-#ifdef CONFIG_PREADV
+#if defined(CONFIG_PREADV) || defined(WIN32)
ioc_klass->io_pwritev = qio_channel_file_pwritev;
ioc_klass->io_preadv = qio_channel_file_preadv;
#endif
diff --git a/io/channel-null.c b/io/channel-null.c
index 49f1c80a54e1337aa39010ef39a5ea5de4c5392f..2032d26b3c14a28fc36aedc8a3f0248a4701abb9 100644
--- a/io/channel-null.c
+++ b/io/channel-null.c
@@ -105,9 +105,9 @@ qio_channel_null_set_blocking(QIOChannel *ioc G_GNUC_UNUSED,
}
-static off_t
+static int64_t
qio_channel_null_seek(QIOChannel *ioc G_GNUC_UNUSED,
- off_t offset G_GNUC_UNUSED,
+ int64_t offset G_GNUC_UNUSED,
int whence G_GNUC_UNUSED,
Error **errp G_GNUC_UNUSED)
{
diff --git a/io/channel.c b/io/channel.c
index 620256f310dbeb060113e71055246ca29431d13d..03d721ec0d699d7c9bcbf2866881d53d7e6b25c0 100644
--- a/io/channel.c
+++ b/io/channel.c
@@ -450,7 +450,7 @@ GSource *qio_channel_add_watch_source(QIOChannel *ioc,
ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
- size_t niov, off_t offset, Error **errp)
+ size_t niov, int64_t offset, Error **errp)
{
QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc);
@@ -468,7 +468,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov,
}
ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
- off_t offset, Error **errp)
+ int64_t offset, Error **errp)
{
struct iovec iov = {
.iov_base = buf,
@@ -481,7 +481,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp)
{
int ret = -1;
@@ -519,7 +519,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
const void *buf,
size_t buflen,
- off_t offset,
+ int64_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = (char *)buf, .iov_len = buflen };
@@ -527,7 +527,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc,
}
ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
- size_t niov, off_t offset, Error **errp)
+ size_t niov, int64_t offset, Error **errp)
{
QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc);
@@ -545,7 +545,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov,
}
ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
- off_t offset, Error **errp)
+ int64_t offset, Error **errp)
{
struct iovec iov = {
.iov_base = buf,
@@ -558,7 +558,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen,
int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp)
{
int ret = -1;
@@ -609,7 +609,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp)
{
int ret = qio_channel_preadv_all_eof(ioc, iov, niov, offset, errp);
@@ -629,7 +629,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
void *buf,
size_t buflen,
- off_t offset,
+ int64_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = buf, .iov_len = buflen };
@@ -639,7 +639,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc,
int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc,
void *buf,
size_t buflen,
- off_t offset,
+ int64_t offset,
Error **errp)
{
struct iovec iov = { .iov_base = buf, .iov_len = buflen };
@@ -696,8 +696,8 @@ int qio_channel_get_peerpid(QIOChannel *ioc,
return 0;
}
-off_t qio_channel_io_seek(QIOChannel *ioc,
- off_t offset,
+int64_t qio_channel_io_seek(QIOChannel *ioc,
+ int64_t offset,
int whence,
Error **errp)
{
diff --git a/migration/channel-block.c b/migration/channel-block.c
index 9cf383d4b57728b2561dbb45afd44c72df15061b..8a0893fb7e4d4cb9e5e91d1418e99674f4562c23 100644
--- a/migration/channel-block.c
+++ b/migration/channel-block.c
@@ -101,7 +101,7 @@ static ssize_t
qio_channel_block_preadv(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp)
{
QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc);
@@ -122,7 +122,7 @@ static ssize_t
qio_channel_block_pwritev(QIOChannel *ioc,
const struct iovec *iov,
size_t niov,
- off_t offset,
+ int64_t offset,
Error **errp)
{
QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc);
@@ -152,9 +152,9 @@ qio_channel_block_set_blocking(QIOChannel *ioc,
}
-static off_t
+static int64_t
qio_channel_block_seek(QIOChannel *ioc,
- off_t offset,
+ int64_t offset,
int whence,
Error **errp)
{
@@ -169,7 +169,7 @@ qio_channel_block_seek(QIOChannel *ioc,
break;
case SEEK_END:
error_setg(errp, "Size of VMstate region is unknown");
- return (off_t)-1;
+ return (int64_t)-1;
default:
g_assert_not_reached();
}
diff --git a/migration/channel-block.h b/migration/channel-block.h
index 31673824e6971398b73f55cfb36a521ca0d91791..b2f6768f6ce5a058dc0a082ccd4d0d9297befd3f 100644
--- a/migration/channel-block.h
+++ b/migration/channel-block.h
@@ -39,7 +39,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelBlock, QIO_CHANNEL_BLOCK)
struct QIOChannelBlock {
QIOChannel parent;
BlockDriverState *bs;
- off_t offset;
+ int64_t offset;
};
diff --git a/migration/file.c b/migration/file.c
index 8ba1de2006eed5a643b7394b9bc4c83cb8d9b4af..5419455d6d314e7529c20116b274d61ce1e38e99 100644
--- a/migration/file.c
+++ b/migration/file.c
@@ -108,7 +108,11 @@ QIOChannel *file_connect_outgoing(MigrationState *s,
goto out;
}
+#ifdef WIN32
+ if (_chsize_s(fioc->fd, (int64_t)offset) != 0) {
+#else
if (ftruncate(fioc->fd, offset)) {
+#endif
error_setg_errno(errp, errno,
"failed to truncate migration file to offset %" PRIx64,
offset);
diff --git a/migration/multifd.h b/migration/multifd.h
index fbc35702b062fdc3213ce92baed35994f5967c2b..2ce94f07403fe1cbe1655728e13c58eeb53dbbe5 100644
--- a/migration/multifd.h
+++ b/migration/multifd.h
@@ -133,7 +133,7 @@ struct MultiFDRecvData {
void *opaque;
size_t size;
/* for preadv */
- off_t file_offset;
+ int64_t file_offset;
};
typedef struct {
diff --git a/migration/qemu-file.c b/migration/qemu-file.c
index df3f96fb24005d0fcf397bf8035b460a04eb2490..4aef4856599e83c6bb72012dbea3f163ab838add 100644
--- a/migration/qemu-file.c
+++ b/migration/qemu-file.c
@@ -532,7 +532,7 @@ void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size)
}
void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
- off_t pos)
+ int64_t pos)
{
Error *err = NULL;
@@ -550,7 +550,7 @@ void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
}
-size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos,
+size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos,
Error **errp)
{
if (f->last_error) {
@@ -566,10 +566,10 @@ size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos,
return buflen;
}
-void qemu_set_offset(QEMUFile *f, off_t off, int whence)
+void qemu_set_offset(QEMUFile *f, int64_t off, int whence)
{
Error *err = NULL;
- off_t ret;
+ int64_t ret;
if (qemu_file_is_writable(f)) {
qemu_fflush(f);
@@ -580,20 +580,20 @@ void qemu_set_offset(QEMUFile *f, off_t off, int whence)
}
ret = qio_channel_io_seek(f->ioc, off, whence, &err);
- if (ret == (off_t)-1) {
+ if (ret == (int64_t)-1) {
qemu_file_set_error_obj(f, -EIO, err);
}
}
-off_t qemu_get_offset(QEMUFile *f)
+int64_t qemu_get_offset(QEMUFile *f)
{
Error *err = NULL;
- off_t ret;
+ int64_t ret;
qemu_fflush(f);
ret = qio_channel_io_seek(f->ioc, 0, SEEK_CUR, &err);
- if (ret == (off_t)-1) {
+ if (ret == (int64_t)-1) {
qemu_file_set_error_obj(f, -EIO, err);
}
return ret;
diff --git a/migration/qemu-file.h b/migration/qemu-file.h
index 966766788ddfb11e08eb8b059d43c69a66260818..c5d2a984611da615e8561866af954f6e778780bf 100644
--- a/migration/qemu-file.h
+++ b/migration/qemu-file.h
@@ -72,11 +72,11 @@ QEMUFile *qemu_file_get_return_path(QEMUFile *f);
int qemu_fflush(QEMUFile *f);
bool qemu_file_set_blocking(QEMUFile *f, bool block, Error **errp);
int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size);
-void qemu_set_offset(QEMUFile *f, off_t off, int whence);
-off_t qemu_get_offset(QEMUFile *f);
+void qemu_set_offset(QEMUFile *f, int64_t off, int whence);
+int64_t qemu_get_offset(QEMUFile *f);
void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen,
- off_t pos);
-size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos,
+ int64_t pos);
+size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos,
Error **errp);
QIOChannel *qemu_file_get_ioc(QEMUFile *file);
diff --git a/migration/ram.c b/migration/ram.c
index e6db3bf523855ee1ea20e79495326979f00d3192..410cfa6a1c2bfe84308d19c36bd8a00157226581 100644
--- a/migration/ram.c
+++ b/migration/ram.c
@@ -1010,7 +1010,7 @@ static uint64_t physical_memory_sync_dirty_bitmap(RAMBlock *rb,
unsigned long *dest = rb->bmap;
/* start address and length is aligned at the start of a word? */
- if (((word * BITS_PER_LONG) << TARGET_PAGE_BITS) ==
+ if ((((ram_addr_t)word * BITS_PER_LONG) << TARGET_PAGE_BITS) ==
(start + rb->offset) &&
!(length & ((BITS_PER_LONG << TARGET_PAGE_BITS) - 1))) {
int k;
@@ -4137,8 +4137,8 @@ static bool handle_zero_mapped_ram(RAMBlock *block, unsigned long from_bit_idx,
return true;
}
- size = TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx);
- offset = from_bit_idx << TARGET_PAGE_BITS;
+ size = (size_t)TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx);
+ offset = ((ram_addr_t)from_bit_idx) << TARGET_PAGE_BITS;
host = host_from_ram_block_offset(block, offset);
if (!host) {
error_setg(errp, "zero page outside of ramblock %s range",
@@ -4172,8 +4172,8 @@ static bool read_ramblock_mapped_ram(QEMUFile *f, RAMBlock *block,
/* Non-zero pages */
clear_bit_idx = find_next_zero_bit(bitmap, num_pages, set_bit_idx + 1);
- unread = TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx);
- offset = set_bit_idx << TARGET_PAGE_BITS;
+ unread = (size_t)TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx);
+ offset = ((ram_addr_t)set_bit_idx) << TARGET_PAGE_BITS;
while (unread > 0) {
host = host_from_ram_block_offset(block, offset);
-28
View File
@@ -1,28 +0,0 @@
diff --git a/Cargo.lock b/Cargo.lock
index 106e75e..01bf052 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "metal2vulkan"
version = "0.2.0"
+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"ash",
"metal2vulkan-air",
@@ -223,6 +224,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-air"
version = "0.2.0"
+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"sha2 0.11.1",
]
@@ -230,6 +232,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-runtime"
version = "0.2.0"
+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"ash",
"libc",
File diff suppressed because it is too large. Load diff
+15 -12
View File
@@ -1,16 +1,19 @@
# Patch queue, in the order the patches are applied (see patches/README.md).
# One patch per line: <target> <file>.
# Targets are "reims-vgpu", "vendor/qemu", and "reims-util".
# Targets are "reims-vgpu", "vendor/qemu", "reims-util", and "metal2vulkan".
# CI (build-runtime.yml via scripts/apply-patch-series.ps1) and
# scripts/pack-runtime.ps1 both read this file; add or retire patches here.
reims-vgpu reims-vgpu-cargo-lock.patch
reims-vgpu reims-vgpu-win32-unicode-input.patch
reims-vgpu reims-vgpu-display-fixed-mode.patch
reims-vgpu reims-ctl-win32-random-bytes.patch
reims-vgpu reims-ctl-virtio-discard-iothread.patch
reims-vgpu reims-ctl-qcow2-l2-cache.patch
reims-util reims-util-parallel-offline-download.patch
vendor/qemu qemu-whpx-win10-compat.patch
vendor/qemu qemu-whpx-win10-startup-ipis.patch
vendor/qemu qemu-whpx-nested-virt-nonfatal.patch
vendor/qemu qemu-win32-coroutine-fiber-commit.patch
reims-vgpu reims-vgpu-win32-unicode-input.patch
reims-vgpu reims-vgpu-display-fixed-mode.patch
reims-vgpu reims-ctl-win32-random-bytes.patch
reims-vgpu reims-ctl-virtio-discard-iothread.patch
reims-vgpu reims-ctl-qcow2-l2-cache.patch
reims-vgpu reims-vgpu-snapshot-replay.patch
reims-util reims-util-parallel-offline-download.patch
metal2vulkan metal2vulkan-snapshot-replay.patch
vendor/qemu qemu-whpx-win10-compat.patch
vendor/qemu qemu-whpx-win10-startup-ipis.patch
vendor/qemu qemu-whpx-nested-virt-nonfatal.patch
vendor/qemu qemu-win32-coroutine-fiber-commit.patch
vendor/qemu qemu-win32-mapped-ram-io.patch
vendor/qemu qemu-intel-whpx-suspend.patch
+10 -5
View File
@@ -16,23 +16,25 @@
was really applied, AGENTS.md rule 5) and report merged or conflicting patches.
.EXAMPLE
pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -ResultFile patches.json
pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -Metal2VulkanRepo $env:RUNNER_TEMP\metal2vulkan -ResultFile patches.json
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ReimsRepo,
[string]$ResultFile = '',
[string]$UtilRepo = ''
[string]$UtilRepo = '',
[string]$Metal2VulkanRepo = ''
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$patchesDir = Join-Path $repoRoot 'patches'
$repositories = @{
'reims-vgpu' = $ReimsRepo
'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu'
'reims-util' = $UtilRepo
'reims-vgpu' = $ReimsRepo
'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu'
'reims-util' = $UtilRepo
'metal2vulkan' = $Metal2VulkanRepo
}
function Read-PatchSeries {
@@ -59,6 +61,9 @@ $series = @(Read-PatchSeries)
if (-not $UtilRepo -and $series.Target -contains 'reims-util') {
throw 'Pass -UtilRepo with a checkout at the reims-util revision pinned by reims-ctl.'
}
if (-not $Metal2VulkanRepo -and $series.Target -contains 'metal2vulkan') {
throw 'Pass -Metal2VulkanRepo with a checkout at the metal2vulkan revision pinned by reims-vgpu.'
}
foreach ($p in $series) {
$file = Join-Path $patchesDir $p.Name
+68 -18
View File
@@ -1,4 +1,4 @@
<#
<#
.SYNOPSIS
Pack a portable reims-vgpu runtime for Windows x64, its matching source
package, and SHA256SUMS.txt, ready to publish as a GitHub Release.
@@ -29,13 +29,14 @@
.EXAMPLE
pwsh -File scripts/pack-runtime.ps1 -Channel alpha
pwsh -File scripts/pack-runtime.ps1 -Patches reims-vgpu-cargo-lock.patch,qemu-whpx-win10-compat.patch
pwsh -File scripts/pack-runtime.ps1 -Patches reims-vgpu-snapshot-replay.patch,metal2vulkan-snapshot-replay.patch,qemu-whpx-win10-compat.patch
#>
[CmdletBinding(PositionalBinding = $false)]
param(
[string]$ReimsRepo = 'D:\DevTools\reims-vgpu',
[string]$UtilRepo = '',
[string]$CargoHome = 'D:\DevTools\cargo',
[string]$ReimsRepo = 'D:\DevTools\reims-vgpu',
[string]$UtilRepo = '',
[string]$Metal2VulkanRepo = '',
[string]$CargoHome = 'D:\DevTools\cargo',
[string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current',
[string]$Msys2 = 'D:\DevTools\msys64',
[string]$OutDir = 'D:\Data\reims-go\releases',
@@ -139,19 +140,35 @@ if (-not $utilTree) { throw "reims-util source at $utilCommit not found" }
$actualUtil = git -C $utilTree rev-parse HEAD
if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" }
# metal2vulkan's git rev as built (Cargo.lock in the build tree).
$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock')
if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.lock' }
$m2vCommit = $Matches[1]
# metal2vulkan's pinned commit (workspace Cargo.toml, falling back to Cargo.lock).
$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.toml')
if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') {
$m2vCommit = $Matches[1]
} else {
$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock')
if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' }
$m2vCommit = $Matches[1]
}
$m2vTree = if ($Metal2VulkanRepo) {
(Resolve-Path -LiteralPath $Metal2VulkanRepo).Path
} else {
Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' -ErrorAction SilentlyContinue |
ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } |
Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
}
if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found (pass -Metal2VulkanRepo or check $checkouts)" }
$actualM2v = (git -C $m2vTree rev-parse HEAD).Trim()
if ($LASTEXITCODE -ne 0 -or $actualM2v -ne $m2vCommit) { throw "metal2vulkan checkout must be at $m2vCommit (got $actualM2v)" }
$qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim()
$utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim()
# ── 2. Patches must equal the build tree's diffs ─────────────
$repositories = @{
'reims-vgpu' = $ReimsRepo
'vendor/qemu' = $qemuRepo
'reims-util' = $utilTree
'reims-vgpu' = $ReimsRepo
'vendor/qemu' = $qemuRepo
'reims-util' = $utilTree
'metal2vulkan' = $m2vTree
}
$series = @(foreach ($line in Get-Content -LiteralPath (Join-Path $patchesDir 'series.txt')) {
$t = $line.Trim()
@@ -257,6 +274,20 @@ foreach ($targetName in $byTarget.Keys) {
Write-Host "Expected patch stack diff --stat:`n$expStat"
throw "Patch stack ($(($group | ForEach-Object { $_.Name }) -join ', ')) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
# Also verify newly created (untracked) files added by patches byte-for-byte.
$addedFiles = @(& git -C $verifyDir ls-files --others --exclude-standard | Where-Object { $_ })
foreach ($rel in $addedFiles) {
$expPath = Join-Path $verifyDir ($rel -replace '/', '\')
$treePath = Join-Path $repo ($rel -replace '/', '\')
if (-not (Test-Path -LiteralPath $treePath -PathType Leaf)) {
throw "Patch stack expected new file $rel in $repo, but it is missing."
}
$expText = [IO.File]::ReadAllText($expPath).Replace("`r`n", "`n")
$treeText = [IO.File]::ReadAllText($treePath).Replace("`r`n", "`n")
if ($treeText -cne $expText) {
throw "New file $rel in $repo does not match the declared patch stack. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
}
} finally {
if (Test-Path -LiteralPath $verifyDir) { Remove-Item -Recurse -Force -LiteralPath $verifyDir }
}
@@ -273,8 +304,10 @@ $otherCtl = Get-Undeclared $ReimsRepo 'reims-vgpu' @('--ignore-submodules=all'
$otherQemu = Get-Undeclared $qemuRepo 'vendor/qemu' @('--untracked-files=no')
$utilStatusArgs = if ($UtilRepo) { '--untracked-files=all' } else { '--untracked-files=no' }
$otherUtil = Get-Undeclared $utilTree 'reims-util' @($utilStatusArgs)
if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count) {
throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil -join "`n")"
$m2vStatusArgs = if ($Metal2VulkanRepo) { '--untracked-files=all' } else { '--untracked-files=no' }
$otherM2v = Get-Undeclared $m2vTree 'metal2vulkan' @($m2vStatusArgs)
if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count -or $otherM2v.Count) {
throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil + $otherM2v -join "`n")"
}
$bundleName = "reims-runtime-win-x64-$id"
@@ -306,7 +339,7 @@ if (Test-Path -LiteralPath (Join-Path $patchesDir 'LICENSE')) {
Copy-Item -LiteralPath (Join-Path $patchesDir 'LICENSE') -Destination "$bundleDir\patches\LICENSE"
}
# The order the patches above were applied in (only those really applied).
Write-Utf8 "$bundleDir\patches\series.txt" ((($patchSpecs | ForEach-Object { '{0,-11} {1}' -f $_.Target, $_.Name }) -join "`n") + "`n")
Write-Utf8 "$bundleDir\patches\series.txt" ((($patchSpecs | ForEach-Object { '{0,-12} {1}' -f $_.Target, $_.Name }) -join "`n") + "`n")
$licenses = @{
'reims-vgpu-LICENSE.txt' = (Join-Path $ReimsRepo 'LICENSE')
'qemu-COPYING.txt' = (Join-Path $qemuRepo 'COPYING')
@@ -388,8 +421,6 @@ Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory |
Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } |
ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force }
$m2vTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' | ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found under $checkouts" }
Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))")
Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))")
foreach ($extra in @(
@@ -411,6 +442,23 @@ New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null
Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\"
Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt"
Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md"
$m2vBuildSteps = if ($byTarget.Contains('metal2vulkan')) {
$m2vDir = "metal2vulkan-$($m2vCommit.Substring(0, 7))"
$m2vApply = ($byTarget['metal2vulkan'] | ForEach-Object { " git -C $m2vDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n"
@"
Before running ``scripts/install-ctl.sh``, apply the ``metal2vulkan`` patches
and point Cargo at the patched checkout via ```$CARGO_HOME/config.toml``:
$m2vApply
cat >> "`${CARGO_HOME:-`$HOME/.cargo}/config.toml" <<EOF
[patch."https://github.com/steelbrain/metal2vulkan"]
metal2vulkan = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan" }
metal2vulkan-runtime = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan-runtime" }
EOF
"@
}
$utilBuildSteps = if ($byTarget.Contains('reims-util')) {
$utilDir = "reims-util-$($utilCommit.Substring(0, 7))"
$utilApply = ($byTarget['reims-util'] | ForEach-Object { " git -C $utilDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n"
@@ -447,7 +495,9 @@ $((($patchSpecs | Where-Object { $_.Target -eq 'reims-vgpu' } | ForEach-Object {
cd vendor/qemu
$((($patchSpecs | Where-Object { $_.Target -eq 'vendor/qemu' } | ForEach-Object { " git apply ../../../patches/$($_.Name)" }) -join "`n"))
(``patch -p1`` works too.) Then build as upstream documents (``scripts/install-ctl.sh``
(``patch -p1`` works too.)
$m2vBuildSteps
Then build as upstream documents (``scripts/install-ctl.sh``
in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2
packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources.
$utilBuildSteps