Merge pull request #185 from yxc0915/feat/win32-raw-partition-aio

feat(storage): Windows raw disk/partition in-place mode and disk cache policy
This commit is contained in:
Xiaochi You authored and GitHub committed 2026-12-05 12:35:33 +08:00
commit 7e1afcfd9b
31 files changed
+1247 -38

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "为 Windows Q35 虚拟机新增原生块设备直通模式(支持物理磁盘或分区就地挂载、`--disk-cache` 主机缓存策略配置,以及配合便携运行时新版 QEMU 的 Win32 原生 IOCP/WHPX/NVMe 性能优化)。",
"en": "Add Windows raw disk/partition in-place mounting and per-VM `--disk-cache` policy support, paired with the Win32 native IOCP AIO, WHPX doorbell/fast-MMIO, and NVMe runtime optimizations."
}
+2
View File
@@ -487,6 +487,7 @@ export const App: React.FC = () => {
const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : ''
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
const canSuspend = state?.can_suspend ?? false
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
@@ -1463,6 +1464,7 @@ export const App: React.FC = () => {
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)}
host={state.host}
fixedModeSupported={fixedModeSupported}
diskCacheSupported={diskCacheSupported}
optimizations={state.optimizations}
running={effectiveState === 'running'}
onCopy={copy}
+19 -3
View File
@@ -27,7 +27,7 @@ import {
} from '../lib/format'
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
import { useVMStats } from '../lib/vmStats'
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats, DiskCache } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
@@ -36,6 +36,7 @@ import { api } from '../wails'
import { formatAffinitySummary } from './AffinityDialog'
import { VMNetworkSettings } from './VMNetworkSettings'
import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk'
import { DiskCacheRow } from './vmSettings/diskCache'
import { KeymapSection, useKeymap } from './vmSettings/keymap'
import { useVMPluginSettings, VMPluginGroup } from './vmSettings/plugins'
import { DriveShareSection, SharedFolderSection, useDriveShares, useSharedFolders, WritableFolderDialog } from './vmSettings/sharing'
@@ -72,6 +73,7 @@ const FIELD_CAT: Record<Field, Cat> = {
displays: 'display',
borderless: 'display',
disk_controller: 'storage',
disk_cache: 'storage',
network: 'storage',
ssh_port: 'storage',
capture: 'input',
@@ -101,6 +103,7 @@ function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean {
case 'log_level':
case 'extra_args':
case 'audio_backend':
case 'disk_cache':
case 'guest_lang': return String(a ?? '').trim() === String(b ?? '').trim()
default: return a === b
}
@@ -117,6 +120,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
graphics: detail.graphics,
displays: detail.displays || 1,
disk_controller: detail.disk_controller,
disk_cache: (detail.disk_cache as DiskCache) || 'default',
resolution: detail.resolution,
borderless: detail.borderless,
capture: detail.capture,
@@ -140,6 +144,7 @@ interface Props {
stats?: VMStats | null
host: HostReport
fixedModeSupported?: boolean
diskCacheSupported?: boolean
optimizations?: Optimization[]
running: boolean
onCopy?: (text: string) => void
@@ -153,7 +158,7 @@ interface Props {
onSaved: () => void
}
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, fixedModeSupported = false, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => {
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, fixedModeSupported = false, diskCacheSupported = false, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
const base = useMemo(() => baseline(detail, host), [detail, host])
@@ -172,7 +177,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const smbios = useSMBIOS(detail, running)
const keymap = useKeymap(detail.name, running, cat === 'input')
const plugins = useVMPluginSettings(`${driverID}:${detail.name}`, setErr)
const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, running, stats, onError: setErr, onDiskChanged })
const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, diskPath: detail.disk, running, stats, onError: setErr, onDiskChanged })
const timezone = useGuestTimezone(driverID, detail.name, running, cat === 'general')
const display = useTargetDisplay({
locale, driverID, vm: detail.name, running, host, shown: cat === 'display', onToast,
@@ -681,6 +686,17 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
/>
}
/>
<DiskCacheRow
locale={locale}
value={(form.disk_cache as DiskCache) || 'default'}
dirty={dirty('disk_cache')}
supported={diskCacheSupported}
reason={tr('diskCacheRequiresRuntime')}
onReset={reset('disk_cache')}
resetLabel={tr('resetField')}
error={issueOf('disk_cache')}
onChange={(disk_cache) => set({ disk_cache })}
/>
<DiskMaintenanceRows locale={locale} running={running} state={disk} onCopy={onCopy} />
{host.defender_realtime_active && <DefenderExclusionRow locale={locale} dataRoot={host.data_root} onCopy={onCopy} onError={setErr} />}
</SetGroup>
+19 -10
View File
@@ -11,14 +11,20 @@ interface DiskOptions {
locale: Locale
driverID: string
vm: string
diskPath?: string
running: boolean
stats?: VMStats | null
onError: (message: string) => void
onDiskChanged?: () => void
}
function isWindowsRawDevicePath(disk?: string): boolean {
const s = (disk ?? '').trim().replace(/\//g, '\\')
return /^\\\\\.\\(physicaldrive|harddiskvolume|harddisk|volume\{)|^\\\\\?\\volume\{/i.test(s)
}
/** Resizing, compacting and optimizing the VM's disk, one at a time. */
export function useDiskMaintenance({ locale, driverID, vm, running, stats, onError, onDiskChanged }: DiskOptions) {
export function useDiskMaintenance({ locale, driverID, vm, diskPath, running, stats, onError, onDiskChanged }: DiskOptions) {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const activeVMNameRef = useRef(vm)
activeVMNameRef.current = vm
@@ -53,7 +59,10 @@ export function useDiskMaintenance({ locale, driverID, vm, running, stats, onErr
}
}
const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2'
const isRawDevice = isWindowsRawDevicePath(diskPath)
const resizeDisabled = running || isRawDevice
const resizeReason = isRawDevice ? tr('diskResizeRawDisabled') : tr('stopBeforeDiskOp')
const isQcow2 = !isRawDevice && (!stats?.disk_format || stats.disk_format === 'qcow2')
const diskRewriteBaseReason = running ? tr('stopBeforeDiskOp')
: (stats?.disk_snapshot_count ?? 0) > 0 ? tr('diskRewriteSnapshots')
: (stats?.disk_backing_depth ?? 0) > 0 ? tr('diskRewriteOverlay')
@@ -93,7 +102,7 @@ export function useDiskMaintenance({ locale, driverID, vm, running, stats, onErr
return {
resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2,
compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
resizeDisabled, resizeReason, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
}
}
@@ -104,16 +113,16 @@ interface RowsProps {
onCopy?: (text: string) => void
}
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, state, onCopy }) => {
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running: _running, state, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state
const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, resizeDisabled, resizeReason, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state
return (
<>
<SetRow
title={tr('diskResizeTitle')}
desc={tr('diskResizeDesc')}
disabled={running}
reason={tr('stopBeforeDiskOp')}
disabled={resizeDisabled}
reason={resizeReason}
block={
<div className="stack-2">
<div className="hstack">
@@ -124,7 +133,7 @@ export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, stat
type="button"
className="preset"
aria-pressed={resizeInput === v}
disabled={running || !!diskOpBusy}
disabled={resizeDisabled || !!diskOpBusy}
onClick={() => setResizeInput(v)}
>
{v}
@@ -139,14 +148,14 @@ export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, stat
value={resizeInput}
spellCheck={false}
autoComplete="off"
disabled={running || !!diskOpBusy}
disabled={resizeDisabled || !!diskOpBusy}
onChange={(e) => setResizeInput(e.target.value)}
placeholder="+64G / 256G"
/>
<Button
variant="secondary"
busy={diskOpBusy === 'resize'}
disabled={running || !!diskOpBusy || !resizeInput.trim()}
disabled={resizeDisabled || !!diskOpBusy || !resizeInput.trim()}
onClick={handleResizeDisk}
>
{tr('diskResizeAction')}
@@ -0,0 +1,59 @@
import React from 'react'
import { I18nKey, t } from '../../i18n'
import { DiskCache, Locale } from '../../types'
import { Segmented, SetRow } from '../../ui/settings'
interface Props {
locale: Locale
value: DiskCache
dirty: boolean
supported?: boolean
reason?: string
onReset: () => void
resetLabel: string
error?: string
onChange: (cache: DiskCache) => void
}
export const DiskCacheRow: React.FC<Props> = ({ locale, value, dirty, supported = true, reason, onReset, resetLabel, error, onChange }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const baseDesc = value === 'writeback'
? tr('diskCacheDescWriteback')
: value === 'none'
? tr('diskCacheDescNone')
: value === 'unsafe'
? tr('diskCacheDescUnsafe')
: tr('diskCacheDescDefault')
const rowDisabled = !supported && value === 'default'
const disableNonDefault = !supported
const desc = !supported && value !== 'default' && reason
? `${baseDesc} · ${reason}`
: baseDesc
return (
<SetRow
field="disk_cache"
dirty={dirty}
disabled={rowDisabled}
reason={reason}
onReset={onReset}
resetLabel={resetLabel}
error={error}
title={tr('diskCacheTitle')}
desc={desc}
control={
<Segmented
label={tr('diskCacheTitle')}
value={value}
onChange={onChange}
options={[
{ value: 'default', label: tr('diskCacheOptionDefault') },
{ value: 'writeback', label: tr('diskCacheOptionWriteback'), disabled: disableNonDefault },
{ value: 'none', label: tr('diskCacheOptionNone'), disabled: disableNonDefault },
{ value: 'unsafe', label: tr('diskCacheOptionUnsafe'), disabled: disableNonDefault },
]}
/>
}
/>
)
}
+22
View File
@@ -120,6 +120,16 @@ export const settingsZh: Record<string, string> = {
"defenderExclusionDesc": "实时扫描可能拖慢虚拟机磁盘访问。可在 Windows 安全中心为数据目录 {path} 添加排除项。",
"defenderExclusionTitle": "Windows Defender 实时防护排除建议",
"defenderOpenSecurity": "打开 Windows 安全中心",
"diskCacheDescDefault": "跟随运行时默认策略(回写缓存并正常转发刷盘请求)",
"diskCacheDescNone": "绕过宿主机页缓存直通磁盘(Direct I/O),适合裸分区直挂",
"diskCacheDescUnsafe": "警告:忽略 Guest 刷盘指令以换取最高吞吐,宿主机断电或崩溃可能导致磁盘损坏",
"diskCacheDescWriteback": "经宿主机页缓存回写,并安全转发 Guest 刷盘请求",
"diskCacheOptionDefault": "默认",
"diskCacheOptionNone": "直通",
"diskCacheOptionUnsafe": "激进 (Unsafe)",
"diskCacheOptionWriteback": "回写",
"diskCacheRequiresRuntime": "当前运行时版本过旧,请更新到支持磁盘缓存策略的新版运行时",
"diskCacheTitle": "磁盘 I/O 缓存策略",
"diskCompactAction": "立即回收",
"diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间",
"diskCompactDone": "已回收 {reclaimed}({before} → {after})",
@@ -144,6 +154,7 @@ export const settingsZh: Record<string, string> = {
"diskResizeAction": "扩容",
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
"diskResizeRawDisabled": "Windows 裸分区不支持在此调整容量",
"diskResizeTitle": "扩大磁盘",
"diskRewriteBusy": "正在进行另一项磁盘操作。",
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",
@@ -656,6 +667,16 @@ export const settingsEn: Record<string, string> = {
"defenderExclusionDesc": "Real-time scanning can slow VM disk access. You can exclude the data folder {path} in Windows Security.",
"defenderExclusionTitle": "Windows Defender real-time protection exclusions",
"defenderOpenSecurity": "Open Windows Security",
"diskCacheDescDefault": "Follows the current runtime default (writeback caching, flushes forwarded to host)",
"diskCacheDescNone": "Direct I/O bypassing host page cache; recommended for raw partition passthrough",
"diskCacheDescUnsafe": "Warning: ignores guest flushes for peak throughput; host power loss or crash can corrupt the disk",
"diskCacheDescWriteback": "Uses host page cache and forwards guest flushes safely to disk",
"diskCacheOptionDefault": "Default",
"diskCacheOptionNone": "Direct",
"diskCacheOptionUnsafe": "Unsafe",
"diskCacheOptionWriteback": "Writeback",
"diskCacheRequiresRuntime": "Update to a newer runtime to configure disk I/O cache policy",
"diskCacheTitle": "Disk I/O cache",
"diskCompactAction": "Reclaim now",
"diskCompactDesc": "Gives space from files deleted in macOS back to Windows. Needs about as much free space as the disk uses now",
"diskCompactDone": "Reclaimed {reclaimed} ({before} → {after})",
@@ -680,6 +701,7 @@ export const settingsEn: Record<string, string> = {
"diskResizeAction": "Expand",
"diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space",
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
"diskResizeRawDisabled": "Windows raw partitions cannot be resized here",
"diskResizeTitle": "Expand disk",
"diskRewriteBusy": "Another disk operation is in progress.",
"diskRewriteOverlay": "This disk shares a backing image and cannot be rewritten directly.",
+11
View File
@@ -179,6 +179,16 @@ export type I18nKey =
| "discardSuspendConfirm"
| "discardSuspendDesc"
| "discardSuspendTitle"
| "diskCacheDescDefault"
| "diskCacheDescNone"
| "diskCacheDescUnsafe"
| "diskCacheDescWriteback"
| "diskCacheOptionDefault"
| "diskCacheOptionNone"
| "diskCacheOptionUnsafe"
| "diskCacheOptionWriteback"
| "diskCacheRequiresRuntime"
| "diskCacheTitle"
| "diskCompactAction"
| "diskCompactDesc"
| "diskCompactDone"
@@ -203,6 +213,7 @@ export type I18nKey =
| "diskResizeAction"
| "diskResizeDesc"
| "diskResizeDone"
| "diskResizeRawDisabled"
| "diskResizeTitle"
| "diskRewriteBusy"
| "diskRewriteOverlay"
+2
View File
@@ -106,6 +106,7 @@ export type DiskResizeResult = driver.DiskResizeResult
export type DiskCompactResult = driver.DiskCompactResult
export type DiskSnapshot = driver.DiskSnapshot
export type StorageBreakdown = Model<app.StorageBreakdown>
export type DiskCache = 'default' | 'writeback' | 'none' | 'unsafe'
export type SetOpts = reims.SetOpts
export type CreateOpts = Model<reims.CreateOpts> & {
@@ -114,6 +115,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
source_mode?: 'offline' | 'apple' | 'installer' | 'disk'
disk_mode?: 'copy' | 'in-place'
disk_controller?: 'nvme' | 'ahci' | 'virtio'
disk_cache?: DiskCache
graphics: 'reims-vgpu' | 'vmware-svga'
cpus: number
memory: string
+6
View File
@@ -3017,6 +3017,7 @@ export namespace reims {
disk?: string;
disk_mode?: string;
disk_controller?: string;
disk_cache?: string;
graphics?: string;
gpu?: string;
resolution?: string;
@@ -3050,6 +3051,7 @@ export namespace reims {
this.disk = source["disk"];
this.disk_mode = source["disk_mode"];
this.disk_controller = source["disk_controller"];
this.disk_cache = source["disk_cache"];
this.graphics = source["graphics"];
this.gpu = source["gpu"];
this.resolution = source["resolution"];
@@ -3073,6 +3075,7 @@ export namespace reims {
graphics?: string;
displays?: number;
disk_controller?: string;
disk_cache?: string;
resolution?: string;
borderless?: boolean;
capture?: boolean;
@@ -3101,6 +3104,7 @@ export namespace reims {
this.graphics = source["graphics"];
this.displays = source["displays"];
this.disk_controller = source["disk_controller"];
this.disk_cache = source["disk_cache"];
this.resolution = source["resolution"];
this.borderless = source["borderless"];
this.capture = source["capture"];
@@ -3175,6 +3179,7 @@ export namespace reims {
memory: string;
disk: string;
disk_controller: string;
disk_cache: string;
graphics: string;
display: string;
displays: number;
@@ -3227,6 +3232,7 @@ export namespace reims {
this.memory = source["memory"];
this.disk = source["disk"];
this.disk_controller = source["disk_controller"];
this.disk_cache = source["disk_cache"];
this.graphics = source["graphics"];
this.display = source["display"];
this.displays = source["displays"];
+9
View File
@@ -44,6 +44,15 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
if err != nil {
return err
}
if !active.Manifest.HasCapability("win32-native-aio") {
loc := i18n.EffectiveLocale(cfgCopy.Locale)
if dcache := strings.TrimSpace(opts.DiskCache); dcache != "" && !strings.EqualFold(dcache, "default") {
return errors.New(i18n.T(loc, "validate.disk_cache_requires_runtime"))
}
if reims.IsWindowsRawDevicePath(opts.Disk) {
return errors.New(i18n.T(loc, "validate.raw_disk_requires_runtime"))
}
}
c := reims.NewClient(&cfgCopy, *active)
// Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
+20
View File
@@ -137,6 +137,16 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
return err
}
} else {
if strings.TrimSpace(opts.DiskCache) != "" {
cfg := a.runtimeConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil {
return fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
}
if !active.Manifest.HasCapability("win32-native-aio") {
return errors.New(i18n.T(i18n.EffectiveLocale(loc), "validate.disk_cache_requires_runtime"))
}
}
c, err := a.client()
if err != nil {
return err
@@ -189,6 +199,16 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
if opts.Displays > 0 && opts.Displays != cur.Displays {
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
}
if dc := strings.ToLower(strings.TrimSpace(opts.DiskController)); dc != "" && !strings.EqualFold(dc, cur.DiskController) {
diffs = append(diffs, PendingChange{Field: "disk_controller", From: cur.DiskController, To: dc})
}
if dcache := strings.ToLower(strings.TrimSpace(opts.DiskCache)); dcache != "" && !strings.EqualFold(dcache, cur.DiskCache) {
from := cur.DiskCache
if from == "" {
from = "default"
}
diffs = append(diffs, PendingChange{Field: "disk_cache", From: from, To: dcache})
}
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
}
+44 -2
View File
@@ -100,6 +100,8 @@ func run(args []string) (i18n.Locale, error) {
return loc, cmdInstaller(cfg, loc, rest[1:])
case "plugin":
return loc, cmdPlugin(cfg, loc, rest[1:])
case "host":
return loc, cmdHost(cfg, rest[1:])
case "version", "-v", "--version":
fmt.Printf("reims-go %s\n", version.Version)
return loc, nil
@@ -501,6 +503,9 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
cpus := fs.Int("cpus", 8, "vCPU count")
mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)")
diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)")
disk := fs.String("disk", "", "Existing disk image or Windows raw partition path")
diskMode := fs.String("disk-mode", "", "Existing disk attach mode (copy, in-place)")
diskCache := fs.String("disk-cache", "", "Disk I/O cache mode (default, writeback, none, unsafe)")
gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path")
capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click")
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
@@ -524,6 +529,9 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
if err != nil {
return err
}
if strings.TrimSpace(*disk) != "" || strings.TrimSpace(*diskMode) != "" || strings.TrimSpace(*diskCache) != "" {
return fmt.Errorf("--disk, --disk-mode, and --disk-cache are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID)
}
req := driver.CreateRequest{
DriverID: drv.ID(),
Name: name,
@@ -547,7 +555,7 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
}
return nil
}
return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow)
return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, Disk: *disk, DiskMode: *diskMode, DiskCache: *diskCache, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow)
}
func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
@@ -555,6 +563,7 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
cpus := fs.Int("cpus", 0, "vCPU count")
mem := fs.String("memory", "", "RAM size")
diskCache := fs.String("disk-cache", "", "Disk I/O cache mode (default, writeback, none, unsafe)")
gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON")
res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT")
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
@@ -573,6 +582,9 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
if *mem != "" {
changes["memory"] = *mem
}
if *diskCache != "" {
changes["disk_cache"] = *diskCache
}
if *gpu != "" {
changes["gpu"] = *gpu
}
@@ -601,9 +613,39 @@ func printJSON(v any) error {
// readOnlySafeCommand reports whether cmd runs without writing to the data
// folder, so it may run while the folder is open read-only.
func cmdHost(cfg *config.Config, args []string) error {
if len(args) == 0 || args[0] != "raw-disks" {
return fmt.Errorf("usage: reims-go host raw-disks [--json]")
}
fs := flag.NewFlagSet("host raw-disks", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output JSON")
if err := fs.Parse(args[1:]); err != nil {
return err
}
list, err := host.ListRawPartitions(cfg.DataRoot)
if err != nil {
return err
}
if *asJSON {
return printJSON(list)
}
if len(list) == 0 {
fmt.Println("No eligible unmounted raw partitions or offline disks found.")
return nil
}
for _, c := range list {
apfs := ""
if c.IsAPFS {
apfs = " [APFS]"
}
fmt.Printf("%-46s %7.1f GiB disk=%d part=%d%s\n", c.DevicePath, float64(c.SizeBytes)/float64(1<<30), c.DiskNumber, c.PartitionNumber, apfs)
}
return nil
}
func readOnlySafeCommand(cmd string) bool {
switch cmd {
case "version", "-v", "--version", "help", "-h", "--help", "doctor":
case "version", "-v", "--version", "help", "-h", "--help", "doctor", "host":
return true
}
return false
+12 -4
View File
@@ -65,9 +65,9 @@ func requireCLIMacOSEnabled(cfg *config.Config, loc i18n.Locale) error {
// macOSCreateOptions is the CLI-neutral input to the native macOS create flow.
type macOSCreateOptions struct {
Name, Dir, MacOS, Memory, DiskSize, GPU, GuestLang string
CPUs int
Capture, Logs bool
Name, Dir, MacOS, Memory, DiskSize, Disk, DiskMode, DiskCache, GPU, GuestLang string
CPUs int
Capture, Logs bool
}
func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in macOSCreateOptions, startAfterCreate, viaWindow bool) error {
@@ -78,8 +78,16 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in
if err != nil {
return err
}
if !prep.Runtime.Manifest.HasCapability("win32-native-aio") {
if dcache := strings.TrimSpace(in.DiskCache); dcache != "" && !strings.EqualFold(dcache, "default") {
return errors.New(i18n.T(loc, "validate.disk_cache_requires_runtime"))
}
if reims.IsWindowsRawDevicePath(in.Disk) {
return errors.New(i18n.T(loc, "validate.raw_disk_requires_runtime"))
}
}
client := prep.Client
opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false}
opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, Disk: in.Disk, DiskMode: in.DiskMode, DiskCache: in.DiskCache, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false}
existingVMs, err := client.List(ctx)
if err != nil {
return fmt.Errorf("check existing VMs before create: %w", err)
+169
View File
@@ -0,0 +1,169 @@
package host
import (
"fmt"
"slices"
"strings"
)
// AppleAPFSPartitionTypeGUID is the canonical GPT partition type GUID for Apple APFS containers.
const AppleAPFSPartitionTypeGUID = "7C3457EF-0000-11AA-AA11-00306543ECAC"
var protectedGPTPartitionTypeGUIDs = map[string]bool{
"C12A7328-F81F-11D2-BA4B-00A0C93EC93B": true, // EFI System Partition
"E3C9E316-0B5C-4DB8-817D-F92DF00215AE": true, // Microsoft Reserved (MSR)
"DE94BBA4-06D1-4D40-A16A-BFD50179D6AC": true, // Windows Recovery Environment
}
// RawDiskCandidate describes a Windows raw volume or offline whole disk
// eligible as an unmounted guest block device.
type RawDiskCandidate struct {
DevicePath string `json:"device_path"`
DiskNumber uint32 `json:"disk_number"`
PartitionNumber uint32 `json:"partition_number,omitempty"`
SizeBytes uint64 `json:"size_bytes"`
PartitionTypeGUID string `json:"partition_type_guid,omitempty"`
IsAPFS bool `json:"is_apfs"`
Offline bool `json:"offline"`
ReadOnly bool `json:"read_only"`
Label string `json:"label,omitempty"`
}
// IsWindowsRawDevicePath reports whether path names a Windows raw disk,
// partition, or volume device path (excluding regular Win32 paths such as \\?\C:\...).
func IsWindowsRawDevicePath(path string) bool {
p := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(path), "/", `\`))
if strings.HasPrefix(p, `\\.\`) {
rest := p[len(`\\.\`):]
return strings.HasPrefix(rest, "physicaldrive") ||
strings.HasPrefix(rest, "harddiskvolume") ||
strings.HasPrefix(rest, "harddisk") ||
strings.HasPrefix(rest, "volume{")
}
if strings.HasPrefix(p, `\\?\`) {
rest := p[len(`\\?\`):]
return strings.HasPrefix(rest, "volume{")
}
return false
}
// RawVolumeObservation captures raw probe fields for a Windows volume or offline disk
// before applying host-safety filters.
type RawVolumeObservation struct {
DevicePath string
DiskNumber uint32
PartitionNumber uint32
SizeBytes uint64
PartitionTypeGUID string
HasMountPoints bool
Filesystem string
Offline bool
ReadOnly bool
Label string
}
type indexedVolumeExtent struct {
start int64
end int64
volDev string
multiExtent bool
hasMountPoints bool
filesystem string
occupied bool
}
func applyPartitionExtentMatches(obs *RawVolumeObservation, partStart int64, partLen uint64, extents []indexedVolumeExtent) {
if obs == nil || len(extents) == 0 || partLen == 0 {
return
}
partEnd := partStart + int64(partLen)
if partEnd <= partStart {
partEnd = 1<<63 - 1
}
for _, ext := range extents {
if ext.end <= partStart || ext.start >= partEnd {
continue
}
if ext.occupied || ext.hasMountPoints {
obs.HasMountPoints = true
}
if ext.filesystem != "" && obs.Filesystem == "" {
obs.Filesystem = ext.filesystem
}
if !ext.multiExtent && ext.start == partStart && ext.volDev != "" {
obs.DevicePath = ext.volDev
}
}
}
func isMountedWindowsFilesystem(fsName string) bool {
switch strings.ToUpper(strings.TrimSpace(fsName)) {
case "NTFS", "FAT", "FAT32", "EXFAT", "REFS", "CDFS", "UDF":
return true
default:
return false
}
}
func filterRawPartitionCandidates(observations []RawVolumeObservation, excludedDisks map[uint32]bool) []RawDiskCandidate {
var out []RawDiskCandidate
for _, obs := range observations {
if obs.DevicePath == "" || obs.SizeBytes == 0 {
continue
}
if excludedDisks[obs.DiskNumber] {
continue
}
if obs.HasMountPoints || isMountedWindowsFilesystem(obs.Filesystem) {
continue
}
guid := strings.ToUpper(strings.TrimSpace(obs.PartitionTypeGUID))
if guid != "" && protectedGPTPartitionTypeGUIDs[guid] {
continue
}
isAPFS := guid == AppleAPFSPartitionTypeGUID
label := strings.TrimSpace(obs.Label)
if label == "" {
if obs.PartitionNumber == 0 {
label = fmt.Sprintf("Disk %d (Offline)", obs.DiskNumber)
} else if isAPFS {
label = fmt.Sprintf("Disk %d Partition %d (APFS)", obs.DiskNumber, obs.PartitionNumber)
} else {
label = fmt.Sprintf("Disk %d Partition %d", obs.DiskNumber, obs.PartitionNumber)
}
}
out = append(out, RawDiskCandidate{
DevicePath: obs.DevicePath,
DiskNumber: obs.DiskNumber,
PartitionNumber: obs.PartitionNumber,
SizeBytes: obs.SizeBytes,
PartitionTypeGUID: guid,
IsAPFS: isAPFS,
Offline: obs.Offline,
ReadOnly: obs.ReadOnly,
Label: label,
})
}
slices.SortFunc(out, func(a, b RawDiskCandidate) int {
if a.IsAPFS != b.IsAPFS {
if a.IsAPFS {
return -1
}
return 1
}
if a.DiskNumber != b.DiskNumber {
if a.DiskNumber < b.DiskNumber {
return -1
}
return 1
}
if a.PartitionNumber < b.PartitionNumber {
return -1
}
if a.PartitionNumber > b.PartitionNumber {
return 1
}
return strings.Compare(a.DevicePath, b.DevicePath)
})
return out
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !windows
package host
// ListRawPartitions returns eligible unmounted partitions or offline whole disks.
// Currently only Windows raw device passthrough is implemented.
func ListRawPartitions(dataRoot string) ([]RawDiskCandidate, error) {
return nil, nil
}
+110
View File
@@ -0,0 +1,110 @@
package host
import "testing"
func TestIsWindowsRawDevicePath(t *testing.T) {
cases := []struct {
path string
want bool
}{
{`\\?\Volume{11111111-2222-3333-4444-555555555555}`, true},
{`//?/volume{11111111-2222-3333-4444-555555555555}`, true},
{`\\.\PhysicalDrive1`, true},
{`\\.\HarddiskVolume3`, true},
{`\\.\Harddisk1Partition2`, true},
{`\\.\Volume{11111111-2222-3333-4444-555555555555}`, true},
{`\\?\C:\VMs\macOS\disk.qcow2`, false},
{`\\?\UNC\server\share\disk.qcow2`, false},
{`D:\ReimsData\disk.qcow2`, false},
{``, false},
}
for _, tc := range cases {
if got := IsWindowsRawDevicePath(tc.path); got != tc.want {
t.Errorf("IsWindowsRawDevicePath(%q) = %v, want %v", tc.path, got, tc.want)
}
}
}
func TestFilterRawPartitionCandidatesSafety(t *testing.T) {
obs := []RawVolumeObservation{
{DevicePath: `\\?\Volume{os-c}`, DiskNumber: 0, PartitionNumber: 3, SizeBytes: 200 << 30, HasMountPoints: true, Filesystem: "NTFS"},
{DevicePath: `\\?\Volume{os-efi}`, DiskNumber: 0, PartitionNumber: 1, SizeBytes: 260 << 20, PartitionTypeGUID: "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"},
{DevicePath: `\\?\Volume{data-apfs}`, DiskNumber: 1, PartitionNumber: 2, SizeBytes: 256 << 30, PartitionTypeGUID: "7c3457ef-0000-11aa-aa11-00306543ecac"},
{DevicePath: `\\?\Volume{mounted-ntfs}`, DiskNumber: 2, PartitionNumber: 2, SizeBytes: 500 << 30, Filesystem: "NTFS"},
{DevicePath: `\\?\Volume{efi-disk2}`, DiskNumber: 2, PartitionNumber: 1, SizeBytes: 200 << 20, PartitionTypeGUID: "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"},
{DevicePath: `\\?\Volume{other-raw}`, DiskNumber: 2, PartitionNumber: 3, SizeBytes: 128 << 30, PartitionTypeGUID: "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7"},
{DevicePath: `\\.\PhysicalDrive3`, DiskNumber: 3, SizeBytes: 512 << 30, Offline: true},
}
excluded := map[uint32]bool{0: true}
got := filterRawPartitionCandidates(obs, excluded)
if len(got) != 3 {
t.Fatalf("got %d candidates %+v, want 3", len(got), got)
}
if !got[0].IsAPFS || got[0].DevicePath != `\\?\Volume{data-apfs}` {
t.Fatalf("expected APFS partition sorted first, got %+v", got[0])
}
if got[1].DevicePath != `\\?\Volume{other-raw}` {
t.Fatalf("unexpected second candidate: %+v", got[1])
}
if !got[2].Offline || got[2].DevicePath != `\\.\PhysicalDrive3` {
t.Fatalf("unexpected third candidate: %+v", got[2])
}
}
func TestApplyPartitionExtentMatches(t *testing.T) {
extents := []indexedVolumeExtent{
{
start: 1 << 20,
end: 100 << 20,
volDev: `\\?\Volume{spanned}`,
multiExtent: true,
occupied: true,
},
{
start: 200 << 20,
end: 300 << 20,
volDev: `\\?\Volume{probe-err}`,
occupied: true,
},
{
start: 400 << 20,
end: 500 << 20,
volDev: `\\?\Volume{apfs}`,
},
}
// Overlapping a multi-extent volume excludes the partition fail-closed.
spannedObs := RawVolumeObservation{DevicePath: `\\.\Harddisk1Partition1`, DiskNumber: 1, PartitionNumber: 1, SizeBytes: 99 << 20}
applyPartitionExtentMatches(&spannedObs, 1<<20, 99<<20, extents)
if !spannedObs.HasMountPoints {
t.Fatalf("expected spanned volume overlap to mark partition occupied")
}
// Probe error on the volume also marks it occupied fail-closed.
errObs := RawVolumeObservation{DevicePath: `\\.\Harddisk1Partition2`, DiskNumber: 1, PartitionNumber: 2, SizeBytes: 100 << 20}
applyPartitionExtentMatches(&errObs, 200<<20, 100<<20, extents)
if !errObs.HasMountPoints {
t.Fatalf("expected volume probe error to mark partition occupied")
}
// Clean unmounted APFS partition passes through with resolved volume device path.
apfsObs := RawVolumeObservation{DevicePath: `\\.\Harddisk1Partition3`, DiskNumber: 1, PartitionNumber: 3, SizeBytes: 100 << 20, PartitionTypeGUID: AppleAPFSPartitionTypeGUID}
applyPartitionExtentMatches(&apfsObs, 400<<20, 100<<20, extents)
if apfsObs.HasMountPoints || apfsObs.DevicePath != `\\?\Volume{apfs}` {
t.Fatalf("unexpected APFS observation after match: %+v", apfsObs)
}
got := filterRawPartitionCandidates([]RawVolumeObservation{spannedObs, errObs, apfsObs}, nil)
if len(got) != 1 || got[0].DevicePath != `\\?\Volume{apfs}` {
t.Fatalf("expected only clean APFS candidate, got %+v", got)
}
}
func TestInspectDiskUsageSkipsRawDevice(t *testing.T) {
du, err := InspectDiskUsage(`\\.\Harddisk1Partition2`)
if err != nil {
t.Fatalf("InspectDiskUsage on raw device returned error: %v", err)
}
if du.Format != "raw" || du.Path != `\\.\Harddisk1Partition2` {
t.Fatalf("unexpected DiskUsage for raw device: %+v", du)
}
}
+417
View File
@@ -0,0 +1,417 @@
//go:build windows
package host
import (
"encoding/binary"
"errors"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
var (
procFindFirstVolumeW = kernel32.NewProc("FindFirstVolumeW")
procFindNextVolumeW = kernel32.NewProc("FindNextVolumeW")
procFindVolumeClose = kernel32.NewProc("FindVolumeClose")
procGetVolumeInformationW = kernel32.NewProc("GetVolumeInformationW")
procGetVolumePathNameW = kernel32.NewProc("GetVolumePathNameW")
)
const (
ioctlVolumeGetVolumeDiskExtents = 0x00560000
ioctlDiskGetDriveLayoutEx = 0x00070050
ioctlDiskGetLengthInfo = 0x0007405C
ioctlDiskGetDiskAttributes = 0x000700F0
diskAttributeOffline = 0x1
diskAttributeReadOnly = 0x2
)
// ListRawPartitions enumerates Windows raw partitions and offline disks that
// are safe to pass through to a VM (excluding OS disk, dataRoot disk, EFI/MSR/Recovery,
// mounted volumes, and Windows filesystems).
func ListRawPartitions(dataRoot string) ([]RawDiskCandidate, error) {
excluded := excludedHostDiskNumbers(dataRoot)
extentsByDisk, err := indexVolumesByExtent()
if err != nil {
return nil, err
}
maxSeenDisk := maxDiskNumber(excluded, extentsByDisk)
var observations []RawVolumeObservation
consecutiveMisses := 0
for diskNum := uint32(0); diskNum < 512; diskNum++ {
if excluded[diskNum] {
consecutiveMisses = 0
continue
}
offline, readOnly, ok := queryDiskAttributes(diskNum)
if !ok {
consecutiveMisses++
if diskNum >= 31 && diskNum >= maxSeenDisk && consecutiveMisses >= 32 {
break
}
continue
}
consecutiveMisses = 0
observations = appendDiskObservations(observations, diskNum, offline, readOnly, extentsByDisk[diskNum])
}
return filterRawPartitionCandidates(observations, excluded), nil
}
func maxDiskNumber(excluded map[uint32]bool, extents map[uint32][]indexedVolumeExtent) uint32 {
var maxDisk uint32
for d := range excluded {
if d > maxDisk {
maxDisk = d
}
}
for d := range extents {
if d > maxDisk {
maxDisk = d
}
}
return maxDisk
}
func appendDiskObservations(observations []RawVolumeObservation, diskNum uint32, offline, readOnly bool, extents []indexedVolumeExtent) []RawVolumeObservation {
dev := fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum)
if offline {
sizeBytes, _ := queryDeviceLengthBytes(dev)
if sizeBytes > 0 {
observations = append(observations, RawVolumeObservation{
DevicePath: dev,
DiskNumber: diskNum,
SizeBytes: sizeBytes,
Offline: true,
ReadOnly: readOnly,
})
}
return observations
}
for _, p := range queryDiskPartitions(diskNum) {
if p.number == 0 || p.length == 0 {
continue
}
obs := RawVolumeObservation{
DevicePath: fmt.Sprintf(`\\.\Harddisk%dPartition%d`, diskNum, p.number),
DiskNumber: diskNum,
PartitionNumber: p.number,
SizeBytes: p.length,
PartitionTypeGUID: p.typeGUID,
ReadOnly: readOnly,
}
applyPartitionExtentMatches(&obs, p.offset, p.length, extents)
if exact, ok := queryDeviceLengthBytes(obs.DevicePath); ok && exact > 0 {
obs.SizeBytes = exact
}
observations = append(observations, obs)
}
return observations
}
type volumeDiskExtent struct {
diskNumber uint32
startingOffset int64
extentLength uint64
}
type diskPartitionEntry struct {
number uint32
offset int64
length uint64
typeGUID string
}
func indexVolumesByExtent() (map[uint32][]indexedVolumeExtent, error) {
out := map[uint32][]indexedVolumeExtent{}
volNames, err := enumVolumeNames()
if err != nil {
return nil, err
}
for _, volWithSlash := range volNames {
volDev := strings.TrimSuffix(volWithSlash, `\`)
extents, ok := queryVolumeDiskExtents(volDev)
if !ok {
continue
}
hasMounts, mountErr := volumeHasMountPoints(volWithSlash)
fsName, fsKnown := queryVolumeFilesystem(volWithSlash)
multi := len(extents) > 1
occupied := multi || mountErr != nil || hasMounts || !fsKnown
for _, ext := range extents {
end := ext.startingOffset + int64(ext.extentLength)
if end <= ext.startingOffset {
end = 1<<63 - 1
}
out[ext.diskNumber] = append(out[ext.diskNumber], indexedVolumeExtent{
start: ext.startingOffset,
end: end,
volDev: volDev,
multiExtent: multi,
hasMountPoints: hasMounts,
filesystem: fsName,
occupied: occupied,
})
}
}
return out, nil
}
func excludedHostDiskNumbers(dataRoot string) map[uint32]bool {
excluded := map[uint32]bool{}
addPath := func(p string) {
p = strings.TrimSpace(p)
if p == "" {
return
}
volDev := volumeDeviceForPath(p)
if volDev == "" {
return
}
if extents, ok := queryVolumeDiskExtents(volDev); ok {
for _, ext := range extents {
excluded[ext.diskNumber] = true
}
}
}
if sysRoot := os.Getenv("SystemRoot"); sysRoot != "" {
addPath(sysRoot)
} else if sysDrive := os.Getenv("SystemDrive"); sysDrive != "" {
addPath(sysDrive + `\`)
}
addPath(dataRoot)
return excluded
}
func volumeDeviceForPath(path string) string {
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return ""
}
mount := make([]uint16, 32768)
r, _, _ := procGetVolumePathNameW.Call(uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&mount[0])), uintptr(len(mount)))
if r == 0 {
return ""
}
var vol [64]uint16
r2, _, _ := procGetVolumeNameForVolumeMountPointW.Call(uintptr(unsafe.Pointer(&mount[0])), uintptr(unsafe.Pointer(&vol[0])), uintptr(len(vol)))
if r2 == 0 {
return ""
}
return strings.TrimSuffix(syscall.UTF16ToString(vol[:]), `\`)
}
func enumVolumeNames() ([]string, error) {
buf := make([]uint16, 32768)
h, _, err := procFindFirstVolumeW.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if h == uintptr(windows.InvalidHandle) {
return nil, err
}
defer procFindVolumeClose.Call(h)
var out []string
for {
name := syscall.UTF16ToString(buf)
if name != "" {
out = append(out, name)
}
r, _, _ := procFindNextVolumeW.Call(h, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if r == 0 {
break
}
}
return out, nil
}
func volumeHasMountPoints(volWithSlash string) (bool, error) {
p, err := windows.UTF16PtrFromString(volWithSlash)
if err != nil {
return true, err
}
buf := make([]uint16, 1024)
var needed uint32
if err := windows.GetVolumePathNamesForVolumeName(p, &buf[0], uint32(len(buf)), &needed); err != nil {
if needed > uint32(len(buf)) {
buf = make([]uint16, needed)
if err := windows.GetVolumePathNamesForVolumeName(p, &buf[0], uint32(len(buf)), &needed); err != nil {
return true, err
}
} else {
return true, err
}
}
return len(buf) > 0 && buf[0] != 0, nil
}
func queryVolumeFilesystem(volWithSlash string) (string, bool) {
p, err := syscall.UTF16PtrFromString(volWithSlash)
if err != nil {
return "", false
}
fsBuf := make([]uint16, 64)
r, _, callErr := procGetVolumeInformationW.Call(
uintptr(unsafe.Pointer(p)),
0, 0,
0, 0, 0,
uintptr(unsafe.Pointer(&fsBuf[0])), uintptr(len(fsBuf)),
)
if r == 0 {
// Unformatted / foreign volumes (e.g. APFS) yield ERROR_UNRECOGNIZED_VOLUME (1005).
// Any other probe error (e.g. ERROR_ACCESS_DENIED) is treated fail-closed by caller.
if errors.Is(callErr, windows.ERROR_UNRECOGNIZED_VOLUME) {
return "", true
}
return "", false
}
return syscall.UTF16ToString(fsBuf), true
}
func openDeviceMeta(devicePath string, access uint32) (windows.Handle, error) {
p, err := windows.UTF16PtrFromString(devicePath)
if err != nil {
return 0, err
}
return windows.CreateFile(
p,
access,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE,
nil,
windows.OPEN_EXISTING,
0,
0,
)
}
func queryVolumeDiskExtents(volDev string) ([]volumeDiskExtent, bool) {
h, err := openDeviceMeta(volDev, 0)
if err != nil {
return nil, false
}
defer windows.CloseHandle(h)
var buf []byte
var n uint32
for size := 256; size <= 65536; size *= 2 {
buf = make([]byte, size)
err = windows.DeviceIoControl(h, ioctlVolumeGetVolumeDiskExtents, nil, 0, &buf[0], uint32(len(buf)), &n, nil)
if err == nil {
break
}
if !errors.Is(err, windows.ERROR_MORE_DATA) {
return nil, false
}
}
if err != nil || n < 32 {
return nil, false
}
count := binary.LittleEndian.Uint32(buf[0:4])
var out []volumeDiskExtent
for i := uint32(0); i < count; i++ {
off := 8 + int(i)*24
if off+24 > int(n) {
break
}
out = append(out, volumeDiskExtent{
diskNumber: binary.LittleEndian.Uint32(buf[off : off+4]),
startingOffset: int64(binary.LittleEndian.Uint64(buf[off+8 : off+16])),
extentLength: binary.LittleEndian.Uint64(buf[off+16 : off+24]),
})
}
return out, len(out) > 0
}
func queryDeviceLengthBytes(devPath string) (uint64, bool) {
h, err := openDeviceMeta(devPath, windows.GENERIC_READ)
if err != nil {
return 0, false
}
defer windows.CloseHandle(h)
var out [8]byte
var n uint32
if err := windows.DeviceIoControl(h, ioctlDiskGetLengthInfo, nil, 0, &out[0], 8, &n, nil); err != nil || n < 8 {
return 0, false
}
return binary.LittleEndian.Uint64(out[:]), true
}
func queryDiskAttributes(diskNum uint32) (offline, readOnly, ok bool) {
h, err := openDeviceMeta(fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum), 0)
if err != nil {
return false, false, false
}
defer windows.CloseHandle(h)
var out [16]byte
var n uint32
if err := windows.DeviceIoControl(h, ioctlDiskGetDiskAttributes, nil, 0, &out[0], uint32(len(out)), &n, nil); err != nil || n < 16 {
return false, false, false
}
attrs := binary.LittleEndian.Uint64(out[8:16])
return (attrs & diskAttributeOffline) != 0, (attrs & diskAttributeReadOnly) != 0, true
}
func queryDiskPartitions(diskNum uint32) []diskPartitionEntry {
h, err := openDeviceMeta(fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum), windows.GENERIC_READ)
if err != nil {
return nil
}
defer windows.CloseHandle(h)
// Accommodate up to 128 GPT partitions: 48 + 128*144 = 18480 bytes.
buf := make([]byte, 48+128*144)
var n uint32
if err := windows.DeviceIoControl(h, ioctlDiskGetDriveLayoutEx, nil, 0, &buf[0], uint32(len(buf)), &n, nil); err != nil || n < 48 {
return nil
}
style := binary.LittleEndian.Uint32(buf[0:4])
if style != 0 && style != 1 {
return nil
}
count := binary.LittleEndian.Uint32(buf[4:8])
var out []diskPartitionEntry
// Per winioctl.h (DRIVE_LAYOUT_INFORMATION_EX), the Mbr/Gpt union is padded to
// 40 bytes (DRIVE_LAYOUT_INFORMATION_GPT), so PartitionEntry[0] starts at byte 48
// for both MBR (style=0) and GPT (style=1).
for i := uint32(0); i < count; i++ {
off := 48 + int(i)*144
if off+144 > int(n) {
break
}
entryStyle := binary.LittleEndian.Uint32(buf[off : off+4])
if style == 0 && entryStyle == 0 {
mbrType := buf[off+32]
if mbrType == 0x00 || mbrType == 0x05 || mbrType == 0x0F {
continue
}
}
startOff := int64(binary.LittleEndian.Uint64(buf[off+8 : off+16]))
length := binary.LittleEndian.Uint64(buf[off+16 : off+24])
num := binary.LittleEndian.Uint32(buf[off+24 : off+28])
guid := ""
if style == 1 && entryStyle == 1 {
guid = formatWinGUID(buf[off+32 : off+48])
}
out = append(out, diskPartitionEntry{
number: num,
offset: startOff,
length: length,
typeGUID: guid,
})
}
return out
}
func formatWinGUID(b []byte) string {
if len(b) < 16 {
return ""
}
d1 := binary.LittleEndian.Uint32(b[0:4])
d2 := binary.LittleEndian.Uint16(b[4:6])
d3 := binary.LittleEndian.Uint16(b[6:8])
return fmt.Sprintf("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
d1, d2, d3, b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15])
}
+3
View File
@@ -76,6 +76,9 @@ func ComputeCPUPercent(prev, cur ProcessSample, logicalCPUs int) float64 {
// InspectDiskUsage returns actual host bytes consumed and virtual logical capacity
// for a .qcow2 or raw disk image without spawning qemu-img.
func InspectDiskUsage(path string) (DiskUsage, error) {
if IsWindowsRawDevicePath(path) {
return DiskUsage{Path: path, Format: "raw"}, nil
}
info, err := os.Stat(path)
if err != nil {
return DiskUsage{}, err
+8
View File
@@ -666,6 +666,7 @@ var catalog = map[Locale]map[string]string{
"validate.dir_inaccessible": "目标目录 {dir} 无法访问,检查权限或选择其他目录",
"validate.dir_not_directory": "目标路径 {dir} 不是目录,选择新目录或空目录",
"validate.dir_not_empty": "目标目录 {dir} 非空,选择新目录或空目录",
"validate.disk_cache_requires_runtime": "当前运行时不支持 --disk-cache,请更新至新版运行时",
"validate.disk_not_found": "所选虚拟磁盘文件不存在",
"validate.eject_before_controller_change": "切换磁盘控制器前须先弹出 macOS 安装盘",
"validate.gpu_icd_not_found": "所选 Vulkan ICD JSON 文件不存在",
@@ -673,6 +674,7 @@ var catalog = map[Locale]map[string]string{
"validate.installer_not_found": "所选安装镜像文件不存在",
"validate.invalid_audio_backend": "不支持的音频后端 \"{backend}\"",
"validate.invalid_cpus": "虚拟处理器核数须在 1 到 {max} 之间",
"validate.invalid_disk_cache": "磁盘缓存策略仅支持 default、writeback、none 或 unsafe",
"validate.invalid_disk_controller": "磁盘控制器仅支持 nvme、ahci 或 virtio",
"validate.invalid_disk_size": "新建磁盘上限不能小于 32G(推荐 128G)",
"validate.invalid_displays": "显示器数量须在 1 到 4 之间",
@@ -687,6 +689,8 @@ var catalog = map[Locale]map[string]string{
"validate.missing_name": "虚拟机名称不能为空",
"validate.missing_release": "请选择要离线安装的 macOS 版本",
"validate.name_taken": "已存在名为 {name} 的虚拟机",
"validate.raw_disk_in_place_only": "Windows 裸分区或物理盘路径仅支持原地直挂(in-place)",
"validate.raw_disk_requires_runtime": "当前运行时不支持 Windows 裸分区/物理盘直通,请更新至新版运行时",
"validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置",
"viewLogs": "查看日志",
"vm.already_running": "{name} 已在运行中",
@@ -1369,6 +1373,7 @@ var catalog = map[Locale]map[string]string{
"validate.dir_inaccessible": "Target folder {dir} cannot be accessed; check permissions or choose another folder",
"validate.dir_not_directory": "Target path {dir} is not a folder; choose a new or empty folder",
"validate.dir_not_empty": "Target folder {dir} is not empty; choose a new or empty folder",
"validate.disk_cache_requires_runtime": "Active runtime does not support --disk-cache; update to a newer runtime",
"validate.disk_not_found": "Selected disk image file does not exist",
"validate.eject_before_controller_change": "Eject the macOS installer before changing disk controller",
"validate.gpu_icd_not_found": "Selected Vulkan ICD JSON file does not exist",
@@ -1376,6 +1381,7 @@ var catalog = map[Locale]map[string]string{
"validate.installer_not_found": "Selected installer image file does not exist",
"validate.invalid_audio_backend": "Unsupported audio backend \"{backend}\"",
"validate.invalid_cpus": "vCPUs must be between 1 and {max}",
"validate.invalid_disk_cache": "Disk cache mode must be default, writeback, none, or unsafe",
"validate.invalid_disk_controller": "Disk controller must be nvme, ahci, or virtio",
"validate.invalid_disk_size": "New disk size must be at least 32G (recommended 128G)",
"validate.invalid_displays": "Displays must be between 1 and 4",
@@ -1390,6 +1396,8 @@ 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.raw_disk_in_place_only": "Windows raw disk or partition paths must be attached in place",
"validate.raw_disk_requires_runtime": "Active runtime does not support Windows raw disk passthrough; update to a newer runtime",
"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",
+3
View File
@@ -117,6 +117,9 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
if srcDisk == "" {
return fmt.Errorf("VM %s has no disk path", sourceName)
}
if reims.IsWindowsRawDevicePath(srcDisk) {
return fmt.Errorf("cannot derive a CoW clone from a raw disk partition")
}
if _, err := os.Stat(srcDisk); err != nil {
return fmt.Errorf("source disk %s: %w", srcDisk, err)
}
+15 -2
View File
@@ -12,6 +12,7 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/plugin"
@@ -248,7 +249,7 @@ func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRe
}
func (d *ReimsMacOSDriver) Create(ctx context.Context, req driver.CreateRequest, stdout, stderr io.Writer) error {
c, err := d.client()
c, active, err := d.startClient()
if err != nil {
return err
}
@@ -256,6 +257,15 @@ func (d *ReimsMacOSDriver) Create(ctx context.Context, req driver.CreateRequest,
if err := decodeMap(req.Options, &opts); err != nil {
return err
}
loc := i18n.EffectiveLocale(d.getConfig().Locale)
if !active.Manifest.HasCapability("win32-native-aio") {
if dcache := strings.TrimSpace(opts.DiskCache); dcache != "" && !strings.EqualFold(dcache, "default") {
return errors.New(i18n.T(loc, "validate.disk_cache_requires_runtime"))
}
if reims.IsWindowsRawDevicePath(opts.Disk) {
return errors.New(i18n.T(loc, "validate.raw_disk_requires_runtime"))
}
}
if opts.Name == "" {
opts.Name = req.Name
}
@@ -299,7 +309,7 @@ func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req driver.SetReques
}
func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdout, stderr io.Writer) error {
c, err := d.client()
c, active, err := d.startClient()
if err != nil {
return err
}
@@ -307,6 +317,9 @@ func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdou
if err := decodeMap(req.Changes, &opts); err != nil {
return err
}
if strings.TrimSpace(opts.DiskCache) != "" && !active.Manifest.HasCapability("win32-native-aio") {
return errors.New(i18n.T(i18n.EffectiveLocale(d.getConfig().Locale), "validate.disk_cache_requires_runtime"))
}
opts.Name = req.Name
cur, release, err := startprep.LockMutableVM(ctx, c, req.Name)
if err != nil {
+8 -2
View File
@@ -28,7 +28,7 @@ func (d *ReimsMacOSDriver) ListSnapshots(ctx context.Context, name string) ([]dr
return nil, err
}
diskPath := det.DiskPath()
if diskPath == "" || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
if diskPath == "" || reims.IsWindowsRawDevicePath(diskPath) || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
return nil, nil
}
cfg := d.getConfig()
@@ -72,7 +72,7 @@ func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, sna
if diskPath == "" {
return fmt.Errorf("VM %s has no disk path", name)
}
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
if reims.IsWindowsRawDevicePath(diskPath) || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
return fmt.Errorf("restore points require a qcow2 disk")
}
releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath)
@@ -104,6 +104,9 @@ func (d *ReimsMacOSDriver) ResizeDisk(ctx context.Context, name, newSize string,
if diskPath == "" {
return driver.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
}
if reims.IsWindowsRawDevicePath(diskPath) {
return driver.DiskResizeResult{}, fmt.Errorf("raw disk partitions cannot be resized here")
}
releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath)
if err != nil {
return driver.DiskResizeResult{}, err
@@ -145,6 +148,9 @@ func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name stri
if diskPath == "" {
return driver.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
}
if reims.IsWindowsRawDevicePath(diskPath) {
return driver.DiskCompactResult{}, fmt.Errorf("raw disk partitions cannot be compacted")
}
releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath)
if err != nil {
return driver.DiskCompactResult{}, err
@@ -110,3 +110,30 @@ func TestReimsMacOSDriverCreateProtectsRegisteredVMInAbortedDir(t *testing.T) {
t.Fatalf("registered VM dir %s must not be removed: %v", vms[0].Directory, statErr)
}
}
func TestReimsMacOSDriverRejectsDiskCacheAndRawDiskWithoutCapability(t *testing.T) {
d := newFakeRuntimeDriver(t)
ctx := context.Background()
var out bytes.Buffer
if err := d.Create(ctx, driver.CreateRequest{
Name: "new-mac",
Options: map[string]any{"disk_cache": "unsafe"},
}, &out, &out); err == nil || !strings.Contains(err.Error(), "--disk-cache") {
t.Fatalf("expected runtime capability error for Create disk_cache, got %v", err)
}
if err := d.Create(ctx, driver.CreateRequest{
Name: "new-mac",
Options: map[string]any{"disk": `\\.\Harddisk1Partition2`, "disk_mode": "in-place"},
}, &out, &out); err == nil {
t.Fatalf("expected runtime capability error for Create raw disk")
}
if err := d.Set(ctx, driver.SetRequest{
Name: "normal-vm",
Changes: map[string]any{"disk_cache": "none"},
}, &out, &out); err == nil || !strings.Contains(err.Error(), "--disk-cache") {
t.Fatalf("expected runtime capability error for Set disk_cache, got %v", err)
}
}
+36 -14
View File
@@ -70,16 +70,20 @@ func (c *Client) LockCoWDisks(ctx context.Context, paths ...string) (func(), err
if path == "" {
continue
}
path = absoluteDiskPath(path)
if !IsWindowsRawDevicePath(path) {
path = absoluteDiskPath(path)
}
keys = append(keys, fmt.Sprintf("path-%x", sha256.Sum256([]byte(diskPathKey(path)))))
if info, err := os.Stat(path); err == nil {
volume, id, err := mediaFileID(path, info)
if err != nil {
if !IsWindowsRawDevicePath(path) {
if info, err := os.Stat(path); err == nil {
volume, id, err := mediaFileID(path, info)
if err != nil {
return nil, err
}
keys = append(keys, fmt.Sprintf("file-%x-%x", volume, id))
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
keys = append(keys, fmt.Sprintf("file-%x-%x", volume, id))
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
@@ -224,13 +228,18 @@ func (c *Client) RegisterCoWClone(ctx context.Context, o CreateOpts, stdout, std
}
func (c *Client) createWithDisk(ctx context.Context, o CreateOpts, args []string, stdout, stderr io.Writer) error {
disk := absoluteDiskPath(config.ExpandHomePath(o.Disk))
disk := config.ExpandHomePath(o.Disk)
if !IsWindowsRawDevicePath(disk) {
disk = absoluteDiskPath(disk)
}
paths := []string{disk}
if err := visitDiskBackings(disk, func(parent string) bool {
paths = append(paths, parent)
return false
}); err != nil {
return err
if !IsWindowsRawDevicePath(disk) {
if err := visitDiskBackings(disk, func(parent string) bool {
paths = append(paths, parent)
return false
}); err != nil {
return err
}
}
release, err := c.LockCoWDisks(ctx, paths...)
if err != nil {
@@ -238,7 +247,11 @@ func (c *Client) createWithDisk(ctx context.Context, o CreateOpts, args []string
}
defer release()
switch o.DiskMode {
mode := strings.ToLower(strings.TrimSpace(o.DiskMode))
if mode == "" && IsWindowsRawDevicePath(disk) {
mode = "in-place"
}
switch mode {
case "in-place", "inplace", "link":
default:
// reims-ctl may copy a large image. Its source and backing files are
@@ -603,6 +616,9 @@ func (c *Client) checkCoWBackingUse(vms []driver.VMInfo, excludeVM string, match
func visitDiskBackings(disk string, visit func(string) bool) error {
seen := make(map[string]bool)
for disk != "" {
if IsWindowsRawDevicePath(disk) {
return nil
}
key := diskPathKey(absoluteDiskPath(disk))
if seen[key] {
return nil
@@ -633,6 +649,9 @@ func newDiskMatch(path string) diskMatch {
if path == "" {
return diskMatch{}
}
if IsWindowsRawDevicePath(path) {
return diskMatch{path: path}
}
path = absoluteDiskPath(path)
info, _ := os.Stat(path)
return diskMatch{path: path, info: info}
@@ -655,6 +674,9 @@ func (d diskMatch) matches(path string) bool {
}
func absoluteDiskPath(path string) string {
if IsWindowsRawDevicePath(path) {
return strings.ReplaceAll(strings.TrimSpace(path), "/", `\`)
}
if abs, err := filepath.Abs(path); err == nil {
path = abs
}
+9
View File
@@ -236,6 +236,9 @@ func BuildCompactDiskArgs(srcPath, dstPath string, opts QCOW2CreateOptions) []st
// NeedsDiskConversion reports whether srcPath is a disk format (VMDK or RAW)
// that should be converted to qcow2 via qemu-img before handing off to reims-ctl.
func NeedsDiskConversion(srcPath string) bool {
if IsWindowsRawDevicePath(srcPath) {
return false
}
ext := strings.ToLower(filepath.Ext(strings.TrimSpace(srcPath)))
return ext == ".vmdk" || ext == ".raw"
}
@@ -315,6 +318,9 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac
// ResizeDisk expands a stopped VM's disk image via `qemu-img resize`.
func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath, sizeSpec string, stdout, stderr io.Writer) (DiskResizeResult, error) {
if IsWindowsRawDevicePath(diskPath) {
return DiskResizeResult{}, fmt.Errorf("raw disk partitions cannot be resized here")
}
if _, err := os.Stat(qemuImgPath); err != nil {
return DiskResizeResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
@@ -351,6 +357,9 @@ func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath,
}
func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) {
if IsWindowsRawDevicePath(diskPath) {
return DiskCompactResult{}, fmt.Errorf("raw disk partitions cannot be compacted")
}
before, err := host.InspectDiskUsage(diskPath)
if err != nil {
return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
+126
View File
@@ -0,0 +1,126 @@
package reims
import (
"context"
"os"
"path/filepath"
"slices"
"testing"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestRawDevicePathAndDiskPath(t *testing.T) {
vol := `\\?\Volume{11111111-2222-3333-4444-555555555555}`
d := VMDetail{Directory: `/tmp/vm`, Disk: vol + ` (128G)`}
if got := d.DiskPath(); got != vol {
t.Fatalf("DiskPath() = %q, want %q", got, vol)
}
if !IsWindowsRawDevicePath(vol) {
t.Fatalf("expected IsWindowsRawDevicePath(%q) = true", vol)
}
if IsWindowsRawDevicePath(`\\?\C:\Users\test\disk.qcow2`) {
t.Fatalf("expected regular extended Win32 path not to match raw device")
}
if NeedsDiskConversion(vol) {
t.Fatalf("expected NeedsDiskConversion(%q) = false", vol)
}
}
func TestDiskCacheValidationAndArgs(t *testing.T) {
vol := `\\?\Volume{11111111-2222-3333-4444-555555555555}`
rep := host.Report{LogicalCPUs: 16}
issues := ValidateCreate(CreateOpts{
Name: "apfs-vm",
CPUs: 8,
Memory: "8G",
Disk: vol,
DiskCache: "unsafe",
}, rep, i18n.EnUS)
if len(issues) != 0 {
t.Fatalf("expected no validation issues for valid raw partition + unsafe cache, got %+v", issues)
}
copyIssues := ValidateCreate(CreateOpts{
Name: "apfs-vm",
CPUs: 8,
Memory: "8G",
Disk: vol,
DiskMode: "copy",
}, rep, i18n.EnUS)
if !slices.ContainsFunc(copyIssues, func(is ValidationIssue) bool { return is.Code == "raw_disk_in_place_only" }) {
t.Fatalf("expected raw_disk_in_place_only issue, got %+v", copyIssues)
}
badCache := ValidateSet(SetOpts{Name: "apfs-vm", DiskCache: "invalid"}, VMDetail{Name: "apfs-vm"}, rep, i18n.EnUS)
if !slices.ContainsFunc(badCache, func(is ValidationIssue) bool { return is.Code == "invalid_disk_cache" }) {
t.Fatalf("expected invalid_disk_cache issue, got %+v", badCache)
}
createArgs, err := BuildCreateArgs(CreateOpts{
Name: "apfs-vm",
Disk: vol,
DiskCache: "none",
})
if err != nil {
t.Fatalf("BuildCreateArgs: %v", err)
}
wantCreate := []string{"create", "apfs-vm", "--disk", vol, "--disk-mode", "in-place", "--disk-cache", "none"}
if !slices.Equal(createArgs, wantCreate) {
t.Fatalf("BuildCreateArgs = %v, want %v", createArgs, wantCreate)
}
setArgs, err := BuildSetArgs(SetOpts{Name: "apfs-vm", DiskCache: "unsafe"})
if err != nil {
t.Fatalf("BuildSetArgs: %v", err)
}
wantSet := []string{"set", "apfs-vm", "--disk-cache", "unsafe"}
if !slices.Equal(setArgs, wantSet) {
t.Fatalf("BuildSetArgs = %v, want %v", setArgs, wantSet)
}
}
func TestParseShowDiskCache(t *testing.T) {
show := `apfs-vm
state stopped
disk \\?\Volume{11111111-2222-3333-4444-555555555555} (nvme)
disk cache unsafe
`
d := ParseShow("apfs-vm", show)
if d.DiskController != "nvme" {
t.Fatalf("DiskController = %q, want nvme", d.DiskController)
}
if d.DiskCache != "unsafe" {
t.Fatalf("DiskCache = %q, want unsafe", d.DiskCache)
}
if dDef := ParseShow("plain", "plain\n state stopped\n"); dDef.DiskCache != "default" {
t.Fatalf("default DiskCache = %q, want default", dDef.DiskCache)
}
}
func TestLockCoWDisksAllowsRawDevicePath(t *testing.T) {
c := &Client{imagesDir: t.TempDir(), Locale: i18n.EnUS}
release, err := c.LockCoWDisks(context.Background(), `\\?\Volume{11111111-2222-3333-4444-555555555555}`)
if err != nil {
t.Fatalf("LockCoWDisks on raw device: %v", err)
}
release()
}
func TestCheckCoWBackingUseSkipsRawDeviceVMs(t *testing.T) {
vmDir := filepath.Join(t.TempDir(), "raw-vm")
if err := os.MkdirAll(vmDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(vmDir, "vm.toml"), []byte("disk = \"\\\\\\\\.\\\\Harddisk1Partition2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
c := &Client{Locale: i18n.EnUS}
vms := []driver.VMInfo{{Name: "raw-vm", Directory: vmDir}}
if err := c.checkCoWBackingUse(vms, "", func(string) bool { return false }); err != nil {
t.Fatalf("checkCoWBackingUse returned error for raw device VM: %v", err)
}
}
+45 -1
View File
@@ -61,12 +61,21 @@ func NewClient(cfg *config.Config, installed rt.Installed) *Client {
return c
}
// IsWindowsRawDevicePath reports whether path targets a Windows raw disk,
// partition, or volume device path.
func IsWindowsRawDevicePath(path string) bool {
return host.IsWindowsRawDevicePath(path)
}
// DiskPath resolves the system disk path returned by reims-ctl show.
func (d VMDetail) DiskPath() string {
raw := strings.TrimSpace(d.Disk)
if idx := strings.LastIndex(raw, " ("); idx > 0 && strings.HasSuffix(raw, ")") {
raw = strings.TrimSpace(raw[:idx])
}
if IsWindowsRawDevicePath(raw) {
return raw
}
raw = config.ExpandHomePath(raw)
if filepath.IsAbs(raw) {
return raw
@@ -91,6 +100,7 @@ type VMDetail struct {
Memory string `json:"memory"`
Disk string `json:"disk"`
DiskController string `json:"disk_controller"`
DiskCache string `json:"disk_cache"`
Graphics string `json:"graphics"`
Display string `json:"display"`
Displays int `json:"displays"`
@@ -156,6 +166,7 @@ type CreateOpts struct {
Disk string `json:"disk,omitempty"`
DiskMode string `json:"disk_mode,omitempty"`
DiskController string `json:"disk_controller,omitempty"`
DiskCache string `json:"disk_cache,omitempty"`
Graphics string `json:"graphics,omitempty"`
GPU string `json:"gpu,omitempty"`
Resolution string `json:"resolution,omitempty"`
@@ -179,6 +190,7 @@ type SetOpts struct {
Graphics string `json:"graphics,omitempty"`
Displays int `json:"displays,omitempty"`
DiskController string `json:"disk_controller,omitempty"`
DiskCache string `json:"disk_cache,omitempty"`
Resolution string `json:"resolution,omitempty"`
Borderless *bool `json:"borderless,omitempty"`
Capture *bool `json:"capture,omitempty"`
@@ -259,13 +271,20 @@ func ValidateCreate(o CreateOpts, rep host.Report, loc i18n.Locale) []Validation
}
}
if o.Disk != "" {
if _, err := os.Stat(o.Disk); err != nil {
if IsWindowsRawDevicePath(o.Disk) {
if mode := strings.ToLower(strings.TrimSpace(o.DiskMode)); mode != "" && mode != "in-place" && mode != "inplace" {
issues = append(issues, ValidationIssue{Field: "disk_mode", Code: "raw_disk_in_place_only", Message: i18n.T(loc, "validate.raw_disk_in_place_only")})
}
} else if _, err := os.Stat(o.Disk); err != nil {
issues = append(issues, ValidationIssue{Field: "disk", Code: "disk_not_found", Message: i18n.T(loc, "validate.disk_not_found")})
}
}
if dc := strings.ToLower(strings.TrimSpace(o.DiskController)); dc != "" && dc != "nvme" && dc != "ahci" && dc != "virtio" {
issues = append(issues, ValidationIssue{Field: "disk_controller", Code: "invalid_disk_controller", Message: i18n.T(loc, "validate.invalid_disk_controller")})
}
if !validDiskCache(o.DiskCache) {
issues = append(issues, ValidationIssue{Field: "disk_cache", Code: "invalid_disk_cache", Message: i18n.T(loc, "validate.invalid_disk_cache")})
}
if o.Installer != "" {
if _, err := os.Stat(o.Installer); err != nil {
issues = append(issues, ValidationIssue{Field: "installer", Code: "installer_not_found", Message: i18n.T(loc, "validate.installer_not_found")})
@@ -322,6 +341,9 @@ func ValidateSet(o SetOpts, current VMDetail, rep host.Report, loc i18n.Locale)
if o.DiskController != "" && current.HasInstaller {
issues = append(issues, ValidationIssue{Field: "disk_controller", Code: "eject_before_controller_change", Message: i18n.T(loc, "validate.eject_before_controller_change")})
}
if !validDiskCache(o.DiskCache) {
issues = append(issues, ValidationIssue{Field: "disk_cache", Code: "invalid_disk_cache", Message: i18n.T(loc, "validate.invalid_disk_cache")})
}
if o.GPU != "" && o.GPU != "auto" && strings.HasSuffix(strings.ToLower(o.GPU), ".json") {
if _, err := os.Stat(o.GPU); err != nil {
issues = append(issues, ValidationIssue{Field: "gpu", Code: "gpu_icd_not_found", Message: i18n.T(loc, "validate.gpu_icd_not_found")})
@@ -383,8 +405,13 @@ func BuildCreateArgs(o CreateOpts) ([]string, error) {
args = append(args, "--disk", o.Disk)
if o.DiskMode != "" {
args = append(args, "--disk-mode", o.DiskMode)
} else if IsWindowsRawDevicePath(o.Disk) {
args = append(args, "--disk-mode", "in-place")
}
}
if dcache := strings.ToLower(strings.TrimSpace(o.DiskCache)); dcache != "" && dcache != "default" {
args = append(args, "--disk-cache", dcache)
}
if o.Graphics != "" {
args = append(args, "--graphics", o.Graphics)
}
@@ -510,6 +537,9 @@ func BuildSetArgs(o SetOpts) ([]string, error) {
if o.DiskController != "" {
args = append(args, "--disk-controller", o.DiskController)
}
if dcache := strings.ToLower(strings.TrimSpace(o.DiskCache)); dcache != "" {
args = append(args, "--disk-cache", dcache)
}
if o.Resolution != "" {
args = append(args, "--resolution", o.Resolution)
}
@@ -592,6 +622,15 @@ func parseDisplayCount(v string) int {
return 1
}
func validDiskCache(v string) bool {
switch strings.ToLower(strings.TrimSpace(v)) {
case "", "default", "writeback", "none", "unsafe":
return true
default:
return false
}
}
// 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 {
@@ -600,6 +639,7 @@ func ParseShow(name, text string) VMDetail {
Displays: 1,
Resolution: "1920x1080",
DiskController: "ahci",
DiskCache: "default",
Graphics: "reims-vgpu",
GPU: "auto",
Capture: true,
@@ -639,6 +679,10 @@ func ParseShow(name, text string) VMDetail {
default:
d.DiskController = "ahci"
}
case "disk cache":
if low := strings.ToLower(strings.TrimSpace(v)); low != "" {
d.DiskCache = low
}
case "graphics":
// "VMware SVGA, no GPU acceleration, in QEMU's window" (3731afd
// cli.rs describe); older builds printed "vmware-svga".
+4
View File
@@ -521,7 +521,11 @@
"validate.missing_release": "Choose the macOS release to install offline",
"validate.invalid_disk_size": "New disk size must be at least 32G (recommended 128G)",
"validate.disk_not_found": "Selected disk image file does not exist",
"validate.raw_disk_in_place_only": "Windows raw disk or partition paths must be attached in place",
"validate.raw_disk_requires_runtime": "Active runtime does not support Windows raw disk passthrough; update to a newer runtime",
"validate.invalid_disk_controller": "Disk controller must be nvme, ahci, or virtio",
"validate.invalid_disk_cache": "Disk cache mode must be default, writeback, none, or unsafe",
"validate.disk_cache_requires_runtime": "Active runtime does not support --disk-cache; update to a newer runtime",
"validate.installer_not_found": "Selected installer image file does not exist",
"validate.gpu_icd_not_found": "Selected Vulkan ICD JSON file does not exist",
"validate.invalid_resolution": "Resolution must match WIDTHxHEIGHT (e.g. 1920x1080)",
+11
View File
@@ -379,11 +379,22 @@
"guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window",
"diskControllerVirtioHint": "Lower overhead but experimental; switch back to NVMe if you hit problems",
"diskControllerNvmeReadyHint": "Fast and works with Recovery. Recommended",
"diskCacheTitle": "Disk I/O cache",
"diskCacheDescDefault": "Follows the current runtime default (writeback caching, flushes forwarded to host)",
"diskCacheDescWriteback": "Uses host page cache and forwards guest flushes safely to disk",
"diskCacheDescNone": "Direct I/O bypassing host page cache; recommended for raw partition passthrough",
"diskCacheDescUnsafe": "Warning: ignores guest flushes for peak throughput; host power loss or crash can corrupt the disk",
"diskCacheOptionDefault": "Default",
"diskCacheOptionWriteback": "Writeback",
"diskCacheOptionNone": "Direct",
"diskCacheOptionUnsafe": "Unsafe",
"diskCacheRequiresRuntime": "Update to a newer runtime to configure disk I/O cache policy",
"diskUsageSummary": "{actual} used of {virtual}",
"diskResizeTitle": "Expand disk",
"diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space",
"diskResizeAction": "Expand",
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
"diskResizeRawDisabled": "Windows raw partitions cannot be resized here",
"diskCompactTitle": "Reclaim space",
"diskRewriteSnapshots": "Delete internal restore points first to preserve them when rewriting the disk.",
"diskRewriteOverlay": "This disk shares a backing image and cannot be rewritten directly.",
+4
View File
@@ -521,7 +521,11 @@
"validate.missing_release": "请选择要离线安装的 macOS 版本",
"validate.invalid_disk_size": "新建磁盘上限不能小于 32G(推荐 128G)",
"validate.disk_not_found": "所选虚拟磁盘文件不存在",
"validate.raw_disk_in_place_only": "Windows 裸分区或物理盘路径仅支持原地直挂(in-place)",
"validate.raw_disk_requires_runtime": "当前运行时不支持 Windows 裸分区/物理盘直通,请更新至新版运行时",
"validate.invalid_disk_controller": "磁盘控制器仅支持 nvme、ahci 或 virtio",
"validate.invalid_disk_cache": "磁盘缓存策略仅支持 default、writeback、none 或 unsafe",
"validate.disk_cache_requires_runtime": "当前运行时不支持 --disk-cache,请更新至新版运行时",
"validate.installer_not_found": "所选安装镜像文件不存在",
"validate.gpu_icd_not_found": "所选 Vulkan ICD JSON 文件不存在",
"validate.invalid_resolution": "分辨率格式须为 宽x高(如 1920x1080)",
+11
View File
@@ -379,11 +379,22 @@
"guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言",
"diskControllerVirtioHint": "VirtIO 开销更低,仍属实验性;遇到问题请改回 NVMe",
"diskControllerNvmeReadyHint": "NVMe 速度快,也兼容恢复模式,推荐",
"diskCacheTitle": "磁盘 I/O 缓存策略",
"diskCacheDescDefault": "跟随运行时默认策略(回写缓存并正常转发刷盘请求)",
"diskCacheDescWriteback": "经宿主机页缓存回写,并安全转发 Guest 刷盘请求",
"diskCacheDescNone": "绕过宿主机页缓存直通磁盘(Direct I/O),适合裸分区直挂",
"diskCacheDescUnsafe": "警告:忽略 Guest 刷盘指令以换取最高吞吐,宿主机断电或崩溃可能导致磁盘损坏",
"diskCacheOptionDefault": "默认",
"diskCacheOptionWriteback": "回写",
"diskCacheOptionNone": "直通",
"diskCacheOptionUnsafe": "激进 (Unsafe)",
"diskCacheRequiresRuntime": "当前运行时版本过旧,请更新到支持磁盘缓存策略的新版运行时",
"diskUsageSummary": "已占用 {actual},上限 {virtual}",
"diskResizeTitle": "扩大磁盘",
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
"diskResizeAction": "扩容",
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
"diskResizeRawDisabled": "Windows 裸分区不支持在此调整容量",
"diskCompactTitle": "回收空间",
"diskRewriteSnapshots": "请先删除内部恢复点,以免重写磁盘时丢失。",
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",