Compare commits

...
4 Commits
Author SHA1 Message Date
Nwflower 5c71ac8482 release: v0.2.8
Release Reims-Go / release (push) Canceled after 0s
2026-11-29 18:17:13 -07:00
Nwflower 78d76f7353 feat(host,ui): probe Vulkan 1.3 GPU capabilities and grade compatibility 2026-11-29 18:16:20 -07:00
Nwflower 5096d162cc fix(runtime): extract .tar.zst archives in pure Go 2026-11-29 18:08:19 -07:00
Nwflower 29e9153d64 fix(vmstart): check WHPX before launch and clarify no-accelerator error 2026-11-29 18:08:12 -07:00
35 changed files with 1572 additions and 129 deletions

No files matched your search

+9
View File
@@ -2,6 +2,15 @@
本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。
## v0.2.8 — 2026-11-29
### 优化与修复
- 修复 Windows 10 22H2 等环境下系统自带 `tar.exe` 缺少 `zstd` 解压器导致在线下载或导入本地 `.tar.zst` 运行时包失败的问题([#5](https://github.com/Nwflower/Reims-Go/issues/5)),改为内置纯 Go 解压 `.tar.zst`。
- 新增真实 Vulkan 1.3 能力探测与显卡兼容性分级:启动器与 `reims-go doctor` 直接通过 `vulkan-1.dll` 核验 Vulkan 版本、PCI ID 与必需扩展,自动标记不满足门槛的老显卡及 Windows 下存在上游黑屏/设备丢失风险的 AMD Vega/Polaris([#4](https://github.com/Nwflower/Reims-Go/issues/4))与 RX 6600 XT 型号,并在向导与设置页支持一键改用 `VMware SVGA`。
- 修复 `ClassifyGPU` 对 AMD 核显(`AMD Radeon Graphics` / `680M/780M/890M` / `Vega`)与 Intel Core Ultra 集成 Arc 显卡的识别,过滤已失效的注册表 ICD 路径;新建虚拟机默认显卡改为 `auto`,避免升级显卡驱动后因 `DriverStore` 路径变化导致配置失效。
- 启动虚拟机前预先检查 WHPX 虚拟化平台状态,未开启虚拟化时给出明确中文/英文指引,不再因 QEMU 返回 `-ENOSPC` 误报磁盘空间不足;同时识别启动日志中的 `ERROR_DEVICE_LOST` 与 Vulkan 门槛拒绝并在排障包中记录 GPU 诊断结论。
## v0.2.7 — 2026-11-29
### 新功能
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.7",
"version": "0.2.8",
"type": "module",
"scripts": {
"dev": "vite",
+37 -4
View File
@@ -6,8 +6,11 @@ import {
MEMORY_MARKS,
controllerLabel,
defaultGuestLang,
findGPU,
formatMemory,
gpuCompatHint,
gpuLabel,
gpuOptionValue,
guestLangLabel,
memorySafeLimitGB,
parseMemoryGB,
@@ -102,8 +105,10 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
disk: '',
disk_mode: 'copy',
disk_controller: 'nvme',
graphics: 'reims-vgpu',
gpu: host.recommended_gpu?.vulkan_icd ?? 'auto',
graphics: host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga',
// Default to "auto" rather than a DriverStore FileRepository ICD path so
// Windows GPU driver updates never break existing VM configs.
gpu: 'auto',
resolution: recommendedResolution(host),
displays: 1,
borderless: false,
@@ -195,6 +200,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : [])
const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual')
const selectedGPU = findGPU(host, opts.gpu)
const selectedGPUHint = gpuCompatHint(locale, selectedGPU)
const threads = Math.max(host.logical_cpus || 0, 1)
const cpuRec = recommendedCPUs(host)
const memRec = recommendedMemoryGB(host)
@@ -485,7 +492,22 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
title={tr('gpuSelect')}
disabled={opts.graphics !== 'reims-vgpu'}
reason={tr('gpuSvgaReason')}
desc={realGPUs.length === 0 ? <span className="warn-text">{tr('gpuUnavailableHint')}</span> : undefined}
desc={
realGPUs.length === 0 ? (
<span className="warn-text">{tr('gpuUnavailableHint')}</span>
) : selectedGPUHint ? (
<span className="warn-text">
{selectedGPUHint}{' '}
<button
type="button"
className="link-btn"
onClick={() => set({ graphics: 'vmware-svga' })}
>
{tr('gpuSwitchSvga')}
</button>
</span>
) : undefined
}
control={
<PopupSelect
id="vm-gpu"
@@ -494,7 +516,18 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
onChange={(gpu) => set({ gpu })}
options={[
{ value: 'auto', label: tr('gpuAutoTitle'), detail: host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : undefined },
...realGPUs.map((g) => ({ value: g.vulkan_icd, label: shortGPUName(g.name) })),
...realGPUs.map((g) => ({
value: gpuOptionValue(g, realGPUs),
label: shortGPUName(g.name),
detail:
g.compat === 'unsupported'
? tr('gpuCompatUnsupported')
: g.compat === 'warn'
? tr('gpuCompatWarn')
: g.vulkan_version
? `Vulkan ${g.vulkan_version}`
: undefined,
})),
]}
/>
}
+19 -10
View File
@@ -1,7 +1,7 @@
import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { formatBytes } from '../lib/format'
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
import { AppState, Locale, RuntimeSource, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { api } from '../wails'
@@ -202,17 +202,26 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
{realGPUs.length === 0 ? (
<div className="row"><span className="row-sub">—</span></div>
) : (
realGPUs.map((g) => (
<div className="row" key={g.vulkan_icd}>
<div className="row-main">
<div className="row-title" title={g.vulkan_icd}>
{g.name}
<span className={`badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
{host.recommended_gpu?.vulkan_icd === g.vulkan_icd && <span className="badge badge-ok">{tr('gpuRecommended')}</span>}
realGPUs.map((g, idx) => {
const meta = gpuMetaLine(g)
const hint = gpuCompatHint(locale, g)
const isRec = sameGPU(host.recommended_gpu, g)
return (
<div className="row" key={gpuKey(g, idx)}>
<div className="row-main">
<div className="row-title" title={g.vulkan_icd}>
{g.name}
<span className={`badge ${g.kind === 'discrete' ? 'badge-accent' : ''}`}>{gpuKind(g.kind)}</span>
{g.compat === 'unsupported' && <span className="badge badge-warn">{tr('gpuCompatUnsupported')}</span>}
{g.compat === 'warn' && <span className="badge badge-warn">{tr('gpuCompatWarn')}</span>}
{isRec && g.compat !== 'warn' && g.compat !== 'unsupported' && <span className="badge badge-ok">{tr('gpuRecommended')}</span>}
</div>
{meta && <div className="row-sub">{meta}</div>}
{hint && <div className="row-sub warn-text">{hint}</div>}
</div>
</div>
</div>
))
)
})
)}
</div>
</section>
+33 -3
View File
@@ -5,7 +5,10 @@ import {
GUEST_LANG_PRESETS,
splitLangLabel,
MEMORY_MARKS,
findGPU,
formatBytes,
gpuCompatHint,
gpuOptionValue,
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
@@ -487,14 +490,21 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
sub: host.recommended_gpu ? tr('gpuAutoSub', { name: shortGPUName(host.recommended_gpu.name) }) : tr('gpuAutoOption'),
},
...realGPUs.map((g) => ({
value: g.vulkan_icd,
value: gpuOptionValue(g, realGPUs),
title: shortGPUName(g.name),
sub: g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : undefined,
sub: [
g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : '',
g.compat === 'unsupported' ? tr('gpuCompatUnsupported') : g.compat === 'warn' ? tr('gpuCompatWarn') : '',
]
.filter(Boolean)
.join(' · ') || undefined,
})),
]
if (form.gpu && form.gpu !== 'auto' && !gpuOptions.some((o) => normPath(o.value) === normPath(form.gpu))) {
gpuOptions.push({ value: form.gpu, title: form.gpu.split(/[\\/]/).pop() || form.gpu, sub: tr('gpuCustomIcd') })
}
const selectedGPU = findGPU(host, form.gpu)
const selectedGPUHint = gpuCompatHint(locale, selectedGPU)
const vgpu = form.graphics !== 'vmware-svga'
const pd = host.primary_display
const hidpiAdvice = hostDisplayAdvice(host, tr)
@@ -527,7 +537,27 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
<SetRow
{...rowProps('gpu')}
title={tr('gpuSelect')}
desc={realGPUs.length === 0 ? <span className="warn-text">{tr('gpuUnavailableHint')}</span> : undefined}
desc={
realGPUs.length === 0 ? (
<span className="warn-text">{tr('gpuUnavailableHint')}</span>
) : selectedGPUHint ? (
<span className="warn-text">
{selectedGPUHint}
{!running && vgpu && (
<>
{' '}
<button
type="button"
className="link-btn"
onClick={() => set({ graphics: 'vmware-svga' })}
>
{tr('gpuSwitchSvga')}
</button>
</>
)}
</span>
) : undefined
}
disabled={!vgpu}
reason={tr('gpuSvgaReason')}
block={<OptionCards label={tr('gpuSelect')} value={gpuOptions.find((o) => normPath(o.value) === normPath(form.gpu))?.value} onChange={(gpu) => set({ gpu })} options={gpuOptions} />}
+15 -2
View File
@@ -4,7 +4,7 @@ import { getLocaleOptions, I18nKey, joinNotices, t } from '../i18n'
import { AppState, DataRootCheck, DataRootChoice, Locale, ResolvedLocalePack, RuntimeSource, Task } from '../types'
import { Button } from '../ui/controls'
import { PopupSelect } from '../ui/settings'
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
@@ -165,6 +165,8 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
}
const whpxOK = host.whpx === 'ready'
const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual')
const gpuHint = gpuCompatHint(locale, gpu)
const gpuOK = !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported'
const recMem = recommendedMemoryGB(host)
return (
<>
@@ -198,9 +200,20 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
<div className="row-main">
<div className="row-title">{tr('setupGPU')}</div>
<div className="row-sub">{gpu ? shortGPUName(gpu.name) : tr('setupNoGPU')}</div>
{gpuHint && <div className="row-sub warn-text">{gpuHint}</div>}
</div>
<div className="row-right">
<span className={`badge ${gpu ? 'badge-ok' : 'badge-warn'}`}>{tr(gpu ? 'whpxReady' : 'hostNeedsAction')}</span>
<span className={`badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
{tr(
gpuOK
? 'whpxReady'
: gpu?.compat === 'unsupported'
? 'gpuCompatUnsupported'
: gpu?.compat === 'warn'
? 'gpuCompatWarn'
: 'hostNeedsAction',
)}
</span>
</div>
</div>
<div className="row">
+16
View File
@@ -403,6 +403,14 @@ const dict = {
gpuIntegrated: '核显',
gpuVirtual: '虚拟',
gpuUnknown: '未知',
gpuCompatWarn: '已知兼容风险',
gpuCompatUnsupported: '不支持加速',
gpuWarnAmdLegacy: 'AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题({ref});若有其他独显请改选独显,否则建议暂用 VMware SVGA',
gpuWarnAmdRdna2: '该 AMD 显卡在 Windows 下存在上游已知设备丢失风险({ref});若卡死黑屏请升级驱动或暂用 VMware SVGA',
gpuErrVulkanTooOld: 'Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA',
gpuErrMissingExt: '缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA',
gpuErrVulkanCpu: '软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA',
gpuSwitchSvga: '改用 VMware SVGA',
// Wizard
wizardTitle: '新建虚拟机',
@@ -1183,6 +1191,14 @@ const dict = {
gpuIntegrated: 'Integrated',
gpuVirtual: 'Virtual',
gpuUnknown: 'Unknown',
gpuCompatWarn: 'Known issue',
gpuCompatUnsupported: 'Unsupported',
gpuWarnAmdLegacy: 'AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues ({ref}); prefer another discrete GPU or use VMware SVGA for now',
gpuWarnAmdRdna2: 'This AMD GPU hits known Windows device-loss issues upstream ({ref}); update drivers or use VMware SVGA if it freezes',
gpuErrVulkanTooOld: 'Vulkan {ver} is below the required 1.3 floor; update GPU drivers or use VMware SVGA',
gpuErrMissingExt: 'Missing required Vulkan extensions ({ext}); update GPU drivers or use VMware SVGA',
gpuErrVulkanCpu: 'Software Vulkan implementation cannot accelerate vGPU; use VMware SVGA',
gpuSwitchSvga: 'Use VMware SVGA',
wizardTitle: 'New virtual machine',
srcOfflineTitle: 'Offline installer',
+57 -3
View File
@@ -62,9 +62,63 @@ export function controllerLabel(raw: string): string {
}
}
function findGPU(host: HostReport, icd: string): GPUInfo | undefined {
const norm = (s: string) => s.replace(/\//g, '\\').toLowerCase()
return (host.gpus ?? []).find((g) => norm(g.vulkan_icd) === norm(icd))
const normPath = (s: string) => s.replace(/\//g, '\\').toLowerCase()
export function gpuKey(g: GPUInfo, idx = 0): string {
const pci = g.vendor_id && g.device_id ? `${g.vendor_id}:${g.device_id}` : ''
return `${pci}|${normPath(g.vulkan_icd || '')}|${g.name}|${idx}`
}
export function sameGPU(a?: GPUInfo, b?: GPUInfo): boolean {
if (!a || !b) return false
if (a.vendor_id && a.device_id && b.vendor_id && b.device_id) {
return a.vendor_id === b.vendor_id && a.device_id === b.device_id
}
return !!a.vulkan_icd && normPath(a.vulkan_icd) === normPath(b.vulkan_icd) && a.name === b.name
}
/** Stable `--gpu` value for a GPU: its ICD path when unique, else its name (for shared AMD ICDs). */
export function gpuOptionValue(g: GPUInfo, all: GPUInfo[]): string {
if (g.vulkan_icd) {
const target = normPath(g.vulkan_icd)
const shared = all.filter((o) => o.vulkan_icd && normPath(o.vulkan_icd) === target).length > 1
if (!shared) return g.vulkan_icd
}
return g.name
}
export function findGPU(host: HostReport, value: string | undefined): GPUInfo | undefined {
if (!value || value === 'auto') return host.recommended_gpu
const norm = normPath(value)
return (host.gpus ?? []).find(
(g) => (g.vulkan_icd && normPath(g.vulkan_icd) === norm) || g.name.toLowerCase() === value.toLowerCase(),
)
}
export function gpuMetaLine(g: GPUInfo): string {
const parts: string[] = []
if (g.vendor_id && g.device_id) parts.push(`${g.vendor_id}:${g.device_id}`)
if (g.vulkan_version) parts.push(`Vulkan ${g.vulkan_version}`)
if (g.driver_version) parts.push(g.driver_version)
return parts.join(' · ')
}
export function gpuCompatHint(locale: Locale, g?: GPUInfo): string {
if (!g) return ''
switch (g.compat_code) {
case 'amd_legacy_win_driver':
return t(locale, 'gpuWarnAmdLegacy', { ref: g.compat_detail || 'steelbrain/reims-vgpu#181' })
case 'amd_rdna2_device_lost':
return t(locale, 'gpuWarnAmdRdna2', { ref: g.compat_detail || 'steelbrain/reims-vgpu#173' })
case 'vulkan_too_old':
return t(locale, 'gpuErrVulkanTooOld', { ver: g.compat_detail || g.vulkan_version || '?' })
case 'vulkan_missing_extensions':
return t(locale, 'gpuErrMissingExt', { ext: g.compat_detail || '' })
case 'vulkan_cpu':
return t(locale, 'gpuErrVulkanCpu')
default:
return ''
}
}
/** Drop vendor boilerplate: "NVIDIA GeForce RTX 4070 Ti" → "RTX 4070 Ti". */
+4 -1
View File
@@ -23,8 +23,11 @@ export type AudioInfo = host.AudioInfo
export type WHPXCapabilities = host.WHPXCapabilities
export type LogicalCPUInfo = host.LogicalCPUInfo
export type GPUInfo = Model<host.GPUInfo> & {
export type GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown'
export type GPUInfo = Omit<Model<host.GPUInfo>, 'compat'> & {
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
compat?: GPUCompat
}
export type OptimizationStatus = 'recommended' | 'available' | 'experimental' | 'auto' | 'unavailable'
+14
View File
@@ -592,6 +592,13 @@ export namespace host {
name: string;
vulkan_icd: string;
kind: string;
vendor_id?: string;
device_id?: string;
driver_version?: string;
vulkan_version?: string;
compat?: string;
compat_code?: string;
compat_detail?: string;
static createFrom(source: any = {}) {
return new GPUInfo(source);
@@ -602,6 +609,13 @@ export namespace host {
this.name = source["name"];
this.vulkan_icd = source["vulkan_icd"];
this.kind = source["kind"];
this.vendor_id = source["vendor_id"];
this.device_id = source["device_id"];
this.driver_version = source["driver_version"];
this.vulkan_version = source["vulkan_version"];
this.compat = source["compat"];
this.compat_code = source["compat_code"];
this.compat_detail = source["compat_detail"];
}
}
export class LogicalCPUInfo {
+1
View File
@@ -3,6 +3,7 @@ module github.com/Nwflower/reims-go
go 1.26.0
require (
github.com/klauspost/compress v1.20.5
github.com/ulikunitz/xz v0.5.17
github.com/wailsapp/wails/v2 v2.17.1
golang.org/x/net v0.60.0
+2
View File
@@ -16,6 +16,8 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck=
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/labstack/echo/v4 v4.16.1 h1:h05NuF1GvNu6jSAZxOv++AdjD/NJK+mZdGy0thiiuns=
github.com/labstack/echo/v4 v4.16.1/go.mod h1:V/EQaTVHYJH92QhbQe7kFQ4mjgcjxLQQUQtAN87zZdw=
github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c=
+4
View File
@@ -1152,6 +1152,10 @@ func (a *App) StartVM(name string) error {
tmpDir := a.cfg.TempDir()
a.mu.Unlock()
rep := host.Inspect(root)
if err := prep.CheckWHPX(rep); err != nil {
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())
+6
View File
@@ -57,6 +57,12 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
"host": b.HostReport,
"optimizations": b.Optimizations,
}
if code, detail := reims.DiagnoseGPULog(b.QEMULog); code != "" {
hostSummary["gpu_diagnosis"] = map[string]string{
"code": code,
"detail": detail,
}
}
if err := addJSON("host-report.json", hostSummary); err != nil {
_ = zw.Close()
_ = f.Close()
+58 -4
View File
@@ -207,11 +207,38 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
} else {
fmt.Printf("%s:\n", i18n.T(loc, "doctor.gpu"))
for _, g := range rep.GPUs {
rec := ""
if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD == g.VulkanICD {
rec = " [" + i18n.T(loc, "doctor.gpu.recommended") + "]"
tags := []string{}
if rep.RecommendedGPU != nil && sameGPU(rep.RecommendedGPU, &g) {
tags = append(tags, i18n.T(loc, "doctor.gpu.recommended"))
}
if g.Compat != "" {
tags = append(tags, i18n.T(loc, "doctor.gpu.compat."+string(g.Compat)))
}
tagStr := ""
if len(tags) > 0 {
tagStr = " [" + strings.Join(tags, " | ") + "]"
}
meta := []string{}
if g.VendorID != "" && g.DeviceID != "" {
meta = append(meta, g.VendorID+":"+g.DeviceID)
}
if g.VulkanVersion != "" {
meta = append(meta, "Vulkan "+g.VulkanVersion)
}
if g.DriverVersion != "" {
meta = append(meta, "drv "+g.DriverVersion)
}
metaStr := ""
if len(meta) > 0 {
metaStr = " (" + strings.Join(meta, ", ") + ")"
}
fmt.Printf(" - [%s] %s%s%s\n", g.Kind, g.Name, metaStr, tagStr)
if g.VulkanICD != "" {
fmt.Printf(" ICD: %s\n", g.VulkanICD)
}
if note := formatGPUCompatNote(loc, g); note != "" {
fmt.Printf(" ! %s\n", note)
}
fmt.Printf(" - [%s] %s%s\n ICD: %s\n", g.Kind, g.Name, rec, g.VulkanICD)
}
}
@@ -223,6 +250,33 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
return nil
}
func sameGPU(a, b *host.GPUInfo) bool {
if a == nil || b == nil {
return false
}
if a.VendorID != "" && a.DeviceID != "" && b.VendorID != "" && b.DeviceID != "" {
return a.VendorID == b.VendorID && a.DeviceID == b.DeviceID
}
return a.VulkanICD != "" && a.VulkanICD == b.VulkanICD && a.Name == b.Name
}
func formatGPUCompatNote(loc i18n.Locale, g host.GPUInfo) string {
switch g.CompatCode {
case "amd_legacy_win_driver":
return i18n.T(loc, "doctor.gpu.warn.amd_legacy", g.CompatDetail)
case "amd_rdna2_device_lost":
return i18n.T(loc, "doctor.gpu.warn.amd_rdna2", g.CompatDetail)
case "vulkan_too_old":
return i18n.T(loc, "doctor.gpu.err.vulkan_too_old", g.CompatDetail)
case "vulkan_missing_extensions":
return i18n.T(loc, "doctor.gpu.err.missing_ext", g.CompatDetail)
case "vulkan_cpu":
return i18n.T(loc, "doctor.gpu.err.vulkan_cpu")
default:
return ""
}
}
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use>")
+3
View File
@@ -40,6 +40,9 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
// Preparation rewrites extra-args and the OpenCore image; never under a live VM.
return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name))
}
if err := prep.CheckWHPX(rep); err != nil {
return err
}
if err := prep.CheckMemory(d.Memory, rep); err != nil {
return err
}
+61
View File
@@ -3,11 +3,14 @@ package reims
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"github.com/Nwflower/reims-go/internal/i18n"
)
// creatingMarker is written by upstream `reims-ctl create` while building a VM
@@ -52,6 +55,15 @@ func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMLi
return target, nil
}
// IsWHPXNoAcceleratorError reports whether QEMU exited because Windows
// Hypervisor was not active. In that branch QEMU logs "WHPX: No accelerator
// found" and returns -ENOSPC ("failed to initialize whpx: No space left on
// device"), which is unrelated to disk space.
func IsWHPXNoAcceleratorError(output string) bool {
return strings.Contains(output, "WHPX: No accelerator found") ||
strings.Contains(output, "failed to initialize whpx: No space left on device")
}
// IsWHPXNestedVirtError reports whether QEMU exited because WHPX failed to
// enable nested virtualization (e.g. hr=80370302 WHV_E_UNKNOWN_PROPERTY on
// Windows 11 builds that advertise Bank1.NestedVirtSupport but reject
@@ -61,6 +73,41 @@ func IsWHPXNestedVirtError(output string) bool {
return strings.Contains(output, "WHPX: Failed to enable nested virtualization")
}
// DiagnoseGPULog inspects QEMU / reims-vgpu output for known Vulkan GPU
// compatibility or device-loss failures and returns a machine-readable code
// ("gpu_device_lost" | "gpu_vulkan_floor") and matching line excerpt.
func DiagnoseGPULog(output string) (code, detail string) {
if output == "" {
return "", ""
}
for _, rawLine := range strings.Split(output, "\n") {
line := strings.TrimSpace(rawLine)
if line == "" {
continue
}
if strings.Contains(line, "ERROR_DEVICE_LOST") ||
strings.Contains(line, "was lost at vkQueueSubmit2") ||
strings.Contains(line, "rt-device-lost-in-flight") {
return "gpu_device_lost", line
}
}
for _, rawLine := range strings.Split(output, "\n") {
line := strings.TrimSpace(rawLine)
if line == "" {
continue
}
low := strings.ToLower(line)
if strings.Contains(line, "VK_ERROR_INCOMPATIBLE_DRIVER") ||
strings.Contains(low, "no vulkan gpu found") ||
strings.Contains(low, "meets the floor") ||
strings.Contains(low, "below the floor") ||
strings.Contains(low, "no physical device") {
return "gpu_vulkan_floor", line
}
}
return "", ""
}
// HasKernelIrqchipArg reports whether extra-args already specifies a
// kernel-irqchip setting.
func HasKernelIrqchipArg(extraArgs string) bool {
@@ -116,6 +163,20 @@ func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stder
return nil
}
combined := outCap.String() + "\n" + errCap.String()
if IsWHPXNoAcceleratorError(combined) {
msg := i18n.T(c.Locale, "err.whpx_no_hypervisor")
if onNote != nil {
onNote(msg)
}
return fmt.Errorf("%s (%w)", msg, err)
}
if gpuCode, _ := DiagnoseGPULog(combined); gpuCode != "" {
msg := i18n.T(c.Locale, "err."+gpuCode)
if onNote != nil {
onNote(msg)
}
return fmt.Errorf("%s (%w)", msg, err)
}
if !IsWHPXNestedVirtError(combined) {
return err
}
+28
View File
@@ -107,6 +107,34 @@ func TestWHPXNestedVirtCompat(t *testing.T) {
}
}
func TestIsWHPXNoAcceleratorError(t *testing.T) {
sample := "2026-11-29T18:01:40.594876Z qemu-system-x86_64.exe: -accel whpx: WHPX: No accelerator found, hr=00000000\n" +
"2026-11-29T18:01:40.596903Z qemu-system-x86_64.exe: -accel whpx: failed to initialize whpx: No space left on device\n"
if !IsWHPXNoAcceleratorError(sample) {
t.Fatalf("expected IsWHPXNoAcceleratorError to match WHPX ENOSPC output")
}
if !IsWHPXNoAcceleratorError("qemu: -accel whpx: failed to initialize whpx: No space left on device") {
t.Fatalf("expected IsWHPXNoAcceleratorError to match ENOSPC line alone")
}
if IsWHPXNoAcceleratorError("write disk.qcow2: No space left on device") {
t.Fatalf("must not misclassify genuine disk-full error as WHPX error")
}
}
func TestDiagnoseGPULog(t *testing.T) {
lost := "reims-vgpu: the rt platform's device on AMD Radeon (TM) Graphics (1002:15e7) was lost at vkQueueSubmit2 (ERROR_DEVICE_LOST)"
if code, detail := DiagnoseGPULog(lost); code != "gpu_device_lost" || detail == "" {
t.Fatalf("DiagnoseGPULog(lost) = (%q, %q), want gpu_device_lost", code, detail)
}
floor := "reims-vgpu: no physical device meets the floor (VK_ERROR_INCOMPATIBLE_DRIVER)"
if code, detail := DiagnoseGPULog(floor); code != "gpu_vulkan_floor" || detail == "" {
t.Fatalf("DiagnoseGPULog(floor) = (%q, %q), want gpu_vulkan_floor", code, detail)
}
if code, _ := DiagnoseGPULog("normal boot log line"); code != "" {
t.Fatalf("expected empty code for normal log, got %q", code)
}
}
func TestMergeAndStripOfflineHelperArgs(t *testing.T) {
base := `-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off -machine kernel-irqchip=off`
merged := MergeOfflineHelperArgs(base, `D:\Data\reims-go\cache\reims-helper.img`)
+6
View File
@@ -23,12 +23,18 @@ import (
type Client struct {
Binary string
Env []string
Locale i18n.Locale
}
func NewClient(cfg *config.Config, installed rt.Installed) *Client {
var loc i18n.Locale
if cfg != nil {
loc = cfg.Locale
}
return &Client{
Binary: installed.ReimsCtlPath(),
Env: rt.BuildChildEnv(cfg, installed),
Locale: loc,
}
}
+260
View File
@@ -0,0 +1,260 @@
package host
import (
"fmt"
"regexp"
"strings"
)
// RequiredVulkanExtensions mirrors the mandatory device extensions enforced by
// upstream metal2vulkan-runtime (crates/metal2vulkan-runtime/src/floor.rs:36-41).
var RequiredVulkanExtensions = []string{
"VK_KHR_swapchain",
"VK_EXT_robustness2",
"VK_EXT_calibrated_timestamps",
"VK_EXT_line_rasterization",
}
// VulkanDeviceProbe holds raw Vulkan physical-device properties queried via
// vulkan-1.dll on Windows.
type VulkanDeviceProbe struct {
Name string
VendorID uint32
DeviceID uint32
DeviceType uint32 // VkPhysicalDeviceType: 1=integrated, 2=discrete, 3=virtual, 4=cpu
APIVersion uint32
Extensions map[string]bool
}
var (
rePCIVen = regexp.MustCompile(`(?i)VEN_([0-9a-f]{4})`)
rePCIDev = regexp.MustCompile(`(?i)DEV_([0-9a-f]{4})`)
)
// ParsePCIIDs extracts lowercase 4-hex vendor and device IDs from a Windows
// PnP MatchingDeviceId string (e.g. "PCI\VEN_1002&DEV_164C&REV_C2").
func ParsePCIIDs(matchingID string) (vendorID, deviceID string) {
if m := rePCIVen.FindStringSubmatch(matchingID); len(m) == 2 {
vendorID = strings.ToLower(m[1])
}
if m := rePCIDev.FindStringSubmatch(matchingID); len(m) == 2 {
deviceID = strings.ToLower(m[1])
}
return vendorID, deviceID
}
// FormatVulkanVersion decodes a Vulkan packed API version uint32 into "major.minor.patch".
func FormatVulkanVersion(apiVersion uint32) string {
if apiVersion == 0 {
return ""
}
major := (apiVersion >> 22) & 0x7F
minor := (apiVersion >> 12) & 0x3FF
patch := apiVersion & 0xFFF
return fmt.Sprintf("%d.%d.%d", major, minor, patch)
}
func vulkanSupports13(apiVersion uint32) bool {
major := (apiVersion >> 22) & 0x7F
minor := (apiVersion >> 12) & 0x3FF
return major > 1 || (major == 1 && minor >= 3)
}
// amdLegacyVegaOrPolarisIDs covers AMD GCN4 (Polaris) and GCN5 (Vega) GPUs
// whose Windows proprietary Adrenalin driver moved to the legacy vega-polaris
// maintenance branch (26.5.2) and currently hits WindowServer black screen /
// vkQueueSubmit2 ERROR_DEVICE_LOST on Windows (steelbrain/reims-vgpu#181).
var amdLegacyVegaOrPolarisIDs = map[string]bool{
// Vega integrated APUs (Raven / Picasso / Renoir / Cezanne / Lucienne / Barcelo)
"15dd": true, // Raven Ridge / Picasso (Ryzen 2000/3000)
"15d8": true, // Picasso (Ryzen 3000U/H)
"1636": true, // Renoir (Ryzen 4000U/H/G)
"1638": true, // Cezanne / Barcelo (Ryzen 5000H/G)
"164c": true, // Lucienne (Ryzen 3 5300U / Ryzen 5 5500U / Ryzen 7 5700U)
"15e7": true, // Barcelo / Barcelo-R (Ryzen 5 5625U / Ryzen 7 5825U / 7530U / 7730U)
// Vega discrete GPUs (Vega 10 / 12 / 20)
"6860": true, "6861": true, "6862": true, "6863": true, "6864": true,
"6867": true, "6868": true, "686c": true, "687f": true,
"69a0": true, "69a1": true, "69a2": true, "69a3": true, "69af": true,
"66a0": true, "66a1": true, "66a2": true, "66a3": true, "66a7": true, "66af": true,
// Polaris discrete GPUs (RX 460/470/480/550/560/570/580/590)
"67df": true, "67ef": true, "67ff": true, "6fdf": true,
}
func isAMDLegacyVegaOrPolaris(vendorID, deviceID, name string) bool {
if vendorID == "1002" && deviceID != "" {
return amdLegacyVegaOrPolarisIDs[strings.ToLower(deviceID)]
}
if vendorID != "" && vendorID != "1002" {
return false
}
// Name fallback only when PCI device ID is unavailable.
low := strings.ToLower(name)
if !strings.Contains(low, "radeon") {
return false
}
for _, pat := range []string{
"radeon(tm) vega", "radeon vega", "rx vega", "radeon vii",
"rx 460", "rx 470", "rx 480", "rx 550", "rx 560", "rx 570", "rx 580", "rx 590",
} {
if strings.Contains(low, pat) {
return true
}
}
return false
}
// isAMDRDNA2DeviceLost reports GPUs hitting deterministic Windows 11
// vkQueueSubmit2 ERROR_DEVICE_LOST / GPU fault (READ_INVALID) at boot
// (steelbrain/reims-vgpu#173).
func isAMDRDNA2DeviceLost(vendorID, deviceID string) bool {
return vendorID == "1002" && strings.ToLower(deviceID) == "73ff"
}
// EvaluateGPUCompat merges optional Vulkan runtime probe data into g and
// assigns a compatibility grade aligned with metal2vulkan-runtime's floor
// requirements and verified Windows upstream issues.
func EvaluateGPUCompat(g GPUInfo, probe *VulkanDeviceProbe) GPUInfo {
if probe != nil {
if g.Name == "" {
g.Name = probe.Name
}
if probe.VendorID != 0 {
g.VendorID = fmt.Sprintf("%04x", probe.VendorID)
}
if probe.DeviceID != 0 {
g.DeviceID = fmt.Sprintf("%04x", probe.DeviceID)
}
g.VulkanVersion = FormatVulkanVersion(probe.APIVersion)
// VkPhysicalDeviceType: 1=INTEGRATED_GPU, 2=DISCRETE_GPU, 3=VIRTUAL_GPU, 4=CPU
switch probe.DeviceType {
case 4:
g.Kind = GPUVirtual
g.Compat = GPUCompatUnsupported
g.CompatCode = "vulkan_cpu"
g.CompatDetail = g.Name
return g
case 3:
g.Kind = GPUVirtual
case 2:
if g.Kind != GPUVirtual {
g.Kind = GPUDiscrete
}
case 1:
if g.Kind != GPUVirtual {
g.Kind = GPUIntegrated
}
}
}
if g.Kind == GPUVirtual {
g.Compat = GPUCompatUnsupported
g.CompatCode = "virtual_adapter"
return g
}
if probe != nil {
if !vulkanSupports13(probe.APIVersion) {
g.Compat = GPUCompatUnsupported
g.CompatCode = "vulkan_too_old"
g.CompatDetail = g.VulkanVersion
return g
}
if len(probe.Extensions) > 0 {
var missing []string
for _, ext := range RequiredVulkanExtensions {
if !probe.Extensions[ext] {
missing = append(missing, ext)
}
}
if len(missing) > 0 {
g.Compat = GPUCompatUnsupported
g.CompatCode = "vulkan_missing_extensions"
g.CompatDetail = strings.Join(missing, ", ")
return g
}
}
}
if isAMDLegacyVegaOrPolaris(g.VendorID, g.DeviceID, g.Name) {
g.Compat = GPUCompatWarn
g.CompatCode = "amd_legacy_win_driver"
g.CompatDetail = "steelbrain/reims-vgpu#181"
return g
}
if isAMDRDNA2DeviceLost(g.VendorID, g.DeviceID) {
g.Compat = GPUCompatWarn
g.CompatCode = "amd_rdna2_device_lost"
g.CompatDetail = "steelbrain/reims-vgpu#173"
return g
}
if probe != nil {
g.Compat = GPUCompatSupported
g.CompatCode = "ok"
return g
}
g.Compat = GPUCompatUnknown
g.CompatCode = "vulkan_unprobed"
return g
}
// MergeRegistryAndVulkanGPUs reconciles Windows display-class registry entries
// with live Vulkan physical devices from vulkan-1.dll, preserving ICD paths and
// driver versions while enriching each GPU with real Vulkan 1.3 capability and
// compatibility grades.
func MergeRegistryAndVulkanGPUs(regGPUs []GPUInfo, vkProbes []VulkanDeviceProbe) []GPUInfo {
used := make([]bool, len(vkProbes))
matchProbe := func(g GPUInfo) *VulkanDeviceProbe {
// 1. Exact PCI vendor:device match.
if g.VendorID != "" && g.DeviceID != "" {
for i := range vkProbes {
if used[i] {
continue
}
if fmt.Sprintf("%04x", vkProbes[i].VendorID) == g.VendorID &&
fmt.Sprintf("%04x", vkProbes[i].DeviceID) == g.DeviceID {
used[i] = true
return &vkProbes[i]
}
}
}
// 2. Case-insensitive name fallback when MatchingDeviceId was absent.
lowName := strings.ToLower(strings.TrimSpace(g.Name))
if lowName != "" {
for i := range vkProbes {
if used[i] {
continue
}
pName := strings.ToLower(strings.TrimSpace(vkProbes[i].Name))
if pName == lowName || strings.Contains(pName, lowName) || strings.Contains(lowName, pName) {
used[i] = true
return &vkProbes[i]
}
}
}
return nil
}
out := make([]GPUInfo, 0, len(regGPUs)+len(vkProbes))
for _, g := range regGPUs {
p := matchProbe(g)
out = append(out, EvaluateGPUCompat(g, p))
}
// Include any non-CPU Vulkan GPU enumerated by vulkan-1.dll that wasn't
// listed under the display-class registry (e.g. registered only under
// HKLM\SOFTWARE\Khronos\Vulkan\Drivers).
for i := range vkProbes {
if used[i] || vkProbes[i].DeviceType == 4 {
continue
}
p := vkProbes[i]
base := GPUInfo{
Name: p.Name,
Kind: ClassifyGPU(p.Name),
}
out = append(out, EvaluateGPUCompat(base, &p))
}
return out
}
+104 -21
View File
@@ -11,10 +11,26 @@ const (
GPUUnknown GPUKind = "unknown"
)
type GPUCompat string
const (
GPUCompatSupported GPUCompat = "supported"
GPUCompatWarn GPUCompat = "warn"
GPUCompatUnsupported GPUCompat = "unsupported"
GPUCompatUnknown GPUCompat = "unknown"
)
type GPUInfo struct {
Name string `json:"name"`
VulkanICD string `json:"vulkan_icd"`
Kind GPUKind `json:"kind"`
Name string `json:"name"`
VulkanICD string `json:"vulkan_icd"`
Kind GPUKind `json:"kind"`
VendorID string `json:"vendor_id,omitempty"`
DeviceID string `json:"device_id,omitempty"`
DriverVersion string `json:"driver_version,omitempty"`
VulkanVersion string `json:"vulkan_version,omitempty"`
Compat GPUCompat `json:"compat,omitempty"`
CompatCode string `json:"compat_code,omitempty"`
CompatDetail string `json:"compat_detail,omitempty"`
}
type WHPXState string
@@ -85,20 +101,43 @@ type Report struct {
Audio AudioInfo `json:"audio"`
}
// ClassifyGPU distinguishes discrete, integrated, and virtual display adapters.
// ClassifyGPU distinguishes discrete, integrated, and virtual display adapters
// from their Windows display adapter name when Vulkan device-type metadata is
// unavailable.
func ClassifyGPU(name string) GPUKind {
low := strings.ToLower(name)
for _, v := range []string{"todesk", "gameviewer", "parsec", "virtual", "idd", "microsoft basic", "spacedesk"} {
low := strings.ToLower(strings.TrimSpace(name))
for _, v := range []string{
"todesk", "gameviewer", "parsec", "virtual", "idd",
"microsoft basic", "microsoft remote", "spacedesk",
"llvmpipe", "lavapipe", "swiftshader",
} {
if strings.Contains(low, v) {
return GPUVirtual
}
}
for _, d := range []string{"nvidia", "geforce", "rtx", "gtx", "quadro", "radeon rx", "radeon pro", "intel(r) arc"} {
// Integrated Intel Arc (Core Ultra Meteor/Arrow/Lunar Lake: "Intel(R) Arc(TM) Graphics",
// "Intel(R) Arc(TM) 140V/130V/140T/130T") must be checked before discrete "intel(r) arc".
if isIntegratedIntelArcName(low) {
return GPUIntegrated
}
for _, d := range []string{
"nvidia", "geforce", "rtx", "gtx", "quadro",
"radeon rx", "radeon pro", "radeon vii", "radeon r9", "radeon r7",
"intel(r) arc", "intel arc",
} {
if strings.Contains(low, d) {
return GPUDiscrete
}
}
for _, i := range []string{"intel(r) uhd", "intel(r) hd", "intel(r) iris", "radeon(tm) graphics"} {
for _, i := range []string{
"intel(r) uhd", "intel(r) hd", "intel(r) iris", "intel(r) graphics",
"intel uhd", "intel hd", "intel iris",
"radeon(tm) graphics", "radeon graphics",
"radeon(tm) vega", "radeon vega",
"radeon 610m", "radeon 660m", "radeon 680m",
"radeon 740m", "radeon 760m", "radeon 780m",
"radeon 880m", "radeon 890m",
} {
if strings.Contains(low, i) {
return GPUIntegrated
}
@@ -106,27 +145,71 @@ func ClassifyGPU(name string) GPUKind {
return GPUUnknown
}
// PickRecommendedGPU selects the best Vulkan GPU (preferring discrete over integrated, skipping virtual).
func isIntegratedIntelArcName(low string) bool {
if !strings.Contains(low, "intel") || !strings.Contains(low, "arc") {
return false
}
// Discrete Arc cards carry an A/B/Pro series model designator (e.g. A380, A770, B580, Pro A60).
for _, token := range []string{" a3", " a5", " a7", " b5", " b7", " pro "} {
if strings.Contains(low, token) {
return false
}
}
return strings.Contains(low, "arc(tm) graphics") ||
strings.Contains(low, "arc graphics") ||
strings.Contains(low, "130v") ||
strings.Contains(low, "140v") ||
strings.Contains(low, "130t") ||
strings.Contains(low, "140t")
}
// PickRecommendedGPU selects the best Vulkan GPU, preferring verified-supported
// discrete GPUs over integrated ones, skipping virtual and unsupported GPUs,
// and falling back to warned GPUs only when no cleaner option exists.
func PickRecommendedGPU(gpus []GPUInfo) *GPUInfo {
for i := range gpus {
if gpus[i].Kind == GPUDiscrete && gpus[i].VulkanICD != "" {
cp := gpus[i]
return &cp
compatRank := func(c GPUCompat) int {
switch c {
case GPUCompatSupported, "":
return 0
case GPUCompatUnknown:
return 1
case GPUCompatWarn:
return 2
default: // GPUCompatUnsupported
return 99
}
}
for i := range gpus {
if gpus[i].Kind == GPUIntegrated && gpus[i].VulkanICD != "" {
cp := gpus[i]
return &cp
kindRank := func(k GPUKind) int {
switch k {
case GPUDiscrete:
return 0
case GPUIntegrated:
return 1
default:
return 2
}
}
bestIdx := -1
bestScore := 1000
for i := range gpus {
if gpus[i].Kind != GPUVirtual && gpus[i].VulkanICD != "" {
cp := gpus[i]
return &cp
g := gpus[i]
if g.Kind == GPUVirtual || g.Compat == GPUCompatUnsupported {
continue
}
if g.VulkanICD == "" && g.VulkanVersion == "" {
continue
}
score := compatRank(g.Compat)*10 + kindRank(g.Kind)
if score < bestScore {
bestScore = score
bestIdx = i
}
}
return nil
if bestIdx < 0 {
return nil
}
cp := gpus[bestIdx]
return &cp
}
// AllCPUsMask returns the 64-bit affinity mask covering logical CPUs 0..n-1
+115
View File
@@ -21,6 +21,121 @@ func TestGPUClassificationAndRecommendation(t *testing.T) {
if rec == nil || rec.VulkanICD != `C:\nv-vk64.json` {
t.Fatalf("expected NVIDIA discrete GPU to be recommended, got %#v", rec)
}
// Regression checks for AMD iGPUs and Intel Core Ultra integrated Arc vs discrete Arc.
cases := []struct {
name string
want GPUKind
}{
{"AMD Radeon Graphics", GPUIntegrated},
{"AMD Radeon(TM) Graphics", GPUIntegrated},
{"AMD Radeon(TM) Vega 8 Graphics", GPUIntegrated},
{"AMD Radeon 780M Graphics", GPUIntegrated},
{"AMD Radeon RX 7900 XTX", GPUDiscrete},
{"Intel(R) Arc(TM) Graphics", GPUIntegrated},
{"Intel(R) Arc(TM) 140V GPU", GPUIntegrated},
{"Intel(R) Arc(TM) A770 Graphics", GPUDiscrete},
{"Intel(R) Arc(TM) B580 Graphics", GPUDiscrete},
{"Microsoft Remote Display Adapter", GPUVirtual},
}
for _, tc := range cases {
if got := ClassifyGPU(tc.name); got != tc.want {
t.Errorf("ClassifyGPU(%q) = %s, want %s", tc.name, got, tc.want)
}
}
}
func TestGPUCompatibilityGradingAndRecommendation(t *testing.T) {
allReqExts := map[string]bool{
"VK_KHR_swapchain": true,
"VK_EXT_robustness2": true,
"VK_EXT_calibrated_timestamps": true,
"VK_EXT_line_rasterization": true,
}
v13 := uint32((1 << 22) | (3 << 12) | 289)
v12 := uint32((1 << 22) | (2 << 12) | 195)
if ven, dev := ParsePCIIDs(`PCI\VEN_1002&DEV_164C&SUBSYS_380117AA`); ven != "1002" || dev != "164c" {
t.Fatalf("ParsePCIIDs = (%q, %q), want (1002, 164c)", ven, dev)
}
if got := FormatVulkanVersion(v13); got != "1.3.289" {
t.Fatalf("FormatVulkanVersion = %q, want 1.3.289", got)
}
// 1. AMD Ryzen 5 5500U (Lucienne Vega 7, 1002:164c) -> warn (#181)
vega7 := EvaluateGPUCompat(
GPUInfo{Name: "AMD Radeon Graphics", VulkanICD: `C:\amd-vulkan64.json`, VendorID: "1002", DeviceID: "164c"},
&VulkanDeviceProbe{Name: "AMD Radeon(TM) Graphics", VendorID: 0x1002, DeviceID: 0x164c, DeviceType: 1, APIVersion: v13, Extensions: allReqExts},
)
if vega7.Kind != GPUIntegrated || vega7.Compat != GPUCompatWarn || vega7.CompatCode != "amd_legacy_win_driver" {
t.Fatalf("vega7 = %+v", vega7)
}
// 2. AMD RX 6600 XT (1002:73ff) -> warn (#173)
rx6600 := EvaluateGPUCompat(
GPUInfo{Name: "AMD Radeon RX 6600 XT", VulkanICD: `C:\amd-vulkan64.json`, VendorID: "1002", DeviceID: "73ff"},
&VulkanDeviceProbe{Name: "AMD Radeon RX 6600 XT", VendorID: 0x1002, DeviceID: 0x73ff, DeviceType: 2, APIVersion: v13, Extensions: allReqExts},
)
if rx6600.Compat != GPUCompatWarn || rx6600.CompatCode != "amd_rdna2_device_lost" {
t.Fatalf("rx6600 = %+v", rx6600)
}
// 3. AMD Radeon 780M (RDNA 3, 1002:15bf) -> supported
rdna3 := EvaluateGPUCompat(
GPUInfo{Name: "AMD Radeon 780M Graphics", VulkanICD: `C:\amd-vulkan64.json`, VendorID: "1002", DeviceID: "15bf"},
&VulkanDeviceProbe{Name: "AMD Radeon 780M Graphics", VendorID: 0x1002, DeviceID: 0x15bf, DeviceType: 1, APIVersion: v13, Extensions: allReqExts},
)
if rdna3.Compat != GPUCompatSupported || rdna3.Kind != GPUIntegrated {
t.Fatalf("rdna3 = %+v", rdna3)
}
// 4. Old Vulkan 1.2 GPU -> unsupported
oldVK := EvaluateGPUCompat(
GPUInfo{Name: "Old GPU", VulkanICD: `C:\old.json`, Kind: GPUDiscrete},
&VulkanDeviceProbe{Name: "Old GPU", VendorID: 0x10de, DeviceID: 0x1180, DeviceType: 2, APIVersion: v12, Extensions: allReqExts},
)
if oldVK.Compat != GPUCompatUnsupported || oldVK.CompatCode != "vulkan_too_old" {
t.Fatalf("oldVK = %+v", oldVK)
}
// 5. Missing required extension -> unsupported
noRob2 := EvaluateGPUCompat(
GPUInfo{Name: "Partial GPU", VulkanICD: `C:\p.json`, Kind: GPUIntegrated},
&VulkanDeviceProbe{Name: "Partial GPU", VendorID: 0x8086, DeviceID: 0x5912, DeviceType: 1, APIVersion: v13, Extensions: map[string]bool{"VK_KHR_swapchain": true}},
)
if noRob2.Compat != GPUCompatUnsupported || noRob2.CompatCode != "vulkan_missing_extensions" {
t.Fatalf("noRob2 = %+v", noRob2)
}
// 6. PickRecommendedGPU skips unsupported discrete GPU and picks supported iGPU.
rec := PickRecommendedGPU([]GPUInfo{oldVK, rdna3})
if rec == nil || rec.DeviceID != "15bf" {
t.Fatalf("PickRecommendedGPU(oldVK, rdna3) = %+v, want 15bf", rec)
}
// 7. PickRecommendedGPU skips unsupported completely -> nil.
if recNone := PickRecommendedGPU([]GPUInfo{oldVK, noRob2}); recNone != nil {
t.Fatalf("expected nil when all GPUs unsupported, got %+v", recNone)
}
// 8. PickRecommendedGPU prefers supported discrete over warned Vega iGPU.
rtx := EvaluateGPUCompat(
GPUInfo{Name: "NVIDIA GeForce RTX 3060", VulkanICD: `C:\nv-vk64.json`, VendorID: "10de", DeviceID: "2504"},
&VulkanDeviceProbe{Name: "NVIDIA GeForce RTX 3060", VendorID: 0x10de, DeviceID: 0x2504, DeviceType: 2, APIVersion: v13, Extensions: allReqExts},
)
recDual := PickRecommendedGPU([]GPUInfo{vega7, rtx})
if recDual == nil || recDual.VendorID != "10de" {
t.Fatalf("PickRecommendedGPU(vega7, rtx) = %+v, want 10de", recDual)
}
// 9. MergeRegistryAndVulkanGPUs matches by PCI ID and appends Vulkan-only GPUs.
merged := MergeRegistryAndVulkanGPUs(
[]GPUInfo{{Name: "AMD Radeon Graphics", VulkanICD: `C:\amd-vulkan64.json`, VendorID: "1002", DeviceID: "164c", DriverVersion: "31.0.21924.61"}},
[]VulkanDeviceProbe{
{Name: "AMD Radeon(TM) Graphics", VendorID: 0x1002, DeviceID: 0x164c, DeviceType: 1, APIVersion: v13, Extensions: allReqExts},
{Name: "NVIDIA GeForce RTX 3060", VendorID: 0x10de, DeviceID: 0x2504, DeviceType: 2, APIVersion: v13, Extensions: allReqExts},
},
)
if len(merged) != 2 || merged[0].Compat != GPUCompatWarn || merged[1].Compat != GPUCompatSupported {
t.Fatalf("merged = %+v", merged)
}
}
func TestAffinityMaskHelpers(t *testing.T) {
+19 -6
View File
@@ -6,6 +6,7 @@ import (
"encoding/binary"
"fmt"
"math/bits"
"os"
"path/filepath"
"runtime"
"sort"
@@ -543,7 +544,7 @@ func isUSBBusVolume(vol string) bool {
func probeVulkanGPUs() []GPUInfo {
const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`
var out []GPUInfo
var regGPUs []GPUInfo
for i := 0; i < 32; i++ {
sub := fmt.Sprintf(`%s\%04d`, baseKey, i)
desc, okDesc := regReadString(hkeyLocalMachine, sub, "DriverDesc")
@@ -554,13 +555,25 @@ func probeVulkanGPUs() []GPUInfo {
if icd == "" {
continue
}
out = append(out, GPUInfo{
Name: desc,
VulkanICD: icd,
Kind: ClassifyGPU(desc),
// Skip stale registry entries left behind by removed adapters or old drivers
// (matching upstream reims-ctl os/windows.rs vulkan_driver_files).
if _, err := os.Stat(icd); err != nil {
continue
}
matchID, _ := regReadString(hkeyLocalMachine, sub, "MatchingDeviceId")
vendorID, deviceID := ParsePCIIDs(matchID)
drvVer, _ := regReadString(hkeyLocalMachine, sub, "DriverVersion")
regGPUs = append(regGPUs, GPUInfo{
Name: desc,
VulkanICD: icd,
Kind: ClassifyGPU(desc),
VendorID: vendorID,
DeviceID: deviceID,
DriverVersion: drvVer,
})
}
return out
vkProbes := probeVulkanDevices()
return MergeRegistryAndVulkanGPUs(regGPUs, vkProbes)
}
func regReadString(root uintptr, subKey, valueName string) (string, bool) {
+9
View File
@@ -24,6 +24,15 @@ func TestWindowsProcessAffinityAndTopology(t *testing.T) {
if len(rep.CPUTopology) == 0 {
t.Fatalf("expected non-empty CPUTopology on Windows")
}
if len(rep.GPUs) > 0 {
for _, g := range rep.GPUs {
if g.Compat == "" {
t.Errorf("GPU %q missing Compat grade: %+v", g.Name, g)
}
t.Logf("probed GPU: name=%q kind=%s pci=%s:%s drv=%s vk=%s compat=%s (%s %s)",
g.Name, g.Kind, g.VendorID, g.DeviceID, g.DriverVersion, g.VulkanVersion, g.Compat, g.CompatCode, g.CompatDetail)
}
}
for i, c := range rep.CPUTopology {
if i > 0 && c.Index <= rep.CPUTopology[i-1].Index {
t.Fatalf("CPUTopology not strictly sorted at %d: %+v", i, rep.CPUTopology)
+15 -1
View File
@@ -197,7 +197,21 @@ func EvaluateOptimizations(rep Report, runtimePatches []string) []Optimization {
}
// 4. Discrete Vulkan GPU acceleration
if rep.RecommendedGPU != nil && rep.RecommendedGPU.Kind == GPUDiscrete {
if rep.RecommendedGPU != nil && rep.RecommendedGPU.Compat == GPUCompatUnsupported {
out = append(out, Optimization{
ID: "discrete_gpu",
Status: "unavailable",
Supported: false,
Detail: rep.RecommendedGPU.Name,
})
} else if rep.RecommendedGPU != nil && rep.RecommendedGPU.Compat == GPUCompatWarn {
out = append(out, Optimization{
ID: "discrete_gpu",
Status: "experimental",
Supported: true,
Detail: rep.RecommendedGPU.Name,
})
} else if rep.RecommendedGPU != nil && rep.RecommendedGPU.Kind == GPUDiscrete {
out = append(out, Optimization{
ID: "discrete_gpu",
Status: "recommended",
+175
View File
@@ -0,0 +1,175 @@
//go:build windows
package host
import (
"bytes"
"encoding/binary"
"syscall"
"unsafe"
)
const (
vkSuccess = 0
vkIncomplete = 5
vkErrorIncompatibleDriver = -9
vkStructureTypeAppInfo = 0
vkStructureTypeInstCreate = 1
vkAPIVersion10 = (1 << 22)
vkAPIVersion13 = (1 << 22) | (3 << 12)
)
// vkApplicationInfo matches VkApplicationInfo on x86-64 Windows (48 bytes).
type vkApplicationInfo struct {
sType uint32
pNext uintptr
pApplicationName uintptr
applicationVersion uint32
pEngineName uintptr
engineVersion uint32
apiVersion uint32
}
// vkInstanceCreateInfo matches VkInstanceCreateInfo on x86-64 Windows (64 bytes).
type vkInstanceCreateInfo struct {
sType uint32
pNext uintptr
flags uint32
pApplicationInfo *vkApplicationInfo
enabledLayerCount uint32
ppEnabledLayerNames uintptr
enabledExtensionCount uint32
ppEnabledExtensionNames uintptr
}
// vkExtensionProperties matches VkExtensionProperties (260 bytes).
type vkExtensionProperties struct {
ExtensionName [256]byte
SpecVersion uint32
}
// probeVulkanDevices loads vulkan-1.dll and enumerates all visible Vulkan
// physical devices along with their API version, PCI IDs, device type, and
// advertised device extensions. Returns nil cleanly if the Vulkan loader is
// absent or refuses instance creation.
func probeVulkanDevices() []VulkanDeviceProbe {
dll := syscall.NewLazyDLL("vulkan-1.dll")
if err := dll.Load(); err != nil {
return nil
}
pCreateInst := dll.NewProc("vkCreateInstance")
pDestroyInst := dll.NewProc("vkDestroyInstance")
pEnumPhys := dll.NewProc("vkEnumeratePhysicalDevices")
pGetProps := dll.NewProc("vkGetPhysicalDeviceProperties")
pEnumExts := dll.NewProc("vkEnumerateDeviceExtensionProperties")
if pCreateInst.Find() != nil || pDestroyInst.Find() != nil ||
pEnumPhys.Find() != nil || pGetProps.Find() != nil || pEnumExts.Find() != nil {
return nil
}
appName := append([]byte("reims-go"), 0)
appInfo := vkApplicationInfo{
sType: vkStructureTypeAppInfo,
pApplicationName: uintptr(unsafe.Pointer(&appName[0])),
apiVersion: vkAPIVersion13,
}
createInfo := vkInstanceCreateInfo{
sType: vkStructureTypeInstCreate,
pApplicationInfo: &appInfo,
}
var instance uintptr
res, _, _ := pCreateInst.Call(
uintptr(unsafe.Pointer(&createInfo)),
0,
uintptr(unsafe.Pointer(&instance)),
)
if int32(res) == vkErrorIncompatibleDriver {
appInfo.apiVersion = vkAPIVersion10
res, _, _ = pCreateInst.Call(
uintptr(unsafe.Pointer(&createInfo)),
0,
uintptr(unsafe.Pointer(&instance)),
)
}
if int32(res) != vkSuccess || instance == 0 {
return nil
}
defer pDestroyInst.Call(instance, 0)
var count uint32
res, _, _ = pEnumPhys.Call(instance, uintptr(unsafe.Pointer(&count)), 0)
if (int32(res) != vkSuccess && int32(res) != vkIncomplete) || count == 0 {
return nil
}
if count > 32 {
count = 32
}
devices := make([]uintptr, count)
res, _, _ = pEnumPhys.Call(
instance,
uintptr(unsafe.Pointer(&count)),
uintptr(unsafe.Pointer(&devices[0])),
)
if int32(res) != vkSuccess && int32(res) != vkIncomplete {
return nil
}
out := make([]VulkanDeviceProbe, 0, count)
for i := uint32(0); i < count; i++ {
pd := devices[i]
if pd == 0 {
continue
}
// VkPhysicalDeviceProperties is ~824 bytes; use 2048 bytes to stay
// immune to padding differences while reading fixed header offsets 0..276.
var propsBuf [2048]byte
pGetProps.Call(pd, uintptr(unsafe.Pointer(&propsBuf[0])))
probe := VulkanDeviceProbe{
APIVersion: binary.LittleEndian.Uint32(propsBuf[0:4]),
VendorID: binary.LittleEndian.Uint32(propsBuf[8:12]),
DeviceID: binary.LittleEndian.Uint32(propsBuf[12:16]),
DeviceType: binary.LittleEndian.Uint32(propsBuf[16:20]),
Name: cstrFromBytes(propsBuf[20:276]),
Extensions: probeVulkanDeviceExtensions(pEnumExts, pd),
}
out = append(out, probe)
}
return out
}
func probeVulkanDeviceExtensions(pEnumExts *syscall.LazyProc, pd uintptr) map[string]bool {
var extCount uint32
res, _, _ := pEnumExts.Call(pd, 0, uintptr(unsafe.Pointer(&extCount)), 0)
if (int32(res) != vkSuccess && int32(res) != vkIncomplete) || extCount == 0 {
return nil
}
if extCount > 2048 {
extCount = 2048
}
exts := make([]vkExtensionProperties, extCount)
res, _, _ = pEnumExts.Call(
pd,
0,
uintptr(unsafe.Pointer(&extCount)),
uintptr(unsafe.Pointer(&exts[0])),
)
if int32(res) != vkSuccess && int32(res) != vkIncomplete {
return nil
}
m := make(map[string]bool, extCount)
for i := uint32(0); i < extCount; i++ {
if name := cstrFromBytes(exts[i].ExtensionName[:]); name != "" {
m[name] = true
}
}
return m
}
func cstrFromBytes(b []byte) string {
if idx := bytes.IndexByte(b, 0); idx >= 0 {
b = b[:idx]
}
return string(b)
}
+30 -2
View File
@@ -192,7 +192,18 @@ var catalog = map[Locale]map[string]string{
"doctor.whpx.unsupported": "非 Windows 宿主(当前处于跨平台开发模式)",
"doctor.gpu": "Vulkan 显卡列表",
"doctor.gpu.none": "未检测到已注册的 Vulkan ICD 显卡驱动",
"doctor.gpu.recommended": "推荐独显",
"doctor.gpu.recommended": "推荐",
"doctor.gpu.compat.supported": "支持",
"doctor.gpu.compat.warn": "已知兼容性风险",
"doctor.gpu.compat.unsupported": "不支持加速",
"doctor.gpu.compat.unknown": "未完成 Vulkan 实测",
"doctor.gpu.warn.amd_legacy": "AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题(%s),建议使用其他独显或在虚拟机设置改用 VMware SVGA",
"doctor.gpu.warn.amd_rdna2": "该 AMD 显卡在 Windows 下存在上游已知设备丢失风险(%s),若黑屏/卡死请升级驱动或临时改用 VMware SVGA",
"doctor.gpu.err.vulkan_too_old": "Vulkan 版本 %s 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA",
"doctor.gpu.err.missing_ext": "缺少必需 Vulkan 扩展(%s),请更新显卡驱动或改用 VMware SVGA",
"doctor.gpu.err.vulkan_cpu": "软件渲染 Vulkan 实现不满足 vGPU 硬件加速要求,请改用 VMware SVGA",
"err.gpu_device_lost": "宿主显卡 Vulkan 设备丢失(ERROR_DEVICE_LOST)。请更新显卡驱动;若为 AMD Vega/Polaris 等受影响显卡,请改用其他独显或在设置中将虚拟显卡切为 VMware SVGA",
"err.gpu_vulkan_floor": "宿主显卡不满足 Reims vGPU 的 Vulkan 1.3 硬件要求。请更新显卡驱动,或在设置中将虚拟显卡切为 VMware SVGA(软件渲染)",
"doctor.runtime": "便携运行时",
"doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)",
"doctor.runtime.active": "当前激活:%s(%s)",
@@ -222,6 +233,9 @@ var catalog = map[Locale]map[string]string{
"err.update_not_writable": "无法写入 Reims-Go 所在目录(%s),请把程序放到可写的位置,或到发布页手动更新",
"err.update_relaunch": "新版本已安装,但没能自动重新打开,请手动启动 Reims-Go",
"err.commit_memory": "内存不够启动:这台虚拟机要 %.0f GB,Windows 现在只能再分配 %.1f GB。关掉一些程序再试,或在设置里把内存改为 %.0f GB",
"err.whpx_missing": "未启用 Windows 虚拟机监控程序平台(WHPX)。在「宿主机」页启用 WHPX 并重启 Windows 后再启动虚拟机",
"err.whpx_no_hypervisor": "Windows Hypervisor 虚拟化引擎未激活(与磁盘空间无关)。确认 BIOS 已开启 Intel VT-x / AMD SVM,在「宿主机」页启用 WHPX,以管理员运行 bcdedit /set hypervisorlaunchtype auto,然后重启 Windows",
"err.whpx_unsupported": "当前系统不支持 Windows 虚拟机监控程序平台(WHPX),需要 Windows 10 1803 或更高版本",
"installer.paused": "已暂停。再次运行 `reims-go installer download %s` 会从中断处继续。",
"installer.done": "离线安装包已就绪:macOS %s -> %s",
"installer.cached.empty": "还没有下载任何安装包。",
@@ -284,7 +298,18 @@ var catalog = map[Locale]map[string]string{
"doctor.whpx.unsupported": "Non-Windows host (cross-platform dev mode)",
"doctor.gpu": "Vulkan GPUs",
"doctor.gpu.none": "No registered Vulkan ICD driver found",
"doctor.gpu.recommended": "Recommended discrete GPU",
"doctor.gpu.recommended": "Recommended",
"doctor.gpu.compat.supported": "Supported",
"doctor.gpu.compat.warn": "Known compatibility issue",
"doctor.gpu.compat.unsupported": "Unsupported for vGPU",
"doctor.gpu.compat.unknown": "Vulkan capabilities unverified",
"doctor.gpu.warn.amd_legacy": "AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues (%s); prefer another discrete GPU or switch the VM to VMware SVGA",
"doctor.gpu.warn.amd_rdna2": "This AMD GPU hits known Windows device-loss issues upstream (%s); update drivers or switch temporarily to VMware SVGA if it freezes",
"doctor.gpu.err.vulkan_too_old": "Vulkan %s is below the required 1.3 floor; update your GPU driver or use VMware SVGA",
"doctor.gpu.err.missing_ext": "Missing required Vulkan extensions (%s); update your GPU driver or use VMware SVGA",
"doctor.gpu.err.vulkan_cpu": "Software Vulkan implementation does not meet the vGPU floor; use VMware SVGA instead",
"err.gpu_device_lost": "Host Vulkan GPU device lost (ERROR_DEVICE_LOST). Update GPU drivers; on affected AMD Vega/Polaris GPUs, switch to another discrete GPU or use VMware SVGA in VM Settings",
"err.gpu_vulkan_floor": "Host GPU does not meet Reims vGPU's Vulkan 1.3 requirements. Update GPU drivers or switch graphics to VMware SVGA (software rendering) in VM Settings",
"doctor.runtime": "Portable Runtime",
"doctor.runtime.none": "Not installed (run `reims-go runtime install <archive>`)",
"doctor.runtime.active": "Active: %s (%s)",
@@ -314,6 +339,9 @@ var catalog = map[Locale]map[string]string{
"err.update_not_writable": "Can't write to the folder Reims-Go runs from (%s); move it somewhere writable, or update from the release page",
"err.update_relaunch": "The new version is installed but didn't reopen; start Reims-Go again",
"err.commit_memory": "Not enough memory to start: this VM needs %.0f GB and Windows can commit only %.1f GB more. Close some programs, or set its memory to %.0f GB",
"err.whpx_missing": "Windows Hypervisor Platform (WHPX) is not enabled. Enable WHPX on the Host page and restart Windows before starting the VM",
"err.whpx_no_hypervisor": "Windows Hypervisor is not active (unrelated to disk space). Ensure Intel VT-x / AMD SVM is enabled in BIOS, enable WHPX on the Host page, run `bcdedit /set hypervisorlaunchtype auto` as Administrator, and restart Windows",
"err.whpx_unsupported": "Windows Hypervisor Platform (WHPX) is not supported on this OS; Windows 10 1803 or newer is required",
"installer.paused": "Paused. Run `reims-go installer download %s` again to continue where it stopped.",
"installer.done": "Offline installer ready: macOS %s -> %s",
"installer.cached.empty": "No installers downloaded yet.",
+1 -1
View File
@@ -60,7 +60,7 @@ type HostCallbacks struct {
func appVersion() string {
v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
if v == "" || v == "dev" {
return "0.2.7"
return "0.2.8"
}
return v
}
+234
View File
@@ -0,0 +1,234 @@
package runtime
import (
"archive/tar"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/klauspost/compress/zstd"
)
type tarEntry struct {
name string
typeflag byte
body string
linkname string
mode int64
}
func writeTestTarZst(t *testing.T, archivePath string, entries []tarEntry) {
t.Helper()
f, err := os.Create(archivePath)
if err != nil {
t.Fatalf("create archive: %v", err)
}
defer f.Close()
zw, err := zstd.NewWriter(f)
if err != nil {
t.Fatalf("new zstd writer: %v", err)
}
tw := tar.NewWriter(zw)
for _, e := range entries {
tf := e.typeflag
if tf == 0 {
tf = tar.TypeReg
}
mode := e.mode
if mode == 0 {
if tf == tar.TypeDir {
mode = 0o755
} else {
mode = 0o644
}
}
hdr := &tar.Header{
Name: e.name,
Typeflag: tf,
Mode: mode,
Linkname: e.linkname,
}
if tf == tar.TypeReg {
hdr.Size = int64(len(e.body))
}
if err := tw.WriteHeader(hdr); err != nil {
t.Fatalf("write tar header %s: %v", e.name, err)
}
if tf == tar.TypeReg {
if _, err := tw.Write([]byte(e.body)); err != nil {
t.Fatalf("write tar body %s: %v", e.name, err)
}
}
}
if err := tw.Close(); err != nil {
t.Fatalf("close tar writer: %v", err)
}
if err := zw.Close(); err != nil {
t.Fatalf("close zstd writer: %v", err)
}
}
func sha256Hex(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
func TestInstallFromArchiveTarZstPureGo(t *testing.T) {
dataRoot := t.TempDir()
cfg := &config.Config{DataRoot: dataRoot}
ctlBody := "fake-reims-ctl-binary"
qemuBody := "fake-qemu-binary"
m := Manifest{
SchemaVersion: 2,
Name: "reims-runtime-win-x64",
Commit: "3731afd",
BuiltAt: "2026-11-29T00:00:00Z",
SHA256: map[string]string{
"bin/reims-ctl.exe": sha256Hex(ctlBody),
"qemu/bin/qemu-system-x86_64.exe": sha256Hex(qemuBody),
},
}
manifestBytes, err := json.Marshal(m)
if err != nil {
t.Fatalf("marshal manifest: %v", err)
}
archivePath := filepath.Join(t.TempDir(), "reims-runtime-win-x64-3731afd.tar.zst")
writeTestTarZst(t, archivePath, []tarEntry{
{name: "./", typeflag: tar.TypeDir},
{name: "reims-runtime-win-x64-3731afd/", typeflag: tar.TypeDir},
{name: "reims-runtime-win-x64-3731afd/manifest.json", body: string(manifestBytes), mode: 0o444},
{name: "reims-runtime-win-x64-3731afd/bin/reims-ctl.exe", body: ctlBody, mode: 0o755},
{name: "reims-runtime-win-x64-3731afd/qemu/bin/qemu-system-x86_64.exe", body: qemuBody, mode: 0o755},
})
// Isolate PATH so the test proves no external tar or zstd binary is invoked.
t.Setenv("PATH", "")
inst, err := InstallFromArchive(cfg, archivePath)
if err != nil {
t.Fatalf("InstallFromArchive failed: %v", err)
}
if inst.Commit != "3731afd" {
t.Fatalf("Commit = %q, want 3731afd", inst.Commit)
}
gotCtl, err := os.ReadFile(filepath.Join(inst.Dir, "bin", "reims-ctl.exe"))
if err != nil {
t.Fatalf("read extracted reims-ctl.exe: %v", err)
}
if string(gotCtl) != ctlBody {
t.Fatalf("extracted reims-ctl.exe = %q, want %q", string(gotCtl), ctlBody)
}
gotQemu, err := os.ReadFile(filepath.Join(inst.Dir, "qemu", "bin", "qemu-system-x86_64.exe"))
if err != nil {
t.Fatalf("read extracted qemu: %v", err)
}
if string(gotQemu) != qemuBody {
t.Fatalf("extracted qemu = %q, want %q", string(gotQemu), qemuBody)
}
}
func TestExtractTarZstRejectsTraversalAndEscapes(t *testing.T) {
cases := []struct {
name string
entries []tarEntry
}{
{
name: "dotdot_file",
entries: []tarEntry{
{name: "../escape.txt", body: "bad"},
},
},
{
name: "nested_dotdot",
entries: []tarEntry{
{name: "a/b/../../../escape.txt", body: "bad"},
},
},
{
name: "backslash_dotdot",
entries: []tarEntry{
{name: `sub\..\..\escape.txt`, body: "bad"},
},
},
{
name: "absolute_unix",
entries: []tarEntry{
{name: "/etc/passwd", body: "bad"},
},
},
{
name: "symlink_escape",
entries: []tarEntry{
{name: "sub/link", typeflag: tar.TypeSymlink, linkname: "../../outside.txt"},
},
},
{
name: "symlink_absolute",
entries: []tarEntry{
{name: "link", typeflag: tar.TypeSymlink, linkname: "/tmp/outside.txt"},
},
},
{
name: "hardlink_escape",
entries: []tarEntry{
{name: "hard", typeflag: tar.TypeLink, linkname: "../outside.txt"},
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
archivePath := filepath.Join(t.TempDir(), tc.name+".tar.zst")
writeTestTarZst(t, archivePath, tc.entries)
destDir := filepath.Join(t.TempDir(), "dest")
if err := os.MkdirAll(destDir, 0o755); err != nil {
t.Fatal(err)
}
err := extractTarZst(archivePath, destDir)
if err == nil {
t.Fatalf("expected error for %s, got nil", tc.name)
}
if !strings.Contains(err.Error(), "illegal tar") {
t.Fatalf("unexpected error for %s: %v", tc.name, err)
}
})
}
}
func TestExtractTarZstCorruptArchive(t *testing.T) {
archivePath := filepath.Join(t.TempDir(), "corrupt.tar.zst")
if err := os.WriteFile(archivePath, []byte("not a valid zstd stream"), 0o644); err != nil {
t.Fatal(err)
}
if err := extractTarZst(archivePath, t.TempDir()); err == nil {
t.Fatal("expected error for corrupt archive, got nil")
}
}
func TestExtractTarZstHardlinkWithinDest(t *testing.T) {
archivePath := filepath.Join(t.TempDir(), "hardlink.tar.zst")
writeTestTarZst(t, archivePath, []tarEntry{
{name: "bundle/a.txt", body: "hello"},
{name: "bundle/b.txt", typeflag: tar.TypeLink, linkname: "bundle/a.txt"},
})
destDir := t.TempDir()
if err := extractTarZst(archivePath, destDir); err != nil {
t.Fatalf("extractTarZst failed: %v", err)
}
got, err := os.ReadFile(filepath.Join(destDir, "bundle", "b.txt"))
if err != nil {
t.Fatalf("read hardlinked file: %v", err)
}
if string(got) != "hello" {
t.Fatalf("hardlink content = %q, want hello", string(got))
}
}
-7
View File
@@ -1,7 +0,0 @@
//go:build !windows
package runtime
import "os/exec"
func configureCmd(cmd *exec.Cmd) {}
-17
View File
@@ -1,17 +0,0 @@
//go:build windows
package runtime
import (
"os/exec"
"syscall"
)
const createNoWindow = 0x08000000
func configureCmd(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: createNoWindow,
}
}
+186 -44
View File
@@ -1,13 +1,14 @@
package runtime
import (
"archive/tar"
"archive/zip"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"sort"
@@ -15,6 +16,7 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/klauspost/compress/zstd"
)
type Manifest struct {
@@ -395,58 +397,198 @@ func fileSHA256(path string) (string, error) {
return fetch.FileSHA256(path)
}
// tarCommand is Windows' own bsdtar (System32/tar.exe, Windows 10 1803+),
// which reads .tar.zst directly and takes "D:\..." paths. A bare "tar" can
// resolve to GNU tar from Git or MSYS2, which does neither.
func tarCommand() string {
if runtime.GOOS == "windows" {
if root := os.Getenv("SystemRoot"); root != "" {
p := filepath.Join(root, "System32", "tar.exe")
if _, err := os.Stat(p); err == nil {
return p
}
}
}
return "tar"
}
// extractTarZst decompresses and extracts a .tar.zst runtime archive in pure Go
// (no dependency on Windows tar.exe libzstd support or an external zstd binary).
func extractTarZst(archivePath, destDir string) error {
tarBin := tarCommand()
cmd := exec.Command(tarBin, "-xf", archivePath, "-C", destDir)
configureCmd(cmd)
out, err := cmd.CombinedOutput()
if err == nil {
return nil
f, err := os.Open(archivePath)
if err != nil {
return fmt.Errorf("open archive: %w", err)
}
// Fallback for a tar without zstd: decompress to a temporary .tar first.
// (Piping zstd into tar deadlocked when tar exited early: zstd blocked on a
// full pipe nobody read.)
zstdBin := findZstd()
if zstdBin == "" {
return fmt.Errorf("tar -xf failed (%v: %s) and zstd was not found", err, strings.TrimSpace(string(out)))
defer f.Close()
zr, err := zstd.NewReader(f)
if err != nil {
return fmt.Errorf("init zstd reader: %w", err)
}
tmpTar := filepath.Join(destDir, ".extract.tar")
defer os.Remove(tmpTar)
z := exec.Command(zstdBin, "-d", "-q", "-f", archivePath, "-o", tmpTar)
configureCmd(z)
if zOut, zErr := z.CombinedOutput(); zErr != nil {
return fmt.Errorf("zstd -d failed: %v (%s)", zErr, strings.TrimSpace(string(zOut)))
defer zr.Close()
cleanDest := filepath.Clean(destDir)
realDest, err := filepath.EvalSymlinks(cleanDest)
if err != nil {
realDest = cleanDest
}
t := exec.Command(tarBin, "-xf", tmpTar, "-C", destDir)
configureCmd(t)
if tOut, tErr := t.CombinedOutput(); tErr != nil {
return fmt.Errorf("tar extract failed: %v (%s)", tErr, strings.TrimSpace(string(tOut)))
tr := tar.NewReader(zr)
for {
hdr, err := tr.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("read tar.zst entry: %w", err)
}
switch hdr.Typeflag {
case tar.TypeXHeader, tar.TypeXGlobalHeader, tar.TypeGNULongName, tar.TypeGNULongLink:
continue
}
target, isRoot, err := safeExtractPath(cleanDest, hdr.Name)
if err != nil {
return err
}
switch hdr.Typeflag {
case tar.TypeDir:
if isRoot {
continue
}
if err := ensureWithinDest(realDest, filepath.Dir(target), hdr.Name); err != nil {
return err
}
if err := os.MkdirAll(target, 0o755); err != nil {
return err
}
case tar.TypeReg, tar.TypeRegA:
if isRoot {
return fmt.Errorf("illegal tar file path: %s", hdr.Name)
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
if err := ensureWithinDest(realDest, filepath.Dir(target), hdr.Name); err != nil {
return err
}
mode := (os.FileMode(hdr.Mode) & 0o777) | 0o600
if err := writeTarFile(target, tr, mode); err != nil {
return err
}
case tar.TypeLink:
if isRoot {
return fmt.Errorf("illegal tar hardlink path: %s", hdr.Name)
}
linkTarget, linkIsRoot, err := safeExtractPath(cleanDest, hdr.Linkname)
if err != nil || linkIsRoot {
return fmt.Errorf("illegal tar hardlink target %q for %s", hdr.Linkname, hdr.Name)
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
if err := ensureWithinDest(realDest, filepath.Dir(target), hdr.Name); err != nil {
return err
}
if err := ensureWithinDest(realDest, filepath.Dir(linkTarget), hdr.Linkname); err != nil {
return err
}
_ = os.Remove(target)
if err := os.Link(linkTarget, target); err != nil {
return fmt.Errorf("create hardlink %s -> %s: %w", hdr.Name, hdr.Linkname, err)
}
case tar.TypeSymlink:
if isRoot {
return fmt.Errorf("illegal tar symlink path: %s", hdr.Name)
}
normLink := strings.ReplaceAll(hdr.Linkname, "\\", "/")
if normLink == "" || strings.HasPrefix(normLink, "/") || filepath.IsAbs(hdr.Linkname) || filepath.VolumeName(hdr.Linkname) != "" || filepath.VolumeName(normLink) != "" {
return fmt.Errorf("illegal tar symlink target %q for %s", hdr.Linkname, hdr.Name)
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
realParent, err := evalWithinDest(realDest, filepath.Dir(target), hdr.Name)
if err != nil {
return err
}
resolved := filepath.Clean(filepath.Join(realParent, filepath.FromSlash(normLink)))
if !isWithinDir(realDest, resolved) {
return fmt.Errorf("illegal tar symlink target %q for %s", hdr.Linkname, hdr.Name)
}
_ = os.Remove(target)
if err := os.Symlink(filepath.FromSlash(normLink), target); err != nil {
// Windows without Developer Mode or admin rights denies os.Symlink;
// fall back to copying if the target is an already-extracted regular file.
if runtime.GOOS == "windows" {
if copyErr := copyFileIfRegular(resolved, target); copyErr == nil {
continue
}
}
return fmt.Errorf("create symlink %s -> %s: %w", hdr.Name, hdr.Linkname, err)
}
default:
return fmt.Errorf("unsupported tar entry type %q for %s", hdr.Typeflag, hdr.Name)
}
}
return nil
}
func findZstd() string {
for _, c := range []string{"zstd", `D:\DevTools\msys64\usr\bin\zstd.exe`, `D:\DevTools\msys64\clang64\bin\zstd.exe`} {
if p, err := exec.LookPath(c); err == nil {
return p
}
func safeExtractPath(cleanDest, rawName string) (target string, isRoot bool, err error) {
norm := strings.ReplaceAll(rawName, "\\", "/")
if norm == "" || strings.HasPrefix(norm, "/") || filepath.IsAbs(rawName) || filepath.VolumeName(rawName) != "" || filepath.VolumeName(norm) != "" {
return "", false, fmt.Errorf("illegal tar path: %s", rawName)
}
return ""
clean := path.Clean(norm)
if clean == "." {
return cleanDest, true, nil
}
if clean == ".." || strings.HasPrefix(clean, "../") {
return "", false, fmt.Errorf("illegal tar path: %s", rawName)
}
target = filepath.Join(cleanDest, filepath.FromSlash(clean))
if !isWithinDir(cleanDest, filepath.Clean(target)) {
return "", false, fmt.Errorf("illegal tar path: %s", rawName)
}
return target, false, nil
}
func isWithinDir(baseDir, candidate string) bool {
base := filepath.Clean(baseDir)
cand := filepath.Clean(candidate)
if cand == base {
return true
}
return strings.HasPrefix(cand, base+string(os.PathSeparator))
}
func evalWithinDest(realDest, dir, entryName string) (string, error) {
realDir, err := filepath.EvalSymlinks(dir)
if err != nil {
return "", err
}
if !isWithinDir(realDest, realDir) {
return "", fmt.Errorf("illegal tar path (symlink escape): %s", entryName)
}
return realDir, nil
}
func ensureWithinDest(realDest, dir, entryName string) error {
_, err := evalWithinDest(realDest, dir, entryName)
return err
}
func writeTarFile(target string, r io.Reader, mode os.FileMode) error {
_ = os.Remove(target)
out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
if err != nil {
return err
}
_, copyErr := io.Copy(out, r)
closeErr := out.Close()
if copyErr != nil {
return copyErr
}
return closeErr
}
func copyFileIfRegular(src, dst string) error {
info, err := os.Stat(src)
if err != nil || !info.Mode().IsRegular() {
return errors.New("not a regular file")
}
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
return writeTarFile(dst, in, (info.Mode()&0o777)|0o600)
}
func extractZip(archivePath, destDir string) error {
+2 -2
View File
@@ -16,8 +16,8 @@ import (
// Version is the current Reims-Go release version. Release builds may override
// it at link time with:
//
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.7"
var Version = "v0.2.7"
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.8"
var Version = "v0.2.8"
const (
DefaultReleasesRepo = "Nwflower/Reims-Go"
+17
View File
@@ -50,6 +50,23 @@ func New(cfg config.Config, log func(string)) (*Prep, error) {
return &Prep{Client: reims.NewClient(&cfg, *active), Runtime: *active, cfg: cfg, log: log}, nil
}
// CheckWHPX refuses to start a VM when Windows Hypervisor Platform is not
// ready. Without it QEMU aborts with "WHPX: No accelerator found, hr=00000000"
// followed by "failed to initialize whpx: No space left on device" (-ENOSPC),
// which misleads users into checking disk space.
func (p *Prep) CheckWHPX(rep host.Report) error {
switch rep.WHPX {
case host.WHPXReady:
return nil
case host.WHPXMissing:
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_missing"))
case host.WHPXNoHypervisor:
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_no_hypervisor"))
default:
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_unsupported"))
}
}
// CheckMemory refuses to start a VM whose guest RAM can't be committed right
// now. Without it QEMU exits with "Cannot set up guest memory 'ram'" (measured
// 2026-11-28, portable-runtime-spec.md §5.1), which says nothing about what to do.
+31
View File
@@ -0,0 +1,31 @@
package vmstart
import (
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestCheckWHPX(t *testing.T) {
pZh := &Prep{cfg: config.Config{Locale: i18n.ZhCN}}
pEn := &Prep{cfg: config.Config{Locale: i18n.EnUS}}
if err := pZh.CheckWHPX(host.Report{WHPX: host.WHPXReady}); err != nil {
t.Fatalf("WHPXReady should pass, got %v", err)
}
if err := pZh.CheckWHPX(host.Report{WHPX: host.WHPXNoHypervisor}); err == nil || !strings.Contains(err.Error(), "hypervisorlaunchtype") {
t.Fatalf("WHPXNoHypervisor (zh-CN) = %v", err)
}
if err := pEn.CheckWHPX(host.Report{WHPX: host.WHPXNoHypervisor}); err == nil || !strings.Contains(err.Error(), "unrelated to disk space") {
t.Fatalf("WHPXNoHypervisor (en-US) = %v", err)
}
if err := pZh.CheckWHPX(host.Report{WHPX: host.WHPXMissing}); err == nil || !strings.Contains(err.Error(), "WHPX") {
t.Fatalf("WHPXMissing (zh-CN) = %v", err)
}
if err := pEn.CheckWHPX(host.Report{WHPX: host.WHPXUnsupported}); err == nil || !strings.Contains(err.Error(), "1803") {
t.Fatalf("WHPXUnsupported (en-US) = %v", err)
}
}