Compare commits

...
21 changed files with 2204 additions and 61 deletions

No files matched your search

+1
View File
@@ -25,6 +25,7 @@
| :--- | :--- | :--- |
| 挂起恢复所用运行时的编号和兼容判定 | Alpha 运行时编号与挂起兼容性规范 | [reims-go/reims-vgpu 的 packaging/windows-runtime/versioning.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/versioning.md) |
| 运行时源码、依赖补丁和补丁退役 | 运行时源码与依赖补丁 | [reims-go/reims-vgpu 的 packaging/windows-runtime/patches/README.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) |
| ARM macOS 实验运行时和准备启动介质 | ARM macOS 实验版 | [docs/arm64-preview.md](docs/arm64-preview.md) |
| FileVault 开机输入与启动镜像 | FileVault 开机输入镜像构建 | [scripts/filevault-input/README.md](scripts/filevault-input/README.md) |
| 虚拟机系统盘性能测量 | 系统盘小文件 I/O 基准与采样工具 | [scripts/io-bench/README.md](scripts/io-bench/README.md) |
| 跨会话工单与 Agent 交接 | 调试工单模板 | [scripts/debug/work-template.md](scripts/debug/work-template.md) |
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "支持在 Windows x86-64 上使用 Stambha 实验运行时启动 ARM macOS。导入配套运行时后,可从已有的启动介质和虚拟磁盘创建虚拟机。",
"en": "Run ARM macOS on Windows x86-64 with the Stambha preview runtime. Import the matching runtime to create a VM from existing boot media and a virtual disk."
}
+28
View File
@@ -0,0 +1,28 @@
# 运行 ARM macOS 实验版
ARM 实验运行时通过 QEMU/WHPX 和 Stambha 在 Windows x86-64 上运行 ARM macOS。使用同一预览配套的 Reims-Go 客户端和 `stambha-hosted` 运行时包。运行时可以和现有 Intel macOS 运行时共存。
## 准备
- Windows x86-64 主机,启用 Windows 虚拟机监控程序平台(WHPX),安装支持 Vulkan 的显卡驱动。
- 一套你自己的 Stambha 启动介质和与之匹配的 ARM macOS 虚拟磁盘。启动目录至少包含 `EFI/stela/stela.cfg`,其中的磁盘分区标识须与虚拟磁盘一致。从目录启动时,客户端在 VM 的独立引导目录中放入运行时自带的 Stambha EFI。
- 为每台运行中的虚拟机准备独立可写副本或 QCOW2 写入层。来宾写入保存在该磁盘文件中。运行时包内提供启动程序、固件和显卡组件,系统文件由用户自行准备。
macOS 27.2.1 的实验配置使用 8 个 vCPU 和 16 GiB 内存。首次登录后,系统索引和缓存初始化会影响交互速度。
## 启动
在客户端的运行时页面导入 ARM 运行时包。新建虚拟机时选择「macOS ARM64(预览)」,填写启动目录和虚拟磁盘路径,创建后点击启动。GPU 加速窗口由运行时打开。
也可在 PowerShell 中操作。将示例路径替换成自己的文件位置。
```powershell
.\reims-go.exe runtime install .\reims-stambha-runtime-win-x64-stambha-arm64-preview.1.tar.zst
.\reims-go.exe vm create --driver builtin.driver.stambha --boot-volume .\arm-boot --disk .\arm-system.qcow2 --cpus 8 --memory 16G arm-macos
.\reims-go.exe vm start --driver builtin.driver.stambha arm-macos
.\reims-go.exe vm stop --driver builtin.driver.stambha arm-macos
```
如果配置使用原始安装介质,可以用 `--usb-image` 指定文件。原始介质须预先包含与托管 Reims vGPU 相容的 Stambha EFI。首次从 IPSW 制作 ARM 安装介质仍是独立流程。
日常关机请在 macOS 的苹果菜单中选择「关机」。客户端的停止操作会向来宾发送电源按键事件。若来宾没有退出,可回到桌面完成关机。只在来宾无响应时使用强制停止。
+6 -4
View File
@@ -14,7 +14,7 @@ import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Si
import { VMPage } from './components/VMPage'
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
import { hasStambhaRuntime, isMacOSDriver, liveVMInfo, splitEndpoints, STAMBHA_DRIVER_ID, vmFeatures } from './lib/endpoints'
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
import { LogLine, appendLog } from './lib/logs'
import { macOSMajor } from './macos/macosRelease'
@@ -462,7 +462,8 @@ 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 hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
const stambhaAvailable = hasStambhaRuntime(state?.runtimes)
const hostReady = !!state && state.host.whpx === 'ready' && (!!state.active_runtime || stambhaAvailable)
const canSuspend = state?.can_suspend ?? false
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
? resolveFullscreenHotkey(state.config.fullscreen_hotkey)
@@ -540,7 +541,7 @@ export const App: React.FC = () => {
const folderDone = async () => {
const s = await api.GetState().catch(() => null)
if (s) setState(s)
setSetupStage(s?.active_runtime ? null : 'runtime')
setSetupStage(s?.active_runtime || hasStambhaRuntime(s?.runtimes) ? null : 'runtime')
}
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
// The data folder opened read-only (internal/dataroot): nothing in it may be
@@ -875,7 +876,7 @@ export const App: React.FC = () => {
}
const openWizard = () => {
if (!state?.active_runtime) {
if (!state?.active_runtime && !stambhaAvailable) {
setSelected(HOST_ID)
toasts.push({ kind: 'error', title: tr('noRuntimeAlert') })
return
@@ -1376,6 +1377,7 @@ export const App: React.FC = () => {
locale={locale}
host={state.host}
fixedModeSupported={fixedModeSupported}
initialDriverID={!state.active_runtime && stambhaAvailable ? STAMBHA_DRIVER_ID : undefined}
tasks={Object.values(taskMap)}
draft={wizardDraft}
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
+16 -8
View File
@@ -1,6 +1,7 @@
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useState } from 'react'
import { useNetworkPlan } from '../lib/useNetworkPlan'
import { STAMBHA_DRIVER_ID } from '../lib/endpoints'
import { NpcapDependency } from './NpcapDependency'
import { NetworkErrorNotice } from './NetworkErrorNotice'
import type { ParsedAppError } from '../i18n'
@@ -53,6 +54,7 @@ interface Props {
locale: Locale
host: HostReport
fixedModeSupported?: boolean
initialDriverID?: string
tasks?: Task[]
draft?: WizardDraft | null
onClose: () => void
@@ -80,7 +82,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
]
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, tasks = [], draft, onClose, onSubmit }) => {
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, initialDriverID = BUILTIN_MACOS_DRIVER, tasks = [], draft, onClose, onSubmit }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [step, setStep] = useState(draft?.step ?? 1)
// Once the user has reached the review step, keep validating so step markers stay current.
@@ -90,7 +92,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [cmdPreview, setCmdPreview] = useState('')
const [drivers, setDrivers] = useState<DriverSummary[]>([])
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
const [driverID, setDriverID] = useState(initialDriverID)
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
const [driverCreating, setDriverCreating] = useState(false)
const [dependencyBusy, setDependencyBusy] = useState(false)
@@ -105,7 +107,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
name: 'macos-tahoe',
name: initialDriverID === STAMBHA_DRIVER_ID ? 'macos-arm64' : 'macos-tahoe',
dir: '',
// 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。
source_mode: 'offline',
@@ -253,7 +255,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
return (
<Modal className="wizard-dialog" title={tr('wizardTitle')} closeLabel={tr('close')} onClose={onClose}>
<nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{driverID !== STAMBHA_DRIVER_ID && <nav className="wizard-steps" aria-label={tr('wizardTitle')}>
{steps.map((key, idx) => {
const n = idx + 1
const bad = issueSteps.has(n) && n !== REVIEW_STEP
@@ -271,7 +273,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
</button>
)
})}
</nav>
</nav>}
<div className="dialog-body">
{err && <div className="notice notice-error">{err}</div>}
@@ -287,11 +289,11 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
<PopupSelect
label={tr('wizardDriverType')}
value={driverID}
options={drivers.map((d) => ({
options={drivers.filter((d) => initialDriverID !== STAMBHA_DRIVER_ID || d.id !== BUILTIN_MACOS_DRIVER).map((d) => ({
value: d.id,
label: locText(d.name, locale, d.id),
}))}
onChange={(id) => { setDriverID(id); setErr('') }}
onChange={(id) => { setDriverID(id); setDriverOpts({}); setErr('') }}
/>
}
/>
@@ -312,6 +314,12 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
schema={activeDriver.create_schema}
values={driverOpts}
onChange={setDriverOpts}
pathFields={driverID === STAMBHA_DRIVER_ID ? {
boot_volume: true,
raw_disk: '*.qcow2;*.raw;*.img',
usb_image: '*.raw;*.img;*.bin',
} : undefined}
onPickError={(e) => setErr(parseAppError(e).summary)}
/>
</Suspense>
)}
@@ -722,7 +730,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
await api.CreateVMWithDriver({
driver_id: driverID,
name: opts.name.trim(),
dir: opts.dir,
dir: driverID === STAMBHA_DRIVER_ID ? '' : opts.dir,
options: driverOpts,
})
onClose()
+39 -32
View File
@@ -5,6 +5,7 @@ import '../i18n/domains/wizard.gen'
import { I18nKey, t } from '../i18n'
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { hasStambhaRuntime, STAMBHA_RUNTIME_KIND } from '../lib/endpoints'
import { AppState, Locale, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { api } from '../wails'
@@ -100,7 +101,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
</div>
</header>
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && !!state.active_runtime && onNewVM && (
{(state.vms?.length ?? 0) === 0 && host.whpx === 'ready' && (!!state.active_runtime || hasStambhaRuntime(runtimes)) && onNewVM && (
<section className="welcome-card">
<h1>{tr('welcomeTitle')}</h1>
<p>{tr('welcomeSub')}</p>
@@ -207,38 +208,44 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
<div className="row" key={rt.commit}>
<div className="row-main">
<div className="row-title"><span className="mono">{rt.commit}</span></div>
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => {
const stambha = rt.kind === STAMBHA_RUNTIME_KIND
const ref = stambha ? STAMBHA_RUNTIME_KIND + '/' + rt.commit : rt.commit
return (
<div className="row" key={ref}>
<div className="row-main">
<div className="row-title"><span className="mono">{stambha ? rt.manifest.name || rt.commit : rt.commit}</span></div>
<div className="row-sub">{rt.manifest.qemu_version?.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
</div>
<div className="row-right">
{confirmDelete === ref ? (
<>
<Button variant="ghost" disabled={removing === ref} onClick={() => setConfirmDelete('')}>
{tr('cancel')}
</Button>
<Button variant="danger" busy={removing === ref} onClick={() => removeRuntime(ref)}>
{tr('runtimeDeleteConfirm')}
</Button>
</>
) : (
<>
{!stambha && (
<Button disabled={removing === ref} onClick={guard(() => api.UseRuntime(rt.commit))}>
{tr('activate')}
</Button>
)}
<IconButton
label={tr('runtimeDelete')}
icon={<Trash size={15} />}
disabled={removing !== ''}
onClick={() => setConfirmDelete(ref)}
/>
</>
)}
</div>
</div>
<div className="row-right">
{confirmDelete === rt.commit ? (
<>
<Button variant="ghost" disabled={removing === rt.commit} onClick={() => setConfirmDelete('')}>
{tr('cancel')}
</Button>
<Button variant="danger" busy={removing === rt.commit} onClick={() => removeRuntime(rt.commit)}>
{tr('runtimeDeleteConfirm')}
</Button>
</>
) : (
<>
<Button disabled={removing === rt.commit} onClick={guard(() => api.UseRuntime(rt.commit))}>
{tr('activate')}
</Button>
<IconButton
label={tr('runtimeDelete')}
icon={<Trash size={15} />}
disabled={removing !== ''}
onClick={() => setConfirmDelete(rt.commit)}
/>
</>
)}
</div>
</div>
))}
)
})}
</div>
</section>
+28 -1
View File
@@ -4,6 +4,8 @@ import '../i18n/domains/settings.gen'
import { locText, t } from '../i18n'
import { Locale, SettingProperty, SettingsSchema } from '../types'
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Button } from '../ui/controls'
import { api } from '../wails'
interface Props {
locale: Locale
@@ -13,6 +15,8 @@ interface Props {
groupFilter?: string
onChange: (next: Record<string, unknown>, patch: Record<string, unknown>) => void
hideGroupHeader?: boolean
pathFields?: Readonly<Record<string, string | true>>
onPickError?: (error: unknown) => void
}
const SECRET_MASK = '••••••••'
@@ -20,7 +24,7 @@ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, and x-scope. */
export const SchemaForm: React.FC<Props> = ({
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader,
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader, pathFields, onPickError,
}) => {
const propsMap = schema.properties ?? {}
const keys = (schema['x-order'] && schema['x-order'].length > 0
@@ -134,6 +138,29 @@ export const SchemaForm: React.FC<Props> = ({
)
}
const pathField = pathFields?.[k]
if (pathField !== undefined) {
return (
<div className="input-group">
<input
type="text"
className="input rg-p-input"
aria-label={label}
value={String(cur ?? '')}
onChange={(e) => setKey(k, e.target.value)}
/>
<Button onClick={async () => {
try {
const path = pathField === true ? await api.PickDirectory(label) : await api.PickFile(label, pathField)
if (path) setKey(k, path)
} catch (error) {
onPickError?.(error)
}
}}>{t(locale, 'choose')}</Button>
</div>
)
}
return (
<input
type="text"
+2 -1
View File
@@ -8,6 +8,7 @@ import { Button } from '../ui/controls'
import { PopupSelect } from '../ui/settings'
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { hasStambhaRuntime } from '../lib/endpoints'
import { api } from '../wails'
import { PluginAppIcon } from './PluginAppIcon'
import { RuntimeOnline } from './RuntimeOnline'
@@ -200,7 +201,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale,
}
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFolderDone, onFinish, onError }) => {
const ready = !!state.active_runtime
const ready = !!state.active_runtime || hasStambhaRuntime(state.runtimes)
const { host } = state
const [enabling, setEnabling] = useState(false)
const enableWHPX = async () => {
+7 -1
View File
@@ -1,9 +1,15 @@
import type { VMEndpoint, VMInfo, VMListItem } from '../types'
import type { InstalledRuntime, VMEndpoint, VMInfo, VMListItem } from '../types'
// Guest family, driver capabilities and endpoint ordering for non-macOS guests.
// Everything here is pure so node:test can load it (scripts/test-endpoints.mjs).
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
export const STAMBHA_DRIVER_ID = 'builtin.driver.stambha'
export const STAMBHA_RUNTIME_KIND = 'stambha-hosted'
export function hasStambhaRuntime(runtimes?: InstalledRuntime[] | null): boolean {
return runtimes?.some((rt) => rt.kind === STAMBHA_RUNTIME_KIND && rt.manifest.runtime_api === '0.1.0') ?? false
}
export type GuestFamily = 'macos' | 'linux' | 'windows' | 'android' | ''
+10 -5
View File
@@ -775,11 +775,16 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
}
return nil, err
}
a.mu.Lock()
a.cfg.ActiveRuntime = inst.Commit
_ = a.saveConfigLocked()
a.mu.Unlock()
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed & activated -> %s", inst.Commit, inst.Dir))
if inst.Active {
a.mu.Lock()
a.cfg.ActiveRuntime = inst.Commit
saveErr := a.saveConfigLocked()
a.mu.Unlock()
if saveErr != nil {
return nil, saveErr
}
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed -> %s", inst.Commit, inst.Dir))
return inst, nil
}
+71 -7
View File
@@ -297,9 +297,11 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
return err
}
cfg.ActiveRuntime = inst.Commit
if err := config.Save("", cfg); err != nil {
return err
if inst.Active {
cfg.ActiveRuntime = inst.Commit
if err := config.Save("", cfg); err != nil {
return err
}
}
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
return nil
@@ -339,6 +341,9 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
for _, item := range list {
if item.Commit == args[1] {
if item.Kind == rt.StambhaKind {
return errors.New("Stambha VMs automatically use an installed compatible Stambha runtime")
}
cfg.ActiveRuntime = item.Commit
if err := config.Save("", cfg); err != nil {
return err
@@ -409,11 +414,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
}
return startVM(ctx, cfg, driverID, name, viaWindow)
case "stop":
driverID, name, err := parseVMTarget(args)
if err != nil {
fs := flag.NewFlagSet("vm stop", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
force := fs.Bool("force", false, "Force stop without waiting for guest shutdown")
if err := fs.Parse(args[1:]); err != nil {
return err
}
return stopVM(ctx, cfg, driverID, name)
if fs.NArg() != 1 {
return errors.New("usage: reims-go vm stop [--driver <id>] [--force] <name>")
}
return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force)
case "suspend":
driverID, name, err := parseVMTarget(args)
if err != nil {
@@ -508,6 +518,7 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
guestLang := fs.String("guest-lang", defaultMacOSGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
start := fs.Bool("start", false, "Start VM immediately after creation")
stambhaFlags := registerStambhaVMFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
@@ -515,6 +526,10 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
}
name := fs.Arg(0)
stambhaOpts := collectStambhaVMFlags(fs, stambhaFlags)
if len(stambhaOpts) > 0 && *driverID != driver.BuiltinStambhaDriverID {
return fmt.Errorf("Stambha VM flags require --driver %s", driver.BuiltinStambhaDriverID)
}
// Route non-reims guest drivers through the plugin Driver Router (§5.3, §10).
if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID {
mgr, router, err := openCLIPluginManager(cfg, false)
@@ -536,6 +551,13 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
"disk_size": *diskSize,
},
}
if drv.ID() == driver.BuiltinStambhaDriverID {
delete(req.Options, "disk_size")
req.Options["gpu"] = *gpu
for key, value := range stambhaOpts {
req.Options[key] = value
}
}
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
@@ -562,13 +584,17 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd")
nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)")
stambhaFlags := registerStambhaVMFlags(fs)
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm set [--driver <id>] [flags] <name>")
}
changes := map[string]any{}
changes := collectStambhaVMFlags(fs, stambhaFlags)
if len(changes) > 0 && *driverID != driver.BuiltinStambhaDriverID {
return fmt.Errorf("Stambha VM flags require --driver %s", driver.BuiltinStambhaDriverID)
}
if *cpus != 0 {
changes["cpus"] = *cpus
}
@@ -595,6 +621,44 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
return setVM(ctx, cfg, *driverID, fs.Arg(0), changes)
}
type stambhaVMFlag struct {
option string
value func() any
}
func registerStambhaVMFlags(fs *flag.FlagSet) map[string]stambhaVMFlag {
boot := fs.String("boot-volume", "", "Stambha boot folder containing EFI/stela/stela.cfg")
usb := fs.String("usb-image", "", "Stambha RAW boot image")
bus := fs.String("media-bus", "", "Stambha RAW boot image bus (usb or nvme)")
disk := fs.String("disk", "", "Stambha writable RAW or QCOW2 virtual disk")
fs.StringVar(disk, "raw-disk", "", "Alias for --disk")
accelerator := fs.String("accelerator", "", "Stambha accelerator (whpx or tcg)")
hosted := fs.Bool("hosted-gpu", true, "Use Reims vGPU for a Stambha VM")
headless := fs.Bool("headless", false, "Run Stambha without a display window")
args := fs.String("stela-args", "", "Additional Stambha options for a boot folder")
return map[string]stambhaVMFlag{
"boot-volume": {"boot_volume", func() any { return *boot }},
"usb-image": {"usb_image", func() any { return *usb }},
"media-bus": {"media_bus", func() any { return *bus }},
"disk": {"raw_disk", func() any { return *disk }},
"raw-disk": {"raw_disk", func() any { return *disk }},
"accelerator": {"accelerator", func() any { return *accelerator }},
"hosted-gpu": {"hosted_gpu", func() any { return *hosted }},
"headless": {"display", func() any { return !*headless }},
"stela-args": {"stela_args", func() any { return *args }},
}
}
func collectStambhaVMFlags(fs *flag.FlagSet, declared map[string]stambhaVMFlag) map[string]any {
options := make(map[string]any)
fs.Visit(func(f *flag.Flag) {
if spec, ok := declared[f.Name]; ok {
options[spec.option] = spec.value()
}
})
return options
}
func printJSON(v any) error {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
+59
View File
@@ -0,0 +1,59 @@
package cli
import (
"context"
"encoding/json"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestStambhaCLIUsesPreviewMediaWithoutAnIntelRuntime(t *testing.T) {
if runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
t.Skip("the built-in Stambha driver runs on Windows x86-64")
}
dir := t.TempDir()
cfg := &config.Config{DataRoot: filepath.Join(dir, "data-root")}
boot := filepath.Join(dir, "boot")
bootConfig := filepath.Join(boot, "EFI", "stela", "stela.cfg")
if err := os.MkdirAll(filepath.Dir(bootConfig), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(bootConfig, []byte("--system\n"), 0o644); err != nil {
t.Fatal(err)
}
disk := filepath.Join(dir, "system.qcow2")
if err := os.WriteFile(disk, []byte("fixture"), 0o644); err != nil {
t.Fatal(err)
}
ctx := context.Background()
args := []string{"--driver", driver.BuiltinStambhaDriverID, "--boot-volume", boot, "--disk", disk, "arm"}
if err := vmCreate(ctx, cfg, i18n.Detect(), args, false); err != nil {
t.Fatal(err)
}
args = []string{"--driver", driver.BuiltinStambhaDriverID, "--hosted-gpu=false", "--headless", "arm"}
if err := vmSet(ctx, cfg, args); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(filepath.Join(cfg.XDGDataDir(), "stambha", "vms", "arm", "stambha.json"))
if err != nil {
t.Fatal(err)
}
var profile struct {
Disk string `json:"raw_disk"`
Display bool `json:"display"`
HostedGPU bool `json:"hosted_gpu"`
Accelerator string `json:"accelerator"`
}
if err := json.Unmarshal(raw, &profile); err != nil {
t.Fatal(err)
}
if profile.Disk != disk || profile.Display || profile.HostedGPU || profile.Accelerator != "whpx" {
t.Fatalf("unexpected preview profile %+v", profile)
}
}
+2 -2
View File
@@ -102,13 +102,13 @@ func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (
return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr)
}
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error {
svc, closeService, err := openCLILifecycle(cfg)
if err != nil {
return err
}
defer closeService()
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr)
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr)
}
func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error {
+11
View File
@@ -12,6 +12,7 @@ import (
"strings"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
)
@@ -19,6 +20,8 @@ import (
const (
// BuiltinReimsMacOSDriverID is the default driver for all unmarked/existing VMs.
BuiltinReimsMacOSDriverID = "builtin.driver.reims-macos"
// BuiltinStambhaDriverID is the ARM64 macOS driver's persisted ID.
BuiltinStambhaDriverID = "builtin.driver.stambha"
// OwnerMarkerFile persists the owning driver ID inside a VM directory.
OwnerMarkerFile = ".reims-go-driver"
)
@@ -324,6 +327,14 @@ func WriteOwnerDriver(vmDir, driverID string) error {
return os.WriteFile(filepath.Join(vmDir, OwnerMarkerFile), []byte(strings.TrimSpace(driverID)+"\n"), 0o644)
}
// WriteVMRecord atomically replaces a driver's local JSON record in its VM directory.
func WriteVMRecord(vmDir, name string, value any) error {
if !filepath.IsLocal(name) || filepath.Base(name) != name || name == "." {
return fmt.Errorf("invalid VM record name %q", name)
}
return atomicfile.WriteJSON(filepath.Join(vmDir, name), value, 0o600)
}
// HostedReportMaxAge is how long a driver-pushed state counts as fresh; past
// it the host asks the driver with `driver/show` while listing.
const HostedReportMaxAge = 15 * time.Second
+3
View File
@@ -24,5 +24,8 @@ func Register(reg *plugin.Registry, cb builtin.HostCallbacks, desiredFn func(str
if err := reg.Register(Definition(ver, cb, desiredFn(ID, true))); err != nil {
return err
}
if err := reg.Register(stambhaDefinition(ver, cb, desiredFn)); err != nil {
return err
}
return reg.Register(ImagesDefinition(ver, desiredFn(IDImages, true)))
}
+37
View File
@@ -0,0 +1,37 @@
package guest
import (
"context"
"runtime"
"github.com/Nwflower/reims-go/internal/macos/stambhadriver"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
func stambhaDefinition(ver string, cb builtin.HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
drv := stambhadriver.NewStambhaDriver(cb.GetConfig)
pack := plugin.RuntimeKindContribution{
Kind: drv.RuntimeKind(), Name: plugin.LocalizedText{ZhCN: "Stambha 运行时", EnUS: "Stambha Runtime"},
RequiredFiles: stambhadriver.StambhaRuntimeFiles(),
DefaultAPIVer: drv.RuntimeAPIRange(),
}
return plugin.PluginDef{
Manifest: plugin.Manifest{Schema: 1, ID: stambhadriver.StambhaDriverID, Version: ver,
Name: drv.DisplayName(), Publisher: "Reims-Go", License: "Apache-2.0",
Permissions: []string{"driver:vm", "vm:control", "runtime:provider"}, DefaultEnabled: true,
Contributes: plugin.Contributes{RuntimeKinds: []plugin.RuntimeKindContribution{pack},
GuestDrivers: []plugin.GuestDriverContribution{{ID: drv.ID(), Name: drv.DisplayName(), RuntimeKind: drv.RuntimeKind(),
RuntimeAPIRange: drv.RuntimeAPIRange(), Capabilities: drv.Capabilities(),
CreateSchema: drv.CreateSchema(), SettingsSchema: drv.SettingsSchema(),
VMRoots: []string{"data/stambha/vms"}}}},
},
Source: plugin.SourceBuiltin, Trust: plugin.TrustOfficial,
Desired: runtime.GOOS == "windows" && runtime.GOARCH == "amd64" && cb.GetConfig != nil && desiredFn(drv.ID(), true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().RegisterRuntimeKind(sc, pack)
sc.Registry().RegisterGuestDriver(sc, drv.ID(), drv)
return nil
},
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,17 @@
//go:build !windows
package stambhadriver
import (
"errors"
"os/exec"
)
type stambhaProcess struct{ PID int }
func stambhaHideConsole(*exec.Cmd) {}
func stambhaStartProcess(*exec.Cmd, string) (int, error) {
return 0, errors.New("Stambha requires Windows x86-64")
}
func stambhaLiveProcess(string) (stambhaProcess, error) { return stambhaProcess{}, nil }
func (stambhaProcess) kill() error { return nil }
@@ -0,0 +1,497 @@
package stambhadriver
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestResolveStambhaRuntimeUsesCompleteCompatiblePackage(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "intel-runtime"}
install := func(commit, api, builtAt string, complete bool) {
t.Helper()
dir := filepath.Join(cfg.RuntimesDir(), StambhaRuntimeKind, commit)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
manifest, _ := json.Marshal(rt.Manifest{Commit: commit, Kind: StambhaRuntimeKind, RuntimeAPI: api, BuiltAt: builtAt})
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), manifest, 0o644); err != nil {
t.Fatal(err)
}
if !complete {
return
}
for _, rel := range StambhaRuntimeFiles() {
path := filepath.Join(dir, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("fixture"), 0o644); err != nil {
t.Fatal(err)
}
}
}
install("working", stambhaAPI, "2026-12-01T00:00:00Z", true)
install("incomplete", stambhaAPI, "2026-12-02T00:00:00Z", false)
install("future-api", "2.0.0", "2026-12-03T00:00:00Z", true)
got, err := resolveStambhaRuntime(&cfg)
if err != nil || got.Commit != "working" {
t.Fatalf("selected runtime = %q, err = %v", got.Commit, err)
}
}
func TestResolveStambhaRuntimeReportsNewestRejection(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "intel-runtime"}
if _, err := resolveStambhaRuntime(&cfg); !errors.Is(err, rt.ErrNoActiveRuntime) {
t.Fatalf("empty runtime error = %v, want ErrNoActiveRuntime", err)
}
install := func(commit, api, builtAt string, omit ...string) {
t.Helper()
dir := filepath.Join(cfg.RuntimesDir(), StambhaRuntimeKind, commit)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
manifest, err := json.Marshal(rt.Manifest{Commit: commit, Kind: StambhaRuntimeKind, RuntimeAPI: api, BuiltAt: builtAt})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), manifest, 0o644); err != nil {
t.Fatal(err)
}
for _, rel := range StambhaRuntimeFiles() {
if slices.Contains(omit, rel) {
continue
}
path := filepath.Join(dir, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("fixture"), 0o644); err != nil {
t.Fatal(err)
}
}
}
install("newest-compatible-missing-efi", stambhaAPI, "2026-12-03T00:00:00Z", stambhaEFIPath)
install("older-incompatible", "2.0.0", "2026-12-02T00:00:00Z")
got, err := resolveStambhaRuntime(&cfg)
if err == nil {
t.Fatalf("unexpectedly resolved runtime %q", got.Commit)
}
if errors.Is(err, rt.ErrNoActiveRuntime) {
t.Fatalf("error = %v, did not expect ErrNoActiveRuntime when Stambha packages exist", err)
}
msg := err.Error()
if !strings.Contains(msg, "newest-compatible-missing-efi") || !strings.Contains(msg, "firmware/stambha.efi") {
t.Fatalf("error = %q, want newest-compatible-missing-efi and firmware/stambha.efi", msg)
}
if strings.Contains(msg, "older-incompatible") {
t.Fatalf("error = %q, must not report older-incompatible", msg)
}
}
func TestStambhaSocketPathUsesBoundedPerUserFallback(t *testing.T) {
volume := filepath.VolumeName(t.TempDir())
root := volume + string(os.PathSeparator)
cache := filepath.Join(root, "cache")
vmDir := filepath.Join(root, strings.Repeat("字", 42), "data", "stambha", "vms", "arm")
otherVMDir := filepath.Join(root, strings.Repeat("字", 42), "other", "stambha", "vms", "arm")
longTemp := filepath.Join(root, strings.Repeat("l", 100), "tmp")
sock, err := stambhaSocketPath(vmDir, longTemp, cache)
if err != nil || !stambhaPathWithin(cache, sock) || len(sock) > 103 {
t.Fatalf("socket = %q, length = %d, err = %v", sock, len(sock), err)
}
other, err := stambhaSocketPath(otherVMDir, longTemp, cache)
if err != nil || other == sock {
t.Fatalf("different data root shares socket %q, err = %v", other, err)
}
if _, err := stambhaSocketPath(vmDir, longTemp); err == nil {
t.Fatal("expected a clear error when no bounded socket is available")
}
}
func TestStambhaRejectsWritableDiskInStageBeforeCleanup(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir()}
d := NewStambhaDriver(func() config.Config { return cfg })
vmDir, err := d.directory("arm")
if err != nil {
t.Fatal(err)
}
stage := filepath.Join(vmDir, stambhaStagedMediaDir)
if err := os.MkdirAll(stage, 0o755); err != nil {
t.Fatal(err)
}
disk := filepath.Join(stage, "disk.qcow2")
if err := os.WriteFile(disk, []byte("keep this disk"), 0o644); err != nil {
t.Fatal(err)
}
boot := t.TempDir()
bootConfig := filepath.Join(boot, "EFI", "stela", "stela.cfg")
if err := os.MkdirAll(filepath.Dir(bootConfig), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(bootConfig, []byte("--system\n"), 0o644); err != nil {
t.Fatal(err)
}
profile := stambhaProfile{BootVolume: boot, Disk: disk}
if err := stambhaValidateMedia(vmDir, &profile); err == nil {
t.Fatal("accepted disk inside staging")
}
if _, err := stageStambhaBootVolume(boot, vmDir, "", profile); err == nil {
t.Fatal("allowed staging with an attached disk inside it")
}
if err := driver.WriteVMRecord(vmDir, stambhaProfileName, profile); err != nil {
t.Fatal(err)
}
if err := d.Delete(context.Background(), "arm", false, nil, nil); err == nil {
t.Fatal("allowed deleting an old profile with an attached disk inside its stage")
}
raw, err := os.ReadFile(disk)
if err != nil || string(raw) != "keep this disk" {
t.Fatalf("disk = %q, err = %v", raw, err)
}
}
func TestStambhaRejectsSymlinkedDiskInStage(t *testing.T) {
vmDir := t.TempDir()
stage := filepath.Join(vmDir, stambhaStagedMediaDir)
if err := os.MkdirAll(stage, 0o755); err != nil {
t.Fatal(err)
}
disk := filepath.Join(stage, "disk.qcow2")
if err := os.WriteFile(disk, []byte("fixture"), 0o644); err != nil {
t.Fatal(err)
}
alias := filepath.Join(t.TempDir(), "alias.qcow2")
if err := os.Symlink(disk, alias); err != nil {
t.Skipf("could not create symlink: %v", err)
}
if err := ensureStambhaMediaOutsideStage(vmDir, stambhaProfile{Disk: alias}); err == nil {
t.Fatal("accepted a disk alias that resolves inside staging")
}
}
func TestStambhaDiskOwnersRejectsRunningWritableHardlink(t *testing.T) {
dir := t.TempDir()
disk, alias := filepath.Join(dir, "system.qcow2"), filepath.Join(dir, "alias.qcow2")
if err := os.WriteFile(disk, []byte("fixture"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Link(disk, alias); err != nil {
t.Skipf("could not create hardlink: %v", err)
}
vm := driver.VMInfo{Name: "other", State: "running", DiskPath: alias}
if err := checkStambhaDiskOwners("arm", disk, []driver.VMInfo{vm}); err == nil {
t.Fatal("accepted a hardlink of a disk already in use")
}
vm.State = "stopped"
if err := checkStambhaDiskOwners("arm", disk, []driver.VMInfo{vm}); err != nil {
t.Fatal(err)
}
}
func TestStambhaRewriteArgsHostedGPUAndQcow2(t *testing.T) {
rawArgs := []string{
"-accel", "tcg,thread=multi",
"-cpu", "max,vendor=GenuineIntel",
"-nodefaults",
"-device", "isa-debug-exit,iobase=0xf4,iosize=4",
"-machine", "q35,smm=off,sata=off,usb=off,smbus=off,hpet=off,i8042=off,vmport=off",
"-display", "sdl",
"-device", "VGA",
"-device", "virtio-keyboard-pci",
"-device", "virtio-tablet-pci",
"-drive", "if=none,id=guest,format=raw,file=D:\\vm\\disk.qcow2",
"-device", "nvme,drive=guest,serial=STELAANS",
}
profile := stambhaProfile{
Accel: "whpx",
Display: true,
HostedGPU: true,
MemoryMiB: 16384,
}
got := rewriteStambhaArgs(rawArgs, profile, `D:\rt\qemu\share`, true, `D:\vm\qmp.sock`)
assertArgPair(t, got, "-accel", "whpx,kernel-irqchip=off")
assertArgPair(t, got, "-cpu", "host")
assertArgPair(t, got, "-display", "none")
assertArgPair(t, got, "-machine", "q35,smm=off,sata=off,usb=off,smbus=off,hpet=on,i8042=off,vmport=off,memory-backend=ram")
assertArgPair(t, got, "-object", "memory-backend-ram,id=ram,size=16384M,share=on")
assertArgPair(t, got, "-drive", "if=none,id=guest,format=qcow2,l2-cache-size=16M,file=D:\\vm\\disk.qcow2")
assertArgPair(t, got, "-L", `D:\rt\qemu\share`)
assertArgPair(t, got, "-device", "VGA,id=stela-console")
assertArgPair(t, got, "-device", "virtio-keyboard-pci")
assertArgPair(t, got, "-device", "virtio-tablet-pci")
assertArgPair(t, got, "-device", "reims-graphics-pci,id=gfx,x-hosted-arm64=on")
assertArgPair(t, got, "-qmp", `unix:D:\vm\qmp.sock,server=on,wait=off`)
for _, a := range got {
if strings.HasPrefix(a, "isa-debug-exit,") {
t.Fatalf("isa-debug-exit must be stripped in hosted GPU mode: %v", got)
}
if a == "VGA" {
t.Fatalf("bare VGA must be replaced by VGA,id=stela-console: %v", got)
}
}
if countArg(got, "virtio-keyboard-pci") != 1 || countArg(got, "virtio-tablet-pci") != 1 {
t.Fatalf("virtio input devices must appear exactly once: %v", got)
}
}
func TestStambhaRewriteArgsLegacyPreserved(t *testing.T) {
rawArgs := []string{
"-accel", "tcg,thread=multi",
"-cpu", "max,vendor=GenuineIntel",
"-device", "isa-debug-exit,iobase=0xf4,iosize=4",
"-machine", "q35,hpet=off,vmport=off",
"-display", "none",
"-device", "usb-storage,drive=volume,serial=STELAUSBIMAGE,bus=host-usb.0,bootindex=0",
"-drive", "if=none,id=guest,format=raw,file=D:\\vm\\disk.img",
}
profile := stambhaProfile{
Accel: "tcg",
MediaBus: "nvme",
Display: false,
HostedGPU: false,
}
got := rewriteStambhaArgs(rawArgs, profile, `D:\rt\qemu\share`, false, `D:\vm\qmp.sock`)
assertArgPair(t, got, "-accel", "tcg,thread=multi")
assertArgPair(t, got, "-cpu", "max,vendor=GenuineIntel")
assertArgPair(t, got, "-device", "isa-debug-exit,iobase=0xf4,iosize=4")
assertArgPair(t, got, "-device", "nvme,drive=volume,serial=STELAMEDIA,bootindex=0")
assertArgPair(t, got, "-drive", "if=none,id=guest,format=raw,file=D:\\vm\\disk.img")
assertArgPair(t, got, "-device", "VGA")
if slices.Contains(got, "reims-graphics-pci,id=gfx,x-hosted-arm64=on") {
t.Fatalf("legacy mode must not attach hosted Reims GPU: %v", got)
}
if slices.Contains(got, "-object") {
t.Fatalf("legacy mode must not attach shared RAM memory-backend: %v", got)
}
}
func TestStambhaNonHostedDisplayUsesPackagedGTK(t *testing.T) {
args := rewriteStambhaArgs([]string{"-display", "sdl"}, stambhaProfile{Display: true}, "", false, "")
assertArgPair(t, args, "-display", "gtk")
}
func TestParseStambhaImageInfo(t *testing.T) {
for _, format := range []string{"raw", "qcow2"} {
raw, _ := json.Marshal(map[string]any{"format": format, "virtual-size": 65536})
if got, err := parseStambhaImageInfo(raw); err != nil || got != format {
t.Fatalf("format = %q, err = %v, want %q", got, err, format)
}
}
raw, _ := json.Marshal(map[string]any{"format": "vhdx", "virtual-size": 65536})
if _, err := parseStambhaImageInfo(raw); err == nil {
t.Fatal("unexpectedly accepted VHDX")
}
}
func TestStambhaApplyEnv(t *testing.T) {
base := []string{"PATH=C:\\Windows\\System32", "REIMS_VGPU_WINDOW=0", "FOO=bar"}
// Windowed hosted GPU with PCI VID:DID selector drops REIMS_VGPU_WINDOW=0 and sets Vulkan selectors.
got := applyStambhaEnv(base, `D:\rt\qemu\bin`, stambhaProfile{HostedGPU: true, Display: true, GPU: "10DE:2231"}, `C:\rec.json`)
if hasEnvKey(got, "REIMS_VGPU_WINDOW") {
t.Fatalf("windowed hosted GPU should drop REIMS_VGPU_WINDOW: %v", got)
}
assertEnvVal(t, got, "MESA_VK_DEVICE_SELECT", "10de:2231")
assertEnvVal(t, got, "VK_LOADER_DEVICE_SELECT", "10de:2231")
if !strings.HasPrefix(getEnvVal(got, "PATH"), `D:\rt\qemu\bin`+string(os.PathListSeparator)) {
t.Fatalf("PATH must prepend qemu/bin: %s", getEnvVal(got, "PATH"))
}
// Headless hosted GPU with auto GPU sets REIMS_VGPU_WINDOW=0 and recommended ICD.
headless := applyStambhaEnv(base, `D:\rt\qemu\bin`, stambhaProfile{HostedGPU: true, Display: false, GPU: "auto"}, `C:\nv-vk64.json`)
assertEnvVal(t, headless, "REIMS_VGPU_WINDOW", "0")
assertEnvVal(t, headless, "VK_ICD_FILENAMES", `C:\nv-vk64.json`)
assertEnvVal(t, headless, "VK_DRIVER_FILES", `C:\nv-vk64.json`)
}
func TestStageStambhaBootVolumeDoesNotMutateSource(t *testing.T) {
src := t.TempDir()
vmDir := t.TempDir()
efiPath := filepath.Join(src, "EFI", "BOOT", "BOOTX64.EFI")
cfgPath := filepath.Join(src, "EFI", "stela", "stela.cfg")
if err := os.MkdirAll(filepath.Dir(efiPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(cfgPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(efiPath, []byte("EFI-PAYLOAD"), 0o644); err != nil {
t.Fatal(err)
}
origCfg := "--storage STELAANS:11111111-2222-3333-4444-555555555555\n"
if err := os.WriteFile(cfgPath, []byte(origCfg), 0o644); err != nil {
t.Fatal(err)
}
runtimeEFI := filepath.Join(t.TempDir(), "stambha.efi")
if err := os.WriteFile(runtimeEFI, []byte("RUNTIME-EFI"), 0o644); err != nil {
t.Fatal(err)
}
staged, err := stageStambhaBootVolume(src, vmDir, runtimeEFI, stambhaProfile{
HostedGPU: true,
StelaArgs: "--tier2 on --tlbi-keep on",
})
if err != nil {
t.Fatal(err)
}
gotCfg, err := os.ReadFile(filepath.Join(staged, "EFI", "stela", "stela.cfg"))
if err != nil {
t.Fatal(err)
}
wantCfg := "--storage STELAANS:11111111-2222-3333-4444-555555555555 --hosted-reims-base 0x300000000 --hosted-reims-irq auto --hosted-reims-irq-mode poll --tier2 on --tlbi-keep on\n"
if string(gotCfg) != wantCfg {
t.Fatalf("staged stela.cfg = %q, want %q", string(gotCfg), wantCfg)
}
gotEFI, err := os.ReadFile(filepath.Join(staged, "EFI", "BOOT", "BOOTX64.EFI"))
if err != nil || string(gotEFI) != "RUNTIME-EFI" {
t.Fatalf("staged EFI = %q, err = %v", gotEFI, err)
}
sourceEFI, err := os.ReadFile(efiPath)
if err != nil || string(sourceEFI) != "EFI-PAYLOAD" {
t.Fatalf("source EFI = %q, err = %v", sourceEFI, err)
}
afterSrc, err := os.ReadFile(cfgPath)
if err != nil {
t.Fatal(err)
}
if string(afterSrc) != origCfg {
t.Fatalf("source stela.cfg was mutated: %q", string(afterSrc))
}
}
func TestStambhaCreateSetShowHostedGPU(t *testing.T) {
dataRoot := t.TempDir()
mediaDir := filepath.Join(t.TempDir(), "media")
if err := os.MkdirAll(filepath.Join(mediaDir, "EFI", "BOOT"), 0o755); err != nil {
t.Fatal(err)
}
cfgPath := filepath.Join(mediaDir, "EFI", "stela", "stela.cfg")
if err := os.MkdirAll(filepath.Dir(cfgPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(cfgPath, []byte("--system\n"), 0o644); err != nil {
t.Fatal(err)
}
diskFile := filepath.Join(t.TempDir(), "guest.qcow2")
if err := os.WriteFile(diskFile, []byte{'Q', 'F', 'I', 0xfb, 0, 0, 0, 3}, 0o644); err != nil {
t.Fatal(err)
}
drv := NewStambhaDriver(func() config.Config { return config.Config{DataRoot: dataRoot} })
ctx := context.Background()
err := drv.Create(ctx, driver.CreateRequest{
DriverID: StambhaDriverID,
Name: "arm-desktop",
Options: map[string]any{
"boot_volume": mediaDir,
"raw_disk": diskFile,
"memory": "16G",
"cpus": 8,
"accelerator": "whpx",
"hosted_gpu": true,
"gpu": "10de:2231",
"display": false,
"stela_args": "--tier2 on --tlbi-keep on",
},
}, nil, nil)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
info, err := drv.Show(ctx, "arm-desktop")
if err != nil {
t.Fatalf("Show failed: %v", err)
}
if info.DriverData["hosted_gpu"] != true || info.DriverData["gpu"] != "10de:2231" || info.DriverData["stela_args"] != "--tier2 on --tlbi-keep on" {
t.Fatalf("unexpected DriverData: %+v", info.DriverData)
}
if err := drv.Set(ctx, driver.SetRequest{Name: "arm-desktop", Changes: map[string]any{"gpu": "auto", "hosted_gpu": false}}, nil, nil); err != nil {
t.Fatalf("Set failed: %v", err)
}
raw, err := os.ReadFile(filepath.Join(info.Directory, stambhaProfileName))
if err != nil {
t.Fatal(err)
}
var saved stambhaProfile
if err := json.Unmarshal(raw, &saved); err != nil {
t.Fatal(err)
}
if saved.HostedGPU || saved.GPU != "auto" {
t.Fatalf("unexpected saved profile: %+v", saved)
}
}
func TestStambhaCapabilities(t *testing.T) {
drv := NewStambhaDriver(nil)
caps := drv.Capabilities()
for _, want := range []string{"guest.arm64", "serial_log", driver.CapAffinity} {
if !slices.Contains(caps, want) {
t.Fatalf("Capabilities() = %v, missing %q", caps, want)
}
}
}
func assertArgPair(t *testing.T, args []string, flag, want string) {
t.Helper()
for i := 0; i+1 < len(args); i++ {
if args[i] == flag && args[i+1] == want {
return
}
}
t.Fatalf("missing arg pair %q %q in %v", flag, want, args)
}
func countArg(args []string, value string) int {
n := 0
for _, a := range args {
if a == value {
n++
}
}
return n
}
func getEnvVal(env []string, key string) string {
for _, kv := range env {
if k, v, ok := strings.Cut(kv, "="); ok && strings.EqualFold(k, key) {
return v
}
}
return ""
}
func hasEnvKey(env []string, key string) bool {
for _, kv := range env {
if k, _, ok := strings.Cut(kv, "="); ok && strings.EqualFold(k, key) {
return true
}
}
return false
}
func assertEnvVal(t *testing.T, env []string, key, want string) {
t.Helper()
if got := getEnvVal(env, key); got != want {
t.Fatalf("env %s = %q, want %q (env=%v)", key, got, want, env)
}
}
@@ -0,0 +1,125 @@
//go:build windows
package stambhadriver
import (
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"syscall"
"github.com/Nwflower/reims-go/internal/driver"
"golang.org/x/sys/windows"
)
type stambhaProcess struct {
PID int `json:"pid"`
Created windows.Filetime `json:"created"`
}
const stambhaProcessRecord = "stambha-process.json"
func stambhaHideConsole(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW}
}
func stambhaStartProcess(cmd *exec.Cmd, dir string) (int, error) {
// Use CREATE_NO_WINDOW without HideWindow (STARTF_USESHOWWINDOW/SW_HIDE) so
// QEMU opens no console window while reims-vgpu's first ShowWindow(SW_SHOW)
// on its native Vulkan display window is not swallowed by Win32.
cmd.SysProcAttr = &syscall.SysProcAttr{
CreationFlags: windows.CREATE_NO_WINDOW | windows.CREATE_NEW_PROCESS_GROUP | windows.CREATE_BREAKAWAY_FROM_JOB,
}
active := cmd
if err := active.Start(); err != nil {
if !errors.Is(err, windows.ERROR_ACCESS_DENIED) {
return 0, err
}
// Parent Job Objects without JOB_OBJECT_LIMIT_BREAKAWAY_OK reject
// CREATE_BREAKAWAY_FROM_JOB with ERROR_ACCESS_DENIED; retry in-job.
retry := exec.Command(cmd.Path, cmd.Args[1:]...)
retry.Dir, retry.Env = cmd.Dir, cmd.Env
retry.Stdin, retry.Stdout, retry.Stderr = cmd.Stdin, cmd.Stdout, cmd.Stderr
retry.SysProcAttr = &syscall.SysProcAttr{
CreationFlags: windows.CREATE_NO_WINDOW | windows.CREATE_NEW_PROCESS_GROUP,
}
if err2 := retry.Start(); err2 != nil {
return 0, err2
}
active = retry
}
pid := active.Process.Pid
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
var created windows.Filetime
if err == nil {
var exit, kernel, user windows.Filetime
err = windows.GetProcessTimes(handle, &created, &exit, &kernel, &user)
windows.CloseHandle(handle)
}
if err == nil {
err = driver.WriteVMRecord(dir, stambhaProcessRecord, stambhaProcess{PID: pid, Created: created})
}
if err != nil {
_ = active.Process.Kill()
_ = active.Wait()
return 0, err
}
go func() { _ = active.Wait() }()
return pid, nil
}
func stambhaLiveProcess(dir string) (stambhaProcess, error) {
raw, err := os.ReadFile(filepath.Join(dir, stambhaProcessRecord))
if errors.Is(err, os.ErrNotExist) {
return stambhaProcess{}, nil
}
if err != nil {
return stambhaProcess{}, err
}
var proc stambhaProcess
if err := json.Unmarshal(raw, &proc); err != nil {
return stambhaProcess{}, err
}
handle, err := proc.open(0)
if handle == 0 || err != nil {
return stambhaProcess{}, err
}
defer windows.CloseHandle(handle)
return proc, nil
}
func (proc stambhaProcess) open(extra uint32) (windows.Handle, error) {
if proc.PID <= 0 || proc.Created == (windows.Filetime{}) {
return 0, nil
}
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE|extra, false, uint32(proc.PID))
if errors.Is(err, windows.ERROR_INVALID_PARAMETER) {
return 0, nil
}
if err != nil {
return 0, err
}
state, err := windows.WaitForSingleObject(handle, 0)
if err != nil || state == windows.WAIT_OBJECT_0 {
windows.CloseHandle(handle)
return 0, err
}
var created, exit, kernel, user windows.Filetime
err = windows.GetProcessTimes(handle, &created, &exit, &kernel, &user)
if err != nil || created != proc.Created {
windows.CloseHandle(handle)
return 0, err
}
return handle, nil
}
func (proc stambhaProcess) kill() error {
handle, err := proc.open(windows.PROCESS_TERMINATE)
if handle == 0 || err != nil {
return err
}
defer windows.CloseHandle(handle)
return windows.TerminateProcess(handle, 1)
}
+2
View File
@@ -20,6 +20,8 @@ var ErrNoActiveRuntime = errors.New("no active runtime installed")
const (
// DefaultKind is the built-in macOS vGPU runtime kind.
DefaultKind = "reims-vgpu"
// StambhaKind is a standalone ARM64 macOS preview runtime.
StambhaKind = "stambha-hosted"
// DefaultRuntimeAPI is the baseline CLI/output contract version for reims-vgpu.
DefaultRuntimeAPI = "1.0.0"
)